/** The default constructor * * \param parent The parent widget * */ RainbruRPG::Gui::QuarantineList::QuarantineList(QWidget* parent) :QWidget(parent){ setWindowTitle(tr("Quarantine")); setMinimumSize(500, 150); // The main layout QVBoxLayout* vb1=new QVBoxLayout(); this->setLayout(vb1); // The tool bar QToolBar* toolBar=new QToolBar(this); // toolBar->setToolButtonStyle(Qt::ToolButtonTextOnly); previewAct=new QAction(QIcon(":/images/preview.png"), tr("Preview"), toolBar); approveAct=new QAction(QIcon(":/images/accept.png"), tr("Approve"), toolBar); deleteAct=new QAction(QIcon(":/images/refuse.png"), tr("Delete"), toolBar); QAction* refreshAct=new QAction(tr("Refresh"), toolBar); QAction* helpAct=new QAction(tr("Help"), toolBar); previewAct->setEnabled(false); approveAct->setEnabled(false); deleteAct->setEnabled(false); toolBar->addAction(previewAct); toolBar->addAction(approveAct); toolBar->addAction(deleteAct); toolBar->addSeparator(); toolBar->addAction(refreshAct); toolBar->addSeparator(); toolBar->addAction(helpAct); vb1->addWidget(toolBar); labStillInTransfer=new QLabel("At least one file is still in transfer, it's size and its type " "could be wrong. You can click the refresh button to update " "informations and look at FTP server (Ctrl+F) to see if the " "transfer is finished."); labStillInTransfer->setVisible(false); labStillInTransfer->setWordWrap(true); vb1->addWidget(labStillInTransfer); // The list widget tree=new QTreeWidget(); tree->setSortingEnabled(true); tree->setSelectionMode(QAbstractItemView::ExtendedSelection); QStringList header; header << tr("Filename") << tr("Size") << tr("Usage") << tr("Type"); tree->setColumnCount(4); tree->setHeaderLabels(header); vb1->addWidget(tree); refresh(); connect(tree, SIGNAL(itemSelectionChanged()), this, SLOT(treeSelectionChanged())); connect(tree, SIGNAL(itemDoubleClicked(QTreeWidgetItem*,int)), this, SLOT(treeDoubleClicked(QTreeWidgetItem*,int))); connect(previewAct, SIGNAL(triggered()), this, SLOT(filePreview())); connect(approveAct, SIGNAL(triggered()), this, SLOT(fileAccept())); connect(deleteAct, SIGNAL(triggered()), this, SLOT(fileRefused())); connect(refreshAct, SIGNAL(triggered()), this, SLOT(refresh())); connect(helpAct, SIGNAL(triggered()), this, SLOT(showHelp())); }
dialog::RESULT textInput::run() { if (!init(size_)) { return dialog::R_NCREAT; } refresh(); bool cont = true; keyMapping::KEYLABEL label = keyMapping::K_UNDEF; t_uint key = 0; while (cont) { key = readAnyKey(); if (!handleKeyboard(key, label)) { // Got something that is not recognized as one of // the keys that are used. enterKey(key); continue; } switch (label) { case keyMapping::K_QUITSCREEN: { cont = false; break; } case keyMapping::K_HELP: { if (showHelp()) { // Resized. return dialog::R_RESIZE; } refresh(); break; } case keyMapping::K_DELETE: { deleteCurrent(); refresh(); break; } case keyMapping::K_SELECT: { // Done setting session name. cont = false; text_entered = true; break; } case keyMapping::K_RESIZE: { return dialog::R_RESIZE; break; } default: { refresh(); break; } } } return dialog::R_QUIT; }
bool parseCommand(int argc, SAP_UC ** argv, OPTIONS* options) { if( argc < 2 || !strcmpU(argv[1], cU("-help")) || !strcmpU(argv[1], cU("-?"))) { showHelp(); return false; } else if(!strcmpU(argv[1], cU("-v"))) { showVersion(); return false; } int i = 1; const SAP_UC * const PATHNAME = cU("PATHNAME="); const SAP_UC * const PORT = cU("PORT="); const size_t PATHNAME_LEN = 9; const size_t PORT_LEN =5; while(i < argc) { const SAP_UC ch1 = argv[i][0]; const SAP_UC ch2 = argv[i++][1]; if(ch1 == cU('-') && ch2) // we found an option { if(ch2 == cU('t')) { options->trace = 1; continue; } else if(ch2 == cU('i')) { options->showSysInfo = true; continue; } if(i > argc - 1 || argv[i][0] == cU('-')) { continue; } switch (ch2) { case cU('h'): options->ashost = argv[i++]; break; case cU('s'): options->sysnr = argv[i++]; break; case cU('u'): options->user = argv[i++]; break; case cU('p'): options->passwd = argv[i++]; break; case cU('c'): options->client = argv[i++]; break; case cU('l'): options->language = argv[i++]; break; case cU('D'): options->dest = argv[i++]; break; case cU('F'): options->function = argv[i++]; break; case cU('E'): { const SAP_UC *param = argv[i++]; if(!strncmpU(param, PATHNAME, PATHNAME_LEN)) { options->path = param + PATHNAME_LEN; } else if(!strncmpU(param, PORT, PORT_LEN)) { options->port = param + PORT_LEN; } } break; default: i++; break; } } } return true; }
int main(int argc, char* argv[]) { char hostName[200] = DEFAULT_HOSTNAME; int port = DEFAULT_RESMGR_TPM_PORT; //DEFAULT_TPM_PORT; TPMI_RH_PROVISION auth = TPM_RH_NULL; TPMI_DH_OBJECT objectHandle; TPMI_DH_OBJECT persistentHandle; setbuf(stdout, NULL); setvbuf (stdout, NULL, _IONBF, BUFSIZ); int opt = -1; const char *optstring = "hvA:H:S:P:p:d:c:"; static struct option long_options[] = { {"help",0,NULL,'h'}, {"version",0,NULL,'v'}, {"auth",1,NULL,'A'}, {"handle",1,NULL,'H'}, {"persistent",1,NULL,'S'}, {"pwda",1,NULL,'P'}, {"port",1,NULL,'p'}, {"debugLevel",1,NULL,'d'}, {"context",1,NULL,'c'}, {0,0,0,0} }; int returnVal = 0; int flagCnt = 0; int h_flag = 0, v_flag = 0, A_flag = 0, H_flag = 0, S_flag = 0, c_flag = 0, P_flag = 0; char *contextFile = NULL; if(argc == 1) { showHelp(argv[0]); return 0; } while((opt = getopt_long(argc,argv,optstring,long_options,NULL)) != -1) { switch(opt) { case 'h': h_flag = 1; break; case 'v': v_flag = 1; break; case 'A': if(strcmp(optarg,"o") == 0 || strcmp(optarg,"O") == 0) auth = TPM_RH_OWNER; else if(strcmp(optarg,"p") == 0 || strcmp(optarg,"P") == 0) auth = TPM_RH_PLATFORM; else { printf("ERROR: auth '%s' not supported!\n", optarg); returnVal = -1; break; } A_flag = 1; break; case 'H': if(getSizeUint32Hex(optarg, &objectHandle) != 0) { returnVal = -2; break; } printf("\nobjecttHanlde: 0x%x\n\n",objectHandle); H_flag = 1; break; case 'S': if(getSizeUint32Hex(optarg, &persistentHandle) != 0) { returnVal = -3; break; } printf("\npersistentHanlde: 0x%x\n\n",persistentHandle); S_flag = 1; break; case 'P': if( optarg == NULL || (strlen(optarg) >= sizeof(TPMU_HA)) ) { printf("\nPlease input the authenticating password(optional,no more than %d characters).\n", (int)sizeof(TPMU_HA)-1); returnVal = -4; break; } if( strlen(optarg) > 0 ) { sessionData.hmac.t.size = strlen(optarg); safeStrNCpy( (char *)&sessionData.hmac.t.buffer[0], optarg, sizeof(sessionData.hmac.t.buffer) ); } P_flag = 1; break; case 'p': if( getPort(optarg, &port) ) { printf("Incorrect port number.\n"); returnVal = -5; } break; case 'd': if( getDebugLevel(optarg, &debugLevel) ) { printf("Incorrect debug level.\n"); returnVal = -6; } break; case 'c': contextFile = optarg; if(contextFile == NULL || contextFile[0] == '\0') { returnVal = -7; break; } printf("contextFile = %s\n", contextFile); c_flag = 1; break; case ':': // printf("Argument %c needs a value!\n",optopt); returnVal = -8; break; case '?': // printf("Unknown Argument: %c\n",optopt); returnVal = -9; break; //default: // break; } if(returnVal) break; }; if(returnVal != 0) return returnVal; flagCnt = h_flag + v_flag + A_flag + H_flag + S_flag + c_flag; if(flagCnt == 1) { if(h_flag == 1) showHelp(argv[0]); else if(v_flag == 1) showVersion(argv[0]); else { showArgMismatch(argv[0]); return -10; } } else if(flagCnt == 3 && A_flag == 1 && (H_flag == 1 || c_flag) && S_flag == 1) { prepareTest(hostName, port, debugLevel); if(c_flag) returnVal = loadTpmContextFromFile(sysContext, &objectHandle, contextFile); if (returnVal == 0) returnVal = evictControl(auth, objectHandle, persistentHandle, P_flag); finishTest(); if(returnVal) return -11; } else { showArgMismatch(argv[0]); return -12; } return 0; }
int main(int argc, char *argv[]) { parseCommandLine (argc, argv); pcl::PointCloud<PointType>::Ptr model (new pcl::PointCloud<PointType> ()); pcl::PointCloud<PointType>::Ptr model_keypoints (new pcl::PointCloud<PointType> ()); pcl::PointCloud<PointType>::Ptr scene (new pcl::PointCloud<PointType> ()); pcl::PointCloud<PointType>::Ptr scene_keypoints (new pcl::PointCloud<PointType> ()); pcl::PointCloud<NormalType>::Ptr model_normals (new pcl::PointCloud<NormalType> ()); pcl::PointCloud<NormalType>::Ptr scene_normals (new pcl::PointCloud<NormalType> ()); pcl::PointCloud<DescriptorType>::Ptr model_descriptors (new pcl::PointCloud<DescriptorType> ()); pcl::PointCloud<DescriptorType>::Ptr scene_descriptors (new pcl::PointCloud<DescriptorType> ()); // // Load clouds // if (pcl::io::loadPCDFile (model_filename_, *model) < 0) { std::cout << "Error loading model cloud." << std::endl; showHelp (argv[0]); return (-1); } std::cout << "density " << model->is_dense << std::endl; pcl::PointCloud<PointType>::Ptr model_filtered (new pcl::PointCloud<PointType>()); std::vector<int> filter_index; pcl::removeNaNFromPointCloud (*model, *model_filtered, filter_index); model = model_filtered; if (pcl::io::loadPCDFile (scene_filename_, *scene) < 0) { std::cout << "Error loading scene cloud." << std::endl; showHelp (argv[0]); return (-1); } // // Set up resolution invariance // if (use_cloud_resolution_) { float resolution = static_cast<float> (computeCloudResolution (model)); if (resolution != 0.0f) { model_ss_ *= resolution; scene_ss_ *= resolution; rf_rad_ *= resolution; descr_rad_ *= resolution; cg_size_ *= resolution; } std::cout << "Model resolution: " << resolution << std::endl; } std::cout << "Model sampling size: " << model_ss_ << std::endl; std::cout << "Scene sampling size: " << scene_ss_ << std::endl; std::cout << "LRF support radius: " << rf_rad_ << std::endl; std::cout << "SHOT descriptor radius: " << descr_rad_ << std::endl; std::cout << "Clustering bin size: " << cg_size_ << std::endl << std::endl; // // Compute Normals // pcl::NormalEstimationOMP<PointType, NormalType> norm_est; norm_est.setKSearch (10); norm_est.setInputCloud (model); norm_est.compute (*model_normals); norm_est.setInputCloud (scene); norm_est.compute (*scene_normals); // // Downsample Clouds to Extract keypoints // pcl::PointCloud<int> sampled_indices; pcl::UniformSampling<PointType> uniform_sampling; uniform_sampling.setInputCloud (model); uniform_sampling.setRadiusSearch (model_ss_); uniform_sampling.compute (sampled_indices); pcl::copyPointCloud (*model, sampled_indices.points, *model_keypoints); std::cout << "Model total points: " << model->size () << "; Selected Keypoints: " << model_keypoints->size () << std::endl; uniform_sampling.setInputCloud (scene); uniform_sampling.setRadiusSearch (scene_ss_); uniform_sampling.compute (sampled_indices); pcl::copyPointCloud (*scene, sampled_indices.points, *scene_keypoints); std::cout << "Scene total points: " << scene->size () << "; Selected Keypoints: " << scene_keypoints->size () << std::endl; // // Compute Descriptor for keypoints // pcl::SHOTEstimationOMP<PointType, NormalType, DescriptorType> descr_est; descr_est.setRadiusSearch (descr_rad_); descr_est.setInputCloud (model_keypoints); descr_est.setInputNormals (model_normals); descr_est.setSearchSurface (model); descr_est.compute (*model_descriptors); descr_est.setInputCloud (scene_keypoints); descr_est.setInputNormals (scene_normals); descr_est.setSearchSurface (scene); descr_est.compute (*scene_descriptors); // // Find Model-Scene Correspondences with KdTree // pcl::CorrespondencesPtr model_scene_corrs (new pcl::Correspondences ()); pcl::KdTreeFLANN<DescriptorType> match_search; match_search.setInputCloud (model_descriptors); // For each scene keypoint descriptor, find nearest neighbor into the model keypoints descriptor cloud and add it to the correspondences vector. for (size_t i = 0; i < scene_descriptors->size (); ++i) { std::vector<int> neigh_indices (1); std::vector<float> neigh_sqr_dists (1); if (!pcl_isfinite (scene_descriptors->at (i).descriptor[0])) //skipping NaNs { continue; } int found_neighs = match_search.nearestKSearch (scene_descriptors->at (i), 1, neigh_indices, neigh_sqr_dists); if(found_neighs == 1 && neigh_sqr_dists[0] < 0.25f) // add match only if the squared descriptor distance is less than 0.25 (SHOT descriptor distances are between 0 and 1 by design) { pcl::Correspondence corr (neigh_indices[0], static_cast<int> (i), neigh_sqr_dists[0]); model_scene_corrs->push_back (corr); } } std::cout << "Correspondences found: " << model_scene_corrs->size () << std::endl; // // Actual Clustering // std::vector<Eigen::Matrix4f, Eigen::aligned_allocator<Eigen::Matrix4f> > rototranslations; std::vector<pcl::Correspondences> clustered_corrs; // Using Hough3D if (use_hough_) { // // Compute (Keypoints) Reference Frames only for Hough // pcl::PointCloud<RFType>::Ptr model_rf (new pcl::PointCloud<RFType> ()); pcl::PointCloud<RFType>::Ptr scene_rf (new pcl::PointCloud<RFType> ()); pcl::BOARDLocalReferenceFrameEstimation<PointType, NormalType, RFType> rf_est; rf_est.setFindHoles (true); rf_est.setRadiusSearch (rf_rad_); rf_est.setInputCloud (model_keypoints); rf_est.setInputNormals (model_normals); rf_est.setSearchSurface (model); rf_est.compute (*model_rf); rf_est.setInputCloud (scene_keypoints); rf_est.setInputNormals (scene_normals); rf_est.setSearchSurface (scene); rf_est.compute (*scene_rf); // Clustering pcl::Hough3DGrouping<PointType, PointType, RFType, RFType> clusterer; clusterer.setHoughBinSize (cg_size_); clusterer.setHoughThreshold (cg_thresh_); clusterer.setUseInterpolation (true); clusterer.setUseDistanceWeight (false); clusterer.setInputCloud (model_keypoints); clusterer.setInputRf (model_rf); clusterer.setSceneCloud (scene_keypoints); clusterer.setSceneRf (scene_rf); clusterer.setModelSceneCorrespondences (model_scene_corrs); //clusterer.cluster (clustered_corrs); clusterer.recognize (rototranslations, clustered_corrs); } else // Using GeometricConsistency { pcl::GeometricConsistencyGrouping<PointType, PointType> gc_clusterer; gc_clusterer.setGCSize (cg_size_); gc_clusterer.setGCThreshold (cg_thresh_); gc_clusterer.setInputCloud (model_keypoints); gc_clusterer.setSceneCloud (scene_keypoints); gc_clusterer.setModelSceneCorrespondences (model_scene_corrs); //gc_clusterer.cluster (clustered_corrs); gc_clusterer.recognize (rototranslations, clustered_corrs); } // // Output results // std::cout << "Model instances found: " << rototranslations.size () << std::endl; for (size_t i = 0; i < rototranslations.size (); ++i) { std::cout << "\n Instance " << i + 1 << ":" << std::endl; std::cout << " Correspondences belonging to this instance: " << clustered_corrs[i].size () << std::endl; // Print the rotation matrix and translation vector Eigen::Matrix3f rotation = rototranslations[i].block<3,3>(0, 0); Eigen::Vector3f translation = rototranslations[i].block<3,1>(0, 3); printf ("\n"); printf (" | %6.3f %6.3f %6.3f | \n", rotation (0,0), rotation (0,1), rotation (0,2)); printf (" R = | %6.3f %6.3f %6.3f | \n", rotation (1,0), rotation (1,1), rotation (1,2)); printf (" | %6.3f %6.3f %6.3f | \n", rotation (2,0), rotation (2,1), rotation (2,2)); printf ("\n"); printf (" t = < %0.3f, %0.3f, %0.3f >\n", translation (0), translation (1), translation (2)); } // // Visualization // pcl::visualization::PCLVisualizer viewer ("Correspondence Grouping"); viewer.addPointCloud (scene, "scene_cloud"); pcl::PointCloud<PointType>::Ptr off_scene_model (new pcl::PointCloud<PointType> ()); pcl::PointCloud<PointType>::Ptr off_scene_model_keypoints (new pcl::PointCloud<PointType> ()); if (show_correspondences_ || show_keypoints_ || show_all_correspondences_) { // We are translating the model so that it doesn't end in the middle of the scene representation pcl::transformPointCloud (*model, *off_scene_model, Eigen::Vector3f (-1,0,0), Eigen::Quaternionf (1, 0, 0, 0)); pcl::transformPointCloud (*model_keypoints, *off_scene_model_keypoints, Eigen::Vector3f (-1,0,0), Eigen::Quaternionf (1, 0, 0, 0)); // pcl::visualization::PointCloudColorHandlerCustom<PointType> off_scene_model_color_handler (off_scene_model, 255, 255, 128); viewer.addPointCloud (off_scene_model, "off_scene_model"); } if (show_keypoints_) { pcl::visualization::PointCloudColorHandlerCustom<PointType> scene_keypoints_color_handler (scene_keypoints, 0, 0, 255); viewer.addPointCloud (scene_keypoints, scene_keypoints_color_handler, "scene_keypoints"); viewer.setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 5, "scene_keypoints"); pcl::visualization::PointCloudColorHandlerCustom<PointType> off_scene_model_keypoints_color_handler (off_scene_model_keypoints, 0, 0, 255); viewer.addPointCloud (off_scene_model_keypoints, off_scene_model_keypoints_color_handler, "off_scene_model_keypoints"); viewer.setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 5, "off_scene_model_keypoints"); } if (show_correspondences_) { for (size_t i = 0; i < rototranslations.size (); ++i) { pcl::PointCloud<PointType>::Ptr rotated_model (new pcl::PointCloud<PointType> ()); pcl::transformPointCloud (*model, *rotated_model, rototranslations[i]); std::stringstream ss_cloud; ss_cloud << "instance" << i; pcl::visualization::PointCloudColorHandlerCustom<PointType> rotated_model_color_handler (rotated_model, 255, 0, 0); viewer.addPointCloud (rotated_model, rotated_model_color_handler, ss_cloud.str ()); for (size_t j = 0; j < clustered_corrs[i].size (); ++j) { std::stringstream ss_line; ss_line << "correspondence_line" << i << "_" << j; PointType& model_point = off_scene_model_keypoints->at (clustered_corrs[i][j].index_query); PointType& scene_point = scene_keypoints->at (clustered_corrs[i][j].index_match); // We are drawing a line for each pair of clustered correspondences found between the model and the scene viewer.addLine<PointType, PointType> (model_point, scene_point, 0, 255, 0, ss_line.str ()); } } } if (show_all_correspondences_) { for (size_t i = 0; i < model_scene_corrs->size (); ++i) { std::stringstream ss_line; ss_line << "correspondence_line" << i; PointType& model_point = off_scene_model_keypoints->at ((*model_scene_corrs)[i].index_query); PointType& scene_point = scene_keypoints->at ((*model_scene_corrs)[i].index_match); // We are drawing a line for each pair of clustered correspondences found between the model and the scene viewer.addLine<PointType, PointType> (model_point, scene_point, 0, 255, 0, ss_line.str ()); } } while (!viewer.wasStopped ()) { viewer.spinOnce (); } return (0); }
int _tmain (int argc, _TCHAR **argv) { for (int i = 0; i < argc; ++i) { out << argv[i] << std::endl; } if (argc < 2) { showHelp (); return (0); } params_t params; if (!parseCmdLine (argc - 1, argv + 1, ¶ms)) { if (otUnknown == params.opType) { out << _T (" : unknown operation") << std::endl; } else { out << _T ("bad command line") << std::endl; } return (-1); } if (FAILED (initLicensing (AppInfo, params.basesPaths, CLicensingPolicy::cmKeyOnly))) { return (-1); } // synchronizeKeys (AppInfo, KeyFile1, 0); #if defined (_WIN32) SetThreadLocale (MAKELCID (MAKELANGID (LANG_ENGLISH, SUBLANG_NEUTRAL), SORT_DEFAULT)); CComLib comLib; #endif switch(params.opType) { case otKeyReg : case otKeyRegAdd : regKey (params.keyFileName, params.keyAddMode); break; case otKeyRevoke : revokeKey (params.serialNumber); break; case otCheckActiveKey : checkActiveKey (); break; case otKeyFileInfo : keyFileInfo (params.keyFileName); break; case otViewInstalledKeys : viewInstalledKeys (); break; case otViewBlacklist : viewBlacklist (params.blacklistName); break; case otCheckAgainstBlacklist: checkAgainstBlackList (params.blacklistName.c_str ()); break; case otCheckKeyBlacklist : checKeyBlacklist (params.keyFileName, params.blacklistName); break; case otCheckKeyFile : case otCheckKeyFileAdd : checkKeyFile (params.keyFileName, params.keyAddMode); break; default : break; } // recreateTest (AppInfo, params.basesPaths, CLicensingPolicy::cmFullCheck); return (0); }
int CPictureViewerGui::show() { neutrino_msg_t msg; neutrino_msg_data_t data; int res = -1; CLCD::getInstance()->setMode(CLCD::MODE_MENU_UTF8, g_Locale->getText(LOCALE_PICTUREVIEWER_HEAD)); m_state = MENU; int timeout; bool loop = true; bool update = true; while (loop) { if (update) { hide(); update = false; paint(); } if (m_state != SLIDESHOW) timeout = 50; // egal else { timeout = (m_time + atoi(g_settings.picviewer_slide_time) - (long)time(NULL))*10; if (timeout < 0) timeout = 1; } g_RCInput->getMsg(&msg, &data, timeout); neutrino_msg_t msg_repeatok = msg & ~CRCInput::RC_Repeat; if (msg == CRCInput::RC_home) { //Exit after cancel key if (m_state != MENU) { endView(); update = true; } else loop = false; } else if (msg == CRCInput::RC_timeout) { if (m_state == SLIDESHOW) { m_time = (long)time(NULL); unsigned int next = selected + 1; if (next >= playlist.size()) next = 0; view(next); } } else if (msg == CRCInput::RC_left) { if (!playlist.empty()) { if (m_state == MENU) { if (selected < listmaxshow) selected = playlist.size()-1; else selected -= listmaxshow; liststart = (selected / listmaxshow) * listmaxshow; paint(); } else { view((selected == 0) ? (playlist.size() - 1) : (selected - 1)); } } } else if (msg == CRCInput::RC_right) { if (!playlist.empty()) { if (m_state == MENU) { selected += listmaxshow; if (selected >= playlist.size()) if (((playlist.size() / listmaxshow) + 1) * listmaxshow == playlist.size() + listmaxshow) selected = 0; else selected = selected < (((playlist.size() / listmaxshow) + 1) * listmaxshow) ? (playlist.size() - 1) : 0; liststart = (selected / listmaxshow) * listmaxshow; paint(); } else { unsigned int next = selected + 1; if (next >= playlist.size()) next = 0; view(next); } } } else if (msg_repeatok == CRCInput::RC_up) { if ((m_state == MENU) && (!playlist.empty())) { int prevselected = selected; if (selected == 0) { selected = playlist.size() - 1; } else selected--; paintItem(prevselected - liststart); unsigned int oldliststart = liststart; liststart = (selected / listmaxshow) * listmaxshow; if (oldliststart != liststart) { update = true; } else { paintItem(selected - liststart); } } } else if (msg_repeatok == CRCInput::RC_down) { if ((m_state == MENU) && (!playlist.empty())) { int prevselected = selected; selected = (selected + 1) %playlist.size(); paintItem(prevselected - liststart); unsigned int oldliststart = liststart; liststart = (selected / listmaxshow) * listmaxshow; if(oldliststart != liststart) { update = true; } else { paintItem(selected - liststart); } } } else if (msg == CRCInput::RC_ok) { if (!playlist.empty()) view(selected); } else if (msg == CRCInput::RC_red) { if (m_state == MENU) { if (!playlist.empty()) { CViewList::iterator p = playlist.begin() + selected; playlist.erase(p); if (selected >= playlist.size()) selected = playlist.size()-1; update = true; } } else if (m_state == SLIDESHOW) { m_state = VIEW; } } else if (msg == CRCInput::RC_green) { if (m_state == MENU) { CFileBrowser filebrowser((g_settings.filebrowser_denydirectoryleave) ? g_settings.picviewer_picturedir : ""); filebrowser.Multi_Select = true; filebrowser.Dirs_Selectable = true; filebrowser.Filter = &picture_filter; hide(); if (filebrowser.exec(Path.c_str())) { Path = filebrowser.getCurrentDir(); CFileList::const_iterator files = filebrowser.getSelectedFiles().begin(); for(; files != filebrowser.getSelectedFiles().end();files++) { if(files->getType() == CFile::FILE_PICTURE) { CPicture pic; pic.Filename = files->Name; std::string tmp = files->Name.substr(files->Name.rfind('/')+1); pic.Name = tmp.substr(0,tmp.rfind('.')); pic.Type = tmp.substr(tmp.rfind('.')+1); struct stat statbuf; if(stat(pic.Filename.c_str(),&statbuf) != 0) printf("stat error"); pic.Date = statbuf.st_mtime; playlist.push_back(pic); } else printf("Wrong Filetype %s:%d\n",files->Name.c_str(), files->getType()); } if (m_sort == FILENAME) std::sort(playlist.begin(), playlist.end(), comparePictureByFilename); else if (m_sort == DATE) std::sort(playlist.begin(), playlist.end(), comparePictureByDate); } update = true; } } else if (msg == CRCInput::RC_yellow) { if (m_state == MENU && !playlist.empty()) { playlist.clear(); selected = 0; update = true; } } else if (msg == CRCInput::RC_blue) { if ((m_state == MENU || m_state == VIEW) && (!playlist.empty())) { m_time = (long)time(NULL); view(selected); m_state=SLIDESHOW; } } else if (msg == CRCInput::RC_help) { if (m_state == MENU) { showHelp(); paint(); } } else if (msg == CRCInput::RC_1) { if (m_state != MENU) m_viewer->Zoom(200/3); } else if (msg == CRCInput::RC_2) { if (m_state != MENU) m_viewer->Move(0,-50); } else if (msg == CRCInput::RC_3) { if (m_state != MENU) m_viewer->Zoom(150); } else if (msg == CRCInput::RC_4) { if (m_state != MENU) m_viewer->Move(-50,0); } else if (msg == CRCInput::RC_5) { if (!playlist.empty()) { if (m_sort == FILENAME) { m_sort=DATE; std::sort(playlist.begin(),playlist.end(),comparePictureByDate); } else if (m_sort==DATE) { m_sort=FILENAME; std::sort(playlist.begin(),playlist.end(),comparePictureByFilename); } update = true; } } else if (msg == CRCInput::RC_6) { if (m_state != MENU) m_viewer->Move(50,0); } else if (msg == CRCInput::RC_8) { if (m_state != MENU) m_viewer->Move(0,50); } else if (msg == CRCInput::RC_0) { if (!playlist.empty()) view(selected, true); } #ifdef ENABLE_GUI_MOUNT else if (msg == CRCInput::RC_setup) { if (m_state == MENU) { CNFSSmallMenu nfsMenu; nfsMenu.exec(this, ""); update = true; CLCD::getInstance()->setMode(CLCD::MODE_MENU_UTF8, g_Locale->getText(LOCALE_PICTUREVIEWER_HEAD)); } } #endif else if (msg == NeutrinoMessages::CHANGEMODE) { if ((data & NeutrinoMessages::mode_mask) != NeutrinoMessages::mode_pic) { loop = false; m_LastMode = data; } } else if (msg == NeutrinoMessages::RECORD_START || msg == NeutrinoMessages::ZAPTO || msg == NeutrinoMessages::STANDBY_ON || msg == NeutrinoMessages::SHUTDOWN || msg == NeutrinoMessages::SLEEPTIMER) { // Exit for Record/Zapto Timers if (m_state != MENU) endView(); loop = false; g_RCInput->postMsg(msg, data); } else { if (CNeutrinoApp::getInstance()->handleMsg(msg, data) & messages_return::cancel_all) { loop = false; } } } hide(); return (res); }
int main(int argc, char** argv) { // Make current directory=path to execuable char *p = strrchr(argv[0], '/'); if (p != NULL) { *p = '\0'; chdir(argv[0]); } const char *config_file = "config/config.yml"; const char *name = NULL; int c; while ((c = getopt(argc, argv, ":c:n:hv")) != -1) { switch (c) { case 'c': config_file = optarg; break; case 'n': name = optarg; break; case 'h': showHelp(); return 0; case 'v': printf( "SAYAN server - ultra-fast, modular and super-lightweight web server\n" "version : sayan/" VERSION "\n" "build-date : " __DATE__ " " __TIME__ "\n" "project page : https://jacob-zak/projets/sayan-server/\n" ); return 0; case '?': fprintf(stderr, "unkown option: -%c\n\n", optopt); showHelp(); return EXIT_FAILURE; } } if ((argc - optind) > 0) { fprintf(stderr, "too many arguments\n\n"); showHelp(); return EXIT_FAILURE; } /* if (name != NULL) */ /* createNewProject(name); */ PRINT("name, %s", name); // Load config file loadConfig("config/config.yml"); /* const Config *config = getConfig(); */ /* PRINT("Config %d", config->port); */ // Init cache initHttpCache(false); // openLog(getConfig()->config.log_file, WARNING); // Run server /* int procs=get_nprocs(); */ int procs=2; HttpServer *server=initHttpServer(procs, 1024, procs); if(getConfig()->isDaemon) runDaemonServer(server); else runNormalServer(server); // Cleanup destroyHttpServer(server); destroyHttpCache(); return (EXIT_SUCCESS); }
int main(int argc, char** argv) { int delay = -1; bool userOnly = false; uid_t userId = 0; int usecolors = 1; char *argCopy; char *pid; Hashtable *pidWhiteList = NULL; int opt, opti=0; static struct option long_opts[] = { {"help", no_argument, 0, 'h'}, {"version", no_argument, 0, 'v'}, {"delay", required_argument, 0, 'd'}, {"sort-key", required_argument, 0, 's'}, {"user", required_argument, 0, 'u'}, {"no-color", no_argument, 0, 'C'}, {"no-colour",no_argument, 0, 'C'}, {"pid", required_argument, 0, 'p'}, {0,0,0,0} }; int sortKey = 0; char *lc_ctype = getenv("LC_CTYPE"); if(lc_ctype != NULL) setlocale(LC_CTYPE, lc_ctype); else if ((lc_ctype = getenv("LC_ALL"))) setlocale(LC_CTYPE, lc_ctype); else setlocale(LC_CTYPE, ""); /* Parse arguments */ while ((opt = getopt_long(argc, argv, "hvCs:d:u:p:", long_opts, &opti))) { if (opt == EOF) break; switch (opt) { case 'h': printHelpFlag(); break; case 'v': printVersionFlag(); break; case 's': if (strcmp(optarg, "help") == 0) { for (int j = 1; j < LAST_PROCESSFIELD; j++) printf ("%s\n", Process_fieldNames[j]); exit(0); } sortKey = ColumnsPanel_fieldNameToIndex(optarg); if (sortKey == -1) { fprintf(stderr, "Error: invalid column \"%s\".\n", optarg); exit(1); } break; case 'd': if (sscanf(optarg, "%d", &delay) == 1) { if (delay < 1) delay = 1; if (delay > 100) delay = 100; } else { fprintf(stderr, "Error: invalid delay value \"%s\".\n", optarg); exit(1); } break; case 'u': if (!setUserOnly(optarg, &userOnly, &userId)) { fprintf(stderr, "Error: invalid user \"%s\".\n", optarg); exit(1); } break; case 'C': usecolors=0; break; case 'p': argCopy = strdup(optarg); pid = strtok(argCopy, ","); if( !pidWhiteList ) { pidWhiteList = Hashtable_new(8, false); } while( pid ) { unsigned int num_pid = atoi(pid); Hashtable_put(pidWhiteList, num_pid, (void *) 1); pid = strtok(NULL, ","); } free(argCopy); break; default: exit(1); } } if (access(PROCDIR, R_OK) != 0) { fprintf(stderr, "Error: could not read procfs (compiled to look in %s).\n", PROCDIR); exit(1); } int quit = 0; int refreshTimeout = 0; int resetRefreshTimeout = 5; bool doRefresh = true; bool doRecalculate = false; Settings* settings; ProcessList* pl = NULL; UsersTable* ut = UsersTable_new(); #ifdef HAVE_LIBNCURSESW char *locale = setlocale(LC_ALL, NULL); if (locale == NULL || locale[0] == '\0') locale = setlocale(LC_CTYPE, NULL); if (locale != NULL && (strstr(locale, "UTF-8") || strstr(locale, "utf-8") || strstr(locale, "UTF8") || strstr(locale, "utf8"))) CRT_utf8 = true; else CRT_utf8 = false; #endif pl = ProcessList_new(ut, pidWhiteList); Process_getMaxPid(); Header* header = Header_new(pl); settings = Settings_new(pl, header, pl->cpuCount); int headerHeight = Header_calculateHeight(header); // FIXME: move delay code to settings if (delay != -1) settings->delay = delay; if (!usecolors) settings->colorScheme = COLORSCHEME_MONOCHROME; CRT_init(settings->delay, settings->colorScheme); Panel* panel = Panel_new(0, headerHeight, COLS, LINES - headerHeight - 2, false, &Process_class); ProcessList_setPanel(pl, panel); if (sortKey > 0) { pl->sortKey = sortKey; pl->treeView = false; pl->direction = 1; } ProcessList_printHeader(pl, Panel_getHeader(panel)); const char* defaultFunctions[] = {"Help ", "Setup ", "Search", "Filter", "Tree ", "SortBy", "Nice -", "Nice +", "Kill ", "Quit ", NULL}; FunctionBar* defaultBar = FunctionBar_new(defaultFunctions, NULL, NULL); IncSet* inc = IncSet_new(defaultBar); ProcessList_scan(pl); usleep(75000); FunctionBar_draw(defaultBar, NULL); int acc = 0; bool follow = false; struct timeval tv; double newTime = 0.0; double oldTime = 0.0; bool recalculate; int ch = ERR; int closeTimeout = 0; bool idle = false; while (!quit) { gettimeofday(&tv, NULL); newTime = ((double)tv.tv_sec * 10) + ((double)tv.tv_usec / 100000); recalculate = (newTime - oldTime > settings->delay); Process* p = (Process*)Panel_getSelected(panel); int following = (follow && p) ? p->pid : -1; if (recalculate) { Header_draw(header); oldTime = newTime; } if (doRefresh) { if (recalculate || doRecalculate) { ProcessList_scan(pl); doRecalculate = false; } if (refreshTimeout == 0 || pl->treeView) { ProcessList_sort(pl); refreshTimeout = 1; } ProcessList_rebuildPanel(pl, true, following, userOnly, userId, IncSet_filter(inc)); idle = false; } doRefresh = true; if (!idle) Panel_draw(panel, true); int prev = ch; if (inc->active) move(LINES-1, CRT_cursorX); ch = getch(); if (ch == ERR) { if (!inc->active) refreshTimeout--; if (prev == ch && !recalculate) { closeTimeout++; if (closeTimeout == 100) { break; } } else closeTimeout = 0; idle = true; continue; } idle = false; if (ch == KEY_MOUSE) { MEVENT mevent; int ok = getmouse(&mevent); if (ok == OK) { if (mevent.bstate & BUTTON1_CLICKED) { if (mevent.y == panel->y) { int x = panel->scrollH + mevent.x + 1; ProcessField field = ProcessList_keyAt(pl, x); if (field == pl->sortKey) { ProcessList_invertSortOrder(pl); pl->treeView = false; } else { setSortKey(pl, field, panel, settings); } refreshTimeout = 0; continue; } else if (mevent.y >= panel->y + 1 && mevent.y < LINES - 1) { Panel_setSelected(panel, mevent.y - panel->y + panel->scrollV - 1); doRefresh = false; refreshTimeout = resetRefreshTimeout; follow = true; continue; } if (mevent.y == LINES - 1) { ch = FunctionBar_synthesizeEvent(inc->bar, mevent.x); } } else if (mevent.bstate & BUTTON4_CLICKED) { ch = KEY_UP; #if NCURSES_MOUSE_VERSION > 1 } else if (mevent.bstate & BUTTON5_CLICKED) { ch = KEY_DOWN; #endif } } } if (inc->active) { doRefresh = IncSet_handleKey(inc, ch, panel, getMainPanelValue, NULL); continue; } if (isdigit((char)ch)) { if (Panel_size(panel) == 0) continue; pid_t pid = ch-48 + acc; for (int i = 0; i < ProcessList_size(pl) && ((Process*) Panel_getSelected(panel))->pid != pid; i++) Panel_setSelected(panel, i); acc = pid * 10; if (acc > 10000000) acc = 0; continue; } else { acc = 0; } switch (ch) { case KEY_RESIZE: Panel_resize(panel, COLS, LINES-headerHeight-1); IncSet_drawBar(inc); break; case 'M': { refreshTimeout = 0; setSortKey(pl, PERCENT_MEM, panel, settings); break; } case 'T': { refreshTimeout = 0; setSortKey(pl, TIME, panel, settings); break; } case 'U': { for (int i = 0; i < Panel_size(panel); i++) { Process* p = (Process*) Panel_get(panel, i); p->tag = false; } doRefresh = true; break; } case 'P': { refreshTimeout = 0; setSortKey(pl, PERCENT_CPU, panel, settings); break; } case KEY_F(1): case 'h': case '?': { showHelp(pl); FunctionBar_draw(defaultBar, NULL); refreshTimeout = 0; break; } case '\014': // Ctrl+L { clear(); FunctionBar_draw(defaultBar, NULL); refreshTimeout = 0; break; } case ' ': { Process* p = (Process*) Panel_getSelected(panel); if (!p) break; Process_toggleTag(p); Panel_onKey(panel, KEY_DOWN); break; } case 's': { Process* p = (Process*) Panel_getSelected(panel); if (!p) break; TraceScreen* ts = TraceScreen_new(p); TraceScreen_run(ts); TraceScreen_delete(ts); clear(); FunctionBar_draw(defaultBar, NULL); refreshTimeout = 0; CRT_enableDelay(); break; } case 'l': { Process* p = (Process*) Panel_getSelected(panel); if (!p) break; OpenFilesScreen* ts = OpenFilesScreen_new(p); OpenFilesScreen_run(ts); OpenFilesScreen_delete(ts); clear(); FunctionBar_draw(defaultBar, NULL); refreshTimeout = 0; CRT_enableDelay(); break; } case 'S': case 'C': case KEY_F(2): { Setup_run(settings, header); // TODO: shouldn't need this, colors should be dynamic ProcessList_printHeader(pl, Panel_getHeader(panel)); headerHeight = Header_calculateHeight(header); Panel_move(panel, 0, headerHeight); Panel_resize(panel, COLS, LINES-headerHeight-1); FunctionBar_draw(defaultBar, NULL); refreshTimeout = 0; break; } case 'F': { follow = true; continue; } case 'u': { Panel* usersPanel = Panel_new(0, 0, 0, 0, true, Class(ListItem)); Panel_setHeader(usersPanel, "Show processes of:"); UsersTable_foreach(ut, addUserToVector, usersPanel); Vector_insertionSort(usersPanel->items); ListItem* allUsers = ListItem_new("All users", -1); Panel_insert(usersPanel, 0, (Object*) allUsers); const char* fuFunctions[] = {"Show ", "Cancel ", NULL}; ListItem* picked = (ListItem*) pickFromVector(panel, usersPanel, 20, headerHeight, fuFunctions, defaultBar, header); if (picked) { if (picked == allUsers) { userOnly = false; } else { setUserOnly(ListItem_getRef(picked), &userOnly, &userId); } } Panel_delete((Object*)usersPanel); break; } case '+': case '=': case '-': { Process* p = (Process*) Panel_getSelected(panel); if (!p) break; p->showChildren = !p->showChildren; refreshTimeout = 0; doRecalculate = true; break; } case KEY_F(9): case 'k': { Panel* signalsPanel = (Panel*) SignalsPanel_new(); const char* fuFunctions[] = {"Send ", "Cancel ", NULL}; ListItem* sgn = (ListItem*) pickFromVector(panel, signalsPanel, 15, headerHeight, fuFunctions, defaultBar, header); if (sgn) { if (sgn->key != 0) { Panel_setHeader(panel, "Sending..."); Panel_draw(panel, true); refresh(); foreachProcess(panel, (ForeachProcessFn) Process_sendSignal, (size_t) sgn->key, NULL); napms(500); } } ProcessList_printHeader(pl, Panel_getHeader(panel)); Panel_delete((Object*)signalsPanel); refreshTimeout = 0; break; } #if (HAVE_LIBHWLOC || HAVE_NATIVE_AFFINITY) case 'a': { if (pl->cpuCount == 1) break; Process* p = (Process*) Panel_getSelected(panel); if (!p) break; Affinity* affinity = Process_getAffinity(p); if (!affinity) break; Panel* affinityPanel = AffinityPanel_new(pl, affinity); Affinity_delete(affinity); const char* fuFunctions[] = {"Set ", "Cancel ", NULL}; void* set = pickFromVector(panel, affinityPanel, 15, headerHeight, fuFunctions, defaultBar, header); if (set) { Affinity* affinity = AffinityPanel_getAffinity(affinityPanel); bool ok = foreachProcess(panel, (ForeachProcessFn) Process_setAffinity, (size_t) affinity, NULL); if (!ok) beep(); Affinity_delete(affinity); } Panel_delete((Object*)affinityPanel); ProcessList_printHeader(pl, Panel_getHeader(panel)); refreshTimeout = 0; break; } #endif case KEY_F(10): case 'q': quit = 1; break; case '<': case ',': case KEY_F(18): case '>': case '.': case KEY_F(6): { Panel* sortPanel = Panel_new(0, 0, 0, 0, true, Class(ListItem)); Panel_setHeader(sortPanel, "Sort by"); const char* fuFunctions[] = {"Sort ", "Cancel ", NULL}; ProcessField* fields = pl->fields; for (int i = 0; fields[i]; i++) { char* name = String_trim(Process_fieldNames[fields[i]]); Panel_add(sortPanel, (Object*) ListItem_new(name, fields[i])); if (fields[i] == pl->sortKey) Panel_setSelected(sortPanel, i); free(name); } ListItem* field = (ListItem*) pickFromVector(panel, sortPanel, 15, headerHeight, fuFunctions, defaultBar, header); if (field) { settings->changed = true; setSortKey(pl, field->key, panel, settings); } else { ProcessList_printHeader(pl, Panel_getHeader(panel)); } Object_delete(sortPanel); refreshTimeout = 0; break; } case 'i': { Process* p = (Process*) Panel_getSelected(panel); if (!p) break; IOPriority ioprio = p->ioPriority; Panel* ioprioPanel = IOPriorityPanel_new(ioprio); const char* fuFunctions[] = {"Set ", "Cancel ", NULL}; void* set = pickFromVector(panel, ioprioPanel, 21, headerHeight, fuFunctions, defaultBar, header); if (set) { IOPriority ioprio = IOPriorityPanel_getIOPriority(ioprioPanel); bool ok = foreachProcess(panel, (ForeachProcessFn) Process_setIOPriority, (size_t) ioprio, NULL); if (!ok) beep(); } Panel_delete((Object*)ioprioPanel); ProcessList_printHeader(pl, Panel_getHeader(panel)); refreshTimeout = 0; break; } case 'I': { refreshTimeout = 0; settings->changed = true; ProcessList_invertSortOrder(pl); break; } case KEY_F(8): case '[': { doRefresh = changePriority(panel, 1); break; } case KEY_F(7): case ']': { doRefresh = changePriority(panel, -1); break; } case KEY_F(3): case '/': IncSet_activate(inc, INC_SEARCH); break; case KEY_F(4): case '\\': IncSet_activate(inc, INC_FILTER); refreshTimeout = 0; doRefresh = true; continue; case 't': case KEY_F(5): refreshTimeout = 0; pl->treeView = !pl->treeView; if (pl->treeView) pl->direction = 1; ProcessList_printHeader(pl, Panel_getHeader(panel)); ProcessList_expandTree(pl); settings->changed = true; if (following != -1) continue; break; case 'H': doRecalculate = true; refreshTimeout = 0; pl->hideUserlandThreads = !pl->hideUserlandThreads; pl->hideThreads = pl->hideUserlandThreads; settings->changed = true; break; case 'K': doRecalculate = true; refreshTimeout = 0; pl->hideKernelThreads = !pl->hideKernelThreads; settings->changed = true; break; default: doRefresh = false; refreshTimeout = resetRefreshTimeout; Panel_onKey(panel, ch); break; } follow = false; } attron(CRT_colors[RESET_COLOR]); mvhline(LINES-1, 0, ' ', COLS); attroff(CRT_colors[RESET_COLOR]); refresh(); CRT_done(); if (settings->changed) Settings_write(settings); Header_delete(header); ProcessList_delete(pl); IncSet_delete(inc); FunctionBar_delete((Object*)defaultBar); Panel_delete((Object*)panel); UsersTable_delete(ut); Settings_delete(settings); if(pidWhiteList) { Hashtable_delete(pidWhiteList); } return 0; }
int main(int argc, char **argv){ sqlite3_int64 iBegin; /* Start time of this program */ int quietFlag = 0; /* True if --quiet or -q */ int verboseFlag = 0; /* True if --verbose or -v */ char *zInsSql = 0; /* SQL statement for --load-db or --load-sql */ int iFirstInsArg = 0; /* First argv[] to use for --load-db or --load-sql */ sqlite3 *db = 0; /* The open database connection */ sqlite3_stmt *pStmt; /* A prepared statement */ int rc; /* Result code from SQLite interface calls */ Blob *pSql; /* For looping over SQL scripts */ Blob *pDb; /* For looping over template databases */ int i; /* Loop index for the argv[] loop */ int onlySqlid = -1; /* --sqlid */ int onlyDbid = -1; /* --dbid */ int nativeFlag = 0; /* --native-vfs */ int rebuildFlag = 0; /* --rebuild */ int vdbeLimitFlag = 0; /* --limit-vdbe */ int timeoutTest = 0; /* undocumented --timeout-test flag */ int runFlags = 0; /* Flags sent to runSql() */ char *zMsg = 0; /* Add this message */ int nSrcDb = 0; /* Number of source databases */ char **azSrcDb = 0; /* Array of source database names */ int iSrcDb; /* Loop over all source databases */ int nTest = 0; /* Total number of tests performed */ char *zDbName = ""; /* Appreviated name of a source database */ const char *zFailCode = 0; /* Value of the TEST_FAILURE environment variable */ int cellSzCkFlag = 0; /* --cell-size-check */ int sqlFuzz = 0; /* True for SQL fuzz testing. False for DB fuzz */ int iTimeout = 120; /* Default 120-second timeout */ int nMem = 0; /* Memory limit */ char *zExpDb = 0; /* Write Databases to files in this directory */ char *zExpSql = 0; /* Write SQL to files in this directory */ iBegin = timeOfDay(); #ifdef __unix__ signal(SIGALRM, timeoutHandler); #endif g.zArgv0 = argv[0]; zFailCode = getenv("TEST_FAILURE"); for(i=1; i<argc; i++){ const char *z = argv[i]; if( z[0]=='-' ){ z++; if( z[0]=='-' ) z++; if( strcmp(z,"cell-size-check")==0 ){ cellSzCkFlag = 1; }else if( strcmp(z,"dbid")==0 ){ if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]); onlyDbid = integerValue(argv[++i]); }else if( strcmp(z,"export-db")==0 ){ if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]); zExpDb = argv[++i]; }else if( strcmp(z,"export-sql")==0 ){ if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]); zExpSql = argv[++i]; }else if( strcmp(z,"help")==0 ){ showHelp(); return 0; }else if( strcmp(z,"limit-mem")==0 ){ if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]); nMem = integerValue(argv[++i]); }else if( strcmp(z,"limit-vdbe")==0 ){ vdbeLimitFlag = 1; }else if( strcmp(z,"load-sql")==0 ){ zInsSql = "INSERT INTO xsql(sqltext) VALUES(CAST(readfile(?1) AS text))"; iFirstInsArg = i+1; break; }else if( strcmp(z,"load-db")==0 ){ zInsSql = "INSERT INTO db(dbcontent) VALUES(readfile(?1))"; iFirstInsArg = i+1; break; }else if( strcmp(z,"m")==0 ){ if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]); zMsg = argv[++i]; }else if( strcmp(z,"native-vfs")==0 ){ nativeFlag = 1; }else if( strcmp(z,"quiet")==0 || strcmp(z,"q")==0 ){ quietFlag = 1; verboseFlag = 0; }else if( strcmp(z,"rebuild")==0 ){ rebuildFlag = 1; }else if( strcmp(z,"result-trace")==0 ){ runFlags |= SQL_OUTPUT; }else if( strcmp(z,"sqlid")==0 ){ if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]); onlySqlid = integerValue(argv[++i]); }else if( strcmp(z,"timeout")==0 ){ if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]); iTimeout = integerValue(argv[++i]); }else if( strcmp(z,"timeout-test")==0 ){ timeoutTest = 1; #ifndef __unix__ fatalError("timeout is not available on non-unix systems"); #endif }else if( strcmp(z,"verbose")==0 || strcmp(z,"v")==0 ){ quietFlag = 0; verboseFlag = 1; runFlags |= SQL_TRACE; }else { fatalError("unknown option: %s", argv[i]); } }else{ nSrcDb++; azSrcDb = safe_realloc(azSrcDb, nSrcDb*sizeof(azSrcDb[0])); azSrcDb[nSrcDb-1] = argv[i]; } } if( nSrcDb==0 ) fatalError("no source database specified"); if( nSrcDb>1 ){ if( zMsg ){ fatalError("cannot change the description of more than one database"); } if( zInsSql ){ fatalError("cannot import into more than one database"); } } /* Process each source database separately */ for(iSrcDb=0; iSrcDb<nSrcDb; iSrcDb++){ rc = sqlite3_open(azSrcDb[iSrcDb], &db); if( rc ){ fatalError("cannot open source database %s - %s", azSrcDb[iSrcDb], sqlite3_errmsg(db)); } rc = sqlite3_exec(db, "CREATE TABLE IF NOT EXISTS db(\n" " dbid INTEGER PRIMARY KEY, -- database id\n" " dbcontent BLOB -- database disk file image\n" ");\n" "CREATE TABLE IF NOT EXISTS xsql(\n" " sqlid INTEGER PRIMARY KEY, -- SQL script id\n" " sqltext TEXT -- Text of SQL statements to run\n" ");" "CREATE TABLE IF NOT EXISTS readme(\n" " msg TEXT -- Human-readable description of this file\n" ");", 0, 0, 0); if( rc ) fatalError("cannot create schema: %s", sqlite3_errmsg(db)); if( zMsg ){ char *zSql; zSql = sqlite3_mprintf( "DELETE FROM readme; INSERT INTO readme(msg) VALUES(%Q)", zMsg); rc = sqlite3_exec(db, zSql, 0, 0, 0); sqlite3_free(zSql); if( rc ) fatalError("cannot change description: %s", sqlite3_errmsg(db)); } if( zInsSql ){ sqlite3_create_function(db, "readfile", 1, SQLITE_UTF8, 0, readfileFunc, 0, 0); rc = sqlite3_prepare_v2(db, zInsSql, -1, &pStmt, 0); if( rc ) fatalError("cannot prepare statement [%s]: %s", zInsSql, sqlite3_errmsg(db)); rc = sqlite3_exec(db, "BEGIN", 0, 0, 0); if( rc ) fatalError("cannot start a transaction"); for(i=iFirstInsArg; i<argc; i++){ sqlite3_bind_text(pStmt, 1, argv[i], -1, SQLITE_STATIC); sqlite3_step(pStmt); rc = sqlite3_reset(pStmt); if( rc ) fatalError("insert failed for %s", argv[i]); } sqlite3_finalize(pStmt); rc = sqlite3_exec(db, "COMMIT", 0, 0, 0); if( rc ) fatalError("cannot commit the transaction: %s", sqlite3_errmsg(db)); rebuild_database(db); sqlite3_close(db); return 0; } if( zExpDb!=0 || zExpSql!=0 ){ sqlite3_create_function(db, "writefile", 2, SQLITE_UTF8, 0, writefileFunc, 0, 0); if( zExpDb!=0 ){ const char *zExDb = "SELECT writefile(printf('%s/db%06d.db',?1,dbid),dbcontent)," " dbid, printf('%s/db%06d.db',?1,dbid), length(dbcontent)" " FROM db WHERE ?2<0 OR dbid=?2;"; rc = sqlite3_prepare_v2(db, zExDb, -1, &pStmt, 0); if( rc ) fatalError("cannot prepare statement [%s]: %s", zExDb, sqlite3_errmsg(db)); sqlite3_bind_text64(pStmt, 1, zExpDb, strlen(zExpDb), SQLITE_STATIC, SQLITE_UTF8); sqlite3_bind_int(pStmt, 2, onlyDbid); while( sqlite3_step(pStmt)==SQLITE_ROW ){ printf("write db-%d (%d bytes) into %s\n", sqlite3_column_int(pStmt,1), sqlite3_column_int(pStmt,3), sqlite3_column_text(pStmt,2)); } sqlite3_finalize(pStmt); } if( zExpSql!=0 ){ const char *zExSql = "SELECT writefile(printf('%s/sql%06d.txt',?1,sqlid),sqltext)," " sqlid, printf('%s/sql%06d.txt',?1,sqlid), length(sqltext)" " FROM xsql WHERE ?2<0 OR sqlid=?2;"; rc = sqlite3_prepare_v2(db, zExSql, -1, &pStmt, 0); if( rc ) fatalError("cannot prepare statement [%s]: %s", zExSql, sqlite3_errmsg(db)); sqlite3_bind_text64(pStmt, 1, zExpSql, strlen(zExpSql), SQLITE_STATIC, SQLITE_UTF8); sqlite3_bind_int(pStmt, 2, onlySqlid); while( sqlite3_step(pStmt)==SQLITE_ROW ){ printf("write sql-%d (%d bytes) into %s\n", sqlite3_column_int(pStmt,1), sqlite3_column_int(pStmt,3), sqlite3_column_text(pStmt,2)); } sqlite3_finalize(pStmt); } sqlite3_close(db); return 0; } /* Load all SQL script content and all initial database images from the ** source db */ blobListLoadFromDb(db, "SELECT sqlid, sqltext FROM xsql", onlySqlid, &g.nSql, &g.pFirstSql); if( g.nSql==0 ) fatalError("need at least one SQL script"); blobListLoadFromDb(db, "SELECT dbid, dbcontent FROM db", onlyDbid, &g.nDb, &g.pFirstDb); if( g.nDb==0 ){ g.pFirstDb = safe_realloc(0, sizeof(Blob)); memset(g.pFirstDb, 0, sizeof(Blob)); g.pFirstDb->id = 1; g.pFirstDb->seq = 0; g.nDb = 1; sqlFuzz = 1; } /* Print the description, if there is one */ if( !quietFlag ){ int i; zDbName = azSrcDb[iSrcDb]; i = strlen(zDbName) - 1; while( i>0 && zDbName[i-1]!='/' && zDbName[i-1]!='\\' ){ i--; } zDbName += i; sqlite3_prepare_v2(db, "SELECT msg FROM readme", -1, &pStmt, 0); if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){ printf("%s: %s\n", zDbName, sqlite3_column_text(pStmt,0)); } sqlite3_finalize(pStmt); } /* Rebuild the database, if requested */ if( rebuildFlag ){ if( !quietFlag ){ printf("%s: rebuilding... ", zDbName); fflush(stdout); } rebuild_database(db); if( !quietFlag ) printf("done\n"); } /* Close the source database. Verify that no SQLite memory allocations are ** outstanding. */ sqlite3_close(db); if( sqlite3_memory_used()>0 ){ fatalError("SQLite has memory in use before the start of testing"); } /* Limit available memory, if requested */ if( nMem>0 ){ void *pHeap; sqlite3_shutdown(); pHeap = malloc(nMem); if( pHeap==0 ){ fatalError("failed to allocate %d bytes of heap memory", nMem); } sqlite3_config(SQLITE_CONFIG_HEAP, pHeap, nMem, 128); } /* Register the in-memory virtual filesystem */ formatVfs(); inmemVfsRegister(); /* Run a test using each SQL script against each database. */ if( !verboseFlag && !quietFlag ) printf("%s:", zDbName); for(pSql=g.pFirstSql; pSql; pSql=pSql->pNext){ for(pDb=g.pFirstDb; pDb; pDb=pDb->pNext){ int openFlags; const char *zVfs = "inmem"; sqlite3_snprintf(sizeof(g.zTestName), g.zTestName, "sqlid=%d,dbid=%d", pSql->id, pDb->id); if( verboseFlag ){ printf("%s\n", g.zTestName); fflush(stdout); }else if( !quietFlag ){ static int prevAmt = -1; int idx = pSql->seq*g.nDb + pDb->id - 1; int amt = idx*10/(g.nDb*g.nSql); if( amt!=prevAmt ){ printf(" %d%%", amt*10); fflush(stdout); prevAmt = amt; } } createVFile("main.db", pDb->sz, pDb->a); openFlags = SQLITE_OPEN_CREATE | SQLITE_OPEN_READWRITE; if( nativeFlag && pDb->sz==0 ){ openFlags |= SQLITE_OPEN_MEMORY; zVfs = 0; } rc = sqlite3_open_v2("main.db", &db, openFlags, zVfs); if( rc ) fatalError("cannot open inmem database"); #ifdef SQLITE_ENABLE_JSON1 { extern int sqlite3_json_init(sqlite3*); sqlite3_json_init(db); } #endif if( cellSzCkFlag ) runSql(db, "PRAGMA cell_size_check=ON", runFlags); setAlarm(iTimeout); #ifndef SQLITE_OMIT_PROGRESS_CALLBACK if( sqlFuzz || vdbeLimitFlag ){ sqlite3_progress_handler(db, 100000, progressHandler, &vdbeLimitFlag); } #endif do{ runSql(db, (char*)pSql->a, runFlags); }while( timeoutTest ); setAlarm(0); sqlite3_close(db); if( sqlite3_memory_used()>0 ) fatalError("memory leak"); reformatVfs(); nTest++; g.zTestName[0] = 0; /* Simulate an error if the TEST_FAILURE environment variable is "5". ** This is used to verify that automated test script really do spot ** errors that occur in this test program. */ if( zFailCode ){ if( zFailCode[0]=='5' && zFailCode[1]==0 ){ fatalError("simulated failure"); }else if( zFailCode[0]!=0 ){ /* If TEST_FAILURE is something other than 5, just exit the test ** early */ printf("\nExit early due to TEST_FAILURE being set\n"); iSrcDb = nSrcDb-1; goto sourcedb_cleanup; } } } } if( !quietFlag && !verboseFlag ){ printf(" 100%% - %d tests\n", g.nDb*g.nSql); } /* Clean up at the end of processing a single source database */ sourcedb_cleanup: blobListFree(g.pFirstSql); blobListFree(g.pFirstDb); reformatVfs(); } /* End loop over all source databases */ if( !quietFlag ){ sqlite3_int64 iElapse = timeOfDay() - iBegin; printf("fuzzcheck: 0 errors out of %d tests in %d.%03d seconds\n" "SQLite %s %s\n", nTest, (int)(iElapse/1000), (int)(iElapse%1000), sqlite3_libversion(), sqlite3_sourceid()); } free(azSrcDb); return 0; }
int main(int argc, char **argv) { FILE *fp; int width, height, alpha; unsigned char *image, *fb; SDL_Surface *screen; struct triangles *triangles, *best, *absbest; long long diff; float percdiff, bestdiff; /* Initialization */ srand(time(NULL)); state.max_shapes = 64; state.max_shapes_incremental = 1; state.temperature = 0.10; state.generation = 0; state.absbestdiff = 100; /* 100% is worst diff possible. */ /* Check arity and parse additional args if any. */ if (argc < 4) { showHelp(argv[0]); exit(1); } if (argc > 4) { int j; for (j = 4; j < argc; j++) { int moreargs = j+1 < argc; if (!strcmp(argv[j],"--use-triangles") && moreargs) { opt_use_triangles = atoi(argv[++j]); } else if (!strcmp(argv[j],"--use-circles") && moreargs) { opt_use_circles = atoi(argv[++j]); } else if (!strcmp(argv[j],"--max-shapes") && moreargs) { state.max_shapes = atoi(argv[++j]); } else if (!strcmp(argv[j],"--initial-shapes") && moreargs) { state.max_shapes_incremental = atoi(argv[++j]); } else if (!strcmp(argv[j],"--restart")) { opt_restart = 1; } else if (!strcmp(argv[j],"--help")) { showHelp(argv[0]); } else { fprintf(stderr,"Invalid options."); showHelp(argv[0]); exit(1); } } } /* Sanity check. */ if (state.max_shapes_incremental > state.max_shapes) { state.max_shapes = state.max_shapes_incremental; } /* Load the PNG in memory. */ fp = fopen(argv[1],"rb"); if (!fp) { perror("Opening PNG file"); exit(1); } if ((image = PngLoad(fp,&width,&height,&alpha)) == NULL) { printf("Can't load the specified image."); exit(1); } printf("Image %d %d, alpha:%d at %p\n", width, height, alpha, image); fclose(fp); /* Initialize SDL and allocate our arrays of triangles. */ screen = sdlInit(width,height,0); fb = malloc(width*height*3); triangles = mkRandomtriangles(state.max_shapes,width,height); best = mkRandomtriangles(state.max_shapes,width,height); absbest = mkRandomtriangles(state.max_shapes,width,height); state.absbestdiff = bestdiff = 100; /* Load the binary file if any. */ if (!opt_restart) loadBinary(argv[2],best); absbest->inuse = best->inuse; memcpy(absbest->triangles,best->triangles, sizeof(struct triangle)*best->count); /* Show the current evolved image and the real image for one scond each. */ memset(fb,0,width*height*3); drawtriangles(fb,width,height,best); sdlShowRgb(screen,fb,width,height); sleep(1); sdlShowRgb(screen,image,width,height); sleep(1); /* Evolve the current solution using simulated annealing. */ while(1) { state.generation++; if (state.temperature > 0 && !(state.generation % 10)) { state.temperature -= 0.00001; if (state.temperature < 0) state.temperature = 0; } /* From time to time allow the current solution to use one more * triangle, up to the configured max number. */ if ((state.generation % 1000) == 0) { if (state.max_shapes_incremental < triangles->count && triangles->inuse > state.max_shapes_incremental-1) { state.max_shapes_incremental++; } } /* Copy what is currenly the best solution, and mutate it. */ memcpy(triangles->triangles,best->triangles, sizeof(struct triangle)*best->count); triangles->inuse = best->inuse; mutatetriangles(triangles,10,width,height); /* Draw the mutated solution, and check what is its fitness. * In our case the fitness is the difference bewteen the target * image and our image. */ memset(fb,0,width*height*3); drawtriangles(fb,width,height,triangles); diff = computeDiff(image,fb,width,height); /* The percentage of difference is calculate taking the ratio between * the maximum difference and the current difference. * The magic constant 422 is actually the max difference between * two pixels as r,g,b coordinates in the space, so sqrt(255^2*3). */ percdiff = (float)diff/(width*height*442)*100; if (percdiff < bestdiff || (state.temperature > 0 && ((float)rand()/RAND_MAX) < state.temperature && (percdiff-state.absbestdiff) < 2*state.temperature)) { /* Save what is currently our "best" solution, even if actually * this may be a jump backward depending on the temperature. * It will be used as a base of the next iteration. */ best->inuse = triangles->inuse; memcpy(best->triangles,triangles->triangles, sizeof(struct triangle)*best->count); if (percdiff < bestdiff) { /* We always save a copy of the absolute best solution we found * so far, after some generation without finding anything better * we may jump back to that solution. * * We also use the absolute best solution to save the program * state in the binary file, and as SVG output. */ absbest->inuse = best->inuse; memcpy(absbest->triangles,best->triangles, sizeof(struct triangle)*best->count); state.absbestdiff = percdiff; } printf("Diff is %f%% (inuse:%d, max:%d, gen:%lld, temp:%f)\n", percdiff, triangles->inuse, state.max_shapes_incremental, state.generation, state.temperature); bestdiff = percdiff; sdlShowRgb(screen,fb,width,height); } processSdlEvents(); /* From time to time save the current state into a binary save * and produce an SVG of the current solution. */ if ((state.generation % 100) == 0) { saveSvg(argv[3],absbest); saveBinary(argv[2],absbest); } } return 0; }
void HelpViewer::homeClicked() { showHelp(HelpViewer::USERMANUAL); }
/** * Called by the "Start" button. Sets up the meta data and enables the * buttons to perform six point calibration of the magnetometer (optionally * accel) to compute the scale and bias of this sensor based on the current * home location magnetic strength. */ void SixPointCalibrationModel::start(bool calibrateAccel, bool calibrateMag) { calibratingAccel = calibrateAccel; calibratingMag = calibrateMag; started(); // check if Homelocation is set HomeLocation::DataFields homeLocationData = homeLocation->getData(); if (!homeLocationData.Set) { displayInstructions(tr("Home location not set, please set your home location and retry."), WizardModel::Warn); displayInstructions(tr("Aborting calibration!"), WizardModel::Failure); stopped(); return; } // Store and reset board rotation before calibration starts storeAndClearBoardRotation(); // Calibration accel AccelGyroSettings::DataFields accelGyroSettingsData = accelGyroSettings->getData(); memento.accelGyroSettingsData = accelGyroSettingsData; accelGyroSettingsData.accel_scale[AccelGyroSettings::ACCEL_SCALE_X] = 1; accelGyroSettingsData.accel_scale[AccelGyroSettings::ACCEL_SCALE_Y] = 1; accelGyroSettingsData.accel_scale[AccelGyroSettings::ACCEL_SCALE_Z] = 1; accelGyroSettingsData.accel_bias[AccelGyroSettings::ACCEL_BIAS_X] = 0; accelGyroSettingsData.accel_bias[AccelGyroSettings::ACCEL_BIAS_Y] = 0; accelGyroSettingsData.accel_bias[AccelGyroSettings::ACCEL_BIAS_Z] = 0; accelGyroSettings->setData(accelGyroSettingsData); // Calibration mag RevoCalibration::DataFields revoCalibrationData = revoCalibration->getData(); memento.revoCalibrationData = revoCalibrationData; // Reset the transformation matrix to identity for (int i = 0; i < RevoCalibration::MAG_TRANSFORM_R2C2; i++) { revoCalibrationData.mag_transform[i] = 0; } revoCalibrationData.mag_transform[RevoCalibration::MAG_TRANSFORM_R0C0] = 1; revoCalibrationData.mag_transform[RevoCalibration::MAG_TRANSFORM_R1C1] = 1; revoCalibrationData.mag_transform[RevoCalibration::MAG_TRANSFORM_R2C2] = 1; revoCalibrationData.mag_bias[RevoCalibration::MAG_BIAS_X] = 0; revoCalibrationData.mag_bias[RevoCalibration::MAG_BIAS_Y] = 0; revoCalibrationData.mag_bias[RevoCalibration::MAG_BIAS_Z] = 0; // Disable adaptive mag nulling revoCalibrationData.MagBiasNullingRate = 0; revoCalibration->setData(revoCalibrationData); // Calibration AuxMag AuxMagSettings::DataFields auxMagSettingsData = auxMagSettings->getData(); memento.auxMagSettings = auxMagSettingsData; // Reset the transformation matrix to identity for (int i = 0; i < AuxMagSettings::MAG_TRANSFORM_R2C2; i++) { auxMagSettingsData.mag_transform[i] = 0; } auxMagSettingsData.mag_transform[AuxMagSettings::MAG_TRANSFORM_R0C0] = 1; auxMagSettingsData.mag_transform[AuxMagSettings::MAG_TRANSFORM_R1C1] = 1; auxMagSettingsData.mag_transform[AuxMagSettings::MAG_TRANSFORM_R2C2] = 1; auxMagSettingsData.mag_bias[AuxMagSettings::MAG_BIAS_X] = 0; auxMagSettingsData.mag_bias[AuxMagSettings::MAG_BIAS_Y] = 0; auxMagSettingsData.mag_bias[AuxMagSettings::MAG_BIAS_Z] = 0; // Disable adaptive mag nulling auxMagSettingsData.MagBiasNullingRate = 0; auxMagSettings->setData(auxMagSettingsData); QThread::usleep(100000); mag_accum_x.clear(); mag_accum_y.clear(); mag_accum_z.clear(); mag_fit_x.clear(); mag_fit_y.clear(); mag_fit_z.clear(); // Need to get as many accel updates as possible memento.accelStateMetadata = accelState->getMetadata(); if (calibrateAccel) { UAVObject::Metadata mdata = accelState->getMetadata(); UAVObject::SetFlightTelemetryUpdateMode(mdata, UAVObject::UPDATEMODE_PERIODIC); mdata.flightTelemetryUpdatePeriod = 100; accelState->setMetadata(mdata); } // Need to get as many mag updates as possible memento.magSensorMetadata = magSensor->getMetadata(); memento.auxMagSensorMetadata = auxMagSensor->getMetadata(); if (calibrateMag) { UAVObject::Metadata mdata = magSensor->getMetadata(); UAVObject::SetFlightTelemetryUpdateMode(mdata, UAVObject::UPDATEMODE_PERIODIC); mdata.flightTelemetryUpdatePeriod = 100; magSensor->setMetadata(mdata); mdata = auxMagSensor->getMetadata(); UAVObject::SetFlightTelemetryUpdateMode(mdata, UAVObject::UPDATEMODE_PERIODIC); mdata.flightTelemetryUpdatePeriod = 100; auxMagSensor->setMetadata(mdata); } // reset dirty state to forget previous unsaved runs m_dirty = false; if (calibrateMag) { currentSteps = &calibrationStepsMag; } else { currentSteps = &calibrationStepsAccelOnly; } position = 0; // Show instructions and enable controls progressChanged(0); displayInstructions((*currentSteps)[0].instructions, WizardModel::Prompt); showHelp((*currentSteps)[0].visualHelp); savePositionEnabledChanged(true); }
int getBootOptions(bool firstRun) { int i; int key; int nextRow; int timeout; int bvCount; BVRef bvr; BVRef menuBVR; bool showPrompt, newShowPrompt, isCDROM; // Initialize default menu selection entry. gBootVolume = menuBVR = selectBootVolume(bvChain); if (biosDevIsCDROM(gBIOSDev)) { isCDROM = true; } else { isCDROM = false; } // ensure we're in graphics mode if gui is setup if (gui.initialised) { if (bootArgs->Video.v_display == VGA_TEXT_MODE) { setVideoMode(GRAPHICS_MODE, 0); } } // Allow user to override default timeout. if (multiboot_timeout_set) { timeout = multiboot_timeout; } else if (!getIntForKey(kTimeoutKey, &timeout, &bootInfo->bootConfig)) { /* If there is no timeout key in the file use the default timeout which is different for CDs vs. hard disks. However, if not booting a CD and no config file could be loaded set the timeout to zero which causes the menu to display immediately. This way, if no partitions can be found, that is the disk is unpartitioned or simply cannot be read) then an empty menu is displayed. If some partitions are found, for example a Windows partition, then these will be displayed in the menu as foreign partitions. */ if (isCDROM) { timeout = kCDBootTimeout; } else { timeout = sysConfigValid ? kBootTimeout : 0; } } if (timeout < 0) { gBootMode |= kBootModeQuiet; } // If the user is holding down a modifier key, enter safe mode. if ((readKeyboardShiftFlags() & 0x0F) != 0) { gBootMode |= kBootModeSafe; } // If user typed F8, abort quiet mode, and display the menu. { bool f8press = false, spress = false, vpress = false; int key; while (readKeyboardStatus()) { key = bgetc (); if (key == 0x4200) f8press = true; if ((key & 0xff) == 's' || (key & 0xff) == 'S') spress = true; if ((key & 0xff) == 'v' || (key & 0xff) == 'V') vpress = true; } if (f8press) { gBootMode &= ~kBootModeQuiet; timeout = 0; } if ((gBootMode & kBootModeQuiet) && firstRun && vpress && (gBootArgsPtr + 3 < gBootArgsEnd)) { *(gBootArgsPtr++) = ' '; *(gBootArgsPtr++) = '-'; *(gBootArgsPtr++) = 'v'; } if ((gBootMode & kBootModeQuiet) && firstRun && spress && (gBootArgsPtr + 3 < gBootArgsEnd)) { *(gBootArgsPtr++) = ' '; *(gBootArgsPtr++) = '-'; *(gBootArgsPtr++) = 's'; } } clearBootArgs(); if (bootArgs->Video.v_display == VGA_TEXT_MODE) { setCursorPosition(0, 0, 0); clearScreenRows(0, kScreenLastRow); if (!(gBootMode & kBootModeQuiet)) { // Display banner and show hardware info. printf(bootBanner, (bootInfo->convmem + bootInfo->extmem) / 1024); printf(getVBEInfoString()); } changeCursor(0, kMenuTopRow, kCursorTypeUnderline, 0); verbose("Scanning device %x...", gBIOSDev); } // When booting from CD, default to hard drive boot when possible. if (isCDROM && firstRun) { const char *val; char *prompt; char *name; int cnt; int optionKey; if (getValueForKey(kCDROMPromptKey, &val, &cnt, &bootInfo->bootConfig)) { cnt += 1; prompt = malloc(cnt); strlcpy(prompt, val, cnt); } else { name = malloc(80); getBootVolumeDescription(gBootVolume, name, 80, false); prompt = malloc(256); sprintf(prompt, "Press any key to start up from %s, or press F8 to enter startup options.", name); free(name); cnt = 0; } if (getIntForKey( kCDROMOptionKey, &optionKey, &bootInfo->bootConfig )) { // The key specified is a special key. } else if (getValueForKey( kCDROMOptionKey, &val, &cnt, &bootInfo->bootConfig ) && cnt >= 1) { optionKey = val[0]; } else { // Default to F8. optionKey = 0x4200; } // If the timeout is zero then it must have been set above due to the // early catch of F8 which means the user wants to set boot options // which we ought to interpret as meaning he wants to boot the CD. if (timeout != 0) { key = countdown(prompt, kMenuTopRow, timeout); } else { key = optionKey; } if (cnt) { free(prompt); } clearScreenRows( kMenuTopRow, kMenuTopRow + 2 ); // Hit the option key ? if (key == optionKey) { gBootMode &= ~kBootModeQuiet; timeout = 0; } else { key = key & 0xFF; // Try booting hard disk if user pressed 'h' if (biosDevIsCDROM(gBIOSDev) && key == 'h') { BVRef bvr; // Look at partitions hosting OS X other than the CD-ROM for (bvr = bvChain; bvr; bvr=bvr->next) { if ((bvr->flags & kBVFlagSystemVolume) && bvr->biosdev != gBIOSDev) { gBootVolume = bvr; } } } goto done; } } if (gBootMode & kBootModeQuiet) { // No input allowed from user. goto done; } if (firstRun && timeout > 0 && countdown("Press any key to enter startup options.", kMenuTopRow, timeout) == 0) { // If the user is holding down a modifier key, // enter safe mode. if ((readKeyboardShiftFlags() & 0x0F) != 0) { gBootMode |= kBootModeSafe; } goto done; } if (gDeviceCount) { // Allocate memory for an array of menu items. menuItems = malloc(sizeof(MenuItem) * gDeviceCount); if (menuItems == NULL) { goto done; } // Associate a menu item for each BVRef. for (bvr=bvChain, i=gDeviceCount-1, selectIndex=0; bvr; bvr=bvr->next) { if (bvr->visible) { getBootVolumeDescription(bvr, menuItems[i].name, 80, true); menuItems[i].param = (void *) bvr; if (bvr == menuBVR) { selectIndex = i; } i--; } } } if (bootArgs->Video.v_display == GRAPHICS_MODE) { // redraw the background buffer drawBackground(); gui.devicelist.draw = true; gui.redraw = true; if (!(gBootMode & kBootModeQuiet)) { bool showBootBanner = true; // Check if "Boot Banner"=N switch is present in config file. getBoolForKey(kBootBannerKey, &showBootBanner, &bootInfo->bootConfig); if (showBootBanner) { // Display banner and show hardware info. gprintf(&gui.screen, bootBanner + 1, (bootInfo->convmem + bootInfo->extmem) / 1024); } // redraw background memcpy(gui.backbuffer->pixels, gui.screen.pixmap->pixels, gui.backbuffer->width * gui.backbuffer->height * 4); } } else { // Clear screen and hide the blinking cursor. clearScreenRows(kMenuTopRow, kMenuTopRow + 2); changeCursor(0, kMenuTopRow, kCursorTypeHidden, 0); } nextRow = kMenuTopRow; showPrompt = true; if (gDeviceCount) { if( bootArgs->Video.v_display == VGA_TEXT_MODE ) { printf("Use \30\31 keys to select the startup volume."); } showMenu( menuItems, gDeviceCount, selectIndex, kMenuTopRow + 2, kMenuMaxItems ); nextRow += min( gDeviceCount, kMenuMaxItems ) + 3; } // Show the boot prompt. showPrompt = (gDeviceCount == 0) || (menuBVR->flags & kBVFlagNativeBoot); showBootPrompt( nextRow, showPrompt ); do { if (bootArgs->Video.v_display == GRAPHICS_MODE) { // redraw background memcpy( gui.backbuffer->pixels, gui.screen.pixmap->pixels, gui.backbuffer->width * gui.backbuffer->height * 4 ); // reset cursor co-ords gui.debug.cursor = pos( gui.screen.width - 160 , 10 ); } key = getc(); updateMenu( key, (void **) &menuBVR ); newShowPrompt = (gDeviceCount == 0) || (menuBVR->flags & kBVFlagNativeBoot); if (newShowPrompt != showPrompt) { showPrompt = newShowPrompt; showBootPrompt( nextRow, showPrompt ); } if (showPrompt) { updateBootArgs(key); } switch (key) { case kReturnKey: if (gui.menu.draw) { key=0; break; } if (*gBootArgs == '?') { char * argPtr = gBootArgs; // Skip the leading "?" character. argPtr++; getNextArg(&argPtr, booterCommand); getNextArg(&argPtr, booterParam); /* * TODO: this needs to be refactored. */ if (strcmp( booterCommand, "video" ) == 0) { if (bootArgs->Video.v_display == GRAPHICS_MODE) { showInfoBox(getVBEInfoString(), getVBEModeInfoString()); } else { printVBEModeInfo(); } } else if ( strcmp( booterCommand, "memory" ) == 0) { if (bootArgs->Video.v_display == GRAPHICS_MODE ) { showInfoBox("Memory Map", getMemoryInfoString()); } else { printMemoryInfo(); } } else if (strcmp(booterCommand, "lspci") == 0) { lspci(); } else if (strcmp(booterCommand, "more") == 0) { showTextFile(booterParam); } else if (strcmp(booterCommand, "rd") == 0) { processRAMDiskCommand(&argPtr, booterParam); } else if (strcmp(booterCommand, "norescan") == 0) { if (gEnableCDROMRescan) { gEnableCDROMRescan = false; break; } } else { showHelp(); } key = 0; showBootPrompt(nextRow, showPrompt); break; } gBootVolume = menuBVR; setRootVolume(menuBVR); gBIOSDev = menuBVR->biosdev; break; case kEscapeKey: clearBootArgs(); break; case kF5Key: // New behavior: // Clear gBootVolume to restart the loop // if the user enabled rescanning the optical drive. // Otherwise boot the default boot volume. if (gEnableCDROMRescan) { gBootVolume = NULL; clearBootArgs(); } break; case kF10Key: gScanSingleDrive = false; scanDisks(gBIOSDev, &bvCount); gBootVolume = NULL; clearBootArgs(); break; case kTabKey: // New behavior: // Switch between text & graphic interfaces // Only Permitted if started in graphics interface if (useGUI) { if (bootArgs->Video.v_display == GRAPHICS_MODE) { setVideoMode(VGA_TEXT_MODE, 0); setCursorPosition(0, 0, 0); clearScreenRows(0, kScreenLastRow); // Display banner and show hardware info. printf(bootBanner, (bootInfo->convmem + bootInfo->extmem) / 1024); printf(getVBEInfoString()); clearScreenRows(kMenuTopRow, kMenuTopRow + 2); changeCursor(0, kMenuTopRow, kCursorTypeHidden, 0); nextRow = kMenuTopRow; showPrompt = true; if (gDeviceCount) { printf("Use \30\31 keys to select the startup volume."); showMenu(menuItems, gDeviceCount, selectIndex, kMenuTopRow + 2, kMenuMaxItems); nextRow += min(gDeviceCount, kMenuMaxItems) + 3; } showPrompt = (gDeviceCount == 0) || (menuBVR->flags & kBVFlagNativeBoot); showBootPrompt(nextRow, showPrompt); //changeCursor( 0, kMenuTopRow, kCursorTypeUnderline, 0 ); } else { gui.redraw = true; setVideoMode(GRAPHICS_MODE, 0); updateVRAM(); } } key = 0; break; default: key = 0; break; } } while (0 == key); done: if (bootArgs->Video.v_display == VGA_TEXT_MODE) { clearScreenRows(kMenuTopRow, kScreenLastRow); changeCursor(0, kMenuTopRow, kCursorTypeUnderline, 0); } shouldboot = false; gui.menu.draw = false; if (menuItems) { free(menuItems); menuItems = NULL; } return 0; }
/** * Parses Command Line Arguments (Argc,Argv) * @param argc * @param argv */ void parseCommandLine (int argc, char *argv[]) { //Show help if (pcl::console::find_switch (argc, argv, "-h")) { showHelp (argv[0]); exit (0); } //Model & scene filenames std::vector<int> filenames; filenames = pcl::console::parse_file_extension_argument (argc, argv, ".pcd"); if (filenames.size () != 2) { std::cout << "Filenames missing.\n"; showHelp (argv[0]); exit (-1); } model_filename_ = argv[filenames[0]]; scene_filename_ = argv[filenames[1]]; //Program behavior if (pcl::console::find_switch (argc, argv, "-k")) { show_keypoints_ = true; } std::string used_algorithm; if (pcl::console::parse_argument (argc, argv, "--algorithm", used_algorithm) != -1) { if (used_algorithm.compare ("Hough") == 0) { use_hough_ = true; } else if (used_algorithm.compare ("GC") == 0) { use_hough_ = false; } else { std::cout << "Wrong algorithm name.\n"; showHelp (argv[0]); exit (-1); } } //General parameters pcl::console::parse_argument (argc, argv, "--model_ss", model_ss_); pcl::console::parse_argument (argc, argv, "--scene_ss", scene_ss_); pcl::console::parse_argument (argc, argv, "--rf_rad", rf_rad_); pcl::console::parse_argument (argc, argv, "--descr_rad", descr_rad_); pcl::console::parse_argument (argc, argv, "--cg_size", cg_size_); pcl::console::parse_argument (argc, argv, "--cg_thresh", cg_thresh_); pcl::console::parse_argument (argc, argv, "--icp_max_iter", icp_max_iter_); pcl::console::parse_argument (argc, argv, "--icp_corr_distance", icp_corr_distance_); pcl::console::parse_argument (argc, argv, "--hv_clutter_reg", hv_clutter_reg_); pcl::console::parse_argument (argc, argv, "--hv_inlier_th", hv_inlier_th_); pcl::console::parse_argument (argc, argv, "--hv_occlusion_th", hv_occlusion_th_); pcl::console::parse_argument (argc, argv, "--hv_rad_clutter", hv_rad_clutter_); pcl::console::parse_argument (argc, argv, "--hv_regularizer", hv_regularizer_); pcl::console::parse_argument (argc, argv, "--hv_rad_normals", hv_rad_normals_); pcl::console::parse_argument (argc, argv, "--hv_detect_clutter", hv_detect_clutter_); }
Browser::Browser() { string input, destination, newpath; path = "/"; vector<string> params; // pass buffer manager.setBuffer(&buffer); string command; pwd = Folder(0, 0, "root"); // WELCOME //printw("%s", "## Welcome in Rapidshare Manager \n"); //printw("%s", "rs#~/ "); //refresh(); //move(linenum,6); //cout << "## Welcome in Rapidshare Manager" << endl; //cout << "rs#~/ "; while(true) { input = buffer.getCommand(); //getline(cin, input); //printw("---- %s -----", input.c_str()); trim(input); split(params, input, is_any_of(" ")); command = params[0]; if(command == "ls"){ manager.listFolder(pwd); } if(command == "help"){ showHelp(); } if(command == "mv"){ params = processParams(input, command, 2); mv(getCurrentPath(params[0]), getCurrentPath(params[1])); } if(command == "cd"){ params = processParams(input, "cd", 1); if(params[0] == ".."){ if(!pwd.isRoot()){ pwd = manager.getFolder(pwd.parent); path = pwd.path; }else{ path = "/"; } }else{ if(pwd.isRoot()){ path = pwd.path + params[0]; }else{ path = pwd.path + "/" + params[0]; } if(manager.getFolder(path).notFound()) { cout << "not found" << endl; }else{ pwd = manager.getFolder(path); } } } if(command == "cp"){ params = processParams(input, "cp", 2); if(params.size() == 2){ bool local = isLocal(params[0]); string destination; if(local){ destination = getCurrentPath(params[1]); path = params[0]; }else{ path = getCurrentPath(params[0]); destination = params[1]; } copy(path, destination, local); } } if(command == "pwd"){ cout << pwd.path << endl; } if(command == "play"){ params = processParams(input, command, 1); /*if(params.size() == 1){ bool isNumber = true; // jedna se o cislo? for(int i = 0; i < (int)params.size();i++){ if(!isdigit(params[0][i])){ isNumber = false; } } if(isNumber){ play(pwd.path, lexical_cast<int>(params[0])); }else{ play(getCurrentPath(params[0])); } }else{ cout << "Wrond number of params" << endl; }*/ } if(command == "clear"){ system("clear"); } if(command == "mkdir") { params = processParams(input, command, 1); mkdir(pwd.path, params[0]); } if(command == "rename"){ params = processParams(input, "rename", 2); path = getCurrentPath(params[0]); rename(path, params[1]); } if(command == "rm") { params = processParams(input, command, 1); path = getCurrentPath(params[0]); rm(path); } if(command == "exit"){ // ukoncime ncurses endwin(); exit(1); } //cout << "rs#~" << pwd.path << " "; buffer.changeStart("rs#~" + pwd.path + " "); buffer.writeStart(); }; cout << endl; }
int main (int argc, char *argv[]) { parseCommandLine (argc, argv); pcl::PointCloud<PointType>::Ptr model (new pcl::PointCloud<PointType> ()); pcl::PointCloud<PointType>::Ptr model_keypoints (new pcl::PointCloud<PointType> ()); pcl::PointCloud<PointType>::Ptr scene (new pcl::PointCloud<PointType> ()); pcl::PointCloud<PointType>::Ptr scene_keypoints (new pcl::PointCloud<PointType> ()); pcl::PointCloud<NormalType>::Ptr model_normals (new pcl::PointCloud<NormalType> ()); pcl::PointCloud<NormalType>::Ptr scene_normals (new pcl::PointCloud<NormalType> ()); pcl::PointCloud<DescriptorType>::Ptr model_descriptors (new pcl::PointCloud<DescriptorType> ()); pcl::PointCloud<DescriptorType>::Ptr scene_descriptors (new pcl::PointCloud<DescriptorType> ()); /** * Load Clouds */ if (pcl::io::loadPCDFile (model_filename_, *model) < 0) { std::cout << "Error loading model cloud." << std::endl; showHelp (argv[0]); return (-1); } if (pcl::io::loadPCDFile (scene_filename_, *scene) < 0) { std::cout << "Error loading scene cloud." << std::endl; showHelp (argv[0]); return (-1); } /** * Compute Normals */ pcl::NormalEstimationOMP<PointType, NormalType> norm_est; norm_est.setKSearch (10); norm_est.setInputCloud (model); norm_est.compute (*model_normals); norm_est.setInputCloud (scene); norm_est.compute (*scene_normals); /** * Downsample Clouds to Extract keypoints */ pcl::UniformSampling<PointType> uniform_sampling; uniform_sampling.setInputCloud (model); uniform_sampling.setRadiusSearch (model_ss_); uniform_sampling.filter (*model_keypoints); std::cout << "Model total points: " << model->size () << "; Selected Keypoints: " << model_keypoints->size () << std::endl; uniform_sampling.setInputCloud (scene); uniform_sampling.setRadiusSearch (scene_ss_); uniform_sampling.filter (*scene_keypoints); std::cout << "Scene total points: " << scene->size () << "; Selected Keypoints: " << scene_keypoints->size () << std::endl; /** * Compute Descriptor for keypoints */ pcl::SHOTEstimationOMP<PointType, NormalType, DescriptorType> descr_est; descr_est.setRadiusSearch (descr_rad_); descr_est.setInputCloud (model_keypoints); descr_est.setInputNormals (model_normals); descr_est.setSearchSurface (model); descr_est.compute (*model_descriptors); descr_est.setInputCloud (scene_keypoints); descr_est.setInputNormals (scene_normals); descr_est.setSearchSurface (scene); descr_est.compute (*scene_descriptors); /** * Find Model-Scene Correspondences with KdTree */ pcl::CorrespondencesPtr model_scene_corrs (new pcl::Correspondences ()); pcl::KdTreeFLANN<DescriptorType> match_search; match_search.setInputCloud (model_descriptors); std::vector<int> model_good_keypoints_indices; std::vector<int> scene_good_keypoints_indices; for (size_t i = 0; i < scene_descriptors->size (); ++i) { std::vector<int> neigh_indices (1); std::vector<float> neigh_sqr_dists (1); if (!pcl_isfinite (scene_descriptors->at (i).descriptor[0])) //skipping NaNs { continue; } int found_neighs = match_search.nearestKSearch (scene_descriptors->at (i), 1, neigh_indices, neigh_sqr_dists); if (found_neighs == 1 && neigh_sqr_dists[0] < 0.25f) { pcl::Correspondence corr (neigh_indices[0], static_cast<int> (i), neigh_sqr_dists[0]); model_scene_corrs->push_back (corr); model_good_keypoints_indices.push_back (corr.index_query); scene_good_keypoints_indices.push_back (corr.index_match); } } pcl::PointCloud<PointType>::Ptr model_good_kp (new pcl::PointCloud<PointType> ()); pcl::PointCloud<PointType>::Ptr scene_good_kp (new pcl::PointCloud<PointType> ()); pcl::copyPointCloud (*model_keypoints, model_good_keypoints_indices, *model_good_kp); pcl::copyPointCloud (*scene_keypoints, scene_good_keypoints_indices, *scene_good_kp); std::cout << "Correspondences found: " << model_scene_corrs->size () << std::endl; /** * Clustering */ std::vector<Eigen::Matrix4f, Eigen::aligned_allocator<Eigen::Matrix4f> > rototranslations; std::vector < pcl::Correspondences > clustered_corrs; if (use_hough_) { pcl::PointCloud<RFType>::Ptr model_rf (new pcl::PointCloud<RFType> ()); pcl::PointCloud<RFType>::Ptr scene_rf (new pcl::PointCloud<RFType> ()); pcl::BOARDLocalReferenceFrameEstimation<PointType, NormalType, RFType> rf_est; rf_est.setFindHoles (true); rf_est.setRadiusSearch (rf_rad_); rf_est.setInputCloud (model_keypoints); rf_est.setInputNormals (model_normals); rf_est.setSearchSurface (model); rf_est.compute (*model_rf); rf_est.setInputCloud (scene_keypoints); rf_est.setInputNormals (scene_normals); rf_est.setSearchSurface (scene); rf_est.compute (*scene_rf); // Clustering pcl::Hough3DGrouping<PointType, PointType, RFType, RFType> clusterer; clusterer.setHoughBinSize (cg_size_); clusterer.setHoughThreshold (cg_thresh_); clusterer.setUseInterpolation (true); clusterer.setUseDistanceWeight (false); clusterer.setInputCloud (model_keypoints); clusterer.setInputRf (model_rf); clusterer.setSceneCloud (scene_keypoints); clusterer.setSceneRf (scene_rf); clusterer.setModelSceneCorrespondences (model_scene_corrs); clusterer.recognize (rototranslations, clustered_corrs); } else { pcl::GeometricConsistencyGrouping<PointType, PointType> gc_clusterer; gc_clusterer.setGCSize (cg_size_); gc_clusterer.setGCThreshold (cg_thresh_); gc_clusterer.setInputCloud (model_keypoints); gc_clusterer.setSceneCloud (scene_keypoints); gc_clusterer.setModelSceneCorrespondences (model_scene_corrs); gc_clusterer.recognize (rototranslations, clustered_corrs); } /** * Stop if no instances */ if (rototranslations.size () <= 0) { cout << "*** No instances found! ***" << endl; return (0); } else { cout << "Recognized Instances: " << rototranslations.size () << endl << endl; } /** * Generates clouds for each instances found */ std::vector<pcl::PointCloud<PointType>::ConstPtr> instances; for (size_t i = 0; i < rototranslations.size (); ++i) { pcl::PointCloud<PointType>::Ptr rotated_model (new pcl::PointCloud<PointType> ()); pcl::transformPointCloud (*model, *rotated_model, rototranslations[i]); instances.push_back (rotated_model); } /** * ICP */ std::vector<pcl::PointCloud<PointType>::ConstPtr> registered_instances; if (true) { cout << "--- ICP ---------" << endl; for (size_t i = 0; i < rototranslations.size (); ++i) { pcl::IterativeClosestPoint<PointType, PointType> icp; icp.setMaximumIterations (icp_max_iter_); icp.setMaxCorrespondenceDistance (icp_corr_distance_); icp.setInputTarget (scene); icp.setInputSource (instances[i]); pcl::PointCloud<PointType>::Ptr registered (new pcl::PointCloud<PointType>); icp.align (*registered); registered_instances.push_back (registered); cout << "Instance " << i << " "; if (icp.hasConverged ()) { cout << "Aligned!" << endl; } else { cout << "Not Aligned!" << endl; } } cout << "-----------------" << endl << endl; } /** * Hypothesis Verification */ cout << "--- Hypotheses Verification ---" << endl; std::vector<bool> hypotheses_mask; // Mask Vector to identify positive hypotheses pcl::GlobalHypothesesVerification<PointType, PointType> GoHv; GoHv.setSceneCloud (scene); // Scene Cloud GoHv.addModels (registered_instances, true); //Models to verify GoHv.setInlierThreshold (hv_inlier_th_); GoHv.setOcclusionThreshold (hv_occlusion_th_); GoHv.setRegularizer (hv_regularizer_); GoHv.setRadiusClutter (hv_rad_clutter_); GoHv.setClutterRegularizer (hv_clutter_reg_); GoHv.setDetectClutter (hv_detect_clutter_); GoHv.setRadiusNormals (hv_rad_normals_); GoHv.verify (); GoHv.getMask (hypotheses_mask); // i-element TRUE if hvModels[i] verifies hypotheses for (int i = 0; i < hypotheses_mask.size (); i++) { if (hypotheses_mask[i]) { cout << "Instance " << i << " is GOOD! <---" << endl; } else { cout << "Instance " << i << " is bad!" << endl; } } cout << "-------------------------------" << endl; /** * Visualization */ pcl::visualization::PCLVisualizer viewer ("Hypotheses Verification"); viewer.addPointCloud (scene, "scene_cloud"); pcl::PointCloud<PointType>::Ptr off_scene_model (new pcl::PointCloud<PointType> ()); pcl::PointCloud<PointType>::Ptr off_scene_model_keypoints (new pcl::PointCloud<PointType> ()); pcl::PointCloud<PointType>::Ptr off_model_good_kp (new pcl::PointCloud<PointType> ()); pcl::transformPointCloud (*model, *off_scene_model, Eigen::Vector3f (-1, 0, 0), Eigen::Quaternionf (1, 0, 0, 0)); pcl::transformPointCloud (*model_keypoints, *off_scene_model_keypoints, Eigen::Vector3f (-1, 0, 0), Eigen::Quaternionf (1, 0, 0, 0)); pcl::transformPointCloud (*model_good_kp, *off_model_good_kp, Eigen::Vector3f (-1, 0, 0), Eigen::Quaternionf (1, 0, 0, 0)); if (show_keypoints_) { CloudStyle modelStyle = style_white; pcl::visualization::PointCloudColorHandlerCustom<PointType> off_scene_model_color_handler (off_scene_model, modelStyle.r, modelStyle.g, modelStyle.b); viewer.addPointCloud (off_scene_model, off_scene_model_color_handler, "off_scene_model"); viewer.setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_POINT_SIZE, modelStyle.size, "off_scene_model"); } if (show_keypoints_) { CloudStyle goodKeypointStyle = style_violet; pcl::visualization::PointCloudColorHandlerCustom<PointType> model_good_keypoints_color_handler (off_model_good_kp, goodKeypointStyle.r, goodKeypointStyle.g, goodKeypointStyle.b); viewer.addPointCloud (off_model_good_kp, model_good_keypoints_color_handler, "model_good_keypoints"); viewer.setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_POINT_SIZE, goodKeypointStyle.size, "model_good_keypoints"); pcl::visualization::PointCloudColorHandlerCustom<PointType> scene_good_keypoints_color_handler (scene_good_kp, goodKeypointStyle.r, goodKeypointStyle.g, goodKeypointStyle.b); viewer.addPointCloud (scene_good_kp, scene_good_keypoints_color_handler, "scene_good_keypoints"); viewer.setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_POINT_SIZE, goodKeypointStyle.size, "scene_good_keypoints"); } for (size_t i = 0; i < instances.size (); ++i) { std::stringstream ss_instance; ss_instance << "instance_" << i; CloudStyle clusterStyle = style_red; pcl::visualization::PointCloudColorHandlerCustom<PointType> instance_color_handler (instances[i], clusterStyle.r, clusterStyle.g, clusterStyle.b); viewer.addPointCloud (instances[i], instance_color_handler, ss_instance.str ()); viewer.setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_POINT_SIZE, clusterStyle.size, ss_instance.str ()); CloudStyle registeredStyles = hypotheses_mask[i] ? style_green : style_cyan; ss_instance << "_registered" << endl; pcl::visualization::PointCloudColorHandlerCustom<PointType> registered_instance_color_handler (registered_instances[i], registeredStyles.r, registeredStyles.g, registeredStyles.b); viewer.addPointCloud (registered_instances[i], registered_instance_color_handler, ss_instance.str ()); viewer.setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_POINT_SIZE, registeredStyles.size, ss_instance.str ()); } while (!viewer.wasStopped ()) { viewer.spinOnce (); } return (0); }
int __cdecl wmain(const int argc, const wchar_t* argv[]) { auto programPath = _wcsdup(argv[0]); auto extension = wcsrchr(programPath, '.') + 1; if (wcscmp(extension, L"exe") != 0) { ::wprintf(W("This executable needs to have 'exe' extension")); return -1; } extension[0] = 'd'; extension[1] = 'l'; extension[2] = 'l'; // Parse the options from the command line bool verbose = false; bool waitForDebugger = false; bool helpRequested = false; int newArgc = argc - 1; const wchar_t **newArgv = argv + 1; auto stringsEqual = [](const wchar_t * const a, const wchar_t * const b) -> bool { return ::_wcsicmp(a, b) == 0; }; auto tryParseOption = [&](const wchar_t* arg) -> bool { if ( stringsEqual(arg, W("/_v")) || stringsEqual(arg, W("-_v")) ) { verbose = true; return true; } else if ( stringsEqual(arg, W("/_d")) || stringsEqual(arg, W("-_d")) ) { waitForDebugger = true; return true; } else if ( stringsEqual(arg, W("/_h")) || stringsEqual(arg, W("-_h")) ) { helpRequested = true; return true; } else { return false; } }; while (newArgc > 0 && tryParseOption(newArgv[0])) { newArgc--; newArgv++; } if (helpRequested) { showHelp(); return -1; } else { Logger log; if (verbose) { log.Enable(); } else { log.Disable(); } DWORD exitCode; auto success = TryRun(newArgc, newArgv, log, verbose, waitForDebugger, exitCode, programPath); log << W("Execution ") << (success ? W("succeeded") : W("failed")) << Logger::endl; return exitCode; } }
int main(int argc, char ** argv) { //string that will hold the API key std::string key = ""; //whether to wait a while before the first request bool initial_wait = false; //resources that will be queried std::unordered_set<std::string> resources_report = std::unordered_set<std::string>(); //resources for which a rescan will be requested std::unordered_set<std::string> resources_rescan = std::unordered_set<std::string>(); //files for which an upload and scan std::unordered_set<std::string> files_scan = std::unordered_set<std::string>(); if ((argc > 1) and (argv != nullptr)) { int i=1; while (i<argc) { if (argv[i] != nullptr) { const std::string param = std::string(argv[i]); //help parameter if ((param=="--help") or (param=="-?") or (param=="/?")) { showHelp(); return 0; }//help //version information requested? else if ((param=="--version") or (param=="-v")) { showVersion(); return 0; } //version else if ((param=="--key") or (param=="--apikey")) { //enough parameters? if ((i+1 < argc) and (argv[i+1] != nullptr)) { key = std::string(argv[i+1]); ++i; //skip next parameter, because it's used as API key already #ifdef SCAN_TOOL_DEBUG std::cout << "API key was set to \"" << key << "\"." << std::endl; #endif } else { std::cout << "Error: You have to enter some text after \"" << param <<"\"." << std::endl; return scantool::rcInvalidParameter; } }//API key else if (param=="--keyfile") { //only one key required if (!key.empty()) { std::cout << "Error: API key was already specified!" << std::endl; return scantool::rcInvalidParameter; } //enough parameters? if ((i+1 < argc) and (argv[i+1] != nullptr)) { const std::string keyfile = std::string(argv[i+1]); if (!libstriezel::filesystem::file::exists(keyfile)) { std::cout << "Error: The specified key file " << keyfile << " does not exist!" << std::endl; /* Technically it's a file error, but let's return "invalid parameter" here, because the file name parameter is wrong/ invalid. */ return scantool::rcInvalidParameter; } //if file does not exist Configuration conf; if (!conf.loadFromFile(keyfile)) { std::cout << "Error: Could not load key from file " << keyfile << "!" << std::endl; return scantool::rcFileError; } if (conf.apikey().empty()) { std::cout << "Error: Key file " << keyfile << " does not contain" << " an API key!" << std::endl; return scantool::rcFileError; } key = conf.apikey(); ++i; //Skip next parameter, because it's used as key file already. #ifdef SCAN_TOOL_DEBUG std::cout << "API key was set to \"" << key << "\"." << std::endl; #endif } else { std::cout << "Error: You have to enter a file name after \"" << param <<"\"." << std::endl; return scantool::rcInvalidParameter; } } //API key from file else if ((param=="--report") or (param=="--resource")) { //enough parameters? if ((i+1 < argc) and (argv[i+1] != nullptr)) { const std::string next_resource = std::string(argv[i+1]); ++i; //skip next parameter, because it's used as resource identifier already if (resources_report.find(next_resource) == resources_report.end()) { std::cout << "Adding resource " << next_resource << " to list of report requests." << std::endl; } resources_report.insert(next_resource); } else { std::cout << "Error: You have to enter a resource ID after \"" << param << "\"." << std::endl; return scantool::rcInvalidParameter; } }//resource report else if ((param=="--re") or (param=="--rescan")) { //enough parameters? if ((i+1 < argc) and (argv[i+1] != nullptr)) { const std::string next_resource = std::string(argv[i+1]); ++i; //Skip next parameter, because it's used as resource identifier already if (resources_rescan.find(next_resource) == resources_rescan.end()) { std::cout << "Adding resource " << next_resource << " to list of rescan requests." << std::endl; } resources_rescan.insert(next_resource); } else { std::cout << "Error: You have to enter a resource ID after \"" << param << "\"." << std::endl; return scantool::rcInvalidParameter; } }//rescan else if ((param=="--file") or (param=="--scan")) { //enough parameters? if ((i+1 < argc) and (argv[i+1] != nullptr)) { const std::string next_file = std::string(argv[i+1]); ++i; //Skip next parameter, because it's used as filename already. if (files_scan.find(next_file) == files_scan.end()) { std::cout << "Adding file " << next_file << " to list of scan files." << std::endl; } files_scan.insert(next_file); } else { std::cout << "Error: You have to enter a file name after \"" << param << "\"." << std::endl; return scantool::rcInvalidParameter; } }//scan file else if ((param=="--initial-wait") or (param=="--wait")) { //Was the parameter already set? if (initial_wait) { std::cout << "Error: Parameter " << param << " must not occur more than once!" << std::endl; return scantool::rcInvalidParameter; } initial_wait = true; } //initial_wait else { //unknown or wrong parameter std::cout << "Invalid parameter given: \"" << param << "\"." << std::endl << "Use --help to get a list of valid parameters.\n"; return scantool::rcInvalidParameter; } }//parameter exists else { std::cout << "Parameter at index " << i << " is null pointer." << std::endl; return scantool::rcInvalidParameter; } ++i;//on to next parameter }//while }//if arguments present if (key.empty()) { std::cout << "Error: This program won't work properly without an API key! " << "Use --apikey to specify the VirusTotal API key." << std::endl; return scantool::rcInvalidParameter; } if (resources_report.empty() && resources_rescan.empty() && files_scan.empty()) { std::cout << "No resources for report retrieval, rescan or file scan were given. Exiting." << std::endl; return scantool::rcInvalidParameter; } //if not resources scantool::virustotal::ScannerV2 scanVT(key); //initial wait to avoid exceeding the rate limit if (initial_wait) { const auto duration = scanVT.timeBetweenConsecutiveScanRequests(); std::cout << "Waiting " << std::chrono::duration_cast<std::chrono::milliseconds>(duration).count() << " millisecond(s) for time limit to expire as requested..." << std::endl; std::this_thread::sleep_for(duration); } //iterate over all resources for rescan requests for(const std::string& i : resources_rescan) { std::string scan_id = ""; if (!scanVT.rescan(i, scan_id)) { std::cout << "Error: Could not initiate rescan for \"" << i << "\"!" << std::endl; return scantool::rcScanError; } std::cout << "Rescan for \"" << i << "\" initiated. " << "Scan-ID for later retrieval is " << scan_id << "." << std::endl; } //for (range-based) //iterate over all resources for report requests for(const std::string& i : resources_report) { scantool::virustotal::ScannerV2::Report report; if (!scanVT.getReport(i, report, false, std::string())) { std::cout << "Error: Could not retrieve report!" << std::endl; return scantool::rcScanError; } std::cout << std::endl; std::cout << "Report data for " << i << ":" << std::endl << " response code: " << report.response_code << std::endl << " verbose message: " << report.verbose_msg << std::endl << " resource: " << report.resource << std::endl << " scan_id: " << report.scan_id << std::endl << " scan_date: " << report.scan_date << std::endl << " scan engines: " << report.total << std::endl << " engines that detected a threat: " << report.positives << std::endl << " permanent link: " << report.permalink << std::endl << " SHA256: " << report.sha256 << std::endl; for (const auto& eng : report.scans) { const auto eng2 = static_cast<scantool::virustotal::EngineV2*>(eng.get()); std::cout << " Engine " << eng->engine << " (version " << eng2->version << " of " << eng2->update << ")"; if (eng->detected) std::cout << " detected " << eng->result << std::endl; else std::cout << " found nothing." << std::endl; } //for (inner, range-based) } //for (range-based) //iterate over all files for scan requests for(const std::string& i : files_scan) { std::string scan_id = ""; if (!scanVT.scan(i, scan_id)) { std::cout << "Error: Could not initiate scan for \"" << i << "\"!" << std::endl; return scantool::rcScanError; } std::cout << "Scan for " << i << " initiated. " << "Scan-ID for later retrieval is " << scan_id << "." << std::endl; } //for (range-based) return 0; }
int main(int argc, char* argv[]) { int opt; char hostName[200] = DEFAULT_HOSTNAME; int port = DEFAULT_RESMGR_TPM_PORT; int returnVal = 0; struct option sOpts[] = { { "index" , required_argument, NULL, 'x' }, { "authHandle" , required_argument, NULL, 'a' }, { "handlePasswd", required_argument, NULL, 'P' }, { "passwdInHex" , no_argument, NULL, 'X' }, { "port" , required_argument, NULL, 'p' }, { "dbg" , required_argument, NULL, 'd' }, { "help" , no_argument, NULL, 'h' }, { "version" , no_argument, NULL, 'v' }, { NULL , no_argument, NULL, 0 }, }; if( argc == 1) { showHelp(argv[0]); return 0; } if( argc > (int)(2*sizeof(sOpts)/sizeof(struct option)) ) { showArgMismatch(argv[0]); return -1; } while ( ( opt = getopt_long( argc, argv, "x:a:P:Xp:d:hv", sOpts, NULL ) ) != -1 ) { switch ( opt ) { case 'h': case '?': showHelp(argv[0]); return 0; case 'v': showVersion(argv[0]); return 0; case 'x': if( getSizeUint32Hex(optarg, &nvIndex) != 0 ) { return -2; } break; case 'a': if( getSizeUint32Hex(optarg, &authHandle) != 0 ) { return -3; } break; case 'P': if( optarg == NULL || (strlen(optarg) >= sizeof(TPMU_HA)) ) { printf("\nPlease input the handle password(optional,no more than %d characters).\n", (int)sizeof(TPMU_HA)-1); return -4; } safeStrNCpy( handlePasswd, optarg, sizeof(handlePasswd) ); break; case 'X': hexPasswd = true; break; case 'p': if( getPort(optarg, &port) ) { printf("Incorrect port number.\n"); return -7; } break; case 'd': if( getDebugLevel(optarg, &debugLevel) ) { printf("Incorrect debug level.\n"); return -8; } break; default: showArgMismatch(argv[0]); return -9; } } if( nvIndex == 0 ) { printf("You must provide an index (!= 0) for the NVRAM area.\n"); return -10; } if( authHandle == 0 ) { printf("You must provide an right auth handle for this operation.\n"); return -11; } prepareTest(hostName, port, debugLevel); returnVal = nvReadLock(authHandle, nvIndex); finishTest(); if(returnVal) return -12; return 0; }
////////////////////////////////////////////////////////////////////////////// // Program main ////////////////////////////////////////////////////////////////////////////// int main( int argc, char** argv) { bool bTestResults = true; shrQAStart(argc, argv); if( cutCheckCmdLineFlag(argc, (const char**)argv, "help") ) { showHelp(); return 0; } shrLog("Run \"nbody -benchmark [-n=<numBodies>]\" to measure perfomance.\n"); shrLog("\t-fullscreen (run n-body simulation in fullscreen mode)\n"); shrLog("\t-fp64 (use double precision floating point values for simulation)\n"); shrLog("\t-numdevices=N (use first N CUDA devices for simulation)\n"); // shrLog("\t-hostmem (stores simulation data in host memory)\n"); // shrLog("\t-cpu (performs simulation on the host)\n"); shrLog("\n"); bFullscreen = (cutCheckCmdLineFlag(argc, (const char**) argv, "fullscreen") != 0); if (bFullscreen) bShowSliders = false; benchmark = (cutCheckCmdLineFlag(argc, (const char**) argv, "benchmark") != 0); compareToCPU = ((cutCheckCmdLineFlag(argc, (const char**) argv, "compare") != 0) || (cutCheckCmdLineFlag(argc, (const char**) argv, "qatest") != 0)); QATest = (cutCheckCmdLineFlag(argc, (const char**) argv, "qatest") != 0); useHostMem = (cutCheckCmdLineFlag(argc, (const char**) argv, "hostmem") != 0); fp64 = (cutCheckCmdLineFlag(argc, (const char**) argv, "fp64") != 0); flopsPerInteraction = fp64 ? 30 : 20; useCpu = (cutCheckCmdLineFlag(argc, (const char**) argv, "cpu") != 0); cutGetCmdLineArgumenti(argc, (const char**) argv, "numdevices", &numDevsRequested); // for multi-device we currently require using host memory -- the devices share // data via the host if (numDevsRequested > 1) useHostMem = true; int numDevsAvailable = 0; bool customGPU = false; cudaGetDeviceCount(&numDevsAvailable); if (numDevsAvailable < numDevsRequested) { shrLog("Error: only %d Devices available, %d requested. Exiting.\n", numDevsAvailable, numDevsRequested); shrQAFinishExit(argc, (const char **)argv, QA_PASSED); } shrLog("> %s mode\n", bFullscreen ? "Fullscreen" : "Windowed"); shrLog("> Simulation data stored in %s memory\n", useHostMem ? "system" : "video" ); shrLog("> %s precision floating point simulation\n", fp64 ? "Double" : "Single"); shrLog("> %d Devices used for simulation\n", numDevsRequested); int devID; cudaDeviceProp props; // Initialize GL and GLUT if necessary if (!benchmark && !compareToCPU) { initGL(&argc, argv); initParameters(); } if (useCpu) { useHostMem = true; compareToCPU = false; bSupportDouble = true; #ifdef OPENMP shrLog("> Simulation with CPU using OpenMP\n"); #else shrLog("> Simulation with CPU\n"); #endif } else { // Now choose the CUDA Device // Either without GL interop: if (benchmark || compareToCPU || useHostMem) { // Note if we are using host memory for the body system, we // don't use CUDA-GL interop. if( cutCheckCmdLineFlag(argc, (const char**)argv, "device") ) { devID = cutilDeviceInit(argc, argv); if (devID < 0) { printf("exiting...\n"); shrQAFinishExit(argc, (const char **)argv, QA_PASSED); } customGPU = true; } else { devID = cutGetMaxGflopsDeviceId(); cudaSetDevice( devID ); } } else // or with GL interop: { if( cutCheckCmdLineFlag(argc, (const char**)argv, "device") ) { cutilGLDeviceInit(argc, argv); customGPU = true; } else { devID = cutGetMaxGflopsDeviceId(); cudaGLSetGLDevice( devID ); } } cutilSafeCall(cudaGetDevice(&devID)); cutilSafeCall(cudaGetDeviceProperties(&props, devID)); bSupportDouble = true; #if CUDART_VERSION < 4000 if (numDevsRequested > 1) { shrLog("MultiGPU n-body requires CUDA 4.0 or later\n"); cutilDeviceReset(); shrQAFinishExit(argc, (const char**)argv, QA_PASSED); } #endif // Initialize devices if(numDevsRequested > 1 && customGPU) { printf("You can't use --numdevices and --device at the same time.\n"); shrQAFinishExit(argc, (const char**)argv, QA_PASSED); } if(customGPU) { cudaDeviceProp props; cutilSafeCall(cudaGetDeviceProperties(&props, devID)); shrLog("> Compute %d.%d CUDA device: [%s]\n", props.major, props.minor, props.name); } else { for (int i = 0; i < numDevsRequested; i++) { cudaDeviceProp props; cutilSafeCall(cudaGetDeviceProperties(&props, i)); shrLog("> Compute %d.%d CUDA device: [%s]\n", props.major, props.minor, props.name); if (useHostMem) { #if CUDART_VERSION >= 2020 if(!props.canMapHostMemory) { fprintf(stderr, "Device %d cannot map host memory!\n", devID); cutilDeviceReset(); shrQAFinishExit(argc, (const char **)argv, QA_PASSED); } if (numDevsRequested > 1) cutilSafeCall(cudaSetDevice(i)); cutilSafeCall(cudaSetDeviceFlags(cudaDeviceMapHost)); #else fprintf(stderr, "This CUDART version does not support <cudaDeviceProp.canMapHostMemory> field\n"); cutilDeviceReset(); shrQAFinishExit(argc, (const char **)argv, QA_PASSED); #endif } } // CC 1.2 and earlier do not support double precision if (props.major*10 + props.minor <= 12) bSupportDouble = false; } //if(numDevsRequested > 1) // cutilSafeCall(cudaSetDevice(devID)); if (fp64 && !bSupportDouble) { fprintf(stderr, "One or more of the requested devices does not support double precision floating-point\n"); cutilDeviceReset(); shrQAFinishExit(argc, (const char **)argv, QA_PASSED); } } numIterations = 0; p = 0; q = 1; cutGetCmdLineArgumenti(argc, (const char**) argv, "i", &numIterations); cutGetCmdLineArgumenti(argc, (const char**) argv, "p", &p); cutGetCmdLineArgumenti(argc, (const char**) argv, "q", &q); if (p == 0) // p not set on command line { p = 256; if (q * p > 256) { p = 256 / q; shrLog("Setting p=%d, q=%d to maintain %d threads per block\n", p, q, 256); } } // default number of bodies is #SMs * 4 * CTA size if (useCpu) #ifdef OPENMP numBodies = 8192; #else numBodies = 4096; #endif else if (numDevsRequested == 1)
int main(int argc, char *argv[]) { int en_daemonize = 0; int i; for(i=1; i<argc; i++){ if(!strcmp(argv[i], "-d")){ en_daemonize = 1; //daemonize("/tmp", "/tmp/pikeyd.pid"); } if(!strcmp(argv[i], "-k")){ daemonKill("/tmp/pikeyd.pid"); exit(0); } if(!strcmp(argv[i], "-r")){ joy_enable_repeat(); } if(!strcmp(argv[i], "-v")){ showVersion(); exit(0); } if(!strcmp(argv[i], "-h")){ showHelp(); exit(0); } } if(en_daemonize){ daemonize("/tmp", "/tmp/pikeyd.pid"); } init_iic(); init_config(); //test_config(); exit(0); //test_iic(0x20); close_iic(); exit(0); //printf("init uinput\n"); if(init_uinput() == 0){ sleep(1); //test_uinput(); if(joy_RPi_init()>=0){ if(!en_daemonize){ printf("Press ^C to exit.\n"); } for(;;){ joy_RPi_poll(); usleep(4000); } joy_RPi_exit(); } close_uinput(); } return 0; }
MainForm::MainForm(QWidget *parent): QMainWindow(parent) { setupUi(this); ///!!!!! //alignButton->hide(); //unalignButton->hide(); setWindowTitle("YAGF"); spellChecker = new SpellChecker(textEdit); spellChecker->enumerateDicts(); selectLangsBox = new QComboBox(); QLabel *label = new QLabel(); label->setMargin(4); label->setText(trUtf8("Recognition language")); frame->show(); toolBar->addWidget(label); selectLangsBox->setFrame(true); toolBar->addWidget(selectLangsBox); graphicsInput = new QGraphicsInput(QRectF(0, 0, 2000, 2000), graphicsView) ; graphicsInput->addToolBarAction(actionHideShowTolbar); graphicsInput->addToolBarAction(this->actionTBLV); graphicsInput->addToolBarAction(this->actionSmaller_view); graphicsInput->addToolBarSeparator(); graphicsInput->addToolBarAction(actionRotate_90_CCW); graphicsInput->addToolBarAction(actionRotate_180); graphicsInput->addToolBarAction(actionRotate_90_CW); graphicsInput->addToolBarAction(actionDeskew); graphicsInput->addToolBarSeparator(); graphicsInput->addToolBarAction(actionSelect_Text_Area); graphicsInput->addToolBarAction(actionSelect_multiple_blocks); graphicsInput->addToolBarAction(ActionClearAllBlocks); statusBar()->show(); imageLoaded = false; useXSane = TRUE; textSaved = TRUE; hasCopy = false; //rotation = 0; m_menu = new QMenu(graphicsView); ifCounter = 0; connect(actionOpen, SIGNAL(triggered()), this, SLOT(loadImage())); connect(actionQuit, SIGNAL(triggered()), this, SLOT(close())); connect(this, SIGNAL(windowShown()), this, SLOT(onShowWindow()), Qt::QueuedConnection); connect(actionScan, SIGNAL(triggered()), this, SLOT(scanImage())); connect(actionPreviousPage, SIGNAL(triggered()), this, SLOT(loadPreviousPage())); connect(actionNextPage, SIGNAL(triggered()), this, SLOT(loadNextPage())); connect(actionRecognize, SIGNAL(triggered()), this, SLOT(recognize())); connect(action_Save, SIGNAL(triggered()), this, SLOT(saveText())); connect(actionAbout, SIGNAL(triggered()), this, SLOT(showAboutDlg())); connect(actionOnlineHelp, SIGNAL(triggered()), this, SLOT(showHelp())); connect(actionCopyToClipboard, SIGNAL(triggered()), this, SLOT(copyClipboard())); textEdit->setContextMenuPolicy(Qt::CustomContextMenu); connect(textEdit, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(contextMenuRequested(QPoint))); connect(textEdit, SIGNAL(copyAvailable(bool)), this, SLOT(copyAvailable(bool))); connect(textEdit, SIGNAL(textChanged()), this, SLOT(textChanged())); connect(graphicsInput, SIGNAL(rightMouseClicked(int, int, bool)), this, SLOT(rightMouseClicked(int, int, bool))); tesMap = new TesMap(); fillLanguagesBox(); initSettings(); delTmpFiles(); scanProcess = new QProcess(this); QXtUnixSignalCatcher::connectUnixSignal(SIGUSR2); ba = new QByteArray(); connect(QXtUnixSignalCatcher::catcher(), SIGNAL(unixSignal(int)), this, SLOT(readyRead(int))); connect(textEdit->document(), SIGNAL(cursorPositionChanged(const QTextCursor &)), this, SLOT(updateSP())); //displayLabel->installEventFilter(this); textEdit->installEventFilter(this); QPixmap l_cursor; l_cursor.load(":/resize.png"); resizeCursor = new QCursor(l_cursor); graphicsInput->setMagnifierCursor(resizeCursor); l_cursor.load(":/resize_block.png"); resizeBlockCursor = new QCursor(l_cursor); // textEdit->setContextMenuPolicy(Qt::ActionsContextMenu); this->sideBar->show(); connect(sideBar, SIGNAL(fileSelected(const QString &)), this, SLOT(fileSelected(const QString &))); connect(actionRecognize_All_Pages, SIGNAL(triggered()), this, SLOT(recognizeAll())); graphicsInput->setSideBar(sideBar); QPixmap pm; pm.load(":/align.png"); //alignButton->setIcon(pm); pm.load(":/undo.png"); //unalignButton->setIcon(pm); //connect(unalignButton, SIGNAL(clicked()), this, SLOT(unalignButtonClicked())); //clearBlocksButton->setDefaultAction(ActionClearAllBlocks); loadFromCommandLine(); emit windowShown(); pdfx = NULL; if (findProgram("pdftoppm")) { pdfx = new PDF2PPT(); } else if (findProgram("gs")) { pdfx = new GhostScr(); } if (pdfx) { connect(pdfx, SIGNAL(addPage(QString)), this, SLOT(addPDFPage(QString)), Qt::QueuedConnection); connect (pdfx, SIGNAL(finished()), this, SLOT(finishedPDF())); } pdfPD.setWindowTitle("YAGF"); pdfPD.setLabelText(trUtf8("Importing pages from the PDF document...")); pdfPD.setCancelButtonText(trUtf8("Cancel")); pdfPD.setMinimum(-1); pdfPD.setMaximum(-1); pdfPD.setWindowIcon(QIcon(":/yagf.png")); if (pdfx) connect(&pdfPD, SIGNAL(canceled()), pdfx, SLOT(cancel())); }
int main(int argc, char **argv) { bool readStdin = false; int numOptions = 0; QString user; Session session = DefaultSession; QString sessionName; bool updateUserTime = true; cin_.setEncoding(QTextStream::Locale); // Scan for command-line options first for(int pos = 1; pos <= argc - 1; pos++) { if(strcmp(argv[pos], "--help") == 0) showHelp(0); else if(strcmp(argv[pos], "--pipe") == 0) { readStdin = true; numOptions++; } else if(strcmp(argv[pos], "--user") == 0) { if(pos <= argc - 2) { user = QString::fromLocal8Bit(argv[pos + 1]); numOptions += 2; pos++; } else { cerr_ << "Missing username for '--user' option!" << endl << endl; showHelp(-1); } } else if(strcmp(argv[pos], "--session") == 0) { if(session == AllSessions) { cerr_ << "ERROR: --session cannot be mixed with --all-sessions!" << endl << endl; showHelp(-1); } else if(pos <= argc - 2) { sessionName = QString::fromLocal8Bit(argv[pos + 1]); numOptions += 2; pos++; } else { cerr_ << "Missing session name for '--session' option!" << endl << endl; showHelp(-1); } } else if(strcmp(argv[pos], "--all-users") == 0) { user = "******"; numOptions++; } else if(strcmp(argv[pos], "--list-sessions") == 0) { session = QuerySessions; numOptions++; } else if(strcmp(argv[pos], "--all-sessions") == 0) { if(!sessionName.isEmpty()) { cerr_ << "ERROR: --session cannot be mixed with --all-sessions!" << endl << endl; showHelp(-1); } session = AllSessions; numOptions++; } else if(strcmp(argv[pos], "--no-user-time") == 0) { updateUserTime = false; numOptions++; } else if(argv[pos][0] == '-') { cerr_ << "Unknown command-line option '" << argv[pos] << "'." << endl << endl; showHelp(-1); } else break; // End of options } argc -= numOptions; KStringList args; #ifdef DCOPQUIT if(argc > 1) { QCString prog = argv[numOptions + 1]; if(!prog.isEmpty()) { args.append(prog); // Pass as-is if it ends with a wildcard if(prog[prog.length() - 1] != '*') { // Strip a trailing -<PID> part. int i = prog.findRev('-'); if((i >= 0) && prog.mid(i + 1).toLong()) { prog = prog.left(i); } args.append("qt/" + prog); args.append("quit()"); } } } #else for(int i = numOptions; i < argc + numOptions - 1; i++) args.append(argv[i + 1]); #endif if(readStdin && args.count() < 3) { cerr_ << "--pipe option only supported for function calls!" << endl << endl; showHelp(-1); } if(user == "*" && args.count() < 3 && session != QuerySessions) { cerr_ << "ERROR: The --all-users option is only supported for function calls!" << endl << endl; showHelp(-1); } if(session == QuerySessions && !args.isEmpty()) { cerr_ << "ERROR: The --list-sessions option cannot be used for actual DCOP calls!" << endl << endl; showHelp(-1); } if(session == QuerySessions && user.isEmpty()) { cerr_ << "ERROR: The --list-sessions option can only be used with the --user or" << endl << "--all-users options!" << endl << endl; showHelp(-1); } if(session != DefaultSession && session != QuerySessions && args.count() < 3) { cerr_ << "ERROR: The --session and --all-sessions options are only supported for function" << endl << "calls!" << endl << endl; showHelp(-1); } UserList users; if(user == "*") users = userList(); else if(!user.isEmpty()) users[user] = userList()[user]; int retval = runDCOP(args, users, session, sessionName, readStdin, updateUserTime); return retval; }
void parseCommandLine (int argc, char *argv[]) { //Show help if (pcl::console::find_switch (argc, argv, "-h")) { showHelp (argv[0]); exit (0); } //Model & scene filenames std::vector<int> filenames; filenames = pcl::console::parse_file_extension_argument (argc, argv, ".pcd"); if (filenames.size () != 2) { std::cout << "Filenames missing.\n"; showHelp (argv[0]); exit (-1); } model_filename_ = argv[filenames[0]]; scene_filename_ = argv[filenames[1]]; //Program behavior if (pcl::console::find_switch (argc, argv, "-k")) { show_keypoints_ = true; } if (pcl::console::find_switch (argc, argv, "-c")) { show_correspondences_ = true; } if (pcl::console::find_switch (argc, argv, "-r")) { use_cloud_resolution_ = true; } if (pcl::console::find_switch (argc, argv, "-ac")) { show_all_correspondences_ = true; } std::string used_algorithm; if (pcl::console::parse_argument (argc, argv, "--algorithm", used_algorithm) != -1) { if (used_algorithm.compare ("Hough") == 0) { use_hough_ = true; }else if (used_algorithm.compare ("GC") == 0) { use_hough_ = false; } else { std::cout << "Wrong algorithm name.\n"; showHelp (argv[0]); exit (-1); } } //General parameters pcl::console::parse_argument (argc, argv, "--model_ss", model_ss_); pcl::console::parse_argument (argc, argv, "--scene_ss", scene_ss_); pcl::console::parse_argument (argc, argv, "--rf_rad", rf_rad_); pcl::console::parse_argument (argc, argv, "--descr_rad", descr_rad_); pcl::console::parse_argument (argc, argv, "--cg_size", cg_size_); pcl::console::parse_argument (argc, argv, "--cg_thresh", cg_thresh_); }
int showHelpCommand(char* param1, char* param2) { showHelp(&shell_wnd); return 1; }
int main(int argc, char *argv[]) { Options options; bool options_chosen = false; std::vector<std::string> filenames; for (int i = 1; i < argc; i++) { std::string s = argv[i]; if(s[0] == '-' && s.size() > 1) { if(s != "-x") options_chosen = true; //only selecting hexadecimal is no choice, keep the defaults for(size_t j = 1; j < s.size(); j++) { char c = s[j]; if(c == 'h') { showHelp(); return 0; } else if(c == 's') options.show_png_summary = true; else if(c == 'p') options.show_png_info = true; else if(c == 'P') { options.show_png_info = true; options.show_extra_png_info = true; } else if(c == 'l') options.show_palette = true; else if(c == 'L') options.show_palette_pixels = true; else if(c == 'a') options.show_ascii_art = true; else if(c == 'A') { options.show_ascii_art = true; options.ascii_art_size += 40; } else if(c == '#') options.show_colors_hex = true; else if(c == '@') options.show_colors_hex_16 = true; else if(c == 'c') options.show_chunks = true; else if(c == 'C') options.show_chunks2 = true; else if(c == 'f') options.show_filters = true; else if(c == 'z') options.zlib_info = true; else if(c == 'b') options.zlib_blocks = true; else if(c == 'B') { options.zlib_blocks = true; options.zlib_counts = true; } else if(c == '7') { options.zlib_blocks = true; options.zlib_full = true; } else if(c == 'x') { options.use_hex = true; std::cout << std::hex; } else { std::cout << "Unknown flag: " << c << ". Use -h for help" << std::endl; return 0; } } } else filenames.push_back(s); } if(filenames.empty()) { std::cout << "Please provide a filename to preview" << std::endl; showHelp(); return 0; } if(!options_chosen) { //fill in defaults options.show_png_info = true; options.show_chunks = true; options.show_filters = true; options.zlib_info = true; } for(size_t i = 0; i < filenames.size(); i++) { if(filenames.size() > 1) std::cout << filenames[i] << std::endl; showFileInfo(filenames[i], options); } }
int runUic(int argc, char *argv[]) { Driver driver; const char *fileName = 0; int arg = 1; while (arg < argc) { QString opt = QString::fromLocal8Bit(argv[arg]); if (opt == QLatin1String("-h") || opt == QLatin1String("-help")) { showHelp(argv[0]); return 0; } else if (opt == QLatin1String("-d") || opt == QLatin1String("-dependencies")) { driver.option().dependencies = true; } else if (opt == QLatin1String("-v") || opt == QLatin1String("-version")) { fprintf(stderr, "Qt User Interface Compiler version %s\n", QT_VERSION_STR); return 0; } else if (opt == QLatin1String("-o") || opt == QLatin1String("-output")) { ++arg; if (!argv[arg]) { showHelp(argv[0]); return 1; } driver.option().outputFile = QFile::decodeName(argv[arg]); } else if (opt == QLatin1String("-p") || opt == QLatin1String("-no-protection")) { driver.option().headerProtection = false; } else if (opt == QLatin1String("-n") || opt == QLatin1String("-no-implicit-includes")) { driver.option().implicitIncludes = false; } else if (opt == QLatin1String("-postfix")) { ++arg; if (!argv[arg]) { showHelp(argv[0]); return 1; } driver.option().postfix = QLatin1String(argv[arg]); } else if (opt == QLatin1String("-3")) { ++arg; if (!argv[arg]) { showHelp(argv[0]); return 1; } driver.option().uic3 = QFile::decodeName(argv[arg]); } else if (opt == QLatin1String("-tr") || opt == QLatin1String("-translate")) { ++arg; if (!argv[arg]) { showHelp(argv[0]); return 1; } driver.option().translateFunction = QLatin1String(argv[arg]); } else if (opt == QLatin1String("-g") || opt == QLatin1String("-generator")) { ++arg; if (!argv[arg]) { showHelp(argv[0]); return 1; } QString name = QString::fromLocal8Bit(argv[arg]).toLower (); driver.option().generator = (name == QLatin1String ("java")) ? Option::JavaGenerator : Option::CppGenerator; } else if (!fileName) { fileName = argv[arg]; } else { showHelp(argv[0]); return 1; } ++arg; } QString inputFile; if (fileName) inputFile = QString::fromLocal8Bit(fileName); else driver.option().headerProtection = false; if (driver.option().dependencies) { return !driver.printDependencies(inputFile); } QTextStream *out = 0; QFile f; if (driver.option().outputFile.size()) { f.setFileName(driver.option().outputFile); if (!f.open(QIODevice::WriteOnly | QFile::Text)) { fprintf(stderr, "Could not create output file\n"); return 1; } out = new QTextStream(&f); out->setCodec(QTextCodec::codecForName("UTF-8")); } bool rtn = driver.uic(inputFile, out); delete out; if (!rtn) { if (driver.option().outputFile.size()) { f.close(); f.remove(); } fprintf(stderr, "File '%s' is not valid\n", inputFile.isEmpty() ? "<stdin>" : inputFile.toLocal8Bit().constData()); } return !rtn; }
/** * Function: main() * Description: main routine of the shell. * Synopsis: int main(int argc, char* argv[]) (conforms to ANSI C) * Return value: * o An integer, indicating exit status. */ int main(int argc, char* argv[]) { char* prompts[] = { "msh", "rshell", "rsnoop" }; enum { P_MSH, P_RSHELL, P_RSNOOP }; int prompt = P_MSH; printf ( "\nWelcome to Microshell Client\nVersion: %s\nType '?' for help.\n", MICROSHELL_VERSION ); memset(&status, 0, sizeof(sh_status_t)); init(); /* We loop until we get the quit signal */ while(status.curr_signal != SH_QUIT) { char cmdline[CMD_LINE_MAX_CHARS] = {0}; /*sh_commands cmd_type;*/ /* Save our state here to restart from here * in case we got interrupted by a SIGALRM */ if(sigsetjmp(jmpbuf, SIGALRM)) { } /* Prompt */ printf("\n%s> ", prompts[prompt]); fgets(cmdline, CMD_LINE_MAX_CHARS, stdin); /* A copy of a command line for processing */ strcpy(status.cmdline, cmdline); if(status.curr_signal == SH_REMOTE) { if(prompt == P_RSHELL) rshell(cmdline); else rsnoop(cmdline); } else { /* Parse the command line */ status.curr_cmd = parseCmd(cmdline); prompt = P_MSH; /* Dispatch according to the command type */ switch(status.curr_cmd) { case QUIT: status.curr_signal = SH_QUIT; /*disconnect();*/ break; case SRV_RSHELL: /*rshell(cmdline);*/ connectSnoopSrv(cmdline); prompt = P_RSHELL; break; case SRV_RSNOOP: /*rsnoop(cmdline);*/ connectSnoopSrv(cmdline); prompt = P_RSNOOP; break; case REGISTER: /* Send connection request */ if(status.connected == true) fprintf(stderr, "This client already opened a connection to the server!\n"); else { connectTimeSrv(); initSignals(); } break; case SRV_VERSION: /* Send version request */ if(status.connected == false) fprintf(stderr, "Server Version Request: Not connected to the server yet.\n"); else srvVersion(); break; case SRV_ELAPSED_TIME: /* Send eslsapsed time request */ if(status.connected == false) fprintf(stderr, "Elapsed Time Request: Not connected to the server yet.\n"); else srvElapsedTime(); break; case SRV_TOD:/* Send time-of-the-day request */ if(status.connected == false) fprintf(stderr, "Time of the Day Request: Not connected to the server yet.\n"); else srvTOD(); break; case PIPELINE: execPipeline(status.pipeline_size, -1); reset(); break; case HELP: showHelp(); break; case BLANK: case UNKNOWN: /* UNKNOWN was meant for error checking. Unused. */ reset(); break; default: fprintf(stderr, "msh: Unexpected command type: %d (internal error)\n", status.curr_cmd); exit(1); } /* switch(status.curr_cmd) */ } /* !SH_REMOTE */ /* Make sure we don't have anything in those streams */ fflush(stdout); fflush(stdin); fflush(stderr); } /* while(not QUIT) */ exit(0); } /* main() */
FindDocWidget::FindDocWidget(LiteApi::IApplication *app, QWidget *parent) : QWidget(parent), m_liteApp(app) { m_findEdit = new SearchEdit; m_findEdit->setPlaceholderText(tr("Search")); m_chaseWidget = new ChaseWidget; m_chaseWidget->setMinimumSize(QSize(16,16)); m_chaseWidget->setSizePolicy(QSizePolicy::Preferred,QSizePolicy::Preferred); QToolButton *findBtn = new QToolButton; findBtn->setPopupMode(QToolButton::InstantPopup); findBtn->setText(tr("Find")); QHBoxLayout *findLayout = new QHBoxLayout; findLayout->setMargin(2); findLayout->addWidget(m_findEdit); findLayout->addWidget(findBtn); findLayout->addWidget(m_chaseWidget); m_browser = m_liteApp->htmlWidgetManager()->createByName(this,"QTextBrowser"); QStringList paths; paths << m_liteApp->resourcePath()+"/golangdoc"; m_browser->setSearchPaths(paths); QVBoxLayout *mainLayout = new QVBoxLayout; mainLayout->setMargin(1); mainLayout->setSpacing(1); mainLayout->addLayout(findLayout); mainLayout->addWidget(m_browser->widget()); QAction *findAll = new QAction(tr("Find All"),this); QAction *findConst = new QAction(tr("Find const"),this); findConst->setData("const"); QAction *findFunc = new QAction(tr("Find func"),this); findFunc->setData("func"); QAction *findInterface = new QAction(tr("Find interface"),this); findInterface->setData("interface"); QAction *findPkg = new QAction(tr("Find pkg"),this); findPkg->setData("pkg"); QAction *findStruct = new QAction(tr("Find struct"),this); findStruct->setData("struct"); QAction *findType = new QAction(tr("Find type"),this); findType->setData("type"); QAction *findVar = new QAction(tr("Find var"),this); findVar->setData("var"); m_useRegexpCheckAct = new QAction(tr("Use Regexp"),this); m_useRegexpCheckAct->setCheckable(true); m_matchCaseCheckAct = new QAction(tr("Match Case"),this); m_matchCaseCheckAct->setCheckable(true); m_matchWordCheckAct = new QAction(tr("Match Word"),this); m_matchWordCheckAct->setCheckable(true); m_useRegexpCheckAct->setChecked(m_liteApp->settings()->value(GODOCFIND_USEREGEXP,false).toBool()); m_matchCaseCheckAct->setChecked(m_liteApp->settings()->value(GODOCFIND_MATCHCASE,true).toBool()); m_matchWordCheckAct->setChecked(m_liteApp->settings()->value(GODOCFIND_MATCHWORD,false).toBool()); QMenu *menu = new QMenu(findBtn); menu->addActions(QList<QAction*>() << findAll //<< findPkg ); menu->addSeparator(); menu->addActions(QList<QAction*>() << findInterface << findStruct << findType << findFunc << findConst << findVar ); menu->addSeparator(); menu->addAction(m_matchWordCheckAct); menu->addAction(m_matchCaseCheckAct); menu->addAction(m_useRegexpCheckAct); findBtn->setMenu(menu); QAction *helpAct = new QAction(tr("Help"),this); menu->addSeparator(); menu->addAction(helpAct); connect(helpAct,SIGNAL(triggered()),this,SLOT(showHelp())); this->setLayout(mainLayout); connect(findAll,SIGNAL(triggered()),this,SLOT(findDoc())); connect(findConst,SIGNAL(triggered()),this,SLOT(findDoc())); connect(findFunc,SIGNAL(triggered()),this,SLOT(findDoc())); connect(findInterface,SIGNAL(triggered()),this,SLOT(findDoc())); connect(findPkg,SIGNAL(triggered()),this,SLOT(findDoc())); connect(findStruct,SIGNAL(triggered()),this,SLOT(findDoc())); connect(findType,SIGNAL(triggered()),this,SLOT(findDoc())); connect(findVar,SIGNAL(triggered()),this,SLOT(findDoc())); m_process = new ProcessEx(this); connect(m_process,SIGNAL(stateChanged(QProcess::ProcessState)),this,SLOT(stateChanged(QProcess::ProcessState))); connect(m_process,SIGNAL(extOutput(QByteArray,bool)),this,SLOT(extOutput(QByteArray,bool))); connect(m_process,SIGNAL(extFinish(bool,int,QString)),this,SLOT(extFinish(bool,int,QString))); connect(m_findEdit,SIGNAL(returnPressed()),findAll,SIGNAL(triggered())); connect(m_findEdit,SIGNAL(rightButtonClicked()),this,SLOT(abortFind())); connect(m_browser,SIGNAL(linkClicked(QUrl)),this,SLOT(openUrl(QUrl))); QString path = m_liteApp->resourcePath()+"/golangdoc/finddoc.html"; QFile file(path); if (file.open(QIODevice::ReadOnly)) { m_templateData = file.readAll(); file.close(); } //QFont font = m_browser->widget()->font(); //font.setPointSize(12); //m_browser->widget()->setFont(font); showHelp(); }