int main(){ char query[1000]; char choice[10]; int numBytes = 1000; int numChoiceBytes = 10; while(1){ printf("Enter query string (or \"quit\" to exit): \n"); fgets(query, numBytes, stdin); if(query != NULL){ if(strcmp(query, "quit\n")){ processQuery(query); } else{ break; } } else{ printf("Error in reading query from stdin \n"); } } return 0; }
/*BindVariables-parses querystring and binds variables*/ char *DBConnection_SQLITE::BindVariables(char *p_query, int p_query_length, DBString *p_arguments, int p_argument_count, int &r_new_query_length) { char *t_parsed_query; t_parsed_query = p_query; int t_parsed_query_length; t_parsed_query_length = p_query_length; bool t_success; t_success = true; if (p_argument_count != 0) { QueryMetadata t_query_metadata; t_query_metadata . argument_count = p_argument_count; t_query_metadata . arguments = p_arguments; DBBuffer t_query_buffer(t_parsed_query_length + 1); t_success = processQuery(p_query, t_query_buffer, queryCallback, &t_query_metadata); t_query_buffer . ensure(1); *t_query_buffer . getFrontier() = '\0'; t_query_buffer . advance(1); t_parsed_query_length = t_query_buffer . getSize(); t_parsed_query = t_query_buffer . grab(); } r_new_query_length = t_parsed_query_length; return t_parsed_query; }
int main(int argc, char **argv) { string input_line; string tile_id ; polygon polygon_object ; float ar =0.0; while(cin && getline(cin, input_line) && !cin.eof()){ size_t pos = input_line.find_first_of(COMMA,0); if (pos == string::npos) return 1; // failure tile_id = input_line.substr(0,pos); pos=input_line.find_first_of(COMMA,pos+1); string sobject = shapebegin + input_line.substr(pos+2,input_line.length()- pos - 3) + shapeend; boost::geometry::read_wkt(sobject, polygon_object); // spatial filtering ar = abs(boost::geometry::area(polygon_object)); if (ar>AVG_AREA) geometry_collction.push_back(sobject); } processQuery(); return 0; // success }
void processWumpus() { char line[32768]; while (fgets(line, sizeof(line), stdin) != NULL) { if ((line[0] == 0) || (line[0] == '\n')) continue; line[strlen(line) - 1] = 0; processQuery(line); } } // end of processWumpus()
void DatabaseUpdatesTest::updates_mysql(Context *c) { QSqlQuery query = CPreparedSqlQueryForDatabase( QLatin1String("SELECT randomNumber FROM world WHERE id = :id"), QSqlDatabase::database(QLatin1String("mysql-") + QThread::currentThread()->objectName())); QSqlQuery updateQuery = CPreparedSqlQueryForDatabase( QLatin1String("UPDATE world SET randomNumber = :randomNumber WHERE id = :id"), QSqlDatabase::database(QLatin1String("mysql-") + QThread::currentThread()->objectName())); processQuery(c, query, updateQuery); }
/** A DesktopQuery basically just looks like @desktop "term1", "term2", ... **/ bool DesktopQuery::parse() { if (!parseQueryString(queryString, CONTAINER_STRING, NULL, memoryLimit)) { syntaxErrorDetected = finished = true; ok = false; } else { if (statisticsQuery == NULL) statisticsQuery = containerQuery; processQuery(); ok = true; } return ok; } // end of parse()
PGresult *DBConnection_POSTGRESQL::ExecuteQuery(char *p_query, DBString *p_arguments, int p_argument_count) { if (!isConnected) return NULL; unsigned int t_query_length; t_query_length = strlen(p_query); char *t_parsed_query; t_parsed_query = p_query; int *t_placeholders; t_placeholders = NULL; int t_placeholder_count; t_placeholder_count = 0; bool t_success; t_success = true; if (p_argument_count != 0) { QueryMetadata t_query_metadata; t_query_metadata . argument_count = p_argument_count; t_query_metadata . arguments = p_arguments; t_query_metadata . connection = dbconn; DBBuffer t_query_buffer(t_query_length + 1); t_success = processQuery(p_query, t_query_buffer, queryCallback, &t_query_metadata); t_query_buffer . ensure(1); *t_query_buffer . getFrontier() = '\0'; t_query_buffer . advance(1); t_query_length = t_query_buffer . getSize(); t_parsed_query = t_query_buffer . grab(); } PGresult *t_query_result; t_query_result = PQexec(dbconn, t_parsed_query); if (p_argument_count != 0) { free(t_parsed_query); } return t_query_result; }
int main(int argc, char **argv) { string input_line; vector<string> fields; while(cin && getline(cin, input_line) && !cin.eof()){ boost::split(fields, input_line, boost::is_any_of(TAB)); areaMap[fields[0]].push_back(boost::lexical_cast< double >( fields[1] ) ); perimeterMap[fields[0]].push_back(boost::lexical_cast< double >( fields[2] )); fields.clear(); } processQuery(); return 0; // success }
// ------------------------------------------------------------------------------------------------- int processSQLQueries(const std::string & query, const aq::Settings & settingsBase, const std::string queryIdent, aq::Base & baseDesc, bool simulateAQEngine, bool keepFiles, bool force) { aq::Logger::getInstance().log(AQ_INFO, "%s\n", query.c_str()); aq::Timer timer; // // Settings aq::Settings settings(settingsBase); // // Load AQ engine aq::AQEngine_Intf * aq_engine; if (simulateAQEngine) { aq::Logger::getInstance().log(AQ_INFO, "Do not use aq engine\n"); aq_engine = new aq::AQEngineSimulate(baseDesc, settings); } else { aq::Logger::getInstance().log(AQ_INFO, "Use aq engine: '%s'\n", settings.aqEngine.c_str()); aq_engine = new aq::AQEngineSystem(baseDesc, settings); } // // prepare and process query std::string answer; if (!((prepareQuery(query, settingsBase, baseDesc, settings, answer, queryIdent, force) == EXIT_SUCCESS) && (processQuery(query, settings, baseDesc, aq_engine, answer, keepFiles) == EXIT_SUCCESS))) { aq::Logger::getInstance().log(AQ_DEBUG, "QUERY FAILED:\n%s\n", query.c_str()); } else { aq::Logger::getInstance().log(AQ_NOTICE, "Query Time elapsed: %s\n", aq::Timer::getString(timer.getTimeElapsed()).c_str()); } return EXIT_SUCCESS; }
bool DBConnection_MYSQL::ExecuteQuery(char *p_query, DBString *p_arguments, int p_argument_count) { if (!isConnected) return false; unsigned int t_query_length; t_query_length = strlen(p_query); char *t_parsed_query; t_parsed_query = p_query; int *t_placeholders; t_placeholders = NULL; int t_placeholder_count; t_placeholder_count = 0; bool t_success; t_success = true; if (p_argument_count != 0) { QueryMetadata t_query_metadata; t_query_metadata . argument_count = p_argument_count; t_query_metadata . arguments = p_arguments; t_query_metadata . connection = getMySQL(); DBBuffer t_query_buffer(t_query_length + 1); t_success = processQuery(p_query, t_query_buffer, queryCallback, &t_query_metadata); t_query_length = t_query_buffer . getSize(); t_parsed_query = t_query_buffer . grab(); } int t_error_code; if (t_success) { if (t_error_code = mysql_real_query(getMySQL(), t_parsed_query, t_query_length)) t_success = false; } if (p_argument_count != 0) free(t_parsed_query); return t_success; }
/* List of files found using slocate */ void KQuery::slotListEntries( QStringList list ) { KFileItem * file = 0; metaKeyRx=new QRegExp(m_metainfokey,true,true); QStringList::Iterator it = list.begin(); QStringList::Iterator end = list.end(); for (; it != end; ++it) { file = new KFileItem( KFileItem::Unknown, KFileItem::Unknown, KURL::fromPathOrURL(*it)); processQuery(file); delete file; } delete metaKeyRx; }
void KQuery::checkEntries() { if (m_insideCheckEntries) return; m_insideCheckEntries=true; metaKeyRx=new QRegExp(m_metainfokey,true,true); KFileItem * file = 0; while ((file=m_fileItems.dequeue())) { processQuery(file); delete file; } delete metaKeyRx; m_insideCheckEntries=false; if (job==0) emit result(m_result); }
int main(int argc, char **argv) { string input_line; string tile_id ; while(cin && getline(cin, input_line) && !cin.eof()){ size_t pos = input_line.find_first_of(COMMA,0); if (pos == string::npos) return 1; // failure tile_id = input_line.substr(0,pos); pos=input_line.find_first_of(COMMA,pos+1); geometry_collction.push_back(shapebegin + input_line.substr(pos+2,input_line.length()- pos - 3) + shapeend); //cout << key<< TAB << index<< TAB << shapebegin <<value <<shapeend<< endl; } processQuery(); return 0; // success }
DbFieldWidget::DbFieldWidget(DatabaseDialog *parent): StepWidget(parent), ui(new Ui::DbFieldWidget()) { ui->setupUi(this); connect(this, SIGNAL(signalAddColumns(QStringList)), this, SLOT(slotAddColumns(QStringList))); dialog->setButtonState(DatabaseDialog::BUTTON_BACK, true); dialog->setButtonState(DatabaseDialog::BUTTON_NEXT, false); dialog->setButtonState(DatabaseDialog::BUTTON_FINISH, false); DatabaseManager *dm = MatchMaker::instance->dbManager; dm->queryConnection(CONNECTION, dialog->db->getColumnQuery(dialog->dbSetup.getTable()), [this](QSqlQuery *query){ //emit signalProcessQuery(query); processQuery(query); }); }
static void blastToPsl(char *blastFile, char *pslFile, char* scoreFile) /* process one query in */ { struct blastFile *bf = blastFileOpenVerify(blastFile); struct blastQuery *bq; FILE *pslFh = mustOpen(pslFile, "w"); FILE *scoreFh = NULL; if (scoreFile != NULL) scoreFh = pslBuildScoresOpen(scoreFile, FALSE); unsigned flags = pslBuildGetBlastAlgo(bf->program) | (pslxFmt ? bldPslx : 0); while ((bq = blastFileNextQuery(bf)) != NULL) { processQuery(bq, flags, pslFh, scoreFh); blastQueryFree(&bq); } blastFileFree(&bf); carefulClose(&scoreFh); carefulClose(&pslFh); }
void CorrectionEngine::buildEngine(const std::string& path) { clear(); std::string resource; if (!boost::filesystem::exists(path)) resource = workdir_; else if(!boost::filesystem::is_directory(path)) resource = workdir_; else resource = path; boost::filesystem::directory_iterator end; for(boost::filesystem::directory_iterator it(resource) ; it != end ; ++it) { const std::string p = it->path().string(); if(boost::filesystem::is_regular_file(p)) { //std::cout<<p<<"\n"; if (!parsers_->isValid(p)) continue; Parser* parser = parsers_->load(p); if (NULL == parser) continue; Parser::iterator it = parser->begin(); for (; it != parser->end(); ++it) { //std::cout<<it->userQuery()<<" : "<<it->freq()<<"\n"; processQuery(it->userQuery(), it->category(), it->freq()); } parsers_->destory(parser); } } filter_->buildFilter(path + "/filter/"); udef_->build(path + "/user-define/"); timestamp_ = time(NULL); flush(); }
void processQuery(WeightedTerm *query, int queryLen, char *queryString) { char wwf[8192], phrase[8192]; int wwfLen = 0; int queryStringLen = strlen(queryString); phrase[0] = phrase[1] = 0; if (strncmp(QUERY_COMMAND, "@bm25tera", 9) != 0) queryStringLen += sprintf(&queryString[queryStringLen], " \"<doc>\"..\"</doc>\" by "); for (int i = 0; i < queryLen; i++) { for (int k = i + 1; k < queryLen; k++) if (strcmp(query[i].term, query[k].term) == 0) { query[i].weight += query[k].weight; query[k].weight = 0.0; } if (query[i].weight > 0.001) { queryStringLen += sprintf(&queryString[queryStringLen], "%s #%.3lf \"%s%s\"", (wwfLen == 0 ? "" : ","), query[i].weight, (STEMMING ? "$" : ""), query[i].term); #if 0 if (i < queryLen - 1) if (query[i + 1].weight > 0.001) { queryStringLen += sprintf(&queryString[queryStringLen], ", #0.5 \"%s %s\"", query[i].term, query[i + 1].term); } #endif sprintf(&phrase[strlen(phrase)], " %s", query[i].term); wwfLen += sprintf(&wwf[wwfLen], "%s\"%s%s\"", (wwfLen == 0 ? "" : "+"), (STEMMING ? "$" : ""), query[i].term); } } #if 0 queryStringLen += sprintf(&queryString[queryStringLen], ", \"%s\"", &phrase[1]); #endif if (INCLUDE_WWF) queryStringLen += sprintf(&queryString[queryStringLen], WWF_STRING, wwf); if (queryLen > 0) processQuery(queryString); } // end of processQuery(WeightedTerm*, int, char*)
bool CDRQuery::parse() { // if no container is given, assume default container char defaultContainer[MAX_CONFIG_VALUE_LENGTH]; if (!getConfigurationValue("DEFAULT_RETRIEVAL_SET", defaultContainer)) strcpy(defaultContainer, DOC_QUERY); if (!parseQueryString(queryString, defaultContainer, NULL, memoryLimit)) { syntaxErrorDetected = finished = true; ok = false; } else if (((elementCount < 1) || (elementCount > CDR_MAX_SCORER_COUNT)) && (maxLevel > 1)) { // @cdr queries may not contain more than CDR_MAX_SCORER_COUNT query terms syntaxErrorDetected = finished = true; ok = false; } else { if (statisticsQuery == NULL) if (visibleExtents != NULL) statisticsQuery = new GCLQuery(index, visibleExtents->getExtentList()); processQuery(); ok = true; } return ok; } // end of parse()
void JsonApiHandlerHttp::processApi(const string &data, const Params ¶msGET) { jsonParam.clear(); //parse the json data json_error_t jerr; json_t *jroot = json_loads(data.c_str(), 0, &jerr); if (!jroot || !json_is_object(jroot)) { cDebugDom("network") << "Error loading json : " << jerr.text << ". No JSON, trying with GET parameters."; jsonParam = paramsGET; if (jroot) { json_decref(jroot); jroot = nullptr; } } else { char *d = json_dumps(jroot, JSON_INDENT(4)); if (d) { cDebugDom("network") << d; free(d); } //decode the json root object into jsonParam jansson_decode_object(jroot, jsonParam); } //check for if username/password matches string user = Utils::get_config_option("calaos_user"); string pass = Utils::get_config_option("calaos_password"); if (Utils::get_config_option("cn_user") != "" && Utils::get_config_option("cn_pass") != "") { user = Utils::get_config_option("cn_user"); pass = Utils::get_config_option("cn_pass"); } if (user != jsonParam["cn_user"] || pass != jsonParam["cn_pass"]) { cDebugDom("network") << "Login failed!"; Params headers; headers.Add("Connection", "close"); headers.Add("Content-Type", "text/html"); string res = httpClient->buildHttpResponse(HTTP_400, headers, HTTP_400_BODY); sendData.emit(res); closeConnection.emit(0, string()); if (jroot) { json_decref(jroot); jroot = nullptr; } return; } //check action now if (jsonParam["action"] == "get_home") processGetHome(); else if (jsonParam["action"] == "get_state") processGetState(jroot); else if (jsonParam["action"] == "get_states") processGetStates(); else if (jsonParam["action"] == "query") processQuery(); else if (jsonParam["action"] == "get_param") processGetParam(); else if (jsonParam["action"] == "set_param") processSetParam(); else if (jsonParam["action"] == "del_param") processDelParam(); else if (jsonParam["action"] == "set_state") processSetState(); else if (jsonParam["action"] == "get_playlist") processGetPlaylist(); else if (jsonParam["action"] == "poll_listen") processPolling(); else if (jsonParam["action"] == "get_cover") processGetCover(); else if (jsonParam["action"] == "get_camera_pic") processGetCameraPic(); else if (jsonParam["action"] == "get_timerange") processGetTimerange(); else if (jsonParam["action"] == "camera") processCamera(); else { if (!jroot) { Params headers; headers.Add("Connection", "close"); headers.Add("Content-Type", "text/html"); string res = httpClient->buildHttpResponse(HTTP_400, headers, HTTP_400_BODY); sendData.emit(res); closeConnection.emit(0, string()); if (jroot) json_decref(jroot); return; } if (jsonParam["action"] == "config") processConfig(jroot); else if (jsonParam["action"] == "get_io") processGetIO(jroot); else if (jsonParam["action"] == "audio") processAudio(jroot); else if (jsonParam["action"] == "audio_db") processAudioDb(jroot); else if (jsonParam["action"] == "set_timerange") processSetTimerange(jroot); else if (jsonParam["action"] == "autoscenario") processAutoscenario(jroot); } if (jroot) json_decref(jroot); }
QueryResult(const std::string& inword, const std::shared_ptr<wordMap>& inmap, const std::shared_ptr<std::vector<std::string>>& infile) : word(inword), map(inmap), file(infile) { processQuery(); }
CoverFoundDialog::CoverFoundDialog( const CoverFetchUnit::Ptr unit, const CoverFetch::Metadata &data, QWidget *parent ) : KDialog( parent ) , m_album( unit->album() ) , m_isSorted( false ) , m_sortEnabled( false ) , m_unit( unit ) , m_queryPage( 0 ) { DEBUG_BLOCK setButtons( KDialog::Ok | KDialog::Cancel | KDialog::User1 ); // User1: clear icon view setButtonGuiItem( KDialog::User1, KStandardGuiItem::clear() ); connect( button( KDialog::User1 ), SIGNAL(clicked()), SLOT(clearView()) ); m_save = button( KDialog::Ok ); QSplitter *splitter = new QSplitter( this ); m_sideBar = new CoverFoundSideBar( m_album, splitter ); KVBox *vbox = new KVBox( splitter ); vbox->setSpacing( 4 ); KHBox *breadcrumbBox = new KHBox( vbox ); QLabel *breadcrumbLabel = new QLabel( i18n( "Finding cover for" ), breadcrumbBox ); AlbumBreadcrumbWidget *breadcrumb = new AlbumBreadcrumbWidget( m_album, breadcrumbBox ); QFont breadcrumbLabelFont; breadcrumbLabelFont.setBold( true ); breadcrumbLabel->setFont( breadcrumbLabelFont ); breadcrumbLabel->setIndent( 4 ); connect( breadcrumb, SIGNAL(artistClicked(const QString&)), SLOT(addToCustomSearch(const QString&)) ); connect( breadcrumb, SIGNAL(albumClicked(const QString&)), SLOT(addToCustomSearch(const QString&)) ); KHBox *searchBox = new KHBox( vbox ); vbox->setSpacing( 4 ); QStringList completionNames; QString firstRunQuery( m_album->name() ); completionNames << firstRunQuery; if( m_album->hasAlbumArtist() ) { const QString &name = m_album->albumArtist()->name(); completionNames << name; firstRunQuery += ' ' + name; } m_query = firstRunQuery; m_album->setSuppressImageAutoFetch( true ); m_search = new KComboBox( searchBox ); m_search->setEditable( true ); // creates a KLineEdit for the combobox m_search->setTrapReturnKey( true ); m_search->setInsertPolicy( QComboBox::NoInsert ); // insertion is handled by us m_search->setCompletionMode( KGlobalSettings::CompletionPopup ); m_search->setSizePolicy( QSizePolicy::MinimumExpanding, QSizePolicy::Fixed ); qobject_cast<KLineEdit*>( m_search->lineEdit() )->setClickMessage( i18n( "Enter Custom Search" ) ); m_search->completionObject()->setOrder( KCompletion::Insertion ); m_search->completionObject()->setIgnoreCase( true ); m_search->completionObject()->setItems( completionNames ); m_search->insertItem( 0, KStandardGuiItem::find().icon(), QString() ); m_search->insertSeparator( 1 ); m_search->insertItem( 2, KIcon("filename-album-amarok"), m_album->name() ); if( m_album->hasAlbumArtist() ) m_search->insertItem( 3, KIcon("filename-artist-amarok"), m_album->albumArtist()->name() ); m_searchButton = new KPushButton( KStandardGuiItem::find(), searchBox ); KPushButton *sourceButton = new KPushButton( KStandardGuiItem::configure(), searchBox ); updateSearchButton( firstRunQuery ); QMenu *sourceMenu = new QMenu( sourceButton ); QAction *lastFmAct = new QAction( i18n( "Last.fm" ), sourceMenu ); QAction *googleAct = new QAction( i18n( "Google" ), sourceMenu ); QAction *yahooAct = new QAction( i18n( "Yahoo!" ), sourceMenu ); QAction *discogsAct = new QAction( i18n( "Discogs" ), sourceMenu ); lastFmAct->setCheckable( true ); googleAct->setCheckable( true ); yahooAct->setCheckable( true ); discogsAct->setCheckable( true ); connect( lastFmAct, SIGNAL(triggered()), this, SLOT(selectLastFm()) ); connect( googleAct, SIGNAL(triggered()), this, SLOT(selectGoogle()) ); connect( yahooAct, SIGNAL(triggered()), this, SLOT(selectYahoo()) ); connect( discogsAct, SIGNAL(triggered()), this, SLOT(selectDiscogs()) ); m_sortAction = new QAction( i18n( "Sort by size" ), sourceMenu ); m_sortAction->setCheckable( true ); connect( m_sortAction, SIGNAL(triggered(bool)), this, SLOT(sortingTriggered(bool)) ); QActionGroup *ag = new QActionGroup( sourceButton ); ag->addAction( lastFmAct ); ag->addAction( googleAct ); ag->addAction( yahooAct ); ag->addAction( discogsAct ); sourceMenu->addActions( ag->actions() ); sourceMenu->addSeparator(); sourceMenu->addAction( m_sortAction ); sourceButton->setMenu( sourceMenu ); connect( m_search, SIGNAL(returnPressed(const QString&)), SLOT(insertComboText(const QString&)) ); connect( m_search, SIGNAL(returnPressed(const QString&)), SLOT(processQuery(const QString&)) ); connect( m_search, SIGNAL(returnPressed(const QString&)), SLOT(updateSearchButton(const QString&)) ); connect( m_search, SIGNAL(editTextChanged(const QString&)), SLOT(updateSearchButton(const QString&)) ); connect( m_search->lineEdit(), SIGNAL(clearButtonClicked()), SLOT(clearQueryButtonClicked())); connect( m_searchButton, SIGNAL(clicked()), SLOT(processQuery()) ); m_view = new KListWidget( vbox ); m_view->setAcceptDrops( false ); m_view->setContextMenuPolicy( Qt::CustomContextMenu ); m_view->setDragDropMode( QAbstractItemView::NoDragDrop ); m_view->setDragEnabled( false ); m_view->setDropIndicatorShown( false ); m_view->setMovement( QListView::Static ); m_view->setGridSize( QSize( 140, 150 ) ); m_view->setIconSize( QSize( 120, 120 ) ); m_view->setSpacing( 4 ); m_view->setViewMode( QListView::IconMode ); m_view->setResizeMode( QListView::Adjust ); connect( m_view, SIGNAL(currentItemChanged(QListWidgetItem*, QListWidgetItem*)), this, SLOT(currentItemChanged(QListWidgetItem*, QListWidgetItem*)) ); connect( m_view, SIGNAL(itemDoubleClicked(QListWidgetItem*)), this, SLOT(itemDoubleClicked(QListWidgetItem*)) ); connect( m_view, SIGNAL(customContextMenuRequested(const QPoint&)), this, SLOT(itemMenuRequested(const QPoint&)) ); splitter->addWidget( m_sideBar ); splitter->addWidget( vbox ); setMainWidget( splitter ); const KConfigGroup config = Amarok::config( "Cover Fetcher" ); const QString source = config.readEntry( "Interactive Image Source", "LastFm" ); m_sortEnabled = config.readEntry( "Sort by Size", false ); m_sortAction->setChecked( m_sortEnabled ); m_isSorted = m_sortEnabled; restoreDialogSize( config ); // call this after setMainWidget() if( source == "LastFm" ) lastFmAct->setChecked( true ); else if( source == "Yahoo" ) yahooAct->setChecked( true ); else if( source == "Discogs" ) discogsAct->setChecked( true ); else googleAct->setChecked( true ); typedef CoverFetchArtPayload CFAP; const CFAP *payload = dynamic_cast< const CFAP* >( unit->payload() ); if( !m_album->hasImage() ) m_sideBar->setPixmap( QPixmap::fromImage( m_album->image(190 ) ) ); else if( payload ) add( m_album->image(), data, payload->imageSize() ); else add( m_album->image(), data ); m_view->setCurrentItem( m_view->item( 0 ) ); updateGui(); connect( The::networkAccessManager(), SIGNAL( requestRedirected( QNetworkReply*, QNetworkReply* ) ), this, SLOT( fetchRequestRedirected( QNetworkReply*, QNetworkReply* ) ) ); }
void JsonApiHandlerWS::processApi(const string &data, const Params ¶msGET) { VAR_UNUSED(paramsGET); //not used for websocket Params jsonRoot; Params jsonData; //parse the json data json_error_t jerr; json_t *jroot = json_loads(data.c_str(), 0, &jerr); if (!jroot || !json_is_object(jroot)) { cDebugDom("network") << "Error loading json : " << jerr.text; return; } char *d = json_dumps(jroot, JSON_INDENT(4)); if (d) { cDebugDom("network") << d; free(d); } //decode the json root object into jsonParam jansson_decode_object(jroot, jsonRoot); json_t *jdata = json_object_get(jroot, "data"); if (jdata) jansson_decode_object(jdata, jsonData); //Format: { msg: "type", msg_id: id, data: {} } if (jsonRoot["msg"] == "login") { //check for if username/password matches string user = Utils::get_config_option("calaos_user"); string pass = Utils::get_config_option("calaos_password"); if (Utils::get_config_option("cn_user") != "" && Utils::get_config_option("cn_pass") != "") { user = Utils::get_config_option("cn_user"); pass = Utils::get_config_option("cn_pass"); } //Not logged in, need to wait for a correct login if (user != jsonData["cn_user"] || pass != jsonData["cn_pass"]) { cDebugDom("network") << "Login failed!"; json_t *jret = json_object(); json_object_set_new(jret, "success", json_string("false")); sendJson("login", jret, jsonRoot["msg_id"]); //Close the connection on login failure closeConnection.emit(WebSocketFrame::CloseCodeNormal, "login failed!"); } else { json_t *jret = json_object(); json_object_set_new(jret, "success", json_string("true")); sendJson("login", jret, jsonRoot["msg_id"]); loggedin = true; } } else if (loggedin) //only process other api if loggedin { if (jsonRoot["msg"] == "get_home") processGetHome(jsonData, jsonRoot["msg_id"]); else if (jsonRoot["msg"] == "get_state") processGetState(jdata, jsonRoot["msg_id"]); else if (jsonRoot["msg"] == "get_states") processGetStates(jsonData, jsonRoot["msg_id"]); else if (jsonRoot["msg"] == "query") processQuery(jsonData, jsonRoot["msg_id"]); else if (jsonRoot["msg"] == "get_param") processGetParam(jsonData, jsonRoot["msg_id"]); else if (jsonRoot["msg"] == "set_param") processSetParam(jsonData, jsonRoot["msg_id"]); else if (jsonRoot["msg"] == "del_param") processDelParam(jsonData, jsonRoot["msg_id"]); else if (jsonRoot["msg"] == "set_state") processSetState(jsonData, jsonRoot["msg_id"]); else if (jsonRoot["msg"] == "get_playlist") processGetPlaylist(jsonData, jsonRoot["msg_id"]); else if (jsonRoot["msg"] == "get_io") processGetIO(jdata, jsonRoot["msg_id"]); else if (jsonRoot["msg"] == "audio") processAudio(jdata, jsonRoot["msg_id"]); else if (jsonRoot["msg"] == "audio_db") processAudioDb(jdata, jsonRoot["msg_id"]); else if (jsonRoot["msg"] == "get_timerange") processGetTimerange(jsonData, jsonRoot["msg_id"]); else if (jsonRoot["msg"] == "set_timerange") processSetTimerange(jdata, jsonRoot["msg_id"]); else if (jsonRoot["msg"] == "autoscenario") processAutoscenario(jdata, jsonRoot["msg_id"]); // else if (jsonParam["action"] == "get_cover") // processGetCover(); // else if (jsonParam["action"] == "get_camera_pic") // processGetCameraPic(); // else if (jsonParam["action"] == "config") // processConfig(jroot); } json_decref(jroot); }
void KinectSensorCollection::setStatusChangeCb(KEventHandler<KinectStatus> cb) { if (!_statusChangedCb) processQuery(buildQuery("StatusChanged")); _statusChangedCb = cb; }
Cda_Def *DBConnection_ORACLE::ExecuteQuery(char *p_query, DBString *p_arguments, int p_argument_count) { int t_affected_rows; t_affected_rows = 0; unsigned int t_query_length; t_query_length = strlen(p_query); Cda_Def *t_cursor; t_cursor = new Cda_Def; bool t_success; t_success = true; sword t_error; if (t_success) { t_error = oopen(t_cursor, getLDA(), (text *)0, -1, -1, NULL, -1); if (t_error != 0) t_success = false; } char *t_parsed_query; t_parsed_query = p_query; PlaceholderMap t_placeholder_map; if (p_argument_count != 0) { t_placeholder_map . length = 0; t_placeholder_map . elements = new int[p_argument_count + 1]; DBBuffer t_query_buffer(t_query_length + 1); t_success = processQuery(p_query, t_query_buffer, queryCallback, &t_placeholder_map); t_query_length = t_query_buffer . getSize(); t_parsed_query = t_query_buffer . grab(); } if (t_success) { if (oparse(t_cursor, (text *)t_parsed_query, t_query_length, DEFER_PARSE, PARSE_V7_LNG) != 0) t_success = false; } if (t_success) { if (!BindVariables(t_cursor, p_arguments, p_argument_count, &t_placeholder_map)) t_success = false; } if (t_success) { t_error = oexec(t_cursor); if (t_error != 0) t_success = false; } if (!t_success) { delete t_cursor; t_cursor = NULL; } return t_cursor; }
int main(int argc, char * argv[]) { if (argc == 3) { //check if 1st arg is file if (!IsFile(argv[1])) { fprintf(stderr, "ERROR: Sorry, %s is not a file.", argv[1]); return 1; } //check if 2nd arg is directory if (!IsDir(argv[2])) { fprintf(stderr, "ERROR: Sorry, %s is not a directory.", argv[2]); return 1; } // make indexer HashTable * index = ReadFile(argv[1]); if (index == NULL){ return 1; } char buffer[QUERY_MAX]; printf("QUERY>: "); while( fgets(buffer, QUERY_MAX , stdin) != NULL ) /* break with ^D or ^Z */ { WordNode * search_results = processQuery(buffer, index); if (!search_results) { // an error that must exit. return 1; } if (search_results->head == NULL) { printf("No results found."); } else { // order by frequency, mergesort returns the head (top-ranking url) of search_results DocNode * doc = mergesort(search_results->head); //set the search_results head to the doc, for freeing purposes. search_results->head = doc; // go through every doc node while ( doc!= NULL){ char * docName = (char *)calloc(5,sizeof(char)); //assuming int ret = snprintf(docName, 5, "%d", doc->docID); if (ret == -1){ fprintf(stderr, "WOW you have tons of files. I cannot handle this. Sorry \n"); free(docName); continue; } char * url = get_url(docName, argv[2]); if (!url){ fprintf(stderr, "Getting the url of doc %s failed. \n", docName); continue; } printf("Document ID: %d URL: %s", doc->docID, url); free(url); free(docName); doc = doc->next; } } //next iteration printf("\nQUERY>: "); free_list(search_results); } printf("done"); free_table(index); return 0; } else { fprintf(stderr,"ERROR: Sorry, you entered in an incorrect number of input arguments. You must have 2 (index filename to read from, directory of html files)"); return 1; } }
void processTREC() { char topic[32768]; char line[32768]; char thisField[32768]; int lineLen, topicLen, queryLen; WeightedTerm query[1024]; while (fgets(line, sizeof(line), stdin) != NULL) { if ((line[0] == 0) || (line[0] == '\n')) continue; line[strlen(line) - 1] = ' '; if (strncasecmp(line, "<top>", 5) == 0) { topicLen = 0; } else if (strncasecmp(line, "</top>", 6) == 0) { topicLen += sprintf(&topic[topicLen], "%s", line); int outPos = 1; for (int i = 1; topic[i] != 0; i++) if ((topic[i] != ' ') || (topic[outPos - 1] != ' ')) topic[outPos++] = topic[i]; topic[outPos] = 0; queryLen = 0; char *topicColon = strstr(topic, "Topic:"); if (topicColon != NULL) for (int i = 0; i < 6; i++) topicColon[i] = ' '; for (int i = 0; topicFields[i] != NULL; i++) if (topicFieldWeights[i] > 0.0) { char *field = strstr(topic, topicFields[i]); if (field == NULL) { fprintf(stderr, "Error: Field \"%s\" not found.\n", topicFields[i]); continue; } field = &field[strlen(topicFields[i])]; char *endOfField = strchr(field, '<'); if (endOfField == NULL) { fprintf(stderr, "Error: No delimiter found for field \"%s\".\n", topicFields[i]); continue; } *endOfField = 0; strcpy(thisField, field); *endOfField = '<'; if (REPLACE_US_AND_UK) replaceUSandUK(thisField); for (int k = 0; thisField[k] != 0; k++) { if (thisField[k] < 0) thisField[k] = ' '; else thisField[k] = translationTable[thisField[k]]; } char *token = strtok(thisField, " "); while (token != NULL) { if (strlen(token) < MAX_TOKEN_LEN) { if ((!REMOVE_STOPWORDS) || (!isStopword(token, LANGUAGE_ENGLISH))) { strcpy(query[queryLen].term, token); query[queryLen].weight = topicFieldWeights[i]; queryLen++; } } token = strtok(NULL, " "); } // end while (token != NULL) } // end for (int i = 0; topicFields[i] != NULL; i++) char *num = strstr(topic, "Number:"); sscanf(&num[strlen("Number:")], "%s", topicID); char queryString[32768]; int queryStringLen = 0; queryStringLen += sprintf(&queryString[queryStringLen], QUERY_COMMAND); queryStringLen += sprintf(&queryString[queryStringLen], "[count=%d][id=%s]%s", documentCount, topicID, FEEDBACK_MODE); processQuery(query, queryLen, queryString); } else topicLen += sprintf(&topic[topicLen], "%s", line); } } // end of processTREC()
void processPlain() { char line[32768]; char wumpusQuery[32768]; int lineLen, topicLen, queryLen; WeightedTerm query[1024]; while (fgets(line, sizeof(line), stdin) != NULL) { if ((line[0] == 0) || (line[0] == '\n')) continue; line[strlen(line) - 1] = 0; if (line[0] == '@') { processQuery(line); continue; } if (REPLACE_US_AND_UK) replaceUSandUK(line); for (int k = 0; line[k] != 0; k++) { if (line[k] < 0) line[k] = ' '; else line[k] = translationTable[line[k]]; } // normalize input string for (int i = 0; line[i] != 0; i++) { if ((line[i] >= 'a') && (line[i] <= 'z')) { line[i] = line[i]; } else if ((line[i] >= 'A') && (line[i] <= 'Z')) { line[i] = (line[i] | 32); } else if ((line[i] >= '0') && (line[i] <= '9')) { line[i] = line[i]; } else line[i] = ' '; } // end for (int i = 0; line[i] != 0; i++) char *token = strtok(line, " "); int queryLen = 0; while (token != NULL) { if (strlen(token) < MAX_TOKEN_LEN) { if (!(REMOVE_STOPWORDS) || (!isStopword(token, LANGUAGE_ENGLISH))) { if ((queryLen == 0) && (strcmp(token, "us") == 0)) strcpy(query[queryLen].term, "usa"); else strcpy(query[queryLen].term, token); query[queryLen].weight = 1.0; queryLen++; } } else { token[MAX_TOKEN_LEN - 3] = 0; strcpy(query[queryLen].term, token); query[queryLen].weight = 1.0; queryLen++; } token = strtok(NULL, " "); } // end while (token != NULL) char queryString[32768]; int queryID, queryStringLen = 0; queryStringLen += sprintf(&queryString[queryStringLen], "%s", QUERY_COMMAND); queryStringLen += sprintf(&queryString[queryStringLen], "[count=%d]", documentCount); if (sscanf(query[0].term, "%d", &queryID) == 1) { sprintf(topicID, "%d", queryID); queryStringLen += sprintf(&queryString[queryStringLen], "[id=%d]", queryID); processQuery(&query[1], queryLen - 1, queryString); } else processQuery(query, queryLen, queryString); } // end while (fgets(line, sizeof(line), stdin) != NULL) } // end of processPlain()
/*------------------------------------------------------------------------------* *------------------------------------------------------------------------------*/ void WebProxy::manageQuery() { QTcpServer *proxyServer = qobject_cast<QTcpServer*>(sender()); QTcpSocket *socket = proxyServer->nextPendingConnection(); connect(socket, SIGNAL(readyRead()), this, SLOT(processQuery())); connect(socket, SIGNAL(disconnected()), socket, SLOT(deleteLater())); } //WebProxy::manageQuery