Example #1
0
std::vector<double> CloverChunk::dumpArray
(const std::string& arr_name, int x_extra, int y_extra)
{
    // number of bytes to allocate for 2d array
    #define BUFSZ2D(x_extra, y_extra)   \
        ( ((x_max) + 2*halo_exchange_depth + x_extra)       \
        * ((y_max) + 2*halo_exchange_depth + y_extra)       \
        * sizeof(double) )

    std::vector<double> host_buffer(BUFSZ2D(x_extra, y_extra)/sizeof(double));

    queue.finish();

    try
    {
        queue.enqueueReadBuffer(arr_names.at(arr_name),
            CL_TRUE, 0, BUFSZ2D(x_extra, y_extra), &host_buffer[0]);
    }
    catch (cl::Error e)
    {
        DIE("Error '%s (%d)' reading array %s back from device",
            e.what(), e.err(), arr_name.c_str());
    }
    catch (std::out_of_range e)
    {
        DIE("Error - %s was not in the arr_names map\n", arr_name.c_str());
    }

    queue.finish();

    return host_buffer;
}
size_t findInStream(std::ifstream &stream, const std::string &sig)
{
    const size_t start = stream.tellg();

    while(!stream.eof())
    {
        auto it = sig.begin();
        for( size_t s=0 ; it != sig.end() ; it++, s++ )
        {
            char c = stream.get();

            if( sig[s] != c )
                break;
        }

        if( it == sig.end() )
            break;
    }

    size_t pos;

    if(stream.eof())
        pos = std::string::npos;
    else
        pos = stream.tellg();

    stream.seekg(start);

    return pos;
}
Example #3
0
int retrieve_status(const std::string & hostname, uint16_t port,
                    const std::string & request_str, int timeout) {
    void *context = zmq_ctx_new();
    void *socket = zmq_socket(context, ZMQ_REQ);
    int linger = 0;
    zmq_setsockopt(socket, ZMQ_LINGER, &linger, sizeof(int));

    std::string connect_str = "tcp://" + hostname + ":" + std::to_string(port);
    zmq_connect(socket, connect_str.c_str());
    zmq_send(socket, request_str.c_str(), request_str.size(), 0);

    zmq_pollitem_t items[] = { {socket, 0, ZMQ_POLLIN, 0} };
    if (zmq_poll(items, 1, timeout) > 0) {
        zmq_msg_t msg;
        zmq_msg_init(&msg);
        if (zmq_msg_recv(&msg, socket, 0) != -1) {
            std::string reply_str((char *)zmq_msg_data(&msg), zmq_msg_size(&msg));
            printf("%s\n", reply_str.c_str());
            return 0;
        } else {
            return 1;
        }
    } else {
        return 1;
    }
}
Example #4
0
NumberType Chipset::findNumberType(const std::string &number)
{
	bool dotFound = false;

	if (isDigit(number[0]) == false && number[0] != '-')
		return (UNKNOWN);
	if (number[0] == '-' && number.size() <= 1)
		return (UNKNOWN);

	if (number[0] == '-')
	{
		if (!isDigit(number[1]))
			return (UNKNOWN);
	}
	size_t i;
	for (i = 1; i < number.length(); i++)
	{
		if (number[i] == '.')
		{
			if (dotFound == true || i == (number.length() - 1))
				return (UNKNOWN);
			dotFound = true;
		}
		else
		{
			if (isDigit(number[i]) == false)
				return (UNKNOWN);
		}
	}

	if (dotFound == true)
		return (FLOTTANT);
	return (ENTIER);
}
Example #5
0
void Queue::readProperties (const std::string& _sBuf)
{
    char *_tmpBuf = new char[_sBuf.length()];
    memcpy(_tmpBuf, _sBuf.data(), _sBuf.length());
    ::qpid::management::Buffer buf(_tmpBuf, _sBuf.length());
    Mutex::ScopedLock mutex(accessLock);

    {
        std::string _tbuf;
        buf.getRawData(_tbuf, writeTimestampsSize());
        readTimestamps(_tbuf);
    }


    for (uint8_t idx = 0; idx < 1; idx++)
        presenceMask[idx] = buf.getOctet();

    {std::string _s; buf.getRawData(_s, vhostRef.encodedSize()); vhostRef.decode(_s);};
    buf.getShortString(name);
    durable = buf.getOctet()==1;
    autoDelete = buf.getOctet()==1;
    exclusive = buf.getOctet()==1;
    buf.getMap(arguments);
    if (presenceMask[presenceByte_altExchange] & presenceMask_altExchange) {
        {std::string _s; buf.getRawData(_s, altExchange.encodedSize()); altExchange.decode(_s);};
    }


    delete [] _tmpBuf;
}
Example #6
0
static void HookMain(void * retAddr)
{
	if(hookInstalled)
		return;
	else
		hookInstalled = true;

	_MESSAGE("HookMain: thread = %d retaddr = %016I64X", GetCurrentThreadId(), retAddr);

	std::string runtimePath = GetRuntimePath();
	_MESSAGE("runtimePath = %s", runtimePath.c_str());

	bool isEditor = false;

	// check version etc
	std::string		dllSuffix;
	ProcHookInfo	procHookInfo;

	if(!IdentifyEXE(runtimePath.c_str(), isEditor, &dllSuffix, &procHookInfo))
	{
		_ERROR("unknown exe");
		return;
	}

	const char	* dllPrefix = (isEditor == false) ? "\\skse64_" : "\\skse64_editor_";

	g_dllPath = GetRuntimeDirectory() + dllPrefix + dllSuffix + ".dll";
	_MESSAGE("dll = %s", g_dllPath.c_str());

	LoadLibrary(g_dllPath.c_str());
}
Example #7
0
void InspIRCd::StripColor(std::string &sentence)
{
	/* refactor this completely due to SQUIT bug since the old code would strip last char and replace with \0 --peavey */
	int seq = 0;

	for (std::string::iterator i = sentence.begin(); i != sentence.end();)
	{
		if (*i == 3)
			seq = 1;
		else if (seq && (( ((*i >= '0') && (*i <= '9')) || (*i == ',') ) ))
		{
			seq++;
			if ( (seq <= 4) && (*i == ',') )
				seq = 1;
			else if (seq > 3)
				seq = 0;
		}
		else
			seq = 0;

		if (seq || ((*i == 2) || (*i == 15) || (*i == 22) || (*i == 21) || (*i == 31)))
			i = sentence.erase(i);
		else
			++i;
	}
}
void printTooltipColors(GtkStyleContext* a_StyleContextLabel, GtkStyleContext* a_StyleContextTooltip, const char* a_Caption)
{
	const std::string dumpFore = dumpStyleContext(a_StyleContextLabel);
	const std::string dumpBack = dumpStyleContext(a_StyleContextTooltip);

	GdkRGBA colorFore;
	styleContext_getForeColor(a_StyleContextLabel, &colorFore);

	const bool hasBackgroundImage = styleContext_hasBackgroundImage(a_StyleContextTooltip);

	GdkRGBA colorBackEstim;
	styleContext_estimateBackColor(a_StyleContextLabel, &colorBackEstim);

	GdkRGBA colorBackValue;
	styleContext_getBackColor(a_StyleContextTooltip, &colorBackValue);

	printf
	(
		"With %s:\n"
		"\tlabel   = %s\n"
		"\ttooltip = %s\n"
		"\t%s = Fore color (via gtk_style_context_get_color(label))\n"
		"\t%s = Back color (via gtk_render_background(label))\n"
		"\t%s = Back color (via gtk_style_context_get_background_color(tooltip))\n"
		"\tbackground-image=%c\n",
		a_Caption,
		dumpFore.c_str(),
		dumpBack.c_str(),
		format_GdkRGBA(colorFore).c_str(),
		format_GdkRGBA(colorBackEstim).c_str(),
		format_GdkRGBA(colorBackValue).c_str(),
		hasBackgroundImage ? 'Y' : 'N'
	);
}
Example #9
0
bool Player::loadFromFile( std::string path,SDL_Renderer *renderer)
{
	free();
	SDL_Texture* newTexture = NULL;
	SDL_Surface* loadedSurface = SDL_LoadBMP( path.c_str() );
	if( loadedSurface == NULL )
	{
		std::cout << "Unable to load image! SDL_image Error: " << path.c_str() << std::endl;
	}
	else
	{
		SDL_SetColorKey( loadedSurface, SDL_TRUE, SDL_MapRGB( loadedSurface->format, 255, 0, 210 ) );
		newTexture = SDL_CreateTextureFromSurface(renderer,loadedSurface);
		if( newTexture == NULL )
		{
			std::cout << "Unable to create texture from! SDL Error: " << path.c_str() << std::endl;
			std::cout << "Renderer " << getRenderer() << std::endl;
		}
		else
		{
			mWidth = loadedSurface->w;
			mHeight = loadedSurface->h;
		}
		SDL_FreeSurface(loadedSurface);
	}
	person = newTexture;
	return person != NULL;
}
Example #10
0
int UdpClient::writeData(const std::string &data) {
	if (!connected) {
		return -1;
	}
	write(sfd, data.c_str(), data.length());
	return 0 ;
}
Example #11
0
/*! This command sets the AFD and the widescreen data of the specified clip. */
int GvgAmpClient::SetAFDSetting(std::string filename,
                                int afd,
                                int widescreen)
{
   std::vector<unsigned char> response; //The full response structure from the server
   char strCommand[100];
   std::string hex_filename;

   stringToHexString(filename,hex_filename);
   sprintf(strCommand,"a23b%04x%02x%02x%04x%s",(unsigned int)filename.length()+4,
                                       (unsigned int)afd,
                                       (unsigned int)widescreen,
                                       (unsigned int)filename.length(),
                                       hex_filename.data());
   if(sendCommand(strCommand,response,0)==0) {
       //Received a valid response
       if(response[0]==0x10 && response[1]==0x01) {
           //ACK received
           return 0;
       } else {
           return -1;
       }
    } else { //Something was wrong, throw exception.
       throw SocketException("SetAFDSetting failed.");
       return -1;
    }
}
int mitk::SiemensDicomDiffusionImageHeaderReader::ExtractSiemensDiffusionInformation( std::string tagString, std::string nameString, std::vector<double>& valueArray, int startPos )
{
  std::string::size_type atPosition = tagString.find( nameString, startPos );
  if ( atPosition == std::string::npos)
  {
    return 0;
  }
  else
  {
    std::string infoAsString = tagString.substr( atPosition, tagString.size()-atPosition+1 );
    const char * infoAsCharPtr = infoAsString.c_str();

    int vm = *(infoAsCharPtr+64);

    int offset = 84;
    for (int k = 0; k < vm; k++)
    {
      int itemLength = *(infoAsCharPtr+offset+4);
      int strideSize = static_cast<int> (ceil(static_cast<double>(itemLength)/4) * 4);
      std::string valueString = infoAsString.substr( offset+16, itemLength );
      valueArray.push_back( atof(valueString.c_str()) );
      offset += 16+strideSize;
    }
    return vm;
  }
}
Example #13
0
int LibFile_INI::GetValueString(std::string &secName, std::string &varName, OUT std::string &valStr)
{
	u32 vecIndex;

	std::map<std::string,u32>::iterator secMapIt;

	secMapIt = mapSectionName.find(secName);
	if (secMapIt == mapSectionName.end()) {
		LibError_SetExtErrorMessage("Can't find section: %s\n", secName.c_str());
		return 1;
	}

	vecIndex = secMapIt->second;

	std::map<std::string,std::string>::iterator varMapIt;

	varMapIt = vecVarBlock[vecIndex].varMap.find(varName);
	if (varMapIt == vecVarBlock[vecIndex].varMap.end()) {
		LibError_SetExtErrorMessage("Can't find variable %s in section: %s\n", varName.c_str(), secName.c_str());
		return 2;
	}

	valStr = varMapIt->second;
	return 0;
}
void MetricsTransmitter::run()
{
    const auto & config = context.getConfigRef();
    auto interval = config.getInt(config_name + ".interval", 60);

    const std::string thread_name = "MericsTrns " + std::to_string(interval) + "s";
    setThreadName(thread_name.c_str());

    const auto get_next_time = [](size_t seconds)
    {
        /// To avoid time drift and transmit values exactly each interval:
        ///  next time aligned to system seconds
        /// (60s -> every minute at 00 seconds, 5s -> every minute:[00, 05, 15 ... 55]s, 3600 -> every hour:00:00
        return std::chrono::system_clock::time_point(
            (std::chrono::duration_cast<std::chrono::seconds>(std::chrono::system_clock::now().time_since_epoch()) / seconds) * seconds
            + std::chrono::seconds(seconds));
    };

    std::vector<ProfileEvents::Count> prev_counters(ProfileEvents::end());

    std::unique_lock lock{mutex};

    while (true)
    {
        if (cond.wait_until(lock, get_next_time(interval), [this] { return quit; }))
            break;

        transmit(prev_counters);
    }
}
Example #15
0
void class_tag::add_tag(const std::string &path, const class_tag &tag,
						class_tag &root){
	if ( path.empty() || path == "/" ){
		tag_map::iterator it = tags_.find(tag.name_);
		if (it == tags_.end()){
			tags_.insert(tag_map_value(tag.name_,tag));
		}else{
			it->second.set_min(tag.min_);
			it->second.set_max(tag.max_);
			it->second.add_tags(tag.tags_);
			it->second.add_keys(tag.keys_);
			it->second.add_links(tag.links_);
		}
		links_.erase (tag.get_name ());
		return ;
	}
	std::string::size_type pos = path.find('/');
	std::string name = path.substr(0,pos);
	std::string next_path = path.substr(pos+1,path.length());

	link_map::const_iterator it_links= links_.find(name);
	if (it_links != links_.end()){
		root.add_tag(it_links->second + "/" + next_path,tag,root);
	}
	tag_map::iterator it_tags = tags_.find(name);
	if (it_tags == tags_.end()){
		class_tag subtag;
		subtag.set_name(name);
		subtag.add_tag(next_path,tag,root);
		tags_.insert(tag_map_value(name,subtag));
		return;
	}
	it_tags->second.add_tag(next_path,tag,root);
}
Example #16
0
  void unpack(const uint8_t** pp, const uint8_t* pend) {
    const uint8_t* p = *pp;
    if(pend - p < 2)
      std::runtime_error("");

    service_type = get8(p);
    p += 1;
    size_t length = get8(p);
    p += 1;

    if(pend - p < length)
      std::runtime_error("");
    service_provider_name.assign(p, p+length);
    p += length;

    if(pend - p < 1)
      std::runtime_error("");
    length = get8(p);
    p += 1;

    if(pend - p < length)
      std::runtime_error("");
    service_name.assign(p, p+length);
    p += length;

    *pp = p;
  }
