text
stringlengths
8
6.88M
#include "Lumigraph.h" bool paircomp (pair<int,double> p, pair<int,double> q) { return (p.second < q.second); } Lumigraph::Lumigraph(void) : uv_count(0) , t_width(0) , s_height(0) , ImgDataSeq(NULL) , kth(0) , proxyWidth(0) { } Lumigraph::~Lumigraph(void) { } Lumigraph::Lumigraph(string filename) { string param = filename + "_parameters.txt"; string data = filename + "_data"; string proxy = filename + "_proxy.txt"; string cameraMat = filename + "_camera.xml"; this->kth = 1; //Read In Calibration File string cali_filename = "C:\\OpenCV_Project\\camera_calibration\\result.xml"; FileStorage fp(cali_filename, FileStorage::READ); fp["Camera_Matrix"] >> this->Camera_K; fp["Distortion_Coefficients"] >> discoeff; cout << "K " << endl << Mat(Camera_K) << endl; fp.release(); // First read in parameters FILE* lfparamfile = fopen(param.c_str(), "r"); if (lfparamfile == NULL) { printf("Could not open file %s\n", param.c_str()); return; } // Read in parameters //int t_width, s_height, uv_count; fscanf(lfparamfile, "%d %d %d %d %d", &t_width, &s_height, &uv_count,&proxyWidth,&proxyHeight); fclose(lfparamfile); //Read in Image data this->ImgDataSeq = (unsigned char*) malloc(sizeof(unsigned char) * t_width * s_height * uv_count *3); // Then grab the data FILE *lfdatafile = fopen(data.c_str(), "rb"); if (lfdatafile == NULL) { printf("Could not open file %s", data.c_str()); return; } fread( this->ImgDataSeq, t_width * s_height * uv_count *3, 1, lfdatafile ); fclose(lfdatafile); string FullPathXML = filename + ".xml"; //FileStorage fs(FullPathXML,FileStorage::READ); vector<string> imagelists; if(!readStringList(FullPathXML, imagelists)) { cout << "Can't locate the file!" << endl; } FileStorage fs1(cameraMat, FileStorage::READ); //Read in Camera Matrix for each image for(int i = 0; i < imagelists.size(); i++) { int namelength = imagelists[i].length() - 4; Mat tempMat; string MatName = imagelists[i].substr(0,namelength); fs1[MatName] >> tempMat; Mat_<double>tempCMat(3,4); tempCMat = tempMat; Matx34d tempCMat1; tempCMat1 = Matx34d(tempCMat(0,0),tempCMat(0,1),tempCMat(0,2),tempCMat(0,3), tempCMat(1,0),tempCMat(1,1),tempCMat(1,2),tempCMat(1,3), tempCMat(2,0),tempCMat(2,1),tempCMat(2,2),tempCMat(2,3)); AllCameraMat.push_back(tempCMat1); } fs1.release(); //Read in Proxy FILE *lfproxyfile = fopen(proxy.c_str(), "r"); if (lfparamfile == NULL) { printf("Could not open file %s\n", param.c_str()); return; } for(int i = 0;i<proxyWidth*proxyHeight*3;i += 3) { int x,y,z; fscanf(lfproxyfile, "%d %d %d", &x,&y,&z); Point3d tempProxy; tempProxy.x = x; tempProxy.y = y; tempProxy.z = z; proxyData.push_back(tempProxy); } fclose(lfproxyfile); } vector<pair<int,double>> Lumigraph::GetWeights(Point3d proxyPoint, Point3d VirtualCameraLoc, vector<Point3d> AllCameraLocs) { vector<pair<int,double>> weights; vector<pair<int,double>> penalities; Point3d VirCamVec = VirtualCameraLoc - proxyPoint; double dist_VirCam = norm(VirCamVec); for(int i = 0; i < AllCameraLocs.size(); i++) { Vec3d curpenalities; //Angle Penalty: Compute Angles Point3d CurCamVec = AllCameraLocs[i] - proxyPoint; double dist_CurCam = norm(CurCamVec); double curangle = CurCamVec.dot(VirCamVec); curangle = curangle / (dist_VirCam * dist_CurCam); curangle = acos(curangle); curpenalities[0] = (curangle); //Resolution Penalty curpenalities[1] = (dist_CurCam - dist_CurCam > 0)?(dist_CurCam - dist_CurCam):0; //Field of View Penalty // project to current camera plane //decomposition Matx33d R(AllCameraMat[i](0,0),AllCameraMat[i](0,1),AllCameraMat[i](0,2), AllCameraMat[i](1,0),AllCameraMat[i](1,1),AllCameraMat[i](1,2), AllCameraMat[i](2,0),AllCameraMat[i](2,1),AllCameraMat[i](2,2)); //Vec3d T; Mat T(3,1,cv::DataType<double>::type); vector<Point3d> tempProxy; T.at<double>(0,0) = AllCameraMat[i](0,3); T.at<double>(1,0) = AllCameraMat[i](1,3); T.at<double>(2,0) = AllCameraMat[i](2,3); tempProxy.push_back(proxyPoint); //Vec2d curimgPoint; vector<Point2d> curimgPoint; //decomposeProjectionMatrix(AllCameraMat[i], K, R, T); //Mat_<double> K = this->Camera_K; Mat K(3,3,cv::DataType<double>::type); K = Camera_K.clone(); cv::Mat rvecR(3,1,cv::DataType<double>::type);//rodrigues rotation matrix cv::Rodrigues(R,rvecR); try { projectPoints(tempProxy, rvecR, T,K, this->discoeff, curimgPoint); } catch(cv::Exception & e) { cout<<e.msg<<endl; } int test = 1; if(curimgPoint[0].x > t_width || curimgPoint[0].y > s_height) curpenalities[2] = DBL_MAX_EXP; else curpenalities[2] = 0; //total penalty double totalcurpenalty; double alpha = 0.4, beta = 0.3, gamma = 0.3; totalcurpenalty = alpha * curpenalities[0] + beta * curpenalities[1] + gamma * curpenalities[2]; penalities.push_back(make_pair(i,totalcurpenalty)); } // find the first kth smallest element in penalities nth_element(penalities.begin(), penalities.begin() + kth, penalities.end(), paircomp); double totalweights = 0; for(int i = 0; i < this->kth; i++) { weights.push_back(penalities[i]); weights[i].second = 1 - weights[i].second / (penalities.begin() + this->kth)->second; totalweights += weights[i].second; } //normalize for(int i = 0; i < this->kth; i++) { if(totalweights != 0) { weights[i].second /= totalweights; } else { int test = 1; } } return weights; } vector<Matx33d> Lumigraph::CalculateFundamentalMat(vector<Matx34d> allcameraMat, Matx34d curP) { vector<Matx33d> F; Matx41d C(0,0,0,1); for(int i=0;i<allcameraMat.size();i++) { Matx33d temp_F; Matx31d P2C = allcameraMat[i] * C; Matx33d P2Cx(0, -P2C(2,0), P2C(1,0), P2C(2,0), 0, -P2C(0,0), -P2C(1,0), P2C(0,0), 0); SVD svd(allcameraMat[i]); Mat_<double> pinvP(4,3); pinvP = svd.vt.t() * Mat::diag(1./svd.w)*svd.u.t(); Matx43d temp_P(pinvP(0,0),pinvP(0,1),pinvP(0,2), pinvP(1,0),pinvP(1,1),pinvP(1,2), pinvP(2,0),pinvP(2,1),pinvP(2,2), pinvP(3,0),pinvP(3,1),pinvP(3,2)); temp_F = P2Cx * curP * temp_P; F.push_back(temp_F); } return F; } Mat Lumigraph::RenderImage(vector<Point3d> proxyPoint, Point3d VirtualCameraLoc, vector<Point3d> AllCameraLocs,Matx33d VirtualRot,Vec3d VirtualTrans) { //Mat Img(s_height,t_width,CV_32FC3); Mat Img(s_height,t_width,CV_8UC3); vector<Vec2d> ProxyProjectPoint; for(int numP = 0;numP<proxyPoint.size();numP++) { CurrFrameWeights = this->GetWeights(proxyPoint[numP],VirtualCameraLoc,AllCameraLocs); double addWeightInten_R = 0; double addWeightInten_G = 0; double addWeightInten_B = 0; for(int i=0;i<this->kth;i++) { //vector<Point2d> curimgPoint; int Num = CurrFrameWeights[i].first; Matx33d R(AllCameraMat[i](0,0),AllCameraMat[i](0,1),AllCameraMat[i](0,2), AllCameraMat[i](1,0),AllCameraMat[i](1,1),AllCameraMat[i](1,2), AllCameraMat[i](2,0),AllCameraMat[i](2,1),AllCameraMat[i](2,2)); Mat T(3,1,cv::DataType<double>::type); vector<Point3d> tempProxy; T.at<double>(0,0) = AllCameraMat[i](0,3); T.at<double>(1,0) = AllCameraMat[i](1,3); T.at<double>(2,0) = AllCameraMat[i](2,3); tempProxy.push_back(proxyPoint[numP]); //Vec2d curimgPoint; vector<Point2d> curimgPoint; //decomposeProjectionMatrix(AllCameraMat[i], K, R, T); Mat K = this->Camera_K; cv::Mat rvecR(3,1,cv::DataType<double>::type);//rodrigues rotation matrix cv::Rodrigues(R,rvecR); //projectPoints((Vec3d)proxyPoint[numP], K, R, T, NULL, curimgPoint); projectPoints(tempProxy, rvecR, T,K, this->discoeff, curimgPoint); if(curimgPoint[0].x > t_width || curimgPoint[0].y > s_height) continue; unsigned char curimgIntensity_R = this->ImgDataSeq[t_width*s_height*3*Num + (int)curimgPoint[0].y*t_width*3 + (int)curimgPoint[0].x]; unsigned char curimgIntensity_G = this->ImgDataSeq[t_width*s_height*3*Num + (int)curimgPoint[0].y*t_width*3 + (int)curimgPoint[0].x + 1]; unsigned char curimgIntensity_B = this->ImgDataSeq[t_width*s_height*3*Num + (int)curimgPoint[0].y*t_width*3 + (int)curimgPoint[0].x + 2]; addWeightInten_R += curimgIntensity_R * CurrFrameWeights[i].second; addWeightInten_G += curimgIntensity_G * CurrFrameWeights[i].second; addWeightInten_B += curimgIntensity_B * CurrFrameWeights[i].second; } vector<Point2d> virtualPoint; vector<Point3d> tempProxy; tempProxy.push_back(proxyPoint[numP]); Mat vR(3,1,cv::DataType<double>::type);//rodrigues rotation matrix Rodrigues(VirtualRot,vR); Mat vT(3,1,cv::DataType<double>::type); vT.at<double>(0,0) = VirtualTrans[0]; vT.at<double>(1,0) = VirtualTrans[1]; vT.at<double>(2,0) = VirtualTrans[2]; //int Num = CurrFrameWeights[i].first; //decomposeProjectionMatrix(VirtualP, K1, R1, T1); //projectPoints((tempProxy, this->Camera_K, VirtualRot, VirtualTrans, this->discoeff, virtualPoint); projectPoints(tempProxy, vR, vT,this->Camera_K, this->discoeff, virtualPoint); if(virtualPoint[0].x > t_width || virtualPoint[0].y > s_height) continue; //assign intesity to Img try { *(Img.data + Img.step[0]*(int)virtualPoint[0].y + Img.step[1]*(int)virtualPoint[0].x) = addWeightInten_R; *(Img.data + Img.step[0]*(int)virtualPoint[0].y + Img.step[1]*(int)virtualPoint[0].x+1) = addWeightInten_G; *(Img.data + Img.step[0]*(int)virtualPoint[0].y + Img.step[1]*(int)virtualPoint[0].x+2) = addWeightInten_B; /*Img.at<float>((int)virtualPoint[0].y,(int)virtualPoint[0].x,1) = addWeightInten_R; Img.at<float>((int)virtualPoint[0].y,(int)virtualPoint[0].x,2) = addWeightInten_G; Img.at<float>((int)virtualPoint[0].y,(int)virtualPoint[0].x,3) = addWeightInten_B;*/ } catch(cv::Exception & e) { cout<<e.msg<<endl; } Vec2d myPoint; myPoint[0] = virtualPoint[0].y; myPoint[1] = virtualPoint[0].x; ProxyProjectPoint.push_back(myPoint); } Mat RenderedImg = this->InterpolateRenderImage(Img,ProxyProjectPoint); //cvNamedWindow("test2"); //imshow("test2",Img); return RenderedImg; } Mat Lumigraph::InterpolateRenderImage(Mat Img, vector<Vec2d> proxy2DPoint) { for(int numP = 0;numP<proxy2DPoint.size()-2;numP++) { int Width = numP + proxyWidth; if((numP + proxyWidth) > proxy2DPoint.size()-2) { Width = proxy2DPoint.size()-2; } for(int y = proxy2DPoint[numP][0];y<proxy2DPoint[Width][0];y++) { for(int x = proxy2DPoint[numP][1];x<proxy2DPoint[numP+1][1];x++) { double x1 = proxy2DPoint[numP][1]; double y1 = proxy2DPoint[numP][0]; double x2 = proxy2DPoint[numP+1][1]; double y2 = proxy2DPoint[numP+1][0]; double x3 = proxy2DPoint[Width][1]; double y3 = proxy2DPoint[Width][0]; double x4 = proxy2DPoint[Width+1][1]; double y4 = proxy2DPoint[Width+1][0]; double Q11 = *(Img.data + Img.step[0]*(int)y1 + Img.step[1]*(int)x1); double Q12 = *(Img.data + Img.step[0]*(int)y2 + Img.step[1]*(int)x2); double Q21 = *(Img.data + Img.step[0]*(int)y3 + Img.step[1]*(int)x3); double Q22 = *(Img.data + Img.step[0]*(int)y4 + Img.step[1]*(int)x4); double k_12 = (y2 - y1) / (x2 - x1); // slope of upper and lower line double alpha = ((y - y3) - k_12 * (x - x3))/((y1 - y3) - k_12 * (x1 - x3)); //ratio between upper and lower double Qleft = alpha * Q11 + (1 - alpha) * Q21;// left point intensity double Qright = alpha * Q12 + (1 - alpha) * Q22; //right point intensity double k_13 = (y3 - y1) / (x3 - x1); // slope of left line double beta = ((y - y1) - k_13 * (x - x1))/((y2 - y1) - k_13 * (x2 - x1)); // ratio between left and right int P = (1 - beta) * Qleft + beta * Qright; // final result // double R1 = (double)(x2-x)/(x2-x1)*Q11 + (double)(x-x1)/(x2-x1)*Q12; // double R2 = (double)(x4-x)/(x4-x3)*Q21 + (double)(x-x3)/(x4-x3)*Q22; // int P = (double)(y3-y)/(y3-y1)*R1 + (double)(y-y2)/(y4-y2)*R2; *(Img.data + Img.step[0]*(int)y + Img.step[1]*(int)x) = (unsigned char) P; *(Img.data + Img.step[0]*(int)y + Img.step[1]*(int)x+1) = (unsigned char) P; *(Img.data + Img.step[0]*(int)y + Img.step[1]*(int)x+2) = (unsigned char) P; //Img.data[Img.step*(int)y + Img.channels()*(int)x] = 255; //Img.data[Img.step*(int)y + Img.channels()*(int)x + 1] = 255; } } } Size size(1024,768); Mat test; resize(Img,test,size); cvNamedWindow("test3"); imshow("test3",test); return Img; } Mat Lumigraph::DrawImage(xform xf) { Point3d vCameraLoc; vCameraLoc.x = xf[12]; vCameraLoc.y = xf[13]; vCameraLoc.z = xf[14]; Matx33d vP_rot(xf[0],xf[4],xf[8], xf[1],xf[5],xf[9], xf[2],xf[6],xf[10]); Vec3d vP_trans; vP_trans[0] = xf[3]; vP_trans[1] = xf[7]; vP_trans[2] = xf[11]; vector<Point3d> AllCameraLocs; for(int i=0;i<this->AllCameraMat.size();i++) { Matx33d K, R; Vec3d T; Point3d vLoc; //decomposeProjectionMatrix(this->AllCameraMat[i], K, R, T); vLoc.x = AllCameraMat[i](0,3); vLoc.y = AllCameraMat[i](1,3); vLoc.z = AllCameraMat[i](2,3); AllCameraLocs.push_back(vLoc); } Mat myImg = this->RenderImage(this->proxyData,vCameraLoc,AllCameraLocs,vP_rot,vP_trans); Size size(1024,768); Mat test; resize(myImg,test,size); cvNamedWindow("test1"); imshow("test1",test); return myImg; }
#include <iostream> #include "memory_view.hpp" namespace memory_view { const uint8_t &v1::operator[](size_t pos) const noexcept { return *(this->m_data + pos); } }
#include "task.h" #include <SDL.h> #include <SDL_opengl.h> #include <GL/gl.h> // Header File For The OpenGL32 Library #include <GL/glu.h> // Header File For The GLu32 Library #include "vector.h" #include "printer.h" // text printing (ie- font rendering) #ifndef __GRAPHICS__H__ #define __GRAPHICS__H__ class Graphics : public Task { public: Graphics(void); ~Graphics(void); bool init(); void pause(); bool stop(); void run(); int LoadTexture(const char *filename); Printer text; }; void DrawCube(Vector pos, Vector scale); void DrawQuad(Vector,Vector); void DrawSkybox(); extern PFNGLFOGCOORDFEXTPROC glFogCoordfEXT; extern PFNGLMULTITEXCOORD2FARBPROC glMultiTexCoord2fARB; extern PFNGLACTIVETEXTUREARBPROC glActiveTextureARB; extern PFNGLCLIENTACTIVETEXTUREARBPROC glClientActiveTextureARB; #endif
#include "init.h" #include "ui_init.h" #include "dimensionement.h" #include "ui_dimensionement.h" #include "dirigeable.h" init::init(QWidget *parent) : QWidget(parent), ui(new Ui::init) { ui->setupUi(this); } init::~init() { delete ui; } void init::on_pushButton_clicked() { nextLayer->showMaximized(); hide(); } void init::setNextLayer(QWidget* w){ nextLayer = w; }
#ifndef GROUND_H #define GROUND_H #include "terrain.h" class Ground : public Terrain { Q_OBJECT public: Ground(QObject *parent = nullptr); Ground(int x, int y, int width, int height, const QString& imgPath, QObject *parent = nullptr); }; #endif // GROUND_H
#include "DataStructure.h" #include <iostream> #include <string> #include "travel.h" #include "droute.h" #include <time.h> #include<process.h> #include<stdio.h> #include<stdlib.h> #include<string.h> extern struct passenger passer; extern struct city graph; extern int currenttime; extern struct order *command,*end; extern int over; extern struct passenger passer; extern int flag;//设计路线信号 extern int fflag;//启动时间信号 extern struct route line1[10]; extern struct route line2[10]; extern struct route temp; extern int ll,middle; extern int ffflag;//一个计划已结束 extern time_t start; extern int differtime; extern int fffflag;//同步锁 extern int state; extern int st; extern int ptime; void FileInput(const char* file_name) { FILE *fp; fp=fopen(file_name,"r"); if(fp==NULL) printf("文件打开失败!"); char command[30]; int j,i=0; int num=0; char city_name[30]; char mode; float danger; while (!feof(fp)) { fscanf(fp,"%s",command); if (strcmp(command,"city")==0) { fscanf(fp,"%s%f",city_name,&danger); while (strcmp(city_name,"-n")!=0) { //graph.vexs[i]=city_name; strcpy(graph.vexs[i],city_name); graph.danger[i]=danger; fscanf(fp,"%s%f",city_name,&danger); i++; } } else if (strcmp(command,"trp")==0) { fscanf(fp,"%c",&mode); fscanf(fp,"%c",&mode); int tDeparture, tArrival,a,b; char cityA[30], cityB[30]; fscanf(fp,"%s",cityA); fscanf(fp,"%s",cityB); fscanf(fp,"%d",&tDeparture); fscanf(fp,"%d",&tArrival); for(j=0;j<=9;j++) { if(strcmp(graph.vexs[j],cityA)==0) a=j; if(strcmp(graph.vexs[j],cityB)==0) b=j; } num=graph.edgnum[a][b]; graph.matrix[a][b][num].tool=mode; graph.matrix[a][b][num].DeTime=tDeparture; graph.matrix[a][b][num].ArTime=tArrival; graph.edgnum[a][b]++; //graph.matrix[a][b].finish } } fclose(fp); } void FileOutput(int kind) { FILE *fp; fp=fopen("log.txt","a"); if(fp==NULL) printf("日志文件打开失败!"); if(kind==0) { fprintf(fp,"旅客状态:时间:%d ",(currenttime%24)); if(passer.start==passer.finish) fprintf(fp,"当前所在城市:%d\n",passer.start); else fprintf(fp,"旅客乘坐%c从%d到%d\n",passer.tool,passer.start,passer.finish); } if(kind==1) { fprintf(fp,"旅客想要到城市%d旅行,选择策略为%d,时间限制为%d\n",command->finish,command->strategy,command->TimeLimit);// } fclose(fp); } void Init(const char* file_name) { // Input data FileInput(file_name);//读取文件,建好邻接矩阵 int a,b,j; for(int i=0;i<10;i++) printf("序号%d代表城市%s\n",i,graph.vexs[i]); printf("交通工具:c表示汽车,t表示火车,p表示飞机\n"); printf("低风险策略0,限制时间内低风险策略1\n"); // for(a=0;a<10;a++) // for(b=0;b<10;b++) // if(a!=b) // for(j=0;j<graph.edgnum[a][b];j++) // printf("%s到%s的出发时间:%d,到达时间:%d,交通工具:%c\n",graph.vexs[a],graph.vexs[b],graph.matrix[a][b][j].DeTime,graph.matrix[a][b][j].ArTime,graph.matrix[a][b][j].tool); printf("请输入旅客所在城市序号:") ; scanf("%d",&passer.start); passer.finish=passer.start; passer.tool='0'; FileOutput(0); } void change()//时间推进有问题,日志输出有问题,唉, { if(state==1) { if(differtime!=1) { differtime--; passer.start=line2[middle].finish; passer.finish=line2[middle+1].finish; passer.tool=line2[middle+1].tool; FileOutput(0); printf("旅客状态:时间:%d 旅客乘坐%c从%d到%d\n",currenttime%24,passer.tool,passer.start,passer.finish); }//旅行状态 else { state=0; middle++; } } if(state==0) { passer.finish=line2[middle].finish; passer.start=line2[middle].finish; FileOutput(0); printf("旅客状态:时间:%d 当前所在城市:%d\n",currenttime%24,passer.start); if(middle==ll) { ll=0; middle=0; ffflag=1; flag=1; }//这次旅行结束 else if((currenttime%24)==line2[middle+1].Detime) { state=1; if(line2[middle+1].Detime<line2[middle+1].Artime) differtime=line2[middle+1].Artime-line2[middle+1].Detime; else differtime=24+line2[middle+1].Artime-line2[middle+1].Detime; } }//等待状态 fffflag=0; } unsigned __stdcall fnInput(void* pArguments) { char ch; printf("P:输入旅行计划,Q:查询旅客当前状态,E:结束旅行\n请输入当前操作"); while(1) { scanf("%c",&ch); if(ch=='P') { int finish,str,time=0; struct order *node; printf("输入城市:"); scanf("%d",&finish); printf("输入策略:") ; scanf("%d",&str); if(str==1) { printf("输入限制时间:"); scanf("%d",&time); } node=(order*)malloc(sizeof(order)); node->finish=finish;node->strategy=str;node->TimeLimit=time; if(command==NULL) { command=node; end=command; } else { end->nextorder=node; end=node; } end->nextorder=NULL; } if (ch=='Q') { printf("旅客状态:时间:%d",(currenttime%24)); if(passer.start==passer.finish) printf("当前所在城市:%d\n",passer.start); else printf("旅客乘坐%c从%d到%d\n",passer.tool,passer.start,passer.finish); } if(ch=='E') over=1; } _endthreadex(0); return 0; } void _time() { time_t tfinish = clock(); double duration = (double)(tfinish - start) ; if(((int)duration-2000*((int)duration/2000))<=2) { ptime++; if(ptime==300) { currenttime++; //printf("%d ",currenttime); fffflag=1; ptime=1; } }//1s加一 }//计时模块 void ordersolve() { if(ffflag==1) { struct order *node; node =command; command=command->nextorder; delete(node); ffflag=0; }//删除头节点 } void fnTimeTick() { ordersolve();//命令链表处理函数 if(command!=NULL&&fflag==1) { start=clock(); st=1; fflag=0; flag=1; } if(st==1) _time(); if(command!=NULL&&flag==1) { FileOutput(1); design();//设计路线 flag=0; printf("旅客从%d到%d的路线为:\n",passer.start,command->finish); printf("起始站:%d 出发时间:%d 交通工具:%c\n",line2[0].finish,line2[1].Detime,line2[1].tool); for(int i=1;i<ll;i++) printf("中间站:%d 交通工具:%c 到达时间:%d 再出发时间:%d\n",line2[i].finish,line2[i+1].tool,line2[i].Artime,line2[i+1].Detime);//再次出发时间:没有赋值 printf("终点站:%d 到达时间:%d\n",line2[ll].finish,line2[ll].Artime); } if(command!=NULL&&fffflag==1) change();//时间推进,状态变化 }
#include "reportwidget.h" ReportDialog::ReportDialog(QWidget *parent) :QDialog(parent) { }
/* ** EPITECH PROJECT, 2018 ** cpp_indie_studio ** File description: ** Point.cpp */ #include "Point.hpp" #include "Direction.hpp" #include <cmath> Point::Point() : Point(0, 0) {} Point::Point(int x, int y) : _x(x), _y(y) {} std::array<int, 2> Point::operator*() const noexcept { return getArray(); } bool Point::operator<(Point const & rhs) const noexcept { return _x * _x + _y * _y < rhs._x * rhs._x + rhs._y * rhs._y; } bool Point::operator>(Point const & rhs) const noexcept { return rhs < *this; } bool Point::operator<=(Point const & rhs) const noexcept { return !(rhs < *this); } bool Point::operator>=(Point const & rhs) const noexcept { return !(*this < rhs); } bool Point::operator==(Point const & rhs) const noexcept { return _x == rhs._x && _y == rhs._y; } bool Point::operator!=(Point const & rhs) const noexcept { return !(*this == rhs); } Point Point::operator+(Point const & rhs) const noexcept { return { _x + rhs._x, _y + rhs._y }; } Point Point::operator-(Point const & rhs) const noexcept { return { _x - rhs._x, _y - rhs._y }; } Point Point::operator*(Point const & rhs) const noexcept { return { _x * rhs._x, _y * rhs._y }; } Point Point::operator/(Point const & rhs) const noexcept { int x = rhs._x == 0 ? 0 : _x / rhs._x; int y = rhs._y == 0 ? 0 : _y / rhs._y; return { x, y }; } Point & Point::operator+=(Point const & rhs) noexcept { _x += rhs._x; _y += rhs._y; return *this; } Point & Point::operator-=(Point const & rhs) noexcept { _x -= rhs._x; _y -= rhs._y; return *this; } Point & Point::operator*=(Point const & rhs) noexcept { _x *= rhs._x; _y *= rhs._y; return *this; } Point & Point::operator/=(Point const & rhs) noexcept { _x /= rhs._x; _y /= rhs._y; return *this; } std::array<int, 2> Point::getArray() const noexcept { std::array<int, 2> arr; arr[0] = _x; arr[1] = _y; return arr; } int Point::x(void) const noexcept { return getX(); } int Point::y(void) const noexcept { return getY(); } int Point::getX(void) const noexcept { return _x; } int Point::getY(void) const noexcept { return _y; } void Point::setX(int x) noexcept { _x = x; } void Point::setY(int y) noexcept { _y = y; } void Point::incX(int inc) noexcept { _x += inc; } void Point::incY(int inc) noexcept { _y += inc; } void Point::move(Direction const & dir) noexcept { move(dir, 1); } void Point::move(Direction const & dir, int inc) noexcept { *this = dir.move(*this, inc); } Point Point::moveAt(Direction const & dir) const noexcept { return moveAt(dir, 1); } Point Point::moveAt(Direction const & dir, int inc) const noexcept { return dir.move(*this, inc); } std::ostream & operator<<(std::ostream & os, Point const & point) { os << "{ " << point.x() << " ; " << point.y() << " }"; return os; } size_t Point::getLength() const noexcept { return std::sqrt(_x * _x + _y * _y); } Point Point::operator+(int const &rhs) const noexcept { return *this + Point(rhs, rhs); } Point Point::operator-(int const &rhs) const noexcept { return *this - Point(rhs, rhs); } Point Point::operator*(int const &rhs) const noexcept { return *this * Point(rhs, rhs); } Point Point::operator/(int const &rhs) const noexcept { return *this / Point(rhs, rhs); } Point &Point::operator+=(int const &rhs) noexcept { *this += Point(rhs, rhs); return *this; } Point &Point::operator-=(int const &rhs) noexcept { *this -= Point(rhs, rhs); return *this; } Point &Point::operator*=(int const &rhs) noexcept { *this *= Point(rhs, rhs); return *this; } Point &Point::operator/=(int const &rhs) noexcept { *this /= Point(rhs, rhs); return *this; }
#include <stdio.h> #include "pico/stdlib.h" #include "hardware/gpio.h" #include "hardware/adc.h" #include "hardware/i2c.h" #include "pico/binary_info.h" #include "pico_display.hpp" #include "MLX90640_API.h" #include <sstream> #include <iomanip> #include <cmath> #include <cfloat> using namespace pimoroni; #define CAM_ON struct Color { constexpr Color(uint8_t r, uint8_t g, uint8_t b) : r(r), g(g), b(b) {} uint8_t r; uint8_t g; uint8_t b; }; // --- CONSTANTS // I2C constexpr uint I2CBaudRate = 1000 * 1000; // Will break ThermalCameraFrameDurationUs if not 1 MHz // Thermal Camera constexpr uint8_t ThermalCameraI2CAddress = 0x33; constexpr uint8_t ThermalCameraWidth = 24; constexpr uint8_t ThermalCameraHeight = 32; constexpr uint8_t ThermalCameraFPS = 4; constexpr int64_t ThermalCameraFrameDurationUs = I2CBaudRate / ThermalCameraFPS; constexpr size_t ThermalCameraEEPROMDataSize = 832; constexpr size_t ThermalCameraFrameDataSize = 834; constexpr int32_t TemperatureSensorWidth = 24; constexpr int32_t TemperatureSensorHeight = 32; constexpr int32_t FinalTemperatureDataSize = TemperatureSensorWidth * TemperatureSensorHeight; constexpr int32_t NearestScaleMult = 4; constexpr int32_t HeatmapTopOffsetPixels = 3; constexpr int32_t TextXOffset = NearestScaleMult * TemperatureSensorWidth + 4; constexpr int32_t TextYOffset = HeatmapTopOffsetPixels; constexpr float HeatmapDeltaMultiplier = 0.000002f; struct ShortColor3 { constexpr ShortColor3(int16_t r, int16_t g, int16_t b) : r(r), g(g), b(b) {} int16_t r; int16_t g; int16_t b; }; constexpr std::array<ShortColor3, 7> HeatmapColors = { ShortColor3( 0, 0, 0), ShortColor3( 0, 0, 255), ShortColor3( 0, 255, 0), ShortColor3(255, 255, 0), ShortColor3(255, 0, 0), ShortColor3(255, 0, 255), ShortColor3(255, 255, 255), }; constexpr size_t lastColorID = HeatmapColors.size() - 1; // ADC/Battery constexpr float BatteryConversionFactor = 3 * 3.3f / (1 << 12); constexpr uint8_t BatteryVoltagePin = 29; constexpr uint8_t ADCInputID = 3; // 0..3, which corresponds to pins 26..29 const Point BatteryTextOrigin(TextXOffset, TextYOffset); // USB constexpr uint8_t USBConnectedPin = 24; constexpr int32_t TextLineHeight = 7; const Point USBTextOrigin(TextXOffset, TextLineHeight + TextYOffset); const std::string UsbConnectedTxt = "USB Power"; const std::string UsbDiconnectedTxt = "Battery Power"; // UI const std::string HoldX = "Hold X - Mark Min (White)"; const std::string HoldY = "Hold Y - Mark Max (Black)"; const std::string PressA = "Hold A + X|Y - Heatmap Min"; const std::string PressB = "Hold B + X|Y - Heatmap Max"; // --- CONSTANTS END // Globals std::array<uint16_t, PicoDisplay::WIDTH * PicoDisplay::HEIGHT> displayBuffer; PicoDisplay display(displayBuffer.data()); std::array<uint16_t, ThermalCameraEEPROMDataSize> cameraEEPROMData; std::array<uint16_t, ThermalCameraFrameDataSize> cameraFrameData; std::array<float, FinalTemperatureDataSize> finalTemperatureData; std::array<Pen, FinalTemperatureDataSize> heatmapPixels; float heatmapMin = 5; float heatmapMax = 50; float emissivity = 1; void CrashWithError(const char* error, int errorCode) { const Point errorMessageOrigin(0, 0); char buffer[512] = {}; sprintf(buffer, "%s: %d", error, errorCode); const std::string errorString = buffer; while (true) { display.set_pen(255, 0, 0); display.clear(); display.set_pen(0, 0, 255); display.text(errorString, errorMessageOrigin, 255, 2); printf(errorString.data()); printf("\n"); display.update(); sleep_ms(500); } } inline Color TemperatureToHeatmap(float value, const float heatmapRange, PicoDisplay& display) { value -= heatmapMin; value /= heatmapRange; float lerpDist = 0; size_t p0ID; size_t p1ID; if (value <= 0) { p0ID = 0; p1ID = 0; } else if (value >= 1) { p0ID = lastColorID; p1ID = lastColorID; } else { value *= lastColorID; p0ID = std::floor(value); p1ID = p0ID + 1; lerpDist = value - static_cast<float>(p0ID); } const uint8_t r = ((HeatmapColors[p1ID].r - HeatmapColors[p0ID].r) * lerpDist) + HeatmapColors[p0ID].r; const uint8_t g = ((HeatmapColors[p1ID].g - HeatmapColors[p0ID].g) * lerpDist) + HeatmapColors[p0ID].g; const uint8_t b = ((HeatmapColors[p1ID].b - HeatmapColors[p0ID].b) * lerpDist) + HeatmapColors[p0ID].b; return Color(r, g, b); } int main() { bi_decl(bi_program_description("Pico Thermal Camera")); stdio_init_all(); adc_init(); adc_gpio_init(BatteryVoltagePin); adc_select_input(ADCInputID); gpio_init(USBConnectedPin); gpio_set_dir(USBConnectedPin, GPIO_IN); i2c_init(i2c_default, I2CBaudRate); gpio_set_function(PICO_DEFAULT_I2C_SDA_PIN, GPIO_FUNC_I2C); gpio_set_function(PICO_DEFAULT_I2C_SCL_PIN, GPIO_FUNC_I2C); gpio_pull_up(PICO_DEFAULT_I2C_SDA_PIN); gpio_pull_up(PICO_DEFAULT_I2C_SCL_PIN); display.init(); display.set_backlight(100); sleep_ms(2000); printf("Starting...\n"); #ifdef CAM_ON uint8_t fpsModeID = 0; switch(ThermalCameraFPS){ case 1: fpsModeID = 0x01; break; case 2: fpsModeID = 0x02; break; case 4: fpsModeID = 0x03; break; case 8: fpsModeID = 0x04; break; case 16: fpsModeID = 0x05; break; case 32: fpsModeID = 0x06; break; case 64: fpsModeID = 0x07; break; default: CrashWithError("Unsupported FPS value", 0); } const int fpsModeResult = MLX90640_SetRefreshRate(ThermalCameraI2CAddress, fpsModeID); if (fpsModeResult != 0) { CrashWithError("Failed to set the camera refresh rate", fpsModeResult); } const int chessModeResult = MLX90640_SetChessMode(ThermalCameraI2CAddress); if (chessModeResult != 0) { CrashWithError("Failed to set the camera to chess mode", chessModeResult); } const int eeDumpResult = MLX90640_DumpEE(ThermalCameraI2CAddress, cameraEEPROMData.data()); if (eeDumpResult != 0) { CrashWithError("Failed to dump camera eeprom data", eeDumpResult); } uint16_t hey = 64; printf("HEY: %d\n\n", hey); for (size_t b = 0; b < cameraFrameData.size(); ++b) { //printf("0x%04d ", cameraFrameData[b]); printf("%d", cameraFrameData[b]); if ((b + 1) % 8 == 0) { printf("\n"); } } paramsMLX90640 mlx90640Params; const int paramExtractResult = MLX90640_ExtractParameters(cameraEEPROMData.data(), &mlx90640Params); if (paramExtractResult != 0) { CrashWithError("Problems when parsing camera eeprom data", paramExtractResult); } #endif // CAM_ON const Pen textColor = display.create_pen(0, 255, 0); const Pen whitePen = display.create_pen(255, 255, 255); const Pen blackPen = display.create_pen( 0, 0, 0); int64_t lastSleepDuration = 0; uint64_t iter = 0; bool xPressed = false; bool yPressed = false; bool aPressed = false; bool bPressed = false; bool xPressedLastTime = false; bool yPressedLastTime = false; bool aPressedLastTime = false; bool bPressedLastTime = false; absolute_time_t previous = get_absolute_time(); while (true) { const absolute_time_t start = get_absolute_time(); const int64_t deltaFrame = absolute_time_diff_us(start, previous); previous = start; xPressed = display.is_pressed(PicoDisplay::X); yPressed = display.is_pressed(PicoDisplay::Y); aPressed = display.is_pressed(PicoDisplay::A); bPressed = display.is_pressed(PicoDisplay::B); display.set_pen(120, 40, 60); display.clear(); const uint16_t rawADC = adc_read(); const float voltage = static_cast<float>(rawADC) * BatteryConversionFactor; display.set_pen(textColor); std::stringstream ss; ss << std::fixed << std::setprecision(3) << voltage << "V"; iter++; const std::string voltageStr = ss.str(); display.text(voltageStr, BatteryTextOrigin, 255, 1); if (gpio_get(USBConnectedPin)) { display.text(UsbConnectedTxt, USBTextOrigin, 255, 1); } else { display.text(UsbDiconnectedTxt, USBTextOrigin, 255, 1); } #ifdef CAM_ON const int frameDataFetchResult = MLX90640_GetFrameData(ThermalCameraI2CAddress, cameraFrameData.data()); if (frameDataFetchResult < 0) { display.update(); CrashWithError("Failed to get the frame data", frameDataFetchResult); } const float ta = MLX90640_GetTa(cameraFrameData.data(), &mlx90640Params); MLX90640_CalculateTo(cameraFrameData.data(), &mlx90640Params, emissivity, ta, finalTemperatureData.data()); MLX90640_BadPixelsCorrection((&mlx90640Params)->brokenPixels, finalTemperatureData.data(), 1, &mlx90640Params); MLX90640_BadPixelsCorrection((&mlx90640Params)->outlierPixels, finalTemperatureData.data(), 1, &mlx90640Params); const float heatmapRange = heatmapMax - heatmapMin; float minTemp = FLT_MAX; Point minTempPixel; float maxTemp = -FLT_MIN; Point maxTempPixel; if (!(aPressed && bPressed)) { if (aPressed && xPressed) { heatmapMin += HeatmapDeltaMultiplier * deltaFrame; } else if (aPressed && yPressed) { heatmapMin -= HeatmapDeltaMultiplier * deltaFrame; } if (bPressed && xPressed) { heatmapMax += HeatmapDeltaMultiplier * deltaFrame; } else if (bPressed && yPressed) { heatmapMax -= HeatmapDeltaMultiplier * deltaFrame; } } float temperatureSum = 0.0f; for (size_t x = 0; x < TemperatureSensorWidth; ++x) { for (size_t y = 0; y < TemperatureSensorHeight; ++y) { float value = finalTemperatureData[TemperatureSensorHeight * (TemperatureSensorWidth - 1 - x) + y]; temperatureSum += value; if (value < minTemp) { minTemp = value; minTempPixel = Point(x, y); } if (value > maxTemp) { maxTemp = value; maxTempPixel = Point(x, y); } const Color color = TemperatureToHeatmap(value, heatmapRange, display); heatmapPixels[y * TemperatureSensorWidth + x] = display.create_pen(color.r, color.g, color.b); } } const float temperatureAverage = temperatureSum / FinalTemperatureDataSize; const Color avgColor = TemperatureToHeatmap(temperatureAverage, heatmapRange, display); // Full brightness LED is blinding in a dark room and makes looking at the screen painful constexpr uint8_t brightnessDivisor = 3; display.set_led(avgColor.r / brightnessDivisor, avgColor.g / brightnessDivisor, avgColor.b / brightnessDivisor); if (xPressed && !(aPressed || bPressed)) { heatmapPixels[minTempPixel.y * TemperatureSensorWidth + minTempPixel.x] = whitePen; } if (yPressed && !(aPressed || bPressed)) { heatmapPixels[maxTempPixel.y * TemperatureSensorWidth + maxTempPixel.x] = blackPen; } for (int32_t x = 0; x < TemperatureSensorWidth; ++x) { for (int32_t y = 0; y < TemperatureSensorHeight; ++y) { const Pen p = heatmapPixels[y * TemperatureSensorWidth + x]; for (int32_t r = 0; r < NearestScaleMult; ++r) { display.set_pen(p); display.pixel_span(Point(x * NearestScaleMult, (y * NearestScaleMult) + HeatmapTopOffsetPixels + r), NearestScaleMult); } } } display.set_pen(textColor); int32_t infoYOffset = USBTextOrigin.y + TextLineHeight * 2; char minValText[64]; sprintf(minValText, "Min: %.2fC", minTemp); display.text(minValText, Point(TextXOffset, infoYOffset), 255, 1); infoYOffset += TextLineHeight; char minValTextPixel[64]; sprintf(minValTextPixel, "Min Pixel: %d %d", minTempPixel.x, minTempPixel.y); display.text(minValTextPixel, Point(TextXOffset, infoYOffset), 255, 1); infoYOffset += TextLineHeight; display.text(HoldX, Point(TextXOffset, infoYOffset), 255, 1); infoYOffset += TextLineHeight * 2; char maxValText[64]; sprintf(maxValText, "MAX: %.2fC", maxTemp); display.text(maxValText, Point(TextXOffset, infoYOffset), 255, 1); infoYOffset += TextLineHeight; char maxValTextPixel[64]; sprintf(maxValTextPixel, "Max Pixel: %d %d", maxTempPixel.x, maxTempPixel.y); display.text(maxValTextPixel, Point(TextXOffset, infoYOffset), 255, 1); infoYOffset += TextLineHeight; display.text(HoldY, Point(TextXOffset, infoYOffset), 255, 1); infoYOffset += TextLineHeight * 2; char avgText[64]; sprintf(avgText, "Avgerage (LED): %.2fC", temperatureAverage); display.text(avgText, Point(TextXOffset, infoYOffset), 255, 1); infoYOffset += TextLineHeight * 2; char heatmapMinText[64]; sprintf(heatmapMinText, "Heatmap Min: %.2f", heatmapMin); display.text(heatmapMinText, Point(TextXOffset, infoYOffset), 255, 1); infoYOffset += TextLineHeight; display.text(PressA, Point(TextXOffset, infoYOffset), 255, 1); infoYOffset += TextLineHeight * 2; char heatmapMaxText[64]; sprintf(heatmapMaxText, "Heatmap Max: %.2f", heatmapMax); display.text(heatmapMaxText, Point(TextXOffset, infoYOffset), 255, 1); infoYOffset += TextLineHeight; display.text(PressB, Point(TextXOffset, infoYOffset), 255, 1); infoYOffset += TextLineHeight * 2; #endif // CAM_ON display.update(); xPressedLastTime = xPressed; yPressedLastTime = yPressed; aPressedLastTime = aPressed; bPressedLastTime = bPressed; const absolute_time_t end = get_absolute_time(); const int64_t durationDeltaUs = absolute_time_diff_us(start, end); lastSleepDuration = ThermalCameraFrameDurationUs - durationDeltaUs; if (lastSleepDuration > 0) { sleep_us(lastSleepDuration); } else { lastSleepDuration = 0; } } }
#ifndef TOOLS_H #define TOOLS_H #include <QObject> #include <QJsonDocument> #include <QAbstractListModel> class Tools : public QObject { Q_OBJECT public: explicit Tools(QObject *parent = 0); Q_INVOKABLE void saveJson(const QString& title, int maxCount, int concentration, QAbstractListModel * model); Q_INVOKABLE QString applicationPath(); Q_INVOKABLE QString version(); }; #endif // TOOLS_H
// MainFrm.cpp : CMainFrame #include "stdafx.h" #include "KEGIES.h" #include "KEGIESDoc.h" #include "MainFrm.h" #include "Dialog.h" #include "SkeletonWindow.h" #include "InputMeshWindow.h" #include "AnimationWindow.h" #include "SuggestionsView.h" #include <iostream> #ifdef _DEBUG #define new DEBUG_NEW #endif IMPLEMENT_DYNCREATE(CMainFrame, CFrameWnd) BEGIN_MESSAGE_MAP(CMainFrame, CFrameWnd) ON_WM_CREATE() ON_WM_MENUSELECT() ON_UPDATE_COMMAND_UI(ID_SPECIAL_F1, &CMainFrame::OnUpdateSpecialF) ON_UPDATE_COMMAND_UI(ID_SPECIAL_F2, &CMainFrame::OnUpdateSpecialF) ON_UPDATE_COMMAND_UI(ID_SPECIAL_F3, &CMainFrame::OnUpdateSpecialF) ON_UPDATE_COMMAND_UI(ID_SPECIAL_F4, &CMainFrame::OnUpdateSpecialF) ON_UPDATE_COMMAND_UI(ID_SPECIAL_F5, &CMainFrame::OnUpdateSpecialF) ON_UPDATE_COMMAND_UI(ID_SPECIAL_F6, &CMainFrame::OnUpdateSpecialF) ON_UPDATE_COMMAND_UI(ID_SPECIAL_F7, &CMainFrame::OnUpdateSpecialF) ON_UPDATE_COMMAND_UI(ID_SPECIAL_F8, &CMainFrame::OnUpdateSpecialF) ON_UPDATE_COMMAND_UI(ID_SPECIAL_F9, &CMainFrame::OnUpdateSpecialF) ON_UPDATE_COMMAND_UI(ID_SPECIAL_F10, &CMainFrame::OnUpdateSpecialF) ON_UPDATE_COMMAND_UI(ID_SIDEDIALOG_HIDE, &CMainFrame::OnUpdateSidedialogMenu) ON_UPDATE_COMMAND_UI(ID_SIDEDIALOG_LEFT, &CMainFrame::OnUpdateSidedialogMenu) ON_UPDATE_COMMAND_UI(ID_SIDEDIALOG_RIGHT, &CMainFrame::OnUpdateSidedialogMenu) ON_BN_CLICKED(IDOK, &CMainFrame::OnBnClickedOk) ON_BN_CLICKED(IDC_BUTTON1, &CMainFrame::OnBnClickedButton1) ON_MESSAGE(WM_TEST, &CKEGIESView::OnData) END_MESSAGE_MAP() static UINT indicators[] = { ID_SEPARATOR, ID_INDICATOR_CAPS, ID_INDICATOR_NUM, ID_INDICATOR_SCRL, ID_INDICATOR_EXT, }; CMainFrame::CMainFrame() { } CMainFrame::~CMainFrame() { } // Creating the general UI int CMainFrame::OnCreate(LPCREATESTRUCT lpCreateStruct) { if (CFrameWnd::OnCreate(lpCreateStruct) == -1){ return -1; } if (!m_wndToolBar.CreateEx(this, TBSTYLE_FLAT, WS_CHILD | WS_VISIBLE | CBRS_TOP | CBRS_GRIPPER | CBRS_TOOLTIPS | CBRS_FLYBY | CBRS_SIZE_DYNAMIC) || !m_wndToolBar.LoadToolBar(IDR_MAINFRAME)) { TRACE0("Error toolbar 1\n"); return -1; } if (!m_wndStatusBar.Create(this) || !m_wndStatusBar.SetIndicators(indicators, sizeof(indicators)/sizeof(UINT))) { TRACE0("Error toolbar 2\n"); return -1; } m_wndStatusBar.SetPaneInfo(4, ID_TIMER_STATUS, SBPS_NORMAL, 60); m_wndStatusBar.SetPaneText(4, _T("Stopped")); CRect rect; int nIndex = m_wndToolBar.GetToolBarCtrl().CommandToIndex(IDD_EDIT_BOX_1); m_wndToolBar.SetButtonInfo(nIndex, IDD_EDIT_BOX_1, TBBS_SEPARATOR, 30); m_wndToolBar.GetToolBarCtrl().GetItemRect(nIndex, &rect); m_edit1.Create(WS_VISIBLE, rect, &m_wndToolBar, IDD_EDIT_BOX_1); nIndex = m_wndToolBar.GetToolBarCtrl().CommandToIndex(IDD_EDIT_BOX_2); m_wndToolBar.SetButtonInfo(nIndex, IDD_EDIT_BOX_2, TBBS_SEPARATOR, 30); m_wndToolBar.GetToolBarCtrl().GetItemRect(nIndex, &rect); m_edit2.Create(WS_VISIBLE, rect, &m_wndToolBar, IDD_EDIT_BOX_2); m_wndToolBar.EnableDocking(CBRS_ALIGN_ANY); EnableDocking(CBRS_ALIGN_ANY); DockControlBar(&m_wndToolBar); sideDlg.init(this); return 0; } BOOL CMainFrame::PreCreateWindow(CREATESTRUCT& cs) { if( !CFrameWnd::PreCreateWindow(cs) ) return FALSE; // TODO: CREATESTRUCT return TRUE; } #ifdef _DEBUG void CMainFrame::AssertValid() const { CFrameWnd::AssertValid(); } void CMainFrame::Dump(CDumpContext& dc) const { CFrameWnd::Dump(dc); } #endif //_DEBUG void CMainFrame::OnMenuSelect(UINT nItemID, UINT nFlags, HMENU hSysMenu) { CFrameWnd::OnMenuSelect(nItemID, nFlags, hSysMenu); } void CMainFrame::OnUpdateSpecialF(CCmdUI *pCmdUI) { // TODO: Add your command update UI handler code here CKEGIESDoc* doc = (CKEGIESDoc*)GetActiveDocument(); CString title = _T("Unused"); pCmdUI->Enable(FALSE); pCmdUI->SetText(title); } void CMainFrame::OnUpdateSidedialogMenu(CCmdUI *pCmdUI) { switch(pCmdUI->m_nIndex){ case 0: sideDlg.OnUpdateSidedialogHide(pCmdUI); break; case 2: sideDlg.OnUpdateSidedialogLeft(pCmdUI); break; case 3: sideDlg.OnUpdateSidedialogRight(pCmdUI); break; } } BOOL CMainFrame::PreTranslateMessage(MSG* pMsg) { // TODO: Add your specialized code here and/or call the base class int nItemID = pMsg->wParam; CKEGIESDoc* doc = (CKEGIESDoc*)GetActiveDocument(); // Special menu function // for (int i = 0; i< 10; i++) // { // if (nItemID == ID_SPECIAL_F1 + i) // { // doc->document->specialMenuFunction(nItemID); // break; // } // } // Side dialog view switch(nItemID) { case ID_SIDEDIALOG_HIDE: sideDlg.OnSidedialogHide(); break; case ID_SIDEDIALOG_LEFT: sideDlg.OnSidedialogLeft(); break; case ID_SIDEDIALOG_RIGHT: sideDlg.OnSidedialogRight(); break; } return CFrameWnd::PreTranslateMessage(pMsg); } void CMainFrame::setStatusBar( CString status, int index ) { m_wndStatusBar.SetPaneText(index, status); } void CMainFrame::timerUpdate( bool start ) { setStatusBar(start? _T("Running..."):_T("Stopped"), 4); CToolBarCtrl& Toolbar = m_wndToolBar.GetToolBarCtrl(); CImageList *pList = Toolbar.GetImageList(); HICON hIcon = LoadIcon(AfxGetInstanceHandle(), MAKEINTRESOURCE(start? ID_ICON_PAUSE:ID_ICON_PLAY)); pList->Replace(5, hIcon); m_wndToolBar.Invalidate(); } void CMainFrame::OnBnClickedOk() { // TODO: Add your control notification handler code here } void CMainFrame::OnBnClickedButton1() { // TODO: Add your control notification handler code here TRACE(_T("dfdfdfdfdfdf\n")); } // Creates the split window view BOOL CMainFrame::OnCreateClient(LPCREATESTRUCT lpcs, CCreateContext* pContext) { int ncwidth = 1200; int ncheight = 600; // Set up the splitter window interface if (!m_mainWndSplitter.CreateStatic(this, 1, 2)){ return FALSE; } m_mainWndSplitter.SetColumnInfo(0, ncwidth*0.6, ncwidth*0.1); m_mainWndSplitter.SetColumnInfo(1, ncwidth*0.4, ncwidth*0.1); // Create left views if (!m_mainLeftWndSplitter.CreateStatic(&m_mainWndSplitter, 2, 1, WS_CHILD | WS_VISIBLE, m_mainWndSplitter.IdFromRowCol(0, 0))){ return FALSE; } m_mainLeftWndSplitter.SetRowInfo(0, ncheight*0.25, ncheight*0.1); m_mainLeftWndSplitter.SetRowInfo(1, ncheight*0.75, ncheight*0.1); m_mainLeftWndSplitter.SetColumnInfo(0, ncwidth*0.75, ncwidth*0.1); if (!m_mainLeftWndSplitter.CreateView(0, 0, RUNTIME_CLASS(SuggestionsView), CSize(ncwidth*0.5, ncheight*0.2), pContext) || !m_mainLeftWndSplitter.CreateView(1, 0, RUNTIME_CLASS(InputMeshWindow), CSize(ncwidth*0.5, ncheight*0.8), pContext)){ m_mainLeftWndSplitter.DestroyWindow(); return FALSE; } // Create right views if (!m_subWndSplitter.CreateStatic(&m_mainWndSplitter, 2, 1, WS_CHILD | WS_VISIBLE, m_mainWndSplitter.IdFromRowCol(0, 1))){ return FALSE; } m_subWndSplitter.SetRowInfo(0, ncheight*0.5, ncheight*0.1); m_subWndSplitter.SetRowInfo(1, ncheight*0.5, ncheight*0.1); m_subWndSplitter.SetColumnInfo(0, ncwidth*0.25, ncwidth*0.1); if (!m_subWndSplitter.CreateView(0, 0, RUNTIME_CLASS(SkeletonWindow), CSize(ncwidth*0.5, ncheight*0.6), pContext) || !m_subWndSplitter.CreateView(1, 0, RUNTIME_CLASS(AnimationWindow), CSize(ncwidth*0.5, ncheight*0.4), pContext)){ m_subWndSplitter.DestroyWindow(); return FALSE; } m_mainLeftWndSplitter.RecalcLayout(); m_subWndSplitter.RecalcLayout(); return TRUE; }
/* * cTestAD.cpp * * Created on: 2018年7月19日 * Author: tarena */ #include "cTestAD.h" static const char *s_addev = "/dev/ttyS5"; //不需要数据 static unsigned char crc_array[256] = { 0x00, 0x5e, 0xbc, 0xe2, 0x61, 0x3f, 0xdd, 0x83, 0xc2, 0x9c, 0x7e, 0x20, 0xa3, 0xfd, 0x1f, 0x41, 0x9d, 0xc3, 0x21, 0x7f, 0xfc, 0xa2, 0x40, 0x1e, 0x5f, 0x01, 0xe3, 0xbd, 0x3e, 0x60, 0x82, 0xdc, 0x23, 0x7d, 0x9f, 0xc1, 0x42, 0x1c, 0xfe, 0xa0, 0xe1, 0xbf, 0x5d, 0x03, 0x80, 0xde, 0x3c, 0x62, 0xbe, 0xe0, 0x02, 0x5c, 0xdf, 0x81, 0x63, 0x3d, 0x7c, 0x22, 0xc0, 0x9e, 0x1d, 0x43, 0xa1, 0xff, 0x46, 0x18, 0xfa, 0xa4, 0x27, 0x79, 0x9b, 0xc5, 0x84, 0xda, 0x38, 0x66, 0xe5, 0xbb, 0x59, 0x07, 0xdb, 0x85, 0x67, 0x39, 0xba, 0xe4, 0x06, 0x58, 0x19, 0x47, 0xa5, 0xfb, 0x78, 0x26, 0xc4, 0x9a, 0x65, 0x3b, 0xd9, 0x87, 0x04, 0x5a, 0xb8, 0xe6, 0xa7, 0xf9, 0x1b, 0x45, 0xc6, 0x98, 0x7a, 0x24, 0xf8, 0xa6, 0x44, 0x1a, 0x99, 0xc7, 0x25, 0x7b, 0x3a, 0x64, 0x86, 0xd8, 0x5b, 0x05, 0xe7, 0xb9, 0x8c, 0xd2, 0x30, 0x6e, 0xed, 0xb3, 0x51, 0x0f, 0x4e, 0x10, 0xf2, 0xac, 0x2f, 0x71, 0x93, 0xcd, 0x11, 0x4f, 0xad, 0xf3, 0x70, 0x2e, 0xcc, 0x92, 0xd3, 0x8d, 0x6f, 0x31, 0xb2, 0xec, 0x0e, 0x50, 0xaf, 0xf1, 0x13, 0x4d, 0xce, 0x90, 0x72, 0x2c, 0x6d, 0x33, 0xd1, 0x8f, 0x0c, 0x52, 0xb0, 0xee, 0x32, 0x6c, 0x8e, 0xd0, 0x53, 0x0d, 0xef, 0xb1, 0xf0, 0xae, 0x4c, 0x12, 0x91, 0xcf, 0x2d, 0x73, 0xca, 0x94, 0x76, 0x28, 0xab, 0xf5, 0x17, 0x49, 0x08, 0x56, 0xb4, 0xea, 0x69, 0x37, 0xd5, 0x8b, 0x57, 0x09, 0xeb, 0xb5, 0x36, 0x68, 0x8a, 0xd4, 0x95, 0xcb, 0x29, 0x77, 0xf4, 0xaa, 0x48, 0x16, 0xe9, 0xb7, 0x55, 0x0b, 0x88, 0xd6, 0x34, 0x6a, 0x2b, 0x75, 0x97, 0xc9, 0x4a, 0x14, 0xf6, 0xa8, 0x74, 0x2a, 0xc8, 0x96, 0x15, 0x4b, 0xa9, 0xf7, 0xb6, 0xe8, 0x0a, 0x54, 0xd7, 0x89, 0x6b, 0x35, }; CTestAD::CTestAD() { // TODO Auto-generated constructor stub } CTestAD::~CTestAD() { // TODO Auto-generated destructor stub } //AD测试 int CTestAD::testAd() { char buffer[1024]={0}; //打开文件 int fd = open(s_addev, O_RDWR|O_NOCTTY|O_NDELAY); if (0 == fd) { printf("ad dev can not open %s\n", s_addev); sprintf(buffer,"ad dev can not open %s",s_addev); sendJSON(DATA,buffer); return -1; } //设置串口文件 if (!setseriopt(fd)) { memset(buffer,0,sizeof(buffer)); sprintf(buffer,"set seriopt error"); sendJSON(DATA,buffer); return -1; } //编写指令 printf("sync now time to stm32\r\n"); vector<char> buf; struct timeval tv; gettimeofday(&tv, NULL); buf.push_back(0x68); buf.push_back(0x9); buf.push_back(0x68); buf.push_back(0x01); buf.push_back(tv.tv_sec); buf.push_back(tv.tv_sec >> 8); buf.push_back(tv.tv_sec >> 16); buf.push_back(tv.tv_sec >> 24); buf.push_back(tv.tv_usec); buf.push_back(tv.tv_usec >> 8); buf.push_back(tv.tv_usec >> 16); buf.push_back(tv.tv_usec >> 24); int cs = 0; //为什么要把所以值都加进去 for (unsigned int i = 0; i != buf.size(); i++) { cs += buf[i]; } buf.push_back(cs % 256); buf.push_back(0x16); //把指令写进去 unsigned int wrSize = write(fd, &buf[0], buf.size()); if (wrSize != buf.size()) { printf("ad uart write error, wrsize is %d, errno is %d", wrSize, errno); memset(buffer,0,sizeof(buffer)); sprintf(buffer,"ad uart write error, wrsize is %d, errno is %d", wrSize, errno); sendJSON(DATA,buffer); close(fd); return -1; } usleep(100 * 1000); printf("begin to read ad data\r\n"); char readTmp[ONE_WAVE_CNT] = {0}; for(int i=0;i<10;) { int flag=0; int ret=spicomm_read(readTmp, sizeof(readTmp)); if (ret != 0) { printf("ad spicomm_read error, read return is %d\r\n", ret); memset(buffer,0,sizeof(buffer)); sprintf(buffer,"ad spicomm_read error, read return is %d\r\n", ret); sendJSON(DATA,buffer); return -1; } bool adValid = false; for (int j = 0; j != 20; j++) { if (readTmp[j] != 0xFF) { adValid = true; break; } } if (!adValid) { flag++; usleep(5 * 1000); continue; } if(flag==10) { printf("AD 10 times unable to read data \n"); memset(buffer,0,sizeof(buffer)); sprintf(buffer,"AD 10 times unable to read data \n"); sendJSON(DATA,buffer); return -1; } i++; } string adTmp; char strTmp[20] = {0}; //读取数据 int Flag=0; memset(buffer,0,sizeof(buffer)); strcpy(buffer,"time : UA UB UC IA IB IC"); sendJSON(DATA,buffer); while(Flag<10) { //c从串口读取数据吗? int ret = spicomm_read(readTmp, sizeof(readTmp)); if (ret != 0) { printf("ad spicomm_read error, read return is %d\r\n", ret); memset(buffer,0,sizeof(buffer)); sprintf(buffer,"ad spicomm_read error, read return is %d\r\n", ret); sendJSON(DATA,buffer); return -1; } bool adValid = false; for (int j = 0; j != 20; j++) { if (readTmp[j] != 0xFF) { adValid = true; break; } } if (!adValid) { usleep(5 * 1000); continue; } //解析与拆分返回来的数据 for(int i=0;i<AD_SAMPLE;i++) { //ua int dataBit=0; int tmp = (readTmp[i*18+dataBit] << 16) | (readTmp[i*18+dataBit+1] << 8) | (readTmp[i*18+dataBit+2]); if ((readTmp[i*18+dataBit] & 0xFC) != 0) { // 负数,计算补码 tmp = ~tmp; tmp &= 0x00FFFFFF; tmp += 1; tmp = -tmp; } sprintf(strTmp, " IA:%d ", tmp); adTmp += strTmp; m_strAdAata[Flag].ia[i]=tmp*CURRENTRATIO; dataBit+=3; //ib tmp = (readTmp[i*18+dataBit] << 16) | (readTmp[i*18+dataBit+1] << 8) | (readTmp[i*18+dataBit+2]); if ((readTmp[i*18+dataBit] & 0xFC) != 0) { // 负数,计算补码 tmp = ~tmp; tmp &= 0x00FFFFFF; tmp += 1; tmp = -tmp; } m_strAdAata[Flag].ib[i]=tmp*CURRENTRATIO; dataBit+=3; //ic tmp = (readTmp[i*18+dataBit] << 16) | (readTmp[i*18+dataBit+1] << 8) | (readTmp[i*18+dataBit+2]); if ((readTmp[i*18+dataBit] & 0xFC) != 0) { // 负数,计算补码 tmp = ~tmp; tmp &= 0x00FFFFFF; tmp += 1; tmp = -tmp; } m_strAdAata[Flag].ic[i]=tmp*CURRENTRATIO; dataBit+=3; //ia tmp = (readTmp[i*18+dataBit] << 16) | (readTmp[i*18+dataBit+1] << 8) | (readTmp[i*18+dataBit+2]); if ((readTmp[i*18+dataBit] & 0xFC) != 0) { // 负数,计算补码 tmp = ~tmp; tmp &= 0x00FFFFFF; tmp += 1; tmp = -tmp; } sprintf(strTmp, " UA:%d ", tmp); adTmp += strTmp; m_strAdAata[Flag].ua[i]=tmp*VOLTAGERATIO; dataBit+=3; //ib tmp = (readTmp[i*18+dataBit] << 16) | (readTmp[i*18+dataBit+1] << 8) | (readTmp[i*18+dataBit+2]); if ((readTmp[i*18+dataBit] & 0xFC) != 0) { // 负数,计算补码 tmp = ~tmp; tmp &= 0x00FFFFFF; tmp += 1; tmp = -tmp; } m_strAdAata[Flag].ub[i]=tmp*VOLTAGERATIO; dataBit+=3; //ic tmp = (readTmp[i*18+dataBit] << 16) | (readTmp[i*18+dataBit+1] << 8) | (readTmp[i*18+dataBit+2]); if ((readTmp[i*18+dataBit] & 0xFC) != 0) { // 负数,计算补码 tmp = ~tmp; tmp &= 0x00FFFFFF; tmp += 1; tmp = -tmp; } m_strAdAata[Flag].uc[i]=tmp*VOLTAGERATIO; } //配置成数据发送 double ua,ub,uc,ia,ib,ic; ua=ub=uc=ia=ib=ic=0; for(int j=0;j<128;j++) { ua+=m_strAdAata[Flag].ua[j]*m_strAdAata[Flag].ua[j]; ub+=m_strAdAata[Flag].ub[j]*m_strAdAata[Flag].ub[j]; uc+=m_strAdAata[Flag].uc[j]*m_strAdAata[Flag].uc[j]; ia+=m_strAdAata[Flag].ia[j]*m_strAdAata[Flag].ia[j]; ib+=m_strAdAata[Flag].ib[j]*m_strAdAata[Flag].ib[j]; ic+=m_strAdAata[Flag].ic[j]*m_strAdAata[Flag].ic[j]; } ua/=(AD_SAMPLE); ub/=(AD_SAMPLE); uc/=(AD_SAMPLE); ia/=(AD_SAMPLE); ib/=(AD_SAMPLE); ic/=(AD_SAMPLE); ua=sqrt(ua); ub=sqrt(ub); uc=sqrt(uc); ia=sqrt(ia); ib=sqrt(ib); ic=sqrt(ic); memset(buffer,0,sizeof(buffer)); sprintf(buffer,"%d : %f %f %f %f %f %f",Flag,ua,ub,uc,ia,ib,ic); printf("AD data:\n%s\n",buffer); sendJSON(DATA,buffer); Flag++; } close(fd); return 0; } //计算开方均根参数得到值 int CTestAD::analyticData() { double ua,ub,uc,ia,ib,ic; ua=ub=uc=ia=ib=ic=0; for(int i=0;i<10;i++) { for(int j=0;j<AD_SAMPLE;j++) { ua+=m_strAdAata[i].ua[j]*m_strAdAata[i].ua[j]; ub+=m_strAdAata[i].ub[j]*m_strAdAata[i].ub[j]; uc+=m_strAdAata[i].uc[j]*m_strAdAata[i].uc[j]; ia+=m_strAdAata[i].ia[j]*m_strAdAata[i].ia[j]; ib+=m_strAdAata[i].ib[j]*m_strAdAata[i].ib[j]; ic+=m_strAdAata[i].ic[j]*m_strAdAata[i].ic[j]; } } ua/=(AD_SAMPLE*10); ub/=(AD_SAMPLE*10); uc/=(AD_SAMPLE*10); ia/=(AD_SAMPLE*10); ib/=(AD_SAMPLE*10); ic/=(AD_SAMPLE*10); ua=sqrt(ua); ub=sqrt(ub); uc=sqrt(uc); ia=sqrt(ia); ib=sqrt(ib); ic=sqrt(ic); char buf[1024]={0}; sprintf(buf,"\nUA:%f UB:%f UC:%f\nIA:%f IB:%f IC:%f",ua,ub,uc,ia,ib,ic); sendJSON(DATA,buf); printf("%s\n",buf); if((ua>200.0)&&(ua<240)&&(ub>200.0)&&(ub<240)&&(uc>200.0)&&(uc<240)) { return 0; } else { return -1; } } //AD测试控制和判断 int CTestAD::test(int sockfd) { char buffer[1024]; printf("Enter the AD test\n"); setFd(sockfd); int Flag=0; if(testAd()!=0) { Flag=-1; } else { if(analyticData()!=0) Flag=-1; } if(Flag!=0) { memset(buffer,0,sizeof(buffer)); strcpy(buffer,"Failure:AD test "); sendJSON(RESULT,buffer); memset(buffer,0,sizeof(buffer)); strcpy(buffer,"AD test end"); sendJSON(END,buffer); return -1; } else { memset(buffer,0,sizeof(buffer)); strcpy(buffer,"Success:AD test"); sendJSON(RESULT,buffer); memset(buffer,0,sizeof(buffer)); strcpy(buffer,"AD test end"); sendJSON(END,buffer); return 0; } } //没实现的功能,不需要了解 unsigned char CTestAD::CRC8_Table(unsigned char *p, int counter) { unsigned char crc8 = 0; for( ; counter > 0; counter--) { crc8 = crc_array[crc8^*p]; //查表得到CRC码 p++; } return crc8; } //设置串口文件 bool CTestAD::setseriopt(int fd) { struct termios options; if (tcgetattr(fd, &options) != 0) { printf("ad dev can not get serial options \r\n"); return false; } // 设置波特率 cfsetispeed(&options, B115200); cfsetospeed(&options, B115200); options.c_cflag |= CLOCAL | CREAD; // 设置数据位 options.c_cflag &= ~CSIZE; options.c_cflag |= CS8; // 设置偶校验位 options.c_cflag |= PARENB; options.c_cflag &= ~PARODD; // 设置停止位 options.c_cflag &= ~CSTOPB; // 修改输出模式,原始数据输出 options.c_oflag &= ~OPOST; options.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON); options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG); // 设置等待时间和最小接收字符 // options.c_cc[VTIME] = 1; /* 读取一个字符等待1*(1/10)s */ // options.c_cc[VMIN] = 1; /* 读取字符的最少个数为1 */ // 如果发生数据溢出,接收数据,但是不再读取 刷新收到的数据但是不读 tcflush(fd,TCIFLUSH); if (tcsetattr(fd, TCSANOW, &options) != 0) { printf("ad dev can not set serial options \r\n"); return false; } return true; }
// // proj09_main.cpp // // Created by Kristjan von Bulow. // Copyright © 2018 Kristjan von Bulow. All rights reserved. // #include<iostream> using std::cout; using std::endl; #include<vector> using std::vector; #include<string> using std::string; #include<sstream> using std::ostringstream; #include<iterator> using std::ostream_iterator; using std::back_inserter; #include<algorithm> using std::copy; using std::upper_bound; using std::find; #include<initializer_list> using std::initializer_list; #include "proj09_trimap.h" int main(){ // used for testing TriMap m; m.insert("w","x"); m.insert("c", "d"); m.insert("a","b"); m.insert("y","z"); bool result = m.remove("c"); ostringstream oss; oss << m; string s = oss.str(); cout << s << endl; return 0; }
#include "client.h" using namespace std; Client::Client() : m_sock(0), m_sockMusique(0), m_port(0), m_portMusique(0), m_ipServeur(0), m_pseudo(0), m_message(0), m_pseudoServeur(0), m_buffer(0), m_bufferMusique(0), m_resultat(0), m_erreur(0) { m_erreur = new int; m_resultat = new int; m_bufferMusique = new char[NOMBRE_OCTET]; m_buffer = new char[NOMBRE_OCTET]; m_pseudoServeur = new char[30]; m_message = new string; m_pseudo = new string; m_ipServeur = new string; m_portMusique = new u_short; m_port = new u_short; m_sock = new SOCKET; m_sockMusique = new SOCKET; *m_erreur = 0; *m_resultat = 0; *m_pseudo = DEFAULT_PSEUDO; *m_ipServeur = DEFAULT_IP; *m_portMusique = DEFAULT_PORT_MUSIQUE; *m_port = DEFAULT_PORT; WSADATA WSAData; if (WSAStartup(MAKEWORD(2, 0), &WSAData) != 0) { cout << "Erreur de la fonction WSAStarup dans le constructeur de la classe client" << endl; *m_erreur = WSAGetLastError(); cout << "Erreur " << *m_erreur << endl; } *m_sock = socket(AF_INET, SOCK_STREAM, 0); m_sin.sin_addr.s_addr = inet_addr(m_ipServeur[0].c_str()); m_sin.sin_family = AF_INET; m_sin.sin_port = htons(*m_port); *m_sockMusique = socket(AF_INET, SOCK_STREAM, 0); m_sinMusique.sin_addr.s_addr = inet_addr(m_ipServeur[0].c_str()); m_sinMusique.sin_family = AF_INET; m_sinMusique.sin_port = htons(*m_portMusique); } Client::Client(u_short port, string ip, string pseudo) : m_sock(0), m_sockMusique(0), m_port(0), m_portMusique(0), m_ipServeur(0), m_pseudo(0), m_message(0), m_pseudoServeur(0), m_buffer(0), m_bufferMusique(0), m_resultat(0), m_erreur(0) { m_erreur = new int; m_resultat = new int; m_bufferMusique = new char[NOMBRE_OCTET]; m_buffer = new char[NOMBRE_OCTET]; m_pseudoServeur = new char[30]; m_message = new string; m_pseudo = new string; m_ipServeur = new string; m_portMusique = new u_short; m_port = new u_short; m_sock = new SOCKET; m_sockMusique = new SOCKET; *m_erreur = 0; *m_resultat = 0; *m_pseudo = pseudo; *m_ipServeur = ip; *m_portMusique = DEFAULT_PORT_MUSIQUE; *m_port = port; WSADATA WSAData; if (WSAStartup(MAKEWORD(2, 0), &WSAData) != 0) { cout << "Erreur de la fonction WSAStarup dans le constructeur de la classe client" << endl; *m_erreur = WSAGetLastError(); cout << "Erreur " << *m_erreur << endl; } *m_sock = socket(AF_INET, SOCK_STREAM, 0); m_sin.sin_addr.s_addr = inet_addr(m_ipServeur[0].c_str()); m_sin.sin_family = AF_INET; m_sin.sin_port = htons(*m_port); *m_sockMusique = socket(AF_INET, SOCK_STREAM, 0); m_sinMusique.sin_addr.s_addr = inet_addr(m_ipServeur[0].c_str()); m_sinMusique.sin_family = AF_INET; m_sinMusique.sin_port = htons(*m_portMusique); } Client::~Client() { cout << "Fermeture du programme" << endl; closesocket(*m_sock); closesocket(*m_sockMusique); WSACleanup(); delete m_sock; delete m_sockMusique; delete m_port; delete m_portMusique; delete m_ipServeur; delete m_message; delete m_pseudoServeur; delete m_buffer; delete m_bufferMusique; delete m_resultat; delete m_erreur; } int Client::connexionAuServeur() { if (*m_sock == INVALID_SOCKET) { cout << "Erreur de la fonction socket dans la methode 'connectToServer' de la classe client"; *m_erreur = WSAGetLastError(); cout << "Erreur " << *m_erreur << endl; return *m_erreur; } cout << endl << "Connexion au serveur " << *m_ipServeur << " sur le port " << *m_port << endl; if (connect(*m_sock, (SOCKADDR *)&m_sin, sizeof(m_sin)) == 0) { send(*m_sock, m_pseudo->c_str(), 15, 0); recv(*m_sock, m_pseudoServeur, 30, 0); cout << "Connexion etablie avec " << m_pseudoServeur << endl; return 0; } else { system("color 4"); cout << "Impossiblde de se connecter au port " << *m_port << " du serveur " << *m_ipServeur << endl; *m_erreur = WSAGetLastError(); cout << "Erreur " << *m_erreur << endl; return *m_erreur; } } int Client::envoieMessage() { if (*m_erreur == 0)//On verifie que le socket n'a pas rencontre d'erreur avant cela { while (commandeEnvoyee() != QUITTER )//On verifie que l'utilisateur n'ai pas saisie '/quit' { getline(cin, *m_message); if (send(*m_sock, m_message->c_str(), NOMBRE_OCTET, 0) != NOMBRE_OCTET) { cout << "Impossible d'envoyer le message a " << *m_ipServeur << " ! Erreur: " << WSAGetLastError() << endl; } cout << *m_pseudo << ">"; } return QUITTER; } else return 1; } void Client::recevoirMessage() { if (*m_erreur == 0)//On verifie que le socket n'a pas rencontre d'erreur avant cela { while (commandeEnvoyee() != QUITTER && commandeRecue() != SERVEUR_OFF) { *m_resultat = recv(*m_sock, m_buffer, NOMBRE_OCTET, 0); if (*m_resultat > 0) { cout << '\r' << m_pseudoServeur << ">" << m_buffer << endl; cout << *m_pseudo << ">"; } } } } int Client::recevoirMusique() { for (int i = 0; i < NOMBRE_OCTET; ++i) m_buffer[i] = 0; cout << "Fonction musique" << endl; //Connexion au port diffusant la musique if (*m_sockMusique == INVALID_SOCKET) { cout << "Erreur de la fonction socket dans la methode 'recevoirMusique' de la classe client"; *m_erreur = WSAGetLastError(); cout << "Erreur " << *m_erreur << endl; return *m_erreur; } cout << endl << "Connexion au serveur: " << *m_ipServeur << " sur le port " << *m_portMusique << endl; if (connect(*m_sockMusique, (SOCKADDR *)&m_sinMusique, sizeof(m_sinMusique)) == 0) { cout << "Connexion etablie " << endl; } else { system("color 4"); cout << "Impossiblde de se connecter au port " << *m_portMusique << " du serveur " << *m_ipServeur << endl; *m_erreur = WSAGetLastError(); cout << "Erreur " << *m_erreur << endl; return *m_erreur; } //Recuperation de la taille du fichier double size; stringstream convertion; *m_resultat = recv(*m_sockMusique, m_bufferMusique, NOMBRE_OCTET, 0); convertion << m_bufferMusique; convertion >> size; cout << "Taille: " << size << "octets" << endl; //Ouverture du fichier d'ecriture ofstream fichierEcriture("temporaire.smm", ofstream::binary | ios::app); double pourcentage = 0; //Si le fichier ne s'ouvre pas if (!fichierEcriture) { cout << "Impposible d'acceder au fichier temporaire" << endl; return 1; } else { cout << "Debut de la reception de la musique" << endl; //On recoit les paquets tant que le fichier n'est pas complet for (int i = 0; i < size; i += NOMBRE_OCTET) { pourcentage = (100 / size)*i; cout << '\r' << "Progression : " << pourcentage << "%" << " Octets: " << i; *m_resultat = recv(*m_sockMusique, m_bufferMusique, NOMBRE_OCTET, 0); fichierEcriture.write(m_bufferMusique, NOMBRE_OCTET); Sleep(40); } cout << endl <<"Fin de la reception" << endl; for (int i = 0; i < NOMBRE_OCTET; ++i) m_bufferMusique[i] = 0; closesocket(*m_sockMusique); return 0; } } int Client::commandeEnvoyee() { if (*m_message == "/quit") return QUITTER; else if (*m_message == "/reboot") { reconnexion(); return REDEMARER; } else if (m_message->substr(0, 7) == "/pseudo") { this->changePseudo(m_message->substr(8, m_message->size() - 8)); return PSEUDO; } else if (*m_message == "/save") { sauvegardeParametre(); return SAVE; } else if (*m_message == "/liste") return LISTE; else if (*m_message == "/connect") { connexionAuServeur(); return CONNEXION; } else return NO_COMMANDE; } int Client::commandeRecue() { if (m_buffer[0] != '/') return NO_COMMANDE; else if (m_buffer[1] == 'm' && m_buffer[2] == 'u' && m_buffer[3] == 's' && m_buffer[4] == 'i' && m_buffer[5] == 'c') { recevoirMusique(); return SERVEUR_MUSIQUE; } } int Client::sauvegardeParametre() { ofstream fichierSauvegarde("dataClient.tsc"); if (!fichierSauvegarde) { cout << "Impposible d'acceder au fichier de sauvegarde" << endl; return 1; } else { fichierSauvegarde << *m_ipServeur << endl; fichierSauvegarde << *m_port<< endl; fichierSauvegarde << *m_pseudo << endl; return 0; } } int Client::chargerParametre() { ifstream fichierSauvegarde("dataClient.tsc"); if (!fichierSauvegarde) { cout << "Impposible d'acceder au fichier de sauvegarde" << endl; return 1; } else { string ligneLue; //Lecture de l'ip du serveur fichierSauvegarde >> ligneLue; for (int i(0); i < sizeof(ligneLue); ++i) m_ipServeur[i] = ligneLue[i]; //Lecture du port fichierSauvegarde >> *m_port; //Lecture du pseudo fichierSauvegarde >> *m_pseudo; return 0; } } int Client::changePseudo(string nouveauPseudo) { *m_pseudo = nouveauPseudo; return 0; } int Client::deconnexion() { closesocket(*m_sock); return 0; } int Client::reconnexion() { cout << "Deconnexion du serveur" << endl; deconnexion(); cout << "Tentative de reconnexion au serveur" << endl; connexionAuServeur(); return 0; } void* threadSendMessage(void* p_data) { data *dataClient = (data*)p_data; dataClient->client.envoieMessage(); return NULL; } void* threadReceiveMessage(void* p_data) { data *dataClient = (data*)p_data; dataClient->client.recevoirMessage(); return NULL; } SOCKET Client::getSocket() const { return* m_sock; } string Client::getPseudo() const { return *m_pseudo; } string Client::getIpServeur() const { return *m_ipServeur; } int Client::getErreur() const { return *m_erreur; } void Client::setIp(string ip) { *m_ipServeur = ip.c_str(); } void Client::setPseudo(string pseudo) { *m_pseudo = pseudo; } void Client::setPort(u_short port) { *m_port = port; } void Client::setMusicPort(u_short port) { *m_portMusique = port; }
// File: globSample.cpp // Library: SimpleOpt // Author: Brodie Thiesfield <code@jellycan.com> // Source: http://code.jellycan.com/simpleopt/ // // MIT LICENCE // =========== // The licence text below is the boilerplate "MIT Licence" used from: // http://www.opensource.org/licenses/mit-license.php // // Copyright (c) 2006, Brodie Thiesfield // // 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. #if defined(_MSC_VER) # include <windows.h> # include <tchar.h> #else # define TCHAR char # define _T(x) x # define _tprintf printf # define _tmain main #endif #include <stdio.h> #include <locale.h> #include "SimpleOpt.h" #include "SimpleGlob.h" static void ShowUsage() { _tprintf( _T("Usage: globSample [OPTIONS] [FILES]\n") _T("\n") _T(" -e Return upon read error (e.g. directory does not have\n") _T(" read permission)\n") _T(" -m Append a slash (backslash in Windows) to each path which\n") _T(" corresponds to a directory\n") _T(" -s Don't sort the returned pathnames\n") _T(" -o Sort all pathnames as a single group instead of in filespec groups\n") _T(" -c If no pattern matches, return the original pattern\n") _T(" -t Tilde expansion is carried out (on Unix platforms)\n") _T(" -d Return only directories (not compatible with --only-file)\n") _T(" -f Return only files (not compatible with --only-dir)\n") _T(" -n Do not return the \".\" or \"..\" special files\n") _T("\n") _T(" -? Output this help.\n") ); } CSimpleOpt::SOption g_rgOptions[] = { { SG_GLOB_ERR, _T("-e"), SO_NONE }, { SG_GLOB_MARK, _T("-m"), SO_NONE }, { SG_GLOB_NOSORT, _T("-s"), SO_NONE }, { SG_GLOB_NOCHECK, _T("-c"), SO_NONE }, { SG_GLOB_TILDE, _T("-t"), SO_NONE }, { SG_GLOB_ONLYDIR, _T("-d"), SO_NONE }, { SG_GLOB_ONLYFILE, _T("-f"), SO_NONE }, { SG_GLOB_NODOT, _T("-n"), SO_NONE }, { SG_GLOB_FULLSORT, _T("-o"), SO_NONE }, { 0, _T("-?"), SO_NONE }, { 0, _T("-h"), SO_NONE }, SO_END_OF_OPTIONS }; static const TCHAR * GetLastErrorText( int a_nError ) { switch (a_nError) { case SO_SUCCESS: return _T("Success"); case SO_OPT_INVALID: return _T("Unrecognized option"); case SO_OPT_MULTIPLE: return _T("Option matched multiple strings"); case SO_ARG_INVALID: return _T("Option does not accept argument"); case SO_ARG_INVALID_TYPE: return _T("Invalid argument format"); case SO_ARG_MISSING: return _T("Required argument is missing"); case SO_ARG_INVALID_DATA: return _T("Invalid argument data"); default: return _T("Unknown error"); } } int _tmain(int argc, TCHAR * argv[]) { unsigned int uiFlags = 0; CSimpleOpt args(argc, argv, g_rgOptions, true); while (args.Next()) { if (args.LastError() != SO_SUCCESS) { _tprintf( _T("%s: '%s' (use --help to get command line help)\n"), GetLastErrorText(args.LastError()), args.OptionText()); continue; } if (args.OptionId() == 0) { ShowUsage(); return 0; } uiFlags |= (unsigned int) args.OptionId(); } CSimpleGlob glob(uiFlags); if (glob.Add(args.FileCount(), args.Files()) < SG_SUCCESS) { _tprintf(_T("Error while globbing files\n")); return 1; } for (int n = 0; n < glob.FileCount(); ++n) _tprintf(_T("file %2d: '%s'\n"), n, glob.File(n)); return 0; }
#include <iostream> #include <vector> #include <unordered_map> using namespace std; // Given an array of integers, return indices of the two numbers such that they add up to a specific target. // You may assume that each input would have exactly one solution, and you may not use the same element twice. /*Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1]. */ /*solution: 1. create a map of numbers that we need to fulfil target. 2. substract target with current number array 3. seek trought map we have and return */ vector<int> twoSums(vector<int>& nums, int target) { unordered_map<int, int> temp; for (int i = 0; i < nums.size(); i++) { int b = target - nums[i]; if(temp.count(b)) { return {i, temp[b]}; } temp[nums[i]] = i; } // for(const auto &z: temp){ // cout << z.first << endl; // } return {}; } int main () { vector<int> num = {2, 7, 11, 15}; //target 13 vector<int> num2 = {3, 2, 4}; // target 6 // print result for(auto &x: twoSums(num, 13)) { cout << x << endl; } return 0; }
// // Skybox.h // Odin.MacOSX // // Created by Daniel on 27/10/15. // Copyright (c) 2015 DG. All rights reserved. // #ifndef __Odin_MacOSX__Skybox__ #define __Odin_MacOSX__Skybox__ #include "CubeMap.h" #include "BoxShape.h" #include "Shader.h" #include "RenderStates.h" namespace odin { namespace render { class Skybox { public: Skybox(); ~Skybox(); void draw(); void load(const std::string& name, const std::string& path); void bind(); void unbind(); private: resource::Cubemap* m_cubemap; shape::BoxShape m_cube; RenderStates m_renderStates; }; } } #endif /* defined(__Odin_MacOSX__Skybox__) */
// Copyright 2012 Yandex #ifndef LTR_LEARNERS_DECISION_TREE_SPLITTING_QUALITY_H_ #define LTR_LEARNERS_DECISION_TREE_SPLITTING_QUALITY_H_ #include <vector> #include "ltr/data/data_set.h" #include "ltr/interfaces/parameterized.h" #include "ltr/utility/shared_ptr.h" using ltr::DataSet; namespace ltr { namespace decision_tree { class SplittingQuality : public Parameterized { public: typedef ltr::utility::shared_ptr<SplittingQuality> Ptr; typedef ltr::utility::shared_ptr<SplittingQuality> BasePtr; virtual double value( DataSet<ltr::Object> data, vector<DataSet<ltr::Object> > split) const = 0; virtual void setDefaultParameters() const {} virtual void checkParameters() const {} }; class FakeSplittingQuality : public SplittingQuality { public: typedef ltr::utility::shared_ptr<FakeSplittingQuality> Ptr; double value( DataSet<ltr::Object> data, vector<DataSet<ltr::Object> > split) const { return 0; } }; }; }; #endif // LTR_LEARNERS_DECISION_TREE_SPLITTING_QUALITY_H_
//------------------------------------------------------------------------------ /* This file is part of rippled: https://github.com/ripple/rippled Copyright (c) 2012, 2013 Ripple Labs Inc. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ //============================================================================== #ifndef RIPPLE_PEERFINDER_PEERINFO_H_INCLUDED #define RIPPLE_PEERFINDER_PEERINFO_H_INCLUDED namespace ripple { namespace PeerFinder { //typedef AgedHistory <std::set <Endpoint> > Endpoints; //-------------------------------------------------------------------------- // we keep one of these for each connected peer struct PeerInfo { enum State { // Some peculiar, unknown state stateUnknown, // A connection attempt is in progress stateConnecting, // A connection has been established but no handshake yet stateConnected, // A connection has been established and the handshake has completed stateEstablished, // A connection (of some kind) that is being torn down stateDisconnecting }; PeerInfo (PeerID const& id_, IPAddress const& address_, bool inbound_, DiscreteTime now) : id (id_) , address (address_) , inbound (inbound_) , fixed (false) , checked (inbound_ ? false : true) , canAccept (inbound_ ? false : true) , connectivityCheckInProgress (false) , peerState (stateUnknown) , whenSendEndpoints (now) , whenAcceptEndpoints (now) { } PeerID id; IPAddress address; bool inbound; // Set to indicate that this is a fixed peer. bool fixed; // Tells us if we checked the connection. Outbound connections // are always considered checked since we successfuly connected. bool mutable checked; // Set to indicate if the connection can receive incoming at the // address advertised in mtENDPOINTS. Only valid if checked is true. bool mutable canAccept; // Set to indicate that a connection check for this peer is in // progress. Valid always. bool mutable connectivityCheckInProgress; // Indicates the state for this peer State peerState; // The time after which we will send the peer mtENDPOINTS DiscreteTime mutable whenSendEndpoints; // The time after which we will accept mtENDPOINTS from the peer // This is to prevent flooding or spamming. Receipt of mtENDPOINTS // sooner than the allotted time should impose a load charge. // DiscreteTime mutable whenAcceptEndpoints; // The set of all recent IPAddress that we have seen from this peer. // We try to avoid sending a peer the same addresses they gave us. // CycledSet <IPAddress, IPAddress::hasher, IPAddress::key_equal> mutable received; }; } } #endif
class Solution { public: int NumberOf1Between1AndN_Solution(int n) { if(n <= 0){ return 0; } int count = 0; for(int i=1; i<=n; i*=10){ int a = n/i; int b = n%i; count += (a+8)/10*i + (a%10 == 1)*(b+1); } return count; } };
#include "ColorTextureProgram.hpp" #include "gl_compile_program.hpp" #include "gl_errors.hpp" Load< ColorTextureProgram > color_texture_program(LoadTagEarly); ColorTextureProgram::ColorTextureProgram() { //Compile vertex and fragment shaders using the convenient 'gl_compile_program' helper function: program = gl_compile_program( //vertex shader: "#version 330\n" "uniform mat4 OBJECT_TO_CLIP;\n" "uniform vec3 PLAYER_POS;\n" "in vec4 Position;\n" "in vec4 Color;\n" "in vec2 TexCoord;\n" "out vec4 color;\n" "out vec2 texCoord;\n" "void main() {\n" " gl_Position = OBJECT_TO_CLIP * Position;\n" " float dist_x = PLAYER_POS.x - Position.x/Position.w;\n" " float dist_y = PLAYER_POS.y - Position.y/Position.w;\n" " float dist_z = PLAYER_POS.z - Position.z/Position.w;\n" " float distance = sqrt(dist_x * dist_x + dist_y * dist_y + dist_z * dist_z);\n" " if(distance < 2) {\n" " color = Color;\n" " }\n" " else {\n" " color = vec4(0.25, 0.25, 0.25, 0.25);\n" " }\n" " texCoord = TexCoord;\n" "}\n" , //fragment shader: "#version 330\n" "uniform sampler2D TEX;\n" "in vec4 color;\n" "in vec2 texCoord;\n" "out vec4 fragColor;\n" "void main() {\n" " fragColor = texture(TEX, texCoord) * color;\n" "}\n" ); //As you can see above, adjacent strings in C/C++ are concatenated. // this is very useful for writing long shader programs inline. //look up the locations of vertex attributes: Position_vec4 = glGetAttribLocation(program, "Position"); Color_vec4 = glGetAttribLocation(program, "Color"); TexCoord_vec2 = glGetAttribLocation(program, "TexCoord"); //look up the locations of uniforms: OBJECT_TO_CLIP_mat4 = glGetUniformLocation(program, "OBJECT_TO_CLIP"); GLuint TEX_sampler2D = glGetUniformLocation(program, "TEX"); PLAYER_POS_vec3 = glGetUniformLocation(program, "PLAYER_POS"); //set TEX to always refer to texture binding zero: glUseProgram(program); //bind program -- glUniform* calls refer to this program now glUniform1i(TEX_sampler2D, 0); //set TEX to sample from GL_TEXTURE0 glUseProgram(0); //unbind program -- glUniform* calls refer to ??? now } ColorTextureProgram::~ColorTextureProgram() { glDeleteProgram(program); program = 0; }
#include"Object.h" Object::Object (const string& nom) : _nom(nom) // registerObject { _pool.insert(this); cout << "enregistrer " << _nom << endl; } static void Object::viderPool() { // vider Pool set<Object*>::iterator it; while ( (it = _pool.begin()) != _pool.end() ) delete (*it); } Object::~Object() //unregisterObject { _pool.erase(this); cout << "liberer " << _nom << endl; } void Object::setNom(const string & nom) { _nom=nom; } /*string str() const;{ return _object; }*/
/* * Copyright (c) 2011 Pierre-Etienne Bougué <pe.bougue(a)gmail.com> * Copyright (c) 2011 Florian Colin <florian.colin28(a)gmail.com> * Copyright (c) 2011 Kamal Fadlaoui <kamal.fadlaoui(a)gmail.com> * Copyright (c) 2011 Quentin Lequy <quentin.lequy(a)gmail.com> * Copyright (c) 2011 Guillaume Pinot <guillaume.pinot(a)tremplin-utc.net> * Copyright (c) 2011 Cédric Royer <cedroyer(a)gmail.com> * Copyright (c) 2011 Guillaume Turri <guillaume.turri(a)gmail.com> * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * */ #include "generateur/alg/StrategyGeneration.hh" #include "generateur/ParseCmdLineGenerateur.hh" #include "generateur/StrategyGenerationSelecter.hh" #include "generateur/WriterSelecter.hh" #include "dtoout/InstanceWriterInterface.hh" #include "dtoout/SolutionDtoout.hh" #include "tools/Checker.hh" #include <iostream> #include <string> #include <boost/foreach.hpp> #include <boost/program_options.hpp> #include <boost/shared_ptr.hpp> using namespace boost; using namespace boost::program_options; using namespace std; int main(int argc, char** argv){ try { variables_map args_l = ParseCmdLineGenerateur::parse(argc, argv); shared_ptr<StrategyGeneration> pStrategy_l = StrategyGenerationSelecter::getStrategy(args_l["strategy"].as<string>()); list<shared_ptr<ContextBO> > instances_l = pStrategy_l->generate(args_l); shared_ptr<InstanceWriterInterface> writer_l = WriterSelecter::getWriter(args_l["writer"].as<string>()); BOOST_FOREACH(shared_ptr<ContextBO> instance_l, instances_l){ assert(check(instance_l.get())); static int compteur_l(0); compteur_l++; ostringstream out_instance_filename_l; out_instance_filename_l << args_l["out"].as<string>() << "_inst_" << compteur_l << ".txt"; writer_l->write(instance_l.get(), out_instance_filename_l.str()); ostringstream out_sol_filename_l; out_sol_filename_l << args_l["out"].as<string>() << "_sol_" << compteur_l << ".txt"; SolutionDtoout::writeSolInit(instance_l.get(), out_sol_filename_l.str()); } } catch (string& s_l ){ cerr << "Exception catchee : " << s_l << endl; } }
#include<bits/stdc++.h> using namespace std; int main() { // only gravity will pull me down // Replace the Bit int t, n, k; cin >> t; while (t--) { cin >> n >> k; int tmp=n, cnt=0; while(tmp) { cnt++; tmp=tmp>>1; } int p = pow(2, cnt-k); if(n & p) { // if kth bit is 1 cout << n-p << endl; } else { cout << n << endl; } } return 0; }
#pragma once class View : public CView { public: View(); ~View(); // Mouse left/right click flags bool LEFT_DOWN; bool RIGHT_DOWN; // Mouse position vec3d m_MousePos; vec3d m_PreMousePos; vec3d m_DMousePos; // Mouse functions afx_msg void OnLButtonDown(UINT nFlags, CPoint point); afx_msg void OnLButtonUp(UINT nFlags, CPoint point); afx_msg void OnRButtonDown(UINT nFlags, CPoint point); afx_msg void OnRButtonUp(UINT nFlags, CPoint point); afx_msg void OnMouseMove(UINT nFlags, CPoint point); afx_msg BOOL OnMouseWheel(UINT nFlags, short zDelta, CPoint pt); };
#include "M3_Timer.h" namespace M3 { // Start time getters and setters. unsigned long Timer::getStartTime() const { return m_startTime; } bool Timer::setStartTime(unsigned long startTime) { m_startTime = startTime; return true; } // Duration getters and setters. unsigned long Timer::getDuration() const { return m_duration; } bool Timer::setDuration(unsigned long duration) { m_duration = duration; return true; } // Constructor. Sets count up or down. Timer::Timer(TimerType timerType) { m_timerType = timerType; } // Methods. // start() with no arguments is used for counting up only. bool Timer::start() { // If the timer is set for counting up then do so. if (m_timerType == Timer::TimerType::COUNT_UP) { m_startTime = millis(); return true; // Otherwise return false as this is invalid. } else { return false; } } // start() with a duration is used for counting down only. bool Timer::start(unsigned long duration) { // If the timer is set for couting down then do so. if (m_timerType == Timer::TimerType::COUNT_DOWN) { m_startTime = millis(); m_duration = duration; return true; // Otherwise return false as this is invalid. } else { return false; } } // reset() can be used to restart while counting up or down. void Timer::reset() { // If counting up, call start(). if (m_timerType == Timer::TimerType::COUNT_UP) { Timer::start(); // Else call start(duration). } else { Timer::start(m_duration); } } // Function used to return the time remaining while counting down. unsigned long Timer::timeRemaining() const{ // If counting down, the return the remaining time. if (m_timerType == Timer::TimerType::COUNT_DOWN) { return m_startTime + m_duration - millis(); // Otherwise return 0 as an indication of error. } else { return 0; } } // Function used to return the elapsed time while counting up. unsigned long Timer::elapsedTime() const{ // If counting up, return the elapsed time. if (m_timerType == Timer::TimerType::COUNT_UP) { return millis() - m_startTime; // Otherwise return 0 as an indication of error. } else { return 0; } } // Function used, while counting down, to determine if the timer has expired or not. bool Timer::isTimerExpired() const { // If counting down, return if the timer has expired. if (m_timerType == Timer::TimerType::COUNT_DOWN) { if (millis() - m_startTime >= m_duration) { return true; } else { return false; } // Else return false to indicate an error situation. } else { return false; } } }
/* ID: dhyanes1 LANG: C++ PROG: bones */ #include <cstdio> #include <algorithm> #include <map> #include <queue> using namespace std; int arr[101]; int main(void) { FILE *fin,*fout; fin=fopen("bones.in","r"); fout = fopen("bones.out","w"); int s[3]; fscanf(fin, "%d %d %d", &s[0], &s[1], &s[2]); /* memset(arr1, 0, sizeof(arr1)); memset(arr2, 0, sizeof(arr1)); arr1[0] = 1; arr2[0] = 1; int *curr = arr1; int *prev = arr2; for(int i = 0; i < 3; ++i) { memset(curr, 0, sizeof(arr1)); for(int j = 1; j <= s[i]; ++j) { for(int k = 100; k >= j; k--) { curr[k] += prev[k] + prev[k-j]; } } swap(curr, prev); } for(int i = 0; i <= 50; ++i) { printf("%d ", prev[i]); } */ memset(arr, 0, sizeof(arr)); for(int i = 1; i <= s[0]; ++i) { for(int j = 1; j <= s[1]; ++j) { for(int k = 1; k <= s[2]; ++k) { arr[i+j+k]++; } } } int max = 0; int p = 0; for(int i = 0; i < 101; ++i) { if (arr[i] > max) { max = arr[i]; p = i; } } fprintf(fout, "%d\n", p); fclose(fout); fclose(fin); return 0; }
#include "pch.h" float Math::RNG::Range(float min_value, float max_value) { if(min_value > max_value) std::swap(min_value, max_value); return (float)rand()/RAND_MAX * (max_value - min_value) + min_value; } int Math::RNG::Range( int min_value, int max_value ) { if (min_value > max_value) std::swap( min_value, max_value ); return min_value + (rand() % (max_value - min_value + 1)); } XMVECTOR Math::RNG::RandomVectorRange(const XMVECTOR& v1,const XMVECTOR& v2) { return XMVectorSet( Range(XMVectorGetX(v1), XMVectorGetX(v2)), Range(XMVectorGetY(v1), XMVectorGetY(v2)), Range(XMVectorGetZ(v1), XMVectorGetZ(v2)), 0); } XMVECTOR Math::RNG::RandomOnSphere() { XMVECTOR v = XMVectorSet((float)rand(), (float)rand(), (float)rand(), 0); return XMVector3Normalize(v); } XMVECTOR Math::RNG::RandomInSphere() { return RandomOnSphere() * Range(-1.0f,1.0f); } XMVECTOR Math::RNG::RandomInBoundingBox(const XMVECTOR & origin, const XMVECTOR & extent) { return origin + RandomVectorRange(-extent, extent); } XMVECTOR Math::RNG::RandomInBoundingBox(const XMVECTOR & origin, const XMVECTOR & extent, const XMVECTOR & orientation) { return origin + XMVector3Rotate(RandomVectorRange(-extent, extent), orientation); } void Math::Gravity(XMVECTOR & position, XMVECTOR & velocity, float dt, const XMVECTOR & acceleration) { velocity += G_GRAVITY*dt; position += velocity*dt; } void Math::NoGravity(XMVECTOR & position, XMVECTOR & velocity, float dt, const XMVECTOR & acceleration) { position += velocity*dt; } void Math::Integrate(XMVECTOR & position, XMVECTOR & velocity, float dt, const XMVECTOR & acceleration) { velocity += acceleration*dt; position += velocity*dt; } int Math::Alignment(int value, int alignment) { return (value + alignment - 1) & ~(alignment - 1); } float Math::Lerp( float lhs, float rhs, float t ) { return lhs + t * (rhs - lhs); } Vector3 Math::Slerp( const Vector3 & a, const Vector3 & b, float f ) { float dot = a.Dot( b ); if (dot < -1) dot = -1; if (dot > 1) dot = 1; float t = acosf( dot ) * f; Vector3 v = b - a * dot; v.Normalize(); return ((a * cosf( t )) + (v * sinf( t ))); }
// // Component.hpp // closedFrameworks // // Created by William Meaton on 12/05/2016. // Copyright © 2016 WillMeaton.uk. All rights reserved. // #ifndef Component_hpp #define Component_hpp #include <stdio.h> #include "Math.h" class Component{ protected: Component(); virtual void update(); }; #endif /* Component_hpp */
// // Created by fab on 12/03/2020. // #include "../../headers/utils/BetterNoise.hpp" BetterNoise::BetterNoise() : PerlinNoise() { zDecayZMax = (float)width; zDecayCut = 1; freq = 1; doPenaltyBottom = true; doPenaltyMiddle = true; doPenaltySky = true; } float BetterNoise::sample(float xBase, float yBase, float zBase) { float sample = PerlinNoise::sample(xBase, yBase, zBase); //Plus light plus on est haut float zDecay_Norm = yBase / zDecayZMax; float penalty = 0; if (zDecayCut < 1 && zDecayCut >= 0) { //Cut au dessus if (doPenaltySky) penalty = (max(0, zDecay_Norm - zDecayCut)); //Remplis en dessous if (doPenaltyMiddle && zDecay_Norm <= zDecayCut) { penalty = (1 - (zDecayCut - zDecay_Norm)); penalty = -pow(penalty, 20); penalty /= 2; } //Remplis au sol if (doPenaltyBottom && zDecay_Norm < 0.1f) { penalty = (0.1f - zDecay_Norm) / 0.1f; penalty = -pow(penalty, 3); penalty /= 4; } } sample -= (penalty / 4.0f); return min(1,max(0,sample)); }
#include <conio.h> #include <stdlib.h> #include <stdio.h> #include <time.h> #include <string.h> #include <math.h> #include <locale.h> #include <ctype.h> float graus,far; int x=0; int main() { printf("\n Insira o valor da temperatura em Graus Celsius: \n"); scanf("%f",&graus); far=(graus*1.8)+32; printf(" \n A temperatura corresponde a %f Fahrenheit \n", far); }
void fireCheck() { if ((gasValue >= gasTrigger) || ((temperatureValue >= temperatureTrigger) || (humidityValue <= humidityTrigger))) { fireValue == 1; } else { fireValue == 0; } }
// Created on: 1994-02-28 // Created by: Bruno DUMORTIER // Copyright (c) 1994-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _GeomFill_SweepSectionGenerator_HeaderFile #define _GeomFill_SweepSectionGenerator_HeaderFile #include <Adaptor3d_Curve.hxx> #include <gp_Ax1.hxx> #include <GeomFill_SequenceOfTrsf.hxx> #include <TColStd_Array1OfReal.hxx> #include <TColStd_Array1OfInteger.hxx> #include <TColgp_Array1OfPnt.hxx> #include <TColgp_Array1OfVec.hxx> #include <TColgp_Array1OfPnt2d.hxx> #include <TColgp_Array1OfVec2d.hxx> class Geom_BSplineCurve; class Geom_Curve; class gp_Trsf; //! class for instantiation of AppBlend. //! evaluate the sections of a sweep surface. class GeomFill_SweepSectionGenerator { public: DEFINE_STANDARD_ALLOC Standard_EXPORT GeomFill_SweepSectionGenerator(); //! Create a sweept surface with a constant radius. Standard_EXPORT GeomFill_SweepSectionGenerator(const Handle(Geom_Curve)& Path, const Standard_Real Radius); //! Create a sweept surface with a constant section Standard_EXPORT GeomFill_SweepSectionGenerator(const Handle(Geom_Curve)& Path, const Handle(Geom_Curve)& FirstSect); //! Create a sweept surface with an evolving section //! The section evaluate from First to Last Section Standard_EXPORT GeomFill_SweepSectionGenerator(const Handle(Geom_Curve)& Path, const Handle(Geom_Curve)& FirstSect, const Handle(Geom_Curve)& LastSect); //! Create a pipe with a constant radius with 2 //! guide-line. Standard_EXPORT GeomFill_SweepSectionGenerator(const Handle(Geom_Curve)& Path, const Handle(Geom_Curve)& Curve1, const Handle(Geom_Curve)& Curve2, const Standard_Real Radius); //! Create a pipe with a constant radius with 2 //! guide-line. Standard_EXPORT GeomFill_SweepSectionGenerator(const Handle(Adaptor3d_Curve)& Path, const Handle(Adaptor3d_Curve)& Curve1, const Handle(Adaptor3d_Curve)& Curve2, const Standard_Real Radius); Standard_EXPORT void Init (const Handle(Geom_Curve)& Path, const Standard_Real Radius); Standard_EXPORT void Init (const Handle(Geom_Curve)& Path, const Handle(Geom_Curve)& FirstSect); Standard_EXPORT void Init (const Handle(Geom_Curve)& Path, const Handle(Geom_Curve)& FirstSect, const Handle(Geom_Curve)& LastSect); Standard_EXPORT void Init (const Handle(Geom_Curve)& Path, const Handle(Geom_Curve)& Curve1, const Handle(Geom_Curve)& Curve2, const Standard_Real Radius); Standard_EXPORT void Init (const Handle(Adaptor3d_Curve)& Path, const Handle(Adaptor3d_Curve)& Curve1, const Handle(Adaptor3d_Curve)& Curve2, const Standard_Real Radius); Standard_EXPORT void Perform (const Standard_Boolean Polynomial = Standard_False); Standard_EXPORT void GetShape (Standard_Integer& NbPoles, Standard_Integer& NbKnots, Standard_Integer& Degree, Standard_Integer& NbPoles2d) const; Standard_EXPORT void Knots (TColStd_Array1OfReal& TKnots) const; Standard_EXPORT void Mults (TColStd_Array1OfInteger& TMults) const; Standard_Integer NbSections() const; //! Used for the first and last section //! The method returns Standard_True if the derivatives //! are computed, otherwise it returns Standard_False. Standard_EXPORT Standard_Boolean Section (const Standard_Integer P, TColgp_Array1OfPnt& Poles, TColgp_Array1OfVec& DPoles, TColgp_Array1OfPnt2d& Poles2d, TColgp_Array1OfVec2d& DPoles2d, TColStd_Array1OfReal& Weigths, TColStd_Array1OfReal& DWeigths) const; Standard_EXPORT void Section (const Standard_Integer P, TColgp_Array1OfPnt& Poles, TColgp_Array1OfPnt2d& Poles2d, TColStd_Array1OfReal& Weigths) const; //! raised if <Index> not in the range [1,NbSections()] Standard_EXPORT const gp_Trsf& Transformation (const Standard_Integer Index) const; //! Returns the parameter of <P>, to impose it for the //! approximation. Standard_EXPORT Standard_Real Parameter (const Standard_Integer P) const; protected: private: Handle(Geom_BSplineCurve) myPath; Handle(Geom_BSplineCurve) myFirstSect; Handle(Geom_BSplineCurve) myLastSect; Handle(Adaptor3d_Curve) myAdpPath; Handle(Adaptor3d_Curve) myAdpFirstSect; Handle(Adaptor3d_Curve) myAdpLastSect; gp_Ax1 myCircPathAxis; Standard_Real myRadius; Standard_Boolean myIsDone; Standard_Integer myNbSections; GeomFill_SequenceOfTrsf myTrsfs; Standard_Integer myType; Standard_Boolean myPolynomial; }; #include <GeomFill_SweepSectionGenerator.lxx> #endif // _GeomFill_SweepSectionGenerator_HeaderFile
#include <bits/stdc++.h> using namespace std; long long n, a[1010], b[1010], ans = 0, sum = 0; bool cmp(int x, int y) { return a[x] < a[y]; } int main() { cin >> n; for (int i = 1; i <= n; i++) scanf("%d", &a[i]), b[i] = i; sort(b + 1, b + n + 1, cmp); for (int i = 1; i <= n; i++) ans += sum, sum += a[b[i]]; for (int i = 1; i <= n; i++) printf("%d ", b[i]); printf("\n%.2lf\n", (ans / (double)n)); return 0; }
#include <vector> #include <string> #include <iostream> #include <fstream> #include <sstream> #include <list> #include <algorithm> #include <sstream> #include <set> #include <cmath> #define INF (1<<20) #define MAX 101 using namespace std; class MagicalGirlLevelTwoDivTwo { public: string isReachable(vector <int> jumpTypes, int x, int y) { if (x==0 && y==0) { return "YES"; } for (int i=0; i<jumpTypes.size(); ++i) { if ((jumpTypes[i]&1) == 0) { return "YES"; } else if(jumpTypes[i] == 1) { if (x==y) { return "YES"; } } } if (((x&1)==1 && (y&1)==0) || ((x&1)==0 && (y&1)==1) ) { return "NO"; } return "YES"; } };
#include <QCoreApplication> #include <QDebug> #include <exception> using namespace std; class Cat { public: Cat() { qInfo() << "Call constructor"; } ~Cat() { qInfo() << "Call destructor"; } int GetAge() { return mAge; } private: int mAge = 10; }; int divide(int a, int b) { if (b == 0) { throw runtime_error("divide by 0"); } return a / b; } void f() { auto cp = make_unique<Cat>(); qInfo() << cp->GetAge(); qInfo() << divide(10, 0); } int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); try { f(); } catch (exception &ex) { qInfo() << ex.what(); } return a.exec(); }
#pragma once #include <stdint.h> #include "Devices/Actuators/Relays/Factory.h" namespace Codingfield { namespace Brew { class Configuration { public: const uint8_t OneWireTemperaturePin() const { return oneWireTemperaturePin; } const uint8_t HeaterRelayPin() const { return heaterRelayPin; } const uint8_t CoolerRelayPin() const { return coolerRelayPin; } const uint8_t FanRelayPin() const { return fanRelayPin; } const bool IsTemperatureSensorStubbed() const { return stubTemperatureSensors; } const Actuators::Relays::Factory::Types RelayType() const { return relayType; } private: uint8_t oneWireTemperaturePin = 2; uint8_t heaterRelayPin = 21; uint8_t coolerRelayPin = 22; uint8_t fanRelayPin = 5; bool stubTemperatureSensors = false; Actuators::Relays::Factory::Types relayType = Actuators::Relays::Factory::Types::Gpio; }; } }
#include <iostream> int main (){ int number; int numberReverse; int res; int mem; std::cin >> number; mem = number; while (number > 0) { res = number % 10; numberReverse = numberReverse * 10 + res; number /= 10; } if(mem == numberReverse) { std::cout << "ayo simetrik e" << std::endl; } else { std::cout << "voch simetrik che" << std::endl; } return 0; }
#pragma once #include <cstddef> template<std::size_t...> struct sum_template_parameters; template<std::size_t i, std::size_t... integers> struct sum_template_parameters<i,integers...> { static const std::size_t value = i + sum_template_parameters<integers...>::value; }; template<> struct sum_template_parameters<> { static const std::size_t value = 0u; }; // unit tests follow static_assert(sum_template_parameters<>::value == 0, "error with no parm case"); static_assert(sum_template_parameters<7>::value == 7, "error with one term case"); static_assert(sum_template_parameters<7,13,42>::value == 62, "error with three term case");
// Watched.h #ifndef WATCHED_H #define WATCHED_H #include <string> class Watched { std::string _name; public: Watched(const std::string& name); const std::string& name(); }; #endif //WATCHED_H
/* BEGIN LICENSE */ /***************************************************************************** * SKCore : the SK core library * Copyright (C) 1995-2005 IDM <skcontact @at@ idm .dot. fr> * $Id: integerlist.cpp,v 1.13.2.5 2005/02/17 15:29:20 krys Exp $ * * Authors: Arnaud de Bossoreille de Ribou <debossoreille @at@ idm .dot. fr> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Alternatively you can contact IDM <skcontact @at@ idm> for other license * contracts concerning parts of the code owned by IDM. * *****************************************************************************/ /* END LICENSE */ #include <nspr/nspr.h> #include "skcoreconfig.h" #include "machine.h" #include "swap.h" #include "error.h" #include "refcount.h" #include "file/skfopen.h" #include "file/file.h" #include "integerlist.h" #include "unichar.h" static int g_sComparePRUint32(const void *p1, const void *p2) { return *(PRUint32*)p1 - *(PRUint32*)p2; } SK_REFCOUNT_IMPL_DEFAULT(SKIntegerList); SKIntegerList::SKIntegerList() { m_iSize = 0; m_pIntegerList = NULL; m_bOwner = PR_FALSE; m_piUCS4Data = NULL; m_bInitialized = PR_FALSE; } SKIntegerList::~SKIntegerList() { if(m_bOwner && m_pIntegerList) delete[] (PRUint32 *)m_pIntegerList; if(m_piUCS4Data) UCS4Free(m_piUCS4Data); } SKERR SKIntegerList::SetFileName(const char *pszFileName, const char *pszDefaultFileName) { m_bInitialized = PR_FALSE; if(m_bOwner && m_pIntegerList) { delete[] (PRUint32 *)m_pIntegerList; m_pIntegerList = NULL; } SKERR err = SKFile::SetFileName(pszFileName, pszDefaultFileName); if(err != noErr) return err; PRFileInfo info; if(PR_GetFileInfo(GetSharedFileName(), &info) != PR_SUCCESS) return err_failure; if((info.size & 0x3)) return err_failure; PRFileDesc *f = skPR_Open(GetSharedFileName(), PR_RDONLY, 0); if(!f) return err_notfound; m_bOwner = PR_TRUE; m_iSize = info.size / 4; m_pIntegerList = new PRUint32[m_iSize]; if(m_iSize && !m_pIntegerList) { PR_Close(f); return err_memory; } if(PR_Read(f, (void *)m_pIntegerList, info.size) != info.size) { PR_Close(f); return err_failure; } #if IS_BIG_ENDIAN for(PRUint32 i = 0; i < m_iSize; ++i) { REVERSE_32(((PRUint32*)m_pIntegerList)[i]); } #endif PR_Close(f); qsort((void *)m_pIntegerList, m_iSize, sizeof(PRUint32), &g_sComparePRUint32); m_bInitialized = PR_TRUE; return noErr; } SKERR SKIntegerList::SetListFromArray(const PRUint32 *piArray, PRUint32 iSize, PRBool bDuplicate) { m_bInitialized = PR_FALSE; if(m_bOwner && m_pIntegerList) { delete[] (PRUint32 *)m_pIntegerList; m_pIntegerList = NULL; } m_iSize = iSize; if(bDuplicate) { m_bOwner = PR_TRUE; m_pIntegerList = new PRUint32[m_iSize]; if(m_iSize && !m_pIntegerList) return err_memory; memcpy((void *)m_pIntegerList, piArray, iSize * sizeof(PRUint32)); qsort((void *)m_pIntegerList, m_iSize, sizeof(PRUint32), &g_sComparePRUint32); } else { m_bOwner = PR_FALSE; m_pIntegerList = piArray; } m_bInitialized = PR_TRUE; return noErr; } SKERR SKIntegerList::SetListFromUTF8String(const char *pszString) { SKERR err; PRUint32 iSize = UTF8ToNewUCS4(&m_piUCS4Data, pszString); if(!m_piUCS4Data) return err_memory; err = SetListFromArray(m_piUCS4Data, iSize, PR_FALSE); if(err != noErr) return err; qsort((void *)m_pIntegerList, m_iSize, sizeof(PRUint32), &g_sComparePRUint32); return noErr; } SKERR SKIntegerList::IsPresent(PRUint32 iValue, PRBool *pbResult) { *pbResult = PR_FALSE; if(!m_bInitialized) return err_failure; if(!m_iSize) return noErr; if((m_pIntegerList[0] == iValue) || (m_pIntegerList[m_iSize - 1] == iValue)) { *pbResult = PR_TRUE; return noErr; } PRUint32 iMin = 0; PRUint32 iMax = m_iSize - 1; while(iMax - iMin > 1) { PRUint32 iMid = (iMin + iMax) >> 1; if(m_pIntegerList[iMid] == iValue) { *pbResult = PR_TRUE; return noErr; } if(m_pIntegerList[iMid] < iValue) { iMin = iMid; } else { iMax = iMid; } } *pbResult = PR_FALSE; return noErr; } SKERR SKIntegerList::FormatToAsciiString(char** ppcResult) { * ppcResult = NULL; for(PRUint32 i = 0; i<m_iSize; i++) *ppcResult = PR_sprintf_append(*ppcResult, "%x ", m_pIntegerList[i]); return noErr; } SKERR SKIntegerList::SetListFromAsciiString(const char* pcString) { PRUint32 *piTmp = NULL; PRUint32 iSize = 0; PRUint32 iCount = 0; while(*pcString) { if(*pcString == ' ') { pcString++; continue; } /* a number to parse */ if(iSize == iCount) { iSize = iSize * 2 + 10; piTmp = (PRUint32*) PR_Realloc(piTmp, iSize * sizeof(PRUint32)); if(!piTmp) return err_memory; } char * pcEnd; piTmp[iCount++] = strtoul(pcString, &pcEnd, 16); pcString = pcEnd; } SetListFromArray(piTmp, iCount, PR_TRUE); PR_Free(piTmp); return noErr; }
/** * Copyright (c) 2021, Timothy Stack * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of Timothy Stack nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <regex> #include "tailer.looper.hh" #include "base/fs_util.hh" #include "base/humanize.network.hh" #include "base/lnav_log.hh" #include "base/paths.hh" #include "config.h" #include "line_buffer.hh" #include "lnav.hh" #include "lnav.indexing.hh" #include "service_tags.hh" #include "tailer.h" #include "tailer.looper.cfg.hh" #include "tailerbin.h" #include "tailerpp.hh" using namespace std::chrono_literals; static const auto HOST_RETRY_DELAY = 1min; static void read_err_pipe(const std::string& netloc, auto_fd& err, std::vector<std::string>& eq) { line_buffer lb; file_range pipe_range; bool done = false; log_info("stderr reader started..."); lb.set_fd(err); while (!done) { auto load_res = lb.load_next_line(pipe_range); if (load_res.isErr()) { done = true; } else { auto li = load_res.unwrap(); pipe_range = li.li_file_range; if (li.li_file_range.empty()) { done = true; } else { lb.read_range(li.li_file_range).then([netloc, &eq](auto sbr) { auto line_str = string_fragment(sbr.get_data(), 0, sbr.length()) .trim("\n"); if (eq.size() < 10) { eq.template emplace_back(line_str.to_string()); } auto level = line_str.startswith("error:") ? lnav_log_level_t::ERROR : line_str.startswith("warning:") ? lnav_log_level_t::WARNING : line_str.startswith("info:") ? lnav_log_level_t::INFO : lnav_log_level_t::DEBUG; log_msg_wrapper(level, "tailer[%s] %.*s", netloc.c_str(), line_str.length(), line_str.data()); }); } } } } static void update_tailer_progress(const std::string& netloc, const std::string& msg) { lnav_data.ld_active_files.fc_progress->writeAccess() ->sp_tailers[netloc] .tp_message = msg; } static void update_tailer_description( const std::string& netloc, const std::map<std::string, logfile_open_options_base>& desired_paths, const std::string& remote_uname) { std::vector<std::string> paths; for (const auto& des_pair : desired_paths) { paths.emplace_back( fmt::format(FMT_STRING("{}{}"), netloc, des_pair.first)); } isc::to<main_looper&, services::main_t>().send( [netloc, paths, remote_uname](auto& mlooper) { auto& fc = lnav_data.ld_active_files; for (const auto& path : paths) { auto iter = fc.fc_other_files.find(path); if (iter == fc.fc_other_files.end()) { continue; } iter->second.ofd_description = remote_uname; } fc.fc_name_to_errors->writeAccess()->erase(netloc); }); } void tailer::looper::loop_body() { auto now = std::chrono::steady_clock::now(); std::vector<std::string> to_erase; for (auto& qpair : this->l_netlocs_to_paths) { auto& netloc = qpair.first; auto& rpq = qpair.second; if (now < rpq.rpq_next_attempt_time) { continue; } if (this->l_remotes.count(netloc) == 0) { auto create_res = host_tailer::for_host(netloc); if (create_res.isErr()) { report_error(netloc, create_res.unwrapErr()); if (std::any_of( rpq.rpq_new_paths.begin(), rpq.rpq_new_paths.end(), [](const auto& pair) { return !pair.second.loo_tail; })) { rpq.send_synced_to_main(netloc); to_erase.push_back(netloc); } else { rpq.rpq_next_attempt_time = now + HOST_RETRY_DELAY; } continue; } auto ht = create_res.unwrap(); this->l_remotes[netloc] = ht; this->s_children.add_child_service(ht); rpq.rpq_new_paths.insert(rpq.rpq_existing_paths.begin(), rpq.rpq_existing_paths.end()); rpq.rpq_existing_paths.clear(); } if (!rpq.rpq_new_paths.empty()) { log_debug("%s: new paths to monitor -- %s", netloc.c_str(), rpq.rpq_new_paths.begin()->first.c_str()); this->l_remotes[netloc]->send( [paths = rpq.rpq_new_paths](auto& ht) { for (const auto& pair : paths) { log_debug("adding path to tailer -- %s", pair.first.c_str()); ht.open_remote_path(pair.first, std::move(pair.second)); } }); rpq.rpq_existing_paths.insert(rpq.rpq_new_paths.begin(), rpq.rpq_new_paths.end()); rpq.rpq_new_paths.clear(); } } for (const auto& netloc : to_erase) { this->l_netlocs_to_paths.erase(netloc); } } void tailer::looper::add_remote(const network::path& path, logfile_open_options_base options) { auto netloc_str = fmt::to_string(path.home()); this->l_netlocs_to_paths[netloc_str].rpq_new_paths[path.p_path] = std::move(options); } void tailer::looper::load_preview(int64_t id, const network::path& path) { auto netloc_str = fmt::to_string(path.home()); auto iter = this->l_remotes.find(netloc_str); if (iter == this->l_remotes.end()) { auto create_res = host_tailer::for_host(netloc_str); if (create_res.isErr()) { auto msg = create_res.unwrapErr(); isc::to<main_looper&, services::main_t>().send( [id, msg](auto& mlooper) { if (lnav_data.ld_preview_generation != id) { return; } lnav_data.ld_preview_status_source.get_description() .set_cylon(false) .clear(); lnav_data.ld_preview_source.clear(); lnav_data.ld_bottom_source.grep_error(msg); }); return; } auto ht = create_res.unwrap(); this->l_remotes[netloc_str] = ht; this->s_children.add_child_service(ht); } this->l_remotes[netloc_str]->send([id, file_path = path.p_path](auto& ht) { ht.load_preview(id, file_path); }); } void tailer::looper::complete_path(const network::path& path) { auto netloc_str = fmt::to_string(path.home()); auto iter = this->l_remotes.find(netloc_str); if (iter == this->l_remotes.end()) { auto create_res = host_tailer::for_host(netloc_str); if (create_res.isErr()) { return; } auto ht = create_res.unwrap(); this->l_remotes[netloc_str] = ht; this->s_children.add_child_service(ht); } this->l_remotes[netloc_str]->send( [file_path = path.p_path](auto& ht) { ht.complete_path(file_path); }); } static std::vector<std::string> create_ssh_args_from_config(const std::string& dest) { const auto& cfg = injector::get<const tailer::config&>(); std::vector<std::string> retval; retval.emplace_back(cfg.c_ssh_cmd); if (!cfg.c_ssh_flags.empty()) { if (startswith(cfg.c_ssh_flags, "-")) { retval.emplace_back(cfg.c_ssh_flags); } else { retval.emplace_back( fmt::format(FMT_STRING("-{}"), cfg.c_ssh_flags)); } } for (const auto& pair : cfg.c_ssh_options) { if (pair.second.empty()) { continue; } retval.emplace_back(fmt::format(FMT_STRING("-{}"), pair.first)); retval.emplace_back(pair.second); } for (const auto& pair : cfg.c_ssh_config) { if (pair.second.empty()) { continue; } retval.emplace_back( fmt::format(FMT_STRING("-o{}={}"), pair.first, pair.second)); } retval.emplace_back(dest); return retval; } Result<std::shared_ptr<tailer::looper::host_tailer>, std::string> tailer::looper::host_tailer::for_host(const std::string& netloc) { log_debug("tailer(%s): transferring tailer to remote", netloc.c_str()); update_tailer_progress(netloc, "Transferring tailer..."); auto& cfg = injector::get<const tailer::config&>(); auto tailer_bin_name = fmt::format(FMT_STRING("tailer.bin.{}"), getpid()); auto rp = humanize::network::path::from_str(netloc).value(); auto ssh_dest = rp.p_locality.l_hostname; if (rp.p_locality.l_username.has_value()) { ssh_dest = fmt::format(FMT_STRING("{}@{}"), rp.p_locality.l_username.value(), rp.p_locality.l_hostname); } { auto in_pipe = TRY(auto_pipe::for_child_fd(STDIN_FILENO)); auto out_pipe = TRY(auto_pipe::for_child_fd(STDOUT_FILENO)); auto err_pipe = TRY(auto_pipe::for_child_fd(STDERR_FILENO)); auto child = TRY(lnav::pid::from_fork()); in_pipe.after_fork(child.in()); out_pipe.after_fork(child.in()); err_pipe.after_fork(child.in()); if (child.in_child()) { auto arg_strs = create_ssh_args_from_config(ssh_dest); std::vector<char*> args; arg_strs.emplace_back( fmt::format(cfg.c_transfer_cmd, tailer_bin_name)); fmt::print(stderr, "tailer({}): executing -- {}\n", netloc, fmt::join(arg_strs, " ")); for (const auto& arg : arg_strs) { args.push_back((char*) arg.data()); } args.push_back(nullptr); execvp(cfg.c_ssh_cmd.c_str(), args.data()); _exit(EXIT_FAILURE); } std::vector<std::string> error_queue; log_debug("tailer(%s): starting err reader", netloc.c_str()); std::thread err_reader([netloc, err = std::move(err_pipe.read_end()), &error_queue]() mutable { log_set_thread_prefix( fmt::format(FMT_STRING("tailer({})"), netloc)); read_err_pipe(netloc, err, error_queue); }); log_debug("tailer(%s): writing to child", netloc.c_str()); auto sf = tailer_bin[0].to_string_fragment(); ssize_t total_bytes = 0; bool write_failed = false; while (total_bytes < sf.length()) { log_debug("attempting to write %d", sf.length() - total_bytes); auto rc = write( in_pipe.write_end(), sf.data(), sf.length() - total_bytes); if (rc < 0) { log_error(" tailer(%s): write failed -- %s", netloc.c_str(), strerror(errno)); write_failed = true; break; } log_debug(" wrote %d", rc); total_bytes += rc; } in_pipe.write_end().reset(); while (!write_failed) { char buffer[1024]; auto rc = read(out_pipe.read_end(), buffer, sizeof(buffer)); if (rc < 0) { break; } if (rc == 0) { break; } log_debug("tailer(%s): transfer output -- %.*s", netloc.c_str(), rc, buffer); } auto finished_child = std::move(child).wait_for_child(); err_reader.join(); if (!finished_child.was_normal_exit() || finished_child.exit_status() != EXIT_SUCCESS) { auto error_msg = error_queue.empty() ? "unknown" : error_queue.back(); return Err(fmt::format(FMT_STRING("failed to ssh to host: {}"), error_msg)); } } update_tailer_progress(netloc, "Starting tailer..."); auto in_pipe = TRY(auto_pipe::for_child_fd(STDIN_FILENO)); auto out_pipe = TRY(auto_pipe::for_child_fd(STDOUT_FILENO)); auto err_pipe = TRY(auto_pipe::for_child_fd(STDERR_FILENO)); auto child = TRY(lnav::pid::from_fork()); in_pipe.after_fork(child.in()); out_pipe.after_fork(child.in()); err_pipe.after_fork(child.in()); if (child.in_child()) { auto arg_strs = create_ssh_args_from_config(ssh_dest); std::vector<char*> args; arg_strs.emplace_back(fmt::format(cfg.c_start_cmd, tailer_bin_name)); fmt::print(stderr, FMT_STRING("tailer({}): executing -- {}\n"), netloc, fmt::join(arg_strs, " ")); for (const auto& arg : arg_strs) { args.push_back((char*) arg.data()); } args.push_back(nullptr); execvp(cfg.c_ssh_cmd.c_str(), args.data()); _exit(EXIT_FAILURE); } return Ok(std::make_shared<host_tailer>(netloc, std::move(child), std::move(in_pipe.write_end()), std::move(out_pipe.read_end()), std::move(err_pipe.read_end()))); } static ghc::filesystem::path remote_cache_path() { return lnav::paths::workdir() / "remotes"; } ghc::filesystem::path tailer::looper::host_tailer::tmp_path() { auto local_path = remote_cache_path(); ghc::filesystem::create_directories(local_path); auto_mem<char> resolved_path; resolved_path = realpath(local_path.c_str(), nullptr); if (resolved_path.in() == nullptr) { return local_path; } return resolved_path.in(); } static std::string scrub_netloc(const std::string& netloc) { const static std::regex TO_SCRUB(R"([^\w\.\@])"); return std::regex_replace(netloc, TO_SCRUB, "_"); } tailer::looper::host_tailer::host_tailer(const std::string& netloc, auto_pid<process_state::running> child, auto_fd to_child, auto_fd from_child, auto_fd err_from_child) : isc::service<host_tailer>(netloc), ht_netloc(netloc), ht_local_path(tmp_path() / scrub_netloc(netloc)), ht_error_reader([netloc, err = std::move(err_from_child), &eq = this->ht_error_queue]() mutable { read_err_pipe(netloc, err, eq); }), ht_state(connected{ std::move(child), std::move(to_child), std::move(from_child), {}}) { } void tailer::looper::host_tailer::open_remote_path(const std::string& path, logfile_open_options_base loo) { this->ht_state.match( [&](connected& conn) { conn.c_desired_paths[path] = std::move(loo); send_packet(conn.ht_to_child.get(), TPT_OPEN_PATH, TPPT_STRING, path.c_str(), TPPT_DONE); }, [&](const disconnected& d) { log_warning("disconnected from host, cannot tail: %s", path.c_str()); }, [&](const synced& s) { log_warning("synced with host, not tailing: %s", path.c_str()); }); } void tailer::looper::host_tailer::load_preview(int64_t id, const std::string& path) { this->ht_state.match( [&](connected& conn) { send_packet(conn.ht_to_child.get(), TPT_LOAD_PREVIEW, TPPT_STRING, path.c_str(), TPPT_INT64, id, TPPT_DONE); }, [&](const disconnected& d) { log_warning("disconnected from host, cannot preview: %s", path.c_str()); auto msg = fmt::format(FMT_STRING("error: disconnected from {}"), this->ht_netloc); isc::to<main_looper&, services::main_t>().send([=](auto& mlooper) { if (lnav_data.ld_preview_generation != id) { return; } lnav_data.ld_preview_status_source.get_description() .set_cylon(false) .set_value(msg); }); }, [&](const synced& s) { require(false); }); } void tailer::looper::host_tailer::complete_path(const std::string& path) { this->ht_state.match( [&](connected& conn) { send_packet(conn.ht_to_child.get(), TPT_COMPLETE_PATH, TPPT_STRING, path.c_str(), TPPT_DONE); }, [&](const disconnected& d) { log_warning("disconnected from host, cannot preview: %s", path.c_str()); }, [&](const synced& s) { require(false); }); } void tailer::looper::host_tailer::loop_body() { const static uint64_t TOUCH_FREQ = 10000; if (!this->ht_state.is<connected>()) { return; } this->ht_cycle_count += 1; if (this->ht_cycle_count % TOUCH_FREQ == 0) { auto now = ghc::filesystem::file_time_type{std::chrono::system_clock::now()}; ghc::filesystem::last_write_time(this->ht_local_path, now); } auto& conn = this->ht_state.get<connected>(); pollfd pfds[1]; pfds[0].fd = conn.ht_from_child.get(); pfds[0].events = POLLIN; pfds[0].revents = 0; auto ready_count = poll(pfds, 1, 100); if (ready_count > 0) { auto read_res = tailer::read_packet(conn.ht_from_child); if (read_res.isErr()) { log_error("read error: %s", read_res.unwrapErr().c_str()); return; } auto packet = read_res.unwrap(); this->ht_state = packet.match( [&](const tailer::packet_eof& te) { log_debug("all done!"); auto finished_child = std::move(conn).close(); if (finished_child.exit_status() != 0 && !this->ht_error_queue.empty()) { report_error(this->ht_netloc, this->ht_error_queue.back()); } return state_v{disconnected()}; }, [&](const tailer::packet_announce& pa) { update_tailer_description( this->ht_netloc, conn.c_desired_paths, pa.pa_uname); this->ht_uname = pa.pa_uname; return std::move(this->ht_state); }, [&](const tailer::packet_log& pl) { log_debug("%s\n", pl.pl_msg.c_str()); return std::move(this->ht_state); }, [&](const tailer::packet_error& pe) { log_debug("Got an error: %s -- %s", pe.pe_path.c_str(), pe.pe_msg.c_str()); lnav_data.ld_active_files.fc_progress->writeAccess() ->sp_tailers.erase(this->ht_netloc); auto desired_iter = conn.c_desired_paths.find(pe.pe_path); if (desired_iter != conn.c_desired_paths.end()) { report_error(this->get_display_path(pe.pe_path), pe.pe_msg); if (!desired_iter->second.loo_tail) { conn.c_desired_paths.erase(desired_iter); } } else { auto child_iter = conn.c_child_paths.find(pe.pe_path); if (child_iter != conn.c_child_paths.end() && !child_iter->second.loo_tail) { conn.c_child_paths.erase(child_iter); } } auto remote_path = ghc::filesystem::absolute( ghc::filesystem::path(pe.pe_path)) .relative_path(); auto local_path = this->ht_local_path / remote_path; log_debug("removing %s", local_path.c_str()); this->ht_active_files.erase(local_path); ghc::filesystem::remove_all(local_path); if (conn.c_desired_paths.empty() && conn.c_child_paths.empty()) { log_info("tailer(%s): all desired paths synced", this->ht_netloc.c_str()); return state_v{synced{}}; } return std::move(this->ht_state); }, [&](const tailer::packet_offer_block& pob) { log_debug("Got an offer: %s %lld - %lld", pob.pob_path.c_str(), pob.pob_offset, pob.pob_length); logfile_open_options_base loo; if (pob.pob_path == pob.pob_root_path) { auto root_iter = conn.c_desired_paths.find(pob.pob_path); if (root_iter == conn.c_desired_paths.end()) { log_warning("ignoring unknown root: %s", pob.pob_root_path.c_str()); return std::move(this->ht_state); } loo = root_iter->second; } else { auto child_iter = conn.c_child_paths.find(pob.pob_path); if (child_iter == conn.c_child_paths.end()) { auto root_iter = conn.c_desired_paths.find(pob.pob_root_path); if (root_iter == conn.c_desired_paths.end()) { log_warning("ignoring child of unknown root: %s", pob.pob_root_path.c_str()); return std::move(this->ht_state); } conn.c_child_paths[pob.pob_path] = std::move(root_iter->second); child_iter = conn.c_child_paths.find(pob.pob_path); } loo = std::move(child_iter->second); } update_tailer_description( this->ht_netloc, conn.c_desired_paths, this->ht_uname); auto remote_path = ghc::filesystem::absolute( ghc::filesystem::path(pob.pob_path)) .relative_path(); auto local_path = this->ht_local_path / remote_path; auto open_res = lnav::filesystem::open_file(local_path, O_RDONLY); if (this->ht_active_files.count(local_path) == 0) { this->ht_active_files.insert(local_path); auto custom_name = this->get_display_path(pob.pob_path); isc::to<main_looper&, services::main_t>().send( [local_path, custom_name, loo, netloc = this->ht_netloc](auto& mlooper) { auto& active_fc = lnav_data.ld_active_files; auto lpath_str = local_path.string(); { safe::WriteAccess<safe_scan_progress> sp( *active_fc.fc_progress); sp->sp_tailers.erase(netloc); } if (active_fc.fc_file_names.count(lpath_str) > 0) { log_debug("already in fc_file_names"); return; } if (active_fc.fc_closed_files.count(custom_name) > 0) { log_debug("in closed"); return; } file_collection fc; fc.fc_file_names[lpath_str] .with_filename(custom_name) .with_source(logfile_name_source::REMOTE) .with_tail(loo.loo_tail) .with_non_utf_visibility(false) .with_visible_size_limit(256 * 1024); update_active_files(fc); }); } if (open_res.isErr()) { log_debug("file not found (%s), sending need block", open_res.unwrapErr().c_str()); send_packet(conn.ht_to_child.get(), TPT_NEED_BLOCK, TPPT_STRING, pob.pob_path.c_str(), TPPT_DONE); return std::move(this->ht_state); } auto fd = open_res.unwrap(); struct stat st; if (fstat(fd, &st) == -1 || !S_ISREG(st.st_mode)) { log_debug("path changed, sending need block"); ghc::filesystem::remove_all(local_path); send_packet(conn.ht_to_child.get(), TPT_NEED_BLOCK, TPPT_STRING, pob.pob_path.c_str(), TPPT_DONE); return std::move(this->ht_state); } if (st.st_size == pob.pob_offset) { log_debug("local file is synced, sending need block"); send_packet(conn.ht_to_child.get(), TPT_NEED_BLOCK, TPPT_STRING, pob.pob_path.c_str(), TPPT_DONE); return std::move(this->ht_state); } constexpr int64_t BUFFER_SIZE = 4 * 1024 * 1024; auto buffer = auto_mem<unsigned char>::malloc(BUFFER_SIZE); auto remaining = pob.pob_length; auto remaining_offset = pob.pob_offset; tailer::hash_frag thf; SHA256_CTX shactx; sha256_init(&shactx); log_debug("checking offer %s[%lld..+%lld]", local_path.c_str(), remaining_offset, remaining); while (remaining > 0) { auto nbytes = std::min(remaining, BUFFER_SIZE); auto bytes_read = pread(fd, buffer, nbytes, remaining_offset); if (bytes_read == -1) { log_debug( "unable to read file, sending need block -- %s", strerror(errno)); ghc::filesystem::remove_all(local_path); break; } if (bytes_read == 0) { break; } sha256_update(&shactx, buffer.in(), bytes_read); remaining -= bytes_read; remaining_offset += bytes_read; } if (remaining == 0) { sha256_final(&shactx, thf.thf_hash); if (thf == pob.pob_hash) { log_debug("local file block is same, sending ack"); send_packet(conn.ht_to_child.get(), TPT_ACK_BLOCK, TPPT_STRING, pob.pob_path.c_str(), TPPT_INT64, pob.pob_offset, TPPT_INT64, pob.pob_length, TPPT_INT64, (int64_t) st.st_size, TPPT_DONE); return std::move(this->ht_state); } log_debug("local file is different, sending need block"); } send_packet(conn.ht_to_child.get(), TPT_NEED_BLOCK, TPPT_STRING, pob.pob_path.c_str(), TPPT_DONE); return std::move(this->ht_state); }, [&](const tailer::packet_tail_block& ptb) { auto remote_path = ghc::filesystem::absolute( ghc::filesystem::path(ptb.ptb_path)) .relative_path(); auto local_path = this->ht_local_path / remote_path; log_debug("writing tail to: %lld/%ld %s", ptb.ptb_offset, ptb.ptb_bits.size(), local_path.c_str()); ghc::filesystem::create_directories(local_path.parent_path()); auto create_res = lnav::filesystem::create_file( local_path, O_WRONLY | O_APPEND | O_CREAT, 0600); if (create_res.isErr()) { log_error("open: %s", create_res.unwrapErr().c_str()); } else { auto fd = create_res.unwrap(); ftruncate(fd, ptb.ptb_offset); pwrite(fd, ptb.ptb_bits.data(), ptb.ptb_bits.size(), ptb.ptb_offset); auto mtime = ghc::filesystem::file_time_type{ std::chrono::seconds{ptb.ptb_mtime}}; // XXX This isn't atomic with the write... ghc::filesystem::last_write_time(local_path, mtime); } return std::move(this->ht_state); }, [&](const tailer::packet_synced& ps) { if (ps.ps_root_path == ps.ps_path) { auto iter = conn.c_desired_paths.find(ps.ps_path); if (iter != conn.c_desired_paths.end()) { if (iter->second.loo_tail) { conn.c_synced_desired_paths.insert(ps.ps_path); } else { log_info("synced desired path: %s", iter->first.c_str()); conn.c_desired_paths.erase(iter); } } } else { auto iter = conn.c_child_paths.find(ps.ps_path); if (iter != conn.c_child_paths.end()) { if (iter->second.loo_tail) { conn.c_synced_child_paths.insert(ps.ps_path); } else { log_info("synced child path: %s", iter->first.c_str()); conn.c_child_paths.erase(iter); } } } if (conn.c_desired_paths.empty() && conn.c_child_paths.empty()) { log_info("tailer(%s): all desired paths synced", this->ht_netloc.c_str()); return state_v{synced{}}; } else if (!conn.c_initial_sync_done && conn.c_desired_paths.size() == conn.c_synced_desired_paths.size() && conn.c_child_paths.size() == conn.c_synced_child_paths.size()) { log_info("tailer(%s): all desired paths synced", this->ht_netloc.c_str()); conn.c_initial_sync_done = true; std::set<std::string> synced_files; for (const auto& desired_pair : conn.c_desired_paths) { synced_files.emplace(fmt::format( FMT_STRING("{}{}"), ht_netloc, desired_pair.first)); } isc::to<main_looper&, services::main_t>().send( [file_set = std::move(synced_files)](auto& mlooper) { file_collection fc; fc.fc_synced_files = file_set; update_active_files(fc); }); } return std::move(this->ht_state); }, [&](const tailer::packet_link& pl) { auto remote_path = ghc::filesystem::absolute( ghc::filesystem::path(pl.pl_path)) .relative_path(); auto local_path = this->ht_local_path / remote_path; auto remote_link_path = ghc::filesystem::path(pl.pl_link_value); std::string link_path; if (remote_link_path.is_absolute()) { auto local_link_path = this->ht_local_path / remote_link_path.relative_path(); link_path = local_link_path.string(); } else { link_path = remote_link_path.string(); } log_debug("symlinking %s -> %s", local_path.c_str(), link_path.c_str()); ghc::filesystem::create_directories(local_path.parent_path()); ghc::filesystem::remove_all(local_path); if (symlink(link_path.c_str(), local_path.c_str()) < 0) { log_error("symlink failed: %s", strerror(errno)); } if (pl.pl_root_path == pl.pl_path) { auto iter = conn.c_desired_paths.find(pl.pl_path); if (iter != conn.c_desired_paths.end()) { if (iter->second.loo_tail) { conn.c_synced_desired_paths.insert(pl.pl_path); } else { log_info("synced desired path: %s", iter->first.c_str()); conn.c_desired_paths.erase(iter); } } } else { auto iter = conn.c_child_paths.find(pl.pl_path); if (iter != conn.c_child_paths.end()) { if (iter->second.loo_tail) { conn.c_synced_child_paths.insert(pl.pl_path); } else { log_info("synced child path: %s", iter->first.c_str()); conn.c_child_paths.erase(iter); } } } return std::move(this->ht_state); }, [&](const tailer::packet_preview_error& ppe) { isc::to<main_looper&, services::main_t>().send( [ppe](auto& mlooper) { if (lnav_data.ld_preview_generation != ppe.ppe_id) { log_debug("preview ID mismatch: %lld != %lld", lnav_data.ld_preview_generation, ppe.ppe_id); return; } lnav_data.ld_preview_status_source.get_description() .set_cylon(false) .clear(); lnav_data.ld_preview_source.clear(); lnav_data.ld_bottom_source.grep_error(ppe.ppe_msg); }); return std::move(this->ht_state); }, [&](const tailer::packet_preview_data& ppd) { isc::to<main_looper&, services::main_t>().send( [netloc = this->ht_netloc, ppd](auto& mlooper) { if (lnav_data.ld_preview_generation != ppd.ppd_id) { log_debug("preview ID mismatch: %lld != %lld", lnav_data.ld_preview_generation, ppd.ppd_id); return; } std::string str(ppd.ppd_bits.begin(), ppd.ppd_bits.end()); lnav_data.ld_preview_status_source.get_description() .set_cylon(false) .set_value("For file: %s:%s", netloc.c_str(), ppd.ppd_path.c_str()); lnav_data.ld_preview_source.replace_with(str) .set_text_format(detect_text_format(str)); }); return std::move(this->ht_state); }, [&](const tailer::packet_possible_path& ppp) { log_debug("possible path: %s", ppp.ppp_path.c_str()); auto full_path = fmt::format( FMT_STRING("{}{}"), this->ht_netloc, ppp.ppp_path); isc::to<main_looper&, services::main_t>().send( [full_path](auto& mlooper) { lnav_data.ld_rl_view->add_possibility( ln_mode_t::COMMAND, "remote-path", full_path); }); return std::move(this->ht_state); }); if (!this->ht_state.is<connected>()) { this->s_looping = false; } } } std::chrono::milliseconds tailer::looper::host_tailer::compute_timeout(mstime_t current_time) const { return 0s; } void tailer::looper::host_tailer::stopped() { if (this->ht_state.is<connected>()) { this->ht_state = disconnected(); } if (this->ht_error_reader.joinable()) { this->ht_error_reader.join(); } } std::string tailer::looper::host_tailer::get_display_path( const std::string& remote_path) const { return fmt::format(FMT_STRING("{}{}"), this->ht_netloc, remote_path); } void* tailer::looper::host_tailer::run() { log_set_thread_prefix( fmt::format(FMT_STRING("tailer({})"), this->ht_netloc)); return service_base::run(); } auto_pid<process_state::finished> tailer::looper::host_tailer::connected::close() && { this->ht_to_child.reset(); this->ht_from_child.reset(); return std::move(this->ht_child).wait_for_child(); } void tailer::looper::child_finished(std::shared_ptr<service_base> child) { auto child_tailer = std::static_pointer_cast<host_tailer>(child); for (auto iter = this->l_remotes.begin(); iter != this->l_remotes.end(); ++iter) { if (iter->second != child_tailer) { continue; } if (child_tailer->is_synced()) { log_info("synced with netloc '%s', removing", iter->first.c_str()); auto netloc_iter = this->l_netlocs_to_paths.find(iter->first); if (netloc_iter != this->l_netlocs_to_paths.end()) { netloc_iter->second.send_synced_to_main(netloc_iter->first); this->l_netlocs_to_paths.erase(netloc_iter); } } lnav_data.ld_active_files.fc_progress->writeAccess()->sp_tailers.erase( iter->first); this->l_remotes.erase(iter); return; } } void tailer::looper::remote_path_queue::send_synced_to_main( const std::string& netloc) { std::set<std::string> synced_files; for (const auto& pair : this->rpq_new_paths) { if (!pair.second.loo_tail) { synced_files.emplace( fmt::format(FMT_STRING("{}{}"), netloc, pair.first)); } } for (const auto& pair : this->rpq_existing_paths) { if (!pair.second.loo_tail) { synced_files.emplace( fmt::format(FMT_STRING("{}{}"), netloc, pair.first)); } } isc::to<main_looper&, services::main_t>().send( [file_set = std::move(synced_files)](auto& mlooper) { file_collection fc; fc.fc_synced_files = file_set; update_active_files(fc); }); } void tailer::looper::report_error(std::string path, std::string msg) { log_error("reporting error: %s -- %s", path.c_str(), msg.c_str()); isc::to<main_looper&, services::main_t>().send([=](auto& mlooper) { file_collection fc; fc.fc_name_to_errors->writeAccess()->emplace(path, file_error_info{ {}, msg, }); update_active_files(fc); lnav_data.ld_active_files.fc_progress->writeAccess()->sp_tailers.erase( path); }); } void tailer::cleanup_cache() { (void) std::async(std::launch::async, []() { auto now = std::chrono::system_clock::now(); auto cache_path = remote_cache_path(); const auto& cfg = injector::get<const config&>(); std::vector<ghc::filesystem::path> to_remove; log_debug("cache-ttl %d", cfg.c_cache_ttl.count()); for (const auto& entry : ghc::filesystem::directory_iterator(cache_path)) { auto mtime = ghc::filesystem::last_write_time(entry.path()); auto exp_time = mtime + cfg.c_cache_ttl; if (now < exp_time) { continue; } to_remove.emplace_back(entry.path()); } for (auto& entry : to_remove) { log_debug("removing cached remote: %s", entry.c_str()); ghc::filesystem::remove_all(entry); } }); }
#ifndef NO_ASSIGNMENT_POSSIBLE_H #define NO_ASSIGNMENT_POSSIBLE_H #include <exception> class No_Assignment_Possible : public std::exception { public: No_Assignment_Possible() noexcept {} No_Assignment_Possible(const No_Assignment_Possible&) noexcept = default; No_Assignment_Possible& operator=(const No_Assignment_Possible&) noexcept = default; virtual ~No_Assignment_Possible() noexcept = default; virtual const char* what() const noexcept{ return "Nu este permis assignment pentru obiecte ce contin membrii constanti!"; } }; #endif // NO_ASSIGNMENT_POSSIBLE_H
// $Id$ // // Copyright (C) 2004-2012 Greg Landrum and Rational Discovery LLC // // @@ All Rights Reserved @@ // This file is part of the RDKit. // The contents are covered by the terms of the BSD license // which is included in the file license.txt, found at the root // of the RDKit source tree. // #include <iostream> #include <fstream> #include <boost/algorithm/string.hpp> #include <boost/algorithm/string/trim.hpp> #include <boost/lexical_cast.hpp> #include <RDGeneral/Invariant.h> #include <RDGeneral/RDLog.h> #include <RDGeneral/utils.h> #include <RDGeneral/StreamOps.h> #include <GraphMol/RDKitBase.h> #include <GraphMol/MolPickler.h> #include <GraphMol/SmilesParse/SmilesParse.h> #include <GraphMol/SmilesParse/SmilesWrite.h> #include <GraphMol/FileParsers/FileParsers.h> #include <GraphMol/FileParsers/MolSupplier.h> #include <GraphMol/Descriptors/MolDescriptors.h> #include <GraphMol/Descriptors/Crippen.h> #include <DataStructs/BitVects.h> #include <DataStructs/BitOps.h> using namespace RDKit; using namespace RDKit::Descriptors; void test1(){ BOOST_LOG(rdErrorLog) << "-------------------------------------" << std::endl; BOOST_LOG(rdErrorLog) << " Test Crippen parameter acquisition." << std::endl; const CrippenParamCollection *params=CrippenParamCollection::getParams(); TEST_ASSERT(params); CrippenParams p=*(params->begin()); TEST_ASSERT(p.idx==0); TEST_ASSERT(p.label=="C1"); TEST_ASSERT(p.smarts=="[CH4]"); BOOST_LOG(rdErrorLog) << " done" << std::endl; } void test2(){ BOOST_LOG(rdErrorLog) << "-------------------------------------" << std::endl; BOOST_LOG(rdErrorLog) << " Test Crippen calculation." << std::endl; ROMol *mol; double logp,mr; mol = SmilesToMol("C"); TEST_ASSERT(mol); calcCrippenDescriptors(*mol,logp,mr); TEST_ASSERT(feq(logp,0.6361)); TEST_ASSERT(feq(mr,6.7310)); // check that caching works: calcCrippenDescriptors(*mol,logp,mr); TEST_ASSERT(feq(logp,0.6361)); TEST_ASSERT(feq(mr,6.7310)); calcCrippenDescriptors(*mol,logp,mr,true,true); TEST_ASSERT(feq(logp,0.6361)); TEST_ASSERT(feq(mr,6.7310)); // check that things work when we don't add Hs: calcCrippenDescriptors(*mol,logp,mr,false,true); TEST_ASSERT(feq(logp,0.1441)); TEST_ASSERT(feq(mr,2.503)); delete mol; mol = SmilesToMol("C=C"); TEST_ASSERT(mol); calcCrippenDescriptors(*mol,logp,mr,true); TEST_ASSERT(feq(logp,0.8022)); TEST_ASSERT(feq(mr,11.2540)); delete mol; mol = SmilesToMol("C#C"); TEST_ASSERT(mol); calcCrippenDescriptors(*mol,logp,mr); TEST_ASSERT(feq(logp,0.2494)); TEST_ASSERT(feq(mr,9.8900)); delete mol; mol = SmilesToMol("CO"); TEST_ASSERT(mol); calcCrippenDescriptors(*mol,logp,mr); TEST_ASSERT(feq(logp,-0.3915)); TEST_ASSERT(feq(mr,8.1428)); delete mol; mol = SmilesToMol("C=O"); TEST_ASSERT(mol); calcCrippenDescriptors(*mol,logp,mr); TEST_ASSERT(feq(logp,-0.1849)); TEST_ASSERT(feq(mr,7.121)); delete mol; mol = SmilesToMol("C#[O+]"); TEST_ASSERT(mol); calcCrippenDescriptors(*mol,logp,mr); TEST_ASSERT(feq(logp,0.0059)); TEST_ASSERT(feq(mr,5.6315)); delete mol; mol = SmilesToMol("C(C)(C)C"); TEST_ASSERT(mol); calcCrippenDescriptors(*mol,logp,mr); TEST_ASSERT(feq(logp,1.6623)); TEST_ASSERT(feq(mr,20.512)); delete mol; mol = SmilesToMol("C(C)(C)(C)O"); TEST_ASSERT(mol); calcCrippenDescriptors(*mol,logp,mr); TEST_ASSERT(feq(logp,0.7772)); TEST_ASSERT(feq(mr,21.9718)); delete mol; BOOST_LOG(rdErrorLog) << " done" << std::endl; } void testIssue262(){ BOOST_LOG(rdErrorLog) << "-------------------------------------" << std::endl; BOOST_LOG(rdErrorLog) << " Test Issue262: problems with Crippen calculation from pickles." << std::endl; ROMol *mol,*mol2; RWMol *mol3; std::string pkl; double rlogp,rmr,logp,mr; mol = SmilesToMol("c1ncccc1"); TEST_ASSERT(mol); calcCrippenDescriptors(*mol,rlogp,rmr); MolPickler::pickleMol(*mol,pkl); mol2=new ROMol(pkl); TEST_ASSERT(mol2); calcCrippenDescriptors(*mol2,logp,mr); TEST_ASSERT(feq(logp,rlogp)); TEST_ASSERT(feq(mr,rmr)); mol3=new RWMol(); TEST_ASSERT(mol3); MolPickler::molFromPickle(pkl,mol3); calcCrippenDescriptors(*mol3,logp,mr); TEST_ASSERT(feq(logp,rlogp)); TEST_ASSERT(feq(mr,rmr)); delete mol; delete mol2; delete mol3; BOOST_LOG(rdErrorLog) << " done" << std::endl; } void test3(){ BOOST_LOG(rdErrorLog) << "-------------------------------------" << std::endl; BOOST_LOG(rdErrorLog) << " Test AMW calculation." << std::endl; ROMol *mol,*mol2; double amw; mol = SmilesToMol("C"); TEST_ASSERT(mol); amw = calcAMW(*mol); TEST_ASSERT(feq(amw,16.043,.001)); amw = calcAMW(*mol,true); TEST_ASSERT(feq(amw,12.011,.001)); mol2 = MolOps::addHs(*mol); amw = calcAMW(*mol2); TEST_ASSERT(feq(amw,16.043,.001)); amw = calcAMW(*mol2,true); TEST_ASSERT(feq(amw,12.011,.001)); delete mol; delete mol2; mol = SmilesToMol("[CH4]"); TEST_ASSERT(mol); amw = calcAMW(*mol); TEST_ASSERT(feq(amw,16.043,.001)); amw = calcAMW(*mol,true); TEST_ASSERT(feq(amw,12.011,.001)); delete mol; mol = SmilesToMol("C[2H]"); TEST_ASSERT(mol); amw = calcAMW(*mol); TEST_ASSERT(feq(amw,17.0,.1)); BOOST_LOG(rdErrorLog) << " done" << std::endl; } void test3a(){ BOOST_LOG(rdErrorLog) << "-------------------------------------" << std::endl; BOOST_LOG(rdErrorLog) << " Test Exact MW calculation." << std::endl; ROMol *mol,*mol2; double mw; mol = SmilesToMol("C"); TEST_ASSERT(mol); mw = calcExactMW(*mol); TEST_ASSERT(feq(mw,16.031,.001)); mw = calcExactMW(*mol,true); TEST_ASSERT(feq(mw,12.000,.001)); mol2 = MolOps::addHs(*mol); mw = calcExactMW(*mol2); TEST_ASSERT(feq(mw,16.031,.001)); mw = calcExactMW(*mol2,true); TEST_ASSERT(feq(mw,12.000,.001)); delete mol; delete mol2; mol = SmilesToMol("[CH4]"); TEST_ASSERT(mol); mw = calcExactMW(*mol); TEST_ASSERT(feq(mw,16.031,.001)); mw = calcExactMW(*mol,true); TEST_ASSERT(feq(mw,12.000,.001)); delete mol; mol = SmilesToMol("C[2H]"); TEST_ASSERT(mol); mw = calcExactMW(*mol); TEST_ASSERT(feq(mw,17.037,.001)); mw = calcExactMW(*mol,true); TEST_ASSERT(feq(mw,12.000,.001)); delete mol; mol = SmilesToMol("Cl"); TEST_ASSERT(mol); mw = calcAMW(*mol); TEST_ASSERT(feq(mw,35.453+1.008,.001)); mw = calcExactMW(*mol); TEST_ASSERT(feq(mw,34.9688+1.0078,.001)); delete mol; mol = SmilesToMol("[35ClH]"); TEST_ASSERT(mol); mw = calcAMW(*mol); TEST_ASSERT(feq(mw,34.9688+1.008,.001)); mw = calcExactMW(*mol); TEST_ASSERT(feq(mw,34.9688+1.0078,.001)); delete mol; mol = SmilesToMol("[36ClH]"); TEST_ASSERT(mol); mw = calcAMW(*mol); TEST_ASSERT(feq(mw,35.9683+1.008,.001)); mw = calcExactMW(*mol); TEST_ASSERT(feq(mw,35.9683+1.0078,.001)); delete mol; BOOST_LOG(rdErrorLog) << " done" << std::endl; } void testLabute(){ BOOST_LOG(rdErrorLog) << "-------------------------------------" << std::endl; BOOST_LOG(rdErrorLog) << " Test Labute ASA descriptors." << std::endl; ROMol *mol; double asa; mol = SmilesToMol("CO"); asa=calcLabuteASA(*mol); TEST_ASSERT(feq(asa,13.5335,.0001)); asa=calcLabuteASA(*mol); TEST_ASSERT(feq(asa,13.5335,.0001)); asa=calcLabuteASA(*mol,true,true); TEST_ASSERT(feq(asa,13.5335,.0001)); delete mol; mol = SmilesToMol("OC(=O)c1ccncc1C(=O)O"); asa=calcLabuteASA(*mol); TEST_ASSERT(feq(asa,67.2924,.0001)); delete mol; mol = SmilesToMol("C1CCC(c2cccnc2)NC1"); asa=calcLabuteASA(*mol); TEST_ASSERT(feq(asa,73.0198,.0001)); delete mol; BOOST_LOG(rdErrorLog) << " done" << std::endl; } void testTPSA(){ BOOST_LOG(rdErrorLog) << "-------------------------------------" << std::endl; BOOST_LOG(rdErrorLog) << " Test TPSA descriptors." << std::endl; std::string fName = getenv("RDBASE"); fName += "/Data/NCI/first_200.tpsa.csv"; std::ifstream inf(fName.c_str()); TEST_ASSERT(inf && !inf.bad()); while(!inf.eof()){ std::string inl=getLine(inf); boost::trim(inl); if(inl.size()==0 || inl[0]=='#') continue; std::vector<std::string> tokens; boost::split(tokens,inl,boost::is_any_of(",")); if(tokens.size()!=2) continue; std::string smiles=tokens[0]; double oTPSA=boost::lexical_cast<double>(tokens[1]); ROMol *mol = SmilesToMol(smiles); TEST_ASSERT(mol); double nTPSA = calcTPSA(*mol); if(!feq(nTPSA,oTPSA,.0001)){ std::cerr<<" TPSA ERR: "<<smiles<<" "<<oTPSA<<" "<<nTPSA<<std::endl; std::vector<double> contribs(mol->getNumAtoms()); getTPSAAtomContribs(*mol,contribs); for(unsigned int i=0;i<mol->getNumAtoms();++i){ std::cerr<<"\t"<<i<<"\t"<<contribs[i]<<std::endl; } } TEST_ASSERT(feq(nTPSA,oTPSA,.0001)); // make sure that adding Hs doesn't affect the value // (this was issue 1969745) ROMol *mol2 = MolOps::addHs(*mol); double hTPSA=calcTPSA(*mol2); TEST_ASSERT(feq(nTPSA,hTPSA,.0001)); delete mol2; delete mol; } BOOST_LOG(rdErrorLog) << " done" << std::endl; } void testLipinski1(){ BOOST_LOG(rdErrorLog) << "-------------------------------------" << std::endl; BOOST_LOG(rdErrorLog) << " Test Lipinski parameters." << std::endl; std::string fName = getenv("RDBASE"); fName += "/Data/NCI/first_200.props.sdf"; SDMolSupplier suppl(fName); int idx=-1; while(!suppl.atEnd()){ ROMol *mol=0; ++idx; try{ mol=suppl.next(); } catch(...){ continue; } if(!mol) continue; unsigned int oVal,nVal; std::string foo; mol->getProp("NUM_HACCEPTORS",foo); oVal=boost::lexical_cast<unsigned int>(foo); nVal = calcNumHBA(*mol); if(oVal!=nVal){ std::cerr<<" failed: "<<idx<<" "<<oVal<<" "<<nVal<<std::endl; } TEST_ASSERT(oVal==nVal); mol->getProp("NUM_HDONORS",foo); oVal=boost::lexical_cast<unsigned int>(foo); nVal = calcNumHBD(*mol); if(oVal!=nVal){ std::cerr<<" failed: "<<idx<<" "<<oVal<<" "<<nVal<<std::endl; } TEST_ASSERT(oVal==nVal); mol->getProp("NUM_LIPINSKIHDONORS",foo); oVal=boost::lexical_cast<unsigned int>(foo); nVal = calcLipinskiHBD(*mol); if(oVal!=nVal){ std::cerr<<" failed: "<<idx<<" "<<oVal<<" "<<nVal<<std::endl; } TEST_ASSERT(oVal==nVal); mol->getProp("NUM_LIPINSKIHACCEPTORS",foo); oVal=boost::lexical_cast<unsigned int>(foo); nVal = calcLipinskiHBA(*mol); if(oVal!=nVal){ std::cerr<<" failed: "<<idx<<" "<<oVal<<" "<<nVal<<std::endl; } TEST_ASSERT(oVal==nVal); mol->getProp("NUM_RINGS",foo); oVal=boost::lexical_cast<unsigned int>(foo); nVal = calcNumRings(*mol); if(oVal!=nVal){ std::cerr<<" failed: "<<idx<<" "<<oVal<<" "<<nVal<<std::endl; } TEST_ASSERT(oVal==nVal); mol->getProp("NUM_HETEROATOMS",foo); oVal=boost::lexical_cast<unsigned int>(foo); nVal = calcNumHeteroatoms(*mol); if(oVal!=nVal){ std::cerr<<" failed: "<<idx<<" "<<oVal<<" "<<nVal<<std::endl; } TEST_ASSERT(oVal==nVal); mol->getProp("NUM_ROTATABLEBONDS",foo); oVal=boost::lexical_cast<unsigned int>(foo); nVal = calcNumRotatableBonds(*mol); if(oVal!=nVal){ std::cerr<<" failed: "<<idx<<" "<<oVal<<" "<<nVal<<std::endl; } TEST_ASSERT(oVal==nVal); delete mol; } BOOST_LOG(rdErrorLog) << " done" << std::endl; } void testVSADescriptors(){ BOOST_LOG(rdErrorLog) << "-------------------------------------" << std::endl; BOOST_LOG(rdErrorLog) << " Test VSA descriptors." << std::endl; { ROMol *mol; std::vector<double> vals; mol = SmilesToMol("CO"); vals = calcSlogP_VSA(*mol); TEST_ASSERT(vals.size()==12); for(unsigned int i=0;i<vals.size();++i){ switch(i){ case 1: TEST_ASSERT(feq(vals[i],12.216,.001)); break; default: TEST_ASSERT(feq(vals[i],0,.001)); } } delete mol; mol = SmilesToMol("CCO"); vals = calcSlogP_VSA(*mol); TEST_ASSERT(vals.size()==12); for(unsigned int i=0;i<vals.size();++i){ switch(i){ case 1: TEST_ASSERT(feq(vals[i],11.713,.001)); break; case 4: TEST_ASSERT(feq(vals[i],6.924,.001)); break; default: TEST_ASSERT(feq(vals[i],0,.001)); } } delete mol; mol = SmilesToMol("Fc1ccccc1"); vals = calcSlogP_VSA(*mol); TEST_ASSERT(vals.size()==12); for(unsigned int i=0;i<vals.size();++i){ switch(i){ case 3: TEST_ASSERT(feq(vals[i],5.817,.001)); break; case 5: TEST_ASSERT(feq(vals[i],30.332,.001)); break; case 9: TEST_ASSERT(feq(vals[i],4.390,.001)); break; default: TEST_ASSERT(feq(vals[i],0,.001)); } } delete mol; } { ROMol *mol; std::vector<double> vals; mol = SmilesToMol("CO"); vals = calcSMR_VSA(*mol); TEST_ASSERT(vals.size()==10); for(unsigned int i=0;i<vals.size();++i){ switch(i){ case 0: TEST_ASSERT(feq(vals[i],5.106,.001)); break; case 5: TEST_ASSERT(feq(vals[i],7.110,.001)); break; default: TEST_ASSERT(feq(vals[i],0,.001)); } } delete mol; mol = SmilesToMol("CCO"); vals = calcSMR_VSA(*mol); TEST_ASSERT(vals.size()==10); for(unsigned int i=0;i<vals.size();++i){ switch(i){ case 0: TEST_ASSERT(feq(vals[i],5.106,.001)); break; case 4: TEST_ASSERT(feq(vals[i],6.924,.001)); break; case 5: TEST_ASSERT(feq(vals[i],6.607,.001)); break; default: TEST_ASSERT(feq(vals[i],0,.001)); } } delete mol; } { ROMol *mol; std::vector<double> vals; mol = SmilesToMol("CO"); vals = calcPEOE_VSA(*mol); TEST_ASSERT(vals.size()==14); for(unsigned int i=0;i<vals.size();++i){ switch(i){ case 0: TEST_ASSERT(feq(vals[i],5.106,.001)); break; case 7: TEST_ASSERT(feq(vals[i],7.110,.001)); break; default: TEST_ASSERT(feq(vals[i],0,.001)); } } delete mol; mol = SmilesToMol("CCO"); vals = calcPEOE_VSA(*mol); TEST_ASSERT(vals.size()==14); for(unsigned int i=0;i<vals.size();++i){ switch(i){ case 0: TEST_ASSERT(feq(vals[i],5.106,.001)); break; case 6: TEST_ASSERT(feq(vals[i],6.924,.001)); break; case 7: TEST_ASSERT(feq(vals[i],6.607,.001)); break; default: TEST_ASSERT(feq(vals[i],0,.001)); } } delete mol; } BOOST_LOG(rdErrorLog) << " done" << std::endl; } void testMolFormula(){ BOOST_LOG(rdErrorLog) << "-------------------------------------" << std::endl; BOOST_LOG(rdErrorLog) << " Test molecular formula calculation." << std::endl; ROMol *mol,*mol2; std::string formula; mol = SmilesToMol("C"); TEST_ASSERT(mol); formula = calcMolFormula(*mol); TEST_ASSERT(formula=="CH4"); mol2 = MolOps::addHs(*mol); formula = calcMolFormula(*mol2); TEST_ASSERT(formula=="CH4"); delete mol; delete mol2; mol = SmilesToMol("[CH4]"); TEST_ASSERT(mol); formula = calcMolFormula(*mol); TEST_ASSERT(formula=="CH4"); delete mol; mol = SmilesToMol("CO"); TEST_ASSERT(mol); formula = calcMolFormula(*mol); TEST_ASSERT(formula=="CH4O"); mol2 = MolOps::addHs(*mol); formula = calcMolFormula(*mol2); TEST_ASSERT(formula=="CH4O"); delete mol; delete mol2; mol = SmilesToMol("C(=O)N"); TEST_ASSERT(mol); formula = calcMolFormula(*mol); TEST_ASSERT(formula=="CH3NO"); mol2 = MolOps::addHs(*mol); formula = calcMolFormula(*mol2); TEST_ASSERT(formula=="CH3NO"); delete mol; delete mol2; mol = SmilesToMol("C(=O)=O"); TEST_ASSERT(mol); formula = calcMolFormula(*mol); TEST_ASSERT(formula=="CO2"); delete mol; mol = SmilesToMol("C(=O)[O-]"); TEST_ASSERT(mol); formula = calcMolFormula(*mol); TEST_ASSERT(formula=="CHO2-"); delete mol; mol = SmilesToMol("C([O-])[O-]"); TEST_ASSERT(mol); formula = calcMolFormula(*mol); TEST_ASSERT(formula=="CH2O2-2"); delete mol; mol = SmilesToMol("C([NH3+])[O-]"); TEST_ASSERT(mol); formula = calcMolFormula(*mol); TEST_ASSERT(formula=="CH5NO"); delete mol; mol = SmilesToMol("C([NH3+])O"); TEST_ASSERT(mol); formula = calcMolFormula(*mol); TEST_ASSERT(formula=="CH6NO+"); delete mol; mol = SmilesToMol("C([NH3+])[NH3+]"); TEST_ASSERT(mol); formula = calcMolFormula(*mol); TEST_ASSERT(formula=="CH8N2+2"); delete mol; // H isotope tests mol = SmilesToMol("[2H]C([3H])O"); TEST_ASSERT(mol); formula = calcMolFormula(*mol); TEST_ASSERT(formula=="CH4O"); formula = calcMolFormula(*mol,true); TEST_ASSERT(formula=="CH2DTO"); formula = calcMolFormula(*mol,true,false); TEST_ASSERT(formula=="CH2[2H][3H]O"); delete mol; // isotope test mol = SmilesToMol("[13CH3]C([2H])O"); TEST_ASSERT(mol); formula = calcMolFormula(*mol); TEST_ASSERT(formula=="C2H6O"); formula = calcMolFormula(*mol,true); TEST_ASSERT(formula=="C[13C]H5DO"); formula = calcMolFormula(*mol,true,false); TEST_ASSERT(formula=="C[13C]H5[2H]O"); delete mol; // isotope test mol = SmilesToMol("[13CH3]C[13CH2]C"); TEST_ASSERT(mol); formula = calcMolFormula(*mol); TEST_ASSERT(formula=="C4H10"); formula = calcMolFormula(*mol,true); TEST_ASSERT(formula=="C2[13C]2H10"); formula = calcMolFormula(*mol,true,false); TEST_ASSERT(formula=="C2[13C]2H10"); delete mol; // order test mol = SmilesToMol("[13CH3]C[13CH2]CB(O)O[2H]"); TEST_ASSERT(mol); formula = calcMolFormula(*mol); TEST_ASSERT(formula=="C4H11BO2"); formula = calcMolFormula(*mol,true); TEST_ASSERT(formula=="C2[13C]2H10DBO2"); formula = calcMolFormula(*mol,true,false); TEST_ASSERT(formula=="C2[13C]2H10[2H]BO2"); delete mol; BOOST_LOG(rdErrorLog) << " done" << std::endl; } void testIssue3415534(){ BOOST_LOG(rdErrorLog) << "-------------------------------------" << std::endl; BOOST_LOG(rdErrorLog) << " Test Issue 3415534." << std::endl; { ROMol *mol= SmilesToMol("CN"); TEST_ASSERT(mol); int nHBD=calcLipinskiHBD(*mol); TEST_ASSERT(nHBD==2); delete mol; } { ROMol *mol= SmilesToMol("CNC"); TEST_ASSERT(mol); int nHBD=calcLipinskiHBD(*mol); TEST_ASSERT(nHBD==1); delete mol; } { ROMol *mol= SmilesToMol("C[NH3+]"); TEST_ASSERT(mol); int nHBD=calcLipinskiHBD(*mol); TEST_ASSERT(nHBD==3); delete mol; } { ROMol *mol= SmilesToMol("CO"); TEST_ASSERT(mol); int nHBD=calcLipinskiHBD(*mol); TEST_ASSERT(nHBD==1); delete mol; } { ROMol *mol= SmilesToMol("C[OH2+]"); TEST_ASSERT(mol); int nHBD=calcLipinskiHBD(*mol); TEST_ASSERT(nHBD==2); delete mol; } { ROMol *mol= SmilesToMol("COC"); TEST_ASSERT(mol); int nHBD=calcLipinskiHBD(*mol); TEST_ASSERT(nHBD==0); delete mol; } BOOST_LOG(rdErrorLog) << " done" << std::endl; } void testIssue3433771(){ BOOST_LOG(rdErrorLog) << "-------------------------------------" << std::endl; BOOST_LOG(rdErrorLog) << " Test Issue3433771: Bad definition for Crippen atom type O11." << std::endl; ROMol *mol; double logp,mr; mol = SmilesToMol("O=C(NC)n1cccc1"); TEST_ASSERT(mol); calcCrippenDescriptors(*mol,logp,mr); TEST_ASSERT(feq(logp,0.6756,.001)); delete mol; mol = SmilesToMol("O=C(n1cccc1)n1cccc1"); TEST_ASSERT(mol); calcCrippenDescriptors(*mol,logp,mr); TEST_ASSERT(feq(logp,1.806,.001)); BOOST_LOG(rdErrorLog) << " done" << std::endl; } #ifdef RDK_TEST_MULTITHREADED namespace { void runblock(const std::vector<ROMol *> &mols,unsigned int count,unsigned int idx){ for(unsigned int j=0;j<1000;j++){ for(unsigned int i=0;i<mols.size();++i){ if(i%count != idx) continue; ROMol *mol = mols[i]; int nHBD=calcNumHBD(*mol); int nHBA=calcNumHBA(*mol); unsigned int oVal; std::string foo; mol->getProp("NUM_HACCEPTORS",foo); oVal=boost::lexical_cast<unsigned int>(foo); TEST_ASSERT(oVal==nHBA); mol->getProp("NUM_HDONORS",foo); oVal=boost::lexical_cast<unsigned int>(foo); TEST_ASSERT(oVal==nHBD); int nAmide=calcNumAmideBonds(*mol); double logp,mr; calcCrippenDescriptors(*mol,logp,mr); } } }; } #include <boost/thread.hpp> void testMultiThread(){ BOOST_LOG(rdErrorLog) << "-------------------------------------" << std::endl; BOOST_LOG(rdErrorLog) << " Test multithreading" << std::endl; std::string fName = getenv("RDBASE"); fName += "/Data/NCI/first_200.props.sdf"; SDMolSupplier suppl(fName); std::cerr<<"reading molecules"<<std::endl; std::vector<ROMol *> mols; while(!suppl.atEnd()&&mols.size()<100){ ROMol *mol=0; try{ mol=suppl.next(); } catch(...){ continue; } if(!mol) continue; mols.push_back(mol); } boost::thread_group tg; std::cerr<<"processing"<<std::endl; unsigned int count=4; for(unsigned int i=0;i<count;++i){ std::cerr<<" launch :"<<i<<std::endl;std::cerr.flush(); tg.add_thread(new boost::thread(runblock,mols,count,i)); } tg.join_all(); for(unsigned int i=0;i<mols.size();++i) delete mols[i]; BOOST_LOG(rdErrorLog) << " done" << std::endl; } #else void testMultiThread(){ } #endif void testCrippenContribs(){ BOOST_LOG(rdErrorLog) << "-------------------------------------" << std::endl; BOOST_LOG(rdErrorLog) << " Test Crippen atom type calculations." << std::endl; { ROMol *mol; mol = SmilesToMol("n1ccccc1CO"); TEST_ASSERT(mol); std::vector<double> logp(mol->getNumAtoms()); std::vector<double> mr(mol->getNumAtoms()); std::vector<unsigned int> ts(mol->getNumAtoms()); std::vector<std::string> ls(mol->getNumAtoms()); getCrippenAtomContribs(*mol,logp,mr,true,&ts,&ls); TEST_ASSERT(ts[0]==59); TEST_ASSERT(ts[1]==25); TEST_ASSERT(ts[2]==25); TEST_ASSERT(ts[3]==25); TEST_ASSERT(ts[4]==25); TEST_ASSERT(ts[5]==28); TEST_ASSERT(ts[6]==17); TEST_ASSERT(ts[7]==69); TEST_ASSERT(ls[0]=="N11"); TEST_ASSERT(ls[7]=="O2"); delete mol; } BOOST_LOG(rdErrorLog) << " done" << std::endl; } void testIssue252(){ BOOST_LOG(rdErrorLog) << "-------------------------------------" << std::endl; BOOST_LOG(rdErrorLog) << " Test Issue252: Bad definitions for Crippen atom types." << std::endl; { ROMol *mol; mol = SmilesToMol("O=[N+]([O-])C"); TEST_ASSERT(mol); std::vector<double> logp(mol->getNumAtoms()); std::vector<double> mr(mol->getNumAtoms()); getCrippenAtomContribs(*mol,logp,mr,true); TEST_ASSERT(feq(logp[0],0.0335,.001)); TEST_ASSERT(feq(logp[1],-0.3396,.001)); TEST_ASSERT(feq(logp[2],0.0335,.001)); TEST_ASSERT(feq(logp[3],-0.2035,.001)); delete mol; } { ROMol *mol; mol = SmilesToMol("CP"); TEST_ASSERT(mol); std::vector<double> logp(mol->getNumAtoms()); std::vector<double> mr(mol->getNumAtoms()); getCrippenAtomContribs(*mol,logp,mr,true); TEST_ASSERT(feq(logp[0],-0.2035,.001)); delete mol; } { ROMol *mol; mol = SmilesToMol("C(C)P"); TEST_ASSERT(mol); std::vector<double> logp(mol->getNumAtoms()); std::vector<double> mr(mol->getNumAtoms()); getCrippenAtomContribs(*mol,logp,mr,true); TEST_ASSERT(feq(logp[0],-0.2035,.001)); delete mol; } { ROMol *mol; mol = SmilesToMol("C(C)(C)P"); TEST_ASSERT(mol); std::vector<double> logp(mol->getNumAtoms()); std::vector<double> mr(mol->getNumAtoms()); getCrippenAtomContribs(*mol,logp,mr,true); TEST_ASSERT(feq(logp[0],-0.2051,.001)); delete mol; } { ROMol *mol; mol = SmilesToMol("C(C)(C)(C)P"); TEST_ASSERT(mol); std::vector<double> logp(mol->getNumAtoms()); std::vector<double> mr(mol->getNumAtoms()); getCrippenAtomContribs(*mol,logp,mr,true); TEST_ASSERT(feq(logp[0],-0.2051,.001)); delete mol; } { ROMol *mol; mol = SmilesToMol("C(=C)c1ccccc1"); TEST_ASSERT(mol); std::vector<double> logp(mol->getNumAtoms()); std::vector<double> mr(mol->getNumAtoms()); getCrippenAtomContribs(*mol,logp,mr,true); TEST_ASSERT(feq(logp[0],0.264,.001)); delete mol; } { ROMol *mol; mol = SmilesToMol("C(=C)(C)c1ccccc1"); TEST_ASSERT(mol); std::vector<double> logp(mol->getNumAtoms()); std::vector<double> mr(mol->getNumAtoms()); getCrippenAtomContribs(*mol,logp,mr,true); TEST_ASSERT(feq(logp[0],0.264,.001)); delete mol; } { ROMol *mol; mol = SmilesToMol("C=C"); TEST_ASSERT(mol); std::vector<double> logp(mol->getNumAtoms()); std::vector<double> mr(mol->getNumAtoms()); getCrippenAtomContribs(*mol,logp,mr,true); TEST_ASSERT(feq(logp[0],0.1551,.001)); delete mol; } { ROMol *mol; mol = SmilesToMol("O=S"); TEST_ASSERT(mol); std::vector<double> logp(mol->getNumAtoms()); std::vector<double> mr(mol->getNumAtoms()); getCrippenAtomContribs(*mol,logp,mr,true); TEST_ASSERT(feq(logp[0],-0.3339,.001)); delete mol; } { ROMol *mol; mol = SmilesToMol("S=O"); TEST_ASSERT(mol); std::vector<double> logp(mol->getNumAtoms()); std::vector<double> mr(mol->getNumAtoms()); getCrippenAtomContribs(*mol,logp,mr,true); TEST_ASSERT(feq(logp[0],-0.0024,.001)); delete mol; } { ROMol *mol; mol = SmilesToMol("C(Cl)C"); TEST_ASSERT(mol); std::vector<double> logp(mol->getNumAtoms()); std::vector<double> mr(mol->getNumAtoms()); getCrippenAtomContribs(*mol,logp,mr,true); TEST_ASSERT(feq(logp[0],-0.2035,.001)); delete mol; } { ROMol *mol; mol = SmilesToMol("C(Cl)(Cl)C"); TEST_ASSERT(mol); std::vector<double> logp(mol->getNumAtoms()); std::vector<double> mr(mol->getNumAtoms()); getCrippenAtomContribs(*mol,logp,mr,true); TEST_ASSERT(feq(logp[0],-0.2051,.001)); delete mol; } { ROMol *mol; mol = SmilesToMol("C(Cl)(Cl)(Cl)C"); TEST_ASSERT(mol); std::vector<double> logp(mol->getNumAtoms()); std::vector<double> mr(mol->getNumAtoms()); getCrippenAtomContribs(*mol,logp,mr,true); TEST_ASSERT(feq(logp[0],-0.2051,.001)); delete mol; } { ROMol *mol; mol = SmilesToMol("C(Cl)c1ccccc1"); TEST_ASSERT(mol); std::vector<double> logp(mol->getNumAtoms()); std::vector<double> mr(mol->getNumAtoms()); getCrippenAtomContribs(*mol,logp,mr,true); TEST_ASSERT(feq(logp[0],-0.0516,.001)); delete mol; } { ROMol *mol; mol = SmilesToMol("C(Cl)(Cl)c1ccccc1"); TEST_ASSERT(mol); std::vector<double> logp(mol->getNumAtoms()); std::vector<double> mr(mol->getNumAtoms()); getCrippenAtomContribs(*mol,logp,mr,true); TEST_ASSERT(feq(logp[0],0.1193,.001)); delete mol; } { ROMol *mol; mol = SmilesToMol("C(Cl)(Cl)(Cl)c1ccccc1"); TEST_ASSERT(mol); std::vector<double> logp(mol->getNumAtoms()); std::vector<double> mr(mol->getNumAtoms()); getCrippenAtomContribs(*mol,logp,mr,true); TEST_ASSERT(feq(logp[0],-0.0967,.001)); delete mol; } BOOST_LOG(rdErrorLog) << " done" << std::endl; } void testChiVs(){ BOOST_LOG(rdErrorLog) << "-------------------------------------" << std::endl; BOOST_LOG(rdErrorLog) << " Test calculation of ChiVs." << std::endl; { std::string sdata[] = {"CCCCCC", "CCC(C)CC", "CC(C)CCC", "CC(C)C(C)C", "CC(C)(C)CC", "CCCCCO", "CCC(O)CC", "CC(O)(C)CC", "c1ccccc1O", "CCCl", "CCBr", "CCI", "EOS"}; double ddata[] = {4.828, 4.992, 4.992, 5.155, 5.207, 4.276, 4.439, 4.654, 3.834, 2.841, 3.671, 4.242}; unsigned int idx=0; while(sdata[idx]!="EOS"){ ROMol *mol; mol = SmilesToMol(sdata[idx]); TEST_ASSERT(mol); double v=calcChi0v(*mol); TEST_ASSERT(feq(v,ddata[idx],0.002)); ++idx; delete mol; } } { std::string sdata[] ={"CCCCCC","CCC(C)CC","CC(C)CCC", "CC(C)C(C)C","CC(C)(C)CC", "CCCCCO","CCC(O)CC","CC(O)(C)CC","c1ccccc1O", "EOS"}; double ddata[] = {2.914,2.808,2.770, 2.643,2.561, 2.523,2.489,2.284,2.134}; unsigned int idx=0; while(sdata[idx]!="EOS"){ ROMol *mol; mol = SmilesToMol(sdata[idx]); TEST_ASSERT(mol); double v=calcChi1v(*mol); TEST_ASSERT(feq(v,ddata[idx],0.002)); ++idx; delete mol; } } { std::string sdata[] ={"CCCCCC","CCC(C)CC","CC(C)CCC", "CC(C)C(C)C","CC(C)(C)CC", "CCCCCO","CCC(O)CC","CC(O)(C)CC","c1ccccc1O", "EOS"}; double ddata[] = {1.707,1.922,2.183, 2.488,2.914, 1.431,1.470,2.166,1.336}; unsigned int idx=0; while(sdata[idx]!="EOS"){ ROMol *mol; mol = SmilesToMol(sdata[idx]); TEST_ASSERT(mol); double v=calcChi2v(*mol); TEST_ASSERT(feq(v,ddata[idx],0.002)); ++idx; delete mol; } } { std::string sdata[] ={"CCCCCC","CCC(C)CC","CC(C)CCC", "CC(C)C(C)C","CC(C)(C)CC", "CCCCCO","CCC(O)CC","CC(O)(C)CC","c1ccccc1O", "EOS"}; double ddata[] = {0.957,1.394,0.866,1.333,1.061, 0.762,0.943,0.865,0.756}; unsigned int idx=0; while(sdata[idx]!="EOS"){ ROMol *mol; mol = SmilesToMol(sdata[idx]); TEST_ASSERT(mol); double v=calcChi3v(*mol); TEST_ASSERT(feq(v,ddata[idx],0.002)); ++idx; delete mol; } } { std::string sdata[] ={"CCCCCC","CCC(C)CC","CC(C)CCC", "CC(C)C(C)C","CC(C)(C)CC", "CCCCCO","CCC(O)CC","CC(O)(C)CC","c1ccccc1O", "EOS"}; double ddata[] = {0.500,0.289,0.577, 0.000,0.000,0.362,0.289,0.000,0.428}; unsigned int idx=0; while(sdata[idx]!="EOS"){ ROMol *mol; mol = SmilesToMol(sdata[idx]); TEST_ASSERT(mol); double v=calcChi4v(*mol); TEST_ASSERT(feq(v,ddata[idx],0.002)); ++idx; delete mol; } } BOOST_LOG(rdErrorLog) << " done" << std::endl; } void testChiNs(){ BOOST_LOG(rdErrorLog) << "-------------------------------------" << std::endl; BOOST_LOG(rdErrorLog) << " Test calculation of ChiNs." << std::endl; { std::string sdata[] = {"CCCCCC", "CCC(C)CC", "CC(C)CCC", "CC(C)C(C)C", "CC(C)(C)CC", "CCCCCO", "CCC(O)CC", "CC(O)(C)CC", "c1ccccc1O", "CCCl", "CCBr", "CCI", "EOS"}; double ddata[] = {4.828, 4.992, 4.992, 5.155, 5.207, 4.276, 4.439, 4.654, 3.834, 2.085, 2.085, 2.085}; unsigned int idx=0; while(sdata[idx]!="EOS"){ ROMol *mol; mol = SmilesToMol(sdata[idx]); TEST_ASSERT(mol); double v=calcChi0n(*mol); TEST_ASSERT(feq(v,ddata[idx],0.002)); ++idx; delete mol; } } { std::string sdata[] ={"CCCCCC","CCC(C)CC","CC(C)CCC", "CC(C)C(C)C","CC(C)(C)CC", "CCCCCO","CCC(O)CC","CC(O)(C)CC","c1ccccc1O", "C=S", "EOS"}; double ddata[] = {2.914,2.808,2.770, 2.643,2.561, 2.523,2.489,2.284,2.134, 0.289 }; unsigned int idx=0; while(sdata[idx]!="EOS"){ ROMol *mol; mol = SmilesToMol(sdata[idx]); TEST_ASSERT(mol); double v=calcChi1n(*mol); TEST_ASSERT(feq(v,ddata[idx],0.002)); ++idx; delete mol; } } { std::string sdata[] ={"CCCCCC","CCC(C)CC","CC(C)CCC", "CC(C)C(C)C","CC(C)(C)CC", "CCCCCO","CCC(O)CC","CC(O)(C)CC","c1ccccc1O", "EOS"}; double ddata[] = {1.707,1.922,2.183, 2.488,2.914, 1.431,1.470,2.166,1.336}; unsigned int idx=0; while(sdata[idx]!="EOS"){ ROMol *mol; mol = SmilesToMol(sdata[idx]); TEST_ASSERT(mol); double v=calcChi2n(*mol); TEST_ASSERT(feq(v,ddata[idx],0.002)); ++idx; delete mol; } } { std::string sdata[] ={"CCCCCC","CCC(C)CC","CC(C)CCC", "CC(C)C(C)C","CC(C)(C)CC", "CCCCCO","CCC(O)CC","CC(O)(C)CC","c1ccccc1O", "EOS"}; double ddata[] = {0.957,1.394,0.866,1.333,1.061, 0.762,0.943,0.865,0.756}; unsigned int idx=0; while(sdata[idx]!="EOS"){ ROMol *mol; mol = SmilesToMol(sdata[idx]); TEST_ASSERT(mol); double v=calcChi3n(*mol); TEST_ASSERT(feq(v,ddata[idx],0.002)); ++idx; delete mol; } } { std::string sdata[] ={"CCCCCC","CCC(C)CC","CC(C)CCC", "CC(C)C(C)C","CC(C)(C)CC", "CCCCCO","CCC(O)CC","CC(O)(C)CC","c1ccccc1O", "EOS"}; double ddata[] = {0.500,0.289,0.577, 0.000,0.000,0.362,0.289,0.000,0.428}; unsigned int idx=0; while(sdata[idx]!="EOS"){ ROMol *mol; mol = SmilesToMol(sdata[idx]); TEST_ASSERT(mol); double v=calcChi4n(*mol); TEST_ASSERT(feq(v,ddata[idx],0.002)); ++idx; delete mol; } } BOOST_LOG(rdErrorLog) << " done" << std::endl; } void testHallKierAlpha(){ BOOST_LOG(rdErrorLog) << "-------------------------------------" << std::endl; BOOST_LOG(rdErrorLog) << " Test calculation of HallKierAlpha." << std::endl; { std::string sdata[] = { "C=O", "CCC1(CC)C(=O)NC(=O)N(C)C1=O", "OCC(O)C(O)C(O)C(O)CO", "OCC1OC(O)C(O)C(O)C1O", "Fc1c[nH]c(=O)[nH]c1=O", "OC1CNC(C(=O)O)C1", "CCCc1[nH]c(=S)[nH]c(=O)c1", "CN(CCCl)CCCl", "CBr", "CI", "EOS" }; double ddata[] = { -0.3300, -1.3900, -0.2400, -0.2400, -1.3900, -0.6100, -0.9000, 0.5400, 0.480, 0.730, }; unsigned int idx=0; while(sdata[idx]!="EOS"){ ROMol *mol; mol = SmilesToMol(sdata[idx]); TEST_ASSERT(mol); double v=calcHallKierAlpha(*mol); TEST_ASSERT(feq(v,ddata[idx],0.002)); ++idx; delete mol; } } BOOST_LOG(rdErrorLog) << " done" << std::endl; } void testKappa1(){ BOOST_LOG(rdErrorLog) << "-------------------------------------" << std::endl; BOOST_LOG(rdErrorLog) << " Test calculation of Kappa1." << std::endl; { std::string sdata[] = { "C12CC2C3CC13", "C1CCC12CC2", "C1CCCCC1", "CCCCCC", "CCC(C)C1CCC(C)CC1", "CC(C)CC1CCC(C)CC1", "CC(C)C1CCC(C)CCC1", "EOS" }; double ddata[] = { 2.344, 3.061, 4.167, 6.000, 9.091, 9.091, 9.091 }; unsigned int idx=0; while(sdata[idx]!="EOS"){ ROMol *mol; mol = SmilesToMol(sdata[idx]); TEST_ASSERT(mol); double v=calcKappa1(*mol); TEST_ASSERT(feq(v,ddata[idx],0.002)); ++idx; delete mol; } } BOOST_LOG(rdErrorLog) << " done" << std::endl; } void testKappa2(){ BOOST_LOG(rdErrorLog) << "-------------------------------------" << std::endl; BOOST_LOG(rdErrorLog) << " Test calculation of Kappa2." << std::endl; { std::string sdata[] = { "[C+2](C)(C)(C)(C)(C)C", "[C+](C)(C)(C)(C)(CC)", "C(C)(C)(C)(CCC)", "CC(C)CCCC", "CCCCCCC", "CCCCCC", "CCCCCCC", "C1CCCC1", "C1CCCC1C", "C1CCCCC1", "C1CCCCCC1", "CCCCC", "CC=CCCC", "C1=CN=CN1", "c1ccccc1", "c1cnccc1", "n1ccncc1", "CCCCF", "CCCCCl", "CCCCBr", "CCC(C)C1CCC(C)CC1", "CC(C)CC1CCC(C)CC1", "CC(C)C1CCC(C)CCC1", "EOS" }; double ddata[] = { 0.667000, 1.240000, 2.344400, 4.167000, 6.000000, 5.000000, 6.000000, 1.440000, 1.633000, 2.222000, 3.061000, 4.000000, 4.740000, 0.884000, 1.606000, 1.552000, 1.500000, 3.930000, 4.290000, 4.480000, 4.133000, 4.133000, 4.133000 }; unsigned int idx=0; while(sdata[idx]!="EOS"){ ROMol *mol; mol = SmilesToMol(sdata[idx]); TEST_ASSERT(mol); double v=calcKappa2(*mol); TEST_ASSERT(feq(v,ddata[idx],0.002)); ++idx; delete mol; } } BOOST_LOG(rdErrorLog) << " done" << std::endl; } void testKappa3(){ BOOST_LOG(rdErrorLog) << "-------------------------------------" << std::endl; BOOST_LOG(rdErrorLog) << " Test calculation of Kappa3." << std::endl; { std::string sdata[] = { "C[C+](C)(C)(C)C(C)(C)C", "CCC(C)C(C)(C)(CC)", "CCC(C)CC(C)CC", "CC(C)CCC(C)CC", "CC(C)CCCC(C)C", "CCC(C)C1CCC(C)CC1", "CC(C)CC1CCC(C)CC1", "CC(C)C1CCC(C)CCC1", "EOS" }; double ddata[] = { 2.000000, 2.380000, 4.500000, 5.878000, 8.000000, 2.500000, 3.265000, 2.844000 }; unsigned int idx=0; while(sdata[idx]!="EOS"){ ROMol *mol; mol = SmilesToMol(sdata[idx]); TEST_ASSERT(mol); double v=calcKappa3(*mol); TEST_ASSERT(feq(v,ddata[idx],0.002)); ++idx; delete mol; } } BOOST_LOG(rdErrorLog) << " done" << std::endl; } void testRingDescriptors(){ BOOST_LOG(rdErrorLog) << "-------------------------------------" << std::endl; BOOST_LOG(rdErrorLog) << " Test ring descriptors" << std::endl; std::string fName = getenv("RDBASE"); fName += "/Code/GraphMol/Descriptors/test_data/aid466.trunc.sdf"; SDMolSupplier suppl(fName); while(!suppl.atEnd()){ ROMol *mol=suppl.next(); TEST_ASSERT(mol); unsigned int iv; mol->getProp("NumRings",iv); TEST_ASSERT(iv==calcNumRings(*mol)); mol->getProp("NumAromaticRings",iv); TEST_ASSERT(iv==calcNumAromaticRings(*mol)); mol->getProp("NumSaturatedRings",iv); TEST_ASSERT(iv==calcNumSaturatedRings(*mol)); mol->getProp("NumAromaticHeterocycles",iv); TEST_ASSERT(iv==calcNumAromaticHeterocycles(*mol)); mol->getProp("NumAromaticCarbocycles",iv); TEST_ASSERT(iv==calcNumAromaticCarbocycles(*mol)); mol->getProp("NumSaturatedHeterocycles",iv); TEST_ASSERT(iv==calcNumSaturatedHeterocycles(*mol)); mol->getProp("NumSaturatedCarbocycles",iv); TEST_ASSERT(iv==calcNumSaturatedCarbocycles(*mol)); mol->getProp("NumAliphaticRings",iv); TEST_ASSERT(iv==calcNumAliphaticRings(*mol)); mol->getProp("NumAliphaticHeterocycles",iv); TEST_ASSERT(iv==calcNumAliphaticHeterocycles(*mol)); mol->getProp("NumAliphaticCarbocycles",iv); TEST_ASSERT(iv==calcNumAliphaticCarbocycles(*mol)); mol->getProp("NumHeterocycles",iv); TEST_ASSERT(iv==calcNumHeterocycles(*mol)); delete mol; } BOOST_LOG(rdErrorLog) << " done" << std::endl; } void testMiscCountDescriptors(){ BOOST_LOG(rdErrorLog) << "-------------------------------------" << std::endl; BOOST_LOG(rdErrorLog) << " Test other count descriptors." << std::endl; { ROMol *mol; mol = SmilesToMol("OCCO"); TEST_ASSERT(feq(calcFractionCSP3(*mol),1.0,0.001)); delete mol; } { ROMol *mol; mol = SmilesToMol("OO"); TEST_ASSERT(feq(calcFractionCSP3(*mol),0.0,0.001)); delete mol; } { ROMol *mol; mol = SmilesToMol("OC=CO"); TEST_ASSERT(feq(calcFractionCSP3(*mol),0.0,0.001)); delete mol; } { ROMol *mol; mol = SmilesToMol("CCC=C"); TEST_ASSERT(feq(calcFractionCSP3(*mol),0.5,0.001)); delete mol; } BOOST_LOG(rdErrorLog) << " done" << std::endl; } void testMQNs(){ BOOST_LOG(rdErrorLog) << "-------------------------------------" << std::endl; BOOST_LOG(rdErrorLog) << " Test MQN" << std::endl; unsigned int tgt[42]={98, 0, 4, 0, 0, 1, 0, 3, 9, 5, 4, 0, 29, 3, 0, 66, 35, 0, 25, 30, 21, 2, 2, 0, 0, 6, 12, 6, 0, 70, 26, 0, 0, 0, 2, 16, 0, 0, 0, 0, 10, 5}; std::vector<unsigned int> accum(42,0); std::string fName = getenv("RDBASE"); fName += "/Code/GraphMol/Descriptors/test_data/aid466.trunc.sdf"; SDMolSupplier suppl(fName); while(!suppl.atEnd()){ ROMol *mol=suppl.next(); TEST_ASSERT(mol); std::vector<unsigned int> v = calcMQNs(*mol); TEST_ASSERT(v.size()==42); for(unsigned int i=0;i<42;++i) accum[i]+=v[i]; delete mol; } for(unsigned int i=0;i<42;++i){ if(accum[i] != tgt[i]){ std::cerr<<" !! "<<i<<accum[i]<<"!="<<tgt[i]<<std::endl; } TEST_ASSERT(accum[i]==tgt[i]); } BOOST_LOG(rdErrorLog) << " done" << std::endl; } void testGitHubIssue56(){ BOOST_LOG(rdErrorLog) << "-------------------------------------" << std::endl; BOOST_LOG(rdErrorLog) << " Test GitHub Issue 56." << std::endl; { ROMol *mol; mol = SmilesToMol("[H+]"); double mw; mw = calcAMW(*mol); TEST_ASSERT(feq(mw,1.008,0.001)); mw = calcExactMW(*mol); TEST_ASSERT(feq(mw,1.0078,0.001)); delete mol; } { ROMol *mol; mol = SmilesToMol("[2H+]"); double mw; mw = calcAMW(*mol); TEST_ASSERT(feq(mw,2.014,0.001)); mw = calcExactMW(*mol); TEST_ASSERT(feq(mw,2.014,0.001)); delete mol; } { ROMol *mol; mol = SmilesToMol("[H]"); double mw; mw = calcAMW(*mol); TEST_ASSERT(feq(mw,1.008,0.001)); mw = calcExactMW(*mol); TEST_ASSERT(feq(mw,1.0078,0.001)); delete mol; } { ROMol *mol; mol = SmilesToMol("[2H]"); double mw; mw = calcAMW(*mol); TEST_ASSERT(feq(mw,2.014,0.001)); mw = calcExactMW(*mol); TEST_ASSERT(feq(mw,2.014,0.001)); delete mol; } BOOST_LOG(rdErrorLog) << " done" << std::endl; } void testGitHubIssue92(){ BOOST_LOG(rdErrorLog) << "-------------------------------------" << std::endl; BOOST_LOG(rdErrorLog) << " Test Github92: Bad Crippen atom type for pyrrole H." << std::endl; { RWMol *mol; mol = SmilesToMol("c1cccn1[H]",0,0); TEST_ASSERT(mol); MolOps::sanitizeMol(*mol); TEST_ASSERT(mol->getNumAtoms()==6); std::vector<double> logp(mol->getNumAtoms()); std::vector<double> mr(mol->getNumAtoms()); getCrippenAtomContribs(*mol,logp,mr,true); TEST_ASSERT(feq(logp[5],0.2142,.001)); delete mol; } BOOST_LOG(rdErrorLog) << " done" << std::endl; } //-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-* // //-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-* int main(){ RDLog::InitLogs(); #if 1 test1(); test2(); testIssue262(); test3(); test3a(); testLabute(); testTPSA(); testLipinski1(); testVSADescriptors(); testMolFormula(); testIssue3415534(); testIssue3433771(); testMultiThread(); testIssue252(); testChiVs(); testChiNs(); testHallKierAlpha(); testKappa1(); testKappa2(); testKappa3(); testCrippenContribs(); testRingDescriptors(); testMiscCountDescriptors(); testMQNs(); #endif testGitHubIssue56(); testGitHubIssue92(); }
#ifndef TRANSLATED_TRIANGLE_HPP_ #define TRANSLATED_TRIANGLE_HPP_ #include <string> namespace translated_triangle { extern const std::string module_name; int run(int argc, char **argv); } #endif // TRANSLATED_TRIANGLE_HPP_
#include "Profile.h" Profile::Profile(){ ploidy = 0; } Profile::Profile(json &individual){ // cout << "Profile - Inicio\n"; ParsingUtils utils; setPloidy( individual["Plody"] ); // cout << "Profile - Cargando Marcadores\n"; for( json &marker : individual["Markers"] ){ // cout << "Profile - marker: " << marker << "\n"; unsigned int marker_type = marker["Type"]; unsigned int mutation_model = marker["Mutation_model"]; if( marker_type == 1 ){ // MARKER_SEQUENCE if( mutation_model == 1 ){ // MUTATION_BASIC unsigned int length = marker["Size"]; unsigned int pool_size = marker["Pool_size"]; double rate = utils.parseValue(marker["Rate"], true, 0, 1.0); vector<double> params; params.push_back(rate); ProfileMarker marker(MARKER_SEQUENCE, length, pool_size, MUTATION_BASIC, params); addMarker(marker); } else{ cerr << "Profile - Unknown Mutation Model (" << mutation_model << ")\n"; } } else if( marker_type == 2 ){ // MICROSATELLITES if( mutation_model == 1 ){ // MUTATION_BASIC unsigned int pool_size = marker["Pool_size"]; double rate = utils.parseValue(marker["Rate"], true, 0, 1.0); // Quizas despues habria que agregar parámetros de la geometrica // Por otra parte, quizas sea mejor eso para mutation_model = 2 vector<double> params; params.push_back(rate); ProfileMarker marker(MARKER_MS, 0, pool_size, MUTATION_BASIC, params); addMarker(marker); } else{ cerr << "Profile - Unknown Mutation Model (" << mutation_model << ")\n"; } } else{ cerr << "Profile - Unknown Marker Type (" << marker_type << ")\n"; } } // cout << "Profile - Fin\n"; } Profile::Profile(const Profile &original){ ploidy = original.getPloidy(); } Profile& Profile::operator=(const Profile& original){ if (this != &original){ ploidy = original.getPloidy(); } return *this; } Profile *Profile::clone(){ return new Profile(*this); } Profile::~Profile(){ } unsigned int Profile::getPloidy() const{ return ploidy; } const vector<ProfileMarker> &Profile::getMarkers() const{ return markers; } unsigned int Profile::getNumMarkers() const{ return markers.size(); } const ProfileMarker &Profile::getMarker(unsigned int pos) const{ assert(pos < markers.size()); return markers[pos]; } void Profile::setPloidy(unsigned int _ploidy){ ploidy = (unsigned char)_ploidy; } void Profile::addMarker(ProfileMarker &marker){ markers.push_back(marker); }
// Created on: 1997-02-18 // Created by: Stagiaire Francois DUMONT // Copyright (c) 1997-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _Hermit_HeaderFile #define _Hermit_HeaderFile #include <Standard.hxx> #include <Standard_DefineAlloc.hxx> #include <Standard_Handle.hxx> class Geom2d_BSplineCurve; class Geom_BSplineCurve; //! This is used to reparameterize Rational BSpline //! Curves so that we can concatenate them later to //! build C1 Curves It builds and 1D-reparameterizing //! function starting from an Hermite interpolation and //! adding knots and modifying poles of the 1D BSpline //! obtained that way. The goal is to build a(u) so that //! if we consider a BSpline curve //! N(u) //! f(u) = ----- //! D(u) //! //! the function a(u)D(u) has value 1 at the umin and umax //! and has 0.0e0 derivative value a umin and umax. //! The details of the computation occurring in this package //! can be found by reading : //! " Etude sur la concatenation de NURBS en vue du //! balayage de surfaces" PFE n S85 Ensam Lille class Hermit { public: DEFINE_STANDARD_ALLOC //! returns the correct spline a(u) which will //! be multiplicated with BS later. Standard_EXPORT static Handle(Geom2d_BSplineCurve) Solution (const Handle(Geom_BSplineCurve)& BS, const Standard_Real TolPoles = 0.000001, const Standard_Real TolKnots = 0.000001); //! returns the correct spline a(u) which will //! be multiplicated with BS later. Standard_EXPORT static Handle(Geom2d_BSplineCurve) Solution (const Handle(Geom2d_BSplineCurve)& BS, const Standard_Real TolPoles = 0.000001, const Standard_Real TolKnots = 0.000001); //! returns the knots to insert to a(u) to //! stay with a constant sign and in the //! tolerances. Standard_EXPORT static void Solutionbis (const Handle(Geom_BSplineCurve)& BS, Standard_Real& Knotmin, Standard_Real& Knotmax, const Standard_Real TolPoles = 0.000001, const Standard_Real TolKnots = 0.000001); }; #endif // _Hermit_HeaderFile
/*========================================================================= Program: Visualization Toolkit Module: vtkOpenVRRenderWindowInteractor.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> #include <cstring> #include "vtkOpenGLState.h" #include "vtkOpenVROverlay.h" #include "vtkOpenVRRenderWindow.h" #include "vtkOpenVRRenderWindowInteractor.h" #include "vtkRendererCollection.h" #include "vtkVRRenderWindow.h" #include "vtkEventData.h" #include "vtkActor.h" #include "vtkCommand.h" #include "vtkMatrix4x4.h" #include "vtkNew.h" #include "vtkObjectFactory.h" #include "vtkOpenVRCamera.h" #include "vtkOpenVRInteractorStyle.h" #include "vtkTextureObject.h" #include "vtkTransform.h" #include <vtksys/SystemTools.hxx> vtkStandardNewMacro(vtkOpenVRRenderWindowInteractor); void (*vtkOpenVRRenderWindowInteractor::ClassExitMethod)(void*) = (void (*)(void*)) nullptr; void* vtkOpenVRRenderWindowInteractor::ClassExitMethodArg = (void*)nullptr; void (*vtkOpenVRRenderWindowInteractor::ClassExitMethodArgDelete)( void*) = (void (*)(void*)) nullptr; //------------------------------------------------------------------------------ // Construct object so that light follows camera motion. vtkOpenVRRenderWindowInteractor::vtkOpenVRRenderWindowInteractor() { vtkNew<vtkOpenVRInteractorStyle> style; this->SetInteractorStyle(style); for (int i = 0; i < vtkEventDataNumberOfDevices; i++) { this->DeviceInputDownCount[i] = 0; } this->ActionManifestFileName = "./vtk_openvr_actions.json"; this->ActionSetName = "/actions/vtk"; } //------------------------------------------------------------------------------ vtkOpenVRRenderWindowInteractor::~vtkOpenVRRenderWindowInteractor() = default; void vtkOpenVRRenderWindowInteractor::SetPhysicalScale(double scale) { vtkVRRenderWindow* win = vtkVRRenderWindow::SafeDownCast(this->RenderWindow); win->SetPhysicalScale(scale); } double vtkOpenVRRenderWindowInteractor::GetPhysicalScale() { vtkVRRenderWindow* win = vtkVRRenderWindow::SafeDownCast(this->RenderWindow); return win->GetPhysicalScale(); } void vtkOpenVRRenderWindowInteractor::SetPhysicalTranslation( vtkCamera*, double t1, double t2, double t3) { vtkVRRenderWindow* win = vtkVRRenderWindow::SafeDownCast(this->RenderWindow); win->SetPhysicalTranslation(t1, t2, t3); } double* vtkOpenVRRenderWindowInteractor::GetPhysicalTranslation(vtkCamera*) { vtkVRRenderWindow* win = vtkVRRenderWindow::SafeDownCast(this->RenderWindow); return win->GetPhysicalTranslation(); } void vtkOpenVRRenderWindowInteractor::ConvertOpenVRPoseToMatrices( const vr::TrackedDevicePose_t& tdPose, vtkMatrix4x4* poseMatrixWorld, vtkMatrix4x4* poseMatrixPhysical /*=nullptr*/) { if (!poseMatrixWorld && !poseMatrixPhysical) { return; } vtkNew<vtkMatrix4x4> poseMatrixPhysicalTemp; for (int row = 0; row < 3; ++row) { for (int col = 0; col < 4; ++col) { poseMatrixPhysicalTemp->SetElement(row, col, tdPose.mDeviceToAbsoluteTracking.m[row][col]); } } if (poseMatrixPhysical) { poseMatrixPhysical->DeepCopy(poseMatrixPhysicalTemp); } if (poseMatrixWorld) { vtkVRRenderWindow* win = vtkVRRenderWindow::SafeDownCast(this->RenderWindow); vtkNew<vtkMatrix4x4> physicalToWorldMatrix; win->GetPhysicalToWorldMatrix(physicalToWorldMatrix); vtkMatrix4x4::Multiply4x4(physicalToWorldMatrix, poseMatrixPhysicalTemp, poseMatrixWorld); } } void vtkOpenVRRenderWindowInteractor::ConvertPoseToWorldCoordinates( const vr::TrackedDevicePose_t& tdPose, double pos[3], // Output world position double wxyz[4], // Output world orientation quaternion double ppos[3], // Output physical position double wdir[3]) // Output world view direction (-Z) { // Convenience function to use the openvr-independant function // TODO: remove it this->ConvertPoseMatrixToWorldCoordinates( tdPose.mDeviceToAbsoluteTracking.m, pos, wxyz, ppos, wdir); } void vtkOpenVRRenderWindowInteractor::ConvertPoseMatrixToWorldCoordinates( const float poseMatrix[3][4], double pos[3], // Output world position double wxyz[4], // Output world orientation quaternion double ppos[3], // Output physical position double wdir[3]) // Output world view direction (-Z) { // TODO: define it in generic superclass VRRenderWindowInteractor vtkVRRenderWindow* win = vtkVRRenderWindow::SafeDownCast(this->RenderWindow); double physicalScale = win->GetPhysicalScale(); double* trans = win->GetPhysicalTranslation(); // Vive to world axes double* vup = win->GetPhysicalViewUp(); double* dop = win->GetPhysicalViewDirection(); double vright[3]; vtkMath::Cross(dop, vup, vright); // extract HMD axes double hvright[3]; hvright[0] = poseMatrix[0][0]; hvright[1] = poseMatrix[1][0]; hvright[2] = poseMatrix[2][0]; double hvup[3]; hvup[0] = poseMatrix[0][1]; hvup[1] = poseMatrix[1][1]; hvup[2] = poseMatrix[2][1]; // convert position to world coordinates // get the position and orientation of the button press for (int i = 0; i < 3; i++) { ppos[i] = poseMatrix[i][3]; } pos[0] = ppos[0] * vright[0] + ppos[1] * vup[0] - ppos[2] * dop[0]; pos[1] = ppos[0] * vright[1] + ppos[1] * vup[1] - ppos[2] * dop[1]; pos[2] = ppos[0] * vright[2] + ppos[1] * vup[2] - ppos[2] * dop[2]; // now adjust for scale and translation for (int i = 0; i < 3; i++) { pos[i] = pos[i] * physicalScale - trans[i]; } // convert axes to world coordinates double fvright[3]; // final vright fvright[0] = hvright[0] * vright[0] + hvright[1] * vup[0] - hvright[2] * dop[0]; fvright[1] = hvright[0] * vright[1] + hvright[1] * vup[1] - hvright[2] * dop[1]; fvright[2] = hvright[0] * vright[2] + hvright[1] * vup[2] - hvright[2] * dop[2]; double fvup[3]; // final vup fvup[0] = hvup[0] * vright[0] + hvup[1] * vup[0] - hvup[2] * dop[0]; fvup[1] = hvup[0] * vright[1] + hvup[1] * vup[1] - hvup[2] * dop[1]; fvup[2] = hvup[0] * vright[2] + hvup[1] * vup[2] - hvup[2] * dop[2]; vtkMath::Cross(fvup, fvright, wdir); double ortho[3][3]; for (int i = 0; i < 3; i++) { ortho[i][0] = fvright[i]; ortho[i][1] = fvup[i]; ortho[i][2] = -wdir[i]; } vtkMath::Matrix3x3ToQuaternion(ortho, wxyz); // calc the return value wxyz double mag = sqrt(wxyz[1] * wxyz[1] + wxyz[2] * wxyz[2] + wxyz[3] * wxyz[3]); if (mag != 0.0) { wxyz[0] = 2.0 * vtkMath::DegreesFromRadians(atan2(mag, wxyz[0])); wxyz[1] /= mag; wxyz[2] /= mag; wxyz[3] /= mag; } else { wxyz[0] = 0.0; wxyz[1] = 0.0; wxyz[2] = 0.0; wxyz[3] = 1.0; } } //--------------------------------------------------------------------------------------------------------------------- // Purpose: Returns true if the action is active and its state is true //--------------------------------------------------------------------------------------------------------------------- bool GetDigitalActionState( vr::VRActionHandle_t action, vr::VRInputValueHandle_t* pDevicePath = nullptr) { vr::InputDigitalActionData_t actionData; vr::VRInput()->GetDigitalActionData( action, &actionData, sizeof(actionData), vr::k_ulInvalidInputValueHandle); if (pDevicePath) { *pDevicePath = vr::k_ulInvalidInputValueHandle; if (actionData.bActive) { vr::InputOriginInfo_t originInfo; if (vr::VRInputError_None == vr::VRInput()->GetOriginTrackedDeviceInfo( actionData.activeOrigin, &originInfo, sizeof(originInfo))) { *pDevicePath = originInfo.devicePath; } } } return actionData.bActive && actionData.bState; } //------------------------------------------------------------------------------ void vtkOpenVRRenderWindowInteractor::StartEventLoop() { this->StartedMessageLoop = 1; this->Done = false; vtkOpenVRRenderWindow* renWin = vtkOpenVRRenderWindow::SafeDownCast(this->RenderWindow); vtkRenderer* ren = static_cast<vtkRenderer*>(renWin->GetRenderers()->GetItemAsObject(0)); while (!this->Done) { this->DoOneEvent(renWin, ren); } } void vtkOpenVRRenderWindowInteractor::ProcessEvents() { vtkOpenVRRenderWindow* renWin = vtkOpenVRRenderWindow::SafeDownCast(this->RenderWindow); vtkRenderer* ren = static_cast<vtkRenderer*>(renWin->GetRenderers()->GetItemAsObject(0)); this->DoOneEvent(renWin, ren); } void vtkOpenVRRenderWindowInteractor::DoOneEvent(vtkOpenVRRenderWindow* renWin, vtkRenderer* ren) { if (!renWin || !ren) { return; } vr::IVRSystem* pHMD = renWin->GetHMD(); if (!pHMD) { // try rendering to create the HMD connection renWin->Render(); return; } vr::VREvent_t event; vtkOpenVROverlay* ovl = renWin->GetDashboardOverlay(); bool result = false; if (vr::VROverlay() && vr::VROverlay()->IsOverlayVisible(ovl->GetOverlayHandle())) { result = vr::VROverlay()->PollNextOverlayEvent(ovl->GetOverlayHandle(), &event, sizeof(vr::VREvent_t)); if (result) { int height = ovl->GetOverlayTexture()->GetHeight(); switch (event.eventType) { case vr::VREvent_MouseButtonDown: { if (event.data.mouse.button == vr::VRMouseButton_Left) { ovl->MouseButtonPress(event.data.mouse.x, height - event.data.mouse.y - 1); } } break; case vr::VREvent_MouseButtonUp: { if (event.data.mouse.button == vr::VRMouseButton_Left) { ovl->MouseButtonRelease(event.data.mouse.x, height - event.data.mouse.y - 1); } } break; case vr::VREvent_MouseMove: { ovl->MouseMoved(event.data.mouse.x, height - event.data.mouse.y - 1); } break; case vr::VREvent_OverlayShown: { renWin->RenderOverlay(); } break; case vr::VREvent_Quit: this->Done = true; break; } } // eat up any pending events while (pHMD->PollNextEvent(&event, sizeof(vr::VREvent_t))) { } } else { result = pHMD->PollNextEvent(&event, sizeof(vr::VREvent_t)); // process all pending events while (result) { result = pHMD->PollNextEvent(&event, sizeof(vr::VREvent_t)); } // Process SteamVR action state // UpdateActionState is called each frame to update the state of the actions themselves. The // application controls which action sets are active with the provided array of // VRActiveActionSet_t structs. vr::VRActiveActionSet_t actionSet = { 0 }; actionSet.ulActionSet = this->ActionsetVTK; vr::VRInput()->UpdateActionState(&actionSet, sizeof(actionSet), 1); for (int tracker = 0; tracker < vtkOpenVRRenderWindowInteractor::NumberOfTrackers; tracker++) { vr::InputOriginInfo_t originInfo; vr::EVRInputError evriError = vr::VRInput()->GetOriginTrackedDeviceInfo( this->Trackers[tracker].Source, &originInfo, sizeof(vr::InputOriginInfo_t)); if (evriError != vr::VRInputError_None) { // this can happen when a tracker isn't online continue; } vr::EVRCompositorError evrcError = vr::VRCompositor()->GetLastPoseForTrackedDeviceIndex( originInfo.trackedDeviceIndex, &this->Trackers[tracker].LastPose, nullptr); if (evrcError != vr::VRCompositorError_None) { vtkErrorMacro("Error in GetLastPoseForTrackedDeviceIndex: " << evrcError); continue; } if (this->Trackers[tracker].LastPose.bPoseIsValid) { double pos[3] = { 0.0 }; double ppos[3] = { 0.0 }; double wxyz[4] = { 0.0 }; double wdir[3] = { 0.0 }; this->ConvertPoseToWorldCoordinates( this->Trackers[tracker].LastPose, pos, wxyz, ppos, wdir); vtkNew<vtkEventDataDevice3D> ed; ed->SetWorldPosition(pos); ed->SetWorldOrientation(wxyz); ed->SetWorldDirection(wdir); switch (tracker) { case LeftHand: ed->SetDevice(vtkEventDataDevice::LeftController); break; case RightHand: ed->SetDevice(vtkEventDataDevice::RightController); break; case Head: ed->SetDevice(vtkEventDataDevice::HeadMountedDisplay); break; } ed->SetType(vtkCommand::Move3DEvent); // would like to remove the three following lines, they are there mostly to support // multitouch and event handling where the handler doesn;t use the data in the event // the first doesn't seem to be a common use pattern for VR, the second isn't used // to my knowledge this->SetPointerIndex(static_cast<int>(ed->GetDevice())); this->SetPhysicalEventPosition(ppos[0], ppos[1], ppos[2], this->PointerIndex); this->SetWorldEventPosition(pos[0], pos[1], pos[2], this->PointerIndex); this->SetWorldEventOrientation(wxyz[0], wxyz[1], wxyz[2], wxyz[3], this->PointerIndex); if (this->Enabled) { this->InvokeEvent(vtkCommand::Move3DEvent, ed); } } } // handle other actions for (auto& it : this->ActionMap) { vr::VRActionHandle_t& actionHandle = it.second.ActionHandle; vtkEventDataDevice3D* edp = nullptr; vr::VRInputValueHandle_t activeOrigin = 0; if (it.second.IsAnalog) { vr::InputAnalogActionData_t analogData; if (vr::VRInput()->GetAnalogActionData(actionHandle, &analogData, sizeof(analogData), vr::k_ulInvalidInputValueHandle) == vr::VRInputError_None && analogData.bActive) { // send a movement event edp = vtkEventDataDevice3D::New(); edp->SetTrackPadPosition(analogData.x, analogData.y); activeOrigin = analogData.activeOrigin; } } else { vr::InputDigitalActionData_t actionData; auto vrresult = vr::VRInput()->GetDigitalActionData( actionHandle, &actionData, sizeof(actionData), vr::k_ulInvalidInputValueHandle); if (vrresult == vr::VRInputError_None && actionData.bActive && actionData.bChanged) { edp = vtkEventDataDevice3D::New(); edp->SetAction( actionData.bState ? vtkEventDataAction::Press : vtkEventDataAction::Release); activeOrigin = actionData.activeOrigin; } } if (edp) { double pos[3] = { 0.0 }; double ppos[3] = { 0.0 }; double wxyz[4] = { 0.0 }; double wdir[3] = { 0.0 }; vr::InputBindingInfo_t inBindingInfo; uint32_t returnedBindingInfoCount = 0; /*vr::EVRInputError abinfo = */ vr::VRInput()->GetActionBindingInfo( actionHandle, &inBindingInfo, sizeof(inBindingInfo), 1, &returnedBindingInfoCount); std::string inputSource = inBindingInfo.rchInputSourceType; if (inputSource == "trackpad") { edp->SetInput(vtkEventDataDeviceInput::TrackPad); } else if (inputSource == "joystick") { edp->SetInput(vtkEventDataDeviceInput::Joystick); } else if (inputSource == "trigger") { edp->SetInput(vtkEventDataDeviceInput::Trigger); } else if (inputSource == "grip") { edp->SetInput(vtkEventDataDeviceInput::Grip); } else { edp->SetInput(vtkEventDataDeviceInput::Unknown); } vr::InputOriginInfo_t originInfo; if (vr::VRInputError_None == vr::VRInput()->GetOriginTrackedDeviceInfo(activeOrigin, &originInfo, sizeof(originInfo))) { if (originInfo.devicePath == this->Trackers[LeftHand].Source) { edp->SetDevice(vtkEventDataDevice::LeftController); this->ConvertPoseToWorldCoordinates(this->Trackers[0].LastPose, pos, wxyz, ppos, wdir); } if (originInfo.devicePath == this->Trackers[RightHand].Source) { edp->SetDevice(vtkEventDataDevice::RightController); this->ConvertPoseToWorldCoordinates(this->Trackers[1].LastPose, pos, wxyz, ppos, wdir); } // edp->SetInput(originInfo.); } edp->SetWorldPosition(pos); edp->SetWorldOrientation(wxyz); edp->SetWorldDirection(wdir); edp->SetType(it.second.EventId); if (it.second.UseFunction) { it.second.Function(edp); } else { this->InvokeEvent(it.second.EventId, edp); } edp->Delete(); } } if (this->RecognizeGestures) { this->RecognizeComplexGesture(nullptr); } this->InvokeEvent(vtkCommand::RenderEvent); auto ostate = renWin->GetState(); renWin->MakeCurrent(); ostate->Reset(); ostate->Push(); renWin->Render(); ostate->Pop(); } } void vtkOpenVRRenderWindowInteractor::HandleGripEvents(vtkEventData* ed) { vtkEventDataDevice3D* edata = ed->GetAsEventDataDevice3D(); if (!edata) { return; } this->PointerIndex = static_cast<int>(edata->GetDevice()); if (edata->GetAction() == vtkEventDataAction::Press) { this->DeviceInputDownCount[this->PointerIndex] = 1; this->StartingPhysicalEventPositions[this->PointerIndex][0] = this->PhysicalEventPositions[this->PointerIndex][0]; this->StartingPhysicalEventPositions[this->PointerIndex][1] = this->PhysicalEventPositions[this->PointerIndex][1]; this->StartingPhysicalEventPositions[this->PointerIndex][2] = this->PhysicalEventPositions[this->PointerIndex][2]; vtkVRRenderWindow* renWin = vtkVRRenderWindow::SafeDownCast(this->RenderWindow); renWin->GetPhysicalToWorldMatrix(this->StartingPhysicalToWorldMatrix); // Both controllers have the grip down, start multitouch if (this->DeviceInputDownCount[static_cast<int>(vtkEventDataDevice::LeftController)] && this->DeviceInputDownCount[static_cast<int>(vtkEventDataDevice::RightController)]) { // we do not know what the gesture is yet this->CurrentGesture = vtkCommand::StartEvent; } return; } // end the gesture if needed if (edata->GetAction() == vtkEventDataAction::Release) { this->DeviceInputDownCount[this->PointerIndex] = 0; if (edata->GetInput() == vtkEventDataDeviceInput::Grip) { if (this->CurrentGesture == vtkCommand::PinchEvent) { this->EndPinchEvent(); } if (this->CurrentGesture == vtkCommand::PanEvent) { this->EndPanEvent(); } if (this->CurrentGesture == vtkCommand::RotateEvent) { this->EndRotateEvent(); } this->CurrentGesture = vtkCommand::NoEvent; return; } } } //------------------------------------------------------------------------------ void vtkOpenVRRenderWindowInteractor::RecognizeComplexGesture(vtkEventDataDevice3D*) { // Recognize gesture only if one button is pressed per controller int lhand = static_cast<int>(vtkEventDataDevice::LeftController); int rhand = static_cast<int>(vtkEventDataDevice::RightController); if (this->DeviceInputDownCount[lhand] > 1 || this->DeviceInputDownCount[lhand] == 0 || this->DeviceInputDownCount[rhand] > 1 || this->DeviceInputDownCount[rhand] == 0) { this->CurrentGesture = vtkCommand::NoEvent; return; } double* posVals[2]; double* startVals[2]; posVals[0] = this->PhysicalEventPositions[lhand]; posVals[1] = this->PhysicalEventPositions[rhand]; startVals[0] = this->StartingPhysicalEventPositions[lhand]; startVals[1] = this->StartingPhysicalEventPositions[rhand]; // The meat of the algorithm // on move events we analyze them to determine what type // of movement it is and then deal with it. if (this->CurrentGesture != vtkCommand::NoEvent) { // calculate the distances double originalDistance = sqrt(vtkMath::Distance2BetweenPoints(startVals[0], startVals[1])); double newDistance = sqrt(vtkMath::Distance2BetweenPoints(posVals[0], posVals[1])); // calculate the translations double t0[3]; t0[0] = posVals[0][0] - startVals[0][0]; t0[1] = posVals[0][1] - startVals[0][1]; t0[2] = posVals[0][2] - startVals[0][2]; double t1[3]; t1[0] = posVals[1][0] - startVals[1][0]; t1[1] = posVals[1][1] - startVals[1][1]; t1[2] = posVals[1][2] - startVals[1][2]; double trans[3]; trans[0] = (t0[0] + t1[0]) / 2.0; trans[1] = (t0[1] + t1[1]) / 2.0; trans[2] = (t0[2] + t1[2]) / 2.0; // calculate rotations double originalAngle = vtkMath::DegreesFromRadians( atan2((double)startVals[1][2] - startVals[0][2], (double)startVals[1][0] - startVals[0][0])); double newAngle = vtkMath::DegreesFromRadians( atan2((double)posVals[1][2] - posVals[0][2], (double)posVals[1][0] - posVals[0][0])); // angles are cyclic so watch for that, -179 and 179 are only 2 apart :) if (newAngle - originalAngle > 180.0) { newAngle -= 360; } if (newAngle - originalAngle < -180.0) { newAngle += 360; } double angleDeviation = newAngle - originalAngle; // do we know what gesture we are doing yet? If not // see if we can figure it out if (this->CurrentGesture == vtkCommand::StartEvent) { // pinch is a move to/from the center point // rotate is a move along the circumference // pan is a move of the center point // compute the distance along each of these axes in meters // the first to break thresh wins double thresh = 0.05; // in meters double pinchDistance = fabs(newDistance - originalDistance); double panDistance = sqrt(trans[0] * trans[0] + trans[1] * trans[1] + trans[2] * trans[2]); double rotateDistance = originalDistance * 3.1415926 * fabs(angleDeviation) / 180.0; if (pinchDistance > thresh && pinchDistance > panDistance && pinchDistance > rotateDistance) { this->CurrentGesture = vtkCommand::PinchEvent; this->Scale = 1.0; this->StartPinchEvent(); } else if (rotateDistance > thresh && rotateDistance > panDistance) { this->CurrentGesture = vtkCommand::RotateEvent; this->Rotation = 0.0; this->StartRotateEvent(); } else if (panDistance > thresh) { this->CurrentGesture = vtkCommand::PanEvent; this->Translation3D[0] = 0.0; this->Translation3D[1] = 0.0; this->Translation3D[2] = 0.0; this->StartPanEvent(); } } // if we have found a specific type of movement then // handle it if (this->CurrentGesture == vtkCommand::RotateEvent) { this->SetRotation(angleDeviation); this->RotateEvent(); } if (this->CurrentGesture == vtkCommand::PinchEvent) { this->SetScale(newDistance / originalDistance); this->PinchEvent(); } if (this->CurrentGesture == vtkCommand::PanEvent) { // Vive to world axes vtkVRRenderWindow* win = vtkVRRenderWindow::SafeDownCast(this->RenderWindow); double* vup = win->GetPhysicalViewUp(); double* dop = win->GetPhysicalViewDirection(); double physicalScale = win->GetPhysicalScale(); double vright[3]; vtkMath::Cross(dop, vup, vright); double wtrans[3]; // convert translation to world coordinates // now adjust for scale for (int i = 0; i < 3; i++) { wtrans[i] = trans[0] * vright[i] + trans[1] * vup[i] - trans[2] * dop[i]; wtrans[i] = wtrans[i] * physicalScale; } this->SetTranslation3D(wtrans); this->PanEvent(); } } } //------------------------------------------------------------------------------ void vtkOpenVRRenderWindowInteractor::AddAction( std::string path, vtkCommand::EventIds eid, bool isAnalog) { auto& am = this->ActionMap[path]; am.EventId = eid; am.UseFunction = false; am.IsAnalog = isAnalog; if (this->Initialized) { vr::VRInput()->GetActionHandle(path.c_str(), &am.ActionHandle); // "path" : "/user/hand/right/input/trackpad" } } void vtkOpenVRRenderWindowInteractor::AddAction( std::string path, bool isAnalog, std::function<void(vtkEventData*)> func) { auto& am = this->ActionMap[path]; am.UseFunction = true; am.Function = func; am.IsAnalog = isAnalog; if (this->Initialized) { vr::VRInput()->GetActionHandle(path.c_str(), &am.ActionHandle); } } //------------------------------------------------------------------------------ void vtkOpenVRRenderWindowInteractor::Initialize() { // make sure we have a RenderWindow and camera if (!this->RenderWindow) { vtkErrorMacro(<< "No renderer defined!"); return; } if (this->Initialized) { return; } vtkVRRenderWindow* ren = vtkVRRenderWindow::SafeDownCast(this->RenderWindow); int* size; this->Initialized = 1; // get the info we need from the RenderingWindow size = ren->GetSize(); ren->GetPosition(); this->Enable(); this->Size[0] = size[0]; this->Size[1] = size[1]; std::string fullpath = vtksys::SystemTools::CollapseFullPath(this->ActionManifestFileName); vr::VRInput()->SetActionManifestPath(fullpath.c_str()); vr::VRInput()->GetActionSetHandle(this->ActionSetName.c_str(), &this->ActionsetVTK); // add in pose events vr::VRInput()->GetInputSourceHandle("/user/hand/left", &this->Trackers[LeftHand].Source); // vr::VRInput()->GetActionHandle("/actions/vtk/in/HandLeft", // &this->Trackers[LeftHand].ActionPose); vr::VRInput()->GetInputSourceHandle("/user/hand/right", &this->Trackers[RightHand].Source); // vr::VRInput()->GetActionHandle( // "/actions/vtk/in/HandRight", &this->Trackers[RightHand].ActionPose); vr::VRInput()->GetInputSourceHandle("/user/head", &this->Trackers[Head].Source); // vr::VRInput()->GetActionHandle("/actions/vtk/in/head", &this->Trackers[Head].ActionPose); this->AddAction("/actions/vtk/in/LeftGripAction", false, [this](vtkEventData* ed) { this->HandleGripEvents(ed); }); this->AddAction("/actions/vtk/in/RightGripAction", false, [this](vtkEventData* ed) { this->HandleGripEvents(ed); }); // add extra event actions for (auto& it : this->ActionMap) { vr::VRInput()->GetActionHandle(it.first.c_str(), &it.second.ActionHandle); } } //------------------------------------------------------------------------------ int vtkOpenVRRenderWindowInteractor::InternalCreateTimer( int vtkNotUsed(timerId), int vtkNotUsed(timerType), unsigned long vtkNotUsed(duration)) { // todo return 0; } //------------------------------------------------------------------------------ int vtkOpenVRRenderWindowInteractor::InternalDestroyTimer(int vtkNotUsed(platformTimerId)) { // todo return 0; } //------------------------------------------------------------------------------ // Specify the default function to be called when an interactor needs to exit. // This callback is overridden by an instance ExitMethod that is defined. void vtkOpenVRRenderWindowInteractor::SetClassExitMethod(void (*f)(void*), void* arg) { if (f != vtkOpenVRRenderWindowInteractor::ClassExitMethod || arg != vtkOpenVRRenderWindowInteractor::ClassExitMethodArg) { // delete the current arg if there is a delete method if ((vtkOpenVRRenderWindowInteractor::ClassExitMethodArg) && (vtkOpenVRRenderWindowInteractor::ClassExitMethodArgDelete)) { (*vtkOpenVRRenderWindowInteractor::ClassExitMethodArgDelete)( vtkOpenVRRenderWindowInteractor::ClassExitMethodArg); } vtkOpenVRRenderWindowInteractor::ClassExitMethod = f; vtkOpenVRRenderWindowInteractor::ClassExitMethodArg = arg; // no call to this->Modified() since this is a class member function } } //------------------------------------------------------------------------------ // Set the arg delete method. This is used to free user memory. void vtkOpenVRRenderWindowInteractor::SetClassExitMethodArgDelete(void (*f)(void*)) { if (f != vtkOpenVRRenderWindowInteractor::ClassExitMethodArgDelete) { vtkOpenVRRenderWindowInteractor::ClassExitMethodArgDelete = f; // no call to this->Modified() since this is a class member function } } //------------------------------------------------------------------------------ void vtkOpenVRRenderWindowInteractor::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); os << indent << "StartedMessageLoop: " << this->StartedMessageLoop << endl; } //------------------------------------------------------------------------------ void vtkOpenVRRenderWindowInteractor::ExitCallback() { if (this->HasObserver(vtkCommand::ExitEvent)) { this->InvokeEvent(vtkCommand::ExitEvent, nullptr); } else if (vtkOpenVRRenderWindowInteractor::ClassExitMethod) { (*vtkOpenVRRenderWindowInteractor::ClassExitMethod)( vtkOpenVRRenderWindowInteractor::ClassExitMethodArg); } this->TerminateApp(); } //------------------------------------------------------------------------------ vtkEventDataDevice vtkOpenVRRenderWindowInteractor::GetPointerDevice() { if (this->PointerIndex == 0) { return vtkEventDataDevice::RightController; } if (this->PointerIndex == 1) { return vtkEventDataDevice::LeftController; } return vtkEventDataDevice::Unknown; } //------------------------------------------------------------------------------ void vtkOpenVRRenderWindowInteractor::GetStartingPhysicalToWorldMatrix( vtkMatrix4x4* startingPhysicalToWorldMatrix) { if (!startingPhysicalToWorldMatrix) { return; } startingPhysicalToWorldMatrix->DeepCopy(this->StartingPhysicalToWorldMatrix); }
/* XMRig * Copyright 2010 Jeff Garzik <jgarzik@pobox.com> * Copyright 2012-2014 pooler <pooler@litecoinpool.org> * Copyright 2014 Lucas Jones <https://github.com/lucasjones> * Copyright 2014-2016 Wolf9466 <https://github.com/OhGodAPet> * Copyright 2016 Jay D Dee <jayddee246@gmail.com> * Copyright 2017-2018 XMR-Stak <https://github.com/fireice-uk>, <https://github.com/psychocrypt> * Copyright 2018 Lee Clagett <https://github.com/vtnerd> * Copyright 2018-2020 SChernykh <https://github.com/SChernykh> * Copyright 2016-2020 XMRig <https://github.com/xmrig>, <support@xmrig.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "base/net/tls/TlsConfig.h" #include "3rdparty/rapidjson/document.h" #include "base/io/json/Json.h" #include "base/io/log/Log.h" #include "base/net/tls/TlsGen.h" namespace xmrig { const char *TlsConfig::kCert = "cert"; const char *TlsConfig::kEnabled = "enabled"; const char *TlsConfig::kCertKey = "cert_key"; const char *TlsConfig::kCiphers = "ciphers"; const char *TlsConfig::kCipherSuites = "ciphersuites"; const char *TlsConfig::kDhparam = "dhparam"; const char *TlsConfig::kGen = "gen"; const char *TlsConfig::kProtocols = "protocols"; static const char *kTLSv1 = "TLSv1"; static const char *kTLSv1_1 = "TLSv1.1"; static const char *kTLSv1_2 = "TLSv1.2"; static const char *kTLSv1_3 = "TLSv1.3"; } // namespace xmrig /** * "cert" load TLS certificate chain from file. * "cert_key" load TLS private key from file. * "ciphers" set list of available ciphers (TLSv1.2 and below). * "ciphersuites" set list of available TLSv1.3 ciphersuites. * "dhparam" load DH parameters for DHE ciphers from file. */ xmrig::TlsConfig::TlsConfig(const rapidjson::Value &value) { if (value.IsObject()) { m_enabled = Json::getBool(value, kEnabled, m_enabled); setProtocols(Json::getString(value, kProtocols)); setCert(Json::getString(value, kCert)); setKey(Json::getString(value, kCertKey)); setCiphers(Json::getString(value, kCiphers)); setCipherSuites(Json::getString(value, kCipherSuites)); setDH(Json::getString(value, kDhparam)); if (m_key.isNull()) { setKey(Json::getString(value, "cert-key")); } if (m_enabled && !isValid()) { generate(Json::getString(value, kGen)); } } else if (value.IsBool()) { m_enabled = value.GetBool(); if (m_enabled) { generate(); } } # ifdef XMRIG_FORCE_TLS else if (value.IsNull()) { generate(); } # endif else if (value.IsString()) { generate(value.GetString()); } else { m_enabled = false; } } bool xmrig::TlsConfig::generate(const char *commonName) { TlsGen gen; try { gen.generate(commonName); } catch (std::exception &ex) { LOG_ERR("%s", ex.what()); return false; } setCert(gen.cert()); setKey(gen.certKey()); m_enabled = true; return true; } rapidjson::Value xmrig::TlsConfig::toJSON(rapidjson::Document &doc) const { using namespace rapidjson; auto &allocator = doc.GetAllocator(); Value obj(kObjectType); obj.AddMember(StringRef(kEnabled), m_enabled, allocator); if (m_protocols > 0) { std::vector<String> protocols; if (m_protocols & TLSv1) { protocols.emplace_back(kTLSv1); } if (m_protocols & TLSv1_1) { protocols.emplace_back(kTLSv1_1); } if (m_protocols & TLSv1_2) { protocols.emplace_back(kTLSv1_2); } if (m_protocols & TLSv1_3) { protocols.emplace_back(kTLSv1_3); } obj.AddMember(StringRef(kProtocols), String::join(protocols, ' ').toJSON(doc), allocator); } else { obj.AddMember(StringRef(kProtocols), kNullType, allocator); } obj.AddMember(StringRef(kCert), m_cert.toJSON(), allocator); obj.AddMember(StringRef(kCertKey), m_key.toJSON(), allocator); obj.AddMember(StringRef(kCiphers), m_ciphers.toJSON(), allocator); obj.AddMember(StringRef(kCipherSuites), m_cipherSuites.toJSON(), allocator); obj.AddMember(StringRef(kDhparam), m_dhparam.toJSON(), allocator); return obj; } void xmrig::TlsConfig::setProtocols(const char *protocols) { const std::vector<String> vec = String(protocols).split(' '); for (const String &value : vec) { if (value == kTLSv1) { m_protocols |= TLSv1; } else if (value == kTLSv1_1) { m_protocols |= TLSv1_1; } else if (value == kTLSv1_2) { m_protocols |= TLSv1_2; } else if (value == kTLSv1_3) { m_protocols |= TLSv1_3; } } } void xmrig::TlsConfig::setProtocols(const rapidjson::Value &protocols) { m_protocols = 0; if (protocols.IsUint()) { return setProtocols(protocols.GetUint()); } if (protocols.IsString()) { return setProtocols(protocols.GetString()); } }
#pragma once namespace Assert { struct test_passed { static constexpr bool passed = true; }; struct test_failed { static constexpr bool passed = false; }; template <bool pass> struct check_true : test_failed {}; template <> struct check_true<true> : test_passed {}; #pragma GCC diagnostic push #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wunneeded-internal-declaration" #pragma GCC diagnostic ignored "-Wunneeded-internal-declaration" auto handle_test = [](auto shouldFail) { static_assert(decltype(shouldFail)::passed,"assertion failed"); }; #pragma clang diagnostic pop #pragma GCC diagnostic pop template <bool x> using is_true = decltype(handle_test(check_true<x>{})); template <bool x> using is_false = decltype(handle_test(check_true<!x>{})); template <typename,typename> struct check_equal : test_failed {}; template <typename A> struct check_equal<A,A> : test_passed {}; template <typename A, typename B> using are_equal = decltype(handle_test(check_equal<A,B>{})); template <typename,typename> struct check_different : test_passed {}; template <typename A> struct check_different<A,A> : test_failed {}; template <typename A, typename B> using are_different = decltype(handle_test(check_different<A,B>{})); };
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 1995-2011 Opera Software ASA. All rights reserved. * * This file is part of the Opera web browser. It may not be distributed * under any circumstances. */ #ifndef WEB_HANDLER_PERMISSION_CONTROLLER_H #define WEB_HANDLER_PERMISSION_CONTROLLER_H #include "adjunct/desktop_util/adt/opproperty.h" #include "adjunct/quick_toolkit/contexts/OkCancelDialogContext.h" #include "modules/windowcommander/OpWindowCommander.h" /** * Controller for the registered web handlers usage permission approval */ class WebHandlerPermissionController : public OkCancelDialogContext { public: /** * Create a new dialog associcated with the callback and window */ static void Add(OpDocumentListener::WebHandlerCallback* cb, DesktopWindow* parent); /** * Close and destroy the dialog without touching the callback object. * Typically to be used when core requests a cancellation the dialog */ static void Remove(OpDocumentListener::WebHandlerCallback* cb); ~WebHandlerPermissionController(); virtual OP_STATUS HandleAction(OpInputAction* action); virtual BOOL DisablesAction(OpInputAction* action); OP_STATUS GetApplication(OpString& application, BOOL validate); virtual void OnTextChanged(const OpStringC& text); protected: virtual void OnCancel(); virtual void OnOk(); private: explicit WebHandlerPermissionController(OpDocumentListener::WebHandlerCallback* cb) : m_webhandler_cb(cb) , m_widgets(0) , m_mode(NotDefined) , m_is_mailto(false) {} // DialogContext virtual void InitL(); virtual void OnRadioChanged(bool new_value); enum Mode { NotDefined = -1, // These types are used in array indexing. See m_radio_value WebHandler = 0, DefaultApplication = 1, CustomApplication = 2, MaxModeCount = 3 // Always last }; OpDocumentListener::WebHandlerCallback* m_webhandler_cb; const TypedObjectCollection* m_widgets; Mode m_mode; OpString m_application; OpProperty<OpString> m_application_text; OpProperty<bool> m_radio_value[3]; bool m_is_mailto; OpProperty<bool> m_dont_ask_again; static OpVector<WebHandlerPermissionController> m_list; }; #endif // WEB_HANDLER_PERMISSION_CONTROLLER_H
#include <cstring> #include "value.h" #include "basicValues.h" #include "arrayValue.h" #include "objectValue.h" #include "array.h" #include "object.h" #include "parser.h" #include "serializer.h" #include "binary.h" #include "stringValue.h" #include "fnv.h" #include "binjson.tcc" #include "path.h" #include "operations.h" namespace json { KeyStart key; const IValue *createByType(ValueType vtype) { switch (vtype) { case undefined: return AbstractValue::getUndefined(); case null: return NullValue::getNull(); case boolean: return BoolValue::getBool(false); case string: return AbstractStringValue::getEmptyString(); case number: return AbstractNumberValue::getZero(); case array: return AbstractArrayValue::getEmptyArray(); case object: return AbstractObjectValue::getEmptyObject(); default: throw std::runtime_error("json::createByType - Invalid type requested"); } } Value::Value(ValueType vtype):v(createByType(vtype)) { } Value::Value(bool value):v(BoolValue::getBool(value)) { } Value::Value(const char * value):v(StringValue::create(value)) { } Value::Value(const std::string & value):v(StringValue::create(value)) { } Value::Value(const StringView<char>& value):v(StringValue::create(value)) { } Value::Value(const StringView<Value>& value) { RefCntPtr<ArrayValue> res = ArrayValue::create(value.length); for (Value z: value) res->push_back(z.getHandle()); v = PValue::staticCast(res); } String Value::toString() const { switch (type()) { case null: case boolean: case number: if (flags() & json::preciseNumber) return String(*this); else return stringify(); case undefined: return String("<undefined>"); case object: return stringify(); case array: return stringify(); case string: if (flags() & binaryString) { BinaryEncoding enc = Binary::getEncoding(v->unproxy()); Value v = enc->encodeBinaryValue(getBinary(enc)); return String(v); } else return String(*this); default: return String("<unknown>"); } } Value Value::fromString(const StringView<char>& string) { std::size_t pos = 0; return parse([&pos,&string]() -> char { if (pos == string.length) return -1; else return string.data[pos++]; }); } Value Value::fromStream(std::istream & input) { return parse([&]() { return (char)input.get(); }); } Value Value::fromFile(FILE * f) { return parse([&] { return (char)fgetc(f); }); } String Value::stringify() const { std::string buff; serialize([&](char c) { buff.push_back(c); }); return String(buff); } String Value::stringify(UnicodeFormat format) const { std::string buff; serialize(format,[&](char c) { buff.push_back(c); }); return String(buff); } void Value::toStream(std::ostream & output) const { serialize([&](char c) { output.put(c); }); } void Value::toStream(UnicodeFormat format, std::ostream & output) const { serialize(format, [&](char c) { output.put(c); }); } template<typename T> PValue allocUnsigned(T x) { if (x == (T)0) return AbstractNumberValue::getZero(); if (sizeof(T) <= sizeof(uintptr_t)) return new UnsignedIntegerValue(uintptr_t(x)); else if (sizeof(T) <= sizeof(ULongInt)) return new UnsignedLongValue(ULongInt(x)); else return new NumberValue((double)x); } template<typename T> PValue allocSigned(T x) { if (x == (T)0) return AbstractNumberValue::getZero(); if (sizeof(T) <= sizeof(intptr_t)) return new IntegerValue(intptr_t(x)); else if (sizeof(T) <= sizeof(LongInt)) return new LongValue(LongInt(x)); else return new NumberValue((double)x); } Value::Value(signed short x):v(allocSigned(x)) { } Value::Value(unsigned short x):v(allocUnsigned(x)) { } Value::Value(signed int x):v(allocSigned(x)) { } Value::Value(unsigned int x):v(allocUnsigned(x)) { } Value::Value(signed long x):v(allocSigned(x)) { } Value::Value(unsigned long x):v(allocUnsigned(x)) { } Value::Value(signed long long x):v(allocSigned(x)) { } Value::Value(unsigned long long x):v(allocUnsigned(x)) { } void Value::toFile(FILE * f) const { serialize([&](char c) { fputc(c, f); }); } void Value::toFile(UnicodeFormat format, FILE * f) const { serialize(format, [&](char c) { fputc(c, f); }); } class SubArray : public AbstractArrayValue { public: SubArray(PValue parent, std::size_t start, std::size_t len) :parent(parent), start(start), len(len) { const IValue *p = parent; if (typeid(*p) == typeid(SubArray)) { const SubArray *x = static_cast<const SubArray *>((const IValue *)parent); this->parent = x->parent; this->start = this->start + x->start; } } virtual std::size_t size() const override { return len; } virtual const IValue *itemAtIndex(std::size_t index) const override { return parent->itemAtIndex(start + index); } virtual bool enumItems(const IEnumFn &fn) const override { for (std::size_t x = 0; x < len; x++) { if (!fn(itemAtIndex(x))) return false; } return true; } virtual bool getBool() const override { return true; } protected: PValue parent; std::size_t start; std::size_t len; }; Value::TwoValues Value::splitAt(int pos) const { if (type() == string) { String s( *this); return s.splitAt(pos); } else { std::size_t sz = size(); if (pos > 0) { if ((unsigned)pos < sz) { return TwoValues(new SubArray(v, 0, pos), new SubArray(v, pos, sz - pos)); } else { return TwoValues(*this, array); } } else if (pos < 0) { if ((int)sz + pos > 0) return splitAt((int)sz + pos); else return TwoValues(array, *this); } else { return TwoValues(array, *this); } return std::pair<Value, Value>(); } } PValue prepareValues(const std::initializer_list<Value>& data) { return Value(array, data).getHandle(); } Value::Value(const std::initializer_list<Value>& data) :v(data.size() == 0? PValue(AbstractArrayValue::getEmptyArray()) :prepareValues(data)) { } /* Value::Value(UInt value):v(new UnsignedIntegerValue(value)) { } Value::Value(Int value):v(new IntegerValue(value)) { } */ Value::Value(double value):v( value == 0?AbstractNumberValue::getZero() :new NumberValue(value) ) { } Value::Value(float value):v( value == 0?AbstractNumberValue::getZero() :new NumberValue(value) ) { } Value::Value(std::nullptr_t):v(NullValue::getNull()) { } Value::Value():v(AbstractValue::getUndefined()) { } Value::Value(const IValue * v):v(v) { } Value::Value(const PValue & v):v(v) { } Value::Value(const Array & value):v(value.commit()) { } Value::Value(const Object & value) : v(value.commit()) { } uintptr_t maxPrecisionDigits = 9; UnicodeFormat defaultUnicodeFormat = emitEscaped; bool enableParsePreciseNumbers = false; ///const double maxMantisaMult = pow(10.0, floor(log10(UInt(-1)))); bool Value::operator ==(const Value& other) const { if (other.v == v) return true; else return other.v->equal(v); } bool Value::operator !=(const Value& other) const { if (other.v == v) return false; else return !other.v->equal(v); } ValueIterator Value::begin() const {return ValueIterator(*this,0);} ValueIterator Value::end() const {return ValueIterator(*this,size());} Value::Value(const String& value):v(value.getHandle()) { } Value Value::reverse() const { Array out; for (UInt i = size(); i > 0; i--) { out.add(this->operator [](i-1)); } return out; } Binary Value::getBinary(BinaryEncoding be) const { return Binary::decodeBinaryValue(*this,be); } Value::Value(const BinaryView& binary, BinaryEncoding enc):v(StringValue::create(binary,enc)) {} Value::Value(const Binary& binary):v(binary.getHandle()) {} static Allocator defaultAllocator = { &::operator new, &::operator delete }; const Allocator * Value::allocator = &defaultAllocator; void *AllocObject::operator new(std::size_t sz) { return Value::allocator->alloc(sz); } void AllocObject::operator delete(void *ptr, std::size_t) { return Value::allocator->dealloc(ptr); } const Allocator *Allocator::getInstance() { return Value::allocator; } Value::Value(ValueType type, const StringView<Value>& values, bool skipUndef) { std::vector<PValue> vp; switch (type) { case array: { RefCntPtr<ArrayValue> vp = ArrayValue::create(values.length); for (const Value &v: values) { if (!skipUndef || v.defined()) vp->push_back(v.getHandle()); } v = PValue::staticCast(vp); break; } case object: { RefCntPtr<ObjectValue> vp = ObjectValue::create(values.length); StrViewA lastKey; bool ordered = true; for (const Value &v: values) { if (!skipUndef || v.defined()) { StrViewA k = v.getKey(); int c = lastKey.compare(k); if (c > 0) { ordered = false; } else if (c == 0) { if (!vp->empty()) vp->pop_back(); } vp->push_back(v.getHandle()); lastKey = k; } } if (!ordered) { vp->sort(); } v = PValue::staticCast(vp); break; } case string: { std::vector<String> tmpStr; tmpStr.reserve(values.length); std::size_t needsz = 0; for (auto &&x : values) { String s = x.toString(); tmpStr.push_back(s); needsz += s.length(); } v = PValue(new (needsz) StringValue(nullptr, needsz, [&](char *c) { for (auto &&x : tmpStr) { std::memcpy(c, x.c_str(), x.length()); c += x.length(); } return needsz; })); break; } default: throw std::runtime_error("json::Value(type,...) - Invalid type requested"); } } static Value setToPathRev(const Path &p, const Value &oldVal, const Value &newVal) { if (p.isRoot()) { if (newVal.flags() & json::valueDiff) { switch (newVal.type()) { case json::object: return Object::applyDiff(oldVal,newVal); case array: //currently unsupported return newVal; default: //cannot merge noncontainer return newVal; } } else { return newVal; } } if (p.isIndex()) { Array a; std::size_t i = p.getIndex(); if (oldVal.type() == array) a.setBaseObject(oldVal); if (i >= a.size()) a.push_back(setToPathRev(p.getParent(),undefined,newVal)); else a.set(i, setToPathRev(p.getParent(),a[i],newVal)); return a; } if (p.isKey()) { Object o; if (oldVal.type() == object) o.setBaseObject(oldVal); StrViewA k = p.getKey(); o.set(k,setToPathRev(p.getParent(),o[k], newVal)); return o; } throw std::runtime_error("Unreachable section reached (setToPathRev)"); } static Value reversePath(const Path &p, const Path &newPath, const Value &oldval, const Value &newval) { if (p.isRoot()) return setToPathRev(newPath, oldval, newval); if (p.isIndex()) return reversePath(p.getParent(),Path(newPath,p.getIndex()), oldval, newval); if (p.isKey()) return reversePath(p.getParent(),Path(newPath,p.getKey()), oldval, newval); throw std::runtime_error("Unreachable section reached (reversePath)"); } Value Value::replace(const Path& path, const Value& val) const { const Path &newpath = Path::root; return reversePath(path, newpath, *this, val); } Value Value::replace(const StrViewA &key, const Value& val) const { return replace(Path::root/key,val); } Value Value::replace(const uintptr_t index, const Value& val) const { return replace(Path::root/index,val); } int Value::compare(const Value &a, const Value &b) { return a.v->compare(b.v); } Range<ValueIterator> Value::range() const { return Range<ValueIterator>(begin(),end()); } std::size_t Value::indexOf(const Value &v, std::size_t start) const { std::size_t len = size(); for (std::size_t i = start; i < len; i++) { if ((*this)[i] == v) return i; } return npos; } std::size_t Value::lastIndexOf(const Value &v, std::size_t start) const { for (std::size_t i = std::min(start,size()); i > 0; ){ --i; if ((*this)[i] == v) return i; } return npos; } static bool findInArray(const Array &a, const Value &v, std::size_t start, std::size_t &pos) { std::size_t i = start; while (i < a.size()) { if (a[i] == v) { pos = i; return true; } ++i; } i = 0; while (i < start) { if (a[i] == v) { pos = i; return true; } ++i; } pos = start; return false; } Value json::Value::merge(const Value& other) const { if (type() != other.type()) return undefined; switch (type()) { case undefined: case null: return other; case boolean: return getBool() != other.getBool(); case number: return getNumber() + other.getNumber(); case string: return String({String(*this), String(other)}); case array: { Array p(*this); auto itr = other.begin(); while (itr != other.end()) { Value v = *itr; if (v.defined()) { p.push_back(v); ++itr; } else { ++itr; std::size_t lastPos = 0; while (itr != other.end()) { Value find = *itr; ++itr; if (itr != other.end()) { Value insert = *itr; ++itr; std::size_t pos; if (findInArray(p, find, lastPos, pos)) { if (insert.defined()) { p.insert(pos, insert); lastPos = pos+1; } else { p.erase(pos); } } else { if (insert.defined()) p.push_back(insert); } } } break; } } return p; } case object: { auto i1 = begin(), e1 = end(); auto i2 = other.begin(), e2 = other.end(); Object res; while (i1 != e1 && i2 != e2) { Value v1 = *i1; Value v2 = *i2; if (v1.getKey() < v2.getKey()) { res.set(v1); ++i1; } else if (v1.getKey() > v2.getKey()) { res.set(v2); ++i2; } else { if (v1.type() == json::object && v2.type() == json::object) { res.set(v1.getKey(),v1.merge(v2)); } else { res.set(v2); } ++i1; ++i2; } } while (i1 != e1) { res.set(*i1); ++i1; } while (i2 != e2) { res.set(*i2); ++i2; } return res; } } return undefined; } Value json::Value::diff(const Value& other) const { if (type() != other.type()) return undefined; switch (type()) { case undefined: case null: return other; case boolean: return getBool() != other.getBool(); case number: return getNumber() - other.getNumber(); case string: { auto str1 = getString(); auto str2 = other.getString(); if (str1.length < str2.length) return *this; if (str1.substr(str1.length - str2.length) == str2) { return str1.substr(0,str1.length - str2.length); } else { return *this; } } case array: { std::size_t tsz = size(); std::size_t osz = other.size(); std::vector<Value> diff; std::vector<Value> append; std::size_t t = 0, o = 0; while (t < tsz && o < osz) { if ((*this)[t] != other[o]) { if (t + 1 < tsz && (*this)[t+1] == other[o]) { diff.push_back((*this)[t]); diff.push_back(json::undefined); t++; } else if (o < osz && (*this)[t] == other[o+1]) { diff.push_back((*this)[t]); diff.push_back(other[o]); o++; } else { diff.push_back((*this)[t]); diff.push_back(other[o]); diff.push_back((*this)[t]); diff.push_back(json::undefined); o++; t++; } } else{ o++; t++; } } while (o < osz) { append.push_back(other[o]); t++; } while (t < tsz) { diff.push_back((*this)[t]); diff.push_back(json::undefined); o++; } if (!diff.empty()) { append.push_back(json::undefined); for (auto &&v : diff) { append.push_back(v); } } return Value(StringView<Value>(append)); } case object: { auto i1 = begin(), e1 = end(); auto i2 = other.begin(), e2 = other.end(); Object res; while (i1 != e1 && i2 != e2) { const Value &v1 = *i1; const Value &v2 = *i2; if (v1.getKey() < v2.getKey()) { res.unset(v1.getKey()); ++i1; } else if (v1.getKey() > v2.getKey()) { res.set(v2); ++i2; } else { if (v1.type() == json::object && v2.type() == json::object) { Value x = v1.diff(v2); if (!x.empty()) res.set(v1.getKey(),x); } else if (v1 != v2) { res.set(v2); } ++i1; ++i2; } } while (i1 != e1) { res.unset((*i1).getKey()); ++i1; } while (i2 != e2) { res.set(*i2); ++i2; } return res.commitAsDiff(); } } return undefined; } Value Value::preciseNumber(const StrViewA number) { UInt pos = 0; auto reader = [&]() -> int { if (pos > number.length) { pos++; return -1; } else { return number[pos++]; } }; typedef Parser<decltype(reader)> P; P parser(std::move(reader), P::allowPreciseNumbers); try { Value v = parser.parseNumber(); if (pos <= number.length) throw InvalidNumericFormat(number); return v; } catch (const ParseError &) { throw InvalidNumericFormat(number); } } InvalidNumericFormat::InvalidNumericFormat(std::string &&val):val(std::move(val)) {} const std::string &InvalidNumericFormat::getValue() const {return val;} const char *InvalidNumericFormat::what() const noexcept { msg = "Invalid numeric format (precise number): " + val; return msg.c_str(); } Value Value::shift() { Value ret; switch (type()) { case string: ret = String(*this).substr(0,1); (*this) = String(*this).substr(1); break; case object: case array: ret = (*this)[0]; (*this) = slice(1); break; default: ret = *this; *this = undefined; break; } return ret; } UInt Value::unshift(const Value &item) { Array newval; newval.reserve(1+item.size()); newval.push_back(item); for (Value x: *this) { newval.push_back(x); } *this = newval; return size(); } UInt Value::push(const Value &item) { Array nw(*this); nw.push_back(item); *this = nw; return size(); } Value Value::pop() { auto sz = size(); if (!sz) return undefined; Array nw(*this); Value ret = nw[sz-1]; nw.erase(sz-1); *this = nw; return ret; } String Value::join(StrViewA separator) const { Array tmp; tmp.reserve(size()); std::size_t needsz = 0; for(Value x: *this) { String s = x.toString(); tmp.push_back(s); needsz+=s.length(); } needsz+=(tmp.size()-1)*separator.length; return String(needsz, [&](char *c){ char *anchor = c; for (std::size_t i =0, cnt = tmp.size(); i < cnt; i++) { if (i) { std::copy(separator.begin(), separator.end(), c); c+=separator.length; } String v(tmp[i]); std::copy(v.begin(), v.end(), c); c+=v.length(); } return c - anchor; }); } Value Value::slice(Int start) const { return slice(start, size()); } Value Value::slice(Int start, Int end) const { Int sz = size(); if (empty()) return json::array; if (start < 0) { if (-start >= sz) return *this; return slice(sz+start); } if (end < 0) { if (-end >= sz) return json::array; return slice(start,sz+end); } if (start >= end || start >= sz) return json::array; if (end >= sz) end = sz; UInt cnt = end - start; std::vector<Value> out; out.reserve(cnt); for (Int x = start; x < end; x++) out.push_back((*this)[x]); if (type() == object) { return Value(json::object, StringView<Value>(out.data(), out.size())); } else { return Value(json::array, StringView<Value>(out.data(), out.size())); } } UInt Value::unshift(const std::initializer_list<Value> &items) { return unshift(items.begin(), items.end()); } template Value Value::find(std::function<bool(Value)> &&) const; template Value Value::rfind(std::function<bool(Value)> &&) const; template Value Value::filter(std::function<bool(Value)> &&) const; template Value Value::find(std::function<bool(Value, UInt)> &&) const; template Value Value::rfind(std::function<bool(Value, UInt)> &&) const; template Value Value::filter(std::function<bool(Value, UInt)> &&) const; template Value Value::find(std::function<bool(Value, UInt, Value)> &&) const; template Value Value::rfind(std::function<bool(Value, UInt, Value)> &&) const; template Value Value::filter(std::function<bool(Value, UInt, Value)> &&) const; String Value::getValueOrDefault(String defval) const { return type() == json::string?toString():defval; } const char *Value::getValueOrDefault(const char *defval) const { return type() == json::string?toString().c_str():defval; } void Value::setItems(const std::initializer_list<std::pair<StrViewA, Value> > &fields) { auto **buffer = static_cast<std::pair<StrViewA, Value> const **>(alloca(fields.size()*sizeof(std::pair<StrViewA, Value> *))); int i = 0; for (const auto &x: fields) buffer[i++] = &x; std::sort(buffer, buffer+fields.size(), [](const auto *a, const auto *b){return a->first < b->first;}); auto res = ObjectValue::create(fields.size()+size()); auto i1 = begin(); auto i2 = buffer; auto e1 = end(); auto e2 = buffer+fields.size(); while (i1 != e1 && i2 != e2) { Value left = *i1; const auto *right = *i2; if (left.getKey() < right->first) { res->push_back(left.v); i1++; } else if (left.getKey() > right->first) { if (right->second.defined()) { auto pv = right->second.setKey(right->first).v; res->push_back(std::move(pv)); } i2++; } else { if (right->second.defined()) { auto pv = right->second.setKey(right->first).v; res->push_back(std::move(pv)); } i1++; i2++; } } while (i1 != e1) { Value left = *i1; res->push_back(left.v); i1++; } while (i2 != e2) { const auto *right = *i2; if (right->second.defined()) { auto pv = right->second.setKey(right->first).v; res->push_back(std::move(pv)); } i2++; } v = PValue(res); } } namespace std { size_t hash<::json::Value>::operator()(const ::json::Value &v)const { size_t ret; FNV1a<sizeof(ret)> fnvcalc(ret); v.stripKey().serializeBinary(fnvcalc,0); return ret; } }
// 问题的描述:二叉树的序列化和反序列化 // 序列化:二叉树被记录成文件的过程 // 反序列化:从文件重建二叉树的过程 // 测试用例有3组: // 1、空子树 // 输入:string seq = "" // 输出为: // 前序遍历:#! // 层序遍历:#! // 2、左(右)斜子树 // 输入:string seq = "1!2!#!3!#!#!#!" // 输出为: // 前序遍历:1!2!3!#!#!#!#! // 层序遍历:1!2!#!3!#!#!#! // 3、正常二叉树 // 输入:string seq = "1!2!3!#!4!5!#!#!#!#!#!" // 输出为: // 前序遍历:1!2!#!4!#!#!3!5!#!#!#! // 层序遍历:1!2!3!#!4!5!#!#!#!#!#! #include <iostream> #include <queue> #include <string> #include <vector> using namespace std; // 树结点的定义 struct Node { int data; struct Node* lchild; struct Node* rchild; }; // 前序遍历的序列化,根据一颗二叉树生成字符串 string SerializationByPreorder(Node* root) { if (root == nullptr) return "#!"; string sequence = to_string(root->data) + '!'; sequence += SerializationByPreorder(root->lchild); sequence += SerializationByPreorder(root->rchild); return sequence; } // 前序遍历的反序列化生成一颗二叉树 Node* HelpDeserialization(queue<string> &values) { string value = values.front(); values.pop(); if (value == "#") return nullptr; Node* root = new Node(); root->data = stoi(value); root->lchild = HelpDeserialization(values); root->rchild = HelpDeserialization(values); return root; } // 前序遍历的反序列化,根据序列构建一颗二叉树 Node* DeserializationByPreorder(const string &sequence) { if (sequence.empty() || (sequence == "#!")) return nullptr; // 从sequence中提取出来每一个值,放在queue中 string temp_sequence = sequence; queue<string> values; string::size_type pos = 0; while (!temp_sequence.empty()) { pos = temp_sequence.find('!'); if (pos == string::npos) break; values.push(temp_sequence.substr(0, pos)); temp_sequence = temp_sequence.substr(pos + 1); } return HelpDeserialization(values); } // 清理前序遍历生成的二叉树结点 void FreeNodeByPreorder(Node* root) { if (root == nullptr) return; FreeNodeByPreorder(root->lchild); FreeNodeByPreorder(root->rchild); delete root; root = nullptr; } // 层序遍历的序列化,根据一颗二叉树生成字符串 string SerializationByLevel(Node* root) { if (root == nullptr) return "#!"; string sequence = to_string(root->data) + '!'; queue<Node*> q; q.push(root); Node* node = nullptr; while (!q.empty()) { node = q.front(); q.pop(); if (node->lchild != nullptr) { q.push(node->lchild); sequence = sequence + to_string(node->lchild->data) + '!'; } else { sequence += "#!"; } if (node->rchild != nullptr) { q.push(node->rchild); sequence = sequence + to_string(node->rchild->data) + '!'; } else { sequence += "#!"; } } return sequence; } // 层序遍历的反序列化,根据层序遍历序列构建一颗二叉树 // 采用vector保存结点,是为了方便后面delete掉new的结点 void DeserializationByLevel(const string &sequence, vector<Node*> &result) { if (sequence.empty() || (sequence == "#!")) return; // 从sequence中提取出来每一个值 string temp_sequence = sequence; vector<string> values; string::size_type pos = 0; while (!temp_sequence.empty()) { pos = temp_sequence.find('!'); if (pos == string::npos) break; values.push_back(temp_sequence.substr(0, pos)); temp_sequence = temp_sequence.substr(pos + 1); } Node* node = nullptr; for (int i = values.size() - 1; i >= 0; --i) { if (values[i] == "#") continue; else { node = new Node(); node->data = stoi(values[i]); if (i < values.size() / 2) { node->lchild = result[2 * i + 1]; node->rchild = result[2 * i + 2]; } else { node->lchild = nullptr; node->rchild = nullptr; } result[i] = node; } } } // 清理层序遍历生成的二叉树结点 void FreeNodeByLevel(vector<Node*> &result) { for (int i = 0; i < result.size(); ++i) { if (result[i] != nullptr) { delete result[i]; result[i] = nullptr; } } } int main() { // 基于前序遍历,测试用例1:空子树 // string seq = ""; // 基于前序遍历,测试用例2:左(右)斜子树 // string seq = "1!2!3!#!#!#!#!"; // 基于前序遍历,测试用例3:正常的二叉树 string seq = "1!2!#!4!#!#!3!5!#!#!#!"; // 基于前序遍历,根据序列生成一颗二叉树(反序列化) Node* root = DeserializationByPreorder(seq); // 基于前序遍历,根据二叉树生成序列(序列化) string preorder_result = SerializationByPreorder(root); cout << preorder_result << endl; FreeNodeByPreorder(root); /* // 基于层序遍历,测试用例1:空子树 // string seq = ""; // 基于层序遍历,测试用例2:左(右)斜子树 // string seq = "1!2!#!3!#!#!#!"; // 基于层序遍历,测试用例3:正常的二叉树 string seq = "1!2!3!#!4!5!#!#!#!#!#!"; // 基于层序遍历,根据序列生成一颗二叉树(反序列化) vector<Node*> result(seq.size() / 2, nullptr); DeserializationByLevel(seq, result); Node* root = nullptr; if (!seq.empty()) root = result[0]; // 基于层序遍历,根据二叉树生成序列(序列化) string level_result = SerializationByLevel(root); cout << level_result << endl; FreeNodeByLevel(result); */ system("pause"); return 0; }
// Copyright (c) 2020 The Orbit Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef ORBIT_LINUX_TRACING_FUNCTION_H_ #define ORBIT_LINUX_TRACING_FUNCTION_H_ #include <cstdint> #include <string> namespace LinuxTracing { class Function { public: Function(std::string binary_path, uint64_t file_offset, uint64_t virtual_address) : binary_path_{std::move(binary_path)}, file_offset_{file_offset}, virtual_address_{virtual_address} {} const std::string& BinaryPath() const { return binary_path_; } uint64_t FileOffset() const { return file_offset_; } uint64_t VirtualAddress() const { return virtual_address_; } private: std::string binary_path_; uint64_t file_offset_; uint64_t virtual_address_; }; } // namespace LinuxTracing #endif // ORBIT_LINUX_TRACING_FUNCTION_H_
// I will test your BinTree class using either this main or // a very similar one, and this buildTree. // You will want to do thorough testing on your own, // which is done by altering the data. // Windows and unix store files slightly differently. Windows does not // always store an end-of-line char on the last line, where unix does. // On windows, always make sure the cursor is on the line after // the last line of data. // presumably bintree.h includes nodedata.h so the include is not needed here #include "bintree.h" #include <fstream> #include <iostream> using namespace std; const int ARRAYSIZE = 100; //global function prototypes void buildTree(BinTree&, ifstream&); void initArray(NodeData* []); int main() { // create file object infile and open it // for testing, call your data file something appropriate, e.g., data2.txt ifstream infile("data2.txt"); if (!infile) { cerr << "File could not be opened." << endl; return 1; } // the NodeData class must have a constructor that takes a string NodeData notND("not"); NodeData andND("and"); NodeData sssND("sss"); NodeData eND("e"); NodeData mND("m"); NodeData tND("t"); BinTree T, T2, dup; NodeData* ndArray[ARRAYSIZE]; initArray(ndArray); cout << "Initial data:" << endl << " "; buildTree(T, infile); // builds and displays initial data cout << endl; BinTree first(T); // test copy constructor dup = dup = T; // test operator=, self-assignment while(!infile.eof()) { cout << "Tree Inorder:" << endl << T; // operator<< does endl T.displaySideways(); // test retrieve NodeData* p; // pointer of retrieved object bool found; // whether or not object was found in tree found = T.retrieve(andND, p); cout << "Retrieve --> and: " << (found ? "found":"not found") << endl; found = T.retrieve(notND, p); cout << "Retrieve --> not: " << (found ? "found":"not found") << endl; found = T.retrieve(sssND, p); cout << "Retrieve --> sss: " << (found ? "found":"not found") << endl; // test getDepth cout << "Depth --> and: " << T.getDepth(andND) << endl; cout << "Depth --> not: " << T.getDepth(notND) << endl; cout << "Depth --> sss: " << T.getDepth(sssND) << endl; // test ==, and != T2 = T; cout << "T == T2? " << (T == T2 ? "equal" : "not equal") << endl; cout << "T != first? " << (T != first ? "not equal" : "equal") << endl; cout << "T == dup? " << (T == dup ? "equal" : "not equal") << endl; dup = T; // somewhat test bstreeToArray and arrayToBSTree T.bstreeToArray(ndArray); T.arrayToBSTree(ndArray); T.displaySideways(); T.makeEmpty(); // empty out the tree initArray(ndArray); // empty out the array cout << "---------------------------------------------------------------" << endl; cout << "Initial data:" << endl << " "; buildTree(T, infile); cout << endl; } return 0; } //------------------------------- buildTree ---------------------------------- // you comment // To build a tree, read strings from a line, terminating when "$$" is // encountered. Since there is some work to do before the actual insert that is // specific to the client problem, it's best that building a tree is not a // member function. It's a global function. void buildTree(BinTree& T, ifstream& infile) { string s; for (;;) { infile >> s; cout << s << ' '; if (s == "$$") break; // at end of one line if (infile.eof()) break; // no more lines of data NodeData* ptr = new NodeData(s); // NodeData constructor takes string // would do a setData if there were more than a string bool success = T.insert(ptr); if (!success) delete ptr; // duplicate case, not inserted } } //------------------------------- initArray ---------------------------------- // initialize the array of NodeData* to NULL pointers void initArray(NodeData* ndArray[]) { for(int i = 0; i < ARRAYSIZE; i++) ndArray[i] = NULL; }
#include <iostream> class Base { public: ~Base() { std::cout << __PRETTY_FUNCTION__ << std::endl; } void func() {} }; class Child : public Base { public: ~Child() { std::cout << __PRETTY_FUNCTION__ << std::endl; } void func() {} }; class BaseV { public: virtual ~BaseV() { std::cout << __PRETTY_FUNCTION__ << std::endl; } }; class ChildV : public BaseV { public: virtual ~ChildV() { std::cout << __PRETTY_FUNCTION__ << std::endl; } }; void test0() { Child child; ChildV childv; auto childvptr = std::unique_ptr<BaseV>(new ChildV); } int main() { test0(); return 0; }
#ifndef __CellCoord_h__ #define __CellCoord_h__ #include <math.h> class Cell; #include "Cell.h" #include "Wall.h" #include "glPoint.h" class CellCoord { public: int x, y, z; CellCoord(int a=0, int b=0, int c=0) { x = a, y = b, z = c; }; inline boolean operator ==(CellCoord &nc) { return (x == nc.x && y == nc.y && z == nc.z); } bool isCellPassage(void); bool isCellPassageSafe(void); void setCellState(Cell::CellState v); Cell::CellState getCellState(); void init(glPoint &p); // distance squared (euclidean) inline int dist2(int i, int j, int k) { return (x - i)*(x - i) + (y - j)*(y - j) + (z - k)*(z - k); } // manhattan distance inline int manhdist(CellCoord &nc) { return abs(x - nc.x) + abs(y - nc.y) + abs(z - nc.z); } /* Return true iff this cell is a legal place to expand into from fromCC. Assumes both are within bounds of maze grid, that they differ in only one axis and by only one unit, that fromCC is already passage, and that this cell is uninitialized. Checks whether this cell is too close to other passages, violating sparsity. */ bool isCellPassable(CellCoord *fromCC); /* Find walls[] array element of wall between this and nc. * Assumes cell coordinates of this and nc differ in only one axis and by at most one unit. * Also assumes the higher of all coord pairs is within bounds 0 <= coord <= w/h/d * (i.e. one extra on the top is ok). E.g. if coords differ in x, then the higher of x and nc->x * must be 0 <= x <= w. */ Wall *findWallTo(CellCoord *nc); /* Set wall between this and nc to given state. * See assumptions of findWallTo(). * Also assumes this is "inside" and nc is "outside", if it matters (this assumption can be incorrect if sparseness <= 1). */ void setStateOfWallTo(CellCoord *nc, Wall::WallState state); /* Set wall of this cell in direction dx,dy,dz to given state. * See assumptions of findWallTo(). * Also assumes this is "inside" and cell in dx,dy,dz is "outside", if it matters (this assumption can be incorrect if sparseness <= 1). */ void setStateOfWallTo(int dx, int dy, int dz, Wall::WallState state); // If the wall in direction dx,dy,dz is closed, open it and return wall. // Else return null. inline Wall *tryOpenWall(int dx, int dy, int dz); /* Open a wall of this cell that is not already open. Prefer vertical walls. */ // Return chosen wall. // ## To do: don't assert Wall *openAWall(); /* Set the camera on the other side of wall w from this cc, facing this cc. */ void standOutside(Wall *w); #if 1 /* Get state of wall between this and nc. * See assumptions of findWallTo(). */ inline Wall::WallState CellCoord::getStateOfWallTo(CellCoord *nc) { Wall *w = findWallTo(nc); return w->state; } /* Get wall of this cell in direction dx,dy,dz. * See assumptions of findWallTo(). */ inline Wall::WallState CellCoord::getStateOfWallTo(int dx, int dy, int dz) { static CellCoord nc; nc.x = x+dx; nc.y = y+dy; nc.z = z+dz; return getStateOfWallTo(&nc); } #else // 0 /* Get state of wall between this and nc. * See assumptions of findWallTo(). */ Wall::WallState getStateOfWallTo(CellCoord *nc); /* Get wall of this cell in direction dx,dy,dz. * See assumptions of findWallTo(). */ inline Wall::WallState getStateOfWallTo(int dx, int dy, int dz); #endif /* Get state of wall between this and nc. * Checks boundaries: does not assume coords are in range. */ Wall::WallState getStateOfWallToSafe(CellCoord *nc); // Convenience function for Wall::drawExit() inline void drawExit(Wall *w, bool isEntrance) { w->drawExit(x, y, z, isEntrance); } /* Randomly shuffle the order of CellCoords in an array. * Ref: http://en.wikipedia.org/wiki/Fisher-Yates_shuffle#The_modern_algorithm */ static void shuffleCCs(CellCoord *ccs, int n); // Find out whether this cell has only one "open" neighbor (i.e. that is passage and has isOnSolutionRoute = true). // If so, populate position of neighbor and return true. bool getSoleOpenNeighbor(CellCoord &neighbor); // Return true if this cc's coords are inside the maze bounds. bool isInBounds(void); // Return true if cc is adjacent to this. bool isNextTo(CellCoord &cc); // Set coordinates to random value within bounding box of maze. void placeRandomly(void); private: // Check whether neighbor cell at this + (dx, dy, dz) is open // (i.e. that is passage and has isOnSolutionRoute = true). // If so, put neighbor cell's coords into neighbor and return true. bool checkNeighborOpen(int dx, int dy, int dz, CellCoord &neighbor); }; extern CellCoord ccExit, ccEntrance; #endif // __CellCoord_h__
#include <cstdio> #include <iostream> using namespace std; int singleNumber2(int A[],int n){ int digit[32] = {0}; int res = 0; for(int i=0; i<32;i++){ for(int j=0;j<n;j++){ digit[i] += (A[j]>>i)&1; //AND in digit i } res |= (digit[i]%3)<<i; // OR in digit i } return res; } int main(){ int a[11] = {1,2,3,1,2,3,5,5,1,2,3}; int res = singleNumber2(a,11); cout << res <<endl; }
#ifndef SD_STREAM_H #define SD_STREAM_H #include <SdStream.h> #include <IPAddress.h> class MacAddress { public: MacAddress() { memset( b, 0, sizeof( b )); } MacAddress( uint8_t b1, uint8_t b2, uint8_t b3, uint8_t b4, uint8_t b5, uint8_t b6 ) { b[0] = b1; b[1] = b2; b[2] = b3; b[3] = b4; b[4] = b5; b[5] = b6; } MacAddress& operator = ( const uint8_t * by ) { memcpy( b, by, sizeof( b )); return *this; } uint8_t operator[](int index) const { return b[index]; }; uint8_t& operator[](int index) { return b[index]; }; byte b[6]; }; class SdStream : public ifstream { public: SdStream() {} SdStream( const char* path, char* buf, uint16_t sbuf, openmode mode = in ) { readBuf = buf; sizeReadBuf = sbuf; open( path, mode ); } uint16_t getInt(); IPAddress getIp(); MacAddress getMac(); private: uint16_t readInt( char ** ps ); uint8_t readHex( char ** ps ); char * readBuf; uint16_t sizeReadBuf; }; #endif // SD_STREAM_H
#include "mapwindow.h" #include "ui_mapwindow.h" mapWindow::mapWindow(QString dsn, QString db, const QStringList &fields, const QSqlQueryModel *mod, QWidget *parent) : QMainWindow(parent), ui(new Ui::mapWindow) { ui->setupUi(this); //set this window to modal this->setWindowModality(Qt::ApplicationModal); //connect signals and slots connect(ui->exportButton, SIGNAL(pressed()), this, SLOT(exportCSV())); connect(ui->cancelButton, SIGNAL(pressed()), this, SLOT(cancel())); connect(ui->actionCancel, SIGNAL(triggered()), this, SLOT(cancel())); connect(ui->actionSave_Map, SIGNAL(triggered()), this, SLOT(saveMap())); connect(ui->actionSave_Map_As, SIGNAL(triggered()), this, SLOT(saveMapAS())); connect(ui->actionOpen_Map, SIGNAL(triggered()), this, SLOT(openMap())); connect(ui->listWidget_3, SIGNAL(itemClicked(QListWidgetItem*)), this, SLOT(toggleMapBool(QListWidgetItem*))); //init mapFilePath = ""; //copy in original field list and data model ogFields = fields; model = mod; //render orig fields setOGfields(); //render new fields to og names as default setNewFields(ogFields); //render default true map bools QStringList mapBools; setMapBools(mapBools); //store validators currentDSN = dsn; currentDBname = db; } mapWindow::~mapWindow() { delete ui; } void mapWindow::cancel() { this->close(); } void mapWindow::exportCSV() { //get path to save CSV QString csvFilePath = QFileDialog::getSaveFileName(this, tr("Save Data CSV"), "./report", tr("CSV Files (*.csv)")); //store column and row counts int rowCount = model->rowCount(); int colCount = model->columnCount(); //open path to write QFile csvFile(csvFilePath); //write over any existing data if(csvFile.open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Truncate)) { QTextStream in(&csvFile); QString field = ""; QStringList newNames = getNewFields(); QStringList mapBools = getMapBools(); //determine qty fields for export int qtyBools = 0; for(int k = 0; k < mapBools.size(); k++) { if(mapBools.at(k).contains("yes")) qtyBools++; } //counter for exported fields int countBools = 0; //write with newly mapped field names for(int j = 0; j < newNames.size(); j++) { if(mapBools.at(j).contains("yes")) { if(countBools == (qtyBools - 1)) in << "\"" << newNames.at(j) << "\"" << '\n'; else in << "\"" << newNames.at(j) << "\"" << ","; countBools++; } } //for each record for(int i = 0; i < rowCount; i++) { //reset bool counter countBools = 0; //write each field, comma separated for(int j = 0; j < colCount; j++) { if(mapBools.at(j).contains("yes")) { QModelIndex index = model->index(i,j); field = model->data(index).toString(); if(countBools == (qtyBools - 1)) in << "\"" << field << "\"" << '\n'; else in << "\"" << field << "\"" << ","; countBools++; } } } csvFile.flush(); csvFile.close(); } else int ret = QMessageBox::warning(this, tr("Export Data"), tr("Failure: Cannot Save File"), QMessageBox::Cancel); } void mapWindow::saveMap() { if(mapFilePath.isEmpty()) mapFilePath = QFileDialog::getSaveFileName(this, tr("Save Field Map"), "./fieldMap", tr("CSV Files (*.csv)")); exportFieldMap(); } void mapWindow::saveMapAS() { mapFilePath = QFileDialog::getSaveFileName(this, tr("Save Field Map"), "./fieldMap", tr("CSV Files (*.csv)")); exportFieldMap(); } void mapWindow::openMap() { mapFilePath = QFileDialog::getOpenFileName(this, tr("Open Field Map"), "./fieldMap", tr("CSV Files (*.csv)")); QFile mapFile(mapFilePath); QStringList newNames, mapBools, validators; if(mapFile.open(QIODevice::ReadOnly | QIODevice::Text)) { QTextStream out(&mapFile); QString line = out.readLine(); validators = line.split(","); if(validators.at(0).contains(currentDSN) && validators.at(1).contains(currentDBname)) { line = out.readLine(); mapBools = line.split(","); setMapBools(mapBools); line = out.readLine(); ogFields = line.split(","); setOGfields(); line = out.readLine(); newNames = line.split(","); setNewFields(newNames); } else int ret = QMessageBox::warning(this, tr("Open Field Map"), tr("Failure: Incorrect DSN/Database Name"), QMessageBox::Cancel); mapFile.close(); } else { int ret = QMessageBox::warning(this, tr("Open Field Map"), tr("Failure: Cannot Open File"), QMessageBox::Cancel); } } void mapWindow::exportFieldMap() { QFile mapFile(mapFilePath); QStringList newNames = getNewFields(); QStringList mapBools = getMapBools(); if(mapFile.open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Truncate)) { QTextStream in(&mapFile); in << currentDSN << "," << currentDBname << '\n'; for(int h = 0; h < mapBools.size(); h++) { if(h == (mapBools.size() - 1)) { if(mapBools.at(h).contains("yes")) { in << "yes" << '\n'; } else { in << "no" << '\n'; } } else { if(mapBools.at(h).contains("yes")) { in << "yes" << ","; } else { in << "no" << ","; } } } for(int i = 0; i < ogFields.size(); i++) { if(i == (ogFields.size() - 1)) in << ogFields.at(i) << '\n'; else in << ogFields.at(i) << ","; } for(int j = 0; j < newNames.size(); j++) { if(j == (newNames.size() - 1)) in << newNames.at(j) << '\n'; else in << newNames.at(j) << ","; } mapFile.flush(); mapFile.close(); } else { int ret = QMessageBox::warning(this, tr("Save Field Map"), tr("Failure: Cannot Save File"), QMessageBox::Cancel); } } QStringList mapWindow::getNewFields() { QStringList newFields; for(int i = 0; i < ui->listWidgetCSV->count(); i++) { newFields.append(ui->listWidgetCSV->item(i)->text()); } return newFields; } void mapWindow::setOGfields() { //clear data ui->listWidgetSQL->clear(); //render orig fields ui->listWidgetSQL->addItems(ogFields); //set og fields alignment to right justification for(int i = 0; i < ui->listWidgetSQL->count(); i++) { ui->listWidgetSQL->item(i)->setTextAlignment(Qt::AlignRight); } } void mapWindow::setNewFields(QStringList l) { //clear data ui->listWidgetCSV->clear(); //render new fields to og names as default ui->listWidgetCSV->addItems(l); //set new fields alignment to right justification for(int i = 0; i < ui->listWidgetCSV->count(); i++) { ui->listWidgetCSV->item(i)->setTextAlignment(Qt::AlignLeft); ui->listWidgetCSV->item(i)->setFlags(ui->listWidgetCSV->item(i)->flags() | Qt::ItemIsEditable); } } void mapWindow::setMapBools(QStringList l) { //clear data ui->listWidget_3->clear(); //set and render each field bool if(!l.isEmpty()) { for(int x = 0; x < l.size(); x++) { if(l.at(x).contains("yes")) { ui->listWidget_3->addItem("-->"); } else ui->listWidget_3->addItem(" X "); ui->listWidget_3->item(x)->setTextAlignment(Qt::AlignCenter); } } else { for(int i = 0; i < ogFields.size(); i++) { ui->listWidget_3->addItem("-->"); ui->listWidget_3->item(i)->setTextAlignment(Qt::AlignCenter); } } } void mapWindow::toggleMapBool(QListWidgetItem *item) { QString currentState = item->text(); if(currentState.contains("-->")) { item->setText(" X "); } else { item->setText("-->"); } } QStringList mapWindow::getMapBools() { QStringList mapBools; for(int i = 0; i < ui->listWidget_3->count(); i++) { if(ui->listWidget_3->item(i)->text().contains("X")) mapBools.append("no"); else mapBools.append("yes"); } return mapBools; }
// This file is part of Eigen, a lightweight C++ template library // for linear algebra. // // Copyright (C) 2008-2009 Gael Guennebaud <gael.guennebaud@inria.fr> // // Eigen is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 3 of the License, or (at your option) any later version. // // Alternatively, you can redistribute it and/or // modify it under the terms of the GNU General Public License as // published by the Free Software Foundation; either version 2 of // the License, or (at your option) any later version. // // Eigen is distributed in the hope that it will be useful, but WITHOUT ANY // WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS // FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License and a copy of the GNU General Public License along with // Eigen. If not, see <http://www.gnu.org/licenses/>. #ifndef EIGEN_SVD_H #define EIGEN_SVD_H template<typename MatrixType, typename Rhs> struct ei_svd_solve_impl; /** \ingroup SVD_Module * * * \class SVD * * \brief Standard SVD decomposition of a matrix and associated features * * \param MatrixType the type of the matrix of which we are computing the SVD decomposition * * This class performs a standard SVD decomposition of a real matrix A of size \c M x \c N. * * \sa MatrixBase::SVD() */ template<typename _MatrixType> class SVD { public: typedef _MatrixType MatrixType; typedef typename MatrixType::Scalar Scalar; typedef typename NumTraits<typename MatrixType::Scalar>::Real RealScalar; typedef typename MatrixType::Index Index; enum { RowsAtCompileTime = MatrixType::RowsAtCompileTime, ColsAtCompileTime = MatrixType::ColsAtCompileTime, PacketSize = ei_packet_traits<Scalar>::size, AlignmentMask = int(PacketSize)-1, MinSize = EIGEN_SIZE_MIN_PREFER_DYNAMIC(RowsAtCompileTime, ColsAtCompileTime), MaxRowsAtCompileTime = MatrixType::MaxRowsAtCompileTime, MaxColsAtCompileTime = MatrixType::MaxColsAtCompileTime, MatrixOptions = MatrixType::Options }; typedef typename ei_plain_col_type<MatrixType>::type ColVector; typedef typename ei_plain_row_type<MatrixType>::type RowVector; typedef Matrix<Scalar, RowsAtCompileTime, RowsAtCompileTime, MatrixOptions, MaxRowsAtCompileTime, MaxRowsAtCompileTime> MatrixUType; typedef Matrix<Scalar, ColsAtCompileTime, ColsAtCompileTime, MatrixOptions, MaxColsAtCompileTime, MaxColsAtCompileTime> MatrixVType; typedef ColVector SingularValuesType; /** * \brief Default Constructor. * * The default constructor is useful in cases in which the user intends to * perform decompositions via SVD::compute(const MatrixType&). */ SVD() : m_matU(), m_matV(), m_sigma(), m_isInitialized(false) {} /** \brief Default Constructor with memory preallocation * * Like the default constructor but with preallocation of the internal data * according to the specified problem \a size. * \sa JacobiSVD() */ SVD(Index rows, Index cols) : m_matU(rows, rows), m_matV(cols,cols), m_sigma(std::min(rows, cols)), m_workMatrix(rows, cols), m_rv1(cols), m_isInitialized(false) {} SVD(const MatrixType& matrix) : m_matU(matrix.rows(), matrix.rows()), m_matV(matrix.cols(),matrix.cols()), m_sigma(std::min(matrix.rows(), matrix.cols())), m_workMatrix(matrix.rows(), matrix.cols()), m_rv1(matrix.cols()), m_isInitialized(false) { compute(matrix); } /** \returns a solution of \f$ A x = b \f$ using the current SVD decomposition of A. * * \param b the right-hand-side of the equation to solve. * * \note_about_checking_solutions * * \note_about_arbitrary_choice_of_solution * * \sa MatrixBase::svd(), */ template<typename Rhs> inline const ei_solve_retval<SVD, Rhs> solve(const MatrixBase<Rhs>& b) const { ei_assert(m_isInitialized && "SVD is not initialized."); return ei_solve_retval<SVD, Rhs>(*this, b.derived()); } const MatrixUType& matrixU() const { ei_assert(m_isInitialized && "SVD is not initialized."); return m_matU; } const SingularValuesType& singularValues() const { ei_assert(m_isInitialized && "SVD is not initialized."); return m_sigma; } const MatrixVType& matrixV() const { ei_assert(m_isInitialized && "SVD is not initialized."); return m_matV; } SVD& compute(const MatrixType& matrix); template<typename UnitaryType, typename PositiveType> void computeUnitaryPositive(UnitaryType *unitary, PositiveType *positive) const; template<typename PositiveType, typename UnitaryType> void computePositiveUnitary(PositiveType *positive, UnitaryType *unitary) const; template<typename RotationType, typename ScalingType> void computeRotationScaling(RotationType *unitary, ScalingType *positive) const; template<typename ScalingType, typename RotationType> void computeScalingRotation(ScalingType *positive, RotationType *unitary) const; inline Index rows() const { ei_assert(m_isInitialized && "SVD is not initialized."); return m_rows; } inline Index cols() const { ei_assert(m_isInitialized && "SVD is not initialized."); return m_cols; } protected: // Computes (a^2 + b^2)^(1/2) without destructive underflow or overflow. inline static Scalar pythag(Scalar a, Scalar b) { Scalar abs_a = ei_abs(a); Scalar abs_b = ei_abs(b); if (abs_a > abs_b) return abs_a*ei_sqrt(Scalar(1.0)+ei_abs2(abs_b/abs_a)); else return (abs_b == Scalar(0.0) ? Scalar(0.0) : abs_b*ei_sqrt(Scalar(1.0)+ei_abs2(abs_a/abs_b))); } inline static Scalar sign(Scalar a, Scalar b) { return (b >= Scalar(0.0) ? ei_abs(a) : -ei_abs(a)); } protected: /** \internal */ MatrixUType m_matU; /** \internal */ MatrixVType m_matV; /** \internal */ SingularValuesType m_sigma; MatrixType m_workMatrix; RowVector m_rv1; bool m_isInitialized; Index m_rows, m_cols; }; /** Computes / recomputes the SVD decomposition A = U S V^* of \a matrix * * \note this code has been adapted from Numerical Recipes, third edition. * * \returns a reference to *this */ template<typename MatrixType> SVD<MatrixType>& SVD<MatrixType>::compute(const MatrixType& matrix) { const Index m = m_rows = matrix.rows(); const Index n = m_cols = matrix.cols(); m_matU.resize(m, m); m_matU.setZero(); m_sigma.resize(n); m_matV.resize(n,n); m_workMatrix = matrix; Index max_iters = 30; MatrixVType& V = m_matV; MatrixType& A = m_workMatrix; SingularValuesType& W = m_sigma; bool flag; Index i=0,its=0,j=0,k=0,l=0,nm=0; Scalar anorm, c, f, g, h, s, scale, x, y, z; bool convergence = true; Scalar eps = NumTraits<Scalar>::dummy_precision(); m_rv1.resize(n); g = scale = anorm = 0; // Householder reduction to bidiagonal form. for (i=0; i<n; i++) { l = i+2; m_rv1[i] = scale*g; g = s = scale = 0.0; if (i < m) { scale = A.col(i).tail(m-i).cwiseAbs().sum(); if (scale != Scalar(0)) { for (k=i; k<m; k++) { A(k, i) /= scale; s += A(k, i)*A(k, i); } f = A(i, i); g = -sign( ei_sqrt(s), f ); h = f*g - s; A(i, i)=f-g; for (j=l-1; j<n; j++) { s = A.col(j).tail(m-i).dot(A.col(i).tail(m-i)); f = s/h; A.col(j).tail(m-i) += f*A.col(i).tail(m-i); } A.col(i).tail(m-i) *= scale; } } W[i] = scale * g; g = s = scale = 0.0; if (i+1 <= m && i+1 != n) { scale = A.row(i).tail(n-l+1).cwiseAbs().sum(); if (scale != Scalar(0)) { for (k=l-1; k<n; k++) { A(i, k) /= scale; s += A(i, k)*A(i, k); } f = A(i,l-1); g = -sign(ei_sqrt(s),f); h = f*g - s; A(i,l-1) = f-g; m_rv1.tail(n-l+1) = A.row(i).tail(n-l+1)/h; for (j=l-1; j<m; j++) { s = A.row(i).tail(n-l+1).dot(A.row(j).tail(n-l+1)); A.row(j).tail(n-l+1) += s*m_rv1.tail(n-l+1).transpose(); } A.row(i).tail(n-l+1) *= scale; } } anorm = std::max( anorm, (ei_abs(W[i])+ei_abs(m_rv1[i])) ); } // Accumulation of right-hand transformations. for (i=n-1; i>=0; i--) { //Accumulation of right-hand transformations. if (i < n-1) { if (g != Scalar(0.0)) { for (j=l; j<n; j++) //Double division to avoid possible underflow. V(j, i) = (A(i, j)/A(i, l))/g; for (j=l; j<n; j++) { s = V.col(j).tail(n-l).dot(A.row(i).tail(n-l)); V.col(j).tail(n-l) += s * V.col(i).tail(n-l); } } V.row(i).tail(n-l).setZero(); V.col(i).tail(n-l).setZero(); } V(i, i) = 1.0; g = m_rv1[i]; l = i; } // Accumulation of left-hand transformations. for (i=std::min(m,n)-1; i>=0; i--) { l = i+1; g = W[i]; if (n-l>0) A.row(i).tail(n-l).setZero(); if (g != Scalar(0.0)) { g = Scalar(1.0)/g; if (m-l) { for (j=l; j<n; j++) { s = A.col(j).tail(m-l).dot(A.col(i).tail(m-l)); f = (s/A(i,i))*g; A.col(j).tail(m-i) += f * A.col(i).tail(m-i); } } A.col(i).tail(m-i) *= g; } else A.col(i).tail(m-i).setZero(); ++A(i,i); } // Diagonalization of the bidiagonal form: Loop over // singular values, and over allowed iterations. for (k=n-1; k>=0; k--) { for (its=0; its<max_iters; its++) { flag = true; for (l=k; l>=0; l--) { // Test for splitting. nm = l-1; // Note that rv1[1] is always zero. //if ((double)(ei_abs(rv1[l])+anorm) == anorm) if (l==0 || ei_abs(m_rv1[l]) <= eps*anorm) { flag = false; break; } //if ((double)(ei_abs(W[nm])+anorm) == anorm) if (ei_abs(W[nm]) <= eps*anorm) break; } if (flag) { c = 0.0; //Cancellation of rv1[l], if l > 0. s = 1.0; for (i=l ;i<k+1; i++) { f = s*m_rv1[i]; m_rv1[i] = c*m_rv1[i]; //if ((double)(ei_abs(f)+anorm) == anorm) if (ei_abs(f) <= eps*anorm) break; g = W[i]; h = pythag(f,g); W[i] = h; h = Scalar(1.0)/h; c = g*h; s = -f*h; V.applyOnTheRight(i,nm,PlanarRotation<Scalar>(c,s)); } } z = W[k]; if (l == k) //Convergence. { if (z < 0.0) { // Singular value is made nonnegative. W[k] = -z; V.col(k) = -V.col(k); } break; } if (its+1 == max_iters) { convergence = false; } x = W[l]; // Shift from bottom 2-by-2 minor. nm = k-1; y = W[nm]; g = m_rv1[nm]; h = m_rv1[k]; f = ((y-z)*(y+z) + (g-h)*(g+h))/(Scalar(2.0)*h*y); g = pythag(f,1.0); f = ((x-z)*(x+z) + h*((y/(f+sign(g,f)))-h))/x; c = s = 1.0; //Next QR transformation: for (j=l; j<=nm; j++) { i = j+1; g = m_rv1[i]; y = W[i]; h = s*g; g = c*g; z = pythag(f,h); m_rv1[j] = z; c = f/z; s = h/z; f = x*c + g*s; g = g*c - x*s; h = y*s; y *= c; V.applyOnTheRight(i,j,PlanarRotation<Scalar>(c,s)); z = pythag(f,h); W[j] = z; // Rotation can be arbitrary if z = 0. if (z!=Scalar(0)) { z = Scalar(1.0)/z; c = f*z; s = h*z; } f = c*g + s*y; x = c*y - s*g; A.applyOnTheRight(i,j,PlanarRotation<Scalar>(c,s)); } m_rv1[l] = 0.0; m_rv1[k] = f; W[k] = x; } } // sort the singular values: { for (Index i=0; i<n; i++) { Index k; W.tail(n-i).maxCoeff(&k); if (k != 0) { k += i; std::swap(W[k],W[i]); A.col(i).swap(A.col(k)); V.col(i).swap(V.col(k)); } } } m_matU.setZero(); if (m>=n) m_matU.block(0,0,m,n) = A; else m_matU = A.block(0,0,m,m); m_isInitialized = true; return *this; } template<typename _MatrixType, typename Rhs> struct ei_solve_retval<SVD<_MatrixType>, Rhs> : ei_solve_retval_base<SVD<_MatrixType>, Rhs> { EIGEN_MAKE_SOLVE_HELPERS(SVD<_MatrixType>,Rhs) template<typename Dest> void evalTo(Dest& dst) const { ei_assert(rhs().rows() == dec().rows()); for (Index j=0; j<cols(); ++j) { Matrix<Scalar,MatrixType::RowsAtCompileTime,1> aux = dec().matrixU().adjoint() * rhs().col(j); for (Index i = 0; i < dec().rows(); ++i) { Scalar si = dec().singularValues().coeff(i); if(si == RealScalar(0)) aux.coeffRef(i) = Scalar(0); else aux.coeffRef(i) /= si; } const Index minsize = std::min(dec().rows(),dec().cols()); dst.col(j).head(minsize) = aux.head(minsize); if(dec().cols()>dec().rows()) dst.col(j).tail(cols()-minsize).setZero(); dst.col(j) = dec().matrixV() * dst.col(j); } } }; /** Computes the polar decomposition of the matrix, as a product unitary x positive. * * If either pointer is zero, the corresponding computation is skipped. * * Only for square matrices. * * \sa computePositiveUnitary(), computeRotationScaling() */ template<typename MatrixType> template<typename UnitaryType, typename PositiveType> void SVD<MatrixType>::computeUnitaryPositive(UnitaryType *unitary, PositiveType *positive) const { ei_assert(m_isInitialized && "SVD is not initialized."); ei_assert(m_matU.cols() == m_matV.cols() && "Polar decomposition is only for square matrices"); if(unitary) *unitary = m_matU * m_matV.adjoint(); if(positive) *positive = m_matV * m_sigma.asDiagonal() * m_matV.adjoint(); } /** Computes the polar decomposition of the matrix, as a product positive x unitary. * * If either pointer is zero, the corresponding computation is skipped. * * Only for square matrices. * * \sa computeUnitaryPositive(), computeRotationScaling() */ template<typename MatrixType> template<typename UnitaryType, typename PositiveType> void SVD<MatrixType>::computePositiveUnitary(UnitaryType *positive, PositiveType *unitary) const { ei_assert(m_isInitialized && "SVD is not initialized."); ei_assert(m_matU.rows() == m_matV.rows() && "Polar decomposition is only for square matrices"); if(unitary) *unitary = m_matU * m_matV.adjoint(); if(positive) *positive = m_matU * m_sigma.asDiagonal() * m_matU.adjoint(); } /** decomposes the matrix as a product rotation x scaling, the scaling being * not necessarily positive. * * If either pointer is zero, the corresponding computation is skipped. * * This method requires the Geometry module. * * \sa computeScalingRotation(), computeUnitaryPositive() */ template<typename MatrixType> template<typename RotationType, typename ScalingType> void SVD<MatrixType>::computeRotationScaling(RotationType *rotation, ScalingType *scaling) const { ei_assert(m_isInitialized && "SVD is not initialized."); ei_assert(m_matU.rows() == m_matV.rows() && "Polar decomposition is only for square matrices"); Scalar x = (m_matU * m_matV.adjoint()).determinant(); // so x has absolute value 1 Matrix<Scalar, MatrixType::RowsAtCompileTime, 1> sv(m_sigma); sv.coeffRef(0) *= x; if(scaling) scaling->lazyAssign(m_matV * sv.asDiagonal() * m_matV.adjoint()); if(rotation) { MatrixType m(m_matU); m.col(0) /= x; rotation->lazyAssign(m * m_matV.adjoint()); } } /** decomposes the matrix as a product scaling x rotation, the scaling being * not necessarily positive. * * If either pointer is zero, the corresponding computation is skipped. * * This method requires the Geometry module. * * \sa computeRotationScaling(), computeUnitaryPositive() */ template<typename MatrixType> template<typename ScalingType, typename RotationType> void SVD<MatrixType>::computeScalingRotation(ScalingType *scaling, RotationType *rotation) const { ei_assert(m_isInitialized && "SVD is not initialized."); ei_assert(m_matU.rows() == m_matV.rows() && "Polar decomposition is only for square matrices"); Scalar x = (m_matU * m_matV.adjoint()).determinant(); // so x has absolute value 1 Matrix<Scalar, MatrixType::RowsAtCompileTime, 1> sv(m_sigma); sv.coeffRef(0) *= x; if(scaling) scaling->lazyAssign(m_matU * sv.asDiagonal() * m_matU.adjoint()); if(rotation) { MatrixType m(m_matU); m.col(0) /= x; rotation->lazyAssign(m * m_matV.adjoint()); } } /** \svd_module * \returns the SVD decomposition of \c *this */ template<typename Derived> inline SVD<typename MatrixBase<Derived>::PlainObject> MatrixBase<Derived>::svd() const { return SVD<PlainObject>(derived()); } #endif // EIGEN_SVD_H
#ifndef OINEUS_OINEUS_PERSISTENCE_BINDINGS_H #define OINEUS_OINEUS_PERSISTENCE_BINDINGS_H #include <iostream> #include <vector> #include <sstream> #include <variant> #include <functional> #include <pybind11/pybind11.h> #include <pybind11/stl.h> #include <pybind11/numpy.h> namespace py = pybind11; #include <oineus/timer.h> #include <oineus/oineus.h> namespace oin = oineus; using dim_type = oin::dim_type; template<class Real> class PyOineusDiagrams { public: PyOineusDiagrams() = default; PyOineusDiagrams(const oin::Diagrams<Real>& _diagrams) :diagrams_(_diagrams) { } PyOineusDiagrams(oin::Diagrams<Real>&& _diagrams) :diagrams_(_diagrams) { } py::array_t<Real> diagram_to_numpy(const typename oin::Diagrams<Real>::Dgm& dgm) const { size_t arr_sz = dgm.size() * 2; Real* ptr = new Real[arr_sz]; for(size_t i = 0 ; i < dgm.size() ; ++i) { ptr[2 * i] = dgm[i].birth; ptr[2 * i + 1] = dgm[i].death; } py::capsule free_when_done(ptr, [](void* p) { Real* pp = reinterpret_cast<Real*>(p); delete[] pp; }); py::array::ShapeContainer shape {static_cast<long int>(dgm.size()), 2L}; py::array::StridesContainer strides {static_cast<long int>(2 * sizeof(Real)), static_cast<long int>(sizeof(Real))}; return py::array_t<Real>(shape, strides, ptr, free_when_done); } py::array_t<Real> get_diagram_in_dimension_as_numpy(dim_type d) const { auto dgm = diagrams_.get_diagram_in_dimension(d); return diagram_to_numpy(dgm); } auto get_diagram_in_dimension(dim_type d) const { return diagrams_.get_diagram_in_dimension(d); } private: oin::Diagrams<Real> diagrams_; }; template<class Int, class Real> using DiagramV = std::pair<PyOineusDiagrams<Real>, typename oin::VRUDecomposition<Int>::MatrixData>; template<class Int, class Real> using DiagramRV = std::tuple<PyOineusDiagrams<Real>, typename oin::VRUDecomposition<Int>::MatrixData, typename oin::VRUDecomposition<Int>::MatrixData>; template<class Int, class Real, size_t D> typename oin::Grid<Int, Real, D> get_grid(py::array_t<Real, py::array::c_style | py::array::forcecast> data, bool wrap) { using Grid = oin::Grid<Int, Real, D>; using GridPoint = typename Grid::GridPoint; py::buffer_info data_buf = data.request(); if (data.ndim() != D) throw std::runtime_error("Dimension mismatch"); Real* pdata {static_cast<Real*>(data_buf.ptr)}; GridPoint dims; for(dim_type d = 0 ; d < D ; ++d) dims[d] = data.shape(d); return Grid(dims, wrap, pdata); } template<class Int, class Real, size_t D> decltype(auto) get_fr_filtration(py::array_t<Real, py::array::c_style | py::array::forcecast> data, bool negate, bool wrap, dim_type max_dim, int n_threads) { auto grid = get_grid<Int, Real, D>(data, wrap); return grid.freudenthal_filtration(max_dim, negate, n_threads); } template<class Int, class Real, size_t D> decltype(auto) get_fr_filtration_and_critical_vertices(py::array_t<Real, py::array::c_style | py::array::forcecast> data, bool negate, bool wrap, dim_type max_dim, int n_threads) { auto grid = get_grid<Int, Real, D>(data, wrap); return grid.freudenthal_filtration_and_critical_vertices(max_dim, negate, n_threads); } template<class Real, size_t D> decltype(auto) numpy_to_point_vector(py::array_t<Real, py::array::c_style | py::array::forcecast> data) { using PointVector = std::vector<oin::Point<Real, D>>; if (data.ndim() != 2 or data.shape(1) != D) throw std::runtime_error("Dimension mismatch"); py::buffer_info data_buf = data.request(); PointVector points(data.shape(0)); Real* pdata {static_cast<Real*>(data_buf.ptr)}; for(size_t i = 0 ; i < data.size() ; ++i) points[i / D][i % D] = pdata[i]; return points; } template<typename Int, typename Real> decltype(auto) list_to_filtration(py::list data, oin::Params& params) //take a list of cells and turn it into a filtration for oineus. The list should contain cells in the form '[id, [boundary], filtration value]'. { using Simplex = oin::Simplex<Int, Real>; using Fil = oin::Filtration<Simplex>; using SimplexVector = typename Fil::CellVector; int n_simps = data.size(); std::cout << "Number of cells in the complex is: " << n_simps << std::endl; SimplexVector FSV; for(int i = 0 ; i < n_simps ; i++) { auto data_i = data[i]; int count = 0; Int id; std::vector<Int> vertices; Real val; for(auto item: data_i) { if (count == 0) { id = item.cast<Int>(); } else if (count == 1) { vertices = item.cast<std::vector<Int>>(); } else if (count == 2) { val = item.cast<Real>(); } count++; } if (params.verbose) std::cout << "parsed the following data. id: " << id << " val: " << val << std::endl; Simplex simp_i(id, vertices, val); FSV.push_back(simp_i); } return Fil(FSV, false, 1); } template<typename Int, typename Real> decltype(auto) get_ls_filtration(const py::list& simplices, const py::array_t<Real>& vertex_values, bool negate, int n_threads) // take a list of cells and a numpy array of their values and turn it into a filtration for oineus. // The list should contain cells, each simplex is a list of vertices, // e.g., triangulation of one segment is [[0], [1], [0, 1]] { using Simplex = oin::Simplex<Int, Real>; using Fil = oin::Filtration<Simplex>; using IdxVector = std::vector<Int>; using SimplexVector = std::vector<Simplex>; Timer timer; timer.reset(); SimplexVector fil_simplices; fil_simplices.reserve(simplices.size()); if (vertex_values.ndim() != 1) { std::cerr << "get_ls_filtration: expected 1-dimensional array in get_ls_filtration, got " << vertex_values.ndim() << std::endl; throw std::runtime_error("Expected 1-dimensional array in get_ls_filtration"); } auto cmp = negate ? [](Real x, Real y) { return x > y; } : [](Real x, Real y) { return x < y; }; auto vv_buf = vertex_values.request(); Real* p_vertex_values = static_cast<Real*>(vv_buf.ptr); for(auto&& item: simplices) { IdxVector vertices = item.cast<IdxVector>(); Int critical_vertex; Real critical_value = negate ? std::numeric_limits<Real>::max() : std::numeric_limits<Real>::lowest(); for(auto v: vertices) { Real vv = p_vertex_values[v]; if (cmp(critical_value, vv)) { critical_vertex = v; critical_value = vv; } } fil_simplices.emplace_back(vertices, critical_value); } // std::cerr << "without filtration ctor, in get_ls_filtration elapsed: " << timer.elapsed_reset() << std::endl; return Fil(std::move(fil_simplices), negate, n_threads); } template<class Int, class Real, size_t D> decltype(auto) get_vr_filtration(py::array_t<Real, py::array::c_style | py::array::forcecast> points, dim_type max_dim, Real max_radius, int n_threads) { return oin::get_vr_filtration<Int, Real, D>(numpy_to_point_vector<Real, D>(points), max_dim, max_radius, n_threads); } template<class Int, class Real> decltype(auto) get_vr_filtration_and_critical_edges_from_pwdists(py::array_t<Real, py::array::c_style | py::array::forcecast> pw_dists, dim_type max_dim, Real max_radius, int n_threads) { if (pw_dists.ndim() != 2 or pw_dists.shape(0) != pw_dists.shape(1)) throw std::runtime_error("Dimension mismatch"); py::buffer_info pw_dists_buf = pw_dists.request(); Real* pdata {static_cast<Real*>(pw_dists_buf.ptr)}; size_t n_points = pw_dists.shape(1); oin::DistMatrix<Real> dist_matrix { pdata, n_points }; return oin::get_vr_filtration_and_critical_edges<Int, Real>(dist_matrix, max_dim, max_radius, n_threads); } template<class Int, class Real> decltype(auto) get_vr_filtration_from_pwdists(py::array_t<Real, py::array::c_style | py::array::forcecast> pw_dists, dim_type max_dim, Real max_radius, int n_threads) { return get_vr_filtration_and_critical_edges_from_pwdists<Int, Real>(pw_dists, max_dim, max_radius, n_threads).first; } template<class Int, class Real, class L> PyOineusDiagrams<Real> compute_diagrams_from_fil(const oineus::Filtration<oineus::Simplex<Int, Real>>& fil, int n_threads) { oineus::VRUDecomposition<Int> d_matrix {fil, false}; oineus::Params params; params.sort_dgms = false; params.clearing_opt = true; params.n_threads = n_threads; d_matrix.reduce_parallel(params); return PyOineusDiagrams<Real>(d_matrix.diagram(fil)); } template<class Int, class Real, size_t D> decltype(auto) get_vr_filtration_and_critical_edges(py::array_t<Real, py::array::c_style | py::array::forcecast> points, dim_type max_dim, Real max_radius, int n_threads) { return oin::get_vr_filtration_and_critical_edges<Int, Real, D>(numpy_to_point_vector<Real, D>(points), max_dim, max_radius, n_threads); } template<class Int, class Real, size_t D> typename oin::VRUDecomposition<Int>::MatrixData get_boundary_matrix(py::array_t<Real, py::array::c_style | py::array::forcecast> data, bool negate, bool wrap, dim_type max_dim, int n_threads) { auto fil = get_fr_filtration<Int, Real, D>(data, negate, wrap, max_dim, n_threads); return fil.boundary_matrix_full(); } template<class Int, class Real, size_t D> typename oin::VRUDecomposition<Int>::MatrixData get_coboundary_matrix(py::array_t<Real, py::array::c_style | py::array::forcecast> data, bool negate, bool wrap, dim_type max_dim, int n_threads) { auto fil = get_fr_filtration<Int, Real, D>(data, negate, wrap, max_dim, n_threads); auto bm = fil.boundary_matrix_full(); return oin::antitranspose(bm); } template<class Int, class Real, size_t D> PyOineusDiagrams<Real> compute_diagrams_ls_freudenthal(py::array_t<Real, py::array::c_style | py::array::forcecast> data, bool negate, bool wrap, dim_type max_dim, oin::Params& params, bool include_inf_points, bool dualize) { // for diagram in dimension d, we need (d+1)-cells Timer timer; auto fil = get_fr_filtration<Int, Real, D>(data, negate, wrap, max_dim + 1, params.n_threads); auto elapsed_fil = timer.elapsed_reset(); oin::VRUDecomposition<Int> decmp {fil, dualize}; auto elapsed_decmp_ctor = timer.elapsed_reset(); if (params.print_time) std::cerr << "Filtration: " << elapsed_fil << ", decomposition ctor: " << elapsed_decmp_ctor << std::endl; decmp.reduce(params); if (params.do_sanity_check and not decmp.sanity_check()) throw std::runtime_error("sanity check failed"); return PyOineusDiagrams<Real>(decmp.diagram(fil, include_inf_points)); } template<typename Int, typename Real> class PyKerImCokDgms { private: oin::KerImCokReduced<Int, Real> KICR; public: PyKerImCokDgms(oin::KerImCokReduced<Int, Real> KICR_) : KICR(KICR_) { } decltype(auto) kernel() { return PyOineusDiagrams<Real>(KICR.get_kernel_diagrams()); } decltype(auto) image() { return PyOineusDiagrams(KICR.get_image_diagrams()); } decltype(auto) cokernel() { return PyOineusDiagrams(KICR.get_cokernel_diagrams()); } }; template<typename Int, typename Real> class PyKerImCokRed { private: oin::KerImCokReduced<Int, Real> KICR; public: bool kernel {false}; bool image {false}; bool cokernel {false}; PyKerImCokRed(oin::KerImCokReduced<Int, Real> KICR_) : KICR(KICR_) { } decltype(auto) kernel_diagrams() { if (!kernel) { KICR.GenerateKerDiagrams(); kernel = true; } return PyOineusDiagrams<Real>(KICR.get_kernel_diagrams()); } decltype(auto) image_diagrams() { if (!image) { KICR.GenerateImDiagrams(); image = true; } return PyOineusDiagrams(KICR.get_image_diagrams()); } decltype(auto) cokernel_diagrams() { if (!cokernel) { KICR.GenerateCokDiagrams(); cokernel = true; } return PyOineusDiagrams(KICR.get_cokernel_diagrams()); } decltype(auto) D_F() { return py::cast(KICR.get_D_f()); } decltype(auto) D_G() { return py::cast(KICR.get_D_g()); } decltype(auto) D_Ker() { return py::cast(KICR.get_D_ker()); } decltype(auto) D_Im() { return py::cast(KICR.get_D_im()); } decltype(auto) D_Cok() { return py::cast(KICR.get_D_cok()); } decltype(auto) R_F() { return py::cast(KICR.get_R_f()); } decltype(auto) R_G() { return py::cast(KICR.get_R_g()); } decltype(auto) R_Ker() { return py::cast(KICR.get_R_ker()); } decltype(auto) R_Im() { return py::cast(KICR.get_R_im()); } decltype(auto) R_Cok() { return py::cast(KICR.get_V_cok()); } decltype(auto) V_F() { return py::cast(KICR.get_V_f()); } decltype(auto) V_G() { return py::cast(KICR.get_V_g()); } decltype(auto) V_Ker() { return py::cast(KICR.get_V_ker()); } decltype(auto) V_Im() { return py::cast(KICR.get_V_im()); } decltype(auto) V_Cok() { return py::cast(KICR.get_V_cok()); } }; template<typename Int, typename Real> decltype(auto) compute_kernel_image_cokernel_reduction(py::list K_, py::list L_, py::list IdMap_, oin::Params& params) //take a list of cells and turn it into a filtration for oineus. The list should contain cells in the form '[id, [boundary], filtration value]. { using IdxVector = std::vector<Int>; using IntSparseColumn = oin::SparseColumn<Int>; using MatrixData = std::vector<IntSparseColumn>; using FiltrationSimplex = oin::Simplex<Int, Real>; using FiltrationSimplexVector = std::vector<FiltrationSimplex>; using Filtration = oin::Filtration<FiltrationSimplex>; using KerImCokReduced = oin::KerImCokReduced<Int, Real>; std::cout << "======================================" << std::endl; std::cout << std::endl; std::cout << "You have called \'compute_kernel_image_cokernel_reduction\', it takes as input a complex K, and a subcomplex L, as lists of cells in the format:" << std::endl; std::cout << " [id, [boundary], filtration value]" << std::endl; std::cout << "and a mapping from L to K, which takes the id of a cell in L and returns the id of the cell in K, as well as an integer, telling oineus how many threads to use." << std::endl; std::cout << std::endl; std::cout << "======================================" << std::endl; std::cout << std::endl; std::cout << "------------ Importing K ------------" << std::endl; Filtration K = list_to_filtration<Int, Real>(K_, params); std::cout << "------------ Importing L ------------" << std::endl; Filtration L = list_to_filtration<Int, Real>(L_, params); int n_L = IdMap_.size(); std::vector<int> IdMapping; for(int i = 0 ; i < n_L ; i++) { int i_map = IdMap_[i].cast<int>(); IdMapping.push_back(i_map); } if (params.verbose) { std::cout << "---------- Map from L to K ----------" << std::endl; for(int i = 0 ; i < n_L ; i++) { std::cout << "Cell " << i << " in L is mapped to cell " << IdMapping[i] << " in K." << std::endl; } } params.sort_dgms = false; params.clearing_opt = false; PyKerImCokRed KICR(oin::reduce_ker_im_cok<Int, Real>(K, L, IdMapping, params)); if (params.kernel) KICR.kernel = true; if (params.image) KICR.image = true; if (params.cokernel) KICR.cokernel = true; return KICR; } template<class Int> void init_oineus_common(py::module& m) { using namespace pybind11::literals; using oin::VREdge; using oin::DenoiseStrategy; using oin::ConflictStrategy; using Decomposition = oin::VRUDecomposition<Int>; using ReductionParams = oin::Params; using IndexDiagram = PyOineusDiagrams<size_t>; std::string vr_edge_name = "VREdge"; std::string index_dgm_class_name = "IndexDiagrams"; py::class_<VREdge>(m, vr_edge_name.c_str()) .def(py::init<Int>()) .def_readwrite("x", &VREdge::x) .def_readwrite("y", &VREdge::y) .def("__getitem__", [](const VREdge& p, int i) { if (i == 0) return p.x; else if (i == 1) return p.y; else throw std::out_of_range("i must be 0 or 1"); }) .def("__repr__", [](const VREdge& p) { std::stringstream ss; ss << p; return ss.str(); }); py::class_<ReductionParams>(m, "ReductionParams") .def(py::init<>()) .def_readwrite("n_threads", &ReductionParams::n_threads) .def_readwrite("chunk_size", &ReductionParams::chunk_size) .def_readwrite("write_dgms", &ReductionParams::write_dgms) .def_readwrite("sort_dgms", &ReductionParams::sort_dgms) .def_readwrite("clearing_opt", &ReductionParams::clearing_opt) .def_readwrite("acq_rel", &ReductionParams::acq_rel) .def_readwrite("print_time", &ReductionParams::print_time) .def_readwrite("elapsed", &ReductionParams::elapsed) .def_readwrite("compute_v", &ReductionParams::compute_v) .def_readwrite("compute_u", &ReductionParams::compute_u) .def_readwrite("do_sanity_check", &ReductionParams::do_sanity_check) .def_readwrite("kernel", &ReductionParams::kernel) .def_readwrite("image", &ReductionParams::image) .def_readwrite("cokernel", &ReductionParams::cokernel) .def_readwrite("verbose", &ReductionParams::verbose) .def(py::pickle( // __getstate__ [](const ReductionParams& p) { return py::make_tuple(p.n_threads, p.chunk_size, p.write_dgms, p.sort_dgms, p.clearing_opt, p.acq_rel, p.print_time, p.compute_v, p.compute_u, p.do_sanity_check, p.elapsed, p.kernel, p.image, p.cokernel, p.verbose); }, // __setstate__ [](py::tuple t) { if (t.size() != 15) throw std::runtime_error("Invalid tuple for ReductionParams"); ReductionParams p; int i = 0; p.n_threads = t[i++].cast<decltype(p.n_threads)>(); p.chunk_size = t[i++].cast<decltype(p.chunk_size)>(); p.write_dgms = t[i++].cast<decltype(p.write_dgms)>(); p.sort_dgms = t[i++].cast<decltype(p.sort_dgms)>(); p.clearing_opt = t[i++].cast<decltype(p.clearing_opt)>(); p.acq_rel = t[i++].cast<decltype(p.acq_rel)>(); p.print_time = t[i++].cast<decltype(p.print_time)>(); p.compute_v = t[i++].cast<decltype(p.compute_v)>(); p.compute_u = t[i++].cast<decltype(p.compute_u)>(); p.do_sanity_check = t[i++].cast<decltype(p.do_sanity_check)>(); p.elapsed = t[i++].cast<decltype(p.elapsed)>(); p.kernel = t[i++].cast<decltype(p.kernel)>(); p.image = t[i++].cast<decltype(p.image)>(); p.cokernel = t[i++].cast<decltype(p.cokernel)>(); p.verbose = t[i++].cast<decltype(p.verbose)>(); return p; })); py::enum_<DenoiseStrategy>(m, "DenoiseStrategy", py::arithmetic()) .value("BirthBirth", DenoiseStrategy::BirthBirth, "(b, d) maps to (b, b)") .value("DeathDeath", DenoiseStrategy::DeathDeath, "(b, d) maps to (d, d)") .value("Midway", DenoiseStrategy::Midway, "((b, d) maps to ((b+d)/2, (b+d)/2)") .def("as_str", [](const DenoiseStrategy& self) { return denoise_strategy_to_string(self); }); py::enum_<ConflictStrategy>(m, "ConflictStrategy", py::arithmetic()) .value("Max", ConflictStrategy::Max, "choose maximal displacement") .value("Avg", ConflictStrategy::Avg, "average gradients") .value("Sum", ConflictStrategy::Sum, "sum gradients") .value("FixCritAvg", ConflictStrategy::FixCritAvg, "use matching on critical, average gradients on other cells") .def("as_str", [](const ConflictStrategy& self) { return conflict_strategy_to_string(self); }); py::class_<Decomposition>(m, "Decomposition") .def(py::init<const oin::Filtration<oin::Simplex<Int, double>>&, bool>()) .def(py::init<const oin::Filtration<oin::Simplex<Int, float>>&, bool>()) .def_readwrite("r_data", &Decomposition::r_data) .def_readwrite("v_data", &Decomposition::v_data) .def_readwrite("u_data_t", &Decomposition::u_data_t) .def_readwrite("d_data", &Decomposition::d_data) .def("reduce", &Decomposition::reduce, py::call_guard<py::gil_scoped_release>()) .def("sanity_check", &Decomposition::sanity_check, py::call_guard<py::gil_scoped_release>()) .def("diagram", [](const Decomposition& self, const oin::Filtration<oin::Simplex<Int, double>>& fil, bool include_inf_points) { return PyOineusDiagrams<double>(self.diagram(fil, include_inf_points)); }) .def("diagram", [](const Decomposition& self, const oin::Filtration<oin::Simplex<Int, float>>& fil, bool include_inf_points) { return PyOineusDiagrams<float>(self.diagram(fil, include_inf_points)); }) .def("zero_persistence_diagram", [](const Decomposition& self, const oin::Filtration<oin::Simplex<Int, float>>& fil) { return PyOineusDiagrams<float>(self.zero_persistence_diagram(fil)); }) .def("index_diagram", [](const Decomposition& self, const oin::Filtration<oin::Simplex<Int, double>>& fil, bool include_inf_points, bool include_zero_persistence_points) { return PyOineusDiagrams<size_t>(self.index_diagram(fil, include_inf_points, include_zero_persistence_points)); }) .def("index_diagram", [](const Decomposition& self, const oin::Filtration<oin::Simplex<Int, float>>& fil, bool include_inf_points, bool include_zero_persistence_points) { return PyOineusDiagrams<size_t>(self.index_diagram(fil, include_inf_points, include_zero_persistence_points)); }); using DgmPointInt = typename oin::DgmPoint<Int>; using DgmPointSizet = typename oin::DgmPoint<size_t>; py::class_<DgmPointInt>(m, "DgmPoint_int") .def(py::init<Int, Int>()) .def_readwrite("birth", &DgmPointInt::birth) .def_readwrite("death", &DgmPointInt::death) .def("__getitem__", [](const DgmPointInt& p, int i) { return p[i]; }) .def("__hash__", [](const DgmPointInt& p) { return std::hash<DgmPointInt>()(p); }) .def("__repr__", [](const DgmPointInt& p) { std::stringstream ss; ss << p; return ss.str(); }); py::class_<DgmPointSizet>(m, "DgmPoint_Sizet") .def(py::init<size_t, size_t>()) .def_readwrite("birth", &DgmPointSizet::birth) .def_readwrite("death", &DgmPointSizet::death) .def("__getitem__", [](const DgmPointSizet& p, int i) { return p[i]; }) .def("__hash__", [](const DgmPointSizet& p) { return std::hash<DgmPointSizet>()(p); }) .def("__repr__", [](const DgmPointSizet& p) { std::stringstream ss; ss << p; return ss.str(); }); py::class_<IndexDiagram>(m, index_dgm_class_name.c_str()) .def(py::init<dim_type>()) .def("in_dimension", &IndexDiagram::get_diagram_in_dimension) .def("__getitem__", &IndexDiagram::get_diagram_in_dimension); } template<class Int, class Real> void init_oineus(py::module& m, std::string suffix) { using namespace pybind11::literals; using DgmPoint = typename oin::Diagrams<Real>::Point; using DgmPtVec = typename oin::Diagrams<Real>::Dgm; using Diagram = PyOineusDiagrams<Real>; using Filtration = oin::Filtration<oin::Simplex<Int, Real>>; using Simplex = typename Filtration::Cell; using oin::VREdge; using VRUDecomp = oin::VRUDecomposition<Int>; using KerImCokRed = oin::KerImCokReduced<Int, Real>; using PyKerImCokRed = PyKerImCokRed<Int, Real>; //using CokRed = oin::CokReduced<Int, Real>; std::string filtration_class_name = "Filtration" + suffix; std::string simplex_class_name = "Simplex" + suffix; std::string dgm_point_name = "DiagramPoint" + suffix; std::string dgm_class_name = "Diagrams" + suffix; std::string ker_im_cok_reduced_class_name = "KerImCokReduced" + suffix; std::string py_ker_im_cok_reduced_class_name = "PyKerImCokRed" + suffix; py::class_<DgmPoint>(m, dgm_point_name.c_str()) .def(py::init<Real, Real>(), py::arg("birth"), py::arg("death")) .def_readwrite("birth", &DgmPoint::birth) .def_readwrite("death", &DgmPoint::death) .def("__getitem__", [](const DgmPoint& p, int i) { return p[i]; }) .def("__hash__", [](const DgmPoint& p) { return std::hash<DgmPoint>()(p); }) .def("__repr__", [](const DgmPoint& p) { std::stringstream ss; ss << p; return ss.str(); }); py::class_<Diagram>(m, dgm_class_name.c_str()) .def(py::init<dim_type>()) .def("in_dimension", [](const Diagram& self, dim_type dim, bool as_numpy) -> std::variant<pybind11::array_t<Real>, DgmPtVec> { if (as_numpy) return self.get_diagram_in_dimension_as_numpy(dim); else return self.get_diagram_in_dimension(dim); }, "return persistence diagram in dimension dim: if as_numpy is False (default), the diagram is returned as list of DgmPoints, else as NumPy array", py::arg("dim"), py::arg("as_numpy")=true) .def("__getitem__", &Diagram::get_diagram_in_dimension_as_numpy); py::class_<Simplex>(m, simplex_class_name.c_str()) .def(py::init<typename Simplex::IdxVector, Real>(), py::arg("vertices"), py::arg("value")) .def(py::init<typename Simplex::Int, typename Simplex::IdxVector, Real>(), py::arg("id"), py::arg("vertices"), py::arg("value")) .def_readwrite("id", &Simplex::id_) .def_readwrite("sorted_id", &Simplex::sorted_id_) .def_readwrite("vertices", &Simplex::vertices_) .def_readwrite("value", &Simplex::value_) .def("dim", &Simplex::dim) .def("boundary", &Simplex::boundary) .def("join", [](const Simplex& sigma, Int new_vertex, Real value, Int new_id) { return sigma.join(new_id, new_vertex, value); }, py::arg("new_vertex"), py::arg("value"), py::arg("new_id") = Simplex::k_invalid_id) .def("__repr__", [](const Simplex& sigma) { std::stringstream ss; ss << sigma; return ss.str(); }); py::class_<Filtration>(m, filtration_class_name.c_str()) .def(py::init<typename Filtration::CellVector, bool, int, bool, bool>(), py::arg("cells"), py::arg("negate")=false, py::arg("n_threads")=1, py::arg("sort_only_by_dimension")=false, py::arg("set_ids")=true) .def("max_dim", &Filtration::max_dim) .def("cells", &Filtration::cells_copy) .def("simplices", &Filtration::cells_copy) .def("size", &Filtration::size) .def("__len__", &Filtration::size) .def("size_in_dimension", &Filtration::size_in_dimension) .def("n_vertices", &Filtration::n_vertices) .def("simplex_value_by_sorted_id", &Filtration::value_by_sorted_id, py::arg("sorted_id")) .def("get_id_by_sorted_id", &Filtration::get_id_by_sorted_id, py::arg("sorted_id")) .def("get_sorted_id_by_id", &Filtration::get_sorted_id, py::arg("id")) .def("get_sorting_permutation", &Filtration::get_sorting_permutation) .def("get_inv_sorting_permutation", &Filtration::get_inv_sorting_permutation) .def("simplex_value_by_vertices", &Filtration::value_by_vertices, py::arg("vertices")) .def("get_sorted_id_by_vertices", &Filtration::get_sorted_id_by_vertices, py::arg("vertices")) .def("boundary_matrix", &Filtration::boundary_matrix_full) .def("reset_ids_to_sorted_ids", &Filtration::reset_ids_to_sorted_ids) .def("__repr__", [](const Filtration& fil) { std::stringstream ss; ss << fil; return ss.str(); }); py::class_<KerImCokRed>(m, ker_im_cok_reduced_class_name.c_str()) .def(py::init<Filtration, Filtration, VRUDecomp, VRUDecomp, VRUDecomp, VRUDecomp, VRUDecomp, std::vector<int>, std::vector<int>, std::vector<int>, std::vector<int>, oin::Params>()); py::class_<PyKerImCokRed>(m, py_ker_im_cok_reduced_class_name.c_str()) .def(py::init<KerImCokRed>()) .def("kernel_diagrams", &PyKerImCokRed::kernel_diagrams) .def("image_diagrams", &PyKerImCokRed::image_diagrams) .def("cokernel_diagrams", &PyKerImCokRed::cokernel_diagrams) .def("D_F", &PyKerImCokRed::D_F) .def("D_G", &PyKerImCokRed::D_G) .def("D_Ker", &PyKerImCokRed::D_Ker) .def("D_Im", &PyKerImCokRed::D_Im) .def("D_Cok", &PyKerImCokRed::D_Cok) .def("R_F", &PyKerImCokRed::R_F) .def("R_G", &PyKerImCokRed::R_G) .def("R_Ker", &PyKerImCokRed::R_Ker) .def("R_Im", &PyKerImCokRed::R_Im) .def("R_Cok", &PyKerImCokRed::R_Cok) .def("V_F", &PyKerImCokRed::V_F) .def("V_G", &PyKerImCokRed::V_G) .def("V_Ker", &PyKerImCokRed::V_Ker) .def("V_Im", &PyKerImCokRed::V_Im) .def("V_Cok", &PyKerImCokRed::V_Cok); std::string func_name; // diagrams func_name = "compute_diagrams_ls" + suffix + "_1"; m.def(func_name.c_str(), &compute_diagrams_ls_freudenthal<Int, Real, 1>); func_name = "compute_diagrams_ls" + suffix + "_2"; m.def(func_name.c_str(), &compute_diagrams_ls_freudenthal<Int, Real, 2>); func_name = "compute_diagrams_ls" + suffix + "_3"; m.def(func_name.c_str(), &compute_diagrams_ls_freudenthal<Int, Real, 3>); // Lower-star Freudenthal filtration func_name = "get_fr_filtration" + suffix + "_1"; m.def(func_name.c_str(), &get_fr_filtration<Int, Real, 1>); func_name = "get_fr_filtration" + suffix + "_2"; m.def(func_name.c_str(), &get_fr_filtration<Int, Real, 2>); func_name = "get_fr_filtration" + suffix + "_3"; m.def(func_name.c_str(), &get_fr_filtration<Int, Real, 3>); func_name = "get_fr_filtration_and_critical_vertices" + suffix + "_1"; m.def(func_name.c_str(), &get_fr_filtration_and_critical_vertices<Int, Real, 1>); func_name = "get_fr_filtration_and_critical_vertices" + suffix + "_2"; m.def(func_name.c_str(), &get_fr_filtration_and_critical_vertices<Int, Real, 2>); func_name = "get_fr_filtration_and_critical_vertices" + suffix + "_3"; m.def(func_name.c_str(), &get_fr_filtration_and_critical_vertices<Int, Real, 3>); // Vietoris--Rips filtration func_name = "get_vr_filtration" + suffix + "_1"; m.def(func_name.c_str(), &get_vr_filtration<Int, Real, 1>); func_name = "get_vr_filtration" + suffix + "_2"; m.def(func_name.c_str(), &get_vr_filtration<Int, Real, 2>); func_name = "get_vr_filtration" + suffix + "_3"; m.def(func_name.c_str(), &get_vr_filtration<Int, Real, 3>); func_name = "get_vr_filtration" + suffix + "_4"; m.def(func_name.c_str(), &get_vr_filtration<Int, Real, 4>); func_name = "get_vr_filtration_and_critical_edges" + suffix + "_1"; m.def(func_name.c_str(), &get_vr_filtration_and_critical_edges<Int, Real, 1>); func_name = "get_vr_filtration_and_critical_edges" + suffix + "_2"; m.def(func_name.c_str(), &get_vr_filtration_and_critical_edges<Int, Real, 2>); func_name = "get_vr_filtration_and_critical_edges" + suffix + "_3"; m.def(func_name.c_str(), &get_vr_filtration_and_critical_edges<Int, Real, 3>); func_name = "get_vr_filtration_and_critical_edges" + suffix + "_4"; m.def(func_name.c_str(), &get_vr_filtration_and_critical_edges<Int, Real, 4>); func_name = "get_vr_filtration_from_pwdists" + suffix; m.def(func_name.c_str(), &get_vr_filtration_from_pwdists<Int, Real>); func_name = "get_vr_filtration_and_critical_edges_from_pwdists" + suffix; m.def(func_name.c_str(), &get_vr_filtration_and_critical_edges_from_pwdists<Int, Real>); // boundary matrix as vector of columns func_name = "get_boundary_matrix" + suffix + "_1"; m.def(func_name.c_str(), &get_boundary_matrix<Int, Real, 1>); func_name = "get_boundary_matrix" + suffix + "_2"; m.def(func_name.c_str(), &get_boundary_matrix<Int, Real, 2>); func_name = "get_boundary_matrix" + suffix + "_3"; m.def(func_name.c_str(), &get_boundary_matrix<Int, Real, 3>); // target values func_name = "get_denoise_target" + suffix; m.def(func_name.c_str(), &oin::get_denoise_target<Simplex>); func_name = "get_wasserstein_matching_target_values" + suffix; m.def(func_name.c_str(), &oin::get_target_from_matching<Simplex>); // target values -- diagram loss func_name = "get_target_values_diagram_loss" + suffix; m.def(func_name.c_str(), &oin::get_prescribed_simplex_values_diagram_loss<Real>); // target values --- X set func_name = "get_target_values_x" + suffix; m.def(func_name.c_str(), &oin::get_prescribed_simplex_values_set_x<Simplex>); // to reproduce "Topology layer for ML" experiments func_name = "get_bruelle_target" + suffix; m.def(func_name.c_str(), &oin::get_bruelle_target<Simplex>); // to reproduce "Well group loss" experiments func_name = "get_well_group_target" + suffix; m.def(func_name.c_str(), &oin::get_well_group_target<Simplex>); func_name = "get_nth_persistence" + suffix; m.def(func_name.c_str(), &oin::get_nth_persistence<Simplex>); // to equidistribute points func_name = "get_barycenter_target" + suffix; m.def(func_name.c_str(), &oin::get_barycenter_target<Simplex>); // to get permutation for Warm Starts func_name = "get_permutation" + suffix; m.def(func_name.c_str(), &oin::targets_to_permutation<Simplex>); func_name = "get_permutation_dtv" + suffix; m.def(func_name.c_str(), &oin::targets_to_permutation_dtv<Simplex>); // reduce to create an ImKerReduced object func_name = "reduce_ker_im_cok" + suffix; m.def(func_name.c_str(), &oin::reduce_ker_im_cok<Int, Real>); func_name = "list_to_filtration" + suffix; m.def(func_name.c_str(), &list_to_filtration<Int, Real>); func_name = "compute_kernel_image_cokernel_reduction" + suffix; m.def(func_name.c_str(), &compute_kernel_image_cokernel_reduction<Int, Real>); func_name = "get_ls_filtration" + suffix; m.def(func_name.c_str(), &get_ls_filtration<Int, Real>); } inline void init_oineus_top_optimizer(py::module& m) { using Real = double; using Int = int; using Simplex = oin::Simplex<Int, Real>; using Filtration = oin::Filtration<Simplex>; using TopologyOptimizer = oin::TopologyOptimizer<Simplex>; using Indices = typename TopologyOptimizer::Indices; using Values = typename TopologyOptimizer::Values; using IndicesValues = typename TopologyOptimizer::IndicesValues; using CrititcalSet = typename TopologyOptimizer::CriticalSet; using Target = typename TopologyOptimizer::Target; using Indices = typename TopologyOptimizer::Indices; using Values = typename TopologyOptimizer::Values; using CriticalSets = typename TopologyOptimizer::CriticalSets; using ConflictStrategy = oin::ConflictStrategy; using Diagram = typename oin::Diagrams<Real>::Dgm; py::class_<IndicesValues>(m, "IndicesValues") .def("__getitem__", [](const IndicesValues& iv, int i) -> std::variant<Indices, Values> { if (i == 0) return {iv.indices}; else if (i == 1) return {iv.values}; else throw std::out_of_range("IndicesValues: i must be 0 or 1"); }) .def("__repr__", [](const IndicesValues& iv) { std::stringstream ss; ss << iv; return ss.str(); }); // optimization py::class_<TopologyOptimizer>(m, "TopologyOptimizer") .def(py::init<const Filtration&>()) .def("compute_diagram", [](TopologyOptimizer& opt, bool include_inf_points) { return PyOineusDiagrams<Real>(opt.compute_diagram(include_inf_points)); }, py::arg("include_inf_points"), "compute diagrams in all dimensions") .def("compute_index_diagram", [](TopologyOptimizer& opt, bool include_inf_points, bool include_zero_persistence_points=false) { return PyOineusDiagrams<size_t>(opt.compute_index_diagram(include_inf_points, include_zero_persistence_points)); }, py::arg("include_inf_points") = true, py::arg("include_zero_persistence_points") = false, "compute persistence pairing (index diagram) in all dimensions") .def("simplify", &TopologyOptimizer::simplify, py::arg("epsilon"), py::arg("strategy"), py::arg("dim"), "make points with persistence less than epsilon go to the diagonal") .def("get_nth_persistence", &TopologyOptimizer::get_nth_persistence, py::arg("dim"), py::arg("n"), "return n-th persistence value in d-dimensional persistence diagram") .def("match", [](TopologyOptimizer& opt, Diagram& template_dgm, dim_type d, Real wasserstein_q, bool return_wasserstein_distance) -> std::variant<IndicesValues, std::pair<IndicesValues, Real>> { if (return_wasserstein_distance) return opt.match_and_distance(template_dgm, d, wasserstein_q); else return opt.match(template_dgm, d, wasserstein_q); }, py::arg("template_dgm"), py::arg("dim"), py::arg("wasserstein_q")=1.0, py::arg("return_wasserstein_distance")=false, "return target from Wasserstein matching" ) .def("singleton", &TopologyOptimizer::singleton) .def("singletons", &TopologyOptimizer::singletons) .def("combine_loss", static_cast<IndicesValues (TopologyOptimizer::*)(const CriticalSets&, ConflictStrategy)>(&TopologyOptimizer::combine_loss), py::arg("critical_sets"), py::arg("strategy"), "combine critical sets into well-defined assignment of new values to indices") .def("update", &TopologyOptimizer::update); // IndicesValues combine_loss(const CriticalSets& critical_sets, ConflictStrategy strategy) } #endif //OINEUS_OINEUS_PERSISTENCE_BINDINGS_H
/* * 题目:198. 打家劫舍 * 链接:https://leetcode-cn.com/problems/house-robber/ * 知识点:动态规划 */ class Solution { public: int rob(vector<int>& nums) { if (nums.empty()) { return 0; } int n = nums.size(); if (n == 1) { return nums[0]; } // dp[i] = max(dp[i - 1], dp[i - 2] + nums[i]) int a = nums[0], b = max(nums[0], nums[1]); for (int i = 2; i < n; i++) { int t = b; b = max(a + nums[i], b); a = t; } return b; } };
#include "triangle.h" #include "gtest/gtest.h" class TriangleTest : public testing::Test{ protected: //virtual void Setup(); //virtual void TearDown(); }; TEST_F(TriangleTest, BoundaryValueTesting) { EXPECT_EQ(IsTriangle(1,1,1),"Equilateral"); EXPECT_EQ(IsTriangle(0,1,1),"Not a Triangle"); EXPECT_EQ(IsTriangle(50,50,70),"Isosceles"); EXPECT_EQ(IsTriangle(200,200,200),"Equilateral"); EXPECT_EQ(IsTriangle(100,200,100),"Not a Triangle"); EXPECT_EQ(IsTriangle(1,150,1),"Not a Triangle"); EXPECT_EQ(IsTriangle(6,7,8),"Scalene"); } TEST_F(TriangleTest, EquivalenceClassTesting) { EXPECT_EQ(IsTriangle(5,5,5),"Equilateral"); EXPECT_EQ(IsTriangle(2,2,3),"Isosceles"); EXPECT_EQ(IsTriangle(3,4,5),"Scalene"); EXPECT_EQ(IsTriangle(4,1,2),"Not a Triangle"); } TEST_F(TriangleTest, EdgeTesing) { EXPECT_EQ(IsTriangle(1,1,1),"Equilateral"); EXPECT_EQ(IsTriangle(200,200,200),"Equilateral"); EXPECT_EQ(IsTriangle(50,50,1),"Isosceles"); EXPECT_EQ(IsTriangle(199,200,200),"Isosceles"); EXPECT_EQ(IsTriangle(198,199,200),"Scalene"); EXPECT_EQ(IsTriangle(1,2,1),"Not a Triangle"); } TEST_F(TriangleTest, DecistionTableTest) { //a != b EXPECT_EQ(IsTriangle(1,2,3),"Not a Triangle"); //a = b EXPECT_EQ(IsTriangle(2,2,3),"Isosceles"); //b != c EXPECT_EQ(IsTriangle(200,150,140),"Scalene"); //a == c EXPECT_EQ(IsTriangle(40,40,40),"Equilateral"); } TEST_F(TriangleTest, C0Test) { EXPECT_EQ("Not a Triangle",IsTriangle(0,0,0)); EXPECT_EQ("Not a Triangle",IsTriangle(1,0,0)); EXPECT_EQ("Not a Triangle",IsTriangle(1,1,0)); EXPECT_EQ("Equilateral",IsTriangle(3,3,3)); EXPECT_EQ("Scalene",IsTriangle(3,4,5)); EXPECT_EQ("Not a Triangle",IsTriangle(1,2,3)); EXPECT_EQ("Isosceles",IsTriangle(2,3,2)); } TEST_F(TriangleTest, C1Test) { //1,2 EXPECT_EQ("Not a Triangle",IsTriangle(5,0,0)); //2,3 EXPECT_EQ("Not a Triangle",IsTriangle(5,3,0)); //3,4 EXPECT_EQ("Not a Triangle",IsTriangle(5,3,1)); //4,5 EXPECT_EQ("Equilateral",IsTriangle(5,5,5)); //5,6 EXPECT_EQ("Scalene",IsTriangle(33,43,53)); //1,2,3 EXPECT_EQ("Not a Triangle",IsTriangle(50,33,0)); //2,3,4 EXPECT_EQ("Not a Triangle",IsTriangle(50,13,13)); //4,5,6 EXPECT_EQ("Isosceles",IsTriangle(14,13,13)); //1,2,3,4 EXPECT_EQ("Not a Triangle",IsTriangle(1,3,1)); //1,2,3,4,5,6 EXPECT_EQ("Isosceles",IsTriangle(140,150,140)); } TEST_F(TriangleTest, MCDCTest) { //a<=0 a>200 EXPECT_EQ("Equilateral",IsTriangle(5,5,5)); EXPECT_EQ("Not a Triangle",IsTriangle(0,5,5)); //b<=0 b>200 EXPECT_EQ("Isosceles",IsTriangle(5,6,5)); EXPECT_EQ("Not a Triangle",IsTriangle(5,0,5)); //c<=0 c>200 EXPECT_EQ("Scalene",IsTriangle(5,4,3)); EXPECT_EQ("Not a Triangle",IsTriangle(5,4,0)); //a<b+c b<a+c c<a+b EXPECT_EQ("Equilateral",IsTriangle(5,5,5)); EXPECT_EQ("Not a Triangle",IsTriangle(100,5,5)); //a==b b==c EXPECT_EQ("Equilateral",IsTriangle(5,5,5)); EXPECT_EQ("Isosceles",IsTriangle(4,5,5)); }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 1995-2009 Opera Software AS. All rights reserved. * * This file is part of the Opera web browser. It may not be distributed * under any circumstances. */ #include "core/pch.h" #ifdef PIXEL_SCALE_RENDERING_SUPPORT #include "modules/display/pixelscaler.h" #endif // PIXEL_SCALE_RENDERING_SUPPORT #include "platforms/mac/pi/display/MacOpGLDevice.h" #include "platforms/mac/pi/CocoaVEGAWindow.h" #include "platforms/mac/pi/CocoaMDEScreen.h" #include "platforms/mac/pi/CocoaOpWindow.h" #include "platforms/mac/CocoaVegaDefines.h" // DSK-290489 Text not being rendered when whole string is not fully visible after scrolling #define PADDING_FOR_MISSING_TEXT 72 struct LockableBitmap { LockableBitmap(void* ptr, CocoaMDEScreen* screen) : ptr(ptr) #ifdef MUTEX_LOCK_CALAYER_UPDATES , screen(screen) #endif { #ifdef MUTEX_LOCK_CALAYER_UPDATES pthread_mutex_init(&mutex, NULL); screen->AddRef(&screen); #endif } void* ptr; #ifdef MUTEX_LOCK_CALAYER_UPDATES CocoaMDEScreen* screen; pthread_mutex_t mutex; #endif }; static const void * GetBytePointer(void *info) { LockableBitmap* lb = (LockableBitmap*)info; #ifdef MUTEX_LOCK_CALAYER_UPDATES pthread_mutex_lock(&lb->mutex); #endif return lb->ptr; } static void ReleaseBytePointer(void *info, const void *pointer) { #ifdef MUTEX_LOCK_CALAYER_UPDATES LockableBitmap* lb = (LockableBitmap*)info; pthread_mutex_unlock(&lb->mutex); if (lb->screen && lb->screen->IsDirty()) { lb->screen->Validate(true); } #endif } static void FreeBitmap(void *info) { LockableBitmap* lb = (LockableBitmap*)info; free(lb->ptr); #ifdef MUTEX_LOCK_CALAYER_UPDATES if (lb->screen) lb->screen->RemoveRef(&lb->screen); #endif OP_DELETE((LockableBitmap*)info); } CGDataProviderDirectCallbacks gProviderCallbacks = { 0, GetBytePointer, ReleaseBytePointer, NULL, FreeBitmap }; CocoaVEGAWindow::CocoaVEGAWindow(CocoaOpWindow* opwnd) : m_background_buffer(NULL) , m_calayer_buffer(NULL) , m_background_image(0) , m_image(0) , m_calayer_provider(0) , m_ctx(0) #ifdef VEGA_USE_HW , m_3dwnd(NULL) #endif , m_opwnd(opwnd) #ifndef NS4P_COMPONENT_PLUGINS # ifndef NP_NO_QUICKDRAW , m_qd_world(NULL) # endif #endif // NS4P_COMPONENT_PLUGINS { m_store.buffer = NULL; m_store.stride = 0; #ifdef VEGA_INTERNAL_FORMAT_RGBA8888 m_store.format = VPSF_RGBA8888; #else m_store.format = VPSF_BGRA8888; #endif m_store.width = m_store.height = 0; } CocoaVEGAWindow::~CocoaVEGAWindow() { if (m_ctx) { CGContextRelease(m_ctx); } if (m_image) { CGImageRelease(m_image); } if (m_background_image) { CGImageRelease(m_background_image); } #ifndef NS4P_COMPONENT_PLUGINS DestroyGWorld(); #endif // NS4P_COMPONENT_PLUGINS if (m_calayer_provider) { CGDataProviderRelease(m_calayer_provider); } } CGContextRef CocoaVEGAWindow::getPainter() { #ifdef VEGA_USE_HW return (m_3dwnd?NULL:m_ctx); #else return m_ctx; #endif } CGImageRef CocoaVEGAWindow::createImage(BOOL background) { if (!m_image) return NULL; if (background) { if (m_background_image && m_bg_rgn.num_rects > 0) return CGImageCreate(m_store.width, m_store.height, 8, 32, CGImageGetBytesPerRow(m_background_image), CGImageGetColorSpace(m_background_image), CGImageGetBitmapInfo(m_background_image), CGImageGetDataProvider(m_background_image), NULL, 0, kCGRenderingIntentAbsoluteColorimetric); // No plugins so no background return NULL; } // Cannot return m_image, or another image with the same backing store, // because CALayer will copy the data asynchronously, // possibly overlapping with the next update. // Meaning, it may copy an unfinished bitmap. #ifdef MUTEX_LOCK_CALAYER_UPDATES return CGImageCreate(m_store.width, m_store.height, 8, 32, CGImageGetBytesPerRow(m_image), CGImageGetColorSpace(m_image), CGImageGetBitmapInfo(m_image), CGImageGetDataProvider(m_image), NULL, 0, kCGRenderingIntentAbsoluteColorimetric); #else if (m_calayer_provider) { // Update dirty UINT8* src = (UINT8*)m_store.buffer; UINT8* dst = (UINT8*)m_calayer_buffer; MDE_RECT union_rect = {0,0,0,0}; for (int i = 0; i < m_dirty_rgn.num_rects; i++) union_rect = MDE_RectUnion(union_rect, m_dirty_rgn.rects[i]); if (m_store.stride == m_store.width*4 && (float)union_rect.w > 0.95*m_store.width) memcpy(dst+union_rect.y*m_store.stride, src+union_rect.y*m_store.stride, m_store.stride*union_rect.h); else for (int i = 0; i < m_dirty_rgn.num_rects; i++) { MDE_RECT r = m_dirty_rgn.rects[i]; if (m_store.stride == m_store.width*4 && r.x == 0 && r.w == m_store.width) memcpy(dst+r.y*m_store.stride, src+r.y*m_store.stride, m_store.stride*r.h); else for (int y = r.y; y < r.y+r.h; y++) memcpy(dst+y*m_store.width*4+r.x*4, src+y*m_store.stride+r.x*4, r.w*4); } } else { m_calayer_buffer = (unsigned char*)calloc(1, m_store.width*m_store.height*4); if (!m_calayer_buffer) return NULL; UINT8* src = (UINT8*)m_store.buffer; UINT8* dst = (UINT8*)m_calayer_buffer; if (m_store.stride == m_store.width*4) memcpy(dst, src, m_store.width*m_store.height*4); else for (unsigned y = 0; y < m_store.height; y++) memcpy(dst+y*m_store.width*4, src+y*m_store.stride, m_store.width*4); LockableBitmap* info = OP_NEW(LockableBitmap, (m_calayer_buffer, m_opwnd->GetScreen())); m_calayer_provider = CGDataProviderCreateDirect(info, m_store.width*m_store.height*4, &gProviderCallbacks); } m_dirty_rgn.Reset(); return CGImageCreate(m_store.width, m_store.height, 8, 32, m_store.width*4, CGImageGetColorSpace(m_image), CGImageGetBitmapInfo(m_image), m_calayer_provider, NULL, 0, kCGRenderingIntentAbsoluteColorimetric); #endif // !MUTEX_LOCK_CALAYER_UPDATES } VEGAPixelStore* CocoaVEGAWindow::getPixelStore() { return &m_store; } unsigned int CocoaVEGAWindow::getWidth() { return m_store.width; } unsigned int CocoaVEGAWindow::getHeight() { return m_store.height; } void CocoaVEGAWindow::present(const OpRect* update_rects, unsigned int num_rects) { MDE_Region reg; for (unsigned int i = 0; i < num_rects; ++i) { OpRect rect = update_rects[i]; #ifdef PIXEL_SCALE_RENDERING_SUPPORT PixelScaler scaler(m_opwnd->GetPixelScale()); rect = FROM_DEVICE_PIXEL(scaler, rect); #endif // PIXEL_SCALE_RENDERING_SUPPORT reg.AddRect(MDE_MakeRect(rect.x, rect.y, rect.width, rect.height)); } m_opwnd->Invalidate(&reg); } void CocoaVEGAWindow::resize(int w, int h, BOOL background) { #ifdef VEGA_USE_HW if (m_3dwnd) { m_3dwnd->resizeBackbuffer(w, h); m_store.width = w; m_store.height = h; return; } #endif m_bg_rgn.Reset(); if (m_calayer_provider) { CGDataProviderRelease(m_calayer_provider); m_calayer_buffer = NULL; m_calayer_provider = NULL; } if (m_image) { if (CGImageGetWidth(m_image) >= static_cast<unsigned int>(w) && CGImageGetHeight(m_image) >= static_cast<unsigned int>(h)) { m_store.width = w; m_store.height = h; return; } CGContextRelease(m_ctx); CGImageRelease(m_image); if (m_background_image) CGImageRelease(m_background_image); m_background_buffer = NULL; m_background_image = NULL; } int bpl= (w*4+3) & ~3; int bitmap_height = h+PADDING_FOR_MISSING_TEXT; void *image_data = calloc(1, bitmap_height*bpl); CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); LockableBitmap* info = OP_NEW(LockableBitmap, (image_data, m_opwnd->GetScreen())); #ifdef MUTEX_LOCK_CALAYER_UPDATES m_opwnd->GetScreen()->SetMutex(&info->mutex); #endif CGDataProviderRef provider = CGDataProviderCreateDirect(info, bitmap_height*bpl, &gProviderCallbacks); CGBitmapInfo alpha = kCGBitmapByteOrderVegaInternal; m_image = CGImageCreate(w, bitmap_height, 8, 32, bpl, colorSpace, (CGImageAlphaInfo)alpha, provider, NULL, 0, kCGRenderingIntentAbsoluteColorimetric); CGDataProviderRelease(provider); CGColorSpaceRelease(colorSpace); m_store.stride = bpl; m_store.width = w; m_store.height = h; m_store.buffer = image_data; m_ctx = CGBitmapContextCreate(m_store.buffer, CGImageGetWidth(m_image), CGImageGetHeight(m_image), 8, CGImageGetBytesPerRow(m_image), CGImageGetColorSpace(m_image), (CGImageAlphaInfo)CGImageGetBitmapInfo(m_image)); #ifndef NS4P_COMPONENT_PLUGINS DestroyGWorld(); #endif // NS4P_COMPONENT_PLUGINS } void CocoaVEGAWindow::CreatePainter(CGContextRef& painter, CGDataProviderRef& provider) { painter = CGBitmapContextCreate(m_store.buffer, CGImageGetWidth(m_image), CGImageGetHeight(m_image), 8, CGImageGetBytesPerRow(m_image), CGImageGetColorSpace(m_image), (CGImageAlphaInfo)CGImageGetBitmapInfo(m_image)); provider = CGImageGetDataProvider(m_image); CGDataProviderRetain(provider); } void CocoaVEGAWindow::MoveToBackground(OpRect rect, bool transparent) { #ifdef VEGA_USE_HW if (m_3dwnd) { ((MacGlWindow*)m_3dwnd)->MoveToBackground(MDE_MakeRect(rect.x, rect.y, rect.width, rect.height)); } else { #endif MDE_RECT mderect={rect.x,rect.y,rect.width,rect.height}; if (transparent) m_bg_rgn.IncludeRect(mderect); unsigned char* buffer = (unsigned char*)m_store.buffer; rect.IntersectWith(OpRect(0,0,m_store.width,m_store.height)); if (transparent && !m_background_buffer) { m_background_buffer = (unsigned char*)calloc(1, CGImageGetHeight(m_image)*CGImageGetBytesPerRow(m_image)); LockableBitmap* info = OP_NEW(LockableBitmap, (m_background_buffer, m_opwnd->GetScreen())); CGDataProviderRef background_provider = CGDataProviderCreateDirect(info, CGImageGetHeight(m_image)*CGImageGetBytesPerRow(m_image), &gProviderCallbacks); m_background_image = CGImageCreate(m_store.width,m_store.height, 8, 32, CGImageGetBytesPerRow(m_image), CGImageGetColorSpace(m_image), (CGImageAlphaInfo)CGImageGetBitmapInfo(m_image), background_provider, NULL, 0, kCGRenderingIntentAbsoluteColorimetric); CGDataProviderRelease(background_provider); } for (int i = rect.y; i<rect.y+rect.height; i++) { int offset = i*m_store.stride+rect.x*4; if (transparent) op_memcpy(m_background_buffer+offset, buffer+offset,rect.width*4); op_memset(buffer+offset, 0, rect.width*4); } #ifdef VEGA_USE_HW } #endif } void CocoaVEGAWindow::ScrollBackground(const MDE_RECT &rect, int dx, int dy) { m_dirty_rgn.IncludeRect(rect); if (m_background_buffer && m_bg_rgn.num_rects > 0) { unsigned char* src, *dst; src = dst = m_background_buffer; if (dy < 0) for (int y = rect.y; y < rect.y+rect.h; y++) memcpy(dst+y*m_store.stride+rect.x*4, src+(y-dy)*m_store.stride+(rect.x+dx)*4, rect.w*4); else if (dy > 0) for (int y = rect.y+rect.h-1; y >= rect.y; y--) memcpy(dst+y*m_store.stride+rect.x*4, src+(y-dy)*m_store.stride+(rect.x+dx)*4, rect.w*4); else if (dx) for (int y = rect.y; y < rect.y+rect.h; y++) memmove(dst+y*m_store.stride+rect.x*4, src+(y-dy)*m_store.stride+(rect.x+dx)*4, rect.w*4); } } CGImageRef CocoaVEGAWindow::CreateImageForRect(OpRect rect) { return CGImageCreateWithImageInRect(m_image, CGRectMake(rect.x, rect.y, rect.width, rect.height)); } /* static */ void CocoaVEGAWindow::ReleasePainter(CGContextRef& painter, CGDataProviderRef& provider) { CGContextRelease(painter); CGDataProviderRelease(provider); } int CocoaVEGAWindow::getBytesPerLine() { if (m_image) { return CGImageGetBytesPerRow(m_image); } return 0; } void CocoaVEGAWindow::ClearBuffer() { m_bg_rgn.Reset(); MDE_RECT rect = {0,0,m_store.width,m_store.height}; m_dirty_rgn.IncludeRect(rect); if (m_store.buffer) { op_memset(m_store.buffer, 0, m_store.stride * m_store.height); if (m_background_buffer) op_memset(m_background_buffer, 0, m_store.stride * m_store.height); } } void CocoaVEGAWindow::ClearBufferRect(const MDE_RECT &rect) { #ifdef VEGA_USE_HW if (m_3dwnd) { ((MacGlWindow*)m_3dwnd)->Erase(rect, true); } else #endif { m_bg_rgn.ExcludeRect(rect); m_dirty_rgn.IncludeRect(rect); if (m_background_buffer) { for (int y = rect.y; y<rect.y+rect.h; y++) { int offset = y*m_store.stride+rect.x*4; op_memset(m_background_buffer+offset, 0, rect.w*4); } } } } OP_STATUS CocoaVEGAWindow::initSoftwareBackend() { return OpStatus::OK; } #ifdef VEGA_USE_HW OP_STATUS CocoaVEGAWindow::initHardwareBackend(VEGA3dWindow* win) { m_3dwnd = win; return OpStatus::OK; } #endif // VEGA_USE_HW
#include<iostream> #define mutqagrel_zangvats int size = 0; std::cout << "Input the size of the Array : " ; std::cin >> size; int array [ size ]; std::cout << "Input the elements " << std::endl; for ( int index = 0; index < size; ++ index ) { std::cin >> array [ index ]; } #define hashvel_zangvatsi_mecaguyn_arjeqy int max = array [0]; for ( int index =0; index < size ; ++ index ) { if ( max < array [ index ] ) { max = array [ index ]; } } #define tpel_zangvatsi_mecaguyn_arjeqy std::cout << "Maximum value : " << max << std::endl; int main () { mutqagrel_zangvats hashvel_zangvatsi_mecaguyn_arjeqy tpel_zangvatsi_mecaguyn_arjeqy return 0; }
#include "pch.h" #include "Common.h" using namespace std; const string WHITESPACE = " \n\r\t\f\v"; string ltrim(const string& s) { size_t start = s.find_first_not_of(WHITESPACE); return (start == string::npos) ? "" : s.substr(start); } string rtrim(const string& s) { size_t end = s.find_last_not_of(WHITESPACE); return (end == string::npos) ? "" : s.substr(0, end + 1); } string trim(const string& s) { return rtrim(ltrim(s)); } void split(const string& s, string& left, string& right) { bool inBrackets = false; bool inMarks = false; if (s[0] == '[') { inBrackets = true; int i = 1; for (i = 1; i < s.size(); i++) { if (s[i] == ']') { inBrackets = false; } if ((s[i + 1] == ' ' || s[i + 1] == '\t') && !inBrackets) { break; } } left = s.substr(0, i + 1); right = s.substr(i + 1); right = trim(right); } else if (s[0] == '\"') { inMarks = true; int i = 1; for (i = 1; i < s.size(); i++) { if (s[i] == '\"') { inMarks = false; } if ((s[i + 1] == ' ' || s[i + 1] == '\t') && !inMarks) { break; } } left = s.substr(0, i + 1); right = s.substr(i + 1); right = trim(right); } else { auto i = s.find_first_of(WHITESPACE); left = s.substr(0, i); right = s.substr(i + 1); right = trim(right); } } void nextLine(ifstream& inStm, string& lineBuf, int& lineNum, string& tempLine, bool& error) { getline(inStm, lineBuf), lineNum++; // Preprocessing: check for comment, if any, delete it. if (lineBuf.find(" /*") != string::npos || lineBuf.find("\t/*") != string::npos) { if (lineBuf.find("*/") == string::npos) { tempLine = lineBuf; while (tempLine.find("*/") == string::npos && !inStm.eof()) { getline(inStm, tempLine), lineNum++; lineBuf += tempLine; } } if (!inStm.eof()) { auto comBegin = lineBuf.find(" /*"); if (comBegin == string:: npos) comBegin = lineBuf.find("\t/*"); auto comEnd = lineBuf.find("*/") + 1; lineBuf = lineBuf.erase(comBegin, comEnd - comBegin + 1); // MAY HAVE A PROBLEM! NOT SURE! } else { cout << "ERROR: Comment not finished." << endl; error = true; } } // Trim white spaces. lineBuf = rtrim(lineBuf); } bool read_parse_lex_file(string path, vector<string>& regedTermsVec, unordered_map<string, string>& regdMap, vector<RERule>& regexRulesVec, string& codeBegin, string& codeEnd) { ifstream inStm; inStm.open(path); if (!inStm) { cout << "File < " << path << "> NOT FOUND. FAILED." << endl; return false; } string lineBuf, tempLine, leftPart, rightPart, regex; int lineNum = 0; bool error = false; enum LexFileState{BEGIN, CONSTANT_DECLARATIONS, REGULAR_DEFINITIONS, TRANSITION_RULES, AUXILIARY_FUNCTIONS}; LexFileState state = BEGIN; vector<string> actions; while (!inStm.eof() && !error) { if (state == CONSTANT_DECLARATIONS || state == AUXILIARY_FUNCTIONS) { getline(inStm, lineBuf), lineNum++; } else { nextLine(inStm, lineBuf, lineNum, tempLine, error); if (lineBuf.empty()) continue; } switch (state) { case BEGIN: if (lineBuf.compare("%{") == 0) state = CONSTANT_DECLARATIONS; else { cout << "File <" << path << "> NOT FOUND. FAILED." << endl; error = true; } break; case CONSTANT_DECLARATIONS: if (lineBuf.compare("%}") == 0) state = REGULAR_DEFINITIONS; else if (inStm.eof()) { cout << "ERROR: No exit token <%}> after constant declarations." << endl; error = true; } else { codeBegin += lineBuf + "\n"; } break; case REGULAR_DEFINITIONS: if (lineBuf.compare("%%") == 0) state = TRANSITION_RULES; else { split(lineBuf, leftPart, rightPart); regdMap[leftPart] = rightPart; regedTermsVec.push_back(leftPart); } break; case TRANSITION_RULES: if (lineBuf.compare("%%") == 0) state = AUXILIARY_FUNCTIONS; else { lineBuf = trim(lineBuf); split(lineBuf, leftPart, rightPart); regex = leftPart; if (rightPart.compare("{") == 0 ) { // Only allow content in a new line. nextLine(inStm, lineBuf, lineNum, tempLine, error), lineBuf = trim(lineBuf); while (lineBuf.compare("}") != 0 && !inStm.eof()) { actions.push_back(lineBuf); nextLine(inStm, lineBuf, lineNum, tempLine, error); lineBuf = trim(lineBuf); } if (inStm.eof()) { cout << "ERROR: Incomplete regular expression - action sequence format (missing '}')." << endl; error = true; } else { regexRulesVec.push_back(RERule{ regex, actions }); actions.clear(); } } else { actions.push_back(rightPart); regexRulesVec.push_back(RERule{ regex, actions }); actions.clear(); } } break; case AUXILIARY_FUNCTIONS: codeEnd += lineBuf + "\n"; break; default: break; } } if (error) { cout << "at: Line " << lineNum << endl; return false; } inStm.close(); return true; }
/* ID: andonov921 TASK: lamps LANG: C++ */ #include <iostream> #include <vector> #include <queue> #include <stack> #include <map> #include <set> #include <unordered_map> #include <unordered_set> #include <string> #include <algorithm> #include <sstream> #include <climits> #include <fstream> #include <cmath> using namespace std; /// ********* debug template by Bidhan Roy ********* template < typename F, typename S > ostream& operator << ( ostream& os, const pair< F, S > & p ) { return os << "(" << p.first << ", " << p.second << ")"; } template < typename T > ostream &operator << ( ostream & os, const vector< T > &v ) { os << "{"; typename vector< T > :: const_iterator it; for( it = v.begin(); it != v.end(); it++ ) { if( it != v.begin() ) os << ", "; os << *it; } return os << "}"; } template < typename T > ostream &operator << ( ostream & os, const set< T > &v ) { os << "["; typename set< T > :: const_iterator it; for ( it = v.begin(); it != v.end(); it++ ) { if( it != v.begin() ) os << ", "; os << *it; } return os << "]"; } template < typename T > ostream &operator << ( ostream & os, const unordered_set< T > &v ) { os << "["; typename unordered_set< T > :: const_iterator it; for ( it = v.begin(); it != v.end(); it++ ) { if( it != v.begin() ) os << ", "; os << *it; } return os << "]"; } template < typename F, typename S > ostream &operator << ( ostream & os, const map< F, S > &v ) { os << "["; typename map< F , S >::const_iterator it; for( it = v.begin(); it != v.end(); it++ ) { if( it != v.begin() ) os << ", "; os << it -> first << ": " << it -> second ; } return os << "]"; } template < typename F, typename S > ostream &operator << ( ostream & os, const unordered_map< F, S > &v ) { os << "["; typename unordered_map< F , S >::const_iterator it; for( it = v.begin(); it != v.end(); it++ ) { if( it != v.begin() ) os << ", "; os << it -> first << ": " << it -> second ; } return os << "]"; } #define debug(x) cerr << #x << " = " << x << endl; typedef long long LL; typedef pair<int, int> PII; typedef pair<LL, LL> PLL; typedef vector<bool> VB; typedef vector<int> VI; typedef vector<LL> VLL; typedef vector<string> VS; typedef vector<VB> VVB; typedef vector<VI> VVI; typedef vector<VLL> VVLL; typedef vector<VS> VVS; ifstream fin("lamps.in"); ofstream fout("lamps.out"); int num_lamps, buttons_pressed; const int CYCLE_SIZE = 6; int init_conf = (1 << CYCLE_SIZE) - 1; int ison = 0, known = 0; int x; bool solved = false; int MASK_ALL = 0x3F; int MASK_ODD = 0x2A; int MASK_EVEN = 0x15; int MASK_K = 0x09; int flip[4] = { MASK_ALL, MASK_ODD, MASK_EVEN, MASK_K }; string to_binary(int x){ string s(num_lamps, ' '); for(int i=0;i<num_lamps;i++){ int bit = 1 << (i % CYCLE_SIZE); if(x & bit) s[i] = '1'; else s[i] = '0'; } return s; } void read_input(){ fin >> num_lamps; fin >> buttons_pressed; while(fin >> x && x != -1){ x--; int bit = 1 << (x % CYCLE_SIZE); ison |= bit; known |= bit; } while(fin >> x && x != -1){ x--; int bit = 1 << (x % CYCLE_SIZE); if(ison & bit){ fout << "IMPOSSIBLE\n"; solved = true; return; } known |= bit; } } bool check(int conf){ for(int i=0;i<CYCLE_SIZE;i++){ int bit = 1 << i; if(!(known & bit)) continue; // bit can be whatever if not known // Return false if conf has set bit and its not set in final_conf if((conf & bit) && !(ison & bit)) return false; // Return false if conf has not set bit and final_conf has it set if(!(conf & bit) && (ison & bit)) return false; } return true; } void solve(){ if(solved) return; set<string> solution; int limit = 1 << 4; for(int i=0;i<limit;i++){ int tmp_conf = init_conf; int ones = 0; for(int j=0;j<4;j++){ if(i & (1 << j)){ ones++; tmp_conf = tmp_conf ^ flip[j]; } } if(buttons_pressed == 0 && ones != 0) continue; if(buttons_pressed == 1 && ones != 1) continue; if(check(tmp_conf)) solution.insert(to_binary(tmp_conf)); } if(!solution.size()){ fout << "IMPOSSIBLE\n"; return; } for(auto sol : solution){ fout << sol << "\n"; } } int main(){ ios_base::sync_with_stdio(false); cin.tie(NULL); read_input(); solve(); return 0; }
#include <iostream> #include <vector> #include <queue> using namespace std; int main() { priority_queue< vector<int> > pq; pq.push( {1,200} ); pq.push( {1,2,3,4,5} ); pq.push( {1,2,3,4,5,6} ); pq.push( {1,2,3,4} ); pq.push( {1,2,3,5} ); pq.push( {-2,3} ); pq.push( {4,1} ); while (!pq.empty() ) { auto x = pq.top(); pq.pop(); for (auto y : x) { cout << y << ", "; } cout << endl; } }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4; c-file-style:"stroustrup" -*- ** ** Copyright (C) 1995-2007 Opera Software AS. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. ** */ #ifndef WINDOWS_DESKTOP_GLOBAL_APPLICATION_H #define WINDOWS_DESKTOP_GLOBAL_APPLICATION_H #include "adjunct/desktop_pi/DesktopGlobalApplication.h" #include "platforms/windows/pi/WindowsOpTaskbar.h" // Implementation of platform hooks for events that affect the Opera application class WindowsDesktopGlobalApplication : public DesktopGlobalApplication { public: WindowsDesktopGlobalApplication(); ~WindowsDesktopGlobalApplication(); //implementing DesktopGlobalApplication virtual void OnStart(); virtual void Exit(); virtual void ExitStarted(); virtual BOOL OnConfirmExit(BOOL /*exit*/) {return FALSE;} virtual void OnHide(); virtual void OnShow(); WindowsOpTaskbar *GetTaskbar() { return m_taskbar; } private: WindowsOpTaskbar* m_taskbar; }; #endif //WINDOWS_DESKTOP_GLOBAL_APPLICATION_H
// Copyright (c) 2021 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 _Poly_MeshPurpose_HeaderFile #define _Poly_MeshPurpose_HeaderFile //! Purpose of triangulation using. typedef unsigned int Poly_MeshPurpose; enum { // main flags Poly_MeshPurpose_NONE = 0, //!< no special use (default) Poly_MeshPurpose_Calculation = 0x0001, //!< mesh for algorithms Poly_MeshPurpose_Presentation = 0x0002, //!< mesh for presentation (LODs usage) // special purpose bits (should not be set externally) Poly_MeshPurpose_Active = 0x0004, //!< mesh marked as currently active in a list Poly_MeshPurpose_Loaded = 0x0008, //!< mesh has currently loaded data Poly_MeshPurpose_AnyFallback = 0x0010, //!< a special flag for BRep_Tools::Triangulation() to return any other defined mesh, // if none matching other criteria was found user-defined flags should have higher values Poly_MeshPurpose_USER = 0x0020 //!< application-defined flags }; #endif // _Poly_MeshPurpose_HeaderFile
#ifndef CLIENTSOCKET_H #define CLIENTSOCKET_H #include "platform/types.h" #include "IFileManager.h" #include "IFileMP2.h" #include "framework.h" #include "isessionmanager.h" #include "wbaseobject.h" #include "wmsgqueue.h" #include "wthread.h" #include "IWMultiWhiteBoard.h" #include "MultiWBMsgProcessor.h" #include "kernel/core/EZWBDef.h" #include "MsgHandler.h" #include "MsgList.h" using namespace WBASELIB; using namespace eztalks; class ClientSocket : public WThread ,public MsgHandler ,public IXMLDocMsgReaderCallback ,public INetWorkRequest { public: ClientSocket(); virtual ~ClientSocket(); BOOL Initialized(ISessionManager2 *pSessionManager,IComponentFactory *pFactory,IFileManager *pNetFileManager,const WBASE_NOTIFY &notify,FUNC_MSGTOMAIN funcMsgToMain); BOOL Create(const GUID *pGuid,DWORD dwUserID,DWORD dwCheckCode,WORD wAppID,const CHAR *lpszSrvAddrLink); void SetNetWorkResponse(INetWorkResponse *pResponse); void SetWBSinkSource(FUNC_WBSINK funcWbSink); BOOL IsWBLogin(); UINT GetWBServerStatus(); public: virtual bool handleMsg(void* pMsg);//UI调用接口 virtual FS_UINT32 ThreadProcEx(); virtual LRESULT OnSessionNotify(UINT nMsgID,WPARAM wParam,LPARAM lParam,FS_UINT32 dwReserved,FS_UINT dwUserData); void ProcessSessionEvent(SESSION_EVENT *pEvent); /// ///\brief 响应接口,IXMLDocMsgReaderCallback, /// public: virtual BOOL OnLoginRep( WORD wResult ); virtual BOOL OnBye(); virtual BOOL OnGetDocRep( CHAR *szDocData,DWORD dwDataLen ); virtual BOOL OnClearDoc(); virtual BOOL OnInsertDocNode( BYTE bInsertType,BYTE bOnlyOne,CHAR* szParentPath,CHAR* szInsertPosPath,CHAR* szNodeData ); virtual BOOL OnModifyDocNode( CHAR *szNodePath,CHAR *szNodeData ); virtual BOOL OnDelDocNode( CHAR *szNodePath ); public: /// ///\brief 网络请求接口INetWorkRequest,供EZWhiteBoard调用。(主讲共享时请求服务器) /// //添加白板 virtual void RequestAddWB(IContainerView *pWB); //添加图元 virtual void RequestAddDrawObject(int32_t nWBId,int nPage,IDrawObject *pDrawObj); //激活白板 virtual void RequestActiveWB(int32_t nWBId); //修改图元 virtual void RequestModifyDrawObject(int32_t nWBId,int nPage,IDrawObject *pDrawObj); //缩放白板 virtual void RequestModifyZoom(int32_t nWBId,int nPage,int nZoom); //指示器位置 virtual void RequestModifyIndicator(int32_t nWBId,int nX,int nY); //滚动条位置 virtual void RequestModifyScroll(int32_t nWBId,int nX,int nY); //旋转白板 virtual void RequestRotate(int32_t nWBId,int nAngle); //设置背景色 virtual void RequestBkColor(int32_t nWBId,int32_t nRgbaColor); //关闭白板 virtual void RequestCloseWB(int32_t nWBId); //关闭所有白板 virtual void RequestCloseAllWB(); //删除图元 virtual void RequestDelDrawObject(int32_t nWBId,int nPage,int nObjId); private: /// ///\brief 对服务器响应,私有,供服务器响应函数调用。INetWorkResponse /// void LoadActionElement(DWORD dwWBID, TiXmlElement *pElement); void LoadWBElement(TiXmlElement *pElement); void LoadSelElement(TiXmlElement *pElement); void LoadFileListElement(DWORD dwWBID, TiXmlElement *pElement); void LoadWBFileElement(DWORD dwWBID, TiXmlElement *pElement); void LoadToolElement(DWORD dwWBID, TiXmlElement *pElement); void LoadRotateElement(DWORD dwWBID, TiXmlElement *pElement); void LoadBkColorElement(DWORD dwWBID, TiXmlElement *pElement); void LoadScrollElement(DWORD dwWBID, TiXmlElement *pElement); void LoadDocElement(DWORD dwWBID, TiXmlElement *pElement); void LoadIndicatorElement(DWORD dwWBID, TiXmlElement *pElement); void LoadDrawObjectElement(DWORD dwWBID,int nPage, TiXmlElement *pElement,BOOL bModifyOrNew = FALSE); private: /// ///\brief 数据包协议相关 /// void AppendToolElement(TiXmlElement*pElement,int nPage,int nZoom); void AppendRotateElement(TiXmlElement*pElement,int nAngle); void AppendBkColorElement(TiXmlElement*pElement,int nColor); void AppendIndicatorElement(TiXmlElement*pElement,int nX,int nY); void AppendDocElement(TiXmlElement*pElement,IDoc *pDoc); void AppendPageElement(TiXmlElement*pElement,int nIdx,IPage *pPage); void AppendDrawObjectElement(TiXmlElement*pElement,IDrawObject *pDrawObj); void AppendScrollElement(TiXmlElement*pElement,int nX,int nY,int nCxRate,int nCyRate); void AppendActionElement(TiXmlElement*pElement,const char*szName); private: BOOL CreateSession(WORD wAppID,const CHAR *lpszSrvAddrLink); BOOL SendNotify(int nEvent); CHAR*ParsePath( CHAR* szPath,CHAR** szName,CHAR** szAttributeName,CHAR** szAttributeValue ); private: ISessionManager2 *m_pSessionManager;//白板组件的会控。接受服务器事件 IComponentFactory *m_pFactory; IFileManager *m_pNetFileManager; WBASE_NOTIFY m_Notify; FUNC_MSGTOMAIN m_fcMainThreadCall; FUNC_WBSINK m_fcWbSink; GUID m_guid; DWORD m_dwUserID; DWORD m_dwCheckCode; WORD m_wSrvAppID; std::string m_strSrvAddrLink; WORD m_wSessionID; BOOL m_bRun; IMemoryAllocator *m_pMemoryAllocator; WElementAllocator<CMsgMpNode>m_NetMsgAllocator; WMsgQueue<CMsgMpNode> m_NetMsgQueue; CMultiWBMsgProcessor m_WBMsgProcessor; INetWorkResponse *m_pResponse;//服务器事件响应器(白板) BOOL m_bFirstWB; BOOL m_bWbLogin; UINT m_nWBServerStatus; }; #endif // CLIENTSOCKET_H
/* * Copyright (c) 2018-2021 Morwenn * SPDX-License-Identifier: MIT */ #include <algorithm> #include <functional> #include <type_traits> #include <utility> #include <vector> #include <catch2/catch.hpp> #include <cpp-sort/sorter_facade.h> #include <cpp-sort/sorter_traits.h> #include <cpp-sort/sorters/selection_sorter.h> #include <cpp-sort/utility/adapter_storage.h> #include <cpp-sort/utility/functional.h> namespace { //////////////////////////////////////////////////////////// // Dummy adapter template<typename Sorter> struct dummy_adapter_impl: cppsort::utility::adapter_storage<Sorter> { dummy_adapter_impl() = default; explicit constexpr dummy_adapter_impl(Sorter&& sorter): cppsort::utility::adapter_storage<Sorter>(std::move(sorter)) {} template< typename ForwardIterator, typename Compare = std::less<>, typename Projection = cppsort::utility::identity > auto operator()(ForwardIterator first, ForwardIterator last, Compare compare={}, Projection projection={}) const -> std::enable_if_t<cppsort::is_projection_iterator_v< Projection, ForwardIterator, Compare >> { this->get()(first, last, compare, projection); } }; template<typename Sorter> struct dummy_adapter: cppsort::sorter_facade<dummy_adapter_impl<Sorter>> { dummy_adapter() = default; explicit constexpr dummy_adapter(Sorter sorter): cppsort::sorter_facade<dummy_adapter_impl<Sorter>>(std::move(sorter)) {} }; //////////////////////////////////////////////////////////// // Immutable & non-empty sorter struct non_empty_sorter_impl { int dummy1=0, dummy2=0; non_empty_sorter_impl() = default; constexpr non_empty_sorter_impl(int a, int b): dummy1(a), dummy2(b) {} template< typename Iterator, typename Compare = std::less<>, typename = std::enable_if_t< not cppsort::is_projection_iterator_v<Compare, Iterator> > > auto operator()(Iterator first, Iterator last, Compare compare={}) const -> void { std::sort(std::move(first), std::move(last), std::move(compare)); } using iterator_category = std::random_access_iterator_tag; using is_always_stable = std::false_type; }; struct non_empty_sorter: cppsort::sorter_facade<non_empty_sorter_impl> { non_empty_sorter() = default; non_empty_sorter(int a, int b): cppsort::sorter_facade<non_empty_sorter_impl>(a, b) {} }; } TEST_CASE( "test correct adapter_storage behavior", "[adapter_storage]" ) { std::vector<int> arr = { 2, 8, 7, 4, 3, 6, 0, 1, 2, 8, 6, 9 }; SECTION( "with an immutable empty sorter" ) { cppsort::selection_sorter original_sorter{}; auto adapted_sorter = dummy_adapter<cppsort::selection_sorter>(original_sorter); adapted_sorter(arr); CHECK( std::is_sorted(std::begin(arr), std::end(arr)) ); } SECTION( "with an immutable non-empty sorter" ) { non_empty_sorter original_sorter(5, 8); auto adapted_sorter = dummy_adapter<non_empty_sorter>(original_sorter); adapted_sorter(arr); CHECK( std::is_sorted(std::begin(arr), std::end(arr)) ); } }
#include<bits/stdc++.h> using namespace std; int as[100000]; main() { int n, k; while(cin>>n>>k) { int i, d, c=0; for(i=1; i<=n; i++) { cin>>d; if(d+k<=5)c++; } cout<<c/3<<endl; } return 0; }
#include "Log.h" #include "Misc.h" #include "ResourcesManager.h" std::ostream& log( const LogType &t ) { switch( t ) { case LOG_DEBUG: std::cout << "[DBG] "; break; case LOG_WARNING: std::cout << "[WRN] "; break; case LOG_ERROR: std::cout << "[ERR] "; break; case LOG_FATAL: std::cout << "[/!\\] "; break; default: std::cout << "[***] "; break; } return std::cout; }
#ifndef VENTA_H #define VENTA_H #include <mysql_connection.h> #include <cppconn/driver.h> #include <cppconn/exception.h> #include <cppconn/resultset.h> #include <cppconn/statement.h> using namespace std; class Venta { public: Venta(); Venta(sql::ResultSet*); virtual ~Venta(); int getVenID(); void setVenID(int); int getCliID(); void setCliID(int); int getTipID(); void setTipID(int); double getImporte(); void setImporte(double); void fillObject(sql::ResultSet*); string toString(); protected: private: int venID; int cliID; int tipID; double importe; }; #endif // VENTA_H
// // Copyright (C) BlockWorks Consulting Ltd - All Rights Reserved. // Unauthorized copying of this file, via any medium is strictly prohibited. // Proprietary and confidential. // Written by Steve Tickle <Steve@BlockWorks.co>, September 2014. // #ifndef __UARTRECEIVER8N1_HPP__ #define __UARTRECEIVER8N1_HPP__ #include <stdint.h> template <uint32_t period, uint32_t ticksPerBit, uint8_t rxMask, uint32_t fifoDepth> class UARTReceiver8N1 { public: uint32_t GetPeriod() { return period; } void ProcessNegativeEdge( uint32_t timestamp ) { if(startDetected == false) { // // Start of byte. // startDetected = true; timestampOfStartBit = timestamp; bitNumber = 0; currentByte = 0; } else { // // Within byte. // } currentLevel = 0; } void ProcessPositiveEdge( uint32_t timestamp ) { currentLevel = 1; } void PeriodicProcessing( uint32_t timestamp, uint8_t inputValue, uint8_t& outputValue ) { currentByte <<= 1; currentByte |= currentLevel; bitNumber++; if(bitNumber >= 10) { startDetected = false; } } uint32_t timestampOfStartBit = 0; bool startDetected = false; uint8_t currentByte = 0; uint8_t currentLevel = 0; uint8_t bitNumber = 0; }; #endif
#ifndef RESOURCEMANAGER_CPP #define RESOURCEMANAGER_CPP #include "ResourceManager.h" #include "Interface.cpp" ResourceManager::ResourceManager() {//the constructor. not much to construct. just need to initalize the local variables. IDc = 1; freeCount = 1; //assign the interface to UID 1. leases.push_back(new Lease(1, globalIn, 65535)); } ResourceManager::~ResourceManager() {//clear out them local variables! IDc = 0; freeCount = -1; } UID ResourceManager::RequestID() {//This method is used to get an ID. I'll probably have to make this thread safe later, but i'm not //going to concern myself with threads for now. //increment the ID number. this makes sure that 0 will never be an ID. ++IDc; //create a new lease for that that ID. Lease *temp = new Lease(IDc); //push that lease into the vector. leases.push_back(temp); //return the new ID return(IDc); } bool ResourceManager::AssignID(UID val, Object* foo) {//this method is used to assign a requested ID to a given object. if the assignment succeeds then //it will return true, if it fails in anyway, it will return false. best plan at that //point is to just ask for a new ID, they are cheap. //find the ID in question amongst the leases int idLoc = findLease(val); //if the lease does not exist, there is no way it can be assigned with certainty that the //resource manager will know. return false if(idLoc == -1) return false; //since there seems to be a lease, get a pointer to the lease. Lease *temp = leases[idLoc]; //if the lease has a refcount greater than 0, then it can't be used as it has already been //assigned to a different object. return false. if(temp->refCount != 0) return false; //so the lease exists and isn't already in use. The lease is then granted, save the //reference to the object that now owns the lease in the lease. temp->pointer = foo; //increment the reference counter on the lease to reflect that the lease now has an owner. ++(temp->refCount); //assignment successful. return true; } bool ResourceManager::RetainID(UID val) {//this method tells the resource manager that some one else is now has interest in this object. //the difference here from AssignID is that if refCount == 0 this method will fail, this //method does not exist to be the assigner of the object, only to make certain its //persistance beyond the inital user declaring it doesn't need it. //find the lease in question. int idLoc = findLease(val); //if the lease does not exist, there is no way it could be incremented. return false. if(idLoc == -1) return false; //so the lease exists. fetch pointer to said lease. Lease *temp = leases[idLoc]; //if the reference count is 0, the lease has not been assigned, and therefore cannot be //retained, as there is nothing to retain. if(temp->refCount == 0) return false; //increment the refCount to reflect the extra interest. ++(temp->refCount); //retenation successful. return true; } Object* ResourceManager::GetIDRetaining(UID val) {//these two methods are as the sound, both will return a pointer to the object of the lease //you request. but one will increase the ref count, one won't. there are valid uses for //both cases, and so both methods exist. int idLoc = findLease(val); if(idLoc == -1) return NULL; Lease *temp = leases[idLoc]; if(temp->refCount == 0) return NULL; ++(temp->refCount); return temp->pointer; } Object* ResourceManager::GetIDNonRetaining(UID val) { TRACE(2); int idLoc = findLease(val);TRACE(5); if(idLoc == -1) return NULL; Lease *temp = leases[idLoc];TRACE(5); if(temp->refCount == 0) return NULL; TRACE(5); return temp->pointer; } void ResourceManager::Release(UID val) {//this does the opposite of retain. it frees up a lease. if this takes the refcount to 0, //it also then deals with the garbage colleting. int idLoc = findLease(val); if(idLoc == -1) return; Lease *temp = leases[idLoc]; if(temp->refCount == 0) return; } int ResourceManager::findLease(UID val) { TRACE(2); //this is a simple binary search for the lease requested by UID. Because I can depend on //vector keeping things in chronological order, and I know that the ID's are given out //sequentially, I know that the object isn't going to be any higher than its ID number. //further, it can only be as low as the number of releases that have happened. this means //that the lowest possible location is the ID - the freeCount. If there were 1m objects //this would take 20 searches with out this trick. with this trick the number can be //as low as 1 if there have been no releases, with a probable case of like 6-8. woohoo! int high = val; int low = val - freeCount; int mid;TRACE(5); for(mid = low + ((high - low)/2);mid != low && leases[mid]->ID != val;) { TRACE(3); if(leases[mid]->ID > val) low = mid; else if(leases[mid]->ID < val) high = mid; else return mid; TRACE(5); mid = low + ((high - low)/2);TRACE(5); } TRACE(5); printf("high: %i mid: %i low: %i \n",high, mid, low); if(mid != -1 && leases[mid]->ID == val) { TRACE(5); return mid; } TRACE(5); return -1; } UID ResourceManager::isDuplicate(const char* val) {//checks to see if the requested load is a duplicate. if it is a duplicate, then don't load it! //just simply send them the one that already exists. //this functionality is yet to come truth be told. but the connections are all in place! if(loaded.count(val)==0) return false;//place holder function, i'll flush this out later. return loaded[val]; } UID ResourceManager::LoadMesh(const char* filename) {//load a Mesh object. this pulls in a .obj file and does the nescessary resource manageing on it. //first check for duplication. UID temp = isDuplicate(filename); //if it is a duplicate, fantastic, return the object it is already loaded, we are done. if(temp != 0) return temp; //if it isn't a duplicate, create the new Mesh. Mesh* val = new Mesh(filename); //get a new ID for this mesh. temp = RequestID(); //assign the ID to the mesh. val->assignID(temp); if(AssignID(temp,val)) {//if the assignment succeeds, then return the newly loaded mesh. loaded[filename] = temp; return temp; } //if it fails. deallocate it and return 0 delete val; return 0; } ResourceManager::Lease::Lease(UID val, Object* foo, unsigned short int bar) {//constructor for a lease where all values are know for the begining. ID = val; pointer = foo; refCount = bar; } ResourceManager::Lease::Lease(UID val) {//constructor for a lease when only the Identifier is known ID = val; pointer = NULL; refCount = 0; } ResourceManager::Lease::~Lease() {//destructor for a lease. ID = 0; pointer = NULL; refCount = 0; } bool ResourceManager::onEvent(const Event& event) { TRACE(5); return false; } bool ResourceManager::RegisterLTI(string val, UID bar) { TRACE(4); if(ResolveLTI(val) == true) return false; TRACE(4); LTIReg[val] = bar; TRACE(4); } UID ResourceManager::ResolveLTI(string val) { TRACE(4); if(LTIReg.count(val)==0) { TRACE(4); return false;//place holder function, i'll flush this out later. } TRACE(4); return LTIReg[val]; } void ResourceManager::RegisterRequest(const Event& val) { DeReqs.push_back(val); } void ResourceManager::ResolveRequests() {//this method resolves load time idetifier requests to link the system up to itself in a non //heirachial manner. TRACE(2); while(DeReqs.size()) { TRACE(5); if (DeReqs[0].receiver == (UID)1) { TRACE(5); globalIn->onEvent(DeReqs[0]); TRACE(5); } else { TRACE(5); GetIDNonRetaining(DeReqs[0].receiver)->onEvent(DeReqs[0]); TRACE(5); } TRACE(5); DeReqs.erase(DeReqs.begin()); } TRACE(1); } #endif /*.S.D.G.*/
#ifndef CODEGEN_H #define CODEGEN_H #include <list> #include <map> #include <vector> #include <string> #include "symbol_table.h" using namespace std; enum machine_function{ MF_ADD_I, MF_ADD_F, MF_MULT_I, MF_MULT_F, MF_DIV_I, MF_DIV_F, MF_COMP_I, MF_COMP_F, MF_J, MF_JE, MF_JNE, MF_JL, MF_JLE, MF_JG, MF_JGE, MF_MOVE, MF_INT_TO_FLOAT, MF_FLOAT_TO_INT, MF_STORE_I, MF_STORE_F, MF_LOAD_I, MF_LOAD_F, MF_PUSH_I, MF_PUSH_F, MF_POP_I, MF_POP_F, MF_PRINT_INT, MF_PRINT_FLOAT, MF_PRINT_STRING }; enum boolean_mode{ MODE_IF_GOTO_ELSE_FALL, MODE_IFNOT_GOTO_ELSE_FALL, MODE_IF_GOTO_ELSE_GOTO, MODE_IFNOT_GOTO_ELSE_GOTO }; class Codegen { vector<string> code; list<int> requested_labels; list<string> registers; public: map<string,data_type> register_content; Codegen(); static string convert_machine_function(machine_function command); int insert_code(string command); int insert_code(machine_function command, string arg1="NULL", string arg2="NULL", string arg3="NULL"); int insert_code(machine_function command, double arg1, string arg2); int insert_code(machine_function command, float arg1, string arg2); int insert_code(machine_function command, int arg1, string arg2="NULL"); string mem_offset(string reg, int offset=0); string mem_offset(string reg, string offset); string create_function_string(string function_identifier, list<SymbolEntry> &locals,int position); int get_size(); string get_register(string reg_name = ""); string front_register(); void put_register(string reg); void swap(); int nextinstr(); void print(); pair<int,int> boolean_code(string reg, boolean_mode mode, int type = 0); int make_boolean(string reg, int type = 0); int backpatch(int line, int target); int backpatch(list<int> l, int target); int add_label(int line); int add_comment(string comment); list<string> caller_saved_registers(); list<string> get_current_registers(); }; // Codegen Generator; #endif
#include "mini/RandomChance/randomchance.h" #include "ui_randomchance.h" #include <stdlib.h> /**************** * Do not modify ****************/ RandomChance::RandomChance(QWidget *parent) : QDialog(parent, Qt::CustomizeWindowHint | Qt::WindowTitleHint ), Minigame(), ui(new Ui::RandomChance) { ui->setupUi(this); ui->b_ok->setEnabled(false); configureGame(); } /**************** * Clean all minigame code ****************/ RandomChance::~RandomChance() { for(int i = 0; i < num; i++) delete this->tile[i]; delete ui; } /******** PRIVATE **********/ /**************** * Configure minigame ****************/ void RandomChance::configureGame() { srand(time(0)); int unique = rand() % 4; QSizePolicy policy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding); for(int i = 0; i < num; i++) { if(i == unique) tile[i] = new RandomChanceTile(i, true, this); else tile[i] = new RandomChanceTile(i, false, this); tile[i]->setSizePolicy(policy); connect(tile[i], SIGNAL(clicked()), this, SLOT(on_b_tile_clicked())); } tile[0]->setText(QString("Is this the \nright box?")); tile[1]->setText(QString("Choose carefully!")); tile[2]->setText(QString("Pick me!")); tile[3]->setText(QString("Oh no, \npick the other box!")); ui->g_grid->addWidget(tile[0], 0, 0); ui->g_grid->addWidget(tile[1], 0, 1); ui->g_grid->addWidget(tile[2], 1, 0); ui->g_grid->addWidget(tile[3], 1, 1); } void RandomChance::disableGame() { for(int i = 0; i < num; i++) this->tile[i]->setEnabled(false); } /**************** * Do not modify ****************/ void RandomChance::setWin() { Minigame::setWin(); ui->t_result->setText(QString("Win!")); ui->t_result->setAlignment(Qt::AlignCenter); } /**************** * Do not modify ****************/ void RandomChance::setLose() { Minigame::setLose(); ui->t_result->setText(QString("Lose!")); ui->t_result->setAlignment(Qt::AlignCenter); } /**************** * Do not modify ****************/ void RandomChance::quit() { Minigame::quit(); disableGame(); ui->b_ok->setEnabled(true); } /******** PRIVATE SLOTS **********/ /**************** * Set win or lose ****************/ void RandomChance::on_b_tile_clicked() { RandomChanceTile* tile = (RandomChanceTile*)sender(); if(tile->getUnique()) setWin(); else setLose(); quit(); } /**************** * Do not modify ****************/ void RandomChance::on_b_ok_clicked() { this->done(QDialog::Accepted); }
#include "Game.h" Game* g_game = 0; const int FPS = 60; const int DELAY_TIME = 1000.0f / FPS; int main(int argc, char* args[]) { /* g_game = new Game(); g_game->init("Game Class", 100, 100, 640, 480, 0); while(g_game->running()) { g_game->handleEvents(); g_game->update(); g_game->render(); SDL_Delay(10); } g_game->clean(); return 0;*/ if(TheGame::Instance()->init("Chapter1", 100, 100, 640, 480, false)) { Uint32 frameStart, frameTime; while(TheGame::Instance()->running()) { frameStart = SDL_GetTicks(); TheGame::Instance()->handleEvents(); TheGame::Instance()->update(); TheGame::Instance()->render(); frameTime = SDL_GetTicks() - frameStart; if(frameTime < DELAY_TIME) { SDL_Delay((int)(DELAY_TIME - frameTime)); } } /*while (TheGame::Instance()->running()) { TheGame::Instance()->handleEvents(); TheGame::Instance()->update(); TheGame::Instance()->render(); SDL_Delay(10); } } else { std::cout << "game init fail" << SDL_GetError() <<"\n"; return -1;*/ } TheGame::Instance()->clean(); return 0; }
// Scintilla source code edit control /** @file LexNull.cxx ** Lexer for no language. Used for plain text and unrecognized files. **/ // Copyright 1998-2001 by Neil Hodgson <neilh@scintilla.org> // The License.txt file describes the conditions under which this software may be distributed. #include <string.h> #include <assert.h> #include <ctype.h> #include <algorithm> #include "ILexer.h" #include "Scintilla.h" #include "SciLexer.h" #include "WordList.h" #include "LexAccessor.h" #include "Accessor.h" #include "StyleContext.h" #include "CharacterSet.h" #include "LexerModule.h" using namespace Scintilla; static void ColouriseNullDoc(Sci_PositionU startPos, Sci_Position length, int, LexerWordList, Accessor &styler) { // Null language means all style bytes are 0 so just mark the end - no need to fill in. if (length > 0) { styler.StartAt(startPos + length - 1); styler.StartSegment(startPos + length - 1); styler.ColourTo(startPos + length - 1, 0); } } static void FoldNullDoc(Sci_PositionU startPos, Sci_Position length, int /* initStyle */, LexerWordList, Accessor &styler) { if (styler.GetPropertyInt("fold") == 0) return; const Sci_Position maxPos = startPos + length; const Sci_Position maxLines = (maxPos == styler.Length()) ? styler.GetLine(maxPos) : styler.GetLine(maxPos - 1); // Requested last line const Sci_Position docLines = styler.GetLine(styler.Length()); // Available last line const bool foldCompact = styler.GetPropertyInt("fold.compact") != 0; // Backtrack to previous non-blank line so we can determine indent level // for any white space lines // and so we can fix any preceding fold level (which is why we go back // at least one line in all cases) int spaceFlags = 0; Sci_Position lineCurrent = styler.GetLine(startPos); int indentCurrent = Accessor::LexIndentAmount(styler, lineCurrent, &spaceFlags, NULL); while (lineCurrent > 0) { lineCurrent--; indentCurrent = Accessor::LexIndentAmount(styler, lineCurrent, &spaceFlags, NULL); if (!(indentCurrent & SC_FOLDLEVELWHITEFLAG)) break; } // Process all characters to end of requested range // Cap processing in all cases // to end of document (in case of unclosed quote at end). while ((lineCurrent <= docLines) && ((lineCurrent <= maxLines))) { // Gather info int lev = indentCurrent; Sci_Position lineNext = lineCurrent + 1; int indentNext = indentCurrent; if (lineNext <= docLines) { // Information about next line is only available if not at end of document indentNext = Accessor::LexIndentAmount(styler, lineNext, &spaceFlags, NULL); } int indentCurrentLevel = indentCurrent & SC_FOLDLEVELNUMBERMASK; if (indentNext & SC_FOLDLEVELWHITEFLAG) indentNext = SC_FOLDLEVELWHITEFLAG | indentCurrentLevel; // Skip past any blank lines for next indent level info while ((lineNext < docLines) && (indentNext & SC_FOLDLEVELWHITEFLAG)) { lineNext++; indentNext = Accessor::LexIndentAmount(styler, lineNext, &spaceFlags, NULL); } const int levelAfterBlank = indentNext & SC_FOLDLEVELNUMBERMASK; const int levelBeforeBlank = std::max(indentCurrentLevel, levelAfterBlank); // Now set all the indent levels on the lines we skipped // Do this from end to start. Once we encounter one line // which is indented more than the line after the end of // the blank-block, use the level of the block before Sci_Position skipLine = lineNext; int skipLevel = levelAfterBlank; while (--skipLine > lineCurrent) { int skipLineIndent = Accessor::LexIndentAmount(styler, skipLine, &spaceFlags, NULL); if (foldCompact) { if ((skipLineIndent & SC_FOLDLEVELNUMBERMASK) > levelAfterBlank) skipLevel = levelBeforeBlank; int whiteFlag = skipLineIndent & SC_FOLDLEVELWHITEFLAG; styler.SetLevel(skipLine, skipLevel | whiteFlag); } else { if ((skipLineIndent & SC_FOLDLEVELNUMBERMASK) > levelAfterBlank && !(skipLineIndent & SC_FOLDLEVELWHITEFLAG)) skipLevel = levelBeforeBlank; styler.SetLevel(skipLine, skipLevel); } } // Set fold header if (!(indentCurrent & SC_FOLDLEVELWHITEFLAG)) { if ((indentCurrent & SC_FOLDLEVELNUMBERMASK) < (indentNext & SC_FOLDLEVELNUMBERMASK)) lev |= SC_FOLDLEVELHEADERFLAG; } // Set fold level for this line and move to next line styler.SetLevel(lineCurrent, foldCompact ? lev : lev & ~SC_FOLDLEVELWHITEFLAG); indentCurrent = indentNext; lineCurrent = lineNext; } // NOTE: Cannot set level of last line here because indentCurrent doesn't have // header flag set; the loop above is crafted to take care of this case! //styler.SetLevel(lineCurrent, indentCurrent); } LexerModule lmNull(SCLEX_NULL, ColouriseNullDoc, "null", FoldNullDoc);
#include<iostream> #include<cstdio> #include<map> #include<set> #include<vector> #include<stack> #include<queue> #include<string> #include<cstring> #include<algorithm> #include<cmath> using namespace std; vector<char> a; bool cmp(char a,char b) { return a > b; } int main() { int n,k; while (scanf("%d",&n) != EOF) { a.clear(); for (int i = 0;i < n; i++) { scanf("%d",&k); a.push_back('0' + k); } sort(a.begin(),a.end(),cmp); int ok = 0; for (int i = a.size()-1;i >= 0; i--) if (a[i]%2) { char mid = a[i]; a.erase(a.begin() + i); a.push_back(mid); ok = 1; break; } if (ok && a[0] != '0') { for (int i = 0;i < a.size(); i++) printf("%c",a[i]); printf("\n"); } else printf("-1\n"); } return 0; }
// // Created by Cristian Marastoni on 24/04/15. // #include "NetAcceptor.h" #include "NetReactor.h" #include "../Socket.h" net::Status Acceptor::listen() { if(mSocket.open() != net::Ok) { return net::Error; } mSocket.setBlocking(false); mSocket.setReuseAddr(true); if(mSocket.bind(mAddress.port) != net::Ok) { mSocket.close(); return net::Error; } if(mSocket.listen(100) != net::Error) { mChannel = new Channel(mSocket.handle()); mChannel->setReadCallback(std::bind(&Acceptor::Accept, this)); mReactor->addChannel(mChannel); return net::Ok; }else { mSocket.close(); return net::Error; } } void Acceptor::stop() { if(mChannel != NULL) { mReactor->removeChannel(mChannel); delete mChannel; } mSocket.close(); } void Acceptor::Accept() { int count = 0; int MAX_ACCEPT = 100; net::socket_details::socket_t peerFd; IpAddress peerAddr; while(count < MAX_ACCEPT) { if(mSocket.accept(peerFd, peerAddr) == net::Ok) { if(mConnectionCallback) { mConnectionCallback(peerFd, peerAddr); }else { net::socket_details::close(peerFd); } } ++count; } }
#include "Interpolation.hpp" #include <algorithm> #include <stdexcept> #include <limits> #include <cmath> Interpolation::Interpolation(const std::vector<double>& x, const std::vector<double>& y) : x_(x), y_(y){ if (x.size() != y.size()){ throw std::runtime_error("Interpolation: differing input sizes"); } if (x.empty()){ throw std::runtime_error("Interpolation: no data"); } double last = -std::numeric_limits<double>::infinity(); for(double d: x_){ if (!std::isfinite(d) || d<=last){ throw std::runtime_error("Interpolation: x is not in order"); } last = d; } for(double d: y){ if(!std::isfinite(d)){ throw std::runtime_error("Interpolation: bad value in y"); } } } double Interpolation::get_simple(double new_x) const { if(!std::isfinite(new_x)){ throw std::runtime_error("Interpolation: bad new_x value in get"); } if (new_x<=x_.front()){ return y_.front(); } if (new_x>=x_.back()){ return y_.back(); } size_t index2=0; for(;index2<x_.size();++index2){ if(new_x<x_.at(index2)){ break; } } auto index1 = index2-1u; double fraction = (new_x-x_.at(index1))/(x_.at(index2)-x_.at(index1)); double y = y_.at(index1) + fraction*(y_.at(index2)-y_.at(index1)); return y; } //C++ has functions to find an element in a sorted vector, // and it is usually best to rely on them rather than to iterate manually. //std::lower_bound returns the earliest location where new_x can // be inserted such that the vector will remain ordered. //It uses an algorithm like https://en.wikipedia.org/wiki/Binary_search_algorithm . //If the vectors are very long, then this will be much quicker than get_simple. double Interpolation::get(double new_x) const { if(!std::isfinite(new_x)){ throw std::runtime_error("Interpolation: bad new_x value in get"); } auto it = std::lower_bound(x_.begin(), x_.end(), new_x); if (it==x_.begin()){//new_x<=x[0] return y_.front(); } if (it==x_.end()){//new_x>x.back() return y_.back(); } auto index2 = it-x_.begin(), index1 = index2-1u; double fraction = (new_x-x_.at(index1))/(x_.at(index2)-x_.at(index1)); double y = y_.at(index1) + fraction*(y_.at(index2)-y_.at(index1)); return y; } std::vector<double> Interpolation::get_many(const std::vector<double>& new_x) const { std::vector<double> y; //Not implemented return y; }
#ifndef exceptions_H_INCLUDE #define exceptions_H_INCLUDE #include<iostream> #include<fstream> #include<string> #include<sstream> #include<unordered_map> using std::istream; using std::ostream; using std::string; using std::unordered_map; using std::make_pair; using std::move; using std::getline; using namespace std; class exceptions{ public: exceptions(){}; bool Read(istream& istr); inline unordered_map<string, string>& getMap(){return exception;}; protected: unordered_map<string, string> exception; }; #endif
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 1995-2010 Opera Software ASA. All rights reserved. * * This file is part of the Opera web browser. * It may not be distributed under any circumstances. */ #ifndef GADGET_INSTALLER_CONTEXT_H #define GADGET_INSTALLER_CONTEXT_H #ifdef WIDGET_RUNTIME_SUPPORT #include "modules/util/OpSharedPtr.h" #include "modules/gadgets/OpGadgetClass.h" /** * The context of a gadget installation. * * The struct acts as a container for various installation-related data and * should not exhibit behavior. * * @author Wojciech Dzierzanowski (wdzierzanowski) */ struct GadgetInstallerContext { GadgetInstallerContext(); /** * Necessary, because OpString::OpString(const OpString&) is not really a * copy constructor. */ GadgetInstallerContext(const GadgetInstallerContext& rhs); GadgetInstallerContext& operator=(const GadgetInstallerContext& rhs); /** * A shortcut to obtain the gadget name from m_gadget_class. * * @return the gadget name as declared by the gadget author */ OpString GetDeclaredName() const; /** * A shortcut to obtain the author name from m_gadget_class. * * @return the gadget author name */ OpString GetAuthorName() const; /** * A shortcut to obtain the description from m_gadget_class. * * @return the gadget description */ OpString GetDescription() const; /** * A shortcut to obtain the path to the icon file. * * @return the path to the icon file relative to the root of the gadget * contents, or an empty string if the gadget has no icon */ OpString GetIconFilePath() const; /** * Represents the gadget to be installed. */ OpSharedPtr<OpGadgetClass> m_gadget_class; /** * The gadget display name. This should be the name that identifies the * gadget installation in the OS from the user's point of view, and is * displayed in shortcuts, etc. May be different than m_declared_name and * m_normalized_name. */ OpString m_display_name; /** * The normalized gadget display name. This should be the name that * identifies the gadget installation in the OS internally, and is used to * build path names, registry entries, etc. May be different than * m_declared_name and m_display_name. */ OpString m_normalized_name; /** * The gadget profile name. This is the name of the Opera profile directory * (just the directory, not the full path) used by a gadget installation. */ OpString m_profile_name; /** * The path to the installation destination directory. */ OpString m_dest_dir_path; /** * The requested shortcut deployment destinations. It is a bitfield with * one flag for each of the possible destinations. * * @see DesktopShortcutInfo::Destination */ INT32 m_shortcuts_bitfield; /** * The preferred OS command that starts the gadget once it's installed. */ OpString m_exec_cmd; /** * Do we want to deploy launcher scripts in platform specific places. */ BOOL m_create_launcher; /** * Do we want to install this gadget for all users, globally. */ BOOL m_install_globally; private: void CopyStrings(const GadgetInstallerContext& rhs); }; #endif // WIDGET_RUNTIME_SUPPORT #endif // GADGET_INSTALLER_CONTEXT_H
#pragma once /** * @file This File contains a template for an integration function as well * as a variety of numerical integration methods. To add additional * integration methods, one simply has to add additional methods * classes below. * source: rosettacode.org/wiki/Numerical_integration#C.2B.2B */ /** * The integration function requires an integration method and returns * the integral of the function f between boundaries a & b. * * @param f is the function to be integrated. eg. double f(double x){...} * @param a is the lower bound of the integral. * @param b is the upper bound of the integral. * @param steps denotes the number of steps to be taken between a & b. * @param m is an integration method according to which the integral is * evaluated. * @details An example to use this function would be: * double s = integrate(f, 0.0, 1.0, 100, simpson()); */ #include <iostream> #include <cmath> #include <vector> #include <boost/math/special_functions/bessel.hpp> using namespace std; template<typename Method, typename Function, typename Double> double integrate(Function f, Double a, Double b, int steps, Method m) { double s = 0; double h = (b-a)/steps; for (int i = 0; i < steps; ++i) s += m(f, a + h*i, h); return h*s; } /** * This is a very simple simpson integration function. */ template<typename Function> double integrate_simps(Function f, double a, double b, int steps) { int extrastep = 0; if (steps % 2 == 1){ //cout << "ERROR in integrator" << endl; //return 0; extrastep = 1; } if (steps <= 0) { cout << "ERROR, integrating with negative steps" << endl; cout << steps; } double stepsize = (b-a)/(double)(steps+extrastep); double res = f(a) + f(b); for (int n = 1; n < steps; ++n){ res += 4* f(a+n*stepsize); ++n; } for (int n = 2; n < steps - 1; ++n){ res += 2 * f(a+n*stepsize); ++n; } return res * stepsize / 3.0; } /** * This class contains the simpson integration method, any other methods * are to be added in the same manner. */ class simpson { public: template<typename Function, typename Double> double operator()(Function f, Double x, Double h) const { return (f(x) + 4.0*f(x+h/2.0) + f(x+h))/6.0; } }; //Trying to integrate oscillatory functions more efficiently. // Structure for Levin u tranformation NRp215 struct LevinU { vector<double> numer, denom; int n,ncv; bool cnvgd; double small, big; double eps,lastval,lasteps; LevinU(int nmax, double epss) : n(0), ncv(0), cnvgd(0), eps(epss), lastval(0.0) { small = 10.0E-308; big = 1.0E308; numer.resize(nmax); denom.resize(nmax); } double next(double sum, double omega, double beta = 1.0) { int j; double fact, ratio, term, val; term = 1.0/(beta+n); //carful with vectors denom[n] = term/omega; numer[n] = sum * denom[n]; if (n > 0) { ratio=(beta+n-1)*term; for (j = 1; j<=n; j++) { fact = (n-j+beta) * term; numer[n-j] = numer[n-j+1] - fact*numer[n-j]; denom[n-j] = denom[n-j+1] - fact*denom[n-j]; term = term * ratio; } } n++; val = abs(denom[0]) < small ? lastval : numer[0]/denom[0]; lasteps = abs(val-lastval); if (lasteps <= eps) ncv++; if (ncv >= 2) cnvgd = 1; return (lastval = val); } }; struct Base_interp { int n, mm, jsav, cor, dj; const double *xx, *yy; Base_interp(vector<double> &x, const double *y, int m) : n(x.size()), mm(m), jsav(0), cor(0), xx(&x[0]), yy(y) { dj = min(1, (int)pow((double)n, 0.25)); } double interp(double x) { int jlo = cor ? hunt(x) : locate(x); return rawinterp(jlo,x); } int locate(const double x); int hunt(const double x); double virtual rawinterp(int jlo, double x) = 0; }; struct Poly_interp : Base_interp { double dy; Poly_interp(vector<double> &xv, vector<double> &yv, int m) : Base_interp(xv,&yv[0],m), dy(0.0) {} double rawinterp(int jl, double x); }; struct Quadrature { int n; virtual double next() = 0; }; template <class T> struct Trapzd : Quadrature { double a,b,s; T &func; Trapzd() {}; Trapzd(T &funcc, const double aa, const double bb) : func(funcc), a(aa), b(bb) { n = 0; } double next() { double x, tnm, sum, del; int it, j; n++; if (n == 1) return (s = 0.5 * (b-a) * (func(a)+func(b))); else { for (it = 1, j = 1; j < n-1; j++) it <<= 1; tnm = it; del = (b-a)/tnm; x = a + 0.5 * del; for (sum = 0.0, j = 0; j < it; j++, x+=del) sum += func(x); s = 0.5 * (s+(b-a) * sum / tnm); return s; } } }; // NRp166 qromb integration method template <class T> double qromb(T &func, double a, double b, const double eps = 1.0e-10) { const int JMAX = 40; const int JMAXP = JMAX + 1; const int K = 10; //cout << eps << endl; vector<double> s,h; s.resize(JMAX); h.resize(JMAXP); Poly_interp polint(h,s,K); h[0] = 1.0; Trapzd<T> t(func,a,b); for (int j=1;j<=JMAX;j++) { s[j-1] = t.next(); if (j >= K) { double ss = polint.rawinterp(j-K,0.0); if (abs(polint.dy) <= eps*abs(ss)) return ss; } h[j] = 0.25 * h[j-1]; } cout << "Too many steps in routine qromb" << endl; throw("Too many steps in routine qromb"); } template <class T> double qgaus(T &func, const double a, const double b) { static const double x[]={0.1488743389816312,0.4333953941292472, 0.6794095682990244,0.8650633666889845,0.9739065285171717}; static const double w[]={0.2955242247147529,0.2692667193099963, 0.2190863625159821,0.1494513491505806,0.0666713443086881}; double xm=0.5*(b+a); double xr=0.5*(b-a); double s=0; for (int j=0;j<5;j++) { double dx=xr*x[j]; s += w[j]*(func(xm+dx)+func(xm-dx)); } return s *= xr; } template<typename T> double integrate_levin(T &f, const double a, const double b) { const double pi = boost::math::constants::pi<double>(); double beta = 1.0, sum = 0.0; double ans; double anew = a; double bnew = a; int nterm = 2.0*(b-a)/pi; if (nterm > 50000) { cout << "nterm too large" << endl; throw("nterm too large"); } else { LevinU series(50000,0.0); //cout << setw(5) << "N" << setw(19) << "Sum (direct)" << setw(21) << "Sum (Levin)" << endl; for (int n = 0; n<=nterm;n++) { bnew+=pi/2; double s = qromb(f, anew, bnew, 1.0E-3); //double s = qgaus(f, anew, bnew); anew=bnew; sum += s; double omega = (beta+n)*s; ans = series.next(sum, omega, beta); //cout << setw(5) << n << fixed << setprecision(14) << setw(21) << sum << setw(21) << ans << endl; } } return ans; }
#include <iostream> #include <vector> #include <map> #include <string> #include <bitset> #include <queue> #include <algorithm> #include <functional> #include <cmath> #include <cstdio> #include <sstream> #include <stack> #include <istream> using namespace std; class TwiceString { public: string getShortest(string s) { string ans = s+s; for (int i=1; i<s.size(); ++i) { string left = s.substr(0,i); string right = s.substr(s.size()-i,i); if (left == right) { string rest = s.substr(i,s.size()-i); ans = s+rest; } } return ans; } };
// Created on: 1995-12-01 // Created by: EXPRESS->CDL V0.2 Translator // Copyright (c) 1995-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _StepBasic_SiUnit_HeaderFile #define _StepBasic_SiUnit_HeaderFile #include <Standard.hxx> #include <Standard_Type.hxx> #include <StepBasic_SiPrefix.hxx> #include <StepBasic_SiUnitName.hxx> #include <StepBasic_NamedUnit.hxx> class StepBasic_DimensionalExponents; class StepBasic_SiUnit; DEFINE_STANDARD_HANDLE(StepBasic_SiUnit, StepBasic_NamedUnit) class StepBasic_SiUnit : public StepBasic_NamedUnit { public: //! Returns a SiUnit Standard_EXPORT StepBasic_SiUnit(); Standard_EXPORT void Init (const Standard_Boolean hasAprefix, const StepBasic_SiPrefix aPrefix, const StepBasic_SiUnitName aName); Standard_EXPORT void SetPrefix (const StepBasic_SiPrefix aPrefix); Standard_EXPORT void UnSetPrefix(); Standard_EXPORT StepBasic_SiPrefix Prefix() const; Standard_EXPORT Standard_Boolean HasPrefix() const; Standard_EXPORT void SetName (const StepBasic_SiUnitName aName); Standard_EXPORT StepBasic_SiUnitName Name() const; Standard_EXPORT virtual void SetDimensions (const Handle(StepBasic_DimensionalExponents)& aDimensions) Standard_OVERRIDE; Standard_EXPORT virtual Handle(StepBasic_DimensionalExponents) Dimensions() const Standard_OVERRIDE; DEFINE_STANDARD_RTTIEXT(StepBasic_SiUnit,StepBasic_NamedUnit) protected: private: StepBasic_SiPrefix prefix; StepBasic_SiUnitName name; Standard_Boolean hasPrefix; }; #endif // _StepBasic_SiUnit_HeaderFile
/* * Copyright (c) 2011 Pierre-Etienne Bougué <pe.bougue(a)gmail.com> * Copyright (c) 2011 Florian Colin <florian.colin28(a)gmail.com> * Copyright (c) 2011 Kamal Fadlaoui <kamal.fadlaoui(a)gmail.com> * Copyright (c) 2011 Quentin Lequy <quentin.lequy(a)gmail.com> * Copyright (c) 2011 Guillaume Pinot <guillaume.pinot(a)tremplin-utc.net> * Copyright (c) 2011 Cédric Royer <cedroyer(a)gmail.com> * Copyright (c) 2011 Guillaume Turri <guillaume.turri(a)gmail.com> * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * */ #include "tools/Checker.hh" #include "tools/Log.hh" #include "alg/ContextALG.hh" #include "bo/BalanceCostBO.hh" #include "bo/ContextBO.hh" #include "bo/LocationBO.hh" #include "bo/MachineBO.hh" #include "bo/MMCBO.hh" #include "bo/ProcessBO.hh" #include "bo/RessourceBO.hh" #include "bo/ServiceBO.hh" #include <boost/foreach.hpp> #include <set> #include <vector> using namespace std; Checker::Checker(ContextALG const * pContextALG_p) : pContextALG_m(pContextALG_p), contextToDelete_m(false) {} Checker::Checker(ContextBO const * pContextBO_p, const vector<int>& sol_p) : pContextALG_m(buildMyContextALG(pContextBO_p, sol_p)), contextToDelete_m(true) {} Checker::Checker(const Checker& checker_p){ throw (string("Interdiction d'utiliser le cpy ctr du Checker")); } Checker::~Checker(){ if ( contextToDelete_m ){ delete pContextALG_m; } } bool Checker::isValid(){ return checkCapaIncludingTransient() && checkConflict() && checkSpread() && checkDependances(); } uint64_t Checker::computeScore(){ ContextBO const * pContextBO_l = pContextALG_m->getContextBO(); return computeLoadCost() + computeBalanceCost() + pContextBO_l->getPoidsPMC() * computePMC() + pContextBO_l->getPoidsSMC() * computeSMC() + pContextBO_l->getPoidsMMC() * computeMMC(); } bool Checker::checkCapaIncludingTransient(){ ContextBO const * pContextBO_l = pContextALG_m->getContextBO(); const int nbRess_l = pContextBO_l->getNbRessources(); for ( int idxRess_l=0 ; idxRess_l < nbRess_l ; idxRess_l++ ){ RessourceBO const * pRess_l = pContextBO_l->getRessource(idxRess_l); if ( ! checkCapaIncludingTransient(pRess_l) ){ return false; } } return true; } bool Checker::checkCapaIncludingTransient(RessourceBO const * pRess_p){ ContextBO const * pContextBO_l = pContextALG_m->getContextBO(); const vector<int>& currentSol_l = pContextALG_m->getCurrentSol(); vector<int> vUsedRess_l(pContextBO_l->getNbMachines(), 0); const int nbProcess_l = pContextBO_l->getNbProcesses(); for ( int idxP_l=0 ; idxP_l < nbProcess_l ; idxP_l++ ){ ProcessBO const * pProcess_l = pContextBO_l->getProcess(idxP_l); const int idxCurMachine_l = currentSol_l[idxP_l]; vUsedRess_l[idxCurMachine_l] += pProcess_l->getRequirement(pRess_p); if ( pRess_p->isTransient() ){ int idxMachineInit_l = pProcess_l->getMachineInit()->getId(); if ( idxCurMachine_l != idxMachineInit_l ){ vUsedRess_l[idxMachineInit_l] += pProcess_l->getRequirement(pRess_p); } } } const int nbMachines_l = pContextBO_l->getNbMachines(); for ( int idxMachine_l=0 ; idxMachine_l < nbMachines_l ; idxMachine_l++ ){ const int capa_l = pContextBO_l->getMachine(idxMachine_l)->getCapa(pRess_p); if ( vUsedRess_l[idxMachine_l] > capa_l ){ LOG(DEBUG) << "La solution viole la contrainte de capa pour la ressource " << pRess_p->getId() << " sur la machine " << idxMachine_l << " (requirement : " << vUsedRess_l[idxMachine_l] << ", capa : " << capa_l << ")" << endl; return false; } } return true; } bool Checker::checkConflict(){ set<pair<int, int> > assocesMachineService_l; const vector<int>& curSol_l = pContextALG_m->getCurrentSol(); ContextBO const * pContextBO_l = pContextALG_m->getContextBO(); for ( int idxP_l=0 ; idxP_l < pContextBO_l->getNbProcesses() ; idxP_l++ ){ const int idxCurMachine_l = curSol_l[idxP_l]; const int idxService_l = pContextBO_l->getProcess(idxP_l)->getService()->getId(); pair<int, int> assoceMachineService_l(idxCurMachine_l, idxService_l); if ( assocesMachineService_l.find(assoceMachineService_l) != assocesMachineService_l.end() ){ LOG(DEBUG) << "La solution viole la contrainte de conflit : plusieurs processes du service " << idxService_l << " sur la machine " << idxCurMachine_l << endl; return false; } assocesMachineService_l.insert(assoceMachineService_l); } return true; } bool Checker::checkSpread(){ const vector<int>& curSol_l = pContextALG_m->getCurrentSol(); ContextBO const * pContextBO_l = pContextALG_m->getContextBO(); vector<set<int> > memory_l(pContextBO_l->getNbServices());; //memory_l[idxService] => liste des locations utilisees for ( int idxP_l=0 ; idxP_l < pContextBO_l->getNbProcesses() ; idxP_l++ ){ const int idxService_l = pContextBO_l->getProcess(idxP_l)->getService()->getId(); const int idxLocation_l = pContextBO_l->getMachine(curSol_l[idxP_l])->getLocation()->getId(); memory_l[idxService_l].insert(idxLocation_l); } for ( int idxS_l=0 ; idxS_l < pContextBO_l->getNbServices() ; idxS_l++ ){ const int spreadMin_l = pContextBO_l->getService(idxS_l)->getSpreadMin(); if ( spreadMin_l > (int) memory_l[idxS_l].size() ){ LOG(DEBUG) << "La solution viole la contrainte de spread : le service " << idxS_l << " s'etend sur " << memory_l[idxS_l].size() << " locations mais a un spread min de " << spreadMin_l << endl; return false; } } return true; } bool Checker::checkDependances(){ ContextBO const * pContextBO_l = pContextALG_m->getContextBO(); const int nbServices_l = pContextBO_l->getNbServices(); for ( int idxS1_l=0 ; idxS1_l < nbServices_l ; idxS1_l++ ){ ServiceBO const * pS1_l = pContextBO_l->getService(idxS1_l); if ( pS1_l->getServicesIDependOn().empty() ){ continue; } unordered_set<int> neighsUsedBy1_l = pContextALG_m->getNeighsUsedByService(pS1_l); BOOST_FOREACH(int idxS2_l, pS1_l->getServicesIDependOn()){ unordered_set<int> neighsUsedBy2_l = pContextALG_m->getNeighsUsedByService(idxS2_l); BOOST_FOREACH(int idxN_l, neighsUsedBy1_l){ if ( neighsUsedBy2_l.find(idxN_l) == neighsUsedBy2_l.end() ){ LOG(DEBUG) << "La solution viole la contrainte de dependances : " << "le service " << idxS1_l << " utilise le neighborhood " << idxN_l << " mais depend du service " << idxS2_l << " qui n'y est pas present" << endl; return false; } } } } return true; } uint64_t Checker::computeLoadCost(){ uint64_t result_l(0); ContextBO const * pContextBO_l = pContextALG_m->getContextBO(); const int nbRess_l = pContextBO_l->getNbRessources(); for ( int idxRess_l=0 ; idxRess_l < nbRess_l ; idxRess_l++ ){ int loadCostRess_l = computeLoadCost(idxRess_l); result_l += loadCostRess_l; } LOG(DEBUG) << "Load cost : " << result_l << endl; return result_l; } uint64_t Checker::computeLoadCost(int idxRess_p){ uint64_t result_l(0); const int nbMachine_l = pContextALG_m->getContextBO()->getNbMachines(); for ( int idxMachine_l=0 ; idxMachine_l < nbMachine_l ; idxMachine_l++ ){ result_l += computeLoadCost(idxRess_p, idxMachine_l); } result_l *= pContextALG_m->getContextBO()->getRessource(idxRess_p)->getWeightLoadCost(); LOG(USELESS) << "\tload cost pour la ress " << idxRess_p << " : " << result_l << endl; return result_l; } uint64_t Checker::computeLoadCost(int idxRess_p, int idxMachine_p){ MachineBO* pMachine_l = pContextALG_m->getContextBO()->getMachine(idxMachine_p); int safetyCapa_l = pMachine_l->getSafetyCapa(idxRess_p); uint64_t result_l = max(0, pContextALG_m->getRessUsedOnMachine(idxRess_p, idxMachine_p) - safetyCapa_l); LOG(USELESS) << "\t\tload cost pour la ress " << idxRess_p << " sur la machine " << idxMachine_p << " : " << result_l << endl; return result_l; } uint64_t Checker::computeBalanceCost(){ const int nbMachines_l = pContextALG_m->getContextBO()->getNbMachines(); uint64_t result_l(0); for ( int idxMachine_l=0 ; idxMachine_l < nbMachines_l ; idxMachine_l++ ){ result_l += computeBalanceCost(idxMachine_l); } return result_l; } uint64_t Checker::computeBalanceCost(int idxMachine_p){ const int nbBalanceCost_l = pContextALG_m->getContextBO()->getNbBalanceCosts(); uint64_t result_l(0); for ( int idxBC_l=0 ; idxBC_l < nbBalanceCost_l ; idxBC_l++ ){ result_l += computeBalanceCost(idxMachine_p, idxBC_l); } return result_l; } uint64_t Checker::computeBalanceCost(int idxMachine_p, int idxBC_l ){ BalanceCostBO const * pBC_l = pContextALG_m->getContextBO()->getBalanceCost(idxBC_l); RessourceBO* pRess1_l = pBC_l->getRessource1(); RessourceBO* pRess2_l = pBC_l->getRessource2(); const int qteRess1Used_l = pContextALG_m->getRessUsedOnMachine(pRess1_l->getId(), idxMachine_p); const int qteRess2Used_l = pContextALG_m->getRessUsedOnMachine(pRess2_l->getId(), idxMachine_p); const int capaRess1_l = pContextALG_m->getContextBO()->getMachine(idxMachine_p)->getCapa(pRess1_l); const int capaRess2_l = pContextALG_m->getContextBO()->getMachine(idxMachine_p)->getCapa(pRess2_l); const int a1_l = capaRess1_l - qteRess1Used_l; const int a2_l = capaRess2_l - qteRess2Used_l; /* FIXME : si on boucle d'abord sur les bc, *puis* sur les machine, on n'aura * a effectuer qu'une multiplication par bc et non une par couple (bc, machine) * (ceci dit, il peut etre interessant de conserver la possibilite d'estimer les bc sur une machine donnee...) */ return pBC_l->getPoids() * max(0, pBC_l->getTarget()*a1_l - a2_l); } uint64_t Checker::computePMC(){ uint64_t result_l = 0; const vector<int>& curSol_l = pContextALG_m->getCurrentSol(); for ( int idx_l=0 ; idx_l < (int) curSol_l.size() ; idx_l++ ){ ProcessBO const * pProcess_l = pContextALG_m->getContextBO()->getProcess(idx_l); if ( curSol_l[idx_l] != pProcess_l->getMachineInit()->getId() ){ result_l += pProcess_l->getPMC(); } } return result_l; } uint64_t Checker::computeSMC(){ const vector<int>& curSol_l = pContextALG_m->getCurrentSol(); const int nbProcess_l = curSol_l.size(); const int nbServices_l = pContextALG_m->getContextBO()->getNbServices(); vector<int> nbProcessMovedByService_l(nbServices_l, 0); for ( int idxP_l=0 ; idxP_l < (int) nbProcess_l ; idxP_l++ ){ ProcessBO const * pProcess_l = pContextALG_m->getContextBO()->getProcess(idxP_l); if ( curSol_l[idxP_l] != pProcess_l->getMachineInit()->getId() ){ nbProcessMovedByService_l[pProcess_l->getService()->getId()]++; } } uint64_t max_l = 0; BOOST_FOREACH(int nbPMoved_l, nbProcessMovedByService_l){ max_l = max(max_l, (uint64_t) nbPMoved_l); } return max_l; } uint64_t Checker::computeMMC(){ const vector<int>& curSol_l = pContextALG_m->getCurrentSol(); const int nbP_l = curSol_l.size(); MMCBO* pMMCBO_l = pContextALG_m->getContextBO()->getMMCBO(); uint64_t result_l(0); for ( int idxP_l=0 ; idxP_l < nbP_l ; idxP_l++ ){ result_l += pMMCBO_l->getCost(pContextALG_m->getContextBO()->getProcess(idxP_l)->getMachineInit()->getId() , curSol_l[idxP_l]); } return result_l; } bool check(ContextALG const * pContextALG_p){ Checker checker_l(pContextALG_p); return checker_l.isValid(); } bool check(ContextBO const * pContextBO_p){ ContextALG contextALG_l(pContextBO_p); return check(&contextALG_l); } ContextALG const * Checker::buildMyContextALG(ContextBO const * pContextBO, const vector<int> sol_p){ ContextALG* pResult_l = new ContextALG(pContextBO, false, false); pResult_l->setCurrentSol(sol_p); return pResult_l; }
#ifndef APPLICATION_CONTROLLER_H #define APPLICATION_CONTROLLER_H #include <stdlib.h> #include <functional> #include <optional> #include "ChatObjects/ChatUpdates.h" #include "Commands/CmdCreator/Commands.h" #include "Client/Client.h" #include "Commands/CmdCreator/CommandCreator.h" #include "UserOptions/BaseUserOptions.h" #include "UserOptions/GuestOptions.h" #include "RoleController/RoleController.h" #include <ChatObjects/ChatRoom.h> // Facade of client lib class Controller: public std::enable_shared_from_this<Controller> { public: static std::shared_ptr<Controller> getInstance(); Controller(const Controller &controller) = delete; Controller(Controller &&controller) = delete; Controller& operator=(const Controller &controller) = delete; Controller& operator=(Controller &&controller) = delete; ~Controller() = default; // Run client connection void runClient(const std::string& ip, const std::string& port, const std::function<void(int)>& errHandler); // Reconnect client connection void reconnectClient(const std::string& ip, const std::string& port); // Send message in select chat void sendMessage(const Message& message, int globalId, const std::shared_ptr<BaseCallback>& callback); // Authorization user void authorization(const UserInfo& authInfo, int globalId, const std::shared_ptr<BaseCallback>& callback); // Update select chat void chatUpdate(const ChatUpdates& chatUpdates, int globalId, const std::shared_ptr<BaseCallback>& callback); // Get list of chats void getListChats(const ListChats& listChats, int globalId, const std::shared_ptr<BaseCallback>& callback); // Get select chat room void getChatRoom(const ChatRoom& chatRoom, int globalId, const std::shared_ptr<BaseCallback>& callback); // Get messages in select chat void getChatMessages(const ChatUpdates& chatUpdates, int globalId, const std::shared_ptr<BaseCallback>& callback); // Get log void getLog(const LogUpdates& logUpdates, int globalId, const std::shared_ptr<BaseCallback>& callback); // Get last message in chat void getLastMessage(const Message& message, int globalId, const std::shared_ptr<BaseCallback>& callback); // Get user void getUser(const UserPreview& user, int globalId, const std::shared_ptr<BaseCallback>& callback); // Set chat observer void setChatObserver(int chatId, const std::shared_ptr<BaseCallback>& callback); // Message handler void readMessageHandler(const std::string& str); // Send chat command void sendChatCommand(const Message& message, int globalId); // Registration new user void registration(const UserInfo& authInfo, int globalId, const std::shared_ptr<BaseCallback>& callback); private: Controller(); private: std::shared_ptr<Client> client; std::shared_ptr<CallbacksHolder> callbackHolder; std::shared_ptr<BaseUserOptions> userOptions; }; #endif //APPLICATION_CONTROLLER_H
#include <iostream> #include <cstring> #include <queue> #include <algorithm> const int INF = 1e9; struct qn{ int x, y, d, k; }; std::string map[1000]; int N, M, K; int dist[11][1000][1000]; std::queue<qn> q; int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, -1, 0, 1}; int main() { std::cin.sync_with_stdio(false); std::cin.tie(NULL); std::fill(dist[0][0], dist[0][0] + 11 * 1000 * 1000, INF); std::cin >> N >> M >> K; for(int i = 0; i < N; i++) { std::cin >> map[i]; } dist[K][0][0] = 1; q.push({0, 0, 1, K}); while(!q.empty()) { auto [x, y, d, k] = q.front(); q.pop(); for(int i = 0; i < 4; i++) { int nx = dx[i] + x; int ny = dy[i] + y; if(nx < 0 || ny < 0 || nx >= N || ny >= M) { continue; } if(map[nx][ny] == '0' && dist[k][nx][ny] > d + 1) { dist[k][nx][ny] = d + 1; q.push({nx, ny, d + 1, k}); } if(map[nx][ny] == '1' && k > 0) { int nd = (d % 2) ? d + 1 : d + 2; if(dist[k - 1][nx][ny] > nd) { dist[k - 1][nx][ny] = nd; q.push({nx, ny, nd, k - 1}); } } } } int ans = INF; for(int i = 0; i <= K; i++) { ans = std::min(ans, dist[i][N - 1][M - 1]); } std::cout << (ans == INF ? -1 : ans) << '\n'; return 0; }
#ifndef VARIABLESTABLE_H #define VARIABLESTABLE_H #include <vector> #include <string> #include <iostream> using namespace std; class Variable { private: string name = ""; string type = ""; bool isField = false; bool isMethod = false; public: Variable(string name, string type, bool isField, bool isMethod); string getName(); string getType(); bool getIsField(); bool getIsMethod(); }; class VariablesTable { private: string test = ""; vector<vector<Variable *>> childs; public: /** * Each class node has its own VariablesTable object in order to store * useful information about its fields, methods, let nodes, ... * * Note on the "childs" variable: it is a vector of containers. A container is added when * when encountering a method, field, or a let node; it is removed when all variables inside * these functions have all been read, and all checkings have been made. For instance, when a field * is encountered, one adds a container (i.e. a vector) to the "childs" vector. Then, the "printCheck" * function of all variables and/or functions inside the field is called. After that, the container * is removed. Such a mechanism allows to perform scope checkings quite easily. */ VariablesTable(); /** This function is used in the LeafNode.cpp file in case of a variable "self". * * @return a string representing the type of the first variable in "childs", or "none" if "childs" is empty */ string getFirstVariable(); /** This function is used in the ClassNode.cpp file when one wants to perform some checks * in order to detect some error. * * @param varName the name of the variable one wants to return * @return an object Variable corresponding to the Variable of the name "varName" */ Variable *getVariableObject(string varName); /** This function is used in multiple classes in order to perform some type checking and detect errors. * * @param varName the name of the Variable to get the type of * @return a string representing the type of the Variable whose name is "varName", "none" if there is no variables * with such a name */ string getVariable(string varName); /** This function is used in the ClassNode.cpp file in order to push the information (i.e. Variables) * about the fields and methods in the current class in case of inheritance. * * @return a vector<Variable *>, the first vector of Variables in the "childs" vector */ vector<Variable *> getContainerVariables(); /** This function forms a Variable object with the arguments and pushes it to the last container * in the "childs" vector. * * @param name * @param type * @param isFieldArg * @param isMethodArg */ void addVariable(string name, string type, bool isFieldArg = false, bool isMethodArg = false); /** Directly add a variable to the last container of the "childs" vector. * * @param var */ void addVariableObject(Variable *var); /** This function adds a container, i.e. a vetor, to the "childs" vector */ void addFunction(); /** This function removes the last container, i.e. vector, of the "childs" vector */ void removeFunction(); /** This function has been used (and can still be) to debug some of the code. * * @return a string containing all variables of each container in the "childs" vector (for debug only) */ string printVariables(); }; #endif
#include <iostream> #include <windows.h> // Faster harcoded version, click and run int main() { // Hide console ShowWindow(GetConsoleWindow(), SW_HIDE); // Change the route and the android device for what ever you want to use system("D: && cd D:\\Programas\\android-sdk\\emulator && emulator -avd Nexus_5_API_30"); return 0; }
#include "TestNetwork.h" #include <event.h> #define LOGI(...) ((void)__android_log_print(ANDROID_LOG_INFO, "TestNetwork", __VA_ARGS__)) #define LOGW(...) ((void)__android_log_print(ANDROID_LOG_WARN, "TestNetwork", __VA_ARGS__)) extern "C" { /*此简单函数返回平台 ABI,此动态本地库为此平台 ABI 进行编译。*/ const char * TestNetwork::getPlatformABI() { #if defined(__arm__) #if defined(__ARM_ARCH_7A__) #if defined(__ARM_NEON__) #define ABI "armeabi-v7a/NEON" #else #define ABI "armeabi-v7a" #endif #else #define ABI "armeabi" #endif #elif defined(__i386__) #define ABI "x86" #else #define ABI "unknown" #endif LOGI("This dynamic shared library is compiled with ABI: %s", ABI); return "This native library is compiled with ABI: %s" ABI "."; } void TestNetwork() { } TestNetwork::TestNetwork() { } TestNetwork::~TestNetwork() { } } struct event ev; struct timeval tv; void timer_cb( int fd, short event, void* arg ) //回调函数 { LOGI( "timer_cb\n" ); event_add( &ev, &tv ); //重新注册 } extern "C" { JNIEXPORT void JNICALL Java_com_TestNetworkApp_TestNetworkApp_NativeTestNetwork( JNIEnv* env, jobject obj ) { LOGI( "yes, test network" ); struct event_base* base = event_init(); //初始化libevent库 tv.tv_sec = 1; tv.tv_usec = 0; event_set( &ev, -1, 0, timer_cb, NULL ); //初始化event结构中成员 event_base_set( base, &ev ); event_add( &ev, &tv ); //将event添加到events事件链表,注册事件 event_base_dispatch( base ); //循环、分发事件 } }
/* Copyright (c) 2014-present PlatformIO <contact@platformio.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. **/ #include <Arduino.h> #include <WiFi.h> #include <BintrayClient.h> #include "SecureOTA.h" const uint16_t OTA_CHECK_INTERVAL = 5000; // ms uint32_t _lastOTACheck = 0; void setup() { pinMode(LED_BUILTIN, OUTPUT); Serial.begin(SERIAL_SPEED); delay(10); Serial.println(); Serial.println(); Serial.print("Device version: v."); Serial.println(VERSION); Serial.print("Connecting to " + String(WIFI_SSID)); WiFi.begin(WIFI_SSID, WIFI_PASS); while (WiFi.status() != WL_CONNECTED) { Serial.print("."); delay(500); } Serial.println(" connected!"); _lastOTACheck = millis(); // your setup code goes here } void loop() { if ((millis() - OTA_CHECK_INTERVAL) > _lastOTACheck) { _lastOTACheck = millis(); checkFirmwareUpdates(); // takes ~1s, make sure this is not a problem in your code } // your loop code goes here digitalWrite(LED_BUILTIN, HIGH); // turn the LED on (HIGH is the voltage level) delay(1000); // wait for a second digitalWrite(LED_BUILTIN, LOW); // turn the LED off by making the voltage LOW delay(1000); }
#include "../../headers.h" #include "../render/CubeMap.h" #include "../render/GLWrappers.h" #include "Sky.h" //------------------------------------------------------------------------------------------------- Sky::Sky() { } //------------------------------------------------------------------------------------------------- void Sky::init(const Settings& settings, CubeMap* cubemap) { settings_ = settings; cubemap_ = cubemap; // init geo initGeo(); // load shaders program_.load("data/shaders/Sky_vertex.glsl", "data/shaders/Sky_fragment.glsl"); } //------------------------------------------------------------------------------------------------- void Sky::setTransforms(const Transforms& transforms) { // // Direction : Spherical coordinates to Cartesian coordinates conversion float h = transforms.HorizAngle; float v = transforms.VertAngle; glm::vec3 direction( cos(v) * sin(h), sin(v), cos(v) * cos(h) ); // Right vector glm::vec3 right = glm::vec3( sin(h - 3.1415926f/2.0f), 0.0f, cos(h - 3.1415926f/2.0f) ); glm::vec3 up = glm::cross( right, direction ); view_ = glm::lookAt(glm::vec3(0, 0, 0), direction, up); mvp_ = transforms.Proj*view_; } //------------------------------------------------------------------------------------------------- void Sky::draw() { glDisable(GL_DEPTH_TEST); //glEnable(GL_CULL_FACE); //glCullFace(GL_FRONT); glBindVertexArray(vao_.getID()); glUseProgram(program_.getID()); GLuint id = glGetUniformLocation(program_.getID(), "MVP"); glUniformMatrix4fv(id, 1, GL_FALSE, &mvp_[0][0]); id = glGetUniformLocation(program_.getID(), "MV"); glUniformMatrix4fv(id, 1, GL_FALSE, &view_[0][0]); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_CUBE_MAP, cubemap_->getID()); program_.setUniformVec3("u_skyColor", settings_.SkyColor); glBindBuffer(GL_ARRAY_BUFFER, vbo_.getID()); // positions glVertexAttribPointer( 0, // attribute 0. No particular reason for 0, but must match the layout in the shader. 3, // size GL_FLOAT, // type GL_FALSE, // normalized? 3*sizeof(float), // stride (void*)0 // array buffer offset ); glEnableVertexAttribArray(0); glDrawArrays(GL_TRIANGLES, 0, 36); glDisableVertexAttribArray(0); glBindVertexArray(0); } //------------------------------------------------------------------------------------------------- void Sky::initGeo() { float s = settings_.SkyboxHalfSize; float vertices[] = { -s, s, -s, -s, -s, -s, s, -s, -s, s, -s, -s, s, s, -s, -s, s, -s, -s, -s, s, -s, -s, -s, -s, s, -s, -s, s, -s, -s, s, s, -s, -s, s, s, -s, -s, s, -s, s, s, s, s, s, s, s, s, s, -s, s, -s, -s, -s, -s, s, -s, s, s, s, s, s, s, s, s, s, -s, s, -s, -s, s, -s, s, -s, s, s, -s, s, s, s, s, s, s, -s, s, s, -s, s, -s, -s, -s, -s, -s, -s, s, s, -s, -s, s, -s, -s, -s, -s, s, s, -s, s }; glBindBuffer(GL_ARRAY_BUFFER, vbo_.getID()); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); glBindVertexArray(vao_.getID()); glEnableVertexAttribArray(0); glBindBuffer(GL_ARRAY_BUFFER, vbo_.getID()); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3*sizeof(float), 0); }
#include <iostream> #include <vector> #include <boost/heap/fibonacci_heap.hpp> #include "value.hpp" using namespace std; using namespace boost::heap; /** * Classe utile a fornire oggetti capaci di gestire un parametro di tipo T in un heap di fibonacci. */ template<typename T> class FibonacciHeapHandler { public: /** * Algoritmo capace di riordinare un vettore. */ template<typename C, typename = std::enable_if<std::is_base_of<Comparator, C>::value>> void heapsort(vector<T> *toSort) { int i; const int N = toSort->size(); fibonacci_heap<T, compare<C>> Q; for (i = 0; i < N; ++i) { Q.push((*toSort)[i]); } toSort->clear(); for (i = 0; i < N; ++i) { toSort->push_back(Q.top()); Q.pop(); } } };
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /* * File: QueueFactory.cpp * Author: ssridhar * * Created on October 31, 2017, 1:06 PM */ #include "QueueFactory.h" #include "one_second_timer.h" #include "StateFactory.h" webclient::Queue_Factory* webclient::Queue_Factory::m_pInstance = NULL; /** * Instance Returns the Queue Factory instance. * @return */ webclient::Queue_Factory* webclient::Queue_Factory::Instance() { if (!webclient::Queue_Factory::m_pInstance) { webclient::Queue_Factory::m_pInstance = new webclient::Queue_Factory(); } return webclient::Queue_Factory::m_pInstance; } /** * ~Queue_Factory Destructor. Cleans up the queue. */ webclient::Queue_Factory::~Queue_Factory() { for (int queue_index = 0; queue_index < total_number_of_queues; queue_index++) { msgq_node *pTemp = (p_g_msgQ + queue_index)->pFront; while (pTemp) { msgq_node *pTemp2 = pTemp->pLink; free(pTemp); pTemp = pTemp2; } free(p_g_msgQ + queue_index); } } #define QUEUE_CURRENT_COUNT "current-queue-count-" /** * set_total_number_of_queues Allocates message queues for each state. * @param queue_total */ void webclient::Queue_Factory::set_total_number_of_queues(uint8_t queue_total) { if (!queue_total) { LOG_ERROR("%s:%d Invalid input parameters.\n", __FILE__, __LINE__); return; } p_g_msgQ = (msgQ *) calloc(queue_total, sizeof (msgQ)); total_number_of_queues = queue_total; //Register for one second timer event callback. for (int count = 0; count < total_number_of_queues; count++) { std::string str_count(QUEUE_CURRENT_COUNT); str_count.append(webclient::State_Factory::convert_state_to_name(count)); LOG_ERROR("Registering %s with one second timer.\n", str_count.c_str()); one_second_timer_factory::Instance()->register_for_one_second_timer( str_count, webclient::Queue_Factory::Instance()->return_current_queue_count); } } /** * return_current_queue_count This is a call back function for the one second timer. * This returns the current number of jobs enqueued in the queue identifier passed in * as an argument to this function. * @param arg queue_name * @return */ long webclient::Queue_Factory::return_current_queue_count(void *arg) { std::string *p_queue_name = (std::string *) arg; long return_value = -1; if (!arg) { LOG_ERROR("%s:%d Invalid input parameters.\n", __FILE__, __LINE__); return return_value; } uint8_t match_found = 0; int index = 0; for (index = 0; index < webclient::State_Factory::get_total_number_of_states(); index++) { std::string str_count(QUEUE_CURRENT_COUNT); str_count.append(webclient::State_Factory::convert_state_to_name(index)); if (p_queue_name->compare(str_count) == 0) { match_found = 1; break; } } if (match_found) { return_value = webclient::Queue_Factory::Instance()->count(index); } else { LOG_ERROR("Match not found for %s.\n", (*p_queue_name).c_str()); } return return_value; } /** * enqueue Enqueue the job to the passed in queue type. * @param queue_type Identifies the queue. * @param message Job address. * @param message_size size of the job address (size of uint64_t) * @return */ /* adds an element to the queue */ uint8_t webclient::Queue_Factory::enqueue(uint8_t queue_type, void * message, uint32_t message_size) { msgq_node *temp = NULL; uint8_t msq_send_return_code = -1; if (!message || (message_size <= 0) || (queue_type < 0) || (queue_type >= total_number_of_queues)) { LOG_ERROR("%s:%d Invalid input parameters.\n", __FILE__, __LINE__); return msq_send_return_code; } if (!(p_g_msgQ + queue_type)) { LOG_ERROR("%s:%d p_g_msgQ is not initialized for %d.\n", __FILE__, __LINE__, queue_type); return msq_send_return_code; } temp = (msgq_node *) calloc(1, sizeof (msgq_node)); if (temp == NULL) { LOG_ERROR("%s:%d Unable to allocate memory for msgq_node\n", __FILE__, __LINE__); return msq_send_return_code; } //temp->pData=calloc(message_size, sizeof(uint8_t)); //memcpy(temp->pData,message,message_size); temp->pData = message; temp->message_length = message_size; temp->pLink = NULL; if (((p_g_msgQ + queue_type)->pFront == NULL) || ((p_g_msgQ + queue_type)->pRear == NULL)) { (p_g_msgQ + queue_type)->pRear = (p_g_msgQ + queue_type)->pFront = temp; } else { (p_g_msgQ + queue_type)->pRear->pLink = temp; (p_g_msgQ + queue_type)->pRear = (p_g_msgQ + queue_type)->pRear->pLink; } (p_g_msgQ + queue_type)->count++; msq_send_return_code = 0; return msq_send_return_code; } //Dequeue an element from the queue. /** * dequeue Dequeue the message from the current queue. * @param queue_type Identifies the queue. * @param ppMessage Job address. * @param pMessageLength Job address length (size of uint64_t) */ void webclient::Queue_Factory::dequeue(uint8_t queue_type, void **ppMessage, uint32_t *pMessageLength) { msgq_node *pTmp = NULL; if (!ppMessage || !pMessageLength || (queue_type < 0) || (queue_type >= total_number_of_queues)) { LOG_ERROR("%s:%d Input parameters are invalid.\n", __FILE__, __LINE__); return; } if (!(p_g_msgQ + queue_type)) { LOG_ERROR("%s:%d p_g_msgQ is not initialized for %d.\n", __FILE__, __LINE__, queue_type); return; } if ((p_g_msgQ + queue_type)->pFront == NULL) { LOG_ERROR("%s:%d No messages in messaqe queue\n", __FILE__, __LINE__); return; } //memcpy(*ppMessage,(p_g_msgQ+queue_type)->pFront->pData,(p_g_msgQ+queue_type)->pFront->message_length); *ppMessage = (p_g_msgQ + queue_type)->pFront->pData; *pMessageLength = (p_g_msgQ + queue_type)->pFront->message_length; //free((p_g_msgQ+queue_type)->pFront->pData); pTmp = (p_g_msgQ + queue_type)->pFront; (p_g_msgQ + queue_type)->pFront = (p_g_msgQ + queue_type)->pFront->pLink; free(pTmp); (p_g_msgQ + queue_type)->count--; } /** * is_empty Checks whether the passed in queue identifier is empty or not. * @param queue_type * @return */ uint8_t webclient::Queue_Factory::is_empty(uint8_t queue_type) { uint8_t are_there_messages_in_msgQ = 1; if ((queue_type < 0) || (queue_type >= total_number_of_queues)) { LOG_ERROR("%s:%d Input parameters are invalid.\n", __FILE__, __LINE__); return are_there_messages_in_msgQ; } if (!(p_g_msgQ + queue_type)) { LOG_ERROR("%s:%d p_g_msgQ is not initialized for %d.\n", __FILE__, __LINE__, queue_type); return are_there_messages_in_msgQ; } if ((p_g_msgQ + queue_type)->pFront != NULL) { are_there_messages_in_msgQ = 0; } return are_there_messages_in_msgQ; } /** * count Returns the total number of Jobs in the passed in queue identifier. * @param queue_type * @return */ long webclient::Queue_Factory::count(uint8_t queue_type) { if ((queue_type < 0) || (queue_type >= total_number_of_queues)) { LOG_ERROR("%s:%d Input parameters are invalid.\n", __FILE__, __LINE__); return -1; } if (!(p_g_msgQ + queue_type)) { LOG_ERROR("%s:%d p_g_msgQ is not initialized for %d.\n", __FILE__, __LINE__, queue_type); return -1; } if ((p_g_msgQ + queue_type)->pFront == NULL) { return -1; } return (p_g_msgQ + queue_type)->count; } /** * peek_at_the_front_of_queue Peeks at the front of the queue to look for Jobs. * Only used for debugging. * @param queue_type * @param ppMessage * @param pMessageLength * @param location */ void webclient::Queue_Factory::peek_at_the_front_of_queue(uint8_t queue_type, void **ppMessage, uint32_t *pMessageLength, long location) { if (!ppMessage || !pMessageLength || (queue_type < 0) || (location < 0) || (queue_type >= total_number_of_queues)) { LOG_ERROR("%s:%d Input parameters are invalid.\n", __FILE__, __LINE__); return; } if (!(p_g_msgQ + queue_type)) { LOG_ERROR("%s:%d p_g_msgQ is not initialized for %d.\n", __FILE__, __LINE__, queue_type); return; } if ((p_g_msgQ + queue_type)->pFront == NULL) { LOG_ERROR("%s:%d No messages in messaqe queue\n", __FILE__, __LINE__); return; } int index = location; msgq_node *pTmp = (p_g_msgQ + queue_type)->pFront; while (index) { pTmp = pTmp->pLink; index--; } //memcpy(*ppMessage,pTmp->pData,pTmp->message_length); *ppMessage = pTmp->pData; *pMessageLength = pTmp->message_length; }