当前位置: 首页>>代码示例>>C++>>正文


C++ StringVector类代码示例

本文整理汇总了C++中StringVector的典型用法代码示例。如果您正苦于以下问题:C++ StringVector类的具体用法?C++ StringVector怎么用?C++ StringVector使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了StringVector类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。

示例1: if

void EditorFileList::AcceptMessage(const Message &message)
{
#ifdef ENGINE_TARGET_WIN32
	if (message.is("KeyPress"))
	{
		int data = utils::lexical_cast<int>(message.getData());
		char key = data;

		if (key == -VK_LEFT)
		{
			if (_cursorPos > 0)
			{
				_cursorPos--;
			}
			_cursorTime = 0.f;
		} else if (key == -VK_RIGHT)
		{
			if (_cursorPos < static_cast<int>(_fileName.length()))
			{
				_cursorPos++;
			}
			_cursorTime = 0.f;
		} else if (key == -VK_UP)
		{
			_cursorPos = static_cast<int>(_fileName.length());
			_cursorTime = 0.f;
		} else if (key == -VK_DOWN)
		{
			_cursorPos = 0;
			_cursorTime = 0.f;
		} else if (data > 0 && key > ' ' && _fileName.length() < 20)
		{
			_fileName.insert(static_cast<size_t>(_cursorPos), 1, key);
			_cursorPos++;
			_cursorTime = 0.f;
		} else if (key == 8)
		{
			if (_cursorPos > 0)
			{
				_cursorPos--;
				_fileName.erase(static_cast<size_t>(_cursorPos), 1);
			}
		}
	} else
#endif
	if (message.is("Init"))
	{
		_names.clear();
		StringVector vec = File::DirectoryListing::Get("Levels/*.*");
		size_t count = vec.size();
		_names.reserve(count);
		int fnd0;
		int fnd1;
		for(size_t i=0;i<count;i++){
			fnd0 = vec[i].find("/");
			fnd1 = vec[i].find(".xml");
			if( fnd0>0 && fnd1 > 0){
				_names.push_back( vec[i].substr(fnd0+1,fnd1-fnd0-1));
			}
		}
	/*} else if (message.is("SetDestLayer"))
	{
		_destLayer = message.getData();
	} else if (message.is("SetDestWidget"))
	{
		_destWidget = message.getData();*/
	} else if (message.is("SetLevelName"))
	{
		_fileName = message.getData();
		_cursorPos = (int) _fileName.length();
	} else if (message.is("AddItem"))
	{
		_names.push_back(message.getData());
	} else if (message.is("Load")){
		if (_currentName >= 0)
		{
			_fileName = _names[_currentName];
			_cursorPos = (int) _fileName.length();

			GUI::Widget *target = Core::guiManager.getLayer(_destLayer) -> getWidget(_destWidget);
			target -> AcceptMessage(Message("LoadLevelForEdit", _fileName));
			Core::messageManager.putMessage(Message("Return", "press"));
		}
	} else if (message.is("Save"))
	{
		bool f = false;
		for (size_t i = 0; i<_names.size(); i++)
		{
			if (_fileName == _names[i])
			{
				f = true;
			}
		}
		if (f)
		{
			Core::guiManager.getLayer("ConfirmRewriteLevel")->getWidget("ConfirmText")->
				AcceptMessage(Message("SetString", "Do you really want to rewrite " + _fileName + "?"));
			Core::messageManager.putMessage(Message("ShowConfirmRewrite"));
		} else {
			Core::guiManager.getLayer(_destLayer)->getWidget(_destWidget)->AcceptMessage(Message("SaveLevel", _fileName));
//.........这里部分代码省略.........
开发者ID:code4funnn,项目名称:4-Elements-Test,代码行数:101,代码来源:EditorFileList.cpp

示例2: DefaultRootWindow

	void X11EGLWindow::initNativeCreatedWindow(const NameValuePairList *miscParams)
	{
		if (miscParams)
		{
			NameValuePairList::const_iterator opt;
			NameValuePairList::const_iterator end = miscParams->end();

			mExternalWindow = 0;
			mNativeDisplay = mGLSupport->getNativeDisplay();
			mParentWindow = DefaultRootWindow((Display*)mNativeDisplay);

			if ((opt = miscParams->find("parentWindowHandle")) != end)
			{
				//vector<String>::type tokens = StringUtil::split(opt->second, " :");
		                StringVector tokens = StringUtil::split(opt->second, " :");

				if (tokens.size() == 3)
				{
					// deprecated display:screen:xid format
					mParentWindow = (Window)StringConverter::parseUnsignedLong(tokens[2]);
				}
				else
				{
					// xid format
					mParentWindow = (Window)StringConverter::parseUnsignedLong(tokens[0]);
				}
			}
			else if ((opt = miscParams->find("externalWindowHandle")) != end)
			{
				//vector<String>::type tokens = StringUtil::split(opt->second, " :");
		                StringVector tokens = StringUtil::split(opt->second, " :");

				LogManager::getSingleton().logMessage(
					"EGLWindow::create: The externalWindowHandle parameter is deprecated.\n"
					"Use the parentWindowHandle or currentGLContext parameter instead.");
				if (tokens.size() == 3)
				{
					// Old display:screen:xid format
					// The old EGL code always created a "parent" window in this case:
					mParentWindow = (Window)StringConverter::parseUnsignedLong(tokens[2]);
				}
				else if (tokens.size() == 4)
				{
					// Old display:screen:xid:visualinfo format
					mExternalWindow = (Window)StringConverter::parseUnsignedLong(tokens[2]);
				}
				else
				{
					// xid format
					mExternalWindow = (Window)StringConverter::parseUnsignedLong(tokens[0]);
				}
			}

		}

		// Ignore fatal XErrorEvents during parameter validation:
		oldXErrorHandler = XSetErrorHandler(safeXErrorHandler);

		// Validate parentWindowHandle
		if (mParentWindow != DefaultRootWindow((Display*)mNativeDisplay))
		{
			XWindowAttributes windowAttrib;

			if (!XGetWindowAttributes((Display*)mNativeDisplay, mParentWindow, &windowAttrib) ||
				windowAttrib.root != DefaultRootWindow((Display*)mNativeDisplay))
			{
				OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR,
					"Invalid parentWindowHandle (wrong server or screen)",
					"EGLWindow::create");
			}
		}

		// Validate externalWindowHandle
		if (mExternalWindow != 0)
		{
			XWindowAttributes windowAttrib;

			if (!XGetWindowAttributes((Display*)mNativeDisplay, mExternalWindow, &windowAttrib) ||
				windowAttrib.root != DefaultRootWindow((Display*)mNativeDisplay))
			{
				OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR,
					"Invalid externalWindowHandle (wrong server or screen)",
					"EGLWindow::create");
			}

			mEglConfig = 0;
			mEglSurface = createSurfaceFromWindow(mEglDisplay, (NativeWindowType)mExternalWindow);
		}

		XSetErrorHandler(oldXErrorHandler);

		mIsTopLevel = (!mIsExternal && mParentWindow == DefaultRootWindow((Display*)mNativeDisplay));

	}
开发者ID:Ali-il,项目名称:gamekit,代码行数:94,代码来源:OgreX11EGLWindow.cpp

示例3: oe_landcover_getBiomeIndex

osg::Shader*
LandCoverLayer::createPredicateShader(const Coverage* coverage) const
{
    const char* defaultCode = "int oe_landcover_getBiomeIndex(in vec4 coords) { return -1; }\n";

    std::stringstream buf;
    buf << "#version 330\n";
    
    osg::ref_ptr<ImageLayer> layer;

    if ( !coverage )
    {
        buf << defaultCode;
        OE_INFO << LC << "No coverage; generating default coverage predicate\n";
    }
    else if ( !coverage->getLegend() )
    {
        buf << defaultCode;
        OE_INFO << LC << "No legend; generating default coverage predicate\n";
    }
    else if ( !coverage->lockLayer(layer) )
    {
        buf << defaultCode;
        OE_INFO << LC << "No classification layer; generating default coverage predicate\n";
    }
    else
    {
        const std::string& sampler = layer->shareTexUniformName().get();
        const std::string& matrix  = layer->shareTexMatUniformName().get();

        buf << "uniform sampler2D " << sampler << ";\n"
            << "uniform mat4 " << matrix << ";\n"
            << "int oe_landcover_getBiomeIndex(in vec4 coords) { \n"
            << "    float value = textureLod(" << sampler << ", (" << matrix << " * coords).st, 0).r;\n";

        for(int biomeIndex=0; biomeIndex<getBiomes().size(); ++biomeIndex)
        {
            const LandCoverBiome* biome = getBiomes().at(biomeIndex).get();

            if ( !biome->getClasses().empty() )
            {
                StringVector classes;
                StringTokenizer(biome->getClasses(), classes, " ", "\"", false);

                for(int i=0; i<classes.size(); ++i)
                {
                    std::vector<const CoverageValuePredicate*> predicates;
                    if ( coverage->getLegend()->getPredicatesForClass(classes[i], predicates) )
                    {
                        for(std::vector<const CoverageValuePredicate*>::const_iterator p = predicates.begin();
                            p != predicates.end(); 
                            ++p)
                        {
                            const CoverageValuePredicate* predicate = *p;

                            if ( predicate->_exactValue.isSet() )
                            {
                                buf << "    if (value == " << predicate->_exactValue.get() << ") return " << biomeIndex << "; \n";
                            }
                            else if ( predicate->_minValue.isSet() && predicate->_maxValue.isSet() )
                            {
                                buf << "    if (value >= " << predicate->_minValue.get() << " && value <= " << predicate->_maxValue.get() << ") return " << biomeIndex << "; \n";
                            }
                            else if ( predicate->_minValue.isSet() )
                            {
                                buf << "    if (value >= " << predicate->_minValue.get() << ")  return " << biomeIndex << "; \n";
                            }
                            else if ( predicate->_maxValue.isSet() )
                            {
                                buf << "    if (value <= " << predicate->_maxValue.get() << ") return " << biomeIndex << "; \n";
                            }

                            else 
                            {
                                OE_WARN << LC << "Class \"" << classes[i] << "\" found, but no exact/min/max value was set in the legend\n";
                            }
                        }
                    }
                    else
                    {
                        OE_WARN << LC << "Class \"" << classes[i] << "\" not found in the legend!\n";
                    }
                }
            }
        }
        buf << "    return -1; \n";
        buf << "}\n";
    }
    
    osg::Shader* shader = new osg::Shader();
    shader->setName("oe Landcover predicate function");
    shader->setShaderSource( buf.str() );

    return shader;
}
开发者ID:jhasse,项目名称:osgearth,代码行数:95,代码来源:LandCover.cpp

示例4: parseCapabilitiesLines

    void RenderSystemCapabilitiesSerializer::parseCapabilitiesLines(CapabilitiesLinesList& lines)
    {
        StringVector tokens;

        for (CapabilitiesLinesList::iterator it = lines.begin(), end = lines.end(); it != end; ++it)
        {
            // restore the current line information for debugging
            mCurrentLine = &(it->first);
            mCurrentLineNumber = it->second;

            tokens = StringUtil::split(it->first);
            // check for incomplete lines
            if(tokens.size() < 2)
            {
                logParseError("No parameters given for the capability keyword");
                continue;
            }

            // the first token must the the keyword identifying the capability
            // the remaining tokens are the parameters
            String keyword = tokens[0];
            String everythingElse = "";
            for(unsigned int i = 1; i < tokens.size() - 1; i ++)
            {
                everythingElse = everythingElse + tokens[i] + " ";
            }
            everythingElse = everythingElse + tokens[tokens.size() - 1];

            CapabilityKeywordType keywordType = getKeywordType(keyword);

            switch(keywordType)
            {
                case UNDEFINED_CAPABILITY_TYPE:
                    logParseError("Unknown capability keyword: " + keyword);
                    break;
                case SET_STRING_METHOD:
                    callSetStringMethod(keyword, everythingElse);
                    break;
                case SET_INT_METHOD:
                {
                    ushort integer = (ushort)StringConverter::parseInt(tokens[1]);
                    callSetIntMethod(keyword, integer);
                    break;
                }
                case SET_BOOL_METHOD:
                {
                    bool b = StringConverter::parseBool(tokens[1]);
                    callSetBoolMethod(keyword, b);
                    break;
                }
                case SET_REAL_METHOD:
                {
                    Real real = StringConverter::parseReal(tokens[1]);
                    callSetRealMethod(keyword, real);
                    break;
                }
                case ADD_SHADER_PROFILE_STRING:
                {
                    addShaderProfile(tokens[1]);
                    break;
                }
                case SET_CAPABILITY_ENUM_BOOL:
                {
                    bool b = StringConverter::parseBool(tokens[1]);
                    setCapabilityEnumBool(tokens[0], b);
                    break;
                }
            }
        }
    }
开发者ID:danyr,项目名称:gamekit,代码行数:70,代码来源:OgreRenderSystemCapabilitiesSerializer.cpp

示例5: atoi

void Logger::initialise( const std::string &id, const Options &options )
{
    char *envPtr;

    if ( !id.empty() )
        this->id( id );

    std::string tempLogFile;
    if ( options.mLogPath.size() )
    {
        mLogPath = options.mLogPath;
        tempLogFile = mLogPath+"/"+mId+".log";
    }
    if ( options.mLogFile.size() )
        tempLogFile = options.mLogFile;
    else
        tempLogFile = mLogPath+"/"+mId+".log";
    if ( (envPtr = getTargettedEnv( "LOG_FILE" )) )
        tempLogFile = envPtr;

    Level tempLevel = INFO;
    Level tempTermLevel = mTermLevel;
    Level tempDatabaseLevel = mDatabaseLevel;
    Level tempFileLevel = mFileLevel;
    Level tempSyslogLevel = mSyslogLevel;

    if ( options.mTermLevel != NOOPT )
        tempTermLevel = options.mTermLevel;
    if ( options.mDatabaseLevel != NOOPT )
        tempDatabaseLevel = options.mDatabaseLevel;
    else
        tempDatabaseLevel = config.log_level_database >= DEBUG1 ? DEBUG9 : config.log_level_database;
    if ( options.mFileLevel != NOOPT )
        tempFileLevel = options.mFileLevel;
    else
        tempFileLevel = config.log_level_file >= DEBUG1 ? DEBUG9 : config.log_level_file;
    if ( options.mSyslogLevel != NOOPT )
        tempSyslogLevel = options.mSyslogLevel;
    else
        tempSyslogLevel = config.log_level_syslog >= DEBUG1 ? DEBUG9 : config.log_level_syslog;

    // Legacy
    if ( (envPtr = getenv( "LOG_PRINT" )) )
        tempTermLevel = atoi(envPtr) ? DEBUG9 : NOLOG;

    if ( (envPtr = getTargettedEnv( "LOG_LEVEL" )) )
        tempLevel = atoi(envPtr);

    if ( (envPtr = getTargettedEnv( "LOG_LEVEL_TERM" )) )
        tempTermLevel = atoi(envPtr);
    if ( (envPtr = getTargettedEnv( "LOG_LEVEL_DATABASE" )) )
        tempDatabaseLevel = atoi(envPtr);
    if ( (envPtr = getTargettedEnv( "LOG_LEVEL_FILE" )) )
        tempFileLevel = atoi(envPtr);
    if ( (envPtr = getTargettedEnv( "LOG_LEVEL_SYSLOG" )) )
        tempSyslogLevel = atoi(envPtr);

    if ( config.log_debug )
    {
        StringVector targets = split( config.log_debug_target, "|" );
        for ( int i = 0; i < targets.size(); i++ )
        {
            const std::string &target = targets[i];
            if ( target == mId || target == "_"+mId || target == "_"+mIdRoot || target == "_"+mIdRoot || target == "" )
            {
                if ( config.log_debug_level > NOLOG )
                {
                    tempLevel = config.log_debug_level;
                    if ( config.log_debug_file[0] )
                    {
                        tempLogFile = config.log_debug_file;
                        tempFileLevel = tempLevel;
                    }
                }
            }
        }
    }

    logFile( tempLogFile );

    termLevel( tempTermLevel );
    databaseLevel( tempDatabaseLevel );
    fileLevel( tempFileLevel );
    syslogLevel( tempSyslogLevel );

    level( tempLevel );

    mFlush = (envPtr = getenv( "LOG_FLUSH")) ? atoi( envPtr ) : false;

    //mRuntime = (envPtr = getenv( "LOG_RUNTIME")) ? atoi( envPtr ) : false;

    {
        struct sigaction action;
        memset( &action, 0, sizeof(action) );
        action.sa_handler = usrHandler;
        action.sa_flags = SA_RESTART;

        if ( sigaction( SIGUSR1, &action, 0 ) < 0 )
        {
            Fatal( "sigaction(), error = %s", strerror(errno) );
//.........这里部分代码省略.........
开发者ID:vttay03,项目名称:slack14-zm,代码行数:101,代码来源:zm_logger.cpp

示例6: sbBuffer

//----------------------------------------------------------------------------------------------------------------
void CConfiguration::LoadItemClasses()
{
    good::string_buffer sbBuffer(szMainBuffer, iMainBufferSize, false);
    sbBuffer = CMod::sModName;

    // Load health /armor / object entity classes.
    for ( TItemType iType = 0; iType < EItemTypeTotal; ++iType )
    {
        // TODO: shouldn't load weapons/ammo.
        // Get mod item section, i.e. [HalfLife2Deathmatch.items.health].
        sbBuffer.erase( CMod::sModName.size() );
        sbBuffer << ".items.";
        sbBuffer <<  CTypeToString::EntityTypeToString(iType);

        good::ini_file::const_iterator it = m_iniFile.find( sbBuffer );
        if ( it == m_iniFile.end() )
            continue;

        // Iterate throught key values.
        for ( good::ini_section::const_iterator itemIt = it->begin(); itemIt != it->end(); ++itemIt )
        {
            // String instances will live until plugin is unloaded.
            CItemClass cEntityClass;
            cEntityClass.sClassName.assign( itemIt->key.c_str(), itemIt->key.size() );

            // Get item flags.
            StringVector aArguments;
            good::split(itemIt->value, aArguments, ',', true);
            for ( int i=0; i < aArguments.size(); ++i )
            {
                StringVector aCurrent;
                good::split<good::vector>(aArguments[i], aCurrent);

                int iFlag = CTypeToString::EntityClassFlagsFromString(aCurrent[0]);

                if ( iFlag == -1 )
                {
                    BLOG_E( "File \"%s\", section [%s]:", m_iniFile.name.c_str(), it->name.c_str() );
                    BLOG_E( "  Invalid entity flag %s for %s.",  aArguments[i].c_str(), itemIt->key.c_str());
                }
                else
                {
                    FLAG_SET(iFlag, cEntityClass.iFlags);
                    /*if ( iFlag == FEntityRespawnable ) // Check respawn time.
                    {
                        if ( aCurrent.size() == 2 )
                        {
                            int iValue = -1;
                            sscanf(aCurrent[1].c_str(), "%d", &iValue);
                            if ( iValue > 0 )
                                SET_2ND_WORD(iValue, cEntityClass.iFlags);
                            else
                                BLOG_E("File \"%s\", section [%s], invalid respawn time for: %s.",  m_iniFile.name.c_str(), it->name.c_str(), itemIt->key.c_str());
                        }
                        else if ( aCurrent.size() > 2 )
                            BLOG_E("File \"%s\", section [%s], invalid arguments count for: %s.",  m_iniFile.name.c_str(), it->name.c_str(), itemIt->key.c_str());
                    }*/
                }
            }

            CItems::AddItemClassFor( iType, cEntityClass );
        }
    }

    // Load object models.
    sbBuffer = CMod::sModName;
    sbBuffer << ".items.object.models";
    good::ini_file::const_iterator it = m_iniFile.find( sbBuffer );
    if ( it != m_iniFile.end() )
    {
        // Iterate throught key values.
        for ( good::ini_section::const_iterator itemIt = it->begin(); itemIt != it->end(); ++itemIt )
        {
            int iValue = CTypeToString::EntityClassFlagsFromString(itemIt->value);
            if ( iValue > 0 )
                CItems::SetObjectFlagForModel(iValue, itemIt->key);
            else
            {
                BLOG_E( "File \"%s\", section [%s]:", m_iniFile.name.c_str(), it->name.c_str() );
                BLOG_E( "  Invalid object model flag: %s.", itemIt->value.c_str() );
                BLOG_E( "  Can be one of: %s", CTypeToString::EntityClassFlagsToString(FEntityAll).c_str() );
            }
        }
    }
}
开发者ID:borzh,项目名称:botrix,代码行数:86,代码来源:config.cpp

示例7: extractHaplotypeReads

// Extract reads from an FM-index that have a k-mer match to any given haplotypes
// Returns true if the reads were successfully extracted, false if there are 
// more reads than maxReads
bool HapgenUtil::extractHaplotypeReads(const StringVector& haplotypes, 
                                       const BWTIndexSet& indices,
                                       int k,
                                       bool doReverse,
                                       size_t maxReads,
                                       int64_t maxIntervalSize,
                                       SeqRecordVector* pOutReads, 
                                       SeqRecordVector* pOutMates)
{
    PROFILE_FUNC("HapgenUtil::extractHaplotypeReads")
    // Extract the set of reads that have at least one kmer shared with these haplotypes
    // This is a bit of a lengthy procedure with a few steps:
    // 1) extract all the kmers in the haplotypes
    // 2) find the intervals for the kmers in the fm-index
    // 3) compute the set of read indices of the reads from the intervals (using the sampled suffix array)
    // 4) finally, extract the read sequences from the index
    // Make a set of kmers from the haplotypes
    std::set<std::string> kmerSet;
    for(size_t i = 0; i < haplotypes.size(); ++i)
    {
        const std::string& h = haplotypes[i];
        if((int)h.size() < k)
            continue;

        for(size_t j = 0; j < h.size() - k + 1; ++j)
        {
            std::string ks = h.substr(j, k);
            if(doReverse)
                ks = reverseComplement(ks);
            kmerSet.insert(ks);
        }
    }

    // Compute suffix array intervals for the kmers
    std::vector<BWTInterval> intervals;
    for(std::set<std::string>::const_iterator iter = kmerSet.begin(); iter != kmerSet.end(); ++iter)
    {
        BWTInterval interval = BWTAlgorithms::findInterval(indices, *iter);
        if(interval.size() < maxIntervalSize)
            intervals.push_back(interval);
    }

    // Compute the set of reads ids 
    std::set<int64_t> readIndices;
    for(size_t i = 0; i < intervals.size(); ++i)
    {
        BWTInterval interval = intervals[i];
        for(int64_t j = interval.lower; j <= interval.upper; ++j)
        {
            // Get index from sampled suffix array
            SAElem elem = indices.pSSA->calcSA(j, indices.pBWT);
            readIndices.insert(elem.getID());
        }
    }

    // Check if we have hit the limit of extracting too many reads
    if(readIndices.size() > maxReads)
        return false;

    for(std::set<int64_t>::const_iterator iter = readIndices.begin(); iter != readIndices.end(); ++iter)
    {
        int64_t idx = *iter;
        
        // Extract the read
        std::stringstream namer;
        namer << "idx-" << idx;
        SeqRecord record;
        record.id = namer.str();
        record.seq = BWTAlgorithms::extractString(indices.pBWT, idx);

        assert(indices.pQualityTable != NULL);
        record.qual = indices.pQualityTable->getQualityString(idx, record.seq.length());
        if(!record.seq.empty())
            pOutReads->push_back(record);

        // Optionally extract its mate
        // If the index is constructed properly, 
        // paired reads are in adjacent indices with the
        // first read at even indices
        if(pOutMates != NULL)
        {
            int64_t mateIdx = idx;
            if(idx % 2 == 0)
                mateIdx += 1;
            else
                mateIdx -= 1;
            
            std::stringstream mateName;
            mateName << "idx-" << mateIdx;
            SeqRecord mateRecord;
            mateRecord.id = mateName.str();
            mateRecord.seq = BWTAlgorithms::extractString(indices.pBWT, mateIdx);
            mateRecord.qual = indices.pQualityTable->getQualityString(mateIdx, mateRecord.seq.length());
            if(!record.seq.empty() && !mateRecord.seq.empty())
                pOutMates->push_back(mateRecord);
        }
    }
//.........这里部分代码省略.........
开发者ID:SherlockThang,项目名称:sga,代码行数:101,代码来源:HapgenUtil.cpp

示例8: trim

void
StringTokenizer::tokenize( const std::string& input, StringVector& output ) const
{
    output.clear();

    std::stringstream buf;
    bool quoted = false;
    for( std::string::const_iterator i = input.begin(); i != input.end(); ++i )
    {
        char c = *i;    

        TokenMap::const_iterator q = _quotes.find( c );

        if ( quoted )
        {
            if ( q != _quotes.end() )
            {
                quoted = false;
                if ( q->second )
                    buf << c;
            }
            else
            {
                buf << c;
            }
        }
        else
        {
            if ( q != _quotes.end() )
            {
                quoted = true;
                if ( q->second )
                    buf << c;
            }
            else
            {
                TokenMap::const_iterator d = _delims.find( c );
                if ( d == _delims.end() )
                {
                    buf << c;
                }
                else
                {
                    std::string token = _trimTokens ? trim(buf.str()) : buf.str();

                    if ( _allowEmpties || !token.empty() )
                        output.push_back( token );

                    if ( d->second == true )
                    {
                        output.push_back( std::string(1, c) );
                    }

                    buf.str("");
                }
            }
        }       
    }

    std::string last = _trimTokens ? trim(buf.str()) : buf.str();
    if ( !last.empty() )
        output.push_back( last );
}
开发者ID:dgraves,项目名称:osgearth,代码行数:63,代码来源:StringUtils.cpp

示例9: main

int main (int argc, const char** argv)
{
	if (argc < 2)
	{
		printf ("USAGE: hlsl2glsltest testfolder\n");
		return 1;
	}

	bool hasOpenGL = InitializeOpenGL ();
	
	clock_t time0 = clock();
	
	Hlsl2Glsl_Initialize ();

	std::string baseFolder = argv[1];

	static const char* kTypeName[2] = { "vertex", "fragment" };
	size_t tests = 0;
	size_t errors = 0;
	for (int type = 0; type < 2; ++type)
	{
		printf ("testing %s...\n", kTypeName[type]);
		std::string testFolder = baseFolder + "/" + kTypeName[type];
		StringVector inputFiles = GetFiles (testFolder, "-in.txt");

		size_t n = inputFiles.size();
		tests += n;
		for (size_t i = 0; i < n; ++i)
		{
			std::string inname = inputFiles[i];
			printf ("test %s\n", inname.c_str());
			std::string outname = inname.substr (0,inname.size()-7) + "-out.txt";
			std::string outnameES = inname.substr (0,inname.size()-7) + "-outES.txt";
			bool ok = TestFile (type==0,
				testFolder + "/" + inname,
				testFolder + "/" + outname,
				false,
				hasOpenGL);
			if (ok)
			{
				ok = TestFile (type==0,
					testFolder + "/" + inname,
					testFolder + "/" + outnameES,
					true,
					false);
			}
			if (!ok)
			{
				++errors;
			}
		}
	}
	clock_t time1 = clock();
	float t = float(time1-time0) / float(CLOCKS_PER_SEC);
	if (errors != 0)
		printf ("%i tests, %i FAILED, %.2fs\n", tests, errors, t);
	else
		printf ("%i tests succeeded, %.2fs\n", tests, t);

	return errors ? 1 : 0;
}
开发者ID:CRivlaldo,项目名称:hlsl2glslfork,代码行数:61,代码来源:hlsl2glsltest.cpp

示例10: ext_dir

bool Materials::loadExtensions(FileName directoryName, wxString& error, wxArrayString& warnings)
{
	directoryName.Mkdir(0755, wxPATH_MKDIR_FULL); // Create if it doesn't exist

	wxDir ext_dir(directoryName.GetPath());
	if(ext_dir.IsOpened() == false)
	{
		error = wxT("Could not open extensions directory.");
		return false;
	}

	wxString filename;
	if(!ext_dir.GetFirst(&filename))
	{
		// No extensions found
		return true;
	}

	do
	{
		FileName fn;
		fn.SetPath(directoryName.GetPath());
		fn.SetFullName(filename);
		if(fn.GetExt() != wxT("xml"))
			continue;

		xmlDocPtr doc = xmlParseFile(fn.GetFullPath().mb_str());

		if(doc)
		{
			xmlNodePtr root = xmlDocGetRootElement(doc);
			
			if(xmlStrcmp(root->name,(const xmlChar*)"materialsextension") != 0){
				xmlFreeDoc(doc);
				warnings.push_back(filename + wxT(": Invalid rootheader."));
				continue;
			}
			std::string ext_name, ext_url, ext_author, ext_author_link, ext_desc, ext_client_str;
			StringVector clientVersions;
			if(
				!readXMLValue(root, "name", ext_name) ||
				!readXMLValue(root, "author", ext_author) ||
				!readXMLValue(root, "description", ext_desc))
			{
				warnings.push_back(filename + wxT(": Couldn't read extension attributes (name, author, description)."));
				continue;
			}


			readXMLValue(root, "url", ext_url);
			ext_url.erase(std::remove(ext_url.begin(), ext_url.end(), '\''), ext_url.end());
			readXMLValue(root, "authorurl", ext_author_link);
			ext_author_link.erase(std::remove(ext_author_link.begin(), ext_author_link.end(), '\''), ext_author_link.end());

			MaterialsExtension* me = newd MaterialsExtension(ext_name, ext_author, ext_desc);
			me->url = ext_url;
			me->author_url = ext_author_link;

			if(readXMLValue(root, "client", ext_client_str))
			{
				size_t last_pos = std::numeric_limits<size_t>::max();
				size_t pos;
				do
				{
					size_t to_pos = (last_pos == std::numeric_limits<size_t>::max()? 0 : last_pos+1);
					pos = ext_client_str.find(';', to_pos);
					if(size_t(pos) != std::string::npos)
					{
						clientVersions.push_back(ext_client_str.substr(to_pos, pos-(to_pos)));
						last_pos = pos;
					}
					else
					{
						clientVersions.push_back(ext_client_str.substr(to_pos));
						break;
					}
				} while(true);

				for(StringVector::iterator iter = clientVersions.begin();
						iter != clientVersions.end();
						++iter)
				{
					me->addVersion(*iter);
				}

				std::sort(me->version_list.begin(), me->version_list.end(), VersionComparisonPredicate);
				me->version_list.erase(std::unique(me->version_list.begin(), me->version_list.end()), me->version_list.end());
			}
			else
			{
				warnings.push_back(filename + wxT(": Extension is not available for any version."));
			}
			extensions.push_back(me);
			
			if(me->isForVersion(gui.GetCurrentVersionID()))
			{
				unserializeMaterials(filename, root, error, warnings);
			}
		}
		else
//.........这里部分代码省略.........
开发者ID:mattyx14,项目名称:rme,代码行数:101,代码来源:materials.cpp

示例11: main

int main (int argc, const char** argv)
{
	if (argc < 2)
	{
		printf ("USAGE: glsloptimizer testfolder\n");
		return 1;
	}

	bool hasOpenGL = InitializeOpenGL ();
	glslopt_ctx* ctx[2] = {
		glslopt_initialize(true),
		glslopt_initialize(false),
	};

	std::string baseFolder = argv[1];

	clock_t time0 = clock();

	static const char* kTypeName[2] = { "vertex", "fragment" };
	size_t tests = 0;
	size_t errors = 0;
	for (int type = 0; type < 2; ++type)
	{
		std::string testFolder = baseFolder + "/" + kTypeName[type];

		static const char* kAPIName[2] = { "OpenGL ES 2.0", "OpenGL" };
		static const char* kApiIn [2] = {"-inES.txt", "-in.txt"};
		static const char* kApiIR [2] = {"-irES.txt", "-ir.txt"};
		static const char* kApiOut[2] = {"-outES.txt", "-out.txt"};
		for (int api = 0; api < 2; ++api)
		{
			printf ("\n** running %s tests for %s...\n", kTypeName[type], kAPIName[api]);
			StringVector inputFiles = GetFiles (testFolder, kApiIn[api]);

			size_t n = inputFiles.size();
			for (size_t i = 0; i < n; ++i)
			{
				std::string inname = inputFiles[i];
				//if (inname != "ast-in.txt")
				//	continue;
				std::string hirname = inname.substr (0,inname.size()-strlen(kApiIn[api])) + kApiIR[api];
				std::string outname = inname.substr (0,inname.size()-strlen(kApiIn[api])) + kApiOut[api];
				bool ok = TestFile (ctx[api], type==0, inname, testFolder + "/" + inname, testFolder + "/" + hirname, testFolder + "/" + outname, api==0, hasOpenGL);
				if (!ok)
				{
					++errors;
				}
				++tests;
			}
		}
	}
	clock_t time1 = clock();
	float timeDelta = float(time1-time0)/CLOCKS_PER_SEC;

	if (errors != 0)
		printf ("\n**** %i tests (%.2fsec), %i !!!FAILED!!!\n", tests, timeDelta, errors);
	else
		printf ("\n**** %i tests (%.2fsec) succeeded\n", tests, timeDelta);
	
	// 3.25s
	// with builtin call linking, 3.84s

	for (int i = 0; i < 2; ++i)
		glslopt_cleanup (ctx[i]);

	return errors ? 1 : 0;
}
开发者ID:anchsm,项目名称:glsl-optimizer,代码行数:67,代码来源:glsl_optimizer_tests.cpp

示例12: readCellNucleusFile

bool NucleusGridFunction::
readCellNucleusFile( const std::string cn_filename,
			    const std::string gridFileName/* = ""*/ )
{
  bool okFlag=false;
  clearGrid2NucleusMap();
  clearNucleus2GridMap();

  FILE *fp=fopen( cn_filename.c_str(),"r");
  if( !fp ) {
    okFlag=false;
    return( okFlag );
  }
  DPrintf(DebugSolver,"reading file '%s'...\n",cn_filename.c_str());
  DPrintf(DebugSolver,"------------------------------\n");
  
  const int bufferLength=1000;
  char buffer[bufferLength];
  
  while( fgets( buffer, bufferLength, fp)) {
    const int lineLength=strlen(buffer);

    typedef std::vector<std::string> StringVector;
    StringVector tokens;

    if( lineLength>0 ) { 
      if( buffer[0]=='#' ) {
	buffer[lineLength-1]=0;
	DPrintf(DebugSolver,"comment< %s >\n", buffer);
      }
      else {
	using namespace std;
	Nucleus thisNuc;
	buffer[lineLength-1]=0;
	//printf("regular< %s >\n", buffer);
	string line(buffer);
	//cout << "<"<<line<<">\n";

	typedef boost::tokenizer<>::iterator           TokIterator;
	typedef boost::char_delimiters_separator<char> TokSeparator;
	//see boost::tokenizer 'char_delimiters_separator' docs
	//  sep( returnable=false, returned="", separators=0)
	// --> separators=0 means anything for which iswhitespace() 
	//     is true is a separator
	TokSeparator sep(false,"",0);
	boost::tokenizer< TokSeparator> tok(line, sep);
	for (TokIterator it=tok.begin(); it!=tok.end(); ++it) {
	  //DPrintf(DebugSolver,"<%s> ", it->c_str());
	  tokens.push_back( *it );
	}
	//..INPUT FILE FORMAT FOR .cwn
	// format: <nucleus #> <radius> <x y z of center> <grid ID(s)>
	// lines with '#' in column 1 are comments
	int nID;      const int idIndex=0; 
	double rad;   const int idRadius=1;
	double x,y,z; const int idX=2, idY=3, idZ=4;
	//std::vector<int> gridIDs;

	sscanf(tokens[idIndex].c_str(),  "%d",   &nID);
	sscanf(tokens[idRadius].c_str(), "%lg",  &rad);
	sscanf(tokens[idX].c_str(),      "%lg",  &x);
	sscanf(tokens[idY].c_str(),      "%lg",  &y);
	sscanf(tokens[idZ].c_str(),      "%lg",  &z);
	DPrintf(DebugSolver,"  #tokens=%d, ztoken=%s -- ", 
	       tokens.size(), tokens[idZ].c_str());

	DPrintf(DebugSolver,"id=%d, R=%f, x=%f, y=%f, z=%f,",nID,rad,x,y,z);
	DPrintf(DebugSolver,"\n");
	thisNuc.setID( nID);
	thisNuc.setCenter(x,y,z);
	thisNuc.setRadius(rad);
	
	Nucleus::NucleusShape nucleusShape=Nucleus::SphericalNucleus;
	thisNuc.setShape( nucleusShape );
	thisNuc.setBoundaryThickness( nucleusBoundaryThickness );

	nucleus.push_back( thisNuc );

	DPrintf(DebugSolver,"gridIDs for nucleus # %d=",nID);
	for( int i=idZ+1; i<tokens.size(); ++i ) {
	  int gID=-1;
	  sscanf(tokens[i].c_str(), "%d", &gID);
	  DPrintf(DebugSolver," %d ",gID);
	  grid2NucleusMap.insert( std::make_pair(gID,nID));
	  nucleus2GridMap.insert( std::make_pair(nID,gID));
	}		 
	DPrintf(DebugSolver,"\n");
      }
    };

  }
  DPrintf(DebugSolver,"-------------done-------------\n");
  fclose(fp);
  okFlag=true;

  return( okFlag ); 
  
  
}
开发者ID:petrifast,项目名称:pde-solvers,代码行数:99,代码来源:NucleusGridFunction.C

示例13: RemoveOldForecast

	//****************************************************************************************************
	ERMsg CEnvCanGribForecast::Execute(CCallback& callback)
	{
		ERMsg msg;
		//string outputPath = GetDir(WORKING_DIR);

		callback.AddMessage(GetString(IDS_UPDATE_DIR));
		callback.AddMessage(m_workingDir, 1);
		callback.AddMessage(GetString(IDS_UPDATE_FROM));
		callback.AddMessage(SERVER_NAME, 1);
		callback.AddMessage("");

		//delete old files
		msg = RemoveOldForecast(callback);
		if (!msg)
			return msg;



		CInternetSessionPtr pSession;
		CHttpConnectionPtr pConnection;


		msg = GetHttpConnection(SERVER_NAME, pConnection, pSession);
		if (!msg)
			return msg;
		

		//size_t type = as<size_t>(TYPE);
		size_t delta_h = m_type == GT_HRDPS ? 1 : 3;
		callback.PushTask("Download gribs list", (MAX_FORECAST_HOURS / delta_h) );


		StringVector fileList;
		//for (size_t HH = 0; HH < 24 && msg; HH+=6)
		size_t HH = GetLatestHH(pConnection);
		if (HH!=NOT_INIT)
		{
			for (size_t hhh = 0; hhh <= MAX_FORECAST_HOURS && msg; hhh += delta_h)
			{
				string remotePath = CEnvCanGribForecast::GetRemoteFilePath(HH, hhh, "*.grib2");

				CFileInfoVector fileListTmp;
				msg = FindFiles(pConnection, remotePath, fileListTmp);

				//keep only some variables
				for (CFileInfoVector::iterator it = fileListTmp.begin(); it != fileListTmp.end(); it++)
				{
					string fileName = GetFileName(it->m_filePath);
					size_t hhh = Gethhh(fileName);
					size_t vv = GetVariable(fileName);
					if (hhh <= 48 && vv != NOT_INIT)
						fileList.push_back(it->m_filePath);
				}

				msg += callback.StepIt();
			}
		}
		
		callback.PopTask();


		callback.AddMessage("Number of gribs to download: " + ToString(fileList.size()));
		callback.PushTask("Download gribs (" + ToString(fileList.size()) +")", fileList.size());

		int nbDownload = 0;
		for (size_t i = 0; i < fileList.size() && msg; i++)
		{
			string outputFilePath = GetOutputFilePath(GetFileName(fileList[i]));

			CreateMultipleDir(GetPath(outputFilePath));
			msg = CopyFile(pConnection, fileList[i], outputFilePath.c_str(), INTERNET_FLAG_TRANSFER_BINARY | INTERNET_FLAG_RELOAD | INTERNET_FLAG_EXISTING_CONNECT | INTERNET_FLAG_DONT_CACHE);
			if (msg)
				nbDownload++;

			msg += callback.StepIt();
		}

		pConnection->Close();
		pSession->Close();


		callback.AddMessage("Number of gribs downloaded: " + ToString(nbDownload));
		callback.PopTask();


		return msg;
	}
开发者ID:RNCan,项目名称:WeatherBasedSimulationFramework,代码行数:88,代码来源:EnvCanGribForecast.cpp

示例14: logBadAttrib


//.........这里部分代码省略.........
            if (params.size() != 2)
            {
                logBadAttrib(line, pFont);
                return;
            }
            // Set
            pFont->setSource(params[1]);
        }
        else if (attrib == "glyph")
        {
            // Check params
            if (params.size() != 6)
            {
                logBadAttrib(line, pFont);
                return;
            }
            // Set
			// Support numeric and character glyph specification
			Font::CodePoint cp;
			if (params[1].at(0) == 'u' && params[1].size() > 1)
			{
				// Unicode glyph spec
				String trimmed = params[1].substr(1);
				cp = StringConverter::parseUnsignedInt(trimmed);
			}
			else
			{
				// Direct character
				cp = params[1].at(0);
			}
            pFont->setGlyphTexCoords(
                cp, 
                StringConverter::parseReal(params[2]),
                StringConverter::parseReal(params[3]),
                StringConverter::parseReal(params[4]),
                StringConverter::parseReal(params[5]), 1.0 ); // assume image is square
        }
        else if (attrib == "size")
        {
            // Check params
            if (params.size() != 2)
            {
                logBadAttrib(line, pFont);
                return;
            }
            // Set
            pFont->setTrueTypeSize(
                StringConverter::parseReal(params[1]));
        }
        else if (attrib == "character_spacer")
        {
            // Check params
            if (params.size() != 2)
            {
                logBadAttrib(line, pFont);
                return;
            }
            // Set
            pFont->setCharacterSpacer(
                StringConverter::parseUnsignedInt(params[1]));
        }
        else if (attrib == "resolution")
        {
            // Check params
            if (params.size() != 2)
            {
                logBadAttrib(line, pFont);
                return;
            }
            // Set
            pFont->setTrueTypeResolution(
                (uint)StringConverter::parseReal(params[1]) );
        }
        else if (attrib == "antialias_colour")
        {
        	// Check params
        	if (params.size() != 2)
        	{
                logBadAttrib(line, pFont);
                return;
        	}
        	// Set
            pFont->setAntialiasColour(StringConverter::parseBool(params[1]));
        }
		else if (attrib == "code_points")
		{
			for (size_t c = 1; c < params.size(); ++c)
			{
				String& item = params[c];
				StringVector itemVec = StringUtil::split(item, "-");
				if (itemVec.size() == 2)
				{
					pFont->addCodePointRange(Font::CodePointRange(
						StringConverter::parseLong(itemVec[0]), 
						StringConverter::parseLong(itemVec[1])));
				}
			}
		}

    }
开发者ID:cartesio88,项目名称:Aura_libs,代码行数:101,代码来源:OgreFontManager.cpp

示例15: lines

/*!
* Extracts and stores logical lines of code.
* Determines and extract logical SLOC to place in the result variable
* using addSLOC function. Each time the addSLOC function is called,
* a new logical SLOC is added. This function assumes that the directive
* is handled before it is called.
*
* \param result counter results
* \param line processed physical line of code
* \param lineBak original physical line of code
* \param strLSLOC processed logical string
* \param strLSLOCBak original logical string
* \param paren_cnt count of parenthesis
* \param forflag found for flag
* \param found_forifwhile found for, if, or while flag
* \param found_while found while flag
* \param prev_char previous character
* \param data_continue continuation of a data declaration line
* \param temp_lines tracks physical line count
* \param phys_exec_lines number of physical executable lines
* \param phys_data_lines number of physical data lines
* \param inArrayDec marks an array declaration
* \param found_for found for loop
* \param openBrackets number of open brackets (no matching close bracket)
* \param loopLevel nested loop level
*/
void CCJavaCsCounter::LSLOC(results* result, string line, size_t lineNumber, string lineBak, string &strLSLOC, string &strLSLOCBak, unsigned int &paren_cnt,
							bool &forflag, bool &found_forifwhile, bool &found_while, char &prev_char, bool &data_continue,
							unsigned int &temp_lines, unsigned int &phys_exec_lines, unsigned int &phys_data_lines,
							bool &inArrayDec, bool &found_for, unsigned int &openBrackets, StringVector &loopLevel)
{
	// paren_cnt is used with 'for' statement only
	size_t start = 0; //starting index of the working string
	size_t i = 0, strSize;
	bool found_do, found_try, found_else, trunc_flag = false;
	string exclude = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_$:";
	string dataExclude = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_$:().";	// avoid double count of casts as data and executable lines (e.g. set { m_uiValue = (uint)value; }

	unsigned int cnt = 0;

	string tmp = CUtil::TrimString(strLSLOC);

	// do, try
	found_do = (CUtil::FindKeyword(tmp, "do") != string::npos);
	found_try = (CUtil::FindKeyword(tmp, "try") != string::npos);
	// else is treated differently, else is included in SLOC, do and try are not
	found_else = (CUtil::FindKeyword(tmp, "else") != string::npos);

	// there may be more than 1 logical SLOC in this line
	while (i < line.length())
	{
		switch (line[i])
		{
		case ';': case '{': // LSLOC terminators
			                // ';' for normal executable or declaration statement
			                // '{' for starting a function or 'do' stmt or a block (which is counted)
			// get the previous logical mark until i-1 index is the new LSLOC
			// except 'do' precedes '{'
			// except '}' precedes ';' ??
			// do nothing inside 'for' statement
			if (found_for == true && paren_cnt > 0 && line[i] == ';')
				break;

			// record open bracket for nested loop processing
			if (print_cmplx)
			{
				if (line[i] == '{')
				{
					openBrackets++;
					if ((unsigned int)loopLevel.size() < openBrackets)
						loopLevel.push_back("");
				}
				else
				{
					if ((unsigned int)loopLevel.size() > openBrackets && openBrackets > 0)
						loopLevel.pop_back();
				}
			}

			// case 'while(...);', 'while(...) {', and '} while(...);'
			// this case is handled in case ')'
			if (found_while && found_forifwhile)
			{
				found_while = false;
				found_forifwhile = false;
				start = i + 1;
				break;
			}

			if (line[i] == '{')
			{
				if (prev_char == '=')
					inArrayDec = true;

				// continue until seeing ';'
				if (inArrayDec)
					break;

				// case for(...); and if (...) {
				// these specials are handled
//.........这里部分代码省略.........
开发者ID:zackkk,项目名称:MIPS,代码行数:101,代码来源:CCJavaCsCounter.cpp


注:本文中的StringVector类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。