Example #17
0
SDL_Rect menu::style::item_size(const std::string& item) const {
	SDL_Rect res = {0,0,0,0};
	std::vector<std::string> img_text_items = utils::split(item, IMG_TEXT_SEPARATOR, utils::REMOVE_EMPTY);
	for (std::vector<std::string>::const_iterator it = img_text_items.begin();
		 it != img_text_items.end(); it++) {
		if (res.w > 0 || res.h > 0) {
			// Not the first item, add the spacing.
			res.w += 5;
		}
		const std::string str = *it;
		if (!str.empty() && str[0] == IMAGE_PREFIX) {
			const std::string image_name(str.begin()+1,str.end());
			surface const img = get_item_image(image_name);
			if(img != NULL) {
				res.w += img->w;
				res.h = std::max<int>(img->h, res.h);
			}
		} else {
			const SDL_Rect area = {0,0,10000,10000};
			const SDL_Rect font_size =
				font::draw_text(NULL,area,get_font_size(),font::NORMAL_COLOUR,str,0,0);
			res.w += font_size.w;
			res.h = std::max<int>(font_size.h, res.h);
		}
	}
	return res;
}
Example #18
0
std::string DataDirLocater::SubstEnvVars(const std::string& in) const
{
	bool escape = false;
	std::ostringstream out;
	for (std::string::const_iterator ch = in.begin(); ch != in.end(); ++ch) {
		if (escape) {
			escape = false;
			out << *ch;
		} else {
			switch (*ch) {
#ifndef _WIN32
				case '\\': {
					escape = true;
					break;
				}
#endif
				case '$': {
					std::ostringstream envvar;
					for (++ch; ch != in.end() && (isalnum(*ch) || *ch == '_'); ++ch)
						envvar << *ch;
					--ch;
					char* subst = getenv(envvar.str().c_str());
					if (subst && *subst)
						out << subst;
					break;
				}
				default: {
					out << *ch;
					break;
				}
			}
		}
	}
	return out.str();
}
Example #19
0
bool InspIRCd::IsValidMask(const std::string &mask)
{
	const char* dest = mask.c_str();
	int exclamation = 0;
	int atsign = 0;

	for (const char* i = dest; *i; i++)
	{
		/* out of range character, bad mask */
		if (*i < 32 || *i > 126)
		{
			return false;
		}

		switch (*i)
		{
			case '!':
				exclamation++;
				break;
			case '@':
				atsign++;
				break;
		}
	}

	/* valid masks only have 1 ! and @ */
	if (exclamation != 1 || atsign != 1)
		return false;

	if (mask.length() > 250)
		return false;

	return true;
}
Example #20
0
void MySQLConnection::PrepareStatement(uint32 index, std::string const& sql, ConnectionFlags flags)
{
    // Check if specified query should be prepared on this connection
    // i.e. don't prepare async statements on synchronous connections
    // to save memory that will not be used.
    if (!(m_connectionFlags & flags))
    {
        m_stmts[index].reset();
        return;
    }

    MYSQL_STMT* stmt = mysql_stmt_init(m_Mysql);
    if (!stmt)
    {
        TC_LOG_ERROR("sql.sql", "In mysql_stmt_init() id: %u, sql: \"%s\"", index, sql.c_str());
        TC_LOG_ERROR("sql.sql", "%s", mysql_error(m_Mysql));
        m_prepareError = true;
    }
    else
    {
        if (mysql_stmt_prepare(stmt, sql.c_str(), static_cast<unsigned long>(sql.size())))
        {
            TC_LOG_ERROR("sql.sql", "In mysql_stmt_prepare() id: %u, sql: \"%s\"", index, sql.c_str());
            TC_LOG_ERROR("sql.sql", "%s", mysql_stmt_error(stmt));
            mysql_stmt_close(stmt);
            m_prepareError = true;
        }
        else
            m_stmts[index] = Trinity::make_unique<MySQLPreparedStatement>(stmt, sql);
    }
}
Example #21
0
bool InspIRCd::ULine(const std::string& sserver)
{
	if (sserver.empty())
		return true;

	return (Config->ulines.find(sserver.c_str()) != Config->ulines.end());
}
Example #22
0
Desktop::Desktop(const Widget2 *const widget) :
    Container(widget),
    gcn::WidgetListener(),
    mWallpaper(nullptr),
    mVersionLabel(nullptr),
    mBackgroundColor(getThemeColor(Theme::BACKGROUND, 128)),
    mBackgroundGrayColor(getThemeColor(Theme::BACKGROUND_GRAY))
{
    addWidgetListener(this);

    Wallpaper::loadWallpapers();

    const std::string appName = branding.getValue("appName", std::string());
    if (appName.empty())
    {
        mVersionLabel = new Label(this, FULL_VERSION);
    }
    else
    {
        mVersionLabel = new Label(this, strprintf("%s (%s)", FULL_VERSION,
            appName.c_str()));
    }

    mVersionLabel->setBackgroundColor(getThemeColor(Theme::BACKGROUND, 128));
}
Example #23
0
void DrawText(ShaderProgram *program, int fontTexture, std::string text, float size, float spacing) {
	float texture_size = 1.0 / 16.0f;
	std::vector<float> vertexData;
	std::vector<float> texCoordData;
	for (int i = 0; i < text.size(); i++) {
		float texture_x = (float)(((int)text[i]) % 16) / 16.0f;
		float texture_y = (float)(((int)text[i]) / 16) / 16.0f;
		vertexData.insert(vertexData.end(), {
			((size + spacing) * i) + (-7.55f * size), 0.5f * size,
			((size + spacing) * i) + (-7.55f * size), -0.5f * size,
			((size + spacing) * i) + (-6.55f * size), 0.5f * size,
			((size + spacing) * i) + (-6.55f * size), -0.5f * size,
			((size + spacing) * i) + (-6.55f * size), 0.5f * size,
			((size + spacing) * i) + (-7.55f * size), -0.5f * size,
		});
		texCoordData.insert(texCoordData.end(), {
			texture_x, texture_y,
			texture_x, texture_y + texture_size,
			texture_x + texture_size, texture_y,
			texture_x + texture_size, texture_y + texture_size,
			texture_x + texture_size, texture_y,
			texture_x, texture_y + texture_size,
		});
	}
	glUseProgram(program->programID);
	glVertexAttribPointer(program->positionAttribute, 2, GL_FLOAT, false, 0, vertexData.data());
	glEnableVertexAttribArray(program->positionAttribute);
	glVertexAttribPointer(program->texCoordAttribute, 2, GL_FLOAT, false, 0, texCoordData.data());
	glEnableVertexAttribArray(program->texCoordAttribute);
	glBindTexture(GL_TEXTURE_2D, fontTexture);
	glDrawArrays(GL_TRIANGLES, 0, text.size() * 6);
	glDisableVertexAttribArray(program->positionAttribute);
	glDisableVertexAttribArray(program->texCoordAttribute);
}
Example #24
0
std::string PVRIptvData::ReadMarkerValue(std::string &strLine, const char* strMarkerName)
{
  int iMarkerStart = (int) strLine.find(strMarkerName);
  if (iMarkerStart >= 0)
  {
    std::string strMarker = strMarkerName;
    iMarkerStart += strMarker.length();
    if (iMarkerStart < (int)strLine.length())
    {
      char cFind = ' ';
      if (strLine[iMarkerStart] == '"')
      {
        cFind = '"';
        iMarkerStart++;
      }
      int iMarkerEnd = (int)strLine.find(cFind, iMarkerStart);
      if (iMarkerEnd < 0)
      {
        iMarkerEnd = strLine.length();
      }
      return strLine.substr(iMarkerStart, iMarkerEnd - iMarkerStart);
    }
  }

  return std::string("");
}
/// Extracts a numeric value from the SC's textual statistics for Vulkan.
/// Params:
///     fileContent: the content of the SC statistics file.
///     attributeToken: the attribute whose value is to be extracted.
//      numericValue: the extracted value.
// Returns: true for success, false otherwise.
static bool ExtractNumericStatistic(const std::string& fileContent, const char* attributeToken, size_t& extractedValue)
{
    bool ret = false;
    size_t valueBeginIndex = fileContent.find(attributeToken);

    if (valueBeginIndex != std::string::npos)
    {
        valueBeginIndex += strlen(attributeToken) + 1;

        if (valueBeginIndex < fileContent.size())
        {
            size_t valueEndIndex = fileContent.find(END_OF_LINE_DELIMITER, valueBeginIndex) - 1;

            if (valueEndIndex != std::string::npos)
            {
                size_t valueLength = valueEndIndex - valueBeginIndex + 1;

                if (valueLength > 0)
                {
                    // Extract the value.
                    std::string value = fileContent.substr(valueBeginIndex, valueLength);
                    std::string::iterator end_pos = std::remove_if(value.begin(),
                    value.end(), [&value](char c) { return (c == ' ' || !std::isdigit(c)); });
                    value.erase(end_pos, value.end());
                    extractedValue = std::stoi(value);
                    ret = true;
                }
            }
        }
    }

    return ret;
}
Example #26
0
void trim(std::string &s){ //Delete leading and trailing spaces of a string
	std::size_t len = s.size();
	if(len == 0){
		return;
	}
	std::size_t i = 0;
	while(i < len){
		if(s[i] != ' '){
			break;
		}
	}
	if(i == len){
		s = "";
		return;
	}
	s.erase(0, i); //Delete leading spaces
	len = s.size();

	std::size_t j = len - 1;
	while(j > i){
		if(s[j] != ' '){
			break;
		}
	}
	if(j != len - 1){
		s.erase(j + 1, len - j - 1); //Delete trailing spaces
	}
}
Example #27
0
void ImageBuffer::drawText(int imageX, int imageY, std::string text) {
    const char* str = text.c_str();

    for (unsigned int i = 0; i < text.size(); i++) {
        drawChar(imageX + i * 9, imageY, str[i]);
    }
}
Example #28
0
	std::vector<int> findSubstring(std::string S, std::vector<std::string> &L) {
		std::vector<int> result;
		std::map<std::string, int> needToFind;
		std::map<std::string, int> hasFound;
		int LLen = L.size();
		if(LLen == 0){
			return result;
		}
		for(int i = 0; i < LLen; ++i){
			++needToFind[L[i]];
		}

		int SLen = S.size();
		int wordLen = L[0].size();
		int count = 0;
		int start = -1;
		bool newTry = true;
		for(int i = 0; i < SLen; ){
			if(newTry && SLen - i < LLen * wordLen){
				break;
			}
			std::string cur = S.substr(i, wordLen);
			if(needToFind.find(cur) != needToFind.end()){
				newTry = false;
				if(count == 0){
					start = i;
				}
				++count;
				if((++hasFound[cur]) > needToFind[cur]){ //Not suitable, try next
					i = start + 1;
					count = 0;
					hasFound.clear();
					start = -1;
					newTry = true;
					continue;
				}
				if(count == LLen){ //Find a substring
					result.push_back(start);
					i = start + 1;
					newTry = true;
					count = 0;
					hasFound.clear();
					start = -1;
					continue;
				}
				i += wordLen;
			}else{
				if(start != -1){
					i = start + 1;
					start = -1;
				}else{
					++i;
				}
				newTry = true;
				count = 0;
				hasFound.clear();
			}
		}
		return result;
	}
