Ejemplo n.º 1
0
UtlBoolean SipRequestContext::getVariable(const char* name, 
                                             UtlString& value, 
                                             int occurance) const
{
    UtlDListIterator iterator((UtlDList&)mVariableList);
    NameValuePair* nameValuePair = NULL;
    int fieldIndex = 0;
    UtlString upperCaseName;
    UtlBoolean foundName = FALSE;

    value.remove(0);

    if(name)
    {
        upperCaseName.append(name);
        upperCaseName.toUpper();
    }
    NameValuePair matchName(upperCaseName);

    // For each name value:
    while(fieldIndex <= occurance)
    {
        // Go to the next header field
        nameValuePair = (NameValuePair*) iterator.findNext(&matchName);

        if(!nameValuePair || fieldIndex == occurance)
        {
            break;
        }
        fieldIndex++;
    }

    if(fieldIndex == occurance && nameValuePair)
    {
        value.append(nameValuePair->getValue());
        foundName = TRUE;
    }

    upperCaseName.remove(0);
    return(foundName);
}
Ejemplo n.º 2
0
bool
Response::fromData(const Name& zone, const Data& data)
{
  label::MatchResult re;
  if (!matchName(data, zone, re))
    return false;

  m_rrLabel = re.rrLabel;
  m_rrType = re.rrType;
  m_version = re.version;

  m_zone = zone;
  size_t len = zone.size();
  m_queryType = data.getName().get(len);

  MetaInfo info = data.getMetaInfo();

  m_freshnessPeriod = time::duration_cast<time::seconds>(info.getFreshnessPeriod());
  m_contentType = NdnsContentType(data.getContentType());

  wireDecode(data.getContent());
  return true;
}
Ejemplo n.º 3
0
/**
 * 	singleLevelWildcard parses a single level of the path and returns all
 * 	ids that match it. If there is a suitable doublehash, it will recurse
 * 	into child elements.
 * 	Returns # of ids found.
 */
