text
stringlengths
8
6.88M
#include<iostream> #include<string> #include<stdlib.h> #include<stdio.h> using namespace std; //ham kiem tra loi bool kiemtraloi(string chuoi) { //lay so ki tu chuoi int length=chuoi.length(); int dem=0; for(int i=0;i<length;i++) { /*day co su khac biet: trong chuoi so cung la 1 ki tu nhung no cung hieu la so! vi dieu kien la chuoi[i]>'9' va ta ko se dk chuoi[i]<0; de danh no cho cai dk sau:diemtoan<0||diemtoan>10 */ if((chuoi[i]>'9')&&chuoi[i]!='.') { return false; break; } if(chuoi[i]=='.') { dem++; if(dem==2) { return false; break; } if(chuoi[0]=='.'||chuoi[length-1]=='.') { return false; } } } return true; } // lass hocsinh class hocsinh { private: string toan,van,hoa; public: void nhapsinhvien() { dtoan: do { fflush(stdin); cout<<"\n nhap vao diem toan:\n"; getline(cin,this->toan); if(kiemtraloi(toan)==false) { cout<<"\n ban nhap sai du lieu.vui long kiem tra lai"; //xoa man hinh system("cls"); } else { //chuyen kieu chuoi sang so int diemtoan=atof((char *)toan.c_str()); if(diemtoan<0||diemtoan>10) { cout<<"\n vui long nhap lai diem(1->10)!"; goto dtoan; } } }while(kiemtraloi(toan)==false); dvan: do { fflush(stdin); cout<<"\n nhap vao diem van:\t"; getline(cin,van); if(kiemtraloi(van)==false) { cout<<"\n ban nhap sai du lieu.vui long kiem tra lai"; } else { //chuyen kieu chuoi sang so int diemvan=atof((char *)van.c_str()); if(diemvan<0||diemvan>10) { cout<<"\n vui long nhap lai diem(1->10)!"; goto dvan; } } }while(kiemtraloi(van)==false); dhoa: do { fflush(stdin); cout<<"\n nhap vao diem hoa:\t"; getline(cin,hoa); if(kiemtraloi(hoa)==false) { cout<<"\n ban nhap sai du lieu.vui long kiem tra lai"; } else { //chuyen kieu chuoi sang so int diemhoa=atof((char *)hoa.c_str()); if(diemhoa<0||diemhoa>10) { cout<<"\n vui long nhap lai diem(1->10)!"; goto dhoa; } } }while(kiemtraloi(hoa)==false); } void xuatsinhvien() { cout<<"\n diem toan:\t"<<toan; cout<<"\n diem van:\t"<<van; cout<<"\n diem hoa:\t"<<hoa; } }; int main() { hocsinh hs; hs.nhapsinhvien(); hs.xuatsinhvien(); return 0; }
#include "binject.h" #include <stdio.h> #include <string.h> #include <errno.h> #include "unistd.h" // Size of the data for the INTERNAL ARRAY mechanism. It should be // a positive integer #ifndef BINJECT_ARRAY_SIZE #define BINJECT_ARRAY_SIZE (9216) #endif // BINJECT_ARRAY_SIZE static void error_report(int internal_error) { if (internal_error != NO_ERROR) fprintf(stderr, "Error %d\n", internal_error); if (0 != errno) fprintf(stderr, "Error %d: %s\n", errno, strerror(errno)); } BINJECT_STATIC_STRING("```replace_data```", BINJECT_ARRAY_SIZE, static_data); static int aux_print_help(const char * command){ printf("\nUsage:\n %s script.txt\n\n", command); printf("script.txt.exe executable will be generated or overwritten.\n"); printf("script.txt.exe will print to the stdout an embedded copy of script.txt.\n\n"); printf("NOTE: depending on the chosen embedding mechanism, some help information will be\n"); printf("appended at end of script.txt.exe.\n"); return 0; } static char * aux_script_prepare(char * buf, int * off, int * siz){ *off = *siz; // buffer processing finished return buf; } static int aux_script_run(const char * scr, int size, int argc, char ** argv){ // Script echo printf("A %d byte script was found (dump:)[", size); int w = fwrite(scr, 1, size, stdout); if (w != size) return ACCESS_ERROR; printf("]\n"); return 0; } // -------------------------------------------------------------------- static int binject_main_app_internal_script_inject(binject_static_t * info, const char * scr_path, const char* bin_path, const char * outpath){ int result = ACCESS_ERROR; // Open the scipt FILE * scr = fopen(scr_path, "rb"); if (!scr) goto end; // Get the original binary size if (fseek(scr, 0, SEEK_END)) goto end; int siz = ftell(scr); if (siz < 0) goto end; if (fseek(scr, 0, SEEK_SET)) goto end; int bufsize = siz; int off = 0; { // Scope block to avoid goto and variable length issue char buf[bufsize]; // Copy the binary result = binject_aux_file_copy(bin_path, outpath); if (NO_ERROR != result) goto end; // Prepare the script for the injection if (0> fread(buf, 1, siz, scr)) goto end; while (off >=0 && off < siz) { char * injdat = buf; injdat = aux_script_prepare(injdat, &off, &siz); // Inject the partial script result = binject_step(info, outpath, injdat, siz); if (NO_ERROR != result) goto end; } } // Finalize by writing static info into the binary result = binject_done(info, outpath); end: error_report(0); if (scr) fclose(scr); return result; } static int binject_main_app_internal_script_handle(binject_static_t * info, const char* bin_path, int argc, char **argv) { unsigned int size; unsigned int offset; // Get information from static section char * script = binject_info(info, &size, &offset); if (script) { // Script found in the static section return aux_script_run(script, size, argc, argv); } else { // Script should be at end of the binary unsigned int script_size = binject_aux_tail_get(bin_path, 0, 0, offset); char buf[script_size]; binject_aux_tail_get(bin_path, buf, script_size, offset); return aux_script_run(buf, script_size, argc, argv); } return NO_ERROR; } int main(int argc, char **argv) { int result = GENERIC_ERROR; // Get information from static section unsigned int size = 0; unsigned int offset = 0; binject_info(static_data, &size, &offset); // Run the proper tool if (size > 0 || offset > 0) { // Script found: handle it result = binject_main_app_internal_script_handle(static_data, argv[0], argc, argv); } else if (argc < 2 || argv[1][0] == '\0') { // No arguments: print help aux_print_help(argv[0]); result = NO_ERROR; } else { // No script found: inject if (argc < 2) { aux_print_help(argv[0]); goto end; } result = binject_main_app_internal_script_inject(static_data, argv[1], argv[0], "injed.exe"); } end: if (result != NO_ERROR) fprintf(stderr, "Error %d\n", result); error_report(0); return result; }
#include <iostream> #include <string> #include <fstream> //for getLine(), creating ifstream inputs #include <sstream> using namespace std; //taken from hw3 description //modification:deleted the constructor with parameter since it is not needed struct lectureNode{ string lectureName; lectureNode *next; lectureNode() { lectureName = ""; next = NULL; } }; //taken from hw3 description, //modifications: changed type of id to string type, //added another pointer(with type Student) to create a linked list(used for queue) of students //deleted constructor with parameters, since it is not needed struct Student{ string name; string id; lectureNode *lectures; Student *next; //for student queue Student() { name = ""; id = "0"; lectures = NULL; next = NULL; } }; //constructor to build a linked list for the lectures(lectures in the lecture file) struct LectureList{ string nameCode; int capacity; LectureList *next; LectureList(){ nameCode = ""; next= NULL; capacity = 0; } }; // assignes students to their lectures with round robin algorithm void roundRobinQueue(Student * & initialS, LectureList * & initialL){ Student *tailStudent = initialS; //created a tail for student queue to pass to the next student when the lecture has been assigned while(1){ //this loop will end only if all the students' lectures has been processed/assigned LectureList *ptr = initialL; //a pointer pointing to head of LectureList, to find the desired lecture for the student if(tailStudent->lectures != NULL){ //continue assigning operation if the student has a lectureNode while(ptr){ if(tailStudent->lectures->lectureName == ptr->nameCode){ //if the ptr shows the same lecture as the student's lecture, if(ptr->capacity > 0){ //assign if capacity left cout << ptr->nameCode << " is assigned to " << tailStudent->name << "(" << tailStudent->id << ")\n"; //proper prompt ptr->capacity = (ptr->capacity) - 1; //decrease capacity of the lecture tailStudent->lectures = tailStudent->lectures->next; //since the student's lecture has been assigned, student should show his/her next wished lecture for the next queue round break; //stop searching for the lecture since student is assigned }else{//dont assign if no capacity left cout << ptr->nameCode << " can not be assigned to " << tailStudent->name << "(" << tailStudent->id << ")\n";//proper prompt tailStudent->lectures = tailStudent->lectures->next; //since the student's lecture can not assigned, student now should show his/her next wished lecture for the next queue round break; //stop searching for the lecture since student can not be assigned } }else{ LectureList *ptr2 = initialL; bool nameChecker = false; while(ptr2){ //if there is no matching lectures between student's and lectureList, record it in nameChecker if(tailStudent->lectures->lectureName == ptr2->nameCode){ nameChecker = true; } ptr2 = ptr2 -> next; } if(!nameChecker){ //if no matchign names are found between student's and lectureList, prompt that student can not be assigned to his/her lecture cout << tailStudent->lectures->lectureName << " can not be assigned to " << tailStudent->name << "(" << tailStudent->id << ")\n"; tailStudent->lectures = tailStudent->lectures->next; break; } } ptr = ptr->next; //seek for the next lecture in LectureList } } if(tailStudent->next == NULL){ //if tail reached the end of the list of students, make the last student point to head of the student list. //Otherwise we would go through the student queue once, matching only one lecture per student tailStudent->next = initialS; } bool checker = false; Student *lectureChecker = tailStudent; while(!checker){ //check if all students' lectures has been assigned/ or processed. if(lectureChecker->lectures != NULL){// lectureChecker->lectures would show NULL if a student's desired lectures has been all processed checker = true; } lectureChecker = lectureChecker->next; } if(!checker){ //if all the student's lectures has been processed end the while loop break; } tailStudent = tailStudent->next; //go to the next student for matching } } void parseLectureFile(ifstream & inputLectures, LectureList * & initial){ string lines; LectureList *tailforLectureList = initial; while (getline(inputLectures, lines)){ if(lines == "<lecture>"){ //indication that a lecture is defined in file if(initial->capacity == 0){//if initial node is empty, first fill it while(getline(inputLectures, lines)){ if(lines.find("<name>") != string::npos){ tailforLectureList->nameCode = lines.substr(7, lines.find("</name>") - 7); //store name } if(lines.find("<capacity>") != string::npos){ tailforLectureList->capacity = stoi(lines.substr(11, lines.find("</capacity>") - 11)); //store capacity } if(lines.find("</lecture>") != string::npos){ break; } } }else{ //if the lectureList is not empty, create a new node and connect to the list LectureList *latestLecture = new LectureList;//create a new node while(getline(inputLectures, lines)){ if(lines.find("<name>") != string::npos){ latestLecture->nameCode = lines.substr(7, lines.find("</name>") - 7); } if(lines.find("<capacity>") != string::npos){ latestLecture->capacity = stoi(lines.substr(11, lines.find("</capacity>") - 11)); } if(lines.find("</lecture>") != string::npos){ tailforLectureList->next = latestLecture; //connect to the list tailforLectureList = latestLecture; break; } } } } } } void parseStudentFile(ifstream & inputStudent, Student * & initial){ string lines; string id; string name; Student *tailforStu = initial;//a tail to track students, beggign with the head of the student linked list while (getline(inputStudent,lines)){ //iterate until a student declaration is found if(lines == "<student>"){ //meaning that a student has been declared in the file if(initial->id == "0"){ //if the head of student list is empty, this should be filled first lectureNode *latestLecture = new lectureNode; //since a student has been declared in the file, a pointer of type lectureNode is created to store the student's wished lectures in a linked list lectureNode *tailforLec = latestLecture; while (getline(inputStudent,lines)){ //iterate until a name or an id or a course declaration is found if(lines.find("<name>") != string::npos){ tailforStu->name = lines.substr(7, lines.find("</name>") - 7); //store name } if(lines.find("<id>") != string::npos){ tailforStu->id = lines.substr(5, lines.find("</id>") - 5); //store id } if(lines.find("<lecture>") != string::npos){ if(latestLecture->lectureName == ""){ //if a lectureNode has been created but empty, this should be processed first tailforLec->lectureName = lines.substr(10, lines.find("</lecture>") - 10); //store lecture's name tailforStu->lectures = tailforLec; //connect the student to the it's lectureNode }else{ //add a node to student's lectureNode lectureNode *addLecture = new lectureNode; addLecture->lectureName = lines.substr(10, lines.find("</lecture>") - 10); //store course tailforLec->next = addLecture; tailforLec = addLecture; } } if(lines.find("</student>") != string::npos){ // end the loop if the student declarion has ended break; } } }else{ //if the head of student list has already been processed(filled with info) Student *latestStudent = new Student; //create a new student to store id, name, and connect a lecture node lectureNode *latestLecture1 = new lectureNode; //create a sigly linked list for lectures latestStudent->lectures = latestLecture1; //connect student to lecture list lectureNode *tailforLec1 = latestLecture1; //trace the end point of lecture list to add a new lecture to the end tailforStu->next = latestStudent; //connect the new created student to the linked list of students(for queue) tailforStu = latestStudent; while (getline(inputStudent,lines)){ //iterate until a name or an id or a course declaration is found if(lines.find("<name>") != string::npos){ tailforStu->name = lines.substr(7, lines.find("</name>") - 7); //store name } if(lines.find("<id>") != string::npos){ tailforStu->id = lines.substr(5, lines.find("</id>") - 5); //store id } if(lines.find("<lecture>") != string::npos){ if(latestLecture1->lectureName == ""){ tailforLec1->lectureName = lines.substr(10, lines.find("</lecture>") - 10); //store course tailforStu->lectures = tailforLec1; }else{ lectureNode *addLecture = new lectureNode; addLecture->lectureName = lines.substr(10, lines.find("</lecture>") - 10); //store course tailforLec1->next = addLecture; tailforLec1 = addLecture; } } if(lines.find("</student>") != string::npos){ // end the loop if the student declarion has ended break; } } } } } } bool checkFileFormatStudent(ifstream & input){ string lines; while(getline(input,lines)){ if(lines == "<student>"){ //means that a student has been declared in file int idCounter =0, nameCounter =0; while(getline(input,lines)){ if(lines.find("<name>") != string::npos){ //if a line has been started with <name>, must finish with </name>, other wise return false nameCounter++; if(lines.find("</name>") == string::npos){ return false; } }else if(lines.find("<id>") != string::npos){ //if a line has been started with <id>, must finish with </id>, other wise return false idCounter++; if(lines.find("</id>") == string::npos){ return false; } }else if(lines.find("<lecture>") != string::npos){ //if a line has been started with <lecture>, must finish with </lecture>, other wise return false if(lines.find("</lecture>") == string::npos){ return false; } }else if(idCounter>1){ //return false if there is more than 1 id(a student can only have 1 id) return false; }else if(nameCounter>1){//return false if there is more than 1 name(a student can only have 1 name) return false; }else if(lines == "</student>" && (idCounter ==0) &&(nameCounter==0)){//if student declariton is finished but there is no id or name return false return false; }else if(lines == "<student>"){ //return false if a student is declared before the previous student finished(reached </student>) return false; }else if(lines == "</student>"){//if student declariton is finished search for the next student break; } } } } input.clear();//go to the beginning of the file input.seekg(0); } bool checkFileFormatLecture(ifstream & input){ string lines; while(getline(input,lines)){ if(lines == "<lecture>"){ //a lecture has been defined in the file int countCapacity =0, nameCounter =0; while(getline(input,lines)){ if(lines.find("<name>") != string::npos){//if a line has been started with <name>, must finish with </name>, other wise return false nameCounter++; if(lines.find("</name>") == string::npos){ return false; } }else if(lines.find("<capacity>") != string::npos){//if a line has been started with <capacity>, must finish with </capacity>, other wise return false countCapacity++; if(lines.find("</capacity>") == string::npos){ return false; } }else if(countCapacity>1){ //return false if there is more than 1 capacity declared return false; }else if(nameCounter>1){//return false if there is more than 1 name for a single lecture return false; }else if(lines == "</lecture>" && (countCapacity ==0) &&(nameCounter==0)){//if student declariton is finished but there is no capacity or name return false return false; }else if(lines == "<lecture>"){ //return false if a lecture is declared before the previous lecture finished return false; }else if(lines == "</lecture>"){//if lecture declariton is finished search for the next lecture break; } } } } input.clear();//go to the beginning of the file input.seekg(0); } int main(){ string studentFile, lectureFile; ifstream inputStudent, inputLectures; Student *initialS = new Student; //create an head pointer, pointing to first student with empty info LectureList *initialL = new LectureList; do{ cout << "Please enter the name of the Student XML file: "; //propmt to ask for a file to open until correct one has been entered cin >> studentFile; inputStudent.open(studentFile.c_str()); if(inputStudent.fail()){ cout << "Invalid file name.\n"; } }while(inputStudent.fail()); do{ cout << "Please enter the name of the Lectures XML file: "; //propmt to ask for a file to open until correct one has been entered cin >> lectureFile; inputLectures.open(lectureFile.c_str()); if(inputLectures.fail()){ cout << "Invalid file name.\n"; } }while(inputLectures.fail()); if(!checkFileFormatStudent(inputStudent)){ //check if student file is in right format cout << "Invalid XML format!.. Exiting." ; cin.get(); cin.ignore(); return 0; } if(!checkFileFormatLecture(inputLectures)){//check if lecture file is in right format cout << "Invalid XML format!.. Exiting." ; cin.get(); cin.ignore(); return 0; } parseStudentFile(inputStudent, initialS); parseLectureFile(inputLectures, initialL); roundRobinQueue(initialS, initialL); cin.get(); cin.ignore(); return 0; }
#include "CNHeatEqMethod.hpp" template<typename X> CNHeatEqMethod<X>::CNHeatEqMethod(Option<X> *__option, X _S_min, X _S_max, int _N, int _M) : FDHeatMethod<X>(__option, _S_min, _S_max, _N, _M) { this->K_1 = new std::vector<X>(this->M + 1); this->K_2 = new std::vector<X>(this->M + 1); for (int i = 0; i < this->M + 1; ++i) { (*this->K_1)[i] = X(0.0); (*this->K_2)[i] = X(0.0); } } template<typename X> void CNHeatEqMethod<X>::solve() { double alphaValue = static_cast<double>(this->alpha); std::cout << "Alpha = " << alphaValue << std::endl; for (int j = 0; j <= this->M; ++j) { (*this->vOld)[j] = this->payoff(this->N, j); } std::vector<X> *tmpPointer; for (int i = 1; i <= this->N + 1; i++) { //obliczanie wekora K (*this->K_1)[1] = this->A(1) * this->lower_bd_cond(i, 1); (*this->K_1)[this->M - 1] = this->C(this->M - 1) * this->upper_bd_cond(i, this->M - 1); (*this->K_2)[1] = this->A(1) * this->lower_bd_cond(i, 1); (*this->K_2)[this->M - 1] = this->C(this->M - 1) * this->upper_bd_cond(i, this->M - 1); std::vector<X> p = this->D((*this->vOld) + (*this->K_1) + (*this->K_2)); (*this->vNew) = this->decompilation(p); (*this->vNew)[0] = this->lower_bd_cond(i, 0); (*this->vNew)[this->M] = this->upper_bd_cond(i, this->M); if (i < this->N) { tmpPointer = this->vOld; this->vOld = this->vNew; this->vNew = tmpPointer; } } } template<typename X> X CNHeatEqMethod<X>::A(const int &j) { return -0.5 * this->alpha; } template<typename X> X CNHeatEqMethod<X>::B(const int &j) { return 1 + this->alpha; } template<typename X> X CNHeatEqMethod<X>::C(const int &j) { return -0.5 * this->alpha; } template<typename X> X CNHeatEqMethod<X>::E1(const int &j) { return A(j); } template<typename X> X CNHeatEqMethod<X>::E2(const int &j) { return -A(j); } template<typename X> X CNHeatEqMethod<X>::F1(const int &j) { return 1 + B(j); } template<typename X> X CNHeatEqMethod<X>::F2(const int &j) { return 1 - B(j); } template<typename X> X CNHeatEqMethod<X>::G1(const int &j) { return C(j); } template<typename X> X CNHeatEqMethod<X>::G2(const int &j) { return -C(j); } template<typename X> std::vector<X> CNHeatEqMethod<X>::decompilation(const std::vector<X> &b) { std::vector<X> q(this->M + 1), u(this->M + 1), y(this->M + 1); y[1] = this->F2(1); q[1] = b[1]; for (int j = 2; j < this->M; ++j) { q[j] = b[j] - this->E2(j) * q[j - 1] / y[j - 1]; y[j] = this->F2(j) - this->E2(j) * this->G2(j - 1) / y[j - 1]; } u[this->M - 1] = q[this->M - 1] / y[this->M - 1]; for (int j = this->M - 2; j > 0; j--) { u[j] = (q[j] - this->G2(j) * u[j + 1]) / y[j]; } return u; } template<typename X> std::vector<X> CNHeatEqMethod<X>::D(const std::vector<X> &q) { std::vector<X> p(this->M + 1); p[1] = this->F1(1) * q[1] + this->G1(1) * q[2]; for (int j = 2; j < this->M - 1; ++j) { p[j] = this->E1(j) * q[j - 1] + this->F1(j) * q[j] + this->G1(j) * q[j + 1]; } p[this->M - 1] = this->E1(this->M - 1) * q[this->M - 2] + this->F1(this->M - 1) * q[this->M - 1]; return p; } template<typename X> CNHeatEqMethod<X>::~CNHeatEqMethod() { delete this->K_1; delete this->K_2; }
//<<<<<< INCLUDES >>>>>> #include "Geometry/HcalAlgo/plugins/DDHCalAngular.h" #include "Geometry/HcalAlgo/plugins/DDHCalBarrelAlgo.h" #include "Geometry/HcalAlgo/plugins/DDHCalEndcapAlgo.h" #include "Geometry/HcalAlgo/plugins/DDHCalEndcapModuleAlgo.h" #include "Geometry/HcalAlgo/plugins/DDHCalFibreBundle.h" #include "Geometry/HcalAlgo/plugins/DDHCalForwardAlgo.h" #include "Geometry/HcalAlgo/plugins/DDHCalLinearXY.h" #include "Geometry/HcalAlgo/plugins/DDHCalTBCableAlgo.h" #include "Geometry/HcalAlgo/plugins/DDHCalTBZposAlgo.h" #include "Geometry/HcalAlgo/plugins/DDHCalTestBeamAlgo.h" #include "Geometry/HcalAlgo/plugins/DDHCalXtalAlgo.h" #include "DetectorDescription/Core/interface/DDAlgorithmFactory.h" #include "FWCore/PluginManager/interface/PluginFactory.h" DEFINE_EDM_PLUGIN(DDAlgorithmFactory, DDHCalAngular, "hcal:DDHCalAngular"); DEFINE_EDM_PLUGIN(DDAlgorithmFactory, DDHCalBarrelAlgo, "hcal:DDHCalBarrelAlgo"); DEFINE_EDM_PLUGIN(DDAlgorithmFactory, DDHCalEndcapAlgo, "hcal:DDHCalEndcapAlgo"); DEFINE_EDM_PLUGIN(DDAlgorithmFactory, DDHCalEndcapModuleAlgo, "hcal:DDHCalEndcapModuleAlgo"); DEFINE_EDM_PLUGIN(DDAlgorithmFactory, DDHCalForwardAlgo, "hcal:DDHCalForwardAlgo"); DEFINE_EDM_PLUGIN(DDAlgorithmFactory, DDHCalFibreBundle, "hcal:DDHCalFibreBundle"); DEFINE_EDM_PLUGIN(DDAlgorithmFactory, DDHCalLinearXY, "hcal:DDHCalLinearXY"); DEFINE_EDM_PLUGIN(DDAlgorithmFactory, DDHCalTBCableAlgo, "hcal:DDHCalTBCableAlgo"); DEFINE_EDM_PLUGIN(DDAlgorithmFactory, DDHCalTBZposAlgo, "hcal:DDHCalTBZposAlgo"); DEFINE_EDM_PLUGIN(DDAlgorithmFactory, DDHCalTestBeamAlgo, "hcal:DDHCalTestBeamAlgo"); DEFINE_EDM_PLUGIN(DDAlgorithmFactory, DDHCalXtalAlgo, "hcal:DDHCalXtalAlgo");
#include "gast_manager.h" #include <core/Godot.hpp> #include <core/NodePath.hpp> #include <core/Vector2.hpp> #include <core/Vector3.hpp> #include <gen/Engine.hpp> #include <gen/Input.hpp> #include <gen/InputEventAction.hpp> #include <gen/MainLoop.hpp> #include <gen/SceneTree.hpp> #include <gen/Object.hpp> #include <gen/Viewport.hpp> namespace gast { namespace { const char *kGastNodeGroupName = "gast_node_group"; } // namespace GastManager *GastManager::singleton_instance_ = nullptr; GastLoader *GastManager::gast_loader_ = nullptr; bool GastManager::gdn_initialized_ = false; bool GastManager::jni_initialized_ = false; jobject GastManager::callback_instance_ = nullptr; jmethodID GastManager::on_render_input_action_ = nullptr; jmethodID GastManager::on_render_input_hover_ = nullptr; jmethodID GastManager::on_render_input_press_ = nullptr; jmethodID GastManager::on_render_input_release_ = nullptr; jmethodID GastManager::on_render_input_scroll_ = nullptr; GastManager::GastManager() = default; GastManager::~GastManager() { reusable_pool_.clear(); } GastManager *GastManager::get_singleton_instance() { ALOG_ASSERT(gdn_initialized_, "Gast is not properly initialized."); if (singleton_instance_ == nullptr) { singleton_instance_ = new GastManager(); } return singleton_instance_; } void GastManager::delete_singleton_instance() { if (!gdn_initialized_ && !jni_initialized_) { delete singleton_instance_; singleton_instance_ = nullptr; } } void GastManager::gdn_initialize(GastLoader *gast_loader) { ALOG_ASSERT(gast_loader_ == nullptr, "Gast is already initialized."); gdn_initialized_ = true; gast_loader_ = gast_loader; } void GastManager::gdn_shutdown() { gdn_initialized_ = false; gast_loader_ = nullptr; delete_singleton_instance(); } void GastManager::jni_initialize(JNIEnv *env, jobject callback) { jni_initialized_ = true; register_callback(env, callback); } void GastManager::jni_shutdown(JNIEnv *env) { jni_initialized_ = false; unregister_callback(env); delete_singleton_instance(); } void GastManager::register_callback(JNIEnv *env, jobject callback) { callback_instance_ = env->NewGlobalRef(callback); ALOG_ASSERT(callback_instance_ != nullptr, "Invalid value for callback."); jclass callback_class = env->GetObjectClass(callback_instance_); ALOG_ASSERT(callback_class != nullptr, "Invalid value for callback."); on_render_input_action_ = env->GetMethodID(callback_class, "onRenderInputAction", "(Ljava/lang/String;IF)V"); ALOG_ASSERT(on_render_input_action_ != nullptr, "Unable to find onRenderInputAction"); on_render_input_hover_ = env->GetMethodID(callback_class, "onRenderInputHover", "(Ljava/lang/String;Ljava/lang/String;FF)V"); ALOG_ASSERT(on_render_input_hover_ != nullptr, "Unable to find onRenderInputHover"); on_render_input_press_ = env->GetMethodID(callback_class, "onRenderInputPress", "(Ljava/lang/String;Ljava/lang/String;FF)V"); ALOG_ASSERT(on_render_input_press_ != nullptr, "Unable to find onRenderInputPress"); on_render_input_release_ = env->GetMethodID(callback_class, "onRenderInputRelease", "(Ljava/lang/String;Ljava/lang/String;FF)V"); ALOG_ASSERT(on_render_input_release_ != nullptr, "Unable to find onRenderInputRelease"); on_render_input_scroll_ = env->GetMethodID(callback_class, "onRenderInputScroll", "(Ljava/lang/String;Ljava/lang/String;FFFF)V"); ALOG_ASSERT(on_render_input_scroll_ != nullptr, "Unable to find onRenderInputScroll"); } void GastManager::unregister_callback(JNIEnv *env) { if (callback_instance_) { env->DeleteGlobalRef(callback_instance_); callback_instance_ = nullptr; on_render_input_action_ = nullptr; on_render_input_hover_ = nullptr; on_render_input_press_ = nullptr; on_render_input_release_ = nullptr; on_render_input_scroll_ = nullptr; } } void GastManager::update_node_visibility(const String &node_path, bool visible) { auto *node = Object::cast_to<Spatial>(get_node(node_path)); if (!node) { ALOGE("Unable to find target node with path %s", get_node_tag(node_path)); return; } node->set_visible(visible); } GastNode *GastManager::get_gast_node(const godot::String &node_path) { auto *gast_node = Object::cast_to<GastNode>(get_node(node_path)); if (!gast_node || !gast_node->is_in_group(kGastNodeGroupName)) { ALOGW("Unable to find a GastNode node with path %s", get_node_tag(node_path)); return nullptr; } return gast_node; } Node *GastManager::get_node(const godot::String &node_path) { // First search by treating the given argument as a node path since it's more efficient. if (node_path.empty()) { ALOGE("Invalid node path argument: %s", get_node_tag(node_path)); return nullptr; } MainLoop *main_loop = Engine::get_singleton()->get_main_loop(); auto *scene_tree = Object::cast_to<SceneTree>(main_loop); if (!scene_tree) { ALOGW("Unable to retrieve scene tree."); return nullptr; } const Viewport *viewport = scene_tree->get_root(); NodePath node_path_obj(node_path); Node *node = viewport->get_node_or_null(node_path_obj); if (!node) { // Treat the parameter as the node's name and give it another try. node = viewport->find_node(node_path, true, false); } return node; } GastNode *GastManager::acquire_and_bind_gast_node(const godot::String &parent_node_path, bool empty_parent) { ALOGV("Retrieving node's parent with path %s", get_node_tag(parent_node_path)); Node *parent_node = get_node(parent_node_path); if (!parent_node) { ALOGE("Unable to retrieve parent node with path %s", get_node_tag(parent_node_path)); return nullptr; } GastNode *gast_node; // Check if we have one already setup in the reusable pool, otherwise create a new one. if (reusable_pool_.empty()) { ALOGV("Creating a new Gast node."); // Creating a new static body node gast_node = GastNode::_new(); // Add the new node to the GastNode group. This is how we keep track of the nodes // that are created and managed by this plugin. gast_node->add_to_group(kGastNodeGroupName); } else { gast_node = reusable_pool_.back(); reusable_pool_.pop_back(); } if (gast_node->get_parent() != nullptr) { ALOGV("Removing Gast node parent."); gast_node->get_parent()->remove_child(gast_node); } ALOGV("Adding the Gast node to the parent node."); if (empty_parent) { remove_all_children_from_node(parent_node); } parent_node->add_child(gast_node); gast_node->set_owner(parent_node); return gast_node; } void GastManager::unbind_and_release_gast_node(GastNode *gast_node) { // Remove the Gast node from its parent and move it to the reusable pool. if (!gast_node) { return; } // Remove the Gast node from its parent. if (gast_node->get_parent() != nullptr) { gast_node->get_parent()->remove_child(gast_node); gast_node->set_owner(nullptr); } // Move the Gast node to the reusable pool. reusable_pool_.push_back(gast_node); } void GastManager::on_process() { // Check if one of the monitored input actions was dispatched. if (input_actions_to_monitor_.empty()) { return; } Input *input = Input::get_singleton(); for (auto const& action : input_actions_to_monitor_) { InputPressState press_state = kInvalid; if (input->is_action_just_pressed(action)) { press_state = kJustPressed; } else if (input->is_action_pressed(action)) { press_state = kPressed; } else if (input->is_action_just_released(action)) { press_state = kJustReleased; } if (press_state != kInvalid) { on_render_input_action(action, press_state, input->get_action_strength(action)); } } } void GastManager::on_render_input_action(const String &action, InputPressState press_state, float strength) { if (callback_instance_ && on_render_input_action_) { JNIEnv *env = godot::android_api->godot_android_get_env(); env->CallVoidMethod(callback_instance_, on_render_input_action_, string_to_jstring(env, action), press_state, strength); } } void GastManager::on_render_input_hover(const String &node_path, const String &pointer_id, float x_percent, float y_percent) { if (gast_loader_) { gast_loader_->emitHoverEvent(node_path, pointer_id, x_percent, y_percent); } if (callback_instance_ && on_render_input_hover_) { JNIEnv *env = godot::android_api->godot_android_get_env(); env->CallVoidMethod(callback_instance_, on_render_input_hover_, string_to_jstring(env, node_path), string_to_jstring(env, pointer_id), x_percent, y_percent); } } void GastManager::on_render_input_press(const String &node_path, const String &pointer_id, float x_percent, float y_percent) { if (gast_loader_) { gast_loader_->emitPressEvent(node_path, pointer_id, x_percent, y_percent); } if (callback_instance_ && on_render_input_press_) { JNIEnv *env = godot::android_api->godot_android_get_env(); env->CallVoidMethod(callback_instance_, on_render_input_press_, string_to_jstring(env, node_path), string_to_jstring(env, pointer_id), x_percent, y_percent); } } void GastManager::on_render_input_release(const String &node_path, const String &pointer_id, float x_percent, float y_percent) { if (gast_loader_) { gast_loader_->emitReleaseEvent(node_path, pointer_id, x_percent, y_percent); } if (callback_instance_ && on_render_input_release_) { JNIEnv *env = godot::android_api->godot_android_get_env(); env->CallVoidMethod(callback_instance_, on_render_input_release_, string_to_jstring(env, node_path), string_to_jstring(env, pointer_id), x_percent, y_percent); } } void GastManager::on_render_input_scroll(const godot::String &node_path, const godot::String &pointer_id, float x_percent, float y_percent, float horizontal_delta, float vertical_delta) { if (gast_loader_) { gast_loader_->emitScrollEvent(node_path, pointer_id, x_percent, y_percent, horizontal_delta, vertical_delta); } if (callback_instance_ && on_render_input_scroll_) { JNIEnv *env = godot::android_api->godot_android_get_env(); env->CallVoidMethod(callback_instance_, on_render_input_scroll_, string_to_jstring(env, node_path), string_to_jstring(env, pointer_id), x_percent, y_percent, horizontal_delta, vertical_delta); } } bool GastManager::update_gast_node_parent(GastNode *node, const String &new_parent_node_path, bool empty_parent) { if (!node) { ALOGW("Invalid GastNode instance!"); return false; } // Check if current parent differs from new one. if (node->get_parent() != nullptr) { String parent_node_path = node->get_parent()->get_path(); if (parent_node_path == new_parent_node_path) { ALOGV("Current parent is same as newly proposed one."); return false; } } // Check if the new parent exists. Node *new_parent = get_node(new_parent_node_path); if (!new_parent) { ALOGW("Unable to retrieve new parent node with path %s", get_node_tag(new_parent_node_path)); return false; } // Perform the update if (node->get_parent() != nullptr) { node->get_parent()->remove_child(node); } if (empty_parent) { remove_all_children_from_node(new_parent); } new_parent->add_child(node); node->set_owner(new_parent); return true; } } // namespace gast
#include "stdafx.h" #include "CppUnitTest.h" #ifndef ELYSIUM_DATA_FILTERING_QUERYEXPRESSION #include "../../../Extended/01-Shared/Elysium.Data/QueryExpression.hpp" #endif #include <string> using namespace Elysium::Data::Querying; using namespace Microsoft::VisualStudio::CppUnitTestFramework; namespace UnitTestData { TEST_CLASS(UnitTestDataFiltering) { public: TEST_METHOD(Data_Filtering_Generic) { // prepare the joins JoinExpression Join1 = JoinExpression(); Join1.JoinOperator = JoinOperator::Natural; Join1.LinkFromTableName = "MyTable"; Join1.LinkFromAttributeName = "Id"; Join1.LinkToTableName = "Table1"; Join1.LinkToAttributeName = "ref_MyTable1"; JoinExpression Join2 = JoinExpression(); Join2.JoinOperator = JoinOperator::Natural; Join2.LinkFromTableName = "MyTable"; Join2.LinkFromAttributeName = "Id"; Join2.LinkToTableName = "Table2"; Join2.LinkToAttributeName = "ref_MyTable2"; // prepare the conditions ConditionExpression Condition1 = ConditionExpression(); Condition1.AttributeName = "Id"; Condition1.ConditionOperator = ConditionOperator::In; Condition1.Values = std::vector<std::string>(2); Condition1.Values[0] = "1337"; Condition1.Values[1] = "5448"; ConditionExpression Condition2 = ConditionExpression(); Condition2.AttributeName = "ClassName"; Condition2.ConditionOperator = ConditionOperator::Equal; Condition2.Values = std::vector<std::string>(1); Condition2.Values[0] = "Person"; // build a query QueryExpression Query = QueryExpression(); Query.RowCount = 10; Query.TableName = "MyTable"; Query.Columns = std::vector<std::string>(3); Query.Columns[0] = "Col1"; Query.Columns[1] = "Col2"; Query.Columns[2] = "Col3"; Query.Joins = std::vector<JoinExpression>(2); Query.Joins[0] = Join1; Query.Joins[1] = Join2; Query.Criteria.FilterOperator = LogicalOperator::Or; Query.Criteria.Conditions = std::vector<ConditionExpression>(2); Query.Criteria.Conditions[0] = Condition1; Query.Criteria.Conditions[1] = Condition2; Logger::WriteMessage("the end -> automatic scope cleanup"); // build an sql-query so we can check the output (this obviously isn't correct SQL-syntax but ok for testing) std::string SqlQuery = "SELECT "; if (Query.RowCount > 0) { SqlQuery += "TOP "; SqlQuery += std::to_string(Query.RowCount); SqlQuery += " "; } if (Query.Columns.size() == 0) { SqlQuery += "*"; } else { for (int i = 0; i < Query.Columns.size(); i++) { SqlQuery += Query.Columns[i].c_str(); if (i + 1 < Query.Columns.size()) { SqlQuery += ", "; } } } SqlQuery += "\r\nFROM "; SqlQuery += Query.TableName.c_str(); for (int i = 0; i < Query.Joins.size(); i++) { SqlQuery += "\r\n"; switch (Query.Joins[i].JoinOperator) { case JoinOperator::Inner: SqlQuery += "INNER JOIN "; break; case JoinOperator::LeftOuter: SqlQuery += "LEFT JOIN "; break; case JoinOperator::Natural: SqlQuery += "NATURAL JOIN "; break; default: break; } SqlQuery += "["; SqlQuery += Query.Joins[i].LinkFromTableName.c_str(); SqlQuery += "].["; SqlQuery += Query.Joins[i].LinkFromAttributeName.c_str(); SqlQuery += "] ON ["; SqlQuery += Query.Joins[i].LinkToTableName.c_str(); SqlQuery += "].["; SqlQuery += Query.Joins[i].LinkToAttributeName.c_str(); SqlQuery += "]"; } if (Query.Criteria.Conditions.size() > 0) { SqlQuery += "\r\nWHERE "; for (int i = 0; i < Query.Criteria.Conditions.size(); i++) { SqlQuery += Query.Criteria.Conditions[i].AttributeName.c_str(); switch (Query.Criteria.Conditions[i].ConditionOperator) { case ConditionOperator::In: SqlQuery += " IN "; break; case ConditionOperator::Equal: SqlQuery += " = "; break; default: break; } for (int j = 0; j < Query.Criteria.Conditions[i].Values.size(); j++) { SqlQuery += Query.Criteria.Conditions[i].Values[j].c_str(); if (j + 1 < Query.Criteria.Conditions[i].Values.size()) { SqlQuery += ", "; } } if (i + 1 < Query.Criteria.Conditions.size()) { switch (Query.Criteria.FilterOperator) { case LogicalOperator::And: SqlQuery += "\r\nAND "; break; case LogicalOperator::Or: SqlQuery += "\r\OR "; break; default: break; } } } } // output Logger::WriteMessage(SqlQuery.c_str()); } }; }
#ifndef CONNECT_MODE_HPP #define CONNECT_MODE_HPP #include <boost/asio/io_service.hpp> #include "settings.hpp" #include "scoped_descriptor.hpp" #include "exception.hpp" namespace sp { class connect_mode { public: typedef sp::exception<connect_mode> exception; connect_mode(boost::asio::io_service& ios, const settings& st, shared_descriptor tap); void setup(); // throws exception private: class private_t; boost::shared_ptr<private_t> p; }; } #endif // CONNECT_MODE_HPP
#include <conio.h> #include <stdlib.h> #include <stdio.h> #include <time.h> #include <string.h> #include <math.h> #include <locale.h> #include <ctype.h> int ladoa,ladob,ladoc; int x=0; int main() { printf(" \n Digite a primeira medida:\n"); scanf("%d",&ladoa); printf(" \n Digite a segunda medida:\n"); scanf("%d",&ladob); printf(" \n Digite a terceira medida:\n"); scanf("%d",&ladoc); if(((ladoa*ladoa)+(ladob*ladob))==(ladoc*ladoc)) { printf("\nIsso e um triangulo retangulo"); } else if(((ladoa*ladoa)+(ladoc*ladoc))==(ladob*ladob)) { printf("\nIsso e um triangulo retangulo"); } else if(((ladob*ladob)+(ladoc*ladoc))==(ladoa*ladoa)) { printf("\nIsso e um triangulo retangulo"); } else { printf("\nIsso nao e um triangulo retangulo"); } }
#include "LytWString.h" LytWString::LytWString() { Length=0; String=new wchar_t[Length+1]; wcscpy(String,L""); } LytWString::LytWString(const wchar_t& Temp) { Length=1; String=new wchar_t[Length+1]; String[0]=Temp; String[1]=0; } LytWString::LytWString(const wchar_t* Temp) { Length=(int)wcslen(Temp); String=new wchar_t[Length+1]; wcscpy(String, Temp); } LytWString::LytWString(const LytWString& Temp) { Length=Temp.Length; String=new wchar_t[Length+1]; wcscpy(String, Temp.String); } LytWString LytWString::operator=(const wchar_t* Temp) { Length=(int)wcslen(Temp); delete[] String; String=new wchar_t[Length+1]; wcscpy(String, Temp); return *this; } LytWString LytWString::operator=(const LytWString& Temp) { Length=Temp.Length; delete[] String; String=new wchar_t[Length+1]; wcscpy(String, Temp.String); return *this; } bool LytWString::operator==(const LytWString& Temp)const { if (wcscmp(String, Temp.String)==0) return true; else return false; } bool LytWString::operator!=(const LytWString& Temp)const { if (wcscmp(String, Temp.String)!=0) return true; else return false; } bool LytWString::operator>(const LytWString& Temp)const { if (wcscmp(String, Temp.String)>0) return true; else return false; } bool LytWString::operator<(const LytWString& Temp)const { if (wcscmp(String, Temp.String)<0) return true; else return false; } bool LytWString::operator>=(const LytWString& Temp)const { if (wcscmp(String, Temp.String)>=0) return true; else return false; } bool LytWString::operator<=(const LytWString& Temp)const { if (wcscmp(String, Temp.String)<=0) return true; else return false; } LytWString LytWString::operator+(const LytWString& Temp)const { wchar_t* s=new wchar_t[Length+Temp.Length+1]; wcscpy(s,String); wcscat(s,Temp.String); s[Length+Temp.Length]=0; LytWString Result=s; delete[] s; return Result; } LytWString LytWString::operator+(const wchar_t* Temp)const { LytWString TempLeft=String; LytWString TempRight=Temp; return TempLeft+TempRight; } LytWString operator+(const wchar_t* TempLeft, const LytWString& TempRight)///////////为什么不可以加const { LytWString Temp=TempLeft; return Temp+TempRight; } LytWString LytWString::operator++()/////////////////////////////////// { String++; Length--; return *this; } LytWString LytWString::operator++(int) { LytWString Temp=*this; ++(*this); return Temp; } LytWString LytWString::operator--() { String--; Length++; return *this; } LytWString LytWString::operator--(int) { LytWString Temp=*this; --(*this); return Temp; } wostream& operator<<(wostream& Output, const LytWString& Temp) { Output<<Temp.String; return Output; } wistream& operator>>(wistream& Input, LytWString& Temp) { wchar_t Buffer[1000]; Input>>Buffer; Temp=Buffer; return Input; } LytWString Wchar_tToLytWString(const wchar_t& Temp) { wchar_t Input[2]; Input[0]=Temp; Input[1]=L'\0'; LytWString Result=Input; return Result; } LytWString LytWString::Sub(const int Index, const int Count)const { if (Index<0 || Index>Length-1 || Count<1 || Count>Length-Index) { LytWString Temp=L""; return Temp; } else { wchar_t* Result=new wchar_t[Count+1]; int Position=Index; for(int i=0; i<=Count-1; i++) { Result[i]=String[Position]; Position++; } Result[Count]=0; LytWString Temp=Result; delete[] Result; return Temp; } } void LytWString::Insert(const int Index, const LytWString Temp) { if (Index>=0 && Index<=Length-1 && wcscmp(Temp.String,L"")!=0) { LytWString S1=String; LytWString S2=S1.Sub(0,Index); LytWString S3=S1.Sub(Index,Length-Index); S1=S2+Temp+S3; delete[] String; Length=Length+Temp.Length; String=new wchar_t[Length+1]; wcscpy(String,S1.String); } } void LytWString::Delete(int Index, int Count) { if (Index>=0 && Index<=Length-1 && Count>0 && Count<=Length-Index) { LytWString S1=String; LytWString S2=S1.Sub(0,Index); LytWString S3=S1.Sub(Index+Count,Length-Count-Index); S1=S2+S3; delete[] String; Length=Length-Count; String=new wchar_t[Length+1]; wcscpy(String,S1.String); } } LytWString LytWString::ToUpper()const { wchar_t* Result=new wchar_t[Length+1]; wcscpy(Result, String); for (int i=0; i<=Length-1; i++) { if (Result[i]>='a' && Result[i]<='z') Result[i]=Result[i]-32; } Result[Length]=0; LytWString Temp=Result; delete[] Result; return Temp; } LytWString LytWString::ToLower()const { wchar_t* Result=new wchar_t[Length+1]; wcscpy(Result, String); for(int i=0; i<=Length-1; i++) { if (Result[i]>='A' && Result[i]<='Z') Result[i]=Result[i]+32; } Result[Length]=0; LytWString Temp=Result; delete[] Result; return Temp; } LytWString LytWString::Left(const int Count)const { if (Count<=0 || Count>Length) { LytWString Temp=L""; return Temp; } else { LytWString Temp=String; return Temp.Sub(0,Count); } } LytWString LytWString::Right(const int Count)const { if (Count<=0 && Count>Length) { LytWString Temp=L""; return Temp; } else { LytWString Temp=String; return Temp.Sub(Length-Count,Count); } } LytWString LytWString::TrimLeft()const { if (String[0]==L' ') { int Position=0; bool Judge=true; while (Judge==true && Position<=Length-1) { if (String[Position]!=L' ') Judge=false; else Position++; } if (Judge==false) { LytWString Temp=String; return Temp.Sub(Position, Length-Position); } else { LytWString Temp=L""; return Temp; } } else { LytWString Temp=String; return Temp; } } LytWString LytWString::TrimRight()const { if(String[Length-1]==L' ') { int Position=Length-1; bool Judge=true; LytWString Temp=String; while (Judge==true && Position>=0) { if (String[Position]!=L' ') Judge=false; else Position--; } if (Judge==false) { LytWString Temp=String; return Temp.Sub(0, Position+1); } else { LytWString Temp=L""; return Temp; } } else { LytWString Temp=String; return Temp; } } LytWString LytWString::Trim()const { return TrimLeft().TrimRight(); } int LytWString::Pos(const LytWString& Temp)const { if (wcscmp(String, Temp.String)==0) return 0; else if(wcscmp(Temp.String, L"")==0) return -1; else { int i=-1,wei1=0,wei2=0; while (wei1<=Length-1 && wei2<=Temp.Length-1) { if (String[wei1]==Temp.String[wei2]) { int j=wei1; bool pd=true; wei1=wei1+1; wei2=wei2+1; while (pd==true && wei1<=Length-1 && wei2<=Temp.Length-1) { if (String[wei1]!=Temp.String[wei2]) {pd=false;} else { wei1=wei1+1; wei2=wei2+1; } } if (pd==true) { i=j; break; } else { wei2=0; wei1=j+1;; } } else {wei1=wei1+1;} } return i; } } int LytWString::Replace(const LytWString& Find , const LytWString& Result) { LytWString S1=String; int k=S1.Pos(Find); if (wcscmp(Find.String, L"")==0 || k==-1) return 0; else if (wcscmp(Find.String, Result.String)==0) return 1; else if (wcscmp(String, Find.String)==0) { delete[] String; Length=Result.Length; String=new wchar_t[Length+1]; wcscpy(String, Result.String); return 1; } else { LytWString S2; int i=0; while(k!=-1) { S1.Delete(k,Find.Length); S1.Insert(k,Result); i=i+1; S2=S2+S1.Sub(0,k+Result.Length+1); S1=S1.Sub(k+Result.Length+1,S1.Length-k-Result.Length-1); k=S1.Pos(Find); } delete[] String; Length=S2.Length; String=new wchar_t[Length+1]; wcscpy(String, S2.String); return i; } } int LytWString::Size()const { return Length; } wchar_t& LytWString::operator[](int Index) { return String[Index]; } const wchar_t* LytWString::Buffer()const { return String; } LytWString::~LytWString() { delete[] String; }
// Problem => Pascal Triangle #include<iostream> using namespace std; int main(){ int row, col, space, n, no; cout<<"Please enter number of rows: "; cin>>no; for(row = 0; row<no; row++){ // Loop to print space for(space=0; space< (no - row); space++){ cout<<" "; } n=1; // Loop to print the values in the triangle for(col = 0; col <= row; col++){ cout<<" "<<n; // Main formula n = n*(row - col) / (col + 1); } cout<<endl; } return 0; } /* ## If we want to find the a particular element from the pascal triangle, suppose element at 5,3 then in that case you can use this formula r-1 C c-1 => 5 C 2 => 4x3/2x1 = 6 Time complexity = O(n) ## If you want to print a particular row of the Pascal Triangle 1. First create n dynamic vectors (which will be empty) @ After that we */ // Optimizied Solution /* class Solution { public: vector<vector<int>> generate(int numRows) { vector<vector<int>> r(numRows); for(int i=0; i < numRows; i++){ r[i].resize(i+1); r[i][0] = r[i][i] = 1; for(int j=1; j < i; j++){ r[i][j] = r[i-1][j-1] + r[i-1][j]; } } return r; } }; */
#include <iostream> using namespace std; int f(int n) { int a[10000]; if(n==1)return 0; return f(n-1); } int main() { int n; cin>>n; f(n); return 0; //52 }
// Fill out your copyright notice in the Description page of Project Settings. #include "Hypoxia.h" #include "TestGlowItem.h" ATestGlowItem::ATestGlowItem() { Light = CreateDefaultSubobject<UPointLightComponent>(TEXT("Glow")); Light->SetIntensity(0.0f); Light->SetupAttachment(Item); } void ATestGlowItem::Tick(float deltaTime) { GlowIntensity -= 10.0f; GlowIntensity = FMath::Max(0.f, GlowIntensity); Light->SetIntensity(GlowIntensity); } void ATestGlowItem::Hear(float volume) { GlowIntensity = FMath::Max(GlowIntensity, volume * 20.f); }
#include <iostream> class Queue { private: int size; int count; int *arr; public: Queue(int a = 5) { size = a; count = 0; arr = new int [size]; for(int i = 0; i < size; ++i) { arr[i] = -1; } } ~Queue() { delete[] arr; } Queue (Queue& obj) { this -> size = obj.getSize(); this -> count = obj.getCount(); this -> arr = new int [size]; for(int i = 0; i < size; ++i) { this -> arr[i] = obj.arr[i]; } } int getSize (void) { return this -> size; } int getCount (void) { return this -> count; } void push (int el) { if (count >= size) { int* temp; temp = new int [size + 5]; for(int i = 0; i < size; ++i) { temp[i + 1] = arr[i]; } for (int i = size; i < size + 5; ++i) { temp[i] = -1; } temp[0] = el; delete [] arr; arr = temp; temp = NULL; size = size + 5; } else { for(int i = size - 1; i > 0; --i) { arr[i] = arr[i - 1]; } arr[0] = el; } count++; } void pop (void) { if ( count + 5 == size) { int* temp; temp = new int [count]; for (int i = 0; i < count; ++i ) { temp[i] = arr[i]; } delete [] arr; arr = temp; temp = NULL; size = count; } arr[count - 1] = 0; --count; } void print() { for(int i = 0; i < count; ++i) { std::cout << "queue[" << i << "]=" << arr[i] << std::endl; } std::cout << "Count = " << count << std::endl; std::cout << "Size = " << size <<std::endl; std::cout<< std::endl; } }; int main() { Queue obj(5); obj.print(); obj.push(1); obj.print(); obj.push(2); obj.print(); obj.push(3); obj.print(); obj.push(4); obj.print(); obj.push(5); obj.print(); obj.push(6); obj.print(); obj.push(7); obj.print(); obj.push(8); obj.print(); obj.push(9); obj.print(); obj.push(10); obj.print(); obj.push(11); obj.print(); obj.pop(); obj.print(); obj.pop(); obj.print(); obj.pop(); obj.print(); obj.pop(); obj.print(); obj.pop(); obj.print(); obj.pop(); obj.print(); obj.pop(); obj.print(); obj.pop(); obj.print(); return 0; }
/**************************************************************************** * * * Author : lukasz.iwaszkiewicz@gmail.com * * ~~~~~~~~ * * License : see COPYING file for details. * * ~~~~~~~~~ * ****************************************************************************/ #ifndef BAJKA_LAYOUTS_TABLEGROUP_H_ #define BAJKA_LAYOUTS_TABLEGROUP_H_ #include "util/ReflectionMacros.h" #include "model/IBox.h" #include "model/Group.h" namespace Model { class TableGroup : public IBox, public Group { public: C__ (void) b_ ("Group") TableGroup () : w (0), h (0), cols (0), spacing (0), margin (0), wrapContentsW (false), wrapContentsH (false), heterogeneous (true) {} virtual ~TableGroup () {} // TODO większość metod wspólna z LinearGroup - zrobić nadklasę bool getWrapContentsW () const { return wrapContentsW; } void setWrapContentsW (bool b) { wrapContentsW = b; } bool getWrapContentsH () const { return wrapContentsH; } void setWrapContentsH (bool b) { wrapContentsH = b; } /*--layout------------------------------------------------------------------*/ void updateLayout (); virtual void update (Event::UpdateEvent *e, Util::UpdateContext *uCtx); /*--IBox--------------------------------------------------------------------*/ double getWidth () const { return w; } m_ (setWidth) void setWidth (double w) { this->w = w; } double getHeight () const { return h; } m_ (setHeight) void setHeight (double h) { this->h = h; } Geometry::Box getBox () const { return Geometry::Box (0, 0, w - 1, h - 1); } /*--------------------------------------------------------------------------*/ bool isBox () const { return true; } virtual CoordinateSystemOrigin getCoordinateSystemOrigin () const { return CENTER; } virtual Geometry::Box getBoundingBoxImpl (Geometry::AffineMatrix const &transformation) const; virtual bool contains (Geometry::Point const &p) const; virtual IModel *findContains (Geometry::Point const &p); private: void adjustMyDimensions (float w, float h); void getChildrenDimensions (float *w, float *h, float colsW[], float rowsH[], int cols, int rows); private: float w, h; int p_ (cols); float p_ (spacing); float p_ (margin); bool p_ (wrapContentsW); bool p_ (wrapContentsH); bool p_ (heterogeneous); E_ (TableGroup) }; } /* namespace Model */ #endif /* TABLEGROUP_H_ */
class ItemCrowbar : ItemCore { scope = 2; model = "\dayz_equip\models\crowbar.p3d"; picture = "\z\addons\dayz_communityassets\pictures\equip_crowbar_CA.paa"; displayName = $STR_EQUIP_NAME_CROWBAR; descriptionShort = $STR_EQUIP_DESC_CROWBAR; class ItemActions { class Toolbelt { text = $STR_ACTIONS_RFROMTB; script = "spawn player_addToolbelt;"; use[] = { "ItemCrowbar" }; output[] = { "MeleeCrowbar" }; }; class ToBack { text = $STR_ACTIONS_2BACK; script = "spawn player_addtoBack;"; use[] = { "ItemCrowbar" }; output[] = { "MeleeCrowbar" }; }; }; }; class ItemCrowbarBent : ItemCore { scope = 2; model = "\dayz_equip\models\crowbar.p3d"; picture = "\dayz_epoch_c\icons\tools\ItemCrowbarBroken.paa"; displayName = $STR_EQUIP_NAME_CROWBARBENT; descriptionShort = $STR_EQUIP_DESC_CROWBARBENT; class ItemActions { class Repair { text = $STR_ACTIONS_FIX_CROWBAR; script = ";['Repair','CfgWeapons', _id] spawn player_craftItem;"; neednearby[] = {"fire"}; requiretools[] = {"ItemToolbox"}; output[] = {}; outputweapons[] = {"ItemCrowbar"}; input[] = {{"PartGeneric",1}}; inputweapons[] = {"ItemCrowbarBent"}; }; }; };
// // NamedEvent.cpp // // $Id: //poco/1.4/Foundation/src/NamedEvent.cpp#2 $ // // Library: Foundation // Package: Processes // Module: NamedEvent // // Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. // and Contributors. // // SPDX-License-Identifier: BSL-1.0 // #include "_/NamedEvent.h" #if defined(___OS_Win32) && defined(___WIN32_UTF8) #include "NamedEvent_WIN32U.cpp" #elif defined(___OS_Win32) #include "NamedEvent_WIN32.cpp" #elif defined(___ANDROID) #include "NamedEvent_Android.cpp" #elif defined(___OS_FAMILY_UNIX) #include "NamedEvent_UNIX.cpp" #else #include "NamedEvent_VMS.cpp" #endif namespace _ { NamedEvent::NamedEvent(const std::string& name): NamedEventImpl(name) { } NamedEvent::~NamedEvent() { } } // namespace _
#include<stdio.h> #include<conio.h> void swap(char *a,char *b) { int t=*a; *a=*b; *b=t; } void permute(char a[],int start,int end) { if(start == end) printf("%s\n",a); for(int j=start;j<=end;j++) { swap((a+start) , (a+j)); permute(a,start+1,end); swap((a+start) , (a+j)); } } int main() { char a[] = "ABCD"; permute(a,0,3); getch(); }
#include "GnMeshPCH.h" #include "GnGamePCH.h" #include "GUserCtlrManager.h" #include "GUserController.h" #include "GnIButton.h" #include "GInterfaceLayer.h" #include "GCollectComponentHeader.h" #include "GInfoBasic.h" #include "GActionAttackCheck.h" #include "GFarAttack.h" #include "GBoltAttack.h" GUserCtlrManager* GUserCtlrManager::CreateActorCtlrManager(GLayer* pActorLayer, GLayer* pInterfaceLayer) { GUserCtlrManager* ctlrManager = GnNew GUserCtlrManager(pActorLayer, pInterfaceLayer); return ctlrManager; } GUserCtlrManager::GUserCtlrManager(GLayer* pActorLayer, GLayer* pInterfaceLayer) : GActorCtlrManager( pActorLayer ), mpInterfaceLayer( (GInterfaceLayer*)pInterfaceLayer ) , mMoveInputEvent( this, &GUserCtlrManager::Move ), mSkillInputEvent( this, &GUserCtlrManager::SkillInput ) { //InitUI(); } GUserCtlrManager::~GUserCtlrManager() { } void GUserCtlrManager::Update(float fDeltaTime) { GActorCtlrManager::Update( fDeltaTime ); GetGameEnvironment()->UserMove( mpUserCtlr ); UpdateBackgroundLayer(); } void GUserCtlrManager::UpdateBackgroundLayer() { float movePoint = GetGameState()->GetGameWidth() / 2; GnVector2 userPos = mpUserCtlr->GetMesh()->GetPositionFromImageCenter(); if( movePoint < userPos.x ) { GActionMove* move = (GActionMove*)mpUserCtlr->GetCurrentAction( GAction::ACTION_MOVE ); if( move == NULL ) return; if( move->GetMoveLeft() ) { CCSize bgSize = GetActorLayer()->getContentSize(); if( bgSize.width - movePoint >= userPos.x ) GetActorLayer()->MoveLayer( move->GetMoveRange().x, 0.0f ); } else if( move->GetMoveRight() ) { GetActorLayer()->MoveLayer( -move->GetMoveRange().x, 0.0f ); } } } void GUserCtlrManager::Init() { float saveScale = GetGameState()->GetGameScale(); GetGameState()->SetGameScale( DEFAULT_SCALE ); mpUserCtlr = GUserController::Create( "C1", 1 ); GetGameState()->SetGameScale( saveScale ); GetGameEnvironment()->CreateActorControllerBasicAction( mpUserCtlr ); GetGameEnvironment()->UserMove( mpUserCtlr ); GetGameEnvironment()->InitActorControllerAction( GetActorLayer(), mpUserCtlr ); GetGameEnvironment()->SetStartPositionToActor( mpUserCtlr, 1, 0 ); GnVector2 pos = mpUserCtlr->GetPosition(); pos.x = 50.0f; mpUserCtlr->SetPosition( pos ); AddActorCtlr( mpUserCtlr ); mpButtonGroup = mpInterfaceLayer->CreateInterface( (gtuint)GInterfaceLayer::UI_MAIN_CONTROLLERS, &mMoveInputEvent ); mpInterfaceLayer->CreateInterface( (gtuint)GInterfaceLayer::UI_MAIN_SKILL, &mSkillInputEvent ); } gint32 GUserCtlrManager::GetUserCurrentHP() { GCurrentActorInfo* curInfo = mpUserCtlr->GetCurrentInfo(); return curInfo->GetHP(); } void GUserCtlrManager::Move(GnInterface* pInterface, GnIInputEvent* pEvent) { if( pEvent->GetEventType() == GnIInputEvent::MOVE ) return; // stop check bool setStand = true; for ( gtuint i = 0; i < GInterfaceLayer::MOVE_NUM; i++ ) { if( mpButtonGroup->GetChild( i )->IsPush() ) { setStand = false; break; } } if( setStand ) { mpUserCtlr->RemoveCurrentAction( GAction::ACTION_MOVE ); mpUserCtlr->AddCurrentAction( mpUserCtlr->GetActionComponent( GAction::ACTION_STAND ) ); return; } if( mpUserCtlr->IsEnableMove() == false ) return; // move GActionMove* move = (GActionMove*)mpUserCtlr->GetActionComponent( GAction::ACTION_MOVE ); if( move == NULL ) return; if( mpUserCtlr->GetCurrentAction( move->GetActionType() ) == NULL ) { mpUserCtlr->AddCurrentAction( move ); } move->CleanMove(); bool moveLeft = mpButtonGroup->GetChild( GInterfaceLayer::MOVELEFT )->IsPush() || mpButtonGroup->GetChild( GInterfaceLayer::MOVELEFTSMALL )->IsPush() || mpButtonGroup->GetChild( GInterfaceLayer::MOVELEFTUP )->IsPush() || mpButtonGroup->GetChild( GInterfaceLayer::MOVELEFTUPSMALL )->IsPush() || mpButtonGroup->GetChild( GInterfaceLayer::MOVELEFTDOWN )->IsPush() || mpButtonGroup->GetChild( GInterfaceLayer::MOVELEFTDOWNSMALL )->IsPush(); bool moveRight = mpButtonGroup->GetChild( GInterfaceLayer::MOVERIGHT )->IsPush() || mpButtonGroup->GetChild( GInterfaceLayer::MOVERIGHTSMALL )->IsPush() || mpButtonGroup->GetChild( GInterfaceLayer::MOVERIGHTUP )->IsPush() || mpButtonGroup->GetChild( GInterfaceLayer::MOVERIGHTUPSMALL )->IsPush() || mpButtonGroup->GetChild( GInterfaceLayer::MOVERIGHTDOWN )->IsPush() || mpButtonGroup->GetChild( GInterfaceLayer::MOVERIGHTDOWNSMALL )->IsPush(); move->SetMoveX( moveLeft, moveRight ); bool moveUp = mpButtonGroup->GetChild( GInterfaceLayer::MOVEUP )->IsPush() || mpButtonGroup->GetChild( GInterfaceLayer::MOVEUPSMALL )->IsPush() || mpButtonGroup->GetChild( GInterfaceLayer::MOVELEFTUP )->IsPush() || mpButtonGroup->GetChild( GInterfaceLayer::MOVELEFTUPSMALL )->IsPush() || mpButtonGroup->GetChild( GInterfaceLayer::MOVERIGHTUP )->IsPush() || mpButtonGroup->GetChild( GInterfaceLayer::MOVERIGHTUPSMALL )->IsPush(); bool moveDown = mpButtonGroup->GetChild( GInterfaceLayer::MOVEDOWN )->IsPush() || mpButtonGroup->GetChild( GInterfaceLayer::MOVEDOWNSMALL )->IsPush() || mpButtonGroup->GetChild( GInterfaceLayer::MOVELEFTDOWN )->IsPush() || mpButtonGroup->GetChild( GInterfaceLayer::MOVELEFTDOWNSMALL )->IsPush() || mpButtonGroup->GetChild( GInterfaceLayer::MOVERIGHTDOWN )->IsPush() || mpButtonGroup->GetChild( GInterfaceLayer::MOVERIGHTDOWNSMALL )->IsPush(); move->SetMoveY( moveUp, moveDown ); } void GUserCtlrManager::SkillInput(GnInterface* pInterface, GnIInputEvent* pEvent) { if( pEvent->GetEventType() != GnIInputEvent::PUSH ) return; GFarAttack* attack = GFarAttack::CreateAttack( (gtuint)pInterface->GetTegID() ); if( attack && attack->GetBasicStartPosition() == GFarAttack::eUserPosition ) { attack->SetFilpX( mpUserCtlr->GetMesh()->GetFlipX() ); attack->SetPosition( mpUserCtlr->GetPosition() ); AddFarAttack( attack, (int)(GetGameState()->GetGameHeight() - mpUserCtlr->GetPosition().y) ); } else if( attack ) { GnVector2ExtraData* pos = NULL; if( eIndexItemFire != pInterface->GetTegID() ) pos = (GnVector2ExtraData*) mpUserCtlr->GetMesh()->GetExtraDataFromType( GExtraData::EXTRA_FARATTACK_POSITION ); else pos = (GnVector2ExtraData*) mpUserCtlr->GetMesh()->GetExtraDataFromType( GExtraData::EXTRA_HEROFIRE_POSITION ); if( pos ) { GnVector2 effectPos = mpUserCtlr->GetMesh()->GetPosition() + pos->GetValueVector2(); attack->SetFilpX( mpUserCtlr->GetMesh()->GetFlipX() ); attack->SetPosition( effectPos ); AddFarAttack( attack, (int)(GetGameState()->GetGameHeight() - mpUserCtlr->GetPosition().y) ); } } }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4; c-file-style: "stroustrup" -*- * * Copyright (C) Opera Software ASA 2012 * * ECMAScript source formatter. */ #include "core/pch.h" #include "modules/ecmascript/carakan/src/es_pch.h" #include "modules/ecmascript/carakan/src/compiler/es_compiler_expr.h" #include "modules/ecmascript/carakan/src/util/es_formatter.h" #include "modules/ecmascript/carakan/src/util/es_formatter_inlines.h" ES_Formatter::ES_Formatter(ES_Lexer *lexer, ES_Context *context, bool is_eval) : expression_stack_used(0) , statement_stack_used(0) , identifier_stack_used(0) , context(context) , gclock(context) , out_text(NULL) , appender(NULL) , lexer(lexer) , program_lexer(context) , depth(0) , strings_table(NULL) , ident_arguments(context->rt_data->idents[ESID_arguments]) , ident_eval(context->rt_data->idents[ESID_eval]) , allow_return_in_program(FALSE) , allow_linebreak(true) , linebreak_seen(false) , is_eval(is_eval) , in_typeof(0) , in_function(0) , in_with(0) , last_char_is_linebreak(true) , can_append_linebreak(true) , is_linebreak_scheduled(false) , is_space_scheduled(false) { state.indent_level = state.brace_indent_level = 0; } ES_Formatter::~ES_Formatter() { OP_DELETE(appender); } void ES_Formatter::Initialize() { out_text = JString::Make(context); appender = OP_NEW_L(ES_JString_Appender, (context, out_text)); lexer->SetEmitComments(TRUE); lexer->SetStringsTable(strings_table = ES_Identifier_List::Make(context, 256)); JString **idents = context->rt_data->idents; unsigned index; /* The following ensures that any occurence of these identifiers (or even any occurence of them as string literals!) are shared, and thus identifiable by plain pointer comparisons. FIXME: Is it a problem that "random" string literals can use strings allocated on the shared rt_data heap? */ strings_table->AppendL(context, ident_arguments, index); strings_table->AppendL(context, ident_eval, index); strings_table->AppendL(context, idents[ESID_length], index); strings_table->AppendL(context, idents[ESID_proto], index); stack_base = reinterpret_cast<unsigned char *>(&index); OP_ASSERT(ES_MINIMUM_STACK_REMAINING < ES_CARAKAN_PARM_MAX_PARSER_STACK); } BOOL ES_Formatter::FormatProgram(uni_char *&program_text_out, unsigned &program_text_out_length, BOOL allow_top_level_function_expr) { OP_ASSERT(lexer); Initialize(); if (ParseSourceElements(false, !!allow_top_level_function_expr)) { JString *formatted = appender->GetString(); program_text_out = Storage(context, formatted); program_text_out_length = formatted->length; return TRUE; } return FALSE; } BOOL ES_Formatter::FormatProgram(JString *&program_string) { const uni_char *program = Storage(context, program_string); unsigned program_length = Length(program_string); ES_Fragments program_fragments; program_fragments.fragments = &program; program_fragments.fragment_lengths = &program_length; program_fragments.fragments_count = 1; program_lexer.SetSource(&program_fragments, program_string); lexer = &program_lexer; Initialize(); if (ParseSourceElements(false)) { program_string = appender->GetString(); return TRUE; } return FALSE; } BOOL ES_Formatter::FormatFunction(uni_char *&body_out, unsigned &body_out_length, const uni_char *body, unsigned body_length) { ES_Fragments fbody(&body, &body_length); ES_Lexer lexer_body(context, NULL, &fbody); lexer = &lexer_body; lexer->SetStringsTable(strings_table); Initialize(); ++in_function; if (ParseSourceElements(false) && token.type == ES_Token::END) { --in_function; body_out = Storage(context, appender->GetString()); body_out_length = Length(appender->GetString()); return TRUE; } return FALSE; } bool ES_Formatter::ParseSourceElements(bool is_body, bool allow_top_level_function_expr) { if (!(is_body ? ParsePunctuator(ES_Token::LEFT_BRACE) : NextToken()) || !HandleLinebreak()) return false; unsigned depth_before = depth; while (token.type != ES_Token::END && !(is_body && token.type == ES_Token::PUNCTUATOR && token.punctuator == ES_Token::RIGHT_BRACE)) { if (token.type == ES_Token::KEYWORD && token.keyword == ES_Token::KEYWORD_FUNCTION) { if (!ParseFunctionDecl(false, allow_top_level_function_expr)) return false; } else if (!ParseStatement()) return false; if (!HandleLinebreak()) return false; } depth = depth_before; return true; } bool ES_Formatter::ParseFunctionDecl(bool skip_function_kw, bool allow_top_level_function_expr) { ScopedContext scoped_context(state, IN_FUNC_DECL); JString *function_name; ++in_function; if (skip_function_kw || ParseKeyword(ES_Token::KEYWORD_FUNCTION)) { if (ParseIdentifier(function_name)) { ScopedIndent scoped_indent(state); if (ParsePunctuator(ES_Token::LEFT_PAREN) && ParseFormalParameterList() && ParsePunctuator(ES_Token::RIGHT_PAREN) && ParseSourceElements(true) && ParsePunctuator(ES_Token::RIGHT_BRACE)) { --in_function; ScheduleLinebreak(); return true; } } else if (is_eval || allow_top_level_function_expr) { --in_function; if (!ParseFunctionExpr()) return false; else { PopExpression(); PushStatement(); return true; } } } return false; } bool ES_Formatter::ParseFunctionExpr() { ScopedContext scoped_context(state, IN_FUNC_EXPR); JString *function_name; unsigned identifiers_before = identifier_stack_used; unsigned statements_before = statement_stack_used; if (IsNearStackLimit()) return false; ++in_function; if (ParseKeyword(ES_Token::KEYWORD_FUNCTION, true)) { if (ParseIdentifier(function_name, true)) { ScopedIndent scoped_indent(state); if (ParsePunctuator(ES_Token::LEFT_PAREN) && ParseFormalParameterList() && ParsePunctuator(ES_Token::RIGHT_PAREN) && ParseSourceElements(true) && ParsePunctuator(ES_Token::RIGHT_BRACE)) { unsigned parameter_names_count = identifier_stack_used - identifiers_before; unsigned statements_count = statement_stack_used - statements_before; PopIdentifiers(parameter_names_count); PopStatements(statements_count); --in_function; /* ES_FunctionExpr. */ PushExpression(false); return true; } } } return false; } bool ES_Formatter::ParseFormalParameterList() { JString *parameter_name; if (!ParseIdentifier(parameter_name)) return true; while (1) { PushIdentifier(); if (!ParsePunctuator(ES_Token::COMMA)) return true; if (!ParseIdentifier(parameter_name)) return false; } } bool ES_Formatter::ParseArguments(unsigned depth) { bool first = true; while (1) { if (ParsePunctuator(ES_Token::RIGHT_PAREN)) return true; if (!first && !ParsePunctuator(ES_Token::COMMA)) return false; else if (!ParseExpression(depth, ES_Expression::PROD_ASSIGNMENT_EXPR, true, expression_stack_used)) return false; first = false; } } bool ES_Formatter::ParseVariableDeclList(unsigned depth, bool allow_in) { bool first = true; while (1) { JString *identifier; ScopedIndent scoped_indent(state); if (!first && state.context != IN_FOR_DECL_LIST) ScheduleLinebreak(); if (!ParseIdentifier(identifier)) return !first; if (ParsePunctuator(ES_Token::ASSIGN)) { if (!ParseExpression(depth, ES_Expression::PROD_ASSIGNMENT_EXPR, allow_in, expression_stack_used)) return false; /* Pop "initializer". */ PopExpression(); } if (token.type == ES_Token::INVALID) return false; PushIdentifier(); /* ES_AssignExpr. */ PushExpression(false); if (!ParsePunctuator(ES_Token::COMMA)) return true; first = false; } } bool ES_Formatter::ParseProperty(JString *&i, bool opt) { ES_Value_Internal v; bool regexp; if (!ParseIdentifier(i, opt, true)) if (ParseLiteral(v, i, regexp, opt)) if (regexp) return false; else switch (v.Type()) { case ESTYPE_INT32: case ESTYPE_DOUBLE: case ESTYPE_STRING: break; default: return false; } else return false; return true; } bool ES_Formatter::ParseLiteral(ES_Value_Internal &v, JString *&i, bool &regexp, bool opt) { if (!HandleLinebreak()) return false; v.SetUndefined(); if (token.type != ES_Token::LITERAL) { lexer->RevertTokenRegexp(); token = lexer->GetToken(); if (token.type != ES_Token::LITERAL) { if (token.type == ES_Token::INVALID) return false; return opt; } else regexp = true; } else regexp = false; v = token.value; AppendLiteral(i = lexer->GetTokenAsJString(false)); if (!NextToken()) return false; return true; } bool ES_Formatter::ParseSemicolon(bool opt) { if (token.type == ES_Token::PUNCTUATOR && token.punctuator == ES_Token::SEMICOLON) { AppendPunctuator(); return NextToken(); } else if (opt || linebreak_seen || token.type == ES_Token::LINEBREAK || token.type == ES_Token::END || (token.type == ES_Token::PUNCTUATOR && token.punctuator == ES_Token::RIGHT_BRACE)) return true; else return false; } bool ES_Formatter::ParseStatement(unsigned depth, bool in_indented_scope) { ScopedContext scoped_context(state, IN_STATEMENT); if (IsNearStackLimit() || ++depth > ES_MAXIMUM_SYNTAX_TREE_DEPTH) return false; if (!HandleLinebreak()) return false; /* Only indent if the block statement has no control statement. Otherwise the control statement has indented already. */ state.in_standalone_block = !in_indented_scope && token.type == ES_Token::PUNCTUATOR && token.punctuator == ES_Token::LEFT_BRACE; ScopedIndent scoped_indent(state.in_standalone_block ? state : fake_state); if (ParsePunctuator(ES_Token::LEFT_BRACE)) { unsigned statements_before = statement_stack_used; while (1) { if (ParsePunctuator(ES_Token::RIGHT_BRACE)) break; else if (!ParseStatement(depth)) return false; } unsigned statements_count = statement_stack_used - statements_before; PopStatements(statements_count); } else if (ParseKeyword(ES_Token::KEYWORD_VAR)) { unsigned identifiers_before = identifier_stack_used; if (!ParseVariableDeclList(depth, true) || !ParseSemicolon()) return false; unsigned decls_count = identifier_stack_used - identifiers_before; /* Pop names. */ PopIdentifiers(decls_count); /* Pop initializers. */ PopExpressions(decls_count); } else if (ParsePunctuator(ES_Token::SEMICOLON)) { } else if (ParseKeyword(ES_Token::KEYWORD_IF)) { if (!ParsePunctuator(ES_Token::LEFT_PAREN) || !ParseExpression(depth, ES_Expression::PROD_EXPRESSION, true, expression_stack_used) || !ParsePunctuator(ES_Token::RIGHT_PAREN)) return false; ScheduleLinebreak(); { ScopedIndent scoped_indent(state); if (!ParseStatement(depth, true)) return false; } /* Pop condition. */ PopExpression(); /* Pop "ifstmt". */ PopStatement(); if (ParseKeyword(ES_Token::KEYWORD_ELSE)) { ScheduleLinebreak(); /* 'Else' followed by 'if', leave indenting to the latter. */ if (token.type != ES_Token::KEYWORD || token.keyword != ES_Token::KEYWORD_IF) { ScopedIndent scoped_indent(state); if (!ParseStatement(depth, true)) return false; } else if (!ParseStatement(depth, false)) return false; /* Pop "elsestmt". */ PopStatement(); } } else if (ParseKeyword(ES_Token::KEYWORD_DO)) { ScheduleLinebreak(); { ScopedIndent scoped_indent(state); if (!ParseStatement(depth, true) || !HandleLinebreak()) return false; } if (!ParseKeyword(ES_Token::KEYWORD_WHILE) || !ParsePunctuator(ES_Token::LEFT_PAREN) || !ParseExpression(depth, ES_Expression::PROD_EXPRESSION, true, expression_stack_used) || !ParsePunctuator(ES_Token::RIGHT_PAREN)) return false; if (!HandleLinebreak() || !ParseSemicolon(true)) return false; /* Pop condition. */ PopExpression(); /* Pop "body". */ PopStatement(); } else if (ParseKeyword(ES_Token::KEYWORD_WHILE)) { if (!ParsePunctuator(ES_Token::LEFT_PAREN) || !ParseExpression(depth, ES_Expression::PROD_EXPRESSION, true, expression_stack_used) || !ParsePunctuator(ES_Token::RIGHT_PAREN)) return false; ScheduleLinebreak(); ScopedIndent scoped_indent(state); if (!ParseStatement(depth, true)) return false; /* Pop condition. */ PopExpression(); /* Pop "body". */ PopStatement(); } else if (ParseKeyword(ES_Token::KEYWORD_FOR)) { bool is_forin = false; if (!ParsePunctuator(ES_Token::LEFT_PAREN)) return false; if (ParseKeyword(ES_Token::KEYWORD_VAR)) { unsigned identifiers_before = identifier_stack_used; { ScopedContext scoped_context(state, IN_FOR_DECL_LIST); if (!ParseVariableDeclList(depth, false)) return false; } unsigned decls_count = identifier_stack_used - identifiers_before; if (decls_count == 1 && ParseKeyword(ES_Token::KEYWORD_IN)) is_forin = true; /* Pop names. */ PopIdentifiers(decls_count); /* Pop initializers. */ PopExpressions(decls_count); } else { unsigned expression_stack_before = expression_stack_used; if (!ParseExpression(depth, ES_Expression::PROD_EXPRESSION, false, expression_stack_used, true)) return false; if (expression_stack_before != expression_stack_used) { /* Pop "init_expr". */ PopExpression(); if (last_expr_is_lvalue && ParseKeyword(ES_Token::KEYWORD_IN)) is_forin = true; } } if (is_forin) { if (!ParseExpression(depth, ES_Expression::PROD_EXPRESSION, true, expression_stack_used)) return false; /* Pop source. */ PopExpression(); } else { if (!ParsePunctuator(ES_Token::SEMICOLON)) return false; unsigned expression_stack_before = expression_stack_used; if (!ParseExpression(depth, ES_Expression::PROD_EXPRESSION, true, expression_stack_used, true)) return false; if (expression_stack_before != expression_stack_used) /* Pop "condition". */ PopExpression(); if (!ParsePunctuator(ES_Token::SEMICOLON)) return false; expression_stack_before = expression_stack_used; if (!ParseExpression(depth, ES_Expression::PROD_EXPRESSION, true, expression_stack_used, true)) return false; if (expression_stack_before != expression_stack_used) PopExpression(); } if (!ParsePunctuator(ES_Token::RIGHT_PAREN)) return false; ScheduleLinebreak(); ScopedIndent scoped_indent(state); if (!ParseStatement(depth, true)) return false; /* Pop "body". */ PopStatement(); } else if (ParseKeyword(ES_Token::KEYWORD_CONTINUE)) { JString *target; bool previous_allow_linebreak = SetAllowLinebreak(false); if (!ParseIdentifier(target, true)) return false; SetAllowLinebreak(previous_allow_linebreak); if (!ParseSemicolon()) return false; } else if (ParseKeyword(ES_Token::KEYWORD_BREAK)) { JString *target; bool previous_allow_linebreak = SetAllowLinebreak(false); if (!ParseIdentifier(target, true)) return false; SetAllowLinebreak(previous_allow_linebreak); if (!ParseSemicolon()) return false; } else if (ParseKeyword(ES_Token::KEYWORD_RETURN)) { if (!in_function && !allow_return_in_program) return false; bool previous_allow_linebreak = SetAllowLinebreak(false); unsigned expression_stack_before = expression_stack_used; if (!ParseExpression(depth, ES_Expression::PROD_EXPRESSION, true, expression_stack_used, true)) return false; if (expression_stack_before != expression_stack_used) PopExpression(); SetAllowLinebreak(previous_allow_linebreak); if (!ParseSemicolon()) return false; } else if (ParseKeyword(ES_Token::KEYWORD_WITH)) { in_with++; if (!ParsePunctuator(ES_Token::LEFT_PAREN) || !ParseExpression(depth, ES_Expression::PROD_EXPRESSION, true, expression_stack_used) || !ParsePunctuator(ES_Token::RIGHT_PAREN)) return false; ScheduleLinebreak(); ScopedIndent scoped_indent(state); if (!ParseStatement(depth, true)) return false; PopExpression(); /* Pop "body". */ PopStatement(); in_with--; } else if (ParseKeyword(ES_Token::KEYWORD_SWITCH)) { if (!ParsePunctuator(ES_Token::LEFT_PAREN) || !ParseExpression(depth, ES_Expression::PROD_EXPRESSION, true, expression_stack_used) || !ParsePunctuator(ES_Token::RIGHT_PAREN)) return false; ScopedIndent scoped_indent(state); if (!ParsePunctuator(ES_Token::LEFT_BRACE)) return false; PopExpression(); unsigned statements_before = statement_stack_used; unsigned case_clauses_count = 0; bool seen_default = false; while (1) { if (ParsePunctuator(ES_Token::RIGHT_BRACE)) break; else if (ParseKeyword(ES_Token::KEYWORD_CASE)) { if (!ParseExpression(depth, ES_Expression::PROD_EXPRESSION, true, expression_stack_used) || !ParsePunctuator(ES_Token::CONDITIONAL_FALSE)) return false; ScheduleLinebreak(); PopExpression(); ++case_clauses_count; } else if (ParseKeyword(ES_Token::KEYWORD_DEFAULT)) { if (seen_default) return false; seen_default = true; if (!ParsePunctuator(ES_Token::CONDITIONAL_FALSE)) return false; ScheduleLinebreak(); ++case_clauses_count; } else { ScopedIndent scoped_indent(state); if (case_clauses_count == 0 || !ParseStatement(depth, true)) return false; } } unsigned statements_count = statement_stack_used - statements_before; PopStatements(statements_count); } else if (ParseKeyword(ES_Token::KEYWORD_THROW)) { bool previous_allow_linebreak = SetAllowLinebreak(false); if (!ParseExpression(depth, ES_Expression::PROD_EXPRESSION, true, expression_stack_used)) return false; SetAllowLinebreak(previous_allow_linebreak); if (!ParseSemicolon()) return false; PopExpression(); } else if (ParseKeyword(ES_Token::KEYWORD_TRY)) { JString *catch_identifier; bool has_catch_block = true; bool has_finally_block = true; { ScopedIndent scoped_indent(state); if (!ParseStatement(depth, true)) return false; } /* Pop "try_block". */ PopStatement(); if (ParseKeyword(ES_Token::KEYWORD_CATCH)) { ++in_with; if (!ParsePunctuator(ES_Token::LEFT_PAREN) || !ParseIdentifier(catch_identifier) || !ParsePunctuator(ES_Token::RIGHT_PAREN)) return false; ScopedIndent scoped_indent(state); if (!ParseStatement(depth, true)) return false; --in_with; /* Pop "catch_block". */ PopStatement(); } else has_catch_block = false; if (ParseKeyword(ES_Token::KEYWORD_FINALLY)) { ScopedIndent scoped_indent(state); if (!ParseStatement(depth, true)) return false; /* Pop "finally_block". */ PopStatement(); } else has_finally_block = false; if (!has_catch_block && !has_finally_block) return false; } else if (ParseKeyword(ES_Token::KEYWORD_FUNCTION)) { if (!ParseFunctionDecl(true)) return false; } else if (ParseKeyword(ES_Token::KEYWORD_DEBUGGER)) { if (!ParseSemicolon()) return false; } else { JString *identifier; unsigned expression_stack_base = expression_stack_used; if (ParseIdentifier(identifier)) { if (ParsePunctuator(ES_Token::CONDITIONAL_FALSE)) { if (!ParseStatement(depth)) return false; PopStatement(); return true; } else /* ES_IdentifierExpr. */ PushExpression(true); } if (!ParseExpression(depth, ES_Expression::PROD_EXPRESSION, true, expression_stack_base)) return false; PopExpression(); if (!ParseSemicolon()) return false; } ScheduleLinebreak(); PushStatement(); return true; } bool ES_Formatter::ParseAccessor(AccessorType type, JString *name) { unsigned identifiers_before = identifier_stack_used; in_function++; ScopedIndent scoped_indent(state); if (!ParsePunctuator(ES_Token::LEFT_PAREN) || type == ACCESSOR_SET && !ParseFormalParameterList() || !ParsePunctuator(ES_Token::RIGHT_PAREN) || !ParseSourceElements(true) || !ParsePunctuator(ES_Token::RIGHT_BRACE)) return false; in_function--; unsigned parameter_names_count = identifier_stack_used - identifiers_before; PopIdentifiers(parameter_names_count); return true; } bool ES_Formatter::ParseExpression(unsigned depth, unsigned production, bool allow_in, unsigned expr_stack_base, bool opt) { ScopedContext scoped_context(state, IN_EXPRESSION); recurse: if (++depth > ES_MAXIMUM_SYNTAX_TREE_DEPTH) return false; unsigned expression_stack_length = expression_stack_used - expr_stack_base; JString *identifier; ES_Value_Internal value; /* These are always allowed and always unambigious. */ if (expression_stack_length == 0) { if (ParseKeyword(ES_Token::KEYWORD_THIS)) { /* ES_ThisExpr. */ PushExpression(false); goto recurse; } if (ParseIdentifier(identifier)) { /* ES_IdentifierExpr. */ PushExpression(true); goto recurse; } bool regexp; if (ParseLiteral(value, identifier, regexp)) { /* ES_RegExpLiteralExpr, ES_LiteralExpr. */ PushExpression(false); goto recurse; } if (ParsePunctuator(ES_Token::LEFT_PAREN)) { // parse grouped expression if (!ParseExpression(depth, ES_Expression::PROD_EXPRESSION, true, expression_stack_used) || !ParsePunctuator(ES_Token::RIGHT_PAREN)) return false; goto recurse; } } ES_Expression::Production p = static_cast<ES_Expression::Production>(production); if (expression_stack_length == 0 && p < ES_Expression::PROD_UNARY_EXPR) p = ES_Expression::PROD_UNARY_EXPR; if (!HandleLinebreak()) return false; switch (p) { case ES_Expression::PROD_EXPRESSION: if (ParsePunctuator(ES_Token::COMMA)) if (ParseExpression(depth, ES_Expression::PROD_ASSIGNMENT_EXPR, allow_in, expression_stack_used)) { /* Pop left and right. */ PopExpressions(2); /* ES_CommaExpr. */ PushExpression(false); goto recurse; } else return false; case ES_Expression::PROD_ASSIGNMENT_EXPR: if (token.type == ES_Token::PUNCTUATOR) { bool is_assign = true; bool is_compound_assign = true; switch (token.punctuator) { case ES_Token::ASSIGN: is_compound_assign = false; break; case ES_Token::ADD_ASSIGN: case ES_Token::MULTIPLY_ASSIGN: case ES_Token::DIVIDE_ASSIGN: case ES_Token::REMAINDER_ASSIGN: case ES_Token::SUBTRACT_ASSIGN: case ES_Token::SHIFT_LEFT_ASSIGN: case ES_Token::SHIFT_SIGNED_RIGHT_ASSIGN: case ES_Token::SHIFT_UNSIGNED_RIGHT_ASSIGN: case ES_Token::BITWISE_AND_ASSIGN: case ES_Token::BITWISE_OR_ASSIGN: case ES_Token::BITWISE_XOR_ASSIGN: break; default: is_assign = false; } if (is_assign) { AppendPunctuator(); if (!NextToken()) return false; /* Pop target. */ PopExpression(); if (!ParseExpression(depth, ES_Expression::PROD_ASSIGNMENT_EXPR, allow_in, expression_stack_used)) return false; /* Pop source. */ PopExpression(); if (!is_compound_assign) { /* ES_AssignExpr. */ PushExpression(false); goto recurse; } /* ES_BinaryNumberExpr or ES_AddExpr or ES_ShiftExpr or ES_BitwiseExpr. */ PushExpression(false); goto recurse; } } case ES_Expression::PROD_CONDITIONAL_EXPR: if (ParsePunctuator(ES_Token::CONDITIONAL_TRUE)) { ScopedContext scoped_context(state, IN_TERNARY_EXPR); if (!ParseExpression(depth, ES_Expression::PROD_ASSIGNMENT_EXPR, true, expression_stack_used) || !ParsePunctuator(ES_Token::CONDITIONAL_FALSE) || !ParseExpression(depth, ES_Expression::PROD_ASSIGNMENT_EXPR, allow_in, expression_stack_used)) return false; /* Pop "second", "first" and "condition". */ PopExpressions(3); /* ES_ConditionalExpr. */ PushExpression(false); goto recurse; } case ES_Expression::PROD_LOGICAL_OR_EXPR: if (ParsePunctuator(ES_Token::LOGICAL_OR)) if (ParseExpression(depth, ES_Expression::PROD_LOGICAL_AND_EXPR, allow_in, expression_stack_used)) { /* Pop left and right. */ PopExpressions(2); /* ES_LogicalExpr. */ PushExpression(false); goto recurse; } else return false; case ES_Expression::PROD_LOGICAL_AND_EXPR: if (ParsePunctuator(ES_Token::LOGICAL_AND)) if (ParseExpression(depth, ES_Expression::PROD_BITWISE_OR_EXPR, allow_in, expression_stack_used)) { /* Pop left and right. */ PopExpressions(2); /* ES_LogicalExpr. */ PushExpression(false); goto recurse; } else return false; case ES_Expression::PROD_BITWISE_OR_EXPR: if (ParsePunctuator(ES_Token::BITWISE_OR)) if (ParseExpression(depth, ES_Expression::PROD_BITWISE_XOR_EXPR, allow_in, expression_stack_used)) { /* Pop left and right. */ PopExpressions(2); /* ES_BitwiseExpr. */ PushExpression(false); goto recurse; } else return false; case ES_Expression::PROD_BITWISE_XOR_EXPR: if (ParsePunctuator(ES_Token::BITWISE_XOR)) if (ParseExpression(depth, ES_Expression::PROD_BITWISE_AND_EXPR, allow_in, expression_stack_used)) { /* Pop left and right. */ PopExpressions(2); /* ES_BitwiseExpr. */ PushExpression(false); goto recurse; } else return false; case ES_Expression::PROD_BITWISE_AND_EXPR: if (ParsePunctuator(ES_Token::BITWISE_AND)) if (ParseExpression(depth, ES_Expression::PROD_EQUALITY_EXPR, allow_in, expression_stack_used)) { /* Pop left and right. */ PopExpressions(2); /* ES_BitwiseExpr. */ PushExpression(false); goto recurse; } else return false; case ES_Expression::PROD_EQUALITY_EXPR: if (token.type == ES_Token::PUNCTUATOR) { bool is_equality = true; switch (token.punctuator) { case ES_Token::EQUAL: case ES_Token::NOT_EQUAL: case ES_Token::STRICT_EQUAL: case ES_Token::STRICT_NOT_EQUAL: break; default: is_equality = false; } if (is_equality) { AppendPunctuator(); if (!NextToken()) return false; if (!ParseExpression(depth, ES_Expression::PROD_RELATIONAL_EXPR, allow_in, expression_stack_used)) return false; /* Pop "right" and "left". */ PopExpressions(2); /* ES_EqualityExpr. */ PushExpression(false); goto recurse; } } case ES_Expression::PROD_RELATIONAL_EXPR: if (token.type == ES_Token::PUNCTUATOR || token.type == ES_Token::KEYWORD) { bool is_relational = false; bool is_instanceof_or_in = false; if (token.type == ES_Token::PUNCTUATOR) { is_relational = true; switch (token.punctuator) { case ES_Token::LESS_THAN: case ES_Token::GREATER_THAN: case ES_Token::LESS_THAN_OR_EQUAL: case ES_Token::GREATER_THAN_OR_EQUAL: break; default: is_relational = false; } } else if (token.keyword == ES_Token::KEYWORD_INSTANCEOF || token.keyword == ES_Token::KEYWORD_IN && allow_in) is_instanceof_or_in = true; if (is_relational || is_instanceof_or_in) { if (is_relational) AppendPunctuator(); else AppendKeyword(); if (!NextToken()) return false; if (!ParseExpression(depth, ES_Expression::PROD_SHIFT_EXPR, true, expression_stack_used)) return false; /* Pop "right" and "left". */ PopExpressions(2); /* ES_RelationalExpr or ES_InstanceofOrInExpr. */ PushExpression(false); goto recurse; } } case ES_Expression::PROD_SHIFT_EXPR: if (token.type == ES_Token::PUNCTUATOR) { bool is_shift = true; switch (token.punctuator) { case ES_Token::SHIFT_LEFT: case ES_Token::SHIFT_SIGNED_RIGHT: case ES_Token::SHIFT_UNSIGNED_RIGHT: break; default: is_shift = false; } if (is_shift) { AppendPunctuator(); if (!NextToken()) return false; if (!ParseExpression(depth, ES_Expression::PROD_ADDITIVE_EXPR, true, expression_stack_used)) return false; /* Pop "right" and "left". */ PopExpressions(2); /* ES_ShiftExpr. */ PushExpression(false); goto recurse; } } case ES_Expression::PROD_ADDITIVE_EXPR: if (token.type == ES_Token::PUNCTUATOR) { bool is_add = false; bool is_subtract = false; if (token.punctuator == ES_Token::ADD) is_add = true; else if (token.punctuator == ES_Token::SUBTRACT) is_subtract = true; if (is_add || is_subtract) { AppendPunctuator(); if (!NextToken()) return false; if (!ParseExpression(depth, ES_Expression::PROD_MULTIPLICATIVE_EXPR, true, expression_stack_used)) return false; /* Pop "right" and "left". */ PopExpressions(2); /* ES_AddExpr or ES_BinaryNumberExpr. */ PushExpression(false); goto recurse; } } case ES_Expression::PROD_MULTIPLICATIVE_EXPR: if (token.type == ES_Token::PUNCTUATOR) { bool is_multiplicative = true; switch (token.punctuator) { case ES_Token::MULTIPLY: case ES_Token::DIVIDE: case ES_Token::REMAINDER: break; default: is_multiplicative = false; } if (is_multiplicative) { AppendPunctuator(); if (!NextToken()) return false; if (!ParseExpression(depth, ES_Expression::PROD_UNARY_EXPR, true, expression_stack_used)) return false; /* Pop "right" and "left". */ PopExpressions(2); /* ES_BinaryNumberExpr. */ PushExpression(false); goto recurse; } } case ES_Expression::PROD_UNARY_EXPR: if (expression_stack_length == 0) { if (ParseKeyword(ES_Token::KEYWORD_DELETE)) { if (!ParseExpression(depth, ES_Expression::PROD_UNARY_EXPR, true, expression_stack_used)) return false; PopExpression(); /* ES_DeleteExpr. */ PushExpression(false); goto recurse; } bool is_unary = true; bool is_inc_or_dec = false; bool is_typeof = false; if (token.type == ES_Token::KEYWORD) { switch (token.keyword) { case ES_Token::KEYWORD_VOID: break; case ES_Token::KEYWORD_TYPEOF: is_typeof = true; break; default: is_unary = false; } if (is_unary) AppendKeyword(); } else if (token.type == ES_Token::PUNCTUATOR) { switch (token.punctuator) { case ES_Token::INCREMENT: case ES_Token::DECREMENT: is_inc_or_dec = true; is_unary = false; break; case ES_Token::ADD: case ES_Token::SUBTRACT: case ES_Token::BITWISE_NOT: case ES_Token::LOGICAL_NOT: break; default: is_unary = false; } if (is_unary || is_inc_or_dec) AppendPunctuator(true); } else is_unary = false; if (is_unary || is_inc_or_dec) { if (!NextToken()) return false; if (is_unary && is_typeof) ++in_typeof; if (!ParseExpression(depth, ES_Expression::PROD_UNARY_EXPR, true, expression_stack_used)) return false; if (is_unary && is_typeof) --in_typeof; PopExpression(); /* ES_LiteralExpr or ES_UnaryExpr or ES_IncrementOrDecrementExpr. */ PushExpression(false); goto recurse; } } case ES_Expression::PROD_POSTFIX_EXPR: if (expression_stack_length > 0) { bool is_postfix = true; bool previous_allow_linebreak = SetAllowLinebreak(false); if (last_token.type == ES_Token::LINEBREAK) is_postfix = false; else if (!ParsePunctuator(ES_Token::INCREMENT) && !ParsePunctuator(ES_Token::DECREMENT)) is_postfix = false; SetAllowLinebreak(previous_allow_linebreak); if (is_postfix) { PopExpression(); /* ES_IncrementOrDecrementExpr. */ PushExpression(false); goto recurse; } } case ES_Expression::PROD_LEFT_HAND_SIDE_EXPR: case ES_Expression::PROD_CALL_EXPR: if (expression_stack_length > 0) { unsigned exprs_before = expression_stack_used; if (ParsePunctuator(ES_Token::LEFT_PAREN)) if (ParseArguments(depth)) { unsigned args_count = expression_stack_used - exprs_before; /* Pop arguments. */ PopExpressions(args_count); /* Pop function. */ PopExpression(); /* ES_CallExpr. */ PushExpression(false); goto recurse; } else return false; } case ES_Expression::PROD_NEW_EXPR: case ES_Expression::PROD_MEMBER_EXPR: if (expression_stack_length > 0) { switch (ParsePunctuator1(ES_Token::LEFT_BRACKET)) { case INVALID_TOKEN: return false; case FOUND: if (!ParseExpression(depth, ES_Expression::PROD_EXPRESSION, true, expression_stack_used) || !ParsePunctuator(ES_Token::RIGHT_BRACKET)) return false; /* Pop "index" and "base". */ PopExpressions(2); /* ES_PropertyReferenceExpr or ES_ArrayReferenceExpr. */ PushExpression(true); goto recurse; } switch (ParsePunctuator1(ES_Token::PERIOD)) { case INVALID_TOKEN: return false; case FOUND: JString *name; if (!ParseIdentifier(name, false, true)) return false; /* Pop base. */ PopExpression(); /* ES_PropertyReferenceExpr. */ PushExpression(true); goto recurse; } } if (expression_stack_length == 0) if (ParseKeyword(ES_Token::KEYWORD_NEW)) { unsigned args_count; if (expression_stack_length > 0) return false; if (!ParseExpression(depth, ES_Expression::PROD_NEW_EXPR, true, expression_stack_used)) return false; unsigned exprs_before = expression_stack_used; if (ParsePunctuator(ES_Token::LEFT_PAREN)) if (ParseArguments(depth)) { args_count = expression_stack_used - exprs_before; /* Pop arguments. */ PopExpressions(args_count); } else return false; else if (production < ES_Expression::PROD_MEMBER_EXPR) { args_count = 0; } else return false; /* Pop constructor. */ PopExpression(); /* ES_NewExpr. */ PushExpression(false); goto recurse; } else if (ParseKeyword(ES_Token::KEYWORD_FUNCTION)) { if (!ParseFunctionExpr()) return false; goto recurse; } case ES_Expression::PROD_PRIMARY_EXPR: if (expression_stack_length == 0) { if (ParsePunctuator(ES_Token::LEFT_BRACKET)) { unsigned exprs_count; unsigned expressions_before = expression_stack_used; while (!ParsePunctuator(ES_Token::RIGHT_BRACKET)) if (ParseExpression(depth, ES_Expression::PROD_ASSIGNMENT_EXPR, true, expression_stack_used)) { if (!ParsePunctuator(ES_Token::COMMA)) if (ParsePunctuator(ES_Token::RIGHT_BRACKET)) break; else return false; } else if (ParsePunctuator(ES_Token::COMMA)) PushExpression(false); else return false; exprs_count = expression_stack_used - expressions_before; /* Pop expressions. */ PopExpressions(exprs_count); /* ES_ArrayLiteralExpr. */ PushExpression(false); goto recurse; } ScopedIndent scoped_indent(state); if (ParsePunctuator(ES_Token::LEFT_BRACE)) { while (1) { JString *name; if (!ParseProperty(name, false)) if (ParsePunctuator(ES_Token::RIGHT_BRACE)) break; else return false; if (name) { JString *actual_name; if (name->Equals(UNI_L("get"), 3)) { ScopedContext scoped_context(state, IN_ACCESSOR); ScheduleSpace(); if (ParseProperty(actual_name, false)) { if (!ParseAccessor(ACCESSOR_GET, actual_name)) return false; } else goto regular_property; } else if (name->Equals(UNI_L("set"), 3)) { ScopedContext scoped_context(state, IN_ACCESSOR); ScheduleSpace(); if (ParseProperty(actual_name, false)) { if (!ParseAccessor(ACCESSOR_SET, actual_name)) return false; } else goto regular_property; } else { regular_property: if (!ParsePunctuator(ES_Token::CONDITIONAL_FALSE) || !ParseExpression(depth, ES_Expression::PROD_ASSIGNMENT_EXPR, true, expression_stack_used)) return false; PopExpression(); } } if (ParsePunctuator(ES_Token::COMMA)) ScheduleLinebreak(); else { if (ParsePunctuator(ES_Token::RIGHT_BRACE)) break; else return false; } } /* ES_ObjectLiteralExpr. */ PushExpression(false); goto recurse; } } if (expression_stack_length == 1 || (expression_stack_length == 0 && opt)) return true; else return false; } /* Never reached. */ return false; } bool ES_Formatter::NextToken() { last_token = token; lexer->NextToken(); token = lexer->GetToken(); while (token.type == ES_Token::PUNCTUATOR && (token.punctuator == ES_Token::SINGLE_LINE_COMMENT || token.punctuator == ES_Token::MULTI_LINE_COMMENT)) { bool is_single_line = token.punctuator == ES_Token::SINGLE_LINE_COMMENT; AppendLiteral(lexer->GetTokenAsJString(false)); lexer->NextToken(); token = lexer->GetToken(); if (token.type == ES_Token::LINEBREAK) if (is_single_line) LinebreakInternal(); else ScheduleLinebreak(); } if (token.type == ES_Token::INVALID) return false; linebreak_seen = token.type == ES_Token::LINEBREAK; return true; } bool ES_Formatter::SetAllowLinebreak(bool new_value) { can_append_linebreak = new_value; bool old_value = allow_linebreak; allow_linebreak = new_value; return old_value; } bool ES_Formatter::GetAllowLinebreak() { return allow_linebreak; }
/* -*- Mode: c++; tab-width: 4; c-basic-offset: 4 -*- * * Copyright (C) 1995-2011 Opera Software ASA. All rights reserved. * * This file is part of the Opera web browser. * It may not be distributed under any circumstances. * * Allowed #if-ery: SYSTEM_* defines, lea_malloc config. */ #ifndef POSIX_SYS_DECLARE_LIBC_H #define POSIX_SYS_DECLARE_LIBC_H __FILE__ /** @file declare_libc.h Opera system-system configuration for C standard library support. * * This simply maps everything in ANSI C's standard library to the relevant op_* * define. It is to be expected that it can be generally used by most platforms * in practice, due to the ubiquity of ANSI C support. */ # if SYSTEM_ABS == YES #define op_abs(n) abs(n) # endif # if SYSTEM_ACOS == YES #define op_acos(x) acos(x) # endif # if SYSTEM_ASIN == YES #define op_asin(x) asin(x) # endif # if SYSTEM_ATAN == YES #define op_atan(x) atan(x) # endif # if SYSTEM_ATAN2 == YES #define op_atan2(y, x) atan2(y, x) # endif # if SYSTEM_ATOI == YES #define op_atoi(s) atoi(s) # endif # if SYSTEM_BSEARCH == YES #define op_bsearch(k, b, n, s, c) bsearch(k, b, n, s, c) # endif # if SYSTEM_CEIL == YES #define op_ceil(x) ceil(x) # endif # if SYSTEM_COS == YES #define op_cos(x) cos(x) # endif # if SYSTEM_EXP == YES #define op_exp(x) exp(x) # endif # if SYSTEM_FABS == YES #define op_fabs(x) fabs(x) # endif # if SYSTEM_FLOOR == YES #define op_floor(x) floor(x) # endif # if SYSTEM_FMOD == YES #define op_fmod(n, d) fmod(n, d) # endif # if SYSTEM_FREXP == YES #define op_frexp(x, r) frexp(x, r) # endif # if SYSTEM_GMTIME == YES #define op_gmtime(c) gmtime(c) # endif # if SYSTEM_LDEXP == YES #define op_ldexp(s, e) ldexp(s, e) # endif /* no op_localeconv ! */ # if SYSTEM_LOCALTIME == YES #define op_localtime(c) localtime(c) # endif # if SYSTEM_LOG == YES #define op_log(x) log(x) # endif # if SYSTEM_MALLOC == YES # if defined(HAVE_DL_MALLOC) && defined(USE_DL_PREFIX) #define op_lowlevel_malloc(n) dlmalloc(n) #define op_lowlevel_free(p) dlfree(p) #define op_lowlevel_calloc(n, s) dlcalloc(n, s) #define op_lowlevel_realloc(p, n) dlrealloc(p, n) # else #define op_lowlevel_malloc(n) malloc(n) #define op_lowlevel_free(p) free(p) #define op_lowlevel_calloc(n, s) calloc(n, s) #define op_lowlevel_realloc(p, n) realloc(p, n) # endif /* Doug Lea's malloc, with prefix */ # endif /* SYSTEM_MALLOC */ # if SYSTEM_MEMCMP == YES #define op_memcmp(s, t, n) memcmp(s, t, n) # endif # if SYSTEM_MEMCPY == YES #define op_memcpy(t, f, n) memcpy(t, f, n) # endif # if SYSTEM_MEMMOVE == YES #define op_memmove(t, f, n) memmove(t, f, n) # endif # if SYSTEM_MEMSET == YES #define op_memset(s, c, n) memset(s, c, n) # endif # if SYSTEM_MKTIME == YES #define op_mktime(t) mktime(t) # endif # if SYSTEM_MODF == YES #define op_modf(x, r) modf(x, r) # endif # if SYSTEM_POW == YES #define op_pow(a, b) pow(a, b) # endif /* SYSTEM_POW */ # if SYSTEM_QSORT == YES #define op_qsort(b, n, s, c) qsort(b, n, s, c) # endif # if SYSTEM_QSORT_S == YES # if defined(__FreeBSD__) /* FreeBSD's qsort_r() uses a different argument order than the * MS-style qsort_s(). We need to transpose the last two * arguments: */ #define op_qsort_s(b, n, s, c, d) qsort_r(b, n, s, d, c) # else /* qsort_r() was added to glibc ni version 2.8. */ /* We use the MS-style qsort_s() singature, as it's more widely copied. Since * glibc chose differently, we have to do a bit of work to re-pack for it; its * comparison function takes the context pointer last, rather than first. * For glibc older than 2.8, there is no known way to support op_qsort_s(). * Patches welcome. */ struct posix2MS_qsort_wrapper { void * context; int (*cmp)(void*, const void*, const void*); /* The MS-style signature */ }; /* The glibc-style signature: */ static inline int posix2MS_qsort_unwrap(const void* one, const void* two, void* data) { struct posix2MS_qsort_wrapper *ctx = (struct posix2MS_qsort_wrapper *)data; return ctx->cmp(ctx->context, one, two); } static inline void op_qsort_s(void *base, size_t count, size_t each, int (*compar)(void *, const void *, const void *), void *data) { struct posix2MS_qsort_wrapper ctx = { data, compar }; qsort_r(base, count, each, posix2MS_qsort_unwrap, &ctx); } # endif /* FreeBSD, glibc-2.8 */ # endif /* SYSTEM_QSORT_S */ # if SYSTEM_RAND == YES #define op_rand rand #define op_srand(s) srand(s) /* Consider using lrand48(void) in place of rand, seeded by srand48(long); their * RAND_MAX is 2**31. */ # endif # if SYSTEM_SETJMP == YES #define op_setjmp(e) setjmp(e) #define op_longjmp(e, v) longjmp(e, v) # endif # if SYSTEM_SETLOCALE == YES #define op_setlocale(c, l) setlocale(c, l) # endif # if SYSTEM_SIN == YES #define op_sin(x) sin(x) # endif # if SYSTEM_SNPRINTF == YES #define op_snprintf snprintf /* varargs */ # endif # if SYSTEM_SPRINTF == YES #define op_sprintf sprintf /* varargs */ # endif # if SYSTEM_SQRT == YES #define op_sqrt(x) sqrt(x) # endif # if SYSTEM_SSCANF == YES #define op_sscanf sscanf /* varargs */ # endif # if SYSTEM_STRCAT == YES #define op_strcat(t, f) strcat(t, f) # endif # if SYSTEM_STRCMP == YES #define op_strcmp strcmp /* at least some code wants its address ! */ # endif # if SYSTEM_STRCPY == YES #define op_strcpy(t, f) strcpy(t, f) # endif # if SYSTEM_STRCSPN == YES #define op_strcspn(s, p) strcspn(s, p) # endif # if SYSTEM_STRLEN == YES #define op_strlen(s) strlen(s) # endif # if SYSTEM_STRNCAT == YES #define op_strncat(t, f, n) strncat(t, f, n) # endif # if SYSTEM_STRNCMP == YES #define op_strncmp(s, t, n) strncmp(s, t, n) # endif # if SYSTEM_STRNCPY == YES #define op_strncpy(t, f, n) strncpy(t, f, n) # endif # if SYSTEM_STRSPN == YES #define op_strspn(s, f) strspn(s, f) # endif # if SYSTEM_TAN == YES #define op_tan(x) tan(x) # endif # if SYSTEM_TIME == YES #define op_time(t) time(t) # endif # if SYSTEM_VSNPRINTF == YES #define op_vsnprintf(b, n, f, a) vsnprintf(b, n, f, a) # endif # if SYSTEM_VSPRINTF == YES #define op_vsprintf(b, f, a) vsprintf(b, f, a) # endif # if SYSTEM_VSSCANF == YES #define op_vsscanf(b, f, a) vsscanf(b, f, a) # endif #endif /* POSIX_SYS_DECLARE_LIBC_H */
//////////////////////////////////////////////////////// // Система поиска документов по словам //////////////////////////////////////////////////////// //У вас есть множество документов. И есть стоп-слова. //Приходит запрос некоторый. //Найдите все документы, где есть хотя бы одно слово из запроса. //Учтите стоп-слова и не включайте их в результаты поиска. // //Функция FindDocuments должна искать и выдавать требуемые идентификаторы документов в виде вектора. //В векторе с результатами не должно быть повторов. // //Ввод: //СТРОКА СТОП-СЛОВ //a the on cat // //ЧИСЛО ДОКУМЕНТОВ //4 // //ДОКУМЕНТ0 //a fat cat sat on a mat and ate a fat rat // //ДОКУМЕНТ1 //little funny fluffy cat // //ДОКУМЕНТ2 //the cat // //ДОКУМЕНТ3 //huge green crocodile // //ЗАПРОС //funny fat cat // //Вывод (id документов): //0 //1 #include <algorithm> #include <iostream> #include <map> #include <set> #include <string> #include <vector> using namespace std; string ReadLine() { string s; getline(cin, s); return s; } int ReadLineWithNumber() { int result; cin >> result; ReadLine(); return result; } vector<string> SplitIntoWords(const string& text) { vector<string> words; string word; for (const char c : text) { if (c == ' ') { words.push_back(word); word = ""; } else { word += c; } } words.push_back(word); return words; } set<string> ParseStopWords(const string& text) { set<string> stop_words; for (const string& word : SplitIntoWords(text)) { stop_words.insert(word); } return stop_words; } vector<string> SplitIntoWordsNoStop(const string& text, const set<string>& stop_words) { vector<string> words; for (const string& word : SplitIntoWords(text)) { if (stop_words.count(word) == 0) { words.push_back(word); } } return words; } void AddDocument(map<string, set<int>>& word_to_documents, int document_id, const string& document) { vector<string> v_doc_words = SplitIntoWords(document); for (const string& elm : v_doc_words) { word_to_documents[elm].insert(document_id); //заполняем словарь: слово - {id документа, где содержится слово} } } vector<int> FindDocuments(const map<string, set<int>>& word_to_documents, const set<string>& stop_words, const string& query) { vector<string> v_query_words = SplitIntoWords(query); sort(v_query_words.begin(), v_query_words.end()); vector<int> rez_id; set<int> temp_id, set_doc_id; for (const string& elm : v_query_words) { if (!stop_words.count(elm)) { set_doc_id = word_to_documents.find(elm)->second; for (auto& elm : set_doc_id) { temp_id.insert(elm); } } } for (auto& now : temp_id) { rez_id.push_back(now); } return rez_id; } int main() { const string stop_words_joined = ReadLine(); const set<string> stop_words = ParseStopWords(stop_words_joined); // Читаем документы map<string, set<int>> word_to_documents; const int document_count = ReadLineWithNumber(); for (int document_id = 0; document_id < document_count; ++document_id) { AddDocument(word_to_documents, document_id, ReadLine()); } // Выводим id const string query = ReadLine(); for (const int document_id : FindDocuments(word_to_documents, stop_words, query)) { cout << document_id << endl; } }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 2012-2012 Opera Software ASA. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. */ #ifndef __OP_SERVER_NAME_H__ #define __OP_SERVER_NAME_H__ #include "modules/url/url_sn.h" /** @class OpServerName * */ class OpServerName { public: /** Destructor. */ virtual ~OpServerName() {} /** Get the current SocketAddress. */ virtual OpSocketAddress* SocketAddress() = 0; /** Set this Host's IP address from the string */ virtual OP_STATUS SetHostAddressFromString(const OpStringC& address) = 0; /** Return the unicode version of this server name. */ virtual const uni_char* UniName() const = 0; /** Return the 8-bit version of this server's name. */ virtual const char *Name() const = 0; /** Return the number of components in the servername. */ virtual uint32 GetNameComponentCount() = 0; /** Return a OpStringC8 object referencing the given name component item of the servername, empty if no component. */ virtual OpStringC8 GetNameComponent(uint32 item) = 0; /** Return a pointer to the servername object for the parent domain. * * @param servername Pointer to the servername object for the parent domain. Servername will be NULL if no parent domain exists. * @return OK or ERR_NO_MEMORY */ virtual OP_STATUS GetParentDomain(OpServerName *&servername) = 0; /** Get a pointer for the most specific common domain name the two domains, NULL if no common domain exists. * * E.g. the common domain of "www.opera.com" and "web.opera.com" is "opera.com", for * "www.microsoft.com" and "www.opera.com" it is "com", and for "www.opera.com" and * "www.opera.com" there is no common domain and it will return a NULL pointer. * * @param servername The servername we are comparing with. * @param result The domain common between this name and the other name, may be NULL. * @return OK or ERR_NO_MEMORY */ virtual OP_STATUS GetCommonDomain(OpServerName *servername, OpServerName *&result) = 0; #ifdef _ASK_COOKIE /** Set the cookie filter setting. */ virtual void SetAcceptCookies(COOKIE_MODES mode) = 0; /** Get the cookie filter setting. * * @param follow_domain If set the top parent domain is used. * @param use_local Use the domain "local" if follow_domain==TRUE and there is no parent domain. */ virtual COOKIE_MODES GetAcceptCookies(BOOL follow_domain = FALSE, BOOL use_local = TRUE) = 0; /** Set the illegal path filter. * * @param mode Should cookies be deleted on exit. */ virtual void SetAcceptIllegalPaths(COOKIE_ILLPATH_MODE mode) = 0; /** Get the illegal path filter. * * @param follow_domain If set the top parent domain is used. * @param use_local Use the domain "local" if follow_domain==TRUE and there is no parent domain. */ virtual COOKIE_ILLPATH_MODE GetAcceptIllegalPaths(BOOL follow_domain = FALSE, BOOL use_local = TRUE) = 0; /** Set Domain specific empty on exit. * * @param mode Should cookies be deleted on exit. */ virtual void SetDeleteCookieOnExit(COOKIE_DELETE_ON_EXIT_MODE mode) = 0; /** Get the delete cookie on exit setting. * * @param follow_domain If set the top parent domain is used. * @param use_local Use the domain "local" if follow_domain==TRUE and there is no parent domain. */ virtual COOKIE_DELETE_ON_EXIT_MODE GetDeleteCookieOnExit(BOOL follow_domain = FALSE, BOOL use_local = TRUE) = 0; #endif /** Set the third party filter setting. */ virtual void SetAcceptThirdPartyCookies(COOKIE_MODES mod) = 0; /** Get the third party filter setting. * @param follow_domain If set the top parent domain is used. * @param first If set, the "local" domain is used. */ virtual COOKIE_MODES GetAcceptThirdPartyCookies(BOOL follow_domain = FALSE, BOOL first = TRUE) = 0; /** Are we permitted to pass usernames (and passwords) embedded in the URL to this server without challenging the user? */ virtual BOOL GetPassUserNameURLsAutomatically(const OpStringC8 &p_name) = 0; /** Set whether or not we are permitted to pass usernames (and passwords) embedded in the URL to this server without challenging the user? */ virtual OP_STATUS SetPassUserNameURLsAutomatically(const OpStringC8 &p_name) = 0; #ifdef TRUST_RATING /** Set Time To Live for the trust rating. */ virtual void SetTrustTTL(unsigned int TTL) = 0; /** Get trust rating level. */ virtual TrustRating GetTrustRating() = 0; /** Set trust rating level. */ virtual void SetTrustRating(TrustRating new_trust_rating) = 0; /** Is the trust rating bypassed for this server? */ virtual BOOL GetTrustRatingBypassed() = 0; /** Specify that trust rating warning is to be bypassed for this server. */ virtual void SetTrustRatingBypassed(BOOL new_trust_rating_bypassed) = 0; /** Add a url to the list of fraud urls we will warn about. */ virtual OP_STATUS AddTrustRatingUrl(const OpStringC &url, int id) = 0; /** See if a fraud url can be found. */ virtual BOOL FindTrustRatingUrl(const OpStringC &url) = 0; /** Add a regular expression to the list of fraud expressions we will warn about. */ virtual OP_STATUS AddTrustRatingRegExp(const OpStringC &regexp) = 0; /** Retrieve first regular expression item. */ virtual FraudListItem *GetFirstTrustRatingRegExp() = 0; /** Is fraud list empty? */ virtual BOOL FraudListIsEmpty() = 0; /** Add advisory for a URL. * * @param homepage_url url for the advisory. * @param advisory_url url for the advisory. * @param text * @param type */ virtual void AddAdvisoryInfo(const uni_char *homepage_url, const uni_char *advisory_url, const uni_char *text, unsigned int src, ServerSideFraudType type) = 0; /** Retrieve the advisory for a URL. * * @param url url for the advisory. * @return Advisory containing more info about the url. */ virtual Advisory *GetAdvisory(const OpStringC &url) = 0; #endif }; class ServerNameCallback { public: virtual void ServerNameResult(OpServerName *server_name, OP_STATUS result) = 0; }; #endif
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef agdktunnel_input_util_hpp #define agdktunnel_input_util_hpp #include "engine.hpp" #include "our_key_codes.hpp" // event type #define COOKED_EVENT_TYPE_JOY 0 #define COOKED_EVENT_TYPE_POINTER_DOWN 1 #define COOKED_EVENT_TYPE_POINTER_UP 2 #define COOKED_EVENT_TYPE_POINTER_MOVE 3 #define COOKED_EVENT_TYPE_KEY_DOWN 4 #define COOKED_EVENT_TYPE_KEY_UP 5 #define COOKED_EVENT_TYPE_BACK 6 #define COOKED_EVENT_TYPE_TEXT_INPUT 7 struct CookedEvent { int type; // for joystick events: float joyX, joyY; // for pointer events int motionPointerId; bool motionIsOnScreen; float motionX, motionY; float motionMinX, motionMaxX; float motionMinY, motionMaxY; // for key events int keyCode; // whether a text input has occurred bool textInputState; }; typedef bool (*CookedEventCallback)(struct CookedEvent *event); bool CookGameActivityKeyEvent(GameActivityKeyEvent *keyEvent, CookedEventCallback callback); bool CookGameActivityMotionEvent(GameActivityMotionEvent *motionEvent, CookedEventCallback callback); bool CookGameControllerEvent(const int32_t gameControllerIndex, CookedEventCallback callback); #endif
#include"parentMode.h" #include"Timeset.h" #pragma execution_character_set("utf-8") USING_NS_CC; #define H_PI 1.570796327f //#include"FlowWord.h" #include "DropDownList.h" #include"ScrollViewScene.h" #include"HelloWorldScene.h" #include"parentstudy.h" #include"introduction.h" #define database UserDefault::getInstance() Scene* parentMode::createScene(){ // 'scene' is an autorelease object auto scene = Scene::create(); // 'layer' is an autorelease object auto layer = parentMode::create(); // add layer as a child to scene scene->addChild(layer); // return the scene return scene; } bool parentMode::init() { if (!Layer::init()) { return false; } visibleSize = Director::getInstance()->getVisibleSize(); Vec2 origin = Director::getInstance()->getVisibleOrigin(); dispatcher = Director::getInstance()->getEventDispatcher(); //log("%s", FileUtils::getInstance()->getWritablePath().c_str()); //auto path = FileUtils::getInstance()->getWritablePath() + "/UserDefault.xml"; auto background = Sprite::create("parent_read/login.png"); float x = visibleSize.width / background->getContentSize().width; float y = visibleSize.height / background->getContentSize().height; background->setScale(x, y); background->setAnchorPoint(Vec2::ZERO); background->setPosition(Vec2::ZERO); this->addChild(background); taglabel = Sprite::create("parentmode/11.png"); float xx = visibleSize.width / taglabel->getContentSize().width; float yy = visibleSize.height / taglabel->getContentSize().height; taglabel->setScale(xx/2,yy); taglabel->setAnchorPoint(Vec2::ZERO); taglabel->setPosition(Vec2::ZERO); this->addChild(taglabel); auto panel = Sprite::create("parentmode/11.png"); panel->setPosition(visibleSize.width / 5 * 3, visibleSize.height / 2); auto label2 = Label::createWithTTF("选择家长", "fonts/my_font3.ttf", 24); label2->setPosition(Vec2(panel->getPosition().x-panel->getContentSize().width/1.7+label2->getContentSize().width, panel->getPosition().y+panel->getContentSize().height/3)); this->addChild(label2, 1); label2->setVisible(false); //auto label3 = Label::createWithTTF("联系方式", "fonts/my_font3.ttf", 24); //label3->setPosition(Vec2(panel->getPosition().x - panel->getContentSize().width / 1.7 + label2->getContentSize().width, panel->getPosition().y + panel->getContentSize().height / 12)); //this->addChild(label3, 3); //auto label4 = Label::createWithTTF("家庭住址", "fonts/my_font3.ttf", 24); //label4->setPosition(Vec2(panel->getPosition().x - panel->getContentSize().width / 1.7 + label2->getContentSize().width, panel->getPosition().y-panel->getContentSize().height / 6)); //this->addChild(label4, 3); auto level_1 = MenuItemImage::create( "my_button.png", "my_button3.png", "my_button2.png", CC_CALLBACK_1(parentMode::Level_1, this)); auto menuWidth = visibleSize.width / 38 * 4.6; auto menuHeight = visibleSize.height / 19 * 2; level_1->setScale(menuWidth / level_1->getContentSize().width, menuHeight / level_1->getContentSize().height); //creat Level_2 auto level_2 = MenuItemImage::create( "my_button.png", "my_button3.png", "my_button2.png", CC_CALLBACK_1(parentMode::Level_1, this)); level_2->setEnabled(false); auto menu = Menu::create(level_1, NULL); menu->alignItemsHorizontallyWithPadding(level_1->getContentSize().width); menu->setPosition(Vec2(visibleSize.width/38*20.72,visibleSize.height/19*2.95)); this->addChild(menu, 3); auto close_item = MenuItemImage::create("CloseNormal.png", "CloseSelected.png", CC_CALLBACK_1(parentMode::menuCloseCallback, this)); close_item->setPosition( Vec2(origin.x + visibleSize.width - close_item->getContentSize().width / 2, origin.y + close_item->getContentSize().height / 2)); // create menu, it's an autorelease object auto mymenu = Menu::create(close_item, NULL); mymenu->setPosition(Vec2::ZERO); this->addChild(mymenu, 1); ///////////////////////////// // 3. add your codes below... // add a label shows "Hello World" // create and initialize a label //创建一个label作为下拉菜单的默认选项 auto label = Label::createWithTTF("妈妈", "fonts/my_font3.ttf", 36); label->setColor(Color3B::BLACK); label->setTextColor(Color4B::BLACK); //设置大小 auto box_size = Size(visibleSize.width/38*5.15, visibleSize.height/19*1.05); // list_box = CustomDropDownListBox::DropDownList::Create(label, box_size, Size(visibleSize.width / 38 * 5.15, visibleSize.height / 19 * 1.05)); //添加一堆label进去 CCDictionary *strings = CCDictionary::createWithContentsOfFile("fonts/chinese.xml"); const char *charchinese = ((CCString*)strings->objectForKey("parent1"))->getCString(); auto labell0 = Label::create(charchinese, "Arial", 18); labell0->setColor(Color3B::BLACK); //auto labell0 = Label::createWithTTF(); list_box->AddLabel(labell0);//不知道怎么把默认显示的label添加到选项里,只好再添加一个 CCDictionary *strings1 = CCDictionary::createWithContentsOfFile("fonts/chinese.xml"); const char *charchinese1 = ((CCString*)strings1->objectForKey("parent2"))->getCString(); auto labell1 = Label::create(charchinese1, "Arial", 18); labell1->setColor(Color3B::BLACK); list_box->AddLabel(labell1); CCDictionary *strings2 = CCDictionary::createWithContentsOfFile("fonts/chinese.xml"); const char *charchinese2 = ((CCString*)strings2->objectForKey("parent3"))->getCString(); auto labell2 = Label::create(charchinese2, "Arial", 18); labell2->setColor(Color3B::BLACK); list_box->AddLabel(labell2); CCDictionary *strings3 = CCDictionary::createWithContentsOfFile("fonts/chinese.xml"); const char *charchinese3 = ((CCString*)strings3->objectForKey("parent4"))->getCString(); auto labell3 = Label::create(charchinese3, "Arial", 18); labell3->setColor(Color3B::BLACK); list_box->AddLabel(labell3); CCDictionary *strings4 = CCDictionary::createWithContentsOfFile("fonts/chinese.xml"); const char *charchinese4 = ((CCString*)strings4->objectForKey("parent5"))->getCString(); auto labell4 = Label::create(charchinese4, "Arial", 18); labell4->setColor(Color3B::BLACK); list_box->AddLabel(labell4); // 设置位置 list_box->setPosition( Vec2(visibleSize.width/38*14.45, visibleSize.height/19*13.85)); this->addChild(list_box, 4); //启动监听 list_box->OpenListener(); testTouchEvent(); /*auto timesetLabel = MenuItemImage::create( "my_button.png", "my_button3.png", "my_button2.png", CC_CALLBACK_1(parentMode::timeset, this)); auto timesetmenu = Menu::create(timesetLabel, NULL); timesetmenu->alignItemsHorizontallyWithPadding(timesetLabel->getContentSize().width / 3 * 2); timesetmenu->setPosition(Vec2(100, visibleSize.height / 4 * 3)); this->addChild(timesetmenu, 3); auto messagelabel = MenuItemImage::create( "my_button.png", "my_button3.png", "my_button2.png", CC_CALLBACK_1(parentMode::message, this)); auto messagemenu = Menu::create(messagelabel, NULL); messagemenu->alignItemsHorizontallyWithPadding(messagelabel->getContentSize().width / 3 * 2); messagemenu->setPosition(Vec2(100, visibleSize.height / 4 * 2)); this->addChild(messagemenu, 3); auto parentstudylabel = MenuItemImage::create( "my_button.png", "my_button3.png", "my_button2.png", CC_CALLBACK_1(parentMode::parentstudy, this)); auto parentstudymenu = Menu::create(parentstudylabel, NULL); parentstudymenu->alignItemsHorizontallyWithPadding(parentstudylabel->getContentSize().width / 3 * 2); parentstudymenu->setPosition(Vec2(100, visibleSize.height / 4)); this->addChild(parentstudymenu, 3);*/ auto back = MenuItemImage::create("timeset/back.png", "timeset/back.png", CC_CALLBACK_1(parentMode::returnto, this)); back->setScale(0.2*visibleSize.height/back->getContentSize().height); auto back_menu = Menu::create(back, NULL); back_menu->setPosition(Vec2(back->getBoundingBox().size.width/2, visibleSize.height - back->getBoundingBox().size.height/2)); this->addChild(back_menu, 3); //CCDictionary *xmlstrings = CCDictionary::createWithContentsOfFile(path.c_str()); if (!database->getBoolForKey("isExist")){ database->setBoolForKey("isExist", true); database->setStringForKey("babyName", "Child's name"); database->setStringForKey("telNumber", "Tel number"); database->setStringForKey("address", "Address"); database->setStringForKey("password", "Password"); database->setIntegerForKey("indexs", 0); } list_box->SetSelectedIndex(database->getIntegerForKey("indexs")); auto childname = database->getStringForKey("babyName"); textEdit = TextFieldTTF::textFieldWithPlaceHolder(childname, "fonts/arial.ttf", 36); textEdit->setPosition(Vec2(visibleSize.width/38*27.95,visibleSize.height/19*14.35)); this->addChild(textEdit, 10); setTouchMode(kCCTouchesOneByOne); setTouchEnabled(true); auto telNumber = database->getStringForKey("telNumber"); textEdit2 = TextFieldTTF::textFieldWithPlaceHolder(telNumber, "fonts/arial.ttf", 36); textEdit2->setPosition(Vec2(visibleSize.width / 38 * 17.78, visibleSize.height / 19 * 10.79)); this->addChild(textEdit2, 10); setTouchMode(kCCTouchesOneByOne); setTouchEnabled(true); auto address = database->getStringForKey("address"); textEdit3 = TextFieldTTF::textFieldWithPlaceHolder(address, "fonts/arial.ttf", 36); textEdit3->setPosition(Vec2(visibleSize.width/38*20.58,visibleSize.height/19*6.85)); this->addChild(textEdit3, 10); setTouchMode(kCCTouchesOneByOne); setTouchEnabled(true); auto password = database->getStringForKey("password"); if (password != "Password") { for (int i = 0; i < password.length(); i++) { password.at(i) = '*'; } } textEdit4 = TextFieldTTF::textFieldWithPlaceHolder(password, "fonts/arial.ttf", 36); textEdit4->setPosition(Vec2(visibleSize.width / 38 * 29.1, visibleSize.height / 19 * 10.79)); this->addChild(textEdit4, 10); setTouchMode(kCCTouchesOneByOne); setTouchEnabled(true); return true; } void parentMode::returnto(Ref* ref) { this->stopAllActions(); auto scene = HelloWorld::createScene(); CCDirector::sharedDirector()->replaceScene(CCTransitionFade::create(0.1, scene, Color3B::GRAY)); } void parentMode::timeset(Ref* ref) { this->stopAllActions(); auto scene = Timeset::createScene(); CCDirector::sharedDirector()->replaceScene(CCTransitionFade::create(0.1, scene, Color3B::GRAY)); } void parentMode::message(Ref* ref) { } void parentMode::parentstudy(Ref *ref) { this->stopAllActions(); auto scene = parentstudy::createScene(); CCDirector::sharedDirector()->replaceScene(CCTransitionFade::create(0.1, scene, Color3B::GRAY)); } void parentMode::testTouchEvent() { streak = MotionStreak::create(0.5f, 10, 30, Color3B::WHITE, "Demo/flash.png"); this->addChild(streak, 2); //10.55 9.1 7.65 6.24 4.75 auto listener = EventListenerTouchOneByOne::create(); listener->onTouchBegan = [&](Touch* touch, Event* event){ touch_pos = touch->getLocation(); //滑动拖尾效果 if (touch_pos.x > 0 && touch_pos.x < visibleSize.width /2 *4.2/17.64) { if (touch_pos.y > visibleSize.height / 14.1*9.1 && touch_pos.y < visibleSize.height / 14.1*10.55) { } else if (touch_pos.y > visibleSize.height / 14.1*7.65 && touch_pos.y < visibleSize.height / 14.1*9.1) { timeset(this); } else if (touch_pos.y > visibleSize.height / 14.1*6.24 && touch_pos.y < visibleSize.height / 14.1*7.65) { parentstudy(this); } else if (touch_pos.y > visibleSize.height / 14.1*4.75 && touch_pos.y < visibleSize.height / 14.1*6.24) { this->stopAllActions(); auto scene = introduction::createScene(); CCDirector::sharedDirector()->replaceScene(CCTransitionFade::create(0.1, scene, Color3B::GRAY)); } } return true; }; listener->onTouchMoved = [&](Touch* touch, Event* event){ }; listener->onTouchEnded = [&](Touch* touch, Event* event){ log("onTouchEnded"); }; dispatcher->addEventListenerWithSceneGraphPriority(listener, this); } void parentMode::CallbackShowMenu(Ref* sender) { this->setPosition(-100, this->getPosition().y); } void parentMode::menuCloseCallback(Ref* pSender) { #if (CC_TARGET_PLATFORM == CC_PLATFORM_WP8) || (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT) MessageBox("You pressed the close button. Windows Store Apps do not implement a close button.", "Alert"); return; #endif Director::getInstance()->end(); #if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) exit(0); #endif } void parentMode::Level_1(Ref* ref) { auto temp1 = textEdit->getString(); if (temp1.length() > 1) { database->setStringForKey("babyName", temp1); } auto temp2 = textEdit2->getString(); if (temp2.length() > 1) { database->setStringForKey("telNumber", temp2); } auto temp3 = textEdit3->getString(); if (temp3.length() > 1) { database->setStringForKey("address", temp3); } auto temp4 = textEdit4->getString(); if (temp4.length() > 1) { database->setStringForKey("password", temp4); } database->setIntegerForKey("indexs", list_box->GetSelectedIndex()); } bool parentMode::onTouchBegan(cocos2d::Touch* touch, cocos2d::Event* event) { bool isClicked = textEdit->boundingBox().containsPoint(touch->getLocation()); //如果点中了控件 if (isClicked) { //弹出软键盘 textEdit->attachWithIME(); textEdit->setTextColor(Color4B::BLACK); } bool isClicked2 = textEdit2->boundingBox().containsPoint(touch->getLocation()); //如果点中了控件 if (isClicked2) { //弹出软键盘 textEdit2->attachWithIME(); textEdit2->setTextColor(Color4B::BLACK); } bool isClicked3 = textEdit3->boundingBox().containsPoint(touch->getLocation()); //如果点中了控件 if (isClicked3) { //弹出软键盘 textEdit3->attachWithIME(); textEdit3->setTextColor(Color4B::BLACK); } //表示接受触摸消息 bool isClicked4 = textEdit4->boundingBox().containsPoint(touch->getLocation()); if (isClicked4) { //弹出软键盘 textEdit4->attachWithIME(); textEdit4->setTextColor(Color4B::BLACK); } return true; } void parentMode::onTouchMoved(cocos2d::Touch* touch, cocos2d::Event* event) { } void parentMode::onTouchEnded(cocos2d::Touch* touch, cocos2d::Event* event) { }
#pragma once #include <string> #include "Model.h" namespace engine{ Model loadModelFile(std::string file, bool &error); }
// Created on: 2005-10-14 // Created by: Mikhail KLOKOV // Copyright (c) 2005-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _IntTools_CurveRangeSampleMapHasher_HeaderFile #define _IntTools_CurveRangeSampleMapHasher_HeaderFile #include <IntTools_CurveRangeSample.hxx> #include <Standard.hxx> #include <Standard_DefineAlloc.hxx> #include <Standard_Integer.hxx> //! class for range index management of curve class IntTools_CurveRangeSampleMapHasher { public: DEFINE_STANDARD_ALLOC //! Computes a hash code for the given key, in the range [1, theUpperBound] //! @param theKey the key which hash code is to be computed //! @param theUpperBound the upper bound of the range a computing hash code must be within //! @return a computed hash code, in the range [1, theUpperBound] static Standard_Integer HashCode (const IntTools_CurveRangeSample& theKey, const Standard_Integer theUpperBound) { return ::HashCode(theKey.GetDepth(), theUpperBound); } //! Returns True when the two keys are the same. Two //! same keys must have the same hashcode, the //! contrary is not necessary. static Standard_Boolean IsEqual (const IntTools_CurveRangeSample& S1, const IntTools_CurveRangeSample& S2) { return S1.IsEqual(S2); } }; #endif // _IntTools_CurveRangeSampleMapHasher_HeaderFile
#include "BrushStone.h" #include "omp.h" #include "Misc.h" BrushStone::BrushStone() { setFuzzy( 10.0f ); setRadius( 40.0f ); setSize( 60 ); transparency = 255; borderTransparency = 255; brushStokeCount = 50; brushStrokeSizeMin = 20; brushStrokeSizeMax = 80; brushStrokeAlpha = 240; saturation = 255; borderSize = 30; selectedColor = ofColor( 255, 255, 255 ); bufferWidth = 1920; bufferHeight = 1080; tDrawStone = true; tDrawBorder = false; layer.allocate( Misc::getDefaultFboSettings() ); //underlyingLayer.allocate( settings ); } BrushStone::~BrushStone() { } void BrushStone::clear() { layer.begin(); ofClear( 0.0, 0.0, 0.0, 1.0 ); layer.end(); //underlyingLayer.begin(); //ofClear( 255, 255, 255, 0 ); //underlyingLayer.end(); locationsPointsDrawn.clear(); contourPoints.clear(); currentGrowRad = 5; maxGrowRad = 700; setFuzzy( 10.0f ); setRadius( 40.0f ); setSize( 60 ); transparency = 255; borderTransparency = 255; brushStokeCount = 50; brushStrokeSizeMin = 20; brushStrokeSizeMax = 80; brushStrokeAlpha = 140; saturation = 255; borderSize = 30; selectedColor = ofColor( 255, 255, 255 ); } void BrushStone::init( float _x, float _y ) { layer.begin(); ofClear( 255, 255, 255, 0 ); layer.end(); //underlyingLayer.begin(); //ofClear( 255, 255, 255, 0 ); //underlyingLayer.end(); centroid = ofPoint( _x, _y ); currentGrowRad = 5; maxGrowRad = 700; setFuzzy( 10.0f ); setRadius( 40.0f ); setSize( 60 ); transparency = 255; borderTransparency = 255; brushStokeCount = 50; brushStrokeSizeMin = 20; brushStrokeSizeMax = 80; brushStrokeAlpha = 240; saturation = 255; borderSize = 30; selectedColor = ofColor( 232, 151, 44 ); } void BrushStone::draw( float x, float y, float w, float h ) { ofPushStyle(); ofEnableAlphaBlending(); if( tDrawStone ) { ofSetColor( selectedColor, transparency ); layer.draw( x, y, w, h ); } //if( tDrawBorder ) { // ofSetColor( selectedColor, borderTransparency ); // underlyingLayer.draw( x, y, w, h ); //} ofPopStyle(); } void BrushStone::grow( ofPolyline line ) { if( currentGrowRad < maxGrowRad ) { currentGrowRad += 0.5f; layer.begin(); int nrToCheck = ( int ) ( ofMap( currentGrowRad, 0, maxGrowRad, 5, 15 ) ); ofPushStyle(); ofEnableAlphaBlending(); std::vector< ofVec2f > pointsToDraw( nrToCheck ); // decide here weather to grow the stone from the centroid of the outline, or from the actual voronoi cell core ofVec2f p = line.getCentroid2D(); // centroid #pragma omp parallel for for( int i = 0; i < nrToCheck; i++ ) { float deg = ofRandom( 0, TWO_PI ); float _x = currentGrowRad * cos( deg ); float _y = currentGrowRad * sin( deg ); //int randomId = ofRandom( 0, points.size() ); ofVec2f pToSave = p + ofVec2f( _x, _y ); pointsToDraw.at( i ) = pToSave; } ofPolyline lineToCheck = line.getResampledBySpacing( 50 ); std::vector< ofPoint > tempLocationsDrawn( nrToCheck ); // checking parallelized for overlapping #pragma omp parallel for for( int i = 0; i < pointsToDraw.size(); i++ ) { ofVec2f p = pointsToDraw.at( i ); ofRectangle bb = lineToCheck.getBoundingBox(); // first check for bounding box inside as its quicker to compute if( bb.inside( p ) ) { if( lineToCheck.inside( p ) ) { tempLocationsDrawn.at( i ) = ofPoint( p.x, p.y ); } } } // removing vectors at around location 0, 0 vector<ofPoint>::iterator it = tempLocationsDrawn.begin(); for( ; it != tempLocationsDrawn.end(); ) { ofPoint *_p = &( *it ); if( _p->x < 4 || _p->y < 4 ) { it = tempLocationsDrawn.erase( it ); } else { ++it; locationsPointsDrawn.push_back( *_p ); } } for( int i = 0; i < tempLocationsDrawn.size(); i++ ) { ofVec2f p = tempLocationsDrawn.at( i ); float s = ofRandom( brushStrokeSizeMin, brushStrokeSizeMax ); ofSetColor( colors.getRandomColor(), brushStrokeAlpha ); brushes.getRandomBrush().draw( p.x - s / 2.0, p.y - s / 2.0, s, s ); } ofDisableAlphaBlending(); ofPopStyle(); layer.end(); //underlyingLayer.begin(); //ofClear( 1.0 ); //underlyingLayer.end(); if( tDrawBorder ) { calcBorder( locationsPointsDrawn ); renderBorder(); } } } void BrushStone::grow() { currentGrowRad = currentGrowRad + 1.0f; if( currentGrowRad < maxGrowRad ) { //calcBorder( locationsPointsDrawn ); //underlyingLayer.begin(); //ofClear( 1.0 ); //underlyingLayer.end(); //renderBorder(); layer.begin(); int nrToCheck = ( int ) ( ofMap( currentGrowRad, 0, maxGrowRad, 5, 15 ) ); ofPushStyle(); //ofEnableAlphaBlending(); ofEnableBlendMode( OF_BLENDMODE_ADD ); for( int i = 0; i < nrToCheck; i++ ) { float deg = ofRandom( 0, TWO_PI ); float _x = currentGrowRad * cos( deg ); float _y = currentGrowRad * sin( deg ); float s = ofRandom( brushStrokeSizeMin, brushStrokeSizeMax ); //int randomId = ofRandom( 0, points.size() ); ofVec2f p( centroid ); //ofVec2f p = getCenterById( randomId ); p += ofVec2f( _x, _y ); ofSetColor( colors.getRandomColor(), brushStrokeAlpha ); locationsPointsDrawn.push_back( ofVec2f( p.x, p.y ) ); brushes.getRandomBrush().draw( p.x - s / 2.0, p.y - s / 2.0, s, s ); } ofDisableBlendMode(); //ofDisableAlphaBlending(); ofPopStyle(); layer.end(); } } void BrushStone::grow(int brushIndex) { currentGrowRad = currentGrowRad + 1.0f; if( currentGrowRad < maxGrowRad ) { //calcBorder( locationsPointsDrawn ); //underlyingLayer.begin(); //ofClear( 1.0 ); //underlyingLayer.end(); //renderBorder(); layer.begin(); int nrToCheck = ( int ) ( ofMap( currentGrowRad, 0, maxGrowRad, 5, 15 ) ); ofPushStyle(); //ofEnableAlphaBlending(); ofEnableBlendMode( OF_BLENDMODE_ADD ); for( int i = 0; i < nrToCheck; i++ ) { float deg = ofRandom( 0, TWO_PI ); float _x = currentGrowRad * cos( deg ); float _y = currentGrowRad * sin( deg ); float s = ofRandom( brushStrokeSizeMin, brushStrokeSizeMax ); //int randomId = ofRandom( 0, points.size() ); ofVec2f p( centroid ); //ofVec2f p = getCenterById( randomId ); p += ofVec2f( _x, _y ); ofSetColor( colors.getRandomColor(), brushStrokeAlpha ); locationsPointsDrawn.push_back( ofVec2f( p.x, p.y ) ); brushes.getBrushById( brushIndex ).draw( p.x - s / 2.0, p.y - s / 2.0, s, s ); } ofDisableBlendMode(); //ofDisableAlphaBlending(); ofPopStyle(); layer.end(); } } void BrushStone::grow( ofPolyline line, ofVec2f center ) { if( currentGrowRad < maxGrowRad ) { currentGrowRad += 0.5f; layer.begin(); int nrToCheck = ( int ) ( ofMap( currentGrowRad, 0, maxGrowRad, 5, 15 ) ); ofPushStyle(); ofEnableAlphaBlending(); std::vector< ofVec2f > pointsToDraw( nrToCheck ); // decide here weather to grow the stone from the centroid of the outline, or from the actual voronoi cell core ofVec2f p = center; // centroid #pragma omp parallel for for( int i = 0; i < nrToCheck; i++ ) { float deg = ofRandom( 0, TWO_PI ); float _x = currentGrowRad * cos( deg ); float _y = currentGrowRad * sin( deg ); //int randomId = ofRandom( 0, points.size() ); ofVec2f pToSave = p + ofVec2f( _x, _y ); pointsToDraw.at( i ) = pToSave; } ofPolyline lineToCheck = line.getResampledBySpacing( 50 ); std::vector< ofPoint > tempLocationsDrawn( nrToCheck ); // checking parallelized for overlapping #pragma omp parallel for for( int i = 0; i < pointsToDraw.size(); i++ ) { ofVec2f p = pointsToDraw.at( i ); ofRectangle bb = lineToCheck.getBoundingBox(); // first check for bounding box inside as its quicker to compute if( bb.inside( p ) ) { if( lineToCheck.inside( p ) ) { tempLocationsDrawn.at( i ) = ofPoint( p.x, p.y ); } } } // removing vectors at around location 0, 0 vector<ofPoint>::iterator it = tempLocationsDrawn.begin(); for( ; it != tempLocationsDrawn.end(); ) { ofPoint *_p = &( *it ); if( _p->x < 4 || _p->y < 4 ) { it = tempLocationsDrawn.erase( it ); } else { ++it; locationsPointsDrawn.push_back( *_p ); } } for( int i = 0; i < tempLocationsDrawn.size(); i++ ) { ofVec2f p = tempLocationsDrawn.at( i ); float s = ofRandom( brushStrokeSizeMin, brushStrokeSizeMax ); ofSetColor( colors.getRandomColor(), brushStrokeAlpha ); brushes.getRandomBrush().draw( p.x - s / 2.0, p.y - s / 2.0, s, s ); } ofDisableAlphaBlending(); ofPopStyle(); layer.end(); //underlyingLayer.begin(); //ofClear( 1.0 ); //underlyingLayer.end(); if( tDrawBorder ) { calcBorder( locationsPointsDrawn ); renderBorder(); } } } bool BrushStone::growForWaterColor( float rad ) { if( rad < maxGrowRad ) { //calcBorder( locationsPointsDrawn ); //underlyingLayer.begin(); //ofClear( 1.0 ); //underlyingLayer.end(); //renderBorder(); // experimenting with drawing on water color canvas. if it failed, reuse this layer //layer.begin(); int nrToCheck = ( int ) ( ofMap( rad, 0, maxGrowRad, 5, 15 ) ); ofPushStyle(); ofEnableAlphaBlending(); for( int i = 0; i < nrToCheck; i++ ) { float deg = ofRandom( 0, TWO_PI ); float _x = rad * cos( deg ); float _y = rad * sin( deg ); float s = ofRandom( brushStrokeSizeMin, brushStrokeSizeMax ); //int randomId = ofRandom( 0, points.size() ); ofVec2f p( centroid ); //ofVec2f p = getCenterById( randomId ); p += ofVec2f( _x, _y ); ofSetColor( colors.getRandomColor(), brushStrokeAlpha ); locationsPointsDrawn.push_back( ofVec2f( p.x, p.y ) ); brushes.getRandomBrush().draw( p.x - s / 2.0, p.y - s / 2.0, s, s ); } ofDisableAlphaBlending(); ofPopStyle(); //layer.end(); return true; } return false; } void BrushStone::growPlain( int brushId ) { currentGrowRad += 1.0f; if( currentGrowRad < maxGrowRad ) { //calcBorder( locationsPointsDrawn ); //underlyingLayer.begin(); //ofClear( 1.0 ); //underlyingLayer.end(); //renderBorder(); // experimenting with drawing on water color canvas. if it failed, reuse this layer layer.begin(); int nrToCheck = ( int ) ( ofMap( currentGrowRad, 0, maxGrowRad, 5, 15 ) ); ofPushStyle(); ofEnableAlphaBlending(); for( int i = 0; i < nrToCheck; i++ ) { float deg = ofRandom( 0, TWO_PI ); float _x = currentGrowRad * cos( deg ); float _y = currentGrowRad * sin( deg ); float s = ofRandom( brushStrokeSizeMin, brushStrokeSizeMax ); //int randomId = ofRandom( 0, points.size() ); ofVec2f p( centroid ); //ofVec2f p = getCenterById( randomId ); p += ofVec2f( _x, _y ); ofSetColor( colors.getRandomColor(), brushStrokeAlpha ); locationsPointsDrawn.push_back( ofVec2f( p.x, p.y ) ); if( brushId == 0 ) { brushes.getRandomBrush().draw( p.x - s / 2.0, p.y - s / 2.0, s, s ); } else if( brushId == 1 ) { brushes.getCircleBrush().draw( p.x - s / 2.0, p.y - s / 2.0, s, s ); } else { brushes.getBrushById(brushId).draw( p.x - s / 2.0, p.y - s / 2.0, s, s ); } } ofDisableAlphaBlending(); ofPopStyle(); layer.end(); } } void BrushStone::setFuzzy( float fuzzy ) { this->fuzzy = fuzzy; } void BrushStone::setRadius( float rad ) { this->radius = rad; } float BrushStone::getRadius() { return this->radius; } float BrushStone::getFuzzy() { return this->fuzzy; } void BrushStone::setSize( int size ) { this->size = size; } int BrushStone::getNumberOfCircles() { return this->size; } std::vector< ofPoint > BrushStone::getContourPoints( float x, float y ) { return contourPoints; } void BrushStone::calcBorder( std::vector< ofPoint > points ) { contourPoints = convexHull.getConvexHull( points ); } int BrushStone::getNumberOfStrokes() { return getNumberOfCircles(); } void BrushStone::setBrushCollection( BrushCollection _b ) { this->brushes = _b; } void BrushStone::renderBorder() { /* underlyingLayer.begin(); ofPushStyle(); ofEnableAlphaBlending(); ofEnableBlendMode( OF_BLENDMODE_ADD ); if( contourPoints.size() > 0 ) { ofFill(); TS_START_NIF( "convert1" ); std::vector< Point1 > convexPoints( contourPoints.size() ); #pragma omp parallel for for( int i = 0; i < contourPoints.size(); i += 1 ) { ofPoint _poi = contourPoints.at( i ); Point1 p; p.x = _poi.x; p.y = _poi.y; convexPoints.at( i ) = p; } TS_STOP_NIF( "convert1" ); TS_START_NIF( "convex" ); std::vector< Point1 > ps = VoronoiLayer::convex_hull( convexPoints ); TS_STOP_NIF( "convex" ); border.clear(); border.setClosed( true ); TS_START_NIF( "convert2" ); std::vector< ofPoint > finalPoints( ps.size() ); #pragma omp parallel for for( int i = 0; i < ps.size(); i++ ) { Point1 from = ps.at( i ); finalPoints.at( i ) = ofPoint( from.x, from.y ); } TS_STOP_NIF( "convert2" ); TS_START_NIF( "etc" ); border.addVertices( finalPoints ); border.setClosed( true ); border = border.getResampledBySpacing( 20 ); ofSetColor( 51, 25, 0, 255 ); float s = 10; ofSeedRandom( 0 ); TS_STOP_NIF( "etc" ); TS_START_NIF( "drawing_b" ); for( int i = 0; i < border.getVertices().size(); i++ ) { ofPoint p = border.getVertices().at( i ); brushes.getRandomBrush().draw( p.x - borderSize / 2.0, p.y - borderSize / 2.0, borderSize, borderSize ); } TS_STOP_NIF( "drawing_b" ); ofSeedRandom(); } else { std::cout << "Contour points empty. No border!" << std::endl; } ofDisableAlphaBlending(); ofPopStyle(); underlyingLayer.end(); */ } void BrushStone::setColorCollection( ColorCollection _c ) { this->colors = _c; } void BrushStone::setTransparency( float _trans ) { transparency = _trans; } void BrushStone::setBrushStrokeCount( int count ) { this->brushStokeCount = count; } void BrushStone::setBrushStrokeSizeMin( float min ) { this->brushStrokeSizeMin = min; } void BrushStone::setBrushStrokeSizeMax( float max ) { brushStrokeSizeMax = max; } void BrushStone::setBrushStrokeAlpha( float alpha ) { brushStrokeAlpha = alpha; } int BrushStone::getBrushStrokeCount() { return this->brushStokeCount; } float BrushStone::getBrushStrokeSizeMin() { return this->brushStrokeSizeMin; } float BrushStone::getBrushStrokeSizeMax() { return this->brushStrokeSizeMax; } float BrushStone::getBrushStrokeAlpha() { return this->brushStrokeAlpha; } void BrushStone::setBorderTransparency( float _trans ) { this->borderTransparency = _trans; } ofFbo BrushStone::getStoneBuffer() { return layer; } void BrushStone::setBorderSize( int _bsize ) { this->borderSize = _bsize; } int BrushStone::getBorderSize() { return this->borderSize; } void BrushStone::setSaturation( float _sat ) { this->saturation = _sat; } float BrushStone::getSaturation() { return this->saturation; } vector<ofVec3f> BrushStone::resamplePolylineToCount( const ofPolyline& polyline, int n ) { vector<ofVec3f> points; float jump = 1.0f / ( n - 1 ); for( int i = 0; i < n; i++ ) { points.push_back( polyline.getPointAtPercent( min( i*jump, 0.99999f ) ) ); } return points; } float BrushStone::getTransparency() { return this->transparency; } void BrushStone::toggleRenderBorder( bool _b ) { this->tDrawBorder = _b; } void BrushStone::toggleDrawStone( bool _s ) { this->tDrawStone = _s; } void BrushStone::setSelectedColor( ofColor col ) { this->selectedColor = col; }
#include<iostream> #include<cstdio> #include<map> #include<set> #include<vector> #include<stack> #include<queue> #include<string> #include<cstring> #include<sstream> #include<algorithm> #include<cmath> #define INF 0x3f3f3f3f #define eps 1e-8 #define pi acos(-1.0) using namespace std; struct point { int x,y; }; point a[10]; bool cmp(point a,point b) { if (a.x == b.x) return a.y < b.y; return a.x < b.x; } int main() { int n; scanf("%d",&n); for (int i = 1;i <= n; i++) scanf("%d%d",&a[i].x,&a[i].y); sort(a+1,a+n+1,cmp); if (n == 1) printf("-1\n"); else { int ans = abs((a[n].x-a[1].x)*(a[n].y - a[1].y)); if (n == 3) { ans = max(ans,abs((a[2].x-a[1].x)*(a[1].y-a[2].y))); ans = max(ans,abs((a[2].x-a[3].x)*(a[2].y-a[3].y))); } if (ans) printf("%d\n",ans); else printf("-1\n"); } return 0; }
//Copyright 2011-2016 Tyler Gilbert; All Rights Reserved #include "hal/Uart.hpp" using namespace hal; Uart::Uart(port_t port) : Periph(CORE_PERIPH_UART, port) {} int Uart::get_attr(uart_attr_t & attr){ return ioctl(I_UART_GETATTR, &attr); } int Uart::set_attr(const uart_attr_t & attr){ return ioctl(I_UART_SETATTR, &attr); } int Uart::get_byte(char * c){ return ioctl(I_UART_GETBYTE, c); } int Uart::flush(){ return ioctl(I_UART_FLUSH); }
// Created on: 1995-11-15 // Created by: Jean-Louis Frenkel <rmi@pernox> // Copyright (c) 1995-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _UnitsAPI_HeaderFile #define _UnitsAPI_HeaderFile #include <Standard.hxx> #include <Standard_DefineAlloc.hxx> #include <Standard_Handle.hxx> #include <Standard_CString.hxx> #include <UnitsAPI_SystemUnits.hxx> class Units_Dimensions; //! The UnitsAPI global functions are used to //! convert a value from any unit into another unit. //! Principles //! Conversion is executed among three unit systems: //! - the SI System //! - the user's Local System //! - the user's Current System. //! The SI System is the standard international unit //! system. It is indicated by SI in the synopses of //! the UnitsAPI functions. //! The MDTV System corresponds to the SI //! international standard but the length unit and all //! its derivatives use millimeters instead of the meters. //! Both systems are proposed by Open CASCADE; //! the SI System is the standard option. By //! selecting one of these two systems, the user //! defines his Local System through the //! SetLocalSystem function. The Local System is //! indicated by LS in the synopses of the UnitsAPI functions. //! The user's Local System units can be modified in //! the working environment. The user defines his //! Current System by modifying its units through //! the SetCurrentUnit function. The Current //! System is indicated by Current in the synopses //! of the UnitsAPI functions. class UnitsAPI { public: DEFINE_STANDARD_ALLOC //! Converts the current unit value to the local system units value. //! Example: CurrentToLS(1.,"LENGTH") returns 1000. if the current length unit //! is meter and LocalSystem is MDTV. Standard_EXPORT static Standard_Real CurrentToLS (const Standard_Real aData, const Standard_CString aQuantity); //! Converts the current unit value to the SI system units value. //! Example: CurrentToSI(1.,"LENGTH") returns 0.001 if current length unit //! is millimeter. Standard_EXPORT static Standard_Real CurrentToSI (const Standard_Real aData, const Standard_CString aQuantity); //! Converts the local system units value to the current unit value. //! Example: CurrentFromLS(1000.,"LENGTH") returns 1. if current length unit //! is meter and LocalSystem is MDTV. Standard_EXPORT static Standard_Real CurrentFromLS (const Standard_Real aData, const Standard_CString aQuantity); //! Converts the SI system units value to the current unit value. //! Example: CurrentFromSI(0.001,"LENGTH") returns 1 if current length unit //! is millimeter. Standard_EXPORT static Standard_Real CurrentFromSI (const Standard_Real aData, const Standard_CString aQuantity); //! Converts the local unit value to the local system units value. //! Example: AnyToLS(1.,"in.") returns 25.4 if the LocalSystem is MDTV. Standard_EXPORT static Standard_Real AnyToLS (const Standard_Real aData, const Standard_CString aUnit); //! Converts the local unit value to the local system units value. //! and gives the associated dimension of the unit Standard_EXPORT static Standard_Real AnyToLS (const Standard_Real aData, const Standard_CString aUnit, Handle(Units_Dimensions)& aDim); //! Converts the local unit value to the SI system units value. //! Example: AnyToSI(1.,"in.") returns 0.0254 Standard_EXPORT static Standard_Real AnyToSI (const Standard_Real aData, const Standard_CString aUnit); //! Converts the local unit value to the SI system units value. //! and gives the associated dimension of the unit Standard_EXPORT static Standard_Real AnyToSI (const Standard_Real aData, const Standard_CString aUnit, Handle(Units_Dimensions)& aDim); //! Converts the local system units value to the local unit value. //! Example: AnyFromLS(25.4,"in.") returns 1. if the LocalSystem is MDTV. //! Note: aUnit is also used to identify the type of physical quantity to convert. Standard_EXPORT static Standard_Real AnyFromLS (const Standard_Real aData, const Standard_CString aUnit); //! Converts the SI system units value to the local unit value. //! Example: AnyFromSI(0.0254,"in.") returns 0.001 //! Note: aUnit is also used to identify the type of physical quantity to convert. Standard_EXPORT static Standard_Real AnyFromSI (const Standard_Real aData, const Standard_CString aUnit); //! Converts the aData value expressed in the //! current unit for the working environment, as //! defined for the physical quantity aQuantity by the //! last call to the SetCurrentUnit function, into the unit aUnit. Standard_EXPORT static Standard_Real CurrentToAny (const Standard_Real aData, const Standard_CString aQuantity, const Standard_CString aUnit); //! Converts the aData value expressed in the unit //! aUnit, into the current unit for the working //! environment, as defined for the physical quantity //! aQuantity by the last call to the SetCurrentUnit function. Standard_EXPORT static Standard_Real CurrentFromAny (const Standard_Real aData, const Standard_CString aQuantity, const Standard_CString aUnit); //! Converts the local unit value to another local unit value. //! Example: AnyToAny(0.0254,"in.","millimeter") returns 1. ; Standard_EXPORT static Standard_Real AnyToAny (const Standard_Real aData, const Standard_CString aUnit1, const Standard_CString aUnit2); //! Converts the local system units value to the SI system unit value. //! Example: LSToSI(1.,"LENGTH") returns 0.001 if the local system //! length unit is millimeter. Standard_EXPORT static Standard_Real LSToSI (const Standard_Real aData, const Standard_CString aQuantity); //! Converts the SI system unit value to the local system units value. //! Example: SIToLS(1.,"LENGTH") returns 1000. if the local system //! length unit is millimeter. Standard_EXPORT static Standard_Real SIToLS (const Standard_Real aData, const Standard_CString aQuantity); //! Sets the local system units. //! Example: SetLocalSystem(UnitsAPI_MDTV) Standard_EXPORT static void SetLocalSystem (const UnitsAPI_SystemUnits aSystemUnit = UnitsAPI_SI); //! Returns the current local system units. Standard_EXPORT static UnitsAPI_SystemUnits LocalSystem(); //! Sets the current unit dimension <aUnit> to the unit quantity <aQuantity>. //! Example: SetCurrentUnit("LENGTH","millimeter") Standard_EXPORT static void SetCurrentUnit (const Standard_CString aQuantity, const Standard_CString aUnit); //! Returns the current unit dimension <aUnit> from the unit quantity <aQuantity>. Standard_EXPORT static Standard_CString CurrentUnit (const Standard_CString aQuantity); //! saves the units in the file .CurrentUnits of the directory pointed by the //! CSF_CurrentUnitsUserDefaults environment variable. Standard_EXPORT static void Save(); Standard_EXPORT static void Reload(); //! return the dimension associated to the quantity Standard_EXPORT static Handle(Units_Dimensions) Dimensions (const Standard_CString aQuantity); Standard_EXPORT static Handle(Units_Dimensions) DimensionLess(); Standard_EXPORT static Handle(Units_Dimensions) DimensionMass(); Standard_EXPORT static Handle(Units_Dimensions) DimensionLength(); Standard_EXPORT static Handle(Units_Dimensions) DimensionTime(); Standard_EXPORT static Handle(Units_Dimensions) DimensionElectricCurrent(); Standard_EXPORT static Handle(Units_Dimensions) DimensionThermodynamicTemperature(); Standard_EXPORT static Handle(Units_Dimensions) DimensionAmountOfSubstance(); Standard_EXPORT static Handle(Units_Dimensions) DimensionLuminousIntensity(); Standard_EXPORT static Handle(Units_Dimensions) DimensionPlaneAngle(); //! Returns the basic dimensions. Standard_EXPORT static Handle(Units_Dimensions) DimensionSolidAngle(); //! Checks the coherence between the quantity <aQuantity> //! and the unit <aUnits> in the current system and //! returns FALSE when it's WRONG. Standard_EXPORT static Standard_Boolean Check (const Standard_CString aQuantity, const Standard_CString aUnit); protected: private: Standard_EXPORT static void CheckLoading (const UnitsAPI_SystemUnits aSystemUnit); }; #endif // _UnitsAPI_HeaderFile
#include <iostream> #include <queue> #include <algorithm> int main() { std::cin.sync_with_stdio(false); std::cin.tie(NULL); int n, mid = 10001; std::priority_queue<int> l; std::priority_queue<int, std::vector<int>, std::greater<int>> r; std::cin >> n; for(int i = 0; i < n; i++) { int number; std::cin >> number; if(mid > number) { l.push(number); } else { r.push(number); } while(l.size() < r.size()) { l.push(r.top()); r.pop(); } while(l.size() > r.size() + 1) { r.push(l.top()); l.pop(); } mid = l.top(); std::cout << mid << '\n'; } return 0; }
// Created on: 1997-11-20 // Created by: Philippe MANGIN // Copyright (c) 1997-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _GeomFill_SectionLaw_HeaderFile #define _GeomFill_SectionLaw_HeaderFile #include <Standard.hxx> #include <Standard_Type.hxx> #include <Standard_Transient.hxx> #include <TColgp_Array1OfPnt.hxx> #include <TColStd_Array1OfReal.hxx> #include <TColgp_Array1OfVec.hxx> #include <Standard_Integer.hxx> #include <TColStd_Array1OfInteger.hxx> #include <GeomAbs_Shape.hxx> class Geom_BSplineSurface; class gp_Pnt; class Geom_Curve; class GeomFill_SectionLaw; DEFINE_STANDARD_HANDLE(GeomFill_SectionLaw, Standard_Transient) //! To define section law in sweeping class GeomFill_SectionLaw : public Standard_Transient { public: //! compute the section for v = param Standard_EXPORT virtual Standard_Boolean D0 (const Standard_Real Param, TColgp_Array1OfPnt& Poles, TColStd_Array1OfReal& Weigths) = 0; //! compute the first derivative in v direction of the //! section for v = param //! Warning : It used only for C1 or C2 approximation Standard_EXPORT virtual Standard_Boolean D1 (const Standard_Real Param, TColgp_Array1OfPnt& Poles, TColgp_Array1OfVec& DPoles, TColStd_Array1OfReal& Weigths, TColStd_Array1OfReal& DWeigths); //! compute the second derivative in v direction of the //! section for v = param //! Warning : It used only for C2 approximation Standard_EXPORT virtual Standard_Boolean D2 (const Standard_Real Param, TColgp_Array1OfPnt& Poles, TColgp_Array1OfVec& DPoles, TColgp_Array1OfVec& D2Poles, TColStd_Array1OfReal& Weigths, TColStd_Array1OfReal& DWeigths, TColStd_Array1OfReal& D2Weigths); //! give if possible an bspline Surface, like iso-v are the //! section. If it is not possible this methode have to //! get an Null Surface. It is the default implementation. Standard_EXPORT virtual Handle(Geom_BSplineSurface) BSplineSurface() const; //! get the format of an section Standard_EXPORT virtual void SectionShape (Standard_Integer& NbPoles, Standard_Integer& NbKnots, Standard_Integer& Degree) const = 0; //! get the Knots of the section Standard_EXPORT virtual void Knots (TColStd_Array1OfReal& TKnots) const = 0; //! get the Multplicities of the section Standard_EXPORT virtual void Mults (TColStd_Array1OfInteger& TMults) const = 0; //! Returns if the sections are rationnal or not Standard_EXPORT virtual Standard_Boolean IsRational() const = 0; //! Returns if the sections are periodic or not Standard_EXPORT virtual Standard_Boolean IsUPeriodic() const = 0; //! Returns if law is periodic or not Standard_EXPORT virtual Standard_Boolean IsVPeriodic() const = 0; //! Returns the number of intervals for continuity //! <S>. //! May be one if Continuity(me) >= <S> Standard_EXPORT virtual Standard_Integer NbIntervals (const GeomAbs_Shape S) const = 0; //! Stores in <T> the parameters bounding the intervals //! of continuity <S>. //! //! The array must provide enough room to accommodate //! for the parameters. i.e. T.Length() > NbIntervals() Standard_EXPORT virtual void Intervals (TColStd_Array1OfReal& T, const GeomAbs_Shape S) const = 0; //! Sets the bounds of the parametric interval on //! the function //! This determines the derivatives in these values if the //! function is not Cn. Standard_EXPORT virtual void SetInterval (const Standard_Real First, const Standard_Real Last) = 0; //! Gets the bounds of the parametric interval on //! the function Standard_EXPORT virtual void GetInterval (Standard_Real& First, Standard_Real& Last) const = 0; //! Gets the bounds of the function parametric domain. //! Warning: This domain it is not modified by the //! SetValue method Standard_EXPORT virtual void GetDomain (Standard_Real& First, Standard_Real& Last) const = 0; //! Returns the tolerances associated at each poles to //! reach in approximation, to satisfy: BoundTol error //! at the Boundary AngleTol tangent error at the //! Boundary (in radian) SurfTol error inside the //! surface. Standard_EXPORT virtual void GetTolerance (const Standard_Real BoundTol, const Standard_Real SurfTol, const Standard_Real AngleTol, TColStd_Array1OfReal& Tol3d) const = 0; //! Is useful, if (me) have to run numerical //! algorithm to perform D0, D1 or D2 //! The default implementation make nothing. Standard_EXPORT virtual void SetTolerance (const Standard_Real Tol3d, const Standard_Real Tol2d); //! Get the barycentre of Surface. //! An very poor estimation is sufficient. //! This information is useful to perform well //! conditioned rational approximation. //! Warning: Used only if <me> IsRational Standard_EXPORT virtual gp_Pnt BarycentreOfSurf() const; //! Returns the length of the greater section. This //! information is useful to G1's control. //! Warning: With an little value, approximation can be slower. Standard_EXPORT virtual Standard_Real MaximalSection() const = 0; //! Compute the minimal value of weight for each poles //! in all sections. //! This information is useful to control error //! in rational approximation. //! Warning: Used only if <me> IsRational Standard_EXPORT virtual void GetMinimalWeight (TColStd_Array1OfReal& Weigths) const; //! Say if all sections are equals Standard_EXPORT virtual Standard_Boolean IsConstant (Standard_Real& Error) const; //! Return a copy of the constant Section, if me //! IsConstant Standard_EXPORT virtual Handle(Geom_Curve) ConstantSection() const; //! Returns True if all section are circle, with same //! plane,same center and linear radius evolution //! Return False by Default. Standard_EXPORT virtual Standard_Boolean IsConicalLaw (Standard_Real& Error) const; //! Return the circle section at parameter <Param>, if //! <me> a IsConicalLaw Standard_EXPORT virtual Handle(Geom_Curve) CirclSection (const Standard_Real Param) const; DEFINE_STANDARD_RTTIEXT(GeomFill_SectionLaw,Standard_Transient) protected: private: }; #endif // _GeomFill_SectionLaw_HeaderFile
#include <bits/stdc++.h> #include "lc.h" using namespace std; extern int yylex(); extern char* yytext; int table[5][6]={{1,0,0, 0, 0}, {0, 2, 0 ,0 ,3, 3,}, {4 ,0 ,0 ,4 ,0, 0}, {0 ,6 ,5, 0, 6 ,6}, {8 ,0 ,0 ,7 ,0 ,0}}; map <int,string> prod; map <char,int> r,c; int parse(string s) { //cout<<s<<" "; stack <char> st; st.push('$'); st.push('E'); int i,j,l,ind=0; char ch; while(ind<s.size()) { if(st.empty()) { return 0; } if(st.top()=='$'&&s[ind]=='$') { return 1; } char top; top=st.top(); //cout<<top<<" "<<id<<endl; if(top>=65&&top<=90) { if(table[r[top]][c[s[ind]]]==0) { return 0; } string pr=prod[table[r[top]][c[s[ind]]]]; if(pr.size()==4&&pr[3]=='@') { st.pop(); } else { st.pop(); for(i=pr.size()-1;i>=0;i--) { if(pr[i]=='>') { break; } st.push(pr[i]); } } } else { if(top==s[ind]) { st.pop(); ind++; } else { return 0; } } } return 0; } int main() { r['E']=0; r['K']=1; r['T']=2; r['M']=3; r['F']=4; c['i']=0; c['+']=1; c['*']=2; c['(']=3; c[')']=4; c['$']=5; prod[1]="E->TK"; prod[2]="K->+TK"; prod[3]="K->@"; prod[4]="T->FM"; prod[5]="M->*FM"; prod[6]="M->@"; prod[7]="F->(E)"; prod[8]="F->i"; int m,n,i,j; /*cin>>m>>n; for(i=0;i<m;i++) { for (j=0;j<n;j++) { cin>>table[i][j]; } }*/ m=5;n=6; int no=yylex(); string s="",os=""; while(no) { if(no==nl) { if(parse(s+"$")) { cout<<os<<" is a Valid String\n"; } else { cout<<os<<" is Not a Valid String\n"; } os=""; s=""; } else if(no==id) { s=s+"i"; for(int i=0;i<strlen(yytext);i++) { os=os+yytext[i]; } } else { for(int i=0;i<strlen(yytext);i++) { s=s+yytext[i]; os=os+yytext[i]; } } no=yylex(); } return 0; } /*5 6 1 0 0 1 0 0 0 2 0 0 3 3 4 0 0 4 0 0 0 6 5 0 6 6 8 0 0 7 0 0*/
/**************************************************************************** * * * Author : lukasz.iwaszkiewicz@gmail.com * * ~~~~~~~~ * * License : see COPYING file for details. * * ~~~~~~~~~ * ****************************************************************************/ #ifndef TWEENINGPROPERTY_H_ #define TWEENINGPROPERTY_H_ #include <cstddef> #include <list> namespace Tween { class IAccessor; /** * */ struct TweeningProperty { TweeningProperty () : accessor (NULL), startValue (0), endValue (0), absolute (true) {} IAccessor const *accessor; double startValue; double endValue; bool absolute; }; typedef std::list <TweeningProperty *> TweeningPropertyList; } /* namespace Tween */ #endif /* TWEENINGPROPERTY_H_ */
/** * @file scene.hpp * * Scene class include file. */ #ifndef BETELGEUSE_SCENE_HPP #define BETELGEUSE_SCENE_HPP namespace betelgeuse { class object; class light; /** * The scene class is used for rendering. It combines all object types and * all instances and renders them onto the screen. */ class scene { public: /// Basic constructor. scene(void); /// Basic destructor. ~scene(void); /** * Sets the horizontal field of view. * * @param fov FOV in radians. */ void set_fov(float fov); /// Sets the display aspect (X/Y). void set_aspect(float aspect); /// Adds an object type. void new_object_type(object *obj); /// Adds a light instance. void add_light(light *lgt); /** * Renders everything into the <tt>output</tt> texture. * * @sa scene::output */ void render(void); /// Displays the <tt>output</tt> texture onto the screen. void display(void); /** * Output texture. This is the place where everything is rendered * to. If you need to, you may access this directly as allowed by * the MACS framework. If you just want to display it one the * screen, use the <tt>display()</tt> method. * * @sa void scene::display(void) */ macs::texture output; private: /// Initializes the view rays. void render_view(void); /// Renders object intersection points. void render_intersection(void); /// Creates the shadow maps. void render_shadows(void); /// Does the light shading. void render_shading(void); /// Adds the ambient lighting. void render_ambient(void); /// Display aspect. float aspect; /// Vertical FOV. macs::types::named<float> yfov; /// Horizontal FOV. macs::types::named<float> xfov; /// Anticipated most far Z value. macs::types::named<float> zfar; /// Camera position. macs::types::named<macs::types::vec4> cam_pos; /// Camera's forward pointing vector. macs::types::named<macs::types::vec3> cam_fwd; /// Camera's right pointing vector. macs::types::named<macs::types::vec3> cam_rgt; /// Camera's up pointing vector. macs::types::named<macs::types::vec3> cam_up; /// List of object classes attached. std::list<object *> objs; /// List of lights attached. std::list<light *> lgts; /// Stencil/depth buffer used for intersection calculcation. macs::stencildepth sd; /// Ray starting points. macs::texture ray_stt; /// Ray directions. macs::texture ray_dir; /// Global intersection point map. macs::texture glob_isct; /// Surface normal map. macs::texture norm_map; /// Surface tangent map. macs::texture tang_map; /// Material ambient map. macs::texture ambient_map; /// Material mirror map. macs::texture mirror_map; /// Material refraction map. macs::texture refract_map; /// Texture UV map. macs::texture uv_map; /// Material layer 0 color map. macs::texture color0_map; /// Material layer 1 color map. macs::texture color1_map; /// Material roughness/isotropy maps for both layers (XY/ZW). macs::texture rp_map; /// "Artificial" stencil buffer (for early-out in fragment shaders). macs::texture asten; /// Initial view rendering object. macs::render *rnd_view; /// Ambient light rendering object. macs::render *rnd_ambient; /// Current light source position (for shadow calculation). macs::types::named<macs::types::vec4> cur_light_pos; }; } #endif
class MinStack { private: stack<int> numStk; stack<int> minStk; public: /** initialize your data structure here. */ MinStack() { } void push(int x) { numStk.push(x); if(minStk.empty() || minStk.top() >= x) minStk.push(x); } void pop() { if(minStk.top() == numStk.top()) minStk.pop(); numStk.pop(); } int top() { return numStk.top(); } int getMin() { return minStk.top(); } }; /** * Your MinStack object will be instantiated and called as such: * MinStack obj = new MinStack(); * obj.push(x); * obj.pop(); * int param_3 = obj.top(); * int param_4 = obj.getMin(); */
#include <vector> #include <queue> #include "UF.hpp" #include "WeightGraph.h" #include "PQ.hpp" #ifndef KRUSKAL_HPP #define KRUSKAL_HPP class Kruskal { private: std::queue<Edge> mst; WeightQuickUnion uf; PQ<Edge> pq; double weight; public: Kruskal(WeightGraph &G) : uf(G.getV()), pq(G.getE()), weight(0.0) { for (Edge e : G.edges()) { pq.insert(e); } while (!pq.isEmpty() && mst.size() < G.getV() - 1) { Edge e = pq.delMin(); int v = e.either(), w = e.other(v); if (uf.connected(v, w)) continue; uf.Union(v, w); weight += e.getWeight(); mst.push(e); } } std::queue<Edge> edges() { return mst; } double getWeight() { return weight; } }; #endif
// // Containers.h // // The MIT License (MIT) // // Copyright (c) 2015 Bradley Wilson // // 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. // #ifndef Tools_Containers_h #define Tools_Containers_h // ================================================================================ Standard Includes // Standard Includes // -------------------------------------------------------------------------------- #include <array> #include <vector> #include <deque> #include <map> #include <unordered_map> // ================================================================================ Tools Includes // Tools Includes // -------------------------------------------------------------------------------- #include "SmartWrapper.h" namespace Core { // ============================================================================ Containers // Containers // // SmartObject/SmartPtr-compatible container classes // ---------------------------------------------------------------------------- Array template < typename value_t, std::size_t element_count > using Array = SmartWrapper< std::array<value_t, element_count> >; // ---------------------------------------------------------------------------- Vector template < typename value_t, typename alloc = std::allocator<value_t> > using Vector = SmartWrapper< std::vector<value_t, alloc> >; // ---------------------------------------------------------------------------- Deque template< typename value_t, typename alloc = std::allocator<value_t> > using Deque = SmartWrapper< std::deque<value_t, alloc> >; // ---------------------------------------------------------------------------- Map template < typename key_t, typename value_t, typename compare = std::less<key_t>, typename alloc = std::allocator< std::pair<const key_t, value_t> > > using Map = SmartWrapper< std::map<key_t, value_t, compare, alloc> >; // ---------------------------------------------------------------------------- Unordered_Map template< typename key_t, typename value_t, typename hash = std::hash<key_t>, typename key_equal = std::equal_to<key_t>, typename alloc = std::allocator< std::pair<const key_t, value_t> > > using Unordered_Map = SmartWrapper< std::unordered_map<key_t, value_t> >; }; #endif
#include<iostream> #include "CFBoard.hpp" /************************************************************************** makeMove Function *This function is to make piece move by passing column and x coordinate after each left or right move, then record its total distance. If the argument is greater and equal to 0, total distance is added xCoordinate. If the argument is smaller that o which means left move, then distace is added -xCoordinate. ***************************************************************************/ bool CFBoard::makeMove(int col, char player){ col = col - 1; if(gameState != UNFINISHED || board[0][col] == 'x' || board[0][col] == 'o') { return false; } else { for(int row = 5; row >= 0; row--){ if (board[row][col] == '.'){ board[row][col] = player; updateGameState(row, col); break; } } return true; } } void CFBoard::updateGameState(int row, int col){ /****************** Check horizontal ******************/ int moveLeft = col; char player = board[row][col]; while(board[row][moveLeft] == player && moveLeft >= 0) moveLeft --; int moveRight = col; while(board[row][moveRight] == player && moveRight <= 6) moveRight ++; int length = moveRight - moveLeft - 1; if(length == 4) { if (player == 'x') { gameState = X_WON; return; } else { gameState = O_WON; return; } } /****************** Check vertical ******************/ int moveUp = row; while(board[moveUp][col] == player && moveUp >= 0) moveUp --; int moveDown = row; while(board[moveDown][col] == player && moveDown <= 5) moveDown ++; length = moveDown - moveUp - 1; if(length == 4) { if (player == 'x') { gameState = X_WON; return; } else { gameState = O_WON; return; } } /****************** Check Anti-diagonal ******************/ moveDown = row; moveLeft = col; while(board[moveDown][moveLeft] == player && moveDown <= 5 && moveLeft >= 0) { moveDown ++; moveLeft --; } moveUp = row; moveRight = col; while(board[moveUp][moveRight] == player && moveUp >= 0 && moveRight <= 6) { moveUp --; moveRight ++; } length = moveDown - moveUp - 1; if(length == 4) { if (player == 'x') { gameState = X_WON; return; } else { gameState = O_WON; return; } } /****************** Check diagonal ******************/ moveUp = row; moveLeft = col; while(board[moveUp][moveLeft] == player && moveUp >= 0 && moveLeft >= 0) { moveUp --; moveLeft --; } moveDown = row; moveRight = col; while(board[moveDown][moveRight] == player && moveDown <= 5 && moveRight <= 6) { moveRight ++; moveDown ++; } length = moveRight - moveLeft - 1; if(length == 4) { if (player == 'x') { gameState = X_WON; return; } else { gameState = O_WON; return; } } /***************************** check gamestate is drow or not *****************************/ // if(row = 0) // { // count = 0; // while(count <= 6){ // if (board[0][count] == 'x' || board[0][count] == 'o') // { // count ++; // } // else // break; // gameState = GameState.DRAW // } // } if(row == 0){ for (int i = 0; i <= 6; i++) { if(board[0][i] == '.') return; } gameState = DRAW; } } GameState CFBoard::getGameState() //getGameState function { return gameState; } void CFBoard::print() { std::cout << "1234567" << std::endl; for(int row = 0; row < 6; row ++) //Initializing array of board { for(int col = 0; col < 7; col++) { std::cout << board[row][col]; } std::cout << std::endl; } }
#ifndef __SKILLCAT__HPP__ #define __SKILLCAT__HPP__ #include "Skill.hpp" class UniqueSkill: public Skill{ private: // Species of the Unique Skill string Species; public: // Default Constructor UniqueSkill(); // User-Defined Constructor UniqueSkill(string name, int basePower, vector<string> elmts, string species, int mastery = 1); // Copy Constructor UniqueSkill(const UniqueSkill& unique); // Operator= UniqueSkill& operator=(const UniqueSkill& unique); // Methods const bool isSkillLearnable(string engimonElmt, string species); const void skillInfo(); // Getter const string getSkillSpecies(); }; class SpecialSkill: public Skill{ private: // Additional Power of The Special Skill int additionalPower; public: // Default Constructor SpecialSkill(); // User-Defined Constructor SpecialSkill(string name, int basePower, vector<string> elmts, int addPower, int mastery = 1); // Copy Constructor SpecialSkill(const SpecialSkill& special); // Operator= SpecialSkill& operator=(const SpecialSkill& special); // Methods const int totalDamage(); const void skillInfo(); // Getter const int getAddPower(); }; #endif
#include "BugStateMachine.h" #include <cmath> bool BugStateMachine::checkWall(const std::vector<lidar::LidarData>& data) const { int cnt = 0; for (const auto& d : data) { if (std::abs(d.angle) < 30 && d.dist < 500) { ++cnt; } } if (cnt > 5) { return true; } return false; } void BugStateMachine::to_TargetState(const std::vector<lidar::LidarData>& data) { if (checkWall(data)) { state = State::WALL_ENCOUNTER; } } void BugStateMachine::wall_encounterState(const std::vector<lidar::LidarData>& data) { state = State::FOLLOWING_WALL; } void BugStateMachine::following_wallState(const std::vector<lidar::LidarData>& data) { auto pos = data[0].robPos; double toTarget = pos.p.dirTo(target); if (abs(scaleAngle(pos.theta) - rad2deg(toTarget)) < 5) { state = State::TO_TARGET; } if (checkWall(data)) { state = State::WALL_ENCOUNTER; } } void BugStateMachine::tick(const std::vector<lidar::LidarData>& data) { switch (state) { case BugStateMachine::State::TO_TARGET: to_TargetState(data); break; case BugStateMachine::State::WALL_ENCOUNTER: wall_encounterState(data); break; case BugStateMachine::State::FOLLOWING_WALL: following_wallState(data); break; default: break; } } BugStateMachine::State BugStateMachine::getState() const { return state; } void BugStateMachine::reset() { state = State::TO_TARGET; } void BugStateMachine::setTarget(const Point& p) { target = p; reset(); } Point BugStateMachine::getTarget() const { return target; }
#pragma once #include <SFML\Graphics.hpp> #include <vector> #include <random> class CellGrid { public: CellGrid(); CellGrid(int numberCellsX, int numberCellsY, int cellWidth, int cellHeight, int FPS); ~CellGrid(); void draw(sf::RenderWindow& window); int getIndexVertex(int i, int j); int getIndex(int i, int j); sf::Color randomGray(); void setCellColor(int i, int j); void setCellPosition(int i, int j); void setOldGrid(); void update(float dT); int updateCell(int i, int j); private: int FPS; int numberCellsX; int numberCellsY; int cellWidth; int cellHeight; std::vector<int> oldGrid; std::vector<int> newGrid; std::vector<sf::Vertex> vertexGrid; };
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4; c-file-style:"stroustrup" -*- * * Copyright (C) 1995-2008 Opera Software AS. All rights reserved. * * This file is part of the Opera web browser. * It may not be distributed under any circumstances. */ #include "core/pch.h" #ifdef VEGA_SUPPORT #include "modules/libvega/src/vegafiltercolortransform.h" #include "modules/libvega/src/vegapixelformat.h" #ifdef VEGA_3DDEVICE #include "modules/libvega/vega3ddevice.h" #endif // VEGA_3DDEVICE #define VEGA_CLAMP_U8(v) (((v) <= 255) ? (((v) >= 0) ? (v) : 0) : 255) #ifdef USE_PREMULTIPLIED_ALPHA #define VEGA_COND_PREMULT(a,r,g,b) \ do{\ (r) = (((a) + 1) * (r)) >> 8;\ (g) = (((a) + 1) * (g)) >> 8;\ (b) = (((a) + 1) * (b)) >> 8;\ }while(0) #define VEGA_COND_UNPREMULT(a,r,g,b) \ do{\ if ((a))\ {\ (r) = 255 * (r) / (a);\ (g) = 255 * (g) / (a);\ (b) = 255 * (b) / (a);\ }\ else\ (r) = (g) = (b) = 0;\ }while(0) #else #define VEGA_COND_PREMULT(a,r,g,b) do{}while(0) #define VEGA_COND_UNPREMULT(a,r,g,b) do{}while(0) #endif // USE_PREMULTIPLIED_ALPHA VEGAFilterColorTransform::VEGAFilterColorTransform(VEGAColorTransformType type, VEGA_FIX* mat) : transform_type(type) { setMatrix(mat); #ifdef VEGA_3DDEVICE xlat_table = NULL; xlat_table_needs_update = TRUE; #endif // VEGA_3DDEVICE } VEGAFilterColorTransform::~VEGAFilterColorTransform() { #ifdef VEGA_3DDEVICE VEGARefCount::DecRef(xlat_table); #endif // VEGA_3DDEVICE } void VEGAFilterColorTransform::setMatrix(VEGA_FIX* mat) { if (!mat) return; for (int i = 0; i < 20; i++) matrix[i] = mat[i]; } void VEGAFilterColorTransform::setCompIdentity(VEGAComponent comp) { for (unsigned int i = 0; i < 256; i++) lut[comp][i] = i; #ifdef VEGA_3DDEVICE xlat_table_needs_update = TRUE; #endif // VEGA_3DDEVICE } void VEGAFilterColorTransform::setCompTable(VEGAComponent comp, VEGA_FIX* c_table, unsigned int c_table_size) { for (unsigned int i = 0; i < 256; i++) { VEGA_FIX fix_c = VEGA_INTTOFIX(i) / 255; unsigned int tidx = VEGA_FIXTOINT(VEGA_FLOOR(fix_c * (c_table_size - 1))); int val; if (tidx < c_table_size-1) { VEGA_FIX frac = fix_c * (c_table_size - 1) - VEGA_INTTOFIX(tidx); VEGA_FIX fix_val = c_table[tidx] + VEGA_FIXMUL(frac, c_table[tidx+1] - c_table[tidx]); val = VEGA_FIXTOINT(255 * fix_val); } else { val = VEGA_FIXTOINT(255 * c_table[c_table_size-1]); } lut[comp][i] = (unsigned char)VEGA_CLAMP_U8(val); } #ifdef VEGA_3DDEVICE xlat_table_needs_update = TRUE; #endif // VEGA_3DDEVICE } void VEGAFilterColorTransform::setCompDiscrete(VEGAComponent comp, VEGA_FIX* c_table, unsigned int c_table_size) { for (unsigned int i = 0; i < 256; i++) { unsigned int tbl_idx = (i * c_table_size) / 255; if (tbl_idx >= c_table_size) tbl_idx = c_table_size - 1; int val = VEGA_FIXTOINT(255 * c_table[tbl_idx]); lut[comp][i] = (unsigned char)VEGA_CLAMP_U8(val); } #ifdef VEGA_3DDEVICE xlat_table_needs_update = TRUE; #endif // VEGA_3DDEVICE } void VEGAFilterColorTransform::setCompLinear(VEGAComponent comp, VEGA_FIX slope, VEGA_FIX intercept) { for (unsigned int i = 0; i < 256; i++) { VEGA_FIX norm_i = VEGA_INTTOFIX(i) / 255; VEGA_FIX lin = VEGA_FIXMUL(slope, norm_i) + intercept; int val = VEGA_FIXTOINT(lin * 255); lut[comp][i] = (unsigned char)VEGA_CLAMP_U8(val); } #ifdef VEGA_3DDEVICE xlat_table_needs_update = TRUE; #endif // VEGA_3DDEVICE } void VEGAFilterColorTransform::setCompGamma(VEGAComponent comp, VEGA_FIX ampl, VEGA_FIX exp, VEGA_FIX offs) { for (unsigned int i = 0; i < 256; i++) { VEGA_FIX norm_i = VEGA_INTTOFIX(i) / 255; VEGA_FIX corr = VEGA_FIXMUL(ampl, VEGA_FIXPOW(norm_i, exp)) + offs; int val = VEGA_FIXTOINT(255 * corr); lut[comp][i] = (unsigned char)VEGA_CLAMP_U8(val); } #ifdef VEGA_3DDEVICE xlat_table_needs_update = TRUE; #endif // VEGA_3DDEVICE } void VEGAFilterColorTransform::setColorSpaceConversion(VEGACSConversionType type) { switch (type) { case VEGACSCONV_SRGB_TO_LINRGB: { // linRGB = (sRGB <= 0.04045) ? sRGB / 12.92 : ((sRGB + 0.055) / 1.055)^(2.4) VEGA_FIX exp = VEGA_INTTOFIX(24) / 10; /* 2.4 */ for (unsigned int i = 0; i < 256; i++) { VEGA_FIX norm_i = VEGA_INTTOFIX(i) / 255; VEGA_FIX corr; if (i < 11) // 11/255 ~= 0.043 { corr = norm_i * 100 / 1292; /* sRGB/12.92 */ } else { VEGA_FIX base = (norm_i * 1000 + VEGA_INTTOFIX(55)) / 1055; /* (sRGB+0.055)/1.055 */ corr = VEGA_FIXPOW(base, exp); } int val = VEGA_FIXTOINT(255 * corr); lut[0][i] = (unsigned char)VEGA_CLAMP_U8(val); } break; } case VEGACSCONV_LINRGB_TO_SRGB: { // sRGB = (linRGB <= 0.00313008) ? linRGB * 12.92 : 1.055*linRGB^(1/2.4)-0.055 VEGA_FIX exp = VEGA_INTTOFIX(10) / 24; /* 1 / 2.4 */ for (unsigned int i = 0; i < 256; i++) { if (i == 0) // 1/255 ~= 0.0039 { lut[0][i] = 0; } else { VEGA_FIX norm_i = VEGA_INTTOFIX(i) / 255; VEGA_FIX corr = (VEGA_FIXPOW(norm_i, exp) * 1055 - VEGA_INTTOFIX(55)) / 1000; int val = VEGA_FIXTOINT(255 * corr); lut[0][i] = (unsigned char)VEGA_CLAMP_U8(val); } } break; } default: OP_ASSERT(0); break; } #ifdef VEGA_3DDEVICE xlat_table_needs_update = TRUE; csconv_type = type; #endif // VEGA_3DDEVICE } #ifdef VEGA_3DDEVICE OP_STATUS VEGAFilterColorTransform::getShader(VEGA3dDevice* device, VEGA3dShaderProgram** out_shader, VEGA3dTexture* srcTex) { VEGA3dShaderProgram::ShaderType shdtype; switch (transform_type) { default: case VEGACOLORTRANSFORM_MATRIX: shdtype = VEGA3dShaderProgram::SHADER_COLORMATRIX; break; case VEGACOLORTRANSFORM_LUMINANCETOALPHA: shdtype = VEGA3dShaderProgram::SHADER_LUMINANCE_TO_ALPHA; break; case VEGACOLORTRANSFORM_COMPONENTTRANSFER: shdtype = VEGA3dShaderProgram::SHADER_COMPONENTTRANSFER; break; case VEGACOLORTRANSFORM_COLORSPACECONV: if (csconv_type == VEGACSCONV_SRGB_TO_LINRGB) shdtype = VEGA3dShaderProgram::SHADER_SRGB_TO_LINEARRGB; else shdtype = VEGA3dShaderProgram::SHADER_LINEARRGB_TO_SRGB; break; } if (transform_type == VEGACOLORTRANSFORM_COMPONENTTRANSFER && !xlat_table) { // Allocate a 256x1 texture (or maybe a 256x4 lum. - or maybe // a 1D even?) and fill it from the relevant tables RETURN_IF_ERROR(device->createTexture(&xlat_table, 256, 4, VEGA3dTexture::FORMAT_ALPHA8)); xlat_table->setFilterMode(VEGA3dTexture::FILTER_NEAREST, VEGA3dTexture::FILTER_NEAREST); } VEGA3dShaderProgram* shader = NULL; RETURN_IF_ERROR(device->createShaderProgram(&shader, shdtype, VEGA3dShaderProgram::WRAP_CLAMP_CLAMP)); device->setShaderProgram(shader); switch (transform_type) { case VEGACOLORTRANSFORM_MATRIX: { int i, j; float mat[16]; for (i = 0; i < 4; ++i) for (j = 0; j < 4; ++j) mat[i*4+j] = VEGA_FIXTOFLT(matrix[i*5+j]); shader->setMatrix4(shader->getConstantLocation("colormat"), mat); for (i = 0; i < 4; ++i) mat[i] = VEGA_FIXTOFLT(matrix[i*5+4]); shader->setVector4(shader->getConstantLocation("colorbias"), mat); } break; case VEGACOLORTRANSFORM_COMPONENTTRANSFER: if (xlat_table_needs_update) { xlat_table->update(0, 0, 256, 1, lut[VEGACOMP_R]); xlat_table->update(0, 1, 256, 1, lut[VEGACOMP_G]); xlat_table->update(0, 2, 256, 1, lut[VEGACOMP_B]); xlat_table->update(0, 3, 256, 1, lut[VEGACOMP_A]); xlat_table_needs_update = FALSE; } device->setTexture(1, xlat_table); break; } device->setTexture(0, srcTex); *out_shader = shader; return OpStatus::OK; } void VEGAFilterColorTransform::putShader(VEGA3dDevice* device, VEGA3dShaderProgram* shader) { OP_ASSERT(device && shader); VEGARefCount::DecRef(shader); } OP_STATUS VEGAFilterColorTransform::apply(VEGABackingStore_FBO* destStore, const VEGAFilterRegion& region, unsigned int frame) { OP_STATUS status = applyShader(destStore, region, frame); if (OpStatus::IsError(status)) status = applyFallback(destStore, region); return status; } #endif // VEGA_3DDEVICE OP_STATUS VEGAFilterColorTransform::apply(const VEGASWBuffer& dest, const VEGAFilterRegion& region) { // Alpha conserving transform BOOL conservesAlpha = FALSE; unsigned int yp; VEGAConstPixelAccessor src = source.GetConstAccessor(region.sx, region.sy); VEGAPixelAccessor dst = dest.GetAccessor(region.dx, region.dy); unsigned int srcPixelStride = source.GetPixelStride(); unsigned int dstPixelStride = dest.GetPixelStride(); srcPixelStride -= region.width; dstPixelStride -= region.width; switch (transform_type) { case VEGACOLORTRANSFORM_MATRIX: /* alpha identity mapping (row 4 == [0 0 0 1 0]) */ if (matrix[15] == 0 && matrix[16] == 0 && matrix[17] == 0 && matrix[18] == 1 && matrix[19] == 0) conservesAlpha = TRUE; if (conservesAlpha) { VEGA_FIX m4_255 = matrix[4] * 255; VEGA_FIX m9_255 = matrix[9] * 255; VEGA_FIX m14_255 = matrix[14] * 255; for (yp = 0; yp < region.height; ++yp) { unsigned cnt = region.width; while (cnt-- > 0) { int sa, sr, sg, sb; src.LoadUnpack(sa, sr, sg, sb); VEGA_COND_UNPREMULT(sa, sr, sg, sb); // Apply matrix int dr = VEGA_FIXTOINT(sr * matrix[0] + sg * matrix[1] + sb * matrix[2] + sa * matrix[3] + m4_255); int dg = VEGA_FIXTOINT(sr * matrix[5] + sg * matrix[6] + sb * matrix[7] + sa * matrix[8] + m9_255); int db = VEGA_FIXTOINT(sr * matrix[10] + sg * matrix[11] + sb * matrix[12] + sa * matrix[13] + m14_255); // Clip color components dr = VEGA_CLAMP_U8(dr); dg = VEGA_CLAMP_U8(dg); db = VEGA_CLAMP_U8(db); VEGA_COND_PREMULT(sa, dr, dg, db); dst.StoreARGB(sa, dr, dg, db); ++src; ++dst; } src += srcPixelStride; dst += dstPixelStride; } } else { VEGA_FIX m4_255 = matrix[4] * 255; VEGA_FIX m9_255 = matrix[9] * 255; VEGA_FIX m14_255 = matrix[14] * 255; VEGA_FIX m19_255 = matrix[19] * 255; for (yp = 0; yp < region.height; ++yp) { unsigned cnt = region.width; while (cnt-- > 0) { int sa, sr, sg, sb; src.LoadUnpack(sa, sr, sg, sb); VEGA_COND_UNPREMULT(sa, sr, sg, sb); // Apply matrix int dr = VEGA_FIXTOINT(sr * matrix[0] + sg * matrix[1] + sb * matrix[2] + sa * matrix[3] + m4_255); int dg = VEGA_FIXTOINT(sr * matrix[5] + sg * matrix[6] + sb * matrix[7] + sa * matrix[8] + m9_255); int db = VEGA_FIXTOINT(sr * matrix[10] + sg * matrix[11] + sb * matrix[12] + sa * matrix[13] + m14_255); int da = VEGA_FIXTOINT(sr * matrix[15] + sg * matrix[16] + sb * matrix[17] + sa * matrix[18] + m19_255); // Clip color components dr = VEGA_CLAMP_U8(dr); dg = VEGA_CLAMP_U8(dg); db = VEGA_CLAMP_U8(db); da = VEGA_CLAMP_U8(da); VEGA_COND_PREMULT(da, dr, dg, db); dst.StoreARGB(da, dr, dg, db); ++src; ++dst; } src += srcPixelStride; dst += dstPixelStride; } } break; case VEGACOLORTRANSFORM_LUMINANCETOALPHA: for (yp = 0; yp < region.height; ++yp) { unsigned cnt = region.width; while (cnt-- > 0) { unsigned sa, sr, sg, sb; src.LoadUnpack(sa, sr, sg, sb); #ifdef USE_PREMULTIPLIED_ALPHA // Premultiplied sa = sa ? ((sr*108 + sg*365 + sb*37) / sa) >> 1 : 0; sa = sa > 255 ? 255 : sa; #else sa = (sr*54 + sg*183 + sb*18) >> 8; #endif // USE_PREMULTIPLIED_ALPHA dst.StoreARGB(sa, 0, 0, 0); ++src; ++dst; } src += srcPixelStride; dst += dstPixelStride; } break; case VEGACOLORTRANSFORM_COMPONENTTRANSFER: for (yp = 0; yp < region.height; ++yp) { unsigned cnt = region.width; while (cnt-- > 0) { unsigned da, dr, dg, db; src.LoadUnpack(da, dr, dg, db); VEGA_COND_UNPREMULT(da, dr, dg, db); da = lut[VEGACOMP_A][da]; dr = lut[VEGACOMP_R][dr&0xff]; dg = lut[VEGACOMP_G][dg&0xff]; db = lut[VEGACOMP_B][db&0xff]; VEGA_COND_PREMULT(da, dr, dg, db); dst.StoreARGB(da, dr, dg, db); ++src; ++dst; } src += srcPixelStride; dst += dstPixelStride; } break; case VEGACOLORTRANSFORM_COLORSPACECONV: for (yp = 0; yp < region.height; ++yp) { unsigned cnt = region.width; while (cnt-- > 0) { unsigned da, dr, dg, db; src.LoadUnpack(da, dr, dg, db); VEGA_COND_UNPREMULT(da, dr, dg, db); dr = lut[0][dr&0xff]; dg = lut[0][dg&0xff]; db = lut[0][db&0xff]; VEGA_COND_PREMULT(da, dr, dg, db); dst.StoreARGB(da, dr, dg, db); ++src; ++dst; } src += srcPixelStride; dst += dstPixelStride; } break; } return OpStatus::OK; } #undef VEGA_COND_PREMULT #undef VEGA_COND_UNPREMULT #undef VEGA_CLAMP_U8 #endif // VEGA_SUPPORT
#include<iostream> #include<cstdio> #include<map> #include<set> #include<vector> #include<stack> #include<queue> #include<string> #include<cstring> #include<sstream> #include<algorithm> #include<cmath> using namespace std; const int inf = 1e9 + 7; int f[100100]; struct Edge { int from,to,dist; }; bool cmp(Edge a,Edge b) { return a.dist < b.dist; } int find(int x) { if (f[x] != x) f[x] = find(f[x]); return f[x]; } Edge edge[100100]; int cost[100100]; int main() { int n,m; while (scanf("%d%d",&n,&m) != EOF) { long long ans = 0; for (int i = 1;i <= n; i++) { f[i] = i; scanf("%d",&cost[i]); ans += cost[i]; } for (int i = 0;i < m; i++) scanf("%d%d%d",&edge[i].from,&edge[i].to,&edge[i].dist); sort(edge,edge+m,cmp); int cou = 1; for (int i = 0;i < m && cou < n; i++) { int k1 = find(edge[i].from),k2 = find(edge[i].to),k; if (cost[k1] < cost[k2]) k = k2; else k = k1; if (k1 != k2 && cost[k] > edge[i].dist) { if (cost[k1] > cost[k2]) f[k] = k2; else f[k2] = k1; cou++; ans += edge[i].dist - cost[k]; } } printf("%lld\n",ans); } return 0; }
// Example 4.2 : Inheritance, overriding, polymorphism, virtual methods // Created by Oleksiy Grechnyev 2017 #include <iostream> #include <memory> #include "./Monster.h" #include "./Vampire.h" int main(){ using namespace std; { cout << "\nMonster demo : \n\n"; Monster g("Grshnak", "Goblin", 9); cout << "Calling g.action()\n"; g.action(); cout << "Calling g.printMe()\n"; g.printMe(); } { cout << "\nVampire demo : \n\n"; Vampire v("Hans", 789); cout << "Calling v.action()\n"; v.action(); cout << "Calling v.printMe()\n"; v.printMe(); cout << "Calling v.Monster::printMe()\n"; v.Monster::printMe(); cout << "Calling v.sayHi()\n"; v.sayHi(); cout << "Calling v.sayBye()\n"; v.sayBye(); } { cout << "\nPolymorphism and virtual demo : \n\n"; Vampire v("Lucius", 1234); // Reference polymorphism Person & p = v; // Person & ref to v, polymorphism ! cout << "Calling p.sayHi()\n"; p.sayHi(); // virtual, Vampire::setHi() is called ! cout << "Calling p.sayBye() : not virtual !!! \n"; p.sayBye(); // non-virtual, Person::setHi() is called ! // Pointer polymorphism Monster * m = &v; // Person & pointer to v, polymorphism ! cout << "Calling m->action()\n"; // virtual, Monster::action() is called ! m->action(); cout << "Calling m->printMe()\n"; // virtual, Monster::printMe() is called ! m->printMe(); } return 0; }
#include "node_robot_2.h" Robot_2::Robot_2() { robot_id = 2; robot_state = "ready"; work_task_id = 0; robot_2_info_client = m_handle.serviceClient<node_robot_msgs::robot_info_report>("robot_info"); agent_task_2_server = m_handle.advertiseService("agent_task_2",&Robot_2::server_deal,this); run(); } Robot_2::~Robot_2() { } bool Robot_2::server_deal(node_robot_msgs::agent_task_2::Request &req,node_robot_msgs::agent_task_2::Response &res) { //cout<<"++++++++++++task id is"<<req.task_id<<endl; if(req.task_id != 0){ robot_state = "executing"; work_task_id = req.task_id; } res.ret = true; return true; } void Robot_2::run() { bool start_flag = false; ros::Rate loop(50); while(ros::ok()){ if(robot_state == "executing"){ if(start_flag == false){ last_time = ros::Time::now(); start_flag = true; } if((current_time - last_time).toSec() >= 3){ robot_state = "ready"; start_flag = false; //cout<<"heehehehehehehehehehehehehehehe"<<endl; } current_time = ros::Time::now(); //cout<<">><<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<"<<(current_time - last_time).toSec()<<endl; } robot_2_srv.request.robot_id = robot_id; robot_2_srv.request.robot_state = robot_state; robot_2_srv.request.working_task_id = work_task_id; robot_2_info_client.call(robot_2_srv); ros::spinOnce(); loop.sleep(); } } int main(int argc ,char**argv) { ros::init(argc,argv,"robot_2"); Robot_2 robot_2; ros::spin(); }
#include<iostream> #include<cstdio> #include<map> #include<set> #include<vector> #include<stack> #include<queue> #include<string> #include<cstring> #include<sstream> #include<algorithm> #include<cmath> using namespace std; bool vis[1010]; int main() { int n,m,k; scanf("%d",&n); scanf("%d",&m); for (int i = 0;i < m; i++) { scanf("%d",&k); vis[k] = true; } scanf("%d",&m); for (int i = 0;i < m; i++) { scanf("%d",&k); vis[k] = true; } bool ans = true; for (int i = 1;i <= n; i++) if (!vis[i]) { ans = false; break; } if (ans) printf("I become the guy.\n"); else printf("Oh, my keyboard!\n"); return 0; }
#include "cmdline.h" #include "io_data.h" int main(int argc, char* argv[]) { //set parameters cmdline::parser cmd; cmd.add<double>("eta", '\0', "noise strength", true); cmd.add<double>("eps", '\0', "disorder strength", false, 0); cmd.add<double>("Lx", 'L', "system length in x direction", true); cmd.add<double>("Ly", '\0', "system length in y direction", false); cmd.add<double>("rho0", '\0', "particle density", false, 1); cmd.add<double>("v0", '\0', "fixed velocity", false, 0.5); cmd.add<int>("nstep", 'n', "total steps to run", true); cmd.add<double>("dt", '\0', "time interval between two steps", false, 1); cmd.add<double>("ext_torque", '\0', "extra torque", false, 0); cmd.add<unsigned long long int>( "seed", 's', "seed of random number", false, 1); cmd.add<double>("defect_sep", '\0', "separation between two defects", false, 0); cmd.add<int>("defect_mode", '\0', "defect mode", false, 0); cmd.add<int>("log_dt", '\0', "step interval to record log", false, 1000); // coarse-grained snapshots cmd.add("cg_on", '\0', "output coarse-grained snapshots"); cmd.add<double>("cg_l", '\0', "boxes size for coarse graining", false, 1); cmd.add<int>("cg_dt", '\0', "step interval to output snapshot", false, 10000); // whether to use vectorial noise cmd.add("vec_noise", '\0', "use vectorial noise"); // is metric-free cmd.add("metric_free", '\0', "is metric-free?"); cmd.parse_check(argc, argv); Ran myran(cmd.get<unsigned long long>("seed")); VM *birds = NULL; if (cmd.exist("metric_free")) { if (cmd.exist("dt")) { birds = new VM_metric_free<V_conti>(cmd, myran); std::cout << "Continous step, dt = " << cmd.get<double>("dt") << "\n"; } else if (cmd.exist("vec_noise")) { birds = new VM_metric_free<V_vectorial>(cmd, myran); std::cout << "Vectorial Noise, dt = " << cmd.get<double>("dt") << "\n"; } else { birds = new VM_metric_free<V_scalar>(cmd, myran); std::cout << "Scalar Noise, dt = " << cmd.get<double>("dt") << "\n"; } } else { if (cmd.exist("dt")) { birds = new VM_metric<V_conti>(cmd, myran); std::cout << "Continous step, dt = " << cmd.get<double>("dt") << "\n"; } else if (cmd.exist("vec_noise")) { birds = new VM_metric<V_vectorial>(cmd, myran); std::cout << "Vectorial Noise, dt = " << cmd.get<double>("dt") << "\n"; } else { birds = new VM_metric<V_scalar>(cmd, myran); std::cout << "Scalar Noise, dt = " << cmd.get<double>("dt") << "\n"; } } ini_output(cmd, birds); int n = cmd.get<int>("nstep"); double dt = cmd.get<double>("dt"); for (int i = 1; i <= n; i++) { birds->align(); birds->stream(dt, myran); output(i, birds); } delete birds; }
#pragma once #ifndef _VECTOR_H #define _VECTOR_H #include "init.h" #include "math.h" class Vector { public: Vector(); Vector(float x, float y, float z); Vector(const Vector& vec); //void set(float x, float y, float z); //void set(Vector& vec); void normalize(); float dot(Vector b); float length(); float distance(Vector &b); Vector cross(Vector b); Vector operator- () const; friend Vector operator+ (const Vector& a, const Vector& b); friend Vector operator- (const Vector& a, const Vector& b); friend Vector operator* (const Vector& a, float f); friend Vector operator* (float f, const Vector& a); friend Vector operator* (const Vector& a, const Vector& b); friend bool operator== (const Vector& a, const Vector& b); float x, y, z; }; typedef Vector Color; #endif // !_VECTOR_H
/* * Copyright 2016 Freeman Zhang <zhanggyb@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef SKLAND_GUI_ABSTRACT_LAYOUT_HPP_ #define SKLAND_GUI_ABSTRACT_LAYOUT_HPP_ #include "abstract-view.hpp" #include "../core/padding.hpp" namespace skland { SKLAND_EXPORT class AbstractLayout : public AbstractView { AbstractLayout(const AbstractLayout &) = delete; AbstractLayout &operator=(const AbstractLayout &) = delete; public: AbstractLayout(const Padding &padding = Padding(5)); virtual ~AbstractLayout(); virtual Size GetMinimalSize() const override; virtual Size GetPreferredSize() const override; virtual Size GetMaximalSize() const override; void AddView(AbstractView *view); void RemoveView(AbstractView *view); const Padding &padding() const { return padding_; } protected: virtual void OnViewAdded(AbstractView *view) = 0; virtual void OnViewDestroyed(AbstractView *view) = 0; virtual void OnMouseEnter(MouseEvent *event) final; virtual void OnMouseLeave(MouseEvent *event) final; virtual void OnMouseMove(MouseEvent *event) final; virtual void OnMouseButton(MouseEvent *event) final; virtual void OnKeyboardKey(KeyEvent *event) final; virtual void OnDraw(const Context *context) final; private: Padding padding_; }; } #endif // SKLAND_GUI_ABSTRACT_LAYOUT_HPP_
// CommandLineOptions.h #ifndef SIMPLE_COMMAND_LINE_OPTIONS_H #define SIMPLE_COMMAND_LINE_OPTIONS_H #include <string> #include <map> #include <set> #include <vector> #include <stdexcept> namespace simple { class CommandLineOptions { public : class ParseException; public : explicit CommandLineOptions( const std::string& nameSign ); CommandLineOptions(const CommandLineOptions& ); CommandLineOptions( const CommandLineOptions&& ) noexcept; CommandLineOptions& operator =( const CommandLineOptions& ) = delete; virtual ~CommandLineOptions() = default; std::string get( const std::string& key ) const; std::string get( const std::string& key, const std::string& defaultValue ) const; std::string getExecutableName() const; bool has( const std::string& key ) const; bool isEmpty() const; void parse( int argc, char* argv[] ); void addKey( const std::string& key ); private : bool isKey( const std::string& token ) const; void checkIfKeyAllowed( const std::string& key ) const; static bool isStartWith( const std::string& data, const std::string& start ); private : typedef std::map< std::string, std::string > OptionsMap; typedef std::set< std::string > KeysSet; KeysSet keys_; OptionsMap options_; std::string executableName_; const std::string keySign_; }; class CommandLineOptions::ParseException : public std::logic_error { public : explicit ParseException( const std::string& message ) : logic_error( message ) { } virtual ~ParseException() noexcept = default; }; } // simple #endif // SIMPLE_COMMAND_LINE_OPTIONS_H
// Copyright (c) 2007-2017 Hartmut Kaiser // Copyright (c) 2013 Agustin Berge // // SPDX-License-Identifier: BSL-1.0 // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #pragma once #include <pika/config.hpp> #include <pika/futures/traits/future_traits.hpp> #include <pika/futures/traits/is_future.hpp> #include <pika/type_support/lazy_conditional.hpp> #include <pika/type_support/type_identity.hpp> #include <type_traits> #include <utility> namespace pika::traits { /////////////////////////////////////////////////////////////////////////// namespace detail { struct no_executor { }; } // namespace detail /////////////////////////////////////////////////////////////////////////// namespace detail { template <typename Future, typename F> struct continuation_not_callable { static auto error(Future future, F& f) { f(PIKA_MOVE(future)); } using type = decltype(error(std::declval<Future>(), std::declval<F&>())); }; /////////////////////////////////////////////////////////////////////// template <typename Future, typename F, typename Enable = void> struct future_then_result { using type = typename continuation_not_callable<Future, F>::type; }; template <typename Future, typename F> struct future_then_result<Future, F, std::void_t<std::invoke_result_t<F&, Future>>> { using cont_result = std::invoke_result_t<F&, Future>; // perform unwrapping of future<future<R>> using result_type = ::pika::detail::lazy_conditional_t< pika::traits::detail::is_unique_future<cont_result>::value, pika::traits::future_traits<cont_result>, pika::detail::type_identity<cont_result>>; using type = pika::future<result_type>; }; } // namespace detail /////////////////////////////////////////////////////////////////////////// template <typename Future, typename F> struct future_then_result : detail::future_then_result<Future, F> { }; template <typename Future, typename F> using future_then_result_t = typename future_then_result<Future, F>::type; } // namespace pika::traits
#include "2-1.h" int main() { int no, count; cin >> no; cin >> count; class Sum A(no, count); cout << A.result(); return 0; } /* #include <iostream> using namespace std; class Sum { private: int a, b; public: Sum(int no, int count) { a = no; b = count; } int result() { return a + b; } }; int sum(int a, int b) { return a + b; } */
/* TouchKeys: multi-touch musical keyboard control software Copyright (c) 2013 Andrew McPherson 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 GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ===================================================================== TouchkeyPitchBendMappingFactory.cpp: factory for the pitch-bend mapping, which handles changing pitch based on relative finger motion. */ #include "TouchkeyPitchBendMappingFactory.h" // Default constructor, containing a reference to the PianoKeyboard class. TouchkeyPitchBendMappingFactory::TouchkeyPitchBendMappingFactory(PianoKeyboard &keyboard, MidiKeyboardSegment& segment) : TouchkeyBaseMappingFactory<TouchkeyPitchBendMapping>(keyboard, segment), bendRangeSemitones_(TouchkeyPitchBendMapping::kDefaultBendRangeSemitones), bendThresholdSemitones_(TouchkeyPitchBendMapping::kDefaultBendThresholdSemitones), bendThresholdKeyLength_(TouchkeyPitchBendMapping::kDefaultBendThresholdKeyLength), bendMode_(TouchkeyPitchBendMapping::kDefaultPitchBendMode), fixedModeMinEnableDistance_(TouchkeyPitchBendMapping::kDefaultFixedModeEnableDistance), fixedModeBufferDistance_(TouchkeyPitchBendMapping::kDefaultFixedModeBufferDistance), bendIgnoresTwoFingers_(TouchkeyPitchBendMapping::kDefaultIgnoresTwoFingers), bendIgnoresThreeFingers_(TouchkeyPitchBendMapping::kDefaultIgnoresThreeFingers) { // Set up the MIDI converter to use pitch wheel // setName("/pitchbend"); setBendParameters(); } // ***** Destructor ***** TouchkeyPitchBendMappingFactory::~TouchkeyPitchBendMappingFactory() { } // ***** Accessors / Modifiers ***** void TouchkeyPitchBendMappingFactory::setName(const string& name) { TouchkeyBaseMappingFactory<TouchkeyPitchBendMapping>::setName(name); setBendParameters(); } // ***** Bend Methods ***** void TouchkeyPitchBendMappingFactory::setBendRange(float rangeSemitones, bool updateCurrent) { /*if(updateCurrent) { // Send new range to all active mappings // TODO: mutex protect std::map<int, mapping_pair>::iterator it = mappings_.begin(); while(it != mappings_.end()) { // Tell this mapping to update its range TouchkeyPitchBendMapping *mapping = it->second.second; mapping->setRange(rangeSemitones); it++; } }*/ bendRangeSemitones_ = rangeSemitones; } void TouchkeyPitchBendMappingFactory::setBendThresholdSemitones(float thresholdSemitones) { bendThresholdSemitones_ = thresholdSemitones; } void TouchkeyPitchBendMappingFactory::setBendThresholdKeyLength(float thresholdKeyLength) { bendThresholdKeyLength_ = thresholdKeyLength; } void TouchkeyPitchBendMappingFactory::setBendThresholds(float thresholdSemitones, float thresholdKeyLength, bool updateCurrent) { /*if(updateCurrent) { // Send new range to all active mappings // TODO: mutex protect std::map<int, mapping_pair>::iterator it = mappings_.begin(); while(it != mappings_.end()) { // Tell this mapping to update its range TouchkeyPitchBendMapping *mapping = it->second.second; mapping->setThresholds(thresholdSemitones, thresholdKeyLength); it++; } }*/ bendThresholdSemitones_ = thresholdSemitones; bendThresholdKeyLength_ = thresholdKeyLength; } // Set the mode to bend a fixed amount up and down the key, regardless of where // the touch starts. minimumDistanceToEnable sets a floor below which the bend isn't // possible (for starting very close to an edge) and bufferAtEnd sets the amount // of key length beyond which no further bend takes place. void TouchkeyPitchBendMappingFactory::setBendFixedEndpoints(float minimumDistanceToEnable, float bufferAtEnd) { bendMode_ = TouchkeyPitchBendMapping::kPitchBendModeFixedEndpoints; fixedModeMinEnableDistance_ = minimumDistanceToEnable; fixedModeBufferDistance_ = bufferAtEnd; } // Set the mode to bend an amount proportional to distance, which means // that the total range of bend will depend on where the finger started. void TouchkeyPitchBendMappingFactory::setBendVariableEndpoints() { bendMode_ = TouchkeyPitchBendMapping::kPitchBendModeVariableEndpoints; } void TouchkeyPitchBendMappingFactory::setBendIgnoresMultipleFingers(bool ignoresTwo, bool ignoresThree) { // TODO: update current bendIgnoresTwoFingers_ = ignoresTwo; bendIgnoresThreeFingers_ = ignoresThree; } #ifndef TOUCHKEYS_NO_GUI // ***** GUI Support ***** MappingEditorComponent* TouchkeyPitchBendMappingFactory::createBasicEditor() { return new TouchkeyPitchBendMappingShortEditor(*this); } #endif // ****** OSC Control Support ****** OscMessage* TouchkeyPitchBendMappingFactory::oscControlMethod(const char *path, const char *types, int numValues, lo_arg **values, void *data) { if(!strcmp(path, "/set-bend-range")) { // Change the range of the pitch bend in semitones if(numValues > 0) { if(types[0] == 'f') { setBendRange(values[0]->f); return OscTransmitter::createSuccessMessage(); } } } else if(!strcmp(path, "/set-bend-threshold")) { // Change the threshold to activate the pitch bend [in semitones] if(numValues > 0) { if(types[0] == 'f') { setBendThresholdSemitones(values[0]->f); return OscTransmitter::createSuccessMessage(); } } } else if(!strcmp(path, "/set-bend-fixed-endpoints")) { // Enable fixed endpoints on the pitch bend if(numValues > 0) { if(types[0] == 'f') { float fixedEndpointBufferAtEnd = 0; if(numValues >= 2) { if(types[1] == 'f') { fixedEndpointBufferAtEnd = values[1]->f; } } setBendFixedEndpoints(values[0]->f, fixedEndpointBufferAtEnd); return OscTransmitter::createSuccessMessage(); } } } else if(!strcmp(path, "/set-bend-variable-endpoints")) { // Enable variable endpoints on the pitch bend setBendVariableEndpoints(); return OscTransmitter::createSuccessMessage(); } else if(!strcmp(path, "/set-bend-ignores-multiple-fingers")) { // Change whether the bend ignores two or three fingers if(numValues >= 2) { if(types[0] == 'i' && types[1] == 'i') { setBendIgnoresMultipleFingers(values[0]->i, values[1]->i); return OscTransmitter::createSuccessMessage(); } } } // If no match, check the base class return TouchkeyBaseMappingFactory<TouchkeyPitchBendMapping>::oscControlMethod(path, types, numValues, values, data); } // TODO: ****** Preset Save/Load ****** XmlElement* TouchkeyPitchBendMappingFactory::getPreset() { PropertySet properties; storeCommonProperties(properties); properties.setValue("bendRangeSemitones", bendRangeSemitones_); properties.setValue("bendThresholdSemitones", bendThresholdSemitones_); properties.setValue("bendThresholdKeyLength", bendThresholdKeyLength_); properties.setValue("bendMode", bendMode_); properties.setValue("fixedModeMinEnableDistance", fixedModeMinEnableDistance_); properties.setValue("fixedModeBufferDistance", fixedModeBufferDistance_); properties.setValue("bendIgnoresTwoFingers", bendIgnoresTwoFingers_); properties.setValue("bendIgnoresThreeFingers", bendIgnoresThreeFingers_); XmlElement* preset = properties.createXml("MappingFactory"); preset->setAttribute("type", "PitchBend"); return preset; } bool TouchkeyPitchBendMappingFactory::loadPreset(XmlElement const* preset) { if(preset == 0) return false; PropertySet properties; properties.restoreFromXml(*preset); if(!loadCommonProperties(properties)) return false; if(!properties.containsKey("bendRangeSemitones") || !properties.containsKey("bendThresholdSemitones") || !properties.containsKey("bendThresholdKeyLength") || !properties.containsKey("bendMode") || !properties.containsKey("fixedModeMinEnableDistance") || !properties.containsKey("fixedModeBufferDistance") || !properties.containsKey("bendIgnoresTwoFingers") || !properties.containsKey("bendIgnoresThreeFingers")) return false; bendRangeSemitones_ = properties.getDoubleValue("bendRangeSemitones"); bendThresholdSemitones_ = properties.getDoubleValue("bendThresholdSemitones"); bendThresholdKeyLength_ = properties.getDoubleValue("bendThresholdKeyLength"); bendMode_ = properties.getIntValue("bendMode"); fixedModeMinEnableDistance_ = properties.getDoubleValue("fixedModeMinEnableDistance"); fixedModeBufferDistance_ = properties.getDoubleValue("fixedModeBufferDistance"); bendIgnoresTwoFingers_ = properties.getBoolValue("bendIgnoresTwoFingers"); bendIgnoresThreeFingers_ = properties.getBoolValue("bendIgnoresThreeFingers"); // Update MIDI information setBendParameters(); return true; } // ***** Private Methods ***** // Set the initial parameters for a new mapping void TouchkeyPitchBendMappingFactory::initializeMappingParameters(int noteNumber, TouchkeyPitchBendMapping *mapping) { mapping->setRange(bendRangeSemitones_); mapping->setThresholds(bendThresholdSemitones_, bendThresholdKeyLength_); if(bendMode_ == TouchkeyPitchBendMapping::kPitchBendModeFixedEndpoints) { mapping->setFixedEndpoints(fixedModeMinEnableDistance_, fixedModeBufferDistance_); } else mapping->setVariableEndpoints(); mapping->setIgnoresMultipleFingers(bendIgnoresTwoFingers_, bendIgnoresThreeFingers_); } void TouchkeyPitchBendMappingFactory::setBendParameters() { // Range of 0 indicates special case of using global pitch wheel range setMidiParameters(MidiKeyboardSegment::kControlPitchWheel, 0.0, 0.0, 0.0); if(midiConverter_ != 0) { midiConverter_->listenToIncomingControl(MidiKeyboardSegment::kControlPitchWheel); } }
// Copyright (c) 2022 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _TopoDSToStep_MakeTessellatedItem_HeaderFile #define _TopoDSToStep_MakeTessellatedItem_HeaderFile #include <Standard.hxx> #include <Standard_DefineAlloc.hxx> #include <Standard_Handle.hxx> #include <TopoDSToStep_Root.hxx> #include <Message_ProgressRange.hxx> class StepVisual_TessellatedItem; class TopoDS_Face; class TopoDS_Shell; class Transfer_FinderProcess; //! This class implements the mapping between //! Face, Shell fromTopoDS and TriangulatedFace from StepVisual. class TopoDSToStep_MakeTessellatedItem : public TopoDSToStep_Root { public: DEFINE_STANDARD_ALLOC Standard_EXPORT TopoDSToStep_MakeTessellatedItem(); Standard_EXPORT TopoDSToStep_MakeTessellatedItem(const TopoDS_Face& theFace, TopoDSToStep_Tool& theTool, const Handle(Transfer_FinderProcess)& theFP, const Message_ProgressRange& theProgress = Message_ProgressRange()); Standard_EXPORT TopoDSToStep_MakeTessellatedItem(const TopoDS_Shell& theShell, TopoDSToStep_Tool& theTool, const Handle(Transfer_FinderProcess)& theFP, const Message_ProgressRange& theProgress = Message_ProgressRange()); Standard_EXPORT void Init(const TopoDS_Face& theFace, TopoDSToStep_Tool& theTool, const Handle(Transfer_FinderProcess)& theFP, const Message_ProgressRange& theProgress = Message_ProgressRange()); Standard_EXPORT void Init(const TopoDS_Shell& theShell, TopoDSToStep_Tool& theTool, const Handle(Transfer_FinderProcess)& theFP, const Message_ProgressRange& theProgress = Message_ProgressRange()); Standard_EXPORT const Handle(StepVisual_TessellatedItem)& Value() const; protected: private: Handle(StepVisual_TessellatedItem) theTessellatedItem; }; #endif // _TopoDSToStep_MakeTessellatedItem_HeaderFile
#ifndef math_util_h #define math_util_h #include "util.hpp" #include "linalg_util.hpp" #include <algorithm> namespace avl { inline float to_radians(float degrees) { return degrees * float(ANVIL_PI) / 180.0f; } inline float to_degrees(float radians) { return radians * 180.0f / float(ANVIL_PI); } template<typename T> T min(const T& x, const T& y) { return ((x) < (y) ? (x) : (y)); } template<typename T> T max(const T& x, const T& y) { return ((x) > (y) ? (x) : (y)); } template <typename T> T min(const T& a, const T& b, const T& c) { return std::min(a, std::min(b, c)); } template <typename T> T max(const T& a, const T& b, const T& c) { return std::max(a, std::max(b, c)); } template<typename T> T clamp(const T& val, const T& min, const T& max) { return std::min(std::max(val, min), max); } template<typename T> T sign(const T& a, const T& b) { return ((b) >= 0.0 ? std::abs(a) : -std::abs(a)); } template<typename T> T sign(const T& a) { return (a == 0) ? T(0) : ((a > 0.0) ? T(1) : T(-1)); } inline float normalize(float value, float min, float max) { return clamp<float>((value - min) / (max - min), 0.0f, 1.0f); } template <typename T> inline bool in_range(T val, T min, T max) { return (val >= min && val <= max); } template <typename T> inline T remap(T value, T inputMin, T inputMax, T outputMin, T outputMax, bool clamp) { T outVal = ((value - inputMin) / (inputMax - inputMin) * (outputMax - outputMin) + outputMin); if (clamp) { if (outputMax < outputMin) { if (outVal < outputMax) outVal = outputMax; else if (outVal > outputMin) outVal = outputMin; } else { if (outVal > outputMax) outVal = outputMax; else if (outVal < outputMin) outVal = outputMin; } } return outVal; } // In radians inline float3 spherical(float theta, float phi) { return safe_normalize(float3(cos(phi) * sin(theta), sin(phi) * sin(theta), cos(theta))); } template <typename T> bool quadratic(T a, T b, T c, T & r1, T & r2) { T q = b * b - 4 * a * c; if (q < 0) return false; T sq = sqrt(q); T d = 1 / (2 * a); r1 = (-b + sq) * d; r2 = (-b - sq) * d; return true; } inline float damped_spring(float target, float current, float & velocity, float delta, const float spring_constant) { float currentToTarget = target - current; float springForce = currentToTarget * spring_constant; float dampingForce = -velocity * 2 * sqrt(spring_constant); float force = springForce + dampingForce; velocity += force * delta; float displacement = velocity * delta; return current + displacement; } } #endif // end math_util_h
#include "condmentdecorator.h" CondmentDecorator::CondmentDecorator(Beverage *b) { this->beverage = b; }
#include <memory> #include <vector> #include <rend/rend.h> #include <string> class Shader; class MaterialAttribute; class Texture; //! The Material class. The class that controlls what your Mesh looks like. /*! This class is used to set the look of your 3D objects. This class uses a Shader and a Texture to calculate what your pbject will look like. Depending on the shader you choose to use you may not need a texture, but a shader will always be required. Example.. shared<Material> material = std::make_shared<Material>(); */ class Material { public: //!This sets the Shader for the Material. /*! This function is used to set the Shader your Material. The shader you use will change the way your object is shadeded and other features. Please make sure that a Shader is set before you call Core->Start(); */ void SetShader(std::shared_ptr<Shader> _shader); //!This sets the Textue for the Renderer. /*! This function is used to set the Texture for the object. Pass the chosen Texture as a shared pointer into the function. You can change the Texture at any time in code, but make sure that a Texture is set before you call Core->Start();. Not all shaders requires a Texture so please make sure you are using the correct shader as you may get an error if you try and pass a Texture in a Shader that does not use one. Same vise versa. */ void SetTexture(std::shared_ptr<Texture>); //!This gets the Shader the Material is using. /*! This function is used to get the Shader the Material is using. This is mainly used for rendering purposes. */ std::shared_ptr<rend::Shader> GetShader(); //!This gets the Texture the Material is using. /*! This function is used to get the Texture the Material is using. This is mainly used for rendering purposes. */ std::shared_ptr<Texture> GetTexture(); //!This sets a Uniform with a float value. /*! This function is used to set a Uniform in the shader, The string paramater, _variable, is the Name of the Uniform, and the float paramater, _value, is the value you wish to set it to. This is mainly used for rendering purposes. */ void setUniform(const std::string& _variable, float _value); //!This sets a Uniform with a mat4 value. /*! This function is used to set a Uniform in the shader, The string paramater, _variable, is the Name of the Uniform, and the float paramater, _value, is the value you wish to set it to. This is mainly used for rendering purposes. */ void setUniform(const std::string& _variable, glm::mat4 _value); //!This sets a Uniform with a vec2 value. /*! This function is used to set a Uniform in the shader, The string paramater, _variable, is the Name of the Uniform, and the float paramater, _value, is the value you wish to set it to. This is mainly used for rendering purposes. */ void setUniform(const std::string& _variable, glm::vec2 _value); //!This sets a Uniform with a vec3 value. /*! This function is used to set a Uniform in the shader, The string paramater, _variable, is the Name of the Uniform, and the float paramater, _value, is the value you wish to set it to. This is mainly used for rendering purposes. */ void setUniform(const std::string& _variable, glm::vec3 _value); //!This sets a Uniform with a vec4 value. /*! This function is used to set a Uniform in the shader, The string paramater, _variable, is the Name of the Uniform, and the float paramater, _value, is the value you wish to set it to. This is mainly used for rendering purposes. */ void setUniform(const std::string& _variable, glm::vec4 _value); //!This checks if the Shader requries Lights /*! This function returns a bool to check if the Shader needs any information about any Lights in the scene. This is mainly used for rendering purposes. */ bool UsesLights(); private: std::shared_ptr<Shader> shader; std::shared_ptr<Texture> texture; std::vector<std::shared_ptr<MaterialAttribute>> attributes; };
#include "afficherclient.h". #include "ui_afficherfinance.h" #include <QPalette> #include <QDesktopWidget> #include <QtGui> #include"menuprincipale.h" #include"menuprincipale.h" afficherclient::afficherclient(QWidget *parent) : QDialog(parent), ui(new Ui::afficherfinance) { ui->setupUi(this); QPalette p = palette(); //Load image to QPixmap, Give full path of image QPixmap pixmap1("C:/Users/ASUS/Desktop/projet/coevercoaching.jpg"); //For emulator C: is ..\epoc32\winscw\c so image must be at that location //resize image if it is larger than screen size. QDesktopWidget* desktopWidget = QApplication::desktop(); QRect rect = desktopWidget->availableGeometry(); QSize size(rect.width() , rect.height()); //resize as per your requirement.. QPixmap pixmap(pixmap1.scaled(640,480)); p.setBrush(QPalette::Background, pixmap); setPalette(p); ui->personneView->hide(); ui->transfertView->hide(); } afficherclient::~afficherclient() { delete ui; } void afficherclient::on_pecedentPB_clicked() { menuprincipale * dlg = new menuprincipale (); dlg->show(); this->hide(); } void afficherclient::on_afficherclientPB_clicked() { ui->personneView->setModel(tmpcp.AfficherClientele()); ui->personneView->show(); ui->transfertView->hide(); } void afficherfinance::on_affichertransfertPB_clicked() { ui->transfertView->setModel(tmCp.AfficherTransfert()); ui->transfertView->show(); ui->personneView->hide(); }
#pragma once #include "DAOImpl.h" // fa::MySQLPersonDAO #include "GlobalHeader.h" // fa::String #include <utility> // std::move #include <mylibs/detail/meta_functions.hpp> // pl::value_type namespace fa { //! delegates to a concrete PersonDAO such as MySQLPersonDAO template <class TargetPersonDAO> class PersonDAODelegator final { public: using this_type = PersonDAODelegator; using value_type = TargetPersonDAO; using dao_type = pl::value_type<value_type>; template <class ...Args> explicit PersonDAODelegator(Args &&...args) : val_{ std::forward<Args>(args)... } { } auto insertPerson(dao_type &person) const -> decltype(auto) { return val_.insertPerson(person); } auto deletePerson(dao_type &person) const -> decltype(auto) { return val_.deletePerson(person); } auto findPerson(String &name) const -> decltype(auto) { return val_.findPerson(name); } auto updatePerson(dao_type &person) const -> decltype(auto) { return val_.updatePerson(person); } private: value_type val_; }; // END of class PersonDAODelegator using PersonDAO = PersonDAODelegator<MySQLPersonDAO>; template <class TargetFoodDAO> class FoodDAODelegator final { public: using this_type = FoodDAODelegator; using value_type = TargetFoodDAO; using dao_type = pl::value_type<value_type>; template <class ...Args> explicit FoodDAODelegator(Args &&...args) : val_{ std::forward<Args>(args)... } { } auto findFood(String food) const -> decltype(auto) { return val_.findFood(std::move(food)); } private: value_type val_; }; // END of class FoodDAODelegator using FoodDAO = FoodDAODelegator<MySQLFoodDAO>; template <class TargetNoteDAO> class NoteDAODelegator final { public: using this_type = NoteDAODelegator; using value_type = TargetNoteDAO; using dao_type = pl::value_type<value_type>; template <class ...Args> explicit NoteDAODelegator(Args &&...args) : val_{ std::forward<Args>(args)... } { } auto findNote(dao_type note) const -> decltype(auto) { return val_.findNote(std::move(note)); } auto insertNote(dao_type note) const -> decltype(auto){ return val_.insertNote(std::move(note)); } auto deleteNote(dao_type note) const -> decltype(auto) { return val_.deletetNote(std::move(note)); } auto updateNote(dao_type note) const -> decltype(auto) { return val_.updateNote(std::move(note)); } private: value_type val_; }; // END of class NoteDAODelegator using NoteDAO = NoteDAODelegator<MySQLNoteDAO>; } // END of namespace fa
// stdafx.cpp : source file that includes just the standard includes // JPEGView.pch will be the pre-compiled header // stdafx.obj will contain the pre-compiled type information #include "stdafx.h" #if (_ATL_VER < 0x0700) #include <atlimpl.cpp> #endif //(_ATL_VER < 0x0700) #if defined(_MSC_VER) && (_MSC_VER >= 1900) FILE _iob[] = { *stdin, *stdout, *stderr }; extern "C" FILE * __cdecl __iob_func(void) { return _iob; } #endif
// Copyright (c) 2019, tlblanc <tlblanc1490 at gmail dot com> #ifndef IO_FLUSHERWRITER_H_ #define IO_FLUSHERWRITER_H_ #include <stddef.h> #include "writer.hpp" #include "flusher.hpp" class FlusherWriter : public Writer, public Flusher { public: FlusherWriter() = default; virtual ~FlusherWriter() = default; }; #endif // IO_FLUSHERWRITER_H_
#include "aeGOFactory.h" namespace aeEngineSDK { aeGOFactory::aeGOFactory() { } aeGOFactory::~aeGOFactory() { } aeGOFactory::aeGOFactory(const aeGOFactory &) { } aeGOFactory & aeGOFactory::operator=(const aeGOFactory &) { return *this; } void aeGOFactory::OnStartUp() { } void aeGOFactory::OnShutDown() { } }
// // Created by 钟奇龙 on 2019-05-16. // #include <iostream> #include <vector> #include <map> using namespace std; int getMaxLength(vector<int> arr,int target){ if(arr.size() == 0){ return 0; } int sum = 0; map<int,int> m; m[0] = -1; int maxLength = 0; for(int i=0; i<arr.size(); ++i){ sum += arr[i]; if(m.find(sum - target) != m.end()){ maxLength = max(maxLength,i-m[sum-target]); } if(m.find(sum) == m.end()){ m[sum] = i; } } return maxLength; } int main(){ cout<<getMaxLength({-8,-4,-3,0,1,2,2,8,9},10)<<endl; // cout<<getMaxLength({1,2,3,3},6)<<endl; return 0; }
#include <iostream> #include <algorithm> using namespace std; int main(void) { ios::sync_with_stdio(false); cout.tie(NULL); cin.tie(NULL); int n, start, end, count = 0; int series[2001]; cin >> n; for (int i = 0; i < n; i++) cin >> series[i]; sort(series, series + n); for (int i = 0; i < n; i++) { start = 0; end = n - 1; while (start < end) { if (series[start] + series[end] == series[i]) { if (start != i && end != i) { count++; break; } else if (start == i) start++; else if (end == i) end--; } else if (series[start] + series[end] < series[i]) start++; else end--; } } cout << count; return 0; }
// -*- Mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- // // Copyright (C) Opera Software AS. All rights reserved. // // This file is part of the Opera web browser. It may not be distributed // under any circumstances. #ifndef WEBFEEDUTIL_H_ #define WEBFEEDUTIL_H_ #ifdef WEBFEEDS_BACKEND_SUPPORT class URL; class FormValue; /** Namespace for Utility functions used by the webfeeds module */ class WebFeedUtil { public: /** Decode Base64 data. \param input Input in base 64. \param decoded A pointer where a buffer with the result will be put. This is a allocated buffer, caller is responsible for calling delete[]. \param decoded_length Length of decoded buffer. \return OpStatus::ERR_NO_MEMORY if OOM. OpStatus::ERR if input cannot be decoded (most likely because it is not valid base64) Otherwise OpStatus::OK. */ static OP_STATUS DecodeBase64(const OpStringC& input, unsigned char*& decoded, UINT& decoded_length); #ifdef UNUSED /** Encode a string as Base64 \param input A pointer to data to encode. Might be binary. \param input_length Length of the data in first parameter. \param encoded OpString where the base64 encoded result will be written. \param append If TRUE then this function will append to the OpString in previous parameter, if FALSE it will replace the content of the string. */ static OP_STATUS EncodeBase64(const char* input, UINT input_length, OpString& encoded, BOOL append = FALSE); #endif // UNUSED #ifdef OLD_FEED_DISPLAY /** Return a human readable representation of the date * Caller must delete[] string returned * returns NULL on OOM */ static uni_char* TimeToString(double date); /** Return a human readable representation of the time in short format. * If the time is the same date, then only a hh:mm timestamp will be returned, * otherwise only the date and month. * Caller must delete[] string returned * returns NULL on OOM */ static uni_char* TimeToShortString(double date, BOOL no_break_space=FALSE); #endif // OLD_FEED_DISPLAY /** Check if string contains HTML. This is because RSS contains no type information, so content might be plain text or HTML. We check if content contains legal HTML tags or legal character referances (e.g. &amp;), and assume it to be HTML if it does. \param content String to check for HTML content \param[out] contains_html True if content is non-empty and contains legal HTML tag(s) */ static BOOL ContentContainsHTML(const uni_char* content); static OP_STATUS ParseAuthorInformation(const OpStringC& input, OpString& email, OpString& name); static OP_STATUS UnescapeContent(const OpStringC& content, OpString& unescaped); static OP_STATUS Replace(OpString& replace_in, const OpStringC& replace_what, const OpStringC& replace_with); static int Find(const OpStringC& string, const OpStringC& search_for, const UINT start_index = 0); /** Removes all tags from string, leaving just content. If there are any stray > in content * they are replaced by &gt; */ static OP_STATUS StripTags(const uni_char* input, OpString& stripped_output, const uni_char* strip_element = NULL, BOOL remove_content=FALSE); #ifdef OLD_FEED_DISPLAY static OP_STATUS EscapeHTML(const uni_char* input, OpString& escaped_output); #endif // OLD_FEED_DISPLAY static OP_STATUS RelativeToAbsoluteURL(OpString& resolved_url, const OpStringC& relative_url, const OpStringC& base_url); #ifdef OLD_FEED_DISPLAY #ifdef WEBFEEDS_DISPLAY_SUPPORT static void WriteGeneratedPageHeaderL(URL& out_url, const uni_char* title); static void WriteGeneratedPageFooterL(URL& out_url); #endif // WEBFEEDS_DISPLAY_SUPPORT #endif // OLD_FEED_DISPLAY }; class DOM_Environment; class ES_Object; /** * Used to keep track of the scripting objects connected to various feeds content. */ class EnvToESObjectHash : private OpHashTable { public: EnvToESObjectHash() : OpHashTable() {} OP_STATUS Add(const DOM_Environment* key, ES_Object* data) { return OpHashTable::Add(key, data); } OP_STATUS Remove(const DOM_Environment* key, ES_Object** data) { return OpHashTable::Remove(key, reinterpret_cast<void **>(data)); } OP_STATUS GetData(const DOM_Environment* key, ES_Object** data) const { return OpHashTable::GetData(key, reinterpret_cast<void **>(data)); } }; #endif // WEBFEEDS_BACKEND_SUPPORT #endif /*WEBFEEDUTIL_H_*/
#include<iostream> using namespace std; int main() { int a,b,c; cin>>a>>b>>c; int min=a; if(b<min) min=b; if(c<min) min=c; cout<<min; }
#include<stdio.h> #define MAX 100 #define COUNTBY 3 int main() { int i; for(i=0;i<MAX;i++) { if(!(i%COUNTBY)) { printf("%d\n",i); } } return 0; }
#define DayZVersion "DayZ Epoch 1.0.7"
#include "Scene.h" #include "Debug.h" #include "Util.h" using namespace gg; Scene::Scene() { _shader = new Shader(Util::resourcePath + "Shaders/basic.vert", Util::resourcePath + "Shaders/basic.frag"); } Scene::~Scene() { delete _shader; }
#ifndef GRAPHWIDGET_H #define GRAPHWIDGET_H #include <QGraphicsView> #include "../../framework/Configuration.hpp" #include "../framework/GUIEventDispatcher.hpp" namespace uipf{ namespace gui{ class Node; //A Class that displays the uipf::Configuration as a directed graph. //layout is generated automatically with fruchtermann_reingold algorithm. class GraphWidget : public QGraphicsView { Q_OBJECT public: GraphWidget(QWidget *parent = 0); void renderConfig(uipf::Configuration& config); void selectNodeByName(const QString name, bool bUnselectOthers=true); void triggerNodeSelected(const uipf::gui::Node*); signals: //for QT to connect void nodeSelected(const uipf::gui::Node*); private slots: void on_selectNodesInGraphView(const std::vector<std::string>& vcNodeNames,uipf::gui::GraphViewSelectionType eType,bool bUnselectOthers); void on_clearSelectionInGraphView(); private: void wheelEvent(QWheelEvent *event) Q_DECL_OVERRIDE; void scaleView(qreal scaleFactor); qreal currentScale_; std::map<std::string,uipf::gui::Node*> nodes_; }; }//gui }//uipf #endif // GRAPHWIDGET_H
#pragma once namespace Poco { class File; } namespace BeeeOn { class FileLoader { public: virtual ~FileLoader(); virtual void load(const Poco::File &file) = 0; virtual void finished() = 0; }; }
#ifndef SPRING_GRAV_OBJ #define SPRING_GRAV_OBJ #include "SelectGravityObject.h" #include <map> class SpringObject : public SelectGravityObject { public: SpringObject(); SpringObject(int weight, Vector* position = new Vector(), Vector* speed = new Vector(), Vector* acceleration = new Vector(), std::map<GravityObject*,std::vector<double> >* links = 0); SpringObject(const SpringObject &gravObj); ~SpringObject(); virtual Vector* getInfluenceFor(const GravityObject* gravObj); virtual void calculateGravityAcceleration(const std::vector<GravityObject*> &universe); virtual std::map<GravityObject*,std::vector<double> >* getLinks() const; private: std::map<GravityObject*,std::vector<double> >* _links; //k, x0 }; #endif
// Given two sorted arrays a,b and integer x determine // whether b can rearrange so that a[i] + b[j] < x #include <iostream> using namespace std; int main() { int t; cout<<"Enter t "; cin>>t; while(t--) { int n,x; cout<<"\nEnter n,x "; cin>>n>>x; int i,j,c=0; int a[n],b[n]; cout<<"Enter 1st array "; for(i=0;i<n;i++) cin>>a[i]; cout<<"Enter 2nd array "; for(j=0;j<n;j++) cin>>b[j]; for(i=0;i<n;i++) { if(a[i] + b[n-i-1] > x) c++; } if(c==0) cout<<"Yes\n"; else cout<<"No\n"; } return 0; }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 2004-2011 Opera Software ASA. All rights reserved. ** ** This file is part of the Opera web browser. ** It may not be distributed under any circumstances. */ #ifndef OPBUFFEREDLOWLEVELFILE_H #define OPBUFFEREDLOWLEVELFILE_H #include "modules/search_engine/FileWrapper.h" /** Buffering wrapper class for OpLowLevelFile's. * * This class can be wrapped around any OpLowLevelFile to perform buffered * reads aligned on block boundaries. It may speed up file usage on Windows. */ class BufferedLowLevelFile : public FileWrapper { public: /** Create an BufferedLowLevelFile object. * * This does not create or open the file (but the supplied wrapped_file * may be already created or open). * * @param wrapped_file The normal, unbuffered OpLowLevelFile that will handle actual I/O. * @param status set to OK, or error code if the return value is NULL. * @param buffer_size The size of the buffer. Optimally it should be a power of 2 * @param transfer_ownership If TRUE, on success of this call the ownership of wrapped_file * is transferred to the new BufferedLowLevelFile, which becomes responsible for * deallocating it in the destructor. In this case the wrapped_file object must have * been allocated using OP_NEW. * @return The new BufferedLowLevelFile, or NULL on error */ static BufferedLowLevelFile* Create(OpLowLevelFile* wrapped_file, OP_STATUS& status, OpFileLength buffer_size, BOOL transfer_ownership = TRUE); ~BufferedLowLevelFile(); OP_STATUS Open(int mode); /** OPPS! Currently not posix compatible. Returns Eof()==TRUE when positioned at end of file, * not after trying to read past the end. */ BOOL Eof() const; OP_STATUS Write(const void* data, OpFileLength len); OP_STATUS Read(void* data, OpFileLength len, OpFileLength* bytes_read); OP_STATUS ReadLine(char** data); OpLowLevelFile* CreateCopy(); OpLowLevelFile* CreateTempFile(const uni_char* prefix); OP_STATUS SafeClose(); OP_STATUS GetFilePos(OpFileLength* pos) const; OP_STATUS GetFileLength(OpFileLength* len) const; OP_STATUS Close(); OP_STATUS Flush(); /** OPPS! Currently not posix compatible. Does not allow setting a position beyond the end of the file */ OP_STATUS SetFilePos(OpFileLength pos, OpSeekMode mode = SEEK_FROM_START); OP_STATUS SetFileLength(OpFileLength len); private: BufferedLowLevelFile(); BufferedLowLevelFile(OpLowLevelFile*, OpFileLength, unsigned char*, BOOL); enum IOop { IO_unknown = 3, IO_read = 1, IO_write = 2 }; unsigned char* const m_buffer; const OpFileLength m_buffer_size; mutable OpFileLength m_buffer_start; mutable OpFileLength m_buffer_end; // non-inclusive mutable OpFileLength m_physical_file_pos; mutable OpFileLength m_virtual_file_pos; mutable OpFileLength m_file_length; IOop m_last_IO_operation; CHECK_RESULT(OP_STATUS EnsureValidFileLength() const); CHECK_RESULT(OP_STATUS EnsureValidVirtualFilePos() const); CHECK_RESULT(OP_STATUS EnsureValidPhysicalFilePos() const); CHECK_RESULT(OP_STATUS EnsurePhysicalFilePos(OpFileLength pos, IOop operation)); CHECK_RESULT(OP_STATUS BufferVirtualFilePos()); CHECK_RESULT(OP_STATUS BufferedRead(void* data, OpFileLength len, OpFileLength* bytes_read)); }; #endif // !OPBUFFEREDLOWLEVELFILE_H
#include <iostream> #include <string> #include "Board.h" //#include "Player.h" using namespace std; int main(){ Player player1('X'); Player player2('O'); string pName; cout << "player 1 enter your name: "; cin >> pName; player1.setName(pName); cout << "player 2 enter your name: "; cin >> pName; player2.setName(pName); Board ttts; ttts.attachPlayer(player1); ttts.attachPlayer(player2); ttts.notifyObservers(); //starts game return 0; }
// Copyright 2015 Stef Pletinck // License: view LICENSE file // SFML includes #include <SFML/Graphics.hpp> // Thor includes #include <Thor/Resources.hpp> // C++ includes #include <iostream> #include <string> // My includes #include "../headers/epengine.h" EpEngine::EpEngine() { } EpEngine::~EpEngine() { delete window; delete testTile; } bool EpEngine::LoadTextures() { try { // Acquire everything here textureHolder.acquire("testTexture", thor::Resources:: fromFile<sf::Texture>("resources/testTexture.png")); } catch (thor::ResourceLoadingException& e) { std::cout << "Texture loading error: " << e.what() << std::endl; return false; } return true; return true; } bool EpEngine::Init() { window = new sf::RenderWindow(sf::VideoMode(800, 600, 32), "Epse's Code Engine Test"); if (window && LoadTextures()) { testTile = new EpTile(textureHolder["testTexture"]); return true; } return false; } void EpEngine::RenderFrame() { window->clear(); testTile->Draw(0, 0, window); window->display(); } void EpEngine::ProcessInput() { sf::Event evt; while (window->pollEvent(evt)) { if (evt.type == sf::Event::Closed) window->close(); } } void EpEngine::Update() { } void EpEngine::MainLoop() { while (window->isOpen()) { ProcessInput(); Update(); RenderFrame(); } } void EpEngine::Go() { if (!Init()) throw "Could not initialize engine"; MainLoop(); }
#include <bits/stdc++.h> using namespace std; class Solution { public: // T(n) = O(max{n, m}); // S(n) = O(m); vector<int> intersect(vector<int>& nums1, vector<int>& nums2) { unordered_map<int, int> memo; int n = nums1.size(); int m = nums2.size(); if (n == 0 || m == 0) return {}; for (int elem : nums2) { if (memo.count(elem)) memo[elem]++; else memo[elem] = 1; } vector<int> res; for (int elem : nums1) { if (memo.count(elem) && memo[elem] > 0) { res.push_back(elem); --memo[elem]; } } return res; } // T(n, m) = O(max{mlogm, nlogn}) // S(n, m) = O(1) // vector<int> intersect(vector<int>& nums1, vector<int>& nums2) { // TODO: sorting + two pointer // } }; int main() { vector<pair<pair<vector<int>, vector<int>>, vector<int>>> test_data = { {}, {}, {} }; for (auto& data : test_data) { auto in = data.first; auto expected = data.second; } return 0; }
#include <iostream> #include <cassert> // Provides assert function #include "sequence1.h" // With value_type defined as double using namespace std; namespace main_savitch_3 { // MOD MEMBER FUNCTIONS // constructor for sequence sequence::sequence() { used = 0; } //sets the index at 0 void sequence::start() { if (size() > 0) { current_index = 0; } } //increases the index by one if it passes assert void sequence::advance() { assert(is_item()); current_index++; } //inserts an entry for the array before the current value void sequence::insert(const value_type& entry) { assert( size() < CAPACITY); if(!is_item()) current_index = 0; //moves all the data in the array for(size_type i = used; i>current_index; --i) data[i] = data[i-1]; //sets the current index to the given entry data[current_index] = entry; //increments the counter used by one ++used; } //attaches a value after current void sequence::attach(const value_type& entry) { assert(size() < CAPACITY); //modifys index to correct value if it is null if (!is_item()) current_index = used - 1; //increases the index to add entry ++current_index; //moves the data for (size_type i = used; i > current_index; --i) { data[i] = data[i - 1]; } data[current_index] = entry; //increments the counter used by one ++used; } //removes the current value void sequence::remove_current() { size_type i; assert(is_item() == true); for (i = current_index; i< used - 1; ++i) { data[i] = data[i + 1]; } //decreases counter variable after removal --used; } //returns the counter variable used to give the value of the size sequence::size_type sequence::size() const { return used; } //returns true if both the current index is greater than 0 and used //our counter is greater than the index bool sequence::is_item() const { return (current_index >=0&& current_index < used); } //returns the current value sequence::value_type sequence::current() const { if (is_item()){ return data[current_index]; } } }
#include <iostream> using namespace std; int square_area(int A) { return A*A; } int rectangle_area(int A, int B) { return A*B; } //exceptions for if one or more number is negative void exceptions(int A, int B){ if(A <= 0 || B <= 0){ //throws an error throw string(" The area can't be negative."); } } int main(void) { float a, b, r; cin >> a; cin >> b; //tries to use the numbers and calls the methods try { exceptions(a,b); float rsquare = square_area(a); float rrectangle = rectangle_area(a,b); cout << rsquare << endl << rrectangle << endl; } //catches a thrown exception catch(string &exc){ cout << "Your input is not valid." << exc << endl; } }
/* * Copyright [2017] <Bonn-Rhein-Sieg University> * * Author: Torsten Jandt * */ #pragma once #include <mir_planner_executor/actions/stage/base_stage_action.h> class MockupStageAction : public BaseStageAction { protected: virtual bool run(std::string& robot, std::string& platform, std::string& object); };
// Copyright 2021 The XLS Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "xls/ir/block.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_format.h" #include "absl/strings/str_join.h" #include "xls/ir/function.h" #include "xls/ir/node.h" #include "xls/ir/node_iterator.h" namespace xls { std::string Block::DumpIr(bool recursive) const { // TODO(meheff): Remove recursive argument. Recursively dumping multiple // functions should be a method at the Package level, not the function/proc // level. XLS_CHECK(!recursive); std::vector<std::string> port_strings; for (const Port& port : GetPorts()) { if (absl::holds_alternative<ClockPort*>(port)) { port_strings.push_back( absl::StrFormat("%s: clock", absl::get<ClockPort*>(port)->name)); } else if (absl::holds_alternative<InputPort*>(port)) { port_strings.push_back( absl::StrFormat("%s: %s", absl::get<InputPort*>(port)->GetName(), absl::get<InputPort*>(port)->GetType()->ToString())); } else { port_strings.push_back(absl::StrFormat( "%s: %s", absl::get<OutputPort*>(port)->GetName(), absl::get<OutputPort*>(port)->operand(0)->GetType()->ToString())); } } std::string res = absl::StrFormat("block %s(%s) {\n", name(), absl::StrJoin(port_strings, ", ")); for (Register* reg : GetRegisters()) { if (reg->reset().has_value()) { absl::StrAppendFormat( &res, " reg %s(%s, reset_value=%s, asynchronous=%s, active_low=%s)\n", reg->name(), reg->type()->ToString(), reg->reset().value().reset_value.ToHumanString(), reg->reset().value().asynchronous ? "true" : "false", reg->reset().value().active_low ? "true" : "false"); } else { absl::StrAppendFormat(&res, " reg %s(%s)\n", reg->name(), reg->type()->ToString()); } } for (Node* node : TopoSort(const_cast<Block*>(this))) { absl::StrAppend(&res, " ", node->ToString(), "\n"); } absl::StrAppend(&res, "}\n"); return res; } absl::StatusOr<InputPort*> Block::AddInputPort( absl::string_view name, Type* type, absl::optional<SourceLocation> loc) { if (ports_by_name_.contains(name)) { return absl::InvalidArgumentError(absl::StrFormat( "Block %s already contains a port named %s", this->name(), name)); } InputPort* port = AddNode(absl::make_unique<InputPort>(loc, name, type, this)); if (name != port->GetName()) { // The name uniquer changed the given name of the input port to preserve // name uniqueness so a node with this name must already exist. return absl::InvalidArgumentError( absl::StrFormat("A node already exists with name %s", name)); } ports_by_name_[name] = port; ports_.push_back(port); input_ports_.push_back(port); return port; } absl::StatusOr<OutputPort*> Block::AddOutputPort( absl::string_view name, Node* operand, absl::optional<SourceLocation> loc) { if (ports_by_name_.contains(name)) { return absl::InvalidArgumentError(absl::StrFormat( "Block %s already contains a port named %s", this->name(), name)); } OutputPort* port = AddNode(absl::make_unique<OutputPort>(loc, operand, name, this)); if (name != port->GetName()) { // The name uniquer changed the given name of the input port to preserve // name uniqueness so a node with this name must already exist. return absl::InvalidArgumentError( absl::StrFormat("A node already exists with name %s", name)); } ports_by_name_[name] = port; ports_.push_back(port); output_ports_.push_back(port); return port; } absl::StatusOr<Register*> Block::AddRegister(absl::string_view name, Type* type, absl::optional<Reset> reset) { if (registers_.contains(name)) { return absl::InvalidArgumentError( absl::StrFormat("Register already exists with name %s", name)); } if (reset.has_value()) { if (type != package()->GetTypeForValue(reset.value().reset_value)) { return absl::InvalidArgumentError(absl::StrFormat( "Reset value %s for register %s is not of type %s", reset.value().reset_value.ToString(), name, type->ToString())); } } registers_[name] = absl::make_unique<Register>(std::string(name), type, reset, this); register_vec_.push_back(registers_[name].get()); return register_vec_.back(); } absl::Status Block::RemoveRegister(Register* reg) { if (reg->block() != this) { return absl::InvalidArgumentError("Register is not owned by block."); } if (!registers_.contains(reg->name())) { return absl::InvalidArgumentError(absl::StrFormat( "Block %s has no register named %s", name(), reg->name())); } XLS_RET_CHECK(registers_.at(reg->name()).get() == reg); auto it = std::find(register_vec_.begin(), register_vec_.end(), reg); XLS_RET_CHECK(it != register_vec_.end()); register_vec_.erase(it); registers_.erase(reg->name()); return absl::OkStatus(); } absl::StatusOr<Register*> Block::GetRegister(absl::string_view name) const { if (!registers_.contains(name)) { return absl::NotFoundError(absl::StrFormat( "Block %s has no register named %s", this->name(), name)); } return registers_.at(name).get(); } absl::Status Block::AddClockPort(absl::string_view name) { if (clock_port_.has_value()) { return absl::InternalError("Block already has clock"); } if (ports_by_name_.contains(name)) { return absl::InternalError( absl::StrFormat("Block already has a port named %s", name)); } clock_port_ = ClockPort{std::string(name)}; ports_.push_back(&clock_port_.value()); return absl::OkStatus(); } absl::Status Block::RemoveNode(Node* n) { // Simliar to parameters in xls::Functions, input and output ports are also // also stored separately as vectors for easy access and to indicate ordering. // Fix up these vectors prior to removing the node. if (n->Is<InputPort>() || n->Is<OutputPort>()) { Port port; if (n->Is<InputPort>()) { port = n->As<InputPort>(); auto it = std::find(input_ports_.begin(), input_ports_.end(), n->As<InputPort>()); XLS_RET_CHECK(it != input_ports_.end()) << absl::StrFormat( "input port node %s is not in the vector of input ports", n->GetName()); input_ports_.erase(it); } else if (n->Is<OutputPort>()) { port = n->As<OutputPort>(); auto it = std::find(output_ports_.begin(), output_ports_.end(), n->As<OutputPort>()); XLS_RET_CHECK(it != output_ports_.end()) << absl::StrFormat( "output port node %s is not in the vector of output ports", n->GetName()); output_ports_.erase(it); } ports_by_name_.erase(n->GetName()); auto port_it = std::find(ports_.begin(), ports_.end(), port); XLS_RET_CHECK(port_it != ports_.end()) << absl::StrFormat( "port node %s is not in the vector of ports", n->GetName()); ports_.erase(port_it); } return FunctionBase::RemoveNode(n); } absl::Status Block::ReorderPorts(absl::Span<const std::string> port_names) { absl::flat_hash_map<std::string, int64_t> port_order; for (int64_t i = 0; i < port_names.size(); ++i) { port_order[port_names[i]] = i; } XLS_RET_CHECK_EQ(port_order.size(), port_names.size()) << "Port order has duplicate names"; for (const Port& port : GetPorts()) { XLS_RET_CHECK(port_order.contains(PortName(port))) << absl::StreamFormat("Port order missing port \"%s\"", PortName(port)); } XLS_RET_CHECK_EQ(port_order.size(), GetPorts().size()) << "Port order includes invalid port names"; std::sort(ports_.begin(), ports_.end(), [&](const Port& a, const Port& b) { return port_order.at(PortName(a)) < port_order.at(PortName(b)); }); return absl::OkStatus(); } /*static*/ std::string Block::PortName(const Port& port) { if (absl::holds_alternative<ClockPort*>(port)) { return absl::get<ClockPort*>(port)->name; } else if (absl::holds_alternative<InputPort*>(port)) { return absl::get<InputPort*>(port)->GetName(); } else { return absl::get<OutputPort*>(port)->GetName(); } } } // namespace xls
/* XMRig * Copyright 2010 Jeff Garzik <jgarzik@pobox.com> * Copyright 2012-2014 pooler <pooler@litecoinpool.org> * Copyright 2014 Lucas Jones <https://github.com/lucasjones> * Copyright 2014-2016 Wolf9466 <https://github.com/OhGodAPet> * Copyright 2016 Jay D Dee <jayddee246@gmail.com> * Copyright 2017-2018 XMR-Stak <https://github.com/fireice-uk>, <https://github.com/psychocrypt> * Copyright 2018 Lee Clagett <https://github.com/vtnerd> * Copyright 2018-2019 SChernykh <https://github.com/SChernykh> * Copyright 2016-2019 XMRig <https://github.com/xmrig>, <support@xmrig.com> * * 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 * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "backend/opencl/OclThreads.h" #include "backend/opencl/wrappers/OclDevice.h" #include "base/crypto/Algorithm.h" #include "crypto/cn/CnAlgo.h" #include <algorithm> namespace xmrig { constexpr const size_t oneMiB = 1024u * 1024u; static inline bool isMatch(const OclDevice &device, const Algorithm &algorithm) { return algorithm.isCN() && device.vendorId() == OCL_VENDOR_AMD && (device.type() == OclDevice::Vega_10 || device.type() == OclDevice::Vega_20); } static inline uint32_t getMaxThreads(const OclDevice &device, const Algorithm &algorithm) { const uint32_t ratio = (algorithm.l3() <= oneMiB) ? 2u : 1u; if (device.type() == OclDevice::Vega_10) { if (device.computeUnits() == 56 && algorithm.family() == Algorithm::CN && CnAlgo<>::base(algorithm) == Algorithm::CN_2) { return 1792u; } } return ratio * 2024u; } static inline uint32_t getPossibleIntensity(const OclDevice &device, const Algorithm &algorithm) { const uint32_t maxThreads = getMaxThreads(device, algorithm); const size_t availableMem = device.freeMemSize() - (128u * oneMiB); const size_t perThread = algorithm.l3() + 224u; const auto maxIntensity = static_cast<uint32_t>(availableMem / perThread); return std::min<uint32_t>(maxThreads, maxIntensity); } static inline uint32_t getIntensity(const OclDevice &device, const Algorithm &algorithm) { const uint32_t maxIntensity = getPossibleIntensity(device, algorithm); if (device.type() == OclDevice::Vega_10) { if (algorithm.family() == Algorithm::CN_HEAVY && device.computeUnits() == 64 && maxIntensity > 976) { return 976; } } return maxIntensity / device.computeUnits() * device.computeUnits(); } static inline uint32_t getWorksize(const Algorithm &algorithm) { Algorithm::Family f = algorithm.family(); if (f == Algorithm::CN_PICO || f == Algorithm::CN_FEMTO) { return 64; } if (CnAlgo<>::base(algorithm) == Algorithm::CN_2) { return 16; } return 8; } static uint32_t getStridedIndex(const Algorithm &algorithm) { return CnAlgo<>::base(algorithm) == Algorithm::CN_2 ? 2 : 1; } static inline uint32_t getMemChunk(const Algorithm &algorithm) { return CnAlgo<>::base(algorithm) == Algorithm::CN_2 ? 1 : 2; } bool ocl_vega_cn_generator(const OclDevice &device, const Algorithm &algorithm, OclThreads &threads) { if (!isMatch(device, algorithm)) { return false; } const uint32_t intensity = getIntensity(device, algorithm); if (intensity == 0) { return false; } const uint32_t worksize = getWorksize(algorithm); const uint32_t memChunk = getMemChunk(algorithm); threads.add(OclThread(device.index(), intensity, worksize, getStridedIndex(algorithm), memChunk, 2, 8)); return true; } } // namespace xmrig
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 1995-2011 Opera Software AS. All rights reserved. * * This file is part of the Opera web browser. It may not be distributed * under any circumstances. * */ #include "core/pch.h" #include "platforms/unix/base/x11/x11_callback.h" #include "modules/hardcore/mh/mh.h" X11CbObject::~X11CbObject() { g_main_message_handler->UnsetCallBacks(this); } OP_STATUS X11CbObject::PostCallback(INTPTR data, unsigned long delay) { const MH_PARAM_1 par1 = reinterpret_cast<MH_PARAM_1>(this); if (!g_main_message_handler->HasCallBack(this, MSG_X11_CALLBACK, par1)) RETURN_IF_ERROR(g_main_message_handler->SetCallBack(this, MSG_X11_CALLBACK, par1)); if (!g_main_message_handler->PostMessage(MSG_X11_CALLBACK, par1, data, delay)) return OpStatus::ERR_NO_MEMORY; return OpStatus::OK; } void X11CbObject::HandleCallback(OpMessage msg, MH_PARAM_1 par1, MH_PARAM_2 par2) { if (msg != MSG_X11_CALLBACK || par1 != reinterpret_cast<MH_PARAM_1>(this)) return; HandleCallBack(par2); }
#include <bits/stdc++.h> using namespace std; typedef long long ll; int main(){ int n, m; cin >> n >> m; vector<int> x; for(int i = 0; i < m; i++) { int tmp; cin >> tmp; x.push_back(tmp); } if (n >= m){ cout << "0" << endl; return 0; } sort(x.begin(), x.end()); vector<pair<int, int>> dx; for(int i = 0; i < m - 1; i++) { dx.push_back(make_pair(x[i+1]-x[i], i)); } sort(dx.begin(),dx.end(),greater<pair<int, int>>()); /* for(auto f: dx) { cout << f.first << " " << f.second << endl; } */ int ans = 0; ll minos = 0; for(int i = 0; i < n - 1; i++) { minos += dx[i].first; } ans = x[x.size()-1] - x[0] - minos; cout << ans << endl; }
#include <SFML/Graphics.hpp> #include <iostream> #include <sstream> #include "Game.hpp" #include "Map.hpp" #define MAP_WIDTH 28 #define MAP_HEIGHT 20 #define SCREEN_WIDTH 600 #define SCREEN_HEIGHT 450 int main(int argc, char *argv[]) { sf::RenderWindow win(sf::VideoMode(SCREEN_WIDTH, SCREEN_HEIGHT), "Ray Caster"); win.setVerticalSyncEnabled(false); win.setMouseCursorVisible(false); win.setKeyRepeatEnabled(false); Game game(&win); sf::Clock frameclock; while (win.isOpen()) { sf::Event ev; while (win.pollEvent(ev)) { if (ev.type == sf::Event::Closed) win.close(); else game.HandleEvent(ev); } float dt = frameclock.restart().asSeconds(); game.Tick(dt); game.Draw(); win.display(); } return EXIT_SUCCESS; }
#include <sfwdraw.h> #include <stdio.h> #include <time.h> #include "Defines.h" #include "GameState.h" int main() { WINDOW(400, 400, "Ghost Puncher") INITIALIZE while (RUNNING) PLAY EXIT }
/** * @author Nicholas Kidd * @version $Id: AHval.cpp 465 2008-11-05 20:39:17Z kidd $ */ #define BDDBIGMEM 0 #if BDDBIGMEM // For large memory machines (i.e., >= 2GB) allocs ~1500 MB //#define BDDMEMSIZE 75000000 // 25000000 ~~ 500 MB, change the multiple to get what you need. #define FIVE_CENT_MB 25000000 #define BDDMEMSIZE (FIVE_CENT_MB*1) #else #define BDDMEMSIZE 10000000 #endif #include <iostream> #include <cassert> #include "wali/domains/lh/intra/AHval.hpp" #include "wali/Common.hpp" using namespace wali::domains::lh::intra; int AHval::LOCKCNT = -1; int AHval::NUMVARS = -1; const int AHval::MAX_LOCKS = 2; bool AHval::is_initialized() { return (LOCKCNT != -1); } void AHval::initialize( int num_locks ) { if (num_locks < 0) { std::cerr << "Must be a positive number of locks." << std::endl; assert(0); } else if (num_locks > MAX_LOCKS) { std::cerr << "Can only have " << MAX_LOCKS << " locks." << std::endl; assert(0); } else if (LOCKCNT != -1) { std::cerr << "AHval::initialize can only be invoked once." << std::endl; assert(0); } // /////////////////////// // Begin initialize BuDDy if (0 == bdd_isrunning()) { int rc = bdd_init( BDDMEMSIZE,100000 ); if( rc < 0 ) { std::cerr << "[ERROR] " << bdd_errstring(rc) << std::endl; assert( 0 ); } } else { std::cerr << "[ERROR] BuDDy already initialized?" << std::endl; assert(0); } // Default is 50,000 (1 Mb),memory is cheap, so use 100,000 bdd_setmaxincrease(100000); // End initialize BuDDy // /////////////////////// LOCKCNT = num_locks; // Need LOCKCNT+1 sets of size LOCKCNT NUMVARS = (LOCKCNT+1) * LOCKCNT; std::cout << "[INFO] There are " << NUMVARS << " vars for " << LOCKCNT << " locks." << std::endl; bdd_setvarnum(NUMVARS); } AHval::AHval() { assert( is_initialized() ); fVal = bdd_nithvar(0); for (int i=1; i < NUMVARS ; i++) fVal = fVal & bdd_nithvar(i); } AHval::AHval( const AHval& that ) : fVal(that.fVal) { assert( is_initialized() ); } AHval::AHval( bdd R ) : fVal(R) { assert( is_initialized() ); } AHval AHval::acquire( int lock ) const { check_lock(lock); //bdd bddlock = fdd_ithvar(0,lock); bdd bddlock = bdd_ithvar(lock); assert((fVal & bddlock) == bddfalse); //bdd R = add_lock_to_set(fVal,0,lock); //bdd exout = bdd_ithvar((setnum * LOCKCNT) + lock); //return bdd_exist(R,exout) & exout; // First, existentially quantify out the lock for // the held lockset L bdd exout = bdd_ithvar(lock); // Second, update the AH for each held lock [l]. // I.e., AH_l = AH_l \cup {lock} for (int l=0; l < LOCKCNT ; l++) { // Is lock [l] in the set of held locks? bdd has_lock_l = fVal & bdd_ithvar(l); if ((l == lock) || has_lock_l != bddfalse ) { int AH_l = (l+1)*LOCKCNT; exout = exout & bdd_ithvar( AH_l + lock); } } bdd R = bdd_exist(fVal,exout) & exout; return AHval(R); } AHval AHval::release( int lock ) const { check_lock(lock); bdd bddlock = bdd_ithvar(lock); assert((fVal & bddlock) != bddfalse); // First, remove [lock] from L bdd R = bdd_exist(fVal,bdd_ithvar(lock)) & bdd_nithvar(lock); //std::cout << " R1 : " << bddset << R << std::endl; // Second, remove AH_{lock} int AH_lock = (lock+1) * LOCKCNT; bdd exout = bdd_ithvar(AH_lock); bdd exin = bdd_nithvar(AH_lock); for (int i=1 ; i < LOCKCNT ; i++) { int varnum = AH_lock+i; exout = exout & bdd_ithvar(varnum); exin = exin & bdd_nithvar(varnum); } R = bdd_exist(R,exout) & exin; return AHval(R); } void AHval::printHandler(char* v, int size) { assert(size == NUMVARS); // for L,AH_1,...,AH_n for (int i = 0 ; i <= LOCKCNT ; i++) { // for lock l \in [0,LOCKCNT) std::cout << "{"; bool first = true; for (int l = 0; l < LOCKCNT ; l++) { int offset = i*LOCKCNT + l; assert(offset < size); if (v[offset]) { if (first) first = false; else std::cout << ", "; std::cout << "l" << l; } } std::cout << "} "; } } std::ostream& AHval::print( std::ostream& o ) const { bdd_allsat(fVal,printHandler); std::cout << "\n"; return o; } void AHval::check_lock(int lock) { if (LOCKCNT == -1) { std::cerr << "[ERROR] AH not initialized" << std::endl; assert(0); } else if (lock >= MAX_LOCKS) { std::cerr << "[ERROR] Invalid lock " << lock << std::endl; assert(0); } } bdd AHval::add_lock_to_set(bdd R, int setnum, int lock) { bdd exout = bdd_ithvar((setnum * LOCKCNT) + lock); return bdd_exist(R,exout) & exout; } std::ostream& operator<<(std::ostream& o, const AHval& ah) { ah.print(o); return o; }
/* https://www.acmicpc.net/problem/1316 */ #include <iostream> #include <cstring> using namespace std; int main(void) { int testCase; scanf("%d", &testCase); int cnt = 0; char** str = new char*[testCase]; for (int i = 0; i < testCase; i++) { str[i] = new char[100]{ 0, }; scanf("%s", str[i]); char tmp[100] = { 0, }; int strLength = strlen(str[i]); int tmpIdx = 0; bool noRepeat = false; for (int j = 0; j < strLength; j++) { if (j != 0) { for (int t = 0; t < tmpIdx; t++) { if (tmp[t] == str[i][j]) { if (str[i][j - 1] == str[i][j]) break; else { noRepeat = true; break; } } if (t == tmpIdx - 1) { tmp[tmpIdx++] = str[i][j]; break; } } if (noRepeat) break; } else tmp[tmpIdx++] = str[i][j]; } if (!noRepeat) cnt++; noRepeat = false; delete[] str[i]; } printf("%d", cnt); delete[] str; return 0; }
#ifndef TREEFACE_GRAPHICS_UTILS_H #define TREEFACE_GRAPHICS_UTILS_H #include "treeface/base/Enums.h" #include "treeface/math/Vec2.h" namespace treeface { struct StrokeVertex { Vec2f position; Vec2f tangent_unorm; float trip; float side; }; struct StrokeStyle { LineCap cap; LineJoin join; float miter_cutoff; float width; }; inline bool vec_are_cclw( const Vec2f& v1, const Vec2f& v2, const Vec2f& v3 ) { int num_neg = 0; if ( (v1 % v2) < 0.0f ) num_neg++; if ( (v2 % v3) < 0.0f ) num_neg++; if ( (v3 % v1) < 0.0f ) num_neg++; return num_neg < 2; } inline bool is_below( const Vec2f& a, const Vec2f& b ) { return a.y < b.y || (a.y == b.y && a.x < b.x); } inline bool is_convex( const Vec2f& edge1, const Vec2f& edge2 ) noexcept { float cross = edge1 % edge2; return cross > 0; } inline bool is_convex( const Vec2f& vtx1, const Vec2f& vtx2, const Vec2f& vtx3 ) noexcept { return is_convex( vtx2 - vtx1, vtx3 - vtx2 ); } } // namespace treeface #endif // TREEFACE_GRAPHICS_UTILS_H
#include "fun.h" float toRadian(float degree) { return (3.14 / 180) * degree; } float dCos(float degree) { return cos(toRadian(degree)); } float dSin(float degree) { return sin(toRadian(degree)); } sf::Vector2f check(sf::Vertex wall[], sf::Vertex ray[]) { float x1 = wall[0].position.x; float x2 = wall[1].position.x; float x3 = ray[0].position.x; float x4 = ray[1].position.x; float y1 = wall[0].position.y; float y2 = wall[1].position.y; float y3 = ray[0].position.y; float y4 = ray[1].position.y; float t = ((x1 - x3) * (y3 - y4) - (y1 - y3) * (x3 - x4)) / ((x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4)); float u = -(((x1 - x2) * (y1 - y3) - (y1 - y2) * (x1 - x3)) / ((x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4))); sf::Vector2f ret; if (t > 0.0 && t < 1.0 && u > 0.0 && u < 1.0) { ret.x = x1 + t * (x2 - x1); ret.y = y1 + t * (y2 - y1); return ret; } return sf::Vector2f(-1,-1); } void drawWalls(std::vector<sf::Vertex*> walls, sf::RenderWindow* window) { for (int i = 0; i < walls.size(); i++) { window->draw(walls[i], 2, sf::Lines); } } void spawnWalls(sf::Vertex walls[][2]) { for (int i = 0; i < 10; i++) { walls[i][0].position = sf::Vector2f(rand() % 1200, rand() % 900); walls[i][1].position = sf::Vector2f(rand() % 1200, rand() % 900); } printf("Randomizing walls done.\n"); } void displayWalls(sf::Vertex walls[][2], sf::RenderWindow *window) { for (int i = 0; i < 10; i++) window->draw(walls[i], 2, sf::Lines); }
////////////////////////////////////////////////////////////////////////////// // // Copyright (c) Triad National Security, LLC. This file is part of the // Tusas code (LA-CC-17-001) and is subject to the revised BSD license terms // in the LICENSE file found in the top-level directory of this distribution. // ////////////////////////////////////////////////////////////////////////////// #ifndef INTERPFLUX_H #define INTERPFLUX_H #include <vector> // Epetra support #include "Epetra_Comm.h" //teuchos support #include <Teuchos_RCP.hpp> //#define TUSAS_INTERPFLUX class interpflux { public: /// Constructor. interpflux(const Teuchos::RCP<const Epetra_Comm>& comm, const std::string timefileString ); /// Destructor. ~interpflux(); bool interp_time(const double time); double theta_; int timeindex_; private: const Teuchos::RCP<const Epetra_Comm> comm_; const std::string timefileString_; std::vector<double> data; void read_file(); }; #endif
//Copyright 2011-2016 Tyler Gilbert; All Rights Reserved #include <stdint.h> #include <cstdlib> #include <cstring> #include <cstdio> #include <mcu/types.h> #if !defined __link #include <reent.h> #endif #include "var/Data.hpp" using namespace var; const int Data::m_zero_value = 0; #define MIN_CHUNK_SIZE 56 size_t Data::min_size(){ return MIN_CHUNK_SIZE; } Data::Data(){ zero(); } Data::Data(void * mem, size_t s, bool readonly){ set(mem, s, readonly); } Data::Data(size_t s){ alloc(s); } int Data::free(){ #ifndef __HWPL_ONLY__ if( m_needs_free ){ ::free(m_mem_write); } #endif zero(); return 0; } #ifndef __HWPL_ONLY__ Data::~Data(){ free(); } #endif void Data::set(void * mem, size_t s, bool readonly){ m_mem_write = mem; m_needs_free = false; m_capacity = s; if( m_mem_write ){ this->m_mem = m_mem_write; } else { mem = (void*)&m_zero_value; } if( readonly ){ m_mem_write = 0; } } void Data::zero(){ m_mem = &m_zero_value; m_mem_write = 0; m_needs_free = false; m_capacity = 0; } int Data::alloc(size_t s, bool resize){ #ifndef __MCU_ONLY__ void * new_data; if( (m_needs_free == false) && (m_mem != &m_zero_value) ){ //this data object can't be resized -- it was created using a pointer (not dyn memory) return -1; } if( s < m_capacity + MIN_CHUNK_SIZE ){ s = m_capacity + MIN_CHUNK_SIZE; } new_data = malloc(s); if( new_data == 0 ){ return -1; } if( resize ){ memcpy(new_data, m_mem, s > m_capacity ? m_capacity : s); } free(); m_mem_write = new_data; m_needs_free = true; m_mem = m_mem_write; m_capacity = s; return 0; #else return -1; #endif } int Data::set_min_capacity(size_t s){ if( s <= capacity() ){ return 0; } return alloc(s, true); } void Data::clear(){ fill(0); } void Data::fill(unsigned char d){ if( m_mem_write ){ memset(m_mem_write, d, capacity()); } }
/******************************************************************************** ** Form generated from reading UI file 'loginscreen.ui' ** ** Created by: Qt User Interface Compiler version 5.13.2 ** ** WARNING! All changes made in this file will be lost when recompiling UI file! ********************************************************************************/ #ifndef UI_LOGINSCREEN_H #define UI_LOGINSCREEN_H #include <QtCore/QVariant> #include <QtWidgets/QApplication> #include <QtWidgets/QDialog> #include <QtWidgets/QLabel> #include <QtWidgets/QLineEdit> #include <QtWidgets/QPushButton> #include <QtWidgets/QVBoxLayout> #include <QtWidgets/QWidget> QT_BEGIN_NAMESPACE class Ui_LoginScreen { public: QPushButton *pushButton_login; QLabel *label; QLabel *label_2; QWidget *layoutWidget; QVBoxLayout *verticalLayout; QLineEdit *lineEdit_login; QLineEdit *lineEdit_password; QPushButton *pushButton; void setupUi(QDialog *LoginScreen) { if (LoginScreen->objectName().isEmpty()) LoginScreen->setObjectName(QString::fromUtf8("LoginScreen")); LoginScreen->resize(400, 300); pushButton_login = new QPushButton(LoginScreen); pushButton_login->setObjectName(QString::fromUtf8("pushButton_login")); pushButton_login->setGeometry(QRect(150, 180, 80, 21)); label = new QLabel(LoginScreen); label->setObjectName(QString::fromUtf8("label")); label->setGeometry(QRect(90, 110, 47, 13)); label_2 = new QLabel(LoginScreen); label_2->setObjectName(QString::fromUtf8("label_2")); label_2->setGeometry(QRect(90, 150, 47, 13)); layoutWidget = new QWidget(LoginScreen); layoutWidget->setObjectName(QString::fromUtf8("layoutWidget")); layoutWidget->setGeometry(QRect(140, 110, 110, 52)); verticalLayout = new QVBoxLayout(layoutWidget); verticalLayout->setObjectName(QString::fromUtf8("verticalLayout")); verticalLayout->setContentsMargins(0, 0, 0, 0); lineEdit_login = new QLineEdit(layoutWidget); lineEdit_login->setObjectName(QString::fromUtf8("lineEdit_login")); verticalLayout->addWidget(lineEdit_login); lineEdit_password = new QLineEdit(layoutWidget); lineEdit_password->setObjectName(QString::fromUtf8("lineEdit_password")); lineEdit_password->setEchoMode(QLineEdit::Password); lineEdit_password->setReadOnly(false); verticalLayout->addWidget(lineEdit_password); pushButton = new QPushButton(LoginScreen); pushButton->setObjectName(QString::fromUtf8("pushButton")); pushButton->setGeometry(QRect(150, 210, 80, 21)); retranslateUi(LoginScreen); QMetaObject::connectSlotsByName(LoginScreen); } // setupUi void retranslateUi(QDialog *LoginScreen) { LoginScreen->setWindowTitle(QCoreApplication::translate("LoginScreen", "Dialog", nullptr)); pushButton_login->setText(QCoreApplication::translate("LoginScreen", "Login", nullptr)); label->setText(QCoreApplication::translate("LoginScreen", "login:", nullptr)); label_2->setText(QCoreApplication::translate("LoginScreen", "password:", nullptr)); pushButton->setText(QCoreApplication::translate("LoginScreen", "New account", nullptr)); } // retranslateUi }; namespace Ui { class LoginScreen: public Ui_LoginScreen {}; } // namespace Ui QT_END_NAMESPACE #endif // UI_LOGINSCREEN_H
#include <fstream> #include "sum_float_opt.h" int main() { ofstream in_pix("input_pixels_regression_result_sum_float_opt.txt"); ofstream fout("regression_result_sum_float_opt.txt"); HWStream<hw_uint<32> > f_update_0_read; HWStream<hw_uint<32> > u_update_0_read; HWStream<hw_uint<32> > sum_float_update_0_write; // Loading input data // cmap : { f_update_0[root = 0, f_0, f_1] -> f_off_chip[0, 0] : 0 <= f_0 <= 29 and 0 <= f_1 <= 29 } // read map: { f_off_chip[0, 0] -> f_update_0[root = 0, f_0, f_1] : 0 <= f_0 <= 29 and 0 <= f_1 <= 29 } // rng : { f_update_0[root = 0, f_0, f_1] : 0 <= f_0 <= 29 and 0 <= f_1 <= 29 } for (int i = 0; i < 900; i++) { hw_uint<32> in_val; set_at<0*32, 32, 32>(in_val, 1*i + 0); in_pix << in_val << endl; f_update_0_read.write(in_val); } // cmap : { u_update_0[root = 0, u_0, u_1] -> u_off_chip[0, 0] : 0 <= u_0 <= 29 and 0 <= u_1 <= 29 } // read map: { u_off_chip[0, 0] -> u_update_0[root = 0, u_0, u_1] : 0 <= u_0 <= 29 and 0 <= u_1 <= 29 } // rng : { u_update_0[root = 0, u_0, u_1] : 0 <= u_0 <= 29 and 0 <= u_1 <= 29 } for (int i = 0; i < 900; i++) { hw_uint<32> in_val; set_at<0*32, 32, 32>(in_val, 1*i + 0); in_pix << in_val << endl; u_update_0_read.write(in_val); } sum_float_opt(f_update_0_read, u_update_0_read, sum_float_update_0_write); for (int i = 0; i < 900; i++) { hw_uint<32> actual = sum_float_update_0_write.read(); auto actual_lane_0 = actual.extract<0*32, 31>(); fout << actual_lane_0 << endl; } in_pix.close(); fout.close(); return 0; }
// // Created by Cristian Marastoni on 23/04/15. // #ifndef NETWORK_DEBUG_H #define NETWORK_DEBUG_H class Debug { public: static void Log(const char *ctx, const char *fmt, ...); static void Error(const char *ctx, const char *fmt, ...); }; #endif //NETWORK_DEBUG_H
#include "SoftwareSerial.h" SoftwareSerial serial_connection(13, 12);//Create a serial connection with TX and RX on these pins #define BUFFER_SIZE 64//This will prevent buffer overruns. char inData[BUFFER_SIZE];//This is a character buffer where the data sent by the python script will go. char inChar=-1;//Initialie the first character as nothing int count=0;//This is the number of lines sent in from the python script int i=0;//Arduinos are not the most capable chips in the world so I just create the looping variable once int msg[2]; // defines pins numbers const int sensorOneTrigPin = 6; const int sensorOneEchoPin = 7; const int sensorTwoTrigPin = 9; const int sensorTwoEchoPin = 10; // defines variables long durationOne, durationTwo; int distanceOne, distanceTwo; void setup() { pinMode(sensorOneTrigPin, OUTPUT); // Sets the trigPin as an Output pinMode(sensorOneEchoPin, INPUT); // Sets the echoPin as an Input pinMode(sensorTwoTrigPin, OUTPUT); // Sets the trigPin as an Output pinMode(sensorTwoEchoPin, INPUT); // Sets the echoPin as an Input Serial.begin(9600); // Starts the serial communication serial_connection.begin(9600);//Initialize communications with the bluetooth module serial_connection.println("Ready!!!");//Send something to just start comms. This will never be seen. Serial.println("Started");//Tell the serial monitor that the sketch has started. } void loop() { // Clears the trigPin digitalWrite(sensorOneTrigPin, LOW); delayMicroseconds(2); // Sets the trigPin on HIGH state for 10 micro seconds digitalWrite(sensorOneTrigPin, HIGH); delayMicroseconds(10); digitalWrite(sensorOneTrigPin, LOW); // Reads the echoPin, returns the sound wave travel time in microseconds durationOne = pulseIn(sensorOneEchoPin, HIGH); // Calculating the distance distanceOne= durationOne*0.034/2; // Clears the trigPin digitalWrite(sensorTwoTrigPin, LOW); delayMicroseconds(2); // Sets the trigPin on HIGH state for 10 micro seconds digitalWrite(sensorTwoTrigPin, HIGH); delayMicroseconds(10); digitalWrite(sensorTwoTrigPin, LOW); // Reads the echoPin, returns the sound wave travel time in microseconds durationTwo = pulseIn(sensorTwoEchoPin, HIGH); // Calculating the distance distanceTwo= durationTwo*0.034/2; // Prints the distance on the Serial Monitor Serial.print("Sensor One Distance: "); Serial.print(distanceOne); Serial.print(" Sensor Two Distance: "); Serial.println(distanceTwo); msg[0]=distanceOne; msg[1]=distanceTwo; serial_connection.println(String(msg[0])+','+String(msg[1]));//Then send an incrmented string back to the python scripy }
#include "SIdict.h" #include <stdio.h> #include <iostream> int main(){ Dict* d = new Dict(); printf("%i\n", d -> addOrUpdate("a", 5)); printf("%i\n", d -> addOrUpdate("b", 7)); printf("%i\n", d -> addOrUpdate("c", 70)); printf("%i\n", d -> remKey("c")); printf("%i\n", d -> addOrUpdate("d", 7000)); printf("%i\n", d -> remKey("a")); printf("%i\n", d -> lookup("a")); printf("%i\n", d -> lookup("b")); printf("%i\n", d -> lookup("c")); printf("%i\n", d -> lookup("d")); printf("%i\n", d -> remKey("l")); }
#include <iostream> int main() { // Задание 6 int threeDigitNum = 0; std::cout << "Enter three-digit number: " << std::endl; std::cin >> threeDigitNum; int doubleDigitNum = threeDigitNum % 10; int newThreeDigitNum = threeDigitNum / 10; std::cout << "New number is: " <<doubleDigitNum << newThreeDigitNum << std::endl; // Задание 19 int givenNum = 546; int primaryNum = ((givenNum%100)/10)*100 + ((givenNum - givenNum%100)/100)*10 + givenNum%10; std::cout << primaryNum << std::endl; return 0; }