text
stringlengths
8
6.88M
#include <vector> #include <string> #include <iostream> #include <fstream> #include <sstream> #include <list> #include <algorithm> #include <sstream> #include <set> #include <cmath> #include <map> #include <stack> #include <queue> #include <stdio.h> #include <string.h> #include <time.h> #include <numeric> const int dy[6] = {-1,-1,0,0,1,1}; const int dx[2][6] = { {-1,0,-1,1,-1,0}, {0,1,-1,1,0,1} }; using namespace std; class Islands { public: int beachLength(vector <string> kingdom) { int Y = (int)kingdom.size(); int X = (int)kingdom[0].size(); int res = 0; for (int y=0; y<Y; ++y) { for (int x=0; x<X; ++x) { if (kingdom[y][x] == '#') { for (int k=0; k<6; ++k) { int cy = y + dy[k]; int cx = x + dx[y%2][k]; if ( (0 <= cx && cx < X && 0 <= cy && cy < Y) && kingdom[cy][cx] == '.' ){ ++res; } } } } } return res; } // BEGIN CUT HERE public: void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); } private: template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); } void verify_case(int Case, const int &Expected, const int &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } } void test_case_0() { string Arr0[] = {".#...#.."}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 4; verify_case(0, Arg1, beachLength(Arg0)); } void test_case_1() { string Arr0[] = {"..#.##", ".##.#.", "#.#..."}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 19; verify_case(1, Arg1, beachLength(Arg0)); } void test_case_2() { string Arr0[] = {"#...#.....", "##..#...#."}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 15; verify_case(2, Arg1, beachLength(Arg0)); } void test_case_3() { string Arr0[] = {"....#.", ".#....", "..#..#", "####.."}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 24; verify_case(3, Arg1, beachLength(Arg0)); } // END CUT HERE }; // BEGIN CUT HERE int main() { Islands ___test; ___test.run_test(-1); } // END CUT HERE
#include <BinomialQueue.h> #include <PuttingVisitor.h> #include <Wrapper.h> #include <iostream> int main(void) { using namespace std; BinomialQueue bq; Int *ip1 = new Int(1); Int *ip2 = new Int(2); Int *ip3 = new Int(3); Int *ip4 = new Int(4); Int *ip5 = new Int(5); Int *ip6 = new Int(6); Int *ip7 = new Int(7); PuttingVisitor pv(cout); bq.Enqueue(*ip4); bq.Enqueue(*ip5); bq.Enqueue(*ip6); bq.Enqueue(*ip7); bq.Enqueue(*ip1); bq.Enqueue(*ip2); bq.Enqueue(*ip3); cout<<bq.FindMin()<<endl; bq.Accept(pv); cout<<bq.DequeueMin ()<<endl; cout<<bq.DequeueMin ()<<endl; cout<<bq.DequeueMin ()<<endl; cout<<bq.DequeueMin ()<<endl; }
#include <bits/stdc++.h> using namespace std; int func(int a, int b, int c, int x, int y); int main() { int g[3], m[2], ret, maior=0; while(scanf("%d %d %d %d %d", &g[0], &g[1], &g[2], &m[0], &m[1]) && (g[0] || g[1] || g[2] || m[0] || m[1])) { sort(g, g+3); ret = func(g[0], g[1], g[2], m[0], m[1]); if(ret==-1) { printf("-1\n"); continue; } else if(ret>maior) maior=ret; for(int i=0;i<5;i++) { next_permutation(g, g+3); ret = func(g[0], g[1], g[2], m[0], m[1]); if(ret==-1) break; else if(ret>maior) maior=ret; } if(ret==-1 || maior>52) printf("-1\n"); else printf("%d\n", maior); maior=0; } return 0; } int func(int a, int b, int c, int x, int y) { int cont=0, aux=c; if(x>a) cont++; if(y>b) cont++; if(cont==1) { do { aux++; }while(aux==a || aux==b || aux==c || aux==x || aux==y); return aux; } else if(cont==2) { aux = 0; do { aux++; }while(aux==a || aux==b || aux==c || aux==x || aux==y); return aux; } else return -1; }
#include <GL/glut.h> #include <cstdlib> #include <memory> #include <vector> using namespace std; static void Timer(int value) { glutPostRedisplay(); glutTimerFunc(10, Timer, value); } class Cube { public: float x; float y; float width; float height; float speed; Cube(float xp, float yp, float w, float h, float s) { x = xp; y = yp; width = w; height = h; speed = s; } virtual void draw() = 0; virtual void move() {}; }; class Enemy :public Cube { public: float fanLength; float fanSpeed; float fanX; float fanY; float rColor; float gColor; float bColor; Enemy(float xp, float yp, float w, float h, float s, float rc, float gc, float bc) :Cube(xp, yp, w, h, s) { fanLength = 48; fanSpeed = 2; fanX = xp + w/2; fanY = yp + h + 2; rColor = rc; gColor = gc; bColor = bc; } void draw() { glColor3f(rColor, gColor, bColor); glBegin(GL_POLYGON); glVertex3f(x, y, 0.0); glVertex3f(x + width, y, 0.0); glVertex3f(x + width, y + height, 0.0); glVertex3f(x, y + height, 0.0); glEnd(); glFlush(); fanLength += fanSpeed; if (fanLength >= 50) { fanSpeed *= -1; fanLength = 48; } if (fanLength <= 0) { fanSpeed *= -1; fanLength = 2; } glColor3f(1.0, 0.0, 0.7); glBegin(GL_LINES); glVertex2f(fanX - (fanLength / 2), fanY); glVertex2f(fanX + (fanLength / 2), fanY); glEnd(); glFlush(); } void move() { if (speed <= 0) { if (x >= 0) { x += speed; fanX += speed; } else speed *= -1; } else { if (x + width <= 480) { x += speed; fanX += speed; } else speed *= -1; } } void levelUp() { speed *= 1.5; } }; class Player :public Cube { public: int score; int life; int array[4]; int level; Player(float xp, float yp, float w, float h, float s) :Cube(xp, yp, w, h, s) { level = 0; score = 0; life = 3; for (int i = 0; i < 4; i++) { array[i] = 0; } } void draw() { glColor3f(1.0, 0.25, 1.0); glBegin(GL_POLYGON); glVertex3f(x, y, 0.0); glVertex3f(x + width, y, 0.0); glVertex3f(x + width, y + height, 0.0); glVertex3f(x, y + height, 0.0); glEnd(); glFlush(); } float moveIn(float coordinate, float s) { return coordinate + s; } void move() { for (int i = 0; i < 4; i++) { if (array[i] == 1) { array[i] = 0; if (i == 0) { x = moveIn(x, -speed); } if (i == 1) { x = moveIn(x, speed); } if (i == 2) { y = moveIn(y, -speed); } if (i == 3) { y = moveIn(y, speed); } if (x <= 0) { x = 0; } if (y <= 0) { y = 0; } if (x + width >= 480) { x = 480 - width; } if (y + height >= 640) { x = 215; y = 95; score++; level++; } } } } void collision(float xc, float w, float yc, float h) { if ((xc >= x && xc <= x + width) || (xc + w >= x && xc + w <= x + width)) { if ((yc >= y && yc <= y + height) || (yc + h >= y && yc + h <= y + height)) { life--; x = 215; y = 95; if (life <= 0) { exit(0); } } } } }; shared_ptr<Player> myCube; vector<shared_ptr<Enemy>> myEnemies; void myInit() { glClearColor(0.0, 1.0, 1.0, 0.0); glColor3f(1.0f, 0.0f, 0.0f); glMatrixMode(GL_PROJECTION); glOrtho(0.0, 480.0, 0.0, 640.0, -1.0, 1.0); } void keyboard(unsigned char key, int x, int y) { if (key == 97) { myCube->array[0] = 1; } if (key == 100) { myCube->array[1] = 1; } if (key == 115) { myCube->array[2] = 1; } if (key == 119) { myCube->array[3] = 1; } glutPostRedisplay(); } void render() { glClear(GL_COLOR_BUFFER_BIT); glColor3f(0.30, 0.55, 1.0); glBegin(GL_POLYGON); glVertex3f(0.0, 0.0, 0.0); glVertex3f(480.0, 0.0, 0.0); glVertex3f(480.0, 240.0, 0.0); glVertex3f(0.0, 240.0, 0.0); glEnd(); glFlush(); myCube->move(); if (myCube->level == 1) { myCube->level = 0; for (int i = 0; i < myEnemies.size(); i++) { myEnemies[i]->levelUp(); } } for (int i = 0; i < myEnemies.size(); i++) { myEnemies[i]->move(); myEnemies[i]->draw(); myCube->collision(myEnemies[i]->x, myEnemies[i]->width, myEnemies[i]->y, myEnemies[i]->height); } myCube->draw(); glColor3f(0.0, 0.0, 0.0); glRasterPos2f(0, 230); char pointText[5] = {'P','O','I','N','T'}; for (int i = 0; i < 5; i++) { glutBitmapCharacter(GLUT_BITMAP_8_BY_13, pointText[i]); } char point = myCube->score + '0'; glColor3f(1.0, 0.0, 0.0); glRasterPos2f(50, 230); glutBitmapCharacter(GLUT_BITMAP_8_BY_13, point); glColor3f(0.0, 0.0, 0.0); glRasterPos2f(0, 210); char lifeText[4] = { 'L','I','F','E'}; for (int i = 0; i < 4; i++) { glutBitmapCharacter(GLUT_BITMAP_8_BY_13, lifeText[i]); } char life = myCube->life + '0'; glColor3f(1.0, 0.0, 0.0); glRasterPos2f(50, 210); glutBitmapCharacter(GLUT_BITMAP_8_BY_13, life); glutSwapBuffers(); } int main(int argc, char** argv) { myCube = make_shared<Player>(215, 95, 50, 50, 10); myEnemies.push_back(make_shared<Enemy>(0, 250, 50, 50, 0.2, 0.0, 0.0, 0.0)); myEnemies.push_back(make_shared<Enemy>(430, 320, 50, 50, 0.3, 1.0, 1.0, 0.0)); myEnemies.push_back(make_shared<Enemy>(430, 400, 50, 50, 0.4, 0.0, 1.0, 0.0)); myEnemies.push_back(make_shared<Enemy>(0, 470, 50, 50, 0.5, 1.0, 0.0, 0.0)); glutInit(&argc, argv); glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA); glutInitWindowSize(480, 640); glutInitWindowPosition(0, 0); glutCreateWindow("Cube Game"); myInit(); glutKeyboardFunc(keyboard); glutDisplayFunc(render); Timer(0); glutMainLoop(); return 0; }
#ifndef SPECEX_PYPSF__H #define SPECEX_PYPSF__H #include <vector> #include <string> #include <specex_unbls.h> #include <specex_psf.h> #include <specex_spot.h> #include <specex_gauss_hermite_psf.h> #include <specex_pyoptions.h> #include <pybind11/pybind11.h> #include <pybind11/numpy.h> namespace py = pybind11; namespace specex { class PyPSF : public std::enable_shared_from_this <PyPSF> { public : typedef std::shared_ptr <PyPSF> pshr; specex::PSF_p psf; vector<Spot_p> fitted_spots; PyPSF(){} int trace_ncoeff, table_nrows, nfibers; int FIBERMIN, FIBERMAX, LEGDEG, TRDEGW; double trace_WAVEMIN, trace_WAVEMAX; double table_WAVEMIN, table_WAVEMAX; long long mjd, plate_id, arc_exposure_id, NPIX_X, NPIX_Y, hSizeX, hSizeY, nparams_all, ncoeff, GHDEGX, GHDEGY; std::string camera_id; double psf_error, readout_noise, gain; std::vector<int> bundle_id, bundle_ndata, bundle_nparams; std::vector<double> bundle_chi2pdf; image_data get_trace(std::string); void set_trace(py::array, int, int); void init_traces(specex::PyOptions); void synchronize_traces(); void set_psf( std::vector<std::string>&, std::vector<double>&, std::vector<int>&, std::vector<int>& ); void SetParamsOfBundle(); }; } #endif
#include <iostream> #include <fstream> #include <string.h> #include <stdio.h> #include <stdlib.h> #include <map> #include <vector> #include <algorithm> #include <math.h> #define pb push_back using namespace std; int a, b; void input() { scanf("%d %d", &a, &b); } void printfChar(int num, char c) { for (int i = 0; i < num; i++) printf("%C", c); } void solve() { printfChar(b, '*'); printf("\n"); for (int i = 0; i < (a - 1); i++) { printfChar((b - 1)/2, ' '); printfChar(1, '*'); printfChar((b - 1)/2, ' '); printf("\n"); } } int main() { freopen("labiec27.inp", "r", stdin); input(); solve(); return 0; }
 #include <stdlib.h> #include <stdio.h> #include <string> #include <stdint.h> #include <time.h> typedef unsigned int uint; typedef unsigned int uint32; typedef int64_t int64; #ifndef _MSC_VER typedef unsigned long DWORD; #endif /* Have our own assert, so we are sure it does not get optimized away in * a release build. */ #define XX_ASSERT(expr) \ do { \ if (!(expr)) { \ fprintf(stderr, \ "Assertion failed in %s on line %d: %s\n", \ __FILE__, \ __LINE__, \ #expr); \ abort(); \ } \ } while (0) #define container_of(ptr, type, member) \ ((type *) ((char *) (ptr) - offsetof(type, member))) /* Die with fatal error. */ #define XX_FATAL(msg) \ do { \ fprintf(stderr, \ "Fatal error in %s on line %d: %s\n", \ __FILE__, \ __LINE__, \ msg); \ fflush(stderr); \ abort(); \ } while (0)