int singleLevelWildcard( Id start, const string& path, vector< Id >& ret )
{
	if ( path.length() == 0 )
		return 0;
	unsigned int nret = ret.size();

/*
#ifdef USE_MPI
	// Won't work for global nodes
	if ( start.node() != Shell::myNode() ) {
		Eref shellE = Id::shellId().eref();
		Shell* sh = static_cast< Shell* >( shellE.data() );
		assert( shellE.e != 0 );
		vector< Nid > kids;
		unsigned int requestId = openOffNodeValueRequest< vector< Nid > >( 
			sh, &kids, 1 );
		unsigned int tgtNode = start.node();
		if ( tgtNode > Shell::myNode() )
			--tgtNode;
		sendTo3< Nid, string, unsigned int >( 
			shellE, singleLevelWildcardSlot, tgtNode,
			start, path, requestId );
		vector< Nid >* temp = 
			closeOffNodeValueRequest< vector< Nid > >( sh, requestId );
		assert( temp == &kids );
		for ( size_t i = 0; i < kids.size(); ++i ) {
			ret.push_back( kids[i] );
		}
		return ret.size() - nret;
	}
#endif
*/

	string beforeBrace;
	string insideBrace;
	unsigned int index;
	// This has to handle ghastly cases like foo[][FIELD(x)=12.3]
	findBraceContent( path, beforeBrace, insideBrace, index );
	if ( beforeBrace == "##" )
		return allChildren( start, insideBrace, index, ret ); // recursive.

	/*
	 * Future off-node stuff. But this really needs to be delegated
	 * to a separate routine, which does nothing but get the wildcard
	 * list off node. Also should bring back the names and indices.
	 *
	vector< Nid > kids;
	unsigned int requestId = openOffNodeValueRequest< vector< Nid > >( 
		sh, &kids, sh->numNodes() - 1 );
	send2< Nid, unsigned int >( shellE, requestLeSlot, start, requestId );
	vector< Nid >* temp = 
		closeOffNodeValueRequest< vector< Nid > >( sh, requestId );
	assert( temp == &kids );
		
	vector< Nid >::iterator i;
	for ( i = kids.begin(); i != kids.end(); i++ ) {
		if ( matchName( start, *i, beforeBrace, insideBrace, index ) )
			ret.push_back( *i );
	}
	return ret.size() - nret;
	*/

	vector< Id > kids; 
	Neutral::getChildren( start.eref(), kids );
// 	cout << start.eref().name() << endl;
// 	for (size_t i = 0; i < kids.size(); i++)
// 		cout << "* " << kids[i].eref().name() << endl;
	vector< Id >::iterator i;
	for ( i = kids.begin(); i != kids.end(); i++ ) {
		if ( matchName( start, *i, beforeBrace, insideBrace, index ) )
			ret.push_back( *i );
	}

	return ret.size() - nret;
}
std::vector<Result> ResultGenerator::findResults(const std::string &text, int duplicateProximity, ResultGenerator::Verbosity verbosity, ResultGenerator::Statistics *statistics) {
    std::vector<Result> results;
#ifdef CPUTIMER
    Timer timer, timerOverFunction;
    int64_t cputime, walltime;
#endif // CPUTIMER

#ifdef CPUTIMER
    timer.start();
    timerOverFunction.start();
#endif // CPUTIMER
    const std::vector<std::string> words = tokenizer->read_words(text, Tokenizer::Duplicates);
    const std::vector<std::string> word_combinations = tokenizer->generate_word_combinations(words, 3 /** TODO configurable */);
    Error::info("Identified %d words, resulting in %d word combinations", words.size(), word_combinations.size());
    if (statistics != nullptr) {
        statistics->word_count = words.size();
        statistics->word_combinations_count = word_combinations.size();
    }
#ifdef CPUTIMER
    if (verbosity > VerbositySilent) {
        timer.elapsed(&cputime, &walltime);
        Error::info("Spent CPU time to tokenize text of length %d: %.1fms == %.1fs  (wall time: %.1fms == %.1fs)", text.length(), cputime / 1000.0, cputime / 1000000.0, walltime / 1000.0, walltime / 1000000.0);
    }
#endif // CPUTIMER

    /// ===================================================================================
    /// Check if the test input contains road labels (e.g. 'E 20') and city/town names.
    /// Then determine the clostest distance between any city/town and any identified road.
    /// If distance is below an acceptable threshold, assume location on road closest to
    /// town as resulting position.
    /// -----------------------------------------------------------------------------------
    if (verbosity > VerbositySilent) {
        Error::info("=== Testing for roads close to cities/towns ===");
#ifdef CPUTIMER
        timer.start();
#endif // CPUTIMER
    }

    const std::vector<struct Sweden::Road> identifiedRoads = sweden->identifyRoads(words);
    Error::info("Identified roads: %d", identifiedRoads.size());
    const std::vector<struct TokenProcessor::RoadMatch> roadMatches = tokenProcessor->evaluteRoads(word_combinations, identifiedRoads);
    Error::info("Identified road matches: %d", roadMatches.size());

    for (const TokenProcessor::RoadMatch &roadMatch : roadMatches) {
        const int distance = roadMatch.distance;

        if (distance < 10000) {
            /// Closer than 10km
            Coord c;
            if (node2Coord->retrieve(roadMatch.bestRoadNode, c)) {
                Result r(c, roadMatch.quality, std::string("roadMatch: road:") + static_cast<std::string>(roadMatch.road) + " near " + roadMatch.word_combination);
                r.elements.push_back(OSMElement(roadMatch.bestRoadNode, OSMElement::Node, OSMElement::UnknownRealWorldType));
                r.elements.push_back(OSMElement(roadMatch.bestWordNode, OSMElement::Node, OSMElement::UnknownRealWorldType));
                results.push_back(r);
                if (verbosity > VerbositySilent)
                    Error::debug("Distance between '%s' and road %s: %.1f km (between road node %llu and word's node %llu)", roadMatch.word_combination.c_str(), roadMatch.road.operator std::string().c_str(), distance / 1000.0, roadMatch.bestRoadNode, roadMatch.bestWordNode);
            }
        }
    }
#ifdef CPUTIMER
    if (verbosity > VerbositySilent) {
        timer.elapsed(&cputime, &walltime);
        Error::info("Spent CPU time to identify roads close to cities/towns: %.1fms == %.1fs  (wall time: %.1fms == %.1fs)", cputime / 1000.0, cputime / 1000000.0, walltime / 1000.0, walltime / 1000000.0);
    }
#endif // CPUTIMER


    if (verbosity > VerbositySilent) {
        Error::info("=== Testing for places inside administrative boundaries ===");
#ifdef CPUTIMER
        timer.start();
#endif // CPUTIMER
    }
    const std::vector<struct Sweden::KnownAdministrativeRegion> adminReg = sweden->identifyAdministrativeRegions(word_combinations);
    Error::info("Identified administrative regions: %d", adminReg.size());
    if (!adminReg.empty()) {
        const std::vector<struct TokenProcessor::AdminRegionMatch> adminRegionMatches = tokenProcessor->evaluateAdministrativeRegions(adminReg, word_combinations);
        Error::info("Identified administrative region matches: %d", adminReg.size());
        for (const auto &adminRegionMatch : adminRegionMatches) {
            Coord c;
            if (getCenterOfOSMElement(adminRegionMatch.match, c)) {
                WriteableString matchName("UNSET");
                switch (adminRegionMatch.match.type) {
                case OSMElement::Node: nodeNames->retrieve(adminRegionMatch.match.id, matchName); break;
                case OSMElement::Way: wayNames->retrieve(adminRegionMatch.match.id, matchName); break;
                case OSMElement::Relation: relationNames->retrieve(adminRegionMatch.match.id, matchName); break;
                case OSMElement::UnknownElementType: matchName = WriteableString("Unknown"); break;
                }

                Result r(c, adminRegionMatch.quality * .95, std::string("Places inside admin bound: ") + adminRegionMatch.adminRegion.name + " (relation " + std::to_string(adminRegionMatch.adminRegion.relationId) + ") > '" + matchName + "' (" + adminRegionMatch.match.operator std::string() + ", found via: '" + adminRegionMatch.combined + "')");
                r.elements.push_back(OSMElement(adminRegionMatch.adminRegion.relationId, OSMElement::Relation));
                r.elements.push_back(adminRegionMatch.match);
                results.push_back(r);
                if (verbosity > VerbositySilent)
                    Error::debug("Found place '%s' (%s) inside admin region '%s' (%d) via combination '%s'", matchName.c_str(), adminRegionMatch.match.operator std::string().c_str(), adminRegionMatch.adminRegion.name.c_str(), adminRegionMatch.adminRegion.relationId, adminRegionMatch.combined.c_str(), adminRegionMatch.combined.c_str());
            }
        }
    }
#ifdef CPUTIMER
    if (verbosity > VerbositySilent) {
        timer.elapsed(&cputime, &walltime);
        Error::info("Spent CPU time to identify places inside administrative boundaries: %.1fms == %.1fs  (wall time: %.1fms == %.1fs)", cputime / 1000.0, cputime / 1000000.0, walltime / 1000.0, walltime / 1000000.0);
    }
#endif // CPUTIMER

    if (verbosity > VerbositySilent) {
        Error::info("=== Testing for local-scope places near global-scope places ===");
#ifdef CPUTIMER
        timer.start();
#endif // CPUTIMER
    }
    std::vector<struct OSMElement> globalPlaces = sweden->identifyPlaces(word_combinations);
    Error::info("Identified global places: %d", globalPlaces.size());
    if (!globalPlaces.empty()) {
        const OSMElement::RealWorldType firstRwt = globalPlaces.front().realworld_type;
        for (auto it = ++globalPlaces.cbegin(); it != globalPlaces.cend();) {
            if (it->realworld_type != firstRwt)
                it = globalPlaces.erase(it);
            else
                ++it;
        }
        const std::vector<struct TokenProcessor::LocalPlaceMatch> localPlacesMatches = tokenProcessor->evaluateNearPlaces(word_combinations, globalPlaces);
        Error::info("Identified local places matches: %d", localPlacesMatches.size());
        for (const auto &localPlacesMatch : localPlacesMatches) {
            Coord c;
            if (getCenterOfOSMElement(localPlacesMatch.local, c)) {
                Result r(c, localPlacesMatch.quality * .75, std::string("Local near global place: ") + localPlacesMatch.local.operator std::string() + " ('" + localPlacesMatch.local.name() + "') near " + localPlacesMatch.global.operator std::string() + " ('" + localPlacesMatch.global.name() + "')");
                r.elements.push_back(localPlacesMatch.global);
                r.elements.push_back(localPlacesMatch.local);
                results.push_back(r);
                if (verbosity > VerbositySilent)
                    Error::debug("Got a result for global place '%s' and local place '%s'", localPlacesMatch.global.operator std::string().c_str(), localPlacesMatch.local.operator std::string().c_str());
            }
        }
    }
#ifdef CPUTIMER
    if (verbosity > VerbositySilent) {
        timer.elapsed(&cputime, &walltime);
        Error::info("Spent CPU time to identify local/global places: %.1fms == %.1fs  (wall time: %.1fms == %.1fs)", cputime / 1000.0, cputime / 1000000.0, walltime / 1000.0, walltime / 1000000.0);
    }
#endif // CPUTIMER


    if (verbosity > VerbositySilent) {
        Error::info("=== Testing word combination occurring only once (unique) in OSM data ===");
#ifdef CPUTIMER
        timer.start();
#endif // CPUTIMER
    }
    std::vector<struct TokenProcessor::UniqueMatch> uniqueMatches = tokenProcessor->evaluateUniqueMatches(word_combinations);
    Error::info("Identified unique matches: %d", uniqueMatches.size());
    for (const auto &uniqueMatch : uniqueMatches) {
        Coord c;
        if (getCenterOfOSMElement(uniqueMatch.element, c)) {
            Result r(c, uniqueMatch.quality * .8, std::string("Unique name '") + uniqueMatch.element.name().c_str() + "' (" + uniqueMatch.element.operator std::string() + ") found via '" + uniqueMatch.combined + "'");
            r.elements.push_back(uniqueMatch.element);
            results.push_back(r);
            if (verbosity > VerbositySilent)
                Error::debug("Got a result for combined word '%s': %s (%s)", uniqueMatch.combined.c_str(), uniqueMatch.element.name().c_str(), uniqueMatch.element.operator std::string().c_str());
        }
    }
#ifdef CPUTIMER
    if (verbosity > VerbositySilent) {
        timer.elapsed(&cputime, &walltime);
        Error::info("Spent CPU time to identify unique places: %.1fms == %.1fs  (wall time: %.1fms == %.1fs)", cputime / 1000.0, cputime / 1000000.0, walltime / 1000.0, walltime / 1000000.0);
    }
#endif // CPUTIMER


    if (!globalPlaces.empty()) {
        /// No good result found, but some places have been recognized in the process.
        /// Pick one of the larger places as result.
        if (verbosity > VerbositySilent) {
            Error::info("=== Testing any known places, trying to pick a good one ===");
#ifdef CPUTIMER
            timer.start();
#endif // CPUTIMER
        }
        // FIXME picking the right place from the list is rather ugly. Can do better?
        OSMElement bestPlace;
        OSMElement::RealWorldType rwt = OSMElement::PlaceSmall;
        for (const OSMElement &place : globalPlaces) {
            if (place.realworld_type == OSMElement::PlaceMedium && rwt >= OSMElement::PlaceSmall) {
                bestPlace = place;
                rwt = place.realworld_type;
            } else if (place.realworld_type < OSMElement::PlaceMedium && rwt >= OSMElement::PlaceMedium) {
                bestPlace = place;
                rwt = place.realworld_type;
            } else if (rwt != OSMElement::PlaceLarge && place.realworld_type == OSMElement::PlaceLargeArea) {
                bestPlace = place;
                rwt = place.realworld_type;
            } else if (rwt == OSMElement::PlaceLargeArea && place.realworld_type == OSMElement::PlaceLarge) {
                bestPlace = place;
                rwt = place.realworld_type;
            }
        }

        if (bestPlace.isValid()) {
            const double quality = rwt == OSMElement::PlaceLarge ? 1.0 : (rwt == OSMElement::PlaceMedium?.9 : (rwt == OSMElement::PlaceLargeArea?.6 : (rwt == OSMElement::PlaceSmall?.8 : .5)));
            Coord c;
            if (getCenterOfOSMElement(bestPlace, c)) {
                Result r(c, quality * .5, std::string("Large place: ") + bestPlace.name() + " (" + bestPlace.operator std::string() + ")");
                r.elements.push_back(bestPlace);
                results.push_back(r);
                if (verbosity > VerbositySilent)
                    Error::debug("Best place is %s (%s)", bestPlace.name().c_str(), bestPlace.operator std::string().c_str());
            }
        }
#ifdef CPUTIMER
        if (verbosity > VerbositySilent) {
            timer.elapsed(&cputime, &walltime);
            Error::info("Spent CPU time to identify known places: %.1fms == %.1fs  (wall time: %.1fms == %.1fs)", cputime / 1000.0, cputime / 1000000.0, walltime / 1000.0, walltime / 1000000.0);
        }
#endif // CPUTIMER
    }


    if (!results.empty()) {
        if (verbosity > VerbositySilent) {
            Error::info("=== Sorting and cleaning results ===");
#ifdef CPUTIMER
            timer.start();
#endif // CPUTIMER
        }
        if (duplicateProximity > 0) {
            const int64_t duplicateProximitySquare = (int64_t)duplicateProximity * (int64_t)duplicateProximity;
            /// Remove results close to even better results
            std::unordered_set<Result> result_set(results.cbegin(), results.cend());
            for (auto outer = result_set.cbegin(); outer != result_set.cend();) {
                bool removedOuter = false;
                const Result &outerR = *outer;
                for (auto inner = result_set.cbegin(); !removedOuter && inner != result_set.cend(); ++inner) {
                    if (inner == outer) continue;
                    const Result &innerR = *inner;
                    if (outerR.quality > innerR.quality) continue; ///< avoid removing results of higher quality
                    const auto d = Coord::distanceXYsquare(outerR.coord, innerR.coord);
                    if (d < duplicateProximitySquare) {
                        /// Less than x meters away? Remove this result!
                        outer = result_set.erase(outer);
                        removedOuter = true;
                    }
                }
                if (!removedOuter)
                    ++outer;
            }
            results.assign(result_set.cbegin(), result_set.cend());
        }
        /// Sort results by quality (highest first)
        std::sort(results.begin(), results.end(), [](Result & a, Result & b) {
            return a.quality > b.quality;
        });
#ifdef CPUTIMER
        if (verbosity > VerbositySilent) {
            timer.elapsed(&cputime, &walltime);
            Error::info("Spent CPU time to clean/sort results: %.1fms == %.1fs  (wall time: %.1fms == %.1fs)", cputime / 1000.0, cputime / 1000000.0, walltime / 1000.0, walltime / 1000000.0);
        }
#endif // CPUTIMER
    }

#ifdef CPUTIMER
    timerOverFunction.elapsed(&cputime, &walltime);
    Error::info("%d results, time %.1fms == %.1fs  (wall time: %.1fms == %.1fs)", results.size(), cputime / 1000.0, cputime / 1000000.0, walltime / 1000.0, walltime / 1000000.0);
#else // CPUTIMER
    Error::debug("%d results", results.size());
#endif // CPUTIMER

    if (verbosity > VerbositySilent)
        Error::info("=== Done generating results ===");

    return results;
}
Ejemplo n.º 5
0
static void GetMacFromDevice(uint8_t mac[6], const char *devicename)
{
	/* UNAVALIABLE LINUX CODE

	int    fd;
	int    err;
	struct ifreq    ifr;

	fd = socket(PF_PACKET, SOCK_RAW, htons(0x0806));
	assert(fd != -1);

	assert(strlen(devicename) < IFNAMSIZ);
	strncpy(ifr.ifr_name, devicename, IFNAMSIZ);
	ifr.ifr_addr.sa_family = AF_INET;

	err = ioctl(fd, SIOCGIFHWADDR, &ifr);
	assert(err != -1);
	memcpy(mac, ifr.ifr_hwaddr.sa_data, 6);

	err = close(fd);
	assert(err != -1);
	return;
	*/
	PIP_ADAPTER_INFO pIpAdapterInfo = new IP_ADAPTER_INFO();
	unsigned long stSize = sizeof(IP_ADAPTER_INFO);
	int nRel = GetAdaptersInfo(pIpAdapterInfo,&stSize);
	int netCardNum = 0;
	int IPnumPerNetCard = 0;
	if (ERROR_BUFFER_OVERFLOW == nRel)
	{
		/*如果函数返回的是ERROR_BUFFER_OVERFLOW
		则说明GetAdaptersInfo参数传递的内存空间不够,同时其传出stSize,表示需要的空间大小
		这也是说明为什么stSize既是一个输入量也是一个输出量*/
		//释放原来的内存空间
		delete pIpAdapterInfo;
		//重新申请内存空间用来存储所有网卡信息
		pIpAdapterInfo = (PIP_ADAPTER_INFO)new BYTE[stSize];
		//再次调用GetAdaptersInfo函数,填充pIpAdapterInfo指针变量
		nRel=GetAdaptersInfo(pIpAdapterInfo,&stSize);    
	}
	if (ERROR_SUCCESS == nRel)
	{
		//输出网卡信息
		//可能有多网卡,因此通过循环去判断
		while (pIpAdapterInfo)
		{
			if (pIpAdapterInfo->Type == MIB_IF_TYPE_ETHERNET)
			{
				char *buf = new char[strlen(devicename)+1];
				strcpy(buf,devicename);
				if (matchName(pIpAdapterInfo->AdapterName,buf))
				{
					//转移MAC数据到mac数组
					for (int k=0;k<6;k++)
					{
						mac[k]=(uint8_t)pIpAdapterInfo->Address[k];
					}
					break;
				}
			}
			pIpAdapterInfo = pIpAdapterInfo->Next;
		}
	}
	return;

}
Ejemplo n.º 6
0
 bool
 match(const Data& data)
 {
   return matchName(data.getName());
 }