text
stringlengths
8
6.88M
/*-----------------------------主函数-------------------- * 文件名:CameraInit.cpp * 作者: 孙霖 * 功能: 摄像头打开设置关闭 ------------------------------------------------------*/ #include "CameraInit.h" //-------------------------函数区------------------------------ /** * @author Seafood * @name PrintDeviceInfo * @return bool * @function 打印摄像头信息 * @para pstMVDevInfo * */ bool PrintDeviceInfo(MV_CC_DEVICE_INFO* pstMVDevInfo) { //查看是否有devInfolist if (NULL == pstMVDevInfo) { printf("%s\n" , "The Pointer of pstMVDevInfoList is NULL!"); return false; } //网络摄像头 if (pstMVDevInfo->nTLayerType == MV_GIGE_DEVICE) { // 打印当前相机ip和用户自定义名字 // print current ip and user defined name printf("%s %x\n" , "nCurrentIp:" , pstMVDevInfo->SpecialInfo.stGigEInfo.nCurrentIp); printf("%s %s\n\n" , "chUserDefinedName:" , pstMVDevInfo->SpecialInfo.stGigEInfo.chUserDefinedName); } //USB摄像头 else if (pstMVDevInfo->nTLayerType == MV_USB_DEVICE) { printf("UserDefinedName:%s\n\n", pstMVDevInfo->SpecialInfo.stUsb3VInfo.chUserDefinedName); } //其他 else { printf("Not support.\n"); } return true; } void paraInit() { //一帧数据大小 nBuffSize = MAX_IMAGE_DATA_SIZE; nRet = -1 ; //相机状态代码 handle = NULL ; //相机用参数 pFrameBuf = NULL; //相机位置 if(mcu_data.env_light > 0 && mcu_data.env_light < 20){ fExposureTime=1000; } else if(mcu_data.env_light >= 20 && mcu_data.env_light < 40){ fExposureTime=3000; } else if(mcu_data.env_light >= 40 && mcu_data.env_light < 60){ fExposureTime=5000; } else if(mcu_data.env_light >= 60 && mcu_data.env_light < 80){ fExposureTime=7000; } else{ fExposureTime=EXPO_CLASS_5; } } /** * @author Seafood * @name cameraInit * @return int * @function 打开摄像头 * @para None * */ int cameraInit() { paraInit(); MV_CC_DEVICE_INFO_LIST stDeviceList; memset(&stDeviceList, 0, sizeof(MV_CC_DEVICE_INFO_LIST)); // 枚举设备 // enum device nRet = MV_CC_EnumDevices(MV_GIGE_DEVICE | MV_USB_DEVICE, &stDeviceList); if (MV_OK != nRet) { printf("MV_CC_EnumDevices fail! nRet [%x]\n", nRet); return -1; } unsigned int nIndex = 0; if (stDeviceList.nDeviceNum > 0) { for (int i = 0; i < stDeviceList.nDeviceNum; i++) { //printf("[device %d]:\n", i); MV_CC_DEVICE_INFO* pDeviceInfo = stDeviceList.pDeviceInfo[i]; if (NULL == pDeviceInfo) { break; } //PrintDeviceInfo(pDeviceInfo); } } else { printf("Find No Devices!\n"); return -1; } //scanf("%d", &nIndex); // 选择设备并创建句柄 // select device and create handle nRet = MV_CC_CreateHandle(&handle, stDeviceList.pDeviceInfo[nIndex]); if (MV_OK != nRet) { printf("MV_CC_CreateHandle fail! nRet [%x]\n", nRet); return -1; } // 打开设备 // open device nRet = MV_CC_OpenDevice(handle); if (MV_OK != nRet) { printf("MV_CC_OpenDevice fail! nRet [%x]\n", nRet); return -1; } nRet = MV_CC_SetFloatValue(handle, "ExposureTime", fExposureTime); // 开始取流 // start grab image nRet = MV_CC_StartGrabbing(handle); if (MV_OK != nRet) { printf("MV_CC_StartGrabbing fail! nRet [%x]\n", nRet); return -1; } return 1; } /** * @author Seafood * @name cameraExit * @return int * @function 摄像头退出 * @para None * */ int cameraExit() { // 停止取流 // end grab image nRet = MV_CC_StopGrabbing(handle); if (MV_OK != nRet) { printf("MV_CC_StopGrabbing fail! nRet [%x]\n", nRet); return -1; } // 关闭设备 // close device nRet = MV_CC_CloseDevice(handle); if (MV_OK != nRet) { printf("MV_CC_CloseDevice fail! nRet [%x]\n", nRet); return -1; } // 销毁句柄 // destroy handle nRet = MV_CC_DestroyHandle(handle); if (MV_OK != nRet) { printf("MV_CC_DestroyHandle fail! nRet [%x]\n", nRet); return -1; } printf("exit\n"); return 1; }
#include <Ethernet.h> #include <PubSubClient.h> #include <RH_ASK.h> #include <SPI.h> // Not actually used but needed to compile // Update these with values suitable for your network. byte mac[] = { 0x16, 0x07, 0x84, 0x01, 0x02, 0x87 }; EthernetClient ethClient; // MQTT Client Settings byte server[] = { 192, 168, 1, 3 }; byte ip[] = { 192, 168, 1, 81 }; int port = 1883; char* topic = "HomeAutomation/RelayControl"; // the MQTT client PubSubClient client(server, port, callback, ethClient); // ASK settings const uint16_t dataRate = 2000; const uint8_t rxPin = 3; const uint8_t txPin = 4; const uint8_t pttPin = 5; const bool pttInverted = false; // the ASK driver RH_ASK rh(dataRate, rxPin, txPin, pttPin, pttInverted); void setup() { // Serial.begin(9600); if (Ethernet.begin(mac) == 0) { // Serial.println("Failed to configure Ethernet using DHCP."); Ethernet.begin(mac, ip); } // Serial.println("Connecting..."); if (client.connect("arClient")) { client.subscribe(topic); // Serial.print("Client connected, subscribing to topic: "); // Serial.println(topic); } else { // Serial.println("Client failed to connect!"); } if (!rh.init()) { // Serial.println("init failed"); } } void loop() { client.loop(); } void callback(char* topic, byte* payload, unsigned int length) { // handle message arrived // Serial.print("MQTT Message received: "); char messageToTransmit[length]; for (int i = 0; i < length; i++) { messageToTransmit[i] = char(payload[i]); } messageToTransmit[length] = '\0'; String str = String(messageToTransmit); // Serial.println(""); if (sizeof(messageToTransmit) > 0) { transmitMessage(messageToTransmit); } } void transmitMessage(char* message) { // Serial.print("Transmitting message via RF: "); char messageToTransmit[strlen(message) - 2]; for (int i = 0; i < strlen(message) - 2; i++) { messageToTransmit[i] = char(message[i]); } messageToTransmit[strlen(message) - 3] = char('\0'); // Serial.println(messageToTransmit); rh.send((uint8_t *) messageToTransmit, strlen(messageToTransmit)); rh.waitPacketSent(); }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * 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" #ifndef NO_CARBON #include "platforms/mac/pi/MacOpColorChooser.h" OP_STATUS OpColorChooser::Create(OpColorChooser** new_object) { *new_object = new MacOpColorChooser; if (*new_object == NULL) return OpStatus::ERR_NO_MEMORY; return OpStatus::OK; } OP_STATUS MacOpColorChooser::Show(COLORREF initial_color, OpColorChooserListener* listener, DesktopWindow* parent/*=NULL*/) { Point pt = {0,0}; unsigned char r,g,b; RGBColor oldColor; RGBColor newColor; r = initial_color & 0x000000FF; g = (initial_color & 0x0000FF00) >> 8; b = (initial_color & 0x00FF0000) >> 16; oldColor.red = r | (r << 8); oldColor.green = g | (g << 8); oldColor.blue = b | (b << 8); if (GetColor(pt, "\p", &oldColor, &newColor)) { r = newColor.red >> 8; g = newColor.green >> 8; b = newColor.blue >> 8; listener->OnColorSelected(r | (g << 8) | (b << 16)); } return OpStatus::OK; } #endif // NO_CARBON
#include <stdio.h> #include <math.h> int main(){ float a,b,c,prec,x,sakne; int n=0; printf("Ievadiet a vertibu "); scanf("%f",&a); printf("Ievadiet b vertibu "); scanf("%f",&b); printf("Ievadiet c vērtību izteinsmei (1+x)*exp(x)=c "); scanf("%f",&c); printf("Ievadiet precizitāti "); scanf("%f",&prec); float vid=a; while((b-a)>=prec){ n++; vid=(a+b)/2; if((1+vid)*exp(vid)==c){ break; } else if(((1+vid)*exp(vid)-c)*((1+a)*exp(a)-c)<0){ b=vid; } else a=vid; } sakne=(1+vid)*exp(vid); printf("\nSakne (1+x)*exp(x)=%.2f izteiksmei ir %f\n",c,vid); printf("f(%.2f)=%f\n",vid,sakne); printf("Nepieciešmo literāciju skaits %d",n); return 0; }
#include "ChessField.h" using namespace chess_piece; namespace chess_field { void ChessField::setMap(map<int, ChessPiece*> chessMap) { this->chessMap_ = chessMap; } void ChessField::printChessMap() const { for (auto itr = this->chessMap_.begin(); itr != this->chessMap_.end(); ++itr) { ChessPiece* piece = itr->second; Sprite dummy = piece->getSprite(); IntRect d = dummy.getTextureRect(); Vector2f vect = dummy.getPosition(); cout << itr->first << " " << vect.x << " " << vect.y << endl; cout << d.left << " " << d.top << endl; cout << endl; } } ChessField::ChessField() { //Dynamically allocate within memory //1. YELLOW ROOK -1. WHITE ROOK //2. YELLOW KNIGHT -2. WHITE KNIGHT //3. YELLOW BISHOP -3. WHITE BISHOP //4. YELLOW QUEEN -4. WHITE QUEEN //5. YELLOW KING -5. WHITE KING //6. YELLOW PAWN -6. WHITE PAWN //Note: 2D array in C++ is just an array of pointers to 1D array this->chessArray = new int*[ROW]; if (this->chessArray == nullptr) { std::cerr << "Error: Unable to allocate 2D chessArray in the heap" << std::endl; } //Allocate individual array to each pointer for (int i = 0; i < ROW; ++i) { this->chessArray[i] = new int[COLUMN]; if (this->chessArray[i] == nullptr) { std::cerr << "Error: Unable to allocate memory for 1D chessArray" << std::endl; } } //Define the chess matrix based on the piece coordinate //1. Yellow Pieces this->chessArray[0][0] = 1; //YELLOW ROOK this->chessArray[0][1] = 2; //YELLOW KNIGHT this->chessArray[0][2] = 3; //YELLOW BISHOP this->chessArray[0][3] = 4; //YELLOW QUEEN this->chessArray[0][4] = 5; //YELLOW KING this->chessArray[0][5] = 3; //YELLOW BISHOP this->chessArray[0][6] = 2; //YELLOW KNIGHT this->chessArray[0][7] = 1; //YELLOW ROOK for (int i = 0; i < ROW; ++i) { this->chessArray[1][i] = 6; //YELLOW PAWN } //2. Empty spaces in between for (int i = 2; i < ROW - 2; ++i) { for (int j = 0; j < COLUMN; ++j) { this->chessArray[i][j] = 0; //VOID } } //2. White Pieces for (int i = 0; i < ROW; ++i) { this->chessArray[6][i] = -6; //WHITE PAWN } this->chessArray[7][0] = -1; //WHITE ROOK this->chessArray[7][1] = -2; //WHITE KNIGHT this->chessArray[7][2] = -3; //WHITE BISHOP this->chessArray[7][3] = -4; //WHITE QUEEN this->chessArray[7][4] = -5; //WHITE KING this->chessArray[7][5] = -3; //WHITE BISHOP this->chessArray[7][6] = -2; //WHITE KNIGHT this->chessArray[7][7] = -1; //WHITE ROOK */ } ChessField::~ChessField() { //Reverse deallocating. Deallocate 1D array first before //the array of pointer for (int i = 0; i < ROW; ++i) { delete[] chessArray[i]; } delete[] chessArray; //deallocating the chess map for (auto itr = this->chessMap_.begin(); itr != this->chessMap_.end(); ++itr) { delete itr->second; } } }
#include <sys/types.h> #include <sys/param.h> #include <dirent.h> #include <stdio.h> #include <string.h> #include <unistd.h> #include <sys/stat.h> #include <time.h> #include <stdlib.h> #include<vector> #include<string> using namespace std; struct node { string name; long long file_size=0; string dir; long int numc=0; // num of children std:: vector<struct node *> children;// max nodes }; long long listdir(struct node *); long int getsize(string path) { struct tm dt; struct stat stats; // returns 0 on successful operation, otherwise -1 if (stat(path.c_str(), &stats) == 0) { return stats.st_size;; } else { return 0; } } void TraverseTree (struct node *rt) { if(rt==NULL) return; for (int i=0;i< rt->numc;i++) { printf("%ld %s\n", rt->children[i]->file_size,(rt->children[i]->dir).c_str()); TraverseTree(rt->children[i]); } } int main() { // Directory path to list files struct node *rt=new node; rt->dir="/"; long int parent_dir_siz=listdir(rt); printf("dir is %s, size is %lld \n", rt->dir.c_str(), parent_dir_siz); printf("..................................................\n"); // TraverseTree(rt); return 0; } /** * Lists all files and sub-directories recursively * considering path as base path. */ long long listdir(struct node *rt) { string path; DIR *dir = opendir((rt->dir).c_str()); if(dir){ struct dirent *dp; while ((dp = readdir(dir)) != NULL) { if (strcmp(dp->d_name, ".") != 0 && strcmp(dp->d_name, "..") != 0 && dp->d_type != DT_LNK) { // create new node struct node* temp= new node; // printf("%s\n", rt->dir); path =(rt->dir)+"/"+string(dp->d_name); temp->dir=path; rt->numc++; temp->name=dp->d_name; temp->file_size=getsize(path); rt->children.push_back(temp); if(dp->d_type==DT_REG) { rt->file_size +=getsize(path); } if(dp->d_type==DT_DIR) rt->file_size+=listdir(temp); } } closedir(dir); } return rt->file_size; }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) Opera Software ASA 2009-2011 * * WebGL GLSL compiler -- dumping outputs. * */ #ifndef WGL_PRINTER_CONSOLE_H #define WGL_PRINTER_CONSOLE_H #include "modules/webgl/src/wgl_printer.h" #include "modules/util/opstring.h" class WGL_ConsolePrinter : public WGL_Printer { public: WGL_ConsolePrinter(const uni_char *url, OpString *log_output, BOOL use_console, BOOL gl_es, BOOL high_prec) : WGL_Printer(gl_es, high_prec) , log_output(log_output) , use_console(use_console) , url(url) { } virtual void OutInt(int i); virtual void OutDouble(double d); virtual void OutBool(BOOL b); virtual void OutString(const char *s); virtual void OutString(uni_char *s); virtual void OutString(const uni_char *s); virtual void OutStringId(const uni_char *s); virtual void OutString(WGL_VarName *s); virtual void OutNewline(); virtual void Flush(BOOL as_error); private: OpString out_buffer; OpString *log_output; BOOL use_console; const uni_char *url; }; #endif // WGL_PRINTER_CONSOLE_H
/********************************************** **Description: Implementation file of Person ***********************************************/ #include "Person.hpp" Person::Person(std::string nameIn, double ageIn){ //constructor name = nameIn; age = ageIn; } std::string Person::getName(){ //This function return name of string type return name; } double Person::getAge(){ //This funtion return age of double type return age; }
#include <bits/stdc++.h> #define REP(i, a, n) for(ll i = ((ll) a); i < ((ll) n); i++) using namespace std; typedef long long ll; vector<string> split(string s, string p) { vector<string> ret; ll h = 0; REP(i, 0, s.size() - p.size() + 1) if(s.substr(i, p.size()) == p) { ret.push_back(s.substr(h, i - h)); h = i + p.size(); i += (ll) p.size() - 1; } ret.push_back(s.substr(h, (ll) s.size() - h)); return ret; } int main(void) { string s = "apple<!>banana<!>orange<!>potato<!><!>tomato<!><!><!>fish<!>"; vector<string> sp = split(s, "<!>"); assert(sp.size() == 10); string expect[] = { "apple", "banana", "orange", "potato", "", "tomato", "", "", "fish", "" }; REP(i, 0, sp.size()) assert(sp[i] == expect[i]); }
#ifndef Tone_h #define Tone_h class Tone { public: Tone() : toneOutput(-1) {}; void attach(uint8_t pin, unsigned int frequency, unsigned long duration_in_msec = 0); void detach(uint8_t pin); void handler(); private: int8_t toneOutput; uint32_t toneToggleCount; }; void tone(uint8_t pin, unsigned int frequency, unsigned long duration_in_msec = 0); void noTone(uint8_t pin); extern "C" void tone_handler(void); extern Tone toneGenerator; #endif
#include <iostream> #include <cstdio> #include <algorithm> #include <vector> #include <functional> #include <queue> #include <string> #include <cstring> #include <numeric> #include <cstdlib> #include <cmath> using namespace std; typedef long long ll; #define INF 10e17 // 4倍しても(4回足しても)long longを溢れない #define rep(i,n) for(int i=0; i<n; i++) #define rep_r(i,n,m) for(int i=m; i<n; i++) #define END cout << endl #define MOD 1000000007 #define pb push_back #define sorti(x) sort(x.begin(), x.end()) #define sortd(x) sort(x.begin(), x.end(), std::greater<int>()) int main() { vector<int> a(5); rep(i,5) { cin >> a[i]; } sorti(a); ll ans = 10000000; do { ll temp = 0; int cnt = 0; for (auto itr : a) { cnt += 1; if (itr % 10 != 0 and cnt != 5) { temp += itr + (10 - itr % 10); } else { temp += itr; } } ans = min<ll>(ans, temp); } while(next_permutation(a.begin(), a.end())); cout << ans << endl; }
//: C10:SimpleStaticMemberFunction.cpp // Kod zrodlowy pochodzacy z ksiazki // "Thinking in C++. Edycja polska" // (c) Bruce Eckel 2000 // Informacje o prawie autorskim znajduja sie w pliku Copyright.txt class X { public: static void f(){}; }; int main() { X::f(); } ///:~
/* filename: moitemset.h author: Sherri Harms last modified: 7/20/01 description: Class moitemset implementations for parallel episodes. This is the implementation FILE moitemset.cpp for the class moitemset. Values of this type are sets of moitem pointers, where an moitem is a composite of episode, support, and a list of occurrences This implementation uses vectors for the moitemset. ****************************************************************************** Known bugs: The constraints are all disjuctive singular events. (need to add Step 5 from alg 5) input validation is not done ******************************************************************************* Local Data Structures: vector<moitemset> split_fac - used in the representative morule generation process has the items from fa and fc, separated by total length of the ant & cons. combined ***************************************************************************** moitemset operations include: output, constructors, clear, insertitem, generate parallel moitemset fc[k], generate serial moitemset fc[k], generate candicates fcc[k+1], and moitemset operations used in generating the representative episodal association rules. *******************************************************************************/ #ifndef moITEMSET_H #define moITEMSET_H #include "event.h" #include "moitem.h" #include "moparallelitem.h" #include "moserialitem.h" #include "mop_ruleitem.h" #include "mos_ruleitem.h" #include "moserialrule.h" #include "moserialruleset.h" #include "morule.h" #include "moruleset.h" #include "timer.h" #include <vector> #include <algorithm> #include <iostream> #include <fstream> using namespace std; typedef vector<moitem> moitem_set; typedef vector<event> event_set; typedef vector<event> event_vec; typedef vector<event_vec> event_vec_vec; typedef vector<event_vec>::const_iterator const_event_vec_vec_ITR; typedef deque<event> event_deque; typedef vector<moitem *> moitem_vec; typedef vector<moitem *>::iterator moITEM_ITR; typedef vector<moitem *>::const_iterator const_moITEM_ITR; typedef vector<moitem *>::reverse_iterator rmoITEM_ITR; typedef vector<moitem *>::const_reverse_iterator rconst_moITEM_ITR; typedef vector<moITEM_ITR> int_vec; typedef vector<moitemset> fc_type; //╩▓├┤╩ăitemset? class moitemset { public: void cleanup(); //delete the used memory in the process of clearing the itemset; static void setantlargest(int in_size) {largest_ant_size=in_size;} //Description: static function to set the size of the largest item in all itemsets //Precondition:in_size is valid integer >0 //Postcondition: largest_item_size has its value set static int seeantlargest() {return largest_ant_size;} //Description: accessor function for largest_item_size static void setconslargest(int in_size) {largest_cons_size=in_size;} //Description: static function to set the size of the largest item in all itemsets //Precondition:in_size is valid integer >0 //Postcondition: largest_item_size has its value set static int seeconslargest() {return largest_cons_size;} //Description: accessor function for largest_item_size static void setnum_records(int in_size) {num_records=in_size;} //Description: static function to set the number of records //Precondition:in_size is valid integer >0 //Postcondition: num_records has its value set static void incrnum_records(int in_size) {num_records+=in_size;} //Description: static function to add to the number of records //Precondition:in_size is valid integer >0 //Postcondition: num_records has its value set static void decrnum_records(int in_size) {num_records-=in_size;} //Description: static function to subtract to the number of records //Precondition:in_size is valid integer >0 //Postcondition: num_records has its value set static int seenum_records() {return num_records;} //Description: accessor function for num_records void clear(); //Description: clear the moitemset - back to an empty moitemset void insertitem(moitem* p); //Description: add the moitem pointer p to the moitemset //Preconditon: moitem pointer p must point to a existing valid moitem void get_parallel_episodes(const event_set& B); //Description: Add to the moitemset an moitem for each event in F that matches the constraints in B //Precondition: event_set B contains the events that meet the constraints //CHANGE when using DNF constraints void get_serial_episodes(const event_set& B); //Description: Add to the moitemset an moitem for each event in F that matches the constraints in B //Precondition: event_set B contains the events that meet the constraints //CHANGE when using DNF constraints // void get_time_stamp_episodes(const event_vec_vec& TimeFvec, const moitemset& fc_k, const event_set& B, int sources); t_stamp_vec accessitems() const; //return the list of episodes as a vector of timestamps // void resetfreqs(); //reset freqs - used when getting the first timestamp serial episodes moitem* get_first_item() const; //Return a pointer to the first moitem in the moitemset // void convert(const t_stamp_vec& TimeF); event_set getevents() const; void bringinnew(const event& E, int t); //reads in the new events at the current time stamp //called in the read new data process void addtimestampitems(const event_vec_vec& TimeFvec, const event_set& B, int sources, int win); // void addtimestampitems(int min_fr); //add timestamp items, used for serial processing // void bringinnewserial(const event& E, int t); //reads in the new events at the current time stamp //called in the read new data process void addfreq(moitemset& fcc_k_b, moitemset& garbage, int min_fr); //add the frequent candidates to the frequent item set, add the infrequent to garbage void Gen_mo(moitemset& fc_k_b, int k, char type); //generate the fc[k] moitemset for parallel and serial items //see the published algorithm //CHANGE when constraints are converted to DNF // void Gen_Parallel_mo(moitemset& fc_k_b, int k, char type); // void Gen_Serial_mo(moitemset& fc_k_b, int k, char type); //generate the fc[k] moitemset for serial items //see the published algorithm //CHANGE when constraints are converted to DNF void Update_Support(int win); //count how many minimal occurrences occur within the win width void fast_generate_parallel_candidates(moitemset& fc_k_b, char type, int k); //generate the next set of candidates from fc_k_b crossed with F, for a given type, //also used to generate candidates from the morule-generation process, which generates base items. void fast_generate_serial_candidates(moitemset& fc_k_b, char type, int k); //generate the next set of candidates from fc_k_b crossed with F, for a given type, //also used to generate candidates from the morule-generation process, which generates base items. void generate_parallel_candidates(const moitemset& fc_k_b, char type, const event_set& B, int k); //generate the next set of candidates from fc_k_b crossed with B //also used to generate candidates from the morule-generation process, which generates base items. //CHANGE when constraints are converted to DNF void generate_serial_candidates(const moitemset& fc_k_b, char type, const moitemset& B1, int k); //generate the next set of candidates from fc_k_b crossed with constraints B //also used to generate candidates from the morule-generation process, which generates base items. //CHANGE when constraints are converted to DNF void fast_generate_parallel_rule_candidates(moitemset& f_l, const moitem* Z, char type, int l); void generate_parallel_rule_candidates(const moitemset& A, const moitem* Z, char type, const event_set& B, int k); //generate the subsets of serial moitem Z, that meet constraints B //used only from the morule-generation process. //CHANGE when constraints are converted to DNF void fast_generate_serial_rule_candidates(moitemset& f_l, const moitem* Z, char type, int l); void generate_serial_rule_candidates(const moitemset& A, const moitem* Z, char type, moitemset B1, int k); //generate the subsets of serial moitem Z, that meet constraints B //used only from the morule-generation process. //CHANGE when constraints are converted to DNF moitem* findsmallest(const fc_type& fc, const moitem* X) const; //used in the representative morule generation process to find the smallest //episode that contains moitem X from all of the itemsets void combine(const moitemset& fa, moitemset& garbage, const fc_type& fc, char type, int lag, int min_fr, char lag_type); //combine the ant and cons into ruleitems void putinsplit(fc_type& split_fc, int& k) const; void loop1parallel(const fc_type& split_fc, double c, moruleset& REAR, int i, int k, char type, const event_set& T, const event_set& C); //the outer loop used in the representative morule generation process //called from the main program as: split_fc[i].loop1(split_fc, min_conf, REAR, i, k, type, B); void loop1serial(const fc_type& split_fc, double c, mos_ruleset& REAR, int i, int k, char type, const event_set& T, const event_set& C); //the outer loop used in the representative morule generation process //called from the main program as: split_fc[i].loop1(split_fc, min_conf, REAR, i, k, type, B); void addrules(double c, moruleset& REAR, int i); void addrules(double c, mos_ruleset& REAR, int i); double computelevelsupport(const moitem* Z) const; // used in the representative morule generation process //when working with one moitem Z, //called from an moitem's get_max_support member function //to find the frequency for an episode that contains moitem Z // at this closure length (or level) //get the max support = support of a larger episode that contains this episode if there is one, otherwise 0 bool does_contain_parallel(const moitem* Y) const; bool does_contain_parallel_rule_item(const moitem* Y) const; bool does_contain_serial_rule_item(const moitem* Y) const; bool does_contain_serial(const moitem* Y) const; //return true if the calling moitemset contains moitem Y //called in the candidate generation process bool empty() const; //return true if the moitemset is empty int access_size() const; int access_num_records() const; void output(ostream& outs) const; void output_episodes(ostream& outs) const; moitemset( ); //Constructor. ~moitemset(){ // delete timer; } friend ostream& operator << (ostream& outs, const moitemset& the_object); //Overloads the << operator for output values of type moitemset. //Precondition: If outs is a file output stream, then outs as //already been connected to a file. void setTimer(Timer* t); //Sets this objects timer data member. private: bool matchp(moitem* cand, char type) const; //return true if the candidate is a parallel injunctive episode //called in the candidate generation process //calls the individual moitem matchp member function bool matchs(moitem* cand, char type) const; //return true if the candidate is a serial injunctive episode //called in the candidate generation process //calls the individual moitem matchs member function bool support_subs_parallel(const moitem* Y, const moitemset& fc_k_b, int k) const; bool support_subs_serial(const moitem* Y, const moitemset& fc_k_b, int k) const; //return true if the moitemset fc_k_b contains all k sized subsets of Y //called in the candidate generation process moitem_vec is; static int largest_ant_size; static int largest_cons_size; static int num_records; static int indexofA(const event& A, const event_set& f_list, int size); static int indexoftimeA(const time_stamp& A, const t_stamp_vec& TimeF, int size); Timer* timer; }; #endif //ITEM_H
// // 11651.cpp // baekjoon // // Created by 최희연 on 2021/07/09. // #include <iostream> #include <vector> #include <algorithm> using namespace std; bool comp(pair<int, int> a, pair<int, int>b){ if(a.second==b.second) return a.first<b.first; else return a.second<b.second; } int main(){ int n; scanf("%d", &n); vector<pair<int, int>> v; for(int i=0;i<n;i++){ int tmp1, tmp2; scanf("%d %d", &tmp1, &tmp2); v.push_back(make_pair(tmp1, tmp2)); } sort(v.begin(), v.end(), comp); for(int i=0;i<v.size();i++){ printf("%d %d\n", v[i].first, v[i].second); } }
#include "Polygon.h" #include <algorithm> #include <cmath> #include <functional> #include <vector> #include <utility> double Polygon::edgeLen(const Vertex& v1, const Vertex& v2) { double x = v2.x - v1.x; double y = v2.y - v1.y; return sqrt(x*x + y*y); } double Polygon::minTriangulationP(std::vector<std::vector<std::pair<double, size_t>>> &subtasks, size_t i, size_t j) const noexcept { if (subtasks[i][j].first >= 0) return subtasks[i][j].first; if (j - i == 1) return subtasks[i][j].first = edgeLen(vertexes[i], vertexes[j]); if (j - i == 2) { double triangleP = edgeLen(vertexes[i ], vertexes[i+1]); triangleP += edgeLen(vertexes[i ], vertexes[i+2]); triangleP += edgeLen(vertexes[i+1], vertexes[i+2]); return subtasks[i][j].first = triangleP; } double minP = std::numeric_limits<double>::infinity(); size_t minPk = 0; for (size_t k = i+1; k < j; ++k) { double P = edgeLen(vertexes[i], vertexes[j]); P += minTriangulationP(subtasks, i, k); P += minTriangulationP(subtasks, k, j); if (P < minP) { minP = P; minPk = k; } } subtasks[i][j].second = minPk; return subtasks[i][j].first = minP; } double Polygon::triangulation(std::vector<Edge> &answer) const { std::vector<std::vector<std::pair<double, size_t>>> subtasks(vertexes.size(), std::vector<std::pair<double, size_t>>(vertexes.size(), std::pair<double, size_t>(-1, 0))); double minP = minTriangulationP(subtasks, 0, vertexes.size() - 1); std::function<void(size_t,size_t)> restoreAnswer = [&](size_t i, size_t j) { size_t minPk = subtasks[i][j].second; if (j - i < 3) return; if (minPk - i > 1) answer.push_back(std::make_pair(vertexes[i], vertexes[minPk])); if (j - minPk > 1) answer.push_back(std::make_pair(vertexes[minPk], vertexes[j])); restoreAnswer(i, minPk); restoreAnswer(minPk, j); }; restoreAnswer(0, vertexes.size() - 1); return minP; }; double Polygon::P() const noexcept { double P = edgeLen(*vertexes.begin(), *std::next(vertexes.end(), -1)); for (auto i = vertexes.begin(); i != std::next(vertexes.end(), -1); ++i) P += edgeLen(*i, *std::next(i)); return P; }
#include <iostream> using namespace std; class B { public: B() : a(1) { } void aa(int a) { ; } int a; }; class d : public B { public: void aa(int a, int b) { ; } }; int main(void) { B *b = new d; cout << b->a << endl; return 0; }
#include<cstdio> #include<iostream> #include<algorithm> #include<vector> #include<cstring> #include<cmath> using namespace std; #define maxn 105 struct edge{ int from,to,cost; }; int d[maxn]; vector<edge> es; int V,E; void bellman_ford(int s){ // printf("get in b_f \n"); for(int i=1;i<=V;i++) d[i]=-1; d[s]=10000000; // printf("s=%d V=%d\n",s,V); while(true){ bool update=false; for(int i=0;i<2*E;i++){ edge e=es[i]; // printf("from=%d to=%d cost=%d\n",e.from,e.to,e.cost); // printf("d:::from=%d to=%d cost=%d\n",d[e.from],d[e.to],e.cost); if(d[e.from]!=-1&&d[e.to]<min(d[e.from],e.cost)){ d[e.to]=min(d[e.from],e.cost); // cout<<"updated!!"<<endl; // printf("up::d:::from=%d to=%d cost=%d\n",d[e.from],d[e.to],e.cost); update=true; } } if(!update) break; } } int cnt=1; int main(){ while(scanf("%d%d",&V,&E)){ if(V==0&&E==0) break; edge te; for(int i=1;i<=E;i++){ scanf("%d%d%d",&te.from,&te.to,&te.cost); es.push_back(te); edge te2; te2.from=te.to; te2.to=te.from; te2.cost=te.cost; es.push_back(te2); } int start,ends,people; scanf("%d%d%d",&start,&ends,&people); bellman_ford(start); // printf("aaaaaaa\n"); printf("Scenario #%d\n",cnt); // printf("d[ends]=%d\n",d[ends]); int times=ceil(people*1.0/((d[ends]-1)*1.0)); printf("Minimum Number of Trips = %d\n\n",times); cnt++; es.clear(); } return 0; }
/** * **/ #pragma once #include <iostream> #include <netinet/in.h> #include <time.h> static const int BUFFER_SIZE = 64; struct HeapTimerNode { HeapTimerNode(int delay, void (*cbf)(void*), void *data): cbFunc(cbf), userData(data) { expire = time(NULL) + delay; } time_t expire; void (*cbFunc)(void*); void *userData; }; class CHeapTimer { public: CHeapTimer(int cap): m_capacity(cap), m_curSize(0) { m_heap = new HeapTimerNode*[m_capacity]; for(int i = 0; i < m_capacity; ++i) { m_heap[i] = NULL; } } ~CHeapTimer() { if( m_heap ) { for(int i = 0; i < m_curSize; ++i) { delete m_heap[i]; } delete[] m_heap; } } bool Empty() const { return m_curSize == 0; } HeapTimerNode* Top() const { return Empty() ? NULL : m_heap[0]; } void PopTimer() { if( Empty() ) { return; } if( m_heap[0] ) { delete m_heap[0]; m_heap[0] = m_heap[--m_curSize]; PercolateDown(0); } } void Tick() { HeapTimerNode *tmp = m_heap[0]; time_t cur = time(NULL); while( !Empty() ) { if( !tmp ) { break; } if( tmp->expire > cur ) { break; } if( tmp->cbFunc ) { tmp->cbFunc(tmp->userData); } PopTimer(); tmp = m_heap[0]; } } HeapTimerNode* AddTimer(time_t expire, void (*cbf)(void*), void *data) { if( m_curSize >= m_capacity ) { Resize(); } int hole = m_curSize++, parent = 0; for(;hole > 0; hole = parent) { parent = (hole - 1) / 2; if( m_heap[parent]->expire <= expire ) { break; } m_heap[hole] = m_heap[parent]; } m_heap[hole] = new HeapTimerNode(expire, cbf, data); return m_heap[hole]; } // lazy delete void DelTimer(HeapTimerNode *timer) { if( timer ) { timer->cbFunc = NULL; } } private: int Resize() { HeapTimerNode **tmp = new HeapTimerNode[2 * m_capacity]; if( tmp == NULL ) { return -1; } m_capacity *= 2; for(int i = 0; i < m_capacity; ++i) { tmp[i] = NULL; } for(int i = 0; i < m_curSize; ++i) { tmp[i] = m_heap[i]; } delete[] m_heap; m_heap = tmp; } void PercolateDown(int root) { int child = 0; HeapTimerNode *tmp = m_heap[root]; for(; (root * 2 + 1) <= (m_curSize - 1); root = child) { child = root * 2 + 1; if( child < (m_curSize - 1) && m_heap[child]->expire > m_heap[child + 1]->expire ) { child += 1; } if( m_heap[child]->expire < tmp->expire ) { m_heap[root] = m_heap[child]; } else { break; } } m_heap[root] = tmp; } int m_capacity; int m_curSize; HeapTimerNode **m_heap; };
// Created on: 1999-06-30 // Created by: Sergey ZARITCHNY // Copyright (c) 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 _TNaming_Translator_HeaderFile #define _TNaming_Translator_HeaderFile #include <Standard.hxx> #include <Standard_DefineAlloc.hxx> #include <TColStd_IndexedDataMapOfTransientTransient.hxx> #include <TopTools_DataMapOfShapeShape.hxx> class TopoDS_Shape; //! only for Shape Copy test - to move in DNaming class TNaming_Translator { public: DEFINE_STANDARD_ALLOC Standard_EXPORT TNaming_Translator(); Standard_EXPORT void Add (const TopoDS_Shape& aShape); Standard_EXPORT void Perform(); Standard_EXPORT Standard_Boolean IsDone() const; //! returns copied shape Standard_EXPORT const TopoDS_Shape Copied (const TopoDS_Shape& aShape) const; //! returns DataMap of results; (shape <-> copied shape) Standard_EXPORT const TopTools_DataMapOfShapeShape& Copied() const; Standard_EXPORT void DumpMap (const Standard_Boolean isWrite = Standard_False) const; protected: private: Standard_Boolean myIsDone; TColStd_IndexedDataMapOfTransientTransient myMap; TopTools_DataMapOfShapeShape myDataMapOfResults; }; #endif // _TNaming_Translator_HeaderFile
/* GTASA C++ SDK See README.md for more details DK22Pac, 2015 */ #pragma once #include <vector> namespace plugin { template <typename T> class ExtenderInterface { public: virtual void AllocateBlocks() = 0; virtual void OnConstructor(T *object) = 0; virtual void OnDestructor(T *object) = 0; }; template <typename T> class ExtendersHandler { protected: static std::vector<ExtenderInterface<T> *> extenders; static bool injected; static void Allocate() { for (auto &i : extenders) i->AllocateBlocks(); } static void Constructor(T *object) { for (auto &i : extenders) i->OnConstructor(object); } static void Destructor(T *object) { for (auto &i : extenders) i->OnDestructor(object); } }; };
#include <iostream> using namespace std; int main(void) { int n; int people[11] = { 0, }; int res[11] = { 0, }; cin >> n; for (int i = 0; i < n; i++) { cin >> people[i]; } for (int i = 0; i < n; i++) { } return 0; }
#include <iostream> #include <fstream> using namespace std; //don't understand this part char getTile(int x, int y, unsigned char data[], int size, int w, int h); // how to know what kind of parameters do we need in this? int writeBytes(int offset, unsigned char data[]); int main() { ifstream map("8x8flipped.bmp"); //NEED TO FLIP ROW ORDER IN PS! otherwise counts from bottom const int BMPSIZE = 248; //actual size in bytes of the bmp file unsigned char bmpBytes[BMPSIZE]; //array of 8-bit integers to store our bytes unsigned char data; //variable to store temporary bytes int whichByte = 0; while (map >> data) { //as long as the file has bytes, plug it into the array bmpBytes[whichByte] = data; whichByte++; } map.close(); const int w = 8; const int h = 8; char grid[h][w]; //load tiles for (int i = 0; i < h; i++) { for (int j = 0; j < w; j++) { grid[j][i] = getTile(j,i,bmpBytes,BMPSIZE,w,h); } } //game loop while(true) { //draw game board cout << "\n\n\n\n"; cout << "MATCH3! Press Control-C to quit."; cout << "\n\n\n\n"; cout << "\t 0 1 2 3 4 5 6 7\n"; cout << "\t ===============\n"; for (int i = 0; i < h; i++) { for (int j = 0; j < w; j++) { if (j == 0) { cout << "\t" << i << " || "; } cout << grid[j][i] << " "; } cout << endl; } cout << "\n\n"; //user input int inputX; int inputY; int inputSwapX; int inputSwapY; cout << "\tPick x coord: "; cin >> inputX; while(inputX<0 || inputX >w){ cout << "\tInvalid entry\n"; cout << "\tPick a valid value:"; cint>>inputX; } cout << "\tPick y coord: "; cin >> inputY; while(inputY<0 || inputY >h){ cout << "\tInvalid entry\n"; cout << "\tPick a valid value:"; cint>>inputX; } cout << "\tSwap which x coord: "; cin >> inputSwapX; while(inputSwapX< inputSwapX-1 || inputSwapX >inputSwapX+1){ cout << "\tInvalid entry\n"; cout << "\tPick a valid value:"; cint>>inputX; } cout << "\tSwap which y coord: "; cin >> inputSwapY; while(inputSwapY<inputSwapY-1 || inputSwapY > inputSwapY+1){ cout << "\tInvalid entry\n"; cout << "\tPick a valid value:"; cint>>inputX; } if(inputX == inputSwapX && inputY == inputSwapY){ cout<<"\n\n Cant' swapt with itself!\n"; continue; } //swap grid positions! //STUDENTS: make sure you can only swap with ADJACENT positions //method 1 // char temp; // if (inputSwapX == inputX && inputSwapY != inputY){ // if(inputSwapY == inputY +1 || inputSwapY == inputY -1){ // temp = grid[inputX][inputY]; // grid[inputX][inputY] = grid[inputSwapX][inputSwapY]; // grid[inputSwapX][inputSwapY] = temp; // } // }else if (inputSwapX != inputX && inputSwapY == inputY){ // if(inputSwapX == inputX +1 || inputSwapX == inputX -1){ // temp = grid[inputX][inputY]; // grid[inputX][inputY] = grid[inputSwapX][inputSwapY]; // grid[inputSwapX][inputSwapY] = temp; // } // }else if(inputSwapX == inputX && inputSwapY == inputY){ // cout << "\nYou need 2 different positions to swap.\n"; // } // else{ // cout << "\nPlease only choose adjacent positions to swap.\n"; // } // cout<<endl; // method 2: // char temp; // if (inputSwapX == inputX && inputSwapY == inputY + 1){ // temp = grid[inputX][inputY]; // grid[inputX][inputY] = grid[inputSwapX][inputSwapY]; // grid[inputSwapX][inputSwapY] = temp; // }else if (inputSwapX == inputX && inputSwapY == inputY - 1){ // temp = grid[inputX][inputY]; // grid[inputX][inputY] = grid[inputSwapX][inputSwapY]; // grid[inputSwapX][inputSwapY] = temp; // }else if (inputSwapX == inputX +1 && inputSwapY == inputY){ // temp = grid[inputX][inputY]; // grid[inputX][inputY] = grid[inputSwapX][inputSwapY]; // grid[inputSwapX][inputSwapY] = temp; // }else if (inputSwapX == inputX -1 && inputSwapY == inputY){ // temp = grid[inputX][inputY]; // grid[inputX][inputY] = grid[inputSwapX][inputSwapY]; // grid[inputSwapX][inputSwapY] = temp; // }else{ // cout << "\nPlease only choose adjacent positions to swap.\n"; // } // cout<<endl; //check for matches: //STUDENTS: (advanced) - to do this properly you'll need a recursive function. int matches = 0; for (int i = 0; i < h; i++) { for (int j = 0; j < w; j++) { if(grid[inputX][inputY] == grid[inputX+i][inputY+j]){ matches++; cout << "match on " << inputX+i<< ", " << inputY+j << endl; } if (grid[inputSwapX][inputSwapY] == grid[inputSwapX+i][inputSwapY+j]) { matches++; cout << "match on " << inputSwapX+i << ", " << inputSwapY+j << endl; } } } match(inputX, inputY, matches); matches ++; if (matches >= 2) { // destroy everything around the original swap position. // STUDENTS: try making it destroy only the tiles matching it. for (int i = -1; i < 2; i++) { for (int j = -1; j < 2; j++) { if(inputX+i >=0 && inputX+i < w && inputY+j >=0 && inputY +j){ if(grid[inputX+i][inputY+j] == grid[inputX][inputY]){ // BEGINNER STUDENTS: make sure it doesn't go off the grid! // right now we can escape the grid entirely by accessing a negative position on the array! grid[inputX+i][inputY+j] = ' '; } } if(inputSwapX+i >=0 && inputSwapX+i < w && inputSwapY+j >=0 && inputSwapY +j){ if(grid[inputSwapX+i][inputSwapY+j] == grid[inputSwapX][inputSwapY]){ // BEGINNER STUDENTS: make sure it doesn't go off the grid! // right now we can escape the grid entirely by accessing a negative position on the array! grid[inputSwapX+i][inputSwapY+j] = ' '; } } } } }else { //BEGINNER STUDENTS: make it swap back! temp = grid[inputX][inputY]; grid[inputX][inputY] = grid[inputSwapX][inputSwapY]; grid[inputSwapX][inputSwapY]= temp; } //ALL STUDENTS: //add a win state //try other mechanics, for example: //match only 1 //try fewer types of tiles //try 16x16 instead of 8x8 for(int i =0; i < w; i++){ for(int j =0; j < h; j++){ if(grid[i][j] == " "){ cout<< "Congratulations! You win!!\n" }cout<<endl; } } //ADVANCED STUDENTS: //add a lose state //make remaining tiles fall down if there is empty space } return 0; } char getTile(int x, int y, unsigned char data[], int size, int w, int h) { int r = 0; int g = 0; int b = 0; int i = 54 + (y * w + x) * 3; //each row has to add up to a multiple of four bytes. int numBytesPerRow = w * 3; int paddingValue = numBytesPerRow % 4; // cout << y * (4-paddingValue) << "\t"; if (paddingValue != 0) { i += y * (4-paddingValue); } b = writeBytes(i,data); g = writeBytes(i+1,data); r = writeBytes(i+2,data); // cout << "x: " << x << ", y: " << y; // cout << "\t- " << r << ", " << g << ", " << b << "\n"; if (r == 255 && g == 0 && b == 0) { //red return 'O'; } else if (r == 0 && g == 255 && b == 0) { //green return 'X'; } else if (r == 0 && g == 0 && b == 255) { //blue return '.'; } else if (r == 255 && g == 0 && b == 255) { //purple return '#'; } else if (r == 255 && g == 255 && b == 0) { //yellow return '?'; } else { return ' '; } } //why do we need the writeBytes? int writeBytes(int offset, unsigned char data[]) { return data[offset]; }
constexpr int maxn = 262144; constexpr int mod = 998244353; using i64 = long long; using poly_t = int[maxn]; using poly = int *const; inline void derivative(const poly &h, const int n, poly &f) { for (int i = 1; i != n; ++i) f[i - 1] = (i64)h[i] * i % mod; f[n - 1] = 0; } inline void integrate(const poly &h, const int n, poly &f) { for (int i = n - 1; i; --i) f[i] = (i64)h[i - 1] * inv[i] % mod; f[0] = 0; /* C */ } void polyln(const poly &h, const int n, poly &f) { /* f = ln h = ∫ h' / h dx */ assert(h[0] == 1); static poly_t ln_t; const int t = n << 1; derivative(h, n, ln_t); std::fill(ln_t + n, ln_t + t, 0); polyinv(h, n, f); DFT(ln_t, t); DFT(f, t); for (int i = 0; i != t; ++i) ln_t[i] = (i64)ln_t[i] * f[i] % mod; IDFT(ln_t, t); integrate(ln_t, n, f); } void polyexp(const poly &h, const int n, poly &f) { /* f = exp(h) = f_0 (1 - ln f_0 + h) */ assert(h[0] == 0); static poly_t exp_t; std::fill(f, f + n + n, 0); f[0] = 1; for (int t = 2; t <= n; t <<= 1) { const int t2 = t << 1; polyln(f, t, exp_t); exp_t[0] = sub(pls(h[0], 1), exp_t[0]); for (int i = 1; i != t; ++i) exp_t[i] = sub(h[i], exp_t[i]); std::fill(exp_t + t, exp_t + t2, 0); DFT(f, t2); DFT(exp_t, t2); for (int i = 0; i != t2; ++i) f[i] = (i64)f[i] * exp_t[i] % mod; IDFT(f, t2); std::fill(f + t, f + t2, 0); } }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 2000-2006 Opera Software ASA. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. ** ** Peter Karlsson */ #if !defined ACCESSORS_LNGLIGHT_H && defined PREFS_HAS_LNGLIGHT #define ACCESSORS_LNGLIGHT_H #include "modules/prefsfile/accessors/prefsaccessor.h" #include "modules/prefsfile/accessors/lng.h" /** * Simplified accessor for 4.0+ language files. This class is only * used from the UI to retrieve the language code and the name of * the language. It speeds the UI up by only storing those two values. */ class LangAccessorLight : public LangAccessor { public: LangAccessorLight() : LangAccessor(), m_hascode(FALSE), m_hasname(FALSE), m_hasbuild(FALSE), m_hasdb(FALSE), m_isinfoblock(FALSE) {}; /** * Retrieve information about this language file. * @param code ISO 639 language code (OUT). * @param name Name of language in its own language (OUT). * @param build Windows build number (OUT). * @return Any error from OpString. */ OP_STATUS GetFileInfo(OpString &code, OpString &name, OpString &build); /** * Retrieve the database version for this language file. * @return Any error from OpString. */ OP_STATUS GetDatabaseVersion(OpString &db_version); protected: virtual BOOL ParseLineL(uni_char *, PrefsMap *); private: OpString m_code, m_name, m_build, m_db; BOOL m_hascode, m_hasname, m_hasbuild, m_hasdb, m_isinfoblock; }; #endif // !ACCESSORS_LNGLIGHT_H && PREFS_HAS_LNGLIGHT
/* * Created by Peng Qixiang on 2018/8/1. */ /* * 二叉搜索树的后序遍历序列 * 输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历的结果。 * 如果是则输出Yes,否则输出No。假设输入的数组的任意两个数字都互不相同。 * */ # include <iostream> # include <vector> using namespace std; class Solution { public: bool VerifySquenceOfBST(vector<int> sequence){ if(sequence.empty()){ return false; } int index = 0, root = sequence.back(); vector<int> left, right; // find the bound between left and right subtree while(index < sequence.size() - 1){ if(sequence[index] < root){ index++; left.push_back(sequence[index]); continue; } else { break; } } for(int i = index; i < sequence.size() - 1; i++){ if(sequence[i] < root){ return false; } else{ right.push_back(sequence[i]); } } return (left.empty()? true : VerifySquenceOfBST(left)) && (right.empty()? true : VerifySquenceOfBST(right)); } //上述版本占用额外空间太多,其实只需保存两个index即可 bool judge(vector<int>& sequence, int start, int end){ if(start >= end){ return true; } //find the bound between left and right subtree int index = start; while(index < end ){ if(sequence[index] > sequence[end]){ break; } index++; } for(int i = index; i < end; i++){ if(sequence[i] < sequence[end]){ return false; } } return judge(sequence, start, index - 1) && judge(sequence, index, end - 1); } bool VerifySquenceOfBST1(vector<int> sequence){ if(sequence.empty()){ return false; } return judge(sequence, 0, sequence.size()-1); } }; int main(){ Solution s = Solution(); return 0; }
int ldr=A0; //Libraries needed #include <ESP8266WiFi.h> #include <NTPClient.h> #include <WiFiUdp.h> #include <FirebaseArduino.h> //Credentials for connection to firebase #define FIREBASE_HOST "smart-iv-hackon.firebaseio.com" #define FIREBASE_AUTH "" //Credentials for connection to Wi-Fi #define WIFI_SSID "Galaxy" #define WIFI_PASSWORD "ssingh9970" float sensorValue=0; boolean isEmpty; void setup() { Serial.begin(9600); WiFi.begin(WIFI_SSID, WIFI_PASSWORD); Serial.print("connecting"); while (WiFi.status() != WL_CONNECTED) { Serial.print("."); delay(500); } Serial.println(); Serial.print("connected: "); Serial.println(WiFi.localIP()); Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH); pinMode(D1,OUTPUT); pinMode(ldr,INPUT); } void loop() { sensorValue=analogRead(ldr); delay(100); Firebase.setFloat("/Room234/Bed10/",sensorValue); if(sensorValue<580) { isEmpty=false; Firebase.setBool("/Room234/Bed10/dripStatus",isEmpty); } if(sensorValue>580) { isEmpty=true; Firebase.setBool("/Room234/Bed10/dripStatus",isEmpty); tone(D1,200,300); } delay(100); }
#include "./platform/UnitTestSupport.hpp" #include "Dot++/src/lexer/states/ProduceToken.hpp" #include <Dot++/lexer/FileInfo.hpp> #include <Dot++/lexer/Token.hpp> #include <Dot++/lexer/TokenizerState.hpp> #include <Dot++/lexer/TokenInfo.hpp> #include <Dot++/lexer/TokenType.hpp> #include <deque> namespace { using namespace dot_pp::lexer; struct ProduceTokenFixture { ProduceTokenFixture() : info("test.dot") , token("abcdefg", TokenType::string) , token2("abc\nabc", TokenType::multiline_comment) { } FileInfo info; Token token; Token token2; std::deque<TokenInfo> tokens; }; TEST_FIXTURE(ProduceTokenFixture, verifyProduceTokenWithOneArgument) { CHECK_EQUAL(0U, tokens.size()); CHECK_EQUAL(TokenizerState::Init, states::produceToken(TokenizerState::Init, tokens, token, info)); REQUIRE CHECK_EQUAL(1U, tokens.size()); CHECK_EQUAL("abcdefg", tokens[0].token().to_string()); CHECK_EQUAL(TokenType::string, tokens[0].token().type()); CHECK_EQUAL(1U, tokens[0].fileInfo().start().line()); CHECK_EQUAL(1U, tokens[0].fileInfo().start().column()); CHECK_EQUAL(1U, tokens[0].fileInfo().end().line()); CHECK_EQUAL(8U, tokens[0].fileInfo().end().column()); CHECK_EQUAL(TokenizerState::Init, states::produceToken(TokenizerState::Init, tokens, token2, info, Token())); REQUIRE CHECK_EQUAL(2U, tokens.size()); CHECK_EQUAL("abc\nabc", tokens[1].token().to_string()); CHECK_EQUAL(TokenType::multiline_comment, tokens[1].token().type()); CHECK_EQUAL(1U, tokens[1].fileInfo().start().line()); CHECK_EQUAL(8U, tokens[1].fileInfo().start().column()); CHECK_EQUAL(2U, tokens[1].fileInfo().end().line()); CHECK_EQUAL(4U, tokens[1].fileInfo().end().column()); } }
#include "MyDLL.h" extern "C" int CalcSum_(int a, int b, int c); int sj() { int a = 17, b = 11, c = 14; int sum = CalcSum_(a, b, c); return sum; }
#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; typedef long long LL; int t[5010],v[5010],f[5010]; int main() { int n,m; scanf("%d%d",&m,&n); for (int i = 1;i <= n; i++) scanf("%d%d",&t[i],&v[i]); for (int i = 1;i <= n; i++) for (int j = m;j >= t[i]; j--) f[j] = max(f[j],f[j-t[i]]+v[i]); printf("%d\n",f[m]); return 0; }
#include <bits/stdc++.h> using namespace std; int main() { int students, team; cin>>students; cin>>team; int arr[students]; map <int, int>checker; //the meaning of this method is to check a data and the data type in list for(int i=0;i<students;i++) { cin>>arr[i]; checker[arr[i]]=i+1; } if(checker.size()< team) { cout<<"NO"; } else { cout<<"YES"<<endl; for(map<int,int>::iterator it=checker.begin(); it!=checker.end(),team>0;++it,team--) { cout<<it->second<<" "; } } return 0; }
#include <algorithm> #include <iostream> #include <string> #include <vector> using namespace std; #define LL long long #define SIZE(x) (int) x.size() #define PB(x) push_back(x) template<class E> class Edge : public E { private: int v; public: Edge(E e, int v) : E(e) { this->v = v; } int getV() { return this->v; } }; template<class V, class E> class Vertex : public V, public std::vector<Edge<E> > { // }; template<class V, class E> class Graph { private: std::vector<Vertex<V, E> > g; int t; public: Graph(int n = 0) : g(n) { } void edgeD(int b, int e, E d = E()) { g[b].PB(Edge<E>(d, e)); } vector<int> bfs(int s) { vector<int> r(SIZE(this->g), 0); for (typename std::vector<Vertex<V, E> >::iterator it = g.begin(); it != g.end(); it++) { it->setT(-1); it->setS(-1); } g[s].setT(0); int qu[SIZE(g)], b = 0, e = 0; qu[0] = s; while (b <= e) { int k = qu[b++]; for (typename std::vector<Edge<E> >::iterator it = g[k].begin(); it != g[k].end(); it++) { if (g[it->getV()].getT() == -1) { qu[++e] = it->getV(); g[it->getV()].setT(g[k].getT() + 1); g[it->getV()].setS(k); } if (g[k].getT() == 1) { r[it->getV()]++; } } } return r; } }; class Empty { }; class Ver { private: int t, s; public: void setT(int t) { this->t = t; } int getT() { return this->t; } void setS(int s) { this->s = s; } int getS() { return this->s; } }; int main() { ios_base::sync_with_stdio(0); cin.tie(NULL); int t, n, x; cin >> t; while (t --> 0) { cin >> n; Graph<Ver, Empty> g(n); for (int i = 0; i < n; i++) { for (int j = 0 ; j < n; j++) { cin >> x; if (x) { g.edgeD(i, j); } } } bool err = false; for (int i = 0; i < n; i++) { vector<int> r = g.bfs(i); for (int j = 0 ; j < n; j++) { cin >> x; if (r[j] != x && !err) { cout << "NIE\n"; err = true; } } } if (!err) { cout << "TAK\n"; } } return 0; }
#include <sys/time.h> #include "microtime.h" #define TEST 0 /* Set to 0 except when testing the code or timer resolution */ double get_microtime_resolution(void) { double time1, time2; time1 = microtime(); do { time2 = microtime(); } while (time1 == time2); return time2 - time1; } double microtime(void) { struct timeval t; gettimeofday(&t, 0); return 1.0e6 * t.tv_sec + (double) t.tv_usec; } #if TEST == 1 #include <stdio.h> int main(void) { unsigned long i, n=100000000; double result = 0.0, time1, time2; printf("Timer resolution = %g micro seconds\n", get_microtime_resolution()); time1 = microtime(); for(i = 1; i < n; i++) result += 1.0 / i; time2 = microtime(); printf("Time taken = %g seconds\n", (time2-time1)/1.0e6); return 0; } #endif
// // Created by askeynil on 2019/11/5. // #include "FeatureMatching.h" FeatureMatching::FeatureMatching(Mat &featureImg, Mat &checkImg, int nfeatures) : featureImgs({featureImg}), checkImg(checkImg), orb(ORB::create(nfeatures)) {} FeatureMatching::FeatureMatching(vector<Mat> &featureImgs, Mat &checkImg, int nfeatures) : featureImgs(featureImgs), checkImg(checkImg), orb(ORB::create(nfeatures)) {} void FeatureMatching::obtainPointsDesc(vector<vector<KeyPoint>> &featureKeyPoints, vector<KeyPoint> &checkPoints, vector<Mat> &featureDesc, Mat &checkDesc) { featureKeyPoints.clear(); featureDesc.clear(); for (const Mat &img: featureImgs) { vector<KeyPoint> keyPoints; Mat desc; orb->detectAndCompute(img, Mat(), keyPoints, desc); } orb->detectAndCompute(checkImg, Mat(), checkPoints, checkDesc); } void FeatureMatching::obtainPointsDesc(vector<KeyPoint> &featureKeyPoints, vector<KeyPoint> &checkPoints, Mat &featureDesc, Mat &checkDesc, int index) { if (index >= featureImgs.size()) throw domain_error("无效索引"); orb->detectAndCompute(featureImgs[index], Mat(), featureKeyPoints, featureDesc); orb->detectAndCompute(checkImg, Mat(), checkPoints, checkDesc); } void _match(const vector<Mat> &featureDesc, const Mat &checkDesc, vector<vector<DMatch>> &allMatches, int type, double percent, int leastNumber) { allMatches.clear(); DescriptorMatcher *matcher = nullptr; if (type == FeatureMatching::BF) { // 创建 BFMatcher matcher = new BFMatcher(NORM_HAMMING, true); } else if (type == FeatureMatching::FLANN) { auto indexPar = makePtr<flann::LshIndexParams>(6, 12, 1); // 检索参数,数值越大越准确,但是也越耗时 auto searchPar = makePtr<flann::SearchParams>(100); // 使用 indexPar 和 searchPar 创建 flannMatcher matcher = new FlannBasedMatcher(indexPar, searchPar); } else { throw domain_error("无效类型"); } for (const auto &i : featureDesc) { vector<DMatch> matches; // 使用 match 处理数据 matcher->match(i, checkDesc, matches); // 排序 sort(matches.begin(), matches.end()); // 对数据进行裁剪 int number = (int) (matches.size() * percent); number = max(number, leastNumber); // 裁剪 matches matches.assign(matches.begin(), matches.begin() + number); allMatches.push_back(matches); } delete matcher; } void FeatureMatching::match(vector<vector<KeyPoint>> &featureKeyPoints, vector<KeyPoint> &checkKeyPoints, vector<vector<DMatch>> &allMatches, int type, double percent, int leastNumber) { vector<Mat> featureDesc; Mat checkDesc; obtainPointsDesc(featureKeyPoints, checkKeyPoints, featureDesc, checkDesc); _match(featureDesc, checkDesc, allMatches, type, percent, leastNumber); } void FeatureMatching::match(vector<KeyPoint> &featureKeyPoints, vector<KeyPoint> &checkKeyPoints, vector<DMatch> &matches, int type, double percent, int leastNumber, int index) { Mat featureDesc; Mat checkDesc; obtainPointsDesc(featureKeyPoints, checkKeyPoints, featureDesc, checkDesc, index); vector<vector<DMatch>> allMatches; _match({featureDesc}, checkDesc, allMatches, type, percent, leastNumber); matches = allMatches[0]; } bool _knnMatch(const vector<Mat> &featureDesc, const Mat &checkDesc, vector<vector<vector<DMatch>>> &allMatches, vector<vector<vector<char>>> &allMatchesMask, int type, double percent, int k) { allMatches.clear(); DescriptorMatcher *matcher = nullptr; if (type == FeatureMatching::BF) { // 创建 BFMatcher matcher = new BFMatcher(NORM_HAMMING); } else if (type == FeatureMatching::FLANN) { auto indexPar = makePtr<flann::LshIndexParams>(6, 12, 1); // 检索参数,数值越大越准确,但是也越耗时 auto searchPar = makePtr<flann::SearchParams>(100); // 使用 indexPar 和 searchPar 创建 flannMatcher matcher = new FlannBasedMatcher(indexPar, searchPar); // matcher->knnMatch() } else { throw domain_error("无效类型"); } for (const auto &i : featureDesc) { vector<vector<DMatch>> matches; vector<vector<char>> matchesMask; // 使用 knnMatch 处理数据 matcher->knnMatch(i, checkDesc, matches, k); for (auto &matche : matches) { DMatch first = matche[0], last = matche[1]; if (first.distance < percent * last.distance) { matchesMask.push_back({1, 0}); } else { matchesMask.push_back({0, 0}); } } allMatches.push_back(matches); allMatchesMask.push_back(matchesMask); } delete matcher; } void FeatureMatching::knnMatch(vector<vector<KeyPoint>> &featureKeyPoints, vector<KeyPoint> &checkKeyPoints, vector<vector<vector<DMatch>>> &allMatches, vector<vector<vector<char>>> &allMatchesMask, int type, double percent, int k) { vector<Mat> featureDesc; Mat checkDesc; obtainPointsDesc(featureKeyPoints, checkKeyPoints, featureDesc, checkDesc); _knnMatch(featureDesc, checkDesc, allMatches, allMatchesMask, type, percent, k); } void FeatureMatching::knnMatch(vector<KeyPoint> &featureKeyPoints, vector<KeyPoint> &checkKeyPoints, vector<vector<DMatch>> &matches, vector<vector<char>> &matchesMask, int type, double percent, int k, int index) { Mat featureDesc; Mat checkDesc; obtainPointsDesc(featureKeyPoints, checkKeyPoints, featureDesc, checkDesc, index); vector<vector<vector<DMatch>>> allMatches; vector<vector<vector<char>>> allMatchesMask; _knnMatch({featureDesc}, checkDesc, allMatches, allMatchesMask, type, percent, k); matches = allMatches[0]; matchesMask = allMatchesMask[0]; } bool _findCorner(const vector<vector<KeyPoint>> &featureKeyPoints, const vector<Mat> &featureImgs, const vector<KeyPoint> &checkPoints, const vector<Mat> &featureDesc, const Mat &checkDesc, vector<vector<DMatch>> &allMatches, vector<vector<char>> &allMatchesMask, int type, double percent, int k, vector<vector<Point>> &allPoints) { allMatches.clear(); DescriptorMatcher *matcher = nullptr; if (type == FeatureMatching::BF) { // 创建 BFMatcher matcher = new BFMatcher(NORM_HAMMING); } else if (type == FeatureMatching::FLANN) { auto indexPar = makePtr<flann::LshIndexParams>(6, 12, 1); // 检索参数,数值越大越准确,但是也越耗时 auto searchPar = makePtr<flann::SearchParams>(100); // 使用 indexPar 和 searchPar 创建 flannMatcher matcher = new FlannBasedMatcher(indexPar, searchPar); } else { throw domain_error("无效类型"); } for (size_t i = 0; i < featureKeyPoints.size(); ++i) { vector<vector<DMatch >> matches; vector<vector<char>> matchesMask; vector<DMatch> goodMatches; // 使用 knnMatch 处理数据 matcher->knnMatch(featureDesc[i], checkDesc, matches, k); for (auto &matche : matches) { DMatch first = matche[0], last = matche[1]; if (first.distance < percent * last.distance) { goodMatches.push_back(first); } } if (goodMatches.size() > 10) { vector<Point2f> srcPoints, dstPoints; for (auto good : goodMatches) { srcPoints.push_back(featureKeyPoints[i][good.queryIdx].pt); dstPoints.push_back(checkPoints[good.trainIdx].pt); } vector<char> mask; Mat M = cv::findHomography(srcPoints, dstPoints, mask, RANSAC); matchesMask.push_back(mask); Mat img1 = featureImgs[i]; vector<Point2f> points{ Point2f(0, 0), Point2f(0, img1.size().height - 1), Point2f(img1.size().width - 1, img1.size().height - 1), Point2f(img1.size().width - 1, 0), }; vector<Point> dst; perspectiveTransform(points, points, M); for (const auto &p : points) { dst.emplace_back(p.x, p.y); } allPoints.push_back(dst); allMatches.push_back(goodMatches); allMatchesMask.push_back(mask); } else { delete matcher; return false; } } delete matcher; } bool FeatureMatching::findCorner(vector<vector<Point>> &allPoints, int type, double percent, int k) { vector<vector<KeyPoint>> featureKeyPoints; vector<KeyPoint> checkKeyPoints; vector<vector<DMatch>> allMatches; vector<vector<char>> allMatchesMask; return findCorner(allPoints, featureKeyPoints, checkKeyPoints, allMatches, allMatchesMask, type, percent, k); } bool FeatureMatching::findCorner(vector<vector<Point>> &allPoints, vector<vector<KeyPoint>> &featureKeyPoints, vector<KeyPoint> &checkKeyPoints, vector<vector<DMatch>> &allMatches, vector<vector<char>> &allMatchesMask, int type, double percent, int k) { vector<Mat> featureDesc; Mat checkDesc; obtainPointsDesc(featureKeyPoints, checkKeyPoints, featureDesc, checkDesc); return _findCorner(featureKeyPoints, featureImgs, checkKeyPoints, featureDesc, checkDesc, allMatches, allMatchesMask, type, percent, k, allPoints); } bool FeatureMatching::findCorner(vector<Point> &points, int type, double percent, int k, int index) { vector<KeyPoint> featureKeyPoints, checkKeyPoints; vector<DMatch> matches; vector<char> matchesMask; return findCorner(points, featureKeyPoints, checkKeyPoints, matches, matchesMask, type, percent, k, index); } bool FeatureMatching::findCorner(vector<Point> &points, vector<KeyPoint> &featureKeyPoints, vector<KeyPoint> &checkKeyPoints, vector<DMatch> &matches, vector<char> &matchesMask, int type, double percent, int k, int index) { Mat featureDesc; Mat checkDesc; obtainPointsDesc(featureKeyPoints, checkKeyPoints, featureDesc, checkDesc, index); vector<vector<DMatch>> allMatches; vector<vector<char>> allMatchesMask; vector<vector<Point>> allPoints; bool result = _findCorner({featureKeyPoints}, {featureImgs[index]}, checkKeyPoints, {featureDesc}, checkDesc, allMatches, allMatchesMask, type, percent, k, allPoints); matches = allMatches[0]; matchesMask = allMatchesMask[0]; points = allPoints[0]; return result; }
// Copyright (c) 2021 Thomas Kaldahl #include "finlin.hpp" // Helper functions void ensureSameMatDim(int h1, int w1, int h2, int w2, const char *operation) { if(w1 != w2) { fprintf( stderr, "Dimension mismatch. Cannot %s matrices of width %d and %d.\n", operation, w1, w2 ); exit(1); } else if(h1 != h2) { fprintf( stderr, "Dimension mismatch. Cannot %s matrices of height %d and %d.\n", operation, h1, h2 ); exit(1); } } void ensureMulMatDims(int w1, int h2, const char *operation) { if(w1 != h2) { fprintf( stderr, "Dimension mismatch. " "Cannot %s matrix of width %d with matrix of height %d.\n", operation, w1, h2 ); exit(1); } } void ensureSquare(int h, int w, const char *operation) { if(w != h) { fprintf( stderr, "Cannot %s of non-square matrix.\n", operation ); exit(1); } } void ensureNonzero(int h, int w, const char *operation) { if(w == 0 || h == 0) { fprintf( stderr, "Cannot %s of matrix with zero elements.\n", operation ); exit(1); } } void ensureInbound(int r, int c, int h, int w, const char *operation) { if(r < 0) { fprintf( stderr, "Cannot %s in negative row (row %d).\n", operation, r ); exit(1); } if(c < 0) { fprintf( stderr, "Cannot %s in negative column (column %d).\n", operation, c ); exit(1); } if(r >= h) { fprintf( stderr, "Matirix only contains %d rows. " "Cannot %s in row %d.\n", h, operation, r ); exit(1); } if(c >= w) { fprintf( stderr, "Matirix only contains %d columns. " "Cannot %s in column %d.\n", w, operation, c ); exit(1); } } // Technical methods void Mati::createMem() { clmem = clCreateBuffer( FinLin::context, CL_MEM_READ_WRITE, w*h * sizeof(int), NULL, &FinLin::err ); FinLin::checkErr(); dirty = true; } Mati Mati::copy() const { Mati res = Mati(h, w); memcpy(res.data, data, w*h * sizeof(int)); return res; } bool Mati::update() { if(!dirty) return false; FinLin::writeBuffer(clmem, 0, w*h * sizeof(int), data); dirty = false; return true; } // Constructors Mati::Mati(int height, int width, int *components) { h = height; w = width; data = components; createMem(); } Mati::Mati(int height, int width) { h = height; w = width; data = (int*)malloc(w*h * sizeof(int)); memset(data, 0, w*h * sizeof(int)); createMem(); } Mati::Mati(int size) { h = size; w = size; data = (int*)malloc(w*h * sizeof(int)); memset(data, 0, w*h * sizeof(int)); for(int i = 0; i < w*h; i += w+1) { data[i] = 1; } createMem(); } Mati::Mati(Mat mat) { w = mat.w; h = mat.h; data = (int*)malloc(w*h * sizeof(int)); for(int i = 0; i < w*h; i++) { data[i] = (int)mat.data[i]; } createMem(); } // Statics Mati Mati::randomUniform(int height, int width, int min, int max) { int *components = (int*)malloc(width*height * sizeof(int)); for(int i = 0; i < width*height; i++) { components[i] = (max - min) * rand() / RAND_MAX + min; } return Mati(height, width, components); } Mati Mati::fromRowVec(Veci row) { return Mati(1, row.d, row.data); } Mati Mati::fromColVec(Veci col) { return Mati(col.d, 1, col.data); } Mati Mati::fromRowVecs(int numVecs, Veci *vecs) { if(numVecs == 0) return Mati(0); int width = vecs[0].d; int *components = (int*)malloc(numVecs*width * sizeof(int)); for(int row = 0; row < numVecs; row++) { if(vecs[row].d != width) { fprintf(stderr, "Cannot construct matrix from vectors" " of varying dimension.\n"); exit(1); } memcpy(components + row*width, vecs[row].data, width * sizeof(int)); } return Mati(numVecs, width, components); } Mati Mati::fromColVecs(int numVecis, Veci *vecs) { return fromRowVecs(numVecis, vecs).T(); } // Accessors int Mati::height() const { return h; } int Mati::width() const { return w; } int Mati::comp(int r, int c) const { ensureInbound(r, c, h, w, "access component"); return data[w*r + c]; } char *Mati::string() const { const int MAXLEN = 12; char *res = (char*)malloc(MAXLEN * w*h * sizeof(char)); snprintf(res, MAXLEN, "(\n"); char *resp = res + 2; for(int r = 0; r < h; r++) { for(int c = 0; c < w; c++) { snprintf(resp, MAXLEN, "\t%d", data[w*r + c]); resp += strlen(resp); } *resp = '\n'; resp++; } snprintf(resp, 2, ")"); return res; } // In-place operations Mati Mati::operator*=(int scalar) { update(); FinLin::setArg(FinLin::scalei, 0, clmem); FinLin::setArg(FinLin::scalei, 1, scalar); FinLin::execKernel(FinLin::scalei, 0, w*h, 0); FinLin::readBuffer(clmem, 0, w*h * sizeof(int), data); return *this; } Mati Mati::operator/=(int divisor) { update(); FinLin::setArg(FinLin::dividei, 0, clmem); FinLin::setArg(FinLin::dividei, 1, divisor); FinLin::execKernel(FinLin::dividei, 0, w*h, 0); FinLin::readBuffer(clmem, 0, w*h * sizeof(int), data); return *this; } Mati Mati::operator%=(int modulus) { update(); FinLin::setArg(FinLin::modulo, 0, clmem); FinLin::setArg(FinLin::modulo, 1, modulus); FinLin::execKernel(FinLin::modulo, 0, w*h, 0); FinLin::readBuffer(clmem, 0, w*h * sizeof(int), data); return *this; } Mati Mati::operator^=(int exponent) { for(int i = 1; i < exponent; i++) { *this = *this * *this; } return *this; } Mati Mati::operator&=(Mati multiplier) { ensureSameMatDim(h, w, multiplier.h, multiplier.w, "multiply"); update(); multiplier.update(); FinLin::setArg(FinLin::hadamardi, 0, clmem); FinLin::setArg(FinLin::hadamardi, 1, multiplier.clmem); FinLin::execKernel(FinLin::hadamardi, 0, w*h, 0); FinLin::readBuffer(clmem, 0, w*h * sizeof(int), data); return *this; } Mati Mati::operator+=(Mati addend) { ensureSameMatDim(h, w, addend.h, addend.w, "add"); update(); addend.update(); FinLin::setArg(FinLin::addi, 0, clmem); FinLin::setArg(FinLin::addi, 1, addend.clmem); FinLin::execKernel(FinLin::addi, 0, w*h, 0); FinLin::readBuffer(clmem, 0, w*h * sizeof(int), data); return *this; } Mati Mati::operator-=(Mati subtrahend) { ensureSameMatDim(h, w, subtrahend.h, subtrahend.w, "subtract"); update(); subtrahend.update(); FinLin::setArg(FinLin::addScaledi, 0, clmem); FinLin::setArg(FinLin::addScaledi, 1, subtrahend.clmem); FinLin::setArg(FinLin::addScaledi, 2, -1); FinLin::execKernel(FinLin::addScaledi, 0, w*h, 0); FinLin::readBuffer(clmem, 0, w*h * sizeof(int), data); return *this; } // Binary operations Mati Mati::operator*(int scalar) const { Mati matrix = copy(); matrix *= scalar; return matrix; } Mati operator*(int scalar, Mati matrix) { Mati product = matrix.copy(); product *= scalar; return product; } Mati Mati::operator/(int divisor) const { Mati dividend = copy(); dividend /= divisor; return dividend; } Mati Mati::operator%(int modulus) const { Mati dividend = copy(); dividend %= modulus; return dividend; } Mati Mati::operator^(int exponent) const { Mat base = copy(); base ^= exponent; return base; } Veci Mati::operator*(Veci vector) { ensureMulMatDims(w, vector.d, "multiply"); update(); vector.update(); cl_mem resBuff = clCreateBuffer( FinLin::context, CL_MEM_READ_WRITE, h * sizeof(int), NULL, &FinLin::err ); FinLin::checkErr(); FinLin::setArg(FinLin::matVeci, 0, clmem); FinLin::setArg(FinLin::matVeci, 1, vector.clmem); FinLin::setArg(FinLin::matVeci, 2, resBuff); FinLin::setArg(FinLin::matVeci, 3, w); FinLin::execKernel(FinLin::matVeci, 0, h, 0); int *resData = (int*)malloc(h * sizeof(int)); FinLin::readBuffer(resBuff, 0, h * sizeof(int), resData); return Veci(h, resData); } Mati Mati::operator*(Mati multiplier) { ensureMulMatDims(w, multiplier.h, "multiply"); update(); multiplier.update(); cl_mem resBuff = clCreateBuffer( FinLin::context, CL_MEM_READ_WRITE, h * multiplier.w * sizeof(int), NULL, &FinLin::err ); FinLin::checkErr(); FinLin::setArg(FinLin::matMuli, 0, clmem); FinLin::setArg(FinLin::matMuli, 1, multiplier.clmem); FinLin::setArg(FinLin::matMuli, 2, resBuff); FinLin::setArg(FinLin::matMuli, 3, w); FinLin::execKernel(FinLin::matMuli, 0, h, multiplier.w, 0); int *resData = (int*)malloc(h * multiplier.w * sizeof(int)); FinLin::readBuffer(resBuff, 0, h * multiplier.w * sizeof(int), resData); return Mati(h, multiplier.w, resData); } Mati Mati::operator&(Mati multiplier) const { Mati multiplicand = copy(); multiplicand &= multiplier; return multiplicand; } Mati Mati::operator+(Mati addend) const { Mati augend = copy(); augend += addend; return augend; } Mati Mati::operator-(Mati subtrahend) const { Mati minuend = copy(); minuend -= subtrahend; return minuend; } // Unary operations int Mati::trace() const { ensureSquare(h, w, "find trace"); int sum = 0; for(int i = 0; i < h; i++) { sum += comp(i, i); } return sum; } Mati Mati::operator-() const { return -1 * *this; } Mati Mati::operator~() const { Mati negated = copy(); negated.update(); FinLin::setArg(FinLin::compNoti, 0, negated.clmem); FinLin::execKernel(FinLin::compNoti, 0, w*h, 0); FinLin::readBuffer(negated.clmem, 0, w*h * sizeof(int), negated.data); return negated; } Mati Mati::T() const { int *res = (int*)malloc(w*h * sizeof(int)); for(int r = 0; r < h; r++) { for(int c = 0; c < w; c++) { res[c*h + r] = data[r*w + c]; } } return Mati(w, h, res); } // Misc operations Veci Mati::rowVeci(int row) const { int *components = (int*)malloc(w * sizeof(int)); memcpy(components, data + row*w, w * sizeof(int)); return Veci(w, components); } Veci Mati::colVeci(int col) const { int *components = (int*)malloc(h * sizeof(int)); for(int r = 0; r < h; r++) { components[r] = comp(r, col); } return Veci(h, components); }
#include <iostream> using namespace std; struct complex_t { float real; float imag; complex_t() { real = 0.0f; imag = 0.0f; } complex_t add( complex_t other) const { complex_t result; result.real = this->real + other.real; result.imag = this->imag + other.imag; return result; } istream & read( istream & stream ) { float areal, aimag; char symbol; if(stream >> symbol && symbol == '(' && stream >> areal && stream >> symbol && symbol == ',' && stream >> aimag && stream >> symbol && symbol == ')') { real = areal; imag = aimag; } else { stream.setstate(ios::failbit); } return stream; } ostream & write( ostream & stream ) const { return stream << '(' << real << ',' << imag << ')'; } complex_t sub( complex_t other ) const { complex_t complex; complex.real = real - other.real; complex.imag = imag - other.imag; return complex; } complex_t mul(complex_t other) const { complex_t complex; complex.real = real * other.real - imag * other.imag; complex.imag = imag * other.real + real * other.imag; return complex; } complex_t div(complex_t other) const { complex_t complex; complex.real= (real * other.real + imag * other.imag) / (other.real * other.real + other.imag * other.imag); complex.imag= (imag * other.real - real * other.imag) / (other.real * other.real + other.imag * other.imag); return complex; } }; int main() { complex_t a; if (a.read(cin)) { char op; cin >> op; complex_t b; if (b.read(cin)) { complex_t c; switch (op) { case '+': c = a.add(b); c.write(cout,c); break; case '-': c = a.sub(b); c.write(cout,c); break; case '*': c = a.mul(b); c.write(cout,c); break; case '/': c = a.div(b); c.write(cout,c); break; } } else { cout <<"An error has occured while reading input data"; } } else { cout << "An error has occured while reading input data"; } cin.get(); cin.get(); return 0; }
/**************************************************************** * TianGong RenderLab * * Copyright (c) Gaiyitp9. All rights reserved. * * This code is licensed under the MIT License (MIT). * *****************************************************************/ #pragma once #include "GraphicsBase.hpp" #include "RenderDevice.hpp" #include "DeviceContext.hpp" #include "SwapChain.hpp" namespace TG::Graphics { struct IFactory { // 枚举显示适配器,如果对应索引存在,则返回true,否则返回false virtual bool EnumAdapter(unsigned int index, AdapterDesc& desc) const = 0; // 创建图形设备和上下文 virtual void CreateDeviceAndContext(ICreateInfo const* info, IRenderDevice** ppDevice, IDeviceContext** ppContext) const = 0; // 创建交换链 virtual void CreateSwapChain(IRenderDevice const* pDevice, HWND hwnd, const SwapChainDesc& desc, ISwapChain** ppSwapChain) const = 0; }; }
/** * @title Parallel vector of strings with RcppParallel * @author Brian J. Knaus * @license GPL (>= 2) * @tags parallel * @summary Demonstrates using a vector of strings with RcppParallel. * * The data structures used by R and Rcpp are not thread safe because garbage * collection may occur. * The [RcppParallel](https://rcppcore.github.com/RcppParallel) package * includes RVector and RMatrix as thread safe dat structures. * However, they can only contain numeric data. * If you have non-numeric data (e.g., string, char) you will need to use a * different data structure. * Most of the C++ data structures should be thread safe. * Here we demonstrate how to use a vector of strings with RcppParallel. * * */ /** * ### Implementation using Rcpp * * */ #include <Rcpp.h> // [[Rcpp::export]] std::string getElement( std::string &mystring, char &split, int &element ) { std::string rstring; int elementN = 0; unsigned int i=0; int start = 0; for(i=1; i<mystring.size(); i++){ if(mystring[i] == split){ // We matched our splitting character. if(elementN == element){ // We've arrived at our desired element. rstring = mystring.substr(start, i - start); return rstring; } else { // We need to iterate to the next element. start = i + 1; i = i + 1; elementN = elementN + 1; } } } // The end of the string has no delimiter. // We test if it is the correct element and parse if so. if(elementN == element){ rstring = mystring.substr(start, i - start); return rstring; } else { rstring = "-999"; return rstring; } } // [[Rcpp::export]] Rcpp::StringVector delimitString( Rcpp::StringVector myvector, char myDelim, int element ) { Rcpp::StringVector rvector( myvector.size() ); std::string myString; // R is one based, C++ is zero based. element = element - 1; unsigned int i=0; for(i=0; i<myvector.size(); i++){ myString = myvector[i]; rvector[i] = getElement(myString, myDelim, element); } return rvector; } /** * ### Implementation using RcppParallel * * */ #include <RcppParallel.h> using namespace RcppParallel; // [[Rcpp::depends(RcppParallel)]] struct getElement : public Worker { // input vector to read from const std::vector< std::string > myVector; // output vector to write to std::vector< std::string > &retVector; std::string myString; // initialize input and output vectors getElement(const std::vector< std::string > myVector, std::vector< std::string > &retVector) : myVector(myVector), retVector(retVector) {} // function call operator that work for the specified range (begin/end) void operator()(std::size_t begin, std::size_t end) { // Rcpp::Rcout << "Value: " << begin << "\n"; for (std::size_t i = begin; i < end; i++) { // retVector[i] = myVector[i]; myString = myVector[i]; char myDelim = ':'; int element = 2; // myString = getElement(myString, myDelim, element); retVector[i] = myString; // Don't do the following/ // Rcpp::Rcout << "Value: " << myString << "\n"; // Or this. // Rcpp::checkUserInterrupt(); } } }; // [[Rcpp::export]] Rcpp::StringVector rcpp_parallel_delimitString(Rcpp::StringVector myVector) { // Because Rcpp data structures are not thread safe // we'll use std::vector for input and output. std::vector< std::string > tmpVector1(myVector.size()); std::vector< std::string > tmpVector2(myVector.size()); // Convert Rcpp::StringVector to std::vector. unsigned int i; std::string tmpString; for(i=0; i<myVector.size(); i++){ // Rcpp::checkUserInterrupt(); tmpString = myVector[i]; tmpVector1[i] = tmpString; } // Create the worker struct getElement getElement(tmpVector1, tmpVector2); // Call it with parallelFor unsigned int grainSize = 100; parallelFor(0, tmpVector1.size() - 1, getElement, grainSize); // allocate the string we will return Rcpp::StringVector retVector(tmpVector2.size()); // Copy to Rcpp container to send back to R. retVector = tmpVector2; return retVector; } /** * ### Fabricate example data * * */ /*** R #n <- 1e7 # n <- 1e6 #n <- 1e1 myGT <- paste(sample(0:1, size = n, replace = TRUE), sample(0:1, size = n, replace = TRUE), sep = "/") myGT <- paste(myGT, LETTERS, paste(sample(1:200, size = n, replace = TRUE), sample(1:200, size = n, replace = TRUE), sep=","), sep = ":") myGT <- paste(myGT, sample(1:200, size = n, replace = TRUE), sep = ":") head(myGT) */ /** * ### Benchmark * * */ /*** R library(microbenchmark) nTimes <- 20 microbenchmark(gt1 <- delimitString(myGT, ":", 3), times = nTimes) head(gt1) */ /*** R # RcppParallel::setThreadOptions(numThreads = 4) microbenchmark(gt2 <- rcpp_parallel_delimitString(myGT), times = nTimes) # head(gt2) */
//Library #include <Arduino.h> #include <Wire.h> #include <Adafruit_Sensor.h> //Sensor Cahaya TSL2561 #include <Adafruit_TSL2561_U.h> //Sensor Suhu & Kelembaban DHT11 #include <DHT.h> #include <DHT_U.h> //Sensor CO2 MH-Z19B #include <MHZ19.h> //MQTT & WiFi #include <WiFi.h> #include <PubSubClient.h> //Macro #define SDA 23 #define SCL 22 #define DHTPIN 4 #define DHTTYPE DHT11 #define CO2PWM 32 #define DELAY_TIME_DHT11 5000 #define DELAY_TIME_TSL2561 1000 #define DELAY_TIME_MHZ19B 15000 //WiFi Credential const char* ssid = "IC-PROC"; const char* password = "0icprocPAUME0"; const char* mqttServer = "192.168.0.63"; const int mqttPort = 1883; //Variabel Global WiFiClient espClient; PubSubClient client(espClient); Adafruit_TSL2561_Unified tsl = Adafruit_TSL2561_Unified(TSL2561_ADDR_FLOAT, 12345); DHT_Unified dht(DHTPIN, DHTTYPE); sensors_event_t event; MHZ19 mhz(&Serial2); float temp_measured = 0.0; float hum_measured = 0.0; float lux_measured = 0.0; int CO2_measured = 0; char tempString[20]; char humString[20]; char luxString[20]; char CO2String[20]; unsigned long lastMsgDHT11 = 0; unsigned long lastMsgTSL2561 = 0; unsigned long lastMsgSoil = 0; unsigned long lastMsgMHZ19B = 0; void setup() { //TSL2561 Wire.begin(SDA, SCL); tsl.begin(); tsl.enableAutoRange(true); tsl.setIntegrationTime(TSL2561_INTEGRATIONTIME_101MS); //DHT11 dht.begin(); //MH-Z19B Serial2.begin(9600); mhz.setRange(MHZ19_RANGE_2000); mhz.setAutoCalibration(true); //Pengaturan WiFi delay(10); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { } //Pengaturan MQTT client.setServer(mqttServer, mqttPort); Serial.begin(115200); } void loop() { long now; if (!client.connected()) { while (!client.connected()) { client.connect("ESP32ClientSensor"); } } client.loop(); now = millis(); if (now - lastMsgDHT11 > DELAY_TIME_DHT11) { lastMsgDHT11 = now; //Baca suhu dht.temperature().getEvent(&event); if (!isnan(event.temperature)) { temp_measured = event.temperature; Serial.print("Suhu: "); Serial.println(temp_measured); } dtostrf(temp_measured, 1, 2, tempString); client.publish("esp32/temperature", tempString); //Baca kelembaban dht.humidity().getEvent(&event); if (!isnan(event.relative_humidity)) { hum_measured = event.relative_humidity; Serial.print("Kelembaban: "); Serial.println(hum_measured); } dtostrf(hum_measured, 1, 2, humString); client.publish("esp32/humidity", humString); } now = millis(); if (now - lastMsgTSL2561 > DELAY_TIME_TSL2561) { lastMsgTSL2561 = now; //Baca intensitas cahaya tsl.getEvent(&event); if (event.light) { lux_measured = event.light; Serial.print("Cahaya: "); Serial.println(lux_measured); } dtostrf(lux_measured, 1, 2, luxString); client.publish("esp32/light_intensity", luxString); } now = millis(); if (now - lastMsgMHZ19B > DELAY_TIME_MHZ19B) { lastMsgMHZ19B = now; MHZ19_RESULT response = mhz.retrieveData(); if (response == MHZ19_RESULT_OK) { CO2_measured = mhz.getCO2(); Serial.print("CO2: "); Serial.println(CO2_measured); } dtostrf(CO2_measured, 1, 2, CO2String); client.publish("esp32/CO2", CO2String); } }
#include<stdio.h> #include<stdlib.h> typedef struct{ int sommet; int taille; int T[40]; }mypile; void empiler(mypile *p,int v){ p->T[p->sommet++]=v; } int depiler(mypile *p){ return p->T[--p->sommet]; } int estpleinne(mypile p){ return p.sommet==p.taille; } int estvide(mypile p){ return p.sommet==0; } void supprimer(mypile *p,int x){ mypile p1; p1.sommet=0; p1.taille==p->taille; int an ; while(!estvide(*p)){ an=depiler(p); if(an!=x){ empiler(&p1,an); } } while(!estvide(p1)){ { empiler(p,depiler(&p1)); } } } int paire(mypile p){ int an; if(estvide(p)){ printf("la pile est vide"); } else{ while(!estvide(p)){ an=depiler(&p); if(an%2==0){ printf("le nombre %d est paire\n ",an); } else{ printf("le nombre %d est impaire\n",an); } } } } void exrit(mypile p){ int an; printf("%d",an); } int max(mypile p){ int an; int m; if(estvide(p)) printf("la pile est vide "); else{ while(!estvide(p)){ an=depiler(&p); if(an>m){ m=an; } } } return m; } void afficher(mypile p ){ int an,choice; if(estvide(p)) printf("la pile est vide "); else{ while(!estvide(p)){ an=depiler(&p); printf("le nombre est = %d \n " ,an); } } } int somme(mypile p){ int an,s=0; if(estvide(p)){ printf("la pile est vide "); } else{ while(!estvide(p)){ an=depiler(&p); s=s+an; } } return s; } int compte(mypile p){ int an,s=0; if(estvide(p)){ printf("la pile est vide "); } else{ while(!estvide(p)){ an=depiler(&p); s++; } } return s; } int moy(mypile p){ int an,cmp=0; float M=0; if(estvide(p)){ printf("la pile est vide "); } else{ while(!estvide(p)){ an=depiler(&p); cmp++; M=M+an/cmp; } } return M; } int main (){ mypile p1; int n,i,chx,a; int option=1; printf("donnez la taille de la pile "); scanf("%d",&p1.taille); p1.sommet=0; for(i=p1.sommet;i<p1.taille;i++){ printf("donnez votre nombre : "); scanf("%d",&n); empiler(&p1,n); } while(option){ printf("\nMenu principal"); printf("\n1.affiche \n2.supprimer \n3.max \n4.paire/impaire \n5.la somme \n6.ordre \n7.la Moyenne de la pile"); printf("\nEntrez votre choix: "); scanf("%d", &chx); switch (chx) { case 1: afficher(p1); break; case 2: printf("donnez le nombre pour supprimer"); scanf("%d",&a); supprimer(&p1,a); afficher(p1); break; case 3: printf("\n le plus grand nombre est =%d",max(p1)); break; case 4: paire(p1); break; case 5: printf("\nla somme de la pille est = %d",somme(p1)); break; case 6: printf("le nombre de element = %d",compte(p1)); break; case 7: printf("\nla Moyenne de la pile = %d",moy(p1)); break; } printf("\n tapez 1 si vous avez continue et 0 pour quitez : "); scanf("%d",&option); } }
#include "pch.h" #include "WaypointSearch.h" #include "Math\SimpleMath.h" #include "TimeManager.h" #include "Renderer\DebugRenderer.h" namespace Hourglass { void WaypointSearch::DrawDebug() { Vector4 debugColor = { 1.0f, 1.0f, 1.0f, 1.0f }; Aabb debugAabb; debugAabb.pMin = m_WaypointGraph->operator[]( m_Start ).m_Waypoint - Vector3( 0.5f, 0.5f, 0.5f ); debugAabb.pMax = m_WaypointGraph->operator[]( m_Start ).m_Waypoint + Vector3( 0.5f, 0.5f, 0.5f ); DebugRenderer::DrawAabb( debugAabb, debugColor ); debugColor = Vector4( 0.0f, 0.0f, 0.0f, 1.0f ); debugAabb.pMin = m_WaypointGraph->operator[]( m_End ).m_Waypoint - Vector3( 0.5f, 0.5f, 0.5f ); debugAabb.pMax = m_WaypointGraph->operator[]( m_End ).m_Waypoint + Vector3( 0.5f, 0.5f, 0.5f ); DebugRenderer::DrawAabb( debugAabb, debugColor ); for (auto& vertex : m_DebugDrawVertices) { DebugRenderer::DrawAabb( vertex, debugColor ); } } void WaypointSearch::Init( WaypointGraph* waypointGraph ) { m_WaypointGraph = waypointGraph; } void WaypointSearch::Configure( unsigned int start, const unsigned int end ) { if (start > 1000000) return; m_Start = start; m_End = end; m_DebugDrawVertices.clear(); m_Visited.clear(); m_Solution = s_kNoSolution; m_Goal = &(*m_WaypointGraph)[end]; Planner& startPlanner = m_Visited[start]; startPlanner.m_Parent = nullptr; startPlanner.m_Vertex = &(*m_WaypointGraph)[start]; startPlanner.m_GivenCost = 0.0f; startPlanner.m_FinalCost = DirectX::SimpleMath::Vector3:: Distance( startPlanner.m_Vertex->m_Waypoint, m_Goal->m_Waypoint ); Queue( &startPlanner ); } void WaypointSearch::FindPath() { int i = 3; while (!m_Open.empty()) { SearchFront(); } } void WaypointSearch::TimeslicedFindPath( float timeslice ) { // Handle time internally to the function for now, allows immedate multithreading double startTime, freqInv; { LARGE_INTEGER startTimeLI, freqLI; QueryPerformanceCounter( &startTimeLI ); QueryPerformanceFrequency( &freqLI ); freqInv = 1.0 / double( freqLI.QuadPart ); startTime = double( startTimeLI.QuadPart ) * freqInv; } while (!m_Open.empty() && m_Solution == s_kNoSolution) { SearchFront(); double timeTaken; { LARGE_INTEGER timeTakenLI; QueryPerformanceCounter( &timeTakenLI ); timeTaken = double( timeTakenLI.QuadPart ) * freqInv - startTime; } if (timeTaken >= timeslice) { break; } } } void WaypointSearch::SearchFront() { m_Current = m_Open.back(); m_Open.pop_back(); WaypointGraph::WVertex* vertex = m_Current->m_Vertex; // Solution found / Reached Goal? if (vertex == m_Goal) { if (!m_Current->m_Parent) { for (unsigned int i = 0; i < m_WaypointGraph->Size(); ++i) { if (&(*m_WaypointGraph)[i] == m_Current->m_Vertex) { m_Solution = i; return; } } } while (m_Current->m_Parent->m_Parent) { m_Current = m_Current->m_Parent; } for (unsigned int i = 0; i < m_Current->m_Parent->m_Vertex->m_Edges.size(); ++i) { if (m_Current->m_Vertex == &(*m_WaypointGraph)[m_Current->m_Parent->m_Vertex->m_Edges[i].m_ToVertex]) { m_Solution = m_Current->m_Parent->m_Vertex->m_Edges[i].m_ToVertex; } } return; } std::vector<WaypointGraph::Edge>& currEdgeList = vertex->m_Edges; unsigned int currNumEdges = unsigned int( currEdgeList.size() ); for (unsigned int i = 0; i < currNumEdges; ++i) { unsigned short toEndpointVertex = currEdgeList[i].m_ToVertex; float newGivenCost = m_Current->m_GivenCost + currEdgeList[i].m_Distance; Aabb debugAabb; debugAabb.pMin = m_WaypointGraph->operator[](toEndpointVertex).m_Waypoint - Vector3( 0.5f, 0.5f, 0.5f ); debugAabb.pMax = m_WaypointGraph->operator[]( toEndpointVertex ).m_Waypoint + Vector3( 0.5f, 0.5f, 0.5f ); m_DebugDrawVertices.push_back( debugAabb ); if (m_Visited.find( toEndpointVertex ) == m_Visited.end()) // no duplicate { Planner& successor = m_Visited[toEndpointVertex]; successor.m_Vertex = &(*m_WaypointGraph)[toEndpointVertex]; // Calculate successor costs float heuristicCost = DirectX::SimpleMath::Vector3:: Distance( successor.m_Vertex->m_Waypoint, m_Goal->m_Waypoint ); successor.m_FinalCost = successor.m_GivenCost = newGivenCost; successor.m_FinalCost += heuristicCost; successor.m_Parent = m_Current; Queue( &successor ); } else // duplicate { Planner& successor = m_Visited[toEndpointVertex]; if (newGivenCost < successor.m_GivenCost) { DeQueue( &successor ); // calcuate successor costs float heuristicCost = successor.m_FinalCost - successor.m_GivenCost; successor.m_FinalCost = successor.m_GivenCost = newGivenCost; successor.m_FinalCost += heuristicCost; successor.m_Parent = m_Current; Queue( &successor ); } } } } bool WaypointSearch::CostCmp( Planner * const & lhs, Planner * const & rhs ) { return lhs->m_FinalCost > rhs->m_FinalCost; } void WaypointSearch::Queue( Planner * planner ) { m_Open.insert( std::upper_bound( m_Open.begin(), m_Open.end(), planner, CostCmp ), planner ); } void WaypointSearch::DeQueue( Planner * planner ) { m_Open.erase( std::remove( m_Open.begin(), m_Open.end(), planner ), m_Open.end() ); } unsigned int WaypointSearch::GetSolutionWaypoint() { return m_Solution; } }
/* * @lc app=leetcode id=231 lang=cpp * * [231] Power of Two * * https://leetcode.com/problems/power-of-two/description/ * * algorithms * Easy (42.16%) * Likes: 470 * Dislikes: 129 * Total Accepted: 238K * Total Submissions: 564.5K * Testcase Example: '1' * * Given an integer, write a function to determine if it is a power of two. * * Example 1: * * * Input: 1 * Output: true * Explanation: 2^0 = 1 * * * Example 2: * * * Input: 16 * Output: true * Explanation: 2^4 = 16 * * Example 3: * * * Input: 218 * Output: false * */ class Solution { public: bool isPowerOfTwo(int n) { // x = [same val]10...00 // x - 1 = [same val]01...11, 由于 x = (x - 1) + 1 // x & (x - 1) = [same val]00...00 // 从而第一个1被抹掉了 return (n > 0) && 0 == (n & (n - 1)); } };
// // Created by thinker on 7/6/16. // #ifndef PROJECT_HTTPREQ_H #define PROJECT_HTTPREQ_H #endif //PROJECT_HTTPREQ_H #include <string.h> #include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <fcntl.h> #include <errno.h> #include <netdb.h> #include <stdarg.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <sys/types.h> #include <sys/socket.h> #define BUFSIZE 41000 #define URLSIZE 1024 #define INVALID_SOCKET -1 #define __DEBUG__ class HttpRequest { public: HttpRequest(); ~HttpRequest(); void DebugOut(const char *fmt, ...); int HttpGet(const char* strUrl, char* strResponse); int HttpPost(const char* strUrl, const char* strData, char* strResponse); private: int HttpRequestExec(const char* strMethod, const char* strUrl, const char* strData, char* strResponse); char* HttpHeadCreate(const char* strMethod, const char* strUrl, const char* strData); char* HttpDataTransmit(char *strHttpHead, const int iSockFd); int GetPortFromUrl(const char* strUrl); char* GetIPFromUrl(const char* strUrl); char* GetParamFromUrl(const char* strUrl); char* GetHostAddrFromUrl(const char* strUrl); int SocketFdCheck(const int iSockFd); static int m_iSocketFd; }; int HttpRequest::HttpGet(const char* strUrl, char* strResponse) { return HttpRequestExec("GET", strUrl, NULL, strResponse); } /** * 功能描述:HttpPost请求 * 参数说明: * strUrl: Http请求URL * strData: POST请求发送的数据 * strResponse:Http请求响应 * 返 回 值: * 1表示成功 * 0表示失败 **/ int HttpRequest::HttpPost(const char* strUrl, const char* strData, char* strResponse) { return HttpRequestExec("POST", strUrl, strData, strResponse); } //执行HTTP请求,GET或POST int HttpRequest::HttpRequestExec(const char* strMethod, const char* strUrl, const char* strData, char* strResponse) { //判断URL是否有效 if((strUrl == NULL) || (0 == strcmp(strUrl, ""))) { DebugOut("%s %s %d\tURL为空\n", __FILE__, __FUNCTION__, __LINE__); return 0; } //限制URL长度 if(URLSIZE < strlen(strUrl)) { DebugOut("%s %s %d\tURL的长度不能超过%d\n", __FILE__, __FUNCTION__, __LINE__, URLSIZE); return 0; } //创建HTTP协议头 char* strHttpHead = HttpHeadCreate(strMethod, strUrl, strData); //判断套接字m_iSocketFd是否有效,有效就直接发送数据 if(m_iSocketFd != INVALID_SOCKET) { //检查SocketFd是否为可写不可读状态 if(SocketFdCheck(m_iSocketFd) > 0) { char* strResult = HttpDataTransmit(strHttpHead, m_iSocketFd); if(NULL != strResult) { strcpy(strResponse, strResult); return 1; } } } //Create socket m_iSocketFd = INVALID_SOCKET; m_iSocketFd = socket(AF_INET, SOCK_STREAM, 0); if (m_iSocketFd < 0 ) { DebugOut("%s %s %d\tsocket error! Error code: %d,Error message: %s\n", __FILE__, __FUNCTION__, __LINE__, errno, strerror(errno)); return 0; } //Bind address and port int iPort = GetPortFromUrl(strUrl); if(iPort < 0) { DebugOut("%s %s %d\t从URL获取端口失败\n", __FILE__, __FUNCTION__, __LINE__); return 0; } char* strIP = GetIPFromUrl(strUrl); if(strIP == NULL) { DebugOut("%s %s %d\t从URL获取IP地址失败\n", __FILE__, __FUNCTION__, __LINE__); return 0; } struct sockaddr_in servaddr; bzero(&servaddr, sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_port = htons(iPort); if (inet_pton(AF_INET, strIP, &servaddr.sin_addr) <= 0 ) { DebugOut("%s %s %d\tinet_pton error! Error code: %d,Error message: %s\n", __FILE__, __FUNCTION__, __LINE__, errno, strerror(errno)); close(m_iSocketFd); m_iSocketFd = INVALID_SOCKET; return 0; } //Set non-blocking int flags = fcntl(m_iSocketFd, F_GETFL, 0); if(fcntl(m_iSocketFd, F_SETFL, flags|O_NONBLOCK) == -1) { close(m_iSocketFd); m_iSocketFd = INVALID_SOCKET; DebugOut("%s %s %d\tfcntl error! Error code: %d,Error message: %s\n", __FILE__, __FUNCTION__, __LINE__, errno, strerror(errno)); return 0; } //非阻塞方式连接 int iRet = connect(m_iSocketFd, (struct sockaddr *)&servaddr, sizeof(servaddr)); if(iRet == 0) { char* strResult = HttpDataTransmit(strHttpHead, m_iSocketFd); if(NULL != strResult) { strcpy(strResponse, strResult); free(strResult); return 1; } else { close(m_iSocketFd); m_iSocketFd = INVALID_SOCKET; free(strResult); return 0; } } else if(iRet < 0) { if(errno != EINPROGRESS) { return 0; } } iRet = SocketFdCheck(m_iSocketFd); if(iRet > 0) { char* strResult = HttpDataTransmit(strHttpHead, m_iSocketFd); if(NULL == strResult) { close(m_iSocketFd); m_iSocketFd = INVALID_SOCKET; return 0; } else { strcpy(strResponse, strResult); free(strResult); return 1; } } else { close(m_iSocketFd); m_iSocketFd = INVALID_SOCKET; return 0; } return 1; } //构建HTTP消息头 char* HttpRequest::HttpHeadCreate(const char* strMethod, const char* strUrl, const char* strData) { char* strHost = GetHostAddrFromUrl(strUrl); char* strParam = GetParamFromUrl(strUrl); char* strHttpHead = (char*)malloc(BUFSIZE); memset(strHttpHead, 0, BUFSIZE); strcat(strHttpHead, strMethod); strcat(strHttpHead, " /"); strcat(strHttpHead, strParam); free(strParam); strcat(strHttpHead, " HTTP/1.1\r\n"); strcat(strHttpHead, "Accept: */*\r\n"); strcat(strHttpHead, "Accept-Language: cn\r\n"); strcat(strHttpHead, "User-Agent: Mozilla/4.0\r\n"); strcat(strHttpHead, "Host: "); strcat(strHttpHead, strHost); strcat(strHttpHead, "\r\n"); strcat(strHttpHead, "Cache-Control: no-cache\r\n"); strcat(strHttpHead, "Connection: Keep-Alive\r\n"); if(0 == strcmp(strMethod, "POST")) { char len[8] = {0}; unsigned uLen = strlen(strData); sprintf(len, "%d", uLen); strcat(strHttpHead, "Content-Type: application/x-www-form-urlencoded\r\n"); strcat(strHttpHead, "Content-Length: "); strcat(strHttpHead, len); strcat(strHttpHead, "\r\n\r\n"); strcat(strHttpHead, strData); } strcat(strHttpHead, "\r\n\r\n"); free(strHost); return strHttpHead; } //发送HTTP请求并接受响应 char* HttpRequest::HttpDataTransmit(char *strHttpHead, const int iSockFd) { char* buf = (char*)malloc(BUFSIZE); memset(buf, 0, BUFSIZE); int ret = send(iSockFd,(void *)strHttpHead,strlen(strHttpHead)+1,0); free(strHttpHead); if (ret < 0) { DebugOut("%s %s %d\tsend error! Error code: %d,Error message: %s\n", __FILE__, __FUNCTION__, __LINE__, errno, strerror(errno)); close(iSockFd); return NULL; } while(1) { ret = recv(iSockFd, (void *)buf, BUFSIZE,0); if (ret == 0) //连接关闭 { close(iSockFd); return NULL; } else if(ret > 0) { return buf; } else if(ret < 0) //出错 { if(errno == EINTR || errno == EWOULDBLOCK || errno == EAGAIN) { continue; } else { close(iSockFd); return NULL; } } } } //从HTTP请求URL中获取主机地址,网址或者点分十进制IP地址 char* HttpRequest::GetHostAddrFromUrl(const char* strUrl) { char url[URLSIZE] = {0}; strcpy(url, strUrl); char* strAddr = strstr(url, "http://");//判断有没有http:// if(strAddr == NULL) { strAddr = strstr(url, "https://");//判断有没有https:// if(strAddr != NULL) { strAddr += 8; } } else { strAddr += 7; } if(strAddr == NULL) { strAddr = url; } int iLen = strlen(strAddr); char* strHostAddr = (char*)malloc(iLen+1); memset(strHostAddr, 0, iLen+1); for(int i=0; i<iLen+1; i++) { if(strAddr[i] == '/') { break; } else { strHostAddr[i] = strAddr[i]; } } return strHostAddr; } //从HTTP请求URL中获取HTTP请参数 char* HttpRequest::GetParamFromUrl(const char* strUrl) { char url[URLSIZE] = {0}; strcpy(url, strUrl); char* strAddr = strstr(url, "http://");//判断有没有http:// if(strAddr == NULL) { strAddr = strstr(url, "https://");//判断有没有https:// if(strAddr != NULL) { strAddr += 8; } } else { strAddr += 7; } if(strAddr == NULL) { strAddr = url; } int iLen = strlen(strAddr); char* strParam = (char*)malloc(iLen+1); memset(strParam, 0, iLen+1); int iPos = -1; for(int i=0; i<iLen+1; i++) { if(strAddr[i] == '/') { iPos = i; break; } } if(iPos == -1) { strcpy(strParam, "");; } else { strcpy(strParam, strAddr+iPos+1); } return strParam; } //从HTTP请求URL中获取端口号 int HttpRequest::GetPortFromUrl(const char* strUrl) { int iPort = -1; char* strHostAddr = GetHostAddrFromUrl(strUrl); if(strHostAddr == NULL) { return -1; } char strAddr[URLSIZE] = {0}; strcpy(strAddr, strHostAddr); free(strHostAddr); char* strPort = strchr(strAddr, ':'); if(strPort == NULL) { iPort = 80; } else { iPort = atoi(++strPort); } return iPort; } //从HTTP请求URL中获取IP地址 char* HttpRequest::GetIPFromUrl(const char* strUrl) { char* strHostAddr = GetHostAddrFromUrl(strUrl); int iLen = strlen(strHostAddr); char* strAddr = (char*)malloc(iLen+1); memset(strAddr, 0, iLen+1); int iCount = 0; int iFlag = 0; for(int i=0; i<iLen+1; i++) { if(strHostAddr[i] == ':') { break; } strAddr[i] = strHostAddr[i]; if(strHostAddr[i] == '.') { iCount++; continue; } if(iFlag == 1) { continue; } if((strHostAddr[i] >= '0') || (strHostAddr[i] <= '9')) { iFlag = 0; } else { iFlag = 1; } } free(strHostAddr); if(strlen(strAddr) <= 1) { return NULL; } //判断是否为点分十进制IP地址,否则通过域名地址获取IP地址 if((iCount == 3) && (iFlag == 0)) { return strAddr; } else { struct hostent *he = gethostbyname(strAddr); free(strAddr); if (he == NULL) { return NULL; } else { struct in_addr** addr_list = (struct in_addr **)he->h_addr_list; for(int i = 0; addr_list[i] != NULL; i++) { return inet_ntoa(*addr_list[i]); } return NULL; } } } //检查SocketFd是否为可写不可读状态 int HttpRequest::SocketFdCheck(const int iSockFd) { struct timeval timeout ; fd_set rset,wset; FD_ZERO(&rset); FD_ZERO(&wset); FD_SET(iSockFd, &rset); FD_SET(iSockFd, &wset); timeout.tv_sec = 3; timeout.tv_usec = 500; int iRet = select(iSockFd+1, &rset, &wset, NULL, &timeout); if(iRet > 0) { //判断SocketFd是否为可写不可读状态 int iW = FD_ISSET(iSockFd,&wset); int iR = FD_ISSET(iSockFd,&rset); if(iW && !iR) { char error[4] = ""; socklen_t len = sizeof(error); int ret = getsockopt(iSockFd,SOL_SOCKET,SO_ERROR,error,&len); if(ret == 0) { if(!strcmp(error, "")) { return iRet;//表示已经准备好的描述符数 } else { DebugOut("%s %s %d\tgetsockopt error code:%d,error message:%s", __FILE__, __FUNCTION__, __LINE__, errno, strerror(errno)); } } else { DebugOut("%s %s %d\tgetsockopt failed. error code:%d,error message:%s", __FILE__, __FUNCTION__, __LINE__, errno, strerror(errno)); } } else { DebugOut("%s %s %d\tsockFd是否在可写字符集中:%d,是否在可读字符集中:%d\t(0表示不在)\n", __FILE__, __FUNCTION__, __LINE__, iW, iR); } } else if(iRet == 0) { return 0;//表示超时 } else { return -1;//select出错,所有描述符集清0 } return -2;//其他错误 } //打印输出 void HttpRequest::DebugOut(const char *fmt, ...) { #ifdef __DEBUG__ va_list ap; va_start(ap, fmt); vprintf(fmt, ap); va_end(ap); #endif } int HttpRequest::m_iSocketFd = INVALID_SOCKET; HttpRequest::HttpRequest(void) { }
#ifndef RECHERCHERSTOCK_H #define RECHERCHERSTOCK_H #include <QDialog> namespace Ui { class rechercherstock; } class rechercherstock : public QDialog { Q_OBJECT public: explicit rechercherstock(QWidget *parent = 0); ~rechercherstock(); private slots: void on_RprecedentPB_clicked(); private: Ui::rechercherstock *ui; }; #endif // RECHERCHERSTOCK_H
#include "Q03.h" // (1) 简单选择排序 time: O(n^2) space: O(1) 不稳定 顺序存储(链式存储) void selectSort(int A[], int n){ // 选择一个最小的值,和第一个值进行交换 for(int i=0; i<n-1; i++) { int min=i; for(int j=i+1; j<n; j++) { if(A[j] < A[min]) min = j; } if(min != i) { int temp = A[i]; A[i] = A[min]; A[min] = temp; } } } // (2) 堆排序: 小根堆 time: O(n*log2(n)) space: O(1) 不稳定 顺序存储(链式存储) void buildMaxHeap(int A[], int n) //建立最大堆 { for(int i=n/2-1; i>=0; i--) maxHeapIfy(A, i, n); } void maxHeapIfy(int A[], int i, int n) //将i节点为根的堆中小的数依次上移,n表示堆中的数据个数 { int l = 2*i+1; // 左儿子 int r = 2*i+2; // 右儿子 int largest = i; // 假设当前最大值为父节点i if (l < n && A[l] > A[largest]) largest = l; if (r < n && A[r] > A[largest]) largest = r; if(largest != i) { swap(A[largest], A[i]); maxHeapIfy(A, largest, n); } } void heapSort(int A[], int n) //堆排序算法 { // 1、建堆 buildMaxHeap(A, n); // 2、交换和下沉 for(int i=n-1; i>0; i--) { swap(A[i], A[0]); maxHeapIfy(A, 0, i); } }
#include <iostream> #include <stack> #include <vector> using namespace std; // 300 600 200 500 (O) | 600, 500 | vector<int> getBuildingsWithView(vector<int> buildings) { vector<int> result; if (buildings.size() == 0) { return result; } stack<int> st; st.push(buildings[0]); for (int i = 1; i < buildings.size(); i++) { if (buildings[i] > st.top()) { st.pop(); while (!st.empty()) { if (buildings[i] > st.top()) { st.pop(); } else { break; } } st.push(buildings[i]); } else { st.push(buildings[i]); } } while(!st.empty()) { result.push_back(st.top()); st.pop(); } } int main() { vector<int> buildings; buildings.push_back(800); buildings.push_back(100); buildings.push_back(80); buildings.push_back(500); vector<int> results = getBuildingsWithView(buildings); for (int i = 0; i < results.size(); i++) { cout << results[i] << " "; } }
#pragma once #include "../../math/maths.h" #include "../buffers/buffer.h" #include "../buffers/indexbuffer.h" #include "../buffers/vertexarray.h" #include "../renderer/renderer2D.h" #include "../shader/shader.h" #include "../texture/texture.h" #include "../../event/events.h" #define _DEBUG_DRAW 1 namespace sge { namespace graphics{ struct VertexData { math::vec3 vertex; math::vec2 uv; float tid; unsigned int color; }; class Renderable2D{ protected: math::Rectangle m_Bounds; math::vec2 m_Position; math::vec2 m_Size; unsigned int m_Color; std::vector<math::vec2> m_UV; Texture *m_Texture; bool isVisible; protected: Renderable2D(){setUVDefaults();m_Texture = nullptr; isVisible = true;} public: Renderable2D(math::vec2 position, math::vec2 size, unsigned int color) : m_Position(position), m_Size(size), m_Color(color){ m_Bounds = math::Rectangle(math::vec2(position.x + size.x/2, position.y + size.y/2), math::vec2(size.x/2, size.y/2)); setUVDefaults(); m_Texture = nullptr; isVisible = true; } virtual ~Renderable2D(){} virtual void submit(Renderer2D* renderer) const{ #if _DEBUG_DRAW renderer->drawRect(m_Bounds, GREEN); #endif renderer->submit(this); } void setColor(unsigned int color){m_Color = color;} void setColor(const math::vec4 color){ int r = color.x * 255.0f; int g = color.y * 255.0f; int b = color.z * 255.0f; int a = color.w * 255.0f; m_Color = a << 24 | b << 16 | g << 8 | r; } virtual void onEvent(events::Event& event) {} virtual void onUpdate() {} inline const math::vec2 getPosition() const { return m_Position;} inline const math::vec2 getSize() const { return m_Size;} inline const math::Rectangle getBoundBox() const { return m_Bounds;} inline const unsigned int getColor() const { return m_Color;} inline const std::vector<math::vec2>& getUV() const { return m_UV;} inline const GLuint getTID() const { return (m_Texture == nullptr) ? 0 : m_Texture->getID();} private: void setUVDefaults(){ m_UV.push_back(math::vec2(0, 0)); m_UV.push_back(math::vec2(0, 1)); m_UV.push_back(math::vec2(1, 1)); m_UV.push_back(math::vec2(1, 0)); } }; }}
#include <bits/stdc++.h> using namespace std; #define MOD 1000000007 #define rep(i, n) for(int i = 0; i < (int)(n); i++) #define rep1(i, n) for(int i = 1; i <= (int)(n); i++) #define show(x) {for(auto i: x){cout << i << " ";} cout<<endl;} #define showm(m) {for(auto i: m){cout << m.x << " ";} cout<<endl;} typedef long long ll; typedef pair<int, int> P; ll gcd(int x, int y){ return y?gcd(y, x%y):x;} ll lcm(ll x, ll y){ return (x*y)/gcd(x,y);} int main() { int len[] = {1, 1, 1, 2, 1, 2, 1, 5, 2, 2, 1, 5, 1, 2, 1, 14, 1, 5, 1, 5, 2, 2, 1, 15, 2, 2, 5, 4, 1, 4, 1, 51}; int k; cin >> k; cout << len[k-1] << endl; }
#include <iostream> #include "daemon.h" int main(int argc, char** argv) { if (argc != 2) { printf("Usage: ./%s filename.cfg\n", DAEMON_NAME); return EXIT_FAILURE; } startDaemon(argv[1]); }
#ifndef SERVO_MOVE_H #define SERVO_MOVE_H #include "bluetooth.h" #include "timeDelay.h" class servo : public Bluetooth, public timeDelay { public: void servoSetup(); void servoRead(); void servoMove(int *finalPos); byte getSpeed(); char getDir(); #define HOMEPOSY 90 #define HOMEPOSZ 90 int finalPosC[13] = {HOMEPOSZ, HOMEPOSZ, HOMEPOSZ, HOMEPOSY - 20, HOMEPOSY + 30, HOMEPOSY - 20, HOMEPOSZ, HOMEPOSZ, HOMEPOSZ, HOMEPOSY - 20, HOMEPOSY + 30, HOMEPOSY - 20, 10}; int finalPosD[13] = {HOMEPOSZ - 30, HOMEPOSZ, HOMEPOSZ - 30, HOMEPOSY, HOMEPOSY, HOMEPOSY, HOMEPOSZ, HOMEPOSZ - 30, HOMEPOSZ, HOMEPOSY, HOMEPOSY, HOMEPOSY, 10}; int finalPosB[13] = {HOMEPOSZ, HOMEPOSZ - 30, HOMEPOSZ, HOMEPOSY, HOMEPOSY, HOMEPOSY, HOMEPOSZ - 30, HOMEPOSZ, HOMEPOSZ - 30, HOMEPOSY, HOMEPOSY, HOMEPOSY, 10}; int finalPosA[13] = {HOMEPOSZ, HOMEPOSZ, HOMEPOSZ, HOMEPOSY + 20, HOMEPOSY - 30, HOMEPOSY + 20, HOMEPOSZ, HOMEPOSZ, HOMEPOSZ, HOMEPOSY + 20, HOMEPOSY - 30, HOMEPOSY + 20, 10}; int finalPosH[13] = {HOMEPOSZ, HOMEPOSZ, HOMEPOSZ, HOMEPOSY + 20, HOMEPOSY - 30, HOMEPOSY + 20, HOMEPOSZ, HOMEPOSZ, HOMEPOSZ, HOMEPOSY - 20, HOMEPOSY + 30, HOMEPOSY - 20, 10}; int finalPosI[13] = {HOMEPOSZ, HOMEPOSZ, HOMEPOSZ, HOMEPOSY - 20, HOMEPOSY + 30, HOMEPOSY - 20, HOMEPOSZ, HOMEPOSZ, HOMEPOSZ, HOMEPOSY + 20, HOMEPOSY - 30, HOMEPOSY + 20, 10}; private: bool delayDone; bool positionOk; int myservo_pos[12]; int diff[12]; int maxDiff; char dir; int var; int moveDelay = 30; int v1; int v2; }; #endif
#pragma once using namespace Ogre; enum E_ENTITY_TYPE { E_NULL_ENTITY_TYPE = 0, E_BRUSH_ENTITY_TYPE, E_NPC_ENTITY_TYPE, E_ENTITY_TYPE_NUM }; class EntityEx : public UserObjectBindings { public: EntityEx(); ~EntityEx(); E_ENTITY_TYPE GetEntityType() const; void SetEntityType( E_ENTITY_TYPE type ); void Create( const String& entityName, const String& meshName, const String& mtlName ); void Destroy(); void setPosition( const Vector3& pos ); Entity* GetEntity() const; SceneNode* GetSceneNode() const; String GetName(); void SetVisible(bool bShow); protected: E_ENTITY_TYPE m_eEntityType; SceneNode* mpSceneNode; Entity* mpEntity; String msEntityName; SceneManager* mpSceneMgr; bool mbVisible; ////////////////////////////////////////////////////////////////////////// SceneNode* mpTipNode; BillboardSet* mpTipBoard; String msBillboardName; };
#ifndef GLOBAL_TYPES_H #define GLOBAL_TYPES_H #include <iostream> #include <unistd.h> #include <cmath> #include <cstdio> #include <cstdlib> #include <stdint.h> #define MAX_COLS 32 #define MAX_MEM_ROWS (1<<16) #define MAX_CHARS 256 #define MAX_TABLES 128 #define MAX_NUM_CMDS 16 #define MAX_CLAUSES 16 #define MAX_AND_CLAUSES 4 #define MAX_OR_CLAUSES (MAX_CLAUSES/MAX_AND_CLAUSES) struct TableMetaEntry { char tableName[MAX_CHARS]; char colNames[MAX_COLS][MAX_CHARS]; uint32_t numRows; uint32_t numCols; uint32_t startAddr; }; enum CmdOp {SELECT, PROJECT, UNION, DIFFERENCE, XPROD, DEDUP, RENAME}; enum CompOp {EQ, LT, LE, GT, GE, NE}; enum ClauseType {COL_COL, COL_VAL}; enum ClauseCon {AND, OR}; struct SelClause { ClauseType clauseType; uint32_t colOffset0; uint32_t colOffset1; CompOp op; long int val; }; struct CmdEntry { CmdOp op; uint32_t table0Addr; uint32_t table0numRows; uint32_t table0numCols; uint32_t outputAddr; //Addr for output table //Select uint32_t numClauses; SelClause clauses[MAX_CLAUSES]; ClauseCon con[MAX_CLAUSES-1]; //AND/OR connectors between clauses //Project uint32_t colProjectMask; //Union/Diff/Xprod uint32_t table1Addr; uint32_t table1numRows; uint32_t table1numCols; }; //Global structures extern uint32_t globalMem[MAX_MEM_ROWS][MAX_COLS]; extern TableMetaEntry globalTableMeta[MAX_TABLES]; extern uint32_t globalNextMeta; extern uint32_t globalNextAddr; extern CmdEntry globalCmdEntryBuff[MAX_NUM_CMDS]; extern uint32_t globalNCmds; //Global access functions /* uint32_t getNextMeta (); uint32_t getNextAddr (TableMetaEntry tableMeta); */ #endif //GLOBAL_TYPES_H
#include <iostream> #include <string> class Move{ public: int x1; int y1; int x2; int y2; int player; Move(); Move(int x1, int y1, int x2, int y2, int player); std::string to_string(); };
#pragma once #include <pthread.h> #include "PThreadHelp.hpp" namespace SCMP { using pthreadhelp::SimpleQueue; template<class T> class Queue : public SimpleQueue<T> { public: Queue(); Queue(const Queue<T> &another); Queue<T>& operator=(const Queue<T> &another); ~Queue(); void enqueue(const T &item); T dequeue(); bool empty() const; private: using typename pthreadhelp::SimpleQueue<T>::QueueNode; using typename pthreadhelp::SimpleQueue<T>::PNode; PNode mStub; }; template<class T> Queue<T>::Queue(const Queue<T> &another) { this->mBack = this->mFront = mStub = new QueueNode(); if (!another.empty()) { PNode cur = another.mFront; if (cur == another.mStub) { cur = cur->next; } for (;cur; cur = cur->next) { enqueue(cur->data); } } } template<class T> Queue<T>& Queue<T>::operator=(const Queue<T> &another) { if (&another == this) { return *this; } this->mBack = this->mFront = mStub = new QueueNode(); if (!another.empty()) { PNode cur = another.mFront; if (cur == another.mStub) { cur = cur->next; } for (;cur; cur = cur->next) { enqueue(cur->data); } } return *this; } template<class T> Queue<T>::Queue() { this->mBack = this->mFront = mStub = new QueueNode(); } template<class T> Queue<T>::~Queue() {} template<class T> bool Queue<T>::empty() const { return this->mBack == mStub; } template<class T> T Queue<T>::dequeue() { PNode front = this->mFront; PNode next = front->next; if (front == mStub) { // trying to pop en element from empty queue if (next == nullptr) { return T(); } this->mFront = next; front = next; next = next->next; } if (next) { this->mFront = next; return front->data; } PNode back = this->mBack; // trying to pop en element from empty queue if (back != front) { return T(); } mStub->next = nullptr; PNode prevNode = (QueueNode*) __sync_val_compare_and_swap(&this->mBack, this->mBack, mStub); prevNode->next = mStub; next = front->next; if (next) { this->mFront = next; return front->data; } return T(); } template<class T> void Queue<T>::enqueue(T const &item) { PNode newNode = new QueueNode(item); PNode prevNode = (QueueNode*) __sync_val_compare_and_swap(&this->mBack, this->mBack, newNode); prevNode->next = this->mBack; } }
#include <iostream> #include <string> #include "BirthAnalysis.h" using namespace std; template <typename T> bool testAnswer(const string &nameOfTest, const T& received, const T& expected) { if (received == expected) { cout << "PASSED " << nameOfTest << ": expected and received " << received << endl; return true; } cout << "FAILED " << nameOfTest << ": expected " << expected << " but received " << received << endl; return false; } int main() { { cout << "Testing with small data file ..." << endl; BirthAnalysis b("data1.txt"); testAnswer("data1.txt: totalNumberOfBirths", b.totalNumberOfBirths(), 10); testAnswer("data1.txt: numberOfBirths in Stanislaus_County", b.numberOfBirths("Stanislaus_County"), 2); testAnswer("data1.txt: countyWithMostBirths", b.countyWithMostBirths(), (string)"Sutter_County"); } { cout << "Testing with large data file ..." << endl; BirthAnalysis b("data2.txt"); testAnswer("data2.txt: totalNumberOfBirths", b.totalNumberOfBirths(), 3076); testAnswer("data2.txt: numberOfBirths in Calaveras_County", b.numberOfBirths("Calaveras_County"), 81); testAnswer("data2.txt: countyWithMostBirths", b.countyWithMostBirths(), (string)"Amador_County"); } // system("pause"); // uncomment to pause main program for testing in Visual Studio return (0); }
// // 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. // // @author Arjan van Leeuwen (arjanl) // #ifndef AUTHENTICATION_COMMAND_H #define AUTHENTICATION_COMMAND_H #include "adjunct/m2/src/backend/imap/commands/ImapCommandItem.h" #include "adjunct/m2/src/backend/imap/imap-protocol.h" namespace ImapCommands { /** @brief Authentication commands */ class Authentication : public ImapCommandItem { public: Authentication() : m_continuation(0) {} OP_STATUS PrepareContinuation(IMAP4& protocol, const OpStringC8& response_text) { m_continuation++; return OpStatus::OK; } BOOL UsesPassword() const { return TRUE; } BOOL IsUnnecessary(const IMAP4& protocol) const { return protocol.GetState() & ImapFlags::STATE_AUTHENTICATED; } OP_STATUS OnSuccessfulComplete(IMAP4& protocol) { protocol.AddState(ImapFlags::STATE_AUTHENTICATED); return OpStatus::OK; } int NeedsState(BOOL secure, IMAP4& protocol) const { return GetDefaultFlags(secure, protocol) & ~(ImapFlags::STATE_AUTHENTICATED | ImapFlags::STATE_ENABLED_QRESYNC | ImapFlags::STATE_COMPRESSED); } ProgressInfo::ProgressAction GetProgressAction() const { return ProgressInfo::AUTHENTICATING; } BOOL IsContinuation() const { return m_continuation > 0; } OP_STATUS PrepareToSend(IMAP4& protocol) { protocol.RemoveState(ImapFlags::STATE_RECEIVED_CAPS); return OpStatus::OK; } OP_STATUS OnFailed(IMAP4& protocol, const OpStringC8& failed_msg); BOOL HandleBye(IMAP4& protocol) { OpStatus::Ignore(OnFailed(protocol, "")); return TRUE; } protected: unsigned m_continuation; }; /** @brief Authenticate meta-command, use if you want to authenticate */ class Authenticate : public ImapCommandItem { public: BOOL IsMetaCommand(IMAP4& protocol) const { return TRUE; } ImapCommandItem* GetExpandedQueue(IMAP4& protocol); }; /** @brief AUTHENTICATE CRAM-MD5 command */ class AuthenticateCramMD5 : public Authentication { public: OP_STATUS PrepareContinuation(IMAP4& protocol, const OpStringC8& response_text); protected: OP_STATUS AppendCommand(OpString8& command, IMAP4& protocol); OpString8 m_md5_response; }; /** @brief AUTHENTICATE LOGIN command */ class AuthenticateLogin : public Authentication { protected: OP_STATUS AppendCommand(OpString8& command, IMAP4& protocol); }; /** @brief AUTHENTICATE PLAIN command */ class AuthenticatePlain : public Authentication { protected: OP_STATUS AppendCommand(OpString8& command, IMAP4& protocol); }; /** @brief LOGIN command (plaintext login) */ class Login : public Authentication { protected: OP_STATUS AppendCommand(OpString8& command, IMAP4& protocol); }; }; #endif // AUTHENTICATION_COMMAND_H
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4; c-file-style: "stroustrup" -*- */ #include "core/pch.h" #include "modules/ecmascript/carakan/src/es_pch.h" #include "modules/ecmascript/carakan/src/builtins/es_builtins.h" #include "modules/ecmascript/carakan/src/kernel/es_string.h" #include "modules/ecmascript/carakan/src/kernel/es_string_inlines.h" #include "modules/ecmascript/carakan/src/builtins/es_string_builtins.h" #include "modules/ecmascript/carakan/src/object/es_string_object.h" #include "modules/ecmascript/carakan/src/object/es_regexp_object.h" #include "modules/ecmascript/carakan/src/object/es_array_object.h" #include "modules/ecmascript/carakan/src/builtins/es_regexp_builtins.h" #include "modules/ecmascript/carakan/src/compiler/es_lexer.h" #include "modules/regexp/include/regexp_advanced_api.h" #ifndef _STANDALONE # include "modules/pi/OpLocale.h" # include "modules/pi/pi_module.h" #endif #define ES_THIS_STRING() if (!ProcessThis(context, argv[-2])) return FALSE; JString *this_string = argv[-2].GetString(); #define ES_CHECK_CALLABLE(index, msg) do { if (index >= argc || !argv[index].IsObject() || !argv[index].GetObject(context)->IsFunctionObject()) context->ThrowTypeError(msg); } while (0) #define TYPE_ERROR_TO_STRING "String.prototype.toString: this is not a String object" #define TYPE_ERROR_VALUE_OF "String.prototype.valueOf: this is not a String object" /* static */ BOOL ES_StringBuiltins::constructor_call(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value) { JString *result_string; if (argc == 0) result_string = context->rt_data->strings[STRING_empty]; else { if (!argv[0].ToString(context)) return FALSE; result_string = argv[0].GetString(); } return_value->SetString(result_string); return TRUE; } /* static */ BOOL ES_StringBuiltins::constructor_construct(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value) { JString *value_string; if (argc == 0) value_string = context->rt_data->strings[STRING_empty]; else { if (!argv[0].ToString(context)) return FALSE; value_string = argv[0].GetString(); } return_value->SetObject(ES_String_Object::Make(context, ES_GET_GLOBAL_OBJECT(), value_string)); return TRUE; } static BOOL ToStringType(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value, BOOL to_string) { JString *this_string; ES_Value_Internal this_arg = argv[-2]; if (this_arg.IsString()) this_string = this_arg.GetString(); else if (this_arg.IsObject() && this_arg.GetObject(context)->IsStringObject()) this_string = static_cast<ES_String_Object *>(this_arg.GetObject(context))->GetValue(); else { context->ThrowTypeError(to_string ? TYPE_ERROR_TO_STRING : TYPE_ERROR_VALUE_OF); return FALSE; } return_value->SetString(this_string); return TRUE; } /* static */ BOOL ES_StringBuiltins::toString(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value) { return ToStringType(context, argc, argv, return_value, TRUE); } /* static */ BOOL ES_StringBuiltins::valueOf(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value) { return ToStringType(context, argc, argv, return_value, FALSE); } /* static */ BOOL ES_StringBuiltins::toLowerCase(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value) { ES_THIS_STRING(); return_value->SetString(ConvertCase(context, this_string, TRUE)); return TRUE; } /* static */ BOOL ES_StringBuiltins::toLocaleLowerCase(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value) { // TODO: implement this function correctly ES_THIS_STRING(); return_value->SetString(ConvertCase(context, this_string, TRUE)); return TRUE; } /* static */ BOOL ES_StringBuiltins::toUpperCase(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value) { ES_THIS_STRING(); return_value->SetString(ConvertCase(context, this_string, FALSE)); return TRUE; } /* static */ BOOL ES_StringBuiltins::toLocaleUpperCase(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value) { // TODO: implement this function correctly ES_THIS_STRING(); return_value->SetString(ConvertCase(context, this_string, FALSE)); return TRUE; } /* static */ BOOL ES_StringBuiltins::charCodeAt(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value) { ES_THIS_STRING(); int idx = 0; if (argc >= 1) { if (!argv[0].ToNumber(context)) return FALSE; idx = argv[0].GetNumAsBoundedInt32(); } if (idx >= 0 && idx < (int)Length(this_string)) { uni_char uc = Element(this_string, (int)idx); return_value->SetUInt32((UINT32)uc); } else return_value->SetNan(); return TRUE; } /* static */ BOOL ES_StringBuiltins::charAt(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value) { ES_THIS_STRING(); int idx = 0; if (argc >= 1) { if (!argv[0].ToNumber(context)) return FALSE; idx = argv[0].GetNumAsBoundedInt32(); } if (idx >= 0 && idx < (int)Length(this_string)) { uni_char uc = Element(this_string, (int)idx); return_value->SetString(JString::Make(context, &uc, 1)); } else return_value->SetString(JString::Make(context, "")); return TRUE; } /* static */ BOOL ES_StringBuiltins::substring(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value) { ES_THIS_STRING(); size_t length = Length(this_string); int startidx = 0; if (argc >= 1) { if (!argv[0].ToNumber(context)) return FALSE; startidx = argv[0].GetNumAsBoundedInt32(); } int endidx = length; if (argc >= 2 && !argv[1].IsUndefined()) { if (!argv[1].ToNumber(context)) return FALSE; endidx = argv[1].GetNumAsBoundedInt32(); } startidx = es_mini(es_maxi(startidx, 0), length); endidx = es_mini(es_maxi(endidx, 0), length); int from = es_mini(startidx, endidx); int to = es_maxi(startidx, endidx); return_value->SetString(JString::Make(context, this_string, from, to - from)); return TRUE; } /* static */ BOOL ES_StringBuiltins::substr(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value) { ES_THIS_STRING(); size_t length = Length(this_string); int startidx = 0; if (argc >= 1) { if (!argv[0].ToNumber(context)) return FALSE; startidx = argv[0].GetNumAsBoundedInt32(); if (startidx < 0) startidx = es_maxi(0, startidx + length); } int slen = length - startidx; if (argc >= 2 && !argv[1].IsUndefined()) { if (!argv[1].ToNumber(context)) return FALSE; slen = es_mini(slen, es_maxi(0, argv[1].GetNumAsBoundedInt32())); } if (slen <= 0) return_value->SetString(context->rt_data->strings[STRING_empty]); else return_value->SetString(JString::Make(context, this_string, startidx, slen)); return TRUE; } /* static */ BOOL ES_StringBuiltins::slice(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value) { ES_THIS_STRING(); size_t length = Length(this_string); int startidx = 0; if (argc >= 1) { if (!argv[0].ToNumber(context)) return FALSE; startidx = argv[0].GetNumAsBoundedInt32(); } int endidx = length; if (argc >= 2 && !argv[1].IsUndefined()) { if (!argv[1].ToNumber(context)) return FALSE; endidx = argv[1].GetNumAsBoundedInt32(); } startidx = startidx < 0 ? es_maxi((int)length + startidx, 0) : es_mini(startidx, length); endidx = endidx < 0 ? es_maxi((int)length + endidx, 0) : es_mini(endidx, length); int slicelen = es_maxi(endidx - startidx, 0); return_value->SetString(JString::Make(context, this_string, startidx, slicelen)); return TRUE; } /* static */ BOOL ES_StringBuiltins::concat(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value) { ES_THIS_STRING(); GC_STACK_ANCHOR(context, this_string); JString *ret = Share(context, this_string); ES_CollectorLock gclock(context); for (unsigned i = 0; i < argc; i++) { if (!argv[i].ToString(context)) return FALSE; Append(context, ret, argv[i].GetString()); } return_value->SetString(Finalize(context, ret)); return TRUE; } static int ES_IndexOf(const uni_char *haystack, unsigned haystack_length, const uni_char *needle, unsigned needle_length, unsigned offset) { haystack_length -= needle_length - 1; for (unsigned i = 0, j; i < haystack_length; ++i) { for (j = 0; j < needle_length; ++j) if (haystack[i + j] != needle[j]) goto next; return (i + offset); next: ; } return -1; } static BOOL ES_MatchInSegmented(JSegmentIterator iter, unsigned index, const uni_char *needle, unsigned needle_length) { const uni_char *haystack = iter.GetBase()->storage + iter.GetOffset(); unsigned haystack_length = iter.GetLength(); for (unsigned i = 0, j = index; i < needle_length; ++i) { if (haystack[j] != needle[i]) return FALSE; if (++j == haystack_length) { iter.Next(); haystack = iter.GetBase()->storage + iter.GetOffset(); haystack_length = iter.GetLength(); j = 0; } } return TRUE; } static int ES_IndexOfInSegmented(JString *haystack, unsigned index, const uni_char *needle, unsigned needle_length, unsigned offset) { JSegmentIterator iter(haystack); unsigned haystack_offset = index; unsigned haystack_length = Length(haystack) - index - (needle_length - 1); while (iter.Next() && haystack_offset >= iter.GetLength()) haystack_offset -= iter.GetLength(); for (unsigned i = 0, j = haystack_offset; i < haystack_length; ++i) { if (ES_MatchInSegmented(iter, j, needle, needle_length)) return (i + offset); if (++j == iter.GetLength()) { iter.Next(); j = haystack_offset = 0; } } return -1; } static int ES_IndexOf(JString *haystack, unsigned index, const uni_char *needle, unsigned needle_length) { unsigned haystack_length = Length(haystack) - index; if (haystack_length >= needle_length) if (!IsSegmented(haystack)) return ES_IndexOf(Storage(NULL, haystack) + index, haystack_length, needle, needle_length, index); else return ES_IndexOfInSegmented(haystack, index, needle, needle_length, index); else return -1; } /* static */ BOOL ES_StringBuiltins::indexOf(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value) { ES_THIS_STRING(); int length = Length(this_string); if (argc >= 1) { if (!argv[0].ToString(context)) return FALSE; JString *search_string = argv[0].GetString(); int pos = 0; if (argc >= 2) { if (!argv[1].ToNumber(context)) return FALSE; pos = argv[1].GetNumAsBoundedInt32(); pos = es_mini(es_maxi(pos, 0), length); } return_value->SetInt32(ES_IndexOf(this_string, pos, Storage(context, search_string), Length(search_string))); } else return_value->SetInt32(-1); return TRUE; } /* static */ BOOL ES_StringBuiltins::lastIndexOf(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value) { ES_THIS_STRING(); int res = -1; int length = Length(this_string); if (argc >= 1) { if (!argv[0].ToString(context)) return FALSE; JString* search_string = argv[0].GetString(); int searchlen = Length(search_string); int pos = INT_MAX; if (argc >= 2) { if (!argv[1].ToNumber(context)) return FALSE; pos = argv[1].GetNumAsBoundedInt32(INT_MAX); } pos = es_mini(es_maxi(pos, 0), length - searchlen); uni_char* src = Storage(context, this_string); uni_char* needle = Storage(context, search_string); for (int i = pos; i >= 0; i--) { int curr_pos = 0; while (curr_pos < searchlen) { OP_ASSERT(i + curr_pos < length); if (src[i + curr_pos] != needle[curr_pos]) break; curr_pos++; } if (curr_pos == searchlen) { res = i; break; } } } return_value->SetInt32(res); return TRUE; } #ifndef _STANDALONE class ES_SuspendedLocaleCompare : public ES_SuspendedCall { public: ES_SuspendedLocaleCompare(ES_Execution_Context *context, JString *str1, JString *str2) : result(-1), status(OpStatus::OK), str1(str1), str2(str2) { context->SuspendedCall(this); } int result; OP_STATUS status; private: virtual void DoCall(ES_Execution_Context *context) { TRAP(status, result = g_oplocale->CompareStringsL(StorageZ(context, str1), StorageZ(context, str2))); } JString *str1; JString *str2; }; #endif // _STANDALONE /* static */ BOOL ES_StringBuiltins::localeCompare(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value) { ES_THIS_STRING(); int res = 0; if (argc >= 1) { if (!argv[0].ToString(context)) return FALSE; JString* compare_string = argv[0].GetString(); #ifndef _STANDALONE ES_SuspendedLocaleCompare lc_compare(context, this_string, compare_string); LEAVE_IF_ERROR(lc_compare.status); res = lc_compare.result; #else res = Compare(context, this_string, compare_string); #endif // _STANDALONE } return_value->SetInt32(res); return TRUE; } typedef ES_Boxed_Array ReplacementItem; /** ReplacementItem is a struct with 3 members: { JStringStorage *base; unsigned offset, length; } We always allocate an array of these, but since we want to allocate them on the ES heap, things get a bit hairy, due to the first member being a ES_Boxed while second and third are scalar. ES_Boxed_Array is used with (nslots : nused) ratio 3:1; The first third of the slots stores the base(s) second 2/3 stores offset(s) and length(s). So i-th items's base is stored at items->slots[i] while its offset & length are stored at items->uints[items->nused + 2*i] and items->uints[items->nused + 2*i+1] That's the sophisticated part of it. */ void SetFinalItem(ReplacementItem *items, unsigned item_idx, JStringStorage *new_base, unsigned new_offset, unsigned new_length) { OP_ASSERT(!IsSegmented(new_base)); OP_ASSERT(new_offset < INT_MAX); OP_ASSERT(item_idx < items->nused); OP_ASSERT(new_length); items->slots[item_idx] = new_base; items->uints[items->nused + 2*item_idx] = new_offset; items->uints[items->nused + 2*item_idx+1] = new_length; } void SetFinalItem(ReplacementItem *items, unsigned item_idx, ES_Context *context, JString *new_base, unsigned new_offset, unsigned new_length) { OP_ASSERT(new_offset < INT_MAX); OP_ASSERT(item_idx < items->nused); OP_ASSERT(new_length); items->slots[item_idx] = StorageSegment(context, new_base, new_offset, new_length); items->uints[items->nused + 2*item_idx] = new_offset; items->uints[items->nused + 2*item_idx+1] = new_length; } static void AllocateItemsSlow(ES_Execution_Context *context, ReplacementItem *&items, unsigned &used, unsigned &allocated, unsigned additional, ES_Value_Internal& save_reg) { unsigned new_allocated = allocated < 8 ? 8 : allocated << 2; while (!(used + additional < new_allocated)) new_allocated <<= 1; ReplacementItem *new_items = ReplacementItem::Make(context, 3 * new_allocated, new_allocated); if (items) { op_memcpy(new_items->slots, items->slots, used * sizeof(items->slots[0])); op_memcpy(new_items->uints + new_items->nused, items->uints + items->nused, 2 * used * sizeof(items->slots[0])); } save_reg.SetBoxed(items = new_items); allocated = new_allocated; } static inline void AllocateItems(ES_Execution_Context *context, ReplacementItem *&items, unsigned &used, unsigned &allocated, unsigned additional, ES_Value_Internal& save_reg) { if (used + additional > allocated) AllocateItemsSlow(context, items, used, allocated, additional, save_reg); } /** Class ReplaceValueGenerator is a no-additional-member-vars subclass of ES_Boxed_Array which is there only to add functions to operate on the data kept in the boxed array. Later when we need a generaor, we actually allocate a boxed array and cast-to/view-it-as a generator in order to get to this generator defined functionallity. All this magic is in order to have ReplaceValueGenerator es-heap allocated and GC-proof. */ class ReplaceValueGenerator : public ES_Boxed_Array { public: struct Part { unsigned literal_offset; unsigned literal_length_or_match_index; }; enum { IDX_parts, IDX_replacement, NUSED, IDX_parts_count = NUSED, NSLOTS }; Part* GetParts() const { if (slots[IDX_parts] != NULL) return reinterpret_cast<Part*>( reinterpret_cast<ES_Box*>(slots[IDX_parts])->Unbox() ); return NULL; } unsigned PartsCount() const { return uints[IDX_parts_count]; } void IncPartsCount() { uints[IDX_parts_count]++; } void SetPartsCount(unsigned n) { uints[IDX_parts_count] = 0; } JString* replacement() const { return reinterpret_cast<JString*>(slots[IDX_replacement]); } void AddPart(unsigned literal_offset, unsigned literal_length_or_match_index); void AllocateParts(ES_Context *context); static ReplaceValueGenerator *Make(ES_Execution_Context *context, JString *replacement, unsigned ncaptures); void Measure(unsigned &length, unsigned &items, JString *source, const RegExpMatch *matches); void Generate(ES_Context *context, ReplacementItem *items, unsigned item_idx, JString *source, const RegExpMatch *matches); static inline void CreateGeneratorObject(ES_Execution_Context *context, JString *replacement, BOOL &created_boxed_array, ES_Boxed *&boxed_array); }; void ReplaceValueGenerator::AddPart(unsigned literal_offset, unsigned literal_length_or_match_index) { OP_ASSERT(literal_offset == UINT_MAX || literal_offset < INT_MAX); if (GetParts()) { Part &part = GetParts()[PartsCount()]; part.literal_offset = literal_offset; part.literal_length_or_match_index = literal_length_or_match_index; } IncPartsCount(); } void ReplaceValueGenerator::AllocateParts(ES_Context *context) { slots[IDX_parts] = ES_Box::Make(context, sizeof(Part)*PartsCount()); SetPartsCount(0); } /*static*/ inline void ReplaceValueGenerator::CreateGeneratorObject(ES_Execution_Context *context, JString *replacement, BOOL &created_boxed_array, ES_Boxed *&boxed_array) { if (!created_boxed_array) { boxed_array = ES_Boxed_Array::Make(context, NSLOTS, NUSED); static_cast<ES_Boxed_Array*>(boxed_array)->uints[IDX_parts_count] = 0; static_cast<ES_Boxed_Array*>(boxed_array)->slots[IDX_replacement] = replacement; created_boxed_array = TRUE; } } /* static */ ReplaceValueGenerator * ReplaceValueGenerator::Make(ES_Execution_Context *context, JString *replacement, unsigned ncaptures) { AutoRegisters regs(context, 1); regs[0].SetBoxed(NULL); ES_Boxed *&barr = regs[0].GetBoxed_ref(); BOOL created_boxed_array = FALSE; // Note the trick on next line: we're casting the boxed array to something it isn't // in order to get to the methods defined in its subclass ReplaceValueIterator; // As long as the subclass does not define any member vars, this will work fine: #define generator static_cast<ReplaceValueGenerator*>(static_cast<ES_Boxed_Array*>( barr )) const uni_char *string = Storage(context, replacement); unsigned string_length = Length(replacement); while (TRUE) { const uni_char *ptr = string, *ptr_end = ptr + string_length, *literal_start = string; while (ptr != ptr_end) if (*ptr++ == '$') if (ptr != ptr_end) { switch (*ptr) { case '$': CreateGeneratorObject(context, replacement, created_boxed_array, barr); generator->AddPart(literal_start - string, ptr - literal_start); literal_start = ++ptr; break; case '&': case '`': case '\'': CreateGeneratorObject(context, replacement, created_boxed_array, barr); if (literal_start != ptr - 1) generator->AddPart(literal_start - string, ptr - literal_start - 1); generator->AddPart(~0u, *ptr == '&' ? 0 : *ptr == '`' ? UINT_MAX - 1 : UINT_MAX); literal_start = ++ptr; break; default: const uni_char *stored_ptr = ptr; if (*ptr >= '0' && *ptr <= '9') { unsigned capture_index = *ptr - '0'; if (capture_index <= ncaptures) { ++ptr; if (ptr != ptr_end && *ptr >= '0' && *ptr <= '9' && capture_index * 10 + *ptr - '0' <= ncaptures) { capture_index = capture_index * 10 + *ptr - '0'; ++ptr; } if (capture_index > 0) { CreateGeneratorObject(context, replacement, created_boxed_array, barr); if (literal_start != stored_ptr - 1) generator->AddPart(literal_start - string, (stored_ptr - 1) - literal_start); generator->AddPart(~0u, capture_index); literal_start = ptr; } else ptr = stored_ptr; } } else ptr = stored_ptr; } } if (literal_start != ptr) { CreateGeneratorObject(context, replacement, created_boxed_array, barr); generator->AddPart(literal_start - string, ptr - literal_start); } if (created_boxed_array && generator->GetParts()) return generator; else if (literal_start == string) return NULL; else { CreateGeneratorObject(context, replacement, created_boxed_array, barr); generator->AllocateParts(context); } } #undef generator } void ReplaceValueGenerator::Measure(unsigned &length, unsigned &items, JString *source, const RegExpMatch *matches) { Part *part = GetParts(); for (unsigned index = 0; index < PartsCount(); ++index, ++part) if (part->literal_offset + 1 != 0) { length += part->literal_length_or_match_index; ++items; } else if (part->literal_length_or_match_index == UINT_MAX - 1) { if (matches[0].start > 0) { length += matches[0].start; ++items; } } else if (part->literal_length_or_match_index == UINT_MAX) { if (matches[0].start + matches[0].length < Length(source)) { length += Length(source) - matches[0].start - matches[0].length; ++items; } } else { const RegExpMatch &match = matches[part->literal_length_or_match_index]; unsigned part_length = match.length; if (match.length != UINT_MAX && part_length != 0) { length += part_length; ++items; } } } void ReplaceValueGenerator::Generate(ES_Context *context, ReplacementItem *items, unsigned item_idx, JString *source, const RegExpMatch *matches) { Part *part = GetParts(); for (unsigned index = 0; index < PartsCount(); ++index, ++part) if (part->literal_offset + 1 != 0) { SetFinalItem(items, item_idx++, context, replacement(), part->literal_offset, part->literal_length_or_match_index); } else if (part->literal_length_or_match_index == UINT_MAX - 1) { if (matches[0].start > 0) SetFinalItem(items, item_idx++, context, source, 0, matches[0].start); } else if (part->literal_length_or_match_index == UINT_MAX) { if (matches[0].start + matches[0].length < Length(source)) SetFinalItem(items, item_idx++, context, source, matches[0].start + matches[0].length, Length(source) - matches[0].start - matches[0].length); } else { const RegExpMatch &match = matches[part->literal_length_or_match_index]; unsigned part_length = match.length; if (match.length != UINT_MAX && part_length != 0) SetFinalItem(items, item_idx++, context, source, match.start, part_length); } } static BOOL DetectLexicalMemberLookupFunction(ES_Execution_Context *context, ES_Object *function, ES_Object *&lookup_object) { if (!function->IsHostObject()) if (ES_FunctionCode *code = static_cast<ES_Function *>(function)->GetFunctionCode()) if (code->data->codewords_count < 64) { code->data->FindInstructionOffsets(context); if (code->data->instruction_count == 3) { ES_CodeWord *codewords = code->data->codewords; unsigned *instruction_offsets = code->data->instruction_offsets; if (codewords[0].instruction == ESI_GET_LEXICAL && codewords[instruction_offsets[1]].instruction == ESI_GET && codewords[instruction_offsets[1] + 2].index == codewords[1].index && codewords[instruction_offsets[1] + 3].index == 2 && codewords[instruction_offsets[2]].instruction == ESI_RETURN_VALUE && codewords[instruction_offsets[2] + 1].index == codewords[instruction_offsets[1] + 1].index) { ES_Value_Internal value; static_cast<ES_Function *>(function)->GetLexical(value, codewords[2].index, ES_PropertyIndex(codewords[3].index)); if (value.IsObject()) lookup_object = value.GetObject(context); return TRUE; } } } return FALSE; } static BOOL Unpack(ES_Execution_Context *context, ES_Value_Internal *result, ES_Value_Internal *value, JString *base, ES_RegExp_Object *regexp, ES_Object *lookup_object) { enum { SEGMENT_LENGTH = 16384 }; ES_Boxed_Array *intermediate; result->SetBoxed(intermediate = ES_Boxed_Array::Make(context, 16, 0)); JStringStorage *current = NULL; unsigned offset = SEGMENT_LENGTH; const uni_char *source = Storage(context, base); uni_char *write = NULL; unsigned length = Length(base), last_index = 0; ES_Property_Value_Table *values = lookup_object->GetHashTable(); while (TRUE) { RegExpMatch *matches = regexp->Exec(context, base, last_index); const uni_char *item = source + last_index; unsigned item_length; if (matches) item_length = matches[0].start - last_index; else item_length = length - last_index; while (item_length) { if (offset == SEGMENT_LENGTH) { if (intermediate->nused == intermediate->nslots) result->SetBoxed(intermediate = ES_Boxed_Array::Grow(context, intermediate)); current = JStringStorage::Make(context, (const char *) NULL, SEGMENT_LENGTH + 1, SEGMENT_LENGTH); write = current->storage; offset = 0; intermediate->slots[intermediate->nused++] = current; } unsigned copy = MIN(item_length, SEGMENT_LENGTH - offset); op_memcpy(write + offset, item, UNICODE_SIZE(copy)); offset += copy; item += copy; item_length -= copy; } if (matches) { if (IsEmpty(matches[0])) last_index = matches[0].start + 1; else last_index = matches[0].start + matches[0].length; GetResult res; JString *string; const uni_char *name = source + matches[0].start; unsigned name_length = matches[0].length; unsigned index; if (name_length && *name >= '0' && *name <= '9' && convertindex(name, name_length, index)) res = lookup_object->GetL(context, index, *value); else { JTemporaryString temporary(name, name_length); ES_Value_Internal *location; ES_Property_Info info; if (values && values->FindLocation(temporary, info, location) && location->IsString()) { string = location->GetString(); goto handle_string; } res = lookup_object->GetL(context, temporary, *value); } if (GET_OK(res)) { if (!value->ToString(context)) return FALSE; string = value->GetString(); } else if (GET_NOT_FOUND(res)) string = context->rt_data->strings[STRING_undefined]; else return FALSE; handle_string: item = Storage(context, string); item_length = Length(string); while (item_length) { if (offset == SEGMENT_LENGTH) { if (intermediate->nused == intermediate->nslots) result->SetBoxed(intermediate = ES_Boxed_Array::Grow(context, intermediate)); current = JStringStorage::Make(context, (const char *) NULL, SEGMENT_LENGTH + 1, SEGMENT_LENGTH); write = current->storage; offset = 0; intermediate->slots[intermediate->nused++] = current; } unsigned copy = MIN(item_length, SEGMENT_LENGTH - offset); op_memcpy(write + offset, item, UNICODE_SIZE(copy)); offset += copy; item += copy; item_length -= copy; } } else break; } unsigned nsegments = intermediate->nused; JStringSegmented *segmented; if (nsegments) { result->SetBoxed(segmented = JStringSegmented::Make(context, nsegments)); op_memcpy(segmented->Bases(), intermediate->slots, nsegments * sizeof(ES_Boxed *)); op_memset(segmented->Offsets(), 0, nsegments * sizeof(unsigned)); for (unsigned index = 0; index < nsegments - 1; ++index) segmented->Lengths()[index] = SEGMENT_LENGTH; segmented->Lengths()[nsegments - 1] = offset; context->heap->Free(intermediate); result->SetString(JString::Make(context, segmented, (nsegments - 1) * SEGMENT_LENGTH + offset)); } else result->SetString(context->rt_data->strings[STRING_empty]); return TRUE; } /* static */ BOOL ES_StringBuiltins::replace(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value) { ES_THIS_STRING(); ES_RegExp_Object *regexp_object = NULL; RegExp *regexp = NULL; JString *needle = NULL; unsigned ncaptures; BOOL global; RegExpMatch *matches, local_match; if (argc >= 1 && argv[0].IsObject() && argv[0].GetObject(context)->IsRegExpObject()) { regexp_object = static_cast<ES_RegExp_Object *>(argv[0].GetObject(context)); regexp = regexp_object->GetValue(); ncaptures = regexp->GetNumberOfCaptures(); global = (regexp_object->GetFlagBits() & REGEXP_FLAG_GLOBAL) != 0; matches = regexp_object->GetMatchArray(); } else { if (!argv[0].ToString(context)) return FALSE; needle = argv[0].GetString(); ncaptures = 0; global = FALSE; matches = &local_match; } ES_Object *function = NULL; ES_Object *lookup_object = NULL; ReplaceValueGenerator *generator = NULL; JString *replacement = NULL, *lookup_name = NULL; if (argc >= 2 && argv[1].IsObject() && argv[1].GetObject(context)->IsFunctionObject()) { function = argv[1].GetObject(context); DetectLexicalMemberLookupFunction(context, function, lookup_object); } else { if (argc >= 2) { if (!argv[1].ToString(context)) return FALSE; replacement = argv[1].GetString(); generator = ReplaceValueGenerator::Make(context, replacement, ncaptures); } else replacement = context->rt_data->strings[STRING_undefined]; } if (regexp_object && lookup_object) return Unpack(context, return_value, &argv[-1], this_string, regexp_object, lookup_object); enum { ridx_generator, ridx_lookup_name = ridx_generator, ridx_final_items, ridx_segmented, ridx_scratch, ridx_count }; AutoRegisters regs(context, ridx_count); if (lookup_object) regs[ridx_lookup_name].SetBoxed(lookup_name = JString::MakeTemporary(context)); if (generator) regs[ridx_generator].SetBoxed(generator); const uni_char *this_storage = !IsSegmented(this_string) || !needle || Length(needle) > 1 ? Storage(context, this_string) : NULL; unsigned this_length = Length(this_string); ReplacementItem *final_items = NULL; unsigned final_items_used = 0, final_items_allocated = 0, final_length = 0, previous_match_end = 0, last_index = 0; BOOL is_segmented_search = FALSE, no_matches = TRUE; unsigned segment_index = 0, segment_offset = 0; JSegmentIterator iter(this_string); do { if (needle) { const uni_char *needle_storage = Storage(context, needle), *ptr = this_storage, *ptr_end = 0; unsigned needle_length = Length(needle); unsigned segment_match_start = 0; if (needle_length == 1) { uni_char ch = needle_storage[0]; if (IsSegmented(this_string)) { is_segmented_search = TRUE; unsigned sindex = 0; while (iter.Next()) { const uni_char *ptr_start = ptr = (iter.GetBase())->storage + iter.GetOffset(); ptr_end = ptr + iter.GetLength(); while (ptr != ptr_end && *ptr != ch) ++ptr; if (ptr != ptr_start) { AllocateItems(context, final_items, final_items_used, final_items_allocated, 1, regs[ridx_final_items]); SetFinalItem(final_items, final_items_used++, iter.GetBase(), iter.GetOffset(), ptr - ptr_start); final_length += ptr - ptr_start; } if (ptr != ptr_end) { segment_index = sindex; segment_offset = ptr - ptr_start + 1; segment_match_start += ptr - ptr_start; break; } segment_match_start += iter.GetLength(); ++sindex; } } else { ptr_end = this_storage + this_length; while (ptr != ptr_end && *ptr != ch) ++ptr; } } else { if (needle_length > this_length) goto return_this; if (needle_length > 0) { ptr_end = this_storage + this_length - needle_length + 1; uni_char ch = needle_storage[0]; while (ptr != ptr_end) { if (*ptr == ch) { unsigned i; for (i = needle_length; i > 0;) if (ptr[i - 1] == needle_storage[i - 1]) --i; else break; if (i == 0) break; } ++ptr; } } } if (ptr == ptr_end) goto return_this; local_match.start = is_segmented_search ? segment_match_start : (ptr - this_storage); local_match.length = needle_length; } else { matches = regexp_object->Exec(context, this_string, last_index); if (!matches) break; if (IsEmpty(matches[0])) last_index = matches[0].start + 1; else last_index = matches[0].start + matches[0].length; argv[0].GetObject(context)->PutCachedAtIndex(ES_PropertyIndex(ES_RegExp_Object::LASTINDEX), last_index); } no_matches = FALSE; if (!is_segmented_search) { if (previous_match_end < matches[0].start) { AllocateItems(context, final_items, final_items_used, final_items_allocated, 1, regs[ridx_final_items]); unsigned length = matches[0].start - previous_match_end; SetFinalItem(final_items, final_items_used++, context, this_string, previous_match_end, length); final_length += length; } previous_match_end = matches[0].start + matches[0].length; } if (lookup_object) { unsigned length = matches[0].length, index; GetResult result; ES_Value_Internal &value = regs[ridx_scratch]; if (convertindex(this_storage + matches[0].start, length, index)) result = lookup_object->GetL(context, index, value); else { lookup_name->SetTemporary(this_string, matches[0].start, length); result = lookup_object->GetL(context, lookup_name, value); } JString *string; if (GET_OK(result)) { if (!value.ToString(context)) goto return_false; string = value.GetString(); } else if (GET_NOT_FOUND(result)) string = context->rt_data->strings[STRING_undefined]; else goto return_false; if (Length(string) > 0) { AllocateItems(context, final_items, final_items_used, final_items_allocated, 1, regs[ridx_final_items]); SetFinalItem(final_items, final_items_used++, context, string, 0, Length(string)); final_length += Length(string); } } else if (function) { ES_Value_Internal *registers = context->SetupFunctionCall(function, ncaptures + 3); registers[0].SetUndefined(); registers[1].SetObject(function); registers[2].SetString(MatchSubString(context, this_string, matches[0])); for (unsigned index = 0; index < ncaptures; ++index) if (matches[1 + index].length == UINT_MAX) registers[3 + index].SetUndefined(); else registers[3 + index].SetString(MatchSubString(context, this_string, matches[1 + index])); registers[3 + ncaptures].SetNumber(matches[0].start); registers[4 + ncaptures].SetString(this_string); ES_Value_Internal &returned = regs[ridx_scratch]; if (!context->CallFunction(registers, ncaptures + 3, &returned)) goto return_false; if (!returned.ToString(context)) goto return_false; JString *returned_string = returned.GetString(); if (Length(returned_string) > 0) { AllocateItems(context, final_items, final_items_used, final_items_allocated, 1, regs[ridx_final_items]); SetFinalItem(final_items, final_items_used++, context, returned_string, 0, Length(returned_string)); final_length += Length(returned_string); } } else if (generator) { unsigned items = 0; generator->Measure(final_length, items, this_string, matches); AllocateItems(context, final_items, final_items_used, final_items_allocated, items, regs[ridx_final_items]); generator->Generate(context, final_items, final_items_used, this_string, matches); final_items_used += items; } else if (Length(replacement) != 0) { AllocateItems(context, final_items, final_items_used, final_items_allocated, 1, regs[ridx_final_items]); SetFinalItem(final_items, final_items_used++, context, replacement, 0, Length(replacement)); final_length += Length(replacement); } } while (global && last_index <= this_length); if (global) argv[0].GetObject(context)->PutCachedAtIndex(ES_PropertyIndex(ES_RegExp_Object::LASTINDEX), 0); if (no_matches) goto return_this; if (is_segmented_search) { if (iter.IsValid()) { if (segment_offset != iter.GetLength()) { AllocateItems(context, final_items, final_items_used, final_items_allocated, 1, regs[ridx_final_items]); SetFinalItem(final_items, final_items_used++, iter.GetBase(), iter.GetOffset() + segment_offset, iter.GetLength() - segment_offset); final_length += iter.GetLength() - segment_offset; } ++segment_index; if (iter.Next()) { AllocateItems(context, final_items, final_items_used, final_items_allocated, GetSegmentCount(this_string) - segment_index, regs[ridx_final_items]); do { SetFinalItem(final_items, final_items_used++, iter.GetBase(), iter.GetOffset(), iter.GetLength()); final_length += iter.GetLength(); } while (iter.Next()); } } } else if (previous_match_end < this_length) { AllocateItems(context, final_items, final_items_used, final_items_allocated, 1, regs[ridx_final_items]); unsigned length = this_length - previous_match_end; SetFinalItem(final_items, final_items_used++, context, this_string, previous_match_end, length); final_length += length; } JString *result; if (final_length == 0) result = context->rt_data->strings[STRING_empty]; else if (final_length > 64 && final_length > final_items_used * (sizeof(JStringStorage *) + 2 * sizeof(unsigned)) * 2) { JStringSegmented *segmented = JStringSegmented::Make(context, final_items_used); regs[ridx_segmented].SetBoxed(segmented); JStringStorage **base = segmented->Bases(); unsigned *offset = segmented->Offsets(); unsigned *length = segmented->Lengths(); for (unsigned item_idx = 0; item_idx < final_items_used; ++item_idx) { *base++ = static_cast<JStringStorage*>(final_items->slots[item_idx]); *offset++ = final_items->uints[final_items->nused + 2*item_idx]; *length++ = final_items->uints[final_items->nused + 2*item_idx+1]; OP_ASSERT(length[-1] != ~0u); } result = JString::Make(context, segmented, final_length); } else { uni_char *storage; result = JString::Make(context, final_length); storage = Storage(context, result); OP_ASSERT(storage); for (unsigned item_idx = 0; item_idx < final_items_used; ++item_idx) { uni_char* str = static_cast<JStringStorage*>(final_items->slots[item_idx])->storage; unsigned offset = final_items->uints[final_items->nused + 2*item_idx]; unsigned length = final_items->uints[final_items->nused + 2*item_idx+1]; op_memcpy(storage, str + offset, length * sizeof(uni_char)); storage += length; } result = Finalize(context, result); } return_value->SetString(result); return TRUE; return_this: return_value->SetString(this_string); return TRUE; return_false: return FALSE; } /* static */ BOOL ES_StringBuiltins::match(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value) { ES_THIS_STRING(); ES_RegExp_Object *object; if (argc >= 1 && argv[0].IsObject() && argv[0].GetObject(context)->IsRegExpObject()) object = static_cast<ES_RegExp_Object *>(argv[0].GetObject(context)); else { JString *source, *empty = context->rt_data->strings[STRING_empty]; if (argc >= 1 && !argv[0].IsUndefined()) { if (!argv[0].ToString(context)) return FALSE; source = argv[0].GetString(); } else source = empty; RegExpFlags flags; unsigned flagbits; ES_RegExp_Object::ParseFlags(context, flags, flagbits, empty); object = ES_GET_GLOBAL_OBJECT()->GetDynamicRegExp(context, source, flags, flagbits); if (!object) { context->ThrowSyntaxError("String.prototype.match: invalid regular expression"); return FALSE; } } ES_CollectorLock gclock(context, TRUE); if ((object->GetFlagBits() & REGEXP_FLAG_GLOBAL) == 0) { ES_Value_Internal *registers; if (argc == 0) registers = context->AllocateRegisters(3); else registers = argv - 2; registers[0].SetObject(object); registers[1].SetObject(argv[-1].GetObject(context)); registers[2].SetString(this_string); BOOL success = ES_RegExpBuiltins::exec(context, 1, registers + 2, return_value); if (argc == 0) context->FreeRegisters(3); return success; } else { ES_Object *array = ES_Array::Make(context, ES_GET_GLOBAL_OBJECT()); unsigned last_index = 0, nmatches = 0, length = Length(this_string); do { RegExpMatch *matches = object->Exec(context, this_string, last_index); if (!matches) break; else array->PutNoLockL(context, nmatches++, JString::Make(context, this_string, matches[0].start, matches[0].length)); last_index = matches[0].start + es_maxu(1, matches[0].length); } while (last_index <= length); if (nmatches == 0) return_value->SetNull(); else { ES_Array::SetLength(context, array, nmatches); ES_Value_Internal lastIndex; lastIndex.SetUInt32(0); object->PutCachedAtIndex(ES_PropertyIndex(ES_RegExp_Object::LASTINDEX), lastIndex); return_value->SetObject(array); } return TRUE; } } /* static */ BOOL ES_StringBuiltins::split(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value) { ES_THIS_STRING(); ES_RegExp_Object *separator_regexp = NULL; JString *separator_string = NULL; unsigned limit = UINT_MAX; if (argc >= 2 && !argv[1].IsUndefined()) { if (!argv[1].ToNumber(context)) return FALSE; limit = argv[1].GetNumAsUInt32(); } if (limit == 0) { ES_Object *array = ES_Array::Make(context, ES_GET_GLOBAL_OBJECT()); return_value->SetObject(array); return TRUE; } if (argc >= 1 && argv[0].IsObject() && argv[0].GetObject(context)->IsRegExpObject()) separator_regexp = static_cast<ES_RegExp_Object *>(argv[0].GetObject(context)); else if (argc < 1 || argv[0].IsUndefined()) { ES_Object *array = ES_Array::Make(context, ES_GET_GLOBAL_OBJECT()); ES_CollectorLock gclock(context); ES_Value_Internal value; value.SetString(this_string); array->PutNoLockL(context, 0u, value); ES_Array::SetLength(context, array, 1); return_value->SetObject(array); return TRUE; } else { if (!argv[0].ToString(context)) return FALSE; separator_string = argv[0].GetString(); } ES_Object *array = ES_Array::Make(context, ES_GET_GLOBAL_OBJECT()); ES_CollectorLock gclock(context); ES_Value_Internal value; unsigned array_length = 0, this_length = Length(this_string); if (separator_regexp) { unsigned index = 0, previous_end = 0, ncaptures = separator_regexp->GetValue()->GetNumberOfCaptures(); while (index <= this_length && limit > 0) { RegExpMatch *matches = separator_regexp->Exec(context, this_string, index); // No match or empty match at end of string. if (!matches || matches[0].start == this_length) { // Return empty array if not a match failure on an empty string (only.) if (matches != NULL && this_length == 0) limit = 0; break; } else if (matches[0].start > previous_end || !IsEmpty(matches[0])) { value.SetString(JString::Make(context, this_string, previous_end, matches[0].start - previous_end)); array->PutNoLockL(context, array_length++, value); previous_end = matches[0].start + matches[0].length; for (unsigned capture_index = 0; capture_index < ncaptures; ++capture_index) { SetMatchValue(context, value, this_string, matches[capture_index + 1]); array->PutNoLockL(context, array_length++, value); } --limit; } index = (IsEmpty(matches[0]) ? matches[0].start + 1 : matches[0].start + matches[0].length); } if (limit > 0) { value.SetString(JString::Make(context, this_string, previous_end, this_length - previous_end)); array->PutNoLockL(context, array_length++, value); } } else { unsigned separator_length = Length(separator_string); if (separator_length == 0) { OP_ASSERT(array->GetIndexedProperties() == NULL); array->SetIndexedProperties(ES_Compact_Indexed_Properties::Make(context, ES_Compact_Indexed_Properties::AppropriateCapacity(this_length))); for (unsigned index = 0; index < this_length && limit > 0; ++index, --limit) { value.SetString(JString::Make(context, this_string, index, 1)); array->PutNoLockL(context, array_length++, value); } } else { const uni_char *this_storage = Storage(context, this_string); const uni_char *separator_storage = Storage(context, separator_string); unsigned index = 0, previous_end = 0; if (this_length >= separator_length) { unsigned adjusted_length = this_length - separator_length; unsigned separator_bytes = separator_length * sizeof(uni_char); int first = separator_storage[0]; while (index <= adjusted_length && limit > 0) { while (index <= adjusted_length && this_storage[index] != first) ++index; if (index <= adjusted_length) if (separator_length == 1 || op_memcmp(this_storage + index, separator_storage, separator_bytes) == 0) { value.SetString(JString::Make(context, this_string, previous_end, index - previous_end)); array->PutNoLockL(context, array_length++, value); index += separator_length; previous_end = index; --limit; } else ++index; } } if (limit > 0) { if (previous_end == 0) value.SetString(this_string); else value.SetString(JString::Make(context, this_string, previous_end, this_length - previous_end)); array->PutNoLockL(context, array_length++, value); } } } ES_Array::SetLength(context, array, array_length); return_value->SetObject(array); return TRUE; } /* static */ BOOL ES_StringBuiltins::search(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value) { ES_THIS_STRING(); ES_RegExp_Object *object; if (argc >= 1 && argv[0].IsObject() && argv[0].GetObject(context)->IsRegExpObject()) object = static_cast<ES_RegExp_Object *>(argv[0].GetObject(context)); else { JString *source, *empty = context->rt_data->strings[STRING_empty]; if (argc >= 1 && !argv[0].IsUndefined()) { if (!argv[0].ToString(context)) return FALSE; source = argv[0].GetString(); } else source = empty; RegExpFlags flags; unsigned flagbits; ES_RegExp_Object::ParseFlags(context, flags, flagbits, empty); object = ES_GET_GLOBAL_OBJECT()->GetDynamicRegExp(context, source, flags, flagbits); if (!object) { context->ThrowSyntaxError("String.prototype.search: invalid regular expression"); return FALSE; } } ES_CollectorLock gclock(context, TRUE); RegExpMatch *matches = object->Exec(context, this_string, 0); if (matches) return_value->SetUInt32(matches[0].start); else return_value->SetInt32(-1); return TRUE; } #define TRIM(ch) (ES_Lexer::IsWhitespace(ch) || ES_Lexer::IsLinebreak(ch)) /* static */ BOOL ES_StringBuiltins::trim(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value) { ES_THIS_STRING(); unsigned length = Length(this_string); if (length == 0) return_value->SetString(this_string); else { unsigned offset = 0; const uni_char *srcstr = Storage(context, this_string); while (TRIM(srcstr[offset]) && ++offset != length) ; if (offset != length) while (TRIM(srcstr[length - 1]) && --length != offset) ; if (offset != length) { length -= offset; return_value->SetString(JString::Make(context, this_string, offset, length)); } else return_value->SetString(context->rt_data->strings[STRING_empty]); } return TRUE; } /* static */ BOOL ES_StringBuiltins::link(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value) { return ES_StringBuiltins::htmlify(context, argc, argv, return_value, "a", "href"); } /* static */ BOOL ES_StringBuiltins::anchor(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value) { return ES_StringBuiltins::htmlify(context, argc, argv, return_value, "a", "name"); } /* static */ BOOL ES_StringBuiltins::fontcolor(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value) { return ES_StringBuiltins::htmlify(context, argc, argv, return_value, "font", "color"); } /* static */ BOOL ES_StringBuiltins::fontsize(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value) { return ES_StringBuiltins::htmlify(context, argc, argv, return_value, "font", "size"); } /* static */ BOOL ES_StringBuiltins::big(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value) { return ES_StringBuiltins::htmlify(context, argc, argv, return_value, "big"); } /* static */ BOOL ES_StringBuiltins::blink(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value) { return ES_StringBuiltins::htmlify(context, argc, argv, return_value, "blink"); } /* static */ BOOL ES_StringBuiltins::bold(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value) { return ES_StringBuiltins::htmlify(context, argc, argv, return_value, "b"); } /* static */ BOOL ES_StringBuiltins::fixed(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value) { return ES_StringBuiltins::htmlify(context, argc, argv, return_value, "tt"); } /* static */ BOOL ES_StringBuiltins::italics(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value) { return ES_StringBuiltins::htmlify(context, argc, argv, return_value, "i"); } /* static */ BOOL ES_StringBuiltins::small(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value) { return ES_StringBuiltins::htmlify(context, argc, argv, return_value, "small"); } /* static */ BOOL ES_StringBuiltins::strike(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value) { return ES_StringBuiltins::htmlify(context, argc, argv, return_value, "strike"); } /* static */ BOOL ES_StringBuiltins::sub(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value) { return ES_StringBuiltins::htmlify(context, argc, argv, return_value, "sub"); } /* static */ BOOL ES_StringBuiltins::sup(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value) { return ES_StringBuiltins::htmlify(context, argc, argv, return_value, "sup"); } static void append_to_storage(uni_char *s, int& pos, const char* str) { int str_len = op_strlen(str); make_doublebyte_in_buffer(str, str_len, s + pos, str_len + 1); pos += str_len; } /* static */ BOOL ES_StringBuiltins::htmlify(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value, const char *tag_name) { ES_THIS_STRING(); int this_len = Length(this_string); int tag_len = op_strlen(tag_name); int slen = this_len + tag_len * 2 + 5; ES_CollectorLock gclock(context); JString *res = JString::Make(context, slen); uni_char *s = Storage(context, res); int pos = 0; append_to_storage(s, pos, "<"); append_to_storage(s, pos, tag_name); append_to_storage(s, pos, ">"); uni_char *this_s = Storage(context, this_string); uni_strncpy(s + pos, this_s, this_len); pos += this_len; append_to_storage(s, pos, "</"); append_to_storage(s, pos, tag_name); s[pos] = '>'; // avoid writing outside string. return_value->SetString(res); return TRUE; } /* static */ BOOL ES_StringBuiltins::htmlify(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value, const char *tag_name, const char *attr_name) { ES_THIS_STRING(); JString* str = context->rt_data->strings[STRING_undefined]; if (argc >= 1) { if (!argv[0].ToString(context)) return FALSE; str = argv[0].GetString(); } int this_len = Length(this_string); int tag_len = op_strlen(tag_name); int attr_len = op_strlen(attr_name); int str_len = Length(str); int slen = this_len + tag_len * 2 + attr_len + str_len + 9; ES_CollectorLock gclock(context); JString *res = JString::Make(context, slen); uni_char *s = Storage(context, res); int pos = 0; append_to_storage(s, pos, "<"); append_to_storage(s, pos, tag_name); append_to_storage(s, pos, " "); append_to_storage(s, pos, attr_name); append_to_storage(s, pos, "=\""); uni_char *str_s = Storage(context, str); uni_strncpy(s + pos, str_s, str_len); pos += str_len; append_to_storage(s, pos, "\">"); uni_char *this_s = Storage(context, this_string); uni_strncpy(s + pos, this_s, this_len); pos += this_len; append_to_storage(s, pos, "</"); append_to_storage(s, pos, tag_name); s[pos] = '>'; // avoid writing outside string. return_value->SetString(res); return TRUE; } /* static */ BOOL ES_StringBuiltins::fromCharCode(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value) { JString *result_string; if (argc == 1) { if (!argv[0].ToNumber(context)) return FALSE; uni_char ch = static_cast<uni_char>(argv[0].GetNumAsUInt32()); result_string = JString::Make(context, &ch, 1); } else if (argc == 0) result_string = context->rt_data->strings[STRING_empty]; else { result_string = JString::Make(context, argc); argv[-1].SetString(result_string); for (unsigned index = 0; index < argc; ++index) { if (!argv[index].ToNumber(context)) return FALSE; Storage(context, result_string)[index] = static_cast<uni_char>(argv[index].GetNumAsUInt32()); } } return_value->SetString(result_string); return TRUE; } /* static */ void ES_StringBuiltins::PopulatePrototype(ES_Context *context, ES_Global_Object *global_object, ES_Object *prototype) { ES_Value_Internal undefined; ASSERT_CLASS_SIZE(ES_StringBuiltins); ES_Function *fn_charCodeAt = MAKE_BUILTIN(1, charCodeAt); ES_Function *fn_charAt = MAKE_BUILTIN(1, charAt); #ifdef ES_NATIVE_SUPPORT fn_charCodeAt->SetFunctionID(ES_BUILTIN_FN_charCodeAt); fn_charAt->SetFunctionID(ES_BUILTIN_FN_charAt); #endif // ES_NATIVE_SUPPORT APPEND_PROPERTY(ES_StringBuiltins, length, 0); APPEND_PROPERTY(ES_StringBuiltins, constructor, undefined); APPEND_PROPERTY(ES_StringBuiltins, toString, MAKE_BUILTIN(0, toString)); APPEND_PROPERTY(ES_StringBuiltins, valueOf, MAKE_BUILTIN(0, valueOf)); APPEND_PROPERTY(ES_StringBuiltins, toLowerCase, MAKE_BUILTIN(0, toLowerCase)); APPEND_PROPERTY(ES_StringBuiltins, toLocaleLowerCase, MAKE_BUILTIN(0, toLocaleLowerCase)); APPEND_PROPERTY(ES_StringBuiltins, toUpperCase, MAKE_BUILTIN(0, toUpperCase)); APPEND_PROPERTY(ES_StringBuiltins, toLocaleUpperCase, MAKE_BUILTIN(0, toLocaleUpperCase)); APPEND_PROPERTY(ES_StringBuiltins, charCodeAt, fn_charCodeAt); APPEND_PROPERTY(ES_StringBuiltins, charAt, fn_charAt); APPEND_PROPERTY(ES_StringBuiltins, substring, MAKE_BUILTIN(2, substring)); APPEND_PROPERTY(ES_StringBuiltins, substr, MAKE_BUILTIN(2, substr)); APPEND_PROPERTY(ES_StringBuiltins, slice, MAKE_BUILTIN(2, slice)); APPEND_PROPERTY(ES_StringBuiltins, concat, MAKE_BUILTIN(1, concat)); APPEND_PROPERTY(ES_StringBuiltins, indexOf, MAKE_BUILTIN(1, indexOf)); APPEND_PROPERTY(ES_StringBuiltins, lastIndexOf, MAKE_BUILTIN(1, lastIndexOf)); APPEND_PROPERTY(ES_StringBuiltins, localeCompare, MAKE_BUILTIN(1, localeCompare)); APPEND_PROPERTY(ES_StringBuiltins, replace, MAKE_BUILTIN(2, replace)); APPEND_PROPERTY(ES_StringBuiltins, match, MAKE_BUILTIN(1, match)); APPEND_PROPERTY(ES_StringBuiltins, split, MAKE_BUILTIN(2, split)); APPEND_PROPERTY(ES_StringBuiltins, search, MAKE_BUILTIN(1, search)); APPEND_PROPERTY(ES_StringBuiltins, trim, MAKE_BUILTIN(0, trim)); APPEND_PROPERTY(ES_StringBuiltins, link, MAKE_BUILTIN(1, link)); APPEND_PROPERTY(ES_StringBuiltins, anchor, MAKE_BUILTIN(1, anchor)); APPEND_PROPERTY(ES_StringBuiltins, fontcolor, MAKE_BUILTIN(1, fontcolor)); APPEND_PROPERTY(ES_StringBuiltins, fontsize, MAKE_BUILTIN(1, fontsize)); APPEND_PROPERTY(ES_StringBuiltins, big, MAKE_BUILTIN(0, big)); APPEND_PROPERTY(ES_StringBuiltins, blink, MAKE_BUILTIN(0, blink)); APPEND_PROPERTY(ES_StringBuiltins, bold, MAKE_BUILTIN(0, bold)); APPEND_PROPERTY(ES_StringBuiltins, fixed, MAKE_BUILTIN(0, fixed)); APPEND_PROPERTY(ES_StringBuiltins, italics, MAKE_BUILTIN(0, italics)); APPEND_PROPERTY(ES_StringBuiltins, small, MAKE_BUILTIN(0, small)); APPEND_PROPERTY(ES_StringBuiltins, strike, MAKE_BUILTIN(0, strike)); APPEND_PROPERTY(ES_StringBuiltins, sub, MAKE_BUILTIN(0, sub)); APPEND_PROPERTY(ES_StringBuiltins, sup, MAKE_BUILTIN(0, sup)); ASSERT_OBJECT_COUNT(ES_StringBuiltins); } /* static */ void ES_StringBuiltins::PopulatePrototypeClass(ES_Context *context, ES_Class_Singleton *prototype_class) { OP_ASSERT(prototype_class->GetPropertyTable()->Capacity() >= ES_StringBuiltinsCount); JString **idents = context->rt_data->idents; ES_Layout_Info layout; DECLARE_PROPERTY(ES_StringBuiltins, length, RO | DE | DD, ES_STORAGE_INT32); DECLARE_PROPERTY(ES_StringBuiltins, constructor, DE, ES_STORAGE_WHATEVER); DECLARE_PROPERTY(ES_StringBuiltins, toString, DE, ES_STORAGE_OBJECT); DECLARE_PROPERTY(ES_StringBuiltins, valueOf, DE, ES_STORAGE_OBJECT); DECLARE_PROPERTY(ES_StringBuiltins, toLowerCase, DE, ES_STORAGE_OBJECT); DECLARE_PROPERTY(ES_StringBuiltins, toLocaleLowerCase, DE, ES_STORAGE_OBJECT); DECLARE_PROPERTY(ES_StringBuiltins, toUpperCase, DE, ES_STORAGE_OBJECT); DECLARE_PROPERTY(ES_StringBuiltins, toLocaleUpperCase, DE, ES_STORAGE_OBJECT); DECLARE_PROPERTY(ES_StringBuiltins, charCodeAt, DE, ES_STORAGE_OBJECT); DECLARE_PROPERTY(ES_StringBuiltins, charAt, DE, ES_STORAGE_OBJECT); DECLARE_PROPERTY(ES_StringBuiltins, substring, DE, ES_STORAGE_OBJECT); DECLARE_PROPERTY(ES_StringBuiltins, substr, DE, ES_STORAGE_OBJECT); DECLARE_PROPERTY(ES_StringBuiltins, slice, DE, ES_STORAGE_OBJECT); DECLARE_PROPERTY(ES_StringBuiltins, concat, DE, ES_STORAGE_OBJECT); DECLARE_PROPERTY(ES_StringBuiltins, indexOf, DE, ES_STORAGE_OBJECT); DECLARE_PROPERTY(ES_StringBuiltins, lastIndexOf, DE, ES_STORAGE_OBJECT); DECLARE_PROPERTY(ES_StringBuiltins, localeCompare, DE, ES_STORAGE_OBJECT); DECLARE_PROPERTY(ES_StringBuiltins, replace, DE, ES_STORAGE_OBJECT); DECLARE_PROPERTY(ES_StringBuiltins, match, DE, ES_STORAGE_OBJECT); DECLARE_PROPERTY(ES_StringBuiltins, split, DE, ES_STORAGE_OBJECT); DECLARE_PROPERTY(ES_StringBuiltins, search, DE, ES_STORAGE_OBJECT); DECLARE_PROPERTY(ES_StringBuiltins, trim, DE, ES_STORAGE_OBJECT); DECLARE_PROPERTY(ES_StringBuiltins, link, DE, ES_STORAGE_OBJECT); DECLARE_PROPERTY(ES_StringBuiltins, anchor, DE, ES_STORAGE_OBJECT); DECLARE_PROPERTY(ES_StringBuiltins, fontcolor, DE, ES_STORAGE_OBJECT); DECLARE_PROPERTY(ES_StringBuiltins, fontsize, DE, ES_STORAGE_OBJECT); DECLARE_PROPERTY(ES_StringBuiltins, big, DE, ES_STORAGE_OBJECT); DECLARE_PROPERTY(ES_StringBuiltins, blink, DE, ES_STORAGE_OBJECT); DECLARE_PROPERTY(ES_StringBuiltins, bold, DE, ES_STORAGE_OBJECT); DECLARE_PROPERTY(ES_StringBuiltins, fixed, DE, ES_STORAGE_OBJECT); DECLARE_PROPERTY(ES_StringBuiltins, italics, DE, ES_STORAGE_OBJECT); DECLARE_PROPERTY(ES_StringBuiltins, small, DE, ES_STORAGE_OBJECT); DECLARE_PROPERTY(ES_StringBuiltins, strike, DE, ES_STORAGE_OBJECT); DECLARE_PROPERTY(ES_StringBuiltins, sub, DE, ES_STORAGE_OBJECT); DECLARE_PROPERTY(ES_StringBuiltins, sup, DE, ES_STORAGE_OBJECT); } /* static */ void ES_StringBuiltins::PopulateConstructor(ES_Context *context, ES_Global_Object *global_object, ES_Object *constructor) { ES_Function *fn_fromCharCode = MAKE_BUILTIN_NO_PROTOTYPE(1, fromCharCode); #ifdef ES_NATIVE_SUPPORT fn_fromCharCode->SetFunctionID(ES_BUILTIN_FN_fromCharCode); #endif // ES_NATIVE_SUPPORT constructor->InitPropertyL(context, context->rt_data->idents[ESID_fromCharCode], fn_fromCharCode, DE); } /* static */ BOOL ES_StringBuiltins::ProcessThis(ES_Execution_Context *context, ES_Value_Internal &this_value) { if (this_value.IsNullOrUndefined()) { context->ThrowTypeError("'this' is not coercible to object"); return FALSE; } if (!this_value.ToString(context)) return FALSE; return TRUE; } #undef ES_THIS_STRING #undef ES_CHECK_CALLABLE #undef TYPE_ERROR_TO_STRING #undef TYPE_ERROR_VALUE_OF
#pragma once #include <stdint.h> #include <stdbool.h> namespace x { typedef bool x_Bool, *x_PBool; typedef int8_t x_Sint8, *x_PSint8; typedef uint8_t x_Uint8, *x_PUint8; typedef int16_t x_Sint16, *x_PSint16; typedef uint16_t x_Uint16, *x_PUint16; typedef int32_t x_Sint32, *x_PSint32; typedef uint32_t x_Uint32, *x_PUint32; typedef int64_t x_Sint64, *x_PSint64; typedef uint64_t x_Uint64, *x_PUint64; typedef char x_Char8, *x_PChar8; typedef char16_t x_Char16, *x_PChar16; typedef char32_t x_Char32, *x_PChar32; typedef wchar_t x_Wchar, *x_PWchar; typedef float x_Float32, *x_PFloat32; typedef double x_Float64, *x_PFloat64; typedef long double x_Float128, *x_PFloat128; typedef size_t x_Size, *x_PSize; }
#ifndef DYCOREGENERATOR_H #define DYCOREGENERATOR_H #include "acoregenerator.h" class DYCoreGenerator : public ACoreGenerator { public: DYCoreGenerator(); double **generate(int size) override; double * generateX(int size) override; double * generateY(int size) override; }; #endif // DYCOREGENERATOR_H
#ifndef COPY_H #define COPY_H #include "Action.h" #include "..\Statements\Statement.h" #include "..\ApplicationManager.h" class Copy : public Action { private: Point Position; Statement *Stat; public: Copy(ApplicationManager *pAppManager); //Read Assignemt statements position virtual void ReadActionParameters(); //Create and add an assignemnt statement to the list of statements virtual void Execute() ; }; #endif
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * 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. * * @author Manuela Hutter (manuelah) */ #ifndef __ST_OPERA_ACCOUNT_MANAGER__ #define __ST_OPERA_ACCOUNT_MANAGER__ #include "adjunct/quick/managers/OperaAccountManager.h" class ST_OperaAccountManager : public OperaAccountManager, public OperaAccountController::OAC_Listener { public: enum SuccessCriteria { SuccessCriteriaAuthentication, SuccessCriteriaDeviceRegistration, SuccessCriteriaDeviceRegistrationForced, SuccessCriteriaDeviceRelease }; ST_OperaAccountManager(SuccessCriteria success_criteria) : m_success_criteria(success_criteria) { AddListener(this); } virtual ~ST_OperaAccountManager() { RemoveListener(this); } OP_STATUS SetPrefsUserName(const OpStringC & username) { return m_prefs_username.Set(username); } OP_STATUS SetWandPassword(const OpStringC & password) { return m_wand_password.Set(password); } protected: virtual OP_STATUS OAuthAuthenticate(const OpStringC& username, const OpStringC& password, const OpStringC& device_name, const OpStringC& install_id, BOOL force = FALSE) { switch(m_success_criteria) { case SuccessCriteriaAuthentication: { if (username.HasContent() && password.HasContent()) { ST_passed(); return OpStatus::OK; } } break; case SuccessCriteriaDeviceRegistration: case SuccessCriteriaDeviceRegistrationForced: { if (username.HasContent() && password.HasContent() && device_name.HasContent() && install_id.HasContent()) { if (m_success_criteria == SuccessCriteriaDeviceRegistrationForced && force == FALSE) { ST_failed("No forced device creation"); } else { ST_passed(); } return OpStatus::OK; } } break; default: { ST_failed("Wrong action or invalid data"); } } return OpStatus::OK; } virtual OP_STATUS OAuthReleaseDevice(const OpStringC& username, const OpStringC& password, const OpStringC& devicename) { if (m_success_criteria == SuccessCriteriaDeviceRelease) { if (username.HasContent() && password.HasContent() && devicename.HasContent()) { ST_passed(); return OpStatus::OK; } } ST_failed("Wrong action or invalid data"); return OpStatus::OK; } virtual void OnOperaAccountDeviceCreate(OperaAuthError error, const OpStringC& shared_secret, const OpStringC& server_message) {} virtual OP_STATUS GetUserNameFromPrefs(OpString & username) const { RETURN_IF_ERROR(username.Set(m_prefs_username)); return OpStatus::OK; } virtual OP_STATUS GetWandPassword(const OpStringC8 &protocol, const OpStringC &server, const OpStringC &username, PrivacyManagerCallback* callback) { if (protocol.Compare(WAND_OPERA_ACCOUNT) != 0 || server.HasContent() || username.IsEmpty() || callback == NULL) { ST_failed("invalid wand information"); } if (m_wand_password.HasContent()) { OnPasswordRetrieved(m_wand_password); } else { OnPasswordFailed(); } return OpStatus::OK; } virtual void OnPasswordMissing() { if (m_current_task == CurrentTaskNone) { ST_failed("password retrieval without current task"); } else { ST_passed(); } } private: SuccessCriteria m_success_criteria; OpString m_prefs_username; OpString m_wand_password; }; #endif // __ST_OPERA_ACCOUNT_MANAGER__
#include<stdio.h> #include<conio.h> #include<graphics.h> #include<dos.h> #include<math.h> struct point{ double x; double y; }p; void c_curve(struct point p,double len,double angle,int n); void main() { int gd=DETECT,gm; int n,run=1; double l,a; while(run==1) { run=0; printf("enter the order of c_curve value"); scanf("%d",&n); p.x=200; p.y=200; l=100; a=0; initgraph(&gd,&gm,"C:\\TURBOC3\\BGI"); c_curve(p,l,a,n); getch(); closegraph(); printf("to run again press 1"); scanf("%d",&run); } } void c_curve(struct point p,double len,double angle,int n) { double m=3.14159; double theta=m/180; if(n>1) { len/=sqrt(2); c_curve(p,len,angle+45,n-1); p.x+=len*cos(theta*(angle+45)); p.y+=len*sin(theta*(angle+45)); c_curve(p,len,angle-45,n-1); } else { line(p.x,p.y,p.x+len*cos(theta*(angle)),p.y+len*sin(theta*(angle))); } }
#pragma once #include "proto/data_base.pb.h" #include "proto/data_player.pb.h" #include "proto/data_chat.pb.h" #include "proto/data_arena.pb.h" #include "proto/data_mail.pb.h" #include "proto/data_yunying.pb.h" #include "proto/data_log.pb.h" #include "proto/data_admin.pb.h" #include "net/conn.hpp" #include "net/server.hpp" #include "db/message.hpp" #include <map> #include <memory> #include <boost/core/noncopyable.hpp> using namespace std; namespace pd = proto::data; namespace nora { class service_thread; namespace gm { class scene; class scene_mgr_class : private boost::noncopyable { public: scene_mgr_class(); static scene_mgr_class& instance() { static scene_mgr_class inst; return inst; } void start(); void stop(); friend ostream& operator<<(ostream& os, const scene_mgr_class& sm); void manage_announcement(uint32_t sid, const pd::announcement& announcement); void server_images_announcement(uint32_t sid, uint32_t server_id, const map<string, uint32_t>& announcements); void gag_role_by_gid(uint32_t sid, int server_id, uint64_t gid, uint32_t gag_until_time, const string& reason); void remove_gag_role_by_gid(uint32_t sid, int server_id, uint64_t gid); void ban_role_by_gid(uint32_t sid, int server_id, uint64_t gid, uint32_t ban_until_time, const string& reason); void remove_ban_role_by_gid(uint32_t sid, int server_id, uint64_t gid); void kick_role_by_gid(uint32_t sid, int server_id, uint64_t gid, const string& reason); void fetch_world_chat(uint32_t sid, int server_id); void find_role_by_gid(uint32_t sid, int server_id, uint64_t gid); void find_role_by_rolename(uint32_t sid, int server_id, const string& rolename); void fetch_rank_list(uint32_t sid, int server_id, const string& rank_type, uint32_t page_size); void internal_recharge(uint32_t sid, int server_id, uint64_t role, uint32_t recharge_id); void reissue_recharge(uint32_t sid, int server_id, uint64_t role, uint64_t order); void recharge(uint32_t sid, uint64_t order, const string& yy_orderno, const string& currency, uint32_t price, uint32_t paytime, const string& product_name, const string& ext_info); void send_mail(uint32_t sid, int server_id, uint32_t channel_id, const pd::gid_array& roles, uint64_t mail_id, const string& title, const string& content, const pd::event_array& events); void fetch_log(uint32_t sid, int server_id, uint64_t role, uint32_t item_id, uint32_t start_time, uint32_t end_time, int page_idx, int page_size); void fetch_punished(uint32_t sid, int server_id, uint64_t role, uint32_t start_time, uint32_t end_time, int page_idx, int page_size); void fetch_sent_mail(uint32_t sid, int server_id, uint64_t role, uint32_t start_time, uint32_t end_time, int page_idx, int page_size); void fetch_login_record(uint32_t sid, int server_id, uint64_t role, int page_idx, int page_size); void fetch_recharge_record(uint32_t sid, int server_id, uint32_t channel_id, uint64_t order, uint64_t role, int start_time, int end_time, int page_idx, int page_size); void fetch_currency_record(uint32_t sid, int server_id, const string& type, uint64_t role, int start_time, int end_time, int page_idx, int page_size); void fetch_role_list(uint32_t sid, const string& username); void set_role_list(uint32_t sid, const pd::yunying_role_simple_info& rsi); bool has_sid(uint32_t sid) const; bool has_server_id(uint32_t sid, int server_id) const; bool has_role_simple_infos(uint32_t sid) const; void add_resource(uint32_t sid, uint64_t gid, uint32_t resource_type, uint32_t resource_count); void add_stuff_by_rolename(uint32_t sid, uint32_t server_id, const string& rolename, const pd::event_array& events); void add_stuff_by_gid(uint32_t sid, uint32_t server_id, uint64_t role, const pd::event_array& events); void dec_stuff_by_rolename(uint32_t sid, uint32_t server_id, const string& rolename, const pd::event_array& events); void dec_stuff_by_gid(uint32_t sid, uint32_t server_id, uint64_t role, const pd::event_array& events); void operates_activity(uint32_t sid, uint32_t activity, uint32_t start_time, uint32_t duration, pd::admin_activity_type type, const vector<string>& server_ids, bool open_activity); private: string name_; shared_ptr<service_thread> st_; shared_ptr<timer_type> timer_; pd::announcement announcement_; set<uint32_t> sids_; map<uint32_t, pd::yunying_role_simple_info_array> sid2role_infos_; uint32_t client_process_count_ = 0; }; inline bool scene_mgr_class::has_sid(uint32_t sid) const { return sids_.count(sid) > 0; } inline bool scene_mgr_class::has_role_simple_infos(uint32_t sid) const { return sid2role_infos_.count(sid) > 0; } } }
#include<bits/stdc++.h> using namespace std; typedef long long ll; #define maxn 100005 int n,m; ll h[maxn],p[maxn]; bool ok(ll time) { ll need; int pos=0; for(int i=0; i<n; i++) { if(abs(h[i]-p[pos])>time) continue; if(h[i]==p[pos]) pos++; if(h[i]>p[pos]) { need=max(h[i]+time-2*(h[i]-p[pos]),h[i]+(time-(h[i]-p[pos]))/2); } else need=h[i]+time; while(p[pos]<=need&&pos<=m) pos++; } return pos>m-1; } int main() { cin>>n>>m; for(int i=0; i<n; i++) cin>>h[i]; for(int i=0; i<m; i++) cin>>p[i]; ll l=-1; ll r=abs(h[0]-p[0])*2+abs(h[0]-p[m-1]); // cout<<r<<endl; ll mid; while(l+1<r) { mid=(l+r)>>1; // cout<<"mid="<<mid<<endl; if(ok(mid)) r=mid; else l=mid; } cout<<r<<endl; return 0; }
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include <folly/MapUtil.h> #include <quic/state/AckEvent.h> #include <chrono> #include <utility> namespace quic { void AckEvent::AckPacket::DetailsPerStream::recordFrameDelivered( const WriteStreamFrame& frame, const bool retransmission) { if (!frame.len) { // may be FIN only return; } auto [it, inserted] = emplace( std::piecewise_construct, std::make_tuple(frame.streamId), std::make_tuple()); auto& outstandingPacketStreamDetails = it->second; outstandingPacketStreamDetails.streamBytesAcked += frame.len; if (retransmission) { outstandingPacketStreamDetails.streamBytesAckedByRetrans += frame.len; } if (frame.fromBufMeta) { outstandingPacketStreamDetails.streamPacketIdx = frame.streamPacketIdx; } } void AckEvent::AckPacket::DetailsPerStream::recordFrameAlreadyDelivered( const WriteStreamFrame& frame, const bool /* retransmission */) { if (!frame.len) { // may be FIN only return; } auto [it, inserted] = emplace( std::piecewise_construct, std::make_tuple(frame.streamId), std::make_tuple()); auto& outstandingPacketStreamDetails = it->second; outstandingPacketStreamDetails.dupAckedStreamIntervals.insert( frame.offset, frame.offset + frame.len - 1); if (frame.fromBufMeta) { outstandingPacketStreamDetails.streamPacketIdx = frame.streamPacketIdx; } } void AckEvent::AckPacket::DetailsPerStream::recordDeliveryOffsetUpdate( StreamId streamId, uint64_t newOffset) { auto [it, inserted] = emplace( std::piecewise_construct, std::make_tuple(streamId), std::make_tuple()); auto& outstandingPacketStreamDetails = it->second; CHECK( !outstandingPacketStreamDetails.maybeNewDeliveryOffset.has_value() || outstandingPacketStreamDetails.maybeNewDeliveryOffset.value() < newOffset); outstandingPacketStreamDetails.maybeNewDeliveryOffset = newOffset; } AckEvent::AckPacket::AckPacket( quic::PacketNum packetNumIn, uint64_t nonDsrPacketSequenceNumberIn, OutstandingPacketMetadata&& outstandingPacketMetadataIn, DetailsPerStream&& detailsPerStreamIn, folly::Optional<OutstandingPacketWrapper::LastAckedPacketInfo> lastAckedPacketInfoIn, bool isAppLimitedIn, folly::Optional<std::chrono::microseconds>&& receiveRelativeTimeStampUsec) : packetNum(packetNumIn), nonDsrPacketSequenceNumber(nonDsrPacketSequenceNumberIn), outstandingPacketMetadata(std::move(outstandingPacketMetadataIn)), detailsPerStream(std::move(detailsPerStreamIn)), lastAckedPacketInfo(std::move(lastAckedPacketInfoIn)), receiveRelativeTimeStampUsec(std::move(receiveRelativeTimeStampUsec)), isAppLimited(isAppLimitedIn) {} AckEvent::AckPacket::Builder&& AckEvent::AckPacket::Builder::setPacketNum( quic::PacketNum packetNumIn) { packetNum = packetNumIn; return std::move(*this); } AckEvent::AckPacket::Builder&& AckEvent::AckPacket::Builder::setNonDsrPacketSequenceNumber( uint64_t nonDsrPacketSequenceNumberIn) { nonDsrPacketSequenceNumber = nonDsrPacketSequenceNumberIn; return std::move(*this); } AckEvent::AckPacket::Builder&& AckEvent::AckPacket::Builder::setOutstandingPacketMetadata( OutstandingPacketMetadata&& outstandingPacketMetadataIn) { outstandingPacketMetadata = std::move(outstandingPacketMetadataIn); return std::move(*this); } AckEvent::AckPacket::Builder&& AckEvent::AckPacket::Builder::setDetailsPerStream( DetailsPerStream&& detailsPerStreamIn) { detailsPerStream = std::move(detailsPerStreamIn); return std::move(*this); } AckEvent::AckPacket::Builder&& AckEvent::AckPacket::Builder::setLastAckedPacketInfo( folly::Optional<OutstandingPacketWrapper::LastAckedPacketInfo>&& lastAckedPacketInfoIn) { lastAckedPacketInfo = std::move(lastAckedPacketInfoIn); return std::move(*this); } AckEvent::AckPacket::Builder&& AckEvent::AckPacket::Builder::setAppLimited( bool appLimitedIn) { isAppLimited = appLimitedIn; return std::move(*this); } AckEvent::AckPacket::Builder&& AckEvent::AckPacket::Builder::setReceiveDeltaTimeStamp( folly::Optional<std::chrono::microseconds>&& receiveTimeStampIn) { receiveRelativeTimeStampUsec = receiveTimeStampIn; return std::move(*this); } AckEvent::AckPacket AckEvent::AckPacket::Builder::build() && { CHECK(packetNum.has_value()); CHECK(outstandingPacketMetadata.has_value()); CHECK(detailsPerStream.has_value()); return AckEvent::AckPacket( packetNum.value(), nonDsrPacketSequenceNumber.value(), std::move(outstandingPacketMetadata.value()), std::move(detailsPerStream.value()), std::move(lastAckedPacketInfo), isAppLimited, std::move(receiveRelativeTimeStampUsec)); } AckEvent::Builder&& AckEvent::Builder::setAckTime(TimePoint ackTimeIn) { maybeAckTime = ackTimeIn; return std::move(*this); } AckEvent::Builder&& AckEvent::Builder::setAdjustedAckTime( TimePoint adjustedAckTimeIn) { maybeAdjustedAckTime = adjustedAckTimeIn; return std::move(*this); } AckEvent::Builder&& AckEvent::Builder::setAckDelay( std::chrono::microseconds ackDelayIn) { maybeAckDelay = ackDelayIn; return std::move(*this); } AckEvent::Builder&& AckEvent::Builder::setPacketNumberSpace( PacketNumberSpace packetNumberSpaceIn) { maybePacketNumberSpace = packetNumberSpaceIn; return std::move(*this); } AckEvent::Builder&& AckEvent::Builder::setLargestAckedPacket( PacketNum largestAckedPacketIn) { maybeLargestAckedPacket = largestAckedPacketIn; return std::move(*this); } AckEvent::Builder&& AckEvent::Builder::setIsImplicitAck(bool isImplicitAckIn) { isImplicitAck = isImplicitAckIn; return std::move(*this); } AckEvent AckEvent::Builder::build() && { return AckEvent(std::move(*this)); } AckEvent::AckEvent(AckEvent::BuilderFields&& builderFields) : ackTime(*CHECK_NOTNULL(builderFields.maybeAckTime.get_pointer())), adjustedAckTime( *CHECK_NOTNULL(builderFields.maybeAdjustedAckTime.get_pointer())), ackDelay(*CHECK_NOTNULL(builderFields.maybeAckDelay.get_pointer())), packetNumberSpace( *CHECK_NOTNULL(builderFields.maybePacketNumberSpace.get_pointer())), largestAckedPacket( *CHECK_NOTNULL(builderFields.maybeLargestAckedPacket.get_pointer())), implicit(builderFields.isImplicitAck) {} } // namespace quic
// // Created by 钟奇龙 on 2019-05-03. // #include <iostream> using namespace std; class Node{ public: int data; int leftMax; int rightMax; Node *left; Node *right; Node(int x):data(0),leftMax(0),rightMax(0),left(NULL),right(NULL){ } }; int maxDistance = INT_MIN; int getMaxDistance(Node *head){ if(!head) return 0; if(head->left){ head->leftMax = getMaxDistance(head->left) + 1; } if(head->right){ head->rightMax = getMaxDistance(head->right) + 1; } int sum = head->leftMax + head->rightMax + 1; if(sum > maxDistance){ maxDistance = sum; } return head->leftMax > head->rightMax ? head->leftMax:head->rightMax; } int main(){ Node *node1 = new Node(1); Node *node2 = new Node(2); Node *node3 = new Node(3); Node *node4 = new Node(4); Node *node5 = new Node(5); Node *node6 = new Node(6); Node *node7 = new Node(7); node1->left = node2; node1->right = node3; node2->left = node4; node2->right = node5; node3->left = node6; node3->right = node7; cout<<getMaxDistance(node1)<<endl; cout<<maxDistance<<endl; return 0; }
#include "vlc_helper.h" #include <mutex> template < typename T > using scoped_do = std::unique_ptr< T, std::function< void( T* ) > >; char* mY_hACkY_wACky_StRDuP( const char* str ) { // Внутри функция text_segment_New дублирует С-строку с помощью strdup и сохраняет указатель внутри сегмента в psz_text. // Копируем строку, забираем указатель и "выкидываем" ненужный сегмент. scoped_do< text_segment_t > unneeded_( text_segment_New( str ), [] ( text_segment_t* p ) { text_segment_Delete( p ); } ); char* ptr = unneeded_->psz_text; unneeded_->psz_text = 0; return ptr; }
/************************************************************************* > File Name: stone.cpp > Author: JY.ZH > Mail: xw2016@mail.ustc.edu.cn > Created Time: 2018年07月20日 星期五 12时31分10秒 ************************************************************************/ #include<iostream> using std::cout; #include "stonewt.h" void display(const Stonewt & st, int n); int main() { Stonewt incognito = 275; Stonewt wolfe(285.7); Stonewt tatf(21, 8); Stonewt poppins(9, 2.8); double p_wt = poppins; cout << "Convert to double => "; cout << "Poppins: " << p_wt << " pounds.\n"; cout << "Convert to int => "; cout << "Poppins: " << int (poppins) << " pounds.\n"; cout << "The celebrity weighed: "; incognito.show_stn(); cout << "The detective weighed: "; wolfe.show_stn(); cout << "The President weighed: "; tatf.show_lbs(); incognito = 276.8; tatf = 325; cout << "After dinner, the celebrity weighed: "; incognito.show_stn(); cout << "After dinner, the President weighed: "; tatf.show_lbs(); display(tatf, 2); cout << "The wrestler weighed even more.\n"; display(422, 2); cout << "No stone left unearned\n"; return 0; } void display(const Stonewt & st, int n) { for (int i = 0; i < n; i++) { cout << "Wow! "; st.show_stn(); } }
// BGS.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include <opencv2\core\core.hpp> #include <opencv2\imgproc\imgproc.hpp> #include <opencv2\highgui\highgui.hpp> #include <opencv2\features2d\features2d.hpp> #include <iostream> #include <conio.h> #include <vector> const double pi = 3.142; const double cthr = 0.00001; const double alpha = 0.002; const double cT = 0.05; const double covariance0 = 11.0; const double cf = 0.1; const double cfbar = 1.0 - cf; const double temp_thr = 9.0*covariance0*covariance0; const double prune = -alpha*cT; const double alpha_bar = 1.0 - alpha; int overall = 0; //高斯模型 struct gaussian { double mean[3], covariance; double weight; gaussian* Next; gaussian* Previous; } *ptr, *start, *rear, *g_temp, *save, *next, *previous, *nptr, *temp_ptr; struct Node { gaussian* pixel_s; gaussian* pixel_r; int no_of_components; Node* Next; } *N_ptr, *N_start, *N_rear; struct Node1 { cv::Mat gauss; int no_of_comp; Node1* Next; } *N1_ptr, *N1_start, *N1_rear; //方便管理像素点结构体的一些函数定义 Node* Create_Node(double info1, double info2, double info3); void Insert_End_Node(Node* np); gaussian* Create_gaussian(double info1, double info2, double info3); Node* Create_Node(double info1, double info2, double info3) { N_ptr = new Node; if (N_ptr != NULL) { N_ptr->Next = NULL; N_ptr->no_of_components = 1; N_ptr->pixel_s = N_ptr->pixel_r = Create_gaussian(info1, info2, info3); } return N_ptr; } gaussian* Create_gaussian(double info1, double info2, double info3) { ptr = new gaussian; if (ptr != NULL) { ptr->mean[0] = info1; ptr->mean[1] = info2; ptr->mean[2] = info3; ptr->covariance = covariance0; ptr->weight = alpha; ptr->Next = NULL; ptr->Previous = NULL; } return ptr; } void Insert_End_Node(Node* np) { if (N_start != NULL) { N_rear->Next = np; N_rear = np; } else N_start = N_rear = np; } void Insert_End_gaussian(gaussian* nptr) { if (start != NULL) { rear->Next = nptr; nptr->Previous = rear; rear = nptr; } else start = rear = nptr; } gaussian* Delete_gaussian(gaussian* nptr) { previous = nptr->Previous; next = nptr->Next; if (start != NULL) { if (nptr == start && nptr == rear) { start = rear = NULL; delete nptr; } else if (nptr == start) { next->Previous = NULL; start = next; delete nptr; nptr = start; } else if (nptr == rear) { previous->Next = NULL; rear = previous; delete nptr; nptr = rear; } else { previous->Next = next; next->Previous = previous; delete nptr; nptr = next; } } else { std::cout << "Underflow........"; _getch(); exit(0); } return nptr; } //主函数 void main() { int i, j, k; i = j = k = 0; // Declare matrices to store original and resultant binary image //存储原始二值图像以及相应的二值图像 cv::Mat orig_img, bin_img; //Declare a VideoCapture object to store incoming frame and initialize it //读取视频文件 cv::VideoCapture capture("E:\\Coding\\C#\\sample.avi"); //Recieveing input from the source and converting it to grayscale //将视频文件图像帧转换为灰度图 capture.read(orig_img); cv::resize(orig_img, orig_img, cv::Size(340, 260)); cv::cvtColor(orig_img, orig_img, CV_BGR2YCrCb); //Initializing the binary image with the same dimensions as original image //初始化临时二值图像变量(维度与原图像一致) bin_img = cv::Mat(orig_img.rows, orig_img.cols, CV_8U, cv::Scalar(0)); double value[3]; //Step 1: initializing with one gaussian for the first time and keeping the no. of models as 1 //第一步:第一次初始化时只使用一个高斯模型,置模型数为1 cv::Vec3f val; uchar* r_ptr; uchar* b_ptr; for (i = 0; i<orig_img.rows; i++) { r_ptr = orig_img.ptr(i); //获取一行像素点 for (j = 0; j<orig_img.cols; j++) //获取第i行上第j列的像素点 { N_ptr = Create_Node(*r_ptr, *(r_ptr + 1), *(r_ptr + 2)); if (N_ptr != NULL) { N_ptr->pixel_s->weight = 1.0; Insert_End_Node(N_ptr); } else { std::cout << "Memory limit reached... "; _getch(); exit(0); } } } capture.read(orig_img); int nL, nC; if (orig_img.isContinuous() == true) { nL = 1; nC = orig_img.rows*orig_img.cols*orig_img.channels(); } else { nL = orig_img.rows; nC = orig_img.cols*orig_img.channels(); } double del[3], mal_dist; double sum = 0.0; double sum1 = 0.0; int count = 0; bool close = false; int background; double mult; double duration, duration1, duration2, duration3; double temp_cov = 0.0; double weight = 0.0; double var = 0.0; double muR, muG, muB, dR, dG, dB, rVal, gVal, bVal; //第二步:对每个像素使用高斯模型进行建模 duration1 = static_cast<double>(cv::getTickCount()); bin_img = cv::Mat(orig_img.rows, orig_img.cols, CV_8UC1, cv::Scalar(0)); while (1) { duration3 = 0.0; if (!capture.read(orig_img)) { break; capture.release(); capture = cv::VideoCapture("PETS2009_sample_1.avi"); capture.read(orig_img); } int count = 0; int count1 = 0; N_ptr = N_start; duration = static_cast<double>(cv::getTickCount()); for (i = 0; i<nL; i++) { r_ptr = orig_img.ptr(i); b_ptr = bin_img.ptr(i); for (j = 0; j<nC; j += 3) { sum = 0.0; sum1 = 0.0; close = false; background = 0; rVal = *(r_ptr++); gVal = *(r_ptr++); bVal = *(r_ptr++); start = N_ptr->pixel_s; rear = N_ptr->pixel_r; ptr = start; temp_ptr = NULL; if (N_ptr->no_of_components > 4) { Delete_gaussian(rear); N_ptr->no_of_components--; } for (k = 0; k<N_ptr->no_of_components; k++) { weight = ptr->weight; mult = alpha / weight; weight = weight*alpha_bar + prune; if (close == false) { muR = ptr->mean[0]; muG = ptr->mean[1]; muB = ptr->mean[2]; dR = rVal - muR; dG = gVal - muG; dB = bVal - muB; var = ptr->covariance; mal_dist = (dR*dR + dG*dG + dB*dB); if ((sum < cfbar) && (mal_dist < 16.0*var*var)) background = 255; if (mal_dist < 9.0*var*var) { weight += alpha; close = true; ptr->mean[0] = muR + mult*dR; ptr->mean[1] = muG + mult*dG; ptr->mean[2] = muB + mult*dB; temp_cov = var + mult*(mal_dist - var); ptr->covariance = temp_cov<5.0 ? 5.0 : (temp_cov>20.0 ? 20.0 : temp_cov); temp_ptr = ptr; } } if (weight < -prune) { ptr = Delete_gaussian(ptr); weight = 0; N_ptr->no_of_components--; } else { sum += weight; ptr->weight = weight; } ptr = ptr->Next; } if (close == false) { ptr = new gaussian; ptr->weight = alpha; ptr->mean[0] = rVal; ptr->mean[1] = gVal; ptr->mean[2] = bVal; ptr->covariance = covariance0; ptr->Next = NULL; ptr->Previous = NULL; if (start == NULL) start = rear = NULL; else { ptr->Previous = rear; rear->Next = ptr; rear = ptr; } temp_ptr = ptr; N_ptr->no_of_components++; } ptr = start; while (ptr != NULL) { ptr->weight /= sum; ptr = ptr->Next; } while (temp_ptr != NULL && temp_ptr->Previous != NULL) { if (temp_ptr->weight <= temp_ptr->Previous->weight) break; else { next = temp_ptr->Next; previous = temp_ptr->Previous; if (start == previous) start = temp_ptr; previous->Next = next; temp_ptr->Previous = previous->Previous; temp_ptr->Next = previous; if (previous->Previous != NULL) previous->Previous->Next = temp_ptr; if (next != NULL) next->Previous = previous; else rear = previous; previous->Previous = temp_ptr; } temp_ptr = temp_ptr->Previous; } N_ptr->pixel_s = start; N_ptr->pixel_r = rear; *b_ptr++ = background; N_ptr = N_ptr->Next; } } duration = static_cast<double>(cv::getTickCount()) - duration; duration /= cv::getTickFrequency(); std::cout << "\n duration :" << duration; std::cout << "\n counts : " << count; cv::imshow("video", orig_img); cv::imshow("gp", bin_img); if (cv::waitKey(1)>0) break; } duration1 = static_cast<double>(cv::getTickCount()) - duration1; duration1 /= cv::getTickFrequency(); std::cout << "\n duration1 :" << duration1; _getch(); }
#include "extractionworker.h" #include "JlCompress.h" extern std::atomic<bool> extractionCompleted; void ExtractionWorker::init(QFileInfo fileDest,QProgressBar* pb) { this->qfi_=fileDest; this->pb_=pb; } void ExtractionWorker::extract() { extractionCompleted=false; QStringList zextracted = JlCompress::extractDir(this,this->qfi_.filePath(), this->qfi_.path(),this->pb_); if(zextracted.isEmpty()) { emit extractionempty(); } emit completed(); }
#pragma once #include "cursur_point.h" #define EMPTY -1 class Board { public: Board(); int GetState(cursur_point pos); void SetState(cursur_point pos, int state); int CheckLineFull(cursur_point reference_pos); private: int board_[10][20]; };
#include "VnaUserDefinedPort.h" // RsaToolbox using namespace RsaToolbox; // Qt #include <QStringList> /*! * \class RsaToolbox::VnaUserDefinedPort * \ingroup VnaGroup * \brief The \c %VnaUserDefinedPort class * controls the setup of user-defined ports */ VnaUserDefinedPort::VnaUserDefinedPort() { _sourcePort = 0; _referencePort = 0; _referenceReceiver = Receiver::A; _measurementPort = 0; _measurementReceiver = Receiver::B; } VnaUserDefinedPort::VnaUserDefinedPort(const VnaUserDefinedPort &other) { this->operator =(other); } bool VnaUserDefinedPort::isSourceSet(uint port) const { return(port == _sourcePort); } uint VnaUserDefinedPort::sourcePort() const { return(_sourcePort); } void VnaUserDefinedPort::setSource(uint port) { _sourcePort = port; } bool VnaUserDefinedPort::isReferenceSet(uint port, VnaUserDefinedPort::Receiver receiver) const { return(port == _referencePort && receiver == _referenceReceiver); } void VnaUserDefinedPort::reference(uint &port, VnaUserDefinedPort::Receiver &receiver) const { port = _referencePort; receiver = _referenceReceiver; } void VnaUserDefinedPort::setReference(uint port, VnaUserDefinedPort::Receiver receiver) { _referencePort = port; _referenceReceiver = receiver; } bool VnaUserDefinedPort::isMeasurementSet(uint port, VnaUserDefinedPort::Receiver receiver) const { return(port == _measurementPort && receiver == _measurementReceiver); } void VnaUserDefinedPort::measurement(uint &port, VnaUserDefinedPort::Receiver &receiver) const { port = _measurementPort; receiver = _measurementReceiver; } void VnaUserDefinedPort::setMeasurement(uint port, VnaUserDefinedPort::Receiver receiver) { _measurementPort = port; _measurementReceiver = receiver; } void VnaUserDefinedPort::operator=(VnaUserDefinedPort const &other) { _sourcePort = other._sourcePort; _referencePort = other._referencePort; _referenceReceiver = other._referenceReceiver; _measurementPort = other._measurementPort; _measurementReceiver = other._measurementReceiver; } bool operator==(const VnaUserDefinedPort &left, const VnaUserDefinedPort &right) { uint leftSourcePort = left.sourcePort(); uint leftReferencePort, leftMeasurePort; VnaUserDefinedPort::Receiver leftReferenceReceiver, leftMeasureReceiver; left.reference(leftReferencePort, leftReferenceReceiver); left.measurement(leftMeasurePort, leftMeasureReceiver); return(right.isSourceSet(leftSourcePort) && right.isReferenceSet(leftReferencePort, leftReferenceReceiver) && right.isMeasurementSet(leftMeasurePort, leftMeasureReceiver)); } bool operator!=(const VnaUserDefinedPort &left, const VnaUserDefinedPort &right) { return(!(left == right)); }
#ifndef DNA_ANALYZER_PROJECT_USERINTERFACE_H #define DNA_ANALYZER_PROJECT_USERINTERFACE_H #include "../Model/dataDNA.h" #include "../Controller/System.h" #include "../Controller/CallBack.h" class UserInterface { public: virtual ~UserInterface(){}; virtual void start(Iwriter& writer, Ireader& reader,dataDNA& containerDna, CallBack<System>& callBack)=0; }; #endif //DNA_ANALYZER_PROJECT_USERINTERFACE_H
// // NamedEvent_Android.h // // $Id: //poco/1.4/Foundation/include/_/NamedEvent_Android.h#1 $ // // Library: Foundation // Package: Processes // Module: NamedEvent // // Definition of the NamedEventImpl class for Android. // // Copyright (c) 2004-2011, Applied Informatics Software Engineering GmbH. // and Contributors. // // SPDX-License-Identifier: BSL-1.0 // #ifndef Foundation_NamedEvent_Android_INCLUDED #define Foundation_NamedEvent_Android_INCLUDED #include "_.h" #if _Android namespace _ { class __API NamedEventImpl { protected: NamedEventImpl(const std::string& name); ~NamedEventImpl(); void setImpl(); void waitImpl(); }; } // namespace _ #endif // Foundation_NamedEvent_Android_INCLUDED
/**************************************************************************** * AAMLibrary * http://code.google.com/p/aam-library * Copyright (c) 2008-2009 by GreatYao, all rights reserved. ****************************************************************************/ #include <ctime> #include "AAM_Basic.h" //============================================================================ AAM_Basic::AAM_Basic() { __G = 0; __current_c_q = 0; __update_c_q = 0; __delta_c_q = 0; __c = 0; __p = 0; __q = 0; __lamda = 0; __s = 0; __t_m = 0; __t_s = 0; __delta_t = 0; } //============================================================================ AAM_Basic::~AAM_Basic() { cvReleaseMat(&__G); cvReleaseMat(&__current_c_q); cvReleaseMat(&__update_c_q); cvReleaseMat(&__delta_c_q); cvReleaseMat(&__p); cvReleaseMat(&__q); cvReleaseMat(&__c); cvReleaseMat(&__lamda); cvReleaseMat(&__s); cvReleaseMat(&__t_s); cvReleaseMat(&__t_m); cvReleaseMat(&__delta_t); } //============================================================================ void AAM_Basic::Train(const file_lists& pts_files, const file_lists& img_files, double scale /* = 1.0 */, double shape_percentage /* = 0.975 */, double texture_percentage /* = 0.975 */, double appearance_percentage /* = 0.975 */) { if(pts_files.size() != img_files.size()) { LOGW("ERROE(%s, %d): #Shapes != #Images\n", __FILE__, __LINE__); exit(0); } LOGD("################################################\n"); LOGD("Build Fixed Jocobian Active Appearance Model ...\n"); __cam.Train(pts_files, img_files, scale, shape_percentage, texture_percentage, appearance_percentage); LOGD("Build Jacobian Matrix...\n"); __G = cvCreateMat(__cam.nModes()+4, __cam.__texture.nPixels(), CV_64FC1); CalcJacobianMatrix(pts_files, img_files); //allocate memory for on-line fitting __current_c_q = cvCreateMat(1, __cam.nModes()+4, CV_64FC1); __update_c_q = cvCreateMat(1, __cam.nModes()+4, CV_64FC1); __delta_c_q = cvCreateMat(1, __cam.nModes()+4, CV_64FC1); __c = cvCreateMat(1, __cam.nModes(), CV_64FC1); __p = cvCreateMat(1, __cam.__shape.nModes(), CV_64FC1); __q = cvCreateMat(1, 4, CV_64FC1); __lamda = cvCreateMat(1, __cam.__texture.nModes(), CV_64FC1); __s = cvCreateMat(1, __cam.__shape.nPoints()*2, CV_64FC1); __t_s = cvCreateMat(1, __cam.__texture.nPixels(), CV_64FC1); __t_m = cvCreateMat(1, __cam.__texture.nPixels(), CV_64FC1); __delta_t = cvCreateMat(1, __cam.__texture.nPixels(), CV_64FC1); LOGD("################################################\n\n"); } //============================================================================ static double rand_in_between(double a, double b) { int A = rand() % 50; return a + (b-a)*A/49; } //============================================================================ void AAM_Basic::CalcJacobianMatrix(const file_lists& pts_files, const file_lists& img_files, double disp_scale /* = 0.2 */, double disp_angle /* = 20 */, double disp_trans /* = 5.0 */, double disp_std /* = 1.0 */, int nExp /* = 30 */) { CvMat* J = cvCreateMat(__cam.nModes()+4, __cam.__texture.nPixels(), CV_64FC1); CvMat* d = cvCreateMat(1, __cam.nModes()+4, CV_64FC1); CvMat* o = cvCreateMat(1, __cam.nModes()+4, CV_64FC1); CvMat* oo = cvCreateMat(1, __cam.nModes()+4, CV_64FC1); CvMat* t = cvCreateMat(1, __cam.__texture.nPixels(), CV_64FC1); CvMat* t_m = cvCreateMat(1, __cam.__texture.nPixels(), CV_64FC1); CvMat* t_s = cvCreateMat(1, __cam.__texture.nPixels(), CV_64FC1); CvMat* t1 = cvCreateMat(1, __cam.__texture.nPixels(), CV_64FC1); CvMat* t2 = cvCreateMat(1, __cam.__texture.nPixels(), CV_64FC1); CvMat* u = cvCreateMat(1, __cam.nModes()+4, CV_64FC1); CvMat* c = cvCreateMat(1, __cam.nModes(), CV_64FC1); CvMat* s = cvCreateMat(1, __cam.__shape.nPoints()*2, CV_64FC1); CvMat* q = cvCreateMat(1, 4, CV_64FC1); CvMat* p = cvCreateMat(1, __cam.__shape.nModes(),CV_64FC1); CvMat* lamda = cvCreateMat(1, __cam.__texture.nModes(), CV_64FC1); double theta = disp_angle * CV_PI / 180; double aa = MAX(fabs(disp_scale*cos(theta)), fabs(disp_scale*sin(theta))); cvmSet(d,0,0,aa); cvmSet(d,0,1,aa); cvmSet(d,0,2,disp_trans); cvmSet(d,0,3,disp_trans); for(int nmode = 0; nmode < __cam.nModes(); nmode++) cvmSet(d,0,4+nmode,disp_std*sqrt(__cam.Var(nmode))); srand(unsigned(time(0))); cvSetZero(u);cvSetZero(J); for(int i = 0; i < pts_files.size(); i++) { IplImage* image = cvLoadImage(img_files[i].c_str(), -1); AAM_Shape Shape; if(!Shape.ReadAnnotations(pts_files[i])) Shape.ScaleXY(image->width, image->height); Shape.Point2Mat(s); AAM_Common::CheckShape(s, image->width, image->height); //calculate current texture vector __cam.__paw.CalcWarpTexture(s, image, t); __cam.__texture.NormalizeTexture(__cam.__MeanG, t); //calculate appearance parameters __cam.__shape.CalcParams(s, p, q); __cam.__texture.CalcParams(t, lamda); __cam.CalcParams(c, p, lamda); //update appearance and pose parameters CvMat subo; cvGetCols(o, &subo, 0, 4); cvCopy(q, &subo); cvGetCols(o, &subo, 4, 4+__cam.nModes()); cvCopy(c, &subo); //get optimal EstResidual EstResidual(image, o, s, t_m, t_s, t1); for(int j = 0; j < nExp; j++) { printf("Pertubing (%d/%d) for image (%d/%d)...\r", j, nExp, i, pts_files.size()); for(int l = 0; l < 4+__cam.nModes(); l++) { double D = cvmGet(d,0,l); double v = rand_in_between(-D, D); cvCopy(o, oo); CV_MAT_ELEM(*oo,double,0,l) += v; EstResidual(image, oo, s, t_m, t_s, t2); cvSub(t1, t2, t2); cvConvertScale(t2, t2, 1.0/v); //accumulate into l-th row CvMat Jl; cvGetRow(J, &Jl, l); cvAdd(&Jl, t2, &Jl); CV_MAT_ELEM(*u, double, 0, l) += 1.0; } } cvReleaseImage(&image); } //normalize for(int l = 0; l < __cam.nModes()+4; l++) { CvMat Jl; cvGetRow(J, &Jl, l); cvConvertScale(&Jl, &Jl, 1.0/cvmGet(u,0,l)); } CvMat* JtJ = cvCreateMat(__cam.nModes()+4, __cam.nModes()+4, CV_64FC1); CvMat* InvJtJ = cvCreateMat(__cam.nModes()+4, __cam.nModes()+4, CV_64FC1); cvGEMM(J, J, 1, NULL, 0, JtJ, CV_GEMM_B_T); cvInvert(JtJ, InvJtJ, CV_SVD); cvMatMul(InvJtJ, J, __G); cvReleaseMat(&J); cvReleaseMat(&d); cvReleaseMat(&o); cvReleaseMat(&oo); cvReleaseMat(&t); cvReleaseMat(&t_s); cvReleaseMat(&t_m); cvReleaseMat(&t1); cvReleaseMat(&t2); cvReleaseMat(&u); cvReleaseMat(&c); cvReleaseMat(&s); cvReleaseMat(&q); cvReleaseMat(&p); cvReleaseMat(&lamda); cvReleaseMat(&JtJ); cvReleaseMat(&InvJtJ); } //============================================================================ double AAM_Basic::EstResidual(const IplImage* image, const CvMat* c_q, CvMat* s, CvMat* t_m, CvMat* t_s, CvMat* deltat) { CvMat c, q; cvGetCols(c_q, &q, 0, 4); cvGetCols(c_q, &c, 4, 4+__cam.nModes()); // generate model texture __cam.CalcTexture(t_m, &c); // generate model shape __cam.CalcShape(s, c_q); // generate warped texture AAM_Common::CheckShape(s, image->width, image->height); __cam.__paw.CalcWarpTexture(s, image, t_s); __cam.__texture.NormalizeTexture(__cam.__MeanG, t_s); // calculate pixel difference cvSub(t_m, t_s, deltat); return cvNorm(deltat); } //============================================================================ void AAM_Basic::SetAllParamsZero() { cvSetZero(__q); cvSetZero(__c); } //============================================================================ void AAM_Basic::InitParams(const IplImage* image) { //shape parameter __cam.__shape.CalcParams(__s, __p, __q); //texture parameter __cam.__paw.CalcWarpTexture(__s, image, __t_s); __cam.__texture.NormalizeTexture(__cam.__MeanG, __t_s); __cam.__texture.CalcParams(__t_s, __lamda); //combined appearance parameter __cam.CalcParams(__c, __p, __lamda); } //============================================================================ bool AAM_Basic::Fit(const IplImage* image, AAM_Shape& Shape, int max_iter /* = 30 */,bool showprocess /* = false */) { //intial some stuff double t = gettime; double e1, e2; const int np = 5; double k_values[np] = {1, 0.5, 0.25, 0.125, 0.0625}; int k; IplImage* Drawimg = 0; Shape.Point2Mat(__s); InitParams(image); CvMat subcq; cvGetCols(__current_c_q, &subcq, 0, 4); cvCopy(__q, &subcq); cvGetCols(__current_c_q, &subcq, 4, 4+__cam.nModes()); cvCopy(__c, &subcq); //calculate error e1 = EstResidual(image, __current_c_q, __s, __t_m, __t_s, __delta_t); //do a number of iteration until convergence for(int iter = 0; iter <max_iter; iter++) { bool converge = false; if(showprocess) { if(Drawimg == 0) Drawimg = cvCloneImage(image); else cvCopy(image, Drawimg); __cam.CalcShape(__s, __current_c_q); AAM_Common::CheckShape(__s, image->width, image->height); Shape.Mat2Point(__s); Draw(Drawimg, Shape, 2); AAM_Common::MkDir("result"); char filename[100]; sprintf(filename, "result/Iter-%02d.jpg", iter); cvSaveImage(filename, Drawimg); } // predict parameter update cvGEMM(__delta_t, __G, 1, NULL, 0, __delta_c_q, CV_GEMM_B_T); //force first iteration if(iter == 0) { cvAdd(__current_c_q, __delta_c_q, __current_c_q); CvMat c; cvGetCols(__current_c_q, &c, 4, 4+__cam.nModes()); //constrain parameters __cam.Clamp(&c); e1 = EstResidual(image, __current_c_q, __s, __t_m, __t_s, __delta_t); } //find largest step size which reduces texture EstResidual else { for(k = 0; k < np; k++) { cvScaleAdd(__delta_c_q, cvScalar(k_values[k]), __current_c_q, __update_c_q); //constrain parameters CvMat c; cvGetCols(__update_c_q, &c, 4, 4+__cam.nModes()); __cam.Clamp(&c); e2 = EstResidual(image, __update_c_q, __s, __t_m, __t_s, __delta_t); //LOGI("%d %d %g: measure=%g %g\n", iter, k, k_values[k], e1, e2); if(e2 <= e1) { converge = true; break; } } //check for convergence if(converge) { e1 = e2; cvCopy(__update_c_q, __current_c_q); } else break; } } cvReleaseImage(&Drawimg); __cam.CalcShape(__s, __current_c_q); AAM_Common::CheckShape(__s, image->width, image->height); Shape.Mat2Point(__s); t = gettime - t; LOGI("AAM-Basic Fitting: time cost=%.3f millisec, measure=%.2f\n", t, e1); if(e1 >= 1.75) return false; return true; } //=========================================================================== void AAM_Basic::Draw(IplImage* image, const AAM_Shape& Shape, int type) { if(type == 0) AAM_Common::DrawPoints(image, Shape); else if(type == 1) AAM_Common::DrawTriangles(image, Shape, __cam.__paw.__tri); else if(type == 2) { double minV, maxV; cvMinMaxLoc(__t_m, &minV, &maxV); cvConvertScale(__t_m, __t_m, 255/(maxV-minV), -minV*255/(maxV-minV)); AAM_PAW paw; paw.Train(Shape, __cam.__Points, __cam.__Storage, __cam.__paw.GetTri(), false); AAM_Common::DrawAppearance(image, Shape, __t_m, paw, __cam.__paw); } else LOGW("ERROR(%s, %d): Unsupported drawing type\n", __FILE__, __LINE__); } //=========================================================================== void AAM_Basic::Write(std::ofstream& os) { __cam.Write(os); WriteCvMat(os, __G); } //=========================================================================== void AAM_Basic::Read(std::ifstream& is) { __cam.Read(is); __G = cvCreateMat(__cam.nModes()+4, __cam.__texture.nPixels(), CV_64FC1); ReadCvMat(is, __G); //allocate memory for on-line fitting __current_c_q = cvCreateMat(1, __cam.nModes()+4, CV_64FC1); __update_c_q = cvCreateMat(1, __cam.nModes()+4, CV_64FC1); __delta_c_q = cvCreateMat(1, __cam.nModes()+4, CV_64FC1); __c = cvCreateMat(1, __cam.nModes(), CV_64FC1); __p = cvCreateMat(1, __cam.__shape.nModes(), CV_64FC1); __q = cvCreateMat(1, 4, CV_64FC1); __lamda = cvCreateMat(1, __cam.__texture.nModes(), CV_64FC1); __s = cvCreateMat(1, __cam.__shape.nPoints()*2, CV_64FC1); __t_s = cvCreateMat(1, __cam.__texture.nPixels(), CV_64FC1); __t_m = cvCreateMat(1, __cam.__texture.nPixels(), CV_64FC1); __delta_t = cvCreateMat(1, __cam.__texture.nPixels(), CV_64FC1); }
#include <Windows.h> #include <Psapi.h> #include <cstdint> __forceinline const bool bDataCompare(const BYTE* pData, const BYTE* bMask, const char* szMask) { for (; *szMask; ++szMask, ++pData, ++bMask) { if (*szMask == 'x' && *pData != *bMask) return false; } return (*szMask) == NULL; } __forceinline const uint64_t FindPattern(const char* szModule, const char* bMask, const char* szMask) { MODULEINFO mi = { 0 }; (K32GetModuleInformation)((GetCurrentProcess)(), (GetModuleHandleA)(szModule), (LPMODULEINFO)&mi, (DWORD)sizeof(mi)); uint64_t dwBaseAddress = uint64_t(mi.lpBaseOfDll); const auto dwModuleSize = mi.SizeOfImage; if (!dwBaseAddress || !dwModuleSize) return 0; for (auto i = 0ul; i < dwModuleSize; i++) { if (bDataCompare(PBYTE(dwBaseAddress + i), (const BYTE*)bMask, szMask)) return uint64_t(dwBaseAddress + i); } return 0; } uint64_t(__fastcall* Present_Original)(uint64_t a1, uint32_t a2, uint32_t a3); uint64_t __fastcall Present_Hook(uint64_t a1, uint32_t a2, uint32_t a3) { static bool once = false; if (!once) { MessageBoxA(0, "Called Present_Hook", "Info", 0); once = true; } return Present_Original(a1, a2, a3); } uint64_t(__fastcall* ResizeBuffers_Original)(uint64_t a1, uint32_t a2, uint32_t a3, uint32_t a4, int a5, int a6); uint64_t __fastcall ResizeBuffers_Hook(uint64_t a1, uint32_t a2, uint32_t a3, uint32_t a4, int a5, int a6) { static bool once = false; if (!once) { MessageBoxA(0, "Called ResizeBuffers_Hook", "Info", 0); once = true; } return ResizeBuffers_Original(a1, a2, a3, a4, a5, a6); } BOOL APIENTRY DllMain( HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved ) { if (ul_reason_for_call == DLL_PROCESS_ATTACH) { const auto pPresentCall = FindPattern("medal-hook64.dll", "\xFF\x15\x00\x00\x00\x00\x33\xD2\x48\x8D\x0D\x00\x00\x00\x00\x8B\xF8\xE8\x00\x00\x00\x00\x48\x8B\x0D\x00\x00\x00\x00\x83\xB9\x00\x00\x00\x00\x00\x74\x08", "xx????xxxxx????xxx????xxx????xx?????xx"); if (pPresentCall) { const auto PresentPtr = PVOID(pPresentCall + *(uint32_t*)(pPresentCall + 2) + 6); *(PVOID*)&Present_Original = _InterlockedExchangePointer((PVOID*)PresentPtr, &Present_Hook); } const auto pResizeBuffersCall = FindPattern("medal-hook64.dll", "\xFF\x15\x00\x00\x00\x00\x33\xD2\x48\x8D\x0D\x00\x00\x00\x00\x8B\xD8\xE8\x00\x00\x00\x00\x48\x8B\x6C\x24\x00\x8B\xC3\x48\x8B\x5C\x24\x00\x48\x8B\x74\x24\x00\xC6\x05\x00\x00\x00\x00\x00", "xx????xxxxx????xxx????xxxx?xxxxxx?xxxx?xx?????"); if (pResizeBuffersCall) { const auto ResizeBuffersPtr = PVOID(pResizeBuffersCall + *(uint32_t*)(pResizeBuffersCall + 2) + 6); *(PVOID*)&Present_Original = _InterlockedExchangePointer((PVOID*)ResizeBuffersPtr, &Present_Hook); } } return TRUE; }
#include "gtest/gtest.h" #include <string> #include <vector> #include "ArgumentsParsing.h" #include "CmdOption.h" #include "Node.h" #include "SyntacticParser.h" namespace ArithmeticalParserTests { using OptionsMap = std::map<arithmetic_parser::CmdOption, arithmetic_parser::OptionInput>; TEST(SyntacticParserInvalidDataTests, OnePlusOne) { } }
/** * @file parseCmdArgs.hpp * @brief Functionality related to command line parsing for indexing and mapping * @author Chirag Jain <cjain7@gatech.edu> */ #ifndef PARSE_CMD_HPP #define PARSE_CMD_HPP #include <iostream> #include <string> #include <fstream> //Own includes #include "map/include/map_parameters.hpp" #include "map/include/map_stats.hpp" #include "map/include/commonFunc.hpp" //External includes #include "common/argvparser.hpp" namespace skch { /** * @brief Initialize the command line argument parser * @param[out] cmd command line parser object */ void initCmdParser(CommandLineProcessing::ArgvParser &cmd) { cmd.setIntroductoryDescription("-----------------\n\ Mashmap is an approximate long read or contig mapper based on Jaccard similarity\n\ -----------------\n\ Example usage: \n\ $ mashmap -r ref.fa -q seq.fq [OPTIONS]\n\ $ mashmap --rl reference_files_list.txt -q seq.fq [OPTIONS]"); cmd.setHelpOption("h", "help", "Print this help page"); cmd.defineOption("ref", "an input reference file (fasta/fastq)[.gz]", ArgvParser::OptionRequiresValue); cmd.defineOptionAlternative("ref","r"); cmd.defineOption("refList", "a file containing list of reference files, one per line", ArgvParser::OptionRequiresValue); cmd.defineOptionAlternative("refList","rl"); cmd.defineOption("query", "an input query file (fasta/fastq)[.gz]", ArgvParser::OptionRequiresValue); cmd.defineOptionAlternative("query","q"); cmd.defineOption("queryList", "a file containing list of query files, one per line", ArgvParser::OptionRequiresValue); cmd.defineOptionAlternative("queryList","ql"); cmd.defineOption("segLength", "mapping segment length [default : 5,000]\n\ sequences shorter than segment length will be ignored", ArgvParser::OptionRequiresValue); cmd.defineOptionAlternative("segLength","s"); cmd.defineOption("noSplit", "disable splitting of input sequences during mapping [enabled by default]"); cmd.defineOption("perc_identity", "threshold for identity [default : 85]", ArgvParser::OptionRequiresValue); cmd.defineOptionAlternative("perc_identity","pi"); cmd.defineOption("threads", "count of threads for parallel execution [default : 1]", ArgvParser::OptionRequiresValue); cmd.defineOptionAlternative("threads","t"); cmd.defineOption("output", "output file name [default : mashmap.out]", ArgvParser::OptionRequiresValue); cmd.defineOptionAlternative("output","o"); cmd.defineOption("kmer", "kmer size <= 16 [default : 16]", ArgvParser::OptionRequiresValue); cmd.defineOptionAlternative("kmer","k"); cmd.defineOption("filter_mode", "filter modes in mashmap: 'map', 'one-to-one' or 'none' [default: map]\n\ 'map' computes best mappings for each query sequence\n\ 'one-to-one' computes best mappings for query as well as reference sequence\n\ 'none' disables filtering", ArgvParser::OptionRequiresValue); cmd.defineOptionAlternative("filter_mode", "f"); cmd.defineOption("secondaries", "number of secondary mappings in 'map' filter_mode [default : 0]", ArgvParser::OptionRequiresValue); cmd.defineOptionAlternative("secondaries", "n"); } /** * @brief Parse the file which has list of reference or query files * @param[in] fileToRead File containing list of ref/query files * @param[out] fileList List of files will be saved in this vector */ template <typename VEC> void parseFileList(std::string &fileToRead, VEC &fileList) { std::string line; std::ifstream in(fileToRead); if (in.fail()) { std::cerr << "ERROR, skch::parseFileList, Could not open " << fileToRead << std::endl; exit(1); } while (std::getline(in, line)) { fileList.push_back(line); } } /** * @brief validate single input file * @param[in] fileName file name */ void validateInputFile(std::string &fileName) { //Open file one by one std::ifstream in(fileName); if (in.fail()) { std::cerr << "ERROR, skch::validateInputFile, Could not open " << fileName << std::endl; exit(1); } } /** * @brief validate the reference and query file(s) * @param[in] querySequences vector containing query file names * @param[in] refSequences vector containing reference file names */ template <typename VEC> void validateInputFiles(VEC &querySequences, VEC &refSequences) { //validate files one by one for(auto &e : querySequences) validateInputFile(e); for(auto &e : refSequences) validateInputFile(e); } /** * @brief Print the parsed cmd line options * @param[in] parameters parameters parsed from command line */ void printCmdOptions(skch::Parameters &parameters) { std::cerr << "[mashz::map] Reference = " << parameters.refSequences << std::endl; std::cerr << "[mashz::map] Query = " << parameters.querySequences << std::endl; std::cerr << "[mashz::map] Kmer size = " << parameters.kmerSize << std::endl; std::cerr << "[mashz::map] Window size = " << parameters.windowSize << std::endl; std::cerr << "[mashz::map] Segment length = " << parameters.segLength << (parameters.split ? " (read split allowed)": " (read split disabled)") << std::endl; std::cerr << "[mashz::map] Block length min = " << parameters.block_length_min << std::endl; std::cerr << "[mashz::map] Alphabet = " << (parameters.alphabetSize == 4 ? "DNA" : "AA") << std::endl; std::cerr << "[mashz::map] Percentage identity threshold = " << parameters.percentageIdentity << "\%" << std::endl; std::cerr << "[mashz::map] Mapping output file = " << parameters.outFileName << std::endl; std::cerr << "[mashz::map] Filter mode = " << parameters.filterMode << " (1 = map, 2 = one-to-one, 3 = none)" << std::endl; std::cerr << "[mashz::map] Execution threads = " << parameters.threads << std::endl; std::cerr << "[mashz::map] Spaced seed parameters = " << parameters.spaced_seed_params.weight << " " << parameters.spaced_seed_params.seed_count << " " << parameters.spaced_seed_params.similarity << " " << parameters.spaced_seed_params.region_length << std::endl; } /** * @brief Parse the cmd line options * @param[in] cmd * @param[out] parameters sketch parameters are saved here */ void parseandSave(int argc, char** argv, CommandLineProcessing::ArgvParser &cmd, skch::Parameters &parameters) { int result = cmd.parse(argc, argv); //Make sure we get the right command line args if (result != ArgvParser::NoParserError) { std::cerr << cmd.parseErrorDescription(result) << std::endl; exit(1); } else if (!cmd.foundOption("ref") && !cmd.foundOption("refList")) { std::cerr << "ERROR, skch::parseandSave, Provide reference file(s)" << std::endl; exit(1); } else if (!cmd.foundOption("query") && !cmd.foundOption("queryList")) { std::cerr << "ERROR, skch::parseandSave, Provide query file(s)" << std::endl; exit(1); } std::stringstream str; //Parse reference files if(cmd.foundOption("ref")) { std::string ref; str << cmd.optionValue("ref"); str >> ref; parameters.refSequences.push_back(ref); } else //list of files { std::string listFile; str << cmd.optionValue("refList"); str >> listFile; parseFileList(listFile, parameters.refSequences); } //Size of reference parameters.referenceSize = skch::CommonFunc::getReferenceSize(parameters.refSequences); str.clear(); //Parse query files if(cmd.foundOption("query")) { std::string query; str << cmd.optionValue("query"); str >> query; parameters.querySequences.push_back(query); } else //list of files { std::string listFile; str << cmd.optionValue("queryList"); str >> listFile; parseFileList(listFile, parameters.querySequences); } str.clear(); parameters.alphabetSize = 4; //Do not expose the option to set protein alphabet in mashmap //parameters.alphabetSize = 20; if(cmd.foundOption("filter_mode")) { str << cmd.optionValue("filter_mode"); std::string filter_input; str >> filter_input; if (filter_input == "map") parameters.filterMode = filter::MAP; else if (filter_input == "one-to-one") parameters.filterMode = filter::ONETOONE; else if (filter_input == "none") parameters.filterMode = filter::NONE; else { std::cerr << "ERROR, skch::parseandSave, Invalid option given for filter_mode" << std::endl; exit(1); }; str.clear(); } else parameters.filterMode = filter::MAP; if(cmd.foundOption("noSplit")) { parameters.split = false; } else parameters.split = true; //Parse algorithm parameters if(cmd.foundOption("kmer")) { str << cmd.optionValue("kmer"); str >> parameters.kmerSize; str.clear(); } else { if(parameters.alphabetSize == 4) parameters.kmerSize = 16; else parameters.kmerSize = 5; } if(cmd.foundOption("segLength")) { str << cmd.optionValue("segLength"); str >> parameters.segLength; str.clear(); if(parameters.segLength < 500) { std::cerr << "ERROR, skch::parseandSave, minimum segment length is required to be >= 500 bp.\n\ This is because Mashmap is not designed for computing short local alignments.\n" << std::endl; exit(1); } } else parameters.segLength = 5000; if(cmd.foundOption("perc_identity")) { str << cmd.optionValue("perc_identity"); str >> parameters.percentageIdentity; str.clear(); if(parameters.percentageIdentity < 70) { std::cerr << "ERROR, skch::parseandSave, minimum nucleotide identity requirement should be >= 70\%\n" << std::endl; exit(1); } } else parameters.percentageIdentity = 85; if(cmd.foundOption("threads")) { str << cmd.optionValue("threads"); str >> parameters.threads; str.clear(); } else parameters.threads = 1; /* * Compute window size for sketching */ //Compute optimal window size parameters.windowSize = skch::Stat::recommendedWindowSize( parameters.pval_cutoff, parameters.confidence_interval, parameters.kmerSize, parameters.alphabetSize, parameters.percentageIdentity, parameters.segLength, parameters.referenceSize); if(cmd.foundOption("output")) { str << cmd.optionValue("output"); str >> parameters.outFileName; str.clear(); } else parameters.outFileName = "mashmap.out"; if(cmd.foundOption("secondaries")) { str << cmd.optionValue("secondaries"); str >> parameters.secondaryToKeep; str.clear(); } else { parameters.secondaryToKeep = 0; } printCmdOptions(parameters); //Check if files are valid validateInputFiles(parameters.querySequences, parameters.refSequences); } } #endif
/* Copyright 2019 Abner Soares e Kallebe Sousa */ #include <stdexcept> #include "tu_entidades.hpp" void TU_Usuario::setUp() { this-> usuario = new Usuario(); estado = SUCESSO; } void TU_Reserva::setUp() { this-> reserva = new Reserva(); estado = SUCESSO; } void TU_Carona::setUp() { this-> carona = new Carona(); estado = SUCESSO; } void TU_Conta::setUp() { this-> conta = new Conta(); estado = SUCESSO; } void TU_Usuario::tearDown() { delete this->usuario; } void TU_Reserva::tearDown() { delete this->reserva; } void TU_Carona::tearDown() { delete this->carona; } void TU_Conta::tearDown() { delete this->conta; } // Teste simultâneo (no mesmo objeto) de sucesso e falha da classe Usuário void TU_Usuario::testarCenario() { try { usuario->setNome(NOME_INVALIDO); if (usuario->getNome().getValor() == NOME_INVALIDO) estado = FALHA; } catch(std::invalid_argument) { if (usuario->getNome().getValor() == NOME_INVALIDO) estado = FALHA; } try { usuario->setNome(NOME_VALIDO); if (usuario->getNome().getValor() != NOME_VALIDO) estado = FALHA; } catch(std::invalid_argument) { estado = FALHA; } try { usuario->setTelefone(TELEFONE_INVALIDO); if (usuario->getTelefone().getValor() == TELEFONE_INVALIDO) estado = FALHA; } catch(std::invalid_argument) { if (usuario->getTelefone().getValor() == TELEFONE_INVALIDO) estado = FALHA; } try { usuario->setTelefone(TELEFONE_VALIDO); if (usuario->getTelefone().getValor() != TELEFONE_VALIDO) estado = FALHA; } catch(std::invalid_argument) { estado = FALHA; } try { usuario->setEmail(EMAIL_INVALIDO); if (usuario->getEmail().getValor() == EMAIL_INVALIDO) estado = FALHA; } catch(std::invalid_argument) { if (usuario->getEmail().getValor() == EMAIL_INVALIDO) estado = FALHA; } try { usuario->setEmail(EMAIL_VALIDO); if (usuario->getEmail().getValor() != EMAIL_VALIDO) estado = FALHA; } catch(std::invalid_argument) { estado = FALHA; } try { usuario->setSenha(SENHA_INVALIDO); if (usuario->getSenha().getValor() == SENHA_INVALIDO) estado = FALHA; } catch(std::invalid_argument) { if (usuario->getSenha().getValor() == SENHA_INVALIDO) estado = FALHA; } try { usuario->setSenha(SENHA_VALIDO); if (usuario->getSenha().getValor() != SENHA_VALIDO) estado = FALHA; } catch(std::invalid_argument) { estado = FALHA; } try { usuario->setCpf(CPF_INVALIDO); if (usuario->getCpf().getValor() == CPF_INVALIDO) estado = FALHA; } catch(std::invalid_argument) { if (usuario->getCpf().getValor() == CPF_INVALIDO) estado = FALHA; } try { usuario->setCpf(CPF_VALIDO); if (usuario->getCpf().getValor() != CPF_VALIDO) estado = FALHA; } catch(std::invalid_argument) { estado = FALHA; } } void TU_Reserva::testarCenario() { try { reserva->setCodigo_de_reserva(CODIGO_INVALIDO); if (reserva->getCodigo_de_reserva().getValor() == CODIGO_INVALIDO) estado = FALHA; } catch(std::invalid_argument) { if (reserva->getCodigo_de_reserva().getValor() == CODIGO_INVALIDO) estado = FALHA; } try { reserva->setCodigo_de_reserva(CODIGO_VALIDO); if (reserva->getCodigo_de_reserva().getValor() != CODIGO_VALIDO) estado = FALHA; } catch(std::invalid_argument) { estado = FALHA; } try { reserva->setAssento(ASSENTO_INVALIDO); if (reserva->getAssento().getValor() == ASSENTO_INVALIDO) estado = FALHA; } catch(std::invalid_argument) { if (reserva->getAssento().getValor() == ASSENTO_INVALIDO) estado = FALHA; } try { reserva->setAssento(ASSENTO_VALIDO); if (reserva->getAssento().getValor() != ASSENTO_VALIDO) estado = FALHA; } catch(std::invalid_argument) { estado = FALHA; } try { reserva->setBagagem(BAGAGEM_INVALIDO); if (reserva->getBagagem().getValor() == BAGAGEM_INVALIDO) estado = FALHA; } catch(std::invalid_argument) { if (reserva->getBagagem().getValor() == BAGAGEM_INVALIDO) estado = FALHA; } try { reserva->setBagagem(BAGAGEM_VALIDO); if (reserva->getBagagem().getValor() != BAGAGEM_VALIDO) estado = FALHA; } catch(std::invalid_argument) { estado = FALHA; } } void TU_Carona::testarCenario() { try { carona->setCodigo_de_carona(CODIGO_INVALIDO); if (carona->getCodigo_de_carona().getValor() == CODIGO_INVALIDO) estado = FALHA; } catch(std::invalid_argument) { if (carona->getCodigo_de_carona().getValor() == CODIGO_INVALIDO) estado = FALHA; } try { carona->setCodigo_de_carona(CODIGO_VALIDO); if (carona->getCodigo_de_carona().getValor() != CODIGO_VALIDO) estado = FALHA; } catch(std::invalid_argument) { estado = FALHA; } try { carona->setCidade_origem(CIDADE_ORIGEM_INVALIDO); if (carona->getCidadeOrigem().getValor() == CIDADE_ORIGEM_INVALIDO) estado = FALHA; } catch(std::invalid_argument) { if (carona->getCidadeOrigem().getValor() == CIDADE_ORIGEM_INVALIDO) estado = FALHA; } try { carona->setCidade_origem(CIDADE_ORIGEM_VALIDO); if (carona->getCidadeOrigem().getValor() != CIDADE_ORIGEM_VALIDO) estado = FALHA; } catch(std::invalid_argument) { estado = FALHA; } try { carona->setEstado_origem(ESTADO_ORIGEM_INVALIDO); if (carona->getEstado_origem().getValor() == ESTADO_ORIGEM_INVALIDO) estado = FALHA; } catch(std::invalid_argument) { if (carona->getEstado_origem().getValor() == ESTADO_ORIGEM_INVALIDO) estado = FALHA; } try { carona->setEstado_origem(ESTADO_ORIGEM_VALIDO); if (carona->getEstado_origem().getValor() != ESTADO_ORIGEM_VALIDO) estado = FALHA; } catch(std::invalid_argument) { estado = FALHA; } try { carona->setCidade_destino(CIDADE_DESTINO_INVALIDO); if (carona->getCidadedestino().getValor() == CIDADE_DESTINO_INVALIDO) estado = FALHA; } catch(std::invalid_argument) { if (carona->getCidadedestino().getValor() == CIDADE_DESTINO_INVALIDO) estado = FALHA; } try { carona->setCidade_destino(CIDADE_DESTINO_VALIDO); if (carona->getCidadedestino().getValor() != CIDADE_DESTINO_VALIDO) estado = FALHA; } catch(std::invalid_argument) { estado = FALHA; } try { carona->setEstado_destino(ESTADO_DESTINO_INVALIDO); if (carona->getEstado_destino().getValor() == ESTADO_DESTINO_INVALIDO) estado = FALHA; } catch(std::invalid_argument) { if (carona->getEstado_destino().getValor() == ESTADO_DESTINO_INVALIDO) estado = FALHA; } try { carona->setEstado_destino(ESTADO_DESTINO_VALIDO); if (carona->getEstado_destino().getValor() != ESTADO_DESTINO_VALIDO) estado = FALHA; } catch(std::invalid_argument) { estado = FALHA; } try { carona->setData(DATA_INVALIDO); if (carona->getData().getValor() == DATA_INVALIDO) estado = FALHA; } catch(std::invalid_argument) { if (carona->getData().getValor() == DATA_INVALIDO) estado = FALHA; } try { carona->setData(DATA_VALIDO); if (carona->getData().getValor() != DATA_VALIDO) estado = FALHA; } catch(std::invalid_argument) { estado = FALHA; } try { carona->setDuracao(DURACAO_INVALIDO); if (carona->getDuracao().getValor() == DURACAO_INVALIDO) estado = FALHA; } catch(std::invalid_argument) { if (carona->getDuracao().getValor() == DURACAO_INVALIDO) estado = FALHA; } try { carona->setDuracao(DURACAO_VALIDO); if (carona->getDuracao().getValor() != DURACAO_VALIDO) estado = FALHA; } catch(std::invalid_argument) { estado = FALHA; } try { carona->setVagas(VAGAS_INVALIDO); if (carona->getVagas().getValor() == VAGAS_INVALIDO) estado = FALHA; } catch(std::invalid_argument) { if (carona->getVagas().getValor() == VAGAS_INVALIDO) estado = FALHA; } try { carona->setVagas(VAGAS_VALIDO); if (carona->getVagas().getValor() != VAGAS_VALIDO) estado = FALHA; } catch(std::invalid_argument) { estado = FALHA; } try { carona->setPreco(PRECO_INVALIDO); if (carona->getPreco().getValor() == PRECO_INVALIDO) estado = FALHA; } catch(std::invalid_argument) { if (carona->getPreco().getValor() == PRECO_INVALIDO) estado = FALHA; } try { carona->setPreco(PRECO_VALIDO); if (carona->getPreco().getValor() != PRECO_VALIDO) estado = FALHA; } catch(std::invalid_argument) { estado = FALHA; } } void TU_Conta::testarCenario() { try { conta->setCodigo_de_banco(BANCO_INVALIDO); if (conta->getCodigo_de_banco().getValor() == BANCO_INVALIDO) estado = FALHA; } catch(std::invalid_argument) { if (conta->getCodigo_de_banco().getValor() == BANCO_INVALIDO) estado = FALHA; } try { conta->setCodigo_de_banco(BANCO_VALIDO); if (conta->getCodigo_de_banco().getValor() != BANCO_VALIDO) estado = FALHA; } catch(std::invalid_argument) { estado = FALHA; } try { conta->setNumero_de_agencia(AGENCIA_INVALIDO); if (conta->getNumero_de_agencia().getValor() == AGENCIA_INVALIDO) estado = FALHA; } catch(std::invalid_argument) { if (conta->getNumero_de_agencia().getValor() == AGENCIA_INVALIDO) estado = FALHA; } try { conta->setNumero_de_agencia(AGENCIA_VALIDO); if (conta->getNumero_de_agencia().getValor() != AGENCIA_VALIDO) estado = FALHA; } catch(std::invalid_argument) { estado = FALHA; } try { conta->setNumero_de_conta(NUMERO_INVALIDO); if (conta->getNumero_de_conta().getValor() == NUMERO_INVALIDO) estado = FALHA; } catch(std::invalid_argument) { if (conta->getNumero_de_conta().getValor() == NUMERO_INVALIDO) estado = FALHA; } try { conta->setNumero_de_conta(NUMERO_VALIDO); if (conta->getNumero_de_conta().getValor() != NUMERO_VALIDO) estado = FALHA; } catch(std::invalid_argument) { estado = FALHA; } } int TU_Usuario::run() { setUp(); testarCenario(); tearDown(); return estado; } int TU_Reserva::run() { setUp(); testarCenario(); tearDown(); return estado; } int TU_Carona::run() { setUp(); testarCenario(); tearDown(); return estado; } int TU_Conta::run() { setUp(); testarCenario(); tearDown(); return estado; }
#include <iostream> #include <math.h> #include <cmath> using namespace std; float f(double x) { return (x*x*x + 6 * x *x - 0.02*exp(x) - 14); } // вычисляемая функция float df(float x) { return (3 * x*x + 12 * x - 0.02*exp(x)); } // производная функции void reshenie() { double x, x1, temp = 0, a = -6, b = 2, h = 0.1, e = 0.0000000001; for (x = a; x < b; x += h) if (f(x)*f(x + h) < 0) // проверка на существование корня(пересечения графика оси Ох) { x1 = a; while (fabs(x1 - temp) > e) { x1 = x - f(x) / df(x); temp = x; x = x1; } cout << "x= " << x1 << " y= " << f(x1) << endl; } } int main() { reshenie(); system("pause"); }
// // Created by 송지원 on 2020/07/07. // #include <iostream> using namespace std; int N, K; int cnt; int student[6][2]; int a, b; int main() { ios::sync_with_stdio(0); cin.tie(0); cin >> N >> K; for (int i=0; i<N; i++) { cin >> a >> b; student[b-1][a]++; } for (int i=0; i<6; i++) { cnt += student[i][0]/K; cnt += student[i][1]/K; if (student[i][0]%K) cnt++; if (student[i][1]%K) cnt++; } cout << cnt; }
#include<iostream> using namespace std; //function declaration //double distance(double velocity, double time_elapsed) ; // function definition double distance(double velocity, double time_elapsed) { return velocity * time_elapsed / 2 ; } int main() { // function call cout<<distance(5544.98, 6.9)<<endl; return 0; }
/* * Created by Peng Qixiang on 2018/5/27. */ /* * 输入一个整数,输出该数二进制表示中1的个数. * 其中负数用补码表示。 */ # include <iostream> using namespace std; // 错误,负数左移最高位填1, 固会陷入死循环 int NumberOf1_v1(int n) { int count = 0; while (n != 0) { count += (n & 1); n = n >> 1; } return count; } // 解法1, n = n & (n-1), 将最右边一个1置0 int NumberOf1(int n){ int count = 0; while( n != 0){ count ++; n = n & (n-1); } return count; } int main(){ cout << NumberOf1(61) << endl; return 0; }
#include "DisplayRender.h" DisplayRender::DisplayRender(Display disp) { display_map = disp; } void DisplayRender::updateMap() { for (int i = 0; i < 16; i++) { openSingle(i, display_map.getColorAt(i)); //Serial.print(display_map.getColorAt(i)); //Serial.print(";"); } //Serial.println(); pixels.show(); } void DisplayRender::updateMap4x4() { byte row = 0; byte four_couter = 0; for (int i = 0; i < 16; i++) { if (i % 4 == 0 && i != 0) { row += 1; four_couter = 0; } openSingle4x4(row, four_couter, display_map.getColorAt(i)); four_couter += 1; } pixelsRow0.show(); pixelsRow1.show(); pixelsRow2.show(); pixelsRow3.show(); } void DisplayRender::openSingle(int num, uint32_t RGB) { int broken_led = 3; int temp_num = num; uint8_t interval = 0; interval = 16 / 2; //Skip broken led if (num > broken_led) { temp_num -= 1; } if (num != broken_led) { for (int i = temp_num * NUM_RING_ONE_PIX; i < ((temp_num + 1) * NUM_RING_ONE_PIX); i++) { pixels.setPixelColor(i, RGB); } } //pixels.show(); } void DisplayRender::openSingle4x4(byte row, int num, uint32_t RGB) { for (int i = num * NUM_RING_ONE_PIX; i < ((num + 1) * NUM_RING_ONE_PIX); i++) { if (row == 0) { pixelsRow0.setPixelColor(i, RGB); } if (row == 1) { pixelsRow1.setPixelColor(i, RGB); } if (row == 2) { pixelsRow2.setPixelColor(i, RGB); } if (row == 3) { pixelsRow3.setPixelColor(i, RGB); } } } void DisplayRender::openSingleRGB(int num, byte r, byte g, byte b) { for (int i = num * NUM_RING_ONE_PIX; i < ((num + 1) * NUM_RING_ONE_PIX); i++) { pixels.setPixelColor(i, r, g, b); } }
#include <stdio.h> #include <string.h> int main(){ char str[1007]; int sum = 0 ; int length; int n; while(gets(str)!=NULL){ sum=0; length=strlen(str); for(int i=0;i<length;i++){ if(str[i]=='(') sum++; else if(str[i]==')') sum--; else if (str[i]=='B') break; } printf("%d\n",sum); } }
#include <iostream> #include <vector> #include <queue> using namespace std; pair<queue<pair<int, int>>, bool> find_path( const vector<vector<char>>& grid, int r = 0, int c = 0, queue<pair<int, int>> path = {}) { if ((r < grid.size()) && (c < grid[r].size()) && (grid[r][c] == 'o')) { path.push({r, c}); } if ((r == (grid.size() - 1)) && (c == (grid[r].size() - 1))) { return {path, true}; } if ((r >= grid.size()) || (c >= grid[r].size()) || (grid[r][c] != 'o')) { return {path, false}; } auto result = find_path(grid, r + 1, c, path); if (result.second) { return result; } else { return find_path(grid, r, c + 1, path); } } int main() { const vector<vector<char>> grid { {'o', 'o', 'o', 'o', 'o'}, {'o', 'o', 'o', 'o', 'o'}, {'o', 'o', 'o', 'x', 'o'}, {'o', 'x', 'o', 'o', 'o'}, {'o', 'x', 'o', 'x', 'o'}, }; auto result = find_path(grid); cout << "Found path: " << result.second << endl; auto path = result.first; while (!path.empty()) { auto pr = path.front(); cout << "(" << pr.first << ", " << pr.second << "), "; path.pop(); } cout << endl; }
/* * Terrier.cpp * * Created on: Jun 7, 2016 * Author: g33z */ #include "Terrier.h" Terrier::~Terrier() { } void Terrier::bark(){ cout << "Gautz " << "Gautz!" << endl; }
/* ======================================================================== DEVise Data Visualization Software (c) Copyright 1992-1996 By the DEVise Development Group Madison, Wisconsin All Rights Reserved. ======================================================================== Under no circumstances is this software to be copied, distributed, or altered in any way without prior permission from the DEVise Development Group. */ /* $Id: CompositeParser.c,v 1.4 1996/09/05 23:14:16 kmurli Exp $ $Log: CompositeParser.c,v $ Revision 1.4 1996/09/05 23:14:16 kmurli Added a destructor to free the fileType char pointer after use. CVS ---------------------------------------------------------------------- Revision 1.3 1996/03/26 20:22:01 jussi Added copyright notice and cleaned up the code a bit. Revision 1.2 1995/09/05 22:14:35 jussi Added CVS header. */ #include <stdio.h> #include "RecInterp.h" #include "CompositeParser.h" #include "Exit.h" #include <malloc.h> CompositeEntry CompositeParser::_entries[MAX_COMPOSITE_ENTRIES]; int CompositeParser::_numEntries = 0; int CompositeParser::_hintIndex = -1; CompositeParser::~CompositeParser() { for(int i = 0; i < _numEntries; i++) free(_entries[i].fileType); } void CompositeParser::Register(char *fileType, UserComposite *userComposite){ if (_numEntries >= MAX_COMPOSITE_ENTRIES) { fprintf(stderr,"CompositeParser:: too many entries\n"); Exit::DoExit(2); } _entries[_numEntries].fileType = (char * )fileType; _entries[_numEntries].userComposite = userComposite; _numEntries++; } void CompositeParser::Decode(char *fileType, RecInterp *recInterp) { if (_hintIndex >= 0 && !strcmp(fileType, _entries[_hintIndex].fileType)) { /* found it */ _entries[_hintIndex].userComposite->Decode(recInterp); return; } /* search for a matching file type */ for(int i = 0; i < _numEntries; i++) { if (!strcmp(fileType,_entries[i].fileType)) { /* found it */ _hintIndex = i; _entries[_hintIndex].userComposite->Decode(recInterp); return; } } /* not found */ fprintf(stderr, "Can't find user composite function for file type %s\n", fileType); Exit::DoExit(2); }
#include "Curativos.h" #include <sstream> #include <iostream> using std::cout; using std::endl; using std::cout; using std::stringstream; Curativos::Curativos(){ } Curativos::Curativos(string n, int nv, string t){ nombre=n; nivel=nv; tipo=t; } string Curativos::getTipo(){ return tipo; } string Curativos::toString(){ stringstream retorno; string r; cout<<Poder::toString(); cout<<"\n Tipo de curacion : "<<tipo; r=retorno.str(); return retorno.str(); }
#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; typedef long long LL; const int maxn = 3e5; const LL mod = 1e9 + 7; struct point { int k,step; }; queue<point> Q; int a[40],dis[maxn + 100]; int main() { int t,n,m; scanf("%d",&t); while (t--) { scanf("%d%d",&n,&m); for (int i = 1;i <= n; i++) scanf("%d",&a[20+i]); for (int i = 0;i <= 20; i++) a[i] = 1 << i; n += 20; memset(dis,INF,sizeof(dis));dis[0] = 0; Q.push((point){0,0}); while (!Q.empty()) { point s = Q.front();Q.pop(); for (int i = 0;i <= n; i++) { int t = s.k^a[i]; if (t <= maxn && dis[t] == INF) { dis[t] = s.step + 1; Q.push((point){t,dis[t]}); } } } //for (int i = 1;i <= maxn; i++) // if (dis[i] == INF) cout << "!"; int x,y; LL ans = 0; for (int i = 1;i <= m; i++) { scanf("%d%d",&x,&y); //cout << dis[x^y] << endl; ans = (ans + (LL)dis[x^y]*i)%mod; } printf("%lld\n",ans); } return 0; }
/* * NIST Utils Class Library * clutils/Str.cc * April 1997 * K. C. Morris * David Sauder * Development of this software was funded by the United States Government, * and is not subject to copyright. */ #include <Str.h> #include <scl_memmgr.h> #ifndef STRING_DELIM #define STRING_DELIM '\'' #endif /****************************************************************** ** Procedure: string functions ** Description: These functions take a character or a string and return ** a temporary copy of the string with the function applied to it. ** Parameters: ** Returns: temporary copy of characters ** Side Effects: ** Status: complete ******************************************************************/ char ToLower( const char c ) { if( isupper( c ) ) { return ( tolower( c ) ); } else { return ( c ); } } char ToUpper( const char c ) { if( islower( c ) ) { return ( toupper( c ) ); } else { return ( c ); } } // Place in strNew a lowercase version of strOld. char * StrToLower( const char * strOld, char * strNew ) { int i = 0; while( strOld[i] != '\0' ) { strNew[i] = ToLower( strOld[i] ); i++; } strNew[i] = '\0'; return strNew; } const char * StrToLower( const char * word, std::string & s ) { char newword [BUFSIZ]; int i = 0; while( word [i] != '\0' ) { newword [i] = ToLower( word [i] ); ++i; } newword [i] = '\0'; s = newword; return const_cast<char *>( s.c_str() ); } const char * StrToUpper( const char * word, std::string & s ) { char newword [BUFSIZ]; int i = 0; while( word [i] != '\0' ) { newword [i] = ToUpper( word [i] ); ++i; } newword [i] = '\0'; s = newword; return const_cast<char *>( s.c_str() ); } const char * StrToConstant( const char * word, std::string & s ) { char newword [BUFSIZ]; int i = 0; while( word [i] != '\0' ) { if( word [i] == '/' || word [i] == '.' ) { newword [i] = '_'; } else { newword [i] = ToUpper( word [i] ); } ++i; } newword [i] = '\0'; s = newword; return const_cast<char *>( s.c_str() ); } /**************************************************************//** ** \fn StrCmpIns (const char * str1, const char * str2) ** \returns Comparison result ** Compares two strings case insensitive (lowercase). ** Returns < 0 when str1 less then str2 ** == 0 when str1 equals str2 ** > 0 when str1 greater then str2 ******************************************************************/ int StrCmpIns( const char * str1, const char * str2 ) { char c1, c2; while ((c1 = tolower(*str1)) == (c2 = tolower(*str2)) && c1 != '\0') { str1++; str2++; } return c1 - c2; } /**************************************************************//** ** \fn PrettyTmpName (char * oldname) ** \returns a new capitalized name in a static buffer ** Capitalizes first char of word, rest is lowercase. Removes '_'. ** Status: OK 7-Oct-1992 kcm ******************************************************************/ const char * PrettyTmpName( const char * oldname ) { int i = 0; static char newname [BUFSIZ]; newname [0] = '\0'; while( ( oldname [i] != '\0' ) && ( i < BUFSIZ ) ) { newname [i] = ToLower( oldname [i] ); if( oldname [i] == '_' ) { /* character is '_' */ ++i; newname [i] = ToUpper( oldname [i] ); } if( oldname [i] != '\0' ) { ++i; } } newname [0] = ToUpper( oldname [0] ); newname [i] = '\0'; return newname; } /**************************************************************//** ** \fn PrettyNewName (char * oldname) ** \returns a new capitalized name ** Capitalizes first char of word, rest is lowercase. Removes '_'. ** Side Effects: allocates memory for the new name ** Status: OK 7-Oct-1992 kcm ******************************************************************/ char * PrettyNewName( const char * oldname ) { char * name = new char [strlen( oldname ) + 1]; strcpy( name, PrettyTmpName( oldname ) ); return name; } /** * Extract the string conforming to P21 from the istream */ std::string ToExpressStr( istream & in, ErrorDescriptor * err ) { char c; in >> ws; // skip white space in >> c; int i_quote = 0; size_t found; string s = ""; if( c == STRING_DELIM ) { s += c; while( i_quote != -1 && in.get( c ) ) { s += c; // to handle a string like 'hi''' if( c == STRING_DELIM ) { // to handle \S\' found = s.rfind( "\\S\\" ); if( !( found != string::npos && ( s.size() == found + 2 ) ) ) { i_quote++; } } else { // # of quotes is odd if( i_quote % 2 != 0 ) { i_quote = -1; // put back last char, take it off from s and update c in.putback( c ); s = s.substr( 0, s.size() - 1 ); c = *s.rbegin(); } } } if( c != STRING_DELIM ) { // non-recoverable error err->AppendToDetailMsg( "Missing closing quote on string value.\n" ); err->AppendToUserMsg( "Missing closing quote on string value.\n" ); err->GreaterSeverity( SEVERITY_INPUT_ERROR ); } } else { in.putback( c ); } return s; } /** *** This function is used to check an input stream following a read. It writes *** error messages in the 'ErrorDescriptor &err' argument as appropriate. *** 'const char *tokenList' argument contains a string made up of delimiters *** that are used to move the file pointer in the input stream to the end of *** the value you are reading (i.e. the ending marked by the presence of the *** delimiter). The file pointer is moved just prior to the delimiter. If the *** tokenList argument is a null pointer then this function expects to find EOF. *** *** If input is being read from a stream then a tokenList should be provided so *** this function can push the file pointer up to but not past the delimiter *** (i.e. not removing the delimiter from the input stream). If you have a *** string containing a single value and you expect the whole string to contain *** a valid value, you can change the string to an istrstream, read the value *** then send the istrstream to this function with tokenList set to null *** and this function will set an error for you if any input remains following *** the value. *** If the input stream can be readable again then *** - any error states set for the the stream are cleared. *** - white space skipped in the input stream *** - if EOF is encountered it returns *** otherwise it peeks at the next character *** - if the tokenList argument exists (i.e. is not null) *** then if looks to see if the char peeked at is in the tokenList string *** if it is then no error is set in the ErrorDescriptor *** if the char peeked at is not in the tokenList string that implies *** that there is garbage following the value that was successfully *** or unsuccessfully read. The garbage is read until EOF or a *** delimiter in the tokenList is found. *** - EOF is found you did not recover -> SEVERITY_INPUT_ERROR *** - delimiter found you recovered successfully => SEVERITY_WARNING *** - if tokenList does not exist then it expects to find EOF, if it does *** not then it is an error but the bad chars are not read since you have *** no way to know when to stop. **/ Severity CheckRemainingInput( istream & in, ErrorDescriptor * err, const char * typeName, // used in error message const char * tokenList ) { // e.g. ",)" std::string skipBuf; char name[64]; name[0] = 0; // 1. CHECK to see if there is invalid input following what you read. // good or fail means you can still read from the input stream. if( in.good() || in.fail() ) // fail means that the input did not match the expected input. { // check for bad input following what you read (or tried to read) but // preceding a delimiter if you are expecting one. in.clear(); // clear the istreams error in >> ws; // skip whitespace if( in.eof() ) { // no input following the desired input (or following the // missing desired input) return err->severity(); } char c; c = in.peek(); if( tokenList ) { // are expecting a delim so read till you find it // 3. FIND a delimiter if( strchr( tokenList, c ) ) { // next char peeked at was delim expected => success return err->severity(); } else { // next character was not a delim and thus is garbage // read bad input until you find the delim in.get( c ); while( in && !strchr( tokenList, c ) ) { // this could chew up the remainder of the input unless you // give it the delim to end an entity value and it knows // about strings skipBuf += c; in.get( c ); } // ENHANCEMENT may want to add the bad data to the err msg. if( strchr( tokenList, c ) ) { // congratulations you recovered err->GreaterSeverity( SEVERITY_WARNING ); sprintf( name, "\tFound invalid %s value...\n", typeName ); err->AppendToUserMsg( name ); err->AppendToDetailMsg( name ); err->AppendToDetailMsg( "\tdata lost looking for end of attribute: " ); err->AppendToDetailMsg( skipBuf.c_str() ); err->AppendToDetailMsg( "\n" ); in.putback( c ); // invalid input // (though a valid value may have been assigned) return err->severity(); } else { // could not recover (of course) err->GreaterSeverity( SEVERITY_INPUT_ERROR ); sprintf( name, "Unable to recover from input error while reading %s %s", typeName, "value.\n" ); err->AppendToUserMsg( name ); err->AppendToDetailMsg( name ); // invalid input // (though a valid value may have been assigned) return err->severity(); } } } else if( in.good() ) // found a char => error // i.e. skipping whitespace did not cause EOF so must have hit a char { // remember we are not expecting more input since no tokenList // or 3. since not expecting a delimiter and there is input there // is an error err->GreaterSeverity( SEVERITY_WARNING ); sprintf( name, "Invalid %s value.\n", typeName ); err->AppendToUserMsg( name ); err->AppendToDetailMsg( name ); // invalid input // (though a valid value may have been assigned) return err->severity(); } } else if( in.eof() ) { // hit EOF when reading for a value // don\'t set any error return err->severity(); } else { // badbit set (in.bad()) means there was a problem when reading istream // this is bad news... it means the input stream is hopelessly messed up err->GreaterSeverity( SEVERITY_INPUT_ERROR ); sprintf( name, "Invalid %s value.\n", typeName ); err->AppendToUserMsg( name ); err->AppendToDetailMsg( name ); // invalid input // (though a valid value may have been assigned) return err->severity(); } return err->severity(); }
/*********************************************************\ * Copyright (c) 2012-2018 The Unrimp Team * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software * and associated documentation files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS 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. \*********************************************************/ //[-------------------------------------------------------] //[ Header guard ] //[-------------------------------------------------------] #pragma once //[-------------------------------------------------------] //[ Includes ] //[-------------------------------------------------------] #include <Renderer/PlatformTypes.h> #include "VulkanRenderer/Vulkan.h" //[-------------------------------------------------------] //[ Forward declarations ] //[-------------------------------------------------------] namespace VulkanRenderer { class VulkanRenderer; } //[-------------------------------------------------------] //[ Namespace ] //[-------------------------------------------------------] namespace VulkanRenderer { //[-------------------------------------------------------] //[ Classes ] //[-------------------------------------------------------] /** * @brief * Vulkan runtime linking for creating and managing the Vulkan instance ("VkInstance") */ class VulkanRuntimeLinking final { //[-------------------------------------------------------] //[ Public definitions ] //[-------------------------------------------------------] public: static const uint32_t NUMBER_OF_VALIDATION_LAYERS; static const char* VALIDATION_LAYER_NAMES[]; //[-------------------------------------------------------] //[ Public methods ] //[-------------------------------------------------------] public: /** * @brief * Constructor * * @param[in] vulkanRenderer * Owner Vulkan renderer instance * @param[in] enableValidation * Enable validation? */ VulkanRuntimeLinking(VulkanRenderer& vulkanRenderer, bool enableValidation); /** * @brief * Destructor */ ~VulkanRuntimeLinking(); /** * @brief * Return whether or not validation is enabled * * @return * "true" if validation is enabled, else "false" */ inline bool isValidationEnabled() const; /** * @brief * Return whether or not Vulkan is available * * @return * "true" if Vulkan is available, else "false" */ bool isVulkanAvaiable(); /** * @brief * Return the Vulkan instance * * @return * Vulkan instance */ inline VkInstance getVkInstance() const; /** * @brief * Load the device level Vulkan function entry points * * @param[in] vkDevice * Vulkan device instance to load the function entry pointers for * * @return * "true" if all went fine, else "false" */ bool loadDeviceLevelVulkanEntryPoints(VkDevice vkDevice) const; //[-------------------------------------------------------] //[ Private methods ] //[-------------------------------------------------------] private: explicit VulkanRuntimeLinking(const VulkanRuntimeLinking& source) = delete; VulkanRuntimeLinking& operator =(const VulkanRuntimeLinking& source) = delete; /** * @brief * Load the shared libraries * * @return * "true" if all went fine, else "false" */ bool loadSharedLibraries(); /** * @brief * Load the global level Vulkan function entry points * * @return * "true" if all went fine, else "false" */ bool loadGlobalLevelVulkanEntryPoints() const; /** * @brief * Create the Vulkan instance * * @param[in] enableValidation * Enable validation layer? (don't do this for shipped products) * * @return * Vulkan instance creation result */ VkResult createVulkanInstance(bool enableValidation); /** * @brief * Load the instance level Vulkan function entry points * * @return * "true" if all went fine, else "false" */ bool loadInstanceLevelVulkanEntryPoints() const; /** * @brief * Setup debug callback */ void setupDebugCallback(); //[-------------------------------------------------------] //[ Private data ] //[-------------------------------------------------------] private: VulkanRenderer& mVulkanRenderer; ///< Owner Vulkan renderer instance bool mValidationEnabled; ///< Validation enabled? void* mVulkanSharedLibrary; ///< Vulkan shared library, can be a null pointer bool mEntryPointsRegistered; ///< Entry points successfully registered? VkInstance mVkInstance; ///< Vulkan instance, stores all per-application states VkDebugReportCallbackEXT mVkDebugReportCallbackEXT; ///< Vulkan debug report callback, can be a null handle bool mInstanceLevelFunctionsRegistered; ///< Instance level Vulkan function pointers registered? bool mInitialized; ///< Already initialized? }; //[-------------------------------------------------------] //[ Namespace ] //[-------------------------------------------------------] } // VulkanRenderer //[-------------------------------------------------------] //[ Macros & definitions ] //[-------------------------------------------------------] #ifndef FNPTR #ifdef VULKAN_DEFINERUNTIMELINKING #define FNPTR(name) PFN_##name name; #else #define FNPTR(name) extern PFN_##name name; #endif #endif // Global Vulkan function pointers FNPTR(vkGetInstanceProcAddr) FNPTR(vkGetDeviceProcAddr) FNPTR(vkEnumerateInstanceExtensionProperties) FNPTR(vkEnumerateInstanceLayerProperties) FNPTR(vkCreateInstance) // Instance based Vulkan function pointers FNPTR(vkDestroyInstance) FNPTR(vkEnumeratePhysicalDevices) FNPTR(vkEnumerateDeviceLayerProperties) FNPTR(vkEnumerateDeviceExtensionProperties) FNPTR(vkGetPhysicalDeviceQueueFamilyProperties) FNPTR(vkGetPhysicalDeviceFeatures) FNPTR(vkGetPhysicalDeviceFormatProperties) FNPTR(vkGetPhysicalDeviceMemoryProperties) FNPTR(vkGetPhysicalDeviceProperties) FNPTR(vkCreateDevice) // "VK_EXT_debug_report"-extension FNPTR(vkCreateDebugReportCallbackEXT) FNPTR(vkDestroyDebugReportCallbackEXT) // "VK_KHR_surface"-extension FNPTR(vkDestroySurfaceKHR) FNPTR(vkGetPhysicalDeviceSurfaceSupportKHR) FNPTR(vkGetPhysicalDeviceSurfaceFormatsKHR) FNPTR(vkGetPhysicalDeviceSurfaceCapabilitiesKHR) FNPTR(vkGetPhysicalDeviceSurfacePresentModesKHR) #ifdef VK_USE_PLATFORM_WIN32_KHR // "VK_KHR_win32_surface"-extension FNPTR(vkCreateWin32SurfaceKHR) #elif defined VK_USE_PLATFORM_ANDROID_KHR // "VK_KHR_android_surface"-extension #warning "TODO(co) Not tested" FNPTR(vkCreateAndroidSurfaceKHR) #elif defined VK_USE_PLATFORM_XLIB_KHR || defined VK_USE_PLATFORM_WAYLAND_KHR #if defined VK_USE_PLATFORM_XLIB_KHR // "VK_KHR_xlib_surface"-extension FNPTR(vkCreateXlibSurfaceKHR) #endif #if defined VK_USE_PLATFORM_WAYLAND_KHR // "VK_KHR_wayland_surface"-extension FNPTR(vkCreateWaylandSurfaceKHR) #endif #elif defined VK_USE_PLATFORM_XCB_KHR // "VK_KHR_xcb_surface"-extension #warning "TODO(co) Not tested" FNPTR(vkCreateXcbSurfaceKHR) #else #error "Unsupported platform" #endif // Device based Vulkan function pointers FNPTR(vkDestroyDevice) FNPTR(vkCreateShaderModule) FNPTR(vkDestroyShaderModule) FNPTR(vkCreateBuffer) FNPTR(vkDestroyBuffer) FNPTR(vkMapMemory) FNPTR(vkUnmapMemory) FNPTR(vkCreateBufferView) FNPTR(vkDestroyBufferView) FNPTR(vkAllocateMemory) FNPTR(vkFreeMemory) FNPTR(vkGetBufferMemoryRequirements) FNPTR(vkBindBufferMemory) FNPTR(vkCreateRenderPass) FNPTR(vkDestroyRenderPass) FNPTR(vkCreateImage) FNPTR(vkDestroyImage) FNPTR(vkGetImageSubresourceLayout) FNPTR(vkGetImageMemoryRequirements) FNPTR(vkBindImageMemory) FNPTR(vkCreateImageView) FNPTR(vkDestroyImageView) FNPTR(vkCreateSampler) FNPTR(vkDestroySampler) FNPTR(vkCreateSemaphore) FNPTR(vkDestroySemaphore) FNPTR(vkCreateFence) FNPTR(vkDestroyFence) FNPTR(vkWaitForFences) FNPTR(vkCreateCommandPool) FNPTR(vkDestroyCommandPool) FNPTR(vkAllocateCommandBuffers) FNPTR(vkFreeCommandBuffers) FNPTR(vkBeginCommandBuffer) FNPTR(vkEndCommandBuffer) FNPTR(vkGetDeviceQueue) FNPTR(vkQueueSubmit) FNPTR(vkQueueWaitIdle) FNPTR(vkDeviceWaitIdle) FNPTR(vkCreateFramebuffer) FNPTR(vkDestroyFramebuffer) FNPTR(vkCreatePipelineCache) FNPTR(vkDestroyPipelineCache) FNPTR(vkCreatePipelineLayout) FNPTR(vkDestroyPipelineLayout) FNPTR(vkCreateGraphicsPipelines) FNPTR(vkCreateComputePipelines) FNPTR(vkDestroyPipeline) FNPTR(vkCreateDescriptorPool) FNPTR(vkDestroyDescriptorPool) FNPTR(vkCreateDescriptorSetLayout) FNPTR(vkDestroyDescriptorSetLayout) FNPTR(vkAllocateDescriptorSets) FNPTR(vkFreeDescriptorSets) FNPTR(vkUpdateDescriptorSets) FNPTR(vkCreateQueryPool) FNPTR(vkDestroyQueryPool) FNPTR(vkGetQueryPoolResults) FNPTR(vkCmdBeginQuery) FNPTR(vkCmdEndQuery) FNPTR(vkCmdResetQueryPool) FNPTR(vkCmdCopyQueryPoolResults) FNPTR(vkCmdPipelineBarrier) FNPTR(vkCmdBeginRenderPass) FNPTR(vkCmdEndRenderPass) FNPTR(vkCmdExecuteCommands) FNPTR(vkCmdCopyImage) FNPTR(vkCmdBlitImage) FNPTR(vkCmdCopyBufferToImage) FNPTR(vkCmdClearAttachments) FNPTR(vkCmdCopyBuffer) FNPTR(vkCmdBindDescriptorSets) FNPTR(vkCmdBindPipeline) FNPTR(vkCmdSetViewport) FNPTR(vkCmdSetScissor) FNPTR(vkCmdSetLineWidth) FNPTR(vkCmdSetDepthBias) FNPTR(vkCmdPushConstants) FNPTR(vkCmdBindIndexBuffer) FNPTR(vkCmdBindVertexBuffers) FNPTR(vkCmdDraw) FNPTR(vkCmdDrawIndexed) FNPTR(vkCmdDrawIndirect) FNPTR(vkCmdDrawIndexedIndirect) FNPTR(vkCmdDispatch) FNPTR(vkCmdClearColorImage) FNPTR(vkCmdClearDepthStencilImage) // "VK_EXT_debug_marker"-extension FNPTR(vkDebugMarkerSetObjectTagEXT) FNPTR(vkDebugMarkerSetObjectNameEXT) FNPTR(vkCmdDebugMarkerBeginEXT) FNPTR(vkCmdDebugMarkerEndEXT) FNPTR(vkCmdDebugMarkerInsertEXT) // "VK_KHR_swapchain"-extension FNPTR(vkCreateSwapchainKHR) FNPTR(vkDestroySwapchainKHR) FNPTR(vkGetSwapchainImagesKHR) FNPTR(vkAcquireNextImageKHR) FNPTR(vkQueuePresentKHR) //[-------------------------------------------------------] //[ Implementation ] //[-------------------------------------------------------] #include "VulkanRenderer/VulkanRuntimeLinking.inl"
#include "Chien.h" //pour créer un chien, on a besoin de savoir son age et son nom : //on appelle le constructeur de Animal avec les paramètres adéquat : Chien::Chien(int age,string nom):Animal("ouafouaf",age,15) { this->nom=nom; cout<<"Le chien a ete cree"<<endl; } //un chien ne se déplace pas de la même façon que tout les animaux... //on doit redéfinir cette fonction : void Chien::seDeplace(int c) { //on teste si on est encore vivant : //on peut faire ça parce que age et ageMaximum sont en protected... if(this->age>=this->ageMaximum){ cout<<"l'oiseau est mort... il ne bouge donc plus..."<<endl; }else cout<<"Le chien marche de "<<c<<" metres"<<endl; }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * 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" #if defined(NEW_PI_MH) #include "platforms/mac/pi/MacOpTimer.h" #include "platforms/mac/util/URestoreQDState.h" #include "platforms/mac/util/UTempResFileChange.h" UINT32 MacOpTimer::timer_id = 0; EventLoopTimerUPP MacOpTimer::timerUPP = NULL; extern ThreadID gMainThreadID; extern EventLoopRef gMainEventLoop; extern Boolean g_isInside; MacOpTimer::MacOpTimer() { m_listener = 0; m_id = 0; m_interval = 0; m_startTime = 0; m_timerRef = 0; if (!timerUPP) { timerUPP = NewEventLoopTimerUPP(sOpTimerEvent); } } MacOpTimer::~MacOpTimer() { if (m_timerRef) { EventLoopTimerRef timer = m_timerRef; m_timerRef = NULL; ::RemoveEventLoopTimer(timer); } } OP_STATUS MacOpTimer::Init() { m_id = ++timer_id; return OpStatus::OK; } void MacOpTimer::opTimerEvent(EventLoopTimerRef timerRef) { EventLoopTimerRef timer = m_timerRef; OpTimerListener *listener = m_listener; if (timer) { if (listener) { listener->OnTimeOut(this); } } } pascal void MacOpTimer::sOpTimerEvent(EventLoopTimerRef timerRef, void *opTimer) { ThreadID currThread = 0; GetCurrentThread(&currThread); if (gMainThreadID == currThread) { URestoreQDState savedState; UTempResFileChange resFile; MacOpTimer *macOpTimer = (MacOpTimer *) opTimer; macOpTimer->opTimerEvent(timerRef); } } void MacOpTimer::Start(UINT32 ms) { UnsignedWide ticks; Microseconds(&ticks); long long msecs = ticks.hi; msecs <<= 32; msecs |= ticks.lo; m_startTime = msecs / 1000; m_interval = ms; EventTimerInterval fireDelay = ms * kEventDurationMillisecond; if (m_timerRef) { SetEventLoopTimerNextFireTime(m_timerRef,fireDelay); } else { InstallEventLoopTimer(gMainEventLoop,//GetMainEventLoop(), fireDelay, kEventDurationNoWait, timerUPP, this, &m_timerRef); } } UINT32 MacOpTimer::Stop() { EventLoopTimerRef timer = m_timerRef; m_timerRef = NULL; if (timer) ::RemoveEventLoopTimer(timer); UnsignedWide ticks; Microseconds(&ticks); long long msecs = ticks.hi; msecs <<= 32; msecs |= ticks.lo; UINT32 endTime = msecs / 1000; UINT32 elapsed = endTime - m_startTime; if( (elapsed < m_interval) && (elapsed >= 0) ) return (UINT32)(m_interval - elapsed); else return 0; } void MacOpTimer::SetTimerListener(OpTimerListener *listener) { m_listener = listener; } UINT32 MacOpTimer::GetId() { return m_id; } #endif
#include <iostream> typedef long long ll; const int MOD = 1e9 + 7; ll n, x, N[1000002], ans; int main() { std::cin.sync_with_stdio(false); std::cin.tie(NULL); std::cin >> n >> x; for(int i = 0; i <= n; i++) { ll A, t; std::cin >> A >> t; N[t] = A; } for(int i = n + 1; i > 0; i--) { ans = x * ans + N[i - 1]; ans %= MOD; } std::cout << ans << '\n'; return 0; }
#pragma once #include "CoreMinimal.h" #include "Engine/GameInstance.h" #include "Engine/AssetManager.h" #include "Engine/StreamableManager.h" #include "Single/ManagerClass/ManagerClass.h" #include "RPGGameInst.generated.h" #ifndef GAME_INST #define GAME_INST #define GetGameInst(worldContextObj) (Cast<URPGGameInst>(worldContextObj->GetGameInstance())) #endif UCLASS() class ARPG_API URPGGameInst final : public UGameInstance { GENERATED_BODY() private : // 등록한 매니저 클래스 인스턴스를 저장합니다. TMap<FString, UManagerClass*> ManagerClasses; private : // ManagerClass 를 등록합니다. void RegisterManagerClass(TSubclassOf<UManagerClass> managerClass); public : virtual void Init() override; virtual void Shutdown() override; // 등록한 ManagerClass 를 얻습니다. template<typename ManagerClassType> FORCEINLINE ManagerClassType* GetManagerClass() { return Cast<ManagerClassType>(ManagerClasses[ManagerClassType::StaticClass()->GetName()]); } template<> FORCEINLINE FStreamableManager* GetManagerClass<FStreamableManager>() { return &UAssetManager::GetStreamableManager(); } };
/**************************************************************************** Copyright (C) 2002-2014 Gilles Debunne. All rights reserved. This file is part of the QGLViewer library version 2.6.3. http://www.libqglviewer.com - contact@libqglviewer.com This file may be used under the terms of the GNU General Public License versions 2.0 or 3.0 as published by the Free Software Foundation and appearing in the LICENSE file included in the packaging of this file. In addition, as a special exception, Gilles Debunne gives you certain additional rights, described in the file GPL_EXCEPTION in this package. libQGLViewer uses dual licensing. Commercial/proprietary software must purchase a libQGLViewer Commercial License. This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. *****************************************************************************/ #ifndef QGLVIEWER_QGLVIEWER_H #define QGLVIEWER_QGLVIEWER_H #include "camera.h" #include <QMap> #include <QClipboard> #include <QTime> class QTabWidget; namespace qglviewer { class MouseGrabber; class ManipulatedFrame; class ManipulatedCameraFrame; } /*! \brief A versatile 3D OpenGL viewer based on QGLWidget. \class QGLViewer qglviewer.h QGLViewer/qglviewer.h It features many classical viewer functionalities, such as a camera trackball, manipulated objects, snapshot saving and much <a href="../features.html">more</a>. Its main goal is to ease the development of new 3D applications. New users should read the <a href="../introduction.html">introduction page</a> to get familiar with important notions such as sceneRadius(), sceneCenter() and the world coordinate system. Try the numerous simple <a href="../examples/index.html">examples</a> to discover the possibilities and understand how it works. <h3>Usage</h3> To use a QGLViewer, derive you viewer class from the QGLViewer and overload its draw() virtual method. See the <a href="../examples/simpleViewer.html">simpleViewer example</a> for an illustration. An other option is to connect your drawing methods to the signals emitted by the QGLViewer (Qt's callback mechanism). See the <a href="../examples/callback.html">callback example</a> for a complete implementation. \nosubgrouping */ class QGLVIEWER_EXPORT QGLViewer : public QGLWidget { Q_OBJECT public: // Complete implementation is provided so that the constructor is defined with QT3_SUPPORT when .h is included. // (Would not be available otherwise since lib is compiled without QT3_SUPPORT). #ifdef QT3_SUPPORT explicit QGLViewer(QWidget* parent=NULL, const char* name=0, const QGLWidget* shareWidget=0, Qt::WindowFlags flags=0) : QGLWidget(parent, name, shareWidget, flags) { defaultConstructor(); } explicit QGLViewer(const QGLFormat& format, QWidget* parent=0, const char* name=0, const QGLWidget* shareWidget=0,Qt::WindowFlags flags=0) : QGLWidget(format, parent, name, shareWidget, flags) { defaultConstructor(); } QGLViewer(QGLContext* context, QWidget* parent, const char* name=0, const QGLWidget* shareWidget=0, Qt::WindowFlags flags=0) : QGLWidget(context, parent, name, shareWidget, flags) { defaultConstructor(); } #else explicit QGLViewer(QWidget* parent=0, const QGLWidget* shareWidget=0, Qt::WindowFlags flags=0); explicit QGLViewer(QGLContext *context, QWidget* parent=0, const QGLWidget* shareWidget=0, Qt::WindowFlags flags=0); explicit QGLViewer(const QGLFormat& format, QWidget* parent=0, const QGLWidget* shareWidget=0, Qt::WindowFlags flags=0); #endif virtual ~QGLViewer(); /*! @name Display of visual hints */ //@{ public: /*! Returns \c true if the world axis is drawn by the viewer. Set by setAxisIsDrawn() or toggleAxisIsDrawn(). Default value is \c false. */ bool axisIsDrawn() const { return axisIsDrawn_; } /*! Returns \c true if a XY grid is drawn by the viewer. Set by setGridIsDrawn() or toggleGridIsDrawn(). Default value is \c false. */ bool gridIsDrawn() const { return gridIsDrawn_; } /*! Returns \c true if the viewer displays the current frame rate (Frames Per Second). Use QApplication::setFont() to define the display font (see drawText()). Set by setFPSIsDisplayed() or toggleFPSIsDisplayed(). Use currentFPS() to get the current FPS. Default value is \c false. */ bool FPSIsDisplayed() const { return FPSIsDisplayed_; } /*! Returns \c true if text display (see drawText()) is enabled. Set by setTextIsEnabled() or toggleTextIsEnabled(). This feature conveniently removes all the possibly displayed text, cleaning display. Default value is \c true. */ bool textIsEnabled() const { return textIsEnabled_; } /*! Returns \c true if the camera() is being edited in the viewer. Set by setCameraIsEdited() or toggleCameraIsEdited(). Default value is \p false. The current implementation is limited: the defined camera() paths (see qglviewer::Camera::keyFrameInterpolator()) are simply displayed using qglviewer::Camera::drawAllPaths(). Actual camera and path edition will be implemented in the future. */ bool cameraIsEdited() const { return cameraIsEdited_; } public Q_SLOTS: /*! Sets the state of axisIsDrawn(). Emits the axisIsDrawnChanged() signal. See also toggleAxisIsDrawn(). */ void setAxisIsDrawn(bool draw=true) { axisIsDrawn_ = draw; Q_EMIT axisIsDrawnChanged(draw); update(); } /*! Sets the state of gridIsDrawn(). Emits the gridIsDrawnChanged() signal. See also toggleGridIsDrawn(). */ void setGridIsDrawn(bool draw=true) { gridIsDrawn_ = draw; Q_EMIT gridIsDrawnChanged(draw); update(); } /*! Sets the state of FPSIsDisplayed(). Emits the FPSIsDisplayedChanged() signal. See also toggleFPSIsDisplayed(). */ void setFPSIsDisplayed(bool display=true) { FPSIsDisplayed_ = display; Q_EMIT FPSIsDisplayedChanged(display); update(); } /*! Sets the state of textIsEnabled(). Emits the textIsEnabledChanged() signal. See also toggleTextIsEnabled(). */ void setTextIsEnabled(bool enable=true) { textIsEnabled_ = enable; Q_EMIT textIsEnabledChanged(enable); update(); } void setCameraIsEdited(bool edit=true); /*! Toggles the state of axisIsDrawn(). See also setAxisIsDrawn(). */ void toggleAxisIsDrawn() { setAxisIsDrawn(!axisIsDrawn()); } /*! Toggles the state of gridIsDrawn(). See also setGridIsDrawn(). */ void toggleGridIsDrawn() { setGridIsDrawn(!gridIsDrawn()); } /*! Toggles the state of FPSIsDisplayed(). See also setFPSIsDisplayed(). */ void toggleFPSIsDisplayed() { setFPSIsDisplayed(!FPSIsDisplayed()); } /*! Toggles the state of textIsEnabled(). See also setTextIsEnabled(). */ void toggleTextIsEnabled() { setTextIsEnabled(!textIsEnabled()); } /*! Toggles the state of cameraIsEdited(). See also setCameraIsEdited(). */ void toggleCameraIsEdited() { setCameraIsEdited(!cameraIsEdited()); } //@} /*! @name Viewer's colors */ //@{ public: /*! Returns the background color of the viewer. This method is provided for convenience since the background color is an OpenGL state variable set with \c glClearColor(). However, this internal representation has the advantage that it is saved (resp. restored) with saveStateToFile() (resp. restoreStateFromFile()). Use setBackgroundColor() to define and activate a background color. \attention Each QColor component is an integer ranging from 0 to 255. This differs from the qreal values used by \c glClearColor() which are in the 0.0-1.0 range. Default value is (51, 51, 51) (dark gray). You may have to change foregroundColor() accordingly. \attention This method does not return the current OpenGL clear color as \c glGet() does. Instead, it returns the QGLViewer internal variable. If you directly use \c glClearColor() or \c qglClearColor() instead of setBackgroundColor(), the two results will differ. */ QColor backgroundColor() const { return backgroundColor_; } /*! Returns the foreground color used by the viewer. This color is used when FPSIsDisplayed(), gridIsDrawn(), to display the camera paths when the cameraIsEdited(). \attention Each QColor component is an integer in the range 0-255. This differs from the qreal values used by \c glColor3f() which are in the range 0-1. Default value is (180, 180, 180) (light gray). Use \c qglColor(foregroundColor()) to set the current OpenGL color to the foregroundColor(). See also backgroundColor(). */ QColor foregroundColor() const { return foregroundColor_; } public Q_SLOTS: /*! Sets the backgroundColor() of the viewer and calls \c qglClearColor(). See also setForegroundColor(). */ void setBackgroundColor(const QColor& color) { backgroundColor_=color; qglClearColor(color); } /*! Sets the foregroundColor() of the viewer, used to draw visual hints. See also setBackgroundColor(). */ void setForegroundColor(const QColor& color) { foregroundColor_ = color; } //@} /*! @name Scene dimensions */ //@{ public: /*! Returns the scene radius. The entire displayed scene should be included in a sphere of radius sceneRadius(), centered on sceneCenter(). This approximate value is used by the camera() to set qglviewer::Camera::zNear() and qglviewer::Camera::zFar(). It is also used to showEntireScene() or to scale the world axis display.. Default value is 1.0. This method is equivalent to camera()->sceneRadius(). See setSceneRadius(). */ qreal sceneRadius() const { return camera()->sceneRadius(); } /*! Returns the scene center, defined in world coordinates. See sceneRadius() for details. Default value is (0,0,0). Simply a wrapper for camera()->sceneCenter(). Set using setSceneCenter(). Do not mismatch this value (that only depends on the scene) with the qglviewer::Camera::pivotPoint(). */ qglviewer::Vec sceneCenter() const { return camera()->sceneCenter(); } public Q_SLOTS: /*! Sets the sceneRadius(). The camera() qglviewer::Camera::flySpeed() is set to 1% of this value by this method. Simple wrapper around camera()->setSceneRadius(). */ virtual void setSceneRadius(qreal radius) { camera()->setSceneRadius(radius); } /*! Sets the sceneCenter(), defined in world coordinates. \attention The qglviewer::Camera::pivotPoint() is set to the sceneCenter() value by this method. */ virtual void setSceneCenter(const qglviewer::Vec& center) { camera()->setSceneCenter(center); } /*! Convenient way to call setSceneCenter() and setSceneRadius() from a (world axis aligned) bounding box of the scene. This is equivalent to: \code setSceneCenter((min+max) / 2.0); setSceneRadius((max-min).norm() / 2.0); \endcode */ void setSceneBoundingBox(const qglviewer::Vec& min, const qglviewer::Vec& max) { camera()->setSceneBoundingBox(min,max); } /*! Moves the camera so that the entire scene is visible. Simple wrapper around qglviewer::Camera::showEntireScene(). */ void showEntireScene() { camera()->showEntireScene(); update(); } //@} /*! @name Associated objects */ //@{ public: /*! Returns the associated qglviewer::Camera, never \c NULL. */ qglviewer::Camera* camera() const { return camera_; } /*! Returns the viewer's qglviewer::ManipulatedFrame. This qglviewer::ManipulatedFrame can be moved with the mouse when the associated mouse bindings are used (default is when pressing the \c Control key with any mouse button). Use setMouseBinding() to define new bindings. See the <a href="../examples/manipulatedFrame.html">manipulatedFrame example</a> for a complete implementation. Default value is \c NULL, meaning that no qglviewer::ManipulatedFrame is set. */ qglviewer::ManipulatedFrame* manipulatedFrame() const { return manipulatedFrame_; } public Q_SLOTS: void setCamera(qglviewer::Camera* const camera); void setManipulatedFrame(qglviewer::ManipulatedFrame* frame); //@} /*! @name Mouse grabbers */ //@{ public: /*! Returns the current qglviewer::MouseGrabber, or \c NULL if no qglviewer::MouseGrabber currently grabs mouse events. When qglviewer::MouseGrabber::grabsMouse(), the different mouse events are sent to the mouseGrabber() instead of their usual targets (camera() or manipulatedFrame()). See the qglviewer::MouseGrabber documentation for details on MouseGrabber's mode of operation. In order to use MouseGrabbers, you need to enable mouse tracking (so that mouseMoveEvent() is called even when no mouse button is pressed). Add this line in init() or in your viewer constructor: \code setMouseTracking(true); \endcode Note that mouse tracking is disabled by default. Use QWidget::hasMouseTracking() to retrieve current state. */ qglviewer::MouseGrabber* mouseGrabber() const { return mouseGrabber_; } void setMouseGrabberIsEnabled(const qglviewer::MouseGrabber* const mouseGrabber, bool enabled=true); /*! Returns \c true if \p mouseGrabber is enabled. Default value is \c true for all MouseGrabbers. When set to \c false using setMouseGrabberIsEnabled(), the specified \p mouseGrabber will never become the mouseGrabber() of this QGLViewer. This is useful when you use several viewers: some MouseGrabbers may only have a meaning for some specific viewers and should not be selectable in others. You can also use qglviewer::MouseGrabber::removeFromMouseGrabberPool() to completely disable a MouseGrabber in all the QGLViewers. */ bool mouseGrabberIsEnabled(const qglviewer::MouseGrabber* const mouseGrabber) { return !disabledMouseGrabbers_.contains(reinterpret_cast<size_t>(mouseGrabber)); } public Q_SLOTS: void setMouseGrabber(qglviewer::MouseGrabber* mouseGrabber); //@} /*! @name State of the viewer */ //@{ public: /*! Returns the aspect ratio of the viewer's widget (width() / height()). */ qreal aspectRatio() const { return width() / static_cast<qreal>(height()); } /*! Returns the current averaged viewer frame rate. This value is computed and averaged over 20 successive frames. It only changes every 20 draw() (previously computed value is otherwise returned). This method is useful for true real-time applications that may adapt their computational load accordingly in order to maintain a given frequency. This value is meaningful only when draw() is regularly called, either using a \c QTimer, when animationIsStarted() or when the camera is manipulated with the mouse. */ qreal currentFPS() { return f_p_s_; } /*! Returns \c true if the viewer is in fullScreen mode. Default value is \c false. Set by setFullScreen() or toggleFullScreen(). Note that if the QGLViewer is embedded in an other QWidget, it returns \c true when the top level widget is in full screen mode. */ bool isFullScreen() const { return fullScreen_; } /*! Returns \c true if the viewer displays in stereo. The QGLViewer object must be created with a stereo format to handle stereovision: \code QGLFormat format; format.setStereoDisplay( TRUE ); QGLViewer viewer(format); \endcode The hardware needs to support stereo display. Try the <a href="../examples/stereoViewer.html">stereoViewer example</a> to check. Set by setStereoDisplay() or toggleStereoDisplay(). Default value is \c false. Stereo is performed using the Parallel axis asymmetric frustum perspective projection method. See Camera::loadProjectionMatrixStereo() and Camera::loadModelViewMatrixStereo(). The stereo parameters are defined by the camera(). See qglviewer::Camera::setIODistance(), qglviewer::Camera::setPhysicalScreenWidth() and qglviewer::Camera::setFocusDistance(). */ bool displaysInStereo() const { return stereo_; } /*! Returns the recommended size for the QGLViewer. Default value is 600x400 pixels. */ virtual QSize sizeHint() const { return QSize(600, 400); } public Q_SLOTS: void setFullScreen(bool fullScreen=true); void setStereoDisplay(bool stereo=true); /*! Toggles the state of isFullScreen(). See also setFullScreen(). */ void toggleFullScreen() { setFullScreen(!isFullScreen()); } /*! Toggles the state of displaysInStereo(). See setStereoDisplay(). */ void toggleStereoDisplay() { setStereoDisplay(!stereo_); } void toggleCameraMode(); private: bool cameraIsInRotateMode() const; //@} /*! @name Display methods */ //@{ public: static void drawArrow(qreal length=1.0, qreal radius=-1.0, int nbSubdivisions=12); static void drawArrow(const qglviewer::Vec& from, const qglviewer::Vec& to, qreal radius=-1.0, int nbSubdivisions=12); static void drawAxis(qreal length=1.0); static void drawGrid(qreal size=1.0, int nbSubdivisions=10); virtual void startScreenCoordinatesSystem(bool upward=false) const; virtual void stopScreenCoordinatesSystem() const; void drawText(int x, int y, const QString& text, const QFont& fnt=QFont()); void displayMessage(const QString& message, int delay=2000); // void draw3DText(const qglviewer::Vec& pos, const qglviewer::Vec& normal, const QString& string, GLfloat height=0.1); protected: virtual void drawLight(GLenum light, qreal scale = 1.0) const; private: void displayFPS(); /*! Vectorial rendering callback method. */ void drawVectorial() { paintGL(); } #ifndef DOXYGEN friend void drawVectorial(void* param); #endif //@} #ifdef DOXYGEN /*! @name Useful inherited methods */ //@{ public: /*! Returns viewer's widget width (in pixels). See QGLWidget documentation. */ int width() const; /*! Returns viewer's widget height (in pixels). See QGLWidget documentation. */ int height() const; /*! Updates the display. Do not call draw() directly, use this method instead. See QGLWidget documentation. */ virtual void updateGL(); /*! Converts \p image into the unnamed format expected by OpenGL methods such as glTexImage2D(). See QGLWidget documentation. */ static QImage convertToGLFormat(const QImage & image); /*! Calls \c glColor3. See QGLWidget::qglColor(). */ void qglColor(const QColor& color) const; /*! Calls \c glClearColor. See QGLWidget documentation. */ void qglClearColor(const QColor& color) const; /*! Returns \c true if the widget has a valid GL rendering context. See QGLWidget documentation. */ bool isValid() const; /*! Returns \c true if display list sharing with another QGLWidget was requested in the constructor. See QGLWidget documentation. */ bool isSharing() const; /*! Makes this widget's rendering context the current OpenGL rendering context. Useful with several viewers. See QGLWidget documentation. */ virtual void makeCurrent(); /*! Returns \c true if mouseMoveEvent() is called even when no mouse button is pressed. You need to setMouseTracking() to \c true in order to use MouseGrabber (see mouseGrabber()). See details in the QWidget documentation. */ bool hasMouseTracking () const; public Q_SLOTS: /*! Resizes the widget to size \p width by \p height pixels. See also width() and height(). */ virtual void resize(int width, int height); /*! Sets the hasMouseTracking() value. */ virtual void setMouseTracking(bool enable); protected: /*! Returns \c true when buffers are automatically swapped (default). See details in the QGLWidget documentation. */ bool autoBufferSwap() const; protected Q_SLOTS: /*! Sets the autoBufferSwap() value. */ void setAutoBufferSwap(bool on); //@} #endif /*! @name Snapshots */ //@{ public: /*! Returns the snapshot file name used by saveSnapshot(). This value is used in \p automatic mode (see saveSnapshot()). A dialog is otherwise popped-up to set it. You can also directly provide a file name using saveSnapshot(const QString&, bool). If the file name is relative, the current working directory at the moment of the method call is used. Set using setSnapshotFileName(). */ const QString& snapshotFileName() const { return snapshotFileName_; } #ifndef DOXYGEN const QString& snapshotFilename() const; #endif /*! Returns the snapshot file format used by saveSnapshot(). This value is used when saveSnapshot() is passed the \p automatic flag. It is defined using a saveAs pop-up dialog otherwise. The available formats are those handled by Qt. Classical values are \c "JPEG", \c "PNG", \c "PPM", \c "BMP". Use the following code to get the actual list: \code QList<QByteArray> formatList = QImageReader::supportedImageFormats(); // or with Qt version 2 or 3: QStringList formatList = QImage::outputFormatList(); \endcode If the library was compiled with the vectorial rendering option (default), three additional vectorial formats are available: \c "EPS", \c "PS" and \c "XFIG". \c "SVG" and \c "PDF" formats should soon be available. The <a href="http://artis.imag.fr/Software/VRender">VRender library</a> was created by Cyril Soler. Note that the VRender library has some limitations: vertex shader effects are not reproduced and \c PASS_THROUGH tokens are not handled so one can not change point and line size in the middle of a drawing. Default value is the first supported among "JPEG, PNG, EPS, PS, PPM, BMP", in that order. This value is set using setSnapshotFormat() or with openSnapshotFormatDialog(). \attention No verification is performed on the provided format validity. The next call to saveSnapshot() may fail if the format string is not supported. */ const QString& snapshotFormat() const { return snapshotFormat_; } /*! Returns the value of the counter used to name snapshots in saveSnapshot() when \p automatic is \c true. Set using setSnapshotCounter(). Default value is 0, and it is incremented after each \p automatic snapshot. See saveSnapshot() for details. */ int snapshotCounter() const { return snapshotCounter_; } /*! Defines the image quality of the snapshots produced with saveSnapshot(). Values must be in the range -1..100. Use 0 for lowest quality and 100 for highest quality (and larger files). -1 means use Qt default quality. Default value is 95. Set using setSnapshotQuality(). See also the QImage::save() documentation. \note This value has no impact on the images produced in vectorial format. */ int snapshotQuality() { return snapshotQuality_; } // Qt 2.3 does not support qreal default value parameters in slots. // Remove "Q_SLOTS" from the following line to compile with Qt 2.3 public Q_SLOTS: void saveSnapshot(bool automatic=true, bool overwrite=false); public Q_SLOTS: void saveSnapshot(const QString& fileName, bool overwrite=false); void setSnapshotFileName(const QString& name); /*! Sets the snapshotFormat(). */ void setSnapshotFormat(const QString& format) { snapshotFormat_ = format; } /*! Sets the snapshotCounter(). */ void setSnapshotCounter(int counter) { snapshotCounter_ = counter; } /*! Sets the snapshotQuality(). */ void setSnapshotQuality(int quality) { snapshotQuality_ = quality; } bool openSnapshotFormatDialog(); void snapshotToClipboard(); private: bool saveImageSnapshot(const QString& fileName); #ifndef DOXYGEN /* This class is used internally for screenshot that require tiling (image size size different from window size). Only in that case, is the private tileRegion_ pointer non null. It then contains the current tiled region, which is used by startScreenCoordinatesSystem to adapt the coordinate system. Not using it would result in a tiled drawing of the parts that use startScreenCoordinatesSystem. Also used by scaledFont for same purposes. */ class TileRegion { public : qreal xMin, yMin, xMax, yMax, textScale; }; #endif public: /*! Return a possibly scaled version of \p font, used for snapshot rendering. From a user's point of view, this method simply returns \p font and can be used transparently. However when internally rendering a screen snapshot using saveSnapshot(), it returns a scaled version of the font, so that the size of the rendered text on the snapshot is identical to what is displayed on screen, even if the snapshot uses image tiling to create an image of dimensions different from those of the current window. This scaled version will only be used when saveSnapshot() calls your draw() method to generate the snapshot. All your calls to QGLWidget::renderText() function hence should use this method. \code renderText(x, y, z, "My Text", scaledFont(QFont())); \endcode will guarantee that this text will be properly displayed on arbitrary sized snapshots. Note that this method is not needed if you use drawText() which already calls it internally. */ QFont scaledFont(const QFont& font) const { if (tileRegion_ == NULL) return font; else { QFont f(font); if (f.pixelSize() == -1) f.setPointSizeF(f.pointSizeF() * tileRegion_->textScale); else f.setPixelSize(int(f.pixelSize() * tileRegion_->textScale)); return f; } } //@} /*! @name Buffer to texture */ //@{ public: GLuint bufferTextureId() const; /*! Returns the texture coordinate corresponding to the u extremum of the bufferTexture. The bufferTexture is created by copyBufferToTexture(). The texture size has powers of two dimensions and the buffer image hence only fills a part of it. This value corresponds to the u coordinate of the extremum right side of the buffer image. Use (0,0) to (bufferTextureMaxU(), bufferTextureMaxV()) texture coordinates to map the entire texture on a quad. */ qreal bufferTextureMaxU() const { return bufferTextureMaxU_; } /*! Same as bufferTextureMaxU(), but for the v texture coordinate. */ qreal bufferTextureMaxV() const { return bufferTextureMaxV_; } public Q_SLOTS: void copyBufferToTexture(GLint internalFormat, GLenum format=GL_NONE); //@} /*! @name Animation */ //@{ public: /*! Return \c true when the animation loop is started. During animation, an infinite loop calls animate() and draw() and then waits for animationPeriod() milliseconds before calling animate() and draw() again. And again. Use startAnimation(), stopAnimation() or toggleAnimation() to change this value. See the <a href="../examples/animation.html">animation example</a> for illustration. */ bool animationIsStarted() const { return animationStarted_; } /*! The animation loop period, in milliseconds. When animationIsStarted(), this is delay waited after draw() to call animate() and draw() again. Default value is 40 milliseconds (25 Hz). This value will define the currentFPS() when animationIsStarted() (provided that your animate() and draw() methods are fast enough). If you want to know the maximum possible frame rate of your machine on a given scene, setAnimationPeriod() to \c 0, and startAnimation() (keyboard shortcut is \c Enter). The display will then be updated as often as possible, and the frame rate will be meaningful. \note This value is taken into account only the next time you call startAnimation(). If animationIsStarted(), you should stopAnimation() first. */ int animationPeriod() const { return animationPeriod_; } public Q_SLOTS: /*! Sets the animationPeriod(), in milliseconds. */ void setAnimationPeriod(int period) { animationPeriod_ = period; } virtual void startAnimation(); virtual void stopAnimation(); /*! Scene animation method. When animationIsStarted(), this method is in charge of the scene update before each draw(). Overload it to define how your scene evolves over time. The time should either be regularly incremented in this method (frame-rate independent animation) or computed from actual time (for instance using QTime::elapsed()) for real-time animations. Note that KeyFrameInterpolator (which regularly updates a Frame) does not use this method to animate a Frame, but rather rely on a QTimer signal-slot mechanism. See the <a href="../examples/animation.html">animation example</a> for an illustration. */ virtual void animate() { Q_EMIT animateNeeded(); } /*! Calls startAnimation() or stopAnimation(), depending on animationIsStarted(). */ void toggleAnimation() { if (animationIsStarted()) stopAnimation(); else startAnimation(); } //@} public: Q_SIGNALS: /*! Signal emitted by the default init() method. Connect this signal to the methods that need to be called to initialize your viewer or overload init(). */ void viewerInitialized(); /*! Signal emitted by the default draw() method. Connect this signal to your main drawing method or overload draw(). See the <a href="../examples/callback.html">callback example</a> for an illustration. */ void drawNeeded(); /*! Signal emitted at the end of the QGLViewer::paintGL() method, when frame is drawn. Can be used to notify an image grabbing process that the image is ready. A typical example is to connect this signal to the saveSnapshot() method, so that a (numbered) snapshot is generated after each new display, in order to create a movie: \code connect(viewer, SIGNAL(drawFinished(bool)), SLOT(saveSnapshot(bool))); \endcode The \p automatic bool variable is always \c true and has been added so that the signal can be connected to saveSnapshot() with an \c automatic value set to \c true. */ void drawFinished(bool automatic); /*! Signal emitted by the default animate() method. Connect this signal to your scene animation method or overload animate(). */ void animateNeeded(); /*! Signal emitted by the default QGLViewer::help() method. Connect this signal to your own help method or overload help(). */ void helpRequired(); /*! This signal is emitted whenever axisIsDrawn() changes value. */ void axisIsDrawnChanged(bool drawn); /*! This signal is emitted whenever gridIsDrawn() changes value. */ void gridIsDrawnChanged(bool drawn); /*! This signal is emitted whenever FPSIsDisplayed() changes value. */ void FPSIsDisplayedChanged(bool displayed); /*! This signal is emitted whenever textIsEnabled() changes value. */ void textIsEnabledChanged(bool enabled); /*! This signal is emitted whenever cameraIsEdited() changes value.. */ void cameraIsEditedChanged(bool edited); /*! This signal is emitted whenever displaysInStereo() changes value. */ void stereoChanged(bool on); /*! Signal emitted by select(). Connect this signal to your selection method or overload select(), or more probably simply drawWithNames(). */ void pointSelected(const QMouseEvent* e); /*! Signal emitted by setMouseGrabber() when the mouseGrabber() is changed. \p mouseGrabber is a pointer to the new MouseGrabber. Note that this signal is emitted with a \c NULL parameter each time a MouseGrabber stops grabbing mouse. */ void mouseGrabberChanged(qglviewer::MouseGrabber* mouseGrabber); /*! @name Help window */ //@{ public: /*! Returns the QString displayed in the help() window main tab. Overload this method to define your own help string, which should shortly describe your application and explain how it works. Rich-text (HTML) tags can be used (see QStyleSheet() documentation for available tags): \code QString myViewer::helpString() const { QString text("<h2>M y V i e w e r</h2>"); text += "Displays a <b>Scene</b> using OpenGL. Move the camera using the mouse."; return text; } \endcode See also mouseString() and keyboardString(). */ virtual QString helpString() const { return tr("No help available."); } virtual QString mouseString() const; virtual QString keyboardString() const; #ifndef DOXYGEN /*! This method is deprecated, use mouseString() instead. */ virtual QString mouseBindingsString () const { return mouseString(); } /*! This method is deprecated, use keyboardString() instead. */ virtual QString shortcutBindingsString () const { return keyboardString(); } #endif public Q_SLOTS: virtual void help(); virtual void aboutQGLViewer(); protected: /*! Returns a pointer to the help widget. Use this only if you want to directly modify the help widget. Otherwise use helpString(), setKeyDescription() and setMouseBindingDescription() to customize the text displayed in the help window tabs. */ QTabWidget* helpWidget() { return helpWidget_; } //@} /*! @name Drawing methods */ //@{ protected: virtual void resizeGL(int width, int height); virtual void initializeGL(); /*! Initializes the viewer OpenGL context. This method is called before the first drawing and should be overloaded to initialize some of the OpenGL flags. The default implementation is empty. See initializeGL(). Typical usage include camera() initialization (showEntireScene()), previous viewer state restoration (restoreStateFromFile()), OpenGL state modification and display list creation. Note that initializeGL() modifies the standard OpenGL context. These values can be restored back in this method. \attention You should not call updateGL() (or any method that calls it) in this method, as it will result in an infinite loop. The different QGLViewer set methods (setAxisIsDrawn(), setFPSIsDisplayed()...) are protected against this problem and can safely be called. \note All the OpenGL specific initializations must be done in this method: the OpenGL context is not yet available in your viewer constructor. */ virtual void init() { Q_EMIT viewerInitialized(); } virtual void paintGL(); virtual void preDraw(); virtual void preDrawStereo(bool leftBuffer=true); /*! The core method of the viewer, that draws the scene. If you build a class that inherits from QGLViewer, this is the method you want to overload. See the <a href="../examples/simpleViewer.html">simpleViewer example</a> for an illustration. The camera modelView matrix set in preDraw() converts from the world to the camera coordinate systems. Vertices given in draw() can then be considered as being given in the world coordinate system. The camera is moved in this world using the mouse. This representation is much more intuitive than the default camera-centric OpenGL standard. \attention The \c GL_PROJECTION matrix should not be modified by this method, to correctly display visual hints (axis, grid, FPS...) in postDraw(). Use push/pop or call camera()->loadProjectionMatrix() at the end of draw() if you need to change the projection matrix (unlikely). On the other hand, the \c GL_MODELVIEW matrix can be modified and left in a arbitrary state. */ virtual void draw() {} virtual void fastDraw(); virtual void postDraw(); //@} /*! @name Mouse, keyboard and event handlers */ //@{ protected: virtual void mousePressEvent(QMouseEvent *); virtual void mouseMoveEvent(QMouseEvent *); virtual void mouseReleaseEvent(QMouseEvent *); virtual void mouseDoubleClickEvent(QMouseEvent *); virtual void wheelEvent(QWheelEvent *); virtual void keyPressEvent(QKeyEvent *); virtual void keyReleaseEvent(QKeyEvent *); virtual void timerEvent(QTimerEvent *); virtual void closeEvent(QCloseEvent *); //@} /*! @name Object selection */ //@{ public: /*! Returns the name (an integer value) of the entity that was last selected by select(). This value is set by endSelection(). See the select() documentation for details. As a convention, this method returns -1 if the selectBuffer() was empty, meaning that no object was selected. Return value is -1 before the first call to select(). This value is modified using setSelectedName(). */ int selectedName() const { return selectedObjectId_; } /*! Returns the selectBuffer() size. See the select() documentation for details. Use setSelectBufferSize() to change this value. Default value is 4000 (i.e. 1000 objects in selection region, since each object pushes 4 values). This size should be over estimated to prevent a buffer overflow when many objects are drawn under the mouse cursor. */ int selectBufferSize() const { return selectBufferSize_; } /*! Returns the width (in pixels) of a selection frustum, centered on the mouse cursor, that is used to select objects. The height of the selection frustum is defined by selectRegionHeight(). The objects that will be drawn in this region by drawWithNames() will be recorded in the selectBuffer(). endSelection() then analyzes this buffer and setSelectedName() to the name of the closest object. See the gluPickMatrix() documentation for details. The default value is 3, which is adapted to standard applications. A smaller value results in a more precise selection but the user has to be careful for small feature selection. See the <a href="../examples/multiSelect.html">multiSelect example</a> for an illustration. */ int selectRegionWidth() const { return selectRegionWidth_; } /*! See the selectRegionWidth() documentation. Default value is 3 pixels. */ int selectRegionHeight() const { return selectRegionHeight_; } /*! Returns a pointer to an array of \c GLuint. This buffer is used by the \c GL_SELECT mode in select() to perform object selection. The buffer size can be modified using setSelectBufferSize(). If you overload endSelection(), you will analyze the content of this buffer. See the \c glSelectBuffer() man page for details. */ GLuint* selectBuffer() { return selectBuffer_; } public Q_SLOTS: virtual void select(const QMouseEvent* event); virtual void select(const QPoint& point); void setSelectBufferSize(int size); /*! Sets the selectRegionWidth(). */ void setSelectRegionWidth(int width) { selectRegionWidth_ = width; } /*! Sets the selectRegionHeight(). */ void setSelectRegionHeight(int height) { selectRegionHeight_ = height; } /*! Set the selectedName() value. Used in endSelection() during a selection. You should only call this method if you overload the endSelection() method. */ void setSelectedName(int id) { selectedObjectId_=id; } protected: virtual void beginSelection(const QPoint& point); /*! This method is called by select() and should draw selectable entities. Default implementation is empty. Overload and draw the different elements of your scene you want to be able to select. The default select() implementation relies on the \c GL_SELECT, and requires that each selectable element is drawn within a \c glPushName() - \c glPopName() block. A typical usage would be (see the <a href="../examples/select.html">select example</a>): \code void Viewer::drawWithNames() { for (int i=0; i<nbObjects; ++i) { glPushName(i); object(i)->draw(); glPopName(); } } \endcode The resulting selected name is computed by endSelection(), which setSelectedName() to the integer id pushed by this method (a value of -1 means no selection). Use selectedName() to update your selection, probably in the postSelection() method. \attention If your selected objects are points, do not use \c glBegin(GL_POINTS); and \c glVertex3fv() in the above \c draw() method (not compatible with raster mode): use \c glRasterPos3fv() instead. */ virtual void drawWithNames() {} virtual void endSelection(const QPoint& point); /*! This method is called at the end of the select() procedure. It should finalize the selection process and update the data structure/interface/computation/display... according to the newly selected entity. The default implementation is empty. Overload this method if needed, and use selectedName() to retrieve the selected entity name (returns -1 if no object was selected). See the <a href="../examples/select.html">select example</a> for an illustration. */ virtual void postSelection(const QPoint& point) { Q_UNUSED(point); } //@} /*! @name Keyboard customization */ //@{ public: /*! Defines the different actions that can be associated with a keyboard shortcut using setShortcut(). See the <a href="../keyboard.html">keyboard page</a> for details. */ enum KeyboardAction { DRAW_AXIS, DRAW_GRID, DISPLAY_FPS, ENABLE_TEXT, EXIT_VIEWER, SAVE_SCREENSHOT, CAMERA_MODE, FULL_SCREEN, STEREO, ANIMATION, HELP, EDIT_CAMERA, MOVE_CAMERA_LEFT, MOVE_CAMERA_RIGHT, MOVE_CAMERA_UP, MOVE_CAMERA_DOWN, INCREASE_FLYSPEED, DECREASE_FLYSPEED, SNAPSHOT_TO_CLIPBOARD }; unsigned int shortcut(KeyboardAction action) const; #ifndef DOXYGEN // QGLViewer 1.x unsigned int keyboardAccelerator(KeyboardAction action) const; Qt::Key keyFrameKey(unsigned int index) const; Qt::KeyboardModifiers playKeyFramePathStateKey() const; // QGLViewer 2.0 without Qt4 support Qt::KeyboardModifiers addKeyFrameStateKey() const; Qt::KeyboardModifiers playPathStateKey() const; #endif Qt::Key pathKey(unsigned int index) const; Qt::KeyboardModifiers addKeyFrameKeyboardModifiers() const; Qt::KeyboardModifiers playPathKeyboardModifiers() const; public Q_SLOTS: void setShortcut(KeyboardAction action, unsigned int key); #ifndef DOXYGEN void setKeyboardAccelerator(KeyboardAction action, unsigned int key); #endif void setKeyDescription(unsigned int key, QString description); void clearShortcuts(); // Key Frames shortcut keys #ifndef DOXYGEN // QGLViewer 1.x compatibility methods virtual void setKeyFrameKey(unsigned int index, int key); virtual void setPlayKeyFramePathStateKey(unsigned int buttonState); // QGLViewer 2.0 without Qt4 support virtual void setPlayPathStateKey(unsigned int buttonState); virtual void setAddKeyFrameStateKey(unsigned int buttonState); #endif virtual void setPathKey(int key, unsigned int index = 0); virtual void setPlayPathKeyboardModifiers(Qt::KeyboardModifiers modifiers); virtual void setAddKeyFrameKeyboardModifiers(Qt::KeyboardModifiers modifiers); //@} public: /*! @name Mouse customization */ //@{ /*! Defines the different mouse handlers: camera() or manipulatedFrame(). Used by setMouseBinding(), setMouseBinding(Qt::KeyboardModifiers modifiers, Qt::MouseButtons, ClickAction, bool, int) and setWheelBinding() to define which handler receives the mouse events. */ enum MouseHandler { CAMERA, FRAME }; /*! Defines the possible actions that can be binded to a mouse click using setMouseBinding(Qt::KeyboardModifiers, Qt::MouseButtons, ClickAction, bool, int). See the <a href="../mouse.html">mouse page</a> for details. */ enum ClickAction { NO_CLICK_ACTION, ZOOM_ON_PIXEL, ZOOM_TO_FIT, SELECT, RAP_FROM_PIXEL, RAP_IS_CENTER, CENTER_FRAME, CENTER_SCENE, SHOW_ENTIRE_SCENE, ALIGN_FRAME, ALIGN_CAMERA }; /*! Defines the possible actions that can be binded to a mouse action (a click, followed by a mouse displacement). These actions may be binded to the camera() or to the manipulatedFrame() (see QGLViewer::MouseHandler) using setMouseBinding(). */ enum MouseAction { NO_MOUSE_ACTION, ROTATE, ZOOM, TRANSLATE, MOVE_FORWARD, LOOK_AROUND, MOVE_BACKWARD, SCREEN_ROTATE, ROLL, DRIVE, SCREEN_TRANSLATE, ZOOM_ON_REGION }; #ifndef DOXYGEN MouseAction mouseAction(unsigned int state) const; int mouseHandler(unsigned int state) const; int mouseButtonState(MouseHandler handler, MouseAction action, bool withConstraint=true) const; ClickAction clickAction(unsigned int state, bool doubleClick, Qt::MouseButtons buttonsBefore) const; void getClickButtonState(ClickAction action, unsigned int & state, bool& doubleClick, Qt::MouseButtons& buttonsBefore) const; unsigned int wheelButtonState(MouseHandler handler, MouseAction action, bool withConstraint=true) const; #endif MouseAction mouseAction(Qt::Key key, Qt::KeyboardModifiers modifiers, Qt::MouseButton button) const; int mouseHandler(Qt::Key key, Qt::KeyboardModifiers modifiers, Qt::MouseButton button) const; void getMouseActionBinding(MouseHandler handler, MouseAction action, bool withConstraint, Qt::Key& key, Qt::KeyboardModifiers& modifiers, Qt::MouseButton& button) const; ClickAction clickAction(Qt::Key key, Qt::KeyboardModifiers modifiers, Qt::MouseButton button, bool doubleClick=false, Qt::MouseButtons buttonsBefore=Qt::NoButton) const; void getClickActionBinding(ClickAction action, Qt::Key& key, Qt::KeyboardModifiers& modifiers, Qt::MouseButton& button, bool& doubleClick, Qt::MouseButtons& buttonsBefore) const; MouseAction wheelAction(Qt::Key key, Qt::KeyboardModifiers modifiers) const; int wheelHandler(Qt::Key key, Qt::KeyboardModifiers modifiers) const; void getWheelActionBinding(MouseHandler handler, MouseAction action, bool withConstraint, Qt::Key& key, Qt::KeyboardModifiers& modifiers) const; public Q_SLOTS: #ifndef DOXYGEN void setMouseBinding(unsigned int state, MouseHandler handler, MouseAction action, bool withConstraint=true); void setMouseBinding(unsigned int state, ClickAction action, bool doubleClick=false, Qt::MouseButtons buttonsBefore=Qt::NoButton); void setMouseBindingDescription(unsigned int state, QString description, bool doubleClick=false, Qt::MouseButtons buttonsBefore=Qt::NoButton); #endif void setMouseBinding(Qt::KeyboardModifiers modifiers, Qt::MouseButton buttons, MouseHandler handler, MouseAction action, bool withConstraint=true); void setMouseBinding(Qt::KeyboardModifiers modifiers, Qt::MouseButton button, ClickAction action, bool doubleClick=false, Qt::MouseButtons buttonsBefore=Qt::NoButton); void setWheelBinding(Qt::KeyboardModifiers modifiers, MouseHandler handler, MouseAction action, bool withConstraint=true); void setMouseBindingDescription(Qt::KeyboardModifiers modifiers, Qt::MouseButton button, QString description, bool doubleClick=false, Qt::MouseButtons buttonsBefore=Qt::NoButton); void setMouseBinding(Qt::Key key, Qt::KeyboardModifiers modifiers, Qt::MouseButton buttons, MouseHandler handler, MouseAction action, bool withConstraint=true); void setMouseBinding(Qt::Key key, Qt::KeyboardModifiers modifiers, Qt::MouseButton button, ClickAction action, bool doubleClick=false, Qt::MouseButtons buttonsBefore=Qt::NoButton); void setWheelBinding(Qt::Key key, Qt::KeyboardModifiers modifiers, MouseHandler handler, MouseAction action, bool withConstraint=true); void setMouseBindingDescription(Qt::Key key, Qt::KeyboardModifiers modifiers, Qt::MouseButton button, QString description, bool doubleClick=false, Qt::MouseButtons buttonsBefore=Qt::NoButton); void clearMouseBindings(); #ifndef DOXYGEN MouseAction wheelAction(Qt::KeyboardModifiers modifiers) const; int wheelHandler(Qt::KeyboardModifiers modifiers) const; void setHandlerKeyboardModifiers(MouseHandler handler, Qt::KeyboardModifiers modifiers); void setHandlerStateKey(MouseHandler handler, unsigned int buttonState); void setMouseStateKey(MouseHandler handler, unsigned int buttonState); #endif private: static QString mouseActionString(QGLViewer::MouseAction ma); static QString clickActionString(QGLViewer::ClickAction ca); //@} /*! @name State persistence */ //@{ public: QString stateFileName() const; virtual QDomElement domElement(const QString& name, QDomDocument& document) const; public Q_SLOTS: virtual void initFromDOMElement(const QDomElement& element); virtual void saveStateToFile(); // cannot be const because of QMessageBox virtual bool restoreStateFromFile(); /*! Defines the stateFileName() used by saveStateToFile() and restoreStateFromFile(). The file name can have an optional prefix directory (no prefix meaning current directory). If the directory does not exist, it will be created by saveStateToFile(). \code // Name depends on the displayed 3D model. Saved in current directory. setStateFileName(3DModelName() + ".xml"); // Files are stored in a dedicated directory under user's home directory. setStateFileName(QDir::homeDirPath + "/.config/myApp.xml"); \endcode */ void setStateFileName(const QString& name) { stateFileName_ = name; } #ifndef DOXYGEN void saveToFile(const QString& fileName=QString::null); bool restoreFromFile(const QString& fileName=QString::null); #endif private: static void saveStateToFileForAllViewers(); //@} /*! @name QGLViewer pool */ //@{ public: /*! Returns a \c QList that contains pointers to all the created QGLViewers. Note that this list may contain \c NULL pointers if the associated viewer has been deleted. Can be useful to apply a method or to connect a signal to all the viewers: \code foreach (QGLViewer* viewer, QGLViewer::QGLViewerPool()) connect(myObject, SIGNAL(IHaveChangedSignal()), viewer, SLOT(update())); \endcode \attention With Qt version 3, this method returns a \c QPtrList instead. Use a \c QPtrListIterator to iterate on the list instead.*/ static const QList<QGLViewer*>& QGLViewerPool() { return QGLViewer::QGLViewerPool_; } /*! Returns the index of the QGLViewer \p viewer in the QGLViewerPool(). This index in unique and can be used to identify the different created QGLViewers (see stateFileName() for an application example). When a QGLViewer is deleted, the QGLViewers' indexes are preserved and NULL is set for that index. When a QGLViewer is created, it is placed in the first available position in that list. Returns -1 if the QGLViewer could not be found (which should not be possible). */ static int QGLViewerIndex(const QGLViewer* const viewer) { return QGLViewer::QGLViewerPool_.indexOf(const_cast<QGLViewer*>(viewer)); } //@} #ifndef DOXYGEN /*! @name Visual hints */ //@{ public: virtual void setVisualHintsMask(int mask, int delay = 2000); virtual void drawVisualHints(); public Q_SLOTS: virtual void resetVisualHints(); //@} #endif private Q_SLOTS: // Patch for a Qt bug with fullScreen on startup void delayedFullScreen() { move(prevPos_); setFullScreen(); } void hideMessage(); private: // Copy constructor and operator= are declared private and undefined // Prevents everyone from trying to use them QGLViewer(const QGLViewer& v); QGLViewer& operator=(const QGLViewer& v); // Set parameters to their default values. Called by the constructors. void defaultConstructor(); void handleKeyboardAction(KeyboardAction id); // C a m e r a qglviewer::Camera* camera_; bool cameraIsEdited_; qreal previousCameraZClippingCoefficient_; unsigned int previousPathId_; // double key press recognition void connectAllCameraKFIInterpolatedSignals(bool connection=true); // C o l o r s QColor backgroundColor_, foregroundColor_; // D i s p l a y f l a g s bool axisIsDrawn_; // world axis bool gridIsDrawn_; // world XY grid bool FPSIsDisplayed_; // Frame Per Seconds bool textIsEnabled_; // drawText() actually draws text or not bool stereo_; // stereo display bool fullScreen_; // full screen mode QPoint prevPos_; // Previous window position, used for full screen mode // A n i m a t i o n bool animationStarted_; // animation mode started int animationPeriod_; // period in msecs int animationTimerId_; // F P S d i s p l a y QTime fpsTime_; unsigned int fpsCounter_; QString fpsString_; qreal f_p_s_; // M e s s a g e s QString message_; bool displayMessage_; QTimer messageTimer_; // M a n i p u l a t e d f r a m e qglviewer::ManipulatedFrame* manipulatedFrame_; bool manipulatedFrameIsACamera_; // M o u s e G r a b b e r qglviewer::MouseGrabber* mouseGrabber_; bool mouseGrabberIsAManipulatedFrame_; bool mouseGrabberIsAManipulatedCameraFrame_; QMap<size_t, bool> disabledMouseGrabbers_; // S e l e c t i o n int selectRegionWidth_, selectRegionHeight_; int selectBufferSize_; GLuint* selectBuffer_; int selectedObjectId_; // V i s u a l h i n t s int visualHint_; // S h o r t c u t k e y s void setDefaultShortcuts(); QString cameraPathKeysString() const; QMap<KeyboardAction, QString> keyboardActionDescription_; QMap<KeyboardAction, unsigned int> keyboardBinding_; QMap<unsigned int, QString> keyDescription_; // K e y F r a m e s s h o r t c u t s QMap<Qt::Key, unsigned int> pathIndex_; Qt::KeyboardModifiers addKeyFrameKeyboardModifiers_, playPathKeyboardModifiers_; // B u f f e r T e x t u r e GLuint bufferTextureId_; qreal bufferTextureMaxU_, bufferTextureMaxV_; int bufferTextureWidth_, bufferTextureHeight_; unsigned int previousBufferTextureFormat_; int previousBufferTextureInternalFormat_; #ifndef DOXYGEN // M o u s e a c t i o n s struct MouseActionPrivate { MouseHandler handler; MouseAction action; bool withConstraint; }; // M o u s e b i n d i n g s struct MouseBindingPrivate { const Qt::KeyboardModifiers modifiers; const Qt::MouseButton button; const Qt::Key key; MouseBindingPrivate(Qt::KeyboardModifiers m, Qt::MouseButton b, Qt::Key k) : modifiers(m), button(b), key(k) {} // This sort order is used in mouseString() to display sorted mouse bindings bool operator<(const MouseBindingPrivate& mbp) const { if (key != mbp.key) return key < mbp.key; if (modifiers != mbp.modifiers) return modifiers < mbp.modifiers; return button < mbp.button; } }; // W h e e l b i n d i n g s struct WheelBindingPrivate { const Qt::KeyboardModifiers modifiers; const Qt::Key key; WheelBindingPrivate(Qt::KeyboardModifiers m, Qt::Key k) : modifiers(m), key(k) {} // This sort order is used in mouseString() to display sorted wheel bindings bool operator<(const WheelBindingPrivate& wbp) const { if (key != wbp.key) return key < wbp.key; return modifiers < wbp.modifiers; } }; // C l i c k b i n d i n g s struct ClickBindingPrivate { const Qt::KeyboardModifiers modifiers; const Qt::MouseButton button; const bool doubleClick; const Qt::MouseButtons buttonsBefore; // only defined when doubleClick is true const Qt::Key key; ClickBindingPrivate(Qt::KeyboardModifiers m, Qt::MouseButton b, bool dc, Qt::MouseButtons bb, Qt::Key k) : modifiers(m), button(b), doubleClick(dc), buttonsBefore(bb), key(k) {} // This sort order is used in mouseString() to display sorted mouse bindings bool operator<(const ClickBindingPrivate& cbp) const { if (key != cbp.key) return key < cbp.key; if (buttonsBefore != cbp.buttonsBefore) return buttonsBefore < cbp.buttonsBefore; if (modifiers != cbp.modifiers) return modifiers < cbp.modifiers; if (button != cbp.button) return button < cbp.button; return doubleClick != cbp.doubleClick; } }; #endif static QString formatClickActionPrivate(ClickBindingPrivate cbp); static bool isValidShortcutKey(int key); QMap<ClickBindingPrivate, QString> mouseDescription_; void setDefaultMouseBindings(); void performClickAction(ClickAction ca, const QMouseEvent* const e); QMap<MouseBindingPrivate, MouseActionPrivate> mouseBinding_; QMap<WheelBindingPrivate, MouseActionPrivate> wheelBinding_; QMap<ClickBindingPrivate, ClickAction> clickBinding_; Qt::Key currentlyPressedKey_; // S n a p s h o t s void initializeSnapshotFormats(); QImage frameBufferSnapshot(); QString snapshotFileName_, snapshotFormat_; int snapshotCounter_, snapshotQuality_; TileRegion* tileRegion_; // Q G L V i e w e r p o o l static QList<QGLViewer*> QGLViewerPool_; // S t a t e F i l e QString stateFileName_; // H e l p w i n d o w QTabWidget* helpWidget_; }; #endif // QGLVIEWER_QGLVIEWER_H
// Question 18 => Find all pairs on integer array whose sum is equal to given number #include<bits/stdc++.h> using namespace std; int getSum1(int arr[], int n, int sum){ int count = 0; for(int i=0; i<n; i++){ for(int j=i+1; j<n; j++){ if(arr[i] + arr[j] == sum){ count++; } } } return count; } int getPairsCount(int arr[], int n, int sum){ int count =0; unordered_map<int,int> m; for(int i=0; i<n; i++){ int x = sum - arr[i]; if(m[x] == 0){ m[arr[i]]++; } else{ count +=m[x]; m[arr[i]]++; } } return count; } int main(){ int arr[] = {1,5,7,-1}; int n = sizeof(arr) / sizeof(arr[0]); int number = 6; cout<<getSum1(arr, n, number)<<endl; cout<<getPairsCount(arr, n, number); }
#include <cstdlib> #include <iostream> #include <iomanip> #include <list> using namespace std; main() { list <string> alumnos; alumnos.push_back("Juan"); alumnos.push_back("Maria"); alumnos.push_back("Camila"); alumnos.push_back("Martin"); alumnos.push_back("Juan"); alumnos.push_back("Milton"); int i=1; cout<<"El tamanio de la lista es: "<<alumnos.size(); cout<<"\n"; alumnos.remove("Milton"); cout<<"El nuevo tamanio de la lista es: "<<alumnos.size(); cout<<"\n"; cout<<"La lista es: "; while(!alumnos.empty()){ cout<<" "<<alumnos.front(); alumnos.pop_front(); i++; } }
#pragma once #include"dlgs.h" // CFileDialogEx class CFileDialogEx : public CFileDialog { DECLARE_DYNAMIC(CFileDialogEx) public: CFileDialogEx(BOOL bOpenFileDialog, // 对于 FileOpen 为 TRUE,对于 FileSaveAs 为 FALSE LPCTSTR lpszDefExt = NULL, LPCTSTR lpszFileName = NULL, DWORD dwFlags = OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT, LPCTSTR lpszFilter = NULL, CWnd* pParentWnd = NULL); CStatic m_Static; CComboBox m_Combo; int m_nMyType; virtual ~CFileDialogEx(); virtual BOOL OnInitDialog(); virtual BOOL OnDestroy(); protected: DECLARE_MESSAGE_MAP() };
#include "Hw264Encoder.h" #include "media/NdkMediaFormat.h" CLASS_LOG_IMPLEMENT(CHw264Encoder, "video[264.encoder]"); extern bool g_IsMTK; CHw264Encoder::CHw264Encoder(AMediaCodec *pCodec, StreamEncodedataParameter *Parameter) : m_pCodec(pCodec), m_ref(-1), m_adj(-1) { THIS_LOGT_print("is created: %p of %s, IsMTK: %d", m_pCodec, Parameter->minetype, g_IsMTK? 1:0); AMediaFormat *format = AMediaFormat_new(); AMediaFormat_setString(format, AMEDIAFORMAT_KEY_MIME, Parameter->minetype); AMediaFormat_setInt32 (format, AMEDIAFORMAT_KEY_WIDTH, Parameter->width); AMediaFormat_setInt32 (format, AMEDIAFORMAT_KEY_HEIGHT, Parameter->height); AMediaFormat_setInt32 (format, AMEDIAFORMAT_KEY_BIT_RATE, Parameter->bitrate); AMediaFormat_setInt32 (format, AMEDIAFORMAT_KEY_I_FRAME_INTERVAL, Parameter->gop); AMediaFormat_setInt32 (format, AMEDIAFORMAT_KEY_FRAME_RATE, Parameter->fps); AMediaFormat_setInt32 (format, AMEDIAFORMAT_KEY_COLOR_FORMAT, g_IsMTK? 19:21); THIS_LOGI_print("configure %s", AMediaFormat_toString(format)); media_status_t ret1 = AMediaCodec_configure(m_pCodec, format, NULL, NULL, AMEDIACODEC_CONFIGURE_FLAG_ENCODE); THIS_LOGD_print("call AMediaCodec_configure return %d", ret1); media_status_t ret2 = AMediaCodec_start(m_pCodec); THIS_LOGD_print("call AMediaCodec_start return %d", ret2); AMediaFormat_delete(format); m_codecid = g_IsMTK? 0/*AV_PIX_FMT_YUV420P*/:25/*AV_PIX_FMT_NV12*/; m_bHasCSD = g_IsMTK == false; } CHw264Encoder::~CHw264Encoder() { AMediaCodec_stop(m_pCodec); AMediaCodec_delete(m_pCodec); THIS_LOGT_print("is deleted"); } int CHw264Encoder::Encode(unsigned char *pktBuf, int pktLen, int64_t &presentationTimeUs, unsigned char *pout) { COST_STAT_DECLARE(cost); ssize_t nIndex = AMediaCodec_dequeueInputBuffer(m_pCodec, 100000); if( nIndex < 0 ) { THIS_LOGE_print("call AMediaCodec_dequeueInputBuffer return %d", nIndex); return nIndex; } size_t nlen; uint8_t *ibuf = AMediaCodec_getInputBuffer(m_pCodec, nIndex, &nlen); if( pktBuf != 0) { assert(ibuf && pktLen <= nlen); memcpy(ibuf, pktBuf, pktLen); } ssize_t nStatus = AMediaCodec_queueInputBuffer(m_pCodec, nIndex, 0, pktLen, presentationTimeUs, 0); if( nStatus < 0) { THIS_LOGE_print("call AMediaCodec_queueInputBuffer return %d", nStatus); return nStatus; } else { AMediaCodecBufferInfo info; ssize_t nIndex = AMediaCodec_dequeueOutputBuffer(m_pCodec, &info, 10000); if( nIndex < 0) { if( m_bHasCSD != false ) { THIS_LOGE_print("call AMediaCodec_dequeueOutputBuffer return %d", nIndex); return nIndex; } else { unsigned char *sps = NULL, *pps = NULL; unsigned char *pos = pout; size_t sps_len = 0, pps_len = 0; AMediaFormat *format = AMediaCodec_getOutputFormat(m_pCodec); AMediaFormat_getBuffer(format, "csd-0", (void**)&sps, &sps_len); memcpy(pos, sps, sps_len); pos += sps_len; AMediaFormat_getBuffer(format, "csd-1", (void**)&pps, &pps_len); memcpy(pos, pps, pps_len); pos += pps_len; AMediaFormat_delete(format); THIS_LOGD_print("got frame[0x0]: pts=%lld, data=%p, size=%d, nalu.type=%d, cost=%lld", presentationTimeUs, pout, sps_len + pps_len, (int)pout[4]&0x1f, GetTickCount() - cost); m_ref = presentationTimeUs; m_bHasCSD = true; return sps_len + pps_len; } } if( info.size ) { uint8_t *obuf = AMediaCodec_getOutputBuffer(m_pCodec, nIndex, &nlen); assert(obuf && info.size <= nlen); memcpy(pout, obuf, info.size); if( m_ref < 0 ) { m_ref = presentationTimeUs; } else { if( m_adj < 0 ) { m_adj = m_ref - info.presentationTimeUs; presentationTimeUs = m_ref; } else { presentationTimeUs = info.presentationTimeUs + m_adj; } } THIS_LOGD_print("got frame[%p]: pts=%lld, data=%p, size=%d, nalu.type=%d, cost=%lld", obuf, presentationTimeUs, pout, info.size, (int)pout[4] & 0x1f, GetTickCount() - cost); } AMediaCodec_releaseOutputBuffer(m_pCodec, nIndex, info.size != 0); return info.size; } }