#include "robot.h" #include <iostream> #include <cmath> float sensorAngle[16] = {PI/2.0,(5.0/18.0)*PI,PI/6.0,PI/18.0,-PI/18.0,-PI/6.0,-(5.0/18.0)*PI,-PI/2.0,-PI/2.0,-(13.0/18.0)*PI,-(5.0/6.0)*PI,-(17.0/18.0)*PI,(17.0/18.0)*PI,(5.0/6.0)*PI,(13.0/18.0)*PI,PI/2.0}; int start = 1; int objectRight, objectLeft = 0; int turnRight = 1; // 0 pra vira esquerda e 1 pra direita int timeInCircle = 0; int lastTurn = 0; // 0 se virou pra direita, 1 se virou pra esquerda float leftVelocity, rightVelocity = 0; float xPosOdometry = -2.97; float yPosOdometry = -0.0976959; float tetaOdometry = 0; float gyroData = 0; float tetaPlot[5] = {0,0,0,0,0}; float xPlot[5] = {-2.97,-2.97,-2.97,-2.97,-2.97}; float yPlot[5] = {-0.0976959,-0.0976959,-0.0976959,-0.0976959,-0.0976959}; //MatrixXd destination(2); //MatrixXd power(2); // power to apply on each motor int stoppedCounter = 0; const float base_speed = 2.0; Robot::Robot(int clientID, const char* name) { std::cout << "initializing robot" << std::endl; FILE *data = fopen("gt.txt", "wt"); if (data!=NULL) fclose(data); data = fopen("sonar.txt", "wt"); if (data!=NULL) fclose(data); this->clientID = clientID; simxGetObjectHandle(clientID, name, &handle, simx_opmode_blocking); /* Get handles of sensors and actuators */ simxGetObjectHandle(clientID, "Pioneer_p3dx_leftWheel",&encoderHandle[0], simx_opmode_oneshot_wait); simxGetObjectHandle(clientID, "Pioneer_p3dx_rightWheel",&encoderHandle[1], simx_opmode_oneshot_wait); std::cout << encoderHandle[0] << std::endl; std::cout << encoderHandle[1] << std::endl; /* Get handles of sensors and actuators */ simxGetObjectHandle(clientID, "Pioneer_p3dx_leftMotor",&motorHandle[0], simx_opmode_oneshot_wait); simxGetObjectHandle(clientID, "Pioneer_p3dx_rightMotor",&motorHandle[1], simx_opmode_oneshot_wait); std::cout << motorHandle[0] << std::endl; std::cout << motorHandle[1] << std::endl; simxChar sensorName[31]; /* Connect to sonar sensors. Requires a handle per sensor. Sensor name: Pioneer_p3dx_ultrasonicSensorX, where * X is the sensor number, from 1 - 16 */ for(int i = 0; i < 16; i++) { sprintf(sensorName,"%s%d","Pioneer_p3dx_ultrasonicSensor",i+1); if (simxGetObjectHandle(clientID, sensorName, &sonarHandle[i], simx_opmode_oneshot_wait) != simx_return_ok) std::cout << "Error on connecting to sensor " + i+1; else { std::cout << "Connected to sensor\n"; /* Reads current value */ simxReadProximitySensor(clientID,sonarHandle[i],NULL,NULL,NULL,NULL,simx_opmode_streaming); } } /* Get the robot current absolute position */ simxGetObjectPosition(clientID,handle,-1,robotPosition,simx_opmode_streaming); simxGetObjectOrientation(clientID,handle,-1,robotOrientation,simx_opmode_streaming); initialPose[0]=robotPosition[0]; initialPose[1]=robotPosition[1]; initialPose[2]=robotOrientation[2]; for(int i = 0; i < 3; i++) { robotLastPosition[i] = robotPosition[i]; } /* Get the encoder data */ /*simxGetJointPosition(clientID,motorHandle[0], &encoder[0],simx_opmode_streaming); // left simxGetJointPosition(clientID,motorHandle[1], &encoder[1],simx_opmode_streaming); // right std::cout << encoder[0] << std::endl; std::cout << encoder[1] << std::endl;*/ } bool Robot::frenteLivre() { return ((sonarReadings[3]==-1 || sonarReadings[3]>0.35) && (sonarReadings[4]==-1 || sonarReadings[4]>0.35)); } bool Robot::esquerdaLivre() { return (sonarReadings[0]==-1 && sonarReadings[15]==-1); } bool Robot::direitaLivre() { return (sonarReadings[7]==-1 && sonarReadings[8]==-1); } void Robot::detectedPosition(simxFloat** position){ int i =0; simxFloat posX,posY,angle,robotRay; robotRay = 0.21; angle = robotOrientation[2]; //std::cout<<"positionRobot"<<i<<" values, x = "<<robotPosition[0]<<" y = "<<robotPosition[1]<<" gamma = "<<angle<<" bot ray"<<robotRay<<std::endl; for(i;i<8;i++){ //std::cout<<"sensor"<<i<<" values, sonar = "<<sonarReadings[i]<<" sensorAngle = "<<sensorAngle[i]<<std::endl; if(sonarReadings[i]==-1){ posX = -5000; posY = -5000; }else{ posX = robotPosition[0]+(sonarReadings[i]+robotRay)*cos(angle+sensorAngle[i]); posY = robotPosition[1]+(sonarReadings[i]+robotRay)*sin(angle+sensorAngle[i]); } position[i][0] = posX; position[i][1] = posY; //std::cout<<"sensor"<<i<<" seen obstacle, x = "<<posX<<" y = "<<posY<<std::endl; } } void Robot::updateInfo() { // std::cout << "leftMotor: " << motorHandle[0] << std::endl; // std::cout << "joint: " << encoder[0] << std::endl; // std::cout << "rightMotor: " << motorHandle[1] << std::endl; // std::cout << "joint: " << encoder[1] << std::endl; /* Update sonars */ for(int i = 0; i < NUM_SONARS; i++) { simxUChar state; // sensor state simxFloat coord[3]; // detected point coordinates [only z matters] /* simx_opmode_streaming -> Non-blocking mode */ /* read the proximity sensor * detectionState: pointer to the state of detection (0=nothing detected) * detectedPoint: pointer to the coordinates of the detected point (relative to the frame of reference of the sensor) */ if (simxReadProximitySensor(clientID,sonarHandle[i],&state,coord,NULL,NULL,simx_opmode_buffer)==simx_return_ok) { if(state > 0) sonarReadings[i] = coord[2]; else sonarReadings[i] = -1; } } for(int i = 0; i < 3; i++) { robotLastPosition[i] = robotPosition[i]; } /*std::cout << robotPosition[0] << "\t"; std::cout << robotPosition[1] << "\t"; std::cout << robotPosition[2] << std::endl;*/ /* Get the robot current position and orientation */ simxGetObjectPosition(clientID,handle,-1,robotPosition,simx_opmode_streaming); simxGetObjectOrientation(clientID,handle,-1,robotOrientation,simx_opmode_streaming); /* Get the encoder data */ simxGetJointPosition(clientID,motorHandle[0], &encoder[0],simx_opmode_streaming); // std::cout << "ok left enconder = "<< encoder[0] << std::endl; // left simxGetJointPosition(clientID,motorHandle[1], &encoder[1],simx_opmode_streaming); // std::cout << "ok right enconder = "<< encoder[1] << std::endl; // right updateOdometry(); lastEncoder[0] = encoder[0]; lastEncoder[1] = encoder[1]; } void Robot::avoidObstacles() { std::cout << "avoid!!" << std::endl; float pLeft,pRight; if (frenteLivre()) { pLeft = 3; pRight = 3; } else { if (direitaLivre()){ pLeft = 1; pRight = -1; lastTurn = 0; } else { pLeft = 1; pRight = -1; lastTurn = 1; } } move(pLeft,pRight); } void Robot::updateOdometry() { float dTeta; float tetaVelocity; float curveRadius; float deltaTeta; float dS; float dX; float dY; float dXPlot[5]; float dYPlot[5]; //***************************************************** // calculo velocidade angular em cada roda if (leftVelocity >= 0) angularVelocity[0] = (encoder[0]>=lastEncoder[0] ? encoder[0]-lastEncoder[0] : 2*PI-lastEncoder[0]+encoder[0]); else angularVelocity[0] = (encoder[0]<=lastEncoder[0] ? encoder[0]-lastEncoder[0] : encoder[0]-lastEncoder[0]-2*PI); if (std::abs(angularVelocity[0]) > 2*PI-1) angularVelocity[0] = 0; if (rightVelocity >= 0) angularVelocity[1] = (encoder[1]>=lastEncoder[1] ? encoder[1]-lastEncoder[1] : 2*PI-lastEncoder[1]+encoder[1]); else angularVelocity[1] = (encoder[1]<=lastEncoder[1] ? encoder[1]-lastEncoder[1] : encoder[1]-lastEncoder[1]-2*PI); if (std::abs(angularVelocity[1]) > 2*PI-1) angularVelocity[1] = 0; //***************************************************** leftVelocity = angularVelocity[0]*R; rightVelocity = angularVelocity[1]*R; // curveRadius = (rightVelocity != leftVelocity ? L*(rightVelocity+leftVelocity)/(rightVelocity-leftVelocity) : 0) ; // tetaVelocity = curveRadius*(angularVelocity[1]-angularVelocity[0])/(2*L); // dTeta = tetaVelocity*0.05; // dX = (angularVelocity[0]+angularVelocity[1])*R/2; // dS = 0.05*((angularVelocity[0]+angularVelocity[1])*curveRadius)/2; dTeta = (rightVelocity-leftVelocity)/L; simxGetFloatSignal(clientID,"gyroZ",&gyroData,simx_opmode_streaming); // std::cout << "gyroData = " << gyroData << " " << gyroData*0.05 << " // dTeta (rodas) = " << dTeta << std::endl; dS = (leftVelocity+rightVelocity)/2; for (int i=0; i<5; ++i) { tetaPlot[i] += ((1+i)*gyroData*0.05 + dTeta)/(2+i); xPlot[i] += dS*cos(tetaPlot[i]+(((1+i)*gyroData*0.05 + dTeta)/(2+i))/2); yPlot[i] += dS*sin(tetaPlot[i]+(((1+i)*gyroData*0.05 + dTeta)/(2+i))/2); } // deltaTeta = (leftVelocity*rightVelocity > 0 ? (4*dTeta+gyroData*0.05)/5 : (2.5*gyroData*0.05 + dTeta)/3.5); deltaTeta = 0.045*gyroData; tetaOdometry += deltaTeta; if (tetaOdometry > PI) tetaOdometry = -PI+(tetaOdometry-PI); if (tetaOdometry < -PI) tetaOdometry = PI-(tetaOdometry+PI); dX = dS*cos(tetaOdometry+deltaTeta/2); dY = dS*sin(tetaOdometry+deltaTeta/2); xPosOdometry += dX; yPosOdometry += dY; // std::cout << " odometry --> [" << xPosOdometry << "," << yPosOdometry << "," << tetaOdometry << "]" << std::endl; // std::cout << " groundTruth [x,y,teta] = [" << robotPosition[0] << "," << robotPosition[1] << "," << robotOrientation[2] << "]" << std::endl; } bool Robot::obstacleFront(){ return sonarReadings[4] != -1 && sonarReadings[4] < 0.4 || sonarReadings[3] != -1 && sonarReadings[3] < 0.4; } int Robot::blockedFront() { return ((sonarReadings[2]!=-1 && sonarReadings[2]<0.3) || sonarReadings[3]!=-1 || sonarReadings[4]!=-1 || (sonarReadings[5]!=-1 && sonarReadings[5]<0.3)); } int Robot::blockedRight() { turnRight = 1; return ((sonarReadings[6]!=-1 && sonarReadings[6]<0.3) || sonarReadings[7]!=-1 || sonarReadings[8]!=-1 || (sonarReadings[9]!=-1 && sonarReadings[9]<0.3)); } int Robot::blockedLeft() { turnRight = 0; return ((sonarReadings[14]!=-1 && sonarReadings[14]<0.3) || sonarReadings[15]!=-1 || sonarReadings[0]!=-1 || (sonarReadings[1]!=-1 && sonarReadings[1]<0.3)); } //int Robot::blockedLeft() { // return ((sonarReadings[15]!=-1 && sonarReadings[15]<0.75) || (sonarReadings[0]!=-1 && sonarReadings[0]<0.75)); //} void Robot::exploreStrategy(){ if (!frenteLivre() || (esquerdaLivre() && direitaLivre())) { avoidObstacles(); error_i = 0; } else { if (!direitaLivre()) wallFollowPID(sonarReadings[8], sonarReadings[7]); else wallFollowPID(sonarReadings[0], sonarReadings[15]); } } float Robot::wallFollowPID(float distance1, float distance2){ //if no wall detected, move forward until find a wall //when a wall is close, adapt individual wheels speed to start following it //if there is an obstacle in front of me, find a way to avoid it if(distance1 == -1 && distance2 == -1 ){ error_i = 0; last_error = 0; // std::cout << "PID - NO WALL" << std::endl; move(base_speed, base_speed); return base_speed; } const float minAcceptedDiff = 0.005; const float maxDistToWall = 1; const float infiniteDistance = 1.5; float rightwheelSpeed = base_speed ; float leftWheelSpeed; float diff = std::abs( distance1 - distance2 ); if(diff > minAcceptedDiff ){ if(distance1 == -1) distance1 = infiniteDistance; if(distance2 == -1) distance2 = infiniteDistance; float Kp = 3; float Ki = 0.2; float Kd = 0.7; float error = distance2 - distance1; //error is difference between two side sensors float diff_error = error - last_error; error_i += error; leftWheelSpeed = base_speed + Kp * error + Ki * error_i + Kd * diff_error; // std::cout << "PID - NORMAL | error: " << error << " ; error_i: " << error_i << " ; diff_error: " << diff_error << std::endl; last_error = error; } else if( distance1 > maxDistToWall) { // std::cout << "PID - BIG DISTANCE TO WALL" << std::endl; leftWheelSpeed = base_speed ; } else { // std::cout << "PID - ELSE" << std::endl; leftWheelSpeed = base_speed; } move(leftWheelSpeed, rightwheelSpeed); return leftWheelSpeed; } void Robot::moveForward() { timeInCircle = 0; float vRight,vLeft; if (blockedFront()) { // std::cout << "--> FRENTE BLOQUEADA"<< std::endl; vRight = -1; vLeft = 1; } else { // std::cout << "--> FRENTE LIVRE"<< std::endl; vRight = 2; vLeft = 2; } move(vLeft,vRight); } void Robot::moveInCircle() { float vRight,vLeft; if (blockedFront()) { // std::cout << "--> CIRCULANDO FRENTE BLOQUEADA"<< std::endl; vRight = -2; vLeft = 2; } else { // std::cout << "--> CIRCULANDO FRENTE LIVRE"<< std::endl; if (turnRight) { // std::cout << "--> CIRCULANDO --> turnRight"<< std::endl; vRight = 1.5; vLeft = 3; } else { // std::cout << "--> CIRCULANDO --> turn left!"<< std::endl; vRight = 3; vLeft = 1.5; } timeInCircle++; } move(vLeft,vRight); } void Robot::updatePosition() { objectRight = blockedRight(); objectLeft = blockedLeft(); if (start) { // std::cout << "--> TO PROCURANDOO A PAREDE..."<< std::endl; moveForward(); if (objectRight || objectLeft) start = 0; } else { if (objectRight || objectLeft) { // std::cout << "--> Paredinha aqui do lado..."<< std::endl; moveForward(); } else { // std::cout << "--> CADE A PAREDE??"<< std::endl; moveInCircle(); if (timeInCircle > 2000) start = 1; } } } void Robot::writeGT() { /* write data to file */ /* file format: robotPosition[x] robotPosition[y] robotPosition[z] robotLastPosition[x] robotLastPosition[y] robotLastPosition[z] * encoder[0] encoder[1] lastEncoder[0] lastEncoder[1] */ float posX; float posY; float robotX; float robotY; FILE *data = fopen("gt.txt", "at"); if (data!=NULL) { for (int i=0; i<3; ++i) fprintf(data, "%.2f\t",robotPosition[i]); for (int i=0; i<3; ++i) fprintf(data, "%.2f\t",robotLastPosition[i]); for (int i=0; i<3; ++i) fprintf(data, "%.2f\t",robotOrientation[i]); for (int i=0; i<2; ++i) fprintf(data, "%.2f\t",encoder[i]); for (int i=0; i<2; ++i) fprintf(data, "%.2f\t",lastEncoder[i]); fprintf(data, "%.2f\t",xPosOdometry); fprintf(data, "%.2f\t",yPosOdometry); fprintf(data, "%.2f\t",tetaOdometry); for (int i=0; i<5; ++i) { fprintf(data, "%.2f\t",xPlot[i]); fprintf(data, "%.2f\t",yPlot[i]); } for (int i=0; i<NUM_SONARS; ++i) { robotX = xPosOdometry; // robotPosition[0] ou xPosOdometry robotY = yPosOdometry; // robotPosition[1] ou yPosOdometry posX = (sonarReadings[i] > 0.2 && sonarReadings[i] < 0.95 ? robotX+(sonarReadings[i]+0.2)*cos(robotOrientation[2]+sensorAngle[i]) : 4); // obstacle X fprintf(data, "%.2f\t",posX); posY = (sonarReadings[i] > 0.2 && sonarReadings[i] < 0.95 ? robotPosition[1]+(sonarReadings[i]+0.2)*sin(robotOrientation[2]+sensorAngle[i]) : 4); // obstacle Y fprintf(data, "%.2f\t",posY); // if (i == 9) // std::cout << "r = " << robotX << "," << robotPosition[1] << "\t s = " << posX << "," << posY << " angle = " << sensorAngle[i] << " sin = " << sin(robotOrientation[2]+sensorAngle[i]) << std::endl; } fprintf(data, "\n"); fflush(data); fclose(data); } else std::cout << "Unable to open file"; } void Robot::writeSonars() { /* write data to file */ /* file format: robotPosition[x] robotPosition[y] robotPosition[z] robotLastPosition[x] robotLastPosition[y] robotLastPosition[z] * encoder[0] encoder[1] lastEncoder[0] lastEncoder[1] */ FILE *data = fopen("sonar.txt", "at"); if (data!=NULL) { if (data!=NULL) { for (int i=0; i<NUM_SONARS; ++i) { fprintf(data, "%.2f\t",sonarReadings[i]); } fprintf(data, "\n"); std::cout << std::endl; fflush(data); fclose(data); } } } void Robot::printPosition() { simxFloat position[3]; //simxGetObjectPosition(_clientID, _handle, -1, position, simx_opmode_streaming); //std::cout << "[" << position[0] << ", " << position[1] << ", " << position[2] << "]" << std::endl; } void Robot::move(float vLeft, float vRight) { simxSetJointTargetVelocity(clientID, motorHandle[0], vLeft, simx_opmode_streaming); simxSetJointTargetVelocity(clientID, motorHandle[1], vRight, simx_opmode_streaming); // std::cout << "*****> vLeft = " << vLeft << " angularLeft = " << angularVelocity[0] << " leftVelocity = " << leftVelocity << std::endl; }
/* Hackerrank problem: https://www.hackerrank.com/challenges/vector-erase/problem */ #include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> int main() { int n, start, number, startDelete, endDelete; std::vector<int> v; std::cin >> n; for(int i = 0; i < n; i++){ std::cin >> number; v.push_back(number); } std::cin >> start; if( start < v.size() ) v.erase(v.begin() + start - 1); std::cin >> startDelete >> endDelete; if( startDelete < endDelete && endDelete < v.size() ) v.erase(v.begin() + startDelete - 1, v.begin() + endDelete - 1); std::cout << v.size() << std::endl; for(auto _v : v) std::cout << _v << " "; std::cout << std::endl; }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 "Message.h" #include "Reader.h" #include "ReaderConfig.h" #include "MessageId.h" #include "ThreadSafeDeferred.h" #include <pulsar/c/result.h> #include <pulsar/c/reader.h> #include <atomic> #include <thread> #include <future> Napi::FunctionReference Reader::constructor; void Reader::Init(Napi::Env env, Napi::Object exports) { Napi::HandleScope scope(env); Napi::Function func = DefineClass(env, "Reader", { InstanceMethod("readNext", &Reader::ReadNext), InstanceMethod("hasNext", &Reader::HasNext), InstanceMethod("isConnected", &Reader::IsConnected), InstanceMethod("seek", &Reader::Seek), InstanceMethod("seekTimestamp", &Reader::SeekTimestamp), InstanceMethod("close", &Reader::Close), }); constructor = Napi::Persistent(func); constructor.SuppressDestruct(); } struct ReaderListenerProxyData { std::shared_ptr<pulsar_message_t> cMessage; Reader *reader; std::function<void(void)> callback; ReaderListenerProxyData(std::shared_ptr<pulsar_message_t> cMessage, Reader *reader, std::function<void(void)> callback) : cMessage(cMessage), reader(reader), callback(callback) {} }; void ReaderListenerProxy(Napi::Env env, Napi::Function jsCallback, ReaderListenerProxyData *data) { Napi::Object msg = Message::NewInstance({}, data->cMessage); Reader *reader = data->reader; Napi::Value ret = jsCallback.Call({msg, reader->Value()}); if (ret.IsPromise()) { Napi::Promise promise = ret.As<Napi::Promise>(); Napi::Value thenValue = promise.Get("then"); if (thenValue.IsFunction()) { Napi::Function then = thenValue.As<Napi::Function>(); Napi::Function callback = Napi::Function::New(env, [data](const Napi::CallbackInfo &info) { data->callback(); }); then.Call(promise, {callback}); return; } } data->callback(); } void ReaderListener(pulsar_reader_t *rawReader, pulsar_message_t *rawMessage, void *ctx) { std::shared_ptr<pulsar_message_t> cMessage(rawMessage, pulsar_message_free); ReaderListenerCallback *readerListenerCallback = (ReaderListenerCallback *)ctx; Reader *reader = (Reader *)readerListenerCallback->reader; if (readerListenerCallback->callback.Acquire() != napi_ok) { return; } std::promise<void> promise; std::future<void> future = promise.get_future(); std::unique_ptr<ReaderListenerProxyData> dataPtr( new ReaderListenerProxyData(cMessage, reader, [&promise]() { promise.set_value(); })); readerListenerCallback->callback.BlockingCall(dataPtr.get(), ReaderListenerProxy); readerListenerCallback->callback.Release(); future.wait(); } void Reader::SetCReader(std::shared_ptr<pulsar_reader_t> cReader) { this->cReader = cReader; } void Reader::SetListenerCallback(ReaderListenerCallback *listener) { if (this->listener != nullptr) { // It is only safe to set the listener once for the lifecycle of the Reader return; } if (listener != nullptr) { listener->reader = this; // If a reader listener is set, the Reader instance is kept alive even if it goes out of scope in JS code. this->Ref(); this->listener = listener; } } Reader::Reader(const Napi::CallbackInfo &info) : Napi::ObjectWrap<Reader>(info), listener(nullptr) {} struct ReaderNewInstanceContext { ReaderNewInstanceContext(std::shared_ptr<ThreadSafeDeferred> deferred, std::shared_ptr<pulsar_client_t> cClient, std::shared_ptr<ReaderConfig> readerConfig) : deferred(deferred), cClient(cClient), readerConfig(readerConfig){}; std::shared_ptr<ThreadSafeDeferred> deferred; std::shared_ptr<pulsar_client_t> cClient; std::shared_ptr<ReaderConfig> readerConfig; static void createReaderCallback(pulsar_result result, pulsar_reader_t *rawReader, void *ctx) { auto instanceContext = static_cast<ReaderNewInstanceContext *>(ctx); auto deferred = instanceContext->deferred; auto cClient = instanceContext->cClient; auto readerConfig = instanceContext->readerConfig; delete instanceContext; if (result != pulsar_result_Ok) { return deferred->Reject(std::string("Failed to create reader: ") + pulsar_result_str(result)); } auto cReader = std::shared_ptr<pulsar_reader_t>(rawReader, pulsar_reader_free); deferred->Resolve([cReader, readerConfig](const Napi::Env env) { Napi::Object obj = Reader::constructor.New({}); Reader *reader = Reader::Unwrap(obj); reader->SetCReader(cReader); reader->SetListenerCallback(readerConfig->GetListenerCallback()); return obj; }); } }; Napi::Value Reader::NewInstance(const Napi::CallbackInfo &info, std::shared_ptr<pulsar_client_t> cClient) { auto deferred = ThreadSafeDeferred::New(info.Env()); Napi::Object config = info[0].As<Napi::Object>(); auto readerConfig = std::make_shared<ReaderConfig>(config, &ReaderListener); const std::string &topic = readerConfig->GetTopic(); if (topic.empty()) { deferred->Reject(std::string("Topic is required and must be specified as a string when creating reader")); return deferred->Promise(); } if (readerConfig->GetCStartMessageId().get() == nullptr) { deferred->Reject(std::string( "StartMessageId is required and must be specified as a MessageId object when creating reader")); return deferred->Promise(); } auto ctx = new ReaderNewInstanceContext(deferred, cClient, readerConfig); pulsar_client_create_reader_async(cClient.get(), topic.c_str(), readerConfig->GetCStartMessageId().get(), readerConfig->GetCReaderConfig().get(), &ReaderNewInstanceContext::createReaderCallback, ctx); return deferred->Promise(); } // We still need a read worker because the c api is missing the equivalent async definition class ReaderReadNextWorker : public Napi::AsyncWorker { public: ReaderReadNextWorker(const Napi::Promise::Deferred &deferred, std::shared_ptr<pulsar_reader_t> cReader, int64_t timeout = -1) : AsyncWorker(Napi::Function::New(deferred.Promise().Env(), [](const Napi::CallbackInfo &info) {})), deferred(deferred), cReader(cReader), timeout(timeout) {} ~ReaderReadNextWorker() {} void Execute() { pulsar_result result; pulsar_message_t *rawMessage; if (timeout > 0) { result = pulsar_reader_read_next_with_timeout(this->cReader.get(), &rawMessage, timeout); } else { result = pulsar_reader_read_next(this->cReader.get(), &rawMessage); } if (result != pulsar_result_Ok) { SetError(std::string("Failed to receive message: ") + pulsar_result_str(result)); } this->cMessage = std::shared_ptr<pulsar_message_t>(rawMessage, pulsar_message_free); } void OnOK() { Napi::Object obj = Message::NewInstance({}, this->cMessage); this->deferred.Resolve(obj); } void OnError(const Napi::Error &e) { this->deferred.Reject(Napi::Error::New(Env(), e.Message()).Value()); } private: Napi::Promise::Deferred deferred; std::shared_ptr<pulsar_reader_t> cReader; std::shared_ptr<pulsar_message_t> cMessage; int64_t timeout; }; Napi::Value Reader::ReadNext(const Napi::CallbackInfo &info) { Napi::Promise::Deferred deferred = Napi::Promise::Deferred::New(info.Env()); if (info[0].IsUndefined()) { ReaderReadNextWorker *wk = new ReaderReadNextWorker(deferred, this->cReader); wk->Queue(); } else { Napi::Number timeout = info[0].As<Napi::Object>().ToNumber(); ReaderReadNextWorker *wk = new ReaderReadNextWorker(deferred, this->cReader, timeout.Int64Value()); wk->Queue(); } return deferred.Promise(); } Napi::Value Reader::HasNext(const Napi::CallbackInfo &info) { int value = 0; pulsar_result result = pulsar_reader_has_message_available(this->cReader.get(), &value); if (result != pulsar_result_Ok) { Napi::Error::New( info.Env(), "Failed to check if next message is available: " + std::string(pulsar_result_str(result))) .ThrowAsJavaScriptException(); return Napi::Boolean::New(info.Env(), false); } else if (value == 1) { return Napi::Boolean::New(info.Env(), true); } else { return Napi::Boolean::New(info.Env(), false); } } Napi::Value Reader::IsConnected(const Napi::CallbackInfo &info) { Napi::Env env = info.Env(); return Napi::Boolean::New(env, pulsar_reader_is_connected(this->cReader.get())); } Napi::Value Reader::Seek(const Napi::CallbackInfo &info) { auto obj = info[0].As<Napi::Object>(); auto *msgId = MessageId::Unwrap(obj); auto deferred = ThreadSafeDeferred::New(Env()); auto ctx = new ExtDeferredContext(deferred); pulsar_reader_seek_async( this->cReader.get(), msgId->GetCMessageId().get(), [](pulsar_result result, void *ctx) { auto deferredContext = static_cast<ExtDeferredContext *>(ctx); auto deferred = deferredContext->deferred; delete deferredContext; if (result != pulsar_result_Ok) { deferred->Reject(std::string("Failed to seek message by id: ") + pulsar_result_str(result)); } else { deferred->Resolve(THREADSAFE_DEFERRED_RESOLVER(env.Null())); } }, ctx); return deferred->Promise(); } Napi::Value Reader::SeekTimestamp(const Napi::CallbackInfo &info) { Napi::Number timestamp = info[0].As<Napi::Object>().ToNumber(); auto deferred = ThreadSafeDeferred::New(Env()); auto ctx = new ExtDeferredContext(deferred); pulsar_reader_seek_by_timestamp_async( this->cReader.get(), timestamp.Int64Value(), [](pulsar_result result, void *ctx) { auto deferredContext = static_cast<ExtDeferredContext *>(ctx); auto deferred = deferredContext->deferred; delete deferredContext; if (result != pulsar_result_Ok) { deferred->Reject(std::string("Failed to seek message by timestamp: ") + pulsar_result_str(result)); } else { deferred->Resolve(THREADSAFE_DEFERRED_RESOLVER(env.Null())); } }, ctx); return deferred->Promise(); } Napi::Value Reader::Close(const Napi::CallbackInfo &info) { auto deferred = ThreadSafeDeferred::New(Env()); auto ctx = new ExtDeferredContext(deferred); this->Cleanup(); pulsar_reader_close_async( this->cReader.get(), [](pulsar_result result, void *ctx) { auto deferredContext = static_cast<ExtDeferredContext *>(ctx); auto deferred = deferredContext->deferred; delete deferredContext; if (result != pulsar_result_Ok) { deferred->Reject(std::string("Failed to close reader: ") + pulsar_result_str(result)); } else { deferred->Resolve(THREADSAFE_DEFERRED_RESOLVER(env.Null())); } }, ctx); return deferred->Promise(); } void Reader::Cleanup() { if (this->listener != nullptr) { this->listener->callback.Release(); this->Unref(); this->listener = nullptr; } } Reader::~Reader() { this->Cleanup(); }
#include "KeyboardSubscriber.h" namespace Game { void KeyboardSubscriber::onEvent(sf::Event event) { switch (event.type) { case sf::Event::KeyPressed:onKeyPress(event.key); break; case sf::Event::KeyReleased:onKeyUp(event.key); break; } } }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4; c-file-style: "stroustrup" -*- * * Copyright (C) 2008-2011 Opera Software ASA. 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 MEDIA_PLAYER_SUPPORT #include "modules/cache/cache_ctxman_multimedia.h" #include "modules/cache/url_dd.h" #include "modules/media/src/coremediaplayer.h" #include "modules/media/src/mediasource.h" #include "modules/media/src/mediasourceutil.h" #include "modules/pi/OpSystemInfo.h" #include "modules/prefs/prefsmanager/collections/pc_network.h" #include "modules/security_manager/include/security_manager.h" #include "modules/url/url2.h" #include "modules/url/url_man.h" #include "modules/url/tools/content_detector.h" // the maximum number of bytes to wait for when needing a seek #define MEDIA_SOURCE_MAX_WAIT (64*1024) // the minimum number of bytes to fetch (to reduce roundtrips) // 8500 happens to be the maximum size requested by GstMediaPlayer. // should perhaps be a tweak? // MUST be smaller than MEDIA_SOURCE_MAX_WAIT #define MEDIA_SOURCE_MIN_SIZE 8500 // the limits for pausing and resuming the transfer when using the // streaming cache, expressed as remaining bytes before overwrite. #define STREAMING_CACHE_PAUSE_LIMIT (64*1024) #define STREAMING_CACHE_RESUME_LIMIT (128*1024) OP_STATUS MediaSourceManagerImpl::GetSource(MediaSource*& source, const URL& url, const URL& referer_url, MessageHandler* message_handler) { OP_ASSERT(!url.IsEmpty()); URL use_url = url; // GetUrlWithMediaContext(url); // Try getting existing instance. MediaSourceImpl* sourceimpl; if (OpStatus::IsSuccess(m_sources.GetData(reinterpret_cast<const void*>(use_url.Id()), reinterpret_cast<void**>(&sourceimpl)))) { if (!sourceimpl->IsStreaming()) { // All is well, use this source. sourceimpl->m_refcount++; source = sourceimpl; return OpStatus::OK; } else { // A streaming source cannot be shared, make a unique copy // of the URL and create a new instance instead. use_url = g_url_api->MakeUniqueCopy(use_url); OP_ASSERT(use_url.GetAttribute(URL::KUnique)); if (use_url.IsEmpty()) return OpStatus::ERR; } } // Create a new instance. // Decide what message handler to use. If no message handler is given as input, use // the global one. The global one will not work from widgets. if (!message_handler) message_handler = g_main_message_handler; // Create new instance. OpAutoPtr<MediaSourceImpl> source_safe(OP_NEW(MediaSourceImpl, (use_url, referer_url, message_handler))); if (!source_safe.get()) return OpStatus::ERR_NO_MEMORY; RETURN_IF_ERROR(source_safe->Init()); // Add it to the set of MediaSource instances. RETURN_IF_ERROR(m_sources.Add(reinterpret_cast<const void*>(use_url.Id()), reinterpret_cast<void*>(source_safe.get()))); source_safe->m_refcount++; source = source_safe.release(); return OpStatus::OK; } OP_STATUS MediaSourceManagerImpl::GetSource(MediaSource*& source, OpMediaHandle handle) { // Theoretically OpMediaHandle could also be a different type of // MediaPlayer but it is only CoreMediaPlayer instances that use // the OpMediaSourceManager. Having a different type of player // here would indicate a serious bug. CoreMediaPlayer* playerimpl = static_cast<CoreMediaPlayer*>(handle); // Get the source from the player and increase refcount. source = playerimpl->GetSource(); if (!source) { OP_ASSERT(!"Don't use OpMediaSource::Create when OpMediaManager::CanPlayURL returned TRUE"); return OpStatus::ERR_NOT_SUPPORTED; } static_cast<MediaSourceImpl*>(source)->m_refcount++; return OpStatus::OK; } void MediaSourceManagerImpl::PutSource(MediaSource* source) { // We know that this is a MediaSourceImpl instance because we created it. MediaSourceImpl* sourceimpl = static_cast<MediaSourceImpl*>(source); if (--sourceimpl->m_refcount == 0) { MediaSourceImpl* removed; OP_STATUS status = m_sources.Remove(reinterpret_cast<const void*>(sourceimpl->m_key_url.Id()), reinterpret_cast<void**>(&removed)); OP_ASSERT(OpStatus::IsSuccess(status)); OpStatus::Ignore(status); OP_ASSERT(removed == sourceimpl); OP_DELETE(removed); } #ifdef DEBUG_ENABLE_OPASSERT else { // Verify that we actually created this source. MediaSourceImpl* existing; OP_ASSERT(OpStatus::IsSuccess(m_sources.GetData(reinterpret_cast<const void*>(sourceimpl->m_key_url.Id()), reinterpret_cast<void**>(&existing))) && sourceimpl == existing); } #endif // DEBUG_ENABLE_OPASSERT } #if 0 URL MediaSourceManagerImpl::GetUrlWithMediaContext(const URL& url) { // Don't override anything but the default context for now. if (url.GetContextId() != 0) return url; // Create new context manager if it doesn't exists already. if (!m_url_context_id) { m_url_context_id = urlManager->GetNewContextID(); OpFileFolder media_cache_folder; if (OpStatus::IsError(g_folder_manager->AddFolder(OPFILE_CACHE_FOLDER, UNI_L("media"), &media_cache_folder))) { OP_ASSERT(!"Failed to create folder for dedicated media cache. Falling back to default"); return url; } Context_Manager_Multimedia::CreateManager(m_url_context_id, media_cache_folder, media_cache_folder, FALSE, PrefsCollectionNetwork::MediaCacheSize); } // Create new url with the media context. const OpStringC tmp_url_str = url.GetAttribute(URL::KUniName_With_Fragment_Username_Password_NOT_FOR_UI, URL::KNoRedirect); return g_url_api->GetURL(tmp_url_str, m_url_context_id); } #endif static const OpMessage source_msgs[] = { MSG_MEDIA_SOURCE_ENSURE_BUFFERING, MSG_MEDIA_SOURCE_NOTIFY_LISTENER }; static const OpMessage url_msgs[] = { MSG_HEADER_LOADED, MSG_URL_DATA_LOADED, MSG_URL_LOADING_FAILED, MSG_URL_MOVED }; MediaSourceImpl::MediaSourceImpl(const URL& url, const URL& referer_url, MessageHandler* message_handler) : m_refcount(0), m_key_url(url), m_referer_url(referer_url), m_url_dd(NULL), m_message_handler(message_handler), m_state(NONE), m_clamp_request(FALSE), m_pending_ensure(FALSE), m_verified_content_type(FALSE), m_read_offset(0) { } MediaSourceImpl::~MediaSourceImpl() { OP_ASSERT(m_refcount == 0); OP_DELETE(m_url_dd); StopBuffering(); if (m_message_handler.get()) m_message_handler->UnsetCallBacks(this); } OP_STATUS MediaSourceImpl::Init() { m_use_url.SetURL(m_key_url); // Purge the resource from cache if it is expired or we are using // the streaming cache. Cache invalidation during the lifetime of // the MediaSourceImpl instance is not supported, see CORE-27748. if (m_use_url->Expired(TRUE) || IsStreaming()) m_use_url->Unload(); m_use_url->SetAttribute(URL::KMultimedia, TRUE); m_use_url->SetAttribute(URL::KSendAcceptEncoding, FALSE); return SetCallBacks(); } OP_STATUS MediaSourceImpl::SetCallBacks() { RETURN_IF_ERROR(m_message_handler->SetCallBackList(this, reinterpret_cast<MH_PARAM_1>(this), source_msgs, ARRAY_SIZE(source_msgs))); return m_message_handler->SetCallBackList(this, static_cast<MH_PARAM_1>(m_use_url->Id()), url_msgs, ARRAY_SIZE(url_msgs)); } void MediaSourceImpl::HandleClientChange() { // Invoke EnsureBuffering asynchronously. if (!m_pending_ensure) { m_message_handler->PostMessage(MSG_MEDIA_SOURCE_ENSURE_BUFFERING, reinterpret_cast<MH_PARAM_1>(this), 0); m_pending_ensure = TRUE; } } #ifdef _DEBUG static Debug& operator<<(Debug& d, const MediaByteRange& range) { d << "["; if (range.IsEmpty()) { d << "empty"; } else { d << (long)range.start; d << ", "; if (range.IsFinite()) d << (long)range.end; else d << "Inf"; } d << "]"; return d; } #endif void MediaSourceImpl::CalcRequest(MediaByteRange& request) { if (IsStreaming()) { // When streaming we only consider the pending range (if any). // When there are no clients, request the entire resource. // To support preload together with streaming, care must be // taken to not restart a preload request [0,Inf] as soon as // data has been evicted and the cached range is e.g. // [500,1000499] if there is no pending request in that range. if (!m_clients.Empty()) { MediaByteRange preload; // unused ReduceRanges(m_clients, request, preload); if (!request.IsEmpty()) { request.SetLength(FILE_LENGTH_NONE); IntersectWithUnavailable(request, m_use_url); if (!request.IsEmpty()) request.SetLength(FILE_LENGTH_NONE); } } else { request.start = 0; } // At this point we should have an unbounded range, but it may // be clamped to the resource length below. OP_ASSERT(!request.IsFinite()); } else { // When not streaming (using multiple range disk cache), both // pending and preload requests are taken into account. // // Example 1: Everything should be preloaded, but since there is a // pending read, start buffering from that offset first. Also, // don't refetch the end of the resource. // // resource: <----------------------> // buffered: <--> <---> // pending: <----> // preload: <----------------------> // request: <--------> // // Example 2: The requested preload is already buffered, so the // request is the empty range. // // resource: <----------------------> // buffered: <--------> // pending: empty range // preload: <-----> // request: empty range MediaByteRange pending, preload; ReduceRanges(m_clients, pending, preload); CombineRanges(pending, preload, request); IntersectWithUnavailable(request, m_use_url); } if (!request.IsEmpty()) { // Extra restrictions if resource length is known (this won't // be needed after CORE-30311 is fixed). OpFileLength resource_length = GetTotalBytes(); if (resource_length > 0) { OP_ASSERT(request.start <= resource_length); MediaByteRange resource(0, resource_length - 1); // Clamp request to resource. request.IntersectWith(resource); // Increase size if it is unreasonably small at the end... if (!request.IsEmpty() && request.Length() < MEDIA_SOURCE_MIN_SIZE && resource.Length() >= MEDIA_SOURCE_MIN_SIZE && request.end == resource.end) { // ... but only if nothing in that range is available. MediaByteRange cand_request(resource_length - MEDIA_SOURCE_MIN_SIZE, resource_length - 1); OP_ASSERT(cand_request.Length() == MEDIA_SOURCE_MIN_SIZE); IntersectWithUnavailable(cand_request, m_use_url); if (cand_request.Length() == MEDIA_SOURCE_MIN_SIZE) request = cand_request; } } } OP_NEW_DBG("CalcRequest", "MediaSource"); OP_DBG(("request: ") << request); } void MediaSourceImpl::EnsureBuffering() { switch (EnsureBufferingInternal()) { case NONE: break; case STARTED: m_state = STARTED; break; case IDLE: if (VerifyContentType()) { m_state = IDLE; for (OpListenersIterator iter(m_listeners); m_listeners.HasNext(iter);) m_listeners.GetNext(iter)->OnIdle(this); } else { OP_ASSERT(m_state == FAILED); } break; case FAILED: LoadFailed(); break; default: OP_ASSERT(!"Unexpected state change"); } } MediaSourceImpl::State MediaSourceImpl::EnsureBufferingInternal() { MediaByteRange request; CalcRequest(request); if (!request.IsEmpty()) { m_clamp_request = FALSE; if (NeedRestart(request)) { StopBuffering(); return StartBuffering(request); } // The request wasn't restarted, so it may need to be clamped // by aborting it once enough data has become available. if (request.IsFinite() && !IsStreaming()) { OpFileLength loading_end = FILE_LENGTH_NONE; m_use_url->GetAttribute(URL::KHTTPRangeEnd, &loading_end); if (loading_end == FILE_LENGTH_NONE || request.end < loading_end) m_clamp_request = TRUE; } } else { // We have all the data we wanted, so stop buffering if possible. switch (m_state) { case NONE: // Already loaded (data: URL or in cache). return IDLE; case IDLE: case FAILED: // not loading break; case STARTED: case HEADERS: case LOADING: case PAUSED: // Only stop a load if it's in fact already complete or if // it's one that we can later resume. However, when using // the streaming cache, continue loading until either the // cache fills up and PauseBuffering() is called or (if // the request fits in cache) IsLoadedURL() is true. if (IsLoadedURL(m_use_url) || (IsResumableURL(m_use_url) && !IsStreaming())) { StopBuffering(); return IDLE; } break; } } return NONE; } MediaSourceImpl::State MediaSourceImpl::StartBuffering(const MediaByteRange& request) { #ifdef DEBUG_ENABLE_OPASSERT OP_ASSERT(m_state == NONE || IsResumableURL(m_use_url)); BOOL available = FALSE; OpFileLength dummy; GetPartialCoverage(request.start, available, dummy); OP_ASSERT(!available); #endif // DEBUG_ENABLE_OPASSERT // Never retry a failed load. if (m_state == FAILED) return NONE; // Treat javascript: URI as an error. if (m_use_url->Type() == URL_JAVASCRIPT) return FAILED; if (m_use_url->Type() == URL_HTTP || m_use_url->Type() == URL_HTTPS) { // HTTP byte ranges are inclusive. m_use_url->SetAttribute(URL::KHTTPRangeStart, &request.start); m_use_url->SetAttribute(URL::KHTTPRangeEnd, &request.end); OP_NEW_DBG("StartBuffering", "MediaSource"); OP_DBG(("") << request); } URL_LoadPolicy loadpolicy(FALSE, URL_Reload_Full, FALSE, FALSE); OP_ASSERT(m_message_handler.get()); CommState cs = m_use_url->LoadDocument(m_message_handler, m_referer_url, loadpolicy); switch (cs) { default: OP_ASSERT(!"Unhandled CommState"); case COMM_REQUEST_FAILED: return FAILED; case COMM_LOADING: return STARTED; case COMM_REQUEST_FINISHED: return IDLE; } } void MediaSourceImpl::StopBuffering() { OP_NEW_DBG("StopBuffering", "MediaSource"); OP_DBG(("")); OP_ASSERT(m_message_handler.get()); m_use_url->StopLoading(m_message_handler); } void MediaSourceImpl::PauseBuffering() { OP_NEW_DBG("PauseBuffering", "MediaSource"); OP_DBG(("")); OP_ASSERT(m_state == LOADING && IsStreaming()); m_use_url->SetAttribute(URL::KPauseDownload, TRUE); m_state = PAUSED; for (OpListenersIterator iter(m_listeners); m_listeners.HasNext(iter);) m_listeners.GetNext(iter)->OnIdle(this); } void MediaSourceImpl::ResumeBuffering() { OP_NEW_DBG("ResumeBuffering", "MediaSource"); OP_DBG(("")); OP_ASSERT(m_state == PAUSED && IsStreaming()); m_use_url->SetAttribute(URL::KPauseDownload, FALSE); m_state = LOADING; } OpFileLength MediaSourceImpl::GetTotalBytes() { // For non-resumable, non-streaming resources we know the duration // for sure once it fully loaded. Otherwise we have to trust the // Content-Length header, or return 0 if there is none. if (!IsResumableURL(m_use_url) && !IsStreaming() && IsLoadedURL(m_use_url)) return m_use_url->ContentLoaded(); return m_use_url->GetContentSize(); } BOOL MediaSourceImpl::IsStreaming() { return m_use_url->UseStreamingCache(); } BOOL MediaSourceImpl::IsSeekable() { return IsResumableURL(m_use_url) || IsLoadedURL(m_use_url); } #ifdef _DEBUG static Debug& operator<<(Debug& d, const OpMediaByteRanges* ranges) { UINT32 length = ranges->Length(); for (UINT32 i = 0; i < length; i++) { if (i > 0) d << ", "; d << "["; d << (long)ranges->Start(i); d << ", "; d << (long)ranges->End(i); d << ")"; } return d; } #endif OP_STATUS MediaSourceImpl::GetBufferedBytes(const OpMediaByteRanges** ranges) { if (!ranges) return OpStatus::ERR_NULL_POINTER; // Note: Multimedia_Storage::GetSortedCoverage requires the output // vector to be empty instead of reusing it. See CORE-37943. m_buffered.ranges.DeleteAll(); RETURN_IF_ERROR(m_use_url->GetSortedCoverage(m_buffered.ranges)); *ranges = &m_buffered; #ifdef DEBUG_ENABLE_OPASSERT // Verify that the ranges are normalized. OpFileLength size = GetTotalBytes(); OpFileLength prev_end = FILE_LENGTH_NONE; for (UINT32 i = 0; i < m_buffered.Length(); i++) { OpFileLength start = m_buffered.Start(i); OpFileLength end = m_buffered.End(i); OP_ASSERT(start != FILE_LENGTH_NONE); OP_ASSERT(end > 0 && end != FILE_LENGTH_NONE); OP_ASSERT(prev_end == FILE_LENGTH_NONE || prev_end < start); OP_ASSERT(start < end); OP_ASSERT(size == 0 || size >= end); prev_end = end; } OP_NEW_DBG("GetBufferedBytes", "MediaSource"); OP_DBG(("size: %d; buffered: ", size) << *ranges); #endif // DEBUG_ENABLE_OPASSERT return OpStatus::OK; } BOOL MediaSourceImpl::NeedRestart(const MediaByteRange& request) { OP_ASSERT(!request.IsEmpty()); // Note: this function assumes that request is not in cache // If not loading we certainly need to start. if (m_state == NONE || m_state == IDLE) return TRUE; // Only restart resumable resources. if (!IsResumableURL(m_use_url)) return FALSE; // Get the currently loading range. MediaByteRange loading; m_use_url->GetAttribute(URL::KHTTPRangeStart, &loading.start); m_use_url->GetAttribute(URL::KHTTPRangeEnd, &loading.end); OP_ASSERT(!loading.IsEmpty()); // When streaming, adjust the loading range to not include what // has already been evicted from the cache. Note: This must not be // done for a request that was just started, as the cache can then // contain data from the previous request which is not relevant. if (m_state >= LOADING && IsStreaming()) { BOOL available = FALSE; OpFileLength length = 0; GetPartialCoverage(loading.start, available, length); if (!available && (!loading.IsFinite() || length < loading.Length())) loading.start += length; } // Restart if request is before currently loading range. if (request.start < loading.start) return TRUE; // Restart if request is after currently loading range. if (loading.IsFinite() && request.start > loading.end) return TRUE; // request is now a subset of loading, check how much we have left // to load until request.start. BOOL available = FALSE; OpFileLength length = 0; GetPartialCoverage(loading.start, available, length); if (!available) length = 0; if (request.start > loading.start + length) { // FIXME: calculate download rate and time taken to reach offset (CORE-27952) OpFileLength remaining = request.start - (loading.start + length); if (remaining > MEDIA_SOURCE_MAX_WAIT) return TRUE; } return FALSE; } OP_STATUS MediaSourceImpl::Read(void* buffer, OpFileLength offset, OpFileLength size) { OP_NEW_DBG("Read", "MediaSource"); OP_DBG(("offset=%ld; size=%ld", offset, size)); m_read_offset = offset; if (!m_url_dd) { OP_ASSERT(m_message_handler.get()); m_url_dd = m_use_url->GetDescriptor(m_message_handler, URL::KNoRedirect, TRUE); if (!m_url_dd) return OpStatus::ERR; } // Check if the requested data is already loaded. BOOL available = FALSE; OpFileLength available_size = 0; GetPartialCoverage(offset, available, available_size); if (!available || available_size < size) { if (available) OP_DBG(("only %ld bytes available", available_size)); else OP_DBG(("not available (%ld bytes to next)", available_size)); return OpStatus::ERR_OUT_OF_RANGE; } OP_ASSERT(available_size > 0); m_url_dd->SetPosition(offset); OP_ASSERT(m_url_dd->GetPosition() == offset); OpFileLength total_read = 0; BOOL more = TRUE; while (total_read < size && more) { unsigned long bytes_read = m_url_dd->RetrieveData(more); if (bytes_read == 0) break; OP_ASSERT(bytes_read == m_url_dd->GetBufSize()); UINT8* dd_buffer = (UINT8*)m_url_dd->GetBuffer(); OP_ASSERT(dd_buffer); // Copy to buffer. unsigned long remaining = (unsigned long)(size - total_read); if (bytes_read > remaining) bytes_read = remaining; op_memcpy(&((UINT8*)buffer)[total_read], dd_buffer, bytes_read); // Consume data and move along. m_url_dd->ConsumeData(bytes_read); total_read += bytes_read; // FIXME: workaround for CORE-27705 if (more && total_read >= available_size) break; } if (total_read < size) return OpStatus::ERR_OUT_OF_RANGE; if (m_state == PAUSED) { BOOL available; OpFileLength remaining; GetStreamingCoverage(available, remaining); if (available && remaining > STREAMING_CACHE_RESUME_LIMIT) ResumeBuffering(); } OP_DBG(("read %ld bytes", total_read)); return OpStatus::OK; } void MediaSourceImpl::LoadFailed() { StopBuffering(); m_state = FAILED; for (OpListenersIterator iter(m_listeners); m_listeners.HasNext(iter);) m_listeners.GetNext(iter)->OnError(this); } BOOL MediaSourceImpl::VerifyContentType() { if (m_verified_content_type) return TRUE; OP_ASSERT(m_use_url->GetAttribute(URL::KMultimedia) != FALSE); ContentDetector content_detector(m_use_url->GetRep(), TRUE, TRUE); OP_STATUS status = content_detector.DetectContentType(); if (OpStatus::IsSuccess(status) && (content_detector.WasTheCheckDeterministic() || IsLoadedURL(m_use_url))) { const char* sniffed_type = GetContentType(); BOOL3 can_play = NO; status = g_media_module.CanPlayType(&can_play, sniffed_type); if (OpStatus::IsSuccess(status)) { if (can_play == NO) status = OpStatus::ERR_NOT_SUPPORTED; else m_verified_content_type = TRUE; } } if (OpStatus::IsError(status)) { RAISE_IF_MEMORY_ERROR(status); LoadFailed(); } return m_verified_content_type; } /* virtual */ void MediaSourceImpl::HandleCallback(OpMessage msg, MH_PARAM_1 par1, MH_PARAM_2 par2) { if (msg == MSG_MEDIA_SOURCE_ENSURE_BUFFERING) { OP_ASSERT(m_pending_ensure); EnsureBuffering(); m_pending_ensure = FALSE; return; } else if (msg == MSG_MEDIA_SOURCE_NOTIFY_LISTENER) { // The listener may have been removed while the message was // pending, so find it in the listeners list before notifying. MediaProgressListener* listener = reinterpret_cast<MediaProgressListener*>(par2); for (OpListenersIterator iter(m_listeners); m_listeners.HasNext(iter);) { if (m_listeners.GetNext(iter) == listener) { if (m_state == FAILED) listener->OnError(this); else if (m_state == IDLE) listener->OnIdle(this); // else: The state has already changed and the // listener was notified just like the others. break; } } return; } // URL_DataDescriptor::RetrieveData posts MSG_URL_DATA_LOADED when // reading, which we are not interested in when idle or paused. // URL messages after an error are irrelevant to us. if (m_state == IDLE || m_state == PAUSED || m_state == FAILED) return; // URL messages in the message queue when calling StopLoading // will arrive after starting a new request, at which point they // must be ignored. Wait for headers/failure/redirect. if (m_state == STARTED && msg == MSG_URL_DATA_LOADED) return; OP_ASSERT(m_state == STARTED || m_state == HEADERS || m_state == LOADING); switch(msg) { case MSG_HEADER_LOADED: OP_ASSERT(m_state == STARTED); m_state = HEADERS; // If we are streaming, tell all listeners except the first to // restart loading, at which point they'll get a new source. if (IsStreaming()) { OpListenersIterator iter(m_listeners); m_listeners.GetNext(iter); while (m_listeners.HasNext(iter)) m_listeners.GetNext(iter)->OnClientCollision(this); } break; case MSG_URL_DATA_LOADED: if (m_state == HEADERS) m_state = LOADING; OP_ASSERT(m_state == LOADING); if (IsSuccessURL(m_use_url)) { // This point will be reached very often while the // transfer is progressing normally, so it is important // that the following steps are not needlessly wasteful. if (!VerifyContentType()) return; // EnsureBuffering does a non-trivial amount of work, so // only call it if (a) the request has finished or (b) the // current request is "too big" and needs clamping. if (m_clamp_request || IsLoadedURL(m_use_url)) { EnsureBuffering(); if (m_state != LOADING) break; } // The listeners are responsible for throttling the // side-effects buffering progress. for (OpListenersIterator iter(m_listeners); m_listeners.HasNext(iter);) m_listeners.GetNext(iter)->OnProgress(this); if (IsStreaming()) { BOOL available; OpFileLength remaining; GetStreamingCoverage(available, remaining); if (available && remaining < STREAMING_CACHE_PAUSE_LIMIT) PauseBuffering(); } } else { LoadFailed(); } break; case MSG_URL_LOADING_FAILED: // Try to recover from a network errors that happen while // loading, but not those that happen before (or after) that. if (m_state == LOADING && IsResumableURL(m_use_url)) { StopBuffering(); m_state = IDLE; EnsureBuffering(); } else { LoadFailed(); } break; case MSG_URL_MOVED: { URL moved_to = m_use_url->GetAttribute(URL::KMovedToURL, URL::KFollowRedirect); if (!moved_to.IsEmpty()) { OP_ASSERT(m_use_url->Id(URL::KFollowRedirect) == (URL_ID)par2 && moved_to.Id(URL::KNoRedirect) == (URL_ID)par2); m_use_url.SetURL(moved_to); OP_DELETE(m_url_dd); m_url_dd = NULL; m_message_handler->UnsetCallBacks(this); RAISE_AND_RETURN_VOID_IF_ERROR(SetCallBacks()); } } break; default: OP_ASSERT(FALSE); } // Ensure that we are notified of further buffering progress. if (m_url_dd) m_url_dd->ClearPostedMessage(); } OP_STATUS MediaSourceImpl::AddProgressListener(MediaProgressListener* listener) { RETURN_IF_ERROR(m_listeners.Add(listener)); if (m_state == IDLE || m_state == FAILED) { // Notify the new listener of the state asynchronously. m_message_handler->PostMessage(MSG_MEDIA_SOURCE_NOTIFY_LISTENER, reinterpret_cast<MH_PARAM_1>(this), reinterpret_cast<MH_PARAM_2>(listener)); } return OpStatus::OK; } OP_STATUS MediaSourceImpl::RemoveProgressListener(MediaProgressListener* listener) { return m_listeners.Remove(listener); } void MediaSourceImpl::GetStreamingCoverage(BOOL &available, OpFileLength &remaining) { OpFileLength length; GetPartialCoverage(m_read_offset, available, length); if (available) { OP_ASSERT(length > 0); OpFileLength cache_size; m_use_url->GetAttribute(URL::KMultimediaCacheSize, &cache_size); OP_ASSERT(length <= cache_size); remaining = cache_size - length; OP_NEW_DBG("GetStreamingCoverage", "MediaSource"); OP_DBG((("cached: %d; remaining: %d"), (int)length, (int)remaining)); } } #endif // MEDIA_PLAYER_SUPPORT
#ifndef SOPNET_GROUND_TRUTH_SEGMENT_EXTRACTOR_H__ #define SOPNET_GROUND_TRUTH_SEGMENT_EXTRACTOR_H__ #include <pipeline/all.h> #include <sopnet/features/SetDifference.h> #include <sopnet/slices/Slices.h> #include <sopnet/segments/Segments.h> class GroundTruthSegmentExtractor : public pipeline::SimpleProcessNode<> { public: GroundTruthSegmentExtractor(); private: void updateOutputs(); /** * Checks, whether the given segment is consistent with the currently found * ones and adds it to the output, if this is the case. */ void probeContinuation(boost::shared_ptr<ContinuationSegment> continuation); /** * Checks, whether the given segment is consistent with the currently found * ones and adds it to the output, if this is the case. */ void probeBranch(boost::shared_ptr<BranchSegment> branch); /** * Get the distance between two slices. */ double distance(const Slice& slice1, const Slice& slice2); // slices of the previous section pipeline::Input<Slices> _prevSlices; // slices of the next section pipeline::Input<Slices> _nextSlices; // extracted segments pipeline::Output<Segments> _segments; // mapping from intensity values to the slices having it std::map<float, std::vector<boost::shared_ptr<Slice> > > _prevSliceValues; // mapping from intensity values to the slices having it std::map<float, std::vector<boost::shared_ptr<Slice> > > _nextSliceValues; // all values in the ground truth images std::set<float> _values; // set of slices that have not been explained so far std::set<boost::shared_ptr<Slice> > _remainingPrevSlices; // set of slices that have not been explained so far std::set<boost::shared_ptr<Slice> > _remainingNextSlices; // the maximally allowed distance between slices in a segment double _maxSegmentDistance; // functor to compute the set difference between slices SetDifference _setDifference; }; #endif // SOPNET_GROUND_TRUTH_SEGMENT_EXTRACTOR_H__
#include <thread> #include <mutex> #include <algorithm> #include "udp_manager.h" #include "main_thread.h" #include "protocol.h" #include "interface.h" #include "path.h" bool on_checkip(const char* remote_ip, const int &remote_port) { file_server_thread::get_instance()->add_log(LOG_TYPE_INFO, "on_checkip---->>>>"); return true; } bool on_recv(const char* data, const int &size, const int &linker_handle, const char* remote_ip, const int &remote_port, const int &consume_timer) { header *header_ptr = (header *)(data); if (nullptr == header_ptr) { file_server_thread::get_instance()->add_log(LOG_TYPE_ERROR, "rudp_on_recv Failed linker_handle=%d size=%d", linker_handle, size); return false; } file_server_thread::get_instance()->add_queue(*header_ptr, (char*)data, size, linker_handle, remote_ip, remote_port); return true; } void on_disconnect(const int &linker_handle, const char* remote_ip, const int &remote_port) { file_server_thread::get_instance()->add_log(LOG_TYPE_INFO, "on_disconnect---->>>> %d", linker_handle); header header_ptr; memset(&header_ptr, 0, sizeof(header_ptr)); header_ptr.protocol_id_ = HARQ_DISCONNECT; file_server_thread::get_instance()->add_queue(header_ptr, nullptr, 0, linker_handle, remote_ip, remote_port); } void on_error(const int &error, const int &linker_handle, const char* remote_ip, const int &remote_port) { file_server_thread::get_instance()->add_log(LOG_TYPE_INFO, "on_error---->>>> %d", error); header header_ptr; memset(&header_ptr, 0, sizeof(header_ptr)); header_ptr.protocol_id_ = HARQ_DISCONNECT; file_server_thread::get_instance()->add_queue(header_ptr, nullptr, 0, linker_handle, remote_ip, remote_port); } void on_rto(const char* remote_ip, const int &remote_port, const int &local_rto, const int &remote_rto) { } void on_rate(const char* remote_ip, const int &remote_port, const unsigned int &send_rate, const unsigned int &recv_rate) { } udp_manager::udp_manager(void *parent) { parent_ = parent; load_so(); } udp_manager::~udp_manager(void) { } void udp_manager::set_option(const std::string &attribute, const std::string &value) { std::string tmp_attribute = attribute; transform(tmp_attribute.begin(), tmp_attribute.end(), tmp_attribute.begin(), ::tolower); if("bind_ip" == tmp_attribute) { bind_ip_ = value; } else if("log" == tmp_attribute) { log_ = value; } else if("harq_so_path" == tmp_attribute) { harq_so_path_ = value; } } void udp_manager::set_option(const std::string &attribute, const int &value) { std::string tmp_attribute = attribute; transform(tmp_attribute.begin(), tmp_attribute.end(), tmp_attribute.begin(), ::tolower); if("listen_port" == tmp_attribute) { listen_port_ = value; } else if("delay_interval" == tmp_attribute) { delay_interval_ = value; } } void udp_manager::set_option(const std::string &attribute, const bool &value) { std::string tmp_attribute = attribute; transform(tmp_attribute.begin(), tmp_attribute.end(), tmp_attribute.begin(), ::tolower); if("delay" == tmp_attribute) { delay_ = value; } } bool udp_manager::load_so() { if(!ustd::path::is_file_exist(((file_server_thread*)parent_)->libso_path_)) { ((file_server_thread*)parent_)->add_log(LOG_TYPE_ERROR, "Load so Falied Not Found libso_path=%s error=%s", ((file_server_thread*)parent_)->libso_path_.c_str(), lib_error()); return false; } lib_handle_ = lib_load(((file_server_thread*)parent_)->libso_path_.c_str()); if(nullptr == lib_handle_) { ((file_server_thread*)parent_)->add_log(LOG_TYPE_ERROR, "Load so Falied libso_path=%s error=%s", ((file_server_thread*)parent_)->libso_path_.c_str(), lib_error()); return false; } //加载so透出的函数; harq_start_server_ptr_ = (HARQ_START_SERVER)lib_function(lib_handle_, "harq_start_server"); harq_send_buffer_handle_ptr_ = (HARQ_SEND_BUFFER_HANDLE)lib_function(lib_handle_, "harq_send_buffer_handle"); harq_close_handle_ptr_ = (HARQ_CLOSE_HANDLE)lib_function(lib_handle_, "harq_close_handle"); harq_version_ptr_ = (HARQ_VERSION)lib_function(lib_handle_, "harq_version"); harq_end_server_ptr_ = (HARQ_END_SERVER)lib_function(lib_handle_, "harq_end_server"); if(nullptr == harq_start_server_ptr_) { ((file_server_thread*)parent_)->add_log(LOG_TYPE_ERROR, "dlsym harq_start_server_ptr_ error\n"); lib_close(lib_handle_); return false; } if(nullptr == harq_send_buffer_handle_ptr_) { ((file_server_thread*)parent_)->add_log(LOG_TYPE_ERROR, "dlsym harq_send_buffer_handle error\n"); lib_close(lib_handle_); return false; } if(nullptr == harq_close_handle_ptr_) { ((file_server_thread*)parent_)->add_log(LOG_TYPE_ERROR, "dlsym harq_close_handle_ptr_ error\n"); lib_close(lib_handle_); return false; } if(nullptr == harq_version_ptr_) { ((file_server_thread*)parent_)->add_log(LOG_TYPE_ERROR, "dlsym harq_version_ptr_ error\n"); lib_close(lib_handle_); return false; } if(nullptr == harq_end_server_ptr_) { ((file_server_thread*)parent_)->add_log(LOG_TYPE_ERROR, "dlsym harq_end_server_ptr_ error\n"); lib_close(lib_handle_); return false; } return true; } bool udp_manager::start_server() { if(harq_start_server_ptr_ != nullptr) { express_handle_ = harq_start_server_ptr_((char*)log_.c_str(), (char*)bind_ip_.c_str(), listen_port_, delay_, delay_interval_, 512 * KB, 10 * MB, &on_checkip, &on_recv, &on_disconnect, &on_error, &on_rto, &on_rate); if (express_handle_ > 0) return true; else return false; } return false; } bool udp_manager::init() { bool ret = start_server(); return ret; } int udp_manager::send_buffer(char* data, int size, int linker_handle) { if(-1 == linker_handle) { return -1; } return harq_send_buffer_handle_ptr_(express_handle_, data, size, linker_handle); } int udp_manager::send_login_response(const int &linker_handle) { if (-1 == linker_handle) return -1; reponse_login login; login.header_.protocol_id_ = EXPRESS_RESPONSE_ONLINE; login.result_ = 0; return harq_send_buffer_handle_ptr_(express_handle_, (char*)&login, sizeof(login), linker_handle); }
#ifndef CNFDIALOG_H #define CNFDIALOG_H #include <QDialog> namespace Ui { class cnfDialog; } class cnfDialog : public QDialog { Q_OBJECT public: explicit cnfDialog(QWidget *parent = 0); ~cnfDialog(); /* private slots: void on_buttonBox_accepted(); */ private: Ui::cnfDialog *ui; }; #endif // CNFDIALOG_H
#include "TrianglesCommand.h" #include <iberbar/RHI/Texture.h> iberbar::Renderer::CTrianglesCommand::CTrianglesCommand() : CRenderCommand( URenderCommandType::Triangles ) , m_pShaderState( nullptr ) , m_pShaderVariableTables( nullptr ) , m_Triangles() { }
const int maxn = 1010; const int maxm = 1010; struct Matrix { int n, m; int a[maxn][maxm]; void clear() { n = m = 0; memset(a, 0, sizeof(a)); } Matrix operator +(const Matrix &b) const { Matrix tmp; tmp.n = n; tmp.m = m; for(int i = 0;i < n;i++) for(int j = 0;j < m;j++) tmp.a[i][j] = a[i][j] + b.a[i][j]; return tmp; } Matrix operator *(const Matrix &b) const { Matrix tmp; tmp.clear(); tmp.n = n; tmp.m = b.m; for(int i = 0;i < n;i++) { for(int j = 0;j < b.m;j++) { for(int k = 0;k < m;k++) { tmp.a[i][j] += a[i][k]*b.a[k][j]; } } } return tmp; } };
/** * Copyright 2008 Matthew Graham * 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 "stdopt/configuration.h" #include <testpp/test.h> #include <sstream> using namespace stdopt; /// Tests for the config_option_c class first /** * Test that preconditions are set properly * in the config_option class. */ TESTPP( test_config_option_initialization ) { config_option_c< std::string > opt( "dog", "description of a dog" ); // assert preconditions assertpp( opt.option_name() ) == "dog"; assertpp( opt.set() ).f(); assertpp( opt.error() ).f(); } /** * Test that preconditions are set properly * in the config_option constructor with a * default value. */ TESTPP( test_config_option_default_init ) { config_option_c< int > opt( 58, "dog", "description of a dog" ); // assert preconditions assertpp( opt.option_name() ) == "dog"; assertpp( opt.value() ) == 58; assertpp( opt.set() ).f(); assertpp( opt.error() ).f(); } /** * Test that the config option class works for the * string type. */ TESTPP( test_string_config_option ) { config_option_c< std::string > opt( "dog", "description" ); opt.parse_value( "cat" ); // assert postconditions assertpp( opt.value() ) == "cat"; assertpp( opt.set() ).t(); assertpp( opt.error() ).f(); } /** * Test that the config_option class works for integers. */ TESTPP( test_int_config_option ) { config_option_c< int > opt( "dog", "description" ); opt.parse_value( "89" ); // assert postconditions assertpp( opt.value() ) == 89; assertpp( opt.set() ).t(); assertpp( opt.error() ).f(); } /** * Test that the config_option class works for booleans. */ TESTPP( test_bool_config_option ) { config_option_c< bool > opt( "dog", "desc" ); opt.parse_value( "1" ); // assert postconditions assertpp( opt.value() ).t(); assertpp( opt.set() ).t(); assertpp( opt.error() ).f(); } /** * Test that parsing an invalid string for integers fails properly. */ TESTPP( test_invalid_int_option ) { config_option_c< int > opt( "dog", "description" ); opt.parse_value( "cat" ); // assert postconditions assertpp( opt.error() ).t(); assertpp( opt.set() ).f(); assertpp( opt.value() ) == 0; } /// Tests for the config_option_list_c class /** * Test that the config_option_c class accepts multiple items. */ TESTPP( test_option_parse_multi_values ) { config_option_c< int > ports( "port", "description" ); ports.parse_value( "5" ); ports.parse_value( "6" ); ports.parse_value( "7" ); ports.parse_value( "8" ); // verify the array access assertpp( ports.size() ) == 4; assertpp( ports.value( 0 ) ) == 5; assertpp( ports.value( 1 ) ) == 6; assertpp( ports.value( 2 ) ) == 7; assertpp( ports.value( 3 ) ) == 8; // verify the iterator access config_option_c< int >::iterator it( ports.begin() ); assertpp( *(it++) ) == 5; assertpp( *(it++) ) == 6; assertpp( *(it++) ) == 7; assertpp( *(it++) ) == 8; } /// Tests for the configuration_c class /** * Test the most basic functionality, 2 string options */ TESTPP( test_basic_string_options ) { config_option_c< std::string > option1( "option1", "desc1" ); config_option_c< std::string > option2( "option2", "desc2" ); config_option_c< std::string > option3( "option3", "desc3" ); configuration_c config; config.add( option1 ); config.add( option2 ); std::istringstream input( "option1=dog\noption2=cat" ); config.parse( input ); assertpp( option1.set() ).t(); assertpp( option2.set() ).t(); assertpp( option3.set() ).f(); assertpp( option1.value() ) == "dog"; assertpp( option2.value() ) == "cat"; } /** * Test the integer and boolean options */ TESTPP( test_int_options ) { config_option_c< int > port( "port", "pdesc" ); config_option_c< int > timeout( "timeout", "todesc" ); config_option_c< bool > debug( "debug", "debug desc" ); std::istringstream input( "port=4000\ntimeout=20\ndebug=1" ); configuration_c config; config.add( port ); config.add( timeout ); config.add( debug ); config.parse( input ); assertpp( port.set() ).t(); assertpp( timeout.set() ).t(); assertpp( debug.set() ).t(); assertpp( port.value() ) == 4000; assertpp( timeout.value() ) == 20; assertpp( debug.value() ).t(); } /** * Test that option_lists are parsed properly */ TESTPP( test_parse_config_list ) { config_option_c< int > ports( "port", "desc" ); std::istringstream input( "port=4000\nport=2000\nport=4001" ); configuration_c config; config.add( ports ); config.parse( input ); assertpp( ports.set() ).t(); assertpp( ports.error() ).f(); assertpp( ports.size() ) == 3; assertpp( ports.value() ) == 4000; assertpp( ports.value( 0 ) ) == 4000; assertpp( ports.value( 1 ) ) == 2000; assertpp( ports.value( 2 ) ) == 4001; assertpp( ports.last_value() ) == 4001; } /** * Test that it still works with windows line endings. */ TESTPP( test_crlf ) { config_option_c< int > timeout( "session-timeout", "desc" ); config_option_c< std::string > split( "split", "desc" ); const char str_input[] = "session-timeout=30\r\n" "split=dog"; std::stringstream input( str_input ); configuration_c config; config.add( split ); config.add( timeout ); config.parse( input ); assertpp( timeout.set() ).t(); assertpp( split.set() ).t(); assertpp( timeout.value() ) == 30; assertpp( split.value() ) == "dog"; } /** * Test that whitespace doesn't mess up the parsing of a config file. */ TESTPP( test_whitespace ) { config_option_c< int > timeouts( "session-timeout", "desc1" ); config_option_c< int > ports( "port", "desc2" ); const char str_input[] = "\nsession-timeout = 20 \n" \ "\n session-timeout = 23 \n "\ "\n port = 9000\n" \ "\n port = 9001 \n"; std::stringstream input( str_input ); configuration_c config; config.add( timeouts ); config.add( ports ); config.parse( input ); assertpp( timeouts.size() ) == 2; assertpp( ports.size() ) == 2; assertpp( timeouts.value( 0 ) ) == 20; assertpp( timeouts.value( 1 ) ) == 23; assertpp( ports.value( 0 ) ) == 9000; assertpp( ports.value( 1 ) ) == 9001; } /** * Test that a non integer value doesn't freak out when an integer * is requested. */ TESTPP( test_non_integer ) { config_option_c< int > timeout( "session-timeout", "desc" ); const char str_input[] = "session-timeout=hh340\n"; std::stringstream input( str_input ); configuration_c config; config.add( timeout ); config.parse( input ); assertpp( timeout.error() ).t(); assertpp( config.error() ).t(); }
../1087/A.cpp
#pragma once #include "random.h" namespace qwaker { template<typename T = int> class treap_array { public: typedef T value_type; treap_array(size_t n = 0) : root(NULL) { root = __init_node(n); } treap_array(treap_array& a, treap_array& b) { __merge(a.root, b.root, root); } ~treap_array() { if (root) { delete root; } } void clear() { if (root) { delete root; root = NULL; } } size_t size() { return __size(root); } value_type& operator[](size_t n) { assert(n < __size(root)); return __find_by_index(n); } const value_type& operator[](size_t n) const { assert(n < __size(root)); return __find_by_index(n); } treap_array& split(size_t pivot, treap_array& partB) { assert(this != &partB); __split(root, pivot, root, partB.root); return *this; } treap_array& split(size_t pivot, treap_array& partA, treap_array& partB) { assert(&partA != &partB); if (this != &partA) partA.clear(); if (this != &partB) partB.clear(); __split(root, pivot, partA.root, partB.root); if (this != &partA && this != &partB) root = NULL; return *this; } treap_array& merge(treap_array& partB) { assert(this != &partB); __merge(root, partB.root, root); partB.root = NULL; return *this; } treap_array& merge(treap_array& partA, treap_array& partB) { assert(&partA != &partB); if (this != &partA && this != &partB) clear(); __merge(partA.root, partB.root, root); if (this != &partA) partA.root = NULL; if (this != &partB) partB.root = NULL; return *this; } void insert(const value_type& x) { Node* newnode = new Node(x); __merge(root, newnode, root); } void insert(const value_type& x, size_t n) { assert(n <= __size(root)); Node *p1, *p2, *newnode = new Node(x); __split(root, n, p1, p2); __merge(p1, newnode, p1); __merge(p1, p2, root); } void erase(size_t n) { assert(n < __size(root)); Node *p1, *p2, *newnode; __split(root, n, p1, p2); __split(p2, 1, newnode, p2); __merge(p1, p2, root); } void cut(size_t l, size_t r, treap_array& seg) { if (&seg != this) seg.clear(); assert(l <= r); assert(r <= __size(root)); Node *p1, *p2; __split(root, l, p1, p2); __split(p2, r - l, seg.root, p2); if (&seg != this) __merge(p1, p2, root); } protected: struct Node { value_type x; size_t size; Node *left, *right; Node(const value_type& x = value_type()) : x(x), size(1), left(NULL), right(NULL) { }; ~Node() { if (left) delete left; if (right) delete right; } }; Node* root; explicit treap_array(Node* root) : root(root) { } treap_array(const treap_array& x) { } inline size_t __size(Node* root) { return root ? root->size : 0; } Node* __init_node(size_t n) { if (!n) return NULL; Node* root = new Node(); root->left = __init_node(n >> 1); root->right = __init_node(n - (n >> 1) - 1); root->size = n; return root; } value_type& __find_by_index(size_t n) { Node* current = root; while (current) { size_t leftsize = __size(current->left); if (n < leftsize) { current = current->left; continue; } if (n == leftsize) { return current->x; } current = current->right; n -= leftsize + 1; } throw "Bad implementation"; } void __split(Node* root, size_t pivot, Node*& left, Node*& right) { if (!root) return void(left = right = NULL); size_t leftsize = __size(root->left); if (pivot <= leftsize) { __split(root->left, pivot, left, root->left); right = root; } else { __split(root->right, pivot - leftsize - 1, root->right, right); left = root; } root->size = __size(root->left) + __size(root->right) + 1; } void __merge(Node* left, Node* right, Node*& root) { if (!left) return void(root = right); if (!right) return void(root = left); if (flip_coin(left->size, right->size)) { __merge(left->right, right, left->right); root = left; } else { __merge(left, right->left, right->left); root = right; } root->size = __size(root->left) + __size(root->right) + 1; } }; }
/* In Linear Search the list is searched sequentially and the position is returned if the key element to be searched is available in the list, otherwise -1 is returned. The search in Linear Search starts at the beginning of an array and move to the end, testing for a match at each item All the elements preceding the search element are traversed before the search element is traversed. If the element to be searched is in position 10, all elements form 1 - 9 are checked before 10. */ #pragma once #ifndef alpha_LinearSearch_h #define alpha_LinearSearch_h #include <iostream> using namespace std; int linearSearch(int a[], int search, int size) { for (int i = 0; i < size; ++i) { if (search == a[i]) return i; } return -1; } #endif
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 1995-2001 Opera Software AS. All rights reserved. * * This file is part of the Opera web browser. It may not be distributed * under any circumstances. */ /** @file fontcache.h * * FontCache class prototype. * * @author Markus Johansson * */ #ifndef _FONTCACHE_H_ #define _FONTCACHE_H_ # include "modules/util/simset.h" #include "modules/pi/OpFont.h" #include "modules/display/FontAtt.h" class FramesDocument; class Window; /** * FontCacheElement's are stored in the font cache. * Every element has a reference counter and a timestamp for the last use. */ class FontCacheElement : public Link { public: FontCacheElement(OpFont* font, const FontAtt &fontatt, UINT32 time, UINT32 scale, Window* window, FramesDocument* doc) : font(font), last_use(time), ref_count(1), packed_init(0), doc(doc) #ifdef FONTCACHE_PER_WINDOW ,window(window) #endif // FONTCACHE_PER_WINDOW { this->fontatt = fontatt; packed.scale = scale; } #ifdef SVG_SUPPORT ~FontCacheElement(); #else ~FontCacheElement() { OP_DELETE(font); } #endif // SVG_SUPPORT OpFont* font; FontAtt fontatt; UINT32 last_use; UINT32 ref_count; union { struct { unsigned int scale:31; unsigned int is_marked_for_purge:1; } packed; unsigned int packed_init; }; FramesDocument* doc; #ifdef FONTCACHE_PER_WINDOW Window* window; #endif // FONTCACHE_PER_WINDOW }; /** * FontCache. This is a cache of created OpFont-objects. * The size of the cache is tweakable, and it can also be tweaked so there is one cache per window, * instead of one global cache. */ class FontCache { public: /** * Constructs a new font cache. * The size will be set to FONTCACHESIZE. */ FontCache() : time(0), num_cached_fonts(0) {} /** * Destroys the font cache. */ ~FontCache(); /** * Clears out all unused fonts from the cache. */ void Clear(); /** * Clears out all unused svgfonts from the cache. */ void ClearSVGFonts(); /** * Gets a font from the font cache. * If the font is not in the cache it will be * created. When creating a font and there is * no space left in the cache, the font which was used * least recently will be thrown out. * When you are done using the font returned from * this function, invoke ReleaseFont(). * @param fontatt Attributes for requested font. * @param scale Scale used to create this font. * @param doc The current FramesDocument (only used for creating SVGFonts). * @return An OpFont object. */ OpFont* GetFont(FontAtt &fontatt, UINT32 scale, FramesDocument* doc = NULL); /** increases the ref count of font (assumed to be in cache) by one. this function serves as an alternative to GetFont, taking an already fetched OpFont instead of a FontAtt, and is needed by the printing code since it's passed an OpFont that might be accessed later. releasing the font is done by invoking ReleaseFont. @param font the font for which to increase the reference count - should be in cache */ void ReferenceFont(OpFont* font); /** * Releases a font. * Call this method when you are not going to use * the font anymore. * @param font Font to release. */ void ReleaseFont(OpFont* font, BOOL force_total_removal = FALSE); /** * Query the cache for any existing font instances with the specified fontnumber * * @param font_num Font number to query * @return TRUE if instance with said fontnumber exists, otherwise FALSE */ BOOL HasCachedInstance(UINT32 font_num); /** * Purge the instance(s) of a webfont with the specified fontnumber * * @param font_num Font number to query * @ return TRUE if all matching entries were removed, FALSE otherwise */ BOOL PurgeWebFont(UINT32 font_num); #ifdef FONTCACHE_PER_WINDOW /** * Clears out all unreferenced fonts associated with a given window. * @param window The Window for which fonts are to be cleared. */ void ClearForWindow(Window *window); #endif // FONTCACHE_PER_WINDOW private: UINT32 time; Head cached_fonts; unsigned int num_cached_fonts; void DeleteFontCacheElement(FontCacheElement* font_elm); }; #endif // _FONTCACHE_H_
#include "cell.h" #include "widget.h" #include <QDebug> extern Widget* widget; Cell::Cell(int s) : QGraphicsItem(), editable(true), red(false), size(s), value(0) {} QRectF Cell::boundingRect() const { return QRect(0, 0, size, size); } void Cell::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) { painter->setPen(QPen(Qt::black, 1)); if(red) painter->setBrush(QBrush(Qt::darkRed)); painter->drawRect(boundingRect()); if (value != 0) { if(editable) painter->setPen(QPen(Qt::darkRed, 1)); painter->setFont(QFont("Times", static_cast<int>(size/2.5), QFont::Normal)); painter->drawText(boundingRect(), Qt::AlignCenter, QString::number(value)); } Q_UNUSED(option); Q_UNUSED(widget); } void Cell::mousePressEvent(QGraphicsSceneMouseEvent *event) { if(!widget->variantsAreShown() && editable) { if(value == 0) widget->showVariants(scenePos()); else setValue(0); } else if(widget->variantsAreShown()) widget->moveBack(); Q_UNUSED(event); } void Cell::setValue(int n) { value = n; update(boundingRect()); } int Cell::getValue() { return value; } void Cell::setEditable(bool condition) { editable = condition; } bool Cell::isEditable() { return editable; } int Cell::getSize() { return size; } void Cell::setRed() { if(red == true) red = false; else red = true; update(); }
#include "stdafx.h" #include "../Monster.h" #include "Uma.h" #include "../../GameData.h" Uma::Uma() { m_anim[Monster::en_idle].Load(L"Assets/modelData/uma/anim_uma_idle.tka"); m_anim[Monster::en_idle].SetLoopFlag(true); m_anim[Monster::en_walk].Load(L"Assets/modelData/uma/anim_uma_walk.tka"); m_anim[Monster::en_walk].SetLoopFlag(true); m_anim[Monster::en_atack].Load(L"Assets/modelData/uma/anim_uma_atack.tka"); m_anim[Monster::en_atack].SetLoopFlag(false); SkinModelRender* sr = NewGO<SkinModelRender>(0, "smr"); sr->Init(L"Assets/modelData/uma.cmo",m_anim,3); //sr->SetScale({ 1.8f,1.8f,1.8f }); //sr->Init(L"Assets/modelData/uma.bone.cmo"); sr->SetPosition(CVector3::Zero()); MonsterInitParam prm; prm.HP = 100; prm.MP = 80; prm.DefencePow = 7; prm.ExDefensePow = 1.7; prm.AttackPow = 13; prm.ExAttackPow = 1; prm.Speed = 10; prm.Radius = 50; prm.Height = 250; prm.ModelRender = sr; prm.NumAnimation = 3; init(prm); m_ID = enUmataur; int cnt = 0; ActionID* ua = GameData::GetMonsterActions(m_ID, cnt); SetUseAction(ua, cnt); }
#pragma once class AbortException : public std::runtime_error { public: explicit AbortException(const char *msg) : std::runtime_error(msg) {} };
#include <stdio.h> #include <sstream> #include <string> #include <iostream> #include "heapfileLib.h" void initializeHeapfile(std::string filename, Heapfile *heapfile, int pageSize) { FILE *colstore = fopen(filename.c_str(), "r+"); if (colstore == NULL) { printf("No colstore found for %s \n", filename.c_str()); throw; } heapfile->file_ptr = colstore; heapfile->page_size = pageSize; } int main(int argc, char *argv[]) { if (argc < 7) { printf("Usage: select3 <colstore_name> <attribute_id> <return_attribute_id> <start> <end> <page_size>\n"); return 0; } std::string dirname (argv[1]); std::string searchAttr (argv[2]); std::string returnAttr (argv[3]); char *start = argv[4]; char *end = argv[5]; int pageSize = atoi(argv[6]); // Initalize relevant column heapfiles std::string searchAttrFile = dirname + "/" + searchAttr; Heapfile *searchHeap = (Heapfile *) malloc(sizeof(Heapfile)); initializeHeapfile(searchAttrFile, searchHeap, pageSize); std::string returnAttrFile = dirname + "/" + returnAttr; Heapfile *returnHeap = (Heapfile *) malloc(sizeof(Heapfile)); initializeHeapfile(returnAttrFile, returnHeap, pageSize); // Process all elements in heapfile and filter by attribute RecordIterator searchIt = RecordIterator(searchHeap); RecordIterator returnIt = RecordIterator(returnHeap); while(searchIt.hasNext()){ Record outer = searchIt.next(); if (strcmp(start, outer[1]) <= 0 && strcmp(end, outer[1]) >= 0) { // Found relevant attribute. Find matching return attribute while (returnIt.hasNext()) { Record inner = returnIt.next(); if (strcmp(inner[0], outer[0]) == 0) { printf("%s\n", inner[1]); free_record(&inner); break; } free_record(&inner); } if (returnIt.hasNext()) { returnIt.forceFree(); } returnIt = RecordIterator(returnHeap); } free_record(&outer); } returnIt.forceFree(); fclose(searchHeap->file_ptr); fclose(returnHeap->file_ptr); free(searchHeap); free(returnHeap); return 0; }
//使用するヘッダーファイル #include "GameL\DrawTexture.h" #include "GameL\SceneManager.h" #include "GameL\SceneObjManager.h" #include "GameL\HitBoxManager.h" #include "GameL\DrawFont.h" #include "GameL\Audio.h" #include "GameHead.h" #include "ObjChangeSwitch.h" //使用するネームスペース using namespace GameL; bool m_delete = true; bool m_change = true; bool m_start_boss = true; bool m_m_change = true; CObjChangeSwitch::CObjChangeSwitch(float x, float y) { m_px = x; //位置 m_py = y; } //イニシャライズ void CObjChangeSwitch::Init() { m_change = true; //画像切り替え m_time = 0; //当たり判定用のHitBoxを作成 Hits::SetHitBox(this, m_px, m_py, 32, 32, ELEMENT_FIELD, OBJ_CHANGESWITCH, 1); } //アクション void CObjChangeSwitch::Action() { //自身のHitBoxを持ってくる CHitBox* hit = Hits::GetHitBox(this); //描画カラー情報 float c[4] = { 1.0f,1.0f,1.0f,1.0f }; float a[4] = { 1.0f,1.0f,1.0f,0.5f }; //主人公と当たっているか確認 if (hit->CheckObjNameHit(COBJ_HERO) != nullptr) { //CObjChangeGate1* change = (CObjChangeGate1*)Objs::GetObj(OBJ_CHANGEGATE); //m_change = change->GetCHANGE(); m_change = false; m_delete = false; m_start_boss = false; m_m_change = false; //hit->SetInvincibility(true); //無敵オン //m_time = 100; } if (m_delete == false) { //自身を削除 this->SetStatus(false); Hits::DeleteHitBox(this); m_delete = true; } /*if (m_time > 0) { m_time--; if (m_time <= 0) { m_time = 0; this->SetStatus(false); Hits::DeleteHitBox(this); } }*/ //ブロック情報を持ってくる CObjBlock* block = (CObjBlock*)Objs::GetObj(OBJ_BLOCK); //HitBoxの位置の変更 hit->SetPos(m_px + block->GetScrollX(), m_py + block->GetScrollY()); } //ドロー void CObjChangeSwitch::Draw() { }
/* Texture functions for cs580 GzLib */ #include "stdafx.h" #include "stdio.h" #include "Gz.h" GzColor *image = NULL; int xs, ys; int reset = 1; #define ARRAY(x,y) (x + (y * xs)) /* Image texture function */ int tex_fun(float u, float v, GzColor color) { unsigned char pixel[3]; unsigned char dummy; char foo[8]; int i, j; FILE *fd; if (reset) { /* open and load texture file */ fd = fopen("texture", "rb"); if (fd == NULL) { fprintf(stderr, "texture file not found\n"); exit(-1); } fscanf(fd, "%s %d %d %c", foo, &xs, &ys, &dummy); image = (GzColor*)malloc(sizeof(GzColor)*(xs + 1)*(ys + 1)); if (image == NULL) { fprintf(stderr, "malloc for texture image failed\n"); exit(-1); } for (i = 0; i < xs*ys; i++) { /* create array of GzColor values */ fread(pixel, sizeof(pixel), 1, fd); image[i][RED] = (float)((int)pixel[RED]) * (1.0 / 255.0); image[i][GREEN] = (float)((int)pixel[GREEN]) * (1.0 / 255.0); image[i][BLUE] = (float)((int)pixel[BLUE]) * (1.0 / 255.0); } reset = 0; /* init is done */ fclose(fd); } /* bounds-test u,v to make sure nothing will overflow image array bounds */ /* determine texture cell corner values and perform bilinear interpolation */ /* set color to interpolated GzColor value and return */ // Clamp u and v between 0 and 1 if (u < 0) { u = 0; } if (u > 1) { u = 1; } if (v < 0) { v = 0; } if (v > 1) { v = 1; } u = u * (xs - 1); v = v * (ys - 1); // Perform bilinear interpolation int A, B, C, D; float s, t; A = floor(u); B = ceil(u); C = floor(v); D = ceil(v); s = u - A; t = v - C; color[RED] = ((s * t * image[ARRAY(B, D)][RED]) + ((1 - s) * (t)* image[ARRAY(A, D)][RED]) + ((s)* (1 - t) * image[ARRAY(B, C)][RED]) + ((1 - s) * (1 - t) * image[ARRAY(A, C)][RED])); color[GREEN] = ((s * t * image[ARRAY(B, D)][GREEN]) + ((1 - s) * (t)* image[ARRAY(A, D)][GREEN]) + ((s)* (1 - t) * image[ARRAY(B, C)][GREEN]) + ((1 - s) * (1 - t) * image[ARRAY(A, C)][GREEN])); color[BLUE] = ((s * t * image[ARRAY(B, D)][BLUE]) + ((1 - s) * (t)* image[ARRAY(A, D)][BLUE]) + ((s)* (1 - t) * image[ARRAY(B, C)][BLUE]) + ((1 - s) * (1 - t) * image[ARRAY(A, C)][BLUE])); return GZ_SUCCESS; } class ComplexNumber { public: float r; float i; ComplexNumber() {}; ~ComplexNumber() {}; }; int ptex_fun(float u, float v, GzColor color) { // Fractal texture: Julia Set int N = 150; ComplexNumber x; ComplexNumber c; // Setting c values c.r = -0.624; c.i = 0.435; // X = u + vi x.r = 2 * u - 0.7; x.i = v - 0.9; int i; float clr; for (i = 0; i < N; i++) { //X^2 + C //(XrYr - XiYi)r + Cr float xr = x.r * x.r - x.i * x.i + c.r; //(XrYi + XiYr)i + Ci float xi = x.r * x.i + x.i * x.r + c.i; if ((x.r * x.r + x.i * x.i) > 4.0) { break; } x.r = xr; x.i = xi; } float lengthX = sqrt(x.r * x.r + x.i * x.i); if (i == N) { color[0] = lengthX / 2; color[1] = lengthX / 2; color[2] = lengthX / 2; } else { clr = ((float) i) / N; color[0] = clr * 10; color[1] = clr * 8; color[2] = clr * 10; } return GZ_SUCCESS; } /* Free texture memory */ int GzFreeTexture() { if(image!=NULL) free(image); return GZ_SUCCESS; }
#include "light_source.hpp" #include "../include/color.hpp" #include "../include/point.hpp" #include <string> #include <ostream> light_source::light_source(): position_(),la_(),ld_(),name_() {} light_source::light_source(std::string const& name , math3d::point const& p, color const& la, color const& ld): position_(p), la_(la), ld_(ld), name_(name) {} light_source::light_source(const light_source& orig): position_(orig.position_), la_(orig.la_), ld_(orig.ld_), name_(orig.name_) {} light_source::~light_source() {} std::ostream& operator<<(std::ostream& str, light_source const& ls) { ls.print_on(str); return str; } void light_source::print_on(std::ostream& str) const { str<<name_<<": "<<position_<<" "<<la_<<" "<<ld_; } math3d::point light_source::get_pos() const { return position_; } color light_source::get_la() const { return la_; } color light_source::get_ld() const { return ld_; }
/* ************************************************************************ * Copyright (C) 2020-2023 Advanced Micro Devices, Inc. All rights reserved. * * 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 cop- * ies 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 IM- * PLIED, 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 CONNE- * CTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * * ************************************************************************ */ #pragma once #include "handle.hpp" #include "logging.hpp" #include "rocblas.h" #include "rocblas_gemm_ex.hpp" #include "utility.hpp" template <typename Ti, typename To, typename Tc> rocblas_status gemm_ext2_batched_template(rocblas_handle handle, rocblas_int m, rocblas_int n, rocblas_int k, const Tc* alpha, const Ti* a, rocblas_stride offset_a, rocblas_int row_stride_a, rocblas_int col_stride_a, rocblas_stride batch_stride_a, const Ti* b, rocblas_stride offset_b, rocblas_int row_stride_b, rocblas_int col_stride_b, rocblas_stride batch_stride_b, const Tc* beta, const To* c, rocblas_stride offset_c, rocblas_int row_stride_c, rocblas_int col_stride_c, rocblas_stride batch_stride_c, To* d, rocblas_stride offset_d, rocblas_int row_stride_d, rocblas_int col_stride_d, rocblas_stride batch_stride_d, rocblas_int batch_count = 1, bool strided_batch = true) { // pre apply offsets for non-batched and strided RocblasContractionProblem<Ti, To, Tc> problem{handle, m, n, k, alpha, a + offset_a, nullptr, row_stride_a, col_stride_a, batch_stride_a, 0 /* offset_a */, b + offset_b, nullptr, row_stride_b, col_stride_b, batch_stride_b, 0 /* offset_b */, beta, c + offset_c, nullptr, row_stride_c, col_stride_c, batch_stride_c, 0 /* offset_c */, d + offset_d, nullptr, row_stride_d, col_stride_d, batch_stride_d, 0 /* offset_d */, batch_count, strided_batch}; return runContractionProblem(problem); } template <typename Ti, typename To = Ti, typename Tc = To> rocblas_status rocblas_gemm_ext2_typecasting(rocblas_handle handle, rocblas_int m, rocblas_int n, rocblas_int k, const void* alpha, const void* a, rocblas_stride offsetAin, rocblas_int row_stride_a, rocblas_int col_stride_a, rocblas_stride batch_stride_a, const void* b, rocblas_stride offsetBin, rocblas_int row_stride_b, rocblas_int col_stride_b, rocblas_stride batch_stride_b, const void* beta, const void* c, rocblas_stride offsetCin, rocblas_int row_stride_c, rocblas_int col_stride_c, rocblas_stride batch_stride_c, void* d, rocblas_stride offsetDin, rocblas_int row_stride_d, rocblas_int col_stride_d, rocblas_stride batch_stride_d, rocblas_int batch_count) { Tc alpha_h, beta_h; RETURN_IF_ROCBLAS_ERROR( rocblas_copy_alpha_beta_to_host_if_on_device(handle, alpha, beta, alpha_h, beta_h, k)); // check alignment of pointers before casting if(!isAligned(a, sizeof(Ti)) || !isAligned(b, sizeof(Ti)) || !isAligned(c, sizeof(To)) || !isAligned(d, sizeof(To))) return rocblas_status_invalid_size; return gemm_ext2_batched_template(handle, m, n, k, (const Tc*)alpha, (const Ti*)a, offsetAin, row_stride_a, col_stride_a, batch_stride_a, (const Ti*)b, offsetBin, row_stride_b, col_stride_b, batch_stride_b, (const Tc*)beta, (const To*)c, offsetCin, row_stride_c, col_stride_c, batch_stride_c, (To*)d, offsetDin, row_stride_d, col_stride_d, batch_stride_d, batch_count); } inline rocblas_status rocblas_gemm_ext2_template(rocblas_handle handle, rocblas_int m, rocblas_int n, rocblas_int k, const void* alpha, const void* a, rocblas_datatype a_type, rocblas_stride offsetAin, rocblas_int row_stride_a, rocblas_int col_stride_a, rocblas_stride batch_stride_a, const void* b, rocblas_datatype b_type, rocblas_stride offsetBin, rocblas_int row_stride_b, rocblas_int col_stride_b, rocblas_stride batch_stride_b, const void* beta, const void* c, rocblas_datatype c_type, rocblas_stride offsetCin, rocblas_int row_stride_c, rocblas_int col_stride_c, rocblas_stride batch_stride_c, void* d, rocblas_datatype d_type, rocblas_stride offsetDin, rocblas_int row_stride_d, rocblas_int col_stride_d, rocblas_stride batch_stride_d, rocblas_int batch_count, rocblas_datatype compute_type, uint32_t flags) { // Note: k==0 is not an early exit, since C still needs to be multiplied by beta if(!m || !n || !batch_count) return rocblas_status_success; rocblas_status rb_status = rocblas_status_not_implemented; #define EX_TYPECASTING_PARM \ handle, m, n, k, alpha, a, offsetAin, row_stride_a, col_stride_a, batch_stride_a, b, \ offsetBin, row_stride_b, col_stride_b, batch_stride_b, beta, c, offsetCin, row_stride_c, \ col_stride_c, batch_stride_c, d, offsetDin, row_stride_d, col_stride_d, batch_stride_d, \ batch_count if(a_type == rocblas_datatype_f64_r && b_type == rocblas_datatype_f64_r && c_type == rocblas_datatype_f64_r && d_type == rocblas_datatype_f64_r && compute_type == rocblas_datatype_f64_r) { rb_status = rocblas_gemm_ext2_typecasting<double>(EX_TYPECASTING_PARM); } else if(a_type == rocblas_datatype_f32_r && b_type == rocblas_datatype_f32_r && c_type == rocblas_datatype_f32_r && d_type == rocblas_datatype_f32_r && compute_type == rocblas_datatype_f32_r) { rb_status = rocblas_gemm_ext2_typecasting<float>(EX_TYPECASTING_PARM); } else if(a_type == rocblas_datatype_f16_r && b_type == rocblas_datatype_f16_r) { if(c_type == rocblas_datatype_f16_r && d_type == rocblas_datatype_f16_r) { if(compute_type == rocblas_datatype_f16_r) { rb_status = rocblas_gemm_ext2_typecasting<rocblas_half>(EX_TYPECASTING_PARM); } else if(compute_type == rocblas_datatype_f32_r) { rb_status = rocblas_gemm_ext2_typecasting<rocblas_half, rocblas_half, float>( EX_TYPECASTING_PARM); } } else if(c_type == rocblas_datatype_f32_r && d_type == rocblas_datatype_f32_r && compute_type == rocblas_datatype_f32_r) { rb_status = rocblas_gemm_ext2_typecasting<rocblas_half, float, float>(EX_TYPECASTING_PARM); } } else if(a_type == rocblas_datatype_bf16_r && b_type == rocblas_datatype_bf16_r && compute_type == rocblas_datatype_f32_r) { if(c_type == rocblas_datatype_bf16_r && d_type == rocblas_datatype_bf16_r) { rb_status = rocblas_gemm_ext2_typecasting<rocblas_bfloat16, rocblas_bfloat16, float>( EX_TYPECASTING_PARM); } else if(c_type == rocblas_datatype_f32_r && d_type == rocblas_datatype_f32_r) { rb_status = rocblas_gemm_ext2_typecasting<rocblas_bfloat16, float, float>( EX_TYPECASTING_PARM); } } else if(a_type == rocblas_datatype_i8_r && b_type == rocblas_datatype_i8_r && c_type == rocblas_datatype_i32_r && d_type == rocblas_datatype_i32_r && compute_type == rocblas_datatype_i32_r) { bool useInt8x4 = flags & rocblas_gemm_flags_pack_int8x4; // Here is point where we decide to branch to real int8 or rocblas_int8x4 // MatrixInstruction kernel uses general int8 (unless rocblas_gemm_flags_pack_int8x4 is set) if(!useInt8x4) { rb_status = rocblas_gemm_ext2_typecasting<int8_t, int32_t>(EX_TYPECASTING_PARM); } // Else, we check if we can pack 4 int8: else { // For now, K must be a multiple of 4 if(k % 4 || col_stride_b % 4 || batch_stride_a % 4 || batch_stride_b % 4) { rb_status = rocblas_status_invalid_size; } else { // adjust by 4 for Tensile col_stride_b /= 4; k /= 4; batch_stride_a /= 4; batch_stride_b /= 4; rb_status = rocblas_gemm_ext2_typecasting<rocblas_int8x4, int32_t>(EX_TYPECASTING_PARM); } } } else if(a_type == rocblas_datatype_f32_c && b_type == rocblas_datatype_f32_c && c_type == rocblas_datatype_f32_c && d_type == rocblas_datatype_f32_c && compute_type == rocblas_datatype_f32_c) { rb_status = rocblas_gemm_ext2_typecasting<rocblas_float_complex, rocblas_float_complex, rocblas_float_complex>(EX_TYPECASTING_PARM); } else if(a_type == rocblas_datatype_f64_c && b_type == rocblas_datatype_f64_c && c_type == rocblas_datatype_f64_c && d_type == rocblas_datatype_f64_c && compute_type == rocblas_datatype_f64_c) { rb_status = rocblas_gemm_ext2_typecasting<rocblas_double_complex, rocblas_double_complex, rocblas_double_complex>(EX_TYPECASTING_PARM); } else { rb_status = rocblas_status_not_implemented; } return rb_status; } #undef EX_TYPECASTING_PARM
#ifndef EXCEPTION_H #define EXCEPTION_H //Fichier de définition des exception class TacheException{ public: TacheException(const QString& message):info(message){} QString getInfo() const { return info; } private: QString info; }; class CalendarException{ public: CalendarException(const QString& message):info(message){} QString getInfo() const { return info; } private: QString info; }; class ProjetException{ public: ProjetException(const QString& message):info(message){} QString getInfo() const { return info; } private: QString info; }; /*! \class TimeException \brief Classe permettant de gérer les exceptions des classes du namespace TIME */ class TimeException{ public: //! Constructeur à partir d'une string TimeException(const QString& m):info(m){} const QString& GetInfo() const { return info; } //<! Retourne l'information stockée dans la classe private: QString info; }; //Pour commit ! #endif // EXCEPTION_H
#ifndef GAME_LOGIC_HEAD_FILE #define GAME_LOGIC_HEAD_FILE #include <vector> #include "Typedef.h" ////////////////////////////////////////////////////////////////////////// //数值掩码 #define LOGIC_MASK_COLOR 0xF0 //花色掩码 #define LOGIC_MASK_VALUE 0x0F //数值掩码 ////////////////////////////////////////////////////////////////////////// #define CopyMemory(Destination,Source,Length) memcpy((Destination),(Source),(Length)) #define CountArray(array) ((sizeof(array))/(sizeof(array[0]))) //游戏逻辑 class CGameLogic { //变量定义 private: static const BYTE m_cbCardListData[52*8]; //扑克定义 //函数定义 public: //构造函数 CGameLogic(); //析构函数 virtual ~CGameLogic(); //类型函数 public: //获取数值 BYTE GetCardValue(BYTE cbCardData) { return cbCardData&LOGIC_MASK_VALUE; } //获取花色 BYTE GetCardColor(BYTE cbCardData) { return cbCardData&LOGIC_MASK_COLOR; } //控制函数 public: //混乱扑克 //void RandCardList(BYTE cbCardBuffer[], BYTE cbBufferCount,LONGLONG dwUserID); void RandCardList(BYTE cbCardBuffer[], BYTE cbBufferCount); //洗牌 BYTE* Shuffle(size_t& count, int randSeed); //逻辑函数 public: std::string GetCardValueName(BYTE card); std::string GetCardColorName(BYTE card); std::string getCardInfo(BYTE card); //获取牌点 BYTE GetCardPip(BYTE cbCardData); //获取牌点 BYTE GetCardListPip(const BYTE cbCardData[], BYTE cbCardCount); //获取扑克总数 static int GetCardCount() { return 52 * 8; } }; ////////////////////////////////////////////////////////////////////////// #endif
#include <iostream> #include <string> #include<vector> #include <cassert> //lets us use assertions in C ++ using namespace std; /// class person class Person { private : string name; string ssnum; int age; public: Person(); Person(string pname, string pssnum, int page); ~Person(); string getName(); string getSSNum(); int getAge(); void setName(string pname); void setSSNum(string pssnum); void setAge(int page); }; Person :: Person() { name = " "; ssnum = " "; age = 0; } Person :: Person(string pname, string pssnum, int page) { name = pname; ssnum = pssnum; age = page; } Person :: ~Person(){ } string Person :: getName() { return name; } string Person :: getSSNum(){ return ssnum; } int Person :: getAge(){ return age; } void Person :: setName(string pname){ name = pname; } void Person :: setSSNum(string pssnum){ ssnum = pssnum; } void Person :: setAge(int page){ age = page; } ///class date class Date { public: int month; int day; int year; Date(); Date(int month,int day,int year); void display1(); void display2(); void increment(); Date &operator=(const Date &T); }; Date::Date() { month = 1;//default month value day = 1;//default day value year = 2000;//default year value } //postcondition: a Date with a month, day and year has been created //precondition: Date will check if any of the conditions have been violated Date::Date(int Month,int Day,int Year) { if((Month < 1||Month > 12)||(Day < 1||Day > 31)||(Year < 1900||Year > 2020)) { std::cout<<"Invalid"<<std::endl; } else { month = Month; day = Day; year = Year; } } //postcondition: Date checked that the code does not violate any of the parameters //precondition: Day will have been incremented by 1 void Date::increment() { //month += 1; //assert(month >= 1 && month <= 12); day += 1; assert(day >= 1 && day <= 31); if(month == 2 && day == 28 || day == 29) { if(year % 4 || year % 400) { std::cout<<"Thats a Leap Year"<<std::endl; //month += 1; day += 1 ; //year++; assert(day >= 1 && day <= 31); assert(month >= 1 && month <= 12); } } } //postcondition: Day has been incremented by 1 void Date::display1() { std::cout<<month<<'/'<<day<<'/'<<year; } //postcondition: Date has been displayed in number format void Date::display2() { string Month; switch(month) { case 1: Month="January"; break; case 2: Month="February"; break; case 3: Month="March"; break; case 4: Month="April"; break; case 5: Month="May"; break; case 6: Month="June"; break; case 7: Month="July"; break; case 8: Month="August"; break; case 9: Month="September"; break; case 10: Month="October"; break; case 11: Month="November"; break; case 12: Month="December"; break; } std::cout<<Month<<'/'<<day<<'/'<<year<<std::endl; } Date &Date::operator=(const Date &T) { month = T.month; day = T.day; year = T.year; return *this; } ///class spouse class Spouse : public Person{ private: Date anniversaryDate; public: Spouse(); Spouse(string pname, string pssnum, int page, int m, int d, int y); ~Spouse(); Date getAnniversaryDate(); void setAnniversarDate(int m, int d, int y); }; Spouse :: Spouse(){ } Spouse :: Spouse(string pname, string pssnum, int page, int m , int d , int y) : Person (pname, pssnum, page){ anniversaryDate = Date(m , d, y); } Spouse :: ~Spouse() { } Date Spouse :: getAnniversaryDate(){ return anniversaryDate; } void Spouse :: setAnniversarDate(int m, int d, int y){ anniversaryDate.month = m; anniversaryDate.day = d; anniversaryDate.year = y; } ///class child class Child : public Person { private: string favoriteToy; public: Child(); Child(string pname, string pssnum, int page, string favToy); ~Child(); string getFavoriteToy(); void setFavoriteToy(string favToy); }; Child :: Child(){ favoriteToy = " "; } Child :: Child(string pname, string pssnum, int page, string favToy) : Person(pname, pssnum, page){ favoriteToy = favToy; } Child :: ~Child(){ } string Child :: getFavoriteToy(){ return favoriteToy; } void Child :: setFavoriteToy (string favToy){ favoriteToy = favToy; } /// class division class Division { private: string divisionName; public: Division(); Division(string s); ~Division(); string getDivisionName(); void setDivisionName(string s); }; Division :: Division(){ divisionName = " "; } Division :: Division(string s){ divisionName = s; } Division :: ~Division(){ } string Division :: getDivisionName(){ return divisionName; } void Division :: setDivisionName(string s){ divisionName = s; } ///class JobDescription class JobDescription { private: string description; public: JobDescription(); JobDescription(string s); ~JobDescription(); string getDescription(); void setDescription(string s); }; JobDescription :: JobDescription(){ description = " "; } JobDescription :: JobDescription(string s){ description = s; } JobDescription :: ~JobDescription(){ } string JobDescription :: getDescription(){ return description; } void JobDescription :: setDescription(string s){ description = s; } ///class employee class Employee : public Person{ private : string companyID; string title; Date startDate; Spouse *spouse; vector<Child *> children; Division *division; vector<JobDescription *> jobs; public : Employee(); Employee(string pname, string pssnum, int page, string id, string s, int m, int d, int y); Employee(Division * div, JobDescription * job); ~Employee(); string getCompanyID(); string getTitle(); Date getStartDate(); Division * getDivision(); JobDescription ** getJobs(); Spouse * getSpouse(); Child** getChildren(); void setCompanyID(string id); void setTitle(string s); void setStartDate(int m, int d, int y); void setDivision(Division * div); void addJob(JobDescription * job); void setSpouse(Spouse * sp); void addChild(Child * ch); void print(); }; Employee :: Employee(){ companyID = " "; title = " "; Division div(" "); division = &div; JobDescription job(" "); jobs.push_back(&job); spouse = NULL; children.clear(); } Employee :: Employee(string pname, string pssnum, int page, string id, string s, int m, int d, int y) : Person (pname, pssnum, page){ companyID =id; title = s; startDate.month = m; startDate.day = d; startDate.year = y; Division divv(" "); division = &divv; spouse = NULL; children.clear(); } Employee :: Employee(Division * div, JobDescription * job){ companyID = " "; title = " "; division = div; jobs.push_back(job); spouse = NULL; children.clear(); } Employee :: ~Employee(){ } string Employee :: getCompanyID(){ return companyID; } string Employee :: getTitle(){ return title; } Date Employee :: getStartDate(){ return startDate; } Division * Employee :: getDivision(){ return division; } JobDescription ** Employee :: getJobs(){ return jobs.data(); } Spouse * Employee :: getSpouse(){ return spouse; } Child** Employee :: getChildren(){ return children.data(); } void Employee :: setCompanyID(string id){ companyID = id; } void Employee :: setTitle(string s){ title = s; } void Employee :: setStartDate(int m, int d, int y){ startDate.month = m; startDate.day = d; startDate.year = y; } void Employee :: setDivision(Division * div){ division = div; } void Employee :: addJob(JobDescription * job){ jobs.push_back(job); } void Employee :: setSpouse(Spouse * sp){ spouse = sp; } void Employee :: addChild(Child * ch){ children.push_back(ch); } void Employee :: print(){ cout<< "name : " << this->getName() << " ssnum : " << this->getSSNum() << " age : " << this->getAge() << "\n\t companyID : " << this->getCompanyID() << " start date : " ; this->getStartDate().display1(); cout << " title : " << this->getTitle() << "\n\t divition : " << this->division->getDivisionName(); cout << " jobs : {" ; for(int i = 0 ; i < this->jobs.size(); i++) { cout << "\n\t\t\t\t\t"; cout << this->jobs[i]->getDescription(); } cout << " } "; cout << "\n\t Spouse : " << this->spouse->getName() << " spouse date : " ; this->spouse->getAnniversaryDate().display1(); cout << " Children : {"; for(int i = 0 ; i < this->children.size(); i++) { cout << "\n\t\t\t\t\t\t\t\t"; cout << this->children[i]->getName() << " " << this->children[i]->getAge() << " " << this->children[i]->getFavoriteToy(); } cout << " } "; cout << endl << endl; } int main() { Division div1("div 1"), div2; div2.setDivisionName("div 2"); JobDescription job1("job 1"), job2( "job 2"), job21; job21.setDescription("job 2.1"); Employee emp1("bat", "ek1", 20, "num1", "title", 1, 1, 2011), emp2(&div2, &job2); emp1.setDivision(&div1); emp1.addJob(&job1); emp2.setName("dorj"); emp2.setSSNum("el2"); emp2.setAge(21); emp2.setCompanyID("num1"); emp2.setTitle("title2"); emp2.setStartDate(12, 31, 2012); emp2.addJob(&job21); Spouse s1("batmaa", "ss1", 19 , 3, 7, 2010), s2("dorjmaa", "ss2", 20 , 11, 20, 2015); emp1.setSpouse(&s1); emp2.setSpouse(&s2); Child b1("bat1", "ekk1", 4, "tobot"), b2("bat2", "ekk2", 3, "barbie"), b3("bat3", "ekk3", 6, "lego"), a1("dorj1", "ell1", 5, "mega"), a2("dorj2", "ell2", 2, "winks"); emp1.addChild(&b1); emp1.addChild(&b2); emp1.addChild(&b3); emp2.addChild(&a1); emp2.addChild(&a2); emp1.print(); emp2.print(); return 0; }
#include <bits/stdc++.h> #define MAXN 100010 using namespace std; typedef long long int lli; int main() { ios_base::sync_with_stdio(false), cin.tie(0), cout.tie(0); int n, x; cin >> n >> x; int v[n]; for(int i=0;i<n;i++){ cin >> v[i]; } sort(v, v+n); int ans = 1; for(int i=n-1;i>=1;i--){ int pos = 1; for(int j=i;j>=1;j--){ if(v[j] - v[j-1] <= x){ pos++; }else{ break; } } ans = max(ans, pos); } cout << ans << endl; return 0; }
// // Created by Celeste Tan on 11/16/20. // #include <iostream> #include "Game.h" #include "NextPiece.h" void Game::run() { window.setKeyRepeatEnabled(false);//to make things more smooth /**design**/ sf::RectangleShape line1, line2; line1.setPosition(10, 10); line1.setSize(sf::Vector2f(10, 1000)); line2.setPosition(900, 10); line2.setSize(sf::Vector2f(10, 1000)); /******/ NextPiece next;//just a variable newBlock(xi); while (window.isOpen()) { events(); if (checkCollision(xi) == true) { rects.push_back(xi); xi = next.giveNext(); x = xi.getPosition().x; y = 0; } for (int i = 0; i < rects.size(); i++) { if (rects[i].checkPos(xi) == true) { /**set block to its x position and the top of the already landed block**/ xi.setPosition(xi.getPosition().x, xi.getPosition().y - (rects[i].getLocalBounds().height)); rects.push_back(xi); xi = next.giveNext(); x = xi.getPosition().x; y = 0; } } update(xi);//makes block fall down screen sf::Color color(20, 100, 50); window.clear(color); window.draw(xi); for (int i = 0; i < rects.size(); i++) { window.draw(rects[i]);//draws all rects in vector } /**design draw**/ window.draw(line1); window.draw(line2); /*****/ window.display(); } } /**checking ground collision**/ bool Game::checkCollision(Blocks &b) { int BlockComing = b.getPosition().y + b.getLocalBounds().height; if (BlockComing >= window.getSize().y) { b.setPosition(b.getPosition().x, window.getSize().y - b.getLocalBounds().height); return true; } return false; } /**function that sets up the block**/ void Game::newBlock(Blocks &b) { NextPiece n; b = n.giveNext(); } /**function that initializes the window**/ Game::Game() : window({920, 1080, 32}, "Tetris") {} /**function that makes the block fall**/ void Game::update(Blocks &item) { float v = 1; y += v; item.setPosition(x, y); } /**events in game**/ void Game::events() { sf::Event event; while (window.pollEvent(event)) { if (event.type == sf::Event::Closed) { window.close(); } /**switching block x**/ if (event.type == sf::Event::MouseButtonPressed) { x = sf::Mouse::getPosition(window).x;//gets the mouses x position xi.setPosition(x, y); } /////**rotation**/ if (sf::Mouse::isButtonPressed(sf::Mouse::Left)) { xi.rotate(90);//rotates 90 degrees everytime mouse clicks } } }
#pragma once #include <RemoteProcess.hpp> #include <easy_lua.hpp> extern void Lua_Export_RemoteModule( lua_State* l, const std::string& global_name ); extern void Lua_Export_RemoteProcess( lua_State* l, const std::string& global_name ); extern std::unique_ptr< haze::CRemoteProcess > g_pRemoteProcess;
#include <iostream> #include <opencv2/opencv.hpp> using namespace std; using namespace cv; int main(int argc, char** argv){ Mat image, mask; int width, height; int nobjects; CvPoint p; image = imread(argv[1],CV_LOAD_IMAGE_GRAYSCALE); if(!image.data){ std::cout << "imagem nao carregou corretamente\n"; return(-1); } width=image.size().width; height=image.size().height; p.x=0; p.y=0; //realizar a eliminação de objetos nas bordas for(int aux = 0; aux < height; aux++){ floodFill(image, CvPoint(aux,0), 0); floodFill(image, CvPoint(aux,255), 0); floodFill(image, CvPoint(0,aux), 0); floodFill(image, CvPoint(255,aux), 0); } // busca objetos com buracos presentes nobjects=0; for(int i=0; i<height; i++){ for(int j=0; j<width; j++){ if(image.at<uchar>(i,j) == 255){ // achou um objeto nobjects++; p.x=j; p.y=i; floodFill(image,p,190); } } } //preencher o fundo da imagem com o tom de cinza 80 floodFill(image, cvPoint(0,0), 80); //Contando os buracos int num_buracos = 0; /* O Loop Funciona da seguinte maneira: depois que o fundo da imagem foi preenchido com tons de cinza 80 e as bolhas foram preenchidas com o tom de cinza 190, os conjuntos de pixels restantes que forem em tom de cinza 0 são os buracos, então a cada pixel com tom 0 que é encontrado, conta-se como um buraco, e realiza um floodFill para que não seja contado de novo */ for(int i = 0; i < height; i++){ for(int j = 0; j < width; j++){ if(image.at<uchar>(i,j) == 0){ p.x = j; p.y = i; floodFill(image, p, 80); num_buracos++; } } } cout << "Numero de objetos: " << nobjects << endl; cout << "Numero de buracos: " << num_buracos << endl; imshow("image", image); imwrite("labeling.png", image); waitKey(); return 0; }
// // George O'Neill @ University of York, 2020/02/05 // // This is a simple program for adapting ROOT files created by 'ungroup2tree' at Orsay for FNT2, and: // - Adds new branches to help time order // - Stores a chained root file and checks whether it exists so should not be rewritten // - Sets up channels, calibrations, gates, and histograms in FNT.h // - Individually adds calibrations, gates, and adjustments in channels.h // - Provides a simple pass check of all numeric conditions in gates.h // - Allows analysis to be fully contained within analysis.cpp // // FNT2 libraries #include "../include/analysis.h" int main(){ // main method will run when compiled // fnt::FNT* f = runfnt(); // method that actually does stuff new fnt::analysis( new fnt::FNT() ); // perform analysis return 1; // exit gracefully } // end main method for compilation void fntsort(){} // allow root compilation
#include <iostream> #include "PerlinNoise.hpp" int main(int argc, char* argv[]) { PerlinNoise PN; const int res = 5; for(int i = 0; i < res; ++i) { for(int j = 0; j < res; ++j) std::cout << PN(static_cast<double>(i)/res, static_cast<double>(j)/res) << " \t"; std::cout << std::endl; } }
#ifndef GN2DTRANSFORM_H #define GN2DTRANSFORM_H #include "GnTransform.h" class GNMAIN_ENTRY Gn2DTransform : public GnTransform { protected: GnVector3 mPostion; GnVector2 mScale; float mRotAngle; public: Gn2DTransform(){}; virtual ~Gn2DTransform(){}; public: inline GnVector3& GetPostion() { return mPostion; } inline void SetPostion(GnVector3 val) { mPostion = val; } inline GnVector2& GetScale() { return mScale; } inline void SetScale(GnVector2 val) { mScale = val; } inline float GetRotAngle() const { return mRotAngle; } inline void SetRotAngle(float val) { mRotAngle = val; } protected: private: }; #endif // GN2DTRANSFORM_H
#ifndef AWS_NODES_STATEMENT_H #define AWS_NODES_STATEMENT_H /* * aws/nodes/statement.h * AwesomeScript Statement * Author: Dominykas Djacenka * Email: Chaosteil@gmail.com */ #include "parsernode.h" namespace AwS{ namespace Nodes{ class Statement : public ParserNode{ public: Statement() : ParserNode(){} virtual ~Statement(){} }; }; }; #endif
#include "mainwindow.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) { setWindowTitle("M580 HIM"); my_mainWidget = new QWidget(this); my_Vlayout = new QVBoxLayout(this); my_Hlayout = new QHBoxLayout(this); my_diode = new Diode(my_mainWidget); QPushButton *diode_button = new QPushButton(tr("&Power Diode"),my_mainWidget); diode_button->setStyleSheet("background-color: rgb(237, 187, 153);" "color: rgb(255, 255, 255);"); connect(diode_button, SIGNAL(clicked()), my_diode, SLOT(setPower()) ); my_Hlayout->addLayout(my_Vlayout, 20); my_Vlayout->addWidget(my_diode); QSpacerItem * horizontalSpacer = new QSpacerItem(20, 100, QSizePolicy::Expanding, QSizePolicy::Minimum); my_Vlayout->addItem(horizontalSpacer); my_Vlayout->addWidget(diode_button); Sender * my_sender = new Sender(); my_Hlayout->addWidget(my_sender); my_mainWidget->setLayout(my_Hlayout); my_mainWidget->setStyleSheet("background-color: rgb(254, 245, 231)"); setCentralWidget(my_mainWidget); } MainWindow::~MainWindow() { qDebug() << "Exit!" ; }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4; c-file-style:"stroustrup" -*- ** ** Copyright (C) 2012 Opera Software AS. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. */ #include "core/pch.h" #if defined(VEGA_SUPPORT) && defined(VEGA_3DDEVICE) #include "modules/libvega/vegapath.h" #include "modules/libvega/src/vegasweepline.h" VEGASweepLine::VEGASweepLine(VEGAPath& path) : m_path(path), m_numLines(path.getNumLines()), m_numUnique(0), m_maxLines(0) , m_vertices(NULL) , m_edges(NULL) , m_order(NULL) #ifdef VEGA_DEBUG_SWEEP_LINE_IMAGE_OUTPUT , m_renderer(NULL), m_renderTarget(NULL), m_bitmap(NULL) #endif // VEGA_DEBUG_SWEEP_LINE_IMAGE_OUTPUT { OP_ASSERT(m_path.isClosed()); OP_ASSERT(!m_path.hasMultipleSubPaths()); } VEGASweepLine::~VEGASweepLine() { OP_DELETEA(m_order); OP_DELETEA(m_edges); OP_DELETEA(m_vertices); #ifdef VEGA_DEBUG_SWEEP_LINE_IMAGE_OUTPUT OP_DELETE(m_renderer); VEGARenderTarget::Destroy(m_renderTarget); OP_DELETE(m_bitmap); #endif // VEGA_DEBUG_SWEEP_LINE_IMAGE_OUTPUT } static int vertComp(void* arg, const void* p1, const void* p2) { VEGASLVertex* vertices = reinterpret_cast<VEGASLVertex*>(arg); const VEGASLVertex& v1 = vertices[*(unsigned short*)p1]; const VEGASLVertex& v2 = vertices[*(unsigned short*)p2]; // compare y values if x values are equal int r = v1.compare(v2); return r; } OP_STATUS VEGASweepLine::init() { OP_ASSERT(m_numLines >= 3); RETURN_IF_ERROR(initVertices()); if (m_numUnique < 3) // This is a straight line. return OpStatus::OK; RETURN_IF_ERROR(initEdges()); // Sort vertices according to x coord. op_qsort_s(m_order, m_numUnique, sizeof(*m_order), vertComp, m_vertices); #ifdef VEGA_DEBUG_SWEEP_LINE_IMAGE_OUTPUT RETURN_IF_ERROR(initDebugRT()); #endif // VEGA_DEBUG_SWEEP_LINE_IMAGE_OUTPUT #ifdef DEBUG_ENABLE_OPASSERT // Initialize unused order to access outside allocated data, so // asserts can catch this later. for (unsigned int i = m_numUnique; i < m_numLines; ++i) m_order[i] = USHRT_MAX; #endif // DEBUG_ENABLE_OPASSERT return OpStatus::OK; } OP_STATUS VEGASweepLine::initVertices() { OP_NEW_DBG("VEGASweepLine::initVertices", "vega.sweepline"); OP_ASSERT(!m_vertices && !m_order); m_vertices = OP_NEWA(VEGASLVertex, m_numLines); RETURN_OOM_IF_NULL(m_vertices); // Used to order vertices according to x coord. m_order = OP_NEWA(unsigned short, m_numLines); RETURN_OOM_IF_NULL(m_order); OP_ASSERT(!m_numUnique); // Initialize vertices. unsigned int pruned = 0; VEGA_FIX* p = m_path.getLine(m_numLines-1); for (unsigned int i = 0; i < m_numLines; ++i) { m_vertices[i].idx = i; VEGA_FIX* v = m_path.getLine(i); m_vertices[i].x = VEGA_FIXTOFLT(v[VEGALINE_STARTX]); m_vertices[i].y = VEGA_FIXTOFLT(v[VEGALINE_STARTY]); m_vertices[i].startOf = m_vertices[i].endOf = 0; m_vertices[i].reflex_handled = false; bool redundant = false; // Needs special handling if the first vertex was discarded, // or v[VEGALINE_END*] won't correspond to the right vertex. if (i == m_numLines-1 && m_order[0] > 0 && m_numUnique > 0) { VEGA_FIX* n = m_path.getLine(m_order[0]); VEGA_FIX rv[4] = { v[0], v[1], n[0], n[1] }; redundant = isRedundant(p, rv); } else redundant = isRedundant(p, v); // Get rid of duplicates, redundant vertices and spikes. if (redundant) { OP_DBG(("pruning vertex %u", i)); ++pruned; m_order[m_numLines - pruned] = i; continue; } m_order[m_numUnique] = i; ++m_numUnique; p = v; } // deal with any remaining identical vertex if (m_numUnique > 1 && !m_vertices[m_order[0]].compare(m_vertices[m_order[m_numUnique-1]])) { OP_DBG(("pruning vertex %u - first and last identical", m_order[m_numUnique-1])); ++pruned; --m_numUnique; // must keep m_order in order, bubble backwards unsigned i = m_numUnique; while (i+1 < m_numLines && m_order[i] < m_order[i+1]) { op_swap(m_order[i], m_order[i+1]); ++i; } for (i = m_numUnique; i < m_numLines-1; ++i) OP_ASSERT(m_order[i] > m_order[i+1]); } OP_ASSERT(m_numUnique < 2 || m_vertices[m_order[0]].compare(m_vertices[m_order[m_numUnique-1]])); OP_ASSERT(m_numUnique + pruned == m_numLines); return OpStatus::OK; } OP_STATUS VEGASweepLine::initEdges() { OP_NEW_DBG("VEGASweepLine::initEdges", "vega.sweepline"); OP_ASSERT(!m_edges); if (!m_maxLines) m_maxLines = m_numLines; OP_ASSERT(m_maxLines >= m_numLines); // The edges of the path. m_edges = OP_NEWA(VEGASLEdge, m_maxLines); RETURN_OOM_IF_NULL(m_edges); unsigned int pruned = m_numLines - m_numUnique; // Initialize edges. unsigned int from = m_order[m_numUnique-1]; for (unsigned int to = 0; to < m_numLines; ++to) { // to has been pruned, it should never be used if (pruned && m_order[m_numUnique + pruned - 1] == to) { m_edges[to].lt = NULL; m_edges[to].rb = NULL; m_edges[to].first = NULL; m_edges[to].second = NULL; #ifdef _DEBUG m_edges[to].idx = USHRT_MAX; #endif // _DEBUG OP_DBG(("vertex %u has been pruned - skipping", to)); --pruned; continue; } m_edges[from].init(m_vertices+from, m_vertices+to); #ifdef _DEBUG m_edges[from].idx = from; #endif // _DEBUG m_vertices[from].startOf = m_edges+from; m_vertices[to] .endOf = m_edges+from; from = to; } OP_ASSERT(!pruned); #ifdef _DEBUG for (unsigned int i = m_numLines; i < m_maxLines; ++i) { m_edges[i].idx = i; m_edges[i].lt = NULL; m_edges[i].rb = NULL; m_edges[i].first = NULL; m_edges[i].second = NULL; } #endif // _DEBUG return OpStatus::OK; } static inline bool isDuplicate(const VEGA_FIX* p, const VEGA_FIX* v) { return (p[VEGALINE_STARTX] == v[VEGALINE_STARTX] && p[VEGALINE_STARTY] == v[VEGALINE_STARTY]); } // true if all three points are on the same line. static inline bool isOnLineOrSpike(const VEGA_FIX* p, const VEGA_FIX* v) { const VEGA_DBLFIX dx = VEGA_FIXTODBLFIX(v[VEGALINE_STARTX] - p[VEGALINE_STARTX]); const VEGA_DBLFIX dy = VEGA_FIXTODBLFIX(v[VEGALINE_STARTY] - p[VEGALINE_STARTY]); const VEGA_DBLFIX px = VEGA_FIXTODBLFIX(v[VEGALINE_ENDX] - p[VEGALINE_STARTX]); const VEGA_DBLFIX py = VEGA_FIXTODBLFIX(v[VEGALINE_ENDY] - p[VEGALINE_STARTY]); return (VEGA_FIXMUL_DBL(px, dy) == VEGA_FIXMUL_DBL(py, dx)); } bool VEGASweepLine::isRedundant(const VEGA_FIX* p, const VEGA_FIX* v) const { return (isDuplicate(p, v) || isOnLineOrSpike(p, v)); } void VEGASLEdge::init(VEGASLVertex* from, VEGASLVertex* to) { first = from; second = to; const int comp = first->compare(*second); OP_ASSERT(comp); // Two consecutive vertices should never be equal. if (comp < 0) { lt = first; rb = second; } else { lt = second; rb = first; } } // Compute angle to l2, using l1 as center-point. The angle is in // range [0; 2*PI[, with 0 to the right of center-point, PI/2 straight // upwards of center-point and so on. static inline float vertAngleAbs(const VEGASLVertex* v1, const VEGASLVertex* v2) { const float dx = v2->x - v1->x; const float dy = v1->y - v2->y; // y grows downwards. float a = (float)op_atan2(dy, dx); if (a < 0.f) a += 2.f*(float)M_PI; return a; } // Convert an absolute angle [0; 3*PI[ to relative [-PI; PI[. static inline float absToRel(float a) { const float twoPI = 2.f*(float)M_PI; if (a >= (float)M_PI) a -= twoPI; OP_ASSERT(a >= -(float)M_PI && a < (float)M_PI); return a; } // Convert a relative angle [-2*PI; PI[ to absolute [0; 2*PI[. static inline float relToAbs(float r) { const float twoPI = 2.f*(float)M_PI; if (r < 0.f) r += twoPI; OP_ASSERT(r >= 0.f && r < twoPI); return r; } /* static */ float VEGASLEdge::getAngleDelta(const VEGASLVertex* pivot, const VEGASLEdge* l1, const VEGASLEdge* l2, bool l1Dir, bool l2Dir) { OP_ASSERT(l1 != l2); const VEGASLEdge* const s1 = l1; const VEGASLEdge* const s2 = l2; float prev_ang = 0; const float twoPI = 2.f*(float)M_PI; bool switched = false; do { const VEGASLVertex* p1 = l1->secondPoint(l1Dir); const VEGASLVertex* p2 = l2->secondPoint(l2Dir); // this direction is a dead end, try other direction and negate result if (p1 == p2) { if (switched) return 0.f; switched = true; prev_ang = 0; l1Dir = !l1Dir; l2Dir = !l2Dir; p1 = l1->secondPoint(l1Dir); p2 = l2->secondPoint(l2Dir); } const float a1abs = vertAngleAbs(pivot, p1); float a1 = a1abs; a1 -= prev_ang; if (a1 < 0.f) a1 += twoPI; a1 = absToRel(a1); float a2 = vertAngleAbs(pivot, p2); a2 -= prev_ang; if (a2 < 0.f) a2 += twoPI; a2 = absToRel(a2); if (a1 != a2) return switched ? (a2-a1) : (a1-a2); prev_ang = a1abs; const float d1 = pivot->squareDistanceTo(*p1); const float d2 = pivot->squareDistanceTo(*p2); if (d2 < d1) { pivot = p2; l2 = l2->nextEdge(l2Dir); } else { pivot = p1; l1 = l1->nextEdge(l1Dir); if (d1 == d2) l2 = l2->nextEdge(l2Dir); } } while (l1 != l2 && (l1 != s1 || l2 != s2)); // We've gone full circle, all bets are off. return 0.f; } float VEGASLEdge::getAngleDelta(const VEGASLEdge& o) const { const VEGASLEdge *l1 = this, *l2 = &o; // true if moving in path order. const bool l1Dir = (l1->lt == l1->first); const bool l2Dir = (l2->lt == l2->first); const VEGASLVertex* p1 = l1->firstPoint(l1Dir); const VEGASLVertex* p2 = l2->firstPoint(l2Dir); const VEGASLVertex* pivot = (p2->compare(*p1) < 0) ? p1 : p1; return getAngleDelta(pivot, this, &o, l1Dir, l2Dir); } bool VEGASLEdge::above(const VEGASLEdge& o) const { OP_ASSERT(idx != o.idx); // This should never be called for intersecting lines! if (lt->x > o.lt->x) return !o.above(*this); // need to use double precision here to stay consistent with // isOnLineOrSpike // perp-dot const double nx = (double)(rb->y - lt->y); const double ny = (double)(lt->x - rb->x); const VEGASLVertex* verts[] = { o.lt, o.rb }; for (unsigned int i = 0; i < ARRAY_SIZE(verts); ++i) { if (verts[i] == lt || verts[i] == rb) continue; const double dx = (double)(verts[i]->x - lt->x); const double dy = (double)(verts[i]->y - lt->y); const double ang = nx*dx + ny*dy; if (ang) return ang < 0; } const float delta = getAngleDelta(o); return delta > 0; } static inline float sign(const float& d) { return d < 0.f ? -1.f : (d > 0.f ? 1.f : 0.f); } bool VEGASLEdge::intersects(const VEGASLEdge& o) const { // Two connected edges can never intersect. if (connectsTo(o)) return false; const double l1[] = { (double)first->x, (double)first->y, (double)second->x, (double)second->y }; const double l2[] = { (double)o.first->x, (double)o.first->y, (double)o.second->x, (double)o.second->y }; unsigned edgenum; const bool r = intersects(l1, l2, &edgenum); if (!edgenum) return r; // Some vertex on edge, need extra checks to determine // intersection. // Gist: Traverse the four neighbours of vertex (two direct, two // from edge) in some direction (cw or ccw). If they occur as // pairs there's no intersection, if they're interleaved there is. const VEGASLVertex* vertex; // Vertex on edge. const VEGASLEdge* edge; // Edge with vertex on it. switch (edgenum) { case 1: vertex = this->first; edge = &o; break; case 2: vertex = this->second; edge = &o; break; case 3: vertex = o.first; edge = this; break; case 4: vertex = o.second; edge = this; break; default: OP_ASSERT(!"expected a valid vertex index"); return false; } // "Neighbouring edges" to edge, needed for breaking ties. For // cases where vertex is on an endpoint of edge (else block) these // are the two edges connected at that endpoint. Otherwise they're // both the same edge, but traversed in different directions. const VEGASLEdge* edge_neighbour_edges[2]; if (vertex->compare(*edge->first) && vertex->compare(*edge->second)) { edge_neighbour_edges[0] = edge; edge_neighbour_edges[1] = edge; } else { const VEGASLVertex* identical = vertex->compare(*edge->first) ? edge->second : edge->first; OP_ASSERT(!vertex->compare(*identical)); edge_neighbour_edges[0] = identical->endOf; edge_neighbour_edges[1] = identical->startOf; } // These are the four neighbours to vertex. const VEGASLVertex* vert_neighbours[] = { vertex->startOf->second, vertex->endOf->first }; const VEGASLVertex* edge_neighbours[] = { edge_neighbour_edges[0]->first, edge_neighbour_edges[1]->second }; // All measured angles are made relative to this one. const float norm = vertAngleAbs(vertex, vert_neighbours[0]); // This is the reference. We check whether both neighbours of edge // are on the same side of this. const float ref = relToAbs(vertAngleAbs(vertex, vert_neighbours[1]) - norm); // Used for breaking ties. const float halfway = ref / 2.f; OP_ASSERT(halfway); // Angle to edge neighbours. float a[2]; for (unsigned i = 0; i < 2; ++i) { a[i] = relToAbs(vertAngleAbs(vertex, edge_neighbours[i]) - norm); const VEGASLEdge* e1; if (!a[i]) // Angle identical to norm. e1 = vertex->startOf; else if (a[i] == ref) e1 = vertex->endOf; else continue; // Reaching this point means angle to current neighbour of // edge was identical to norm or ref. Tie is broken using // getAngleDelta. const VEGASLEdge* e2 = edge_neighbour_edges[i]; const bool d1 = (e1 == vertex->startOf); const bool d2 = (i == 0); const bool same_direction = (e1->lt == vertex) == (e2->lt == edge_neighbours[i]); const float tiebreak = getAngleDelta(vertex, e1, e2, d1, same_direction == d2); if (!tiebreak) // loop, treat as intersecting return true; a[i] -= sign(tiebreak) * halfway; if (a[i] >= (float)M_PI) a[i] -= 2.f*(float)M_PI; a[i] = relToAbs(a[i]); } OP_ASSERT(a[0] && a[0] != ref); OP_ASSERT(a[1] && a[1] != ref); // Intersecting if edge_neighbour_edges on different sides of ref. return ((a[0] > ref) != (a[1] > ref)); } /* static */ bool VEGASLEdge::intersects(const double* l1, const double* l2, unsigned* edgenum/* = NULL*/) { // Intersection is at p1 + fact*(p2-p1), where fact is num/den. if (edgenum) *edgenum = 0; // doubles are called for here, or we might miss intersection due // to precision loss - see 'biglayouttree' const double den = (l2[VEGALINE_ENDY]-l2[VEGALINE_STARTY])* (l1[VEGALINE_ENDX]-l1[VEGALINE_STARTX]) - (l2[VEGALINE_ENDX]-l2[VEGALINE_STARTX])* (l1[VEGALINE_ENDY]-l1[VEGALINE_STARTY]); // Two perpendicular lines can never intersect. if (!den) return false; const double num1 = (l2[VEGALINE_ENDX] -l2[VEGALINE_STARTX])* (l1[VEGALINE_STARTY]-l2[VEGALINE_STARTY]) - (l2[VEGALINE_ENDY] -l2[VEGALINE_STARTY])* (l1[VEGALINE_STARTX]-l2[VEGALINE_STARTX]); const double num2 = (l1[VEGALINE_ENDX] -l1[VEGALINE_STARTX])* (l1[VEGALINE_STARTY]-l2[VEGALINE_STARTY]) - (l1[VEGALINE_ENDY] -l1[VEGALINE_STARTY])* (l1[VEGALINE_STARTX]-l2[VEGALINE_STARTX]); if (edgenum) { if (!num1 || !num2) { *edgenum = num1 ? 3 : 1; return false; } if (num1 == den || num2 == den) { *edgenum = (num2 == den) ? 4 : 2; return false; } } // num / den in ]0; 1[ => intersection between endpoints if (den > 0) { if (num1 <= 0 || num1 >= den || num2 <= 0 || num2 >= den) return false; } else { if (num1 >= 0 || num1 <= den || num2 >= 0 || num2 <= den) return false; } return true; } void VEGASLVerticalEdges::insert(VEGASLEdge* l) { OP_ASSERT(l); for (VEGASLEdge* e = First(); e; e = e->Suc()) { if (l->above(*e)) { l->Precede(e); return; } } l->Into(this); } OP_BOOLEAN VEGASelfIntersect::isSelfIntersecting() { RETURN_IF_ERROR(init()); #ifdef VEGA_DEBUG_SELF_INTERSECT_IMAGE_OUTPUT_OUTLINE DebugDumpOutline(); #endif // VEGA_DEBUG_SELF_INTERSECT_IMAGE_OUTPUT_OUTLINE // Path is made up of connected edges, so at least three are // needed for intersection to be possible. if (m_numUnique < 3) return OpBoolean::IS_FALSE; // FIXME: This should be a balanced tree! VEGASLVerticalEdges active_edges; OP_NEW_DBG("VEGASelfIntersect::isSelfIntersecting", "vega.selfintersect"); for (unsigned int v = 0; v < m_numUnique; ++v) { const unsigned int i = m_order[v]; OP_ASSERT(i < m_numLines); OP_DBG(("* visiting vertex %u", i)); VEGASLVertex* p = m_vertices+i; // Since it's a closed path there are two edges for each vertex. VEGASLEdge* s[] = { p->startOf, p->endOf }; for (unsigned int j = 0; j < ARRAY_SIZE(s); ++j) { VEGASLEdge* si = s[j]; OP_ASSERT(si->idx < m_numLines); const bool left = si->lt == p; if (left) active_edges.insert(si); OP_DBG(("* processing edge %u", si->idx)); for (VEGASLEdge* e = active_edges.First(); e; e = e->Suc()) OP_DBG((" edge %3u", e->idx)); VEGASLEdge* prev_edge = si->Pred(); VEGASLEdge* next_edge = si->Suc(); if (!left) si->Out(); bool moved; do { if (left) { if (prev_edge && si->intersects(*prev_edge)) { OP_DBG((" edge %3u intersects edge %3u\n", si->idx, prev_edge->idx)); return OpBoolean::IS_TRUE; } if (next_edge && si->intersects(*next_edge)) { OP_DBG((" edge %3u intersects edge %3u\n", si->idx, next_edge->idx)); return OpBoolean::IS_TRUE; } } else { if (prev_edge && next_edge && prev_edge->intersects(*next_edge)) { OP_DBG((" edge %3u intersects edge %3u\n", prev_edge->idx, next_edge->idx)); return OpBoolean::IS_TRUE; } } // HACK: Because we support duplicate edges we have to // follow the chains here. moved = false; if (VEGASLEdge* tmp = (prev_edge ? prev_edge->Pred() : NULL)) { if (prev_edge->identicalTo(*tmp)) { OP_DBG((" advancing prev_edge")); prev_edge = tmp; moved = true; } } if (VEGASLEdge* tmp = ((!moved && next_edge) ? next_edge->Suc() : NULL)) { if (next_edge->identicalTo(*tmp)) { OP_DBG((" advancing next_edge")); next_edge = tmp; moved = true; } } } while (moved); } } return OpBoolean::IS_FALSE; } #endif // VEGA_SUPPORT && VEGA_3DDEVICE
#include <iostream> #include "generation.cpp" int main() { srand(time(NULL)); Generation gen(48,48,4,4,4,4); if(gen.Start(12,6,10,6,10) == -1) std::cout << "ERROR: The rooms can't fit into the map, decrease the minimum rooms size or the amount!" << std::endl; else for(int j = 0; j < gen.HEIGHT; j++) std::cout << gen.map[j] << std::endl; return 0; }
#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; int r[100100],c[100100],g[]; int lowbit(int k) { return k & (-k); } void updata(int a[],int k,int n) { while (k <= n) { a[k] += 1; k += lowbit(k); } } void updata2d() int getsum(int a[],int k) { int ans = 0; while (k > 0) { ans += a[k]; k -= lowbit(k); } return ans; } int main() { int n,m,k,q; scanf("%d%d%d%d",&n,&m,&k,&q); for (int i = 1;i <= k; i++) { int x,y; scanf("%d%d",&x,&y); updata(r,x,n); updata(c,y,m); updata2d() } for (int i = 1;i <= q; i++) { int xl,xr,yl,yr; scanf("%d%d%d%d",&xl,&yl,&xr,&yr); printf("%d %d %d %d\n",getsum(r,xr),getsum(r,xl-1),getsum(c,yr),getsum(c,yl-1)); if (getsum(r,xr) - getsum(r,xl-1) == xr-xl+1 && getsum(c,yr) - getsum(c,yl-1) == yr-yl+1) printf("YES\n"); else printf("NO\n"); } return 0; }
#pragma once #include "IQuestionView_fwd.h" #include "QuestionState_fwd.h" #include "types.h" namespace qp { class CQuestionViewController : public boost::noncopyable { public: CQuestionViewController(IQuestionStatePtr const& questionState, IQuestionViewPtr const& view); virtual ~CQuestionViewController(); bool Run(); protected: enum UserInput { DEFAULT, SUBMIT, SKIP, EXIT }; private: void OnSubmitRequest(); void OnSkipRequest(); void OnExitRequest(); ScopedConnection m_submitRequestConnection; ScopedConnection m_skipRequestConnection; ScopedConnection m_exitRequestConnection; IQuestionStatePtr const m_questionState; IQuestionViewPtr const m_view; UserInput m_handleUserInputResult; }; }
#ifndef Q04_H #define Q04_H #include<iostream> using namespace std; /** * 4. 归并排序 */ // time: O(n*log2(n)) space: O(n) 稳定 顺序存储和链式存储 void merge_sort(int *data, int start, int end, int *result); void merge(int *data,int start,int end,int *result); #endif
#include <iostream> #include <string.h> #include "BufferManager.h" using namespace std; CBufferManager_t::CBufferManager_t() { } CBufferManager_t::~CBufferManager_t() { if (m_pStart != NULL) { delete[] m_pStart; m_pStart = NULL; } } bool CBufferManager_t::Init(unsigned int maxLength) { m_pStart = new unsigned char[maxLength]; if (m_pStart == 0) { //debug fprintf(stderr, "new maxLength:%d error\n", maxLength); return false; } m_Lenght = maxLength; m_Offset = 0; return true; } bool CBufferManager_t::Register(string name, CBufferInfo_t* info) { pair<map<string, CBufferInfo_t*>::iterator, bool> ret; ret = m_RegMap.insert(pair<string, CBufferInfo_t*>(name, info)); if (!ret.second) { fprintf(stderr, "CmdDespatch::RegisterCmdHandle L_Insert name:%s error\n", name.c_str()); return false; } fprintf(stderr, "CmdDespatch::RegisterCmdHandle L_Insert name:%s success\n", name.c_str()); return true; } bool CBufferManager_t::UnRegister(string name) { map<string, CBufferInfo_t*>::iterator l_it; l_it = m_RegMap.find(name); if (l_it == m_RegMap.end()) { fprintf(stderr, "UnregisterCmdHandle name:%s error\n", name.c_str()); return false; } else { fprintf(stderr, "UnregisterCmdHandle name:%s erase\n", name.c_str()); m_RegMap.erase(l_it);//delete 112; return true; } } void CBufferManager_t::Sync() { map<string, CBufferInfo_t*>::iterator l_it; for (l_it = m_RegMap.begin(); l_it != m_RegMap.end(); l_it++) { string name = l_it->first; CBufferInfo_t* pInfo = l_it->second; if (pInfo != NULL) { CCircularQueue<CBuffer_t>* bufferQueue = pInfo->usingQueue(); bufferQueue->SyncRwPoint(); } } } bool CBufferManager_t::Write(unsigned char* data, unsigned int length, unsigned long long pts) { if (data == NULL || length <= 0 || m_pStart == NULL) { return false; } if (length > m_Lenght) return false; //default: We believe that the cache is large enough, there is no cover immediately if (m_Offset + length > m_Lenght) { m_Offset = 0; } //fprintf(stderr, "Write data:%p length:%u pts:%llu \n", data, length, pts); unsigned char* pos = m_pStart + m_Offset; memcpy(pos, data, length); m_Offset += length; //Traverse Map, updated info map<string, CBufferInfo_t*>::iterator l_it; for (l_it = m_RegMap.begin(); l_it != m_RegMap.end(); l_it++) { string name = l_it->first; CBufferInfo_t* pInfo = l_it->second; if (pInfo != NULL) { CCircularQueue<CBuffer_t>* bufferQueue = pInfo->usingQueue(); CBuffer_t buffer; buffer.data = pos; buffer.lenght = length; buffer.pts = pts; bufferQueue->PushBack(buffer); } } return true; } /////////////////////////////////////////////////////////////////////////////////////// CBufferInfo_t::CBufferInfo_t(int nQueueSize) { m_BufferQueue = new CCircularQueue<CBuffer_t>(nQueueSize); } CBufferInfo_t::~CBufferInfo_t() { if (m_BufferQueue != NULL) { delete m_BufferQueue; m_BufferQueue = NULL; } }
#include "CGetPayInfo.h" #include "json/json.h" #include "Logger.h" #include "threadres.h" #include "JsonValueConvert.h" #include "StrFunc.h" #include "TcpMsg.h" int CGetPayInfo::do_request(const Json::Value& root, char *client_ip, HttpResult& out) { //Json::Value ret; //Json::FastWriter write; out["result"] = 0; out["tips"] = "订单不存在"; int mid = Json::SafeConverToInt32(root["mid"]); int sid = Json::SafeConverToInt32(root["sid"]); int gameid = Json::SafeConverToInt32(root["gameid"]); int cid = Json::SafeConverToInt32(root["cid"]); int pid = Json::SafeConverToInt32(root["pid"]); int ctype =Json::SafeConverToInt32(root["ctype"]); std::string payDealNo = root["param"]["pdealno"].asString(); if (mid <= 0 || payDealNo.empty()) { //out = write.write(ret); return status_param_error; } CAutoUserDoing userDoing(mid); if (userDoing.IsDoing()) { out["msg"] = "您操作太快了,请休息一会!"; return status_param_error; } LOGGER(E_LOG_DEBUG) << root.toStyledString(); Json::Value payInfo; std::string tips; if (payDealNo.find("wr") != std::string::npos) { if (getWithdrawalsByDealNo(payDealNo, payInfo)) { if (payInfo["pstatus"] == 4) { out["ptype"] = 7; tips = "你的申请兑换单号"; tips += payInfo["pdealno"].asString(); tips += "审核不通过,请联系客服。"; } else { out["ptype"] = 6; tips = "你的申请兑换"; tips += payInfo["pamount"].asString(); tips += "元请求已经收到,我们会在十分钟处理到账。"; } out["tips"] = tips; } else { //out += write.write(ret); return status_ok; } } else { if (getPayByDealNo(payDealNo, payInfo)) { out["result"] = 1; out["ptype"] = 1; tips = "购买成功,得到"; tips += payInfo["pamount"].asString(); tips += "金币"; } else { //out = write.write(ret); return status_ok; } } out["result"] = 1; out["exchangenum"] = payInfo["pexchangenum"].asInt(); out["viptime"] = 0; out["rool"] = 0; out["roll1"] = 0; out["source"] = 0; out["pdealno"] = payDealNo; out["tips"] = tips; CTcpMsg::getMoney(out , mid); //out = write.write(ret); return status_ok; } bool CGetPayInfo::getWithdrawalsByDealNo(std::string payDealNo, Json::Value& info) { info["pdealno"] = payDealNo; MySqlDBAccess* pDBAccess = ThreadResource::getInstance().getDBConnMgr()->DBMaster(); const std::string strTb_Pc_withdrawals = "paycenter.pc_withdrawals"; std::string strSql = StrFormatA("SELECT pamount, pexchangenum, pstatus FROM %s WHERE pdealno='%s';", strTb_Pc_withdrawals.c_str(), payDealNo.c_str()); MySqlResultSet *pResult = pDBAccess->Query(strSql.c_str()); if (pResult == NULL) { return false; } if (pResult->hasNext()) { info["pamount"] = pResult->getFloatValue(0); info["pexchangenum"] = pResult->getFloatValue(1); info["pstatus"] = pResult->getIntValue(2); delete pResult; return true; } delete pResult; return false; } bool CGetPayInfo::getPayByDealNo(std::string payDealNo, Json::Value& info) { info["pdealno"] = payDealNo; MySqlDBAccess* pDBAccess = ThreadResource::getInstance().getDBConnMgr()->DBMaster(); if (NULL == pDBAccess) return false; const std::string strTb_Pc_payment = "paycenter.pc_payment"; std::string strSql = StrFormatA("SELECT pamount, pexchangenum FROM %s WHERE pdealno='%s' AND pstatus in (2, 3);", strTb_Pc_payment.c_str(), payDealNo.c_str()); MySqlResultSet *pResult = pDBAccess->Query((char*)strSql.c_str()); if (pResult == NULL) { return false; } if (pResult->hasNext()) { info["pamount"] = pResult->getFloatValue(0); info["pexchangenum"] = pResult->getIntValue(1); delete pResult; return true; } delete pResult; return false; }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 1995-2002 Opera Software AS. All rights reserved. * * This file is part of the Opera web browser. It may not be distributed * under any circumstances. */ #include "core/pch.h" #include "modules/widgets/OpTime.h" #include "modules/forms/datetime.h" #include "modules/forms/webforms2number.h" #include "modules/widgets/OpSpinner.h" #include "modules/widgets/OpEdit.h" #include "modules/display/vis_dev.h" // == OpTime =========================================================== DEFINE_CONSTRUCT(OpTime) OpTime::OpTime() : m_hour_field(NULL), #ifndef PATTERN_EDIT m_minute_field(NULL), m_colon1_field(NULL), #endif m_has_min_value(FALSE), m_has_max_value(FALSE), m_has_step(FALSE), m_precision(TIME_PRECISION_MINUTES), m_readonly(FALSE) { OP_STATUS status; #ifdef PATTERN_EDIT status = OpEdit::Construct(&m_hour_field); #else status = OpNumberEdit::Construct(&m_hour_field); #endif // PATTERN_EDIT CHECK_STATUS(status); AddChild(m_hour_field, TRUE); #ifdef PATTERN_EDIT m_hour_field->SetPattern(UNI_L(" : ")); m_hour_field->SetAllowedChars("0123456789"); #else m_hour_field->SetMaxValue(23.0); // 23 is the last hour m_hour_field->SetMinValue(0.0); m_hour_field->SetWrapAround(TRUE); status = OpEdit::Construct(&m_colon1_field); CHECK_STATUS(status); AddChild(m_colon1_field, TRUE); m_colon1_field->SetText(UNI_L(":")); m_colon1_field->SetFlatMode(); m_colon1_field->SetEnabled(FALSE); status = OpNumberEdit::Construct(&m_minute_field); CHECK_STATUS(status); AddChild(m_minute_field, TRUE); m_minute_field->SetMaxValue(59.0); // 59 is the last minute m_minute_field->SetMinValue(0.0); m_minute_field->SetWrapAround(TRUE); m_minute_field->SetListener(this); #endif m_hour_field->SetListener(this); status = OpSpinner::Construct(&m_spinner); CHECK_STATUS(status); AddChild(m_spinner, TRUE); m_spinner->SetListener(this); TimeSpec empty_time; empty_time.Clear(); m_last_set_full_time = empty_time; } /** * This is called to refill the widget after reflow or history movement. */ OP_STATUS OpTime::SetText(const uni_char* text) { if (!text || !*text) { // Clear the time return SetEmptyValue(); } TimeSpec time; // Parse... if (!time.SetFromISO8601String(text)) { return OpStatus::ERR; } return SetValue(time); } OP_STATUS OpTime::SetValue(TimeSpec time) { #ifdef PATTERN_EDIT m_last_set_full_time = time; switch (m_precision) { // case TIME_PRECISION_HOURS: // time.pattern = UNI_L(" "); // break; case TIME_PRECISION_MINUTES: time.SetSecondUndefined(); time.SetFractionUndefined(); break; case TIME_PRECISION_SECONDS: if (time.IsSecondUndefined()) { time.m_second = 0; } time.SetFractionUndefined(); break; case TIME_PRECISION_SUBSECOND: case TIME_PRECISION_SUBSECOND2: case TIME_PRECISION_SUBSECOND3: if (time.IsSecondUndefined()) { time.m_second = 0; } if (time.IsFractionUndefined()) { time.SetFraction(0,3); } break; } // We need 6-13 chars depending on how many decimals we have. OpString buf_obj; int str_len = time.GetISO8601StringLength(); uni_char* buf = buf_obj.Reserve(MAX(str_len+1, 20)); if (!buf) { return OpStatus::ERR_NO_MEMORY; } time.ToISO8601String(buf); int expected_len = str_len; if (m_precision == TIME_PRECISION_SUBSECOND) { expected_len = 12; } else if (m_precision == TIME_PRECISION_SUBSECOND2) { expected_len = 15; } else if (m_precision == TIME_PRECISION_SUBSECOND3) { expected_len = 18; } while (expected_len > str_len) { // Pad with zeroes buf[str_len++] = '0'; buf[str_len] = '\0'; } while (expected_len < str_len) { // Just truncate buf[--str_len] = '\0'; } OP_STATUS status = m_hour_field->SetText(buf); OP_ASSERT(OpStatus::IsSuccess(status)); UpdateButtonState(); return status; #else uni_char buf[3] = { 0, 0, 0}; buf[0] = time.m_hour/10+'0'; buf[1] = time.m_hour%10+'0'; RETURN_IF_ERROR(m_hour_field->SetText(buf)); buf[0] = time.m_minute/10+'0'; buf[1] = time.m_minute%10+'0'; return m_minute_field->SetText(buf); #endif // PATTERN_EDIT } OP_STATUS OpTime::GetText(OpString &str) { // XXX Ever used? OP_ASSERT(FALSE); // If this never triggers we can remove this method if (HasValue()) { TimeSpec time; if (GetTime(time)) { uni_char* buf = str.Reserve(time.GetISO8601StringLength()+1); if (!buf) { return OpStatus::ERR_NO_MEMORY; } time.ToISO8601String(buf); } } return OpStatus::OK; } void OpTime::SetReadOnly(BOOL readonly) { if (readonly != m_readonly) { m_readonly = readonly; m_hour_field->SetReadOnly(readonly); #ifndef PATTERN_EDIT m_minute_field->SetReadOnly(readonly); #endif // PATTERN_EDIT UpdateButtonState(); } } /*virtual*/ void OpTime::GetPreferedSize(INT32* w, INT32* h, INT32 cols, INT32 rows) { UINT32 colon_char_w = GetVisualDevice()->GetFontStringWidth(UNI_L(":"), 1); // Place for two colons and 5% of the rest INT32 colon_width = colon_char_w; // 3*colon_char_w/2 + 5; UINT32 two_digits_w = GetVisualDevice()->GetFontStringWidth(UNI_L("00"), 2); int padding_border_overhead_w = 8; // Guesses int padding_border_overhead_h = 4; // Guesses #ifdef PATTERN_EDIT switch (m_precision) { // case TIME_PRECISION_HOURS: case TIME_PRECISION_MINUTES: *w = two_digits_w*2 + colon_width; break; case TIME_PRECISION_SECONDS: *w = two_digits_w*3 + colon_width*2; break; case TIME_PRECISION_SUBSECOND: *w = two_digits_w*5 + colon_width*3; break; case TIME_PRECISION_SUBSECOND2: *w = two_digits_w*6 + colon_width*3; break; default: OP_ASSERT(FALSE); // Should not be reachable case TIME_PRECISION_SUBSECOND3: *w = two_digits_w*8 + colon_width*3; break; } INT32 spinner_width = 0; INT32 spinner_height = 0; // We guess a height. If we get this wrong we will answer with a too wide or too narrow size GetPreferredSpinnerSize(font_info.size+padding_border_overhead_h+4, &spinner_width, &spinner_height); *w += padding_border_overhead_w + spinner_width + 2; // 2 pixels between the field and the spinner #else *w = (two_digits_w + 23) *2 + 1*colon_width; #endif // PATTERN_EDIT // m_timezone_field *h = 0; // don't care } void OpTime::GetPreferredSpinnerSize(int widget_height, INT32* spinner_width, INT32* spinner_height) { m_spinner->GetPreferedSize(spinner_width, spinner_height); if (*spinner_height != 0) { float spinner_height_scale = static_cast<float>(widget_height)/ *spinner_height; *spinner_width = static_cast<int>(spinner_height_scale * *spinner_width + 0.5f); } *spinner_height = widget_height; } void OpTime::OnResize(INT32* new_w, INT32* new_h) { int width = *new_w; int height = *new_h; INT32 spinner_width = 0; INT32 spinner_height = 0; GetPreferredSpinnerSize(height, &spinner_width, &spinner_height); m_spinner->SetRect(OpRect(width - spinner_width, 0, spinner_width, spinner_height)); width -= spinner_width + 2; // Margin of 2 pixels #ifdef PATTERN_EDIT INT32 field_width = width; #else UINT32 colon_char_w = GetVisualDevice()->GetFontStringWidth(UNI_L(":"), 1); const int field_count = 2; const int colon_count = 1; // Place for two colons and 5% of the rest INT32 colon_width = 3*colon_char_w/2 + (width - 3*colon_char_w/2)/20; INT32 field_width = (width - colon_count*colon_width) / field_count; // One third each of the rest #endif // PATTERN_EDIT int current_x = 0; m_hour_field->SetRect(OpRect(current_x, 0, field_width, height)); #ifndef PATTERN_EDIT current_x += field_width; m_colon1_field->SetRect(OpRect(current_x, 0, colon_width, height)); current_x += colon_width; m_minute_field->SetRect(OpRect(current_x, 0, field_width, height)); #endif // !PATTERN_EDIT } const uni_char* OpTime::GetEditPattern() const { // Could be a table instead switch (m_precision) { // case OpTime::TIME_PRECISION_HOURS: // pattern = UNI_L(" "); // break; case OpTime::TIME_PRECISION_MINUTES: return UNI_L(" : "); case OpTime::TIME_PRECISION_SECONDS: return UNI_L(" : : "); break; case OpTime::TIME_PRECISION_SUBSECOND: return UNI_L(" : : . "); case OpTime::TIME_PRECISION_SUBSECOND2: return UNI_L(" : : . "); } OP_ASSERT(m_precision == OpTime::TIME_PRECISION_SUBSECOND3); return UNI_L(" : : . "); } void OpTime::EndChangeProperties() { // propagate background color to edit field if (!m_color.use_default_background_color) m_hour_field->SetBackgroundColor(m_color.background_color); m_hour_field->SetHasCssBackground(HasCssBackgroundImage()); m_hour_field->SetHasCssBorder(HasCssBorder()); } void OpTime::OnFocus(BOOL focus, FOCUS_REASON reason) { if (focus) { m_hour_field->SetFocus(reason); } else { // Don't leave anything broken so that the user won't be tricked into // believing that we'll use what he, she wrote. if (HasValue()) { TimeSpec dummy_time_spec; if (!GetTime(dummy_time_spec)) { // Broken input SetEmptyValue(); } } } } BOOL OpTime::OnMouseWheel(INT32 delta,BOOL vertical) { if (IsEnabled() && !m_readonly && !IsDead()) { for(int i = 0; i < op_abs(delta); i++) OnClick(m_spinner, delta > 0 ? 1 : 0); return TRUE; } return FALSE; } void OpTime::OnChangeWhenLostFocus(OpWidget *widget) { if (listener && (widget == m_hour_field #ifndef PATTERN_EDIT || widget == m_minute_field #endif // PATTERN_EDIT )) { // We no longer need any backup to keep parts of the time since the user has // written a new time that we will use instead. TimeSpec empty_time; empty_time.Clear(); m_last_set_full_time = empty_time; // m_seconds = 0; // m_hundreths = 0; listener->OnChange(this); } } OP_STATUS OpTime::SetEmptyValue() { const uni_char* pattern = GetEditPattern(); return m_hour_field->SetText(pattern); } BOOL OpTime::HasValue() const { #ifdef PATTERN_EDIT OpString text_val; m_hour_field->GetText(text_val); if (text_val.IsEmpty()) { return FALSE; } const uni_char* pattern = GetEditPattern(); return uni_strcmp(text_val.CStr(), pattern) != 0; #else return m_hour_field->HasValue() || m_minute_field->HasValue(); #endif // PATTERN_EDIT } BOOL OpTime::GetTime(TimeSpec& out_value) const { #ifdef PATTERN_EDIT if (!HasValue()) #else if (!m_hour_field->HasValue() || !m_minute_field->HasValue()) #endif // PATTERN_EDIT { return FALSE; } // All has values #ifdef PATTERN_EDIT OpString text_val; m_hour_field->GetText(text_val); if (!out_value.SetFromISO8601String(text_val.CStr())) { return FALSE; } switch (m_precision) { case TIME_PRECISION_MINUTES: // We have lost seconds and hundreths if (!m_last_set_full_time.IsSecondUndefined()) { out_value.m_second = m_last_set_full_time.m_second; } // fall through case TIME_PRECISION_SECONDS: // We have lost hundreths if (!m_last_set_full_time.IsFractionUndefined()) { OP_ASSERT(!m_last_set_full_time.IsSecondUndefined()); out_value.SetFraction(m_last_set_full_time.GetFraction(), m_last_set_full_time.GetFractionDigitCount()); } } return TRUE; #else int hour; int minute; if (!m_hour_field->GetIntValue(hour) || !m_minute_field->GetIntValue(minute)) { return FALSE; } if (hour < 0 || hour > 23 || minute < 0 || minute > 59) { return FALSE; } TimeSpec time_spec = { hour, minute }; out_value = time_spec; return TRUE; #endif // PATTERN_EDIT } void OpTime::SetTimePrecision(TimeFieldPrecision precision) { if (precision != m_precision) { m_precision = precision; const uni_char* pattern = GetEditPattern(); m_hour_field->SetPattern(pattern); } } void OpTime::SetMinValueInternal(BOOL enable, TimeSpec new_min) { if (enable && (!m_has_min_value || new_min.AsDouble() != m_min_value.AsDouble())) { m_has_min_value = TRUE; m_min_value = new_min; UpdateButtonState(); } else if (!enable && m_has_min_value) { m_has_min_value = FALSE; UpdateButtonState(); } // else same state - avoid triggering repaint } void OpTime::SetMaxValueInternal(BOOL enable, TimeSpec new_max) { if (enable && (!m_has_max_value || new_max.AsDouble() != m_max_value.AsDouble())) { m_has_max_value = TRUE; m_max_value = new_max; UpdateButtonState(); } else if (!enable && m_has_max_value) { m_has_max_value = FALSE; UpdateButtonState(); } // else same state - avoid triggering repaint } void OpTime::SetStepInternal(BOOL enable, TimeSpec step_base, double step_value_milliseconds) { if (enable && (!m_has_step || m_step_base.AsDouble() != step_base.AsDouble() || m_step_value_milliseconds != step_value_milliseconds)) { m_has_step = TRUE; m_step_base = step_base; m_step_value_milliseconds = step_value_milliseconds; UpdateButtonState(); // Can affect the button state if the step only allows a single date of the day } else if (!enable && m_has_step) { m_has_step = FALSE; UpdateButtonState(); // Can affect the button state if the step only allows a single date of the day } // else same state - avoid triggering repaint } void OpTime::UpdateButtonState() { BOOL is_enabled = IsEnabled() && !m_readonly; BOOL enable_up_button = is_enabled; BOOL enable_down_button = is_enabled; TimeSpec written_time; if (GetTime(written_time)) { if (m_has_max_value && !(m_has_min_value && m_min_value.IsAfter(m_max_value))) { if (!written_time.IsBefore(m_max_value)) { enable_up_button = FALSE; } } if (m_has_min_value && !(m_has_max_value && m_min_value.IsAfter(m_max_value))) { if (!written_time.IsAfter(m_min_value)) { enable_down_button = FALSE; } } if (m_has_step) { double value_number = written_time.AsDouble()*1000; BOOL wrap_around = !m_has_min_value && !m_has_max_value; double min_value = m_has_min_value ? m_min_value.AsDouble()*1000.0 : 0.0; double max_value = m_has_max_value ? m_max_value.AsDouble()*1000.0 : (wrap_around ? 86400000.0 : 86399999.0); // 23:59:59.999 double dummy_result_value; for (int direction = -1; direction <= 1; direction += 2) { OP_STATUS status = WebForms2Number::StepNumber(value_number, min_value, max_value, m_has_step ? (m_step_base.AsDouble()*1000) : value_number, m_step_value_milliseconds, direction, wrap_around, /* wrap_around */ TRUE, /* fuzzy step, be helpful. */ dummy_result_value); if (OpStatus::IsError(status)) { if (direction == -1) { enable_down_button = FALSE; } else { enable_up_button = FALSE; } } } } } m_spinner->SetDownEnabled(enable_down_button); m_spinner->SetUpEnabled(enable_up_button); } void OpTime::MinMaxAdjust(int delta, TimeSpec& unadjusted_value) const { // Correct value with respect to min and max if (delta > 0 && m_has_max_value && !(m_has_min_value && m_min_value.IsAfter(m_max_value))) { if (unadjusted_value.IsAfter(m_max_value)) { unadjusted_value = m_max_value; } } else if (delta < 0 && m_has_min_value && !(m_has_max_value && m_min_value.IsAfter(m_max_value))) { if (unadjusted_value.IsBefore(m_min_value)) { unadjusted_value = m_min_value; } } } void OpTime::OnClick(OpWidget *object, UINT32 id) { if (m_readonly) return; if (object == m_spinner) { int caret_pos = -1; int delta = id ? -1 : 1; TimeSpec written_time; if (GetTime(written_time)) { int step_value_milliseconds = m_has_step ? static_cast<int>(m_step_value_milliseconds + 0.5): 0; caret_pos = m_hour_field->GetCaretOffset(); if (step_value_milliseconds == 0 || (step_value_milliseconds < 1000 && caret_pos < 9) || (step_value_milliseconds == 60000 && caret_pos < 6) || (step_value_milliseconds == 3600000 && caret_pos < 3)) { if (caret_pos < 3) { // hour field - step an hour if (m_has_step) { int new_delta = static_cast<int>((delta * 3600000)/step_value_milliseconds + delta/2); // delta/2 to get rounding if (new_delta != 0) { OP_ASSERT(new_delta * delta > 0); // Same sign delta = new_delta; } } else { step_value_milliseconds = 3600000; } } else if (caret_pos < 6) { // minute field - step a minute if (step_value_milliseconds > 0) { int new_delta = static_cast<int>((delta * 60000)/step_value_milliseconds + delta/2); if (new_delta != 0) { OP_ASSERT(new_delta * delta > 0); // Same sign delta = new_delta; } } else { step_value_milliseconds = 60000; } } else if (caret_pos < 9) { // second field - step a second if (step_value_milliseconds > 0) { int new_delta = static_cast<int>((delta * 1000)/step_value_milliseconds + delta/2); if (new_delta != 0) { OP_ASSERT(new_delta * delta > 0); // Same sign delta = new_delta; } } else { step_value_milliseconds = 1000; } } else { // hundreths if (step_value_milliseconds == 0) { int digit_count = written_time.GetFractionDigitCount(); int precision = static_cast<int>(op_pow(10.0, digit_count)); step_value_milliseconds = 1000/precision; OP_ASSERT(step_value_milliseconds > 0); // 1, 10 or 100 } } } // Step with the step_value after making every value into the unit "milliseconds since midnight" double result_value; double value_number = written_time.AsDouble()*1000; BOOL wrap_around = !m_has_min_value && !m_has_max_value; double min_value = m_has_min_value ? m_min_value.AsDouble()*1000 : 0.0; double max_value = m_has_max_value ? m_max_value.AsDouble()*1000 : (wrap_around ? 86400000.0 : 86399999.0); // 23:59:59.999 OP_STATUS status = WebForms2Number::StepNumber(value_number, min_value, max_value, m_has_step ? (m_step_base.AsDouble()*1000) : value_number, step_value_milliseconds, delta, wrap_around, /* wrap_around */ TRUE, /* fuzzy step, be helpful. */ result_value); if (OpStatus::IsSuccess(status)) { // Now we have result value in thousands of seconds OP_ASSERT(result_value >= 0.0); int int_result = static_cast<int>(result_value + 0.5); if (int_result >= 86400000) { int_result = wrap_around ? 0 : 86399999; } written_time.m_hour = int_result / 3600000; int_result -= written_time.m_hour * 3600000; written_time.m_minute = int_result / 60000; int_result -= written_time.m_minute * 60000; if (written_time.m_second != -1 || int_result > 0) { written_time.m_second = int_result / 1000; int_result -= written_time.m_second*1000; if (int_result > 0 || written_time.GetFractionDigitCount() > 0) { if (int_result == 0) { written_time.SetFraction(0, 0); } else if ((int_result/100) * 100 == int_result) { written_time.SetFraction(int_result/100, 1); } else if ((int_result/10) * 10 == int_result) { written_time.SetFraction(int_result/10, 2); } else { written_time.SetFraction(int_result, 3); } } } } } else { // No current time, start with 00:00:00.000 written_time.m_hour = 0; written_time.m_minute = 0; written_time.m_second = 0; written_time.SetFraction(0, 3); MinMaxAdjust(delta, written_time); } OP_STATUS status = SetValue(written_time); #ifdef _DEBUG OP_ASSERT(OpStatus::IsSuccess(status)); #else OpStatus::Ignore(status); #endif // _DEBUG if (caret_pos != -1) { // Set back caret where it was so next spinner action affects the same unit as this time. m_hour_field->SetCaretOffset(caret_pos); } if (listener) { listener->OnChange(this); } } } void OpTime::SetEnabled(BOOL enabled) { OpWidget::SetEnabled(enabled); UpdateButtonState(); } /** *********************************************************************** ** ** OnInputAction ** ************************************************************************ */ BOOL OpTime::OnInputAction(OpInputAction* action) { #if defined OP_KEY_DOWN_ENABLED && defined OP_KEY_UP_ENABLED && defined OP_KEY_LEFT_ENABLED && defined OP_KEY_RIGHT_ENABLED if (action->GetAction() == OpInputAction::ACTION_LOWLEVEL_PREFILTER_ACTION && action->GetChildAction()->GetAction() == OpInputAction::ACTION_LOWLEVEL_KEY_PRESSED) { OpKey::Code key = action->GetChildAction()->GetActionKeyCode(); switch (key) { case OP_KEY_UP: case OP_KEY_DOWN: // Simulate click on the up or down button OnClick(m_spinner, key == OP_KEY_DOWN ? 1 : 0); return TRUE; } } #endif // defined OP_KEY_DOWN_ENABLED && defined OP_KEY_UP_ENABLED && defined OP_KEY_LEFT_ENABLED && defined OP_KEY_RIGHT_ENABLED return FALSE; }
#ifndef MATH_IS_ODD_HPP #define MATH_IS_ODD_HPP namespace Math { static bool isOdd(int num) { return num & 1; } } // namespace Math #endif /* end of include guard : MATH_IS_ODD_HPP */
#pragma once #include "Manager.h" namespace m2 { namespace server { class RegisterManager: public Manager { struct userInfo { uuids::uuid fingerprint; std::string clientPublicKey; }; public: RegisterManager(Database *db); virtual HttpResponse::Code doAction(const std::string &data, std::string &response) final; public: static const ResponseType m_response_type = ResponseType::Register; private: StringsPair deserialize(const std::string &data); response_result createResponse (const StringsPair &pair, userInfo &result); }; } }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 1995-2010 Opera Software AS. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. */ #ifndef OP_SCOPE_DOCUMENT_LISTENER_H #define OP_SCOPE_DOCUMENT_LISTENER_H #if defined(SCOPE_DOCUMENT_MANAGER) || defined(SCOPE_PROFILER) #include "modules/dochand/docman.h" class OpScopeDocumentListener { public: /** * Arguments for OnAboutToLoadDocument. The contents copy the parameters * of DocumentManager::OpenURL. */ struct AboutToLoadDocumentArgs { DocumentManager::OpenURLOptions options; URL_Rep *url; URL_Rep *referrer_url; BOOL check_if_expired; BOOL reload; }; // AboutToLoadDocumentArgs /** * Check if document listener is enabled. If it isn't, the caller * does not need to send events. * * @return TRUE if enabled, FALSE if disabled. */ static BOOL IsEnabled(); /** * Call this when a document is about to be loaded. (Not when it * has finished loading). * * @param docman The DocumentManager that is about to be loaded. * @param args Arguments to DocumentManager::OpenURL. See OnLoadDocumentArgs. */ static OP_STATUS OnAboutToLoadDocument(DocumentManager *docman, const AboutToLoadDocumentArgs &args); }; // OpScopeDocumentListener #endif // SCOPE_DOCUMENT_MANAGER || SCOPE_PROFILER #endif // OP_SCOPE_DOCUMENT_LISTENER_H
// Ed Callaghan // Constructs plots of energies against time - plot using drawAll.cxx // April 2016 TGraph *gSingleChannel(int ich) { double HR_PER_SEC = 1.0/3600.0 ; TChain *dataTree = new TChain("tree") ; dataTree->Add("../filling_pulser.root") ; double file_start_time, first_event_time ; dataTree->SetBranchAddress("file_start_timeDouble", &file_start_time) ; dataTree->SetBranchAddress("first_event_time", &first_event_time) ; double energy[10] ; dataTree->SetBranchAddress("energy1_pz", &energy) ; double time ; dataTree->SetBranchAddress("timestampDouble", &time) ; TGraph *gEnergy = new TGraph() ; int ipt = 0 ; int nEntries = dataTree->GetEntries() ; cout << nEntries << '\n' ; double timeStart ; dataTree->GetEntry(0) ; time = file_start_time - first_event_time + time*40/1e9 ; timeStart = -time ; for (int iEntry = 0 ; iEntry < nEntries ; iEntry++) { dataTree->GetEntry(iEntry) ; time = file_start_time - first_event_time + time*40/1e9 ; time += timeStart ; time *= HR_PER_SEC ; gEnergy->SetPoint(ipt, time, energy[ich]) ; ipt++ ; } delete dataTree ; return gEnergy ; } TGraph *gXeMass() { double HR_PER_SEC = 1.0/3600.0 ; TChain *slowTree = new TChain("tree") ; slowTree->Add("../test_20160307_075550.root") ; double slowtime, mXe ; slowTree->SetBranchAddress("timeStamp", &slowtime) ; slowTree->SetBranchAddress("massXe", &mXe) ; TGraph *gXe = new TGraph() ; int iptXe = 0 ; int nEntries = slowTree->GetEntries() ; cout << nEntries << '\n' ; double slowStart = 1457366150.0 ; // 20160307_075550 in POSIX double mXeStart ; slowTree->GetEntry(0) ; slowStart = 0.0 ; // FIXME should this be? slowStart -= slowtime ; mXeStart = mXe ; for (int iEntry = 0 ; iEntry < nEntries ; iEntry++) { slowTree->GetEntry(iEntry) ; slowtime += slowStart ; slowtime *= HR_PER_SEC ; mXe = mXeStart - mXe ; // if (time < slowtime) // only during filling // continue ; gXe->SetPoint(iptXe, slowtime, mXe) ; iptXe++ ; } delete slowTree ; return gXe ; } TGraph *gCapacitance() { double HR_PER_SEC = 1.0/3600.0 ; TChain *slowTree = new TChain("tree") ; slowTree->Add("../test_20160307_075550.root") ; double slowtime, ca ; slowTree->SetBranchAddress("timeStamp", &slowtime) ; slowTree->SetBranchAddress("capacitance", &ca) ; TGraph *gCa = new TGraph() ; int iptCa = 0 ; int nEntries = slowTree->GetEntries() ; cout << nEntries << '\n' ; double slowStart = 1457366150.0 ; // 20160307_075550 in POSIX double mXeStart ; slowTree->GetEntry(0) ; slowStart = 0.0 ; // FIXME should this be? slowStart -= slowtime ; for (int iEntry = 0 ; iEntry < nEntries ; iEntry++) { slowTree->GetEntry(iEntry) ; slowtime += slowStart ; slowtime *= HR_PER_SEC ; // if (time < slowtime) // only during filling // continue ; gCa->SetPoint(iptCa, slowtime, ca) ; iptCa++ ; } delete slowTree ; return gCa ; } TGraph *gChargeEnergy() { double HR_PER_SEC = 1.0/3600.0 ; TChain *dataTree = new TChain("tree") ; dataTree->Add("../filling_pulser.root") ; double file_start_time, first_event_time ; dataTree->SetBranchAddress("file_start_timeDouble", &file_start_time) ; dataTree->SetBranchAddress("first_event_time", &first_event_time) ; double energy ; dataTree->SetBranchAddress("chargeEnergy", &energy) ; double time ; dataTree->SetBranchAddress("timestampDouble", &time) ; TGraph *gEnergy = new TGraph() ; int ipt = 0 ; int nEntries = dataTree->GetEntries() ; cout << nEntries << '\n' ; double timeStart ; dataTree->GetEntry(0) ; time = file_start_time - first_event_time + time*40/1e9 ; timeStart = -time ; for (int iEntry = 0 ; iEntry < nEntries ; iEntry++) { dataTree->GetEntry(iEntry) ; time = file_start_time - first_event_time + time*40/1e9 ; time += timeStart ; time *= HR_PER_SEC ; gEnergy->SetPoint(ipt, time, energy) ; ipt++ ; } delete dataTree ; return gEnergy ; } void configureChYaxis(TGraph *g) { double x, y ; double mean, mean_old, stdv, stdv_old ; g->GetPoint(0, x, mean_old) ; stdv_old = 0.0 ; int npts = g->GetN() ; for (int ipt = 1 ; ipt < npts ; ipt++) { g->GetPoint(ipt, x, y) ; mean = mean_old + (y - mean_old)/(ipt + 1) ; stdv = stdv_old + (y - mean)*(y - mean_old) ; } stdv = pow(stdv/npts, 1.0/2.0) ; g->GetYaxis()->SetRangeUser(mean - 10.0*stdv, mean + 70.0*stdv) ; } void singleChannelFilling() { const int nch = 8 ; TCanvas *c = new TCanvas() ; TPad *chPad = new TPad("chPad", "", 0, 0, 1, 1) ; chPad->Draw() ; TPad *xePad = new TPad("xePad", "", 0, 0, 1, 1) ; xePad->Draw() ; xePad->SetFillStyle(4000) ; xePad->SetFillColor(0) ; xePad->SetFrameFillStyle(4000) ; TPad *caPad = new TPad("caPad", "", 0, 0, 1, 1) ; caPad->Draw() ; caPad->SetFillStyle(4000) ; caPad->SetFillColor(0) ; caPad->SetFrameFillStyle(4000) ; cout << "Building xenon plot... " ; TGraph *gXe = gXeMass() ; gXe->GetXaxis()->SetTitle("hours from 03/07/2016 07:55:50") ; gXe->GetXaxis()->SetRangeUser(0.0, 3.5) ; // gXe->GetYaxis()->SetTitle("mass Xe in cell [kg]") ; gXe->GetXaxis()->SetLabelSize(0.0) ; gXe->GetXaxis()->SetTickSize(0.0) ; gXe->GetYaxis()->SetRangeUser(-0.1, 6.5) ; gXe->GetYaxis()->SetAxisColor(6) ; gXe->GetYaxis()->SetLabelColor(6) ; gXe->GetYaxis()->SetTitleColor(6) ; gXe->SetMarkerColor(6) ; // purple cout << "Building capacitance plot... " ; TGraph *gCa = gCapacitance() ; gCa->GetXaxis()->SetTitle("hours from 03/07/2016 07:55:50") ; gCa->GetXaxis()->SetRangeUser(0.0, 3.5) ; // gCa->GetYaxis()->SetTitle("capacitance [a.u.]") ; gCa->GetXaxis()->SetLabelSize(0.0) ; gCa->GetXaxis()->SetTickSize(0.0) ; gCa->GetYaxis()->SetLabelSize(0.0) ; gCa->GetYaxis()->SetTickSize(0.0) ; gCa->GetYaxis()->SetRangeUser(31.5, 34.5) ; // gCa->GetYaxis()->SetAxisColor(3) ; // gCa->GetYaxis()->SetLabelColor(3) ; // gCa->GetYaxis()->SetTitleColor(3) ; gCa->SetMarkerColor(3) ; // green cout << "Building total charge plot... " ; TGraph *gCharge = gChargeEnergy() ; gCharge->SetTitle("Total Charge Energy - Filling") ; gCharge->GetXaxis()->SetRangeUser(0.0, 3.5) ; gCharge->GetYaxis()->SetTitle("total charge energy") ; configureChYaxis(gCharge) ; gCharge->GetYaxis()->SetTitleOffset(1.5) ; char title[100] ; TGraph *gChs[nch] ; for (int ich = 0 ; ich < nch ; ich++) { cout << "Building channel " << ich << "... " ; gChs[ich] = gSingleChannel(ich) ; sprintf(title, "Channel %d Charge Energy - Filling", ich) ; gChs[ich]->SetTitle(title) ; gChs[ich]->GetXaxis()->SetRangeUser(0.0, 3.5) ; gChs[ich]->GetYaxis()->SetTitle("energy1_pz") ; configureChYaxis(gChs[ich]) ; gChs[ich]->GetYaxis()->SetTitleOffset(1.5) ; } TFile *fout = new TFile("singlePlots.root", "RECREATE") ; chPad->cd() ; chPad->Clear() ; gCharge->Draw("ap") ; xePad->cd() ; xePad->Clear() ; gXe->Draw("apY+") ; caPad->cd() ; caPad->Clear() ; gCa->Draw("apY+") ; c->SetName("totalChargeEnergy") ; c->Write() ; char cname[15] ; for (int ich = 0 ; ich < nch ; ich++) { cout << "Drawing channel " << ich << "...\n" ; chPad->cd() ; chPad->Clear() ; // gChs[ich]->GetYaxis()->SetRangeUser(5000.0, 14000.0) ; gChs[ich]->Draw("ap") ; xePad->cd() ; xePad->Clear() ; gXe->Draw("apY+") ; caPad->cd() ; caPad->Clear() ; gCa->Draw("apY+") ; sprintf(cname, "timePlot_%d", ich) ; c->SetName(cname) ; c->Write() ; } delete fout ; delete gCa ; delete gXe ; delete gCharge ; for (int ich = 0 ; ich < nch ; ich++) delete gChs[ich] ; }
// One Arduino Leonardo has 2 motor drivers connected, each is driving 2 motors, so together 4 motors // Note: if motors is close to supplied with 100% of 24V i.e. PWM is 255, than even if we stop motor, a few sensor impulses could be produced, it can be max 1,2 for super power jack, but for smaller one it could be up to 5, but for the sake of simplicity, we are not counting them #include "consts.h" #include "utils.h" typedef struct{ bool moving; bool blocked; volatile unsigned long currentImpulses; unsigned long targetImpulses; byte speed; byte command; byte currentMotorON; }Status; Status state = {false, false, 0, 0, 0, 0, NO_MOTOR}; boolean enableInterrupts = false; // we need a special variable, because calling attachInterrupt causes immediate interrupt // the setup function runs once when you press reset or power the board void setup() { Serial.begin(9600); while (!Serial) { ; // wait for serial port to connect. Needed for Leonardo only } // enable D2 - required for drivers to work pinMode(DRIVER1_D2_PIN, OUTPUT); digitalWrite(DRIVER1_D2_PIN, HIGH); pinMode(DRIVER2_D2_PIN, OUTPUT); digitalWrite(DRIVER2_D2_PIN, HIGH); pinMode(MOTOR1_DIRECTION_PIN, OUTPUT); pinMode(MOTOR1_SPEED_PIN, OUTPUT); analogWrite(MOTOR1_SPEED_PIN, 0); digitalWrite(MOTOR1_SENSOR_PIN, HIGH); pinMode(MOTOR2_DIRECTION_PIN, OUTPUT); pinMode(MOTOR2_SPEED_PIN, OUTPUT); analogWrite(MOTOR2_SPEED_PIN, 0); digitalWrite(MOTOR2_SENSOR_PIN, HIGH); pinMode(MOTOR3_DIRECTION_PIN, OUTPUT); pinMode(MOTOR3_SPEED_PIN, OUTPUT); analogWrite(MOTOR3_SPEED_PIN, 0); pinMode(MOTOR3_SENSOR_PIN, INPUT_PULLUP); pinMode(MOTOR4_DIRECTION_PIN, OUTPUT); pinMode(MOTOR4_SPEED_PIN, OUTPUT); analogWrite(MOTOR4_SPEED_PIN, 0); pinMode(MOTOR4_SENSOR_PIN, INPUT_PULLUP); attachInterrupt(mapInterrupt(MOTOR1_SENSOR_PIN), interrupt_handler1, RISING); attachInterrupt(mapInterrupt(MOTOR2_SENSOR_PIN), interrupt_handler2, RISING); enableInterrupts = true; } // the loop function runs over and over again forever void loop() { readSerialForInput(); switch (state.command) { case 1: disableMotors(); break; case 2: enableMotors(); break; case 10: goForwardSmallMotor1(); reset(); break; case 11: goBackSmallMotor1(); reset(); break; case 30: goForwardBigMotor1(); reset(); break; case 31: goBackBigMotor1(); reset(); break; case 40: goForwardBigMotor2(); reset(); break; case 41: goBackBigMotor2(); reset(); break; } delay(SERIAL_INPUT_DELAY); // TODO: make as constant } void goForwardSmallMotor1() { if (state.moving == false && state.blocked == false){ state.currentMotorON = MOTOR1; digitalWrite(MOTOR1_DIRECTION_PIN, LOW); analogWrite(MOTOR1_SPEED_PIN, state.speed); state.moving = true; checkProgress(MOTOR1_SPEED_PIN); } else{ Serial.println("eRejecting command, motor is moving or blocked"); } } void goBackSmallMotor1() { if (state.moving == false && state.blocked == false){ state.currentMotorON = MOTOR1; digitalWrite(MOTOR1_DIRECTION_PIN, HIGH); analogWrite(MOTOR1_SPEED_PIN, state.speed); state.moving = true; checkProgress(MOTOR1_SPEED_PIN); }else{ Serial.println("eRejecting command, motor is moving or blocked"); } } void goForwardSmallMotor2() { if (state.moving == false && state.blocked == false){ state.currentMotorON = MOTOR2; digitalWrite(MOTOR2_DIRECTION_PIN, LOW); analogWrite(MOTOR2_SPEED_PIN, state.speed); state.moving = true; checkProgress(MOTOR2_SPEED_PIN); }else{ Serial.println("eRejecting command, motor is moving or blocked"); } } void goBackSmallMotor2() { if (state.moving == false && state.blocked == false){ state.currentMotorON = MOTOR2; digitalWrite(MOTOR2_DIRECTION_PIN, HIGH); analogWrite(MOTOR2_SPEED_PIN, state.speed); state.moving = true; checkProgress(MOTOR2_SPEED_PIN); }else{ Serial.println("eRejecting command, motor is moving or blocked"); } } void checkProgress(byte speedPIN) { int before; int after; while (state.currentImpulses < state.targetImpulses) { before = state.currentImpulses; delay(SENSOR1_TIMEOUT); if (before == state.currentImpulses && state.currentImpulses < state.targetImpulses) { Serial.println("eMotor stopped not reaching target"); stopMotor(speedPIN); break; } } } void interrupt_handler1() { if (enableInterrupts && state.currentMotorON == MOTOR1) { //we are counting only impluses from the sensor of motor 1 state.currentImpulses++; Serial.print("i"); Serial.println(state.currentImpulses, DEC); if (state.currentImpulses >= state.targetImpulses) { stopMotor(MOTOR1_SPEED_PIN); } } } void interrupt_handler2() { if (enableInterrupts && state.currentMotorON == MOTOR2) { //we are counting only impluses from the sensor of motor 2 state.currentImpulses++; Serial.print("i"); Serial.println(state.currentImpulses, DEC); if (state.currentImpulses >= state.targetImpulses) { stopMotor(MOTOR2_SPEED_PIN); } } } void readSerialForInput() { state.command = getCommand(); int param1 = 0; if (state.command > 9) { while (param1 == 0) { param1 = getParam1(); delay(1); } int param2 = 0; while (param2 == 0) { param2 = getParam2(); delay(1); } state.speed = param1; state.targetImpulses = param2; Serial.print("mCommand: "); Serial.print(state.command); Serial.print(" Param1: "); Serial.print(param1); Serial.print(" Param2: "); Serial.println(param2); } } byte getCommand() { if (Serial.available() > 0) { return Serial.read(); } else { return 0; } } byte getParam1() { if (Serial.available() > 0) { return Serial.read(); } else { return 0; } } unsigned long getParam2() { if (Serial.available() > 3) { return readULongFromBytes(); } else { return 0; } } void disableMotors() { state.moving = false; state.blocked = true; state.currentMotorON = NO_MOTOR; digitalWrite(DRIVER1_D2_PIN, LOW); digitalWrite(DRIVER2_D2_PIN, LOW); Serial.println("mSTOP"); } void enableMotors() { reset(); } void doWork(byte sensorPIN) { int value; boolean logicalValue = false; boolean previousLogicalValue = false; unsigned long previousTime = millis(); while (state.currentImpulses < state.targetImpulses) { value = analogRead(sensorPIN); previousLogicalValue = logicalValue; if (value > CUSTOM_HIGH) { logicalValue = true; } if (value < CUSTOM_LOW) { logicalValue = false; } if ((logicalValue == false) && (previousLogicalValue == true)) { previousTime = millis(); state.currentImpulses++; Serial.print("i"); Serial.println(state.currentImpulses, DEC); } else if ((millis() - previousTime) > SENSOR2_TIMEOUT) { // no signal change last SENSOR2_TIMEOUT msec Serial.println("eMotor stopped not reaching target"); break; } delay(SENSOR2_READ_FREQ); } } void goForwardBigMotor1() { if (state.moving == false && state.blocked == false){ state.currentMotorON = MOTOR3; digitalWrite(MOTOR3_DIRECTION_PIN, HIGH); analogWrite(MOTOR3_SPEED_PIN, state.speed); doWork(MOTOR3_SENSOR_PIN); stopMotor(MOTOR3_SPEED_PIN); }else{ Serial.println("eRejecting command, motor is moving or blocked"); } } void goBackBigMotor1() { if (state.moving == false && state.blocked == false){ state.currentMotorON = MOTOR3; digitalWrite(MOTOR3_DIRECTION_PIN, LOW); analogWrite(MOTOR3_SPEED_PIN, state.speed); doWork(MOTOR3_SENSOR_PIN); stopMotor(MOTOR3_SPEED_PIN); }else{ Serial.println("eRejecting command, motor is moving or blocked"); } } void goForwardBigMotor2() { if (state.moving == false && state.blocked == false){ state.currentMotorON = MOTOR4; digitalWrite(MOTOR4_DIRECTION_PIN, HIGH); analogWrite(MOTOR4_SPEED_PIN, state.speed); doWork(MOTOR4_SENSOR_PIN); stopMotor(MOTOR4_SPEED_PIN); }else{ Serial.println("eRejecting command, motor is moving or blocked"); } } void goBackBigMotor2() { if (state.moving == false && state.blocked == false){ state.currentMotorON = MOTOR4; digitalWrite(MOTOR4_DIRECTION_PIN, LOW); analogWrite(MOTOR4_SPEED_PIN, state.speed); doWork(MOTOR4_SENSOR_PIN); stopMotor(MOTOR4_SPEED_PIN); }else{ Serial.println("eRejecting command, motor is moving or blocked"); } } inline void stopMotor(byte motorSpeedPin) { state.moving = false; state.currentMotorON = 0; analogWrite(motorSpeedPin, 0); Serial.println("mSTOP"); } inline void reset() { // sets variables to the default state, also stops all motors by setting speed to 0 state = {false, false, 0, 0, 0, 0, 0}; digitalWrite(DRIVER1_D2_PIN, HIGH); digitalWrite(DRIVER2_D2_PIN, HIGH); analogWrite(MOTOR1_SPEED_PIN, 0); digitalWrite(MOTOR1_SENSOR_PIN, HIGH); analogWrite(MOTOR2_SPEED_PIN, 0); digitalWrite(MOTOR2_SENSOR_PIN, HIGH); analogWrite(MOTOR3_SPEED_PIN, 0); analogWrite(MOTOR4_SPEED_PIN, 0); }
/** * 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. * * @file injector.bind.hh */ #ifndef lnav_injector_bind_hh #define lnav_injector_bind_hh #include "injector.hh" namespace injector { namespace details { template<typename I, typename R, typename... Args> std::function<std::shared_ptr<I>()> create_factory(R (*)(Args...)) { return []() { return std::make_shared<I>(::injector::get<Args>()...); }; } template<typename I, std::enable_if_t<has_injectable<I>::value, bool> = true> std::function<std::shared_ptr<I>()> create_factory() { typename I::injectable* i = nullptr; return create_factory<I>(i); } template<typename I, std::enable_if_t<!has_injectable<I>::value, bool> = true> std::function<std::shared_ptr<I>()> create_factory() noexcept { return []() { return std::make_shared<I>(); }; } } // namespace details template<typename T, typename... Annotations> struct bind : singleton_storage<T, Annotations...> { template<typename I = T, std::enable_if_t<has_injectable<I>::value, bool> = true> static bool to_singleton() noexcept { typename I::injectable* i = nullptr; singleton_storage<T, Annotations...>::ss_owner = create_from_injectable<I>(i)(); singleton_storage<T, Annotations...>::ss_data = singleton_storage<T, Annotations...>::ss_owner.get(); singleton_storage<T, Annotations...>::ss_scope = scope::singleton; return true; } template<typename I = T, std::enable_if_t<!has_injectable<I>::value, bool> = true> static bool to_singleton() noexcept { singleton_storage<T, Annotations...>::ss_owner = std::make_shared<T>(); singleton_storage<T, Annotations...>::ss_data = singleton_storage<T, Annotations...>::ss_owner.get(); singleton_storage<T, Annotations...>::ss_scope = scope::singleton; return true; } struct lifetime { ~lifetime() { singleton_storage<T, Annotations...>::ss_owner = nullptr; singleton_storage<T, Annotations...>::ss_data = nullptr; } }; template<typename I = T, std::enable_if_t<has_injectable<I>::value, bool> = true> static lifetime to_scoped_singleton() noexcept { typename I::injectable* i = nullptr; singleton_storage<T, Annotations...>::ss_owner = create_from_injectable<I>(i)(); singleton_storage<T, Annotations...>::ss_data = singleton_storage<T, Annotations...>::ss_owner.get(); singleton_storage<T, Annotations...>::ss_scope = scope::singleton; return {}; } template<typename... Args> static bool to_instance(T* (*f)(Args...)) noexcept { singleton_storage<T, Annotations...>::ss_data = f(::injector::get<Args>()...); singleton_storage<T, Annotations...>::ss_scope = scope::singleton; return true; } static bool to_instance(T* data) noexcept { singleton_storage<T, Annotations...>::ss_data = data; singleton_storage<T, Annotations...>::ss_scope = scope::singleton; return true; } template<typename I> static bool to() noexcept { singleton_storage<T, Annotations...>::ss_factory = details::create_factory<I>(); singleton_storage<T, Annotations...>::ss_scope = scope::none; return true; } }; template<typename T> struct bind_multiple : multiple_storage<T> { bind_multiple() noexcept = default; template<typename I> bind_multiple& add() noexcept { multiple_storage<T>::get_factories()[typeid(I).name()] = details::create_factory<I>(); return *this; } template<typename I, typename... Annotations> bind_multiple& add_singleton() noexcept { auto factory = details::create_factory<I>(); auto single = factory(); if (sizeof...(Annotations) > 0) { bind<T, Annotations...>::to_instance(single.get()); } bind<I, Annotations...>::to_instance(single.get()); multiple_storage<T>::get_factories()[typeid(I).name()] = [single]() { return single; }; return *this; } }; } // namespace injector #endif
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 1995-2006 Opera Software AS. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. ** */ #include "core/pch.h" #include "modules/forms/formvaluecolor.h" #include "modules/forms/piforms.h" #include "modules/logdoc/htm_elm.h" #include "modules/logdoc/htm_lex.h" #include "modules/logdoc/logdoc_util.h" /* static */ OP_STATUS FormValueColor::ConstructFormValueColor(HTML_Element* he, FormValue*& out_value) { OP_ASSERT(he->Type() == HE_INPUT); FormValueColor *color_value = OP_NEW(FormValueColor, ()); if (!color_value) { return OpStatus::ERR_NO_MEMORY; } const uni_char* html_value = he->GetStringAttr(ATTR_VALUE); if (html_value) { OP_STATUS status = color_value->SetValueFromText(he, html_value); if (OpStatus::IsMemoryError(status)) { OP_DELETE(color_value); return status; } } out_value = color_value; return OpStatus::OK; } /* virtual */ FormValue* FormValueColor::Clone(HTML_Element *he) { FormValueColor* clone = OP_NEW(FormValueColor, ()); if (clone) { if (he && IsValueExternally()) { m_color = GetWidgetColor(he->GetFormObject()); } clone->m_color = m_color; OP_ASSERT(!clone->IsValueExternally()); } return clone; } /* virtual */ OP_STATUS FormValueColor::GetValueAsText(HTML_Element* he, OpString& out_value) const { COLORREF color = m_color; if (IsValueExternally()) { color = GetWidgetColor(he->GetFormObject()); } if (!out_value.Reserve(10)) { return OpStatus::ERR_NO_MEMORY; } HTM_Lex::GetRGBStringFromVal(color, out_value.CStr(), TRUE); return OpStatus::OK; } static COLORREF ParseSimpleColor(const uni_char* value) { if (value) { while (IsHTML5Space(*value)) { value++; } size_t len = uni_strlen(value); while (len > 0 && IsHTML5Space(value[len-1])) { len--; } BOOL valid = len == 7 && value[0] == '#'; if (valid) { int r = HexToInt(value + 1, 2, TRUE); int g = HexToInt(value + 3, 2, TRUE); int b = HexToInt(value + 5, 2, TRUE); if (r != -1 && g != -1 && b != -1) { return OP_RGB(r, g, b); } } } // Fallback to #000000. return OP_RGB(0, 0, 0); } /* virtual */ OP_STATUS FormValueColor::SetValueFromText(HTML_Element* he, const uni_char* in_value) { m_color = ParseSimpleColor(in_value); if (IsValueExternally()) { SetWidgetColor(he->GetFormObject(), m_color); } return OpStatus::OK; } /* virtual */ OP_STATUS FormValueColor::ResetToDefault(HTML_Element* he) { OP_ASSERT(he->GetFormValue() == this); ResetChangedFromOriginal(); const uni_char* default_value = he->GetStringAttr(ATTR_VALUE); return SetValueFromText(he, default_value); } /* virtual */ BOOL FormValueColor::Externalize(FormObject* form_object_to_seed) { if (!FormValue::Externalize(form_object_to_seed)) { return FALSE; // It was wrong to call Externalize } OpStatus::Ignore(SetWidgetColor(form_object_to_seed, m_color)); return TRUE; } /* virtual */ void FormValueColor::Unexternalize(FormObject* form_object_to_replace) { if (IsValueExternally()) { m_color = GetWidgetColor(form_object_to_replace); FormValue::Unexternalize(form_object_to_replace); } } /* static */ OP_STATUS FormValueColor::SetWidgetColor(FormObject* form_object, COLORREF color) { OP_ASSERT(OP_GET_A_VALUE(color) == 255 || !"Will generate the wrong string that might not fit the buffer"); uni_char color_string[8]; // ARRAY OK bratell 2010-01-03. HTM_Lex::GetRGBStringFromVal(color, color_string, TRUE); return form_object->SetFormWidgetValue(color_string); } /* static */ COLORREF FormValueColor::GetWidgetColor(FormObject* form_object) { OpString val_as_text; OP_STATUS status = form_object->GetFormWidgetValue(val_as_text); if (OpStatus::IsSuccess(status)) { return ParseSimpleColor(val_as_text.CStr()); } return OP_RGB(0, 0, 0); }
#include<bits/stdc++.h> using namespace std; bool flag=false; int mp[5][5]; int main(){ for(int i=0;i<4;i++){ for(int j=0;j<4;j++) cin>>mp[i][j]; } if(mp[0][3]==1){ for(int i=0;i<3;i++) if(mp[0][i]==1) flag=true; if(mp[3][2]==1||mp[1][0]==1||mp[2][1]==1) flag=true; } if(mp[1][3]==1){ for(int i=0;i<3;i++) if(mp[1][i]==1) flag=true; if(mp[0][2]==1||mp[2][0]==1||mp[3][1]==1) flag=true; } if(mp[2][3]==1){ for(int i=0;i<3;i++) if(mp[2][i]==1) flag=true; if(mp[1][2]==1||mp[3][0]==1||mp[0][1]==1) flag=true; } if(mp[3][3]==1){ for(int i=0;i<3;i++) if(mp[3][i]==1) flag=true; if(mp[2][2]==1||mp[0][0]==1||mp[1][1]==1) flag=true; } if(flag==true) cout<<"YES\n"; else cout<<"NO\n"; return 0; }
/**************************************************************************** * * * Author : lukasz.iwaszkiewicz@gmail.com * * ~~~~~~~~ * * License : see COPYING file for details. * * ~~~~~~~~~ * ****************************************************************************/ #include <Platform.h> #include <errno.h> #include <time.h> #include <android/log.h> #include <util/Exceptions.h> #include <android_native_app_glue.h> #include <common/dataSource/DataSource.h> namespace U = Util; /****************************************************************************/ uint32_t getCurrentMs () { timespec ts; if (clock_gettime (CLOCK_MONOTONIC, &ts) == -1) { throw U::RuntimeException ("clock_gettime (CLOCK_MONOTONIC) failed"); } return ts.tv_sec * 1000 + ts.tv_nsec / 1000000.0; } /****************************************************************************/ void delayMs (uint32_t ms) { timespec req, res; req.tv_sec = ms / 1000; req.tv_nsec = (ms % 1000) * 1000000; if (nanosleep (&req, &res) == -1) { throw U::RuntimeException ("nanosleep (&req, &res) failed"); } } /****************************************************************************/ int printlogImpl (const char *format, ...) { va_list args; va_start(args, format); int ret = __android_log_vprint (ANDROID_LOG_INFO, "bajka", format, args); va_end(args); return ret; } /****************************************************************************/ android_app *androidAppInternal (android_app *a) { static android_app *app = NULL; if (a) { app = a; } return app; } /****************************************************************************/ Common::DataSource *newDataSource () { android_app *app = androidAppInternal (NULL); return new Common::DataSource (app->activity->assetManager); } /****************************************************************************/ void deleteDataSource (Common::DataSource *ds) { delete ds; } /****************************************************************************/ void quit () { printlog ("Quit request by user"); android_app *app = androidAppInternal (NULL); ANativeActivity_finish(app->activity); }
// Copyright 2011 Yandex #include "ltr/scorers/linear_scorer.h" #include <boost/lexical_cast.hpp> #include <string> #include <sstream> #include "logog/logog.h" using std::string; using boost::lexical_cast; namespace ltr { string LinearScorer::toString() const { std::stringstream str; std::fixed(str); str.precision(2); str << "Linear scorer with coefficients: ["; for (size_t i = 0; i < weights.size(); ++i) { if (i != 0) { str << ", "; } str << weights[i]; } str << "]"; return str.str(); } double LinearScorer::scoreImpl(const Object& obj) const { double output = weights[0]; for (int i = 0; i < (int)obj.features().size(); ++i) { output += obj[i] * weights[i + 1]; } return output; } string LinearScorer::generateCppCodeImpl(const string& function_name) const { string code; code.append("double " + function_name + "(const std::vector<double>& features) {\n"). append("\tdouble output = " + lexical_cast<string>(weights[0]) + ";\n"); for (int i = 1; i < (int)weights.size(); ++i) { code.append("\toutput += " + lexical_cast<string>(weights[i]) + " * features[" + lexical_cast<string>(i - 1) +"];\n"); } code.append("\treturn output;\n"). append("}\n"); return code; } };
#ifndef FABRIC_GLOBAL_PORT_INFO_UTILS_H #define FABRIC_GLOBAL_PORT_INFO_UTILS_H /******************************************************************** * Include header files that are required by function declaration *******************************************************************/ #include <vector> #include "fabric_global_port_info.h" /******************************************************************** * Function declaration *******************************************************************/ /* begin namespace openfpga */ namespace openfpga { std::vector<FabricGlobalPortId> find_fabric_global_programming_reset_ports(const FabricGlobalPortInfo& fabric_global_port_info); std::vector<FabricGlobalPortId> find_fabric_global_programming_set_ports(const FabricGlobalPortInfo& fabric_global_port_info); } /* end namespace openfpga */ #endif
/** * Created by K. Suwatchai (Mobizt) * * Email: k_suwatchai@hotmail.com * * Github: https://github.com/mobizt/Firebase-ESP8266 * * Copyright (c) 2023 mobizt * */ /** This example will show how to authenticate using * the legacy token or database secret with the new APIs (using config and auth data). */ #include <Arduino.h> #if defined(ESP32) #include <WiFi.h> #include <FirebaseESP32.h> #elif defined(ESP8266) #include <ESP8266WiFi.h> #include <FirebaseESP8266.h> #elif defined(ARDUINO_RASPBERRY_PI_PICO_W) #include <WiFi.h> #include <FirebaseESP8266.h> #endif // Provide the RTDB payload printing info and other helper functions. #include <addons/RTDBHelper.h> /* 1. Define the WiFi credentials */ #define WIFI_SSID "WIFI_AP" #define WIFI_PASSWORD "WIFI_PASSWORD" /* 2. If work with RTDB, define the RTDB URL and database secret */ #define DATABASE_URL "URL" //<databaseName>.firebaseio.com or <databaseName>.<region>.firebasedatabase.app #define DATABASE_SECRET "DATABASE_SECRET" /* 3. Define the Firebase Data object */ FirebaseData fbdo; /* 4, Define the FirebaseAuth data for authentication data */ FirebaseAuth auth; /* Define the FirebaseConfig data for config data */ FirebaseConfig config; unsigned long dataMillis = 0; int count = 0; #if defined(ARDUINO_RASPBERRY_PI_PICO_W) WiFiMulti multi; #endif void setup() { Serial.begin(115200); #if defined(ARDUINO_RASPBERRY_PI_PICO_W) multi.addAP(WIFI_SSID, WIFI_PASSWORD); multi.run(); #else WiFi.begin(WIFI_SSID, WIFI_PASSWORD); #endif Serial.print("Connecting to Wi-Fi"); unsigned long ms = millis(); while (WiFi.status() != WL_CONNECTED) { Serial.print("."); delay(300); #if defined(ARDUINO_RASPBERRY_PI_PICO_W) if (millis() - ms > 10000) break; #endif } Serial.println(); Serial.print("Connected with IP: "); Serial.println(WiFi.localIP()); Serial.println(); Serial.printf("Firebase Client v%s\n\n", FIREBASE_CLIENT_VERSION); /* Assign the certificate file (optional) */ // config.cert.file = "/cert.cer"; // config.cert.file_storage = StorageType::FLASH; /* Assign the database URL and database secret(required) */ config.database_url = DATABASE_URL; config.signer.tokens.legacy_token = DATABASE_SECRET; Firebase.reconnectWiFi(true); // The WiFi credentials are required for Pico W // due to it does not have reconnect feature. #if defined(ARDUINO_RASPBERRY_PI_PICO_W) config.wifi.clearAP(); config.wifi.addAP(WIFI_SSID, WIFI_PASSWORD); #endif /* Initialize the library with the Firebase authen and config */ Firebase.begin(&config, &auth); // Or use legacy authenticate method // Firebase.begin(DATABASE_URL, DATABASE_SECRET); } void loop() { if (millis() - dataMillis > 5000) { dataMillis = millis(); Serial.printf("Set int... %s\n", Firebase.setInt(fbdo, "/test/int", count++) ? "ok" : fbdo.errorReason().c_str()); } }
//This example will use a ostream_logger: a log that writes to an output stream. #include <lm/ostream_logger.h> //Of course, we need the sentries to write to a logger. #include <lm/log.h> #include <iostream> #include <vector> #include <cmath> using namespace lm; void say_something(lm::logger& _logger); int main(int, char **) { std::cout<<"Building a ostream logger from std::cout..."<<std::endl; lm::ostream_logger ol(std::cout); std::cout<<"Current mask value :"<<ol.get_mask()<<std::endl; //Using all levels... say_something(ol); //Masking some levels... std::cout<<"We will mask out error and info now..."<<std::endl; int mask_value=lm::levels::all; mask_value&=~lm::levels::error; mask_value&=~lm::levels::info; ol.set_mask(mask_value); //TODO: There's a bug here: a couple of spaces are inserted... std::cout<<"Current mask value :"<<ol.get_mask()<<std::endl; say_something(ol); return 0; } void say_something(lm::logger& _logger) { lm::log(_logger).emergency()<<"State of emergency!"<<std::endl; lm::log(_logger).alert()<<"This is an alert"<<std::endl; lm::log(_logger).critical()<<"This is a critical entry"<<std::endl; lm::log(_logger).error()<<"This is an error"<<std::endl; lm::log(_logger).warning()<<"This is merely a warning"<<std::endl; lm::log(_logger).notice()<<"This is just a notice..."<<std::endl; lm::log(_logger).info()<<"Some info here..."<<std::endl; lm::log(_logger).debug()<<"And debug"<<std::endl; }
#include <GLFW/glfw3.h> #include <glm/glm.hpp> class Input { public: Input(GLFWwindow *m_window); bool isKeyPressed(int32_t keycode); bool isMouseButtonPressed(int32_t button); glm::vec2 getMousePosition(); private: GLFWwindow *m_window; };
#ifndef LANGEVIN_H #define LANGEVIN_H #include <vector> #include "lorentz.h" double delta_qhat(int pid, double E, double M, double T); double qhat_small_angle_LOpQCD(int pid, double E, double M, double T); double qhat_L_small_angle_LOpQCD(int pid, double E, double M, double T); double qhat(int pid, double E, double M, double T); double qhat_L(int pid, double E, double M, double T); double dqhat_L_dp2(int pid, double E, double M, double T); void Ito_update(int pid, double dt, double M, double T, std::vector<double> v, const fourvec & pIn, fourvec & pOut, bool is_virtual); #endif
/* * httpservice.h * PennCloud CIS 505 * Author T01 * Date: Nov 6 2017 */ #ifndef HTTPSERVICE_H #define HTTPSERVICE_H #pragma once #include "feconfig.h" #include "../common/MasterServiceClient.h" #include "StorageRepositoryClient.h" using masterservice::WriteResponse; using masterservice::AddressDTO; using masterservice::MasterFileDTO; typedef struct { string SessionID; string Domain; string Path; string Expire; } Cookie; //=================== // Http header class //=================== class RespHeader{ public: string URI; string Http_v; string content_type; string connection_type; string cache_ctrl; string post_req; int content_len; bool has_cookie; Cookie cookie; RespHeader(): URI(""), Http_v("HTTP/1.1"), content_type(ctype_html), connection_type("keep-alive"), cache_ctrl(""), post_req(""), has_cookie(false),content_len(0) {}; }; //================= //HttpService Class //================= class HttpService{ private: RespHeader *Rheader; string usrname; int connfd; // file decriptor for worker threads bool set_cookie; bool db; bool is_login; string fpath; MasterServiceClient* masterServer; AdminConsoleRepositoryClient *adminClient; unordered_set<string> RouteSet; int HandleERR(); //---GET---__ int HandleGET(const string &Req); //---POST--- int HandlePOST(const string &Req); int HandleLogin(); int HandleDELETE(); int HandleSHOWMail(); int HandleRegister(); int HandleCHPWD(); int HandleUpload(); int HandleSendEmail(); int HandleDownload(const string &fileid); int HandleCFolder(); // create folder int HandleOFolder(); // open folder int HandleRename(); int HandleMove(); //---Common--- int ParseReq(const string & Req); int ParseContentType(const string & action, string &content_type); int renderPage(const string & URL); int sendFile(const string &fileName); int SendNonHTML(); int SendNonHTML(string body); int SetCookie(const string &username); void RemoveCookie(); void ParseUAPOST(string &username, string &password); // UAPOST stands for useraccount POST //---Helper--- string gen_rand_string(size_t length); // helper function void urlDecode(char *dst, const char *src) ; void findAllFolders(unordered_map<string, vector <FileDTO> > &FolderMap, const string &path, const string& parentPath); //---Operations via gRPC--- bool ValidateUser(const UserDTO &user); bool CreateUser(const UserDTO &user); // return false if user already exist bool ChangePwd(const string &oldpwd, const string &newpwd); // return false if client typed the wrong old password int showMailul(stringstream &html_content); // add user's email to the inbox page int showFiles(stringstream &html_content, const unordered_map<string, vector <FileDTO> > &FolderMap); // add user's files to the drive page // int showFileTree(stringstream &html_content); // add user's file tree to the drive page unordered_map<string, vector <FileDTO> > showFileTree(stringstream &html_content); void fileTreehelper(unordered_map<string, vector <FileDTO> > &FolderMap, stringstream &html_content, string foldername); public: HttpService( int connfd, bool db, MasterServiceClient* masterServer); // connfd is the fd for thread ~HttpService(); int HandleCMD(const string &Cmd); int handleHttpRedirect(const string &cmd, const string &address); void addRoute(const string &route); void setAdminClient(AdminConsoleRepositoryClient* adminClientPtr) { this->adminClient = adminClientPtr; } void setLogin(const bool &isLoggedIn) { this->is_login = isLoggedIn; } }; #endif
#pragma once #include <iosfwd> template<typename T> class Ray { public: mutable T tMax; Point3<T> origin; Vector3<T> direction; T time; //const Medium *medium; Ray() { tMax = Infinity<T>(); time = (T)0; //medium(nullptr) } Ray(const Point3<T> &o, const Vector3<T> &d, T tM = Infinity<T>(), T ti = (T)0/*,const med = Medium(nullptr)*/) { origin = o; direction = d; tMax = tM; time = ti; // medium = med; } Point3<T> operator()(T t)const { return origin + destination * t; } }; template <typename T> class RayDifferential : public Ray<T> { public: bool hasDifferentials; Point3<T> rayXOrigin, rayYOrigin; Vector3<T> rayXDirection, rayYDirection; RayDifferential(const Ray &ray) : Ray(ray) { hasDifferentials = false; } RayDifferential() { hasDiffrentials = false; } RayDifferential(const Point3<T> &o, const Vector3<T> &d, T tM = Infinity<T>(), T ti = (T)0/*,const Medium *med = nullptr*/) { origin = o; direction = d; tMax = tM; time = ti; //medium = med; hasDifferentials = false; } void ScaleDifferentials(T s) { rayXOrigin = (rayXOrigin - origin)*s + origin; rayXDirection = (rayXDirection - direction)*s + direction; rayYOrigin = (rayYOrigin - origin)*s + origin; rayYDirection = (rayYDirection - direction)*s + direction; } };
#ifndef CVISA_H #define CVISA_H #include <QObject> #include <QtNetwork/qnetworkaccessmanager.h> #include <QtNetwork/qnetworkreply.h> #include <QtNetwork/qnetworkrequest.h> #include <QTextCodec> #include <QDebug> #include <QStringList> class CVisa : public QObject { Q_OBJECT public: explicit CVisa(QObject *parent = 0); virtual ~CVisa(); Q_INVOKABLE void Consultar(const QString &cartao); Q_INVOKABLE void AdicionarParaConsulta(const QString &cartao); Q_INVOKABLE void IniciarCosulta(); Q_INVOKABLE void Cancelar(); private: QNetworkAccessManager *_net; bool _cancelar; QStringList _cartoes; QUrl UrlParaConsulta(QString cartao, bool todasAnteriores); const QString _urlConsulta, _urlReferer; signals: void consultaFinalizada(); void iniciandoConsulta(const QString &cartao); void consultaCartaoFinalizada(const QString &cartao, const QString &extrato); void consultaCancelada(); void erroConexao(); private slots: void erroConexaoHandlerSlot(); public slots: virtual void consultaFinalizadaResposta(); virtual void baixandoPagina(); }; #endif // CVISA_H
// Created on : Sat May 02 12:41:16 2020 // Created by: Irina KRYLOVA // Generator: Express (EXPRESS -> CASCADE/XSTEP Translator) V3.0 // Copyright (c) Open CASCADE 2020 // // 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 _StepKinematics_ScrewPairWithRange_HeaderFile_ #define _StepKinematics_ScrewPairWithRange_HeaderFile_ #include <Standard.hxx> #include <StepKinematics_ScrewPair.hxx> #include <TCollection_HAsciiString.hxx> #include <StepRepr_RepresentationItem.hxx> #include <StepKinematics_KinematicJoint.hxx> DEFINE_STANDARD_HANDLE(StepKinematics_ScrewPairWithRange, StepKinematics_ScrewPair) //! Representation of STEP entity ScrewPairWithRange class StepKinematics_ScrewPairWithRange : public StepKinematics_ScrewPair { public : //! default constructor Standard_EXPORT StepKinematics_ScrewPairWithRange(); //! Initialize all fields (own and inherited) Standard_EXPORT void Init(const Handle(TCollection_HAsciiString)& theRepresentationItem_Name, const Handle(TCollection_HAsciiString)& theItemDefinedTransformation_Name, const Standard_Boolean hasItemDefinedTransformation_Description, const Handle(TCollection_HAsciiString)& theItemDefinedTransformation_Description, const Handle(StepRepr_RepresentationItem)& theItemDefinedTransformation_TransformItem1, const Handle(StepRepr_RepresentationItem)& theItemDefinedTransformation_TransformItem2, const Handle(StepKinematics_KinematicJoint)& theKinematicPair_Joint, const Standard_Real theScrewPair_Pitch, const Standard_Boolean hasLowerLimitActualRotation, const Standard_Real theLowerLimitActualRotation, const Standard_Boolean hasUpperLimitActualRotation, const Standard_Real theUpperLimitActualRotation); //! Returns field LowerLimitActualRotation Standard_EXPORT Standard_Real LowerLimitActualRotation() const; //! Sets field LowerLimitActualRotation Standard_EXPORT void SetLowerLimitActualRotation (const Standard_Real theLowerLimitActualRotation); //! Returns True if optional field LowerLimitActualRotation is defined Standard_EXPORT Standard_Boolean HasLowerLimitActualRotation() const; //! Returns field UpperLimitActualRotation Standard_EXPORT Standard_Real UpperLimitActualRotation() const; //! Sets field UpperLimitActualRotation Standard_EXPORT void SetUpperLimitActualRotation (const Standard_Real theUpperLimitActualRotation); //! Returns True if optional field UpperLimitActualRotation is defined Standard_EXPORT Standard_Boolean HasUpperLimitActualRotation() const; DEFINE_STANDARD_RTTIEXT(StepKinematics_ScrewPairWithRange, StepKinematics_ScrewPair) private: Standard_Real myLowerLimitActualRotation; //!< optional Standard_Real myUpperLimitActualRotation; //!< optional Standard_Boolean defLowerLimitActualRotation; //!< flag "is LowerLimitActualRotation defined" Standard_Boolean defUpperLimitActualRotation; //!< flag "is UpperLimitActualRotation defined" }; #endif // _StepKinematics_ScrewPairWithRange_HeaderFile_
#include "StopMotionStones.h" StopMotionStones::StopMotionStones() : x( 30 ), y( 20 ), xSpacing( 1920 / x ), ySpacing( 1080 / y ), transparency( 255 ), showVector( false ) { voro = new VoronoiLayer(); voro->setSmoothAmount( 10 ); waterEffect = new ofxPostProcessing(); stonesTex.init(); cutter.init(); noi.render(); vectorField.setup( 1920, 1080, 12 ); vectorField.randomize(); } StopMotionStones::~StopMotionStones() { delete voro; delete waterEffect; } void StopMotionStones::init() { lastMove1 = lastMove2 = lastMove3 = 0; currentStone = 0; secondCurrentStone = 0; thirdCurrentStone = 0; doGrow = false; transparency = 255; isStarted = false; flickeringStonesRelativeTransparency = 0.0; vectorFieldTransparency = 0; showVector = false; //cutter.init(); voro->clear(); stones.clear(); transparencies.clear(); voronoiCentroids.clear(); stones.reserve( x * y ); toDrawStone.clear(); /* Creates grid aligned voronoi diagram */ for( int i = 0; i < y; i++ ) { for( int j = 0; j < x; j++ ) { voro->addPoint( ( 50 + j * xSpacing ) + ofRandom( -5, 5 ), ( 40 + i * ySpacing ) + ofRandom( -5, 5 ) ); } } voro->compute(); for( int i = 0; i < voro->pts.size(); i++ ) { ofVec2f * p = &voro->pts.at( i ); Stone s; s.init( p->x, p->y, *voro->getLine( i ) ); s.maxGrowRad = 150; stones.push_back( s ); } for( int j = 0; j < 3; j++ ) { for( int i = 0; i < stones.size(); i++ ) { stones.at( i ).currentGrowRad = 10; stones.at( i ).grow( voro->getLine( i ), true ); } } centered = getMostCenteredVoronoiCellCenter(); for( int i = 0; i < x*y; i++ ) { transparencies.push_back( 255 ); } delete waterEffect; waterEffect = new ofxPostProcessing(); waterEffect->init( 1920, 1080 ); waterEffect->setFlip( false ); waterEffectPointer = waterEffect->createPass<NoiseWarpPass>(); waterEffectPointer->setEnabled( false ); waterEffectPointer->setAmplitude( 0.004 ); waterEffectPointer->setFrequency( 0.976 ); } void StopMotionStones::start() { isStarted = true; startedMillis = ofGetElapsedTimeMillis(); } void StopMotionStones::update( unsigned long long millis ) { unsigned long long millisStopMotionPart1 = 30000; unsigned long long millisStopMotionPart1AndAHalf = 40000; unsigned long long millisStopMotionPart2 = 70000; unsigned long long millisBrownianMotionPart1 = 115000; unsigned long long millisBrownianMotionPart2 = 185000; unsigned long long millisStartFadeAllOut = 222000; if( isStarted ) { if( isWithinMillis( millis, 0, millisStopMotionPart1 ) ) { //std::cout << "millis: " << millis << std::endl; //ofExit( 0 ); showVector = true; toDrawStone.clear(); vectorFieldTransparency += 0.5; vectorFieldTransparency = std::min( 80.0f, vectorFieldTransparency ); flickeringStonesRelativeTransparency += 1.5f; flickeringStonesRelativeTransparency = std::min( 200.0f, flickeringStonesRelativeTransparency ); currentStone += 1; } if( isWithinMillis( millis, millisStopMotionPart1, millisStopMotionPart1AndAHalf ) ) { toDrawStone.clear(); currentStone += 1; secondCurrentStone += 2; } if( isWithinMillis( millis, millisStopMotionPart1AndAHalf, millisStopMotionPart2 ) ) { toDrawStone.clear(); secondCurrentStone += 1; currentStone += 2; thirdCurrentStone += 4; ofPoint index2d = get2DFromIndex( currentStone ); int _xIndex = index2d.x; int _yIndx = index2d.y; float rand = ofRandom( -1, 1 ); if( rand > 0.95f ) { _yIndx++; } else if( rand < -0.95f ) { _yIndx--; } currentStone = getIndexFrom2D( ofPoint( _xIndex, _yIndx ) ); } if( isWithinMillis( millis, millisStopMotionPart2, millisBrownianMotionPart1 ) ) { if( ofGetFrameNum() % 4 == 0 ) { toDrawStone.clear(); currentStone = doBrownianMotion( currentStone, 0 ); secondCurrentStone = doBrownianMotion( secondCurrentStone, 1 ); thirdCurrentStone = doBrownianMotion( thirdCurrentStone, 2 ); } } if( isWithinMillis( millis, millisBrownianMotionPart1, millisBrownianMotionPart2 ) ) { if( ofGetFrameNum() % 4 == 0 ) { currentStone = doBrownianMotion( currentStone, 0 ); secondCurrentStone = doBrownianMotion( secondCurrentStone, 1 ); thirdCurrentStone = doBrownianMotion( thirdCurrentStone, 2 ); } flickeringStonesRelativeTransparency -= 1; flickeringStonesRelativeTransparency = std::max( 0.0f, flickeringStonesRelativeTransparency ); vectorFieldTransparency -= 1; } if( isWithinMillis( millis, millisBrownianMotionPart2, millisStartFadeAllOut ) ) { showVector = false; for( int i = 0; i < 5; i++ ) { auto rand = static_cast< int >( ofRandom( x * y ) ); toDrawStone.insert( rand ); } } if( isPastMillis( millis, millisStartFadeAllOut ) ) { for( int i = 0; i < 18; i++ ) { int rand = ( int ) ( ofRandom( x * y ) ); transparencies.at( rand ) -= 2; } } } if( currentStone >= stones.size() ) { currentStone = 0; } if( secondCurrentStone >= stones.size() ) { secondCurrentStone = 0; } if( thirdCurrentStone >= stones.size() ) { thirdCurrentStone = 0; } toDrawStone.insert( currentStone ); toDrawStone.insert( secondCurrentStone ); toDrawStone.insert( thirdCurrentStone ); removeOuterEdges(); selectedLines.clear(); // select lines to be rendered for( std::set<int>::iterator it = toDrawStone.begin(); it != toDrawStone.end(); ++it ) { int inde = *it; selectedLines.push_back( stones.at( inde ).border ); } stonesTex.render( selectedLines, transparencies, centered ); } void StopMotionStones::draw() { ofFbo * buf = cutter.getCutout( noi, stonesTex.getBuffer() ); waterEffect->begin(); ofPushStyle(); ofSetColor( 255, transparency ); buf->draw( 0, 0 ); //ofSetColor( 255, 0, 0, transparency ); drawCustomVoronoi(); ofPopStyle(); waterEffect->end(); if( showVector ) { ofPushStyle(); vectorField.animate( 0.008 ); vectorField.draw( vectorFieldTransparency ); ofPopStyle(); } } void StopMotionStones::drawCustomVoronoi() { ofPushStyle(); ofSetColor( 255, 0, 0, transparency ); std::vector< ofVec2f > pts = voro->getPoints(); for( std::set<int>::iterator it = toDrawStone.begin(); it != toDrawStone.end(); ++it ) { int inde = *it; int _x = inde % x; int _y = ( inde - _x ) / x; // excludes cell centers at the edges ofVec2f pt = pts[ inde ]; if( pt.x > 95 && pt.x < 1860 && pt.y > 68 && pt.y < 1037 ) { //ofSetColor( 0, transparencies.at( inde ) ); //ofCircle( pts[ inde ].x, pts[ inde ].y, 2.5 ); } } for( int i = 0; i < voro->pts.size(); i++ ) { ofPoint cent = voro->pts.at( i); ofSetColor( ofRandom( 40, 100 ), flickeringStonesRelativeTransparency ); ofCircle( cent.x, cent.y, 1 ); } ofPopStyle(); } void StopMotionStones::moveRandom( float str ) { /* Trying to move stones away from their grid position */ for( std::vector<ofVec2f>::iterator it = voro->pts.begin(); it != voro->pts.end(); ++it ) { it->x = it->x + ofRandom( -str, str ); it->y = it->y + ofRandom( -str, str ); } voro->compute(); } void StopMotionStones::setGrowing( bool gr ) { this->doGrow = gr; } ofPoint StopMotionStones::get2DFromIndex( int index ) { int _x = index % x; int _y = ( index - _x ) / x; return ofPoint( _x, _y ); } int StopMotionStones::getIndexFrom2D( ofPoint d ) { int _x = static_cast<int>( d.x ); int _y = static_cast<int>( d.y ); int index = _y * x + _x; return index; } bool StopMotionStones::isGrowing() { return doGrow; } void StopMotionStones::removeOuterEdges() { int index = 1; for( std::set<int>::iterator it = toDrawStone.begin(); it != toDrawStone.end(); ++it ) { Stone * s = &stones.at( *it ); int modulatedIndex = index % 5; if( modulatedIndex == 0 ) modulatedIndex = 1; if( ofGetFrameNum() % modulatedIndex == 0 ) { s->grow( voro->getLine( *it ), true ); } int ind = *it; ofPoint p = get2DFromIndex( ind ); if( p.x == 0 ) { toDrawStone.erase( it ); } else if( p.x == x - 1 ) { toDrawStone.erase( it ); } else if( p.y == 0 ) { toDrawStone.erase( it ); } else if( p.y == y - 1 ) { toDrawStone.erase( it ); } index++; } } bool StopMotionStones::isWithinMillis( unsigned long long currentSystemMillis, unsigned long long start, unsigned long long end ) { /* if( currentSystemMillis > start && currentSystemMillis < end ) { return true; } return false; */ //unsigned long long currentMillis = currentSystemMillis; return currentSystemMillis - startedMillis > start && currentSystemMillis - startedMillis < end; } int StopMotionStones::doBrownianMotion( int currStone, int which ) { int lastMove = 0; if( which == 0 ) { lastMove = lastMove1; } else if( which == 1 ) { lastMove = lastMove2; } else if( which == 2 ) { lastMove = lastMove3; } float rand = ofRandom( 4 ); ofPoint index2d = get2DFromIndex( currentStone ); if( rand > 0 && rand < 1 && lastMove != 2 ) { index2d.x += 1; lastMove = 1; } else if( rand > 1 && rand < 2 && lastMove != 1 ) { index2d.x -= 1; lastMove = 2; } else if( rand > 2 && rand < 3 && lastMove != 4 ) { index2d.y -= 1; lastMove = 3; } else if( rand > 3 && rand < 4 && lastMove != 3 ) { index2d.y += 1; lastMove = 4; } if( which == 0 ) { lastMove1 = lastMove; } else if( which == 1 ) { lastMove2 = lastMove; } else if( which == 2 ) { lastMove3 = lastMove; } int ind = getIndexFrom2D( index2d ); return ind; } bool StopMotionStones::isPastMillis( unsigned long long currentSystemMillis, unsigned long long mill ) { unsigned long long currentMillis = currentSystemMillis; return currentMillis - startedMillis > mill; } ofPoint StopMotionStones::getMostCenteredVoronoiCellCenter() { float distance = 1000; ofPoint selectedVoronoiCenter; for( int i = 0; i < stones.size(); i++ ) { ofPoint cent = stones.at( i ).border.getCentroid2D(); float d = ofDist( 1920 / 2, 1080 / 2, cent.x, cent.y ); if( d < distance ) { distance = d; selectedVoronoiCenter = cent; } } return selectedVoronoiCenter; } int StopMotionStones::getMostCenteredVoronoiStoneIndex() { float distance = 1000; int index = 0; for( int i = 0; i < stones.size(); i++ ) { ofPoint cent = stones.at( i ).border.getCentroid2D(); float d = ofDist( 1920 / 2, 1080 / 2, cent.x, cent.y ); if( d < distance ) { distance = d; index = i; } } return index; } void StopMotionStones::detectedStoneCount( int count ) { switch( count ) { case 0: break; case 1: break; case 2: break; case 3: break; } }
#ifndef HISTOGRAM_MANAGER_H #define HISTOGRAM_MANAGER_H #include "TFile.h" #include "TList.h" class HistogramManager { public: HistogramManager(); ~HistogramManager(); TList* LoadHistograms(std::string fileName, const char *dir_name); private: TList* ExtractHistograms(TFile* inputFile, const char *dir_name); bool CheckFileIntegrity(TFile* inputFile); }; #endif
#ifndef __NEIGHBOR_H_INCLUDED__ #define __NEIGHBOR_H_INCLUDED__ #include "GrowArray.h" class Neighbor : public GrowArray { public: // Constructors and Destructor Neighbor(); Neighbor(int i); Neighbor(int i, int j); ~Neighbor(); // Generators void pickGenerator(); void GeneratePeriodic(); void Generate_Old(); void GenerateZFBC(); void GenerateZFBC_Old(); std::string boundaryCondition; // Growth - Need to override from parent class since we use these differently void grow1D(bool extend); // Should be the same essentially as grow1ColBack void grow2DBasic(bool vertextend, bool horizextend); void grow2DSquare(bool vertextend, bool horizextend); void grow1ColBack(bool horizextend); void grow1ColFront(bool horizextend); void grow2Rows(bool vertextend); void grow2Cols(bool horizextend); void growTrap(bool vertextend, bool horizextend); void growthSwitcher(bool vertextend, bool horizextend); // Shifts short lrshift {0}; short udshift {0}; }; #endif
#if defined(__WXMSW__) # include <cairo-win32.h> #elif defined(__WXGTK__) # include <gdk/gdk.h> //# include "gtk/gtk.h" #endif // __WXMSW__ #include "fw/mainPanel.h" #include "gw/main_ui.h" CMainPanel::CMainPanel(wxWindow* parent, wxWindowID id, const wxPoint& pos, const wxSize& size, long style, const wxString& name) : wxPanel(parent, id, pos, size, style, name) { m_mainui = new CMainUI(32,32); m_refreshtimer = new wxTimer(this); this->Connect(wxEVT_PAINT, wxPaintEventHandler(CMainPanel::__OnPaint)); this->Connect(wxEVT_KEY_DOWN, wxKeyEventHandler(CMainPanel::__OnKeyDown)); this->Connect(wxEVT_KEY_UP, wxKeyEventHandler(CMainPanel::__OnKeyUp)); this->Connect(wxEVT_TIMER, wxTimerEventHandler(CMainPanel::__OnRefreshTimer)); this->Connect(wxEVT_LEFT_UP, wxMouseEventHandler(CMainPanel::__OnMouseLeftUp)); m_refreshtimer->Start(1000/g_frame_rate); } CMainPanel::~CMainPanel() { m_refreshtimer->Stop(); delete m_refreshtimer; delete m_mainui; } void CMainPanel::__OnPaint(wxPaintEvent& evt) { wxPaintDC dc(this); wxRect rect = GetClientRect(); if(rect.width == 0 || rect.height == 0) { return; } #ifdef __WXMSW__ HWND hwnd = (HWND)this->GetHandle(); HDC hdc = ::GetDC(hwnd); // Create a double buffer for blitting to // the screen to prevent screen flicker. Pass // the double buffer to cairo and blit it // in the paint routine. HDC dcbuffer = CreateCompatibleDC(hdc); HBITMAP hbuffer = CreateCompatibleBitmap(hdc, rect.width, rect.height); SelectObject(dcbuffer, hbuffer); cairo_surface_t* cairo_surface = cairo_win32_surface_create(dcbuffer); cairo_t* cairo_image = cairo_create(cairo_surface); Render(true, cairo_image, rect.width, rect.height); BitBlt(hdc, 0, 0, rect.width, rect.height, dcbuffer, 0, 0, SRCCOPY); // Tear down the cairo object now that we don't need // it anymore. cairo_destroy(cairo_image); cairo_surface_destroy(cairo_surface); DeleteDC(dcbuffer); DeleteObject(hbuffer); // Because we called ::GetDC make sure we relase the handle // back to the system or we'll have a memory leak. ::ReleaseDC(hwnd,hdc); #elif defined(__WXMAC__) CGContextRef context = (CGContextRef) dc.GetGraphicsContext()->GetNativeContext(); if(context == 0) { return; } cairo_surface_t* cairo_surface = cairo_quartz_surface_create_for_cg_context(context, rect.width, rect.height); cairo_t* cairo_image = cairo_create(cairo_surface); Render(true, cairo_image, rect.width, rect.height); cairo_surface_flush(cairo_surface); CGContextFlush( context ); cairo_surface_destroy(cairo_surface); cairo_destroy(cairo_image); #elif defined(__WXGTK__) // If it's GTK then use the gdk_cairo_create() method. The GdkDrawable object // is stored in m_window of the wxPaintDC. // the second argument is necessary, or will get memory leak. Context ctx(gdk_cairo_create(dc.m_window), true); m_mainui->CopyToContext(&ctx, rect.width, rect.height); #endif return; } void CMainPanel::__OnKeyDown(wxKeyEvent& evt) { //typeof(m_mainui) ui = m_mainui; //int key = evt.GetKeyCode(); return; } void CMainPanel::__OnKeyUp(wxKeyEvent& evt) { //typeof(m_mainui) ui = m_mainui; //int key = evt.GetKeyCode(); return; } void CMainPanel::__OnRefreshTimer(wxTimerEvent& evt) { bool bRefresh = true; if (bRefresh) { //wxPuts(wxT("refresh")); this->Refresh(); } return; } void CMainPanel::__OnMouseLeftUp(wxMouseEvent& evt) { int x, y; evt.GetPosition(&x, &y); m_mainui->onMouseLeftUp(x, y); return; }
// Created on: 2000-06-23 // Created by: Sergey MOZOKHIN // Copyright (c) 2000-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 _StlAPI_Writer_HeaderFile #define _StlAPI_Writer_HeaderFile #include <Message_ProgressScope.hxx> #include <Message_ProgressIndicator.hxx> class TopoDS_Shape; //! This class creates and writes //! STL files from Open CASCADE shapes. An STL file can be written to an existing STL file or to a new one. class StlAPI_Writer { public: DEFINE_STANDARD_ALLOC //! Creates a writer object with default parameters: ASCIIMode. Standard_EXPORT StlAPI_Writer(); //! Returns the address to the flag defining the mode for writing the file. //! This address may be used to either read or change the flag. //! If the mode returns True (default value) the generated file is an ASCII file. //! If the mode returns False, the generated file is a binary file. Standard_Boolean& ASCIIMode() { return myASCIIMode; } //! Converts a given shape to STL format and writes it to file with a given filename. //! \return the error state. Standard_EXPORT Standard_Boolean Write (const TopoDS_Shape& theShape, const Standard_CString theFileName, const Message_ProgressRange& theProgress = Message_ProgressRange()); private: Standard_Boolean myASCIIMode; }; #endif // _StlAPI_Writer_HeaderFile
class PartOre: CA_Magazine { scope = 2; count = 1; type = 256; displayName = $STR_ORE_NAME_IRON; model = "\z\addons\dayz_epoch\models\iron_ore.p3d"; picture="\z\addons\dayz_epoch\pictures\equip_iron_ore_CA.paa"; descriptionShort = $STR_ORE_NAME_IRON_DESC; class ItemActions { class Crafting { text = $STR_EPOCH_PLAYER_265; script = ";['Crafting','CfgMagazines', _id] spawn player_craftItem;"; neednearby[] = {"fire"}; requiretools[] = {"ItemSledge"}; output[] = {{"PartGeneric",1},{"ItemWaterbottleUnfilled",1}}; input[] = {{"PartOre",4},{"ItemWaterbottle",1}}; }; }; }; class PartOreSilver: CA_Magazine { scope = 2; count = 1; type = 256; displayName = $STR_ORE_NAME_SILVER; model = "\z\addons\dayz_epoch\models\silver_ore.p3d"; picture="\z\addons\dayz_epoch\pictures\equip_silver_ore_CA.paa"; descriptionShort = $STR_ORE_DESC; class ItemActions { class Crafting { text = $STR_EPOCH_PLAYER_266; script = ";['Crafting','CfgMagazines', _id] spawn player_craftItem;"; neednearby[] = {"fire"}; requiretools[] = {"ItemSledge"}; output[] = {{"ItemSilverBar",1},{"ItemWaterbottleUnfilled",1}}; input[] = {{"PartOreSilver",1},{"ItemWaterbottle",1}}; }; }; }; class PartOreGold: CA_Magazine { scope = 2; count = 1; type = 256; displayName = $STR_ORE_NAME_GOLD; model = "\z\addons\dayz_epoch\models\gold_ore.p3d"; picture="\z\addons\dayz_epoch\pictures\equip_gold_ore_CA.paa"; descriptionShort = $STR_ORE_DESC; class ItemActions { class Crafting { text = $STR_EPOCH_PLAYER_267; script = ";['Crafting','CfgMagazines', _id] spawn player_craftItem;"; neednearby[] = {"fire"}; requiretools[] = {"ItemSledge"}; output[] = {{"ItemGoldBar",1},{"ItemWaterbottleUnfilled",1}}; input[] = {{"PartOreGold",1},{"ItemWaterbottle",1}}; }; }; };
#pragma once #include "LobbyUser.h" class RoomManager : public CMultiThreadSync<RoomManager> { public: RoomManager(); ~RoomManager(); private: DWORD mMaxRoomCount; DWORD mCurrentRoomCount; std::vector<Room*> mRoomVector; public: BOOL Begin(DWORD maxRoomCount); BOOL End(); Room* QuickJoin(LobbyUser * user, USHORT &slotIndex); Room* CreateRoom(LobbyUser * user, USHORT &slotIndex); VOID SetRoomListData(ROOM_LIST_DATA *room_data); Room* GetRoomByIndex(int Index); };
#include <iostream> #include <cstdlib> #include "RobotomyRequestForm.hpp" RobotomyRequestForm::RobotomyRequestForm(std::string const &target) : Form("RobotomyRequestForm", 72, 45, target) { std::cout << "[RobotomyRequestForm](std::string const&)" " Ctor called" << std::endl; return ; } RobotomyRequestForm::~RobotomyRequestForm() { std::cout << "[RobotomyRequestForm]() Dtor called" << std::endl; return ; } void RobotomyRequestForm::execute( Bureaucrat const &executor) const { std::cout << "Makes some drilling noises. "; if (std::rand() % 2) std::cout << this->getTarget() << " has been robotomized successfully" << std::endl; else std::cout << "Robotomization failed on " << this->getTarget() << std::endl; (void)executor; return ; }
#include "BarbWire.h" BarbWire::BarbWire() { gridResolutionY = 15; gridResolutionX = 15; distance = 150; barbWireKnobSize = 12; gridDeformAmount = 10; barbWireThickness = 2; hueVal = 0; brightness = 0; transparency = 0; } BarbWire::~BarbWire() { } void BarbWire::draw() { ofPushStyle(); ofSetColor( ofColor::fromHsb( hueVal, 255, brightness ), transparency ); glLineWidth( barbWireThickness ); for( int i = 0; i < xLines.size(); i++ ) { xLines.at( i ).draw(); yLines.at( i ).draw(); } ofPopStyle(); } void BarbWire::setTransparency( float _trans ) { this->transparency = _trans; } float BarbWire::getTransparency() { return transparency; } void BarbWire::init() { xLines.clear(); yLines.clear(); for( int y = 0; y < gridResolutionY; y++ ) { ofPolyline xLine, yLine; for( int x = 0; x < gridResolutionX; x++ ) { ofPoint firstPointX( distance * x, distance * y ); ofPoint firstPointY( distance * y, distance * x ); ofPoint secondPointY( distance * y, distance * ( x + 1 ) ); ofPoint secondPointX( distance * ( x + 1 ), distance * y ); ofPoint addToX( ofRandom( -gridDeformAmount, gridDeformAmount ), ofRandom( -gridDeformAmount, gridDeformAmount ) ); firstPointX += addToX; ofPoint addToY( ofRandom( -gridDeformAmount, gridDeformAmount ), ofRandom( -gridDeformAmount, gridDeformAmount ) ); firstPointY += addToY; ofPoint addToX2( ofRandom( -gridDeformAmount, gridDeformAmount ), ofRandom( -gridDeformAmount, gridDeformAmount ) ); secondPointX += addToX2; ofPoint addToY2( ofRandom( -gridDeformAmount, gridDeformAmount ), ofRandom( -gridDeformAmount, gridDeformAmount ) ); secondPointY += addToY2; xLine.curveTo( firstPointX ); xLine.curveTo( secondPointX ); yLine.curveTo( firstPointY ); yLine.curveTo( secondPointY ); if( x == 0 ) { xLine.curveTo( firstPointX ); xLine.curveTo( secondPointX ); yLine.curveTo( firstPointY ); yLine.curveTo( secondPointY ); } // barbwire knot for( int i = 0; i < 5; i++ ) { float _addx = ofRandom( -barbWireKnobSize, barbWireKnobSize ); float _addy = ofRandom( -barbWireKnobSize, barbWireKnobSize ); ofPoint xto = secondPointX + ofPoint( _addx, _addy ); ofPoint yto = secondPointY + ofPoint( _addx, _addy ); xLine.curveTo( xto ); yLine.curveTo( yto ); } } xLines.push_back( xLine ); yLines.push_back( yLine ); } } void BarbWire::setHue( float _hue ) { this->hueVal = _hue; } float BarbWire::getHue() { return this->hueVal; } void BarbWire::setThickness( float _thick ) { this->barbWireThickness = _thick; } float BarbWire::getThickness() { return this->barbWireThickness; } void BarbWire::setBrightness( float _bright ) { this->brightness = _bright; } float BarbWire::getBrightness() { return this->brightness; }
// Programmable-Air // Author: tinkrmind // https://github.com/orgs/Programmable-Air // // Crawling catterpillar // Needs two added valve extension boards // // PCB v0.3/v0.4/v0.5 #include "programmable_air.h" #define DEBUG 1 int state = UN_KNOWN; int atmospheric_pressure[3] = {520, 520, 512}; int upper_threshold = 35; int lower_threshold = -10; void setup() { initializePins(); vent(1); vent(2); vent(3); for (int i = 1; i <= 3; i++) { readPressure(i, 20); } delay(200); for (int i = 1; i <= 3; i++) { atmospheric_pressure[i - 1] = readPressure(i, 10); } closeAllValves(); } void loop() { if (readBtn(RED)) { switchOnPumps(80); for (int j = 0; j <= 10; j++) { for (int i = 3; i >= 1; i--) { blowSection(i); } for (int i = 3; i >= 1; i--) { ventSection(i); } } switchOffPumps(); } if (readBtn(BLUE)) { ventSection(4); } } void blowSection(int i) { // int pressure = readPressure(i); // int pressure_diff = pressure - atmospheric_pressure[i - 1]; // while (pressure_diff < upper_threshold) { // pressure = readPressure(i); // pressure_diff = pressure - atmospheric_pressure[i - 1]; // Serial.println(pressure_diff); // blow(i); // delay(200); // } blow(i); delay(3000); closeAllValves(); } void ventSection(int i) { if (i >= 1 && i <= 3) { vent(i); delay(500); closeAllValves(); } if (i == 4) { vent(1); vent(2); vent(3); while (!readBtn(BLUE)) { delay(10); } closeAllValves(); } }
#include "redisDb.h" redisDb::redisDb() { } redisDb::~redisDb() { }
#include <stdio.h> #include <iostream> #include <string> using namespace std; int main() { string wow ="INTJ"; for (char i : wow) { cout << "[" << i << "]"; } cout << '\n'; return 0; }
#include<stdio.h> #include<stdlib.h> int main() { FILE *fp; char ch; fp=fopen("Sample.txt","r"); if(fp==NULL) printf("File not found\n"); else { while(!feof(fp)) { ch=fgetc(fp); printf("%c",ch); } fclose(fp); } }
#ifndef __mir9__AttackEnemyInfo__ #define __mir9__AttackEnemyInfo__ #include "figure/Monomer.h" #include "publicDef/PublicDef.h" using namespace ui; class AttackEnemyInfo: public Layer { LoadingBar* m_bloodPro; TextAtlas* m_level; Text* m_nickName; Layout* m_widget; public: AttackEnemyInfo(); virtual ~AttackEnemyInfo(); CREATE_FUNC(AttackEnemyInfo); bool init(); void hide(); void showAttackInfo(Monomer* sender); protected: void updateAttackInfo(float delay); }; #endif /* defined(__mir9__AttackEnemyInfo__) */
#include "bricks/io/substream.h" namespace Bricks { namespace IO { Substream::Substream(Stream* stream, u64 offset) : stream(stream), offset(offset), position(0) { length = stream->GetLength() - offset; } Substream::Substream(Stream* stream, u64 offset, u64 length) : stream(stream), offset(offset), position(0), length(length) { } void Substream::Flush() { stream->Flush(); } size_t Substream::Read(void* buffer, size_t size) { if (position + size > length) size = length - position; if (stream->GetPosition() != offset + position) stream->SetPosition(offset + position); size = stream->Read(buffer, size); position += size; return size; } size_t Substream::Write(const void* buffer, size_t size) { if (position + size > length) size = length - position; if (stream->GetPosition() != offset + position) stream->SetPosition(offset + position); size = stream->Write(buffer, size); position += size; return size; } u64 Substream::GetStreamOffset(Stream* parent) { #if BRICKS_CONFIG_RTTI Substream* substream = CastToDynamic<Substream>(stream); if (substream && stream != parent) return substream->GetStreamOffset(parent) + offset; #endif return offset; } } }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 1995-2011 Opera Software AS. All rights reserved. * * This file is part of the Opera web browser. It may not be distributed * under any circumstances. */ #ifndef DOM_COMPASSNEEDSCALIBRATIONEVENT_H #define DOM_COMPASSNEEDSCALIBRATIONEVENT_H #ifdef DOM_DEVICE_ORIENTATION_EVENT_SUPPORT #include "modules/dom/src/domevents/domevent.h" class DOM_CompassNeedsCalibrationEvent : public DOM_Event { public: static OP_STATUS Make(DOM_CompassNeedsCalibrationEvent*& result, DOM_Runtime* runtime); private: virtual OP_STATUS DefaultAction(BOOL cancelled); }; #endif // DOM_DEVICE_ORIENTATION_EVENT_SUPPORT #endif // DOM_COMPASSNEEDSCALIBRATIONEVENT_H
#include "InterfaceNative.h" class Implementation : public IInterface2 { private: MyValue value; public: Implementation() { value = MyValue{ 1, 3.0 }; } Implementation(int intValue, double doubleValue) { value = {intValue, doubleValue}; } virtual MyValue __stdcall GetValue() override { return value; } virtual MyValue __stdcall GetValue2() override { return value; } void __stdcall AddToThis(IInterface2* interfaces[], int numInstances) override { for (int i = 0; i < numInstances; ++i) { value.I += interfaces[i]->GetValue2().I; value.J += interfaces[i]->GetValue2().J; } } }; class PropertyImplementation : public InterfaceWithProperties { bool isTrue; int value; int value2; public: PropertyImplementation(bool isTrue, int value, int value2) : isTrue(isTrue), value(value), value2(value2) {} virtual bool __stdcall IsTrue() override { return isTrue; } virtual RESULT __stdcall IsTrueOutProp(bool* value) { *value = isTrue; return 0; } virtual int __stdcall GetValue() { return value; } virtual void __stdcall SetValue(int value) { this->value = value; } virtual RESULT __stdcall GetValue2(int* value) { *value = value2; return 0; } virtual void __stdcall SetValue2(int value) { value2 = value; } virtual int __stdcall GetValuePersistent() { return value; } virtual RESULT __stdcall GetValue2Persistent(int* value) { *value = value2; return 0; } virtual InterfaceWithProperties* __stdcall GetSelfPersistent() { return this; } virtual RESULT __stdcall GetSelfOutPersistent(InterfaceWithProperties** self) { *self = this; return 0; } }; class FastOutInterfaceImplementation : public FastOutInterface { virtual void DoNothing() {} }; struct PassThroughMethodTestImpl: public PassThroughMethodTest { virtual size_t PassThrough(size_t test) { return test; } virtual long PassThroughLong(long test) { return test; } }; extern "C" __declspec(dllexport) IInterface2 * __stdcall CreateInstance(void) { return new Implementation(); } extern "C" __declspec(dllexport) IInterface* __stdcall CreateInstance2(int i, double j) { return new Implementation(i, j); } extern "C" __declspec(dllexport) bool __stdcall CloneInstance(IInterface* interface, IInterface** clonedInterface) { auto value = interface->GetValue(); *clonedInterface = new Implementation(value.I, value.J); return true; } extern "C" __declspec(dllexport) InterfaceWithProperties* CreatePropertyTest(bool isTrue, int value, int value2) { return new PropertyImplementation(isTrue, value, value2); } extern "C" __declspec(dllexport) void FastOutInterfaceTest(FastOutInterface** out) { *out = new FastOutInterfaceImplementation(); } extern "C" __declspec(dllexport) PassThroughMethodTest* GetPassThroughMethodTest() { return new PassThroughMethodTestImpl(); }
// Дана строка, содержащая пробелы. Найдите, сколько в ней слов (слово – это последовательность // непробельных символов, слова разделены одним пробелом, первый и последний символ строки – не // пробел). // Входные данные // На вход подается несколько строк. // Выходные данные // Необходимо вывести количество слов в первой из введенных строк. #include <iostream> using namespace std; int main() { string s; getline(cin, s); int count = 0; for (auto w : s) { if (w == ' ') { ++count; }; } cout << count + 1 << endl; return 0; }
#include <stdio.h> #include <stdlib.h> #include <time.h> /* reference : a book : Robot Intelligence how to compile: $ g++ -Wall filename.cpp -o executablename */ int main() { int **population; // 個体集合 int num; // 個体数 int length; // 遺伝子長 int i, j; num = 10; length = 5; population = new int*[num]; for(i=0 ; i < num ; i ++){ population[i] = new int[length]; } // initiate random function srand ((unsigned) time (NULL)); for ( i=0; i<num; i++ ){ for ( j = 0; j < length; j++ ){ population[i][j] = rand() % 2; printf ("%d", population[i][j]); } printf("\n"); } for ( i = 0; i < num ; i++ ){ delete []population[i]; } delete []population; return 0; }
#include <iostream> #include <string> #include <map> #include <vector> #include <fstream> using namespace std; int main(){ string letterList = "abcdefghijklmnopqrstuvwxyz"; int number; string letter; map<string, int> alphabet; for(int i=0;i<26;i++){ letter = letterList[i]; number = i; alphabet.insert(pair<string, int> (letter, number)); cout << letter << ", " << number << endl; } letter = letterList[0]; // cout<< "map[0]=" << alphabet[0]<<endl; cout<< "map[a]=" << alphabet[letter]<<endl; for(int i=0;i<26;i++){ letter = letterList[i]; cout<< letter; // letter = letterList[number]; cout<<", " << alphabet[letter]; } }
// BEGIN CUT HERE // PROBLEM STATEMENT // // We have an arithmetic expression made up of positive // integers, the + and - operators and parentheses. All the // parentheses, // however, have been erased by the cleaning staff and we // want to calculate the minimum value the original // expression may have had. // // You will be given a string e containing the expression // without the parentheses. Return the minimum value // the original expression could have had before the // parentheses were erased. // // // DEFINITION // Class:LostParentheses // Method:minResult // Parameters:string // Returns:int // Method signature:int minResult(string e) // // // NOTES // -All operations in the original expression were addition // and subtraction; there were no parentheses placed between // two consecutive digits. // // // CONSTRAINTS // -e will contain between 1 and 50 characters, inclusive. // -Each character of e will be a digit ('0'-'9'), a plus // sign ('+') or a minus sign ('-'). // -The first and last characters of e will be digits. // -No two operators (characters '+' and '-') will appear // consecutively in e. // -There will not be a sequence of more than 5 consecutive // digits in e. // // // EXAMPLES // // 0) // "55-50+40" // // Returns: -35 // // The expression can only have two different values: 55- // 50+40=45 and 55-(50+40)=-35. // // 1) // "10+20+30+40" // // Returns: 100 // // Since the sum is associative, any parenthesization of the // expression would get the same result. // // 2) // "00009-00009" // // Returns: 0 // // Numbers may contain leading zeroes. // // END CUT HERE #line 69 "LostParentheses.cpp" #include <string> #include <vector> #include <iostream> #include <sstream> #include <algorithm> #include <numeric> #include <functional> #include <map> #include <set> #include <cassert> #include <list> #include <deque> #include <iomanip> #include <cstring> #include <cmath> #include <cstdio> #include <cctype> using namespace std; #define fi(n) for(int i=0;i<(n);i++) #define fj(n) for(int j=0;j<(n);j++) #define f(i,a,b) for(int (i)=(a);(i)<(b);(i)++) typedef vector <int> VI; typedef vector <string> VS; typedef vector <VI> VVI; template<class T> T fromString(string inp) { stringstream s(inp); T a; s>>a; return a; } VS toks(string inp,string delim) { char *ch = strdup(inp.c_str()); char *ptr = strtok(ch,delim.c_str()); VS ret; while (ptr != NULL){ ret.push_back(ptr); ptr = strtok(NULL,delim.c_str()); } free(ch); return ret; } template<class T> vector<T> toksT(string inp,string delim) { VS temp = toks(inp,delim); vector<T> ret; for(int i=0;i<temp.size();i++) ret.push_back(fromString<T>(temp[i])); return ret; } class LostParentheses { public: int minResult(string e) { VI t = toksT<int>(e, "+-"); if (t.size() == 1) return t[0]; int lastpos = 0; int j = 0; int ret = t[j++]; while (1) { int pos = e.find_first_of("+-", lastpos + 1); if (pos == string::npos) break; if (e[pos] == '+') { ret += t[j++]; lastpos = pos; } if (e[pos] == '-') { int te = 0; int lp = pos; while (1) { int p = e.find_first_of("+-", lp + 1); te += t[j++]; if (p == string::npos || e[p] == '-') break; lp = p; } ret -= te; lastpos = lp; } } return ret; } // BEGIN CUT HERE public: void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); } private: template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); } void verify_case(int Case, const int &Expected, const int &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } } void test_case_0() { string Arg0 = "55-50+40"; int Arg1 = -35; verify_case(0, Arg1, minResult(Arg0)); } void test_case_1() { string Arg0 = "10+20+30+40"; int Arg1 = 100; verify_case(1, Arg1, minResult(Arg0)); } void test_case_2() { string Arg0 = "00009-00009"; int Arg1 = 0; verify_case(2, Arg1, minResult(Arg0)); } // END CUT HERE }; // BEGIN CUT HERE int main() { LostParentheses ___test; ___test.run_test(-1); } // END CUT HERE
// Copyright (c) 2012-2017 The Cryptonote developers // Copyright (c) 2018-2023 Conceal Network & Conceal Devs // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "gtest/gtest.h" #include "CryptoNoteCore/CryptoNoteFormatUtils.h" #include "CryptoNoteCore/Currency.h" #include <Logging/LoggerGroup.h> using namespace cn; namespace { const size_t TEST_NUMBER_OF_DECIMAL_PLACES = 8; void do_pos_test(uint64_t expected, const std::string& str) { logging::LoggerGroup logger; cn::Currency currency = cn::CurrencyBuilder(logger).numberOfDecimalPlaces(TEST_NUMBER_OF_DECIMAL_PLACES).currency(); uint64_t val; std::string number_str = str; std::replace(number_str.begin(), number_str.end(), '_', '.'); number_str.erase(std::remove(number_str.begin(), number_str.end(), '~'), number_str.end()); ASSERT_TRUE(currency.parseAmount(number_str, val)); ASSERT_EQ(expected, val); } void do_neg_test(const std::string& str) { logging::LoggerGroup logger; cn::Currency currency = cn::CurrencyBuilder(logger).numberOfDecimalPlaces(TEST_NUMBER_OF_DECIMAL_PLACES).currency(); uint64_t val; std::string number_str = str; std::replace(number_str.begin(), number_str.end(), '_', '.'); number_str.erase(std::remove(number_str.begin(), number_str.end(), '~'), number_str.end()); ASSERT_FALSE(currency.parseAmount(number_str, val)); } } #define TEST_pos(expected, str) \ TEST(parse_amount, handles_pos_ ## str) \ { \ do_pos_test(UINT64_C(expected), #str); \ } #define TEST_neg(str) \ TEST(parse_amount, handles_neg_ ## str) \ { \ do_neg_test(#str); \ } #define TEST_neg_n(str, name) \ TEST(parse_amount, handles_neg_ ## name) \ { \ do_neg_test(#str); \ } TEST_pos(0, 0); TEST_pos(0, 00); TEST_pos(0, 00000000); TEST_pos(0, 000000000); TEST_pos(0, 00000000000000000000000000000000); TEST_pos(0, _0); TEST_pos(0, _00); TEST_pos(0, _00000000); TEST_pos(0, _000000000); TEST_pos(0, _00000000000000000000000000000000); TEST_pos(0, 00000000_); TEST_pos(0, 000000000_); TEST_pos(0, 00000000000000000000000000000000_); TEST_pos(0, 0_); TEST_pos(0, 0_0); TEST_pos(0, 0_00); TEST_pos(0, 0_00000000); TEST_pos(0, 0_000000000); TEST_pos(0, 0_00000000000000000000000000000000); TEST_pos(0, 00_); TEST_pos(0, 00_0); TEST_pos(0, 00_00); TEST_pos(0, 00_00000000); TEST_pos(0, 00_000000000); TEST_pos(0, 00_00000000000000000000000000000000); TEST_pos(1, 0_00000001); TEST_pos(1, 0_000000010); TEST_pos(1, 0_000000010000000000000000000000000); TEST_pos(9, 0_00000009); TEST_pos(9, 0_000000090); TEST_pos(9, 0_000000090000000000000000000000000); TEST_pos( 100000000, 1); TEST_pos( 6553500000000, 65535); TEST_pos( 429496729500000000, 4294967295); TEST_pos(18446744073700000000, 184467440737_); TEST_pos(18446744073700000000, 184467440737_0); TEST_pos(18446744073700000000, 184467440737_00000000); TEST_pos(18446744073700000000, 184467440737_000000000); TEST_pos(18446744073700000000, 184467440737_0000000000000000000); TEST_pos(18446744073709551615, 184467440737_09551615); // Invalid numbers TEST_neg_n(~, empty_string); TEST_neg_n(-0, minus_0); TEST_neg_n(+0, plus_0); TEST_neg_n(-1, minus_1); TEST_neg_n(+1, plus_1); TEST_neg_n(_, only_point); // A lot of fraction digits TEST_neg(0_000000001); TEST_neg(0_000000009); TEST_neg(184467440737_000000001); // Overflow TEST_neg(184467440737_09551616); TEST_neg(184467440738); TEST_neg(18446744073709551616); // Two or more points TEST_neg(__); TEST_neg(0__); TEST_neg(__0); TEST_neg(0__0); TEST_neg(0_0_); TEST_neg(_0_0); TEST_neg(0_0_0);
//Program Name: Triangle Challenge //Created by Kartik Nagpal - kn8767 #include <iostream> #include <cmath> using std::cin; using std::cout; using std::endl; using std::string; int main () { char array_alphabets [26] = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'}; cout << array_alphabets [19]; cout << array_alphabets [0]; cout << array_alphabets [2]; cout << array_alphabets [2]; cout << array_alphabets [18]; cout << array_alphabets [19]; cout << array_alphabets [4]; cout << array_alphabets [17] << endl; }
#ifndef _EVENT_LIST_H_ #define _EVENT_LIST_H_ #include <map> #include "NanoTimer.h" #include "Event.h" using namespace std; //enum EventType { CREATE = 1, SPLIT = 2, ENDSIM = 10 }; class EventList{ private: // Id del escenario unsigned int id; vector<Event*> events; // unsigned int gen_start; // unsigned int gen_finish; unsigned int cur_pos; public: EventList(); EventList(const EventList &original); EventList& operator=(const EventList& original); virtual EventList *clone(); virtual ~EventList(); // bool hasEvent(unsigned int gen); // unsigned int start(); // // unsigned int finish(); unsigned int size(); Event *getEvent(unsigned int pos); Event *getFirst(); Event *getLast(); void reset(); bool hasNext(); Event *next(); void setId(unsigned int _id); unsigned int getId() const; // void resize(unsigned int size){ // events.resize(size); // } void addEvent(Event *event){ events.push_back(event); } // Metodo de debug void print(){ cout << "EventList::print - id: " << id << "\n"; cout << "EventList::print - n_events: " << events.size() << "\n"; for( Event *e : events ){ e->print(); } } unsigned int serializedSize(){ // return 0; unsigned int n_bytes = 0; // id, n_events, cada evento n_bytes += sizeof(int); n_bytes += sizeof(int); for(Event *e : events){ n_bytes += e->serializedSize(); } return n_bytes; } void serialize(char *buff){ // cout << "EventList::serialize - Inicio\n"; memcpy(buff, (char*)&id, sizeof(int)); buff += sizeof(int); unsigned int n_events = events.size(); memcpy(buff, (char*)&n_events, sizeof(int)); buff += sizeof(int); for(Event *e : events){ e->serialize(buff); buff += e->serializedSize(); } // cout << "EventList::serialize - Fin\n"; } unsigned int loadSerialized(char *buff){ // cout << "EventList::loadSerialized - Inicio\n"; // Guardo el original para calcular desplazamiento char *buff_original = buff; memcpy((char*)&id, buff, sizeof(int)); buff += sizeof(int); unsigned int n_events = 0; memcpy((char*)&n_events, buff, sizeof(int)); buff += sizeof(int); for(unsigned int i = 0; i < n_events; ++i){ Event *e = new Event(); buff += e->loadSerialized(buff); events.push_back(e); } // cout << "EventList::loadSerialized - Fin (bytes usados: " << (buff - buff_original) << ")\n"; return (buff - buff_original); } }; #endif
#include <ezLCDLib.h> ezLCD3 lcd; // create lcd object void setup() { lcd.begin( EZM_BAUD_RATE ); lcd.cls(); lcd.light(70); lcd.picture(0,0,"Map2.gif"); } void loop(){ }
#include <iostream> #include <thread> #include <mutex> #include <vector> using namespace std; once_flag callflag; void print_once() { cout << "!"; } void print(size_t x) { std::call_once (callflag, print_once); cout << x; } int main() { vector<thread> v; for (size_t i=0; i<10; i++) v.emplace_back(print, i); for (auto& t : v) t.join(); cout << "\n"; }
//By SCJ //#include<iostream> #include<bits/stdc++.h> using namespace std; #define endl '\n' #define maxn 2005 int p[maxn],dp[maxn][maxn],go[maxn],back[maxn],c[maxn],start[maxn]; int main() { ios::sync_with_stdio(0); cin.tie(0); int test;cin>>test; while(test--) { int n;cin>>n; for(int i=1;i<=n;++i) cin>>p[i]>>go[i]>>c[i],back[i]=go[i]; for(int i=2;i<=n;++i) c[i]+=c[i-1],p[i]+=p[i-1]; int MIN=back[n]; for(int i=n-1;i>0;--i) { MIN=min(back[i],MIN+c[i]-c[i-1]); back[i]=MIN; } // cout<<"back : "; // for(int i=1;i<=n;++i) // { // cout<<back[i]<<' '; // } // cout<<endl; int B,R;cin>>B>>R; memset(start,0,sizeof(start)); for(int i=1;i<=n;++i) { for(int j=i;j>0;--j) { int sum=c[i-1]-c[j-1]+go[i]+back[j]; if(sum<=B) start[i]=j; //else break; } } // cout<<"start :"; // for(int i=1;i<=n;++i) cout<<start[i]<<' '; // cout<<endl; for(int i=1;i<=n;++i) { for(int j=1;j<=R;++j) { dp[i][j]=dp[i-1][j]; if(start[i]) dp[i][j]=max(dp[i][j],dp[start[i]-1][j-1]+p[i]-p[start[i]-1]); } } cout<<dp[n][R]<<endl; } } /* 2 3 10 2 3 10 4 2 10 5 5 11 1 3 10 2 3 10 4 2 10 5 5 11 2 2 1 100 10 10 20 1 1 100 10 10 10 1 */
#include <iostream> using namespace std; int test() { int m, n, x, y; cin >> m >> n >> x >> y; int year = -1; for (int i = 0; year <= 40000; i++) { year = i * m + x; int rest = year % n > ? year % n : n; if (rest == y) { return year; } } return -1; } int main() { int T; cin >> T; while (T--) { cout << test() << endl; } return 0; }
#include "utils.hpp" #include "recharge_ptts.hpp" #include "mail_ptts.hpp" using namespace std; namespace pc = proto::config; namespace nora { namespace config { recharge_ptts& recharge_ptts_instance() { static recharge_ptts inst; return inst; } void recharge_ptts_set_funcs() { recharge_ptts_instance().check_func_ = [] (const auto& ptt) { if (!check_events(ptt.events())) { CONFIG_ELOG << ptt.id() << " check events failed"; } if (ptt.days() > 0) { if (!check_events(ptt.day_events())) { CONFIG_ELOG << ptt.id() << " check days events failed"; } } }; recharge_ptts_instance().modify_func_ = [] (auto& ptt) { if (ptt.days() > 0) { if (ptt.id() == 1) { ptt.set__type(pc::RT_GOLD_MONTH_CARD); } if (ptt.id() == 2) { ptt.set__type(pc::RT_GENERAL_MONTH_CARD); } } }; recharge_ptts_instance().verify_func_ = [] (const auto& ptt) { if (!verify_events(ptt.events())) { CONFIG_ELOG << ptt.id() << " verify events failed"; } if (ptt.days() > 0) { if (!verify_events(ptt.day_events())) { CONFIG_ELOG << ptt.id() << " verify days events failed"; } } if (ptt.has_day_events_mail()) { if (!PTTS_HAS(mail, ptt.day_events_mail())) { CONFIG_ELOG << "day events mail not exit " << ptt.day_events_mail(); } } }; } vip_ptts& vip_ptts_instance() { static vip_ptts inst; return inst; } void vip_ptts_set_funcs() { vip_ptts_instance().check_func_ = [] (const auto& ptt) { if (ptt.has_box()) { if (!check_conditions(ptt.box().conditions())) { CONFIG_ELOG << ptt.level() << " check box conditions failed"; } if (!check_events(ptt.box().events())) { CONFIG_ELOG << ptt.level() << " check box events failed"; } } }; vip_ptts_instance().modify_func_ = [] (auto& ptt) { auto *conditions = ptt.mutable_box()->mutable_conditions(); auto *c = conditions->add_conditions(); c->set_type(pd::condition::VIP_LEVEL_GE); c->add_arg(to_string(ptt.level())); if (ptt.has_buy_box()) { modify_events_by_conditions(ptt.buy_box().conditions(), *ptt.mutable_buy_box()->mutable_events()); } }; vip_ptts_instance().verify_func_ = [] (const auto& ptt) { if (ptt.has_box()) { if (!verify_conditions(ptt.box().conditions())) { CONFIG_ELOG << ptt.level() << " verify box conditions failed"; } if (!verify_events(ptt.box().events())) { CONFIG_ELOG << ptt.level() << " verify box events failed"; } } }; } } }
#pragma once #include "aabb_able.h" namespace sbg { struct AABBBox : AABB_able { AABBBox() = default; AABBBox(const AABBBox&) = default; AABBBox(AABBBox&&) = default; AABBBox(std::pair<Vector2d, Vector2d> box); ~AABBBox() = default; void setBox(std::pair<Vector2d, Vector2d> box); std::pair<Vector2d, Vector2d> getBox() const; std::pair< Vector2d, Vector2d > getBoundingBox() const override; private: std::pair<Vector2d, Vector2d> _box; }; }
#ifndef function_h #define function_h #include <highgui.h> //#include <cxcore.h> #include <cv.h> #include "stdio.h" #include <queue> #include <atlbase.h> #include <cmath> #include "templeteclass.h" using namespace std; CvPoint2D32f originpoints[4]; //保存四个点的原始坐标 CvPoint2D32f newpoints[4]; //保存这四个点的新坐标 int cnt = 0;//透视变换边界点计数 bool flag = true;//标记:是否取过点 int num = 0;//路径点个数 int number = 0; CvPoint beginpoint, head, tail, center;//路径起点、小车头尾和中心 int headX, headY, tailX, tailY; IplImage* video; IplImage* transimg1 = cvCreateImage(cvSize(400, 400), IPL_DEPTH_8U, 3);//创建一个400*400的24位彩色图像,保存变换结果//感觉400*400太小? IplImage* transimg2 = cvCreateImage(cvSize(400, 400), 8, 1); IplImage* transimg3 = cvCreateImage(cvSize(400, 400), IPL_DEPTH_8U, 3);//保存追踪图像? //IplImage* temp = cvCreateImage(cvSize(400, 400), 8, 1);//transimg2的副本,没用到 IplImage* Convert = cvCreateImage(cvSize(400, 400), IPL_DEPTH_8U, 3);//追踪的时候用它~ IplImage* themap = cvCreateImage(cvSize(400, 400), 8, 3);//1.画出轨道路径点 CvMat* transmat = cvCreateMat(3, 3, CV_32FC1); //创建一个3*3的单通道32位浮点矩阵保存变换数据(透视变换时作为变换矩阵) int gothsv = 0;//选取车头车尾时用来计数 double hue[2], sat[2], val[2];//车头和车尾的hsv //手动确定透视变换边界点 void mouse0(int mouseevent, int x, int y, int flags, void*param)//发现该函数会不停的执行,不知道是否必要? { if ((mouseevent == CV_EVENT_LBUTTONDOWN) && (cnt < 4)) { cout << "选取的透视变换的第"<< cnt+1 <<"个点为(" << x << "," << y <<")"<< endl; originpoints[cnt].x = x; originpoints[cnt].y = y; ++cnt; } } CvPoint* point;//路径点 double distance2(int x1, int y1, int x2, int y2) { double tmp = (x1 - x2)*(x1 - x2) + (y1 - y2)*(y1 - y2); std::cout << tmp << std::endl; return tmp; } //细化处理 void cvThin(IplImage* src, IplImage* dst, int iterations) { cvCopyImage(src, dst); BwImage dstdat(dst); IplImage* t_image = cvCloneImage(src); BwImage t_dat(t_image); for (int n = 0; n < iterations; n++) for (int s = 0; s <= 1; s++) { cvCopyImage(dst, t_image); for (int i = 0; i < src->height; i++) for (int j = 0; j < src->width; j++) if (t_dat[i][j]) { int a = 0, b = 0; int d[8][2] = { { -1, 0 }, { -1, 1 }, { 0, 1 }, { 1, 1 }, { 1, 0 }, { 1, -1 }, { 0, -1 }, { -1, -1 } }; int p[8]; p[0] = (i == 0) ? 0 : t_dat[i - 1][j]; for (int k = 1; k <= 8; k++) { if (i + d[k % 8][0] < 0 || i + d[k % 8][0] >= src->height || j + d[k % 8][1] < 0 || j + d[k % 8][1] >= src->width) p[k % 8] = 0; else p[k % 8] = t_dat[i + d[k % 8][0]][j + d[k % 8][1]]; if (p[k % 8]) { b++; if (!p[k - 1]) a++; } } if (b >= 2 && b <= 6 && a == 1) if (!s && !(p[2] && p[4] && (p[0] || p[6]))) dstdat[i][j] = 0; else if (s && !(p[0] && p[6] && (p[2] || p[4]))) dstdat[i][j] = 0; } } cvReleaseImage(&t_image); } //霍夫变换//实际上没有用到 /* void Hough(IplImage* src, IplImage *dst) { CvMemStorage* storage = cvCreateMemStorage(); CvSeq* lines = cvHoughLines2(src, storage, CV_HOUGH_PROBABILISTIC, 1, CV_PI / 180, 30, 40, 40); //Hough变换找直线 cvSetZero(dst); for (int i = 0; i < lines->total; i++) { CvPoint* line = (CvPoint*)cvGetSeqElem(lines, i); cvLine(dst, line[0], line[1], cvScalar(255)); } } */ //获取两点距离的函数 int getDistance(CvPoint x, CvPoint y) { return sqrt(pow(x.x - y.x, 2) + pow(x.y - y.y, 2)); } /* //计算向量夹角的函数 double calculateSinAngle(CvPoint2D32f roadPointd, CvPoint2D32f roadPointf, int headX, int headY, int tailX, int tailY) { int road_x = roadPointd.x - roadPointf.x; int road_y = roadPointd.y - roadPointf.y; int car_x = headX - tailX; int car_y = headY - tailY; double carLength = sqrt(car_x*car_x + car_y*car_y); double roadLength = sqrt(road_x*road_x + road_y*road_y); double sinAngle = (car_x*road_y - car_y*road_x) / (carLength*roadLength); return(sinAngle); } double calculateCosAngle(CvPoint2D32f roadPointd, CvPoint2D32f roadPointf, int headX, int headY, int tailX, int tailY) { int road_x = roadPointd.x - roadPointf.x; int road_y = roadPointd.y - roadPointf.y; int car_x = headX - tailX; int car_y = headY - tailY; double carLength = sqrt(car_x*car_x + car_y*car_y); double roadLength = sqrt(road_x*road_x + road_y*road_y); double cosAngle = (car_x*road_x + car_y*road_y) / (carLength*roadLength); return(cosAngle); } */ //手动确定起点的函数 void mouse1(int mouseevent, int x, int y, int flags, void* param)// { if ((mouseevent == CV_EVENT_LBUTTONDOWN) && (number == 0)){ beginpoint = cvPoint(x, y); cvCircle(transimg2, beginpoint, 10, cvScalar(255), 3); cvShowImage("win2", transimg2); cout << "begin point is (" << beginpoint.x << "," << beginpoint.y << ")" << endl; number++; } } //选取车头车尾的函数 void mouse_gothsv(int mouseevent, int x, int y, int flags, void* param) { cvCvtColor(transimg3, Convert, CV_BGR2HSV);//把transimg3保存到Convert中,并从BGR空间转换到HSV空间,其实相当于凭空创建一个HSV空间的Convert RGBImage imgcol(Convert);// bgr 分别对应 hsv if (mouseevent == CV_EVENT_LBUTTONUP&& gothsv == 0) { //车头识别点选择 head.x = x; head.y = y; hue[0] = imgcol[head.y][head.x].b; sat[0] = imgcol[head.y][head.x].g; val[0] = imgcol[head.y][head.x].r; ++gothsv; } if (mouseevent == CV_EVENT_LBUTTONDOWN && gothsv == 1) { //车尾识别点选择 tail.x = x; tail.y = y; hue[1] = imgcol[tail.y][tail.x].b; sat[1] = imgcol[tail.y][tail.x].g; val[1] = imgcol[tail.y][tail.x].r; ++gothsv; } } #endif