Example #29
0
int main()
{
    std::cout << "/////////////////////////////////////////////////////////\n\n";
    std::cout << "\t\tAn employee parser for Spirit...\n\n";
    std::cout << "/////////////////////////////////////////////////////////\n\n";

    typedef std::string::iterator iterator_type;
    typedef test::record_parser<iterator_type, qi::space_type> record_parser;

    record_parser g; // Our grammar

	std::string s = "john";

    std::vector<test::record> emps;
    iterator_type iter = recs.begin();
    iterator_type end = recs.end();

    bool r = boost::spirit::qi::phrase_parse(iter, end, g(phx::ref(s)), qi::space, emps);

    if (r)
    {
        std::cout << "-------------------------\n";
        std::cout << "Parsing succeeded\n";
        std::cout << "got: " << emps.size() << " employees" << std::endl;
        std::cout << "\n-------------------------\n";
    }
    else
    {
        std::cout << "-------------------------\n";
        std::cout << "Parsing failed\n";
        std::cout << "-------------------------\n";
    }
    
    return 0;
}
Example #30
0
std::tuple<rct_string_id, rct_string_id, rct_string_id> LocalisationService::GetLocalisedScenarioStrings(const std::string& scenarioFilename) const
{
    auto result0 = _languageCurrent->GetScenarioOverrideStringId(scenarioFilename.c_str(), 0);
    auto result1 = _languageCurrent->GetScenarioOverrideStringId(scenarioFilename.c_str(), 1);
    auto result2 = _languageCurrent->GetScenarioOverrideStringId(scenarioFilename.c_str(), 2);
    return std::make_tuple(result0, result1, result2);
}