예제 #1
0
void BaseFileFind::runNewSearch(const QString &txt, Find::FindFlags findFlags,
                                    SearchResultWindow::SearchMode searchMode)
{
    m_currentFindSupport = 0;
    if (m_filterCombo)
        updateComboEntries(m_filterCombo, true);
    SearchResult *search = Find::SearchResultWindow::instance()->startNewSearch(label(),
                           toolTip().arg(Find::IFindFilter::descriptionForFindFlags(findFlags)),
                           txt, searchMode, QString::fromLatin1("TextEditor"));
    search->setTextToReplace(txt);
    search->setSearchAgainSupported(true);
    FileFindParameters parameters;
    parameters.text = txt;
    parameters.flags = findFlags;
    parameters.nameFilters = fileNameFilters();
    parameters.additionalParameters = additionalParameters();
    search->setUserData(qVariantFromValue(parameters));
    connect(search, SIGNAL(activated(Find::SearchResultItem)), this, SLOT(openEditor(Find::SearchResultItem)));
    if (searchMode == SearchResultWindow::SearchAndReplace) {
        connect(search, SIGNAL(replaceButtonClicked(QString,QList<Find::SearchResultItem>)),
                this, SLOT(doReplace(QString,QList<Find::SearchResultItem>)));
    }
    connect(search, SIGNAL(visibilityChanged(bool)), this, SLOT(hideHighlightAll(bool)));
    connect(search, SIGNAL(cancelled()), this, SLOT(cancel()));
    connect(search, SIGNAL(paused(bool)), this, SLOT(setPaused(bool)));
    connect(search, SIGNAL(searchAgainRequested()), this, SLOT(searchAgain()));
    connect(this, SIGNAL(enabledChanged(bool)), search, SLOT(setSearchAgainEnabled(bool)));
    runSearch(search);
}
예제 #2
0
void BaseFileFind::runNewSearch(const QString &txt, FindFlags findFlags,
                                    SearchResultWindow::SearchMode searchMode)
{
    d->m_currentFindSupport = 0;
    if (d->m_filterCombo)
        updateComboEntries(d->m_filterCombo, true);
    SearchResult *search = SearchResultWindow::instance()->startNewSearch(label(),
                           toolTip().arg(IFindFilter::descriptionForFindFlags(findFlags)),
                           txt, searchMode, SearchResultWindow::PreserveCaseEnabled,
                           QString::fromLatin1("TextEditor"));
    search->setTextToReplace(txt);
    search->setSearchAgainSupported(true);
    FileFindParameters parameters;
    parameters.text = txt;
    parameters.flags = findFlags;
    parameters.nameFilters = fileNameFilters();
    parameters.additionalParameters = additionalParameters();
    search->setUserData(qVariantFromValue(parameters));
    connect(search, &SearchResult::activated, this, &BaseFileFind::openEditor);
    if (searchMode == SearchResultWindow::SearchAndReplace)
        connect(search, &SearchResult::replaceButtonClicked, this, &BaseFileFind::doReplace);
    connect(search, &SearchResult::visibilityChanged, this, &BaseFileFind::hideHighlightAll);
    connect(search, &SearchResult::cancelled, this, &BaseFileFind::cancel);
    connect(search, &SearchResult::paused, this, &BaseFileFind::setPaused);
    connect(search, &SearchResult::searchAgainRequested, this, &BaseFileFind::searchAgain);
    connect(this, &BaseFileFind::enabledChanged, search, &SearchResult::requestEnabledCheck);
    connect(search, &SearchResult::requestEnabledCheck, this, &BaseFileFind::recheckEnabled);

    runSearch(search);
}
//Processing the results of search done by each thread and constructing  a response
void StringProcessor::processMessages(){
	sout << "\nIn string processor for string : " << srchString;

	try{
		int j = 0;
		Timer timer; timer.start();

		while (true){
			SearchResult sr = bqOut.deQ();
			if (sr.isFound()){
				filesFoundIn.push_back(sr.getFile());
			}
			//construct response
			j++;
			if (j == numFiles){
				//sout << "\nexiting from string processor";
				break;
			}
			/*for (std::thread* thrd : threads){
				thrd->join();
			}*/
			/*if (bqOut.isEmpty()){
				sout << "\nExiting from string processor\n";
				break;
				}*/
		}
		timer.stop();
		elapsedTime  = timer.elapsedTime<std::chrono::milliseconds>();
		constructResponse();

	}catch (exception e){
		sout << e.what();
	}
}
예제 #4
0
void SymbolsFindFilter::searchAgain()
{
    SearchResult *search = qobject_cast<SearchResult *>(sender());
    QTC_ASSERT(search, return);
    search->restart();
    startSearch(search);
}
예제 #5
0
QVariantList SearchApi::search(const int moduleID, const QString &queryString)
{
    DEBUG_FUNC_NAME
    SearchQuery query;
    query.searchText = queryString;
    query.queryType = SearchQuery::Simple;
    query.range = SearchQuery::Whole;

    SearchResult *result = new SearchResult();
    result->searchQuery = query;
    QVariantList res;

    Bible *module = (Bible*) m_moduleManager->newTextRangesVerseModule(moduleID);
    if(module != nullptr) {
        module->search(query, result);

        result->sort();
        foreach(const SearchHit &h, result->hits()) {
            QVariantMap m;
            QMapIterator<int, QVariant> i(h.m_map);
            while (i.hasNext()) {
                 i.next();
                 m[QString::number(i.key())] = i.value();
             }

            res << QVariant(m);
        }

        delete result;
        delete module;
    }
예제 #6
0
//void ArestShopPlugin::SinglePageFound()
//{
//#ifdef USE_WEBKIT
//	QWebFrame * ptrFrame = getWebPage()->mainFrame();
//	parseProductPage(m_stCompData);
//	m_stCompData.strCompURL = ptrFrame->url().toString();
//	emit priceSearchedFinished(m_stCompData);
//	productFoundFinish();
//#endif
//};
void ArestShopPlugin::parseSearchProductPage(SearchResult & stResult,bool & bNextPage)
{
	//run XML search page parse

	bNextPage=false;
#ifdef USE_WEBKIT
	QWebFrame * ptrFrame = getWebPage()->mainFrame();
	//////////////////////////////////////////////////////////////////////////
	QWebElementCollection tableProdRows = ptrFrame->findAllElements("table[class=pricelist]");
	
	for(int iIndex=0;iIndex<tableProdRows.count();++iIndex)
	{
		QWebElement prodNameHeader = tableProdRows.at(iIndex).findFirst("td[class=nazwa]");
		if (prodNameHeader.isNull())
			continue;
		QWebElement productLink = prodNameHeader.findFirst("a");
		QUrl stProductURL = productLink.attribute("href");
		//////////////////////////////////////////////////////////////////////////
		QString strName = productLink.toPlainText();
		stResult.insert(std::make_pair(strName,stProductURL));
	}
	//////////////////////////////////////////////////////////////////////////
	QWebElement tablePageNavi = ptrFrame->findFirstElement("li[class=next]");
	if (tablePageNavi.isNull())
	{
		bNextPage=false;
		return;
	}
	bNextPage=true;
#endif
	stResult.insert(Arest::mSearchResult.begin(),Arest::mSearchResult.end());
	bNextPage=m_bLoadNextPage;
}
예제 #7
0
/**
 * @brief TestAlgorithm::run start the search
 * @return a list of data packets containing results
 */
QList<DataPacket*> TestAlgorithm::run() {
    QList<DataPacket*> list;
    SearchResult* result = new SearchResult();
    list.append(dynamic_cast<DataPacket*>(result));

    for (QString& datasetPath : mQuery->getDatasets()) {
        Dataset dataset(datasetPath);

        for (Medium* medium : dataset.getMediaList()) {
            if (mCancel == true) {
                return list;
            }

            SearchObject* object = new SearchObject();
            object->setMedium(medium->getPath());
            object->setSourceDataset(dataset.getPath());

            //new result element
            SearchResultElement* resultElement = new SearchResultElement();
            resultElement->setSearchObject(*object);
            resultElement->setScore(std::rand() % 20);

            //add to result list
            result->addResultElement(*resultElement);
        }
    }
    QThread::msleep(1500);
    return list;
}
void WindowWithSearchResults::setResults(QList<Movie> movies) {
    this->results = movies;

    foreach (Movie movie, movies) {
        SearchResult *searchResult = new SearchResult(&movie, ui->listWidget, this);
        ui->listWidget->addItem(searchResult->getListItem());
        searchResult->fetchIcon();
    }
예제 #9
0
void FindResultsTab::DoOpenSearchResult(const SearchResult& result, wxStyledTextCtrl* sci, int markerLine)
{
    if(!result.GetFileName().IsEmpty()) {
        LEditor* editor = clMainFrame::Get()->GetMainBook()->OpenFile(result.GetFileName());
        if(editor && result.GetLen() >= 0) {
            // Update the destination position if there have been subsequent changes in the editor
            int position = result.GetPosition();
            std::vector<int> changes;
            editor->GetChanges(changes);
            unsigned int changesTotal = changes.size();
            int changePosition = 0;
            int changeLength = 0;
            int resultLength = result.GetLen();
            bool removed = false;
            for(unsigned int i = 0; i < changesTotal; i += 2) {
                changePosition = changes.at(i);
                changeLength = changes.at(i + 1);
                if((changeLength < 0) && (changePosition - changeLength > position) &&
                   (changePosition < position + resultLength)) {
                    // It looks like the data corresponding to this search result has been deleted
                    // While it's possible that it's been cut, then (later in the changes) re-pasted
                    // so that the result still matches, it's more likely to have been replaced by different text
                    // We can't easily tell, so assume the worst and label the result invalid
                    removed = true;
                    // Explain the failure
                    clMainFrame::Get()->GetStatusBar()->SetMessage(_("Search result is no longer valid"));
                    break;
                } else if(changePosition <= position) {
                    position += changeLength;
                }
            }
            if(!removed) {
                editor->SetEnsureCaretIsVisible(
                    position,
                    true,
                    true); // The 3rd parameter sets a small delay, otherwise it fails for long folded files
                int lineNumber = editor->LineFromPos(position);
                if(lineNumber) {
                    lineNumber--;
                }
                editor->SetLineVisible(lineNumber);
                editor->SetSelection(position, position + resultLength);

#ifdef __WXGTK__
                editor->ScrollToColumn(0);
#endif

                if(sci) {
                    // remove the previous marker and add the new one
                    sci->MarkerDeleteAll(7);
                    sci->MarkerAdd(markerLine, 7);
                    sci->EnsureVisible(markerLine);
                    sci->GotoLine(markerLine);
                }
            }
        }
    }
}
예제 #10
0
void SymbolsFindFilter::finish()
{
    auto watcher = static_cast<QFutureWatcher<SearchResultItem> *>(sender());
    SearchResult *search = m_watchers.value(watcher);
    if (search)
        search->finishSearch(watcher->isCanceled());
    m_watchers.remove(watcher);
    watcher->deleteLater();
}
예제 #11
0
void QSearchDisplayModel::downloadTorrent()
{
	if (m_pTorrentListView->model() != this)
	{
		return;
	}

	QModelIndex index = m_pTorrentListView->currentIndex();
	SearchResult* searchResult = index.data(SearchItemRole).value<SearchResult*>();
	m_pTorrentDownloader->download(searchResult->TorrentFileUrl());
}
예제 #12
0
void SymbolsFindFilter::addResults(int begin, int end)
{
    auto watcher = static_cast<QFutureWatcher<SearchResultItem> *>(sender());
    SearchResult *search = m_watchers.value(watcher);
    if (!search) {
        // search was removed from search history while the search is running
        watcher->cancel();
        return;
    }
    QList<SearchResultItem> items;
    for (int i = begin; i < end; ++i)
        items << watcher->resultAt(i);
    search->addResults(items, SearchResult::AddSorted);
}
예제 #13
0
void
GaduEditAccount::slotSearchResult( const SearchResult& result, unsigned int seq )
{
	if ( !( seq != 0 && seqNr != 0 && seq == seqNr ) || result.isEmpty() ) {
		return;
	}

	connectLabel->setText( " " );
		
	uiName->setText( result[0].firstname );
	uiSurname->setText( result[0].surname );
	nickName->setText( result[0].nickname );
	uiYOB->setText( result[0].age );
	uiCity->setText( result[0].city );

	kDebug( 14100 ) << "gender found: " << result[0].gender;
	if ( result[0].gender == QString( GG_PUBDIR50_GENDER_SET_FEMALE ) ) {
		uiGender->setCurrentIndex( 1 );
		kDebug(14100) << "looks like female";
	}
	else {
		if ( result[0].gender == QString( GG_PUBDIR50_GENDER_SET_MALE ) ) {
			uiGender->setCurrentIndex( 2 );
			kDebug( 14100 ) <<" looks like male";
		}
	}

	uiMeiden->setText( result[0].meiden );
	uiOrgin->setText( result[0].orgin );

	enableUserInfo( true );
	
	disconnect( SLOT(slotSearchResult(SearchResult,uint)) );
}
예제 #14
0
QVariant QSearchDisplayModel::data(const QModelIndex& index, int role /*= Qt::DisplayRole*/) const
{
	if(index.isValid())
	{
		int row = index.row();
		int col = index.column();
		SearchItemsStorragePtr results = m_pSearchEngine->GetResults();

		if(row > results->length())
		{
			return QVariant();
		}

		SearchResult* res = (*results) [row];

		switch(role)
		{
			case SearchItemRole:
			{
				return qVariantFromValue(res);
			}

			case SearchItemName:
			{
				return res->Name();
			}

			case SearchItemSize:
			{
				return res->Size();
			}

			case SearchItemSeeders:
			{
				return res->Seeders();
			}

			case SearchItemPeers:
			{
				return res->Leechers();
			}
		}
	}

	return QVariant();
}
예제 #15
0
void SymbolsFindFilter::findAll(const QString &txt, FindFlags findFlags)
{
    SearchResultWindow *window = SearchResultWindow::instance();
    SearchResult *search = window->startNewSearch(label(), toolTip(findFlags), txt);
    search->setSearchAgainSupported(true);
    connect(search, SIGNAL(activated(Core::SearchResultItem)),
            this, SLOT(openEditor(Core::SearchResultItem)));
    connect(search, SIGNAL(cancelled()), this, SLOT(cancel()));
    connect(search, SIGNAL(paused(bool)), this, SLOT(setPaused(bool)));
    connect(search, SIGNAL(searchAgainRequested()), this, SLOT(searchAgain()));
    connect(this, SIGNAL(enabledChanged(bool)), search, SLOT(setSearchAgainEnabled(bool)));
    window->popup(IOutputPane::ModeSwitch | IOutputPane::WithFocus);

    SymbolSearcher::Parameters parameters;
    parameters.text = txt;
    parameters.flags = findFlags;
    parameters.types = m_symbolsToSearch;
    parameters.scope = m_scope;
    search->setUserData(qVariantFromValue(parameters));
    startSearch(search);
}
예제 #16
0
void
GaduSession::sendResult( gg_pubdir50_t result )
{
	int i, count, age;
	ResLine resultLine;
	SearchResult sres;

	count = gg_pubdir50_count( result );

	if ( !count ) {
		kdDebug(14100) << "there was nothing found in public directory for requested details" << endl;
	}

	for ( i = 0; i < count; i++ ) {
		resultLine.uin		= QString( gg_pubdir50_get( result, i, GG_PUBDIR50_UIN ) ).toInt();
		resultLine.firstname	= textcodec->toUnicode( gg_pubdir50_get( result, i, GG_PUBDIR50_FIRSTNAME ) );
		resultLine.surname	= textcodec->toUnicode( gg_pubdir50_get( result, i, GG_PUBDIR50_LASTNAME ) );
		resultLine.nickname	= textcodec->toUnicode( gg_pubdir50_get( result, i, GG_PUBDIR50_NICKNAME ) );
		resultLine.age		= textcodec->toUnicode( gg_pubdir50_get( result, i, GG_PUBDIR50_BIRTHYEAR ) );
		resultLine.city		= textcodec->toUnicode( gg_pubdir50_get( result, i, GG_PUBDIR50_CITY ) );
		QString stat		= textcodec->toUnicode( gg_pubdir50_get( result, i, GG_PUBDIR50_STATUS ) );
		resultLine.orgin	= textcodec->toUnicode( gg_pubdir50_get( result, i, GG_PUBDIR50_FAMILYCITY ) );
		resultLine.meiden	= textcodec->toUnicode( gg_pubdir50_get( result, i, GG_PUBDIR50_FAMILYNAME ) );
		resultLine.gender	= textcodec->toUnicode( gg_pubdir50_get( result, i, GG_PUBDIR50_GENDER ) );

		resultLine.status	= stat.toInt();
		age = resultLine.age.toInt();
		if ( age ) {
			resultLine.age = QString::number( QDate::currentDate().year() - age );
		}
		else {
			resultLine.age.truncate( 0 );
		}
		sres.append( resultLine );
		kdDebug(14100) << "found line "<< resultLine.uin << " " << resultLine.firstname << endl;
	}

	searchSeqNr_ = gg_pubdir50_next( result );
	emit pubDirSearchResult( sres, gg_pubdir50_seq( result ) );
}
예제 #17
0
void ClientManager::on(NmdcSearch, Client* aClient, const string& aSeeker, int aSearchType, int64_t aSize,
									int aFileType, const string& aString) throw()
{
	Speaker<ClientManagerListener>::fire(ClientManagerListener::IncomingSearch(), aString);

	bool isPassive = (aSeeker.compare(0, 4, "Hub:") == 0);

	// We don't wan't to answer passive searches if we're in passive mode...
	if(isPassive && !ClientManager::getInstance()->isActive()) {
		return;
	}

	SearchResult::List l;
	ShareManager::getInstance()->search(l, aString, aSearchType, aSize, aFileType, aClient, isPassive ? 5 : 10);
//		dcdebug("Found %d items (%s)\n", l.size(), aString.c_str());
	if(l.size() > 0) {
		if(isPassive) {
			string name = aSeeker.substr(4);
			// Good, we have a passive seeker, those are easier...
			string str;
			for(SearchResult::Iter i = l.begin(); i != l.end(); ++i) {
				SearchResult* sr = *i;
				str += sr->toSR(*aClient);
				str[str.length()-1] = 5;
				str += name;
				str += '|';

				sr->decRef();
			}

			if(str.size() > 0)
				aClient->send(str);

		} else {
			try {
				string ip, file;
				uint16_t port = 0;
				Util::decodeUrl(aSeeker, ip, port, file);
				ip = Socket::resolve(ip);

				// Temporary fix to avoid spamming hublist.org and dcpp.net
				if(ip == "70.85.55.252" || ip == "207.44.220.108") {
					LogManager::getInstance()->message("Someone is trying to use your client to spam " + ip + ", please urge hub owner to fix this");
					return;
				}

				if(port == 0)
					port = 412;
				for(SearchResult::Iter i = l.begin(); i != l.end(); ++i) {
					SearchResult* sr = *i;
					udp.writeTo(ip, port, sr->toSR(*aClient));
					sr->decRef();
				}
			} catch(const SocketException& /* e */) {
				dcdebug("Search caught error\n");
			}
		}
	}
}
예제 #18
0
void SearchManager::onRES(const AdcCommand& cmd, const User::Ptr& from, const string& remoteIp) {
	int freeSlots = -1;
	int64_t size = -1;
	string file;
	string tth;
	string token;

	for(StringIterC i = cmd.getParameters().begin(); i != cmd.getParameters().end(); ++i) {
		const string& str = *i;
		if(str.compare(0, 2, "FN") == 0) {
			file = Util::toNmdcFile(str.substr(2));
		} else if(str.compare(0, 2, "SL") == 0) {
			freeSlots = Util::toInt(str.substr(2));
		} else if(str.compare(0, 2, "SI") == 0) {
			size = Util::toInt64(str.substr(2));
		} else if(str.compare(0, 2, "TR") == 0) {
			tth = str.substr(2);
		} else if(str.compare(0, 2, "TO") == 0) {
			token = str.substr(2);
		}
	}

	if(!file.empty() && freeSlots != -1 && size != -1) {

		StringList names = ClientManager::getInstance()->getHubNames(from->getCID());
		string hubName = names.empty() ? STRING(OFFLINE) : Util::toString(names);
		StringList hubs = ClientManager::getInstance()->getHubs(from->getCID());
		string hub = hubs.empty() ? STRING(OFFLINE) : Util::toString(hubs);

		SearchResult::Types type = (file[file.length() - 1] == '\\' ? SearchResult::TYPE_DIRECTORY : SearchResult::TYPE_FILE);
		if(type == SearchResult::TYPE_FILE && tth.empty())
			return;
		/// @todo Something about the slots
		SearchResult* sr = new SearchResult(from, type, 0, freeSlots, size,
			file, hubName, hub, remoteIp, TTHValue(tth), token);
		fire(SearchManagerListener::SR(), sr);
		sr->decRef();
	}
}
예제 #19
0
void BaseFileFind::runNewSearch(const QString &txt, Core::FindFlags findFlags,
                                    SearchResultWindow::SearchMode searchMode)
{
    d->m_currentFindSupport = 0;
    if (d->m_filterCombo)
        updateComboEntries(d->m_filterCombo, true);
    SearchResult *search = Core::SearchResultWindow::instance()->startNewSearch(label(),
                           toolTip().arg(Core::IFindFilter::descriptionForFindFlags(findFlags)),
                           txt, searchMode, QString::fromLatin1("TextEditor"));
    search->setTextToReplace(txt);
    search->setSearchAgainSupported(true);
    FileFindParameters parameters;
    parameters.text = txt;
    parameters.flags = findFlags;
    parameters.nameFilters = fileNameFilters();
    parameters.additionalParameters = additionalParameters();
    search->setUserData(qVariantFromValue(parameters));
    connect(search, SIGNAL(activated(Core::SearchResultItem)), this, SLOT(openEditor(Core::SearchResultItem)));
    if (searchMode == SearchResultWindow::SearchAndReplace) {
        connect(search, SIGNAL(replaceButtonClicked(QString,QList<Core::SearchResultItem>,bool)),
                this, SLOT(doReplace(QString,QList<Core::SearchResultItem>,bool)));
    }
//Processing that goes on in each thread
void StringProcessor::search(){
	try{
		ostringstream ossStart;
		ossStart << "\n Started Thread ID : " << std::this_thread::get_id() << " \n";
		sout << ossStart.str();

		while (true){
			if (bqIn.isEmpty()){
				ostringstream ossEnd;
				ossEnd << "\n Exiting from Thread ID : " << std::this_thread::get_id() << " \n";
				sout << ossEnd.str();

				return;
			}
			SearchResult sr = bqIn.deQ();
			ostringstream ossProcess;
			ossProcess << "\n Processing in Thread ID : " << std::this_thread::get_id() << " file " << sr.getFile() << " for string " << srchString << "\n";
			sout << ossProcess.str();
			if (searchStr(sr.getFile(), srchString)){
				sr.setFound(true);
			}
			else{
				sr.setFound(false);
			}
			bqOut.enQ(sr);
			if (sr.isFound()){
				thread::id tid = (std::this_thread::get_id());
				stringstream ss;
				ss << tid;
				string msg = "\nIn  thread " + ss.str() + " found \"" + srchString + "\" in file " + sr.getFile() + "\n";
				sout << msg;
				//filesFoundIn.push_back(sr.getFile());
			}
		}
	}catch (exception e){
		sout << e.what();
	}
}
예제 #21
0
    SearchResult * Index::search(SearchParams &params) {
        SearchResult * results = new SearchResult(busca_imd_core::directUltraFastHash);

        for (auto &&word : params.words) {
            FileHashMap * index;
            try {
                index = get(word);
            } catch (int e) {
                if (params.exclusive) {
                    //exclusive behavior, ia word is out there is no results
                    for (auto &&entry : *results) {
                        delete entry.value;
                    }
                    delete results;
                    return nullptr;
                } else {
                    continue;
                }
            }

            for (FileHashMap::Entry entry : *index) {
                List<int> * list;
                try {
                    list = results->get(*entry.key);
                } catch (int e) {
                    results->put(*entry.key, new List<int>(*entry.value));
                    continue;
                }
                if (params.exclusive) {
                    list->intersection(*entry.value, int_comparator);
                } else {
                    list->join(*entry.value, int_comparator);
                }
            }
        }
        return results;
    }
예제 #22
0
void TrackAnnotation::runSearch (QString query, QList <SearchResult*> &results) {
//    qDebug() << "TrackAnnotation::runSearch";

    QMap <QString,AnnotationItem*>::iterator i = data.names.find(query);
    QString query_l = query.toLower();

    if (i == data.names.end()) {
        for (i = data.names.begin(); i != data.names.end(); i++) {
            if (i.key().toLower() == query_l) break;
        }
    }

    if (i == data.names.end()) {
        bool found = false;
        for (i = data.names.begin(); i != data.names.end(); i++) {
            if (i.key().indexOf(query,0,Qt::CaseInsensitive) != -1) {
                SearchResult *sr = new SearchResult;
                sr->fromAnnotationItem (this, i.value());
                results.append(sr);
                found = true;
            }
        }
        if (found) return;
    }

    if (i != data.names.end()) {
        SearchResult *sr = new SearchResult;
        sr->fromAnnotationItem (this, i.value());
        results.append(sr);
        return;
    }

    for (QMap <QString,QList <AnnotationItem*> >::iterator j = data.items.begin(); j != data.items.end(); j++) {
        for (int k = 0; k < j.value().size(); k++) {
            if (j.value()[k]->description.indexOf(query,0,Qt::CaseInsensitive) != -1) {
                SearchResult *sr = new SearchResult;
                sr->fromAnnotationItem (this, j.value()[k]);
                results.append(sr);
            }
        }
    }
}
예제 #23
0
SearchResult InventorSearcher::search(string query)
{
    auto g = pminer.g.get();
    SearchResult result;
    unordered_map<int, vector<QueryItem>> inventor_pats;

    //searching section
    LOG(INFO) << "Searching for query: " << query;
    auto enumer = pminer.search_patents(query, pat_count);

    LOG(INFO) << "Generating Inventor Pats... patents: " << enumer.size();
    for (auto& item : enumer) {
        auto vi = g->Vertices();
        vi->MoveTo(item.docId);
        for (auto edgeIt = vi->InEdges(); edgeIt->Alive(); edgeIt->Next()) {
            if (edgeIt->TypeName() == "PatentInventor") {
                int gid = edgeIt->SourceId();
                inventor_pats[gid].push_back(item);
            }
        }
    }

    LOG(INFO) << "Scoring... inventors: " << inventor_pats.size();
    //start caculation score
    for (auto& gpats : inventor_pats) {
        QueryItem item{gpats.first, get_score_inventor(gpats, pminer)};
        if (item.score > 20 || result.size() <= 5000)
            result.push_back(item);
    }

    LOG(INFO) << "Sorting...";
    std::sort(result.begin(), result.end());
    if (result.size() > 5000)
        result.resize(5000);

    return result;
}
예제 #24
0
void SearchManager::onData(const uint8_t* buf, size_t aLen, const string& remoteIp) {
	string x((char*)buf, aLen);
	if(x.compare(0, 4, "$SR ") == 0) {
		string::size_type i, j;
		// Directories: $SR <nick><0x20><directory><0x20><free slots>/<total slots><0x05><Hubname><0x20>(<Hubip:port>)
		// Files:		$SR <nick><0x20><filename><0x05><filesize><0x20><free slots>/<total slots><0x05><Hubname><0x20>(<Hubip:port>)
		i = 4;
		if( (j = x.find(' ', i)) == string::npos) {
			return;
		}
		string nick = x.substr(i, j-i);
		i = j + 1;

		// A file has 2 0x05, a directory only one
		size_t cnt = count(x.begin() + j, x.end(), 0x05);

		SearchResult::Types type = SearchResult::TYPE_FILE;
		string file;
		int64_t size = 0;

		if(cnt == 1) {
			// We have a directory...find the first space beyond the first 0x05 from the back
			// (dirs might contain spaces as well...clever protocol, eh?)
			type = SearchResult::TYPE_DIRECTORY;
			// Get past the hubname that might contain spaces
			if((j = x.rfind(0x05)) == string::npos) {
				return;
			}
			// Find the end of the directory info
			if((j = x.rfind(' ', j-1)) == string::npos) {
				return;
			}
			if(j < i + 1) {
				return;
			}
			file = x.substr(i, j-i) + '\\';
		} else if(cnt == 2) {
			if( (j = x.find((char)5, i)) == string::npos) {
				return;
			}
			file = x.substr(i, j-i);
			i = j + 1;
			if( (j = x.find(' ', i)) == string::npos) {
				return;
			}
			size = Util::toInt64(x.substr(i, j-i));
		}
		i = j + 1;

		if( (j = x.find('/', i)) == string::npos) {
			return;
		}
		int freeSlots = Util::toInt(x.substr(i, j-i));
		i = j + 1;
		if( (j = x.find((char)5, i)) == string::npos) {
			return;
		}
		int slots = Util::toInt(x.substr(i, j-i));
		i = j + 1;
		if( (j = x.rfind(" (")) == string::npos) {
			return;
		}
		string hubName = x.substr(i, j-i);
		i = j + 2;
		if( (j = x.rfind(')')) == string::npos) {
			return;
		}

		string hubIpPort = x.substr(i, j-i);
		string url = ClientManager::getInstance()->findHub(hubIpPort);

		string encoding = ClientManager::getInstance()->findHubEncoding(url);
		nick = Text::toUtf8(nick, encoding);
		file = Text::toUtf8(file, encoding);
		hubName = Text::toUtf8(hubName, encoding);

		User::Ptr user = ClientManager::getInstance()->findUser(nick, url);
		if(!user) {
			// Could happen if hub has multiple URLs / IPs
			user = ClientManager::getInstance()->findLegacyUser(nick);
			if(!user)
				return;
		}

		string tth;
		if(hubName.compare(0, 4, "TTH:") == 0) {
			tth = hubName.substr(4);
			StringList names = ClientManager::getInstance()->getHubNames(user->getCID());
			hubName = names.empty() ? STRING(OFFLINE) : Util::toString(names);
		}

		if(tth.empty() && type == SearchResult::TYPE_FILE) {
			return;
		}


		SearchResult* sr = new SearchResult(user, type, slots, freeSlots, size,
			file, hubName, url, remoteIp, TTHValue(tth), Util::emptyString);
		fire(SearchManagerListener::SR(), sr);
		sr->decRef();
	} else if(x.compare(1, 4, "RES ") == 0 && x[x.length() - 1] == 0x0a) {
		AdcCommand c(x.substr(0, x.length()-1));
		if(c.getParameters().empty())
			return;
		string cid = c.getParam(0);
		if(cid.size() != 39)
			return;

		User::Ptr user = ClientManager::getInstance()->findUser(CID(cid));
		if(!user)
			return;

		// This should be handled by AdcCommand really...
		c.getParameters().erase(c.getParameters().begin());

		onRES(c, user, remoteIp);

	} /*else if(x.compare(1, 4, "SCH ") == 0 && x[x.length() - 1] == 0x0a) {
		try {
			respond(AdcCommand(x.substr(0, x.length()-1)));
		} catch(ParseException& ) {
		}
	}*/ // Needs further DoS investigation
}
예제 #25
0
/*
 * Patch interpolation, where destination and source fields are nodal.
 */
void patch_serial_transfer(MEField<> &src_coord_field, UInt _nfields, MEField<>* const* _sfields, _field* const *_dfields, const std::vector<Interp::FieldPair> &fpairs, SearchResult &sres, Mesh &srcmesh) {
   Trace __trace("patch_serial_transfer(MEField<> &src_coord_field, UInt _nfields, MEField<>* const* _sfields, _field* const *_dfields, int *iflag, SearchResult &sres)");


   std::set<int> pdeg_set;
   std::map<int, ElemPatch<>*> patch_map;
   
  if (_nfields == 0) return;

  // Get mask field pointer
  MEField<> *src_mask_ptr = srcmesh.GetField("mask");


  std::vector<MEField<>* > fields;
  std::vector<_field* > dfields;
  std::vector<int> orders;
  UInt nrhs = 0;
  
  for (UInt i = 0; i < _nfields; i++) {
  
    // Only process interp_patch  
    if (fpairs[i].idata != Interp::INTERP_PATCH) continue;
   
    pdeg_set.insert(fpairs[i].patch_order);

    //ThrowRequire(_sfields[i]->is_nodal());
  
    fields.push_back(_sfields[i]); dfields.push_back(_dfields[i]);
    orders.push_back(fpairs[i].patch_order);
    
    nrhs += _sfields[i]->dim(); // how many rhs for recovery
  }

  // Create the  recovery field
  SearchResult::iterator sb = sres.begin(), se = sres.end();

  for (; sb != se; sb++) {
    Search_result &sres = **sb;
    // Trick:  Gather the data from the source field so we may call interpolate point
    const MeshObj &elem = *(*sb)->elem;
//std::cout << "Transfer: elem:" << elem.get_id() << std::endl;

    {
      std::set<int>::iterator pi = pdeg_set.begin(), pe = pdeg_set.end();
      
      for (; pi != pe; ++pi) {
        
        ElemPatch<> *epatch = new ElemPatch<>();
    
        epatch->CreateElemPatch(*pi, ElemPatch<>::GAUSS_PATCH,
                               elem,
                               src_coord_field,
				src_mask_ptr,
                               fields.size(),
                               &fields[0],
                               700000
                                );
  
        patch_map[*pi] = epatch;
        
      }
    }
    
    // Gather parametric coords into an array.
    UInt pdim = GetMeshObjTopo(elem)->parametric_dim;
    UInt npts = sres.nodes.size(); // number of points to interpolate
    std::vector<double> pc(pdim*npts);
    
    for (UInt np = 0; np < npts; np++) {
    
      for (UInt pd = 0; pd < pdim; pd++) {
    
        pc[np*pdim+pd] = sres.nodes[np].pcoord[pd];
    
      }
    
    }

    std::map<int, std::vector<double> > result;
    
    {
      std::set<int>::iterator pi = pdeg_set.begin(), pe = pdeg_set.end();
      
      for (; pi != pe; ++pi) {

        std::pair<std::map<int, std::vector<double> >::iterator, bool> ri
             = result.insert(std::make_pair(*pi, std::vector<double>()));
        
        ThrowRequire(ri.second == true);
        
        ri.first->second.resize(nrhs*npts);
        
        ElemPatch<> &epatch = *patch_map[*pi];
        
        epatch.Eval(npts, &pc[0], &(ri.first->second[0]));
        
      }
      
    }
    
    std::vector<std::vector<double>* > field_results;
    
    for (UInt i = 0; i < dfields.size(); i++)
      field_results.push_back(&result[orders[i]]);
    
    // Now copy data into fields
    for (UInt np = 0; np < npts; np++) {
    
      const MeshObj &snode = *sres.nodes[np].node;
      UInt cur_field = 0;
    
      for (UInt i = 0; i < dfields.size(); i++) {
    
        const _field &dfield = *dfields[i];

        std::vector<double> &results = *field_results[i];
        
        if (dfield.OnObj(snode)) {
          UInt fdim = dfield.dim(snode);
          double *data = dfield.data(snode);
    
          for (UInt f = 0; f < fdim; f++) {
            data[f] = results[np*nrhs+(cur_field+f)];
          }

        }
        
        cur_field += dfield.dim(snode);

      } // for fi

    } // for np

   std::map<int, ElemPatch<>*>::iterator pi = patch_map.begin(), pe = patch_map.end();
   for (; pi != pe; ++pi) delete pi->second;
    
      
  } // for searchresult
  
}
예제 #26
0
void point_serial_transfer(Mesh &srcrend, Interp::UserFunc *ufunc, UInt num_fields, MEField<> *const *sfields, _field *const *dfields, int *iflag, SearchResult &sres) {
  Trace __trace("point_serial_transfer(Interp::UserFunc *ufunc, UInt num_fields, MEField<> *const *sfields, _field *const *dfields, int *iflag, SearchResult &sres)");
  

  if (num_fields == 0) return;

  SearchResult::iterator sb = sres.begin(), se = sres.end();

  for (; sb != se; sb++) {

    Search_result &sres = **sb;

    // Trick:  Gather the data from the source field so we may call interpolate point
    const MeshObj &elem = *(*sb)->elem;

    UInt pdim = GetMeshObjTopo(elem)->parametric_dim;

    // Inner loop through fields
    for (UInt i = 0; i < num_fields; i++) {

      if (iflag[i] != Interp::INTERP_STD) continue;

      MEField<> &sfield = *sfields[i];
      _field &dfield = *dfields[i];


     // Load Parametric coords
     UInt npts = sres.nodes.size(); // number of points to interpolate
     std::vector<double> pcoord(pdim*npts);
     for (UInt np = 0; np < npts; np++) {
       for (UInt pd = 0; pd < pdim; pd++)
         pcoord[np*pdim+pd] = sres.nodes[np].pcoord[pd];
     }

     std::vector<double> ires(npts*sfield.dim());

     if (!ufunc) {

       MEValues<> mev(sfield.GetMEFamily());

       arbq pintg(pdim, npts, &pcoord[0]);
       mev.Setup(elem, MEV::update_sf, &pintg);
       mev.ReInit(elem);
  
       mev.GetFunctionValues(sfield, &ires[0]);
    } else {

      ufunc->evaluate(srcrend, elem, sfield, npts, &pcoord[0], &ires[0]);

    }

     // Copy data to nodes
     for (UInt n = 0; n < npts; n++) {
       const MeshObj &node = *sres.nodes[n].node;
       for (UInt d = 0; d < dfield.dim(node); d++)
         ((double*)dfield.data(node))[d] = ires[n*dfield.dim(node)+d];
     }


    } // for fields


  } // for searchresult
}
예제 #27
0
SearchResult::SearchResult(const SearchResult &other): QObject(other.parent()), m_url(other.m_url), m_title(other.m_title), m_thumb(other.m_thumb)
{

}
예제 #28
0
void SearchThread::DoSearchLineRE(const wxString& line,
                                  const int lineNum,
                                  const int lineOffset,
                                  const wxString& fileName,
                                  const SearchData* data,
                                  TextStatesPtr statesPtr)
{
    wxRegEx& re = GetRegex(data->GetFindString(), data->IsMatchCase());
    size_t col = 0;
    int iCorrectedCol = 0;
    int iCorrectedLen = 0;
    wxString modLine = line;
    if(re.IsValid()) {
        while(re.Matches(modLine)) {
            size_t start, len;
            re.GetMatch(&start, &len);
            col += start;

            // Notify our match
            // correct search Pos and Length owing to non plain ASCII multibyte characters
            iCorrectedCol = clUTF8Length(line.c_str(), col);
            iCorrectedLen = clUTF8Length(line.c_str(), col + len) - iCorrectedCol;
            SearchResult result;
            result.SetPosition(lineOffset + col);
            result.SetColumnInChars((int)col);
            result.SetColumn(iCorrectedCol);
            result.SetLineNumber(lineNum);
            result.SetPattern(line);
            result.SetFileName(fileName);
            result.SetLenInChars((int)len);
            result.SetLen(iCorrectedLen);
            result.SetFlags(data->m_flags);
            result.SetFindWhat(data->GetFindString());

            // Make sure our match is not on a comment
            int position(wxNOT_FOUND);
            bool canAdd(true);

            if(statesPtr) {
                position = statesPtr->LineToPos(lineNum - 1);
                position += iCorrectedCol;
            }

            if(statesPtr && position != wxNOT_FOUND && data->GetSkipComments()) {
                if(statesPtr->states.size() > (size_t)position) {
                    short state = statesPtr->states.at(position).state;
                    if(state == CppWordScanner::STATE_CPP_COMMENT || state == CppWordScanner::STATE_C_COMMENT) {
                        canAdd = false;
                    }
                }
            }

            if(statesPtr && position != wxNOT_FOUND && data->GetSkipStrings()) {
                if(statesPtr->states.size() > (size_t)position) {
                    short state = statesPtr->states.at(position).state;
                    if(state == CppWordScanner::STATE_DQ_STRING || state == CppWordScanner::STATE_SINGLE_STRING) {
                        canAdd = false;
                    }
                }
            }

            result.SetMatchState(CppWordScanner::STATE_NORMAL);
            if(canAdd && statesPtr && position != wxNOT_FOUND && data->GetColourComments()) {
                // set the match state
                if(statesPtr->states.size() > (size_t)position) {
                    short state = statesPtr->states.at(position).state;
                    if(state == CppWordScanner::STATE_C_COMMENT || state == CppWordScanner::STATE_CPP_COMMENT) {
                        result.SetMatchState(state);
                    }
                }
            }

            if(canAdd) {
                m_results.push_back(result);
                m_summary.SetNumMatchesFound(m_summary.GetNumMatchesFound() + 1);
            }

            col += len;

            // adjust the line
            if(line.Length() - col <= 0) break;
            modLine = modLine.Right(line.Length() - col);
        }
    }
}
예제 #29
0
void SearchThread::DoSearchLine(const wxString& line,
                                const int lineNum,
                                const int lineOffset,
                                const wxString& fileName,
                                const SearchData* data,
                                const wxString& findWhat,
                                const wxArrayString& filters,
                                TextStatesPtr statesPtr)
{
    wxString modLine = line;

    if(!data->IsMatchCase()) {
        modLine.MakeLower();
    }

    int pos = 0;
    int col = 0;
    int iCorrectedCol = 0;
    int iCorrectedLen = 0;
    while(pos != wxNOT_FOUND) {
        pos = modLine.Find(findWhat);
        if(pos != wxNOT_FOUND) {
            col += pos;
            
            // Pipe support
            bool allFiltersOK = true;
            if(!filters.IsEmpty()) {
                // Apply the filters
                for(size_t i = 0; i < filters.size() && allFiltersOK; ++i) {
                    allFiltersOK = (modLine.Find(filters.Item(i)) != wxNOT_FOUND);
                }
            }
            
            // Pipe filtes OK?
            if(!allFiltersOK) return;
            
            // we have a match
            if(data->IsMatchWholeWord()) {

                // make sure that the word before is not in the wordChars map
                if((pos > 0) && (m_wordCharsMap.find(modLine.GetChar(pos - 1)) != m_wordCharsMap.end())) {
                    if(!AdjustLine(modLine, pos, findWhat)) {

                        break;
                    } else {
                        col += (int)findWhat.Length();
                        continue;
                    }
                }
                // if we have more characters to the right, make sure that the first char does not match any
                // in the wordCharsMap
                if(pos + findWhat.Length() <= modLine.Length()) {
                    wxChar nextCh = modLine.GetChar(pos + findWhat.Length());
                    if(m_wordCharsMap.find(nextCh) != m_wordCharsMap.end()) {
                        if(!AdjustLine(modLine, pos, findWhat)) {

                            break;
                        } else {
                            col += (int)findWhat.Length();
                            continue;
                        }
                    }
                }
            }

            // Notify our match
            // correct search Pos and Length owing to non plain ASCII multibyte characters
            iCorrectedCol = clUTF8Length(line.c_str(), col);
            iCorrectedLen = clUTF8Length(findWhat.c_str(), findWhat.Length());
            SearchResult result;
            result.SetPosition(lineOffset + col);
            result.SetColumnInChars(col);
            result.SetColumn(iCorrectedCol);
            result.SetLineNumber(lineNum);
            result.SetPattern(line);
            result.SetFileName(fileName);
            result.SetLenInChars((int)findWhat.Length());
            result.SetLen(iCorrectedLen);
            result.SetFindWhat(data->GetFindString());
            result.SetFlags(data->m_flags);

            int position(wxNOT_FOUND);
            bool canAdd(true);

            if(statesPtr) {
                position = statesPtr->LineToPos(lineNum - 1);
                position += iCorrectedCol;
            }

            // Make sure our match is not on a comment
            if(statesPtr && position != wxNOT_FOUND && data->GetSkipComments()) {
                if(statesPtr->states.size() > (size_t)position) {
                    short state = statesPtr->states.at(position).state;
                    if(state == CppWordScanner::STATE_CPP_COMMENT || state == CppWordScanner::STATE_C_COMMENT) {
                        canAdd = false;
                    }
                }
            }

            if(statesPtr && position != wxNOT_FOUND && data->GetSkipStrings()) {
                if(statesPtr->states.size() > (size_t)position) {
                    short state = statesPtr->states.at(position).state;
                    if(state == CppWordScanner::STATE_DQ_STRING || state == CppWordScanner::STATE_SINGLE_STRING) {
                        canAdd = false;
                    }
                }
            }

            result.SetMatchState(CppWordScanner::STATE_NORMAL);
            if(canAdd && statesPtr && position != wxNOT_FOUND && data->GetColourComments()) {
                // set the match state
                if(statesPtr->states.size() > (size_t)position) {
                    short state = statesPtr->states.at(position).state;
                    if(state == CppWordScanner::STATE_C_COMMENT || state == CppWordScanner::STATE_CPP_COMMENT) {
                        result.SetMatchState(state);
                    }
                }
            }

            if(canAdd) {
                m_results.push_back(result);
                m_summary.SetNumMatchesFound(m_summary.GetNumMatchesFound() + 1);
            }

            if(!AdjustLine(modLine, pos, findWhat)) {
                break;
            }
            col += (int)findWhat.Length();
        }
    }
}