text
stringlengths
8
6.88M
/* * main.cpp * Author: Ulises Olivares * uolivares@unam.mx * June 12, 2020 */ #include <iostream> #include <stdio.h> #include <stdlib.h> #include <string> #include "exploracion.h" //A* #include "tree.h" //Nodos #include "dijkstra.h" //Dijkstra #include "bell-ford.h" //Bellman-Ford #include <tclap/CmdLine.h> #include "raster.h" #include "distance.h" using namespace std; // Variable declaration struct points_export{ int x, y, xMin, xMax, yMin, yMax; }; // TODO: Evaluate which variables can be local and passed as argument instead of global. char is_usable; string map_biomass, map_friction, hName, region, map_npa, map_waterbodies; char algorithm, heuristic; int demanda, optValidation, gridsToValidate, exportPoints, rows = 0, cols = 0; // TODO: Use a common class for all structures Point2D centroid; float** biomass; float** friction; // Object definition Raster objRaster; // Create files to export info ofstream info, bestInfo, coords; string path, outPath; // Methods declaration void parseParameters(int argc, const char** argv); void runValidation4(); void runCommonValidation(CostDistance objDist, map<float,Grid> grids); int main(int argc, const char** argv){ //parse command-line parameters parseParameters(argc, argv); // Import biomass and friction cout << "-------------------------------------------------------"<< endl; cout << "Importing data ... " << endl; //FIXME: add a directive to detect OS and use a relative path path = "/Users/ulisesolivares2/Documents/GitHub/PowerPlantOptimization/src/input/"; // MACBOOK outPath = "/Users/ulisesolivares2/Documents/GitHub/PowerPlantOptimization/src/output/"; map_biomass = path + map_biomass; map_friction = path + map_friction; clock_t begin = clock(); // start timer // Import input maps biomass = objRaster.importRaster(map_biomass, true); friction = objRaster.importRaster(map_friction, false); // In case of a non-supported projection //cout << objRaster.epsg << endl; //objRaster.reproject_coords(map_biomass); clock_t end = clock(); rows = objRaster.getRows(); cols = objRaster.getCols(); double elapsed_secs = double(end - begin) / CLOCKS_PER_SEC; cout << "Total importation time: " << elapsed_secs << " secs." << endl; cout << "-------------------------------------------------------"<< endl; ostringstream ss, bestSs; ss << "centroids_" << demanda << "_" << hName << ".csv"; bestSs << "Exported_points.csv"; //string fileName = "puntos_" + stop + ".csv" info.open(ss.str().c_str()); info << "X, Y, Size, Biomass, Cost" << endl; bestInfo.open(bestSs.str().c_str()); // Verify if there is a map of Natural Protected Areas if(map_npa != "") { float** npa_matrix = objRaster.importRaster(map_npa, false); objRaster.check_npa(npa_matrix, biomass); } // Verify if there is a map of Water bodies if(map_waterbodies != "") { float** water_matrix = objRaster.importRaster(map_waterbodies, false); objRaster.check_waterbodies(water_matrix, biomass); } // Define the number of grids for each axis int sizeX = 0, sizeY = 0; objRaster.defineGridSize(demanda, sizeX, sizeY); map<float,Grid> grids; string validation; //really necessary? // CostDistance object CostDistance objDist(cols, rows); // Write in the CSV file switch(algorithm){ case 'a': bestInfo << "A*,"; break; case 't': bestInfo << "Depth Search"; break; } // write information to .CSV file bestInfo << demanda << "," << hName << "," << region << "," << validation << "," << gridsToValidate << "," << exportPoints << endl; // Obatain all girds in sorted by key summation(biomass / firction) grids = objRaster.defineGrids(rows, cols, sizeX, sizeY, biomass, friction); switch (optValidation){ case 1: // Run in the best grid gridsToValidate = 1; validation = "Best-candidate search"; runCommonValidation(objDist, grids); break; case 2: // Run the optimization algorithm for a set of grids gridsToValidate = objRaster.getTotalGrids(); validation = "Candidates where relation >= average validation"; runCommonValidation(objDist, grids); break; case 3: // Run the optimization algorithm for a custom number of grids validation = "Custom validation"; runCommonValidation(objDist, grids); break; case 4: // Global validation: Run all valid grids runValidation4(); break; } info.close(); bestInfo.close(); } void runValidation4(){ CostDistance objDist(cols, rows); float bestCost = 0, bestxMin, bestxMax, bestyMin, bestyMax; int bestX, bestY, cont = 1; for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { centroid.x = i; centroid.y = j; if (biomass[i][j] > 0) { cout << biomass[i][j] << endl; coords.open("coords.txt"); cout << "Power Plant index: " << centroid.x << ", " << centroid.y << endl; cout << "No. " << cont << " / " << objRaster.getValidPoints() << endl; coords << centroid.y << " " << centroid.x; coords.close(); objRaster.reproject_coords(map_biomass); clock_t begin_cd = clock(); objDist.inicio_cost_distance(friction, centroid.x, centroid.y, biomass, objRaster.getIntervals(), i - 80, i + 80, j - 80, j + 80, objRaster.getProjection()); clock_t end_cd = clock(); double elapsed_secs_cd = double(end_cd - begin_cd) / CLOCKS_PER_SEC; cout << "Cost Distance time = " << elapsed_secs_cd << " secs." << endl; switch(algorithm) { case 'B': //Binary search case 'b': { string algName = "Breadth_First_Search"; Tree rn; rn.COL = cols; rn.ROW = rows; clock_t begin2 = clock(); rn.inicio_rutas(biomass, objDist.getOutputRaster(), centroid.x, centroid.y, demanda, info, heuristic); clock_t end2 = clock(); double elapsed_secs2 = double(end2 - begin2) / CLOCKS_PER_SEC; cout << "Nodes time = " << elapsed_secs2 << " secs." << "\n\n"; if(rn.cost > bestCost) { bestCost = rn.cost; bestX = rn.x; bestY = rn.y; bestxMin = i - 50; bestxMax = i + 50; bestyMin = j - 50; bestyMax = j + 50; } objDist.freeMem(); rn.freeMem(); break; } case 'A': //A* search case 'a': { Explore e; string algName = "AStar"; e.COL = cols; e.ROW = rows; e.inicio(biomass); clock_t begin2 = clock(); e.explore(objDist.getOutputRaster(), centroid.x, centroid.y, demanda, info, heuristic); clock_t end2 = clock(); double elapsed_secs2 = double(end2 - begin2) / CLOCKS_PER_SEC; cout << "A* Search time = " << elapsed_secs2 << " secs." << endl; if(e.cost > bestCost) { bestCost = e.cost; bestX = e.X; bestY = e.Y; bestxMin = i - 50; bestxMax = i + 50; bestyMin = j - 50; bestyMax = j + 50; } e.freeMem(); objDist.freeMem(); break; } } cont++; } } } cout << "*** Best point ***" << endl; coords.open("coords.txt"); coords << bestY << " " << bestX; coords.close(); objRaster.reproject_coords(map_biomass); //cout << "Source = " << bestX << ", " << bestY << endl; bestInfo << bestX << ", " << bestY << ","; // FIXME: use a switch if(algorithm == 'a' || algorithm == 'A') { objDist.inicio_cost_distance(friction, bestX, bestY, biomass, objRaster.getIntervals(), bestxMin, bestxMax, bestyMin, bestyMax, objRaster.getProjection()); Explore e; string algName = "AStar"; e.COL = cols; e.ROW = rows; e.inicio(biomass); clock_t begin2 = clock(); e.explore(objDist.getOutputRaster(), bestX, bestY, demanda, bestInfo, heuristic); clock_t end2 = clock(); double elapsed_secs2 = double(end2 - begin2) / CLOCKS_PER_SEC; cout << "A* Search time = " << elapsed_secs2 << " secs." << endl; clock_t begin3 = clock(); objRaster.writeImage(e.matrix_path, rows, cols, hName, demanda, region, algName); objRaster.exportTiff(outPath, e.matrix_path, rows, cols, hName, demanda, region, algName); clock_t end3 = clock(); double elapsed_secs3 = double(end3 - begin3) / CLOCKS_PER_SEC; cout << "Creating the final route image took " << elapsed_secs3 << " secs." << endl; e.freeMem(); } else if(algorithm == 'b' || algorithm == 'B') { objDist.inicio_cost_distance(friction, bestX, bestY, biomass, objRaster.getIntervals(), bestxMin, bestxMax, bestyMin, bestyMax, objRaster.getProjection()); string algName = "Breadth_First_Search"; Tree rn; rn.COL = cols; rn.ROW = rows; clock_t begin2 = clock(); rn.inicio_rutas(biomass, objDist.getOutputRaster(), bestX, bestY, demanda, bestInfo, heuristic); clock_t end2 = clock(); double elapsed_secs2 = double(end2 - begin2) / CLOCKS_PER_SEC; cout << "Nodes time = " << elapsed_secs2 << " secs." << "\n\n"; clock_t begin3 = clock(); cout << "Image creation..." << endl; objRaster.writeImage(rn.matrix_path, rows, cols, hName, demanda, region, algName); objRaster.exportTiff(outPath, rn.matrix_path, rows, cols, hName, demanda, region, algName); clock_t end3 = clock(); double elapsed_secs3 = double(end3 - begin3) / CLOCKS_PER_SEC; cout << "Creating the final route image took " << elapsed_secs3 << " secs." << endl; rn.freeMem(); } } void runCommonValidation(CostDistance objDist, map<float,Grid> grids){ int count = 1; float bestCost = 0, bestxMin, bestxMax, bestyMin, bestyMax; int bestX, bestY; map <float, points_export> mapa_puntos; // TODO: Use a new method from here while(count <= gridsToValidate) { coords.open("coords.txt"); //cout << "\n\n" << endl; // TODO:Insert EM algorithm here objRaster.runEM(grids, biomass, friction, outPath); centroid = objRaster.findCentroid(grids, biomass, friction); if(!grids.empty()) grids.erase(--grids.end()); cout << "No. " << " / " << gridsToValidate << endl; //centroid.x = 49; centroid.y = 93; //cout << "Source = " << centroid.x << ", " << centroid.y << endl; info << centroid.x << ", " << centroid.y << ","; coords << centroid.y << " " << centroid.x; coords.close(); objRaster.reproject_coords(map_biomass); clock_t begin_cd = clock(); objDist.inicio_cost_distance(friction, centroid.x, centroid.y, biomass, objRaster.getIntervals(), objRaster.getXMin(), objRaster.getXMax(), objRaster.getYMin(), objRaster.getYMax(), objRaster.getProjection()); //cout << centroid.x << ", " << centroid.y << " - " << objRaster.getXMin() << " - " << objRaster.getXMax() << " - " << objRaster.getYMin() << " - " << objRaster.getYMax() << endl; //objDist.inicio_cost_distance(friction, centroid.x, centroid.y, biomass, objRaster.getIntervals(), 0, 498, 0, 256, objRaster.getProjection()); clock_t end_cd = clock(); double elapsed_secs_cd = double(end_cd - begin_cd) / CLOCKS_PER_SEC; cout << count << "Cost Distance time = " << elapsed_secs_cd << " secs." << endl; //objRaster.exportTiff(objDist.getOutputRaster(), rows, cols, "", 0, "", "cost_distance"); //exit(0); switch(algorithm) { case 'B': //Binary search case 'b': { string algName = "Breadth_First_Search"; Tree rn; rn.COL = cols; rn.ROW = rows; clock_t begin2 = clock(); if(optValidation == 1) { bestInfo << centroid.x << ", " << centroid.y << ","; rn.inicio_rutas(biomass, objDist.getOutputRaster(), centroid.x, centroid.y, demanda, bestInfo, heuristic); } else rn.inicio_rutas(biomass, objDist.getOutputRaster(), centroid.x, centroid.y, demanda, info, heuristic); clock_t end2 = clock(); double elapsed_secs2 = double(end2 - begin2) / CLOCKS_PER_SEC; cout << "Nodes time = " << elapsed_secs2 << " secs." << "\n\n"; if (optValidation == 1) { clock_t begin3 = clock(); cout << "---------------------------" << endl; cout << "Image creation..." << endl; objRaster.writeImage(rn.matrix_path, rows, cols, hName, demanda, region, algName); objRaster.exportTiff(outPath, rn.matrix_path, rows, cols, hName, demanda, region, algName); clock_t end3 = clock(); double elapsed_secs3 = double(end3 - begin3) / CLOCKS_PER_SEC; cout << "Creating the final route image took " << elapsed_secs3 << " secs." << endl; exit(0); } if(exportPoints == 1){ if(rn.cost > bestCost) { bestCost = rn.cost; bestX = rn.x; bestY = rn.y; bestxMin = objRaster.getXMin(); bestxMax = objRaster.getXMax(); bestyMin = objRaster.getYMin(); bestyMax = objRaster.getYMax(); } }else{ points_export pp; pp.x = centroid.x; pp.y = centroid.y; pp.xMin = objRaster.getXMin(); pp.xMax = objRaster.getXMax(); pp.yMin = objRaster.getYMin(); pp.yMax = objRaster.getYMax(); mapa_puntos.insert(make_pair(rn.cost, pp)); } objDist.freeMem(); rn.freeMem(); break; } case 'A': //A* search case 'a': { Explore e; string algName = "AStar"; e.COL = cols; e.ROW = rows; e.inicio(biomass); clock_t begin2 = clock(); if(optValidation == 1) { bestInfo << centroid.x << ", " << centroid.y << ","; e.explore(objDist.getOutputRaster(), centroid.x, centroid.y, demanda, bestInfo, heuristic); } else e.explore(objDist.getOutputRaster(), centroid.x, centroid.y, demanda, info, heuristic); clock_t end2 = clock(); double elapsed_secs2 = double(end2 - begin2) / CLOCKS_PER_SEC; cout << "A* Search time = " << elapsed_secs2 << " secs." << endl; if (optValidation == 1) { clock_t begin3 = clock(); //cout << "Tiff path: " << e.matrix_path << endl; objRaster.writeImage(e.matrix_path, rows, cols, hName, demanda, region, algName); objRaster.exportTiff(outPath, e.matrix_path, rows, cols, hName, demanda, region, algName); clock_t end3 = clock(); double elapsed_secs3 = double(end3 - begin3) / CLOCKS_PER_SEC; cout << "Creating the final route image took " << elapsed_secs3 << " secs." << endl; exit(0); } if(exportPoints == 1){ if(e.cost > bestCost) { bestCost = e.cost; bestX = e.X; bestY = e.Y; bestxMin = objRaster.getXMin(); bestxMax = objRaster.getXMax(); bestyMin = objRaster.getYMin(); bestyMax = objRaster.getYMax(); } }else{ points_export pp; pp.x = centroid.x; pp.y = centroid.y; pp.xMin = objRaster.getXMin(); pp.xMax = objRaster.getXMax(); pp.yMin = objRaster.getYMin(); pp.yMax = objRaster.getYMax(); mapa_puntos.insert(make_pair(e.cost, pp)); } e.freeMem(); objDist.freeMem(); break; } case 'D': //Dijkstra search case 'd': { Dijkstra objDijkstra; objDijkstra.COL = cols; objDijkstra.ROW = rows; clock_t begin2 = clock(); objDijkstra.initDijkstra(biomass, objDist.getOutputRaster(), centroid.x, centroid.y, demanda, heuristic); clock_t end2 = clock(); double elapsed_secs2 = double(end2 - begin2) / CLOCKS_PER_SEC; cout << "Dijkstra time = " << elapsed_secs2 << " secs." << endl; /*clock_t begin3 = clock(); objRaster.exportTiff(objDijkstra.matrix_path, rows, cols); clock_t end3 = clock(); double elapsed_secs3 = double(end3 - begin3) / CLOCKS_PER_SEC; cout << "Matrix to TIFF = " << elapsed_secs3 << endl;*/ break; } case 'F': //Bellman-Ford search case 'f': { BellmanFord bf; bf.COL = cols; bf.ROW = rows; clock_t begin2 = clock(); bf.bellford_start(biomass, objDist.getOutputRaster(), centroid.x, centroid.y, demanda, heuristic); clock_t end2 = clock(); double elapsed_secs2 = double(end2 - begin2) / CLOCKS_PER_SEC; cout << "Bellman-Ford time = " << elapsed_secs2 << " secs." << endl; /*clock_t begin3 = clock(); objRaster.exportTiff(bf.matrix_path, rows, cols); clock_t end3 = clock(); double elapsed_secs3 = double(end3 - begin3) / CLOCKS_PER_SEC; cout << "Matrix to TIFF = " << elapsed_secs3 << endl;*/ break; } default: exit(0); break; } count++; } map <float, points_export> :: reverse_iterator itr; int cont_puntos = 1; if(exportPoints == 1){ cout << "*** Best point ***" << endl; coords.open("coords.txt"); coords << bestY << " " << bestX; coords.close(); objRaster.reproject_coords(map_biomass); //cout << "Source = " << bestX << ", " << bestY << endl; bestInfo << bestX << ", " << bestY << ","; if(algorithm == 'a' || algorithm == 'A') { objDist.inicio_cost_distance(friction, bestX, bestY, biomass, objRaster.getIntervals(), bestxMin, bestxMax, bestyMin, bestyMax, objRaster.getProjection()); Explore e; string algName = "AStar"; e.COL = cols; e.ROW = rows; e.inicio(biomass); clock_t begin2 = clock(); e.explore(objDist.getOutputRaster(), bestX, bestY, demanda, bestInfo, heuristic); clock_t end2 = clock(); double elapsed_secs2 = double(end2 - begin2) / CLOCKS_PER_SEC; cout << "A* Search time = " << elapsed_secs2 << " secs." << endl; clock_t begin3 = clock(); objRaster.writeImage(e.matrix_path, rows, cols, hName, demanda, region, algName); objRaster.exportTiff(outPath, e.matrix_path, rows, cols, hName, demanda, region, algName); clock_t end3 = clock(); double elapsed_secs3 = double(end3 - begin3) / CLOCKS_PER_SEC; cout << "Creating the final route image took " << elapsed_secs3 << " secs." << endl; e.freeMem(); } else if(algorithm == 'b' || algorithm == 'B') { objDist.inicio_cost_distance(friction, bestX, bestY, biomass, objRaster.getIntervals(), bestxMin, bestxMax, bestyMin, bestyMax, objRaster.getProjection()); string algName = "Breadth_First_Search"; Tree rn; rn.COL = cols; rn.ROW = rows; clock_t begin2 = clock(); rn.inicio_rutas(biomass, objDist.getOutputRaster(), bestX, bestY, demanda, bestInfo, heuristic); clock_t end2 = clock(); double elapsed_secs2 = double(end2 - begin2) / CLOCKS_PER_SEC; cout << "Nodes time = " << elapsed_secs2 << " secs." << "\n\n"; clock_t begin3 = clock(); cout << "Image creation..." << endl; objRaster.writeImage(rn.matrix_path, rows, cols, hName, demanda, region, algName); objRaster.exportTiff(outPath, rn.matrix_path, rows, cols, hName, demanda, region, algName); clock_t end3 = clock(); double elapsed_secs3 = double(end3 - begin3) / CLOCKS_PER_SEC; cout << "Creating the final route image took " << elapsed_secs3 << " secs." << endl; rn.freeMem(); } }else{ for(itr = mapa_puntos.rbegin(); itr != mapa_puntos.rend(); itr++){ if(cont_puntos <= exportPoints){ cout << "Best points *** " << cont_puntos << "***" << endl; coords.open("coords.txt"); coords << itr->second.y << " " << itr->second.x; coords.close(); objRaster.reproject_coords(map_biomass); //cout << "Source = " << itr->second.x << ", " << itr->second.y << endl; bestInfo << itr->second.x << ", " << itr->second.y << ","; if(algorithm == 'a' || algorithm == 'A') { objDist.inicio_cost_distance(friction, itr->second.x, itr->second.y, biomass, objRaster.getIntervals(), itr->second.xMin, itr->second.xMax, itr->second.yMin, itr->second.yMax, objRaster.getProjection()); Explore e; stringstream s; s << cont_puntos << "_A_Star"; string algName = s.str(); e.COL = cols; e.ROW = rows; e.inicio(biomass); clock_t begin2 = clock(); e.explore(objDist.getOutputRaster(), itr->second.x, itr->second.y, demanda, bestInfo, heuristic); clock_t end2 = clock(); double elapsed_secs2 = double(end2 - begin2) / CLOCKS_PER_SEC; cout << "A* Search time = " << elapsed_secs2 << " secs." << endl; clock_t begin3 = clock(); objRaster.writeImage(e.matrix_path, rows, cols, hName, demanda, region, algName); objRaster.exportTiff(outPath, e.matrix_path, rows, cols, hName, demanda, region, algName); clock_t end3 = clock(); double elapsed_secs3 = double(end3 - begin3) / CLOCKS_PER_SEC; cout << "Creating the final route image took " << elapsed_secs3 << " secs." << endl; e.freeMem(); } else if(algorithm == 'b' || algorithm == 'B') { objDist.inicio_cost_distance(friction, itr->second.x, itr->second.y, biomass, objRaster.getIntervals(), itr->second.xMin, itr->second.xMax, itr->second.yMin, itr->second.yMax, objRaster.getProjection()); stringstream s; s << cont_puntos << "_Breadth_First_Search"; string algName = s.str(); Tree rn; rn.COL = cols; rn.ROW = rows; clock_t begin2 = clock(); rn.inicio_rutas(biomass, objDist.getOutputRaster(), itr->second.x, itr->second.y, demanda, bestInfo, heuristic); clock_t end2 = clock(); double elapsed_secs2 = double(end2 - begin2) / CLOCKS_PER_SEC; cout << "Nodes time = " << elapsed_secs2 << " secs." << "\n\n"; clock_t begin3 = clock(); cout << "Image creation..." << endl; objRaster.writeImage(rn.matrix_path, rows, cols, hName, demanda, region, algName); objRaster.exportTiff(outPath, rn.matrix_path, rows, cols, hName, demanda, region, algName); clock_t end3 = clock(); double elapsed_secs3 = double(end3 - begin3) / CLOCKS_PER_SEC; cout << "Creating the final route image took " << elapsed_secs3 << " secs." << endl; rn.freeMem(); } cont_puntos++; }else{ break; } } } } void parseParameters(int argc, const char** argv){ try { // Define the command line object, and insert a message // that describes the program. The "Command description message" // is printed last in the help text. The second argument is the // delimiter (usually space) and the last one is the version number. // The CmdLine object parses the argv array based on the Arg objects // that it contains. TCLAP::CmdLine cmd("Command description message", ' ', "1"); // Define a value argument and add it to the command line. // A value arg defines a flag and a type of value that it expects, // such as "-n Bishop". //TCLAP::ValueArg<std::string> nameArg("n","name","Name to print",true,"homer","string"); TCLAP::ValueArg<std::string> biomass("b","biomass","Absolute path to biomass_map.tif",true,"/path/to/image.tif","string"); TCLAP::ValueArg<std::string> friction("f","friction","Absolute path to friction_map.tif",true,"/path/to/image.tif","string"); TCLAP::ValueArg<std::string> algor("a","algorithm","Searching algorithm",true,"A","char"); TCLAP::ValueArg<std::string> stop("s","demand","Biomass demand",true,"5000","float"); TCLAP::ValueArg<std::string> watts("w","watts","Watts demand",true,"20","float"); TCLAP::ValueArg<std::string> humedad("i","humidity","Humidity content (%)",false,"40","float"); TCLAP::ValueArg<std::string> merma("l","loss","Percentage of expected loss in plant (%)",false,"30","float"); TCLAP::ValueArg<std::string> produccion("p","production","Annual percentage of production / operation of plant (%)",false,"20","float"); TCLAP::ValueArg<std::string> heur("u","heuristic","Searching heuristic",false,"d","char"); TCLAP::ValueArg<std::string> reg("r","region","Name of the region/country",false,"Haiti","string"); TCLAP::ValueArg<std::string> validation("v","validation","Validation option",true,"1","int"); TCLAP::ValueArg<std::string> grids_validate("g","gridsToValidate","Number of grids to validate",false,"50","int"); TCLAP::ValueArg<std::string> export_p("o","exportPoints","Export a number of points",false,"4","int"); TCLAP::ValueArg<std::string> npa("n","npa","Map of Natural Protected Areas (NPA)",false,"/path/to/npa_map.tif","int"); TCLAP::ValueArg<std::string> waterbody("m","waterbody","Map of Water bodies",false,"/path/to/water_bodies_map.tif","int"); TCLAP::ValueArg<std::string> usable("e","usable","Biomass' info represents usable biomass",true,"y/n","char"); // Add the argument nameArg to the CmdLine object. The CmdLine object // uses this Arg to parse the command line. cmd.xorAdd(stop, watts); cmd.add(biomass); cmd.add(friction); cmd.add(algor); cmd.add(heur); cmd.add(reg); cmd.add(validation); cmd.add(grids_validate); cmd.add(humedad); cmd.add(merma); cmd.add(produccion); cmd.add(export_p); cmd.add(npa); cmd.add(waterbody); cmd.add(usable); // Parse the argv array. cmd.parse( argc, argv ); // Get the value parsed by each arg. map_biomass = biomass.getValue(); map_friction = friction.getValue(); string algoritmo = algor.getValue(); algorithm = algoritmo[0]; string heuristic2 = heur.getValue(); heuristic = heuristic2[0]; region = reg.getValue(); string validacion = validation.getValue(); optValidation = atoi(validacion.c_str()); string grids_a_validar = grids_validate.getValue(); gridsToValidate = atoi(grids_a_validar.c_str()); string exp = export_p.getValue(); exportPoints = atoi(exp.c_str()); string demand; string usa = usable.getValue(); is_usable = usa[0]; if(optValidation > 4 || optValidation < 1) { cerr << "Please verify the validation option. (-v):\n 1 -- Best-candidate search.\n 2 -- Candidates where relation >= average validation.\n 3 -- Custom validation.\n 4 -- All-points validation." << endl; exit(0); } if(optValidation == 3 && !grids_validate.isSet()) { cerr << "Please indicate the number of grids to validate. (-g)." << endl; exit(0); } if(optValidation == 3 && gridsToValidate == 0) { cerr << "Please indicate a positive number of grids to validate. (-g)." << endl; exit(0); } if(optValidation == 2 || optValidation == 3){ if(export_p.isSet() && exportPoints <= 0){ cerr << "Please select a positive number for points to export. (-o)" << endl; exit(0); }else if(!export_p.isSet()){ exportPoints = 1; }else if(export_p.isSet() && exportPoints > gridsToValidate){ cerr << "Please select a number of points to export less than or equal to the number of grids to validate. (-o)" << endl; exit(0); } } else { exportPoints = 1; } if(!heur.isSet()) heuristic = 'x'; if(!grids_validate.isSet()) gridsToValidate = 1; if(npa.isSet()) map_npa = npa.getValue(); if(waterbody.isSet()) map_waterbodies = waterbody.getValue(); if ( stop.isSet() ){ demand = stop.getValue(); demanda = strtof(demand.c_str(),0); if (demanda <= 0) { cerr << "Biomass demand must be greater than 0 (-s)." << endl; exit(0); } } else if ( watts.isSet() ){ if(merma.isSet() && humedad.isSet() && produccion.isSet()){ demand = watts.getValue(); float w = strtof(demand.c_str(),0); if (w <= 0) { cerr << "Watts demand must be greater than 0 (-w)." << endl; exit(0); } string mer = merma.getValue(); string hum = humedad.getValue(); string prod = produccion.getValue(); float humidity = strtof(hum.c_str(), 0); float merm = strtof(mer.c_str(),0); float produ = strtof(prod.c_str(),0); float v1 = 1 - (humidity / 100), v2 = 1 - (merm / 100), v3 = (produ / 100); float hpa = 8760 * v3; float sp = w * hpa; float eb = sp / v2; float biomasa = eb / (5 * v1); demanda = biomasa; }else{ cerr << "Please verify that the following flags are set: -i [--humidity] -l [--loss] -p [--production]" << endl; exit(0); } } } catch (TCLAP::ArgException &e) // catch any exceptions { std::cerr << "error: " << e.error() << " for arg " << e.argId() << std::endl; } // Heuristic selection hName = "No_heuristic"; switch(heuristic){ case 'e': hName = "Euclidean"; break; case 'm': hName = "Manhattan"; break; case 'd': hName = "Diagonal"; break; case 'a': hName = "More_than_median"; break; case 'b': hName = "Best_2_nodes"; break; } }
#pragma once void initializer(const char* title) { // Just for fun std::cout << "Performing " << title << ".." << std::endl; } void swap(int &a, int &b) { // swap function int temp = a; a = b; b = temp; } void get_array(int arr[], int n) { // Get input from user for(int i = 0; i < n; i++) { std::cin >> arr[i]; } } void print(int arr[], int n) { // Print the array std::cout << "["; for (int i = 0; i < n; i++) { std::cout << arr[i]; if(i < n-1) { std::cout << ", "; } } std::cout << "]" << std::endl; }
// // Copyright Jason Rice 2016 // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // #ifndef NBDL_DETAIL_COMMON_TYPE_HPP #define NBDL_DETAIL_COMMON_TYPE_HPP #include<type_traits> namespace nbdl { namespace detail { // fixes bug in Xcodes outdated version of libc++ :( template<typename ...T> struct common_type { using type = typename std::common_type<T...>::type; }; template<> struct common_type<void, void> { using type = void; }; template<typename ...T> using common_type_t = typename nbdl::detail::common_type<T...>::type; } // detail } // nbdl #endif
/* this is the solution of beakjoon #1991 https://www.acmicpc.net/problem/1991 */ #include <iostream> using namespace std; int A[27][2]; void preorder(int x){ if(x==-1)return; cout<<(char)(x+'A'); preorder(A[x][0]); preorder(A[x][1]); } void inorder(int x){ if(x==-1)return; inorder(A[x][0]); cout<<(char)(x+'A'); inorder(A[x][1]); } void postorder(int x){ if(x==-1)return; postorder(A[x][0]); postorder(A[x][1]); cout<<(char)(x+'A'); } int main(){ int n; cin>>n; for(int i=0;i<n;i++){ char x,y,z; cin>>x>>y>>z; x=x-'A'; if(y=='.'){ A[x][0]=-1; }else{ A[x][0]=y-'A'; } if(z=='.'){ A[x][1]=-1; }else{ A[x][1]=z-'A'; } } preorder(0); cout<<'\n'; inorder(0); cout<<'\n'; postorder(0); cout<<'\n'; return 0; }
#include<bits/stdc++.h> const int maxN = 1e5+1; using namespace std; int ar[maxN]; pair<int,int>st[4*maxN]; pair<int,int> combine(pair<int,int> a,pair<int,int> b) { if(a.first<b.first) return a; if(b.first<a.first) return b; return {a.first,(a.second+b.second)}; } void buildtree(int si,int ss,int se) { if(ss==se) { st[si]={ar[ss],1}; return; } int mid=(ss+se)/2; buildtree(2*si,ss,mid); buildtree(2*si+1,mid+1,se); st[si]=combine(st[2*si],st[2*si+1]); } void update(int si,int ss,int se,int qi,int val) { if(ss==se) { st[si]={val,1}; return; } int mid=(ss+se)/2; if(qi<=mid) update(2*si,ss,mid,qi,val); else update(2*si+1,mid+1,se,qi,val); st[si]=combine(st[2*si],st[2*si+1]); } pair<int,int> query(int si,int ss,int se,int qs,int qe) { if(qs>qe)return {INT_MAX,0}; if(ss==qs &&se==qe) return st[si]; int mid=(ss+se)/2; return combine(query(2*si,ss,mid,qs,min(mid,qe)),query(2*si+1,mid+1,se,max(qs,mid+1),qe)); } int main() { ios_base::sync_with_stdio(false); cin.tie(0); int n,m,type,l,r; cin>>n>>m; for(int i=1;i<=n;i++) cin>>ar[i]; buildtree(1,1,n); while(m--) { cin>>type>>l>>r; if(type==1) { update(1,1,n,l+1,r); } else { pair<int,int> x=query(1,1,n,l+1,r); cout<<x.first<<" "<<x.second<<"\n"; } } }
// C++ for the Windows Runtime vv1.0.170303.6 // Copyright (c) 2017 Microsoft Corporation. All rights reserved. #pragma once #include "Windows.UI.Notifications.1.h" WINRT_EXPORT namespace winrt { namespace ABI::Windows::Foundation::Collections { #ifndef WINRT_GENERIC_b0d63b78_78ad_5e31_b6d8_e32a0e16c447 #define WINRT_GENERIC_b0d63b78_78ad_5e31_b6d8_e32a0e16c447 template <> struct __declspec(uuid("b0d63b78-78ad-5e31-b6d8-e32a0e16c447")) __declspec(novtable) IIterable<Windows::Foundation::Uri> : impl_IIterable<Windows::Foundation::Uri> {}; #endif #ifndef WINRT_GENERIC_ac7f26f2_feb7_5b2a_8ac4_345bc62caede #define WINRT_GENERIC_ac7f26f2_feb7_5b2a_8ac4_345bc62caede template <> struct __declspec(uuid("ac7f26f2-feb7-5b2a-8ac4-345bc62caede")) __declspec(novtable) IMapView<hstring, hstring> : impl_IMapView<hstring, hstring> {}; #endif } namespace ABI::Windows::Foundation { #ifndef WINRT_GENERIC_604d0c4c_91de_5c2a_935f_362f13eaf800 #define WINRT_GENERIC_604d0c4c_91de_5c2a_935f_362f13eaf800 template <> struct __declspec(uuid("604d0c4c-91de-5c2a-935f-362f13eaf800")) __declspec(novtable) IReference<Windows::Foundation::TimeSpan> : impl_IReference<Windows::Foundation::TimeSpan> {}; #endif #ifndef WINRT_GENERIC_5541d8a7_497c_5aa4_86fc_7713adbf2a2c #define WINRT_GENERIC_5541d8a7_497c_5aa4_86fc_7713adbf2a2c template <> struct __declspec(uuid("5541d8a7-497c-5aa4-86fc-7713adbf2a2c")) __declspec(novtable) IReference<Windows::Foundation::DateTime> : impl_IReference<Windows::Foundation::DateTime> {}; #endif } namespace ABI::Windows::Foundation::Collections { #ifndef WINRT_GENERIC_f6d1f700_49c2_52ae_8154_826f9908773c #define WINRT_GENERIC_f6d1f700_49c2_52ae_8154_826f9908773c template <> struct __declspec(uuid("f6d1f700-49c2-52ae-8154-826f9908773c")) __declspec(novtable) IMap<hstring, hstring> : impl_IMap<hstring, hstring> {}; #endif #ifndef WINRT_GENERIC_60310303_49c5_52e6_abc6_a9b36eccc716 #define WINRT_GENERIC_60310303_49c5_52e6_abc6_a9b36eccc716 template <> struct __declspec(uuid("60310303-49c5-52e6-abc6-a9b36eccc716")) __declspec(novtable) IKeyValuePair<hstring, hstring> : impl_IKeyValuePair<hstring, hstring> {}; #endif #ifndef WINRT_GENERIC_4b8385bd_a2cd_5ff1_bf74_7ea580423e50 #define WINRT_GENERIC_4b8385bd_a2cd_5ff1_bf74_7ea580423e50 template <> struct __declspec(uuid("4b8385bd-a2cd-5ff1-bf74-7ea580423e50")) __declspec(novtable) IVectorView<Windows::Foundation::Uri> : impl_IVectorView<Windows::Foundation::Uri> {}; #endif #ifndef WINRT_GENERIC_0d82bd8d_fe62_5d67_a7b9_7886dd75bc4e #define WINRT_GENERIC_0d82bd8d_fe62_5d67_a7b9_7886dd75bc4e template <> struct __declspec(uuid("0d82bd8d-fe62-5d67-a7b9-7886dd75bc4e")) __declspec(novtable) IVector<Windows::Foundation::Uri> : impl_IVector<Windows::Foundation::Uri> {}; #endif #ifndef WINRT_GENERIC_7f7d8ad7_b4d2_5a03_be6f_2b89875fb32d #define WINRT_GENERIC_7f7d8ad7_b4d2_5a03_be6f_2b89875fb32d template <> struct __declspec(uuid("7f7d8ad7-b4d2-5a03-be6f-2b89875fb32d")) __declspec(novtable) IVector<Windows::UI::Notifications::NotificationBinding> : impl_IVector<Windows::UI::Notifications::NotificationBinding> {}; #endif #ifndef WINRT_GENERIC_b60de92b_4e12_55af_b42f_afe2d70ba278 #define WINRT_GENERIC_b60de92b_4e12_55af_b42f_afe2d70ba278 template <> struct __declspec(uuid("b60de92b-4e12-55af-b42f-afe2d70ba278")) __declspec(novtable) IVectorView<Windows::UI::Notifications::AdaptiveNotificationText> : impl_IVectorView<Windows::UI::Notifications::AdaptiveNotificationText> {}; #endif #ifndef WINRT_GENERIC_4f729c64_a213_52e9_af8b_58adca3e597f #define WINRT_GENERIC_4f729c64_a213_52e9_af8b_58adca3e597f template <> struct __declspec(uuid("4f729c64-a213-52e9-af8b-58adca3e597f")) __declspec(novtable) IVectorView<Windows::UI::Notifications::ScheduledTileNotification> : impl_IVectorView<Windows::UI::Notifications::ScheduledTileNotification> {}; #endif #ifndef WINRT_GENERIC_ba0aff1f_6a8a_5a7e_a9f7_505b6266a436 #define WINRT_GENERIC_ba0aff1f_6a8a_5a7e_a9f7_505b6266a436 template <> struct __declspec(uuid("ba0aff1f-6a8a-5a7e-a9f7-505b6266a436")) __declspec(novtable) IVectorView<Windows::UI::Notifications::ScheduledToastNotification> : impl_IVectorView<Windows::UI::Notifications::ScheduledToastNotification> {}; #endif #ifndef WINRT_GENERIC_e09d090a_12e2_569b_ad29_fb0dfb98a1da #define WINRT_GENERIC_e09d090a_12e2_569b_ad29_fb0dfb98a1da template <> struct __declspec(uuid("e09d090a-12e2-569b-ad29-fb0dfb98a1da")) __declspec(novtable) IVectorView<Windows::UI::Notifications::ToastCollection> : impl_IVectorView<Windows::UI::Notifications::ToastCollection> {}; #endif } namespace ABI::Windows::Foundation { #ifndef WINRT_GENERIC_9310ec47_9f0a_5999_80c2_4b31e9f77e8e #define WINRT_GENERIC_9310ec47_9f0a_5999_80c2_4b31e9f77e8e template <> struct __declspec(uuid("9310ec47-9f0a-5999-80c2-4b31e9f77e8e")) __declspec(novtable) IAsyncOperation<Windows::UI::Notifications::ToastCollection> : impl_IAsyncOperation<Windows::UI::Notifications::ToastCollection> {}; #endif #ifndef WINRT_GENERIC_61c2402f_0ed0_5a18_ab69_59f4aa99a368 #define WINRT_GENERIC_61c2402f_0ed0_5a18_ab69_59f4aa99a368 template <> struct __declspec(uuid("61c2402f-0ed0-5a18-ab69-59f4aa99a368")) __declspec(novtable) TypedEventHandler<Windows::UI::Notifications::ToastNotification, Windows::UI::Notifications::ToastDismissedEventArgs> : impl_TypedEventHandler<Windows::UI::Notifications::ToastNotification, Windows::UI::Notifications::ToastDismissedEventArgs> {}; #endif #ifndef WINRT_GENERIC_ab54de2d_97d9_5528_b6ad_105afe156530 #define WINRT_GENERIC_ab54de2d_97d9_5528_b6ad_105afe156530 template <> struct __declspec(uuid("ab54de2d-97d9-5528-b6ad-105afe156530")) __declspec(novtable) TypedEventHandler<Windows::UI::Notifications::ToastNotification, Windows::Foundation::IInspectable> : impl_TypedEventHandler<Windows::UI::Notifications::ToastNotification, Windows::Foundation::IInspectable> {}; #endif #ifndef WINRT_GENERIC_95e3e803_c969_5e3a_9753_ea2ad22a9a33 #define WINRT_GENERIC_95e3e803_c969_5e3a_9753_ea2ad22a9a33 template <> struct __declspec(uuid("95e3e803-c969-5e3a-9753-ea2ad22a9a33")) __declspec(novtable) TypedEventHandler<Windows::UI::Notifications::ToastNotification, Windows::UI::Notifications::ToastFailedEventArgs> : impl_TypedEventHandler<Windows::UI::Notifications::ToastNotification, Windows::UI::Notifications::ToastFailedEventArgs> {}; #endif #ifndef WINRT_GENERIC_2dddc10e_38e6_5655_adf3_820e8fb14dcc #define WINRT_GENERIC_2dddc10e_38e6_5655_adf3_820e8fb14dcc template <> struct __declspec(uuid("2dddc10e-38e6-5655-adf3-820e8fb14dcc")) __declspec(novtable) IAsyncOperation<Windows::UI::Notifications::ToastNotifier> : impl_IAsyncOperation<Windows::UI::Notifications::ToastNotifier> {}; #endif #ifndef WINRT_GENERIC_2a22fecb_4b96_551f_b7b9_a7b5beecad05 #define WINRT_GENERIC_2a22fecb_4b96_551f_b7b9_a7b5beecad05 template <> struct __declspec(uuid("2a22fecb-4b96-551f-b7b9-a7b5beecad05")) __declspec(novtable) IAsyncOperation<Windows::UI::Notifications::ToastNotificationHistory> : impl_IAsyncOperation<Windows::UI::Notifications::ToastNotificationHistory> {}; #endif } namespace ABI::Windows::Foundation::Collections { #ifndef WINRT_GENERIC_a819f3de_60aa_5159_8407_f0a7fb1f6832 #define WINRT_GENERIC_a819f3de_60aa_5159_8407_f0a7fb1f6832 template <> struct __declspec(uuid("a819f3de-60aa-5159-8407-f0a7fb1f6832")) __declspec(novtable) IVectorView<Windows::UI::Notifications::ToastNotification> : impl_IVectorView<Windows::UI::Notifications::ToastNotification> {}; #endif #ifndef WINRT_GENERIC_1c157d0f_5efe_5cec_bbd6_0c6ce9af07a5 #define WINRT_GENERIC_1c157d0f_5efe_5cec_bbd6_0c6ce9af07a5 template <> struct __declspec(uuid("1c157d0f-5efe-5cec-bbd6-0c6ce9af07a5")) __declspec(novtable) IIterator<Windows::Foundation::Uri> : impl_IIterator<Windows::Foundation::Uri> {}; #endif #ifndef WINRT_GENERIC_66187f56_9ee1_5c48_82da_6cb9ddf879e7 #define WINRT_GENERIC_66187f56_9ee1_5c48_82da_6cb9ddf879e7 template <> struct __declspec(uuid("66187f56-9ee1-5c48-82da-6cb9ddf879e7")) __declspec(novtable) IIterator<Windows::UI::Notifications::NotificationBinding> : impl_IIterator<Windows::UI::Notifications::NotificationBinding> {}; #endif #ifndef WINRT_GENERIC_e8d9489c_635e_5153_8ab7_389f2ee9faca #define WINRT_GENERIC_e8d9489c_635e_5153_8ab7_389f2ee9faca template <> struct __declspec(uuid("e8d9489c-635e-5153-8ab7-389f2ee9faca")) __declspec(novtable) IIterable<Windows::UI::Notifications::NotificationBinding> : impl_IIterable<Windows::UI::Notifications::NotificationBinding> {}; #endif #ifndef WINRT_GENERIC_9e4d0240_6d5c_582a_a29d_734e84750738 #define WINRT_GENERIC_9e4d0240_6d5c_582a_a29d_734e84750738 template <> struct __declspec(uuid("9e4d0240-6d5c-582a-a29d-734e84750738")) __declspec(novtable) IVectorView<Windows::UI::Notifications::NotificationBinding> : impl_IVectorView<Windows::UI::Notifications::NotificationBinding> {}; #endif #ifndef WINRT_GENERIC_13cf8eab_bcf0_5f03_a79b_fafde70516f3 #define WINRT_GENERIC_13cf8eab_bcf0_5f03_a79b_fafde70516f3 template <> struct __declspec(uuid("13cf8eab-bcf0-5f03-a79b-fafde70516f3")) __declspec(novtable) IVector<Windows::UI::Notifications::AdaptiveNotificationText> : impl_IVector<Windows::UI::Notifications::AdaptiveNotificationText> {}; #endif #ifndef WINRT_GENERIC_18015daa_cbc3_5a51_9f4b_3c069135b0e0 #define WINRT_GENERIC_18015daa_cbc3_5a51_9f4b_3c069135b0e0 template <> struct __declspec(uuid("18015daa-cbc3-5a51-9f4b-3c069135b0e0")) __declspec(novtable) IIterator<Windows::UI::Notifications::AdaptiveNotificationText> : impl_IIterator<Windows::UI::Notifications::AdaptiveNotificationText> {}; #endif #ifndef WINRT_GENERIC_0343e8f2_ca4c_5f40_b8d1_3ff47047ce43 #define WINRT_GENERIC_0343e8f2_ca4c_5f40_b8d1_3ff47047ce43 template <> struct __declspec(uuid("0343e8f2-ca4c-5f40-b8d1-3ff47047ce43")) __declspec(novtable) IIterable<Windows::UI::Notifications::AdaptiveNotificationText> : impl_IIterable<Windows::UI::Notifications::AdaptiveNotificationText> {}; #endif #ifndef WINRT_GENERIC_69272d2c_74a5_5cd9_b2c5_51af99fcc732 #define WINRT_GENERIC_69272d2c_74a5_5cd9_b2c5_51af99fcc732 template <> struct __declspec(uuid("69272d2c-74a5-5cd9-b2c5-51af99fcc732")) __declspec(novtable) IVector<Windows::UI::Notifications::ScheduledTileNotification> : impl_IVector<Windows::UI::Notifications::ScheduledTileNotification> {}; #endif #ifndef WINRT_GENERIC_5665e491_6543_5036_935f_b5157950b359 #define WINRT_GENERIC_5665e491_6543_5036_935f_b5157950b359 template <> struct __declspec(uuid("5665e491-6543-5036-935f-b5157950b359")) __declspec(novtable) IIterator<Windows::UI::Notifications::ScheduledTileNotification> : impl_IIterator<Windows::UI::Notifications::ScheduledTileNotification> {}; #endif #ifndef WINRT_GENERIC_4b60d1e5_52ae_5766_9720_be4ad086f952 #define WINRT_GENERIC_4b60d1e5_52ae_5766_9720_be4ad086f952 template <> struct __declspec(uuid("4b60d1e5-52ae-5766-9720-be4ad086f952")) __declspec(novtable) IIterable<Windows::UI::Notifications::ScheduledTileNotification> : impl_IIterable<Windows::UI::Notifications::ScheduledTileNotification> {}; #endif #ifndef WINRT_GENERIC_693ec648_d35a_5be9_a9c1_ba334c337b83 #define WINRT_GENERIC_693ec648_d35a_5be9_a9c1_ba334c337b83 template <> struct __declspec(uuid("693ec648-d35a-5be9-a9c1-ba334c337b83")) __declspec(novtable) IVector<Windows::UI::Notifications::ScheduledToastNotification> : impl_IVector<Windows::UI::Notifications::ScheduledToastNotification> {}; #endif #ifndef WINRT_GENERIC_304238b6_888a_5dd2_96cd_bfca8927483b #define WINRT_GENERIC_304238b6_888a_5dd2_96cd_bfca8927483b template <> struct __declspec(uuid("304238b6-888a-5dd2-96cd-bfca8927483b")) __declspec(novtable) IIterator<Windows::UI::Notifications::ScheduledToastNotification> : impl_IIterator<Windows::UI::Notifications::ScheduledToastNotification> {}; #endif #ifndef WINRT_GENERIC_7a7b2a51_c182_5846_a861_4f9c036f24ad #define WINRT_GENERIC_7a7b2a51_c182_5846_a861_4f9c036f24ad template <> struct __declspec(uuid("7a7b2a51-c182-5846-a861-4f9c036f24ad")) __declspec(novtable) IIterable<Windows::UI::Notifications::ScheduledToastNotification> : impl_IIterable<Windows::UI::Notifications::ScheduledToastNotification> {}; #endif #ifndef WINRT_GENERIC_d0ee15ce_85f3_5ee1_8c83_e69bb60337da #define WINRT_GENERIC_d0ee15ce_85f3_5ee1_8c83_e69bb60337da template <> struct __declspec(uuid("d0ee15ce-85f3-5ee1-8c83-e69bb60337da")) __declspec(novtable) IVector<Windows::UI::Notifications::ToastCollection> : impl_IVector<Windows::UI::Notifications::ToastCollection> {}; #endif #ifndef WINRT_GENERIC_1512ed75_8c74_5520_ac88_134a1403f7ad #define WINRT_GENERIC_1512ed75_8c74_5520_ac88_134a1403f7ad template <> struct __declspec(uuid("1512ed75-8c74-5520-ac88-134a1403f7ad")) __declspec(novtable) IIterator<Windows::UI::Notifications::ToastCollection> : impl_IIterator<Windows::UI::Notifications::ToastCollection> {}; #endif #ifndef WINRT_GENERIC_8928d527_db5d_5a10_ae9b_430fa0906e74 #define WINRT_GENERIC_8928d527_db5d_5a10_ae9b_430fa0906e74 template <> struct __declspec(uuid("8928d527-db5d-5a10-ae9b-430fa0906e74")) __declspec(novtable) IIterable<Windows::UI::Notifications::ToastCollection> : impl_IIterable<Windows::UI::Notifications::ToastCollection> {}; #endif } namespace ABI::Windows::Foundation { #ifndef WINRT_GENERIC_8d44ca1e_15d7_5bcb_b002_384c87171c74 #define WINRT_GENERIC_8d44ca1e_15d7_5bcb_b002_384c87171c74 template <> struct __declspec(uuid("8d44ca1e-15d7-5bcb-b002-384c87171c74")) __declspec(novtable) AsyncOperationCompletedHandler<Windows::UI::Notifications::ToastCollection> : impl_AsyncOperationCompletedHandler<Windows::UI::Notifications::ToastCollection> {}; #endif #ifndef WINRT_GENERIC_fde26ed7_bc37_5a7c_b3da_3e41ac97bba4 #define WINRT_GENERIC_fde26ed7_bc37_5a7c_b3da_3e41ac97bba4 template <> struct __declspec(uuid("fde26ed7-bc37-5a7c-b3da-3e41ac97bba4")) __declspec(novtable) AsyncOperationCompletedHandler<Windows::UI::Notifications::ToastNotifier> : impl_AsyncOperationCompletedHandler<Windows::UI::Notifications::ToastNotifier> {}; #endif #ifndef WINRT_GENERIC_c661d5da_6762_5d93_9138_e7dacd571056 #define WINRT_GENERIC_c661d5da_6762_5d93_9138_e7dacd571056 template <> struct __declspec(uuid("c661d5da-6762-5d93-9138-e7dacd571056")) __declspec(novtable) AsyncOperationCompletedHandler<Windows::UI::Notifications::ToastNotificationHistory> : impl_AsyncOperationCompletedHandler<Windows::UI::Notifications::ToastNotificationHistory> {}; #endif } namespace ABI::Windows::Foundation::Collections { #ifndef WINRT_GENERIC_810f8c42_a267_5ba0_9538_48b9ecc433b8 #define WINRT_GENERIC_810f8c42_a267_5ba0_9538_48b9ecc433b8 template <> struct __declspec(uuid("810f8c42-a267-5ba0-9538-48b9ecc433b8")) __declspec(novtable) IVector<Windows::UI::Notifications::ToastNotification> : impl_IVector<Windows::UI::Notifications::ToastNotification> {}; #endif #ifndef WINRT_GENERIC_fe1e726a_3aa9_5d98_b19b_97e3e17eec7b #define WINRT_GENERIC_fe1e726a_3aa9_5d98_b19b_97e3e17eec7b template <> struct __declspec(uuid("fe1e726a-3aa9-5d98-b19b-97e3e17eec7b")) __declspec(novtable) IIterator<Windows::UI::Notifications::ToastNotification> : impl_IIterator<Windows::UI::Notifications::ToastNotification> {}; #endif #ifndef WINRT_GENERIC_52c9428b_d37a_554d_bf55_b8685d5f552d #define WINRT_GENERIC_52c9428b_d37a_554d_bf55_b8685d5f552d template <> struct __declspec(uuid("52c9428b-d37a-554d-bf55-b8685d5f552d")) __declspec(novtable) IIterable<Windows::UI::Notifications::ToastNotification> : impl_IIterable<Windows::UI::Notifications::ToastNotification> {}; #endif #ifndef WINRT_GENERIC_e9bdaaf0_cbf6_5c72_be90_29cbf3a1319b #define WINRT_GENERIC_e9bdaaf0_cbf6_5c72_be90_29cbf3a1319b template <> struct __declspec(uuid("e9bdaaf0-cbf6-5c72-be90-29cbf3a1319b")) __declspec(novtable) IIterable<Windows::Foundation::Collections::IKeyValuePair<hstring, hstring>> : impl_IIterable<Windows::Foundation::Collections::IKeyValuePair<hstring, hstring>> {}; #endif } namespace ABI::Windows::Foundation { #ifndef WINRT_GENERIC_34d4fa14_252b_5cb4_a7da_971ee5daec7c #define WINRT_GENERIC_34d4fa14_252b_5cb4_a7da_971ee5daec7c template <> struct __declspec(uuid("34d4fa14-252b-5cb4-a7da-971ee5daec7c")) __declspec(novtable) IAsyncOperation<Windows::Foundation::Collections::IVectorView<Windows::UI::Notifications::ToastCollection>> : impl_IAsyncOperation<Windows::Foundation::Collections::IVectorView<Windows::UI::Notifications::ToastCollection>> {}; #endif } namespace ABI::Windows::Foundation::Collections { #ifndef WINRT_GENERIC_05eb86f1_7140_5517_b88d_cbaebe57e6b1 #define WINRT_GENERIC_05eb86f1_7140_5517_b88d_cbaebe57e6b1 template <> struct __declspec(uuid("05eb86f1-7140-5517-b88d-cbaebe57e6b1")) __declspec(novtable) IIterator<Windows::Foundation::Collections::IKeyValuePair<hstring, hstring>> : impl_IIterator<Windows::Foundation::Collections::IKeyValuePair<hstring, hstring>> {}; #endif } namespace ABI::Windows::Foundation { #ifndef WINRT_GENERIC_4650e069_3052_530e_bc38_93c411773b77 #define WINRT_GENERIC_4650e069_3052_530e_bc38_93c411773b77 template <> struct __declspec(uuid("4650e069-3052-530e-bc38-93c411773b77")) __declspec(novtable) AsyncOperationCompletedHandler<Windows::Foundation::Collections::IVectorView<Windows::UI::Notifications::ToastCollection>> : impl_AsyncOperationCompletedHandler<Windows::Foundation::Collections::IVectorView<Windows::UI::Notifications::ToastCollection>> {}; #endif } namespace Windows::UI::Notifications { struct IAdaptiveNotificationContent : Windows::Foundation::IInspectable, impl::consume<IAdaptiveNotificationContent> { IAdaptiveNotificationContent(std::nullptr_t = nullptr) noexcept {} }; struct IAdaptiveNotificationText : Windows::Foundation::IInspectable, impl::consume<IAdaptiveNotificationText>, impl::require<IAdaptiveNotificationText, Windows::UI::Notifications::IAdaptiveNotificationContent> { IAdaptiveNotificationText(std::nullptr_t = nullptr) noexcept {} }; struct IBadgeNotification : Windows::Foundation::IInspectable, impl::consume<IBadgeNotification> { IBadgeNotification(std::nullptr_t = nullptr) noexcept {} }; struct IBadgeNotificationFactory : Windows::Foundation::IInspectable, impl::consume<IBadgeNotificationFactory> { IBadgeNotificationFactory(std::nullptr_t = nullptr) noexcept {} }; struct IBadgeUpdateManagerForUser : Windows::Foundation::IInspectable, impl::consume<IBadgeUpdateManagerForUser> { IBadgeUpdateManagerForUser(std::nullptr_t = nullptr) noexcept {} }; struct IBadgeUpdateManagerStatics : Windows::Foundation::IInspectable, impl::consume<IBadgeUpdateManagerStatics> { IBadgeUpdateManagerStatics(std::nullptr_t = nullptr) noexcept {} }; struct IBadgeUpdateManagerStatics2 : Windows::Foundation::IInspectable, impl::consume<IBadgeUpdateManagerStatics2> { IBadgeUpdateManagerStatics2(std::nullptr_t = nullptr) noexcept {} }; struct IBadgeUpdater : Windows::Foundation::IInspectable, impl::consume<IBadgeUpdater> { IBadgeUpdater(std::nullptr_t = nullptr) noexcept {} }; struct IKnownAdaptiveNotificationHintsStatics : Windows::Foundation::IInspectable, impl::consume<IKnownAdaptiveNotificationHintsStatics> { IKnownAdaptiveNotificationHintsStatics(std::nullptr_t = nullptr) noexcept {} }; struct IKnownAdaptiveNotificationTextStylesStatics : Windows::Foundation::IInspectable, impl::consume<IKnownAdaptiveNotificationTextStylesStatics> { IKnownAdaptiveNotificationTextStylesStatics(std::nullptr_t = nullptr) noexcept {} }; struct IKnownNotificationBindingsStatics : Windows::Foundation::IInspectable, impl::consume<IKnownNotificationBindingsStatics> { IKnownNotificationBindingsStatics(std::nullptr_t = nullptr) noexcept {} }; struct INotification : Windows::Foundation::IInspectable, impl::consume<INotification> { INotification(std::nullptr_t = nullptr) noexcept {} }; struct INotificationBinding : Windows::Foundation::IInspectable, impl::consume<INotificationBinding> { INotificationBinding(std::nullptr_t = nullptr) noexcept {} }; struct INotificationData : Windows::Foundation::IInspectable, impl::consume<INotificationData> { INotificationData(std::nullptr_t = nullptr) noexcept {} }; struct INotificationDataFactory : Windows::Foundation::IInspectable, impl::consume<INotificationDataFactory> { INotificationDataFactory(std::nullptr_t = nullptr) noexcept {} }; struct INotificationVisual : Windows::Foundation::IInspectable, impl::consume<INotificationVisual> { INotificationVisual(std::nullptr_t = nullptr) noexcept {} }; struct IScheduledTileNotification : Windows::Foundation::IInspectable, impl::consume<IScheduledTileNotification> { IScheduledTileNotification(std::nullptr_t = nullptr) noexcept {} }; struct IScheduledTileNotificationFactory : Windows::Foundation::IInspectable, impl::consume<IScheduledTileNotificationFactory> { IScheduledTileNotificationFactory(std::nullptr_t = nullptr) noexcept {} }; struct IScheduledToastNotification : Windows::Foundation::IInspectable, impl::consume<IScheduledToastNotification> { IScheduledToastNotification(std::nullptr_t = nullptr) noexcept {} }; struct IScheduledToastNotification2 : Windows::Foundation::IInspectable, impl::consume<IScheduledToastNotification2> { IScheduledToastNotification2(std::nullptr_t = nullptr) noexcept {} }; struct IScheduledToastNotification3 : Windows::Foundation::IInspectable, impl::consume<IScheduledToastNotification3> { IScheduledToastNotification3(std::nullptr_t = nullptr) noexcept {} }; struct IScheduledToastNotificationFactory : Windows::Foundation::IInspectable, impl::consume<IScheduledToastNotificationFactory> { IScheduledToastNotificationFactory(std::nullptr_t = nullptr) noexcept {} }; struct IShownTileNotification : Windows::Foundation::IInspectable, impl::consume<IShownTileNotification> { IShownTileNotification(std::nullptr_t = nullptr) noexcept {} }; struct ITileFlyoutNotification : Windows::Foundation::IInspectable, impl::consume<ITileFlyoutNotification> { ITileFlyoutNotification(std::nullptr_t = nullptr) noexcept {} }; struct ITileFlyoutNotificationFactory : Windows::Foundation::IInspectable, impl::consume<ITileFlyoutNotificationFactory> { ITileFlyoutNotificationFactory(std::nullptr_t = nullptr) noexcept {} }; struct ITileFlyoutUpdateManagerStatics : Windows::Foundation::IInspectable, impl::consume<ITileFlyoutUpdateManagerStatics> { ITileFlyoutUpdateManagerStatics(std::nullptr_t = nullptr) noexcept {} }; struct ITileFlyoutUpdater : Windows::Foundation::IInspectable, impl::consume<ITileFlyoutUpdater> { ITileFlyoutUpdater(std::nullptr_t = nullptr) noexcept {} }; struct ITileNotification : Windows::Foundation::IInspectable, impl::consume<ITileNotification> { ITileNotification(std::nullptr_t = nullptr) noexcept {} }; struct ITileNotificationFactory : Windows::Foundation::IInspectable, impl::consume<ITileNotificationFactory> { ITileNotificationFactory(std::nullptr_t = nullptr) noexcept {} }; struct ITileUpdateManagerForUser : Windows::Foundation::IInspectable, impl::consume<ITileUpdateManagerForUser> { ITileUpdateManagerForUser(std::nullptr_t = nullptr) noexcept {} }; struct ITileUpdateManagerStatics : Windows::Foundation::IInspectable, impl::consume<ITileUpdateManagerStatics> { ITileUpdateManagerStatics(std::nullptr_t = nullptr) noexcept {} }; struct ITileUpdateManagerStatics2 : Windows::Foundation::IInspectable, impl::consume<ITileUpdateManagerStatics2> { ITileUpdateManagerStatics2(std::nullptr_t = nullptr) noexcept {} }; struct ITileUpdater : Windows::Foundation::IInspectable, impl::consume<ITileUpdater> { ITileUpdater(std::nullptr_t = nullptr) noexcept {} }; struct ITileUpdater2 : Windows::Foundation::IInspectable, impl::consume<ITileUpdater2> { ITileUpdater2(std::nullptr_t = nullptr) noexcept {} }; struct IToastActivatedEventArgs : Windows::Foundation::IInspectable, impl::consume<IToastActivatedEventArgs> { IToastActivatedEventArgs(std::nullptr_t = nullptr) noexcept {} }; struct IToastCollection : Windows::Foundation::IInspectable, impl::consume<IToastCollection> { IToastCollection(std::nullptr_t = nullptr) noexcept {} }; struct IToastCollectionFactory : Windows::Foundation::IInspectable, impl::consume<IToastCollectionFactory> { IToastCollectionFactory(std::nullptr_t = nullptr) noexcept {} }; struct IToastCollectionManager : Windows::Foundation::IInspectable, impl::consume<IToastCollectionManager> { IToastCollectionManager(std::nullptr_t = nullptr) noexcept {} }; struct IToastDismissedEventArgs : Windows::Foundation::IInspectable, impl::consume<IToastDismissedEventArgs> { IToastDismissedEventArgs(std::nullptr_t = nullptr) noexcept {} }; struct IToastFailedEventArgs : Windows::Foundation::IInspectable, impl::consume<IToastFailedEventArgs> { IToastFailedEventArgs(std::nullptr_t = nullptr) noexcept {} }; struct IToastNotification : Windows::Foundation::IInspectable, impl::consume<IToastNotification> { IToastNotification(std::nullptr_t = nullptr) noexcept {} }; struct IToastNotification2 : Windows::Foundation::IInspectable, impl::consume<IToastNotification2> { IToastNotification2(std::nullptr_t = nullptr) noexcept {} }; struct IToastNotification3 : Windows::Foundation::IInspectable, impl::consume<IToastNotification3> { IToastNotification3(std::nullptr_t = nullptr) noexcept {} }; struct IToastNotification4 : Windows::Foundation::IInspectable, impl::consume<IToastNotification4> { IToastNotification4(std::nullptr_t = nullptr) noexcept {} }; struct IToastNotificationActionTriggerDetail : Windows::Foundation::IInspectable, impl::consume<IToastNotificationActionTriggerDetail> { IToastNotificationActionTriggerDetail(std::nullptr_t = nullptr) noexcept {} }; struct IToastNotificationFactory : Windows::Foundation::IInspectable, impl::consume<IToastNotificationFactory> { IToastNotificationFactory(std::nullptr_t = nullptr) noexcept {} }; struct IToastNotificationHistory : Windows::Foundation::IInspectable, impl::consume<IToastNotificationHistory> { IToastNotificationHistory(std::nullptr_t = nullptr) noexcept {} }; struct IToastNotificationHistory2 : Windows::Foundation::IInspectable, impl::consume<IToastNotificationHistory2> { IToastNotificationHistory2(std::nullptr_t = nullptr) noexcept {} }; struct IToastNotificationHistoryChangedTriggerDetail : Windows::Foundation::IInspectable, impl::consume<IToastNotificationHistoryChangedTriggerDetail> { IToastNotificationHistoryChangedTriggerDetail(std::nullptr_t = nullptr) noexcept {} }; struct IToastNotificationHistoryChangedTriggerDetail2 : Windows::Foundation::IInspectable, impl::consume<IToastNotificationHistoryChangedTriggerDetail2> { IToastNotificationHistoryChangedTriggerDetail2(std::nullptr_t = nullptr) noexcept {} }; struct IToastNotificationManagerForUser : Windows::Foundation::IInspectable, impl::consume<IToastNotificationManagerForUser> { IToastNotificationManagerForUser(std::nullptr_t = nullptr) noexcept {} }; struct IToastNotificationManagerForUser2 : Windows::Foundation::IInspectable, impl::consume<IToastNotificationManagerForUser2> { IToastNotificationManagerForUser2(std::nullptr_t = nullptr) noexcept {} }; struct IToastNotificationManagerStatics : Windows::Foundation::IInspectable, impl::consume<IToastNotificationManagerStatics> { IToastNotificationManagerStatics(std::nullptr_t = nullptr) noexcept {} }; struct IToastNotificationManagerStatics2 : Windows::Foundation::IInspectable, impl::consume<IToastNotificationManagerStatics2> { IToastNotificationManagerStatics2(std::nullptr_t = nullptr) noexcept {} }; struct IToastNotificationManagerStatics4 : Windows::Foundation::IInspectable, impl::consume<IToastNotificationManagerStatics4> { IToastNotificationManagerStatics4(std::nullptr_t = nullptr) noexcept {} }; struct IToastNotificationManagerStatics5 : Windows::Foundation::IInspectable, impl::consume<IToastNotificationManagerStatics5> { IToastNotificationManagerStatics5(std::nullptr_t = nullptr) noexcept {} }; struct IToastNotifier : Windows::Foundation::IInspectable, impl::consume<IToastNotifier> { IToastNotifier(std::nullptr_t = nullptr) noexcept {} }; struct IToastNotifier2 : Windows::Foundation::IInspectable, impl::consume<IToastNotifier2> { IToastNotifier2(std::nullptr_t = nullptr) noexcept {} }; struct IUserNotification : Windows::Foundation::IInspectable, impl::consume<IUserNotification> { IUserNotification(std::nullptr_t = nullptr) noexcept {} }; struct IUserNotificationChangedEventArgs : Windows::Foundation::IInspectable, impl::consume<IUserNotificationChangedEventArgs> { IUserNotificationChangedEventArgs(std::nullptr_t = nullptr) noexcept {} }; } }
#include<stdio.h> #include<malloc.h> struct node{ int data; struct node *next; }; int push(struct node **,int); int printList(struct node *); int NodeFromLast(struct node *,int); int push(struct node **head_ref,int new_data){ struct node *temp=(struct node *)malloc(sizeof(struct node )); temp->data=new_data; temp->next=*head_ref; *head_ref=temp; } int NodeFromLast(struct node *head,int n){ struct node *temp=head; int len =0; while(temp!=NULL){ temp=temp->next; len++; } if(len<n) return 0; temp=head; for(int i=1;i<len-n+1;i++) temp=temp->next; printf("%d",temp->data); } int main(){ struct node *head=NULL; push(&head,2); push(&head,12); push(&head,4); push(&head,6); push(&head,8); push(&head,9); push(&head,7); printList(head); printf("\n......."); NodeFromLast(head,5); printf("\n"); printList(head); return 0; } int printList(struct node *head){ while(head!=NULL){ printf(" %d ",head->data); head=head->next; } }
/* vim:tabstop=4:expandtab:shiftwidth=4 * * Idesk -- Timer.h * * Copyright (c) 2005, FixXxeR (avelar@gmail.com) * based from Timer.cc (vdesk project) by MrChuoi <mrchuoi at yahoo dot com> * 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 the <ORGANIZATION> nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * (See the included file COPYING / BSD ) */ #ifndef TIMER_CLASS #define TIMER_CLASS #include <time.h> #include "XDesktopContainer.h" #include <fcntl.h> class TimerControl { private: long start; long delay; public: void SetDelay( long d ) { delay = d; start = time(0); } long GetDelay( long n ) { return start + delay - n; } void Finish() { start = delay;} long Reset() { start = time(0); return delay; } virtual bool IsOneShot() { return true; } virtual void OnTime() = 0; }; class Timer{ private: static vector<TimerControl*> items; AbstractContainer * container; int c; public: Timer(AbstractContainer * con); void Update(); public: static void Add( TimerControl *t, long d ); static void Remove( TimerControl *t ); }; #endif
//udppeer_test.cpp #include <iostream> #include <chrono> #include <sys/socket.h> #include <arpa/inet.h> #include <string.h> #include <unistd.h> using namespace std; int main(int argc, char** argv) { if(argc < 2){ cout<<"usage: cmd [local port]\n"; return 0; } int port = atoi(argv[1]); sockaddr_in addr; memset(&addr, 0, sizeof(addr)); addr.sin_family = AF_INET; addr.sin_addr.s_addr = INADDR_ANY; addr.sin_port = htons(port); int fd = socket(AF_INET, SOCK_DGRAM, 0); if(fd == -1 ){ perror("socket"); return 0; } if( bind(fd, (sockaddr*)&addr, sizeof(addr)) == -1){ perror("bind"); return 0; } sockaddr_in inaddr; ::memset(&inaddr, 0, sizeof(inaddr)); socklen_t naddr=sizeof(inaddr); char buf[24]={0}; int size=2; int n=5000000; auto t1=chrono::high_resolution_clock::now(); for(int i=0; i<n; i++){ recvfrom(fd, buf, size, 0, (sockaddr*)&inaddr, &naddr); //read(fd, buf, size); } auto t2=chrono::high_resolution_clock::now(); auto d=t2-t1; auto dms=chrono::duration_cast<chrono::milliseconds>(d); long ms = dms.count(); cout<<"took:"<<ms<<"ms\n"; cout<<n/ms*1000<<" times call per second\n"; return 0; }
/********************************************************** * License: The MIT License * https://www.github.com/doc97/TxtAdv/blob/master/LICENSE **********************************************************/ #include "catch.hpp" #include "ResponseMatch.h" namespace txt { TEST_CASE("ResponseMatch - isMatch", "[ResponseMatch]") { SECTION("boolean constructor") { ResponseMatch match(true); REQUIRE(match.IsMatch()); match = ResponseMatch(false); REQUIRE(!match.IsMatch()); } SECTION("boolean & capture constructor") { ResponseMatch match(true, {}); REQUIRE(match.IsMatch()); match = ResponseMatch(false, {}); REQUIRE(!match.IsMatch()); } } TEST_CASE("ResponseMatch - captures", "[ResponseMatch]") { ResponseMatch match(true, {}); REQUIRE(match.CaptureCount() == 0); match = ResponseMatch(true, { "a" }); REQUIRE(match.CaptureCount() == 1); REQUIRE(match.GetCapture(0) == "a"); match = ResponseMatch(true, { "b", "c" }); REQUIRE(match.CaptureCount() == 2); REQUIRE(match.GetCapture(0) == "b"); REQUIRE(match.GetCapture(1) == "c"); try { match.GetCapture(2); FAIL("Accessing with out-of-range index should throw std::out_of_range"); } catch (std::out_of_range) {} } } // namespace txt
#include "stdafx.h" #include "Resource.h" #include <iostream> #include <string> using std::string; using std::cout; using std::endl; Resource::Resource(std::string name):name(name) { cout << "constructor resourse " << name << endl; } Resource::~Resource() { cout << "destructor resourse " << name << endl; }
#include "include/photocell.h" void photocellInitial(Chain *ptrchain){ sensorPin[0]= ptrchain->sensorPin.sensorLeftPin; sensorPin[1]= ptrchain->sensorPin.sensorRightPin; waitUpThre = ptrchain->waitUpThre; sensorRange[0]= ptrchain->sensorRange.left; sensorRange[1]= ptrchain->sensorRange.right; } boolean waitUp(){ boolean result = false; int readingLeft, readingRight; readingLeft = analogRead(sensorPin[0]); readingRight = analogRead(sensorPin[1]); if((readingLeft>waitUpThre)||(readingRight>waitUpThre)) result=true; return result; } int cellResult(){ int readingLeft, readingRight, angle; readingLeft = analogRead(sensorPin[0]); readingRight = analogRead(sensorPin[1]); angle = map(readingRight-readingLeft, sensorRange[0], sensorRange[1], 0, 179); return angle; }
#include<bits/stdc++.h> #define int long long using namespace std; signed main() { int T; cin >> T; while(T--) { int n, k; scanf("%lld%lld",&n,&k); if(n-k>=2) printf("No\n"); else printf("Yes\n"); } }
#include<bits/stdc++.h> using namespace std; struct node { int data; int count = 0; struct node* left = NULL; struct node* right = NULL; }; typedef struct node Node; Node* newnode(int data) { Node* temp = new Node(); temp->data=data; return temp; } int insert(Node*& root,int data) { if(root==NULL) { root = newnode(data); return 0; } if(data > root->data) { //right and cur root is less than me root->count+=1; return insert(root->right,data); } else { //left and cur root is greater than me and it is left to me // all its count(greater than it will so be greater than cur) return root->count+1+insert(root->left,data); } return -1; } int main() { int n; cin >> n; Node* root = NULL; int* arr = new int[n]; int* count = new int[n](); for(int i=0;i<n;i++) { cin >> arr[i]; } for(int i=0;i<n;i++) { count[i]=insert(root,arr[i]); } for(int i=0;i<n;i++) { cout << count[i] << " "; } cout << endl; return 0; }
#pragma once #include <functional> #include <map> #include <queue> #include <vector> #include <memory> #include "messaging/Messages.hpp" namespace cobalt { namespace messaging { typedef std::shared_ptr<Message> MessagePtr; typedef std::function<void(MessagePtr)> Subscriber; class MessageBus { public: MessageBus(); void addSubscriber(MessageID msgID, Subscriber subscriber); void sendMessage(MessagePtr msg); void notify(); private: std::map<MessageID, std::vector<Subscriber>> m_subscribers; std::map<MessageID, std::queue<MessagePtr>> m_unsentMessages; }; }; };
// MyAccountDlg.cpp : implementation file // #include "stdafx.h" #include "MyAccount.h" #include "MyAccountDlg.h" #include "afxdialogex.h" #include "MyDlg.h" #include "DialogModify.h" #ifdef _DEBUG #define new DEBUG_NEW #endif // CAboutDlg dialog used for App About class CAboutDlg : public CDialog { public: CAboutDlg(); // Dialog Data enum { IDD = IDD_ABOUTBOX }; protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support // Implementation protected: DECLARE_MESSAGE_MAP() }; CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD) { } void CAboutDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); } BEGIN_MESSAGE_MAP(CAboutDlg, CDialog) END_MESSAGE_MAP() // CMyAccountDlg dialog CMyAccountDlg::CMyAccountDlg(CWnd* pParent /*=NULL*/) : CDialog(CMyAccountDlg::IDD, pParent) { m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME); } void CMyAccountDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); DDX_Control(pDX, IDC_COMBO1, m_ComboBox); DDX_Control(pDX, IDC_EDIT1, m_EditUserName); DDX_Control(pDX, IDC_EDIT2, m_EditPassword); } BEGIN_MESSAGE_MAP(CMyAccountDlg, CDialog) ON_WM_SYSCOMMAND() ON_WM_PAINT() ON_WM_QUERYDRAGICON() ON_CBN_SELCHANGE(IDC_COMBO1, &CMyAccountDlg::OnCbnSelchangeCombo1) ON_BN_CLICKED(IDOK, &CMyAccountDlg::OnBnClickedOk) ON_BN_CLICKED(IDC_Deleate, &CMyAccountDlg::OnBnClickedDeleate) ON_BN_CLICKED(IDCANCEL, &CMyAccountDlg::OnBnClickedCancel) ON_BN_CLICKED(IDC_BUTTON1, &CMyAccountDlg::OnBnClickedButton1) END_MESSAGE_MAP() // CMyAccountDlg message handlers BOOL CMyAccountDlg::OnInitDialog() { CDialog::OnInitDialog(); // Add "About..." menu item to system menu. // IDM_ABOUTBOX must be in the system command range. ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX); ASSERT(IDM_ABOUTBOX < 0xF000); CMenu* pSysMenu = GetSystemMenu(FALSE); if (pSysMenu != NULL) { BOOL bNameValid; CString strAboutMenu; bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX); ASSERT(bNameValid); if (!strAboutMenu.IsEmpty()) { pSysMenu->AppendMenu(MF_SEPARATOR); pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu); } } // Set the icon for this dialog. The framework does this automatically // when the application's main window is not a dialog SetIcon(m_hIcon, TRUE); // Set big icon SetIcon(m_hIcon, FALSE); // Set small icon // TODO: Add extra initialization here ((CEdit*)m_ComboBox.GetWindow(GW_CHILD))->SetReadOnly(); //Creat directory TCHAR* pszDirectoryName = _T("C:\\Program Files\\MyAccount"); if (!(GetFileAttributes(pszDirectoryName) == FILE_ATTRIBUTE_DIRECTORY)) { if (!CreateDirectory(pszDirectoryName, NULL)) { MessageBox(_T("Make Dir Error")); } } //Creat file TCHAR* pszFileName = _T("C:\\Program Files\\MyAccount\\account.dat"); if (!theApp.f.Open(pszFileName, CFile::modeCreate | CFile::modeNoTruncate | CFile::modeReadWrite)) { MessageBox(_T("Make File Error")); } CString strLine; CString all; int num_Vaild = 0; CString accountInfo[3]; theApp.f.SeekToBegin(); while (theApp.f.ReadString(strLine)) { if (num_Vaild%3 == 0) m_ComboBox.AddString(strLine); num_Vaild++; if (theApp.nstrLine < 3) { accountInfo[theApp.nstrLine++] = strLine; } //MessageBoxW(strLine); } theApp.f.Close(); //Clear flag theApp.nstrLine = 0; //Combo box m_ComboBox.SetCurSel(0); //Edit control SetDlgItemText(IDC_EDIT1, accountInfo[1]); SetDlgItemText(IDC_EDIT2, accountInfo[2]); return TRUE; // return TRUE unless you set the focus to a control } void CMyAccountDlg::OnSysCommand(UINT nID, LPARAM lParam) { if ((nID & 0xFFF0) == IDM_ABOUTBOX) { CAboutDlg dlgAbout; dlgAbout.DoModal(); } else { CDialog::OnSysCommand(nID, lParam); } } // If you add a minimize button to your dialog, you will need the code below // to draw the icon. For MFC applications using the document/view model, // this is automatically done for you by the framework. void CMyAccountDlg::OnPaint() { if (IsIconic()) { CPaintDC dc(this); // device context for painting SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0); // Center icon in client rectangle int cxIcon = GetSystemMetrics(SM_CXICON); int cyIcon = GetSystemMetrics(SM_CYICON); CRect rect; GetClientRect(&rect); int x = (rect.Width() - cxIcon + 1) / 2; int y = (rect.Height() - cyIcon + 1) / 2; // Draw the icon dc.DrawIcon(x, y, m_hIcon); } else { CDialog::OnPaint(); } } // The system calls this function to obtain the cursor to display while the user drags // the minimized window. HCURSOR CMyAccountDlg::OnQueryDragIcon() { return static_cast<HCURSOR>(m_hIcon); } void CMyAccountDlg::OnCbnSelchangeCombo1() { // TODO: Add your control notification handler code here //Creat file TCHAR* pszFileName = _T("C:\\Program Files\\MyAccount\\account.dat"); if (!theApp.f.Open(pszFileName, CFile::modeCreate | CFile::modeNoTruncate | CFile::modeReadWrite)) { MessageBox(_T("Make File Error")); } CString strLine; CString accountInfo[3]; CString oneUserName; int nIndex = m_ComboBox.GetCurSel(); CString strCBText; m_ComboBox.GetLBText(nIndex, strCBText); theApp.f.SeekToBegin(); while (theApp.f.ReadString(strLine)) { if (!strLine.Compare(strCBText)) { theApp.flag = 1; } if (theApp.flag) { if (theApp.nstrLine < 3) { accountInfo[theApp.nstrLine++] = strLine; } } } theApp.f.Close(); //Clear Flag theApp.nstrLine = 0; theApp.flag = 0; SetDlgItemText(IDC_EDIT1, accountInfo[1]); SetDlgItemText(IDC_EDIT2, accountInfo[2]); } void CMyAccountDlg::OnBnClickedOk() { // TODO: Add your control notification handler code here CMyDlg dlg; dlg.DoModal(); //CDialog::OnOK(); } //Split string(By Myself) void CMyAccountDlg::Split(CString strSource, CStringArray& strDest) { strDest.RemoveAll(); TCHAR seps[] = _T("\r\n"); TCHAR *token, *next_token; token = _tcstok_s((LPTSTR)(LPCTSTR)strSource, seps, &next_token); while (token != NULL) { strDest.Add(CString(token)); token = _tcstok_s(NULL, seps, &next_token); } } //Deleate one account void CMyAccountDlg::OnBnClickedDeleate() { // TODO: Add your control notification handler code here CString strCBText; CString strLine; CString accountInfo[3]; CString totalInfo; CStringArray strDest; CString tempLine; CString allLine; int num_Vaild = 0; //Return if Commbo box is empty int nSel = m_ComboBox.GetCurSel(); if (nSel == CB_ERR) { return; } m_ComboBox.GetLBText(nSel, strCBText); //Open file TCHAR* pszFileName = _T("C:\\Program Files\\MyAccount\\account.dat"); if (!theApp.f.Open(pszFileName, CFile::modeCreate | CFile::modeNoTruncate | CFile::modeRead)) { MessageBox(_T("Make File Error")); } //Relocation to the begin of file theApp.f.SeekToBegin(); while (theApp.f.ReadString(strLine)) { totalInfo += strLine; if (!strLine.Compare(strCBText)) { theApp.flag = 1; } if (theApp.flag) { if (theApp.nstrLine < 3) { //Retrieve the "User name & Password" of current account accountInfo[theApp.nstrLine++] = strLine;//Retrieve the value of element } } } //f--Close file theApp.f.Close(); //Clear flag theApp.nstrLine = 0; theApp.flag = 0; num_Vaild = 0; //Remove the elements which user want to deleted totalInfo.Replace(accountInfo[0], _T("")); totalInfo.Replace(accountInfo[1], _T("")); totalInfo.Replace(accountInfo[2], _T("")); //Split string CMyAccountDlg::Split(totalInfo, strDest); //Append "\r\n" for every element so that write to file by line for (int i = 0; i<strDest.GetSize(); i++) { tempLine = strDest.GetAt(i); tempLine += _T("\r\n"); allLine += tempLine; } //Remove "\r\n" in the accountInfo[0] accountInfo[0].Remove('\r'); accountInfo[0].Remove('\n'); //Whether remove the infomation(Interact with the user) if (MessageBox(_T("确定要删除账户《") + accountInfo[0] + _T("》的信息吗?"), NULL, MB_OKCANCEL) == IDCANCEL) { return; } //ff--Write file CStdioFile ff(_T("C:\\Program Files\\MyAccount\\account.dat"), CFile::modeCreate | CFile::modeWrite); ff.WriteString(allLine); ff.Close(); //Reset the list of combox m_ComboBox.ResetContent(); //df--Open File CStdioFile df(_T("C:\\Program Files\\MyAccount\\account.dat"), CFile::modeRead); while (df.ReadString(strLine)) { if (num_Vaild % 3 == 0) { //Reset the list of combox m_ComboBox.AddString(strLine); //retrieves the list of combox } num_Vaild++; if (theApp.nstrLine < 3) { //Retrieve the "User name & Password" of first account currently accountInfo[theApp.nstrLine++] = strLine; } } //Clean flag theApp.nstrLine = 0; num_Vaild = 0; //df--Close File df.Close(); //Set the "User name & Password" of first account currently //SetCurSel(0) if (m_ComboBox.SetCurSel(0) == CB_ERR)//if Combo box is empty { SetDlgItemText(IDC_EDIT1, _T("")); SetDlgItemText(IDC_EDIT2, _T("")); } else//if Combo box is not empty { SetDlgItemText(IDC_EDIT1, accountInfo[1]); SetDlgItemText(IDC_EDIT2, accountInfo[2]); } } //Quit void CMyAccountDlg::OnBnClickedCancel() { // TODO: Add your control notification handler code here CDialog::OnCancel(); } void CMyAccountDlg::OnBnClickedButton1() { // TODO: Add your control notification handler code here int nSel=m_ComboBox.GetCurSel(); if (nSel == CB_ERR) { MessageBox(_T("Cann't modify the account info which is empty!")); } else { DialogModify dlg; dlg.DoModal(); } }
#ifndef CLIENT_H #define CLIENT_H #include <QWidget> #include <QSqlTableModel> namespace Ui { class client; } class client : public QWidget { Q_OBJECT public: explicit client(QWidget *parent = nullptr); ~client(); void sendSignal(); QSqlDatabase db; signals: void mySignal(); private slots: void on_pushButtonreturn_clicked(); void on_pushButtonquit_clicked(); void on_pushButtonbuy_clicked(); void on_pushButtonans_clicked(); void on_pushButtonfresh_clicked(); private: Ui::client *ui; QSqlTableModel *model; }; #endif // CLIENT_H
// // main.cpp // hw5 // // Created by Christopher Chandler on 3/9/16. // Copyright © 2016 Christopher Chandler. All rights reserved. // #include <iostream> #include <list> #include "MultiLL.h" int main(int argc, const char * argv[]) { // insert code here... std::cout << "Hello, World!\n"; std::list<int> kayla; for(int i = 0; i<47; ++i){ kayla.push_back(i); } std::cout<<"contents of kayla: "<<std::endl; return 0; }
#include "ContactForceDist.h" ContactForceDist::ContactForceDist():VECNUM(1024){ cylArray = 0; planeArray = 0; collCal = 0; TargetID = 0; } ContactForceDist::~ContactForceDist(){ } void ContactForceDist::Associate(CylinderArray* cyArray){ cylArray = cyArray; } void ContactForceDist::Associate(PlaneArray* plnArray){ planeArray = plnArray; } void ContactForceDist::Associate(CollisionCalc* collisionCalc){ collCal = collisionCalc; } void ContactForceDist::CreateForceDistFile(const char *FileName, int CylinderID, double RecordTimestep, int RecordStepNum){ char binFileName[64]; strcpy(binFileName, FileName); strcat(binFileName, ".bin"); fout.open(binFileName, ios_base::binary); int cylType = cylArray->GetCylinderType(CylinderID); double cylRadius = cylArray->GetCylinderRadius(CylinderID); double cylPos[3]; cylArray->GetPos(CylinderID, cylPos); double begin, end; cylArray->GetDisplayBeginEnd(CylinderID, &begin, &end); fout.write((char*)&cylType, sizeof(int)); fout.write((char*)&cylRadius, sizeof(double)); fout.write((char*)cylPos, sizeof(double)*3); fout.write((char*)&begin, sizeof(double)); fout.write((char*)&end, sizeof(double)); fout.write((char*)&RecordTimestep, sizeof(double)); fout.write((char*)&RecordStepNum, sizeof(int)); TargetID = CylinderID; } void ContactForceDist::WriteForceDistData(){ ForceDetailList = collCal->GetContactForceDist(TargetID); int distNum = ForceDetailList.size(); fout.write((char*)&distNum, sizeof(int)); for(int i=0; i<distNum; i++){ fout.write((char*)&ForceDetailList[i], sizeof(ContactForceDetail)); } } void ContactForceDist::CreatePlaneForceDistFile(const char *FileName, int PlaneID, double RecordTimestep, int RecordStepNum){ char binFileName[64]; strcpy(binFileName, FileName); strcat(binFileName, ".bin"); fout.open(binFileName, ios_base::binary); double planePos[3]; double planeNormal[3]; planeArray->GetPos(PlaneID, planePos, planeNormal); double V0[3],V1[3],V2[3],V3[3]; planeArray->GetVertex(PlaneID, V0, V1, V2, V3); fout.write((char*)planePos, sizeof(double)*3); fout.write((char*)planeNormal, sizeof(double)*3); fout.write((char*)V0, sizeof(double)*3); fout.write((char*)V1, sizeof(double)*3); fout.write((char*)V2, sizeof(double)*3); fout.write((char*)V3, sizeof(double)*3); fout.write((char*)&RecordTimestep, sizeof(double)); fout.write((char*)&RecordStepNum, sizeof(int)); TargetID = PlaneID; } void ContactForceDist::WritePlaneForceDistData(){ ForceDetailList = collCal->GetPlaneContactForceDist(TargetID); int distNum = ForceDetailList.size(); fout.write((char*)&distNum, sizeof(int)); for(int i=0; i<distNum; i++){ fout.write((char*)&ForceDetailList[i], sizeof(ContactForceDetail)); } } void ContactForceDist::CloseForceDistFile(){ fout.close(); } void ContactForceDist::FileLoad(const char *FileName, CylinderParam& cylinderParam, SimParam& simParam, vector< vector<ContactForceDetail> >& CFDarray){ ifstream fin; char binFileName[64]; strcpy(binFileName, FileName); strcat(binFileName, ".bin"); fin.open(binFileName, ios_base::binary); fin.read((char*)&cylinderParam.cylType, sizeof(int)); fin.read((char*)&cylinderParam.cylRadius, sizeof(double)); fin.read((char*)cylinderParam.cylPos, sizeof(double)*3); fin.read((char*)&cylinderParam.begin, sizeof(double)); fin.read((char*)&cylinderParam.end, sizeof(double)); fin.read((char*)&simParam.timeStep, sizeof(double)); fin.read((char*)&simParam.stepNum, sizeof(int)); CFDarray.resize(simParam.stepNum); for(int i=0; i<simParam.stepNum; i++){ int distNum; fin.read((char*)&distNum, sizeof(int)); for(int j=0; j<distNum; j++){ ContactForceDetail cfd; fin.read((char*)&cfd, sizeof(ContactForceDetail)); CFDarray[i].push_back(cfd); } } fin.close(); } void ContactForceDist::FileLoad(const char *FileName, PlaneParam& planeParam, SimParam& simParam, vector< vector<ContactForceDetail> >& CFDarray){ ifstream fin; char binFileName[64]; strcpy(binFileName, FileName); strcat(binFileName, ".bin"); fin.open(binFileName, ios_base::binary); fin.read((char*)planeParam.planePos, sizeof(double)*3); fin.read((char*)planeParam.planeNormal, sizeof(double)*3); fin.read((char*)planeParam.vertex0, sizeof(double)*3); fin.read((char*)planeParam.vertex1, sizeof(double)*3); fin.read((char*)planeParam.vertex2, sizeof(double)*3); fin.read((char*)planeParam.vertex3, sizeof(double)*3); fin.read((char*)&simParam.timeStep, sizeof(double)); fin.read((char*)&simParam.stepNum, sizeof(int)); CFDarray.resize(simParam.stepNum); for(int i=0; i<simParam.stepNum; i++){ int distNum; fin.read((char*)&distNum, sizeof(int)); for(int j=0; j<distNum; j++){ ContactForceDetail cfd; fin.read((char*)&cfd, sizeof(ContactForceDetail)); CFDarray[i].push_back(cfd); } } fin.close(); } void ContactForceDist::Convert2AVS_Cyl_Force(const char *FileName){ CylinderParam cParam; SimParam sParam; vector< vector<ContactForceDetail> > cfdArray; FileLoad(FileName, cParam, sParam, cfdArray); char fldFileName[64]; strcpy(fldFileName, FileName); strcat(fldFileName, "_force.fld"); ofstream fout1, fout2, fout3; fout1.open(fldFileName, ios::out | ios::trunc); fout1 << "# AVS field file\n"; fout1 << "#\n"; fout1 << "nstep= " << sParam.stepNum << '\n'; fout1 << "ndim= 1\n"; fout1 << "dim1= " << VECNUM << '\n'; fout1 << "nspace= 3\n"; fout1 << "veclen= 3\n"; fout1 << "data= float\n"; fout1 << "field= irregular\n"; fout1 << "label= x y z\n\n"; fout1 << "time file=./" << FileName << "_force.dat filetype=ascii skip=0 close=0\n"; fout1 << "variable 1 file=./" << FileName << "_force.dat filetype=ascii skip=1 offset=0 stride=6 close=0\n"; fout1 << "variable 2 file=./" << FileName << "_force.dat filetype=ascii skip=1 offset=1 stride=6 close=0\n"; fout1 << "variable 3 file=./" << FileName << "_force.dat filetype=ascii skip=1 offset=2 stride=6 close=0\n"; fout1 << "coord 1 file=./" << FileName << "_force.dat filetype=ascii skip=1 offset=3 stride=6 close=0\n"; fout1 << "coord 2 file=./" << FileName << "_force.dat filetype=ascii skip=1 offset=4 stride=6 close=0\n"; fout1 << "coord 3 file=./" << FileName << "_force.dat filetype=ascii skip=1 offset=5 stride=6 close=0\n"; fout1 << "EOT\n"; fout1 << "DO\n"; fout1 << "time file=./" << FileName << "_force.dat filetype=ascii skip=" << VECNUM << " close=0\n"; fout1 << "variable 1 file=./" << FileName << "_force.dat filetype=ascii skip=1 offset=0 stride=6 close=0\n"; fout1 << "variable 2 file=./" << FileName << "_force.dat filetype=ascii skip=1 offset=1 stride=6 close=0\n"; fout1 << "variable 3 file=./" << FileName << "_force.dat filetype=ascii skip=1 offset=2 stride=6 close=0\n"; fout1 << "coord 1 file=./" << FileName << "_force.dat filetype=ascii skip=1 offset=3 stride=6 close=0\n"; fout1 << "coord 2 file=./" << FileName << "_force.dat filetype=ascii skip=1 offset=4 stride=6 close=0\n"; fout1 << "coord 3 file=./" << FileName << "_force.dat filetype=ascii skip=1 offset=5 stride=6 close=0\n"; fout1 << "EOT\n"; fout1 << "ENDDO" << endl; fout1.close(); char datFileName[64]; strcpy(datFileName, FileName); strcat(datFileName, "_force.dat"); fout2.open(datFileName, ios::out | ios::trunc); for(int i=0; i<cfdArray.size(); i++){ fout2 << i << endl; for(int j=0; j<cfdArray[i].size(); j++){ fout2 << cfdArray[i][j].nForce[0] + cfdArray[i][j].tForce[0] << ' ' << cfdArray[i][j].nForce[1] + cfdArray[i][j].tForce[1] << ' ' << cfdArray[i][j].nForce[2] + cfdArray[i][j].tForce[2] << ' ' << cfdArray[i][j].ContactPoint[0] << ' ' << cfdArray[i][j].ContactPoint[1] << ' ' << cfdArray[i][j].ContactPoint[2] << endl; } for(int j=0; j<VECNUM-cfdArray[i].size(); j++){ fout2 << "0 0 0 0 0 0\n"; } } fout2.close(); char mgfFileName[64]; strcpy(mgfFileName, FileName); strcat(mgfFileName, "_force.mgf"); fout3.open(mgfFileName, ios::out | ios::trunc); if(cParam.cylType == 0){ } else if(cParam.cylType == 1){ fout3 << "# Micro AVS Geom:2.00\n"; fout3 << "circle\n"; fout3 << "Region\n"; fout3 << "empty\n"; fout3 << "color\n"; fout3 << "256\n"; fout3 << "2\n"; fout3 << cParam.cylType << ' ' << cParam.cylPos[0] << ' ' << cParam.begin << ' ' << cParam.cylPos[2] << ' ' << cParam.cylRadius << " 1.0 1.0 1.0\n"; fout3 << cParam.cylType << ' ' << cParam.cylPos[0] << ' ' << cParam.end << ' ' << cParam.cylPos[2] << ' ' << cParam.cylRadius << " 1.0 1.0 1.0\n"; } else if(cParam.cylType ==2){ } fout3.close(); } void ContactForceDist::Convert2AVS_Cyl_Velo(const char *FileName){ CylinderParam cParam; SimParam sParam; vector< vector<ContactForceDetail> > cfdArray; FileLoad(FileName, cParam, sParam, cfdArray); char fldFileName[64]; strcpy(fldFileName, FileName); strcat(fldFileName, "_velo.fld"); ofstream fout1, fout2, fout3; fout1.open(fldFileName, ios::out | ios::trunc); fout1 << "# AVS field file\n"; fout1 << "#\n"; fout1 << "nstep= " << sParam.stepNum << '\n'; fout1 << "ndim= 1\n"; fout1 << "dim1= " << VECNUM << '\n'; fout1 << "nspace= 3\n"; fout1 << "veclen= 3\n"; fout1 << "data= float\n"; fout1 << "field= irregular\n"; fout1 << "label= x y z\n\n"; fout1 << "time file=./" << FileName << "_velo.dat filetype=ascii skip=0 close=0\n"; fout1 << "variable 1 file=./" << FileName << "_velo.dat filetype=ascii skip=1 offset=0 stride=6 close=0\n"; fout1 << "variable 2 file=./" << FileName << "_velo.dat filetype=ascii skip=1 offset=1 stride=6 close=0\n"; fout1 << "variable 3 file=./" << FileName << "_velo.dat filetype=ascii skip=1 offset=2 stride=6 close=0\n"; fout1 << "coord 1 file=./" << FileName << "_velo.dat filetype=ascii skip=1 offset=3 stride=6 close=0\n"; fout1 << "coord 2 file=./" << FileName << "_velo.dat filetype=ascii skip=1 offset=4 stride=6 close=0\n"; fout1 << "coord 3 file=./" << FileName << "_velo.dat filetype=ascii skip=1 offset=5 stride=6 close=0\n"; fout1 << "EOT\n"; fout1 << "DO\n"; fout1 << "time file=./" << FileName << "_velo.dat filetype=ascii skip=" << VECNUM << " close=0\n"; fout1 << "variable 1 file=./" << FileName << "_velo.dat filetype=ascii skip=1 offset=0 stride=6 close=0\n"; fout1 << "variable 2 file=./" << FileName << "_velo.dat filetype=ascii skip=1 offset=1 stride=6 close=0\n"; fout1 << "variable 3 file=./" << FileName << "_velo.dat filetype=ascii skip=1 offset=2 stride=6 close=0\n"; fout1 << "coord 1 file=./" << FileName << "_velo.dat filetype=ascii skip=1 offset=3 stride=6 close=0\n"; fout1 << "coord 2 file=./" << FileName << "_velo.dat filetype=ascii skip=1 offset=4 stride=6 close=0\n"; fout1 << "coord 3 file=./" << FileName << "_velo.dat filetype=ascii skip=1 offset=5 stride=6 close=0\n"; fout1 << "EOT\n"; fout1 << "ENDDO" << endl; fout1.close(); char datFileName[64]; strcpy(datFileName, FileName); strcat(datFileName, "_velo.dat"); fout2.open(datFileName, ios::out | ios::trunc); for(int i=0; i<cfdArray.size(); i++){ fout2 << i << endl; for(int j=0; j<cfdArray[i].size(); j++){ fout2 << cfdArray[i][j].ContactVelo[0] << ' ' << cfdArray[i][j].ContactVelo[1] << ' ' << cfdArray[i][j].ContactVelo[2] << ' ' << cfdArray[i][j].ContactPoint[0] << ' ' << cfdArray[i][j].ContactPoint[1] << ' ' << cfdArray[i][j].ContactPoint[2] << endl; } for(int j=0; j<VECNUM-cfdArray[i].size(); j++){ fout2 << "0 0 0 0 0 0\n"; } } fout2.close(); char mgfFileName[64]; strcpy(mgfFileName, FileName); strcat(mgfFileName, "_velo.mgf"); fout3.open(mgfFileName, ios::out | ios::trunc); if(cParam.cylType == 0){ } else if(cParam.cylType == 1){ fout3 << "# Micro AVS Geom:2.00\n"; fout3 << "circle\n"; fout3 << "Region\n"; fout3 << "empty\n"; fout3 << "color\n"; fout3 << "256\n"; fout3 << "2\n"; fout3 << cParam.cylType << ' ' << cParam.cylPos[0] << ' ' << cParam.begin << ' ' << cParam.cylPos[2] << ' ' << cParam.cylRadius << " 1.0 1.0 1.0\n"; fout3 << cParam.cylType << ' ' << cParam.cylPos[0] << ' ' << cParam.end << ' ' << cParam.cylPos[2] << ' ' << cParam.cylRadius << " 1.0 1.0 1.0\n"; } else if(cParam.cylType ==2){ } fout3.close(); } void ContactForceDist::CoordTrans(vector< vector<ContactForceDetail> >& CFDarray, CylinderParam cylinderParam, double CenterPosAngle){ if(cylinderParam.cylType == 0){ } else if(cylinderParam.cylType == 1){ for(int i=0; i<CFDarray.size(); i++){ for(int j=0; j<CFDarray[i].size(); j++){ double rad = atan2(CFDarray[i][j].ContactPoint[2]-cylinderParam.cylPos[2], CFDarray[i][j].ContactPoint[0]-cylinderParam.cylPos[0]) - CenterPosAngle; double convN[3]; convN[0] = CFDarray[i][j].nForce[0]*cos(-rad)-CFDarray[i][j].nForce[2]*sin(-rad); convN[1] = CFDarray[i][j].nForce[1]; convN[2] = CFDarray[i][j].nForce[0]*sin(-rad)+CFDarray[i][j].nForce[2]*cos(-rad); double convT[3]; convT[0] = CFDarray[i][j].tForce[0]*cos(-rad)-CFDarray[i][j].tForce[2]*sin(-rad); convT[1] = CFDarray[i][j].tForce[1]; convT[2] = CFDarray[i][j].tForce[0]*sin(-rad)+CFDarray[i][j].tForce[2]*cos(-rad); double convV[3]; convV[0] = CFDarray[i][j].ContactVelo[0]*cos(-rad)-CFDarray[i][j].ContactVelo[2]*sin(-rad); convV[1] = CFDarray[i][j].ContactVelo[1]; convV[2] = CFDarray[i][j].ContactVelo[0]*sin(-rad)+CFDarray[i][j].ContactVelo[2]*cos(-rad); double convPos[3]; convPos[0] = cylinderParam.cylRadius*rad; convPos[1] = CFDarray[i][j].ContactPoint[1]; convPos[2] = 0; CFDarray[i][j].nForce[0] = convN[0]; CFDarray[i][j].nForce[1] = convN[1]; CFDarray[i][j].nForce[2] = convN[2]; CFDarray[i][j].tForce[0] = convT[0]; CFDarray[i][j].tForce[1] = convT[1]; CFDarray[i][j].tForce[2] = convT[2]; CFDarray[i][j].ContactVelo[0] = convV[0]; CFDarray[i][j].ContactVelo[1] = convV[1]; CFDarray[i][j].ContactVelo[2] = convV[2]; CFDarray[i][j].ContactPoint[0] = convPos[0]; CFDarray[i][j].ContactPoint[1] = convPos[1]; CFDarray[i][j].ContactPoint[2] = convPos[2]; } } } else if(cylinderParam.cylType == 2){ } } void ContactForceDist::Convert2AVS_Cyl_TransformedNForce(const char *FileName, double CenterPosAngle, double DisplayArea, double ScaleSize){ CylinderParam cParam; SimParam sParam; vector< vector<ContactForceDetail> > cfdArray; FileLoad(FileName, cParam, sParam, cfdArray); CoordTrans(cfdArray, cParam, CenterPosAngle); char fldFileName[64]; strcpy(fldFileName, FileName); strcat(fldFileName, "_TransformedNForce.fld"); char datFileName[64]; strcpy(datFileName, FileName); strcat(datFileName, "_TransformedNForce.dat"); ofstream fout1, fout2, fout3; fout1.open(fldFileName, ios::out | ios::trunc); fout1 << "# AVS field file\n"; fout1 << "#\n"; fout1 << "nstep= " << sParam.stepNum << '\n'; fout1 << "ndim= 1\n"; fout1 << "dim1= " << VECNUM << '\n'; fout1 << "nspace= 3\n"; fout1 << "veclen= 3\n"; fout1 << "data= float\n"; fout1 << "field= irregular\n"; fout1 << "label= x y z\n\n"; fout1 << "time file=./" << datFileName << " filetype=ascii skip=0 close=0\n"; fout1 << "variable 1 file=./" << datFileName << " filetype=ascii skip=1 offset=0 stride=6 close=0\n"; fout1 << "variable 2 file=./" << datFileName << " filetype=ascii skip=1 offset=1 stride=6 close=0\n"; fout1 << "variable 3 file=./" << datFileName << " filetype=ascii skip=1 offset=2 stride=6 close=0\n"; fout1 << "coord 1 file=./" << datFileName << " filetype=ascii skip=1 offset=3 stride=6 close=0\n"; fout1 << "coord 2 file=./" << datFileName << " filetype=ascii skip=1 offset=4 stride=6 close=0\n"; fout1 << "coord 3 file=./" << datFileName << " filetype=ascii skip=1 offset=5 stride=6 close=0\n"; fout1 << "EOT\n"; fout1 << "DO\n"; fout1 << "time file=./" << datFileName << " filetype=ascii skip=" << VECNUM << " close=0\n"; fout1 << "variable 1 file=./" << datFileName << " filetype=ascii skip=1 offset=0 stride=6 close=0\n"; fout1 << "variable 2 file=./" << datFileName << " filetype=ascii skip=1 offset=1 stride=6 close=0\n"; fout1 << "variable 3 file=./" << datFileName << " filetype=ascii skip=1 offset=2 stride=6 close=0\n"; fout1 << "coord 1 file=./" << datFileName << " filetype=ascii skip=1 offset=3 stride=6 close=0\n"; fout1 << "coord 2 file=./" << datFileName << " filetype=ascii skip=1 offset=4 stride=6 close=0\n"; fout1 << "coord 3 file=./" << datFileName << " filetype=ascii skip=1 offset=5 stride=6 close=0\n"; fout1 << "EOT\n"; fout1 << "ENDDO" << endl; fout1.close(); fout2.open(datFileName, ios::out | ios::trunc); for(int i=0; i<cfdArray.size(); i++){ fout2 << i << endl; for(int j=0; j<cfdArray[i].size(); j++){ fout2 << cfdArray[i][j].nForce[0] << ' ' << cfdArray[i][j].nForce[1] << ' ' << cfdArray[i][j].nForce[2] << ' ' << cfdArray[i][j].ContactPoint[0] << ' ' << cfdArray[i][j].ContactPoint[1] << ' ' << cfdArray[i][j].ContactPoint[2] << endl; } for(int j=0; j<VECNUM-cfdArray[i].size(); j++){ fout2 << "0 0 0 0 0 0\n"; } } fout2.close(); char mgfFileName[64]; strcpy(mgfFileName, FileName); strcat(mgfFileName, "_TransformedNForce.mgf"); fout3.open(mgfFileName, ios::out | ios::trunc); int scaleNum = (int)(DisplayArea*0.5/ScaleSize); int vertexNum = (scaleNum*2+3)*2; if(cParam.cylType == 0){ } else if(cParam.cylType == 1){ fout3 << "# Micro AVS Geom:2.00\n"; fout3 << "disjoint line\n"; fout3 << "Region\n"; fout3 << "color\n"; fout3 << vertexNum << '\n'; fout3 << -DisplayArea*0.5 << ' ' << cParam.begin << " 0.0 1.0 1.0 1.0\n"; fout3 << DisplayArea*0.5 << ' ' << cParam.begin << " 0.0 1.0 1.0 1.0\n\n"; fout3 << -DisplayArea*0.5 << ' ' << cParam.end << " 0.0 1.0 1.0 1.0\n"; fout3 << DisplayArea*0.5 << ' ' << cParam.end << " 0.0 1.0 1.0 1.0\n\n"; fout3 << "0.0 " << cParam.begin << " 0.0 0.7 0.0 0.7\n"; fout3 << "0.0 " << cParam.end << " 0.0 0.7 0.0 0.7\n\n"; for(int i=1; i<=scaleNum; i++){ fout3 << i*ScaleSize << ' ' << cParam.begin << " 0.0 0.5 0.5 0.5\n"; fout3 << i*ScaleSize << ' ' << cParam.end << " 0.0 0.5 0.5 0.5\n\n"; fout3 << -i*ScaleSize << ' ' << cParam.begin << " 0.0 0.5 0.5 0.5\n"; fout3 << -i*ScaleSize << ' ' << cParam.end << " 0.0 0.5 0.5 0.5\n\n"; } } else if(cParam.cylType ==2){ } fout3.close(); } void ContactForceDist::Convert2AVS_Cyl_TransformedTForce(const char *FileName, double CenterPosAngle, double DisplayArea, double ScaleSize){ CylinderParam cParam; SimParam sParam; vector< vector<ContactForceDetail> > cfdArray; FileLoad(FileName, cParam, sParam, cfdArray); CoordTrans(cfdArray, cParam, CenterPosAngle); char fldFileName[64]; strcpy(fldFileName, FileName); strcat(fldFileName, "_TransformedTForce.fld"); char datFileName[64]; strcpy(datFileName, FileName); strcat(datFileName, "_TransformedTForce.dat"); ofstream fout1, fout2, fout3; fout1.open(fldFileName, ios::out | ios::trunc); fout1 << "# AVS field file\n"; fout1 << "#\n"; fout1 << "nstep= " << sParam.stepNum << '\n'; fout1 << "ndim= 1\n"; fout1 << "dim1= " << VECNUM << '\n'; fout1 << "nspace= 3\n"; fout1 << "veclen= 3\n"; fout1 << "data= float\n"; fout1 << "field= irregular\n"; fout1 << "label= x y z\n\n"; fout1 << "time file=./" << datFileName << " filetype=ascii skip=0 close=0\n"; fout1 << "variable 1 file=./" << datFileName << " filetype=ascii skip=1 offset=0 stride=6 close=0\n"; fout1 << "variable 2 file=./" << datFileName << " filetype=ascii skip=1 offset=1 stride=6 close=0\n"; fout1 << "variable 3 file=./" << datFileName << " filetype=ascii skip=1 offset=2 stride=6 close=0\n"; fout1 << "coord 1 file=./" << datFileName << " filetype=ascii skip=1 offset=3 stride=6 close=0\n"; fout1 << "coord 2 file=./" << datFileName << " filetype=ascii skip=1 offset=4 stride=6 close=0\n"; fout1 << "coord 3 file=./" << datFileName << " filetype=ascii skip=1 offset=5 stride=6 close=0\n"; fout1 << "EOT\n"; fout1 << "DO\n"; fout1 << "time file=./" << datFileName << " filetype=ascii skip=" << VECNUM << " close=0\n"; fout1 << "variable 1 file=./" << datFileName << " filetype=ascii skip=1 offset=0 stride=6 close=0\n"; fout1 << "variable 2 file=./" << datFileName << " filetype=ascii skip=1 offset=1 stride=6 close=0\n"; fout1 << "variable 3 file=./" << datFileName << " filetype=ascii skip=1 offset=2 stride=6 close=0\n"; fout1 << "coord 1 file=./" << datFileName << " filetype=ascii skip=1 offset=3 stride=6 close=0\n"; fout1 << "coord 2 file=./" << datFileName << " filetype=ascii skip=1 offset=4 stride=6 close=0\n"; fout1 << "coord 3 file=./" << datFileName << " filetype=ascii skip=1 offset=5 stride=6 close=0\n"; fout1 << "EOT\n"; fout1 << "ENDDO" << endl; fout1.close(); fout2.open(datFileName, ios::out | ios::trunc); for(int i=0; i<cfdArray.size(); i++){ fout2 << i << endl; for(int j=0; j<cfdArray[i].size(); j++){ fout2 << cfdArray[i][j].tForce[0] << ' ' << cfdArray[i][j].tForce[1] << ' ' << cfdArray[i][j].tForce[2] << ' ' << cfdArray[i][j].ContactPoint[0] << ' ' << cfdArray[i][j].ContactPoint[1] << ' ' << cfdArray[i][j].ContactPoint[2] << endl; } for(int j=0; j<VECNUM-cfdArray[i].size(); j++){ fout2 << "0 0 0 0 0 0\n"; } } fout2.close(); char mgfFileName[64]; strcpy(mgfFileName, FileName); strcat(mgfFileName, "_TransformedTForce.mgf"); fout3.open(mgfFileName, ios::out | ios::trunc); int scaleNum = (int)(DisplayArea*0.5/ScaleSize); int vertexNum = (scaleNum*2+3)*2; if(cParam.cylType == 0){ } else if(cParam.cylType == 1){ fout3 << "# Micro AVS Geom:2.00\n"; fout3 << "disjoint line\n"; fout3 << "Region\n"; fout3 << "color\n"; fout3 << vertexNum << '\n'; fout3 << -DisplayArea*0.5 << ' ' << cParam.begin << " 0.0 1.0 1.0 1.0\n"; fout3 << DisplayArea*0.5 << ' ' << cParam.begin << " 0.0 1.0 1.0 1.0\n\n"; fout3 << -DisplayArea*0.5 << ' ' << cParam.end << " 0.0 1.0 1.0 1.0\n"; fout3 << DisplayArea*0.5 << ' ' << cParam.end << " 0.0 1.0 1.0 1.0\n\n"; fout3 << "0.0 " << cParam.begin << " 0.0 0.7 0.0 0.7\n"; fout3 << "0.0 " << cParam.end << " 0.0 0.7 0.0 0.7\n\n"; for(int i=1; i<=scaleNum; i++){ fout3 << i*ScaleSize << ' ' << cParam.begin << " 0.0 0.5 0.5 0.5\n"; fout3 << i*ScaleSize << ' ' << cParam.end << " 0.0 0.5 0.5 0.5\n\n"; fout3 << -i*ScaleSize << ' ' << cParam.begin << " 0.0 0.5 0.5 0.5\n"; fout3 << -i*ScaleSize << ' ' << cParam.end << " 0.0 0.5 0.5 0.5\n\n"; } } else if(cParam.cylType ==2){ } fout3.close(); } void ContactForceDist::Convert2AVS_Cyl_TransformedVelo(const char *FileName, double CenterPosAngle, double DisplayArea, double ScaleSize){ CylinderParam cParam; SimParam sParam; vector< vector<ContactForceDetail> > cfdArray; FileLoad(FileName, cParam, sParam, cfdArray); CoordTrans(cfdArray, cParam, CenterPosAngle); char fldFileName[64]; strcpy(fldFileName, FileName); strcat(fldFileName, "_TransformedVelo.fld"); char datFileName[64]; strcpy(datFileName, FileName); strcat(datFileName, "_TransformedVelo.dat"); ofstream fout1, fout2, fout3; fout1.open(fldFileName, ios::out | ios::trunc); fout1 << "# AVS field file\n"; fout1 << "#\n"; fout1 << "nstep= " << sParam.stepNum << '\n'; fout1 << "ndim= 1\n"; fout1 << "dim1= " << VECNUM << '\n'; fout1 << "nspace= 3\n"; fout1 << "veclen= 3\n"; fout1 << "data= float\n"; fout1 << "field= irregular\n"; fout1 << "label= x y z\n\n"; fout1 << "time file=./" << datFileName << " filetype=ascii skip=0 close=0\n"; fout1 << "variable 1 file=./" << datFileName << " filetype=ascii skip=1 offset=0 stride=6 close=0\n"; fout1 << "variable 2 file=./" << datFileName << " filetype=ascii skip=1 offset=1 stride=6 close=0\n"; fout1 << "variable 3 file=./" << datFileName << " filetype=ascii skip=1 offset=2 stride=6 close=0\n"; fout1 << "coord 1 file=./" << datFileName << " filetype=ascii skip=1 offset=3 stride=6 close=0\n"; fout1 << "coord 2 file=./" << datFileName << " filetype=ascii skip=1 offset=4 stride=6 close=0\n"; fout1 << "coord 3 file=./" << datFileName << " filetype=ascii skip=1 offset=5 stride=6 close=0\n"; fout1 << "EOT\n"; fout1 << "DO\n"; fout1 << "time file=./" << datFileName << " filetype=ascii skip=" << VECNUM << " close=0\n"; fout1 << "variable 1 file=./" << datFileName << " filetype=ascii skip=1 offset=0 stride=6 close=0\n"; fout1 << "variable 2 file=./" << datFileName << " filetype=ascii skip=1 offset=1 stride=6 close=0\n"; fout1 << "variable 3 file=./" << datFileName << " filetype=ascii skip=1 offset=2 stride=6 close=0\n"; fout1 << "coord 1 file=./" << datFileName << " filetype=ascii skip=1 offset=3 stride=6 close=0\n"; fout1 << "coord 2 file=./" << datFileName << " filetype=ascii skip=1 offset=4 stride=6 close=0\n"; fout1 << "coord 3 file=./" << datFileName << " filetype=ascii skip=1 offset=5 stride=6 close=0\n"; fout1 << "EOT\n"; fout1 << "ENDDO" << endl; fout1.close(); fout2.open(datFileName, ios::out | ios::trunc); for(int i=0; i<cfdArray.size(); i++){ fout2 << i << endl; for(int j=0; j<cfdArray[i].size(); j++){ fout2 << cfdArray[i][j].ContactVelo[0] << ' ' << cfdArray[i][j].ContactVelo[1] << ' ' << cfdArray[i][j].ContactVelo[2] << ' ' << cfdArray[i][j].ContactPoint[0] << ' ' << cfdArray[i][j].ContactPoint[1] << ' ' << cfdArray[i][j].ContactPoint[2] << endl; } for(int j=0; j<VECNUM-cfdArray[i].size(); j++){ fout2 << "0 0 0 0 0 0\n"; } } fout2.close(); char mgfFileName[64]; strcpy(mgfFileName, FileName); strcat(mgfFileName, "_TransformedVelo.mgf"); fout3.open(mgfFileName, ios::out | ios::trunc); int scaleNum = (int)(DisplayArea*0.5/ScaleSize); int vertexNum = (scaleNum*2+3)*2; if(cParam.cylType == 0){ } else if(cParam.cylType == 1){ fout3 << "# Micro AVS Geom:2.00\n"; fout3 << "disjoint line\n"; fout3 << "Region\n"; fout3 << "color\n"; fout3 << vertexNum << '\n'; fout3 << -DisplayArea*0.5 << ' ' << cParam.begin << " 0.0 1.0 1.0 1.0\n"; fout3 << DisplayArea*0.5 << ' ' << cParam.begin << " 0.0 1.0 1.0 1.0\n\n"; fout3 << -DisplayArea*0.5 << ' ' << cParam.end << " 0.0 1.0 1.0 1.0\n"; fout3 << DisplayArea*0.5 << ' ' << cParam.end << " 0.0 1.0 1.0 1.0\n\n"; fout3 << "0.0 " << cParam.begin << " 0.0 0.7 0.0 0.7\n"; fout3 << "0.0 " << cParam.end << " 0.0 0.7 0.0 0.7\n\n"; for(int i=1; i<=scaleNum; i++){ fout3 << i*ScaleSize << ' ' << cParam.begin << " 0.0 0.5 0.5 0.5\n"; fout3 << i*ScaleSize << ' ' << cParam.end << " 0.0 0.5 0.5 0.5\n\n"; fout3 << -i*ScaleSize << ' ' << cParam.begin << " 0.0 0.5 0.5 0.5\n"; fout3 << -i*ScaleSize << ' ' << cParam.end << " 0.0 0.5 0.5 0.5\n\n"; } } else if(cParam.cylType ==2){ } fout3.close(); } void ContactForceDist::Convert2AVS_Pln_Force(const char *FileName){ PlaneParam pParam; SimParam sParam; vector< vector<ContactForceDetail> > cfdArray; FileLoad(FileName, pParam, sParam, cfdArray); char fldFileName[64]; strcpy(fldFileName, FileName); strcat(fldFileName, "_force.fld"); ofstream fout1, fout2, fout3; fout1.open(fldFileName, ios::out | ios::trunc); fout1 << "# AVS field file\n"; fout1 << "#\n"; fout1 << "nstep= " << sParam.stepNum << '\n'; fout1 << "ndim= 1\n"; fout1 << "dim1= " << VECNUM << '\n'; fout1 << "nspace= 3\n"; fout1 << "veclen= 3\n"; fout1 << "data= float\n"; fout1 << "field= irregular\n"; fout1 << "label= x y z\n\n"; fout1 << "time file=./" << FileName << "_force.dat filetype=ascii skip=0 close=0\n"; fout1 << "variable 1 file=./" << FileName << "_force.dat filetype=ascii skip=1 offset=0 stride=6 close=0\n"; fout1 << "variable 2 file=./" << FileName << "_force.dat filetype=ascii skip=1 offset=1 stride=6 close=0\n"; fout1 << "variable 3 file=./" << FileName << "_force.dat filetype=ascii skip=1 offset=2 stride=6 close=0\n"; fout1 << "coord 1 file=./" << FileName << "_force.dat filetype=ascii skip=1 offset=3 stride=6 close=0\n"; fout1 << "coord 2 file=./" << FileName << "_force.dat filetype=ascii skip=1 offset=4 stride=6 close=0\n"; fout1 << "coord 3 file=./" << FileName << "_force.dat filetype=ascii skip=1 offset=5 stride=6 close=0\n"; fout1 << "EOT\n"; fout1 << "DO\n"; fout1 << "time file=./" << FileName << "_force.dat filetype=ascii skip=" << VECNUM << " close=0\n"; fout1 << "variable 1 file=./" << FileName << "_force.dat filetype=ascii skip=1 offset=0 stride=6 close=0\n"; fout1 << "variable 2 file=./" << FileName << "_force.dat filetype=ascii skip=1 offset=1 stride=6 close=0\n"; fout1 << "variable 3 file=./" << FileName << "_force.dat filetype=ascii skip=1 offset=2 stride=6 close=0\n"; fout1 << "coord 1 file=./" << FileName << "_force.dat filetype=ascii skip=1 offset=3 stride=6 close=0\n"; fout1 << "coord 2 file=./" << FileName << "_force.dat filetype=ascii skip=1 offset=4 stride=6 close=0\n"; fout1 << "coord 3 file=./" << FileName << "_force.dat filetype=ascii skip=1 offset=5 stride=6 close=0\n"; fout1 << "EOT\n"; fout1 << "ENDDO" << endl; fout1.close(); char datFileName[64]; strcpy(datFileName, FileName); strcat(datFileName, "_force.dat"); fout2.open(datFileName, ios::out | ios::trunc); for(int i=0; i<cfdArray.size(); i++){ fout2 << i << endl; for(int j=0; j<cfdArray[i].size(); j++){ fout2 << cfdArray[i][j].nForce[0] + cfdArray[i][j].tForce[0] << ' ' << cfdArray[i][j].nForce[1] + cfdArray[i][j].tForce[1] << ' ' << cfdArray[i][j].nForce[2] + cfdArray[i][j].tForce[2] << ' ' << cfdArray[i][j].ContactPoint[0] << ' ' << cfdArray[i][j].ContactPoint[1] << ' ' << cfdArray[i][j].ContactPoint[2] << endl; } for(int j=0; j<VECNUM-cfdArray[i].size(); j++){ fout2 << "0 0 0 0 0 0\n"; } } fout2.close(); char mgfFileName[64]; strcpy(mgfFileName, FileName); strcat(mgfFileName, "_force.mgf"); double color[3] = {1.0,1.0,1.0}; fout3.open(mgfFileName, ios::out | ios::trunc); fout3 << "# Micro AVS Geom:2.00\n"; fout3 << "polyline\n"; fout3 << "平面壁\n"; fout3 << "color\n"; fout3 << 5 << '\n'; fout3 << pParam.vertex0[0] << ' ' << pParam.vertex0[1] << ' ' << pParam.vertex0[2] << ' ' << color[0] << ' ' << color[1] << ' ' << color[2] << '\n'; fout3 << pParam.vertex1[0] << ' ' << pParam.vertex1[1] << ' ' << pParam.vertex1[2] << ' ' << color[0] << ' ' << color[1] << ' ' << color[2] << '\n'; fout3 << pParam.vertex2[0] << ' ' << pParam.vertex2[1] << ' ' << pParam.vertex2[2] << ' ' << color[0] << ' ' << color[1] << ' ' << color[2] << '\n'; fout3 << pParam.vertex3[0] << ' ' << pParam.vertex3[1] << ' ' << pParam.vertex3[2] << ' ' << color[0] << ' ' << color[1] << ' ' << color[2] << '\n'; fout3 << pParam.vertex0[0] << ' ' << pParam.vertex0[1] << ' ' << pParam.vertex0[2] << ' ' << color[0] << ' ' << color[1] << ' ' << color[2] << endl; fout3.close(); } void ContactForceDist::SameIDExtraction(const vector<ContactForceDetail>& inFirst, const vector<ContactForceDetail>& inSecond, vector<ContactForceDetail>& outFirst, vector<ContactForceDetail>& outSecond){ for(int i=0; i<inFirst.size(); i++){ for(int j=0; j<inSecond.size(); j++){ if(inFirst[i].ParticleID == inSecond[j].ParticleID){ outFirst.push_back(inFirst[i]); outSecond.push_back(inSecond[j]); } } } } vector<ContactForceDetail> ContactForceDist::OutputProfile(double ProfilePos, const vector<ContactForceDetail>& FirstFlame, const vector<ContactForceDetail>& SecondFlame){ vector<ContactForceDetail> extractFirst, extractSecond; SameIDExtraction(FirstFlame, SecondFlame, extractFirst, extractSecond); vector<ContactForceDetail> profile; for(int i=0; i<extractFirst.size(); i++){ if(extractFirst[i].ContactPoint[0] < ProfilePos && extractSecond[i].ContactPoint[0] > ProfilePos){ ContactForceDetail cfdtemp = extractSecond[i]; cfdtemp.ContactPoint[0] = ProfilePos; profile.push_back(cfdtemp); } } return profile; } vector<ContactForceDetail> ContactForceDist::OutputTimeSeries(vector< vector<ContactForceDetail> >& TransedCFDarray, SimParam simParam, double ProfilePos, double LTratio){ vector<ContactForceDetail> timeSeries; for(int i=0; i<simParam.stepNum-1; i++){ vector<ContactForceDetail> profile = OutputProfile(ProfilePos, TransedCFDarray[i], TransedCFDarray[i+1]); for(int j=0; j<profile.size(); j++){ profile[j].ContactPoint[0] = LTratio*simParam.timeStep*i; timeSeries.push_back(profile[j]); } } return timeSeries; } void ContactForceDist::OutputAreaAve(vector< vector<ContactForceDetail> >& TransedCFDarray, CylinderParam cylinderParam, double Position, double Pitch, Result* result){ double area = (cylinderParam.end-cylinderParam.begin) * Pitch; int stepNum = TransedCFDarray.size(); double nPsum=0; double tPsum=0; double VAvesum=0; double DensitySum=0; for(int i=1; i<stepNum; i++){ double nP=0; double tP=0; double VAve=0; double Density=0; for(int j=0; j<TransedCFDarray[i].size(); j++){ if(TransedCFDarray[i][j].ContactPoint[0] >= Position-Pitch*0.5 && TransedCFDarray[i][j].ContactPoint[0] < Position+Pitch*0.5){ nP += sqrt(pow(TransedCFDarray[i][j].nForce[0],2)+pow(TransedCFDarray[i][j].nForce[1],2)+pow(TransedCFDarray[i][j].nForce[2],2)); tP += sqrt(pow(TransedCFDarray[i][j].tForce[0],2)+pow(TransedCFDarray[i][j].tForce[1],2)+pow(TransedCFDarray[i][j].tForce[2],2)); VAve += sqrt(pow(TransedCFDarray[i][j].ContactVelo[0],2)+pow(TransedCFDarray[i][j].ContactVelo[1],2)+pow(TransedCFDarray[i][j].ContactVelo[2],2)); Density += 1; } } nP /= area; tP /= area; if(Density != 0) VAve /= Density; else VAve = 0; Density /= area*1000000; nPsum += nP; tPsum += tP; VAvesum += VAve; DensitySum += Density; } result->PressureNormal = nPsum / (double)(stepNum-1); result->PressureTangent = tPsum / (double)(stepNum-1); result->VeloAve = VAvesum / (double)(stepNum-1); result->Density = DensitySum / (double)(stepNum-1); } void ContactForceDist::OutputCSV_Cyl_Digest(const char *inFileName, double CenterPosAngle, double begin, double end, double outputPitch){ CylinderParam cylParam; SimParam sParam; vector< vector<ContactForceDetail> > cfdArray; FileLoad(inFileName, cylParam, sParam, cfdArray); CoordTrans(cfdArray, cylParam, CenterPosAngle); ofstream fout1; char csvFileName[64]; strcpy(csvFileName, inFileName); strcat(csvFileName, ".csv"); fout1.open(csvFileName, ios::out | ios::trunc); fout1 << "ニップ中央からの位置 m,法線方向摺擦力平均 N,接線方向方向摺擦力平均 N,すべり速度平均 m/s,キャリア密度 個/mm^2" << endl; double pos = begin; do{ Result calcResult; OutputAreaAve(cfdArray, cylParam, pos, outputPitch, &calcResult); fout1 << pos << ',' << calcResult.PressureNormal << ',' << calcResult.PressureTangent << ',' << calcResult.VeloAve << ',' << calcResult.Density << endl; pos += outputPitch; } while(pos <= end); fout1.close(); } void ContactForceDist::OutputCSV_Cyl(const char *inFileName, double CenterPosAngle){ CylinderParam cylParam; SimParam sParam; vector< vector<ContactForceDetail> > cfdArray; FileLoad(inFileName, cylParam, sParam, cfdArray); CoordTrans(cfdArray, cylParam, CenterPosAngle); ofstream fout1; char csvFileName[64]; strcpy(csvFileName, inFileName); strcat(csvFileName, ".csv"); fout1.open(csvFileName, ios::out | ios::trunc); for(int i=0; i<cfdArray.size(); i++){ fout1 << "Step" << i << ",X座標,Y座標,X方向摺擦力,Y方向摺擦力,Z(法線)方向摺擦力,X方向すべり速度,Y方向すべり速度" << endl; for(int j=0; j<cfdArray[i].size(); j++){ fout1 << ',' << cfdArray[i][j].ContactPoint[0] << ',' << cfdArray[i][j].ContactPoint[1] << ',' << cfdArray[i][j].tForce[0] << ',' << cfdArray[i][j].tForce[1] << ',' << cfdArray[i][j].nForce[2] << ',' << cfdArray[i][j].ContactVelo[0] << ',' << cfdArray[i][j].ContactVelo[1] << endl; } fout1 << '\n'; } fout1.close(); } void ContactForceDist::OutputCSV_Pln_Digest(const char *inFileName){ PlaneParam pParam; SimParam sParam; vector< vector<ContactForceDetail> > cfdArray; FileLoad(inFileName, pParam, sParam, cfdArray); ofstream fout1; char csvFileName[64]; strcpy(csvFileName, inFileName); strcat(csvFileName, ".csv"); double area = sqrt(pow(pParam.vertex1[0]-pParam.vertex0[0],2)+pow(pParam.vertex1[1]-pParam.vertex0[1],2)+pow(pParam.vertex1[2]-pParam.vertex0[2],2)) * sqrt(pow(pParam.vertex2[0]-pParam.vertex1[0],2)+pow(pParam.vertex2[1]-pParam.vertex1[1],2)+pow(pParam.vertex2[2]-pParam.vertex1[2],2)); double wholeForce = 0; vector<double> nforce; for(int i=0; i<cfdArray[cfdArray.size()-1].size(); i++){ double temp = sqrt(pow(cfdArray[cfdArray.size()-1][i].nForce[0], 2)+pow(cfdArray[cfdArray.size()-1][i].nForce[1], 2)+pow(cfdArray[cfdArray.size()-1][i].nForce[2], 2)); nforce.push_back(temp); wholeForce += temp; } double pressure = wholeForce / area; int num = cfdArray[cfdArray.size()-1].size(); double density = (double)num / area * 0.000001; double ave = wholeForce / (double)num; sort(nforce.begin(), nforce.end()); double max = nforce[num-1]; double min = nforce[0]; fout1.open(csvFileName, ios::out | ios::trunc); fout1 << "板面積,反力合計,圧力,接触キャリア個数,接触キャリア密度,接触力平均,接触力最大,接触力最小" << endl; fout1 << area << ',' << wholeForce << ',' << pressure << ',' << num << ',' << density << ',' << ave << ',' << max << ',' << min << endl; fout1.close(); }
/* * Copyright (c) 2013, Hernan Saez * 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 the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef CRIMILD_CORE_FOUNDATION_SHARED_OBJECT_LIST_ #define CRIMILD_CORE_FOUNDATION_SHARED_OBJECT_LIST_ #include "Foundation/SharedObject.hpp" #include "Mathematics/Random.hpp" #include <list> #include <functional> namespace crimild { template< class T > class NoCallbacksPolicy { public: void onAdded( SharedPointer< T > const &object ) { } void onRemoved( SharedPointer< T > const &object ) { } }; template< class T > class InvokeCallbacksPolicy { typedef std::function< void( SharedPointer< T > const & ) > CallbackType; public: void setOnAddCallback( CallbackType callback ) { _onAddedCallback = callback; } void onAdded( SharedPointer< T > const &object ) { _onAddedCallback( object ); } void setOnRemovedCallback( CallbackType callback ) { _onRemovedCallback = callback; } void onRemoved( SharedPointer< T > const &object ) { _onRemovedCallback( object ); } private: CallbackType _onAddedCallback; CallbackType _onRemovedCallback; }; /** \deprecated Use List< SharedPointer< ObjectType >> instead */ template< class ObjectType, template < class > class CallbackPolicy = NoCallbacksPolicy > class SharedObjectList : public SharedObject, public CallbackPolicy< ObjectType > { private: typedef SharedPointer< ObjectType > ObjectPtr; typedef CallbackPolicy< ObjectType > CallbackPolicyImpl; public: SharedObjectList( void ) { } virtual ~SharedObjectList( void ) { clear(); } unsigned int size( void ) const { return _objects.size(); } bool isEmpty( void ) const { return _objects.size() == 0; } void add( ObjectPtr const &obj ) { _objects.push_back( obj ); CallbackPolicyImpl::onAdded( obj ); } void add( ObjectType *obj ) { add( crimild::retain( obj ) ); } void addFront( ObjectPtr const &obj ) { _objects.push_front( obj ); CallbackPolicyImpl::onAdded( obj ); } void addFront( ObjectType *obj ) { addFront( crimild::retain( obj ) ); } ObjectPtr remove( ObjectPtr const &obj ) { _objects.remove( obj ); CallbackPolicyImpl::onRemoved( obj ); return obj; } ObjectPtr remove( ObjectType *obj ) { return remove( std::move( crimild::retain( obj ) ) ); } ObjectPtr popFront( void ) { auto obj = _objects.front(); _objects.pop_front(); CallbackPolicyImpl::onRemoved( obj ); return obj; } ObjectPtr popBack( void ) { auto obj = _objects.back(); _objects.pop_back(); CallbackPolicyImpl::onRemoved( obj ); return obj; } void clear( void ) { auto os = _objects; for ( auto obj : os ) CallbackPolicyImpl::onRemoved( obj ); _objects.clear(); } void each( std::function< void( ObjectType *, int index ) > callback ) { int i = 0; auto os = _objects; for ( auto o : os ) callback( crimild::get_ptr( o ), i++ ); } ObjectType *find( std::function< bool( ObjectPtr const & ) > callback ) { ObjectType result = nullptr; auto os = _objects; for ( auto o : os ) { if ( callback( o ) ) { result = crimild::get_ptr( o ); break; } } return result; } ObjectType *front( void ) { return _objects.front(); } void shuffle( void ) { Random::shuffle( _objects ); } private: std::list< ObjectPtr > _objects; }; } #endif
#include<bits/stdc++.h> using namespace std; typedef long long ll; void ipop(){ #ifndef ONLINE_JUDGE freopen("../input.txt","r",stdin); freopen("../op.txt","w",stdout); #endif } void solve(){ ll n,m; cin>>n>>m; vector<ll>a(n+1,0); for(ll i=1;i<=n;i++) cin>>a[i]; for(ll i=1;i<n;i++) a[i]+=a[i-1]; ll ans=INT_MAX; for(ll i=0;i<=n;i++){ for(ll j=0;j<=i;j++){ ll k= (j&i); if(k+i>=n) continue; ll x=a[n-i]-a[k]; if(x!=0 && (x%m)==0){ ll count=__builtin_popcountll(i); ans=min(ans,count); } } } cout<<(ans==INT_MAX?-1:ans)<<"\n"; } int main() { ipop(); int t=1,x=1; cin>>t; while(t--){ //cout<<"Case #"<<x<<":"<<" ";x++; solve(); } }
#include<cstdio> #include<iostream> #include<vector> using namespace std; bool isToeplitzMatrix(char matrix[4][4]) { for(int i = 1; i < 3; i++) for(int j = 1; j < 4; j++) { if(matrix[i][j] != matrix[i-1][j-1]) return false; } return true; } int main() { char a[4][4]= { {1,2,3,4}, {5,1,2,3}, {9,5,1,2}}; cout << isToeplitzMatrix(a) << endl; return 0; }
#include <ros/ros.h> #include <move_base_msgs/MoveBaseAction.h> #include <actionlib/client/simple_action_client.h> #include <std_msgs/UInt8.h> typedef actionlib::SimpleActionClient<move_base_msgs::MoveBaseAction> MoveBaseClient; int main(int argc, char** argv){ ros::init(argc, argv, "side_parking"); ros::NodeHandle n; ros::Publisher task_finish_pub = n.advertise<std_msgs::UInt8>("task_finished", 1); //tell the action client that we want to spin a thread by default MoveBaseClient ac("move_base", true); //wait for the action server to come up while(!ac.waitForServer(ros::Duration(5.0))){ ROS_INFO("Waiting for the move_base action server to come up"); } move_base_msgs::MoveBaseGoal goal; //we'll send a goal to the robot to move 1 meter forward goal.target_pose.header.frame_id = "map"; goal.target_pose.header.stamp = ros::Time::now(); // fifth goal goal.target_pose.pose.position.x = 2.0; goal.target_pose.pose.position.y = 1.0; goal.target_pose.pose.orientation.z = 0.707; goal.target_pose.pose.orientation.w = 0.707; ROS_INFO("Sending Fifth Goal"); ac.sendGoal(goal); ac.waitForResult(); if(ac.getState() == actionlib::SimpleClientGoalState::SUCCEEDED) ROS_INFO("Fifth Goal Reached!"); else ROS_INFO("Failed"); // sixth goal goal.target_pose.pose.position.x = 2.4; goal.target_pose.pose.position.y = 0.25; goal.target_pose.pose.orientation.z = 0.707; goal.target_pose.pose.orientation.w = 0.707; ROS_INFO("Sending Sixth Goal"); ac.sendGoal(goal); ac.waitForResult(); if(ac.getState() == actionlib::SimpleClientGoalState::SUCCEEDED) ROS_INFO("Sixth Goal Reached!"); else ROS_INFO("Failed"); ros::Duration(5).sleep(); // sixth goal goal.target_pose.pose.position.x = 1.0; goal.target_pose.pose.position.y = 1.15; goal.target_pose.pose.orientation.z = 0.9854497; goal.target_pose.pose.orientation.w = 0.1699671; ROS_INFO("Sending Sixth Goal"); ac.sendGoal(goal); ac.waitForResult(); if(ac.getState() == actionlib::SimpleClientGoalState::SUCCEEDED) ROS_INFO("Sixth Goal Reached!"); else ROS_INFO("Failed"); std_msgs::UInt8 msg; msg.data = 1; task_finish_pub.publish(msg); return 0; }
#ifndef BULLET_H #define BULLET_H #include "movable.h" class Bullet : public Movable { public: Bullet(int x, int y); Bullet(int x, int y, double raw_theta); void move(int to_x = 0, int to_y = 0); private: }; #endif
#include <iostream> #include <vector> #include <algorithm> using namespace std; int main() { int t; cin>>t; while(t--) { int n; cin>>n; vector<int> a(n),b(n); for(int i=0;i<n;i++) { cin>>a[i]; } for(int i=0;i<n;i++) { cin>>b[i]; } sort(a.begin(),a.end()); sort(b.begin(),b.end()); int index = 0,count=0; for(int i=0;i<n;i++) { for(int j=index;j<n;j++) { if(a[i]<=b[j]) { count++; index = j+1; break; } } } cout<<count<<endl; } return 0; }
#ifndef JULIAN_H #define JULIAN_H #include "date.h" namespace lab2 { class Julian : public Date_impl { public: Julian(); Julian(const Date& src); Date& operator=(const Date& src); Julian(int year, int month, int day); ~Julian(); private: bool is_leap_year(int year) const; void date_from_julian(double julian, int &day, int &month, int &year) const; double julian_from_date(int day, int month, int year) const; }; } // namespace lab2 #endif // JULIAN_H
/******************************************************************************** ** Form generated from reading UI file 'dialog.ui' ** ** Created by: Qt User Interface Compiler version 5.10.0 ** ** WARNING! All changes made in this file will be lost when recompiling UI file! ********************************************************************************/ #ifndef UI_DIALOG_H #define UI_DIALOG_H #include <QtCore/QVariant> #include <QtWidgets/QAction> #include <QtWidgets/QApplication> #include <QtWidgets/QButtonGroup> #include <QtWidgets/QDialog> #include <QtWidgets/QDialogButtonBox> #include <QtWidgets/QHBoxLayout> #include <QtWidgets/QHeaderView> #include <QtWidgets/QLabel> #include <QtWidgets/QLineEdit> #include <QtWidgets/QPushButton> #include <QtWidgets/QVBoxLayout> QT_BEGIN_NAMESPACE class Ui_Dialog { public: QVBoxLayout *verticalLayout; QHBoxLayout *horizontalLayout; QLabel *label; QLineEdit *lineEditInputDoc; QPushButton *pushButtonSelectDoc; QHBoxLayout *horizontalLayout_2; QLabel *label_2; QLineEdit *lineEditOutputPath; QPushButton *pushButtonSelectPath; QLabel *state; QPushButton *pushButtonSep; QDialogButtonBox *buttonBox; void setupUi(QDialog *Dialog) { if (Dialog->objectName().isEmpty()) Dialog->setObjectName(QStringLiteral("Dialog")); Dialog->resize(541, 140); verticalLayout = new QVBoxLayout(Dialog); verticalLayout->setObjectName(QStringLiteral("verticalLayout")); horizontalLayout = new QHBoxLayout(); horizontalLayout->setObjectName(QStringLiteral("horizontalLayout")); label = new QLabel(Dialog); label->setObjectName(QStringLiteral("label")); horizontalLayout->addWidget(label); lineEditInputDoc = new QLineEdit(Dialog); lineEditInputDoc->setObjectName(QStringLiteral("lineEditInputDoc")); horizontalLayout->addWidget(lineEditInputDoc); pushButtonSelectDoc = new QPushButton(Dialog); pushButtonSelectDoc->setObjectName(QStringLiteral("pushButtonSelectDoc")); horizontalLayout->addWidget(pushButtonSelectDoc); verticalLayout->addLayout(horizontalLayout); horizontalLayout_2 = new QHBoxLayout(); horizontalLayout_2->setObjectName(QStringLiteral("horizontalLayout_2")); label_2 = new QLabel(Dialog); label_2->setObjectName(QStringLiteral("label_2")); horizontalLayout_2->addWidget(label_2); lineEditOutputPath = new QLineEdit(Dialog); lineEditOutputPath->setObjectName(QStringLiteral("lineEditOutputPath")); horizontalLayout_2->addWidget(lineEditOutputPath); pushButtonSelectPath = new QPushButton(Dialog); pushButtonSelectPath->setObjectName(QStringLiteral("pushButtonSelectPath")); horizontalLayout_2->addWidget(pushButtonSelectPath); verticalLayout->addLayout(horizontalLayout_2); state = new QLabel(Dialog); state->setObjectName(QStringLiteral("state")); verticalLayout->addWidget(state); pushButtonSep = new QPushButton(Dialog); pushButtonSep->setObjectName(QStringLiteral("pushButtonSep")); verticalLayout->addWidget(pushButtonSep); buttonBox = new QDialogButtonBox(Dialog); buttonBox->setObjectName(QStringLiteral("buttonBox")); buttonBox->setOrientation(Qt::Horizontal); buttonBox->setStandardButtons(QDialogButtonBox::Cancel|QDialogButtonBox::Ok); verticalLayout->addWidget(buttonBox); retranslateUi(Dialog); QObject::connect(buttonBox, SIGNAL(accepted()), Dialog, SLOT(accept())); QObject::connect(buttonBox, SIGNAL(rejected()), Dialog, SLOT(reject())); QMetaObject::connectSlotsByName(Dialog); } // setupUi void retranslateUi(QDialog *Dialog) { Dialog->setWindowTitle(QApplication::translate("Dialog", "Dialog", nullptr)); label->setText(QApplication::translate("Dialog", "\350\276\223\345\205\245\346\225\260\346\215\256\346\226\207\344\273\266\357\274\232", nullptr)); pushButtonSelectDoc->setText(QApplication::translate("Dialog", "\351\200\211\346\213\251\346\226\207\344\273\266", nullptr)); label_2->setText(QApplication::translate("Dialog", "\350\276\223\345\207\272\346\225\260\346\215\256\346\226\207\344\273\266\357\274\232", nullptr)); lineEditOutputPath->setText(QApplication::translate("Dialog", "D:/data", nullptr)); pushButtonSelectPath->setText(QApplication::translate("Dialog", "\351\200\211\346\213\251\350\267\257\345\276\204", nullptr)); state->setText(QApplication::translate("Dialog", "\347\212\266\346\200\201\357\274\232", nullptr)); pushButtonSep->setText(QApplication::translate("Dialog", "\345\274\200\345\247\213\345\210\206\345\211\262", nullptr)); } // retranslateUi }; namespace Ui { class Dialog: public Ui_Dialog {}; } // namespace Ui QT_END_NAMESPACE #endif // UI_DIALOG_H
#include "CLog.h" #include "CDateTime.h" #include "CAutoLock.h" #include <sys/stat.h> using namespace Util; CLog::CLog() { } void CLog::bind(const std::string& dirName, FILE* pFileHandle) { mkdir(dirName.c_str(), 0754); std::string fileName = dirName + "/" + CDateTime().asString("YYYY-MM-DD") + ".log"; if (NULL == freopen(fileName.c_str(), "a", pFileHandle)) { fprintf(pFileHandle, "error redirecting\n"); } } void CLog::init(const std::string& dirName) { bind(dirName, stdout); bind(dirName + "_Error", stderr); } void CLog::log(ELogType logType, const std::string& content) { CAutoLock lock(getLock()); std::ostringstream stream; stream << "<" << CDateTime().asString() << "> "; switch ((int)logType) { case ELogType_Debug: stream << "[Debug]"; break; case ELogType_Info: stream << "[Info]"; break; case ELogType_Error: stream << "[Error]"; break; } stream << content << std::endl; if (ELogType_Error == logType) { std::cerr << stream.str(); } std::cout << stream.str(); }
#include<iostream> #include<cstdlib> #include<cstdio> #include<vector> #include<cstring> #include<fstream> #include<map> #include<string> #define MAX_V 10000 using namespace std; int V; vector<int> G[MAX_V]; //グラフの隣接リストを表現 vector<int> rG[MAX_V]; //辺の向きを逆にしたグラフ vector<int> vs; //帰りがけ順の並び. backtrackするごとに入れる。 bool used[MAX_V]; //すでに調べたか int cmp[MAX_V]; //属する強連結成分のトポロジカル順序 vector<int> component[MAX_V]; void add_edge(int from,int to); void rdfs(int v, int k); int scc(); int main(){ int a,b; int max = 0; string rtext,ltext; map<string,int> mp; map<string,int> flag; string str; int valu = 0; //ifstream ifs("listdat.txt"); string reading_line_buffer; ifstream reading_file; reading_file.open("IDedgelist.dat"); //reading_file.open("edgelist0.dat"); if(reading_file.fail()){ cerr<<"File do not exist\n"; exit(0); } //cout << mp["abd"]; //keyを入れていないものに対しては、0出力する。 //trueはひたすらファイルを読みこむことになる while(true){ //sscanf(str.data(),"%s %s",rtext.c_str(),ltext.c_str()); reading_file >> ltext >> rtext; if(reading_file.eof()) break; if(flag[ltext]!=1) {mp[ltext] = valu; flag[ltext]=1;valu++;} if(flag[rtext]!=1) {mp[rtext] = valu; flag[rtext]=1;valu++;} add_edge(mp[ltext],mp[rtext]); if(mp[rtext]>mp[ltext] && mp[rtext] > max){ max = mp[rtext]; }else if(mp[ltext] >= mp[rtext] && mp[ltext] > max){ max = mp[ltext]; } //cout << valu << endl; } //cout << "D" << " " << mp["D"] << endl; V = max + 1; int num_in_DAG = scc(); printf("total nodes = %d\n",max); printf("totl nodes in compressed DAG: %d\n",num_in_DAG); //scc component int count = 0; for(int i=0;i<num_in_DAG;i++){ int ss = component[i].size(); if(ss> 1) count+=1; } cout << "total SCCs: " << count << endl; } void add_edge(int from,int to){ G[from].push_back(to); rG[to].push_back(from); } void dfs(int v){ used[v] = true; for(int i = 0;i < G[v].size(); i++){ if(!used[G[v][i]]) dfs(G[v][i]); } //backtrackで戻ってきたと同時に格納。 vs.push_back(v); } void rdfs(int v, int k){ used[v] = true; cmp[v] = k; //printf("k = %d\n",k); component[k].push_back(v); for(int i=0;i<rG[v].size(); i++){ if(!used[rG[v][i]]) rdfs(rG[v][i],k); } } int scc(){ memset(used,0,sizeof(used)); vs.clear(); for(int v=0;v<V;v++){ if(!used[v]) dfs(v); } memset(used,0,sizeof(used)); int k = 0; int j; for(int i=vs.size()-1; i >= 0; i--){ //printf("%d\n",vs[i]); if(!used[vs[i]]) rdfs(vs[i],k++); } return k; //number of scc's 一つの点からなるものも強連結成分になる。 //to print specific scc. specify topological order. }
#include <cosmos/cosmos.hpp> #include <data/encoding/ascii.hpp> #include <abstractions/script/pow.hpp> #include <abstractions/script/pay_to_address.hpp> #include <abstractions/pattern/pay_to_address.hpp> #include <abstractions/crypto/address.hpp> #include <iostream> namespace cosmos::bitcoin { namespace pow { class error : std::exception { std::string Message; public: error(std::string s) : Message{s} {} const char* what() const noexcept final override { return Message.c_str(); } }; // patterns recognized by this wallet (only one for now) abstractions::pattern::pay_to_address<secret, pubkey, address, transaction> p2pkh{}; uint read_uint_dec(const std::string&); byte read_byte_dec(const std::string&); satoshi read_satoshi_amount(const std::string&); abstractions::work::uint24 read_uint24_dec(const std::string&); inline const secret read_wif(const std::string& s) { secret k{s}; if (!k.valid()) throw error{"invalid wif"}; } using ascii = data::encoding::ascii::string; inline const ascii read_ascii(const std::string& s) { data::encoding::ascii::string z{&s}; if (!z.valid()) throw error{"Cannot read ascii string"}; return z; } inline const address read_address(const std::string& s) { address a{s}; if (!a.valid()) throw error{"invalid address"}; return a; } inline const address read_address_from_script(const bytes& b) { struct abstractions::script::pay_to_address p{b}; if (!p.valid()) throw error{"invalid pay-to-address script"}; return p.Address; } inline const work::target read_target( const std::string& exponent, const std::string& value) { return work::target{read_byte_dec(exponent), read_uint24_dec(value)}; } inline const script pow_lock(work::message m, work::target t) { return abstractions::script::lock_by_pow(m, t)->compile(); } inline const output pow_lock_output( satoshi s, work::message m, work::target t) { return output{s, pow_lock(m, t)}; } inline const output pay_to_address_output(satoshi s, address a) { return output{s, abstractions::script::pay_to(a)->compile()}; } const transaction main( const list<spendable> outputs, const ascii data, const satoshi spend, const work::target target, const address change, const satoshi fee); /*{ list<spendable> to_be_redeemed{}; satoshi redeemed_value = 0; for (spendable o : outputs) { if (!o.valid()) throw error{"invalid reference to previous tx"}; address address = read_address_from_script(o.Spendable.Output.ScriptPubKey); if (!address.valid()) throw error{"invalid output script"}; if (address != address{o.Spendable.Key}) throw error{"cannot redeem address with key"}; to_be_redeemed = to_be_redeemed + o.Spendable; redeemed_value += o.Spendable.Output.Value; } return redeem({p2pkh}, vertex{to_be_redeemed, { abstractions::bitcoin::op_return{bytes(data)}, pow_lock_output(spend, abstractions::work::reference(hash(data)), target), pay_to_address_output(redeemed_value - fee, change)}}); }*/ class program { list<spendable> Previous; ascii Data; satoshi Spend; work::target Target; address Change; satoshi Fee; program( transaction tx, outpoint r, secret k, ascii d, satoshi s, work::target t, address c, satoshi f) : Previous{{tx, r, k}}, Data{d}, Target{t}, Change{c}, Fee{f} {} public: // Transform intput into constructed types. static const program make(const list<std::string> input) { if (input.size() != 9) throw error{"nine inputs required"}; transaction p{input[0]}; if (!p.valid()) throw error{"transaction is not valid"}; return program{p, outpoint{p.id(), read_uint_dec(input[1])}, read_wif(input[2]), read_ascii(input[3]), read_satoshi_amount(input[4]), read_target(input[5], input[6]), read_address(input[7]), read_satoshi_amount(input[8])}; } bool valid() const { return data::fold([](bool p, spendable x)->bool{return p && x.valid();}, 0, Previous); } const bitcoin::transaction operator()() const { const bitcoin::transaction tx{pow::main(Previous, Data, Spend, Target, Change, Fee)}; if (!tx.valid()) throw error{"invalid tx was produced"}; auto p = Previous; auto i = bitcoin::transaction::representation{tx}.Inputs; uint n = 0; while(!p.empty()) { bitcoin::output o = p.first().Spendable.Output; if (!bitcoin::machine{tx, n, o.Value}.run(o.ScriptPubKey, i.first().ScriptSignature)) throw error{"redemption script not valid"}; p = p.rest(); i = i.rest(); n++; } // TODO test whether pow_lock object can be reconstructed from the script. // TODO test redeem tx (optional; only for small pow targets). return tx; }; }; } const list<std::string> read_input(int argc, char* argv[]) noexcept { list<std::string> l{}; for (int i = 0; i < argc; i++) l = l + std::string(argv[i]); return l; } } namespace cosmos { string run(const list<std::string> input) noexcept { try { return data::encoding::hex::write(bitcoin::pow::program::make(input)()); } catch (std::exception& e) { return e.what(); } catch (...) { return "unknown error."; } } } int main(int argc, char* argv[]) { std::cout << cosmos::run(cosmos::read_input(argc, argv)); return 0; }
// // Created by steven on 2020-09-22. // #ifndef A1_CELL_H #define A1_CELL_H #include <tuple> #include "glm/glm.hpp" #include "GL/glew.h" // Include GLEW - OpenGL Extension Wrangler #include "../Framework/Renderer.h" #include <mutex> #include "tbb/spin_mutex.h" #define UP 0 #define UP_RIGHT 1 #define UP_LEFT 2 #define DOWN 3 #define DOWN_RIGHT 4 #define DOWN_LEFT 5 #define LEFT 6 #define RIGHT 7 class Cell { private: float *x; float *y; glm::vec3 *color; tbb::spin_mutex *mtx = new tbb::spin_mutex(); tbb::spin_mutex *direction_lock = new tbb::spin_mutex(); int *direction = 0; public: Cell(float _x, float _y, glm::vec3 _color); ~Cell(); Cell(const Cell &cell); Cell &operator=(const Cell &cell); void setPosition( float _x, float _y); void setColor(glm::vec3 _color); glm::vec3 getColor(); float getX(); float getY(); void setDirection(int); int getDirection(); }; #endif //A1_CELL_H
// C++ for the Windows Runtime vv1.0.170303.6 // Copyright (c) 2017 Microsoft Corporation. All rights reserved. #pragma once #include "Windows.Security.Authentication.Identity.Provider.2.h" WINRT_EXPORT namespace winrt { namespace Windows::Security::Authentication::Identity::Provider { struct WINRT_EBO SecondaryAuthenticationFactorAuthentication : Windows::Security::Authentication::Identity::Provider::ISecondaryAuthenticationFactorAuthentication { SecondaryAuthenticationFactorAuthentication(std::nullptr_t) noexcept {} static Windows::Foundation::IAsyncAction ShowNotificationMessageAsync(hstring_view deviceName, Windows::Security::Authentication::Identity::Provider::SecondaryAuthenticationFactorAuthenticationMessage message); static Windows::Foundation::IAsyncOperation<Windows::Security::Authentication::Identity::Provider::SecondaryAuthenticationFactorAuthenticationResult> StartAuthenticationAsync(hstring_view deviceId, const Windows::Storage::Streams::IBuffer & serviceAuthenticationNonce); static event_token AuthenticationStageChanged(const Windows::Foundation::EventHandler<Windows::Security::Authentication::Identity::Provider::SecondaryAuthenticationFactorAuthenticationStageChangedEventArgs> & handler); using AuthenticationStageChanged_revoker = factory_event_revoker<ISecondaryAuthenticationFactorAuthenticationStatics>; static AuthenticationStageChanged_revoker AuthenticationStageChanged(auto_revoke_t, const Windows::Foundation::EventHandler<Windows::Security::Authentication::Identity::Provider::SecondaryAuthenticationFactorAuthenticationStageChangedEventArgs> & handler); static void AuthenticationStageChanged(event_token token); static Windows::Foundation::IAsyncOperation<Windows::Security::Authentication::Identity::Provider::SecondaryAuthenticationFactorAuthenticationStageInfo> GetAuthenticationStageInfoAsync(); }; struct WINRT_EBO SecondaryAuthenticationFactorAuthenticationResult : Windows::Security::Authentication::Identity::Provider::ISecondaryAuthenticationFactorAuthenticationResult { SecondaryAuthenticationFactorAuthenticationResult(std::nullptr_t) noexcept {} }; struct WINRT_EBO SecondaryAuthenticationFactorAuthenticationStageChangedEventArgs : Windows::Security::Authentication::Identity::Provider::ISecondaryAuthenticationFactorAuthenticationStageChangedEventArgs { SecondaryAuthenticationFactorAuthenticationStageChangedEventArgs(std::nullptr_t) noexcept {} }; struct WINRT_EBO SecondaryAuthenticationFactorAuthenticationStageInfo : Windows::Security::Authentication::Identity::Provider::ISecondaryAuthenticationFactorAuthenticationStageInfo { SecondaryAuthenticationFactorAuthenticationStageInfo(std::nullptr_t) noexcept {} }; struct WINRT_EBO SecondaryAuthenticationFactorInfo : Windows::Security::Authentication::Identity::Provider::ISecondaryAuthenticationFactorInfo, impl::require<SecondaryAuthenticationFactorInfo, Windows::Security::Authentication::Identity::Provider::ISecondaryAuthenticationFactorInfo2> { SecondaryAuthenticationFactorInfo(std::nullptr_t) noexcept {} }; struct WINRT_EBO SecondaryAuthenticationFactorRegistration : Windows::Security::Authentication::Identity::Provider::ISecondaryAuthenticationFactorRegistration { SecondaryAuthenticationFactorRegistration(std::nullptr_t) noexcept {} static Windows::Foundation::IAsyncOperation<winrt::Windows::Security::Authentication::Identity::Provider::SecondaryAuthenticationFactorDevicePresenceMonitoringRegistrationStatus> RegisterDevicePresenceMonitoringAsync(hstring_view deviceId, hstring_view deviceInstancePath, Windows::Security::Authentication::Identity::Provider::SecondaryAuthenticationFactorDevicePresenceMonitoringMode monitoringMode); static Windows::Foundation::IAsyncOperation<winrt::Windows::Security::Authentication::Identity::Provider::SecondaryAuthenticationFactorDevicePresenceMonitoringRegistrationStatus> RegisterDevicePresenceMonitoringAsync(hstring_view deviceId, hstring_view deviceInstancePath, Windows::Security::Authentication::Identity::Provider::SecondaryAuthenticationFactorDevicePresenceMonitoringMode monitoringMode, hstring_view deviceFriendlyName, hstring_view deviceModelNumber, const Windows::Storage::Streams::IBuffer & deviceConfigurationData); static Windows::Foundation::IAsyncAction UnregisterDevicePresenceMonitoringAsync(hstring_view deviceId); static bool IsDevicePresenceMonitoringSupported(); static Windows::Foundation::IAsyncOperation<Windows::Security::Authentication::Identity::Provider::SecondaryAuthenticationFactorRegistrationResult> RequestStartRegisteringDeviceAsync(hstring_view deviceId, Windows::Security::Authentication::Identity::Provider::SecondaryAuthenticationFactorDeviceCapabilities capabilities, hstring_view deviceFriendlyName, hstring_view deviceModelNumber, const Windows::Storage::Streams::IBuffer & deviceKey, const Windows::Storage::Streams::IBuffer & mutualAuthenticationKey); static Windows::Foundation::IAsyncOperation<Windows::Foundation::Collections::IVectorView<Windows::Security::Authentication::Identity::Provider::SecondaryAuthenticationFactorInfo>> FindAllRegisteredDeviceInfoAsync(Windows::Security::Authentication::Identity::Provider::SecondaryAuthenticationFactorDeviceFindScope queryType); static Windows::Foundation::IAsyncAction UnregisterDeviceAsync(hstring_view deviceId); static Windows::Foundation::IAsyncAction UpdateDeviceConfigurationDataAsync(hstring_view deviceId, const Windows::Storage::Streams::IBuffer & deviceConfigurationData); }; struct WINRT_EBO SecondaryAuthenticationFactorRegistrationResult : Windows::Security::Authentication::Identity::Provider::ISecondaryAuthenticationFactorRegistrationResult { SecondaryAuthenticationFactorRegistrationResult(std::nullptr_t) noexcept {} }; } }
#include <utility> #include <algorithm> #include <iostream> #include <vector> #include <map> #include <string.h> int main() { static const std::vector<const char*> values{"a", "b", "c", "d"}; int c = std::any_of(values.begin(), values.end(), [](const char* v) { return strcmp(v, "a") != 0; }); std::cout << c << std::endl; // braced initializer trick static const std::map<int, std::pair<const char*, const char*>> tags{ {1, {"2", "3"} }, {2, {"3", "4"} } }; std::map<int, int> a1; std::map<int, int> b1; a1[1] = 2; a1[3] = 4; b1 = a1; std::cout << b1[3] << std::endl; int ai[3]{1,2,3}; int bi[3]; bi = ai; std::cout << bi[2] << std::endl; }
// // main.cpp // Quazy Quaves // // Created by Lee Mulvey on 2019-03-31. // Copyright © 2019 Lee Mulvey. All rights reserved. // #include "game.h" int main( int argc, char* args[] ) { Game game; return 0; }
/*====================================================================* - Copyright (C) 2001 Leptonica. All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions - are met: - 1. Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - 2. 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. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL ANY - 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. *====================================================================*/ /* * kernel.c * * Basic operations on kernels for image convolution * * Create/destroy/copy * L_KERNEL *kernelCreate() * void kernelDestroy() * L_KERNEL *kernelCopy() * * Accessors: * l_int32 kernelGetElement() * l_int32 kernelSetElement() * l_int32 kernelGetParameters() * l_int32 kernelSetOrigin() * l_int32 kernelGetSum() * l_int32 kernelGetMinMax() * * Normalize/invert * L_KERNEL *kernelNormalize() * L_KERNEL *kernelInvert() * * Helper function * l_float32 **create2dFloatArray() * * Serialized I/O * L_KERNEL *kernelRead() * L_KERNEL *kernelReadStream() * l_int32 kernelWrite() * l_int32 kernelWriteStream() * * Making a kernel from a compiled string * L_KERNEL *kernelCreateFromString() * * Making a kernel from a simple file format * L_KERNEL *kernelCreateFromFile() * * Making a kernel from a Pix * L_KERNEL *kernelCreateFromPix() * * Display a kernel in a pix * PIX *kernelDisplayInPix() * * Parse string to extract numbers * NUMA *parseStringForNumbers() * * Simple parametric kernels * L_KERNEL *makeFlatKernel() * L_KERNEL *makeGaussianKernel() * L_KERNEL *makeGaussianKernelSep() * L_KERNEL *makeDoGKernel() */ #include <string.h> #include <math.h> #include "allheaders.h" /*------------------------------------------------------------------------* * Create / Destroy * *------------------------------------------------------------------------*/ /*! * kernelCreate() * * Input: height, width * Return: kernel, or null on error * * Notes: * (1) kernelCreate() initializes all values to 0. * (2) After this call, (cy,cx) and nonzero data values must be * assigned. */ L_KERNEL * kernelCreate(l_int32 height, l_int32 width) { L_KERNEL *kel; PROCNAME("kernelCreate"); if ((kel = (L_KERNEL *)CALLOC(1, sizeof(L_KERNEL))) == NULL) { return (L_KERNEL *)ERROR_PTR("kel not made", procName, NULL); } kel->sy = height; kel->sx = width; if ((kel->data = create2dFloatArray(height, width)) == NULL) { return (L_KERNEL *)ERROR_PTR("data not allocated", procName, NULL); } return kel; } /*! * kernelDestroy() * * Input: &kel (<to be nulled>) * Return: void */ void kernelDestroy(L_KERNEL **pkel) { l_int32 i; L_KERNEL *kel; PROCNAME("kernelDestroy"); if (pkel == NULL) { L_WARNING("ptr address is NULL!\n", procName); return; } if ((kel = *pkel) == NULL) { return; } for (i = 0; i < kel->sy; i++) { FREE(kel->data[i]); } FREE(kel->data); FREE(kel); *pkel = NULL; return; } /*! * kernelCopy() * * Input: kels (source kernel) * Return: keld (copy of kels), or null on error */ L_KERNEL * kernelCopy(L_KERNEL *kels) { l_int32 i, j, sx, sy, cx, cy; L_KERNEL *keld; PROCNAME("kernelCopy"); if (!kels) { return (L_KERNEL *)ERROR_PTR("kels not defined", procName, NULL); } kernelGetParameters(kels, &sy, &sx, &cy, &cx); if ((keld = kernelCreate(sy, sx)) == NULL) { return (L_KERNEL *)ERROR_PTR("keld not made", procName, NULL); } keld->cy = cy; keld->cx = cx; for (i = 0; i < sy; i++) for (j = 0; j < sx; j++) { keld->data[i][j] = kels->data[i][j]; } return keld; } /*----------------------------------------------------------------------* * Accessors * *----------------------------------------------------------------------*/ /*! * kernelGetElement() * * Input: kel * row * col * &val * Return: 0 if OK; 1 on error */ l_int32 kernelGetElement(L_KERNEL *kel, l_int32 row, l_int32 col, l_float32 *pval) { PROCNAME("kernelGetElement"); if (!pval) { return ERROR_INT("&val not defined", procName, 1); } *pval = 0; if (!kel) { return ERROR_INT("kernel not defined", procName, 1); } if (row < 0 || row >= kel->sy) { return ERROR_INT("kernel row out of bounds", procName, 1); } if (col < 0 || col >= kel->sx) { return ERROR_INT("kernel col out of bounds", procName, 1); } *pval = kel->data[row][col]; return 0; } /*! * kernelSetElement() * * Input: kernel * row * col * val * Return: 0 if OK; 1 on error */ l_int32 kernelSetElement(L_KERNEL *kel, l_int32 row, l_int32 col, l_float32 val) { PROCNAME("kernelSetElement"); if (!kel) { return ERROR_INT("kel not defined", procName, 1); } if (row < 0 || row >= kel->sy) { return ERROR_INT("kernel row out of bounds", procName, 1); } if (col < 0 || col >= kel->sx) { return ERROR_INT("kernel col out of bounds", procName, 1); } kel->data[row][col] = val; return 0; } /*! * kernelGetParameters() * * Input: kernel * &sy, &sx, &cy, &cx (<optional return>; each can be null) * Return: 0 if OK, 1 on error */ l_int32 kernelGetParameters(L_KERNEL *kel, l_int32 *psy, l_int32 *psx, l_int32 *pcy, l_int32 *pcx) { PROCNAME("kernelGetParameters"); if (psy) { *psy = 0; } if (psx) { *psx = 0; } if (pcy) { *pcy = 0; } if (pcx) { *pcx = 0; } if (!kel) { return ERROR_INT("kernel not defined", procName, 1); } if (psy) { *psy = kel->sy; } if (psx) { *psx = kel->sx; } if (pcy) { *pcy = kel->cy; } if (pcx) { *pcx = kel->cx; } return 0; } /*! * kernelSetOrigin() * * Input: kernel * cy, cx * Return: 0 if OK; 1 on error */ l_int32 kernelSetOrigin(L_KERNEL *kel, l_int32 cy, l_int32 cx) { PROCNAME("kernelSetOrigin"); if (!kel) { return ERROR_INT("kel not defined", procName, 1); } kel->cy = cy; kel->cx = cx; return 0; } /*! * kernelGetSum() * * Input: kernel * &sum (<return> sum of all kernel values) * Return: 0 if OK, 1 on error */ l_int32 kernelGetSum(L_KERNEL *kel, l_float32 *psum) { l_int32 sx, sy, i, j; PROCNAME("kernelGetSum"); if (!psum) { return ERROR_INT("&sum not defined", procName, 1); } *psum = 0.0; if (!kel) { return ERROR_INT("kernel not defined", procName, 1); } kernelGetParameters(kel, &sy, &sx, NULL, NULL); for (i = 0; i < sy; i++) { for (j = 0; j < sx; j++) { *psum += kel->data[i][j]; } } return 0; } /*! * kernelGetMinMax() * * Input: kernel * &min (<optional return> minimum value) * &max (<optional return> maximum value) * Return: 0 if OK, 1 on error */ l_int32 kernelGetMinMax(L_KERNEL *kel, l_float32 *pmin, l_float32 *pmax) { l_int32 sx, sy, i, j; l_float32 val, minval, maxval; PROCNAME("kernelGetMinmax"); if (!pmin && !pmax) { return ERROR_INT("neither &min nor &max defined", procName, 1); } if (pmin) { *pmin = 0.0; } if (pmax) { *pmax = 0.0; } if (!kel) { return ERROR_INT("kernel not defined", procName, 1); } kernelGetParameters(kel, &sy, &sx, NULL, NULL); minval = 10000000.0; maxval = -10000000.0; for (i = 0; i < sy; i++) { for (j = 0; j < sx; j++) { val = kel->data[i][j]; if (val < minval) { minval = val; } if (val > maxval) { maxval = val; } } } if (pmin) { *pmin = minval; } if (pmax) { *pmax = maxval; } return 0; } /*----------------------------------------------------------------------* * Normalize/Invert * *----------------------------------------------------------------------*/ /*! * kernelNormalize() * * Input: kels (source kel, to be normalized) * normsum (desired sum of elements in keld) * Return: keld (normalized version of kels), or null on error * or if sum of elements is very close to 0) * * Notes: * (1) If the sum of kernel elements is close to 0, do not * try to calculate the normalized kernel. Instead, * return a copy of the input kernel, with a warning. */ L_KERNEL * kernelNormalize(L_KERNEL *kels, l_float32 normsum) { l_int32 i, j, sx, sy, cx, cy; l_float32 sum, factor; L_KERNEL *keld; PROCNAME("kernelNormalize"); if (!kels) { return (L_KERNEL *)ERROR_PTR("kels not defined", procName, NULL); } kernelGetSum(kels, &sum); if (L_ABS(sum) < 0.00001) { L_WARNING("null sum; not normalizing; returning a copy\n", procName); return kernelCopy(kels); } kernelGetParameters(kels, &sy, &sx, &cy, &cx); if ((keld = kernelCreate(sy, sx)) == NULL) { return (L_KERNEL *)ERROR_PTR("keld not made", procName, NULL); } keld->cy = cy; keld->cx = cx; factor = normsum / sum; for (i = 0; i < sy; i++) for (j = 0; j < sx; j++) { keld->data[i][j] = factor * kels->data[i][j]; } return keld; } /*! * kernelInvert() * * Input: kels (source kel, to be inverted) * Return: keld (spatially inverted, about the origin), or null on error * * Notes: * (1) For convolution, the kernel is spatially inverted before * a "correlation" operation is done between the kernel and the image. */ L_KERNEL * kernelInvert(L_KERNEL *kels) { l_int32 i, j, sx, sy, cx, cy; L_KERNEL *keld; PROCNAME("kernelInvert"); if (!kels) { return (L_KERNEL *)ERROR_PTR("kels not defined", procName, NULL); } kernelGetParameters(kels, &sy, &sx, &cy, &cx); if ((keld = kernelCreate(sy, sx)) == NULL) { return (L_KERNEL *)ERROR_PTR("keld not made", procName, NULL); } keld->cy = sy - 1 - cy; keld->cx = sx - 1 - cx; for (i = 0; i < sy; i++) for (j = 0; j < sx; j++) { keld->data[i][j] = kels->data[sy - 1 - i][sx - 1 - j]; } return keld; } /*----------------------------------------------------------------------* * Helper function * *----------------------------------------------------------------------*/ /*! * create2dFloatArray() * * Input: sy (rows == height) * sx (columns == width) * Return: doubly indexed array (i.e., an array of sy row pointers, * each of which points to an array of sx floats) * * Notes: * (1) The array[sy][sx] is indexed in standard "matrix notation", * with the row index first. */ l_float32 ** create2dFloatArray(l_int32 sy, l_int32 sx) { l_int32 i; l_float32 **array; PROCNAME("create2dFloatArray"); if ((array = (l_float32 **)CALLOC(sy, sizeof(l_float32 *))) == NULL) { return (l_float32 **)ERROR_PTR("ptr array not made", procName, NULL); } for (i = 0; i < sy; i++) { if ((array[i] = (l_float32 *)CALLOC(sx, sizeof(l_float32))) == NULL) { return (l_float32 **)ERROR_PTR("array not made", procName, NULL); } } return array; } /*----------------------------------------------------------------------* * Kernel serialized I/O * *----------------------------------------------------------------------*/ /*! * kernelRead() * * Input: filename * Return: kernel, or null on error */ L_KERNEL * kernelRead(const char *fname) { FILE *fp; L_KERNEL *kel; PROCNAME("kernelRead"); if (!fname) { return (L_KERNEL *)ERROR_PTR("fname not defined", procName, NULL); } if ((fp = fopenReadStream(fname)) == NULL) { return (L_KERNEL *)ERROR_PTR("stream not opened", procName, NULL); } if ((kel = kernelReadStream(fp)) == NULL) { return (L_KERNEL *)ERROR_PTR("kel not returned", procName, NULL); } fclose(fp); return kel; } /*! * kernelReadStream() * * Input: stream * Return: kernel, or null on error */ L_KERNEL * kernelReadStream(FILE *fp) { l_int32 sy, sx, cy, cx, i, j, ret, version, ignore; L_KERNEL *kel; PROCNAME("kernelReadStream"); if (!fp) { return (L_KERNEL *)ERROR_PTR("stream not defined", procName, NULL); } ret = fscanf(fp, " Kernel Version %d\n", &version); if (ret != 1) { return (L_KERNEL *)ERROR_PTR("not a kernel file", procName, NULL); } if (version != KERNEL_VERSION_NUMBER) { return (L_KERNEL *)ERROR_PTR("invalid kernel version", procName, NULL); } if (fscanf(fp, " sy = %d, sx = %d, cy = %d, cx = %d\n", &sy, &sx, &cy, &cx) != 4) { return (L_KERNEL *)ERROR_PTR("dimensions not read", procName, NULL); } if ((kel = kernelCreate(sy, sx)) == NULL) { return (L_KERNEL *)ERROR_PTR("kel not made", procName, NULL); } kernelSetOrigin(kel, cy, cx); for (i = 0; i < sy; i++) { for (j = 0; j < sx; j++) { ignore = fscanf(fp, "%15f", &kel->data[i][j]); } ignore = fscanf(fp, "\n"); } ignore = fscanf(fp, "\n"); return kel; } /*! * kernelWrite() * * Input: fname (output file) * kernel * Return: 0 if OK, 1 on error */ l_int32 kernelWrite(const char *fname, L_KERNEL *kel) { FILE *fp; PROCNAME("kernelWrite"); if (!fname) { return ERROR_INT("fname not defined", procName, 1); } if (!kel) { return ERROR_INT("kel not defined", procName, 1); } if ((fp = fopenWriteStream(fname, "wb")) == NULL) { return ERROR_INT("stream not opened", procName, 1); } kernelWriteStream(fp, kel); fclose(fp); return 0; } /*! * kernelWriteStream() * * Input: stream * kel * Return: 0 if OK, 1 on error */ l_int32 kernelWriteStream(FILE *fp, L_KERNEL *kel) { l_int32 sx, sy, cx, cy, i, j; PROCNAME("kernelWriteStream"); if (!fp) { return ERROR_INT("stream not defined", procName, 1); } if (!kel) { return ERROR_INT("kel not defined", procName, 1); } kernelGetParameters(kel, &sy, &sx, &cy, &cx); fprintf(fp, " Kernel Version %d\n", KERNEL_VERSION_NUMBER); fprintf(fp, " sy = %d, sx = %d, cy = %d, cx = %d\n", sy, sx, cy, cx); for (i = 0; i < sy; i++) { for (j = 0; j < sx; j++) { fprintf(fp, "%15.4f", kel->data[i][j]); } fprintf(fp, "\n"); } fprintf(fp, "\n"); return 0; } /*----------------------------------------------------------------------* * Making a kernel from a compiled string * *----------------------------------------------------------------------*/ /*! * kernelCreateFromString() * * Input: height, width * cy, cx (origin) * kdata * Return: kernel of the given size, or null on error * * Notes: * (1) The data is an array of chars, in row-major order, giving * space separated integers in the range [-255 ... 255]. * (2) The only other formatting limitation is that you must * leave space between the last number in each row and * the double-quote. If possible, it's also nice to have each * line in the string represent a line in the kernel; e.g., * static const char *kdata = * " 20 50 20 " * " 70 140 70 " * " 20 50 20 "; */ L_KERNEL * kernelCreateFromString(l_int32 h, l_int32 w, l_int32 cy, l_int32 cx, const char *kdata) { l_int32 n, i, j, index; l_float32 val; L_KERNEL *kel; NUMA *na; PROCNAME("kernelCreateFromString"); if (h < 1) { return (L_KERNEL *)ERROR_PTR("height must be > 0", procName, NULL); } if (w < 1) { return (L_KERNEL *)ERROR_PTR("width must be > 0", procName, NULL); } if (cy < 0 || cy >= h) { return (L_KERNEL *)ERROR_PTR("cy invalid", procName, NULL); } if (cx < 0 || cx >= w) { return (L_KERNEL *)ERROR_PTR("cx invalid", procName, NULL); } kel = kernelCreate(h, w); kernelSetOrigin(kel, cy, cx); na = parseStringForNumbers(kdata, " \t\n"); n = numaGetCount(na); if (n != w * h) { numaDestroy(&na); fprintf(stderr, "w = %d, h = %d, num ints = %d\n", w, h, n); return (L_KERNEL *)ERROR_PTR("invalid integer data", procName, NULL); } index = 0; for (i = 0; i < h; i++) { for (j = 0; j < w; j++) { numaGetFValue(na, index, &val); kernelSetElement(kel, i, j, val); index++; } } numaDestroy(&na); return kel; } /*----------------------------------------------------------------------* * Making a kernel from a simple file format * *----------------------------------------------------------------------*/ /*! * kernelCreateFromFile() * * Input: filename * Return: kernel, or null on error * * Notes: * (1) The file contains, in the following order: * - Any number of comment lines starting with '#' are ignored * - The height and width of the kernel * - The y and x values of the kernel origin * - The kernel data, formatted as lines of numbers (integers * or floats) for the kernel values in row-major order, * and with no other punctuation. * (Note: this differs from kernelCreateFromString(), * where each line must begin and end with a double-quote * to tell the compiler it's part of a string.) * - The kernel specification ends when a blank line, * a comment line, or the end of file is reached. * (2) All lines must be left-justified. * (3) See kernelCreateFromString() for a description of the string * format for the kernel data. As an example, here are the lines * of a valid kernel description file In the file, all lines * are left-justified: * # small 3x3 kernel * 3 3 * 1 1 * 25.5 51 24.3 * 70.2 146.3 73.4 * 20 50.9 18.4 */ L_KERNEL * kernelCreateFromFile(const char *filename) { char *filestr, *line; l_int32 nlines, i, j, first, index, w, h, cx, cy, n; l_float32 val; size_t size; NUMA *na, *nat; SARRAY *sa; L_KERNEL *kel; PROCNAME("kernelCreateFromFile"); if (!filename) { return (L_KERNEL *)ERROR_PTR("filename not defined", procName, NULL); } filestr = (char *)l_binaryRead(filename, &size); sa = sarrayCreateLinesFromString(filestr, 1); FREE(filestr); nlines = sarrayGetCount(sa); /* Find the first data line. */ for (i = 0; i < nlines; i++) { line = sarrayGetString(sa, i, L_NOCOPY); if (line[0] != '#') { first = i; break; } } /* Find the kernel dimensions and origin location. */ line = sarrayGetString(sa, first, L_NOCOPY); if (sscanf(line, "%d %d", &h, &w) != 2) { return (L_KERNEL *)ERROR_PTR("error reading h,w", procName, NULL); } line = sarrayGetString(sa, first + 1, L_NOCOPY); if (sscanf(line, "%d %d", &cy, &cx) != 2) { return (L_KERNEL *)ERROR_PTR("error reading cy,cx", procName, NULL); } /* Extract the data. This ends when we reach eof, or when we * encounter a line of data that is either a null string or * contains just a newline. */ na = numaCreate(0); for (i = first + 2; i < nlines; i++) { line = sarrayGetString(sa, i, L_NOCOPY); if (line[0] == '\0' || line[0] == '\n' || line[0] == '#') { break; } nat = parseStringForNumbers(line, " \t\n"); numaJoin(na, nat, 0, -1); numaDestroy(&nat); } sarrayDestroy(&sa); n = numaGetCount(na); if (n != w * h) { numaDestroy(&na); fprintf(stderr, "w = %d, h = %d, num ints = %d\n", w, h, n); return (L_KERNEL *)ERROR_PTR("invalid integer data", procName, NULL); } kel = kernelCreate(h, w); kernelSetOrigin(kel, cy, cx); index = 0; for (i = 0; i < h; i++) { for (j = 0; j < w; j++) { numaGetFValue(na, index, &val); kernelSetElement(kel, i, j, val); index++; } } numaDestroy(&na); return kel; } /*----------------------------------------------------------------------* * Making a kernel from a Pix * *----------------------------------------------------------------------*/ /*! * kernelCreateFromPix() * * Input: pix * cy, cx (origin of kernel) * Return: kernel, or null on error * * Notes: * (1) The origin must be positive and within the dimensions of the pix. */ L_KERNEL * kernelCreateFromPix(PIX *pix, l_int32 cy, l_int32 cx) { l_int32 i, j, w, h, d; l_uint32 val; L_KERNEL *kel; PROCNAME("kernelCreateFromPix"); if (!pix) { return (L_KERNEL *)ERROR_PTR("pix not defined", procName, NULL); } pixGetDimensions(pix, &w, &h, &d); if (d != 8) { return (L_KERNEL *)ERROR_PTR("pix not 8 bpp", procName, NULL); } if (cy < 0 || cx < 0 || cy >= h || cx >= w) { return (L_KERNEL *)ERROR_PTR("(cy, cx) invalid", procName, NULL); } kel = kernelCreate(h, w); kernelSetOrigin(kel, cy, cx); for (i = 0; i < h; i++) { for (j = 0; j < w; j++) { pixGetPixel(pix, j, i, &val); kernelSetElement(kel, i, j, (l_float32)val); } } return kel; } /*----------------------------------------------------------------------* * Display a kernel in a pix * *----------------------------------------------------------------------*/ /*! * kernelDisplayInPix() * * Input: kernel * size (of grid interiors; odd; either 1 or a minimum size * of 17 is enforced) * gthick (grid thickness; either 0 or a minimum size of 2 * is enforced) * Return: pix (display of kernel), or null on error * * Notes: * (1) This gives a visual representation of a kernel. * (2) There are two modes of display: * (a) Grid lines of minimum width 2, surrounding regions * representing kernel elements of minimum size 17, * with a "plus" mark at the kernel origin, or * (b) A pix without grid lines and using 1 pixel per kernel element. * (3) For both cases, the kernel absolute value is displayed, * normalized such that the maximum absolute value is 255. * (4) Large 2D separable kernels should be used for convolution * with two 1D kernels. However, for the bilateral filter, * the computation time is independent of the size of the * 2D content kernel. */ PIX * kernelDisplayInPix(L_KERNEL *kel, l_int32 size, l_int32 gthick) { l_int32 i, j, w, h, sx, sy, cx, cy, width, x0, y0; l_int32 normval; l_float32 minval, maxval, max, val, norm; PIX *pixd, *pixt0, *pixt1; PROCNAME("kernelDisplayInPix"); if (!kel) { return (PIX *)ERROR_PTR("kernel not defined", procName, NULL); } /* Normalize the max value to be 255 for display */ kernelGetParameters(kel, &sy, &sx, &cy, &cx); kernelGetMinMax(kel, &minval, &maxval); max = L_MAX(maxval, -minval); if (max == 0.0) { return (PIX *)ERROR_PTR("kernel elements all 0.0", procName, NULL); } norm = 255. / (l_float32)max; /* Handle the 1 element/pixel case; typically with large kernels */ if (size == 1 && gthick == 0) { pixd = pixCreate(sx, sy, 8); for (i = 0; i < sy; i++) { for (j = 0; j < sx; j++) { kernelGetElement(kel, i, j, &val); normval = (l_int32)(norm * L_ABS(val)); pixSetPixel(pixd, j, i, normval); } } return pixd; } /* Enforce the constraints for the grid line version */ if (size < 17) { L_WARNING("size < 17; setting to 17\n", procName); size = 17; } if (size % 2 == 0) { size++; } if (gthick < 2) { L_WARNING("grid thickness < 2; setting to 2\n", procName); gthick = 2; } w = size * sx + gthick * (sx + 1); h = size * sy + gthick * (sy + 1); pixd = pixCreate(w, h, 8); /* Generate grid lines */ for (i = 0; i <= sy; i++) pixRenderLine(pixd, 0, gthick / 2 + i * (size + gthick), w - 1, gthick / 2 + i * (size + gthick), gthick, L_SET_PIXELS); for (j = 0; j <= sx; j++) pixRenderLine(pixd, gthick / 2 + j * (size + gthick), 0, gthick / 2 + j * (size + gthick), h - 1, gthick, L_SET_PIXELS); /* Generate mask for each element */ pixt0 = pixCreate(size, size, 1); pixSetAll(pixt0); /* Generate crossed lines for origin pattern */ pixt1 = pixCreate(size, size, 1); width = size / 8; pixRenderLine(pixt1, size / 2, (l_int32)(0.12 * size), size / 2, (l_int32)(0.88 * size), width, L_SET_PIXELS); pixRenderLine(pixt1, (l_int32)(0.15 * size), size / 2, (l_int32)(0.85 * size), size / 2, width, L_FLIP_PIXELS); pixRasterop(pixt1, size / 2 - width, size / 2 - width, 2 * width, 2 * width, PIX_NOT(PIX_DST), NULL, 0, 0); /* Paste the patterns in */ y0 = gthick; for (i = 0; i < sy; i++) { x0 = gthick; for (j = 0; j < sx; j++) { kernelGetElement(kel, i, j, &val); normval = (l_int32)(norm * L_ABS(val)); pixSetMaskedGeneral(pixd, pixt0, normval, x0, y0); if (i == cy && j == cx) { pixPaintThroughMask(pixd, pixt1, x0, y0, 255 - normval); } x0 += size + gthick; } y0 += size + gthick; } pixDestroy(&pixt0); pixDestroy(&pixt1); return pixd; } /*------------------------------------------------------------------------* * Parse string to extract numbers * *------------------------------------------------------------------------*/ /*! * parseStringForNumbers() * * Input: string (containing numbers; not changed) * seps (string of characters that can be used between ints) * Return: numa (of numbers found), or null on error * * Note: * (1) The numbers can be ints or floats. */ NUMA * parseStringForNumbers(const char *str, const char *seps) { char *newstr, *head, *tail; l_float32 val; NUMA *na; PROCNAME("parseStringForNumbers"); if (!str) { return (NUMA *)ERROR_PTR("str not defined", procName, NULL); } newstr = stringNew(str); /* to enforce const-ness of str */ na = numaCreate(0); head = strtokSafe(newstr, seps, &tail); val = atof(head); numaAddNumber(na, val); FREE(head); while ((head = strtokSafe(NULL, seps, &tail)) != NULL) { val = atof(head); numaAddNumber(na, val); FREE(head); } FREE(newstr); return na; } /*------------------------------------------------------------------------* * Simple parametric kernels * *------------------------------------------------------------------------*/ /*! * makeFlatKernel() * * Input: height, width * cy, cx (origin of kernel) * Return: kernel, or null on error * * Notes: * (1) This is the same low-pass filtering kernel that is used * in the block convolution functions. * (2) The kernel origin (@cy, @cx) is typically placed as near * the center of the kernel as possible. If height and * width are odd, then using cy = height / 2 and * cx = width / 2 places the origin at the exact center. * (3) This returns a normalized kernel. */ L_KERNEL * makeFlatKernel(l_int32 height, l_int32 width, l_int32 cy, l_int32 cx) { l_int32 i, j; l_float32 normval; L_KERNEL *kel; PROCNAME("makeFlatKernel"); if ((kel = kernelCreate(height, width)) == NULL) { return (L_KERNEL *)ERROR_PTR("kel not made", procName, NULL); } kernelSetOrigin(kel, cy, cx); normval = 1.0 / (l_float32)(height * width); for (i = 0; i < height; i++) { for (j = 0; j < width; j++) { kernelSetElement(kel, i, j, normval); } } return kel; } /*! * makeGaussianKernel() * * Input: halfheight, halfwidth (sx = 2 * halfwidth + 1, etc) * stdev (standard deviation) * max (value at (cx,cy)) * Return: kernel, or null on error * * Notes: * (1) The kernel size (sx, sy) = (2 * halfwidth + 1, 2 * halfheight + 1). * (2) The kernel center (cx, cy) = (halfwidth, halfheight). * (3) The halfwidth and halfheight are typically equal, and * are typically several times larger than the standard deviation. * (4) If pixConvolve() is invoked with normalization (the sum of * kernel elements = 1.0), use 1.0 for max (or any number that's * not too small or too large). */ L_KERNEL * makeGaussianKernel(l_int32 halfheight, l_int32 halfwidth, l_float32 stdev, l_float32 max) { l_int32 sx, sy, i, j; l_float32 val; L_KERNEL *kel; PROCNAME("makeGaussianKernel"); sx = 2 * halfwidth + 1; sy = 2 * halfheight + 1; if ((kel = kernelCreate(sy, sx)) == NULL) { return (L_KERNEL *)ERROR_PTR("kel not made", procName, NULL); } kernelSetOrigin(kel, halfheight, halfwidth); for (i = 0; i < sy; i++) { for (j = 0; j < sx; j++) { val = expf(-(l_float32)((i - halfheight) * (i - halfheight) + (j - halfwidth) * (j - halfwidth)) / (2. * stdev * stdev)); kernelSetElement(kel, i, j, max * val); } } return kel; } /*! * makeGaussianKernelSep() * * Input: halfheight, halfwidth (sx = 2 * halfwidth + 1, etc) * stdev (standard deviation) * max (value at (cx,cy)) * &kelx (<return> x part of kernel) * &kely (<return> y part of kernel) * Return: 0 if OK, 1 on error * * Notes: * (1) See makeGaussianKernel() for description of input parameters. * (2) These kernels are constructed so that the result of both * normalized and un-normalized convolution will be the same * as when convolving with pixConvolve() using the full kernel. * (3) The trick for the un-normalized convolution is to have the * product of the two kernel elemets at (cx,cy) be equal to max, * not max**2. That's why the max for kely is 1.0. If instead * we use sqrt(max) for both, the results are slightly less * accurate, when compared to using the full kernel in * makeGaussianKernel(). */ l_int32 makeGaussianKernelSep(l_int32 halfheight, l_int32 halfwidth, l_float32 stdev, l_float32 max, L_KERNEL **pkelx, L_KERNEL **pkely) { PROCNAME("makeGaussianKernelSep"); if (!pkelx || !pkely) { return ERROR_INT("&kelx and &kely not defined", procName, 1); } *pkelx = makeGaussianKernel(0, halfwidth, stdev, max); *pkely = makeGaussianKernel(halfheight, 0, stdev, 1.0); return 0; } /*! * makeDoGKernel() * * Input: halfheight, halfwidth (sx = 2 * halfwidth + 1, etc) * stdev (standard deviation of narrower gaussian) * ratio (of stdev for wide filter to stdev for narrow one) * Return: kernel, or null on error * * Notes: * (1) The DoG (difference of gaussians) is a wavelet mother * function with null total sum. By subtracting two blurred * versions of the image, it acts as a bandpass filter for * frequencies passed by the narrow gaussian but stopped * by the wide one.See: * http://en.wikipedia.org/wiki/Difference_of_Gaussians * (2) The kernel size (sx, sy) = (2 * halfwidth + 1, 2 * halfheight + 1). * (3) The kernel center (cx, cy) = (halfwidth, halfheight). * (4) The halfwidth and halfheight are typically equal, and * are typically several times larger than the standard deviation. * (5) The ratio is the ratio of standard deviations of the wide * to narrow gaussian. It must be >= 1.0; 1.0 is a no-op. * (6) Because the kernel is a null sum, it must be invoked without * normalization in pixConvolve(). */ L_KERNEL * makeDoGKernel(l_int32 halfheight, l_int32 halfwidth, l_float32 stdev, l_float32 ratio) { l_int32 sx, sy, i, j; l_float32 pi, squaredist, highnorm, lownorm, val; L_KERNEL *kel; PROCNAME("makeDoGKernel"); sx = 2 * halfwidth + 1; sy = 2 * halfheight + 1; if ((kel = kernelCreate(sy, sx)) == NULL) { return (L_KERNEL *)ERROR_PTR("kel not made", procName, NULL); } kernelSetOrigin(kel, halfheight, halfwidth); pi = 3.1415926535; for (i = 0; i < sy; i++) { for (j = 0; j < sx; j++) { squaredist = (l_float32)((i - halfheight) * (i - halfheight) + (j - halfwidth) * (j - halfwidth)); highnorm = 1. / (2 * stdev * stdev); lownorm = highnorm / (ratio * ratio); val = (highnorm / pi) * expf(-(highnorm * squaredist)) - (lownorm / pi) * expf(-(lownorm * squaredist)); kernelSetElement(kel, i, j, val); } } return kel; }
#ifndef MEM_H #define MEM_H #include "reg_def.h" #include <cstdio> class MEM { public: unsigned char type; ERROR_NUM err_no; MEM(); void set_Reg(unsigned int arg_rd, unsigned long long arg_alu, unsigned long long arg_data); void set_pc(REG arg_pc); void set_ctrl(INST32_CTRL_BIT arg_ctrl); ERROR_NUM MemRW(char* memory); void get_meminfo(unsigned long long &addr, int &read, int &size); unsigned long long get_mem_content(); REG get_pc(); INST32_CTRL_BIT get_ctrl(); unsigned long long get_alu(); unsigned int get_rd(); void print(); unsigned long long get_cycles(); private: REG pc; unsigned int rd; unsigned long long alu, data; unsigned long long mem_content; INST32_CTRL_BIT ctrl; MEMRW_CTRL get_MemRW(); }; #endif // MEM_H
#pragma warning(default:4996) #include "std_lib_facilities.h" #include "Image.h" #include "ImageIOBase.h" #include "ImageIOFactory.h" #include "ImageFilter.h" #include "ThresholdImageFilter.h" #include "StatisticsImageFilter.h" #include "MaskImageFilter.h" #include "ConvolutionImageFilter.h" #include "ComplementImageFilter.h" #include <memory> int main() { cout << "Please enter input filename: \n"; string iname; cin >> iname; try { unique_ptr<ImageIOBase> io = ImageIOFactory::getIO(iname); //handle the output filename string extension = iname.substr(iname.find('.')); int position = iname.find('.'); string name = iname.substr(0, position); //read the input image Image image = io->read(); //Threshold Image Filter ThresholdImageFilter threshFilter; threshFilter.setInput(image); int thresh=500; //user-defined threshold value threshFilter.setThreshold(thresh); threshFilter.update(); shared_ptr<Image> image_out_thresh = threshFilter.getOutput(); string nameOUT_thresh = name + "_threshold" + to_string(thresh) + "_out" + extension; io = ImageIOFactory::getIO(nameOUT_thresh); io->write(*image_out_thresh); //Statistics Image Filter StatisticsImageFilter statFilter; statFilter.setInput(image); statFilter.update(); int maxValue = statFilter.getMaxIntensity(); int minValue = statFilter.getMinIntensity(); int meanValue = statFilter.getMeanIntensity(); //Mask Image Filter MaskImageFilter maskFilter; maskFilter.setInput(image); maskFilter.setMask(*image_out_thresh); //binary image obtained after the threshold application maskFilter.update(); shared_ptr<Image> image_out_mask = maskFilter.getOutput(); string nameOUT_mask = name + "_mask" + "_out" + extension; io = ImageIOFactory::getIO(nameOUT_mask); io->write(*image_out_mask); //Convolution Image Filter ConvolutionImageFilter convFilter; convFilter.setInput(image); int convolutionRadius = 5; //user-defined kernel radius convFilter.setRadius(convolutionRadius); convFilter.update(); shared_ptr<Image> image_out_conv = convFilter.getOutput(); string nameOUT_conv = name + "_convolution" + to_string(convolutionRadius) + "_out" + extension; io = ImageIOFactory::getIO(nameOUT_conv); io->write(*image_out_conv); //Complement Image Filter ComplementImageFilter compFilter; compFilter.setInput(image); compFilter.update(); shared_ptr<Image> image_out_comp = compFilter.getOutput(); string nameÏUT_comp = name + "_complement" + "_out" + extension; io = ImageIOFactory::getIO(nameÏUT_comp); io->write(*image_out_comp); } catch (const char* exception) { cerr << "Error: " << exception << endl; } }
#ifndef _IRIN_SERVICE_HEADER_H_ #define _IRIN_SERVICE_HEADER_H_ #include "server/http-response.h" #include "services/content-service.h" #include "services/proxy-service.h" #include <vector> class IrinService { public: IrinService(std::vector<std::string> proxy_uris, std::unique_ptr<ContentService> &content_service, std::unique_ptr<ProxyService> &proxy_service); std::unique_ptr<HttpResponse> Handle(const std::unique_ptr<HttpRequest> &request); private: std::vector<std::string> proxy_uris_; std::unique_ptr<ContentService> content_service_; std::unique_ptr<ProxyService> proxy_service_; std::string parse_uri_root(const std::string &request_uri); }; #endif
#include<bits/stdc++.h> using namespace std; #define maxN 100001 vector<int>adj[maxN]; void dfs(int node,int des,vector<int>x) { x.push_back(node); if(node==des) { for(int i=0;i<x.size();i++) cout<<x[i]<<" "; cout<<"\n"; return; } for(int child:adj[node]) { dfs(child,des,x); } x.pop_back(); } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); int n,m,a,b; cin>>n>>m; for(int i=0;i<m;i++) { cin>>a>>b; adj[a].push_back(b); // directed graph } vector<int>x; dfs(1,n,x); }
#include<iostream> using namespace std; typedef int TypeValue; int m,n; int data[80][80]; TypeValue dp[80][80]; TypeValue process(int row) { for(int i=0;i<n;i++) { for(int j=i+1;j<n;j++) { for(int k=i;k<j;k++) { dp[i][j]=max(dp[i][k]+dp[k+1][j]+data[ } } } return 0; } int main() { }
#pragma once // // ART.h // PianoPlayer // // Created by Ben Smith on 10/10/11. // Copyright 2011 __MyCompanyName__. All rights reserved. // #include "artCategory.h" #include <vector.h> #include "OSCSend.h" #define RECENCY_DECAY_RATE 0.99 // how quickly the recency vector decays. This is how quickly ideas become familiar and no longer fresh #define OBSERVATION_VALUE 0.01 // how much an observation weights a category. //#define USING_RECENCY // comment out to block using the recency vector during importance calculations using namespace std; class ART { private: int mDimensions; // how many dimensions to match data on vector<ArtCategory*> mCategories; vector<ResonanceGroup> mResonanceWeights; vector<double> mObservations; // how many times each category has been seen. trying to measure how "confident" we are in the observation int inputCount; // how many inputs we have seen vector<double> mRecency; double maxRecency; double mChoice, mLearnRate, mVigilance; double *input, *choices; int recentChoice, choiceSize; // the most recently chosen category, the size of the choices array double residual; // how much the chosen category changed with the last input/learning step // private member functions void normalizeInput(); inline void complementCode(); void setInput(const double *_in, int size); // set the mVigilance just high enough to reset the chosen category and look again. int increaseVigilance(); void FillCategoryChoice(); void DecayRecency(); public: ART(double _choice, double _learnRate, double _Vigilance); ~ART(); void ProcessNewObservation(const double *input, int length); void setVigilance(double v); void setLearnRate(double v); void setChoice(double v); double GetResidual(); const double* GetCategoryChoice(); int GetCategoryCount(); // how many categories? void AddResonanceGroup(int startIndex, int groupSize, double weight); int makeChoice(); int makeChoice(double workingVigilance); double PredictChoice(); double PredictChoice(double workingVigilance); int GetChosenCategoryID(); double calcDistance(int cat); // use set input and calculate distance to center of specified category const double *getWeights(); // return all of the weights of all of our categories const double* GetWeights(int index); double GetImportanceSum(); double calcDistance(int thatCategory, int thisCategory); // calculate the distance between the two IDd categories double calcCurvature(int thatCategory, int thisCategory); // calculate the angle between the two IDd categories // to store and recover this ART! char* Serialize(int &size); void Deserialize(char* data, int size); };
#include<iostream> #include<cstdlib> #include<conio.h> using namespace std; class node { private: char data; node* next; friend class stack; friend class queue; }; class stack { private: node *head; public: void push(char data); char pop(); int empty(void); void init(); }; class queue { private: node *front; node *rear; public: void enqueue(char data); char dequeue(); int empty(void); void queue::search(char data); void init(); }; int stack::empty(void) { if(head == 0) { cout << "Is empty"<< endl; return 1; } else return 0; } void stack::push(char data) { node* temp = new node; temp->data = data; temp->next = 0; node* p = head; if(head ==0) head = temp; else { temp->next = head; head = temp; } } char stack::pop() { node *p; char data; if( head == 0) { cout << "Is empty" << endl; return NULL; } else { data = head->data; p = head; head = head->next; delete p; return data; } } void stack::init() { head = 0; } void queue::enqueue(char data) { node *temp = new node; temp->data =data; temp->next =0; if (front == 0) { /* 큐가 empty인경우 */ front = temp; rear = temp; } else { rear->next = temp; rear = temp; } } char queue::dequeue() { node *p; char data; if (front == 0) { cout << "Is empty" << endl; front = 0; rear = 0; return NULL; } else { p = front; data = front->data; front = front->next; delete p; return data; if(front == rear) { front = 0; rear = 0; } } } int queue::empty() { if (front == 0) return 1; else return 0; } void queue::search(char data) { node *p; node *q; if( empty() ) { cout << "Is empty" << endl << endl; return; } else { if( front->data == data) cout << "Data is in the list" << endl; else { while(p!=0 && p->data != data) { q=p; p=p->next; } if(p!=0) cout << "Data is in the list" << endl << endl; else cout << "Data is not in the list" << endl << endl; } } } void queue::init() { front = 0; rear = 0; } void main() { stack sta; queue que; sta.init(); que.init(); int select; char data; while(1) { cout << "1.Push 2.Pop 3.Enque 4.Deque 5.SearchQue : "; cin >> select; switch(select) { case 1: cout << "Push data: " ; cin >> data ; sta.push(data); cout << endl; break; case 2: cout << "Pop data: " << sta.pop(); cout << endl << endl;; break; case 3: cout << "Enque data: " ; cin >> data; que.enqueue(data); cout << endl; break; case 4: cout << "Deque data: " << que.dequeue(); cout << endl << endl; break; case 5: cout << "SearchQue data: "; cin >> data; que.search(data); } } }
//////////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2006-2010 MStar Semiconductor, Inc. // All rights reserved. // // Unless otherwise stipulated in writing, any and all information contained // herein regardless in any format shall remain the sole proprietary of // MStar Semiconductor Inc. and be kept in strict confidence // (''MStar Confidential Information'') by the recipient. // Any unauthorized act including without limitation unauthorized disclosure, // copying, use, reproduction, sale, distribution, modification, disassembling, // reverse engineering and compiling of the contents of MStar Confidential // Information is unlawful and strictly prohibited. MStar hereby reserves the // rights to any and all damages, losses, costs and expenses resulting therefrom. // //////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////// // This file is automatically generated by SkinTool [Version:0.2.3][Build:Dec 28 2015 14:35:41] ///////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////// // Window List (Position) WINDOWPOSDATA _MP_TBLSEG _GUI_WindowPositionList_Zui_Channel_List[] = { // HWND_MAINFRAME { HWND_MAINFRAME, HWND_OP_MSGBOX_DELETE_OP_3, { 0, 0, 376, 433 }, }, // HWND_CHLIST_TRANSPARENT_BG { HWND_MAINFRAME, HWND_CHLIST_TRANSPARENT_BG, { 0, 0, 376, 433 }, }, // HWND_CHLIST_BG_PANE { HWND_MAINFRAME, HWND_CHLIST_OP_MENU_BOTTOM_HALF_DELETE_PROFILE_BTN, { 0, 0, 376, 433 }, }, // HWND_CHLIST_BG_L { HWND_CHLIST_BG_PANE, HWND_CHLIST_BG_L, { 0, 0, 3, 433 }, }, // HWND_CHLIST_BG_C { HWND_CHLIST_BG_PANE, HWND_CHLIST_BG_C, { 3, 0, 369, 433 }, }, // HWND_CHLIST_BG_R { HWND_CHLIST_BG_PANE, HWND_CHLIST_BG_R, { 371, 0, 3, 433 }, }, // HWND_CHLIST_TOP_HALF_LIST_BG { HWND_CHLIST_BG_PANE, HWND_CHLIST_TOP_HALF_LIST_BG, { 0, 0, 376, 433 }, }, // HWND_CHLIST_TOP_HALF_BANNER_TITLE { HWND_CHLIST_BG_PANE, HWND_CHLIST_TOP_HALF_BANNER_TITLE, { 0, 0, 376, 45 }, }, // HWND_CHLIST_BOTTOM_HALF_OK_BTN { HWND_CHLIST_BG_PANE, HWND_CHLIST_BOTTOM_HALF_OK_BTN, { 168, 405, 39, 19 }, }, // HWND_CHLIST_BOTTOM_HALF_OP_MENU_BTN { HWND_CHLIST_BG_PANE, HWND_CHLIST_BOTTOM_HALF_OP_MENU_BTN, { 279, 402, 70, 26 }, }, // HWND_CHLIST_OP_BOTTOM_HALF_EXIT_OP_BTN { HWND_CHLIST_BG_PANE, HWND_CHLIST_OP_BOTTOM_HALF_EXIT_OP_BTN, { 279, 402, 70, 26 }, }, // HWND_CHLIST_OP_MENU_BOTTOM_HALF_ENTER_OP_BTN { HWND_CHLIST_BG_PANE, HWND_CHLIST_OP_MENU_BOTTOM_HALF_ENTER_OP_BTN, { 279, 402, 70, 26 }, }, // HWND_CHLIST_OP_MENU_BOTTOM_HALF_DELETE_PROFILE_BTN { HWND_CHLIST_BG_PANE, HWND_CHLIST_OP_MENU_BOTTOM_HALF_DELETE_PROFILE_BTN, { 46, 402, 84, 26 }, }, // HWND_CHLIST_LIST_PANE { HWND_MAINFRAME, HWND_OP_MENU_ITEM9_DELIVERY_SYS_TYPE, { 50, 42, 5, 6 }, }, // HWND_CHLIST_ITEM0 { HWND_CHLIST_LIST_PANE, HWND_OP_MENU_ITEM0_DELIVERY_SYS_TYPE, { 0, 46, 376, 33 }, }, // HWND_CHLIST_ITEM0_TYPE { HWND_CHLIST_ITEM0, HWND_CHLIST_ITEM0_TYPE, { 314, 54, 35, 17 }, }, // HWND_CHLIST_ITEM0_FAV { HWND_CHLIST_ITEM0, HWND_CHLIST_ITEM0_FAV, { 285, 54, 18, 17 }, }, // HWND_CHLIST_ITEM0_SKIP { HWND_CHLIST_ITEM0, HWND_CHLIST_ITEM0_SKIP, { 285, 54, 18, 17 }, }, // HWND_CHLIST_ITEM0_LOCK { HWND_CHLIST_ITEM0, HWND_CHLIST_ITEM0_LOCK, { 256, 54, 18, 17 }, }, // HWND_CHLIST_ITEM0_TEXT { HWND_CHLIST_ITEM0, HWND_CHLIST_ITEM0_TEXT, { 51, 46, 260, 33 }, }, // HWND_CHLIST_ITEM0_SCRAMBLE { HWND_CHLIST_ITEM0, HWND_CHLIST_ITEM0_SCRAMBLE, { 227, 54, 18, 17 }, }, // HWND_CHLIST_ITEM0_UPDOWN_ARROW { HWND_CHLIST_ITEM0, HWND_CHLIST_ITEM0_UPDOWN_ARROW, { 16, 47, 21, 29 }, }, // HWND_OP_MENU_ITEM0_DELIVERY_SYS_TYPE { HWND_CHLIST_ITEM0, HWND_OP_MENU_ITEM0_DELIVERY_SYS_TYPE, { 285, 54, 53, 17 }, }, // HWND_CHLIST_ITEM1 { HWND_CHLIST_LIST_PANE, HWND_OP_MENU_ITEM1_DELIVERY_SYS_TYPE, { 0, 81, 376, 33 }, }, // HWND_CHLIST_ITEM1_TYPE { HWND_CHLIST_ITEM1, HWND_CHLIST_ITEM1_TYPE, { 314, 89, 35, 17 }, }, // HWND_CHLIST_ITEM1_FAV { HWND_CHLIST_ITEM1, HWND_CHLIST_ITEM1_FAV, { 285, 89, 18, 17 }, }, // HWND_CHLIST_ITEM1_SKIP { HWND_CHLIST_ITEM1, HWND_CHLIST_ITEM1_SKIP, { 285, 89, 18, 17 }, }, // HWND_CHLIST_ITEM1_LOCK { HWND_CHLIST_ITEM1, HWND_CHLIST_ITEM1_LOCK, { 256, 89, 18, 17 }, }, // HWND_CHLIST_ITEM1_TEXT { HWND_CHLIST_ITEM1, HWND_CHLIST_ITEM1_TEXT, { 51, 81, 260, 33 }, }, // HWND_CHLIST_ITEM1_SCRAMBLE { HWND_CHLIST_ITEM1, HWND_CHLIST_ITEM1_SCRAMBLE, { 227, 89, 18, 16 }, }, // HWND_CHLIST_ITEM1_UPDOWN_ARROW { HWND_CHLIST_ITEM1, HWND_CHLIST_ITEM1_UPDOWN_ARROW, { 16, 83, 21, 29 }, }, // HWND_OP_MENU_ITEM1_DELIVERY_SYS_TYPE { HWND_CHLIST_ITEM1, HWND_OP_MENU_ITEM1_DELIVERY_SYS_TYPE, { 285, 89, 53, 17 }, }, // HWND_CHLIST_ITEM2 { HWND_CHLIST_LIST_PANE, HWND_OP_MENU_ITEM2_DELIVERY_SYS_TYPE, { 0, 116, 376, 33 }, }, // HWND_CHLIST_ITEM2_TYPE { HWND_CHLIST_ITEM2, HWND_CHLIST_ITEM2_TYPE, { 314, 124, 35, 17 }, }, // HWND_CHLIST_ITEM2_FAV { HWND_CHLIST_ITEM2, HWND_CHLIST_ITEM2_FAV, { 285, 124, 18, 17 }, }, // HWND_CHLIST_ITEM2_SKIP { HWND_CHLIST_ITEM2, HWND_CHLIST_ITEM2_SKIP, { 285, 124, 18, 17 }, }, // HWND_CHLIST_ITEM2_LOCK { HWND_CHLIST_ITEM2, HWND_CHLIST_ITEM2_LOCK, { 256, 124, 18, 17 }, }, // HWND_CHLIST_ITEM2_TEXT { HWND_CHLIST_ITEM2, HWND_CHLIST_ITEM2_TEXT, { 51, 116, 260, 33 }, }, // HWND_CHLIST_ITEM2_SCRAMBLE { HWND_CHLIST_ITEM2, HWND_CHLIST_ITEM2_SCRAMBLE, { 227, 124, 18, 16 }, }, // HWND_CHLIST_ITEM2_UPDOWN_ARROW { HWND_CHLIST_ITEM2, HWND_CHLIST_ITEM2_UPDOWN_ARROW, { 16, 118, 21, 29 }, }, // HWND_OP_MENU_ITEM2_DELIVERY_SYS_TYPE { HWND_CHLIST_ITEM2, HWND_OP_MENU_ITEM2_DELIVERY_SYS_TYPE, { 285, 124, 53, 17 }, }, // HWND_CHLIST_ITEM3 { HWND_CHLIST_LIST_PANE, HWND_OP_MENU_ITEM3_DELIVERY_SYS_TYPE, { 0, 151, 376, 33 }, }, // HWND_CHLIST_ITEM3_TYPE { HWND_CHLIST_ITEM3, HWND_CHLIST_ITEM3_TYPE, { 314, 159, 35, 17 }, }, // HWND_CHLIST_ITEM3_FAV { HWND_CHLIST_ITEM3, HWND_CHLIST_ITEM3_FAV, { 285, 159, 18, 17 }, }, // HWND_CHLIST_ITEM3_SKIP { HWND_CHLIST_ITEM3, HWND_CHLIST_ITEM3_SKIP, { 285, 159, 18, 17 }, }, // HWND_CHLIST_ITEM3_LOCK { HWND_CHLIST_ITEM3, HWND_CHLIST_ITEM3_LOCK, { 256, 159, 18, 17 }, }, // HWND_CHLIST_ITEM3_TEXT { HWND_CHLIST_ITEM3, HWND_CHLIST_ITEM3_TEXT, { 51, 151, 260, 33 }, }, // HWND_CHLIST_ITEM3_SCRAMBLE { HWND_CHLIST_ITEM3, HWND_CHLIST_ITEM3_SCRAMBLE, { 227, 159, 18, 16 }, }, // HWND_CHLIST_ITEM3_UPDOWN_ARROW { HWND_CHLIST_ITEM3, HWND_CHLIST_ITEM3_UPDOWN_ARROW, { 16, 153, 21, 29 }, }, // HWND_OP_MENU_ITEM3_DELIVERY_SYS_TYPE { HWND_CHLIST_ITEM3, HWND_OP_MENU_ITEM3_DELIVERY_SYS_TYPE, { 285, 159, 53, 17 }, }, // HWND_CHLIST_ITEM4 { HWND_CHLIST_LIST_PANE, HWND_OP_MENU_ITEM4_DELIVERY_SYS_TYPE, { 0, 187, 376, 33 }, }, // HWND_CHLIST_ITEM4_TYPE { HWND_CHLIST_ITEM4, HWND_CHLIST_ITEM4_TYPE, { 314, 194, 35, 17 }, }, // HWND_CHLIST_ITEM4_FAV { HWND_CHLIST_ITEM4, HWND_CHLIST_ITEM4_FAV, { 285, 194, 18, 17 }, }, // HWND_CHLIST_ITEM4_SKIP { HWND_CHLIST_ITEM4, HWND_CHLIST_ITEM4_SKIP, { 285, 194, 18, 17 }, }, // HWND_CHLIST_ITEM4_LOCK { HWND_CHLIST_ITEM4, HWND_CHLIST_ITEM4_LOCK, { 256, 194, 18, 17 }, }, // HWND_CHLIST_ITEM4_TEXT { HWND_CHLIST_ITEM4, HWND_CHLIST_ITEM4_TEXT, { 51, 187, 260, 33 }, }, // HWND_CHLIST_ITEM4_SCRAMBLE { HWND_CHLIST_ITEM4, HWND_CHLIST_ITEM4_SCRAMBLE, { 227, 194, 18, 16 }, }, // HWND_CHLIST_ITEM4_UPDOWN_ARROW { HWND_CHLIST_ITEM4, HWND_CHLIST_ITEM4_UPDOWN_ARROW, { 16, 188, 21, 29 }, }, // HWND_OP_MENU_ITEM4_DELIVERY_SYS_TYPE { HWND_CHLIST_ITEM4, HWND_OP_MENU_ITEM4_DELIVERY_SYS_TYPE, { 285, 194, 53, 17 }, }, // HWND_CHLIST_ITEM5 { HWND_CHLIST_LIST_PANE, HWND_OP_MENU_ITEM5_DELIVERY_SYS_TYPE, { 0, 222, 376, 33 }, }, // HWND_CHLIST_ITEM5_TYPE { HWND_CHLIST_ITEM5, HWND_CHLIST_ITEM5_TYPE, { 314, 229, 35, 17 }, }, // HWND_CHLIST_ITEM5_FAV { HWND_CHLIST_ITEM5, HWND_CHLIST_ITEM5_FAV, { 285, 229, 18, 17 }, }, // HWND_CHLIST_ITEM5_SKIP { HWND_CHLIST_ITEM5, HWND_CHLIST_ITEM5_SKIP, { 285, 229, 18, 17 }, }, // HWND_CHLIST_ITEM5_LOCK { HWND_CHLIST_ITEM5, HWND_CHLIST_ITEM5_LOCK, { 256, 229, 18, 16 }, }, // HWND_CHLIST_ITEM5_TEXT { HWND_CHLIST_ITEM5, HWND_CHLIST_ITEM5_TEXT, { 51, 221, 260, 33 }, }, // HWND_CHLIST_ITEM5_SCRAMBLE { HWND_CHLIST_ITEM5, HWND_CHLIST_ITEM5_SCRAMBLE, { 227, 229, 18, 16 }, }, // HWND_CHLIST_ITEM5_UPDOWN_ARROW { HWND_CHLIST_ITEM5, HWND_CHLIST_ITEM5_UPDOWN_ARROW, { 16, 223, 21, 29 }, }, // HWND_OP_MENU_ITEM5_DELIVERY_SYS_TYPE { HWND_CHLIST_ITEM5, HWND_OP_MENU_ITEM5_DELIVERY_SYS_TYPE, { 285, 229, 53, 17 }, }, // HWND_CHLIST_ITEM6 { HWND_CHLIST_LIST_PANE, HWND_OP_MENU_ITEM6_DELIVERY_SYS_TYPE, { 0, 257, 376, 33 }, }, // HWND_CHLIST_ITEM6_TYPE { HWND_CHLIST_ITEM6, HWND_CHLIST_ITEM6_TYPE, { 314, 265, 35, 17 }, }, // HWND_CHLIST_ITEM6_FAV { HWND_CHLIST_ITEM6, HWND_CHLIST_ITEM6_FAV, { 285, 265, 18, 17 }, }, // HWND_CHLIST_ITEM6_SKIP { HWND_CHLIST_ITEM6, HWND_CHLIST_ITEM6_SKIP, { 285, 265, 18, 17 }, }, // HWND_CHLIST_ITEM6_LOCK { HWND_CHLIST_ITEM6, HWND_CHLIST_ITEM6_LOCK, { 256, 265, 18, 17 }, }, // HWND_CHLIST_ITEM6_TEXT { HWND_CHLIST_ITEM6, HWND_CHLIST_ITEM6_TEXT, { 51, 257, 260, 33 }, }, // HWND_CHLIST_ITEM6_SCRAMBLE { HWND_CHLIST_ITEM6, HWND_CHLIST_ITEM6_SCRAMBLE, { 227, 265, 18, 16 }, }, // HWND_CHLIST_ITEM6_UPDOWN_ARROW { HWND_CHLIST_ITEM6, HWND_CHLIST_ITEM6_UPDOWN_ARROW, { 16, 258, 21, 29 }, }, // HWND_OP_MENU_ITEM6_DELIVERY_SYS_TYPE { HWND_CHLIST_ITEM6, HWND_OP_MENU_ITEM6_DELIVERY_SYS_TYPE, { 285, 265, 53, 17 }, }, // HWND_CHLIST_ITEM7 { HWND_CHLIST_LIST_PANE, HWND_OP_MENU_ITEM7_DELIVERY_SYS_TYPE, { 0, 292, 376, 33 }, }, // HWND_CHLIST_ITEM7_TYPE { HWND_CHLIST_ITEM7, HWND_CHLIST_ITEM7_TYPE, { 314, 300, 35, 17 }, }, // HWND_CHLIST_ITEM7_FAV { HWND_CHLIST_ITEM7, HWND_CHLIST_ITEM7_FAV, { 285, 300, 18, 17 }, }, // HWND_CHLIST_ITEM7_SKIP { HWND_CHLIST_ITEM7, HWND_CHLIST_ITEM7_SKIP, { 285, 300, 18, 17 }, }, // HWND_CHLIST_ITEM7_LOCK { HWND_CHLIST_ITEM7, HWND_CHLIST_ITEM7_LOCK, { 256, 300, 18, 17 }, }, // HWND_CHLIST_ITEM7_TEXT { HWND_CHLIST_ITEM7, HWND_CHLIST_ITEM7_TEXT, { 51, 292, 260, 33 }, }, // HWND_CHLIST_ITEM7_SCRAMBLE { HWND_CHLIST_ITEM7, HWND_CHLIST_ITEM7_SCRAMBLE, { 227, 300, 18, 16 }, }, // HWND_CHLIST_ITEM7_UPDOWN_ARROW { HWND_CHLIST_ITEM7, HWND_CHLIST_ITEM7_UPDOWN_ARROW, { 16, 293, 21, 29 }, }, // HWND_OP_MENU_ITEM7_DELIVERY_SYS_TYPE { HWND_CHLIST_ITEM7, HWND_OP_MENU_ITEM7_DELIVERY_SYS_TYPE, { 285, 300, 53, 17 }, }, // HWND_CHLIST_ITEM8 { HWND_CHLIST_LIST_PANE, HWND_OP_MENU_ITEM8_DELIVERY_SYS_TYPE, { 0, 327, 376, 33 }, }, // HWND_CHLIST_ITEM8_TYPE { HWND_CHLIST_ITEM8, HWND_CHLIST_ITEM8_TYPE, { 314, 335, 35, 17 }, }, // HWND_CHLIST_ITEM8_FAV { HWND_CHLIST_ITEM8, HWND_CHLIST_ITEM8_FAV, { 285, 335, 18, 17 }, }, // HWND_CHLIST_ITEM8_SKIP { HWND_CHLIST_ITEM8, HWND_CHLIST_ITEM8_SKIP, { 285, 335, 18, 17 }, }, // HWND_CHLIST_ITEM8_LOCK { HWND_CHLIST_ITEM8, HWND_CHLIST_ITEM8_LOCK, { 256, 335, 18, 17 }, }, // HWND_CHLIST_ITEM8_TEXT { HWND_CHLIST_ITEM8, HWND_CHLIST_ITEM8_TEXT, { 51, 327, 260, 33 }, }, // HWND_CHLIST_ITEM8_SCRAMBLE { HWND_CHLIST_ITEM8, HWND_CHLIST_ITEM8_SCRAMBLE, { 227, 335, 18, 16 }, }, // HWND_CHLIST_ITEM8_UPDOWN_ARROW { HWND_CHLIST_ITEM8, HWND_CHLIST_ITEM8_UPDOWN_ARROW, { 16, 329, 21, 29 }, }, // HWND_OP_MENU_ITEM8_DELIVERY_SYS_TYPE { HWND_CHLIST_ITEM8, HWND_OP_MENU_ITEM8_DELIVERY_SYS_TYPE, { 285, 335, 53, 17 }, }, // HWND_CHLIST_ITEM9 { HWND_CHLIST_LIST_PANE, HWND_OP_MENU_ITEM9_DELIVERY_SYS_TYPE, { 0, 362, 376, 33 }, }, // HWND_CHLIST_ITEM9_TYPE { HWND_CHLIST_ITEM9, HWND_CHLIST_ITEM9_TYPE, { 314, 370, 35, 17 }, }, // HWND_CHLIST_ITEM9_FAV { HWND_CHLIST_ITEM9, HWND_CHLIST_ITEM9_FAV, { 285, 370, 18, 17 }, }, // HWND_CHLIST_ITEM9_SKIP { HWND_CHLIST_ITEM9, HWND_CHLIST_ITEM9_SKIP, { 285, 370, 18, 17 }, }, // HWND_CHLIST_ITEM9_LOCK { HWND_CHLIST_ITEM9, HWND_CHLIST_ITEM9_LOCK, { 256, 370, 18, 17 }, }, // HWND_CHLIST_ITEM9_TEXT { HWND_CHLIST_ITEM9, HWND_CHLIST_ITEM9_TEXT, { 51, 362, 260, 33 }, }, // HWND_CHLIST_ITEM9_SCRAMBLE { HWND_CHLIST_ITEM9, HWND_CHLIST_ITEM9_SCRAMBLE, { 227, 370, 18, 16 }, }, // HWND_CHLIST_ITEM9_UPDOWN_ARROW { HWND_CHLIST_ITEM9, HWND_CHLIST_ITEM9_UPDOWN_ARROW, { 16, 364, 21, 29 }, }, // HWND_OP_MENU_ITEM9_DELIVERY_SYS_TYPE { HWND_CHLIST_ITEM9, HWND_OP_MENU_ITEM9_DELIVERY_SYS_TYPE, { 285, 370, 53, 17 }, }, // HWND_OP_MSGBOX_PANE { HWND_MAINFRAME, HWND_OP_MSGBOX_DELETE_OP_3, { 138, 3, 231, 194 }, }, // HWND_OP_MSGBOX_BG { HWND_OP_MSGBOX_PANE, HWND_OP_MSGBOX_BG_R, { 138, 3, 231, 194 }, }, // HWND_OP_MSGBOX_BG_TOP { HWND_OP_MSGBOX_BG, HWND_OP_MSGBOX_BG_TOP, { 138, 3, 231, 31 }, }, // HWND_OP_MSGBOX_BG_L { HWND_OP_MSGBOX_BG, HWND_OP_MSGBOX_BG_L, { 138, 35, 4, 162 }, }, // HWND_OP_MSGBOX_BG_C { HWND_OP_MSGBOX_BG, HWND_OP_MSGBOX_BG_C, { 142, 35, 223, 162 }, }, // HWND_OP_MSGBOX_BG_R { HWND_OP_MSGBOX_BG, HWND_OP_MSGBOX_BG_R, { 366, 35, 4, 162 }, }, // HWND_OP_MSGBOX_BTN_PANE { HWND_OP_MSGBOX_PANE, HWND_OP_BTN_NO_TEXT, { 138, 176, 231, 21 }, }, // HWND_OP_BTN_YES { HWND_OP_MSGBOX_BTN_PANE, HWND_OP_BTN_YES_TEXT, { 138, 176, 0, 0 }, }, // HWND_OP_BTN_YES_LEFT_ARROW { HWND_OP_BTN_YES, HWND_OP_BTN_YES_LEFT_ARROW, { 138, 176, 15, 21 }, }, // HWND_OP_BTN_YES_TEXT { HWND_OP_BTN_YES, HWND_OP_BTN_YES_TEXT, { 154, 176, 71, 21 }, }, // HWND_OP_BTN_NO { HWND_OP_MSGBOX_BTN_PANE, HWND_OP_BTN_NO_TEXT, { 261, 170, 0, 0 }, }, // HWND_OP_BTN_NO_RIGHT_ARROW { HWND_OP_BTN_NO, HWND_OP_BTN_NO_RIGHT_ARROW, { 355, 176, 15, 21 }, }, // HWND_OP_BTN_NO_TEXT { HWND_OP_BTN_NO, HWND_OP_BTN_NO_TEXT, { 283, 176, 71, 21 }, }, // HWND_OP_MSGBOX_DELETE_OP_1 { HWND_OP_MSGBOX_PANE, HWND_OP_MSGBOX_DELETE_OP_1, { 145, 57, 210, 21 }, }, // HWND_OP_MSGBOX_DELETE_OP_2 { HWND_OP_MSGBOX_PANE, HWND_OP_MSGBOX_DELETE_OP_2, { 145, 80, 210, 21 }, }, // HWND_OP_MSGBOX_DELETE_OP_3 { HWND_OP_MSGBOX_PANE, HWND_OP_MSGBOX_DELETE_OP_3, { 145, 104, 210, 21 }, }, };
#include<bits/stdc++.h> using namespace std; int merge(int start,int middle,int end,int arr[],int n) { int sizetemp1=middle-start+1; int sizetemp2=end-middle; int temp1[sizetemp1],temp2[sizetemp2]; for(int i=0;i<sizetemp1;i++) { temp1[i]=arr[start+i]; } for(int i=0;i<sizetemp2;i++) { temp2[i]=arr[middle+1+i]; } int k=start; int i=0,j=0; while(i<sizetemp1 && j<sizetemp2) { if(temp1[i]<temp2[j]) { arr[k]=temp1[i];i++; } else { arr[k]=temp2[j];j++; } k++; } while(i<sizetemp1) { arr[k]=temp1[i];i++;k++; } while(j<sizetemp2) { arr[k]=temp2[j];j++;k++; } } void mergesort(int start,int end,int arr[],int n) { if(start<end) { int middle=(start+end)/2; mergesort(start,middle,arr,n); mergesort(middle+1,end,arr,n); merge(start,middle,end,arr,n); } } int main() { int arr[]={0,-38,46,0,14,-3774,0,0,-273,37,-39,0,142,83,-293,0,383,38,0,-38}; int n=sizeof(arr)/sizeof(arr[0]); mergesort(0,n-1,arr,n); for(int i=0;i<n;i++) { cout<<arr[i]<<" "; } cout<<endl; }
#pragma once #include "BaseAnimation.h" #include <functional> namespace GraphicsEngine { class GeneralAnimation : public BaseAnimation { public: using UpdateFunctionType = std::function<void(const Common::Timer&, float)>; public: GeneralAnimation(float startInMilliseconds, float durationInMilliseconds, const UpdateFunctionType& updateFunction); void FixedUpdate(const Common::Timer& timer) const override; nlohmann::json ToJson() const override; private: UpdateFunctionType m_updateFunction; }; }
// // Created by Tidesun on 2019-04-25. // #include "bfb_calculator.hpp" BFBCalculator::BFBCalculator(Graph _g,double _costThreshold, char _baseDir, char _extendingDir){ algorithm = nullptr; g = _g; costThreshold = _costThreshold; baseDir = _baseDir; extendingDir = _extendingDir; } void BFBCalculator::setAlgorithm(int type) { if (type == foldbackAlgo) { algorithm = new FoldbackAlgorithm(&g,costThreshold, baseDir, extendingDir); } if (type == traverseAlgo) { algorithm = new TraverseAlgorithm(&g,costThreshold, baseDir, extendingDir); } } void BFBCalculator::runAlgorithm() { g.backupCopy(); if (!algorithm) { cout<< "Set algorithm first!"; return; } auto start = std::chrono::system_clock::now(); algorithm->traverseUtil(); algorithm->printResult(); auto end = std::chrono::system_clock::now(); std::chrono::duration<double> elapsed_seconds = end-start; std::time_t end_time = std::chrono::system_clock::to_time_t(end); std::cout << "elapsed time: " << elapsed_seconds.count() << "s\n"; g.restoreCopy(); }
#include "imageDownloader.h" ImageDownloader::ImageDownloader() { //ctor } ImageDownloader::~ImageDownloader() { //dtor } /* Method to download a URL to a specified file */ bool ImageDownloader::DownloadFile(wxString url, wxString destination) { wxLogMessage(_T("NOAADOPPLER: Downloading File: %s"), url.c_str()); wxURL fileDL(url); if (fileDL.GetError()==wxURL_NOERR) { wxInputStream *in = fileDL.GetInputStream(); if (in && in->IsOk()) { wxFFileOutputStream out(destination); in->Read(out); } delete in; return true; } return false; } /* Method to generate the http:// filename requested to be downloaded */ wxString ImageDownloader::GenerateDownloadFilename(wxString station, wxString radarType) { wxString filename = _T("http://radar.weather.gov/ridge/RadarImg/"); filename.append(radarType); filename.append(_T("/")); filename.append(station); filename.append(_T("_")); filename.append(radarType); filename.append(_T("_0.gif")); return filename; } /* Method to generate the local filename to save to */ wxString ImageDownloader::GenerateSavedFilename(wxString station, wxString radarType) { wxString filename = _T("/home/matt/opencpn/radar/"); filename.append(station); filename.append(_T("_")); filename.append(radarType); filename.append(_T("_Live.gif")); return filename; return _T("/home/matt/opencpn/radar/ATX_N0R_Live.gif"); } /* Method to generate the world file filename */ wxString ImageDownloader::GenerateWorldFilename(wxString station, wxString radarType) { return _T("http://radar.weather.gov/ridge/RadarImg/N0R/ATX_N0R_0.gfw"); }
//20M19118 //module load intel-mpi //compile with mpicxx mpi_openmp_simd_code.cpp -fopenmp -march=native -O3 -std=c++11 //mpirun -np 4 ./a.out #include <immintrin.h> #include <bits/stdc++.h> #include <mpi.h> #include <omp.h> using namespace std; int main(int argc, char** argv) { int size, rank; MPI_Init(&argc, &argv); MPI_Comm_size(MPI_COMM_WORLD, &size); MPI_Comm_rank(MPI_COMM_WORLD, &rank); const int N = 256; vector<float> A(N * N); vector<float> B(N * N); vector<float> C(N * N, 0); vector<float> subA(N * N / size); vector<float> subB(N * N / size); vector<float> subC(N * N / size, 0); for (int i=0; i<N; i++) { for (int j=0; j<N; j++) { A[N*i+j] = drand48(); B[N*i+j] = drand48(); } } int offset = N / size * rank; for (int i = 0; i < N / size; i++) for (int j = 0; j < N; j++) subA[N * i + j] = A[N * (i + offset) + j]; for (int i = 0; i < N; i++) for (int j = 0; j < N / size; j++) subB[N / size * i + j] = B[N * i + j + offset]; int recv_from = (rank + 1) % size; int send_to = (rank - 1 + size) % size; float columnSect[N]; int n_chunks = N / 64; double comp_time = 0, comm_time = 0; for (int irank = 0; irank < size; irank++) { auto tic = chrono::steady_clock::now(); offset = N / size * ((rank + irank) % size); int chunk, i, j, k; # pragma omp parallel shared (subA, subB, subC, size, offset) private (chunk, i, j, k, columnSect) { # pragma omp for for (chunk = 0; chunk < n_chunks; chunk++) { for (i = chunk * (N / size / n_chunks); i < (chunk + 1) * (N / size / n_chunks); i++) { for (j = 0; j < N / size; j++) { for (k = 0; k < N; k++) { columnSect[k] = subB[N / size * k + j]; } __m128 vc = _mm_set_ps1(0.0f); for (k = 0; k < N; k += 4) { __m128 va = _mm_load_ps(&subA[N * i + k]); __m128 vb = _mm_load_ps(&columnSect[k]); __m128 vres = _mm_mul_ps(va, vb); vc = _mm_add_ps(vc, vres); } vc = _mm_hadd_ps(vc, vc); vc = _mm_hadd_ps(vc, vc); subC[N * i + j + offset] = _mm_cvtss_f32(vc); } } } } auto toc = chrono::steady_clock::now(); comp_time += chrono::duration<double>(toc - tic).count(); MPI_Send(&subB[0], N * N / size, MPI_FLOAT, send_to, 0, MPI_COMM_WORLD); MPI_Recv(&subB[0], N * N / size, MPI_FLOAT, recv_from, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); tic = chrono::steady_clock::now(); comm_time += chrono::duration<double>(tic - toc).count(); } MPI_Allgather(&subC[0], N * N / size, MPI_FLOAT, &C[0], N * N / size, MPI_FLOAT, MPI_COMM_WORLD); for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) for (int k = 0; k < N; k++) C[N * i + j] -= A[N * i + k] * B[N * k + j]; // Record the Error double err = 0; for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) err += fabs(C[N * i + j]); if (rank == 0) { double time = comp_time + comm_time; printf("N : %d\n", N); printf("comp : %lf s\n", comp_time); printf("comm : %lf s\n", comm_time); printf("total: %lf s (%lf GFlops)\n", time, 2. * N * N * N / time / 1e9); printf("error: %lf\n", err / N / N); } MPI_Finalize(); }
#include "stdafx.h" #include "Hook.h" #include "disasm.h" /* Author:火哥 QQ:471194425 群号:1026716399 */ void __declspec(naked) HookHeadDispatch() { } int Hook::CopyMemcpy(void * desc, void *src, size_t size) { char * tempSrc = (char *)src; char * tempDesc = (char *)desc; while (size-- != 0) { *tempDesc++ = *tempSrc++; } return 0; } bool Hook::UpdatePageCopyMemcpy(void * desc, void *src, size_t size) { DWORD orginProtect = 0; if (VirtualProtect((LPVOID)desc, size, PAGE_EXECUTE_READWRITE, &orginProtect)) { this->CopyMemcpy((void*)desc, src, size); VirtualProtect((LPVOID)desc, size, orginProtect, &orginProtect); return true; } return false; } bool Hook::InstallHook(ULONG oldFunc, ULONG newFunc, HookType type) { if (this->isHookSuccess) return true; bool isResult = false; switch(type) { /* case HookType::CallHeadHook: isResult = this->CallHeadHook(oldFunc, newFunc); break; case HookType::CallNotHeadHook: isResult = this->CallNotHeadHook(oldFunc, newFunc); break; */ case HookType::JmpHeadHook: isResult = this->JmpHeadHook(oldFunc, newFunc); break; case HookType::JmpNotHeadHook: isResult = this->JmpNotHeadHook(oldFunc, newFunc); break; } if (isResult) { this->type = type; this->isHookSuccess = true; } return isResult; } /* bool Hook::CallHeadHook(ULONG oldFunc, ULONG newFunc) { return false; } bool Hook::CallNotHeadHook(ULONG oldFunc, ULONG newFunc) { return false; } */ ULONG Hook::calcResetCode(ULONG oldFunc, ULONG hookCodeSize) { size_t sizeTotal = 0; //计算长度 Disasm disasm; do { sizeTotal += disasm.DisasmCode((PUCHAR)oldFunc + sizeTotal, 16); } while (sizeTotal < hookCodeSize); return sizeTotal; } bool Hook::JmpHeadHook(ULONG oldFunc, ULONG newFunc) { char bufCode[] = {0xe9,0,0,0,0}; HMODULE module = LoadLibraryA("ntdll.dll"); if (!module) return false; size_t sizeTotal = this->calcResetCode(oldFunc, sizeof(bufCode)); this->CopyMemcpy(this->orginCode, (PUCHAR)oldFunc, sizeTotal); this->orginLen = sizeTotal; this->oldFuncAddress = oldFunc; this->oldFuncRetAddress = oldFunc + sizeTotal; this->newFuncAddress = newFunc; //修正 *(PULONG)&bufCode[1] =(ULONG)newFunc - (oldFunc + 5); //查找ntdll 空白处 PIMAGE_DOS_HEADER pDos = (PIMAGE_DOS_HEADER)module; PIMAGE_NT_HEADERS pNts = (PIMAGE_NT_HEADERS)((char *)module + pDos->e_lfanew); PIMAGE_SECTION_HEADER pSection = (PIMAGE_SECTION_HEADER)((char*)pNts +sizeof(pNts->Signature) + sizeof(pNts->FileHeader) + pNts->FileHeader.SizeOfOptionalHeader); char * start = (pSection->VirtualAddress + (char *)module); int sc = pSection->SizeOfRawData % pNts->OptionalHeader.SectionAlignment; size_t sectionSize = pNts->OptionalHeader.SectionAlignment - sc + pSection->SizeOfRawData; sizeTotal = this->orginLen + 5; char * retCallCode = new char[sizeTotal]; memset(retCallCode, 0, sizeTotal); bool isFindSpace = false; for (ULONG i = 0; i < sectionSize - sizeTotal; i++) { if (memcmp(retCallCode, start + i, sizeTotal) == 0) { isFindSpace = true; start += i; break; } } if (!isFindSpace) { start = (char *)VirtualAlloc(NULL, sizeTotal, MEM_COMMIT, PAGE_EXECUTE_READWRITE); if (start == NULL) { delete[] retCallCode; return false; } } this->CopyMemcpy(retCallCode, this->orginCode, this->orginLen); retCallCode[this->orginLen] = 0xE9; *(PULONG)&retCallCode[this->orginLen + 1] = this->oldFuncRetAddress - (ULONG)(start + this->orginLen + 5); bool isSuccess = this->UpdatePageCopyMemcpy(start, retCallCode, sizeTotal); delete[] retCallCode; if (!isSuccess) { if (!isFindSpace) VirtualFree(start, sizeTotal, MEM_RELEASE); return isSuccess; } this->calloldFuncAddress = (ULONG)start; //开始HOOK isSuccess = this->UpdatePageCopyMemcpy((void*)this->oldFuncAddress, bufCode, sizeof(bufCode)); return isSuccess; } bool Hook::JmpNotHeadHook(ULONG oldFunc, ULONG newFunc) { return false; } Hook::Hook() { this->isHookSuccess = false; this->orginLen = 0; memset(this->orginCode, 0, 20); this->oldFuncAddress = 0; this->oldFuncRetAddress = 0; this->newFuncAddress = 0; this->calloldFuncAddress = 0; } bool Hook::UnInstallHook() { if (!this->isHookSuccess) return false; return this->UpdatePageCopyMemcpy((void*)this->oldFuncAddress, this->orginCode, this->orginLen); } Hook::~Hook() { this->UnInstallHook(); }
/* Multipurpose RC controller. This implementation will be specifically for a * quadcopter with an arduino receiver and MultiWii FLight Controller. * Guillermo Colom 1 - GND 2 - VCC 3.3V !!! NOT 5V 3 - CE to Arduino pin 9 4 - CSN to Arduino pin 10 5 - SCK to Arduino pin 13 6 - MOSI to Arduino pin 11 7 - MISO to Arduino pin 12 8 - UNUSED - Analog Joystick or two 10K potentiometers: GND to Arduino GND VCC to Arduino +5V X1 Pot to Arduino A0 Y1 Pot to Arduino A1 M1 Pot to Arduino A6 X2 Pot to Arduino A2 Y2 Pot to Arduino A3 M2 Pot to Arduino A7 - V1.00 11/26/13 Based on examples at http://www.bajdi.com/ Questions: terry@yourduino.com */ /*-----( Import needed libraries )-----*/ #include <SPI.h> #include <nRF24L01.h> #include <RF24.h> #include <Wire.h> // for LCD. Comes with Arduino IDE #include <LiquidCrystal_I2C.h> //for LCD. /*-----( Declare Constants and Pin Numbers )-----*/ #define CE_PIN 9 #define CSN_PIN 10 #define JOYSTICK_X1 A3 #define JOYSTICK_Y1 A2 #define JOYSTICK_X2 A1 #define JOYSTICK_Y2 A0 #define AUX1 A7 #define AUX2 A6 #define AUX3 3 #define AUX4 4 #define DEADZONE 110 // distance from center for defining "deadzone" #define DEADPULSE 1500 // default "center" pulse width #define MINPULSE 1000 // minimum pulse width #define MAXPULSE 2000 // maximum pulse width #define CHANNELS 8 // number of channels #define XBYTES 18 // number of bytes to be transmited // NOTE: the "LL" at the end of the constant is "LongLong" type const uint64_t pipe = 0xE8E8F0F0E1LL; // Define the transmit pipe /*-----( Declare objects )-----*/ RF24 radio(CE_PIN, CSN_PIN); // Create a Radio /*-----( Declare Variables )-----*/ // set the LCD address to 0x27 for a 16 chars 2 line display // A FEW use address 0x3F // Set the pins on the I2C chip used for LCD connections: // addr, en,rw,rs,d4,d5,d6,d7,bl,blpol LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE); // Set the LCD I2C address //Values to transmit byte transmitBytes[XBYTES]; // 2 bytes per value int pulseValues[CHANNELS]; // actual pulse values {Throttle Y2, Roll X1, Pitch Y1, Yaw X2} int transmitDelay = 10000; // microseconds between transmissions unsigned long startTime; // used to find elapsed time unsigned long stopTime; // used to find elapsed time //Variables for calculating pulse widths bool reverseX1 = true; // reverse axis direction roll bool reverseY1 = true; // reverse axis direction pitch bool reverseX2 = false; // reverse axis direction yaw bool reverseY2 = false; // reverse axis direction throttle void setup() /****** SETUP: RUNS ONCE ******/ { Serial.begin(9600); // Initialize Display initializeDisplay (); displayOnLine("Hello", 0, 2); displayOnLine("Quadcopter", 1, 1); displayOnLine("Controller", 2, 1); delay(2000); while(digitalRead(3)+digitalRead(4)) { displayOnLine("Warning!", 0, 2); displayOnLine("Set switches", 1, 1); displayOnLine("To Low ", 2, 1); } radio.begin(); radio.openWritingPipe(pipe); startTime = micros(); }//--(end setup )--- void loop() /****** LOOP: RUNS CONSTANTLY ******/ { stopTime = micros(); if ((stopTime - startTime) >= transmitDelay || (stopTime < startTime)) { startTime = micros(); pulseValues[0] = pulseCalculate2(JOYSTICK_X1, 1.25, 512, reverseX1); //Roll pulseValues[1] = pulseCalculate2(JOYSTICK_Y1, 1.25, 512, reverseY1); //Pitch pulseValues[2] = pulseCalculate2(JOYSTICK_Y2, 1.25, 512, reverseY2); //Throttle pulseValues[3] = pulseCalculate2(JOYSTICK_X2, 1.25, 512, reverseX2); //Yaw pulseValues[4] = pulseCalculate(AUX1, false); //Aux1 pulseValues[5] = pulseCalculate(AUX2, false); //Aux2 pulseValues[6] = pinPulse(AUX3); //Aux3 pulseValues[7] = pinPulse(AUX4); //Aux4 pulseToByteArray(pulseValues, transmitBytes); transmitBytes[XBYTES-2] = 1; transmitBytes[XBYTES-1] = 1; radio.write( transmitBytes, sizeof(transmitBytes) ); displayValues(); } }//--(end main loop )--- /*-----( Declare User-written Functions )-----*/ // Calculate Pulse Values int pulseCalculate(int aPin, bool reverse) { float input; int pulseOut; int readVal = reverseAxis(analogRead(aPin), reverse); input = (float)readVal; pulseOut = (int)(input*1000.0/1023.0); pulseOut += MINPULSE; return pulseOut; }// end pulseCalculate() int pinPulse(int pin) { if (digitalRead(pin)) return 2000; else return 1000; } //This function is meant to help create a "Dead Zone" when the Joysticks are //approximately centered, to output 1500 as values int pulseCalculate2(int aPin, float sensitivity, int center, bool reverse) { int pulseOut; int readVal = reverseAxis(analogRead(aPin), reverse); if (readVal >= center - DEADZONE && readVal <= center + DEADZONE) pulseOut = DEADPULSE; if (readVal < center - DEADZONE) pulseOut =(int)(sensitivity * (readVal - (center - DEADZONE)) + DEADPULSE); if (readVal > center + DEADZONE) pulseOut =(int)(sensitivity * (readVal - (center + DEADZONE)) + DEADPULSE); if (pulseOut < MINPULSE) pulseOut = MINPULSE; if (pulseOut > MAXPULSE) pulseOut = MAXPULSE; return pulseOut; }// end pulseCalculate() // Pulse to byteArray, high byte first void pulseToByteArray(int pulses[], byte bytes[]) { for (int i = 0; i < CHANNELS; i++) { bytes[2*i] = pulses[i]/256; bytes[2*i+1] = pulses[i]%256; } }// end pulseToByteArray() int reverseAxis(int axis, bool reverse) { if (reverse) axis = 1023 - axis; return axis; } // ens reverseAxis() //Initialize LCD Display void initializeDisplay () { lcd.begin(16,4); // initialize the lcd for 16 chars 4 lines, turn on backlight // ------- Quick 3 blinks of backlight ------------- for(int i = 0; i< 3; i++) { lcd.backlight(); delay(100); lcd.noBacklight(); delay(100); } lcd.backlight(); // finish with backlight on }// end initializeDisplay() void displayOnLine(char script[], int row, int col) { lcd.setCursor(col, row); lcd.print(script); }// en displayOnLine() void displayValues() { displayOnLine("Roll:", 0, 0); lcd.print(pulseValues[0]); displayOnLine("Ptch:", 1, 0); lcd.print(pulseValues[1]); lcd.print(" "); displayOnLine("Thr: ", 2, 0); lcd.print(pulseValues[2]); displayOnLine("Yaw: ", 3, 0); lcd.print(pulseValues[3]); displayOnLine(" 1:", 0, 9); lcd.print((float)pulseValues[4]/1000); displayOnLine(" 2:", 1, 9); lcd.print((float)pulseValues[5]/1000); displayOnLine(" 3:", 2, 9); if (pulseValues[6]>1000) lcd.print("high"); else lcd.print("low "); displayOnLine(" 4:", 3, 9); if (pulseValues[7]>1000) lcd.print("high"); else lcd.print("low "); }// end displayValues() //*********( THE END )***********
// // Created by zyx on 19-6-4. // #include "Detector.h" Detector::Detector(bool traceResultOn, bool traceDebugOn, bool colorOn) { radonAngleRange = 63; radonOperation = radon::RT_SUM; beginPoint = cv::Point(-1, -1); traceResultOn_ = traceResultOn; traceDebugOn_ = traceDebugOn; colorOn_ = colorOn; } Detector::~Detector() {} /* * Function thresholds the input oblique image in three channels * @param src [the input image] * @return none * note: the input image is modified in this function */ void Detector::oblique_threshold(cv::Mat src) { const int R_MAX_1 = 170; cv::Mat_<Vec3b>::iterator it1{src.begin<Vec3b>()}; while (it1 != src.end<Vec3b>()) { if ((*it1)[0] > 200 && (*it1)[1] > 200 && (*it1)[2] > 200) { (*it1)[0] = 255; (*it1)[1] = 255; (*it1)[2] = 255; } else if ((*it1)[0] > (*it1)[1] && (*it1)[0] > (*it1)[2]) { (*it1)[0] = 0; (*it1)[1] = 0; (*it1)[2] = 0; } else { (*it1)[0] = 0; (*it1)[1] = 0; (*it1)[2] = 0; } it1++; } } /* * Function thresholds the input vertical image in three channels * @param src [the input image] * @return none * note: the input image is modified in this function */ void Detector::vertical_threshold(cv::Mat src) { cv::Mat_<Vec3b>::iterator it1{src.begin<Vec3b>()}; while (it1 != src.end<Vec3b>()) { if ((*it1)[2] - (*it1)[1] > 30 && (*it1)[2] - (*it1)[0] > 30 && (*it1)[2] > 100) { (*it1)[0] = 255; (*it1)[1] = 255; (*it1)[2] = 255; } else { (*it1)[0] = 0; (*it1)[1] = 0; (*it1)[2] = 0; } it1++; } } /* * Function processes the private variable operate_image in defined process type * @param processType [process type, OBLIQUE for oblique knife image, VERTICAL * for vertical knife image] note: the private variable operate_image is * modified in this function */ cv::Mat Detector::pretreatment(int processType) { double minVal, maxVal; cv::Mat gaussianImg, grayImg, grayImgRadon; if (colorOn_) { cv::GaussianBlur(this->operate_image, gaussianImg, Size(5, 5), 0, 0, cv::BORDER_DEFAULT); } else gaussianImg = this->operate_image.clone(); switch (processType) { case OBLIQUE: if (colorOn_) oblique_threshold(gaussianImg); break; case VERTICAL: if (colorOn_) vertical_threshold(gaussianImg); break; default: break; } if (colorOn_) { cv::cvtColor(gaussianImg, grayImg, COLOR_BGRA2GRAY); radon::radonTransform(grayImg, grayImgRadon, radonAngleRange, radonOperation); } else radon::radonTransform(gaussianImg, grayImgRadon, radonAngleRange, radonOperation); cv::minMaxLoc(grayImgRadon, &minVal, &maxVal); grayImgRadon -= minVal; grayImgRadon.convertTo(grayImgRadon, CV_8UC1, 255.0 / (maxVal - minVal)); return grayImgRadon; } /* * Function gets the radon transform corresponding line * look up the complete coordinate online by (x,-1) or (-1,y). * @param priorRadonImgSize [The size of the image not transformed] * @param subsequentRadonImgSize [The size of the image already transformed] * @param referencePoint [The randon transform maximum point] * @param targetPointX [The x coordinate of point online you wanna * get,-1 for non-use] * @param targetPointY [The y coordinate of point online you wanna * get,-1 for non-use] * @return the complete coordinate of a point online known one coordinate. */ cv::Point Detector::getPointOnline(const cv::Size& priorRadonImgSize, const cv::Size& subsequentRadonImgSize, const cv::Point& referencePoint, const int& targetPointX, const int& targetPointY) { int x0, y0; double k; double beta = M_PI * (obliqueMaxLoc.x) / 180.0; int offset = subsequentRadonImgSize.height / 2 - referencePoint.y; x0 = priorRadonImgSize.width / 2 + offset * cos(beta); y0 = priorRadonImgSize.height / 2 + offset * sin(beta); k = -1 / tan(beta); if (targetPointX >= 0) return cv::Point(targetPointX, k * (targetPointX - x0) + y0); else if (targetPointY >= 0) return cv::Point((targetPointY - y0) / k + x0, targetPointY); } /* * Function refines the intersection coordinate */ void Detector::refineLoc() { // image pretreatment cv::Mat gaussianImg, grayImg; if (colorOn_) { cv::GaussianBlur(this->operate_image, gaussianImg, Size(15, 15), 0, 0, cv::BORDER_DEFAULT); cv::cvtColor(gaussianImg, grayImg, COLOR_BGRA2GRAY); cv::Canny(grayImg, grayImg, 5, 40, 3); } else grayImg = this->operate_image.clone(); cv::Size RectSize(200, 160); cv::Point initPoint(beginPoint.x - RectSize.width / 1.5, beginPoint.y - RectSize.height / 1.5); cv::Rect rect(initPoint, RectSize); cv::Mat refineImg{grayImg(rect)}; cv::Mat refineImgRadon; radon::radonTransform(refineImg, refineImgRadon, radonAngleRange, radonOperation); cv::Point maxLoc; cv::Mat mask{Mat::zeros(refineImgRadon.size(), CV_8UC1)}; mask(cv::Rect(cv::Point(20, 0), cv::Size(130, refineImgRadon.size().height))) .setTo(255); cv::minMaxLoc(refineImgRadon, nullptr, nullptr, nullptr, &maxLoc, mask); cv::Point refinedBeginPoint{getPointOnline(refineImg.size(), refineImgRadon.size(), maxLoc, (beginPoint - initPoint).x, -1)}; beginPoint = refinedBeginPoint + initPoint; } /* * Function draws a box described by a CvBox2D * @param box [the box properties] * @param img [the canva] * @return none */ static void DrawBox(CvBox2D box, cv::Mat img) { CvPoint2D32f point[4]; cvBoxPoints(box, point); //计算二维盒子顶点 CvPoint pt[4]; for (int i = 0; i < 4; i++) { pt[i].x = (int)point[i].x; pt[i].y = (int)point[i].y; } cv::line(img, pt[0], pt[1], cvScalar(255), 2, 8, 0); cv::line(img, pt[1], pt[2], cvScalar(255), 2, 8, 0); cv::line(img, pt[2], pt[3], cvScalar(255), 2, 8, 0); cv::line(img, pt[3], pt[0], cvScalar(255), 2, 8, 0); } /* * Function computes the begin point of knife trace which is the intersection of * the oblique knife trace and the vertical knife trace * @return the pixel coordinate of the begin point. */ cv::Point Detector::get_BeginPoint(const cv::Mat& test_image_) { cv::Mat clone_image{test_image_.clone()}; cv::resize(clone_image, clone_image, cv::Size(640, 480)); if (!colorOn_) { cv::GaussianBlur(clone_image, clone_image, Size(15, 15), 0, 0, cv::BORDER_DEFAULT); cv::cvtColor(clone_image, clone_image, COLOR_BGRA2GRAY); cv::Canny(clone_image, clone_image, 5, 40, 3); // clone_image.rowRange(0,110).setTo(0); clone_image.rowRange(400, 480).setTo(0); } this->operate_image = clone_image.clone(); cv::Mat sdfdsfs; cv::resize(test_image_, sdfdsfs, cv::Size(640, 480)); this->display_image = sdfdsfs.clone(); obliqueImg = pretreatment(OBLIQUE); verticalImg = pretreatment(VERTICAL); cv::minMaxLoc(obliqueImg, nullptr, nullptr, nullptr, &obliqueMaxLoc); assert(0 < obliqueMaxLoc.x); cv::minMaxLoc(verticalImg.col(0), nullptr, nullptr, nullptr, &verticalMaxLoc); assert(0 <= verticalMaxLoc.x); verticalMaxLoc.x = verticalImg.size().height / 2 - verticalMaxLoc.y + this->operate_image.size().width / 2; beginPoint = getPointOnline(this->operate_image.size(), obliqueImg.size(), obliqueMaxLoc, verticalMaxLoc.x); refineLoc(); this->borderPoint = getPointOnline(this->operate_image.size(), obliqueImg.size(), obliqueMaxLoc, -1, this->operate_image.rows); if (this->borderPoint.x < 0 || this->borderPoint.x > this->operate_image.cols) this->borderPoint = getPointOnline(this->operate_image.size(), obliqueImg.size(), obliqueMaxLoc, this->operate_image.cols, -1); if (traceResultOn_) { cv::circle(this->display_image, beginPoint, 5, Scalar(255, 0, 0), -1); cv::line(this->display_image, beginPoint, borderPoint, Scalar(0, 0, 255), 2); cv::line(this->display_image, cv::Point(verticalMaxLoc.x, this->operate_image.rows), cv::Point(verticalMaxLoc.x, 0), Scalar(255, 255, 0), 2); imshow("detection result", this->display_image); waitKey(0); cv::destroyAllWindows(); } return beginPoint; } /* * Function gets the complete knife Trace (the oblique one) * @param test_image_ [the input test image] * @return all coordinates of the knife trace */ std::vector<cv::Point> Detector::get_knifeTrace(const cv::Mat& test_image_) { get_BeginPoint(test_image_); std::vector<cv::Point> knife_trace{get_knife_trace(traceDebugOn_)}; if (traceResultOn_) { cv::circle(this->display_image, beginPoint, 5, Scalar(255, 0, 0), -1); cv::polylines(this->display_image, knife_trace, false, Scalar(0, 255, 0), 2); imshow("detection result", this->display_image); waitKey(0); cv::destroyAllWindows(); } return knife_trace; } /* * Function computes all coordinates of the knife trace * @debug [trigger for displaying all intermediate processed image] * @return all coordinates of the knife trace */ std::vector<cv::Point> Detector::get_knife_trace(bool debug) { cv::Mat mask = Mat::zeros(this->operate_image.size(), CV_8UC1); CvBox2D box; box.size.width = norm(borderPoint - beginPoint); box.size.height = 15; box.angle = atan2((beginPoint - borderPoint).y, (beginPoint - borderPoint).x) * 180.0 / M_PI; box.center.x = (borderPoint.x + beginPoint.x) / 2; box.center.y = (borderPoint.y + beginPoint.y) / 2; DrawBox(box, mask); cv::floodFill(mask, box.center, 255, nullptr, cvScalarAll(0), cvScalarAll(0), CV_FLOODFILL_FIXED_RANGE); cv::Mat newImg, newImgCanny; if (colorOn_) { cv::GaussianBlur(this->operate_image, newImgCanny, Size(15, 15), 0, 0, cv::BORDER_DEFAULT); cv::cvtColor(newImgCanny, newImgCanny, COLOR_BGRA2GRAY); cv::Canny(newImgCanny, newImgCanny, 5, 40); } else { newImgCanny = this->operate_image.clone(); } newImgCanny.copyTo(newImg, mask); if (debug) { imshow("knife trace canny image", newImg); waitKey(0); } cv::blur(newImg, newImg, cv::Size(3, 3)); if (debug) { imshow("knife trace mean blur image", newImg); waitKey(0); } cv::threshold(newImg, newImg, 30, 255, CV_THRESH_BINARY); if (debug) { imshow("knife trace threshold image", newImg); waitKey(0); } Mat element = getStructuringElement(MORPH_RECT, Size(2, 2)); morphologyEx(newImg, newImg, MORPH_GRADIENT, element); if (debug) { imshow("knife trace gradient image", newImg); waitKey(0); } vector<vector<Point>> contours; vector<Vec4i> hierarcy; findContours(newImg, contours, hierarcy, CV_RETR_TREE, CV_CHAIN_APPROX_NONE); double maxArea = 0; vector<cv::Point> maxContour; for (const auto& contour : contours) { double area = cv::contourArea(contour); if (area > maxArea) { maxArea = area; maxContour = contour; } } if (debug) { std::vector<std::vector<cv::Point>> maxContours; maxContours.push_back(maxContour); cv::Mat contoursDisplayImg = Mat::zeros(this->operate_image.size(), CV_8UC1); cv::drawContours(contoursDisplayImg, maxContours, 0, Scalar(255, 255, 255)); imshow("knife trace contours image", contoursDisplayImg); waitKey(0); } std::vector<cv::Point> knife_trace; knife_trace = maxContour; knife_trace.resize(knife_trace.size() / 2); return knife_trace; } std::vector<cv::Point> Detector::get_traceSegments( const std::vector<cv::Point>& knife_trace, int segement_number) { std::vector<cv::Point> segments; if (!knife_trace.empty()) { int interval = knife_trace.size() / segement_number; if (segement_number == 0) return knife_trace; for (int i = 0; i < segement_number; ++i) { segments.push_back(knife_trace[i * interval]); } } return segments; }
/* Copyright (c) 2005-2023, University of Oxford. All rights reserved. University of Oxford means the Chancellor, Masters and Scholars of the University of Oxford, having an administrative office at Wellington Square, Oxford OX1 2JD, UK. This file is part of Chaste. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the University of Oxford nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "BackwardEulerIvpOdeSolver.hpp" #include <cmath> void BackwardEulerIvpOdeSolver::ComputeResidual(AbstractOdeSystem* pAbstractOdeSystem, double timeStep, double time, std::vector<double>& rCurrentYValues, std::vector<double>& rCurrentGuess) { std::vector<double> dy(mSizeOfOdeSystem); //For JC to optimize pAbstractOdeSystem->EvaluateYDerivatives(time+timeStep, rCurrentGuess, dy); for (unsigned i=0; i<mSizeOfOdeSystem; i++) { mResidual[i] = rCurrentGuess[i] - timeStep * dy[i] - rCurrentYValues[i]; } } void BackwardEulerIvpOdeSolver::ComputeJacobian(AbstractOdeSystem* pAbstractOdeSystem, double timeStep, double time, std::vector<double>& rCurrentYValues, std::vector<double>& rCurrentGuess) { for (unsigned i=0; i<mSizeOfOdeSystem; i++) { for (unsigned j=0; j<mSizeOfOdeSystem; j++) { mJacobian[i][j] = 0.0; } } if (pAbstractOdeSystem->GetUseAnalyticJacobian() && !mForceUseOfNumericalJacobian) { // The ODE system has an analytic jacobian, so use that AbstractOdeSystemWithAnalyticJacobian* p_ode_system = static_cast<AbstractOdeSystemWithAnalyticJacobian*>(pAbstractOdeSystem); p_ode_system->AnalyticJacobian(rCurrentGuess, mJacobian, time, timeStep); } else { ComputeNumericalJacobian(pAbstractOdeSystem, timeStep, time, rCurrentYValues, rCurrentGuess); } } void BackwardEulerIvpOdeSolver::SolveLinearSystem() { double fact; for (unsigned i=0; i<mSizeOfOdeSystem; i++) { for (unsigned ii=i+1; ii<mSizeOfOdeSystem; ii++) { fact = mJacobian[ii][i]/mJacobian[i][i]; for (unsigned j=i; j<mSizeOfOdeSystem; j++) { mJacobian[ii][j] -= fact*mJacobian[i][j]; } mResidual[ii] -= fact*mResidual[i]; } } // This needs to int, since a downloop in unsigned won't terminate properly for (int i=mSizeOfOdeSystem-1; i>=0; i--) { mUpdate[i] = mResidual[i]; for (unsigned j=i+1; j<mSizeOfOdeSystem; j++) { mUpdate[i] -= mJacobian[i][j]*mUpdate[j]; } mUpdate[i] /= mJacobian[i][i]; } } double BackwardEulerIvpOdeSolver::ComputeNorm(double* pVector) { double norm = 0.0; for (unsigned i=0; i<mSizeOfOdeSystem; i++) { if (fabs(pVector[i]) > norm) { norm = fabs(pVector[i]); } } return norm; } void BackwardEulerIvpOdeSolver::ComputeNumericalJacobian(AbstractOdeSystem* pAbstractOdeSystem, double timeStep, double time, std::vector<double>& rCurrentYValues, std::vector<double>& rCurrentGuess) { std::vector<double> residual(mSizeOfOdeSystem); std::vector<double> residual_perturbed(mSizeOfOdeSystem); std::vector<double> guess_perturbed(mSizeOfOdeSystem); double epsilon = mNumericalJacobianEpsilon; ComputeResidual(pAbstractOdeSystem, timeStep, time, rCurrentYValues, rCurrentGuess); for (unsigned i=0; i<mSizeOfOdeSystem; i++) { residual[i] = mResidual[i]; } for (unsigned global_column=0; global_column<mSizeOfOdeSystem; global_column++) { for (unsigned i=0; i<mSizeOfOdeSystem; i++) { guess_perturbed[i] = rCurrentGuess[i]; } guess_perturbed[global_column] += epsilon; ComputeResidual(pAbstractOdeSystem, timeStep, time, rCurrentYValues, guess_perturbed); for (unsigned i=0; i<mSizeOfOdeSystem; i++) { residual_perturbed[i] = mResidual[i]; } // Compute residual_perturbed - residual double one_over_eps = 1.0/epsilon; for (unsigned i=0; i<mSizeOfOdeSystem; i++) { mJacobian[i][global_column] = one_over_eps*(residual_perturbed[i] - residual[i]); } } } void BackwardEulerIvpOdeSolver::CalculateNextYValue(AbstractOdeSystem* pAbstractOdeSystem, double timeStep, double time, std::vector<double>& rCurrentYValues, std::vector<double>& rNextYValues) { // Check the size of the ODE system matches the solvers expected assert(mSizeOfOdeSystem == pAbstractOdeSystem->GetNumberOfStateVariables()); unsigned counter = 0; // const double eps = 1e-6 * rCurrentGuess[0]; // Our tolerance (should use min(guess) perhaps?) const double eps = 1e-6; // JonW tolerance double norm = 2*eps; std::vector<double> current_guess(mSizeOfOdeSystem); current_guess.assign(rCurrentYValues.begin(), rCurrentYValues.end()); while (norm > eps) { // Calculate Jacobian and mResidual for current guess ComputeResidual(pAbstractOdeSystem, timeStep, time, rCurrentYValues, current_guess); ComputeJacobian(pAbstractOdeSystem, timeStep, time, rCurrentYValues, current_guess); // // Update norm (our style) // norm = ComputeNorm(mResidual); // Solve Newton linear system SolveLinearSystem(); // Update norm (JonW style) norm = ComputeNorm(mUpdate); // Update current guess for (unsigned i=0; i<mSizeOfOdeSystem; i++) { current_guess[i] -= mUpdate[i]; } counter++; assert(counter < 20); // avoid infinite loops } rNextYValues.assign(current_guess.begin(), current_guess.end()); } BackwardEulerIvpOdeSolver::BackwardEulerIvpOdeSolver(unsigned sizeOfOdeSystem) { mSizeOfOdeSystem = sizeOfOdeSystem; // default epsilon mNumericalJacobianEpsilon = 1e-6; mForceUseOfNumericalJacobian = false; // allocate memory mResidual = new double[mSizeOfOdeSystem]; mUpdate = new double[mSizeOfOdeSystem]; mJacobian = new double*[mSizeOfOdeSystem]; for (unsigned i=0; i<mSizeOfOdeSystem; i++) { mJacobian[i] = new double[mSizeOfOdeSystem]; } } BackwardEulerIvpOdeSolver::~BackwardEulerIvpOdeSolver() { // Delete pointers delete[] mResidual; delete[] mUpdate; for (unsigned i=0; i<mSizeOfOdeSystem; i++) { delete[] mJacobian[i]; } delete[] mJacobian; } void BackwardEulerIvpOdeSolver::SetEpsilonForNumericalJacobian(double epsilon) { assert(epsilon > 0); mNumericalJacobianEpsilon = epsilon; } void BackwardEulerIvpOdeSolver::ForceUseOfNumericalJacobian() { mForceUseOfNumericalJacobian = true; } // Serialization for Boost >= 1.36 #include "SerializationExportWrapperForCpp.hpp" CHASTE_CLASS_EXPORT(BackwardEulerIvpOdeSolver)
#pragma once #include <spdlog/spdlog.h> #include <chrono> #include <fstream> #include <iostream> namespace days { enum class day { day_1 = 1, day_2, day_3, day_4, day_5, day_6, day_7, day_8, day_9, day_10, day_11, day_12, day_13, day_14, day_15, day_16, day_17, day_18, day_19, day_20, day_21, day_22, day_23, day_24, day_25, num }; enum class part { part_1 = 1, part_2, num }; template<day Day, part Part> extern auto solve(std::istream &input) -> std::string; template<day Day, part Part> auto solve_problem() -> void { spdlog::info("solving day {} part {}", Day, Part); auto const input_file_name = fmt::format("input{}.txt", Day); std::ifstream file(input_file_name); if (file.good()) { using clock = std::chrono::high_resolution_clock; auto const start = clock::now(); auto const out = solve<Day, Part>(file); spdlog::info("Result: {}", out); auto const finish = clock::now(); auto const microseconds = std::chrono::duration_cast<std::chrono::microseconds>(finish - start); spdlog::info("+solved day {} part {} in {} microseconds", Day, Part, microseconds.count()); } else { spdlog::error("the input file for day {} does not exist", Day); } } }// namespace days
#ifndef __URIMAGE_H__ #define __URIMAGE_H__ #include "png.h" class urImage { protected: png_structp png_ptr; png_infop info_ptr; png_uint_32 width; png_uint_32 height; int bit_depth, color_type, interlace_type, channels; png_bytep buffer; public: png_uint_32 getWidth() { return width; } png_uint_32 getHeight() { return height; } int getBitDepth() { return bit_depth; } int getColorType() { return color_type; } int getInterlaceType() { return interlace_type; } const void* getBuffer() { return buffer; } void resize(png_uint_32 width, png_uint_32 height); void flipPixels(); urImage(const char* file_name); ~urImage(void); }; #endif // __URIMAGE_H__
/* NO WARRANTY * * BECAUSE THE PROGRAM IS IN THE PUBLIC DOMAIN, THERE IS NO * WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE * LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE AUTHORS * AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT * WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY * AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO * THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD * THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL * NECESSARY SERVICING, REPAIR OR CORRECTION. * * IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN * WRITING WILL ANY AUTHOR, OR ANY OTHER PARTY WHO MAY MODIFY * AND/OR REDISTRIBUTE THE PROGRAM, BE LIABLE TO YOU FOR DAMAGES, * INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL * DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM * (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING * RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES * OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER * PROGRAMS), EVEN IF SUCH AUTHOR OR OTHER PARTY HAS BEEN ADVISED * OF THE POSSIBILITY OF SUCH DAMAGES. */ #ifndef _DRAGDROPDRAWABLE_H_ #define _DRAGDROPDRAWABLE_H_ #include "DragDropobject.h" class DragDropDrawable : public DragDropObject{ typedef DragDropObject inherited; public: DragDropDrawable(); DragDropDrawable(CRect* pRect); DragDropDrawable(CPoint location, CSize size); virtual int SetPenStyle(int nPenStyle); virtual int SetPenWidth(int nPenWidth); virtual COLORREF SetPenColor(COLORREF penColor); virtual int GetStockPen() { return (int)m_wStockPen; } virtual int GetPenStyle() { return (int)m_wPenStyle; } virtual int GetPenWidth() { return (int)m_wPenWidth; } virtual COLORREF GetPenColor() { return m_colorPen; } virtual int SetStockBrush(int nStockBrush); virtual COLORREF SetBrushColor(COLORREF brushColor); virtual int GetStockBrush() {return (int)m_wStockBrush; } virtual COLORREF GetBrushColor() { return m_colorBrush; } virtual int SetStockPen(int nStockPen); virtual BOOL paint(CDC* pDC); virtual void Serialize(CArchive& ar); virtual DragDropObject* Clone() const; protected: WORD m_wStockPen; // One of NULL, BLACK_PEN, NULL_PEN, WHITE_PEN WORD m_wPenStyle; // pen Style for border WORD m_wPenWidth; // pen Width for border WORD m_wStockBrush; // One of NULL, BLACK_BRUSH, DKGRAY_BRUSH, HOLLOW_BRUSH, LTGRAY_BRUSH, // NULL_BRUSH, or WHITE_BRUSH COLORREF m_colorPen; // pen Color for border COLORREF m_colorBrush; // Color for CreateSolidBrush virtual void PreparePen(CDC* pDC, CPen*& pPen, CPen*& pOldPen); //new, should obsolete above routines soon virtual void PostPen(CDC* pDC, CPen* pPen, CPen* pOldPen); virtual void PrepareBrush(CDC* pDC, CBrush*& pBrush, CBrush*& pOldBrush); virtual void PostBrush(CDC* pDC, CBrush* pBrush, CBrush* pOldBrush); private: void Init(); DECLARE_SERIAL(DragDropDrawable) }; #endif
class Solution { public: int maximumSwap(int num) { string orgVal = to_string(num); string maxVal = orgVal; sort(maxVal.begin(), maxVal.end(), greater<char>()); int left = 0; int right = maxVal.length() - 1; while(left < right) { while(left < right && orgVal[left] == maxVal[left]) { left++; } while(left < right && maxVal[left] != orgVal[right]) { right--; } if (left != right) { swap(orgVal[left], orgVal[right]); break; } } return stoi(orgVal); } };
//************************************************************ // Ryan Copenhaver // COP2000.0M1 // Project 2: Average Rainfall // This program averages rainfall from three months entered by // the user. //************************************************************ #include <iostream> #include <string> // Needed for string objects #include <iomanip> // Needed to use stream manipulators using namespace std; int main() { string month1, month2, month3; // to hold the values for months entered by user. double rain1, rain2, rain3, average; // to hold values of rainfall and average rainfall. // Prompt user to enter month1 cout << "This program will calculate the average rainfall of three months\n" << "\nPlease enter the name of the first month: "; getline(cin, month1); // Prompt user to enter rainfall for month1 and clear keyboard buffer cout << "What was the total rainfall, in inches, for " + month1 + ": "; cin >> rain1; cin.ignore(); // Prompt user to enter month2 cout << "\nPlease enter the name of the second month: "; getline(cin, month2); // Prompt user to enter rainfall for month2 and clear keyboard buffer cout << "What was the total rainfall, in inches, for " + month2 + ": "; cin >> rain2; cin.ignore(); // Prompt user to enter month3 cout << "\nPlease enter the name of the third month: "; getline(cin, month3); // Prompt user to enter rainfall for month3 cout << "What was the total rainfall, in inches, for " + month3 + ": "; cin >> rain3; // Find the average of the three months average = (rain1 + rain2 + rain3)/3; // Display the result cout << fixed << setprecision(2); cout << "\nThe average monthly rainfall for " + month1 + ", " + month2 + ", and " << month3 + " was " << average << " inches.\n"; return 0; }
// C++ for the Windows Runtime vv1.0.170303.6 // Copyright (c) 2017 Microsoft Corporation. All rights reserved. #pragma once WINRT_EXPORT namespace winrt { namespace ABI::Windows::Data::Pdf { struct IPdfDocument; struct IPdfDocumentStatics; struct IPdfPage; struct IPdfPageDimensions; struct IPdfPageRenderOptions; struct PdfDocument; struct PdfPage; struct PdfPageDimensions; struct PdfPageRenderOptions; } namespace Windows::Data::Pdf { struct IPdfDocument; struct IPdfDocumentStatics; struct IPdfPage; struct IPdfPageDimensions; struct IPdfPageRenderOptions; struct PdfDocument; struct PdfPage; struct PdfPageDimensions; struct PdfPageRenderOptions; } namespace Windows::Data::Pdf { template <typename T> struct impl_IPdfDocument; template <typename T> struct impl_IPdfDocumentStatics; template <typename T> struct impl_IPdfPage; template <typename T> struct impl_IPdfPageDimensions; template <typename T> struct impl_IPdfPageRenderOptions; } namespace Windows::Data::Pdf { enum class PdfPageRotation { Normal = 0, Rotate90 = 1, Rotate180 = 2, Rotate270 = 3, }; } }
#if !defined(AFX_CONFIGDIALOG_H__1BD101C2_420D_11D5_B612_002018BA6D85__INCLUDED_) #define AFX_CONFIGDIALOG_H__1BD101C2_420D_11D5_B612_002018BA6D85__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 // ConfigDialog.h : Header-Datei // #include "resource.h" #include "SnapDialog.h" #include "xShadeButton.h" ///////////////////////////////////////////////////////////////////////////// // Dialogfeld CConfigDialog class CConfigDialog : public CSnapDialog { typedef CSnapDialog inherited; // Konstruktion public: CConfigDialog(CWnd* pParent = NULL); // Standardkonstruktor // Dialogfelddaten //{{AFX_DATA(CConfigDialog) enum { IDD = IDD_CONFIG_DIALOG }; // HINWEIS: Der Klassen-Assistent fügt hier Datenelemente ein //}}AFX_DATA // Überschreibungen // Vom Klassen-Assistenten generierte virtuelle Funktionsüberschreibungen //{{AFX_VIRTUAL(CConfigDialog) protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV-Unterstützung //}}AFX_VIRTUAL // Implementierung protected: // Generierte Nachrichtenzuordnungsfunktionen //{{AFX_MSG(CConfigDialog) // HINWEIS: Der Klassen-Assistent fügt hier Member-Funktionen ein //}}AFX_MSG DECLARE_MESSAGE_MAP() }; //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ fügt unmittelbar vor der vorhergehenden Zeile zusätzliche Deklarationen ein. #endif // AFX_CONFIGDIALOG_H__1BD101C2_420D_11D5_B612_002018BA6D85__INCLUDED_
#include "melsec.h" #include <QString> #include <QTimer> #include <QDebug> RxMelsec::RxMelsec(): nPort(5002) ,nC(0),plcAddr(1) // кноструктор, треба уточнити { // теймер для періодичної відправки запитів //connSend=new QTimer(this); //connSend->setInterval(1000); //connect(connSend,SIGNAL(timeout()),this,SLOT(slotSend())); // теймер паузи між спробами встановити нове з’єднання connWait=new QTimer(this); connWait->setInterval(10000); connect(connWait,SIGNAL(timeout()),this,SLOT(slotNewConnect())); // таймер для відліку таймайту з’єднання connTimeout=new QTimer(this); connTimeout->setInterval(30000); connect(connTimeout,SIGNAL(timeout()),this,SLOT(slotTimeout())); // сокет для здійснення обміну даними pS=new QTcpSocket(this); connect(pS,SIGNAL(connected()),this,SLOT(slotConnected())); connect(pS,SIGNAL(error(QAbstractSocket::SocketError)),this,SLOT(slotError(QAbstractSocket::SocketError))); connect(pS,SIGNAL(readyRead()),this,SLOT(slotRead())); connect(pS,SIGNAL(disconnected()),this,SLOT(slotDisconnect())); cmdpref["D"]=qint8(0xA8); cmdpref["X"]=qint8(0x9C); cmdpref["Y"]=qint8(0x9D); cmdpref["M"]=qint8(0x90); cmdpref["L"]=qint8(0x92); // десь тут ще потрібно сформувати пакунок на запити } RxMelsec::~RxMelsec() // поки-що тривіальний деструктор { pS->close(); } void RxMelsec::slotConnected () // приєдналися { //connSend->start(); connTimeout->start(); nLen=0; qDebug() << "Connected to host" << sHostname; // slotSend(); // розпочати обмін pS->write(query_list[0]); // qDebug() << "query_list[0]" << query_list[0].size(); nC=0; emit Alert(QString("Connected to PLC: %1:%2").arg(sHostname).arg(nPort)); } void RxMelsec::slotNewConnect() { connWait->stop(); pS->connectToHost(sHostname,nPort); } void RxMelsec::slotTimeout() // таймаут отримання даних від сервера { // connSend->stop(); connTimeout->stop(); connWait->start(); pS->close(); emit Alert(QString("Connection to PLC lost: %1:%2").arg(sHostname).arg(nPort)); qDebug() << QString("Connection to PLC lost: %1:%2").arg(sHostname).arg(nPort); } void RxMelsec::slotDisconnect() // відєднання зі сторони сервера { //connSend->stop(); // зупинити таймер, коли від’єднано немає сенсу слати запити pS->close(); } void RxMelsec::slotError(QAbstractSocket::SocketError) { //connSend->stop(); connTimeout->stop(); connWait->start(); //qDebug() << "Connection error"; emit Alert(QString("Connection to PLC error: %1:%2. %3").arg(sHostname).arg(nPort).arg(pS->errorString())); pS->close(); } // виявилося що не получається виконувавти асинхронні запити до контролера I-8000, це не дуже добре. /* void RxMelsec::slotSend() { #ifdef ASYNC //qDebug() << "Start -------------------------------------------------------------------------------"; if(1>local_read[0]) { pS->write(query_list[0]); local_read[0]=query_read[0]; } local_read[0]--; nC=0; #else // асинхронне виконання //qDebug() << "slotSend"; for(int i=1;i<query_list.size();++i) { if(1>local_read[i]) { //qDebug() << i; pS->write(query_list[i]); local_read[i]=query_read[i]; } local_read[i]--; } #endif } */ void RxMelsec::slotRead() { QDataStream in(pS); qint16 v16; quint8 v8; in.setByteOrder(QDataStream::LittleEndian); // встановити порядок байт // qDebug() << "slotRead()" << pS->bytesAvailable() ; for(;;) { if(nLen==0) // читати заголовок { if(pS->bytesAvailable()<9) // якщо тут мало байт { break; } // вичитати мусор, можливо воно щось означає... in >> v8; in >> v16; in >> v16; in >> v16; in >> v16; // вичитати довжину nLen=v16; // зкорегувати та зберегти довжину // qDebug() << "nLen" << nLen; } if(pS->bytesAvailable()<nLen) { break; } in >> v16; // знову мусор // отримано весь пакунок, розібрати на частини //qDebug() << "Start packet proccess Index" << Index << "nLen" << nLen << "as " << as << "fc" << fc; //тепер тут є чотири варіанти // 1 - отримано певну кількісит слів, котрі є регістрами D // 2 - отримано певну кількість тетрад (спакованих в байти) котрі є бітами // 3 - нічого не отримано, якщо перед цим була передача даних // 4 - отримано якесь повідомлення про помилку у відповідь на передачу даних. if(nC<query_list.size()) // якщо попереду був пакунок із query_list { // тоді треба зберегти отримані від контролера дані if(quint8(query_list[nC][18])==0xA8) // що то за дані якщо 0xA8 згачить D-регістри { for(int i=0;i<(nLen-2)/2;++i) // читати слова { in >> v16; data_raw[Index[nC]+i]=v16; } } else // інакще там біти { for(int i=0;i<nLen-2;++i) { in >> v8; data_raw[Index[nC]+i*2]=v8&0x10?-1:0; // якось так. data_raw[Index[nC]+i*2+1]=v8&0x1?-1:0; } } } else // інакще щоб там не було споржнити до кінця { while(!in.atEnd()) // чи це спрацює ? треба ретельно перевірити.... in >> v8; } #ifdef ASYNC //qDebug() << "nC " << nC << "query_list.size()" << query_list.size() ; // відправити наступний запит ++nC; while(nC<query_list.size()) { local_read[nC]--; if(1>local_read[nC]) { pS->write(query_list[nC]); local_read[nC]=query_read[nC]; break; } ++nC; } // перерахувати шкальовані значення if(nC==query_list.size()) { //qDebug() << "Calculate data_scale"; updateScaledValue(); emit updateData(); } if(! (nC < query_list.size())) { //qDebug() << "Process query queue" ; if(query_queue.isEmpty()) // перевірити чергу при умові що інших запитів немає. { pS->write(query_list[0]); nC=0; } else pS->write(query_queue.dequeue()); // якщо не пуста, передати } #endif nLen=0; } connTimeout->stop(); connTimeout->start(); // qDebug() << data_raw; } int RxMelsec::loadList(QString fileName) { QFile f(fileName); int i; QString s; QStringList sl; QString type,type_old; int wc=0, wc_last=0; // лічильник слів qint16 next_addr=0,current_addr=0; //адреси qint16 current_len=0,packet_len=0; // поточна довжина qint16 current_rf=0,last_rf=0; // прапори читання QByteArray query; QDataStream qry(&query,QIODevice::WriteOnly); qry.setByteOrder(QDataStream::LittleEndian); QHash<QString,QString> tag_scale; // тут будуть теги, які шкалюються по іншому параметру QStringList ft; ft << "Integer" << "Bool" << "Real" << "Timer" << "Long" << "EBOOL" ; qint16 current_ft=0; // пити полів, для виявлення EBOOL //qDebug() << "file " << fileName; // очистити все на випадок повторного завантаження tags.clear(); query_list.clear(); query_read.clear(); local_read.clear(); if(f.open(QIODevice::ReadOnly)) { for(i=0;!f.atEnd();++i) { s=QString::fromUtf8(f.readLine()).trimmed(); //читати //qDebug() << i << s; sl= s.split("\t"); // розбити на поля if(sl.size()>4) // якщо є всі поля { s= sl[0]; // назва тега //qDebug() << s; type_old=type; type=sl[1].left(1); if(type=="X" || type=="Y") // це кодується в 16-й системі current_addr=sl[1].right(sl[1].size()-1).toInt(0,16); else current_addr=sl[1].right(sl[1].size()-1).toInt(); // індекс, тут би для повного щася треба б було перевірити чи воно правильно перетворилося на число tags[s] << wc // 0-index << current_addr ; // 1- address current_rf=sl[3].toInt(); wc_last=wc; // це потрібно для правильного формування поля id транзакції яке містить зміщення індексу в масиві даних // метод не зовсім стандартний, на інших контролерах може і не буде працювати // розпізнати типи даних if(type=="D") { if(sl[2]=="Integer" ) { ++wc; current_len=1; } else if (sl[2]=="Real" || sl[2]=="Timer" || sl[2]=="Long" ) { wc+=2; current_len=2; } else { qDebug() << tr("Unknown data type") << sl[2] << sl; ::exit(1); } } else if(type=="M" || type=="L" || type=="X" || type=="Y") // це точно байт { ++wc; current_len=1; // тут треба зімітувати дірку } else // невідомий тип даних { qDebug() << tr("Unknown data type") << type << sl[2] << sl; ::exit(1); } current_ft=ft.indexOf(sl[2]); //qDebug() << sl[2] << ft[current_ft]; tags[s] << current_ft // 2-довжина !!! це місце треба перевірити << current_rf // 3-кратність читання << sl[4].toInt() // 4-прапори запису історії << 0 // 5 шкаліровка, може мінятися далі в програмі << cmdpref[type] ; // 6 тип змінної packet_len+=current_len; if( // packet_len>124 || current_addr>next_addr || // виявити дірки, current_rf!=last_rf || // межі пакунків, type != type_old ) // зміна типу // (current_ft==5 && last_ft!=5) || // кратність читання // (current_ft!=5 && last_ft==5)) // чи зміну типу { // Зберегти індекс в масиві даних Index << wc_last; if(query.size()) // якщо щось є, { query_list << query; // зберегти dataLen << packet_len; //qDebug() << packet_len-current_len; // //qDebug() << query; } // підготуватися до нового запиту qry.device()->seek(0); query.clear(); // сформувати заголовок packet_len=current_len; // сформувати запит qry << qint8(0x50) << qint8(0) // subheader << qint8(1) // netv No << plcAddr // Addres PLC << qint8(0xFF) << qint8(0x03) << qint8(0x0) // не знаю що це << qint8(0x0c) << qint8(0x0) // data length << qint8(0x30) << qint8(0x0) // timer << qint8(0x01) << qint8(0x4) // command << (type=="D" ?qint8(0x0):qint8(1)) << qint8(0x0) // subcommand << current_addr << qint8(0x0) // start // адреса задається в трома байтами, тут старший завжди нуль, відповідно можна отримати тільки 65536 слів << cmdpref[type] ; // Data type //<< qint16(0x0); // len //^^^^^^^^^^^^^^^^^^^^^^ можливо для інших контролерів цей декримент непотрібен //qDebug() << qint16(wc_last) << qint16(0) << qint16(6) << qint8(1) << qint8(sl[2]=="EBOOL"?GETMCR:GETMHR) << qint16(current_addr-1); query_read << current_rf; //прапор read на пакунок local_read << 0; } else // в іншому разі поновити дані про довжину. { qry.device()->seek(query.size()-2); } qry << packet_len; //додати довжину пакунка next_addr=current_addr+current_len; // розрахувати новий наступний очікуваний адрес last_rf=current_rf; //last_ft=current_ft; if(sl.size()>6) text[s]=sl[6] ; // назва тега else text[s]="-"; // цей код би винести в окремий клас if(sl[5]!="-") { //qDebug() << "sl[5] " << sl[5]; if(sl[5]=="+") { tags[s][5]=1; QSettings set; //qDebug() << QString("/ioserv/scale/%1").arg(objectName()); set.beginGroup(QString("/ioserv/scale/%1").arg(objectName())); data_scale[s] << 0.0 << set.value(QString("Zero/%1").arg(s),0.0).toDouble() << set.value(QString("Full/%1").arg(s),100.0).toDouble(); //qDebug() << QString("Zero/%1").arg(s) << set.value(QString("Zero/%1").arg(s),0.0).toDouble(); //qDebug() << QString("Full/%1").arg(s) << set.value(QString("Full/%1").arg(s),100.0).toDouble() << "\n\n"; } else { QStringList f=sl[5].split(" "); // розбити поле на дві частини if(f.size()==2) // якщо там його насправді двое { bool o1,o2; double zs,fs; zs=f[0].toDouble(&o1); fs=f[1].toDouble(&o2); if(o1 && o2) { data_scale[s] << 0.0 << zs << fs; } else { data_scale[s] << 0.0 << 0.0 << 100.0; } } else // якщо дойшли сюди то там мабуть тег { tag_scale[s]=sl[5]; // запам’ятати } } } } } if(query.size()) // зберегти останній запит. { query_list << query; dataLen << packet_len; //qDebug() << packet_len; query_read << current_rf; } data_raw.resize(wc); // ініціалізувати пам’ять під змінні f.close(); // завантаженя відложених тегів, якщо є foreach(QString f,tag_scale.keys()) { if(data_scale.contains(tag_scale[f])) { data_scale[f] << 0.0 << data_scale[tag_scale[f]][1] << data_scale[tag_scale[f]][2] ; } else { //qDebug() << "Scale not found tag"<< f << "scaled on " << tag_scale[f]; } } //qDebug() << "Scaled tags " << data_scale.size() << "\n" << data_scale.keys(); //qDebug() << tags.keys(); //loadScale(fileName); /* qDebug() << "Query list ------------"; foreach(QByteArray ba, query_list) { QString out=""; foreach(qint8 b,ba) { out+=QString("0x%1,\n").arg(qint32(b)&0xFF,2,16,QChar('0')); } qDebug() << ba.size() << "--\n" << out << "--"; } qDebug() << "-----------------------"; */ return i; } else { return 0; } } void RxMelsec::setHostName(QString hostName) { sHostname=hostName; } void RxMelsec::setPort(int Port) { nPort=Port; } void RxMelsec::start() { // тут би треба зробити якісь додаткові перевірки pS->connectToHost(sHostname,nPort); } void RxMelsec::sendValue(QString tag,qint16 v) { // qDebug() << "sendValue(qint16" << tag << "," << v << ") type" << tags[tag][2]; QVector<qint16> t; t << v; sendValue(tag,t); } void RxMelsec::sendValue(QString tag,qint32 v) { // qDebug() << "sendValue(qint32 " << tag << "," << v << ") type" << tags[tag][2]; QVector<qint16> t(2); *((qint32*)t.data())=v; if(data_scale.contains(tag)) // якщо датий тег присутній в масиві шкальованих значень тоді відшкалювати його data_scale[tag][0]=((double)v/4000.0*(data_scale[tag][2]-data_scale[tag][1])+data_scale[tag][1]); sendValue(tag,t); } void RxMelsec::sendValue(QString tag,double v) { QVector<qint16> t(2); // qDebug() << "sendValue(doulbe " << tag << "," << v << ") type" << tags[tag][2]; switch(tags[tag][2]) { case 2: *((float*)t.data())=(float)v; sendValue(tag,t); break; case 0: sendValue(tag,qint16(v)); break; case 3: case 4: sendValue(tag,qint32(v)); break; } if(data_scale.contains(tag)) // якщо датий тег присутній в масиві шкальованих значень тоді відшкалювати його { data_scale[tag][0]=(v/4000.0*(data_scale[tag][2]-data_scale[tag][1])+data_scale[tag][1]); qDebug() << "tag " << tag << " value " << v << "scaled " << data_scale[tag][0]; } } void RxMelsec::sendValue(QString tag,QVector<qint16> &v) { // qDebug() << "sendValue(QVector<qint16> " << tag << "," << v << ") type" << tags[tag][2]; QByteArray q; QDataStream qry(&q,QIODevice::WriteOnly); qry.setByteOrder(QDataStream::LittleEndian); QVector<qint8> vp; // масив, у якому будуть підгтовані для передачі дані qint16 pLen,vLen=v.size(); if(tags.contains(tag) ) // перевірити наявність заданого тега { if(quint8(tags[tag][6])!=0xA8) // якщо D-регістер { if(tags[tag][6]==0x9C) // якщ там X-регісти return; // далі можна не продовжувати if(v.size()%2) // кількість змінних має бути парною, інакше буде проблема v << 0; // дописати нуль, контролер його проігнорує for(int i=0;i<v.size();i+=2) vp << qint8( (v[i]?0x10:0 )| (v[i+1]?0x01:0) ); pLen=vp.size(); // qDebug() << "vp" << vp; } else { pLen=v.size()*2; } //qDebug() << tag << QString("%1").arg(qint32(tags[tag][6])&0xff,2,16,QChar('0')) << v; qry << qint8(0x50) << qint8(0) // subheader << qint8(1) // netv No << plcAddr // Addres PLC << qint8(0xFF) << qint8(0x03) << qint8(0x0) // не знаю що це << qint16(pLen+12) // data length << qint8(0x30) << qint8(0x0) // timer << qint8(0x01) << qint8(0x14) // command << ( quint8(tags[tag][6])==0xA8 ?qint8(0x0):qint8(1)) << qint8(0x0) // subcommand // << qint8(0x1) << qint8(0x0) // subcommand << qint16(tags[tag][1]) << qint8(0x0) // start // адреса задається в трома байтами, тут старший завжди нуль, відповідно можна отримати тільки 65536 слів << qint8(tags[tag][6]) // Data type << vLen ; // Розмір масиву з даними. if(quint8(tags[tag][6])==0xA8) { foreach(qint16 t,v) { qry << t; // завантажити дані } } else { foreach(qint8 t,vp) { qry << t; // завантажити дані } } // наступний фрагмент занесе змінені дані в сховище int x=tags[tag][0]; foreach(qint16 t,v) data_raw[x++]=t; // записати в буфер /*{ QString s=""; qDebug() << "sendValue() ----------------------------"; foreach (quint8 val, q) { s+=QString("%1 ").arg(quint32(val)&0xFF,2,16,QChar('0')); } qDebug() << "Size" << q.size() << "\n" << s; qDebug() << "-----------------------------------------"; }*/ #ifdef ASYNC query_queue.enqueue(q); // поставити в чергу на відправку в контролер #endif if(data_scale.contains(tag) && v.size()==2) // якщо датий тег присутній в масиві шкальованих значень тоді відшкалювати його і записувалося одиночне значення { double tv; switch(tags[tag][2]) // тип даних { default: case 2: // Real tv=*(float*)v.data(); break; case 3: // Timer case 4: // Long tv=*(int*)v.data(); break; } data_scale[tag][0]=(tv/4000.0*(data_scale[tag][2]-data_scale[tag][1])+data_scale[tag][1]); } } }
#include <bits/stdc++.h> using namespace std; void check(double a[], double b[], int n){ int dem = 0; for (int i=0; i<n; ++i){ if (a[i]<b[i]){ dem ++; } } if (dem != 0){ cout << "No"; } else cout << "Yes"; } void giamDan (double a[], double n){ double tg=0.00; for (int i=0; i<n-1; ++i){ for (int j=i+1; j<n; j++){ if (a[i]>a[j]){ tg = a[i]; a[i] = a[j]; a[j] = tg; } } } } int main(){ int n; cin >> n; double a[n], b[n]; for (int i=0; i<n; ++i){ cin >> a[i] >> b[i]; } giamDan(a, n); giamDan(b, n); check (a, b, n); }
#pragma once #include "../Vector2.h" #include "../MathExtender.h" class Profile { public: Profile(); virtual void GetOffsetAndHeading(Vector2& offset, Vector2& heading); }; class PointProfile : public Profile { public: PointProfile(); void GetOffsetAndHeading(Vector2& offset, Vector2& heading); }; class CircleProfile : public Profile { public: CircleProfile(float radius, bool radiate); float Radius; bool Radiate; void GetOffsetAndHeading(Vector2& offset, Vector2& heading); }; class BoxProfile : public Profile { public: BoxProfile(float width, float height); float Width; float Height; void GetOffsetAndHeading(Vector2& offset, Vector2& heading); }; class RingProfile : public Profile { public: RingProfile(float radius, bool radiate); float Radius; bool Radiate; void GetOffsetAndHeading(Vector2& offset, Vector2& heading); }; class BoxFillProfile : public Profile { public: BoxFillProfile(float width, float height); float Width; float Height; void GetOffsetAndHeading(Vector2& offset, Vector2& heading); };
//ros #include <ros/ros.h> #include <ros/package.h> #include <image_transport/image_transport.h> #include <cv_bridge/cv_bridge.h> #include <sensor_msgs/image_encodings.h> //tinyxml #include "tinyxml2.h" //opencv #include <opencv2/opencv.hpp> #include <opencv2/aruco.hpp> #include <opencv2/core.hpp> #include <opencv2/calib3d.hpp> #include <opencv2/imgcodecs.hpp> #include <opencv2/imgproc.hpp> #include <opencv2/highgui.hpp> //c++ #include <sstream> #include <iostream> #include <string> #include <cmath> #include <fstream> #include <algorithm> #define rw 640 #define rh 480 using namespace cv; using namespace std; using namespace tinyxml2; int main(int argc,char *argv[]) { int object_num = 3; string object_adr[3]; int file_num = 800; //for every object int total_index = 1; vector<string> file_table; vector<string> test_table; vector<string> val_table; vector<string> train_table; vector<string> trainval_table; float test_ratio = 0.15; float val_ratio = 0.08; object_adr[0] = "/home/mzm/build_dataset_pic/src/build_dataset/object_dataset/movefree"; object_adr[1] = "/home/mzm/build_dataset_pic/src/build_dataset/object_dataset/zhencui"; object_adr[2] = "/home/mzm/build_dataset_pic/src/build_dataset/object_dataset/taiping"; string xml_file = "/object_xmlfile/"; string rgb_file = "/object_rgb_dataset/"; string new_xml_file = "/home/mzm/build_dataset_pic/src/build_dataset/voc2007_object_dataset/Annotations/"; string new_rgb_file = "/home/mzm/build_dataset_pic/src/build_dataset/voc2007_object_dataset/JPEGImages/"; string new_config_file = "/home/mzm/build_dataset_pic/src/build_dataset/voc2007_object_dataset/ImageSets/Main/"; string test_file = "/test.txt"; string train_file = "/train.txt"; string val_file = "/val.txt"; string trainval_file = "/trainval.txt"; for(int n=0;n<object_num;n++) { for(int i = 1;i<=file_num;i++) { char file_name[7]="000000"; char new_file_name[7]="000000"; int index = i; int new_index = total_index; for(int j=5;j>=0;j--) { if(index>0) { file_name[j] ='0' + index%10; index/=10; } else file_name[j] = '0'; } for(int j=5;j>=0;j--) { if(new_index>0) { new_file_name[j] ='0' + new_index%10; new_index/=10; } else new_file_name[j] = '0'; } stringstream ss1; string i1; ss1<<file_name; ss1>>i1; stringstream ss2; string i2; ss2<<new_file_name; ss2>>i2; string title1 = object_adr[n]+xml_file+i1+".xml"; string title2 = new_xml_file+i2+".xml"; //save xml files XMLDocument docXml; XMLError errXml = docXml.LoadFile(title1.c_str()); if (XML_SUCCESS == errXml) { XMLError eResult = docXml.SaveFile(title2.c_str()); if (XML_SUCCESS == eResult) cout<<"save no: "<< i2 <<" xml success."<<endl; } else { cout<<"save xml file failed."<<endl; } //save rgb images string title3 = object_adr[n]+rgb_file+i1+".jpg"; string title4 = new_rgb_file+i2+".jpg"; Mat rgb; rgb = imread(title3); imwrite(title4,rgb); cout<<"save no: "<< i2 <<" jpg success."<<endl; total_index++; } } //save config files for(int i=1;i<=file_num*object_num;i++) { char result_file_name[7]="000000"; int result_index = i; for(int j=5;j>=0;j--) { if(result_index>0) { result_file_name[j] ='0' + result_index%10; result_index/=10; } else result_file_name[j] = '0'; } stringstream ss3; string i3; ss3<<result_file_name; ss3>>i3; file_table.push_back(i3.c_str()); } random_shuffle(file_table.begin(),file_table.end()); /* 打乱顺序 */ int test_num = file_num*object_num*test_ratio; int val_num = (file_num*object_num-test_num)*val_ratio; for(int i=0;i<test_num;i++) { test_table.push_back(file_table[i]); } for(int i=test_num;i<test_num+val_num;i++) { val_table.push_back(file_table[i]); } for(int i=test_num+val_num;i<file_table.size();i++) { train_table.push_back(file_table[i]); } for(int i=test_num;i<file_table.size();i++) { trainval_table.push_back(file_table[i]); } ofstream test_stream; ofstream train_stream; ofstream val_stream; ofstream trainval_stream; string title5 = new_config_file+test_file; string title6 = new_config_file+train_file; string title7 = new_config_file+val_file; string title8 = new_config_file+trainval_file; test_stream.open(title5.c_str()); train_stream.open(title6.c_str()); val_stream.open(title7.c_str()); trainval_stream.open(title8.c_str()); cout<<"file:"<<endl; for (int i = 0; i<file_table.size(); i++) { cout<<file_table[i]<<" "; /* 显示打乱顺序后的元素 */ } cout<<endl; cout<<"test:"<<endl; for (int i = 0; i<test_table.size(); i++) { cout<<test_table[i]<<" "; /* 显示打乱顺序后的元素 */ test_stream<<test_table[i]<<endl; } cout<<endl; cout<<"val:"<<endl; for (int i = 0; i<val_table.size(); i++) { cout<<val_table[i]<<" "; /* 显示打乱顺序后的元素 */ val_stream<<val_table[i]<<endl; } cout<<endl; cout<<"train:"<<endl; for (int i = 0; i<train_table.size(); i++) { cout<<train_table[i]<<" "; /* 显示打乱顺序后的元素 */ train_stream<<train_table[i]<<endl; } cout<<endl; cout<<"trainval:"<<endl; for (int i = 0; i<trainval_table.size(); i++) { cout<<trainval_table[i]<<" "; /* 显示打乱顺序后的元素 */ trainval_stream<<trainval_table[i]<<endl; } test_stream.close(); train_stream.close(); val_stream.close(); trainval_stream.close(); // cout<<file_table<<endl; }
#ifndef RECTHREAD_H #define RECTHREAD_H #include <QFile> #include <QAudioInput> #include <QVariant> #include <QAudioDeviceInfo> class WavPcmFile; class AudioInfo; class QAudioFormat; class RecThread : public QObject { Q_OBJECT public: explicit RecThread(QAudioFormat format); ~RecThread(); void run(); bool isRunning(){ return isRun;} QAudioInput * inputAudio; void startTest(); QString getWavFile(); void switchAutoMod(bool); void setOverK(double); void setIT1(int); void setITstep1(int); void setIT2(int); void setITstep2(int); void setDelay(int); QList<QString> getDevices(); void isNeedToSavaTmpFiles(bool); protected: bool isRun; WavPcmFile * m_file; AudioInfo * m_audioInfo; QAudioFormat m_format; bool isTesting; QAudioDeviceInfo m_device; QList<QAudioDeviceInfo> devices; signals: void logging(QString); void setVolumeValue(QVariant); void setVolumeRange(QVariant); void testStopped(int); void needToStop(); public slots: void changeAudioDevice(int); void stopRecording(); void checkRecording(); void refreshVolumeInfo(); void stopTest(); }; #endif // RECTHREAD_H
#include "GV.h" static int font[2];//フォント用 static char *fonttype;//フォントタイプ static int place_x = 260;//文字のx座標 static int start_y = 250, start_x_size = 150, start_y_size = 30;//startの座標 static int record_y = 310, record_x_size = 150, record_y_size = 30; //recordの座標 static int close_y = 370, close_x_size = 150, close_y_size = 30;//closeの座標 static int start_f = 0, record_f = 0, close_f = 0;//マウスで選択されているかのフラグ static int background, rogo;//画像用 //ゲーム処理ループ void startmenu_update() { //マウスがstartの上にあるかの判定 if (mouse_x > place_x - start_f * 10 && mouse_x < place_x + start_f * 10 + start_x_size && mouse_y > start_y - start_f * 10 && mouse_y < start_y + start_f * 10 + start_y_size) start_f = 1; else start_f = 0; //マウスがrecordの上にあるかの判定 if (mouse_x > place_x - record_f * 10 && mouse_x < place_x + record_f * 10 + record_x_size && mouse_y > record_y - record_f * 10 && mouse_y < record_y + record_f * 10 + record_y_size) record_f = 1; else record_f = 0; //マウスがcloseの上にあるかの判定 if (mouse_x > place_x - close_f * 10 && mouse_x < place_x + close_f * 10 + close_x_size && mouse_y > close_y - close_f * 10 && mouse_y < close_y + close_f * 10 + close_y_size) close_f = 1; else close_f = 0; if (Mouse[0] == 1) { //マウスの左ボタンが押されていたら start_music(3); if (start_f == 1) Game_Scene = 1; if (record_f == 1) Game_Scene = 5; if (close_f == 1) game_loop = 1; } } //描画処理 void startmenu_draw() { DrawGraph(0, 0, background, TRUE); //画像の描画 DrawStringToHandle(place_x - start_f * 10, start_y - start_f * 10, "start", GetColor(255, 255, 255), font[start_f]); DrawStringToHandle(place_x - record_f * 10, record_y - record_f * 10, "record", GetColor(255, 255, 255), font[record_f]); DrawStringToHandle(place_x - close_f * 10, close_y - close_f * 10, "close", GetColor(255, 255, 255), font[close_f]); DrawGraph(220, 100, rogo, TRUE); //画像の描画 } //初期化関数 void startmenu_initialize() { fonttype = "Segoe Script"; font[1] = CreateFontToHandle(fonttype, 50, 3, DX_FONTTYPE_ANTIALIASING_EDGE);//フォント初期化 if (font[0] == -1) { printf("not find " + *fonttype); exit(-1); } font[0] = CreateFontToHandle(fonttype, 30, 3, DX_FONTTYPE_ANTIALIASING_EDGE);//フォント初期化 if (font[1] == -1) { printf("not find " + *fonttype); exit(-1); } background = LoadGraph("img/mati2.jpg");//画像ロード if (background == -1) { printf("not find mati1.jpg"); exit(-1); } rogo = LoadGraph("img/rogo1.png");//画像ロード if (rogo == -1) { printf("not find rogo1.png"); exit(-1); } } //ゲーム処理の終了関数 void startmenu_finalize() { }
#ifndef __FORCEMANAGER_H__ #define __FORCEMANAGER_H__ #include <map> #include "types.h" #include "primitive.h" #include "body.h" #include "force_generator.h" namespace physics { class ForceManager { public: ~ForceManager(); typedef map<int, ForceGenerator *> MapGenerators; // This compare method is used to make sure that // we can get same element in same map's iterations struct CompareByPriID { bool operator()(const RigidBody *b1, const RigidBody *b2) const { return b1->primitive->id < b2->primitive->id; } }; typedef std::map<RigidBody *, MapGenerators, CompareByPriID> MapBodies; MapBodies registrations; public: static unsigned int __force_id; void resetID(); unsigned int genID(); unsigned int add(RigidBody *body, ForceGenerator *fg); ForceGenerator *remove(RigidBody *body, unsigned int id); void clear(); void updateForces(ffloat duration); void render(); }; } #endif
#include "autoTile.h" #include "pointVector.h" #include "coordTransform.h" using namespace Gdiplus; void Autotile::drawLU(POINT l, POINT r, POINT u, POINT d, POINT lu) { if (ID == u && ID == l) { if (ID == lu) { cellData[0].x = 2; cellData[0].y = 4; } else { cellData[0].x = 4; cellData[0].y = 0; } } else if (ID == u && ID != l) { cellData[0].x = 0; if (ID == d) { cellData[0].y = 4; } else { cellData[0].y = 6; } } else if (ID != u && ID == l) { cellData[0].y = 2; if (ID == r) { cellData[0].x = 2; } else { cellData[0].x = 4; } } else { cellData[0].x = 0; cellData[0].y = 2; } } void Autotile::drawRU(POINT l, POINT r, POINT u, POINT d, POINT ru) { if (ID == u && ID == r) { if (ID == ru) { cellData[1].x = 3; cellData[1].y = 4; } else { cellData[1].x = 5; cellData[1].y = 0; } } else if (ID == u && ID != r) { cellData[1].x = 5; if (ID == d) { cellData[1].y = 4; } else { cellData[1].y = 6; } } else if (ID != u && ID == r) { cellData[1].y = 2; if (ID == l) { cellData[1].x = 3; } else { cellData[1].x = 1; } } else { cellData[1].x = 5; cellData[1].y = 2; } } void Autotile::drawLD(POINT l, POINT r, POINT u, POINT d, POINT ld) { if (ID == d && ID == l) { if (ID == ld) { cellData[2].x = 2; cellData[2].y = 5; } else { cellData[2].x = 4; cellData[2].y = 1; } } else if (ID == d && ID != l) { cellData[2].x = 0; if (ID == u) { cellData[2].y = 5; } else { cellData[2].y = 3; } } else if (ID != d && ID == l) { cellData[2].y = 7; if (ID == r) { cellData[2].x = 2; } else { cellData[2].x = 4; } } else { cellData[2].x = 0; cellData[2].y = 7; } } void Autotile::drawRD(POINT l, POINT r, POINT u, POINT d, POINT rd) { if (ID == d && ID == r) { if (ID == rd) { cellData[3].x = 3; cellData[3].y = 5; } else { cellData[3].x = 5; cellData[3].y = 1; } } else if (ID == d && ID != r) { cellData[3].x = 5; if (ID == u) { cellData[3].y = 5; } else { cellData[3].y = 3; } } else if (ID != d && ID == r) { cellData[3].y = 7; if (ID == l) { cellData[3].x = 3; } else { cellData[3].x = 1; } } else { cellData[3].x = 5; cellData[3].y = 7; } } void Autotile::draw(Graphics & g, int layer, Rect & dest, std::string mapName) { SpriteManager& sm = SpriteManager::getInstance(); POINT drawPoint = { dest.X, dest.Y }; Image* sprite = sm.getAutotileSprite(name); drawPoint = pixelToTile(drawPoint); POINT l = MapManager::getLayerData(mapName, layer, drawPoint + POINT({ -1, 0 })); POINT r = MapManager::getLayerData(mapName, layer, drawPoint + POINT({ 1, 0 })); POINT u = MapManager::getLayerData(mapName, layer, drawPoint + POINT({ 0, -1 })); POINT d = MapManager::getLayerData(mapName, layer, drawPoint + POINT({ 0, 1 })); POINT lu = MapManager::getLayerData(mapName, layer, drawPoint + POINT({ -1, -1 })); POINT ru = MapManager::getLayerData(mapName, layer, drawPoint + POINT({ 1, -1 })); POINT ld = MapManager::getLayerData(mapName, layer, drawPoint + POINT({ -1, 1 })); POINT rd = MapManager::getLayerData(mapName, layer, drawPoint + POINT({ 1, 1 })); Rect luRect = { dest.X, dest.Y, TILE_PIXEL / 2, TILE_PIXEL / 2 }; Rect ruRect = { dest.X + TILE_PIXEL / 2, dest.Y, TILE_PIXEL / 2, TILE_PIXEL / 2 }; Rect ldRect = { dest.X, dest.Y + TILE_PIXEL / 2, TILE_PIXEL / 2, TILE_PIXEL / 2 }; Rect rdRect = { dest.X + TILE_PIXEL / 2,dest.Y + TILE_PIXEL / 2, TILE_PIXEL / 2, TILE_PIXEL / 2 }; drawLU(l, r, u, d, lu); drawRU(l, r, u, d, ru); drawLD(l, r, u, d, ld); drawRD(l, r, u, d, rd); g.DrawImage(sprite, luRect, (TILE_PIXEL / 2)*cellData[0].x, (TILE_PIXEL / 2)*cellData[0].y, TILE_PIXEL / 2, TILE_PIXEL / 2, UnitPixel); g.DrawImage(sprite, ruRect, (TILE_PIXEL / 2)*cellData[1].x, (TILE_PIXEL / 2)*cellData[1].y, TILE_PIXEL / 2, TILE_PIXEL / 2, UnitPixel); g.DrawImage(sprite, ldRect, (TILE_PIXEL / 2)*cellData[2].x, (TILE_PIXEL / 2)*cellData[2].y, TILE_PIXEL / 2, TILE_PIXEL / 2, UnitPixel); g.DrawImage(sprite, rdRect, (TILE_PIXEL / 2)*cellData[3].x, (TILE_PIXEL / 2)*cellData[3].y, TILE_PIXEL / 2, TILE_PIXEL / 2, UnitPixel); }
// // FocusingView.h // iPet // // Created by KimSteve on 2017. 7. 3.. // Copyright © 2017년 KimSteve. All rights reserved. // 화면에 포커싱되는 효과를 주는 view #ifndef FocusingView_h #define FocusingView_h #include "../Base/SMView.h" class ShapeCircle; class ShapeSolidRect; class ShapeArcRing; class OnFocusingListener; class FocusLayer : public SMView { public: static FocusLayer* create(); void startAutoFocus(); void finishAutoFocus(); protected: FocusLayer(); virtual ~FocusLayer(); virtual bool init() override; void setRadius(float radius); float getRadius() {return _radius;} void onFinishUpdate(float t); void onTimeOut(float dt); protected: float _showValue; private: class FocusingAction; class FinishAction; // shape ShapeCircle* _mainRing; ShapeCircle* _subRing; ShapeArcRing* _arcRing; ShapeSolidRect* _crosshairV; ShapeSolidRect* _crosshairH; float _radius; FinishAction* _finishAction; }; class FocusingView : public SMView { public: static FocusingView * create(OnFocusingListener* l); void setFocusLayer(float x, float y, float scale, bool isMirror, const cocos2d::Size& size);; void setEnableFocus(bool enabled); protected: FocusingView(); virtual ~FocusingView(); bool initWithListener(OnFocusingListener* l); virtual void performClick(const cocos2d::Vec2& worldPoint) override; private: float _baseScale; bool _isMirror; FocusLayer * _focusLayer; OnFocusingListener * _listener; }; #endif /* FocusingView_h */
#include <bits/stdc++.h> using namespace std; int pai[1001]; int posto[1001]; int find(int x){ if(pai[x] != x) pai[x] = find(pai[x]); return pai[x]; } void unio(int a, int b){ a = find(a); b = find(b); if(a == b) return; if(posto[a] >= posto[b]){ pai[b] = a; if(posto[a] == posto[b]) posto[a]++; }else{ pai[a] = b; } return; } int main() { int qnt, inf; cin >> qnt >> inf; char letra; int vetor[qnt+1]; memset(vetor, -1, sizeof (vetor)); for(int i = 0; i<=qnt; i++) pai[i] = i; int p, q; for(int i = 0; i < inf; i++){ cin >> letra; cin >> p >> q; if(letra == 'F'){ unio(p,q); }else{ if(vetor[p] != -1){ unio(q,vetor[p]); } if(vetor[q] != -1){ unio(p,vetor[q]); } vetor[p] = q; vetor[q] = p; } } set<int> Set; for(int i = 1; i <= qnt; i++){ Set.insert(find(i)); } cout << Set.size() << endl; return 0; }
/************************************************************************ created: Tue Feb 28 2006 author: Paul D Turner <paul@cegui.org.uk> *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2014 Paul D Turner & The CEGUI Development Team * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. ***************************************************************************/ #ifndef _CEGUIFreeFunctionSlot_h_ #define _CEGUIFreeFunctionSlot_h_ #include "CEGUI/SlotFunctorBase.h" #include "CEGUI/EventArgs.h" // Start of CEGUI namespace section namespace CEGUI { /*! \brief Slot functor class that calls back via a free function pointer. */ class FreeFunctionSlot : public SlotFunctorBase<EventArgs> { public: //! Slot function type. typedef bool (SlotFunction)(const EventArgs&); FreeFunctionSlot(SlotFunction* func) : d_function(func) {} bool operator()(const EventArgs& args) override { return d_function(args); } private: SlotFunction* d_function; }; /*! \brief Slot functor class that calls back via a free function pointer. This variant doesn't require a handler that returns bool. \note This functor always returns true to CEGUI, which means the event was handled. */ class FreeFunctionSlotVoid : public SlotFunctorBase<EventArgs> { public: //! Slot function type. typedef void (SlotFunction)(const EventArgs&); FreeFunctionSlotVoid(SlotFunction* func) : d_function(func) {} bool operator()(const EventArgs& args) override { d_function(args); return true; } private: SlotFunction* d_function; }; /*! \brief Slot functor class that calls back via a free function pointer. This variant ignores passed EventArgs. */ class FreeFunctionSlotNoArgs : public SlotFunctorBase<EventArgs> { public: //! Slot function type. typedef bool (SlotFunction)(); FreeFunctionSlotNoArgs(SlotFunction* func) : d_function(func) {} bool operator()(const EventArgs& /*args*/) override { return d_function(); } private: SlotFunction* d_function; }; /*! \brief Slot functor class that calls back via a free function pointer. This variant ignores passed EventArgs and the handler doesn't have to return a bool. \note This functor always returns true to CEGUI, which means the event was handled. */ class FreeFunctionSlotVoidNoArgs : public SlotFunctorBase<EventArgs> { public: //! Slot function type. typedef void (SlotFunction)(); FreeFunctionSlotVoidNoArgs(SlotFunction* func) : d_function(func) {} bool operator()(const EventArgs&) override { d_function(); return true; } private: SlotFunction* d_function; }; } // End of CEGUI namespace section #endif // end of guard _CEGUIFreeFunctionSlot_h_
#include <stdio.h> #include <list> #include <string> using namespace std; list<int> li; int T, Q; int main() { freopen("input.txt", "r", stdin); scanf("%d", &T); while(T--){ li.clear(); scanf("%d", &Q); while (Q--) { char input[10]; int combination[101]; scanf("%s", input); string tmp(input); if (tmp == "insert") { int x; scanf("%d", &x); if (li.size() > 0) { auto it = lower_bound(li.begin(), li.end(), x); if(it==li.end()) li.insert(it, x); else { if (*it != x) li.insert(it, x); } } else li.insert(li.begin(), x); } if (tmp == "erase") { int x; scanf("%d", &x); auto it = lower_bound(li.begin(), li.end(), x); if (it != li.end()) { if (*it == x) li.erase(it); } } if (tmp == "update") { int x, y; scanf("%d %d", &x, &y); auto it2 = lower_bound(li.begin(), li.end(), y); if (it2 == li.end()) { auto it1 = lower_bound(li.begin(), li.end(), x); if (it1 != li.end()) { it1=li.erase(it1); auto it3=lower_bound(li.begin(), li.end(), y); li.insert(it3, y); } } } if (tmp == "front") { if (li.size() == 0) { printf("empty\n"); continue; } int c; scanf("%d\n", &c); int pos; if (c > li.size()) pos = li.size(); else pos = c; auto it = next(li.begin(), (pos-1)); printf("%d\n", *it); } if (tmp == "back") { if (li.size() == 0) { printf("empty\n"); continue; } int c; scanf("%d\n", &c); int pos; if (c > li.size()) pos = li.size(); else pos = c; auto it = prev((li.end()), pos); printf("%d\n", *it); } } } return 0; }
#include "dvdtypes.h" char DVDTypeToCode(DVDType type) { switch(type) { case ComedyDVD: { return 'F'; } case DramaDVD: { return 'D'; } case ClassicDVD: { return 'C'; } default: { return 0; } } } DVDType codeToDVDType(char code) { switch(code) { case 'F': { return ComedyDVD; } case 'D': { return DramaDVD; } case 'C': { return ClassicDVD; } default: { return None; } } } std::string intToDVDType(int code) { switch(code) { case 0: { return "DVD Comedy "; } case 1: { return "DVD Drama "; } case 2: { return "DVD Classic"; } default: { return "None"; } } }
#include <ESP8266WiFi.h> #include <ESP8266HTTPClient.h> const char* wifissid = "IU13-Conference Center"; const char* wifipass = ""; String url = "http://wp-of-things.pw/wp-json/wp/v2/posts/?per_page=1"; void setup() { Serial.begin( 74880 ); Serial.println(); Serial.println(); Serial.printf( "Connecting to %s ", wifissid ); WiFi.begin( wifissid, wifipass ); while ( WiFi.status() != WL_CONNECTED ) { delay( 500 ); Serial.print( "." ); } Serial.println(); Serial.println( "WiFi connected" ); Serial.print( "IP address: " ); Serial.println( WiFi.localIP() ); } void loop() { HTTPClient http; http.begin( url ); int httpCode = http.GET(); if ( httpCode != HTTP_CODE_OK ) { Serial.printf( "[HTTP] GET... failed, error %d: %s\n", httpCode, http.errorToString( httpCode ).c_str() ); String payload = http.getString(); Serial.println( payload ); delay( 5000 ); return; } String payload = http.getString(); int start = payload.indexOf( "\"date\":\"" ) + 8; String date = payload.substring( start ); date = date.substring( 0, date.indexOf( '"' ) ); start = payload.indexOf( "\"title\":{\"rendered\":\"" ) + 21; String title = payload.substring( start ); title = title.substring( 0, title.indexOf( '"' ) ); Serial.println( "Most recent post (" + title + ") was published on " + date ); delay( 5000 ); }
#ifndef GLOBALS_H #define GLOBALS_H namespace globals { const float SCREEN_WIDTH = 640; const float SCREEN_HEIGHT = 480; const float SPRITE_SCALE = 2.0f; } namespace sides { enum Side { TOP, BOTTOM, LEFT, RIGHT, NONE }; inline Side getOppositeSide(Side side) { return side == TOP ? BOTTOM : side == BOTTOM ? TOP : side == LEFT ? RIGHT : side == RIGHT ? LEFT : NONE; } } enum Direction { LEFT, RIGHT, UP, DOWN, INSIDE }; enum Surface { NOTHING, RECTANGLE, SLOPE }; struct Vector2 { void setX(float x) { this->x = x; }; void setY(float y) { this->y = y; }; float getX() { return x; }; float getY() { return y; }; float x, y; Vector2() : x(0), y(0) {} Vector2(float x, float y) : x(x), y(y) {} Vector2 zero() { return Vector2(0, 0); } }; #endif
#include <cstdio> int main() { int n = 0; typedef struct{ char name[15]; char no[15]; int score; } Student; // BETTER: 设计一个最外边界就不需要init判断了 int max = -1, maxId = 0, min = 101, minId = 0; scanf("%d", &n); Student stu[n]; for(int i = 0; i < n; i++) { scanf("%s %s %d", stu[i].name, stu[i].no, &stu[i].score); if(max < stu[i].score) { max = stu[i].score; maxId = i; } if(min > stu[i].score) { min = stu[i].score; minId = i; } } printf("%s %s\n", stu[maxId].name, stu[maxId].no); printf("%s %s", stu[minId].name, stu[minId].no); return 0; }
#include <bits/stdc++.h> using namespace std; using ll = long long; using vi = vector<int>; #define pb push_back #define all(x) x.begin(), x.end() #define rep(i, a, b) for(ll i = a; i < b; ++i) #define rsz(x, n) x.resize(n) using pi = pair<int, int>; #define f first #define s second void setIO(string name = "cowcode") { ios_base::sync_with_stdio(0); cin.tie(0); if (name.size()) { freopen((name + ".in").c_str(), "r", stdin); freopen((name + ".out").c_str(), "w", stdout); } } string str; ll n; ll sz; ll a; ll cnt = 0; char find(ll x) { if (x <= sz) return str[x - 1]; ll b = sz; while (b * 2 < x) b *= 2; ll diff = x - b; --diff; if (diff == 0) diff = b; return find(diff); } int main() { setIO(); cin >> str >> n; sz = str.size(); a = n / sz; while (a != 0) { ++cnt; a /= 2; } cout << find(n); }
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> #include <QFileDialog> #include <QMessageBox> #include "family.h" #include "about.h" #include "help.h" QT_BEGIN_NAMESPACE namespace Ui { class MainWindow; } QT_END_NAMESPACE class MainWindow : public QMainWindow { Q_OBJECT public: MainWindow(QWidget *parent = nullptr); ~MainWindow(); Family *fml; about *abt; help *hlp; bool can = false; bool from_file = false; private slots: void on_resultButtom_clicked(); void on_Input_textChanged(); void on_actionOpen_file_triggered(); void on_actionHelp_triggered(); void on_actionAbout_triggered(); void on_actionExit_triggered(); private: Ui::MainWindow *ui; }; #endif // MAINWINDOW_H
#include "service.hpp" bool service::RegisterAndStart(const std::wstring& driver_path) { const static DWORD ServiceTypeKernel = 1; const std::wstring driver_name = intel_driver::GetDriverNameW(); const std::wstring servicesPath = L"SYSTEM\\CurrentControlSet\\Services\\" + driver_name; const std::wstring nPath = L"\\??\\" + driver_path; HKEY dservice; LSTATUS status = RegCreateKeyW(HKEY_LOCAL_MACHINE, servicesPath.c_str(), &dservice); //Returns Ok if already exists if (status != ERROR_SUCCESS) { Log("[-] Can't create service key" << std::endl); return false; } status = RegSetKeyValueW(dservice, NULL, L"ImagePath", REG_EXPAND_SZ, nPath.c_str(), (DWORD)(nPath.size()*sizeof(wchar_t))); if (status != ERROR_SUCCESS) { RegCloseKey(dservice); Log("[-] Can't create 'ImagePath' registry value" << std::endl); return false; } status = RegSetKeyValueW(dservice, NULL, L"Type", REG_DWORD, &ServiceTypeKernel, sizeof(DWORD)); if (status != ERROR_SUCCESS) { RegCloseKey(dservice); Log("[-] Can't create 'Type' registry value" << std::endl); return false; } RegCloseKey(dservice); HMODULE ntdll = GetModuleHandleA("ntdll.dll"); if (ntdll == NULL) { return false; } auto RtlAdjustPrivilege = (nt::RtlAdjustPrivilege)GetProcAddress(ntdll, "RtlAdjustPrivilege"); auto NtLoadDriver = (nt::NtLoadDriver)GetProcAddress(ntdll, "NtLoadDriver"); ULONG SE_LOAD_DRIVER_PRIVILEGE = 10UL; BOOLEAN SeLoadDriverWasEnabled; NTSTATUS Status = RtlAdjustPrivilege(SE_LOAD_DRIVER_PRIVILEGE, TRUE, FALSE, &SeLoadDriverWasEnabled); if (!NT_SUCCESS(Status)) { Log("Fatal error: failed to acquire SE_LOAD_DRIVER_PRIVILEGE. Make sure you are running as administrator." << std::endl); return false; } std::wstring wdriver_reg_path = L"\\Registry\\Machine\\System\\CurrentControlSet\\Services\\" + driver_name; UNICODE_STRING serviceStr; RtlInitUnicodeString(&serviceStr, wdriver_reg_path.c_str()); Status = NtLoadDriver(&serviceStr); Log("[+] NtLoadDriver Status 0x" << std::hex << Status << std::endl); //Never should occur since kdmapper checks for "IsRunning" driver before if (Status == 0xC000010E) {// STATUS_IMAGE_ALREADY_LOADED return true; } return NT_SUCCESS(Status); } bool service::StopAndRemove(const std::wstring& driver_name) { HMODULE ntdll = GetModuleHandleA("ntdll.dll"); if (ntdll == NULL) return false; std::wstring wdriver_reg_path = L"\\Registry\\Machine\\System\\CurrentControlSet\\Services\\" + driver_name; UNICODE_STRING serviceStr; RtlInitUnicodeString(&serviceStr, wdriver_reg_path.c_str()); HKEY driver_service; std::wstring servicesPath = L"SYSTEM\\CurrentControlSet\\Services\\" + driver_name; LSTATUS status = RegOpenKeyW(HKEY_LOCAL_MACHINE, servicesPath.c_str(), &driver_service); if (status != ERROR_SUCCESS) { if (status == ERROR_FILE_NOT_FOUND) { return true; } return false; } RegCloseKey(driver_service); auto NtUnloadDriver = (nt::NtUnloadDriver)GetProcAddress(ntdll, "NtUnloadDriver"); NTSTATUS st = NtUnloadDriver(&serviceStr); Log("[+] NtUnloadDriver Status 0x" << std::hex << st << std::endl); if (st != 0x0) { Log("[-] Driver Unload Failed!!" << std::endl); status = RegDeleteKeyW(HKEY_LOCAL_MACHINE, servicesPath.c_str()); return false; //lets consider unload fail as error because can cause problems with anti cheats later } status = RegDeleteKeyW(HKEY_LOCAL_MACHINE, servicesPath.c_str()); if (status != ERROR_SUCCESS) { return false; } return true; }
// This file has been generated by Py++. #ifndef FalagardPropertyBaseVerticalTextFormatting_hpp__pyplusplus_wrapper #define FalagardPropertyBaseVerticalTextFormatting_hpp__pyplusplus_wrapper void register_FalagardPropertyBaseVerticalTextFormatting_class(); #endif//FalagardPropertyBaseVerticalTextFormatting_hpp__pyplusplus_wrapper
#include "../headers/director.h" #include <exception> #include <iostream> double director::dir_base_bonus_salary = 400; double director::dir_bonus_bonus_salary = 1.5; // da aggiungere al bonus di base del contratto full time int director::dir_bonus_vac_day = 1; director::director(): worker(), level1() {} director::director(std::string n, std::string sn, std::string cf): worker(n, sn, cf), level1() {} director::director(std::string n, std::string sn, std::string cf, int wd, int wh, double base, double bonus, double salary, int sen, int hol): worker(n,sn,cf,wd,wh,base,bonus,salary,sen,hol), level1() {} director::director(const worker& w): worker(w), level1() {} double director::getBaseBonusSalary() const { return this->dir_base_bonus_salary; } double director::getBonusBonusSalary() const { return this->dir_bonus_bonus_salary; } int director::getBonusVacDay() const { return this->dir_bonus_vac_day; } double director::calcBaseSal() const { double basesal = worker::getLastMonthWorkedDays() * level1::getWorkHours() * level1::getSalary(); return basesal + dir_base_bonus_salary; } double director::calcBonus() const { double bonussal = (worker::getLastMonthWorkedHours() - (worker::getLastMonthWorkedDays() * level1::getWorkHours())) * (level1::getSalary()+level1::getSalaryBonus()+dir_bonus_bonus_salary); if (bonussal < 0){ throw std::domain_error("Something went wrong! The data you inserted is not coherent"); } return bonussal; } void director::updateVacAcc() { setVacAcc(level1::getVacPerMonth() + dir_bonus_vac_day); } double director::calcFullSal(const int& wd, const int& wh) { updateWorkData(wd, wh); updateVacAcc(); updateSeniority(); this->setLastMonthBaseSalary(calcBaseSal()); this->setLastMonthBonusSalary(calcBonus()); setLastMonthSalary(this->getLastMonthBaseSalary() + this->getLastMonthBonusSalary()); return getLastMonthSalary(); }
#include <Snow/Application.h> #include <Snow/GUI/GUI.h> #include <Snow/Graphics/Renderer.h> #include <Snow/Input/Input.h> #include <Snow/Core/Time.h> #include "Resources.h" namespace Snow { Application::Application() { window = std::make_unique<Snow::Impl::Window>(); window->on_window_closed([=]() { try { exit.dispatch(); } catch (std::exception &exception) { SNOW_CORE_ERROR(exception.what()); } catch (const char *exception) { SNOW_CORE_ERROR(exception); } this->is_running = false; }); GUI::init(window.get()); Input::set_window(window.get()); auto camera_entity = registry.create(); auto camera = CameraComponent(); registry.emplace<CameraComponent>(camera_entity, camera); registry.emplace<TransformComponent>(camera_entity); sprite_renderer_system = new SpriteRendererSystem(registry); } void Application::run() { while (is_running) { auto time = (float)glfwGetTime(); Time::deltaTime = time - Time::time; Time::time = time; window->update(); update(); CameraSystem::update(registry); sprite_renderer_system->update(registry); GUI::update(); Renderer::swap_buffers(window.get()); } } Application::~Application() { delete sprite_renderer_system; Resources::cleanup(); GUI::shutdown(); } }
#ifndef _chnkload_hpp #define _chnkload_hpp 1 #include "chnkload.h" #ifdef __cplusplus #include "chunk.hpp" #include "shpchunk.hpp" #include "obchunk.hpp" #include "bmpnames.hpp" #include "projload.hpp" #if 0 extern BOOL copy_to_mainshpl (Shape_Chunk *shape, int list_pos); extern BOOL copy_to_mainshpl (Shape_Sub_Shape_Chunk *shape, int list_pos); #endif extern void copy_to_module (Object_Chunk * ob, int mod_pos, int shplst_pos); extern BOOL copy_to_shapeheader ( RIFFHANDLE, ChunkShape const & cshp, SHAPEHEADER *& shphd, Chunk_With_Children * shape, int flags, int local_max_index, int * local_tex_index_nos, int listpos = GLS_NOTINLIST, const ChunkObject* object=0 //object used so that conversion from float to int can be done in world coordinates ); extern BOOL copy_preprocessed_to_shapeheader ( RIFFHANDLE, Shape_Preprocessed_Data_Chunk*, SHAPEHEADER *& shphd, Chunk_With_Children * shape, int flags, int local_max_index, int * local_tex_index_nos, int listpos = GLS_NOTINLIST, const ChunkObject* object=0 //object used so that conversion from float to int can be done in world coordinates ); extern BOOL copy_sprite_to_shapeheader (RIFFHANDLE, SHAPEHEADER *& shphd,Sprite_Header_Chunk* shc, int listpos = GLS_NOTINLIST); extern BOOL copy_to_map6(Object_Chunk *,MAPBLOCK6*, int shplst_pos); extern void merge_polygons_in_chunkshape (ChunkShape & shp, Shape_Merge_Data_Chunk * smdc); extern File_Chunk * Env_Chunk; extern double local_scale; // copies shape to msl #if SupportMorphing && LOAD_MORPH_SHAPES typedef struct { int start_list_pos; int main_list_pos; MORPHCTRL * mc; } CTM_ReturnType; #else typedef int CTM_ReturnType; #endif CTM_ReturnType copy_to_mainshapelist(RIFFHANDLE, Shape_Chunk *, int flags,const ChunkObject* object=0); #define CopyToMainshapelist(h,r,p,f) copy_to_mainshapelist(h,r,p,f) // copies sprite to msl int copy_sprite_to_mainshapelist(RIFFHANDLE, Sprite_Header_Chunk *, int flags); #define CopySpriteToMainshapelist(h,p,f) copy_sprite_to_mainshapelist(h,p,f) // hook to load a bitmap - so you can load them from test directories, etc. should return tex index extern int load_rif_bitmap (char const * fname, BMPN_Flags flags); #define LoadRIFBitmap(s,f) load_rif_bitmap(s,f) // project specific shape pre processing - usually merge polys extern void pre_process_shape (RIFFHANDLE, ChunkShape &, Chunk_With_Children * shape_chunk, int flags); #define PreProcessShape(h,r,p,f) pre_process_shape(h,r,p,f) struct _RifHandle : Project_RifHandle { File_Chunk * fc; Environment_Data_Chunk * envd; Chunk_With_Children * palparent; List<int> shape_nums; int max_index; int * tex_index_nos; ~_RifHandle() {} _RifHandle() : fc(0) , envd(0) , max_index(0) , tex_index_nos(0) , palparent(0) {} }; #endif #endif
#ifndef PERSONPAGE_H #define PERSONPAGE_H #include <QMainWindow> #include <QDialog> namespace Ui { class personpage; } class personpage : public QMainWindow { Q_OBJECT public: explicit personpage(QWidget *parent = 0); ~personpage(); void init(); QString pgname; private slots: void on_pushButton_mycon_clicked(); private: Ui::personpage *ui; }; #endif // PERSONPAGE_H
#ifndef VERTEXBUFFER_H #define VERTEXBUFFER_H #include <GxGraphics/GxGraphicsResource.h> #include <GxGraphics/GxVertexBuffer.h> #include <pcx/buffer.h> #include <pcx/datastream.h> class VertexBuffer : public Gx::GraphicsResource { public: VertexBuffer(); VertexBuffer(Gx::GraphicsDevice &device, unsigned bytes, Gx::Graphics::Usage::Flags usage, Gx::Graphics::Pool pool); VertexBuffer(Gx::GraphicsDevice &device, const pcx::buffer &buffer, Gx::Graphics::Usage::Flags usage, Gx::Graphics::Pool pool); VertexBuffer(Gx::GraphicsDevice &device, pcx::data_istream &ds, Gx::Graphics::Usage::Flags usage, Gx::Graphics::Pool pool); virtual void reset(Gx::GraphicsDevice &device) override; virtual void release() override; virtual bool isDeviceBound() const override; unsigned size() const; unsigned capacity() const; void renderTriangleList(Gx::GraphicsDevice &device, unsigned stride) const; void renderLineList(Gx::GraphicsDevice &device, unsigned stride) const; void renderPointList(Gx::GraphicsDevice &device, unsigned stride) const; private: friend class VertexStream; Gx::VertexBuffer vb; unsigned n; }; #endif // VERTEXBUFFER_H
#ifndef FASTCG_VULKAN_BUFFER_H #define FASTCG_VULKAN_BUFFER_H #ifdef FASTCG_VULKAN #include <FastCG/Graphics/Vulkan/Vulkan.h> #include <FastCG/Graphics/BaseBuffer.h> namespace FastCG { class VulkanGraphicsContext; class VulkanGraphicsSystem; class VulkanBuffer : public BaseBuffer { public: VulkanBuffer(const BufferArgs &rArgs); VulkanBuffer(const VulkanBuffer &rOther) = delete; VulkanBuffer(const VulkanBuffer &&rOther) = delete; virtual ~VulkanBuffer(); VulkanBuffer &operator=(const VulkanBuffer &rOther) = delete; private: VkBuffer mBuffer{VK_NULL_HANDLE}; VmaAllocation mAllocation{VK_NULL_HANDLE}; VmaAllocationInfo mAllocationInfo; inline VkBuffer GetBuffer() const { return mBuffer; } inline VmaAllocation GetAllocation() const { return mAllocation; } inline VmaAllocationInfo GetAllocationInfo() const { return mAllocationInfo; } inline VkAccessFlags GetDefaultAccessFlags() const { return GetVkBufferAccessFlags(GetUsage()); } inline VkPipelineStageFlags GetDefaultStageFlags() const { return GetVkBufferPipelineStageFlags(GetUsage()); } void CreateBuffer(); void DestroyBuffer(); friend class VulkanGraphicsContext; friend class VulkanGraphicsSystem; }; } #endif #endif
// This file has been generated by Py++. #include "boost/python.hpp" #include "generators/include/python_CEGUI.h" #include "ImageCodec.pypp.hpp" namespace bp = boost::python; struct ImageCodec_wrapper : CEGUI::ImageCodec, bp::wrapper< CEGUI::ImageCodec > { ImageCodec_wrapper(::CEGUI::String const & name ) : CEGUI::ImageCodec( boost::ref(name) ) , bp::wrapper< CEGUI::ImageCodec >(){ // constructor } virtual ::CEGUI::Texture * load( ::CEGUI::RawDataContainer const & data, ::CEGUI::Texture * result ){ bp::override func_load = this->get_override( "load" ); return func_load( boost::ref(data), boost::python::ptr(result) ); } }; void register_ImageCodec_class(){ { //::CEGUI::ImageCodec typedef bp::class_< ImageCodec_wrapper, boost::noncopyable > ImageCodec_exposer_t; ImageCodec_exposer_t ImageCodec_exposer = ImageCodec_exposer_t( "ImageCodec", bp::no_init ); bp::scope ImageCodec_scope( ImageCodec_exposer ); ImageCodec_exposer.def( bp::init< CEGUI::String const & >(( bp::arg("name") ), "*\n\ \n\ Constructor \n\ \n\ @param name of the codec \n\ *\n") ); { //::CEGUI::ImageCodec::getIdentifierString typedef ::CEGUI::String const & ( ::CEGUI::ImageCodec::*getIdentifierString_function_type )( ) const; ImageCodec_exposer.def( "getIdentifierString" , getIdentifierString_function_type( &::CEGUI::ImageCodec::getIdentifierString ) , bp::return_value_policy< bp::copy_const_reference >() , "*!\n\ \n\ Return the name of the image codec object \n\ \n\ Return the name of the image codec \n\ \n\ @return a string containing image codec name \n\ *\n" ); } { //::CEGUI::ImageCodec::getSupportedFormat typedef ::CEGUI::String const & ( ::CEGUI::ImageCodec::*getSupportedFormat_function_type )( ) const; ImageCodec_exposer.def( "getSupportedFormat" , getSupportedFormat_function_type( &::CEGUI::ImageCodec::getSupportedFormat ) , bp::return_value_policy< bp::copy_const_reference >() , "*! \n\ \n\ Return the list of image file format supported \n\ \n\ Return a list of space separated image format supported by this\n\ codec\n\ \n\ @return \n\ list of supported image file format separated with space \n\ *\n" ); } { //::CEGUI::ImageCodec::load typedef ::CEGUI::Texture * ( ::CEGUI::ImageCodec::*load_function_type )( ::CEGUI::RawDataContainer const &,::CEGUI::Texture * ) ; ImageCodec_exposer.def( "load" , bp::pure_virtual( load_function_type(&::CEGUI::ImageCodec::load) ) , ( bp::arg("data"), bp::arg("result") ) , bp::return_value_policy< bp::reference_existing_object >() , "*!\n\ \n\ Load an image from a memory buffer \n\ \n\ @param data the image data \n\ \n\ @param result the texture to use for storing the image data \n\ \n\ @return result on success or 0 if the load failed \n\ *\n" ); } } }
// Copyright (C) 2017 Elviss Strazdins // This file is part of the Ouzel engine. #include "SoundResource.h" #include "SoundData.h" #include "Stream.h" namespace ouzel { namespace audio { SoundResource::SoundResource() { } SoundResource::~SoundResource() { } bool SoundResource::init(const std::shared_ptr<SoundData>& newSoundData, bool newRelativePosition) { std::lock_guard<std::mutex> lock(uploadMutex); soundData = newSoundData; relativePosition = newRelativePosition; if (soundData) { stream = soundData->createStream(); } dirty |= DIRTY_SOUND_DATA | DIRTY_POSITION | DIRTY_PITCH | DIRTY_GAIN | DIRTY_PLAY_STATE; return true; } void SoundResource::setPosition(const Vector3& newPosition) { std::lock_guard<std::mutex> lock(uploadMutex); position = newPosition; dirty |= DIRTY_POSITION; } void SoundResource::setPitch(float newPitch) { std::lock_guard<std::mutex> lock(uploadMutex); pitch = newPitch; dirty |= DIRTY_PITCH; } void SoundResource::setGain(float newGain) { std::lock_guard<std::mutex> lock(uploadMutex); gain = newGain; dirty |= DIRTY_GAIN; } bool SoundResource::play(bool repeatSound) { std::lock_guard<std::mutex> lock(uploadMutex); shouldPlay = true; repeat = repeatSound; dirty |= DIRTY_PLAY_STATE; return true; } bool SoundResource::pause() { std::lock_guard<std::mutex> lock(uploadMutex); shouldPlay = false; dirty |= DIRTY_PLAY_STATE; return true; } bool SoundResource::stop() { std::lock_guard<std::mutex> lock(uploadMutex); shouldPlay = false; reset = true; dirty |= DIRTY_PLAY_STATE; return true; } std::vector<uint8_t> SoundResource::getData(uint32_t size, uint16_t channels, uint32_t samplesPerSecond) { std::lock_guard<std::mutex> lock(uploadMutex); std::vector<uint8_t> result; if (channels == 0 || soundData->getChannels() == 0) { return result; } if (!shouldPlay) { result = std::vector<uint8_t>(); } else if (soundData && stream) { std::vector<uint8_t> data = soundData->getData(stream.get(), (size / channels) * soundData->getChannels()); if (channels == soundData->getChannels() && samplesPerSecond == soundData->getSamplesPerSecond()) { result = std::move(data); } else { result.resize(size); if (channels != soundData->getChannels()) { uint32_t dstSamples = size / sizeof(int16_t); uint32_t srcSamples = static_cast<uint32_t>(data.size()) / sizeof(int16_t); // front left channel if (channels >= 1) { int16_t* dstBuffer = reinterpret_cast<int16_t*>(result.data()); if (soundData->getChannels() >= 1) { int16_t* srcBuffer = reinterpret_cast<int16_t*>(data.data()); for (uint32_t i = 0; i < dstSamples / channels && i < srcSamples / soundData->getChannels(); ++i) { *dstBuffer = *srcBuffer; dstBuffer += channels; srcBuffer += soundData->getChannels(); } } else { // fill the front left channel with zeros for (uint32_t i = 0; i < dstSamples / channels && i < srcSamples / soundData->getChannels(); ++i) { *dstBuffer = 0; dstBuffer += channels; } } } // front right channel if (channels >= 2) { int16_t* dstBuffer = reinterpret_cast<int16_t*>(result.data()); // sound data has front right channel if (soundData->getChannels() >= 2) { int16_t* srcBuffer = reinterpret_cast<int16_t*>(data.data()); for (uint32_t i = 0; i < dstSamples / channels && i < srcSamples / soundData->getChannels(); ++i) { *(dstBuffer + 1) = *(srcBuffer + 1); dstBuffer += channels; srcBuffer += soundData->getChannels(); } } else { // copy the front left channel in to the front right one for (uint32_t i = 0; i < dstSamples / channels && i < srcSamples / soundData->getChannels(); ++i) { *(dstBuffer + 1) = *dstBuffer; dstBuffer += channels; } } } // center channel if (channels >= 3) { int16_t* dstBuffer = reinterpret_cast<int16_t*>(result.data()); if (soundData->getChannels() >= 3) { int16_t* srcBuffer = reinterpret_cast<int16_t*>(data.data()); for (uint32_t i = 0; i < dstSamples / channels && i < srcSamples / soundData->getChannels(); ++i) { *(dstBuffer + 2) = *(srcBuffer + 2); dstBuffer += channels; srcBuffer += soundData->getChannels(); } } else if (channels >= 2) { // calculate the average of the front left and the front right channel for (uint32_t i = 0; i < dstSamples / channels && i < srcSamples / soundData->getChannels(); ++i) { *(dstBuffer + 2) = (*dstBuffer + *(dstBuffer + 1)) / 2; dstBuffer += channels; } } else { // copy the front left channel in to the center one for (uint32_t i = 0; i < dstSamples / channels && i < srcSamples / soundData->getChannels(); ++i) { *(dstBuffer + 2) = *dstBuffer; dstBuffer += channels; } } } // LFE channel if (channels >= 4) { int16_t* dstBuffer = reinterpret_cast<int16_t*>(result.data()); if (soundData->getChannels() >= 4) { int16_t* srcBuffer = reinterpret_cast<int16_t*>(data.data()); for (uint32_t i = 0; i < dstSamples / channels && i < srcSamples / soundData->getChannels(); ++i) { *(dstBuffer + 3) = *(srcBuffer + 3); dstBuffer += channels; srcBuffer += soundData->getChannels(); } } else { // fill the LFE channel with zeros for (uint32_t i = 0; i < dstSamples / channels && i < srcSamples / soundData->getChannels(); ++i) { *(dstBuffer + 3) = 0; dstBuffer += channels; } } } // back left channel if (channels >= 5) { int16_t* dstBuffer = reinterpret_cast<int16_t*>(result.data()); // sound data has back left channel if (soundData->getChannels() >= 5) { int16_t* srcBuffer = reinterpret_cast<int16_t*>(data.data()); for (uint32_t i = 0; i < dstSamples / channels && i < srcSamples / soundData->getChannels(); ++i) { *(dstBuffer + 4) = *(srcBuffer + 4); dstBuffer += channels; srcBuffer += soundData->getChannels(); } } else { // copy the front left channel in to the back left one for (uint32_t i = 0; i < dstSamples / channels && i < srcSamples / soundData->getChannels(); ++i) { *(dstBuffer + 4) = *dstBuffer; dstBuffer += channels; } } } // back right channel if (channels >= 6) { int16_t* dstBuffer = reinterpret_cast<int16_t*>(result.data()); // sound data has back right channel if (soundData->getChannels() >= 6) { int16_t* srcBuffer = reinterpret_cast<int16_t*>(data.data()); for (uint32_t i = 0; i < dstSamples / channels && i < srcSamples / soundData->getChannels(); ++i) { *(dstBuffer + 5) = *(srcBuffer + 5); dstBuffer += channels; srcBuffer += soundData->getChannels(); } } else { // copy the front right channel in to the back right one for (uint32_t i = 0; i < dstSamples / channels && i < srcSamples / soundData->getChannels(); ++i) { *(dstBuffer + 5) = *(dstBuffer + 1); dstBuffer += channels; } } } } else { result = std::move(data); } if (samplesPerSecond != soundData->getSamplesPerSecond()) { // TODO: resample } std::vector<float> channelVolume(channels, gain); uint32_t samples = static_cast<uint32_t>(result.size()) / sizeof(int16_t); int16_t* buffer = reinterpret_cast<int16_t*>(result.data()); for (uint32_t i = 0; i < samples / channels; ++i) { for (uint32_t channel = 0; channel < channels; ++channel) { *buffer = static_cast<int16_t>(*buffer * channelVolume[channel]); ++buffer; } } } } return result; } } // namespace audio } // namespace ouzel
#include "RobTest.h" #include "../EngineLayer/PeptideSpectralMatch.h" #include "../EngineLayer/CommonParameters.h" #include "../EngineLayer/Ms2ScanWithSpecificMass.h" #include "../EngineLayer/ProteinParsimony/ProteinParsimonyEngine.h" #include "../EngineLayer/ProteinParsimony/ProteinParsimonyResults.h" #include "../EngineLayer/ProteinScoringAndFdr/ProteinScoringAndFdrEngine.h" #include "../EngineLayer/ProteinScoringAndFdr/ProteinScoringAndFdrResults.h" #include "../EngineLayer/ProteinParsimony/ProteinGroup.h" using namespace Chemistry; using namespace EngineLayer; using namespace MassSpectrometry; using namespace MzLibUtil; using namespace NUnit::Framework; using namespace Proteomics; using namespace Proteomics::Fragmentation; using namespace Proteomics::ProteolyticDigestion; namespace Test { void RobTest::TestParsimony() { // creates some proteins to test parsimony with std::vector<std::wstring> proteinSequences = {L"AB--------", L"--C-------", L"---D---HHH--", L"-B-D---HHH--", L"-B--E-----", L"----EFG---", L"-----F----", L"--------I-", L"-B------I-", L"----EFG--J"}; auto proteins = std::vector<Protein*>(); for (int i = 0; i < proteinSequences.size(); i++) { Protein tempVar(proteinSequences[i], std::to_wstring(i + 1)); proteins.push_back(&tempVar); } Protein tempVar2(L"-----F----*", L"D1", isDecoy: true); proteins.push_back(&tempVar2); Protein tempVar3(L"-----F----**", L"C1", isContaminant: true); proteins.push_back(&tempVar3); Protein tempVar4(L"----E----**", L"C2", isContaminant: true); proteins.push_back(&tempVar4); // create the protease std::vector<DigestionMotif*> digestionMotifs = { new DigestionMotif(L"A", nullptr, 1, nullptr), new DigestionMotif(L"B", nullptr, 1, nullptr), new DigestionMotif(L"C", nullptr, 1, nullptr), new DigestionMotif(L"D", nullptr, 1, nullptr), new DigestionMotif(L"E", nullptr, 1, nullptr), new DigestionMotif(L"F", nullptr, 1, nullptr), new DigestionMotif(L"G", nullptr, 1, nullptr), new DigestionMotif(L"H", nullptr, 1, nullptr), new DigestionMotif(L"I", nullptr, 1, nullptr), new DigestionMotif(L"J", nullptr, 1, nullptr), new DigestionMotif(L"-", nullptr, 1, nullptr) }; auto protease = new Protease(L"test", CleavageSpecificity::Full, nullptr, nullptr, digestionMotifs); ProteaseDictionary::Dictionary->Add(protease->Name, protease); DigestionParams *digestionParams = new DigestionParams(protease: protease->Name, minPeptideLength: 1); // digest the proteins auto peptides = std::unordered_set<PeptideWithSetModifications*>(); for (auto protein : proteins) { for (PeptideWithSetModifications *peptide : protein->Digest(digestionParams, std::vector<Modification*>(), std::vector<Modification*>())) { //C# TO C++ CONVERTER NOTE: The following 'switch' operated on a string variable and was converted to C++ 'if-else' logic: // switch (peptide.BaseSequence) //ORIGINAL LINE: case "A": if (peptide->BaseSequence == L"A") { peptides.insert(peptide); } //ORIGINAL LINE: case "B": else if (peptide->BaseSequence == L"B") { peptides.insert(peptide); } //ORIGINAL LINE: case "C": else if (peptide->BaseSequence == L"C") { peptides.insert(peptide); } //ORIGINAL LINE: case "D": else if (peptide->BaseSequence == L"D") { peptides.insert(peptide); } //ORIGINAL LINE: case "E": else if (peptide->BaseSequence == L"E") { peptides.insert(peptide); } //ORIGINAL LINE: case "F": else if (peptide->BaseSequence == L"F") { peptides.insert(peptide); } //ORIGINAL LINE: case "G": else if (peptide->BaseSequence == L"G") { peptides.insert(peptide); } //ORIGINAL LINE: case "H": else if (peptide->BaseSequence == L"H") { peptides.insert(peptide); } //ORIGINAL LINE: case "I": else if (peptide->BaseSequence == L"I") { peptides.insert(peptide); } } } // create PSMs for the peptides std::unordered_map<std::wstring, PeptideSpectralMatch*> temp; MzSpectrum tempVar5(new double[] {1}, new double[] {1}, false); MsDataScan *fakeScan = new MsDataScan(&tempVar5, 0, 1, true, Polarity::Positive, NAN, nullptr, nullptr, MZAnalyzerType::Orbitrap, NAN, nullptr, nullptr, L"scan=1", NAN, nullptr, nullptr, NAN, nullptr, DissociationType::AnyActivationType, 0, nullptr); CommonParameters tempVar6(); Ms2ScanWithSpecificMass *scan = new Ms2ScanWithSpecificMass(fakeScan, 2, 0, L"File", &tempVar6); for (auto peptide : peptides) { TValue psm; std::unordered_map<std::wstring, PeptideSpectralMatch*>::const_iterator temp_iterator = temp.find(peptide.BaseSequence); if (temp_iterator != temp.end()) { psm = temp_iterator->second; psm::AddOrReplace(peptide, 1, 0, true, std::vector<MatchedFragmentIon*>()); } else { psm = temp_iterator->second; PeptideSpectralMatch tempVar7(peptide, 0, 1, 0, scan, digestionParams, new std::vector<MatchedFragmentIon*>()); temp.emplace(peptide->BaseSequence, &tempVar7); } } std::vector<PeptideSpectralMatch*> psms = temp.Values->ToList(); for (auto psm : psms) { psm->ResolveAllAmbiguities(); psm->SetFdrValues(0, 0, 0, 0, 0, 0, 0, 0, 0, false); } // run parsimony CommonParameters tempVar8(); ProteinParsimonyEngine *parsimonyEngine = new ProteinParsimonyEngine(psms, false, &tempVar8, std::vector<std::wstring>()); auto parsimonyResults = static_cast<ProteinParsimonyResults*>(parsimonyEngine->Run()); auto proteinGroups = parsimonyResults->getProteinGroups(); CommonParameters tempVar9(); ProteinScoringAndFdrEngine *proteinScoringAndFdrEngine = new ProteinScoringAndFdrEngine(proteinGroups, psms, true, false, true, &tempVar9, std::vector<std::wstring>()); auto proteinScoringAndFdrResults = static_cast<ProteinScoringAndFdrResults*>(proteinScoringAndFdrEngine->Run()); proteinGroups = proteinScoringAndFdrResults->SortedAndScoredProteinGroups; // select the PSMs' proteins std::vector<std::wstring> parsimonyProteinSequences = psms.SelectMany([&] (std::any p) { p::BestMatchingPeptides->Select([&] (std::any v) { v::Peptide::Protein; }); })->Select([&] (std::any v) { v::BaseSequence; }).Distinct().ToList(); // check that correct proteins are in parsimony list Assert->Contains(L"AB--------", parsimonyProteinSequences); Assert->Contains(L"--C-------", parsimonyProteinSequences); Assert->Contains(L"-B-D---HHH--", parsimonyProteinSequences); Assert->Contains(L"----E----**", parsimonyProteinSequences); Assert->Contains(L"-B------I-", parsimonyProteinSequences); Assert->Contains(L"----EFG---", parsimonyProteinSequences); Assert->Contains(L"----EFG--J", parsimonyProteinSequences); Assert::AreEqual(8, parsimonyProteinSequences.size()); // sequence coverage test for (auto proteinGroup : proteinGroups) { for (auto coverage : proteinGroup->getSequenceCoveragePercent()) { Assert::That(coverage <= 1.0); } } // test protein groups Assert::AreEqual(3, proteinGroups.size()); Assert::AreEqual(1, proteinGroups.front().Proteins->Count); Assert::AreEqual(L"AB--------", proteinGroups.front().Proteins::First().BaseSequence); Assert::AreEqual(2, proteinGroups.front().AllPsmsBelowOnePercentFDR->Count); Assert::AreEqual(2, proteinGroups.front().ProteinGroupScore); delete proteinScoringAndFdrEngine; delete parsimonyEngine; //C# TO C++ CONVERTER TODO TASK: A 'delete scan' statement was not added since scan was passed to a method or constructor. Handle memory management manually. //C# TO C++ CONVERTER TODO TASK: A 'delete fakeScan' statement was not added since fakeScan was passed to a method or constructor. Handle memory management manually. //C# TO C++ CONVERTER TODO TASK: A 'delete digestionParams' statement was not added since digestionParams was passed to a method or constructor. Handle memory management manually. //C# TO C++ CONVERTER TODO TASK: A 'delete protease' statement was not added since protease was passed to a method or constructor. Handle memory management manually. } void RobTest::TestPTMOutput() { std::vector<Modification*> variableModifications; std::vector<Modification*> fixedModifications; ModificationMotif motif; ModificationMotif::TryGetMotif(L"S", motif); Modification tempVar(_originalId: L"resMod", _modificationType: L"HaHa", _target: motif, _locationRestriction: L"Anywhere.", _chemicalFormula: ChemicalFormula::ParseFormula(L"H")); variableModifications.push_back(&tempVar); auto proteinList = std::vector<Protein*> {new Protein(L"MNNNSKQQQ", L"accession")}; auto protease = new Protease(L"CustomProtease", CleavageSpecificity::Full, nullptr, nullptr, std::vector<DigestionMotif*> {new DigestionMotif(L"K", nullptr, 1, nullptr)}); ProteaseDictionary::Dictionary->Add(protease->Name, protease); std::unordered_map<Modification*, unsigned short> modsDictionary = { {variableModifications.back(), 1} }; DigestionParams *digestionParams = new DigestionParams(protease: protease->Name, maxMissedCleavages: 0, minPeptideLength: 1); auto modPep = proteinList.front().Digest(digestionParams, fixedModifications, variableModifications).Last(); std::unordered_set<PeptideWithSetModifications*> value = {modPep}; PeptideWithSetModifications *compactPeptide1 = value.First(); Assert::AreEqual(L"QQQ", value.First().FullSequence); //this might be base auto firstProtDigest = proteinList.front().Digest(digestionParams, fixedModifications, variableModifications).ToList(); std::unordered_set<PeptideWithSetModifications*> value2 = std::vector<std::unordered_set<PeptideWithSetModifications*>>(0) }; PeptideWithSetModifications *compactPeptide2 = value2.First(); Assert::AreEqual(L"MNNNSK", value2.First().FullSequence); //this might be base std::unordered_set<PeptideWithSetModifications*> value2mod = std::vector<std::unordered_set<PeptideWithSetModifications*>>(1) }; PeptideWithSetModifications *compactPeptide2mod = value2mod.Last(); Assert::AreEqual(L"MNNNS[HaHa:resMod on S]K", value2mod.Last().FullSequence); //this might be base std::unordered_set<PeptideWithSetModifications*> value3 = std::vector<std::unordered_set<PeptideWithSetModifications*>>(2) }; PeptideWithSetModifications *compactPeptide3 = value3.First(); Assert::AreEqual(L"NNNSK", value3.First().FullSequence); //this might be base std::unordered_set<PeptideWithSetModifications*> value3mod = std::vector<std::unordered_set<PeptideWithSetModifications*>>(3) }; PeptideWithSetModifications *compactPeptide3mod = value3mod.Last(); Assert::AreEqual(L"NNNS[HaHa:resMod on S]K", value3mod.Last().FullSequence); //this might be base auto peptideList = std::unordered_set<PeptideWithSetModifications*>(); for (auto protein : proteinList) { for (auto peptide : protein->Digest(digestionParams, std::vector<Modification*>(), variableModifications)) { peptideList.insert(peptide); } } MzSpectrum tempVar2(new double[] {1}, new double[] {1}, false); MsDataScan *jdfk = new MsDataScan(&tempVar2, 0, 1, true, Polarity::Positive, NAN, nullptr, nullptr, MZAnalyzerType::Orbitrap, NAN, nullptr, nullptr, L"scan=1", NAN, nullptr, nullptr, NAN, nullptr, DissociationType::AnyActivationType, 0, nullptr); CommonParameters tempVar3(); Ms2ScanWithSpecificMass *ms2scan = new Ms2ScanWithSpecificMass(jdfk, 2, 0, L"File", &tempVar3); Tolerance *fragmentTolerance = new AbsoluteTolerance(0.01); auto match1 = new PeptideSpectralMatch(peptideList.ElementAt(0), 0, 10, 0, ms2scan, digestionParams, std::vector<MatchedFragmentIon*>()) { }; match1->SetFdrValues(0, 0, 0, 0, 0, 0, 0, 0, 0, false); auto match2 = new PeptideSpectralMatch(peptideList.ElementAt(1), 0, 10, 0, ms2scan, digestionParams, std::vector<MatchedFragmentIon*>()) { }; match2->SetFdrValues(0, 0, 0, 0, 0, 0, 0, 0, 0, false); auto match3 = new PeptideSpectralMatch(peptideList.ElementAt(1), 0, 10, 0, ms2scan, digestionParams, std::vector<MatchedFragmentIon*>()) { }; match3->SetFdrValues(0, 0, 0, 0, 0, 0, 0, 0, 0, false); std::vector<PeptideSpectralMatch*> psms = {match1, match2, match3}; std::for_each(psms.begin(), psms.end(), [&] (std::any p) { p::ResolveAllAmbiguities(); }); CommonParameters tempVar4(); ProteinParsimonyEngine *engine = new ProteinParsimonyEngine(psms, true, &tempVar4, std::vector<std::wstring> {L"ff"}); auto cool = static_cast<ProteinParsimonyResults*>(engine->Run()); auto proteinGroups = cool->getProteinGroups(); CommonParameters tempVar5(); ProteinScoringAndFdrEngine *f = new ProteinScoringAndFdrEngine(proteinGroups, psms, false, false, true, &tempVar5, std::vector<std::wstring>()); f->Run(); Assert::AreEqual(L"#aa5[resMod on S,info:occupancy=0.67(2/3)];", proteinGroups.front().ModsInfo[0]); delete f; delete engine; delete match3; delete match2; delete match1; delete fragmentTolerance; //C# TO C++ CONVERTER TODO TASK: A 'delete ms2scan' statement was not added since ms2scan was passed to a method or constructor. Handle memory management manually. //C# TO C++ CONVERTER TODO TASK: A 'delete jdfk' statement was not added since jdfk was passed to a method or constructor. Handle memory management manually. //C# TO C++ CONVERTER TODO TASK: A 'delete digestionParams' statement was not added since digestionParams was passed to a method or constructor. Handle memory management manually. //C# TO C++ CONVERTER TODO TASK: A 'delete protease' statement was not added since protease was passed to a method or constructor. Handle memory management manually. } void RobTest::TestProteinGroupsAccessionOutputOrder() { auto p = std::unordered_set<Protein*>(); std::vector<std::tuple<std::wstring, std::wstring>> gn; // make protein B Protein tempVar(L"-----F----*", L"B", nullptr, gn, new std::unordered_map<int, std::vector<Modification*>>(), isDecoy: true); p.insert(&tempVar); // make protein A Protein tempVar2(L"-----F----**", L"A", nullptr, gn, new std::unordered_map<int, std::vector<Modification*>>(), isDecoy: true); p.insert(&tempVar2); // add protein B and A to the protein group ProteinGroup *testGroup = new ProteinGroup(p, nullptr, nullptr); // test order is AB and not BA Assert::That(testGroup->getProteinGroupName() == L"A|B"); Assert::That(testGroup->getProteins().First().Accession->Equals(L"B")); delete testGroup; } }
#ifndef MENU_CHICKFILA_TESTS #define MENU_CHICKFILA_TESTS #include "gtest/gtest.h" #include "../../composite/menu_component.hpp" #include "../../composite/menu_burger/header/menu_items_chickfila.hpp" #include "../../composite/menu_burger/header/menu_chickfila.hpp" #include <iostream> using namespace std; TEST(MenuTest, ChickFilA_CustomerFavorites) { menu_component *m_chickfila_customer_favorites = new menu_chickfila("Customer Favorites", "Following Options are the Most Popular Items at Chick-Fil-A"); EXPECT_EQ(m_chickfila_customer_favorites->get_name(), "Customer Favorites"); EXPECT_EQ(m_chickfila_customer_favorites->get_description(), "Following Options are the Most Popular Items at Chick-Fil-A"); menu_component *chicken_sandwhich = new menu_items_chickfila(1, "Chicken Sandwich", "A boneless breast of chicken seasoned to perfection, hand-breaded, pressure cooked in 100% refined peanut oil and served on a toasted, buttered bun with dill pickle chips. Gluten-free bun or multigrain bun also available at an additional cost.", 4.29); m_chickfila_customer_favorites->add(chicken_sandwhich); cout << "EXPECTED ITEM NUMBER: 1" << "\nRECEIVIED: " << chicken_sandwhich->get_item_number() << endl; EXPECT_EQ(chicken_sandwhich->get_item_number(), 1); menu_component *spicy_chicken_sandwhich = new menu_items_chickfila(2, "Spicy Chicken Sandwich", "A boneless breast of chicken seasoned with a spicy blend of peppers, hand-breaded, pressure cooked in 100% refined peanut oil and served on a toasted, buttered bun with dill pickle chips. Gluten-free bun or multigrain bun also available at an additional cost.", 4.65); m_chickfila_customer_favorites->add(spicy_chicken_sandwhich); cout << "EXPECTED ITEM NUMBER: 2" << "\nRECEIVIED: " << spicy_chicken_sandwhich->get_item_number() << endl; EXPECT_EQ(spicy_chicken_sandwhich->get_item_number(), 2); menu_component *chickfila_nuggets_4_piece = new menu_items_chickfila(3, "Chick-fil-a Nuggets 4 Piece","Bite-sized pieces of boneless chicken breast, seasoned to perfection, freshly-breaded and pressure cooked in 100% refined peanut oil. Available with choice of dipping sauce.", 2.20); m_chickfila_customer_favorites->add(chickfila_nuggets_4_piece); cout << "EXPECTED ITEM NUMBER: 3" << "\nRECEIVIED: " << chickfila_nuggets_4_piece->get_item_number() << endl; EXPECT_EQ(chickfila_nuggets_4_piece->get_item_number(), 3); menu_component *chickfila_nuggets_8_piece = new menu_items_chickfila(4, "Chick-fil-a Nuggets 8 Piece","Bite-sized pieces of boneless chicken breast, seasoned to perfection, freshly-breaded and pressure cooked in 100% refined peanut oil. Available with choice of dipping sauce.", 4.39); m_chickfila_customer_favorites->add(chickfila_nuggets_8_piece); cout << "EXPECTED ITEM NUMBER: 4" << "\nRECEIVIED: " << chickfila_nuggets_8_piece->get_item_number() << endl; EXPECT_EQ(chickfila_nuggets_8_piece->get_item_number(), 4); menu_component *chickfila_nuggets_12_piece = new menu_items_chickfila(5, "Chick-fil-a Nuggets 12 Piece", "Bite-sized pieces of boneless chicken breast, seasoned to perfection, freshly-breaded and pressure cooked in 100% refined peanut oil. Available with choice of dipping sauce.", 6.29); m_chickfila_customer_favorites->add(chickfila_nuggets_12_piece); cout << "EXPECTED ITEM NUMBER: 5" << "\nRECEIVIED: " << chickfila_nuggets_12_piece->get_item_number() << endl; EXPECT_EQ(chickfila_nuggets_12_piece->get_item_number(), 5); menu_component *waffle_fries_small = new menu_items_chickfila(6, "Waffle Potato Fries (Small)", "Waffle-cut potatoes cooked in canola oil until crispy outside and tender inside. Lightly sprinkled with Sea Salt.", 1.95); m_chickfila_customer_favorites->add(waffle_fries_small); cout << "EXPECTED ITEM NUMBER: 6" << "\nRECEIVIED: " << waffle_fries_small->get_item_number() << endl; EXPECT_EQ(waffle_fries_small->get_item_number(), 6); menu_component *waffle_fries_medium = new menu_items_chickfila(7, "Waffle Potato Fries (Medium)", "Waffle-cut potatoes cooked in canola oil until crispy outside and tender inside. Lightly sprinkled with Sea Salt.", 2.25); cout << "EXPECTED ITEM NUMBER: 7" << "\nRECEIVIED: " << waffle_fries_medium->get_item_number() << endl; EXPECT_EQ(waffle_fries_medium->get_item_number(), 7); menu_component *waffle_fries_large = new menu_items_chickfila(8, "Waffle Potato Fries (Large)", "Waffle-cut potatoes cooked in canola oil until crispy outside and tender inside. Lightly sprinkled with Sea Salt.", 2.55); m_chickfila_customer_favorites->add(waffle_fries_large); cout << "EXPECTED ITEM NUMBER: 8" << "\nRECEIVIED: " << waffle_fries_large->get_item_number() << endl; EXPECT_EQ(waffle_fries_large->get_item_number(), 8); menu_component *mac_and_cheese_small = new menu_items_chickfila(9, "Mac and Cheese (Small)", "A classic macaroni and cheese recipe featuring a special blend of cheeses including Parmesan, Cheddar, and Romano. Baked in-restaurant to form a crispy top layer of baked cheese.", 2.89); m_chickfila_customer_favorites->add(mac_and_cheese_small); cout << "EXPECTED ITEM NUMBER: 9" << "\nRECEIVIED: " << mac_and_cheese_small->get_item_number() << endl; EXPECT_EQ(mac_and_cheese_small->get_item_number(), 9); menu_component *mac_and_cheese_medium = new menu_items_chickfila(10, "Mac and Cheese (Medium)", "A classic macaroni and cheese recipe featuring a special blend of cheeses including Parmesan, Cheddar, and Romano. Baked in-restaurant to form a crispy top layer of baked cheese.", 3.65); m_chickfila_customer_favorites->add(mac_and_cheese_medium); cout << "EXPECTED ITEM NUMBER: 10" << "\nRECEIVIED: " << mac_and_cheese_medium->get_item_number() << endl; EXPECT_EQ(mac_and_cheese_medium->get_item_number(), 10); m_chickfila_customer_favorites->print(); } #endif /* MENU_CHICKFILA_TESTS */
// C++ for the Windows Runtime vv1.0.170303.6 // Copyright (c) 2017 Microsoft Corporation. All rights reserved. #pragma once #include "Windows.ApplicationModel.UserDataTasks.1.h" WINRT_EXPORT namespace winrt { namespace ABI::Windows::Foundation { #ifndef WINRT_GENERIC_cdb5efb3_5788_509d_9be1_71ccb8a3362a #define WINRT_GENERIC_cdb5efb3_5788_509d_9be1_71ccb8a3362a template <> struct __declspec(uuid("cdb5efb3-5788-509d-9be1-71ccb8a3362a")) __declspec(novtable) IAsyncOperation<bool> : impl_IAsyncOperation<bool> {}; #endif #ifndef WINRT_GENERIC_3e1fe603_f897_5263_b328_0806426b8a79 #define WINRT_GENERIC_3e1fe603_f897_5263_b328_0806426b8a79 template <> struct __declspec(uuid("3e1fe603-f897-5263-b328-0806426b8a79")) __declspec(novtable) IAsyncOperation<hstring> : impl_IAsyncOperation<hstring> {}; #endif #ifndef WINRT_GENERIC_548cefbd_bc8a_5fa0_8df2_957440fc8bf4 #define WINRT_GENERIC_548cefbd_bc8a_5fa0_8df2_957440fc8bf4 template <> struct __declspec(uuid("548cefbd-bc8a-5fa0-8df2-957440fc8bf4")) __declspec(novtable) IReference<int32_t> : impl_IReference<int32_t> {}; #endif #ifndef WINRT_GENERIC_5541d8a7_497c_5aa4_86fc_7713adbf2a2c #define WINRT_GENERIC_5541d8a7_497c_5aa4_86fc_7713adbf2a2c template <> struct __declspec(uuid("5541d8a7-497c-5aa4-86fc-7713adbf2a2c")) __declspec(novtable) IReference<Windows::Foundation::DateTime> : impl_IReference<Windows::Foundation::DateTime> {}; #endif #ifndef WINRT_GENERIC_e02c4e60_78aa_5eb8_badb_ead22dca9679 #define WINRT_GENERIC_e02c4e60_78aa_5eb8_badb_ead22dca9679 template <> struct __declspec(uuid("e02c4e60-78aa-5eb8-badb-ead22dca9679")) __declspec(novtable) IAsyncOperation<Windows::ApplicationModel::UserDataTasks::UserDataTaskStore> : impl_IAsyncOperation<Windows::ApplicationModel::UserDataTasks::UserDataTaskStore> {}; #endif #ifndef WINRT_GENERIC_d9274ef2_63e0_544c_8db2_fe2d5b825d9e #define WINRT_GENERIC_d9274ef2_63e0_544c_8db2_fe2d5b825d9e template <> struct __declspec(uuid("d9274ef2-63e0-544c-8db2-fe2d5b825d9e")) __declspec(novtable) IAsyncOperation<Windows::ApplicationModel::UserDataTasks::UserDataTaskList> : impl_IAsyncOperation<Windows::ApplicationModel::UserDataTasks::UserDataTaskList> {}; #endif } namespace ABI::Windows::Foundation::Collections { #ifndef WINRT_GENERIC_0910e3ae_2075_5486_866f_f1590ade3616 #define WINRT_GENERIC_0910e3ae_2075_5486_866f_f1590ade3616 template <> struct __declspec(uuid("0910e3ae-2075-5486-866f-f1590ade3616")) __declspec(novtable) IVectorView<Windows::ApplicationModel::UserDataTasks::UserDataTaskList> : impl_IVectorView<Windows::ApplicationModel::UserDataTasks::UserDataTaskList> {}; #endif } namespace ABI::Windows::Foundation { #ifndef WINRT_GENERIC_b8b749b1_a847_5c34_866c_ea560cde1f49 #define WINRT_GENERIC_b8b749b1_a847_5c34_866c_ea560cde1f49 template <> struct __declspec(uuid("b8b749b1-a847-5c34-866c-ea560cde1f49")) __declspec(novtable) IAsyncOperation<Windows::ApplicationModel::UserDataTasks::UserDataTask> : impl_IAsyncOperation<Windows::ApplicationModel::UserDataTasks::UserDataTask> {}; #endif } namespace ABI::Windows::Foundation::Collections { #ifndef WINRT_GENERIC_0cfeaf9b_8758_5aa6_9806_32b0ea40d4b8 #define WINRT_GENERIC_0cfeaf9b_8758_5aa6_9806_32b0ea40d4b8 template <> struct __declspec(uuid("0cfeaf9b-8758-5aa6-9806-32b0ea40d4b8")) __declspec(novtable) IVectorView<Windows::ApplicationModel::UserDataTasks::UserDataTask> : impl_IVectorView<Windows::ApplicationModel::UserDataTasks::UserDataTask> {}; #endif } namespace ABI::Windows::Foundation { #ifndef WINRT_GENERIC_d36b10df_1cab_544c_8c2e_3c7bc4d24b24 #define WINRT_GENERIC_d36b10df_1cab_544c_8c2e_3c7bc4d24b24 template <> struct __declspec(uuid("d36b10df-1cab-544c-8c2e-3c7bc4d24b24")) __declspec(novtable) IAsyncOperation<Windows::ApplicationModel::UserDataTasks::UserDataTaskBatch> : impl_IAsyncOperation<Windows::ApplicationModel::UserDataTasks::UserDataTaskBatch> {}; #endif #ifndef WINRT_GENERIC_903861c5_d29d_5083_a03d_6b2a0233dcca #define WINRT_GENERIC_903861c5_d29d_5083_a03d_6b2a0233dcca template <> struct __declspec(uuid("903861c5-d29d-5083-a03d-6b2a0233dcca")) __declspec(novtable) IReference<winrt::Windows::ApplicationModel::UserDataTasks::UserDataTaskDaysOfWeek> : impl_IReference<winrt::Windows::ApplicationModel::UserDataTasks::UserDataTaskDaysOfWeek> {}; #endif #ifndef WINRT_GENERIC_5246fa7f_f9e9_5574_80f7_4aa359b0023d #define WINRT_GENERIC_5246fa7f_f9e9_5574_80f7_4aa359b0023d template <> struct __declspec(uuid("5246fa7f-f9e9-5574-80f7-4aa359b0023d")) __declspec(novtable) IReference<winrt::Windows::ApplicationModel::UserDataTasks::UserDataTaskWeekOfMonth> : impl_IReference<winrt::Windows::ApplicationModel::UserDataTasks::UserDataTaskWeekOfMonth> {}; #endif #ifndef WINRT_GENERIC_03e790f2_eacf_53eb_9060_6bfeec5bc375 #define WINRT_GENERIC_03e790f2_eacf_53eb_9060_6bfeec5bc375 template <> struct __declspec(uuid("03e790f2-eacf-53eb-9060-6bfeec5bc375")) __declspec(novtable) TypedEventHandler<Windows::ApplicationModel::UserDataTasks::UserDataTaskListSyncManager, Windows::Foundation::IInspectable> : impl_TypedEventHandler<Windows::ApplicationModel::UserDataTasks::UserDataTaskListSyncManager, Windows::Foundation::IInspectable> {}; #endif #ifndef WINRT_GENERIC_c1d3d1a2_ae17_5a5f_b5a2_bdcc8844889a #define WINRT_GENERIC_c1d3d1a2_ae17_5a5f_b5a2_bdcc8844889a template <> struct __declspec(uuid("c1d3d1a2-ae17-5a5f-b5a2-bdcc8844889a")) __declspec(novtable) AsyncOperationCompletedHandler<bool> : impl_AsyncOperationCompletedHandler<bool> {}; #endif #ifndef WINRT_GENERIC_b79a741f_7fb5_50ae_9e99_911201ec3d41 #define WINRT_GENERIC_b79a741f_7fb5_50ae_9e99_911201ec3d41 template <> struct __declspec(uuid("b79a741f-7fb5-50ae-9e99-911201ec3d41")) __declspec(novtable) AsyncOperationCompletedHandler<hstring> : impl_AsyncOperationCompletedHandler<hstring> {}; #endif #ifndef WINRT_GENERIC_33c9c615_2f80_587d_9f51_027ec457b7a3 #define WINRT_GENERIC_33c9c615_2f80_587d_9f51_027ec457b7a3 template <> struct __declspec(uuid("33c9c615-2f80-587d-9f51-027ec457b7a3")) __declspec(novtable) AsyncOperationCompletedHandler<Windows::ApplicationModel::UserDataTasks::UserDataTaskStore> : impl_AsyncOperationCompletedHandler<Windows::ApplicationModel::UserDataTasks::UserDataTaskStore> {}; #endif #ifndef WINRT_GENERIC_eefb814a_6af7_5d59_bf3f_b6c73b8c74a2 #define WINRT_GENERIC_eefb814a_6af7_5d59_bf3f_b6c73b8c74a2 template <> struct __declspec(uuid("eefb814a-6af7-5d59-bf3f-b6c73b8c74a2")) __declspec(novtable) AsyncOperationCompletedHandler<Windows::ApplicationModel::UserDataTasks::UserDataTaskList> : impl_AsyncOperationCompletedHandler<Windows::ApplicationModel::UserDataTasks::UserDataTaskList> {}; #endif } namespace ABI::Windows::Foundation::Collections { #ifndef WINRT_GENERIC_abbd21ed_d35d_5f62_b547_54b2b0e1dd0c #define WINRT_GENERIC_abbd21ed_d35d_5f62_b547_54b2b0e1dd0c template <> struct __declspec(uuid("abbd21ed-d35d-5f62-b547-54b2b0e1dd0c")) __declspec(novtable) IVector<Windows::ApplicationModel::UserDataTasks::UserDataTaskList> : impl_IVector<Windows::ApplicationModel::UserDataTasks::UserDataTaskList> {}; #endif #ifndef WINRT_GENERIC_8e989bcb_9d7c_512f_89da_fdb75532d665 #define WINRT_GENERIC_8e989bcb_9d7c_512f_89da_fdb75532d665 template <> struct __declspec(uuid("8e989bcb-9d7c-512f-89da-fdb75532d665")) __declspec(novtable) IIterator<Windows::ApplicationModel::UserDataTasks::UserDataTaskList> : impl_IIterator<Windows::ApplicationModel::UserDataTasks::UserDataTaskList> {}; #endif #ifndef WINRT_GENERIC_2c4d63bc_cffb_50d2_8a82_a9aefad651d3 #define WINRT_GENERIC_2c4d63bc_cffb_50d2_8a82_a9aefad651d3 template <> struct __declspec(uuid("2c4d63bc-cffb-50d2-8a82-a9aefad651d3")) __declspec(novtable) IIterable<Windows::ApplicationModel::UserDataTasks::UserDataTaskList> : impl_IIterable<Windows::ApplicationModel::UserDataTasks::UserDataTaskList> {}; #endif } namespace ABI::Windows::Foundation { #ifndef WINRT_GENERIC_a731c0cd_206d_5af8_ad64_85b7200f4ce2 #define WINRT_GENERIC_a731c0cd_206d_5af8_ad64_85b7200f4ce2 template <> struct __declspec(uuid("a731c0cd-206d-5af8-ad64-85b7200f4ce2")) __declspec(novtable) AsyncOperationCompletedHandler<Windows::ApplicationModel::UserDataTasks::UserDataTask> : impl_AsyncOperationCompletedHandler<Windows::ApplicationModel::UserDataTasks::UserDataTask> {}; #endif } namespace ABI::Windows::Foundation::Collections { #ifndef WINRT_GENERIC_cc681ce4_da95_5297_adbe_dc4e47f3fa2a #define WINRT_GENERIC_cc681ce4_da95_5297_adbe_dc4e47f3fa2a template <> struct __declspec(uuid("cc681ce4-da95-5297-adbe-dc4e47f3fa2a")) __declspec(novtable) IVector<Windows::ApplicationModel::UserDataTasks::UserDataTask> : impl_IVector<Windows::ApplicationModel::UserDataTasks::UserDataTask> {}; #endif #ifndef WINRT_GENERIC_98733fc7_1908_532f_bfe3_3868445d29d6 #define WINRT_GENERIC_98733fc7_1908_532f_bfe3_3868445d29d6 template <> struct __declspec(uuid("98733fc7-1908-532f-bfe3-3868445d29d6")) __declspec(novtable) IIterator<Windows::ApplicationModel::UserDataTasks::UserDataTask> : impl_IIterator<Windows::ApplicationModel::UserDataTasks::UserDataTask> {}; #endif #ifndef WINRT_GENERIC_8ae8becd_375f_5932_91ed_f82a74224365 #define WINRT_GENERIC_8ae8becd_375f_5932_91ed_f82a74224365 template <> struct __declspec(uuid("8ae8becd-375f-5932-91ed-f82a74224365")) __declspec(novtable) IIterable<Windows::ApplicationModel::UserDataTasks::UserDataTask> : impl_IIterable<Windows::ApplicationModel::UserDataTasks::UserDataTask> {}; #endif } namespace ABI::Windows::Foundation { #ifndef WINRT_GENERIC_e63bf8b8_91f0_5f13_a1c9_dee1879d0a52 #define WINRT_GENERIC_e63bf8b8_91f0_5f13_a1c9_dee1879d0a52 template <> struct __declspec(uuid("e63bf8b8-91f0-5f13-a1c9-dee1879d0a52")) __declspec(novtable) AsyncOperationCompletedHandler<Windows::ApplicationModel::UserDataTasks::UserDataTaskBatch> : impl_AsyncOperationCompletedHandler<Windows::ApplicationModel::UserDataTasks::UserDataTaskBatch> {}; #endif #ifndef WINRT_GENERIC_2a4e06ee_9030_5ce6_ad7f_cf551795765d #define WINRT_GENERIC_2a4e06ee_9030_5ce6_ad7f_cf551795765d template <> struct __declspec(uuid("2a4e06ee-9030-5ce6-ad7f-cf551795765d")) __declspec(novtable) IAsyncOperation<Windows::Foundation::Collections::IVectorView<Windows::ApplicationModel::UserDataTasks::UserDataTaskList>> : impl_IAsyncOperation<Windows::Foundation::Collections::IVectorView<Windows::ApplicationModel::UserDataTasks::UserDataTaskList>> {}; #endif #ifndef WINRT_GENERIC_4aba8568_5231_526c_b2e4_805006b8ef2f #define WINRT_GENERIC_4aba8568_5231_526c_b2e4_805006b8ef2f template <> struct __declspec(uuid("4aba8568-5231-526c-b2e4-805006b8ef2f")) __declspec(novtable) AsyncOperationCompletedHandler<Windows::Foundation::Collections::IVectorView<Windows::ApplicationModel::UserDataTasks::UserDataTaskList>> : impl_AsyncOperationCompletedHandler<Windows::Foundation::Collections::IVectorView<Windows::ApplicationModel::UserDataTasks::UserDataTaskList>> {}; #endif } namespace Windows::ApplicationModel::UserDataTasks { struct IUserDataTask : Windows::Foundation::IInspectable, impl::consume<IUserDataTask> { IUserDataTask(std::nullptr_t = nullptr) noexcept {} }; struct IUserDataTaskBatch : Windows::Foundation::IInspectable, impl::consume<IUserDataTaskBatch> { IUserDataTaskBatch(std::nullptr_t = nullptr) noexcept {} }; struct IUserDataTaskList : Windows::Foundation::IInspectable, impl::consume<IUserDataTaskList> { IUserDataTaskList(std::nullptr_t = nullptr) noexcept {} }; struct IUserDataTaskListLimitedWriteOperations : Windows::Foundation::IInspectable, impl::consume<IUserDataTaskListLimitedWriteOperations> { IUserDataTaskListLimitedWriteOperations(std::nullptr_t = nullptr) noexcept {} }; struct IUserDataTaskListSyncManager : Windows::Foundation::IInspectable, impl::consume<IUserDataTaskListSyncManager> { IUserDataTaskListSyncManager(std::nullptr_t = nullptr) noexcept {} }; struct IUserDataTaskManager : Windows::Foundation::IInspectable, impl::consume<IUserDataTaskManager> { IUserDataTaskManager(std::nullptr_t = nullptr) noexcept {} }; struct IUserDataTaskManagerStatics : Windows::Foundation::IInspectable, impl::consume<IUserDataTaskManagerStatics> { IUserDataTaskManagerStatics(std::nullptr_t = nullptr) noexcept {} }; struct IUserDataTaskQueryOptions : Windows::Foundation::IInspectable, impl::consume<IUserDataTaskQueryOptions> { IUserDataTaskQueryOptions(std::nullptr_t = nullptr) noexcept {} }; struct IUserDataTaskReader : Windows::Foundation::IInspectable, impl::consume<IUserDataTaskReader> { IUserDataTaskReader(std::nullptr_t = nullptr) noexcept {} }; struct IUserDataTaskRecurrenceProperties : Windows::Foundation::IInspectable, impl::consume<IUserDataTaskRecurrenceProperties> { IUserDataTaskRecurrenceProperties(std::nullptr_t = nullptr) noexcept {} }; struct IUserDataTaskRegenerationProperties : Windows::Foundation::IInspectable, impl::consume<IUserDataTaskRegenerationProperties> { IUserDataTaskRegenerationProperties(std::nullptr_t = nullptr) noexcept {} }; struct IUserDataTaskStore : Windows::Foundation::IInspectable, impl::consume<IUserDataTaskStore> { IUserDataTaskStore(std::nullptr_t = nullptr) noexcept {} }; } }
#include "Shader.h" const std::string Shader::IMPORT_DIRECTIVE = "%%import"; const std::string Shader::SHADER_DIRECTORY = "./assets/shader/"; void Shader::handleError(std::string name,GLuint shaderId) { GLint maxLength = 0; glGetShaderiv(shaderId, GL_INFO_LOG_LENGTH, &maxLength); // The maxLength includes the NULL character std::vector<GLchar> errorLog(maxLength); glGetShaderInfoLog(shaderId, maxLength, &maxLength, &errorLog[0]); // Exit with failure. glDeleteShader(shaderId); // Don't leak the shader. //Log std::cout << "Failed to load shader " << name << std::endl; for (GLchar c : errorLog) { std::cout << c; } } GLuint Shader::loadStandardProgram() { GLuint vertexShader; GLuint fragmentShader; GLuint program; if (!loadShader(this->vertexShader,GL_VERTEX_SHADER,vertexShader)) { handleError(this->vertexShader, vertexShader); glDeleteShader(vertexShader); system("PAUSE"); exit(1); } if (!loadShader(this->fragmentShader, GL_FRAGMENT_SHADER, fragmentShader)) { handleError(this->fragmentShader, fragmentShader); glDeleteShader(vertexShader); glDeleteShader(fragmentShader); system("PAUSE"); exit(1); } //Create Program program = glCreateProgram(); // Attach our shaders to our program glAttachShader(program, vertexShader); glAttachShader(program, fragmentShader); // Link our program glLinkProgram(program); // Note the different functions here: glGetProgram* instead of glGetShader*. GLint isLinked = 0; glGetProgramiv(program, GL_LINK_STATUS, (int *)&isLinked); if (isLinked == GL_FALSE) { GLint maxLength = 0; glGetProgramiv(program, GL_INFO_LOG_LENGTH, &maxLength); // The maxLength includes the NULL character std::vector<GLchar> infoLog(maxLength); glGetProgramInfoLog(program, maxLength, &maxLength, &infoLog[0]); // We don't need the program anymore. glDeleteProgram(program); // Don't leak shaders either. glDeleteShader(vertexShader); glDeleteShader(fragmentShader); // Use the infoLog as you see fit. std::cout << "Failed to link shader " << this->vertexShader << " and " << this->fragmentShader<< std::endl; for (GLchar c : infoLog) { std::cout << c; } // In this simple program, we'll just leave system("PAUSE"); exit(1); } // Always detach shaders after a successful link. glDetachShader(program, vertexShader); glDetachShader(program, fragmentShader); return program; } GLuint Shader::loadComputeProgram() { GLuint computeShader; GLuint program; if (!loadShader(this->computeShader, GL_COMPUTE_SHADER, computeShader)) { handleError(this->vertexShader, computeShader); glDeleteShader(computeShader); system("PAUSE"); exit(1); } //Create Program program = glCreateProgram(); // Attach our shaders to our program glAttachShader(program, computeShader); // Link our program glLinkProgram(program); // Note the different functions here: glGetProgram* instead of glGetShader*. GLint isLinked = 0; glGetProgramiv(program, GL_LINK_STATUS, (int *)&isLinked); if (isLinked == GL_FALSE) { GLint maxLength = 0; glGetProgramiv(program, GL_INFO_LOG_LENGTH, &maxLength); // The maxLength includes the NULL character std::vector<GLchar> infoLog(maxLength); glGetProgramInfoLog(program, maxLength, &maxLength, &infoLog[0]); // We don't need the program anymore. glDeleteProgram(program); // Don't leak shaders either. glDeleteShader(computeShader); // Use the infoLog as you see fit. std::cout << "Failed to link shader " << this->vertexShader << " and " << this->fragmentShader << std::endl; for (GLchar c : infoLog) { std::cout << c; } // In this simple program, we'll just leave system("PAUSE"); exit(1); } // Always detach shaders after a successful link. glDetachShader(program, computeShader); return program; } bool Shader::loadShader(std::string filePath, GLenum shaderType, GLuint & shaderHandle) { std::string shaderSource = readFile(SHADER_DIRECTORY + filePath); shaderHandle = glCreateShader(shaderType); const GLchar *source = (const GLchar *)shaderSource.c_str(); glShaderSource(shaderHandle, 1, &source, 0); glCompileShader(shaderHandle); GLint isCompiled = 0; glGetShaderiv(shaderHandle, GL_COMPILE_STATUS, &isCompiled); return isCompiled == GL_TRUE; } GLint Shader::getUniformLocation(std::string location) { auto search = locations.find(location); //GLint locationId = glGetUniformLocation(handle, location.c_str()); //locations.insert(std::make_pair(location, locationId)); //return locationId; if (search != locations.end()) { return search->second; } else { GLint locationId = glGetUniformLocation(handle, location.c_str()); locations.insert(std::make_pair(location, locationId)); return locationId; } } std::string Shader::readFile(std::string filePath) { std::ifstream shaderFile; shaderFile.open(filePath); if (!shaderFile) { std::cout << "Failed to open shader " << filePath << std::endl; system("PAUSE"); exit(1); } std::string shaderCode = ""; std::string line = ""; while (std::getline(shaderFile,line)) { //processDirectives(line); shaderCode += line + '\n'; } shaderFile.close(); processDirectives(shaderCode); return shaderCode; } /** *Processes preprocessor directives in glsl file *edits source **/ void Shader::processDirectives(std::string & source) { processImport(source); } /** *Processes preprocessor import directive *Syntax: IMPORT_DIRECTIVE path/to/file *replace directive with filecontent of file **/ void Shader::processImport(std::string & source) { std::size_t offset = 0; std::size_t pos = 0; std::vector<std::string> loadedShaderNames; while ((pos = source.find(IMPORT_DIRECTIVE,pos+1)) != std::string::npos) { std::size_t lineEnd = source.find('\n', pos); std::size_t len = lineEnd - (pos + IMPORT_DIRECTIVE.length()+1); std::string token = source.substr(pos+IMPORT_DIRECTIVE.length()+1, len); if (std::find(loadedShaderNames.begin(), loadedShaderNames.end(), token) == loadedShaderNames.end()) { std::string importCode = readFile(SHADER_DIRECTORY+token); source.erase(pos, lineEnd - pos); source.insert(pos, importCode); loadedShaderNames.push_back(token); } else { source.replace(pos, len, ""); } } } Shader::Shader(std::string vertexShader, std::string fragmentShader) { this->vertexShader = vertexShader; this->fragmentShader = fragmentShader; this->handle = loadStandardProgram(); } Shader::Shader(std::string computeShader) { this->computeShader = computeShader; this->handle = loadComputeProgram(); } void Shader::setUniform(std::string uniform, const glm::vec3& value) { GLint location = getUniformLocation(uniform); setUnifrom(location, value); } void Shader::setUnifrom(GLint location, const glm::vec3& value) { glUniform3f(location, value.x, value.y, value.z); } void Shader::setUniform(std::string uniform, const glm::uvec3& value) { GLint location = getUniformLocation(uniform); setUnifrom(location, value); } void Shader::setUnifrom(GLint location, const glm::uvec3& value) { glUniform3ui(location, value.x, value.y, value.z); } void Shader::setUniform(std::string uniform, const int value) { GLint location = getUniformLocation(uniform); setUniform(location, value); } void Shader::setUniform(GLint location, const int value) { glUniform1i(location, value); } void Shader::setUniform(std::string uniform, const float value) { GLint location = getUniformLocation(uniform); setUniform(location, value); } void Shader::setUniform(GLint location, const float value) { glUniform1f(location, value); } void Shader::setUniform(std::string uniform, const glm::mat4 & mat) { GLint location = getUniformLocation(uniform); setUniform(location, mat); } void Shader::setUniform(GLint location, const glm::mat4 & mat) { glUniformMatrix4fv(location, 1, GL_FALSE, &mat[0][0]); } void Shader::setUniform(std::string uniform, const glm::mat3 & mat) { GLint location = getUniformLocation(uniform); setUniform(location, mat); } void Shader::setUniform(GLint location, const glm::mat3 & mat) { glUniformMatrix3fv(location, 1, GL_FALSE, &mat[0][0]); } void Shader::use() { glUseProgram(handle); } void Shader::unuse() { glUseProgram(0); } Shader::~Shader() { GLuint attachedShaders[2]; GLsizei numberOfShaders; glGetAttachedShaders(handle, 2, &numberOfShaders, attachedShaders); glDeleteProgram(handle); for (int i = 0; i < numberOfShaders; ++i) { glDeleteShader(attachedShaders[i]); } std::cout << "Shader Deleted" << std::endl; }
#ifndef _EXAMPLE_OPENCV_H #define _EXAMPLE_OPENCV_H #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> using namespace cv; void example_opencv(); #endif
#include "mainwindow.h" #include "ui_mainwindow.h" #include <QMessageBox> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); m_db = QSqlDatabase::addDatabase("QSQLITE"); //соединение объекта базы данных // с СУБД m_db.setDatabaseName("myDB2"); //определение имени базы данных query = new QSqlQuery(m_db); // создание объекта для запроса if(!m_db.open()) // проверка на ошибку при открытии или создании базы данных throw "can't open database"; if(!m_db.tables().contains("Person")) // если в базе не существует таблица Person, { //то создание таблицы Person и заполнение данными query->clear(); // очистка запроса query->exec("CREATE TABLE Person(ID INTEGER PRIMARY KEY, Name VARCHAR, Year INTEGER, Genre VARCHAR, Length INTEGER);"); // исполнение запроса на добавление записи query->clear(); query->exec("INSERT INTO Person (ID,Name,Year,Genre,Length) VALUES (1,'Interstellar', 2016, 'sci-fi', 135);"); query->clear(); query->exec("INSERT INTO Person (ID,Name,Year,Genre,Length) VALUES (2,'Truman Show', 1998, 'comedy', 100);"); } model = new QSqlTableModel(this,m_db); // создание // редактируемой модели базы данных model->setTable("Person"); // создание модели таблицы Person model->select(); // заполнение модели данными model->setEditStrategy(QSqlTableModel::OnFieldChange); // выбор стратегии // сохранения изменений в базе данных //- сохранение происходит при переходе к другому полю ui->tableView->setModel(model); // соединение модели // и ее табличного представления в форме } MainWindow::~MainWindow() { delete ui; delete query; delete model; } void MainWindow::on_pushButtonadd_clicked() { if(ui->lineEditid->text().isEmpty()||ui->lineEditname->text().isEmpty()||ui->lineEdityear->text().isEmpty()||ui->lineEditgenre->text().isEmpty()||ui->lineEditlength->text().isEmpty()) return; QString id = ui->lineEditid->text(); QString name = ui->lineEditname->text(); QString year = ui->lineEdityear->text(); QString genre = ui->lineEditgenre->text(); QString length = ui->lineEditlength->text(); QString buf = tr("INSERT INTO Person (Id,Name,Year,Genre,Length) VALUES (")+id+tr(",'")+name+tr("',")+year+tr(",'")+genre+tr("',")+length+tr(");"); query->clear(); query->exec(buf); model->select(); } void MainWindow::on_pushButton_clicked() { model->setFilter(""); model->select(); ui->tableView->setModel(model); } void MainWindow::on_pushButtonrem_clicked() { QString id = ui->lineEditid2->text(); QString name = ui->lineEditid2->text(); QString year = ui->lineEditid2->text(); QString genre = ui->lineEditid2->text(); QString length = ui->lineEditid2->text(); QString buf = tr("DELETE FROM Person WHERE id=")+id+tr(";"); query->clear(); query->exec(buf); model->select(); } void MainWindow::on_pushButton_3_clicked() { model->setFilter("Length>100"); model->select(); ui->tableView->setModel(model); } void MainWindow::on_pushButton_2_clicked() { model->setFilter("Length<100"); model->select(); ui->tableView->setModel(model); } void MainWindow::on_pushButtonYear_clicked() { if(ui->checkBox->isChecked()) { model->setFilter("Year<2000"); model->select(); ui->tableView->setModel(model); } else { model->setFilter(""); model->select(); ui->tableView->setModel(model); } }
#include <LiquidCrystal.h> #include <Keypad.h> LiquidCrystal lcd(32, 33, 34, 35, 36, 37); //RS, E, DB4, DB5, DB6, DB7 const byte ROWS = 4; // Four rows const byte COLS = 3; // Three columns // Define the Keymap char keys[ROWS][COLS] = { {'1','2','3'}, {'4','5','6'}, {'7','8','9'}, {'*','0','#'} }; char key; char ch = ' '; int s = 0; String menu[11] = { "1.Tea Rs. 10", "2.Coffee Rs. 25", "3.Dosa Rs. 50", "4.Fries Rs. 100", "5.Burger Rs. 125", "6.Pizza Rs. 175", "7.Softie Rs. 75", "8.Salad Rs. 35", "9.Coke Rs. 30", "10.Juice Rs. 20", "Escape: 0" }; int price[10] = {10, 25, 50, 100, 125, 275, 75, 35, 30, 20}; String order = "*"; boolean flag = false; //int counter = 0; // Connect keypad ROW0, ROW1, ROW2 and ROW3 to these Arduino pins. byte rowPins[ROWS] = { 2,3,4,5 }; // Connect keypad COL0, COL1 and COL2 to these Arduino pins. byte colPins[COLS] = { 6,7,8 }; // Create the Keypad Keypad kpd = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS ); void intro() { lcd.clear(); lcd.setCursor(0,0); lcd.print("Auto Order Taker"); lcd.setCursor(0,1); lcd.print("will take order!"); delay(3000); lcd.clear(); delay(10); lcd.setCursor(0,0); lcd.print(" Choose wisely!"); lcd.setCursor(0,1); lcd.print(" Don't be shy!"); delay(3000); lcd.clear(); delay(10); } void instructions() { lcd.clear(); lcd.setCursor(0,0); lcd.print("To start order:"); lcd.setCursor(0,1); lcd.print(" Press * "); delay(3000); lcd.clear(); delay(10); lcd.setCursor(0,0); lcd.print("To select item:"); lcd.setCursor(0,1); lcd.print(" Press 5 "); delay(3000); lcd.clear(); delay(10); lcd.setCursor(0,0); lcd.print("To see next:"); lcd.setCursor(0,1); lcd.print(" Press 6 "); delay(3000); lcd.clear(); delay(10); lcd.setCursor(0,0); lcd.print("To see previous:"); lcd.setCursor(0,1); lcd.print(" Press 4 "); delay(3000); lcd.clear(); delay(10); lcd.setCursor(0,0); lcd.print("To confirm order:"); lcd.setCursor(0,1); lcd.print(" Press # "); delay(3000); lcd.clear(); delay(10); lcd.setCursor(0,0); lcd.print("To delete order:"); lcd.setCursor(0,1); lcd.print(" Press 8 "); delay(3000); lcd.clear(); delay(10); } void displayMenu() { for(int i = 0; i< 11; i++) { key = NO_KEY; lcd.clear(); lcd.setCursor(0,0); lcd.print(menu[i]); lcd.setCursor(0,1); lcd.print("Next: 6|Prev: 4"); delay(100); while(key == NO_KEY) returnKey(); if(key == '6') { if(i == 10 ) i = -1; continue; } else if(key == '4') { if(i == 0) { i = -1; continue; } else { i -= 2; continue; } } else if(key == '5') { int temp=i+1; if(temp<10) { order += "0"; order += temp; } else order += temp; order += "*"; s += price[i]; Serial.println(order); lcd.clear(); lcd.setCursor(0,0); lcd.print(menu[i]); lcd.setCursor(0,1); lcd.print("Entered!"); delay(1000); lcd.clear(); delay(10); i -= 1; continue; } else if(key == '#') { order += "#"; lcd.clear(); lcd.setCursor(0,0); lcd.print("Order Accepted!"); lcd.setCursor(0,1); lcd.print("****************"); delay(2000); lcd.clear(); delay(10); Serial1.println(order); Serial.flush(); order = "*"; lcd.clear(); lcd.setCursor(0,0); lcd.print(" Total Cost: "); lcd.setCursor(0,1); lcd.print(s); delay(3000); lcd.clear(); delay(10); flag = true; if(flag == true) { flag = false; break; } break; } else if(key == '0') break; else if(key == '8') { order = "*"; lcd.clear(); lcd.setCursor(0,0); lcd.print(" Order Cleared! "); lcd.setCursor(0,1); lcd.print("****************"); delay(3000); lcd.clear(); delay(10); break; } else { errDisplay2(); i -= 1; continue; } lcd.clear(); delay(10); } } void errDisplay() { lcd.clear(); lcd.setCursor(0,0); lcd.print("Oops! Begin Your"); lcd.setCursor(0,1); lcd.print(" Order First! "); delay(3000); lcd.clear(); delay(10); } void errDisplay2() { lcd.clear(); lcd.setCursor(0,0); lcd.print("Oops!"); lcd.setCursor(0,1); lcd.print("Bad Choice!"); delay(3000); lcd.setCursor(0,0); lcd.print(" Try Again! "); lcd.setCursor(0,1); lcd.print("****************"); delay(3000); lcd.clear(); delay(10); } void setup() { //Serial for Serial Monitor Serial.begin(9600); //Serial for Bluetooth Serial1.begin(9600); //Pins of LCD Screen pinMode(32,OUTPUT); pinMode(33,OUTPUT); pinMode(34,OUTPUT); pinMode(35,OUTPUT); pinMode(36,OUTPUT); pinMode(37,OUTPUT); pinMode(52,OUTPUT); digitalWrite(52,HIGH); pinMode(53,OUTPUT); digitalWrite(53,HIGH); //Initializing the 16x2 LCD screen lcd.begin(16,2); intro(); }//End of setup() void loop() { returnKey(); if(key == NO_KEY) { //lcd.clear(); lcd.setCursor(0,0); lcd.print("Instructions: 1"); lcd.setCursor(0,1); lcd.print(" Start Order: * "); } else { switch(key) { case '1': key = NO_KEY; instructions(); break; case '*': key = NO_KEY; displayMenu(); break; case '#': key = NO_KEY; errDisplay(); break; case '4': key = NO_KEY; errDisplay(); break; case '6': key = NO_KEY; errDisplay(); break; case '5': key = NO_KEY; errDisplay(); break; case '0': key = NO_KEY; errDisplay(); break; default: key = NO_KEY; errDisplay2(); }//End of switch construct }//End of else condition } char returnKey() { key=kpd.getKey(); //storing pressed value in key variable return key; }
// file : liblava/app/app.hpp // copyright : Copyright (c) 2018-present, Lava Block OÜ // license : MIT; see accompanying LICENSE file #pragma once #include <liblava/frame.hpp> #include <liblava/block.hpp> #include <liblava/app/forward_shading.hpp> #include <liblava/app/camera.hpp> #include <liblava/app/gui.hpp> namespace lava { struct app : frame { struct config { bool save_window = true; bool auto_load = true; bool auto_save = true; seconds save_interval{ 300 }; bool v_sync = false; index physical_device = 0; lava::font font; }; explicit app(frame_config config); explicit app(name name, argh::parser cmd_line = {}); bool setup(); bool user_reload_requested = false; lava::window window; lava::input input; lava::gui gui; gui::config gui_config; device_ptr device = nullptr; lava::camera camera; lava::staging staging; lava::block block; renderer plotter; forward_shading shading; render_target::ptr target; lava::run_time run_time; using update_func = std::function<bool(delta)>; update_func on_update; using create_func = std::function<bool()>; create_func on_create; using destroy_func = std::function<void()>; destroy_func on_destroy; bool v_sync() const { return config.v_sync; } ui32 get_frame_counter() const { return frame_counter; } void draw_about(bool separator = true) const; config config; json_file config_file; using process_func = std::function<void(VkCommandBuffer, index)>; process_func on_process; id::ref block_cmd() const { return block_command; } private: void handle_config(); void handle_input(); void handle_window(); void update(); void render(); bool create_gui(); void destroy_gui(); bool create_target(); void destroy_target(); bool create_block(); void set_window_icon(); texture::ptr fonts; bool toggle_v_sync = false; ui32 frame_counter = 0; file_callback config_callback; id block_command; }; } // lava
#define HEATER_PIN 26 //A3/T1 #define TANK_PIN 19 //A6/JP6 #define SWITCH_PIN 22 //A7/JP7 #define RELAY_PIN 16 //D12/C #define TEMPERATURE_SAMPLES 5 // max adc: 305 #define NUMTEMPS 19 short temptable[NUMTEMPS][2] = { {1, 341}, {17, 150}, {33, 120}, {49, 103}, {65, 91}, {81, 81}, {97, 73}, {113, 66}, {129, 60}, {145, 54}, {161, 49}, {177, 43}, {193, 38}, {209, 32}, {225, 26}, {241, 20}, {257, 12}, {273, 3}, {289, -10} }; int read_thermistor(uint8_t sample_pin) { int raw = sample_temperature(sample_pin); int celsius = 0; byte i; for (i=1; i<NUMTEMPS; i++) { if (temptable[i][0] > raw) { celsius = temptable[i-1][1] + (raw - temptable[i-1][0]) * (temptable[i][1] - temptable[i-1][1]) / (temptable[i][0] - temptable[i-1][0]); if (celsius > 255) celsius = 255; break; } } // Overflow: We just clamp to 0 degrees celsius if (i == NUMTEMPS) celsius = 0; return celsius; } int sample_temperature(uint8_t pin) { int raw = 0; //read in a certain number of samples for (byte i=0; i<TEMPERATURE_SAMPLES; i++) raw += analogRead(pin); //average the samples raw = raw/TEMPERATURE_SAMPLES; //send it back. return raw; } void setup(){ pinMode(RELAY_PIN, OUTPUT); pinMode(SWITCH_PIN, INPUT); pinMode(HEATER_PIN, INPUT); pinMode(TANK_PIN, INPUT); } int main(){ if (read_thermistor(TANK_PIN) < 50 and read_thermistor(HEATER_PIN) > 40) { // 50 degrees C, 120 F digitalWrite(RELAY_PIN, HIGH); } else { digitalWrite(RELAY_PIN, LOW); } // if (digitalRead(SWITCH_PIN == LOW) { digitalWrite(RELAY_PIN, HIGH); } delay(1000); }
// bodymove.cpp : Defines the Body Motion Actions // #include "stdafx.h" #include "bodymove.h" #include "freewilltools.h" #define _USE_MATH_DEFINES #include <math.h> #define DEG2RAD(d) ( (d) * (FWFLOAT)M_PI / 180.0f ) #define RAD2DEG(r) ( 180.0f * (r) / (FWFLOAT)M_PI ) /////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////// // Class CActionBend CActionBend::CActionBend() : m_pBody(NULL) { } CActionBend::~CActionBend() { if (m_pBody) m_pBody->Release(); } HRESULT CActionBend::HandleEvent(struct ACTION_EVENT *pEvent) { if (pEvent->nEvent == EVENT_TICK) { } return S_OK; } HRESULT CActionBend::Create(IFWCreateContext *p) { HRESULT h; IFWEnumParams *pEnum = NULL; p->EnumParams(&pEnum); // params: std & body FWFLOAT fAngle1, fAngle2; try { h = QueryStdParams(pEnum); if (FAILED(h)) throw(h); h = pEnum->QueryPBODY(IID_IBody, (FWPUNKNOWN*)&m_pBody); if (FAILED(h)) throw(h); h = pEnum->QueryFLOAT(&fAngle1); if (FAILED(h)) fAngle1 = DEG2RAD(50); h = pEnum->QueryFLOAT(&fAngle2); if (FAILED(h)) fAngle2 = 0; } catch (HRESULT h) { return ErrorStdParams(pEnum, h); } // create transform IAction *pAction = NULL; ITransform *pT, *pX; m_pBody->CreateCompatibleTransform(&pT); m_pBody->CreateCompatibleTransform(&pX); // plan lower level actions pT->FromRotationZ(fAngle1); {CParam params[] = { this, m_nStartTime, m_nPeriod, m_pBody, BODY_SPINE, pT }; FWDevice()->CreateObjectEx(L"Action", L"Rotate", sizeof(params)/sizeof(FWPARAM), params, IID_IAction, (IFWUnknown**)&pAction);} pAction->Release(); pT->FromRotationZ(-fAngle2); pX->FromRotationZ(fAngle2); { CParam params[] = { this, m_nStartTime, m_nPeriod, m_pBody, BODY_PELVIS, BODY_FOOT + BODY_LEFT, pT, BODY_LEG + BODY_LEFT, pX }; FWDevice()->CreateObjectEx(L"Action", L"RotateInv", sizeof(params)/sizeof(FWPARAM), params, IID_IAction, (IFWUnknown**)&pAction); } pAction->Release(); pT->FromRotationZ(fAngle2); {CParam params[] = { this, m_nStartTime, m_nPeriod, m_pBody, BODY_LEG + BODY_RIGHT, pT }; FWDevice()->CreateObjectEx(L"Action", L"Rotate", sizeof(params)/sizeof(FWPARAM), params, IID_IAction, (IFWUnknown**)&pAction);} pAction->Release(); pT->FromRotationZ(-fAngle2); {CParam params[] = { this, m_nStartTime, m_nPeriod, m_pBody, BODY_FOOT + BODY_RIGHT, pT }; FWDevice()->CreateObjectEx(L"Action", L"Rotate", sizeof(params)/sizeof(FWPARAM), params, IID_IAction, (IFWUnknown**)&pAction);} pAction->Release(); pT->Release(); pX->Release(); pEnum->Release(); return S_OK; } /////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////// // Class CActionSquat CActionSquat::CActionSquat() : m_pBody(NULL) { } CActionSquat::~CActionSquat() { if (m_pBody) m_pBody->Release(); } HRESULT CActionSquat::HandleEvent(struct ACTION_EVENT *pEvent) { if (pEvent->nEvent == EVENT_TICK) { } return S_OK; } HRESULT CActionSquat::Create(IFWCreateContext *p) { HRESULT h; IFWEnumParams *pEnum = NULL; p->EnumParams(&pEnum); // params: std & body FWFLOAT fAngle1, fAngle2, fAngle3; try { h = QueryStdParams(pEnum); if (FAILED(h)) throw(h); h = pEnum->QueryPBODY(IID_IBody, (FWPUNKNOWN*)&m_pBody); if (FAILED(h)) throw(h); h = pEnum->QueryFLOAT(&fAngle1); if (FAILED(h)) fAngle1 = DEG2RAD(50); h = pEnum->QueryFLOAT(&fAngle2); if (FAILED(h)) fAngle2 = DEG2RAD(8); h = pEnum->QueryFLOAT(&fAngle3); if (FAILED(h)) fAngle3 = DEG2RAD(30); } catch (HRESULT h) { return ErrorStdParams(pEnum, h); } // create transform IAction *pAction = NULL; ITransform *pT, *pX, *pY; m_pBody->CreateCompatibleTransform(&pT); m_pBody->CreateCompatibleTransform(&pX); m_pBody->CreateCompatibleTransform(&pY); // plan lower level actions pT->FromRotationZ(fAngle1); {CParam params[] = { this, m_nStartTime, m_nPeriod, m_pBody, BODY_SPINE, pT }; FWDevice()->CreateObjectEx(L"Action", L"Rotate", sizeof(params)/sizeof(FWPARAM), params, IID_IAction, (IFWUnknown**)&pAction);} pAction->Release(); // PROBLEM!!! CURRENT VERSION DOES NOT ACCEPT 3 LIMBS pT->FromRotationZ(fAngle3 - fAngle2); pX->FromRotationZ(-fAngle3-fAngle3); pY->FromRotationZ(fAngle3 + fAngle2); { CParam params[] = { this, m_nStartTime, m_nPeriod, m_pBody, BODY_PELVIS, BODY_FOOT + BODY_LEFT, pT, BODY_LEG + 1 + BODY_LEFT, pX, BODY_LEG + BODY_LEFT, pY }; FWDevice()->CreateObjectEx(L"Action", L"RotateInv", sizeof(params)/sizeof(FWPARAM), params, IID_IAction, (IFWUnknown**)&pAction); } pAction->Release(); pT->FromRotationZ(fAngle2 + fAngle3); {CParam params[] = { this, m_nStartTime, m_nPeriod, m_pBody, BODY_LEG + BODY_RIGHT, pT }; FWDevice()->CreateObjectEx(L"Action", L"Rotate", sizeof(params)/sizeof(FWPARAM), params, IID_IAction, (IFWUnknown**)&pAction);} pAction->Release(); pT->FromRotationZ(-fAngle3 - fAngle3); {CParam params[] = { this, m_nStartTime, m_nPeriod, m_pBody, BODY_LEG + 1 + BODY_RIGHT, pT }; FWDevice()->CreateObjectEx(L"Action", L"Rotate", sizeof(params)/sizeof(FWPARAM), params, IID_IAction, (IFWUnknown**)&pAction);} pAction->Release(); pT->FromRotationZ(-fAngle2 + fAngle3); {CParam params[] = { this, m_nStartTime, m_nPeriod, m_pBody, BODY_FOOT + BODY_RIGHT, pT }; FWDevice()->CreateObjectEx(L"Action", L"Rotate", sizeof(params)/sizeof(FWPARAM), params, IID_IAction, (IFWUnknown**)&pAction);} pAction->Release(); pT->Release(); pX->Release(); pY->Release(); pEnum->Release(); return S_OK; } /////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////// // Class CActionSwing CActionSwing::CActionSwing() : m_pBody(NULL) { } CActionSwing::~CActionSwing() { if (m_pBody) m_pBody->Release(); } HRESULT CActionSwing::HandleEvent(struct ACTION_EVENT *pEvent) { if (pEvent->nEvent == EVENT_TICK) { } return S_OK; } HRESULT CActionSwing::Create(IFWCreateContext *p) { HRESULT h; IFWEnumParams *pEnum = NULL; p->EnumParams(&pEnum); // params: std & body FWFLOAT fAngle1, fAngle2; try { h = QueryStdParams(pEnum); if (FAILED(h)) throw(h); h = pEnum->QueryPBODY(IID_IBody, (FWPUNKNOWN*)&m_pBody); if (FAILED(h)) throw(h); h = pEnum->QueryFLOAT(&fAngle1); if (FAILED(h)) fAngle1 = DEG2RAD(40); h = pEnum->QueryFLOAT(&fAngle2); if (FAILED(h)) fAngle2 = fAngle1 * 3 / 4; } catch (HRESULT h) { return ErrorStdParams(pEnum, h); } // create transform IAction *pAction = NULL; ITransform *pT; m_pBody->CreateCompatibleTransform(&pT); pT->FromRotationZ(fAngle1); {CParam params[] = { this, m_nStartTime, m_nPeriod, m_pBody, BODY_SPINE, pT }; FWDevice()->CreateObjectEx(L"Action", L"Rotate", sizeof(params)/sizeof(FWPARAM), params, IID_IAction, (IFWUnknown**)&pAction);} pAction->Release(); pT->FromRotationZ(-fAngle2); {CParam params[] = { this, m_nStartTime, m_nPeriod, m_pBody, BODY_LEG + BODY_RIGHT, pT }; FWDevice()->CreateObjectEx(L"Action", L"Rotate", sizeof(params)/sizeof(FWPARAM), params, IID_IAction, (IFWUnknown**)&pAction);} pAction->Release(); pT->Release(); pEnum->Release(); return S_OK; }
#pragma once #include "QtSql\qsqldatabase.h" class StoryDB { public: static bool init(); static QSqlQuery doQuery(const QString &query); private: static bool bInitialized; };
#include"Header.h" void GSF(cx_mat * TI,cx_mat * TIp,ofstream & Fidelity,ofstream &Nonlocal,ofstream &OrderFile,ofstream &Spectrum ,ofstream&VNE,double&J,ofstream&Nonlocal1) { int Xl=Xi[1]; cx_mat Help0; cx_mat Help1; cx_mat Help2; Help0=trans(TIp[0])*TI[0]; complex<double> s; s=0; s=Help0(0,0); Fidelity<<setprecision (15)<<" "<<abs(s)<<endl; double Myorder; /*******************************************************/ complex<double> img(0,1); cx_mat PZ(2,2); PZ.zeros(); PZ(0,0)=1; PZ(1,1)=-1; cx_mat PI(2,2); PI.eye(2,2); cx_mat PX(2,2); PX.zeros(); PX(0,1)=1; PX(1,0)=1; cx_mat PY(2,2); PY.zeros(); PY(0,1)=-img; PY(1,0)=img; PX=0.5*PX; PZ=0.5*PZ; PY=0.5*PY; /***************************************************************/ cx_mat * o1=new cx_mat[1]; cx_mat * o2=new cx_mat[1]; cx_mat * o3=new cx_mat[1]; cx_mat * o1X=new cx_mat[1]; cx_mat * o2X=new cx_mat[1]; cx_mat * o3X=new cx_mat[1]; cx_mat *IHelp=new cx_mat[1]; o1[0]=kron(kron(PZ,PI),kron(PI,PI))-kron(kron(PI,PZ),kron(PI,PI))+ kron(kron(PI,PI),kron(PZ,PI))-kron(kron(PI,PI),kron(PI,PZ)); o2[0]=kron(kron(PZ,PI),kron(PI,PI))+kron(kron(PI,PZ),kron(PI,PI))+ kron(kron(PI,PI),kron(PZ,PI))+kron(kron(PI,PI),kron(PI,PZ)); o3[0]=kron(kron(PI,PI),kron(PI,PI)); o1X[0]=kron(kron(PX,PI),kron(PI,PI))+kron(kron(PI,PX),kron(PI,PI))+ kron(kron(PI,PI),kron(PX,PI))+kron(kron(PI,PI),kron(PI,PX)); o3X[0]=kron(kron(PI,PI),kron(PI,PI)); /****************************************************/ /*******************************Magnetization**************************/ int iS=0; int jS=1; IHelp[0]=TI[0]; RefreshT2site( o1X,o3X, IHelp, iS,jS); Help0=trans(TI[0])*IHelp[0]; iS=1; jS=0; IHelp[0]=TI[0]; RefreshT2site( o1X,o3X, IHelp, iS,jS); Help0=trans(TI[0])*IHelp[0]+Help0; iS=2; jS=0; IHelp[0]=TI[0]; RefreshT2site( o1X,o3X, IHelp, iS,jS); Help0=trans(TI[0])*IHelp[0]+Help0; iS=3; jS=0; IHelp[0]=TI[0]; RefreshT2site( o1X,o3X, IHelp, iS,jS); Help0=trans(TI[0])*IHelp[0]+Help0; VNE<<" "<<real(Help0(0,0)/16.00); cout<< "Magnetization=" <<real(Help0(0,0)/16.00)<<" "; double DerivativeX=real(Help0(0,0)/16.00); /**********************************************************************/ /*******************************MagnetizationDerivative**************************/ iS=0; jS=1; IHelp[0]=TIp[0]; RefreshT2site( o1X,o3X, IHelp, iS,jS); Help0=trans(TIp[0])*IHelp[0]; iS=1; jS=0; IHelp[0]=TIp[0]; RefreshT2site( o1X,o3X, IHelp, iS,jS); Help0=trans(TIp[0])*IHelp[0]+Help0; iS=2; jS=0; IHelp[0]=TIp[0]; RefreshT2site( o1X,o3X, IHelp, iS,jS); Help0=trans(TIp[0])*IHelp[0]+Help0; iS=3; jS=0; IHelp[0]=TIp[0]; RefreshT2site( o1X,o3X, IHelp, iS,jS); Help0=trans(TIp[0])*IHelp[0]+Help0; DerivativeX=(abs(DerivativeX)-abs(real(Help0(0,0)/16.00)))*(1.00/DeltaFidelity); VNE<<setprecision (15)<<" "<<abs(DerivativeX); cout<< "DerivativeMagnetization=" <<abs(DerivativeX)<<" "; /**********************CorrelationZZ************************************************/ o1X[0]=kron(kron(PZ,PZ),kron(PI,PI)); for(int i=0;i<4;i++){ iS=i; jS=(i+1)%(4); IHelp[0]=TI[0]; RefreshT2site( o1X,o3X, IHelp, iS,jS); Help0=trans(TI[0])*IHelp[0]; VNE<<" "<<real(Help0(0,0)); } o1X[0]=kron(kron(PI,PI),kron(PZ,PZ)); for(int i=0;i<4;i++){ iS=i; jS=(i+1)%(4); IHelp[0]=TI[0]; RefreshT2site( o1X,o3X, IHelp, iS,jS); Help0=trans(TI[0])*IHelp[0]; VNE<<" "<<real(Help0(0,0)); } o1[0]=kron(kron(PI,PZ),kron(PI,PI)); o2[0]=kron(kron(PZ,PI),kron(PI,PI)); iS=0; jS=1; IHelp[0]=TI[0]; RefreshT2site( o1,o2, IHelp, iS,jS); Help0=trans(TI[0])*IHelp[0]; VNE<<" "<<real(Help0(0,0)); o1[0]=kron(kron(PI,PI),kron(PI,PZ)); o2[0]=kron(kron(PI,PI),kron(PZ,PI)); iS=0; jS=1; IHelp[0]=TI[0]; RefreshT2site( o1,o2, IHelp, iS,jS); Help0=trans(TI[0])*IHelp[0]; VNE<<" "<<real(Help0(0,0)); o1[0]=kron(kron(PI,PZ),kron(PI,PI)); o2[0]=kron(kron(PZ,PI),kron(PI,PI)); iS=2; jS=3; IHelp[0]=TI[0]; RefreshT2site( o1,o2, IHelp, iS,jS); Help0=trans(TI[0])*IHelp[0]; VNE<<" "<<real(Help0(0,0)); o1[0]=kron(kron(PI,PI),kron(PI,PZ)); o2[0]=kron(kron(PI,PI),kron(PZ,PI)); iS=2; jS=3; IHelp[0]=TI[0]; RefreshT2site( o1,o2, IHelp, iS,jS); Help0=trans(TI[0])*IHelp[0]; VNE<<" "<<real(Help0(0,0)); o1[0]=kron(kron(PI,PI),kron(PZ,PI)); o2[0]=kron(kron(PZ,PI),kron(PI,PI)); iS=0; jS=2; IHelp[0]=TI[0]; RefreshT2site( o1,o2, IHelp, iS,jS); Help0=trans(TI[0])*IHelp[0]; VNE<<" "<<real(Help0(0,0)); o1[0]=kron(kron(PI,PI),kron(PI,PZ)); o2[0]=kron(kron(PI,PZ),kron(PI,PI)); iS=0; jS=2; IHelp[0]=TI[0]; RefreshT2site( o1,o2, IHelp, iS,jS); Help0=trans(TI[0])*IHelp[0]; VNE<<" "<<real(Help0(0,0)); o1[0]=kron(kron(PI,PI),kron(PZ,PI)); o2[0]=kron(kron(PZ,PI),kron(PI,PI)); iS=1; jS=3; IHelp[0]=TI[0]; RefreshT2site( o1,o2, IHelp, iS,jS); Help0=trans(TI[0])*IHelp[0]; VNE<<" "<<real(Help0(0,0)); o1[0]=kron(kron(PI,PI),kron(PI,PZ)); o2[0]=kron(kron(PI,PZ),kron(PI,PI)); iS=1; jS=3; IHelp[0]=TI[0]; RefreshT2site( o1,o2, IHelp, iS,jS); Help0=trans(TI[0])*IHelp[0]; VNE<<" "<<real(Help0(0,0)); o1X[0]=kron(kron(PZ,PI),kron(PZ,PI)); for(int i=0;i<4;i++){ iS=i; jS=(i+1)%(4); IHelp[0]=TI[0]; RefreshT2site( o1X,o3X, IHelp, iS,jS); Help0=trans(TI[0])*IHelp[0]; VNE<<" "<<real(Help0(0,0)); } o1X[0]=kron(kron(PI,PZ),kron(PI,PZ)); for(int i=0;i<4;i++){ iS=i; jS=(i+1)%(4); IHelp[0]=TI[0]; RefreshT2site( o1X,o3X, IHelp, iS,jS); Help0=trans(TI[0])*IHelp[0]; VNE<<" "<<real(Help0(0,0)); } /*************************************g*g*******************************/ o1[0]=kron(kron(PX,PX),kron(PX,PX))*(16.00); o2[0]=o1[0]; iS=0; jS=1; IHelp[0]=TI[0]; RefreshT2site( o1,o2, IHelp, iS,jS); iS=2; jS=3; RefreshT2site( o1,o2, IHelp, iS,jS); Help0=trans(TI[0])*IHelp[0]; VNE<<" "<<real(Help0(0,0)/1.00); cout<< "SymmetryX="<<real(Help0(0,0)/1.00)<<endl; /*********************************************************************/ if(Xl<=70){ cx_mat Spectrum1(Xl*Xl,Xl*Xl); for(int i=0;i<Xl;i++) for(int j=0;j<Xl;j++) for(int m=0;m<Xl;m++) for(int n=0;n<Xl;n++) Spectrum1(i*Xl+j,m*Xl+n)=TI[0](i*Xl*Xl*Xl+j*Xl*Xl+m*Xl+n,0); cx_mat U; cx_mat V; vec s0; svd_econ(U, s0, V, Spectrum1,'b',"std"); vec NVecH=pow(s0,2); if(Xl>=15){ for(int i=0;i<100;i++) Spectrum<<J<<" "<<setprecision(15)<<NVecH(i)<<endl; Spectrum<<endl<<endl;} double nsun=0; for(int i=0;i<Xl*Xl;i++){ if(NVecH(i)>1.0e-15) nsun=(-NVecH(i)*((log(NVecH(i)))/log(2)))+nsun; } VNE<<setprecision(15)<<" "<<nsun<<endl<<endl; } delete [] o1; delete [] o2; delete [] o3; delete [] o1X; delete [] o2X; delete [] o3X; delete [] IHelp; }
#pragma once #include <string> #include <unordered_map> #include <algorithm> #include <vector> #include <iostream> enum HTTPMETHOD { HTTPMETHOD_GET_COMMON, HTTPMETHOD_POST, HTTPMETHOD_OTHER, HTTPMETHOD_GET_PARAERROR }; struct httpMethodStr { HTTPMETHOD httpMethod; std::string dir; std::unordered_map<std::string, std::string> contentPairs; httpMethodStr(HTTPMETHOD h = HTTPMETHOD::HTTPMETHOD_OTHER, std::string d = "", std::unordered_map<std::string, std::string> cP = {}) { httpMethod = h; dir = d; contentPairs = cP; } //==ÔËËã·ûÖØÔØ bool operator==(const httpMethodStr &hms) { return (this->httpMethod == hms.httpMethod && this->dir == hms.dir && this->contentPairs == hms.contentPairs ); } }; httpMethodStr parserFirstLine(std::string input); void parserFirstLineTest(void);