예제 #1
0
void SQLiteIDSubIDSubIDNameValueList::create ()
{
	StringVector sql;
	sql.push_back ( "CREATE TABLE " + tableName + " ( "\
			+ n1 [0] + " TEXT NOT NULL, "\
			+ n1 [1] + " TEXT NOT NULL, "\
			+ n1 [2] + " TEXT NOT NULL, "\
			+ n1 [3] + " TEXT NOT NULL, "\
			+ n1 [4] + " TEXT, "\
			+ n1 [5] + " TEXT, "\
			+ n1 [6] + " INTEGER CHECK ( " + n1 [6] + " = 0 OR " + n1 [6] + " = 1 ), "\
			+ n1 [7] + " INTEGER CHECK ( " + n1 [7] + " = 0 OR " + n1 [7] + " = 1 ), "\
			+ "PRIMARY KEY ( "\
				+ n1 [0] + ", "\
				+ n1 [1] + ", "\
				+ n1 [2] + ", "\
				+ n1 [3] + ", "\
				+ n1 [4]\
			+ " ) "\
		+ ")" );
	createTables ( sql );
}
예제 #2
0
        void split(StringVector& v, const String& s, const String& separator)
        {
            String sTmp(s);
            char *p = NULL;
            const char *sep = separator.c_str();
            char *tokenHelper = NULL;

            p = strtok_s(
                const_cast<char*>(sTmp.c_str()), 
                sep, 
                &tokenHelper);
            
            while (p != NULL)
            {
                v.push_back(p);
                
                p = strtok_s(
                    NULL,
                    sep, 
                    &tokenHelper);
            }
        }
예제 #3
0
    //-----------------------------------------------------------------------
    StringVector ConfigFile::getMultiSetting(const String& key, const String& section) const
    {
        StringVector ret;


        SettingsBySection::const_iterator seci = mSettings.find(section);
        if (seci != mSettings.end())
        {
            SettingsMultiMap::const_iterator i;

            i = seci->second->find(key);
            // Iterate over matches
            while (i != seci->second->end() && i->first == key)
            {
                ret.push_back(i->second);
                ++i;
            }
        }
        return ret;


    }
예제 #4
0
static void initialiseIndexScore ()
{
	int numEntries;
	char* info = getFileInfo ( MsparamsDir::instance ().getParamPath ( "indicies.txt" ), '>', 1, true, &numEntries );

	for ( int i = 0 ; i < numEntries ; i++ ) {
		names.push_back ( ( i == 0 ) ? strtok ( info, "\n" ) : strtok ( NULL, "\n" ) );
		DoubleVector dv (52);
		indexV.push_back ( dv );
		fill ( dv.begin (), dv.end (), 0.0 );
		for ( ; ; ) {
			char aa;
			double value;
			char* line = strtok ( NULL, "\n" );

			if ( !strcmp ( line, ">" ) ) break;
			sscanf ( line, "%c %lf", &aa, &value );
			indexV [i][aa-'A'] = value;
		}
	}
	initialised = true;
}
예제 #5
0
KDvoid SdkSample::_setup ( RenderWindow* pWindow )
{
    // assign mRoot here in case Root was initialised after the Sample's constructor ran.
    m_pRoot = Root::getSingletonPtr ( );
    m_pWindow = pWindow;
    
    locateResources ( );
    createSceneManager ( );
    setupView ( );
    
    m_pTrayMgr = new SdkTrayManager ( "SampleControls", pWindow, this );  // create a tray interface
    
    loadResources ( );
    m_bResourcesLoaded = true;
    
    // show stats and logo and hide the cursor
    m_pTrayMgr->showFrameStats ( TL_BOTTOMLEFT );
    m_pTrayMgr->showLogo ( TL_BOTTOMRIGHT );
    m_pTrayMgr->hideCursor ( );
    
    // create a params panel for displaying sample details
    StringVector  aItems;
    aItems.push_back ( "cam.pX" );
    aItems.push_back ( "cam.pY" );
    aItems.push_back ( "cam.pZ" );
    aItems.push_back ( ""       );
    aItems.push_back ( "cam.oW" );
    aItems.push_back ( "cam.oX" );
    aItems.push_back ( "cam.oY" );
    aItems.push_back ( "cam.oZ" );
    aItems.push_back ( ""       );
    aItems.push_back ( "Filtering" );
    aItems.push_back ( "Poly Mode" );
    
    m_pDetailsPanel = m_pTrayMgr->createParamsPanel ( TL_NONE, "DetailsPanel", 200, aItems );
    m_pDetailsPanel->hide ( );
    
    m_pDetailsPanel->setParamValue (  9, "Bilinear" );
    m_pDetailsPanel->setParamValue ( 10, "Solid" );
    
    setupContent ( );
    m_bContentSetup = true;
    
    m_bDone = false;
}
예제 #6
0
//-------------------------------------------------------------------------------------
void BaseApplication::createFrameListener(void) {
	LogManager::getSingletonPtr()->logMessage("*** Initializing OIS ***");

	auto keyMouse = getForWindow(_window);

	_keyboard = keyMouse.keyboard;
	_mouse = keyMouse.mouse;

	OgreBites::InputContext inputContext;
	inputContext.mKeyboard = _keyboard;
	inputContext.mMouse =_mouse;

	_trayMgr = new OgreBites::SdkTrayManager("InterfaceName", _window, inputContext, this);
	_trayMgr->showFrameStats(OgreBites::TL_BOTTOMLEFT);
	_trayMgr->showLogo(OgreBites::TL_BOTTOMRIGHT);
	_trayMgr->hideCursor();

	// create a params panel for displaying sample details
	StringVector items;
	items.push_back("cam.pX");
	items.push_back("cam.pY");
	items.push_back("cam.pZ");
	items.push_back("");
	items.push_back("cam.oW");
	items.push_back("cam.oX");
	items.push_back("cam.oY");
	items.push_back("cam.oZ");
	items.push_back("");
	items.push_back("Filtering");
	items.push_back("Poly Mode");

	_detailsPanel = _trayMgr->createParamsPanel(OgreBites::TL_NONE, "DetailsPanel", 200, items);
	_detailsPanel->setParamValue(9, "Bilinear");
	_detailsPanel->setParamValue(10, "Solid");
	_detailsPanel->hide();

	_root->addFrameListener(this);
	_mouse->setEventCallback(this);
	_keyboard->setEventCallback(this);
}
//return the eader in the same position as they was added
StringVector CLocation::GetSSIHeader()const
{
    vector<pair<size_t, string>> orderPair;
    for (SiteSpeceficInformationMap::const_iterator it = m_siteSpeceficInformation.begin(); it != m_siteSpeceficInformation.end(); it++)
        orderPair.push_back(make_pair(it->second.second, it->first));

    std::sort(orderPair.begin(), orderPair.end());

    StringVector header;
    for (vector<pair<size_t, string>>::const_iterator it = orderPair.begin(); it != orderPair.end(); it++)
        header.push_back(it->second);

    return header;

    //return GetSSIOrder();

    //StringVector header;
    //for( SiteSpeceficInformationMap::const_iterator it = m_siteSpeceficInformation.begin(); it!=m_siteSpeceficInformation.end(); it++)
    //for (StringVector::const_iterator it = order.begin(); it != order.end(); it++)
    //header.push_back(m_siteSpeceficInformation[*it]. );

    //return header;
}
예제 #8
0
static int luaFuncExeDirs(lua_State* l)
{
	Block* b = mbGetActiveContext()->ActiveBlock();	
	if (!b)
	{
		MB_LOGERROR("must be within a block");
		mbExitError();
	}
	
    luaL_checktype(l, 1, LUA_TTABLE);
    int tableLen =  luaL_len(l, 1);
    
	StringVector strings;
    for (int i = 1; i <= tableLen; ++i)
    {
        lua_rawgeti(l, 1, i);
		strings.push_back(std::string());
		mbLuaToStringExpandMacros(&strings.back(), b, l, -1);
    }
	b->AddExeDirs(strings);
		
    return 0;
}
예제 #9
0
StringVector split(const std::string& string,
                   const std::string& delimiter)
{
    size_t begin = 0;
    size_t end = 0;
    StringVector strings;

    while(end != std::string::npos)
    {
        end = string.find(delimiter, begin);

        if(end > begin)
        {
            std::string substring = string.substr(begin, end - begin);

            if(!substring.empty()) strings.push_back(substring);
        }

        begin = end + delimiter.size();
    }

    return strings;
}
예제 #10
0
	void SkeletalAnimation::setupModels()
	{

		SceneNode* sn = NULL;
		Entity* ent = NULL;
		AnimationState* as = NULL;

        for (unsigned int i = 0; i < NUM_MODELS; i++)
        {
			// create scene nodes for the models at regular angular intervals
			sn = mSceneManager->getRootSceneNode()->createChildSceneNode();
			sn->yaw(Radian(Math::TWO_PI * (float)i / (float)NUM_MODELS));
			sn->translate(0, 0, -20, Node::TS_LOCAL);
			mModelNodes.push_back(sn);

			// create and attach a jaiqua entity
            ent = mSceneManager->createEntity("Sinbad" + StringConverter::toString(i + 1), "Sinbad.mesh");
			sn->attachObject(ent);

			// enable the entity's sneaking animation at a random speed and loop it manually since translation is involved
			as = ent->getAnimationState("Dance");
            as->setEnabled(true);
			as->setLoop(true);
			mAnimSpeeds.push_back(Math::RangeRandom(0.5, 1.5));
			mAnimStates.push_back(as);
        }

		// create name and value for skinning mode
		StringVector names;
		names.push_back("Skinning");
		String value = "Software";

		// change the value if hardware skinning is enabled
        Pass* pass = ent->getSubEntity(0)->getMaterial()->getBestTechnique()->getPass(0);
		if (pass->hasVertexProgram() && pass->getVertexProgram()->isSkeletalAnimationIncluded()) value = "Hardware";

	}
  ConfigDocument::StringVector 
  ConfigDocument::getInstances(const std::string& _type)
  {
    StringVector names;    

    if (document_ != NULL) {
      QString section = section_.c_str();
      QString type = _type.c_str();
      
      // get the root nodes first child
      QDomNode n1 = document_->documentElement().firstChild();
      while(!n1.isNull()) {
	QDomElement e1 = n1.toElement();
	if (!e1.isNull() &&
	    ( (n1.nodeName() == "section" &&
	       e1.attribute("name") == section) ||
	      (n1.nodeName() == section))) {
	  
	  QDomNode n2 = n1.firstChild();
	  while (!n2.isNull()) {
	    QDomElement e2 = n2.toElement();
	    if (!e2.isNull() &&
		n2.nodeName() == "instance" &&
		e2.attribute("type") == type) {
	      std::string name = e2.attribute("name").latin1();
	      if (name != "")
		names.push_back(name);
	    }
	    n2 = n2.nextSibling();
	  }
	}
	n1 = n1.nextSibling();
      }
    }

    return names;
  }
예제 #12
0
파일: aliases.cpp 프로젝트: Quna/mspdev
void get_lname_aliases (const std::string& name,
                        StringVector& aliases)
{
    for (std::size_t i = 0; locale_aliases [i].name; i++) {
        if (0 == ci_compare (locale_aliases [i].name, name.c_str ())) {
            // store the whole structure data
            store_aliases (aliases, locale_aliases [i]);
            break;
        }

        // check the entry's aliases as well
        for (std::size_t j = 0; locale_aliases [i].aliases [j]; j++) {
            if (0 == ci_compare (locale_aliases [i].aliases [j],
                                 name.c_str ())) {
                // store the whole structure data
                store_aliases (aliases, locale_aliases [i]);
                break;
            }
        }
    }

    if (aliases.empty ())
        aliases.push_back (name);
}
예제 #13
0
void splitByCharA(LPCSTR str, StringVector& parts, CHAR sepChar)
{
	if (NULL == str) return;

	std::string temp = str;
	temp += sepChar;

	std::string::size_type begin = 0;
	std::string::size_type pos = temp.find(sepChar);

	while (pos != std::string::npos)
	{
		std::string part;
		if (pos > begin)
		{
			part = temp.substr(begin, pos - begin);
		}

		parts.push_back(part);

		begin = pos + 1;
		pos = temp.find(sepChar, begin);
	}
}
예제 #14
0
파일: AppDelegate.cpp 프로젝트: bihai/GouJi
bool AppDelegate::initSearchPaths(StringVector& kPaths)
{
	string strPlatformUIPath = "Published-iOS";

#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
	strPlatformUIPath = "Published-Android";
#endif

	m_strLuaScriptPath = m_strBasePlatformPath + string("lua_scripts");
	m_strImagePath = m_strBasePlatformPath + string("images");
	m_strAppIconPath = m_strBasePlatformPath + string("images/app_icon");
	m_strFontPath = m_strBasePlatformPath + string("fonts");
	m_strSoundPath = m_strBasePlatformPath + string("sounds");
	m_strPublishedPath = m_strBasePlatformPath + string("ui_system/") + strPlatformUIPath;

	kPaths.push_back(m_strLuaScriptPath);
	kPaths.push_back(m_strImagePath);
	kPaths.push_back(m_strAppIconPath);
	kPaths.push_back(m_strFontPath);
	kPaths.push_back(m_strSoundPath);
	kPaths.push_back(m_strPublishedPath);

	return true;
}
예제 #15
0
TEST_F(IdfFixture, IdfObject_StringFieldGetterWithReturnDefaultOption) {
  // NON-EXTENSIBLE OBJECT
  std::stringstream text;
  text << "Refrigeration:Condenser:AirCooled," << std::endl
       << "  MyCondenser," << std::endl
       << "  ," << std::endl
       << "  ," << std::endl // default is 0.0
       << "  ," << std::endl // default is "Fixed"
       << "  125.0;";        // default is 250.0
                             // default is 0.2
                             //
                             // default is "General"
                             // default is 0.0
                             // default is 0.0
                             // default is 0.0
  OptionalIdfObject oObj = IdfObject::load(text.str());
  ASSERT_TRUE(oObj);
  IdfObject object = *oObj;

  // returns set values
  OptionalString idfField = object.getString(0,true);
  ASSERT_TRUE(idfField);
  EXPECT_EQ("MyCondenser",*idfField);
  idfField = object.getString(1,true);
  ASSERT_TRUE(idfField);
  EXPECT_EQ("",*idfField);
  idfField = object.getString(4,true);
  ASSERT_TRUE(idfField);
  EXPECT_EQ("125.0",*idfField);

  // returns default for fields behind fields with set values
  idfField = object.getString(2,true);
  ASSERT_TRUE(idfField);
  EXPECT_EQ("0.0",*idfField);
  idfField = object.getString(3,true);
  ASSERT_TRUE(idfField);
  EXPECT_EQ("Fixed",*idfField);

  // returns default for non-existent fields
  idfField = object.getString(6,true);
  EXPECT_FALSE(idfField);
  idfField = object.getString(7,true);
  ASSERT_TRUE(idfField);
  EXPECT_EQ("General",*idfField);
  idfField = object.getString(8,true);
  ASSERT_TRUE(idfField);
  EXPECT_EQ("0.0",*idfField);
  idfField = object.getString(10,true);
  ASSERT_TRUE(idfField);
  EXPECT_EQ("0.0",*idfField);
  idfField = object.getString(11,true);
  EXPECT_FALSE(idfField);

  // EXTENSIBLE OBJECT
  text.str("");
  text << "DaylightingDevice:Tubular," << std::endl
       << "  MyTDD," << std::endl
       << "  MyDome," << std::endl
       << "  MyDiffuser," << std::endl
       << "  MyConstruction," << std::endl
       << "  1.0," << std::endl
       << "  2.0;";
       // \default 0.28
       // Transition Zone 1 Name
       // Transition Zone 1 Length
       // ... (extensible 2)
  oObj = IdfObject::load(text.str());
  ASSERT_TRUE(oObj);
  object = *oObj;
  EXPECT_EQ(6u,object.numFields());

  // returns set values
  idfField = object.getString(0,true);
  ASSERT_TRUE(idfField);
  EXPECT_EQ("MyTDD",*idfField);
  idfField = object.getString(5,true);
  ASSERT_TRUE(idfField);
  EXPECT_EQ("2.0",*idfField);

  // returns default for non-existent, non-extensible fields
  idfField = object.getString(6,true);
  ASSERT_TRUE(idfField);
  EXPECT_EQ("0.28",*idfField);
  EXPECT_EQ(6u,object.numFields());
  idfField = object.getString(6);
  EXPECT_FALSE(idfField);

  StringVector newGroup;
  newGroup.push_back("MyFirstTransistionZone");
  newGroup.push_back("1.5");
  ASSERT_FALSE(object.pushExtensibleGroup(newGroup).empty());

  // returns default for fields behind fields with set values
  idfField = object.getString(6,true);
  ASSERT_TRUE(idfField);
  EXPECT_EQ("0.28",*idfField);
  idfField = object.getString(6);
  ASSERT_TRUE(idfField);
  EXPECT_TRUE(idfField->empty());

  // return evaluates to false for extensible fields that do not exist
  idfField = object.getString(10);
  EXPECT_FALSE(idfField);
}
예제 #16
0
IceUtilInternal::Options::StringVector
IceUtilInternal::Options::parse(const StringVector& args)
{
    RecMutex::Lock sync(_m);

    if(parseCalled)
    {
        throw APIException(__FILE__, __LINE__, "cannot call parse() more than once on the same Option instance");
    }
    parseCalled = true;

    set<string> seenNonRepeatableOpts; // To catch repeated non-repeatable options.

    StringVector result;

    string::size_type i;
    for(i = 1; i < args.size(); ++i)
    {
        if(args[i] == "-" || args[i] == "--")
        {
            ++i;
            break; // "-" and "--" indicate end of options.
        }

        string opt;
        ValidOpts::iterator pos;
        bool argDone = false;

        if(args[i].compare(0, 2, "--") == 0)
        {
            //
            // Long option. If the option has an argument, it can either be separated by '='
            // or appear as a separate argument. For example, "--name value" is the same
            // as "--name=value".
            //
            string::size_type p = args[i].find('=', 2);
            if(p != string::npos)
            {
                opt = args[i].substr(2, p - 2);
            }
            else
            {
                opt = args[i].substr(2);
            }

            pos = checkOpt(opt, LongOpt);

            if(pos->second->repeat == NoRepeat)
            {
                set<string>::iterator seenPos = seenNonRepeatableOpts.find(opt);
                if(seenPos != seenNonRepeatableOpts.end())
                {
                    string err = "`--";
                    err += opt + ":' option cannot be repeated";
                    throw BadOptException(__FILE__, __LINE__, err);
                }
                seenNonRepeatableOpts.insert(seenPos, opt);
                string synonym = getSynonym(opt);
                if(!synonym.empty())
                {
                    seenNonRepeatableOpts.insert(synonym);
                }
            }

            if(p != string::npos)
            {
                if(pos->second->arg == NoArg && p != args[i].size() - 1)
                {
                    string err = "`";
                    err += args[i];
                    err += "': option does not take an argument";
                    throw BadOptException(__FILE__, __LINE__, err);
                }
                setOpt(opt, "", args[i].substr(p + 1), pos->second->repeat);
                argDone = true;
            }
        }
        else if(!args[i].empty() && args[i][0] == '-')
        {
            //
            // Short option.
            //
            for(string::size_type p = 1; p < args[i].size(); ++p)
            {
                opt.clear();
                opt.push_back(args[i][p]);
                pos = checkOpt(opt, ShortOpt);

                if(pos->second->repeat == NoRepeat)
                {
                    set<string>::iterator seenPos = seenNonRepeatableOpts.find(opt);
                    if(seenPos != seenNonRepeatableOpts.end())
                    {
                        string err = "`-";
                        err += opt + ":' option cannot be repeated";
                        throw BadOptException(__FILE__, __LINE__, err);
                    }
                    seenNonRepeatableOpts.insert(seenPos, opt);
                    string synonym = getSynonym(opt);
                    if(!synonym.empty())
                    {
                        seenNonRepeatableOpts.insert(synonym);
                    }
                }

                if(pos->second->arg == NeedArg && p != args[i].size() - 1)
                {
                    string optArg = args[i].substr(p + 1);
                    setOpt(opt, "", optArg, pos->second->repeat);
                    argDone = true;
                    break;
                }
            }
        }
        else
        {
            //
            // Not an option or option argument.
            //
            result.push_back(args[i]);
            argDone = true;
        }

        if(!argDone)
        {
            if(pos->second->arg == NeedArg) // Need an argument that is separated by whitespace.
            {
                if(i == args.size() - 1)
                {
                    string err = "`-";
                    if(opt.size() != 1)
                    {
                        err += "-";
                    }
                    err += opt;
                    err += "' option requires an argument";
                    throw BadOptException(__FILE__, __LINE__, err);
                }
                setOpt(opt, "", args[++i], pos->second->repeat);
            }
            else
            {
                setOpt(opt, "", "1", pos->second->repeat);
            }
        }
    }

    _synonyms.clear(); // Don't need the contents anymore.

    while(i < args.size())
    {
        result.push_back(args[i++]);
    }

    return result;
}
예제 #17
0
IceUtilInternal::Options::StringVector
IceUtilInternal::Options::split(const string& line)
{
    const string IFS = " \t\n"; // Internal Field Separator.

    //
    // Strip leading and trailing whitespace.
    //
    string::size_type start = line.find_first_not_of(IFS);
    if(start == string::npos)
    {
        return StringVector();
    }
    string::size_type end = line.find_last_not_of(IFS);
    assert(end != string::npos);

    string l(line, start, end - start + 1);

    StringVector vec;

    enum ParseState { Normal, DoubleQuote, SingleQuote, ANSIQuote };
    ParseState state = Normal;

    string arg;

    for(string::size_type i = 0; i < l.size(); ++i)
    {
        char c = l[i];
        switch(state)
        {
            case Normal:
            {
                switch(c)
                {
                    case '\\':
                    {
                        //
                        // Ignore a backslash at the end of the string,
                        // and strip backslash-newline pairs. If a
                        // backslash is followed by a space, single quote,
                        // double quote, or dollar sign, we drop the backslash
                        // and write the space, single quote, double quote,
                        // or dollar sign. This is necessary to allow quotes
                        // to be escaped. Dropping the backslash preceding a
                        // space deviates from bash quoting rules, but is
                        // necessary so we don't drop backslashes from Windows
                        // path names.)
                        //
                        if(i < l.size() - 1 && l[++i] != '\n')
                        {
                            switch(l[i])
                            {
                                case ' ':
                                case '$':
                                case '\'':
                                case '"':
                                {
                                    arg.push_back(l[i]);
                                    break;
                                }
                                default:
                                {
                                    arg.push_back('\\');
                                    arg.push_back(l[i]);
                                    break;
                                }
                            }
                        }
                        break;
                    }
                    case '\'':
                    {
                        state = SingleQuote;
                        break;
                    }
                    case '"':
                    {
                        state = DoubleQuote;
                        break;
                    }
                    case '$':
                    {
                        if(i < l.size() - 1 && l[i + 1] == '\'')
                        {
                            state = ANSIQuote; // Bash uses $'<text>' to allow ANSI escape sequences within <text>.
                            ++i;
                        }
                        else
                        {
                            arg.push_back('$');
                        }
                        break;
                    }
                    default:
                    {
                        if(IFS.find(l[i]) != string::npos)
                        {
                            vec.push_back(arg);
                            arg.clear();

                            //
                            // Move to start of next argument.
                            //
                            while(++i < l.size() && IFS.find(l[i]) != string::npos)
                            {
                                ;
                            }
                            --i;
                        }
                        else
                        {
                            arg.push_back(l[i]);
                        }
                        break;
                    }
                }
                break;
            }
            case DoubleQuote:
            {
                //
                // Within double quotes, only backslash retains its special
                // meaning, and only if followed by double quote, backslash,
                // or newline. If not followed by one of these characters,
                // both the backslash and the character are preserved.
                //
                if(c == '\\' && i < l.size() - 1)
                {
                    switch(c = l[++i])
                    {
                        case '"':
                        case '\\':
                        case '\n':
                        {
                            arg.push_back(c);
                            break;
                        }
                        default:
                        {
                            arg.push_back('\\');
                            arg.push_back(c);
                            break;
                        }
                    }
                }
                else if(c == '"') // End of double-quote mode.
                {
                    state = Normal;
                }
                else
                {
                    arg.push_back(c); // Everything else is taken literally.
                }
                break;
            }
            case SingleQuote:
            {
                if(c == '\'') // End of single-quote mode.
                {
                    state = Normal;
                }
                else
                {
                    arg.push_back(c); // Everything else is taken literally.
                }
                break;
            }
            case ANSIQuote:
            {
                switch(c)
                {
                    case '\\':
                    {
                        if(i == l.size() - 1)
                        {
                            break;
                        }
                        switch(c = l[++i])
                        {
                            //
                            // Single-letter escape sequences.
                            //
                            case 'a':
                            {
                                arg.push_back('\a');
                                break;
                            }
                            case 'b':
                            {
                                arg.push_back('\b');
                                break;
                            }
                            case 'f':
                            {
                                arg.push_back('\f');
                                break;
                            }
                            case 'n':
                            {
                                arg.push_back('\n');
                                break;
                            }
                            case 'r':
                            {
                                arg.push_back('\r');
                                break;
                            }
                            case 't':
                            {
                                arg.push_back('\t');
                                break;
                            }
                            case 'v':
                            {
                                arg.push_back('\v');
                                break;
                            }
                            case '\\':
                            {
                                arg.push_back('\\');
                                break;
                            }
                            case '\'':
                            {
                                arg.push_back('\'');
                                break;
                            }
                            case 'e': // Not ANSI-C, but used by bash.
                            {
                                arg.push_back('\033');
                                break;
                            }

                            //
                            // Process up to three octal digits.
                            //
                            case '0':
                            case '1':
                            case '2':
                            case '3':
                            case '4':
                            case '5':
                            case '6':
                            case '7':
                            {
                                static const string octalDigits = "01234567";
                                unsigned short us = 0;
                                string::size_type j;
                                for(j = i;
                                    j < i + 3 && j < l.size() && octalDigits.find_first_of(c = l[j]) != string::npos;
                                    ++j)
                                {
                                    us = us * 8 + c - '0';
                                }
                                i = j - 1;
                                arg.push_back(static_cast<char>(us));
                                break;
                            }

                            //
                            // Process up to two hex digits.
                            //
                            case 'x':
                            {
                                if(i < l.size() - 1 && !isxdigit(static_cast<unsigned char>(l[i + 1])))
                                {
                                    arg.push_back('\\');
                                    arg.push_back('x');
                                    break;
                                }

                                Int64 ull = 0;
                                string::size_type j;
                                for(j = i + 1; j < i + 3 && j < l.size() && 
                                    isxdigit(static_cast<unsigned char>(c = l[j])); ++j)
                                {
                                    ull *= 16;
                                    if(isdigit(static_cast<unsigned char>(c)))
                                    {
                                        ull += c - '0';
                                    }
                                    else if(islower(static_cast<unsigned char>(c)))
                                    {
                                        ull += c - 'a' + 10;
                                    }
                                    else
                                    {
                                        ull += c - 'A' + 10;
                                    }
                                }
                                i = j - 1;
                                arg.push_back(static_cast<char>(ull));
                                break;
                            }

                            //
                            // Process control-chars.
                            //
                            case 'c':
                            {
                                c = l[++i];
                                if(IceUtilInternal::isAlpha(c) || c == '@' || (c >= '[' && c <= '_'))
                                {
                                    arg.push_back(static_cast<char>(toupper(static_cast<unsigned char>(c)) - '@'));
                                }
                                else
                                {
                                    //
                                    // Bash does not define what should happen if a \c
                                    // is not followed by a recognized control character.
                                    // We simply treat this case like other unrecognized
                                    // escape sequences, that is, we preserve the escape
                                    // sequence unchanged.
                                    //
                                    arg.push_back('\\');
                                    arg.push_back('c');
                                    arg.push_back(c);
                                }
                                break;
                            }

                            //
                            // If inside an ANSI-quoted string, a backslash isn't followed by
                            // one of the recognized characters, both the backslash and the
                            // character are preserved.
                            //
                            default:
                            {
                                arg.push_back('\\');
                                arg.push_back(c);
                                break;
                            }
                        }
                        break;
                    }
                    case '\'': // End of ANSI-quote mode.
                    {
                        state = Normal;
                        break;
                    }
                    default:
                    {
                        arg.push_back(c); // Everything else is taken literally.
                        break;
                    }
                }
                break;
            }
            default:
            {
                assert(!"Impossible parse state");
                break;
            }
        }
    }

    switch(state)
    {
        case Normal:
        {
            vec.push_back(arg);
            break;
        }
        case SingleQuote:
        {
            throw BadOptException(__FILE__, __LINE__, "missing closing single quote");
            break;
        }
        case DoubleQuote:
        {
            throw BadOptException(__FILE__, __LINE__, "missing closing double quote");
            break;
        }
        case ANSIQuote:
        {
            throw BadOptException(__FILE__, __LINE__, "unterminated $' quote");
            break;
        }
        default:
        {
            assert(!"Impossible parse state");
            break;
        }
    }

    return vec;
}
예제 #18
0
StringVector ImfFile::sectionNames() const {
  StringVector result;
  BOOST_FOREACH(const SectionMapType::value_type& pair, m_sectionMap){
    result.push_back(pair.first);
  }
예제 #19
0
int FfmpegCamera::OpenFfmpeg() {

    Debug ( 2, "OpenFfmpeg called." );

    mOpenStart = time(NULL);
    mIsOpening = true;

    // Open the input, not necessarily a file
#if !LIBAVFORMAT_VERSION_CHECK(53, 2, 0, 4, 0)
    Debug ( 1, "Calling av_open_input_file" );
    if ( av_open_input_file( &mFormatContext, mPath.c_str(), NULL, 0, NULL ) !=0 )
#else
    // Handle options
    AVDictionary *opts = 0;
    StringVector opVect = split(Options(), ",");
    
    // Set transport method as specified by method field, rtpUni is default
    if ( Method() == "rtpMulti" )
    	opVect.push_back("rtsp_transport=udp_multicast");
    else if ( Method() == "rtpRtsp" )
        opVect.push_back("rtsp_transport=tcp");
    else if ( Method() == "rtpRtspHttp" )
        opVect.push_back("rtsp_transport=http");
    
  	Debug(2, "Number of Options: %d",opVect.size());
    for (size_t i=0; i<opVect.size(); i++)
    {
    	StringVector parts = split(opVect[i],"=");
    	if (parts.size() > 1) {
    		parts[0] = trimSpaces(parts[0]);
    		parts[1] = trimSpaces(parts[1]);
    	    if ( av_dict_set(&opts, parts[0].c_str(), parts[1].c_str(), 0) == 0 ) {
    	        Debug(2, "set option %d '%s' to '%s'", i,  parts[0].c_str(), parts[1].c_str());
    	    }
    	    else
    	    {
    	        Warning( "Error trying to set option %d '%s' to '%s'", i, parts[0].c_str(), parts[1].c_str() );
    	    }
    		  
    	}
       else
       {
           Warning( "Unable to parse ffmpeg option %d '%s', expecting key=value", i, opVect[i].c_str() );
       }
    }    
	Debug ( 1, "Calling avformat_open_input" );

    mFormatContext = avformat_alloc_context( );
    mFormatContext->interrupt_callback.callback = FfmpegInterruptCallback;
    mFormatContext->interrupt_callback.opaque = this;

    if ( avformat_open_input( &mFormatContext, mPath.c_str(), NULL, &opts ) !=0 )
#endif
    {
        mIsOpening = false;
        Error( "Unable to open input %s due to: %s", mPath.c_str(), strerror(errno) );
        return -1;
    }

    AVDictionaryEntry *e;
    if ((e = av_dict_get(opts, "", NULL, AV_DICT_IGNORE_SUFFIX)) != NULL) {
        Warning( "Option %s not recognized by ffmpeg", e->key);
    }

    mIsOpening = false;
    Debug ( 1, "Opened input" );

    // Locate stream info from avformat_open_input
#if !LIBAVFORMAT_VERSION_CHECK(53, 6, 0, 6, 0)
    Debug ( 1, "Calling av_find_stream_info" );
    if ( av_find_stream_info( mFormatContext ) < 0 )
#else
    Debug ( 1, "Calling avformat_find_stream_info" );
    if ( avformat_find_stream_info( mFormatContext, 0 ) < 0 )
#endif
        Fatal( "Unable to find stream info from %s due to: %s", mPath.c_str(), strerror(errno) );

    Debug ( 1, "Got stream info" );

    // Find first video stream present
    mVideoStreamId = -1;
    for (unsigned int i=0; i < mFormatContext->nb_streams; i++ )
    {
#if (LIBAVCODEC_VERSION_CHECK(52, 64, 0, 64, 0) || LIBAVUTIL_VERSION_CHECK(50, 14, 0, 14, 0))
        if ( mFormatContext->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO )
#else
        if ( mFormatContext->streams[i]->codec->codec_type == CODEC_TYPE_VIDEO )
#endif
        {
            mVideoStreamId = i;
            break;
        }
    }
    if ( mVideoStreamId == -1 )
        Fatal( "Unable to locate video stream in %s", mPath.c_str() );

    Debug ( 1, "Found video stream" );

    mCodecContext = mFormatContext->streams[mVideoStreamId]->codec;

    // Try and get the codec from the codec context
    if ( (mCodec = avcodec_find_decoder( mCodecContext->codec_id )) == NULL )
        Fatal( "Can't find codec for video stream from %s", mPath.c_str() );

    Debug ( 1, "Found decoder" );

    // Open the codec
#if !LIBAVFORMAT_VERSION_CHECK(53, 8, 0, 8, 0)
    Debug ( 1, "Calling avcodec_open" );
    if ( avcodec_open( mCodecContext, mCodec ) < 0 )
#else
    Debug ( 1, "Calling avcodec_open2" );
    if ( avcodec_open2( mCodecContext, mCodec, 0 ) < 0 )
#endif
        Fatal( "Unable to open codec for video stream from %s", mPath.c_str() );

    Debug ( 1, "Opened codec" );

    // Allocate space for the native video frame
#if LIBAVCODEC_VERSION_CHECK(55, 28, 1, 45, 101)
    mRawFrame = av_frame_alloc();
#else
    mRawFrame = avcodec_alloc_frame();
#endif

    // Allocate space for the converted video frame
#if LIBAVCODEC_VERSION_CHECK(55, 28, 1, 45, 101)
    mFrame = av_frame_alloc();
#else
    mFrame = avcodec_alloc_frame();
#endif

    if(mRawFrame == NULL || mFrame == NULL)
        Fatal( "Unable to allocate frame for %s", mPath.c_str() );

    Debug ( 1, "Allocated frames" );
    
    int pSize = avpicture_get_size( imagePixFormat, width, height );
    if( (unsigned int)pSize != imagesize) {
        Fatal("Image size mismatch. Required: %d Available: %d",pSize,imagesize);
    }

    Debug ( 1, "Validated imagesize" );
    
#if HAVE_LIBSWSCALE
    Debug ( 1, "Calling sws_isSupportedInput" );
    if(!sws_isSupportedInput(mCodecContext->pix_fmt)) {
        Fatal("swscale does not support the codec format: %c%c%c%c",(mCodecContext->pix_fmt)&0xff,((mCodecContext->pix_fmt>>8)&0xff),((mCodecContext->pix_fmt>>16)&0xff),((mCodecContext->pix_fmt>>24)&0xff));
    }
예제 #20
0
int FfmpegCamera::PrimeCapture()
{
    Info( "Priming capture from %s", mPath.c_str() );
    


    // Open the input, not necessarily a file
#if LIBAVFORMAT_VERSION_INT < AV_VERSION_INT(53, 4, 0)
    if ( av_open_input_file( &mFormatContext, mPath.c_str(), NULL, 0, NULL ) !=0 )
#else
    // Handle options
    AVDictionary *opts = 0;
    StringVector opVect = split(Options(), ",");
    
    // Set transport method as specified by method field, rtpUni is default
    if ( Method() == "rtpMulti" )
    	opVect.push_back("rtsp_transport=udp_multicast");
    else if ( Method() == "rtpRtsp" )
        opVect.push_back("rtsp_transport=tcp");
    else if ( Method() == "rtpRtspHttp" )
        opVect.push_back("rtsp_transport=http");
    
  	Debug(2, "Number of Options: %d",opVect.size());
    for (size_t i=0; i<opVect.size(); i++)
    {
    	StringVector parts = split(opVect[i],"=");
    	if (parts.size() > 1) {
    		parts[0] = trimSpaces(parts[0]);
    		parts[1] = trimSpaces(parts[1]);
    	    if ( av_dict_set(&opts, parts[0].c_str(), parts[1].c_str(), 0) == 0 ) {
    	        Debug(2, "set option %d '%s' to '%s'", i,  parts[0].c_str(), parts[1].c_str());
    	    }
    	    else
    	    {
    	        Warning( "Error trying to set option %d '%s' to '%s'", i, parts[0].c_str(), parts[1].c_str() );
    	    }
    		  
    	}
    }

    if ( avformat_open_input( &mFormatContext, mPath.c_str(), NULL, &opts ) !=0 )
#endif
        Fatal( "Unable to open input %s due to: %s", mPath.c_str(), strerror(errno) );

    // Locate stream info from input
#if LIBAVFORMAT_VERSION_INT < AV_VERSION_INT(53, 4, 0)
    if ( av_find_stream_info( mFormatContext ) < 0 )
#else
    if ( avformat_find_stream_info( mFormatContext, 0 ) < 0 )
#endif
        Fatal( "Unable to find stream info from %s due to: %s", mPath.c_str(), strerror(errno) );
    
    // Find first video stream present
    mVideoStreamId = -1;
    for (unsigned int i=0; i < mFormatContext->nb_streams; i++ )
    {
#if LIBAVUTIL_VERSION_INT >= AV_VERSION_INT(51,2,1)
        if ( mFormatContext->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO )
#else
        if ( mFormatContext->streams[i]->codec->codec_type == CODEC_TYPE_VIDEO )
#endif
        {
            mVideoStreamId = i;
            break;
        }
    }
    if ( mVideoStreamId == -1 )
        Fatal( "Unable to locate video stream in %s", mPath.c_str() );

    mCodecContext = mFormatContext->streams[mVideoStreamId]->codec;

    // Try and get the codec from the codec context
    if ( (mCodec = avcodec_find_decoder( mCodecContext->codec_id )) == NULL )
        Fatal( "Can't find codec for video stream from %s", mPath.c_str() );

    // Open the codec
#if LIBAVFORMAT_VERSION_INT < AV_VERSION_INT(53, 7, 0)
    if ( avcodec_open( mCodecContext, mCodec ) < 0 )
#else
    if ( avcodec_open2( mCodecContext, mCodec, 0 ) < 0 )
#endif
        Fatal( "Unable to open codec for video stream from %s", mPath.c_str() );

    // Allocate space for the native video frame
    mRawFrame = avcodec_alloc_frame();

    // Allocate space for the converted video frame
    mFrame = avcodec_alloc_frame();
    
	if(mRawFrame == NULL || mFrame == NULL)
		Fatal( "Unable to allocate frame for %s", mPath.c_str() );
	
	int pSize = avpicture_get_size( imagePixFormat, width, height );
	if( (unsigned int)pSize != imagesize) {
		Fatal("Image size mismatch. Required: %d Available: %d",pSize,imagesize);
	}
	
#if HAVE_LIBSWSCALE
	if(!sws_isSupportedInput(mCodecContext->pix_fmt)) {
		Fatal("swscale does not support the codec format: %c%c%c%c",(mCodecContext->pix_fmt)&0xff,((mCodecContext->pix_fmt>>8)&0xff),((mCodecContext->pix_fmt>>16)&0xff),((mCodecContext->pix_fmt>>24)&0xff));
	}
예제 #21
0
void EdiDocument::CreateRow(StringVector& v) const {
    for (size_t i = 0; i < GetColCount(); i++) {
        v.push_back(GetColumnDescriptor(i).GetDefaultValue());
    }
};
예제 #22
0
void
NumericExpression::init()
{
    _vars.clear();
    _rpn.clear();

    StringTokenizer variablesTokenizer( "", "" );
    variablesTokenizer.addDelims( "[]", true );
    variablesTokenizer.addQuotes( "'\"", true );
    variablesTokenizer.keepEmpties() = false;

    StringTokenizer operandTokenizer( "", "" );
    operandTokenizer.addDelims( ",()%*/+-", true );
    operandTokenizer.addQuotes( "'\"", true );
    operandTokenizer.keepEmpties() = false;

    StringVector variablesTokens;
    variablesTokenizer.tokenize( _src, variablesTokens );

    StringVector t;
    bool invar = false;
    for( unsigned i=0; i<variablesTokens.size(); ++i )
    {
        if ( variablesTokens[i] == "[" && !invar )
        {
            // Start variable, add "[" token
            invar = true;
            t.push_back(variablesTokens[i]);
        }
        else if ( variablesTokens[i] == "]" && invar )
        {
            // End variable, add "]" token
            invar = false;
            t.push_back(variablesTokens[i]);
        }
        else if ( invar )
        {
            // Variable, add variable token
            t.push_back(variablesTokens[i]);
        }
        else
        {
            // Operands, tokenize it and add tokens
            StringVector operandTokens;
            operandTokenizer.tokenize( variablesTokens[i], operandTokens );
            t.insert(t.end(), operandTokens.begin(), operandTokens.end());
        }
    }

    // identify tokens:
    AtomVector infix;
    invar = false;
    for( unsigned i=0; i<t.size(); ++i ) {
        if ( t[i] == "[" && !invar ) {
            invar = true;
        }
        else if ( t[i] == "]" && invar ) {
            invar = false;
            infix.push_back( Atom(VARIABLE,0.0) );
            _vars.push_back( Variable(t[i-1],0) );
        }
        else if ( t[i] == "(" ) infix.push_back( Atom(LPAREN,0.0) );
        else if ( t[i] == ")" ) infix.push_back( Atom(RPAREN,0.0) );
        else if ( t[i] == "," ) infix.push_back( Atom(COMMA,0.0) );
        else if ( t[i] == "%" ) infix.push_back( Atom(MOD,0.0) );
        else if ( t[i] == "*" ) infix.push_back( Atom(MULT,0.0) );
        else if ( t[i] == "/" ) infix.push_back( Atom(DIV,0.0) );
        else if ( t[i] == "+" ) infix.push_back( Atom(ADD,0.0) );
        else if ( t[i] == "-" ) infix.push_back( Atom(SUB,0.0) );
        else if ( t[i] == "min" ) infix.push_back( Atom(MIN,0.0) );
        else if ( t[i] == "max" ) infix.push_back( Atom(MAX,0.0) );
        else if ( (t[i][0] >= '0' && t[i][0] <= '9') || t[i][0] == '.' )
            infix.push_back( Atom(OPERAND,as<double>(t[i],0.0)) );
        else if ( t[i] != "," && (i == 0 || t[i-1] != "["))
        {
          std::string var = t[i];
          // If this is a call to a script function, store the entire function
          // call in the variable string
          if (i < t.size() - 1 && t[i+1] == "(")
          {
            int parenCount = 0;
            do
            {
              ++i;
              var += t[i];

              if (t[i] == "(")
                parenCount++;
              else if (t[i] == ")")
                parenCount--;

            } while (i < t.size() - 1 && parenCount > 0);
          }

          infix.push_back( Atom(VARIABLE, 0.0) );
          _vars.push_back( Variable(var, 0) );
        }

        // note: do nothing for a comma
    }

    // convert to RPN:
    // http://en.wikipedia.org/wiki/Shunting-yard_algorithm
    AtomStack s;
    unsigned var_i = 0;

    for( unsigned i=0; i<infix.size(); ++i )
    {
        Atom& a = infix[i];

        if ( a.first == LPAREN )
        {
            s.push( a );
        }
        else if ( a.first == RPAREN )
        {
            while( s.size() > 0 )
            {
                Atom top = s.top();
                s.pop();
                if ( top.first == LPAREN )
                    break;
                else
                    _rpn.push_back( top );
            }
        }
        else if ( a.first == COMMA )
        {
            while( s.size() > 0 && s.top().first != LPAREN )
            {
                _rpn.push_back( s.top() );
                s.pop();
            }
        }
        else if ( IS_OPERATOR(a) )
        {
            if ( s.empty() || a.first > s.top().first )
            {
                s.push( a );
            }
            else 
            {
                while( s.size() > 0 && a.first < s.top().first && IS_OPERATOR(s.top()) )
                {
                    _rpn.push_back( s.top() );
                    s.pop();
                }
                s.push( a );
            }
        }
        else if ( a.first == MIN || a.first == MAX )
        {
            s.push( a );
        }
        else if ( a.first == OPERAND )
        {
            _rpn.push_back( a );
        }
        else if ( a.first == VARIABLE )
        {
            _rpn.push_back( a );
            _vars[var_i++].second = _rpn.size()-1; // store the index
        }
    }

    while( s.size() > 0 )
    {
        _rpn.push_back( s.top() );
        s.pop();
    }
}
예제 #23
0
파일: glob.cpp 프로젝트: bbannier/csvsqldb
 size_t expand(const std::string& pattern, StringVector& files)
 {
     // sorry, no file pattern expansion on windows
     files.push_back(pattern);
     return files.size();
 }
예제 #24
0
파일: O_String.cpp 프로젝트: psxcode/demo4
	//-----------------------------------------------------------------------
	StringVector StringUtil::tokenise( const String& str, const String& singleDelims, const String& doubleDelims, unsigned int maxSplits)
	{
        StringVector ret;
        // Pre-allocate some space for performance
        ret.reserve(maxSplits ? maxSplits+1 : 10);    // 10 is guessed capacity for most case

        unsigned int numSplits = 0;
		String delims = singleDelims + doubleDelims;

		// Use STL methods 
        size_t start, pos;
		char curDoubleDelim = 0;
        start = 0;
        do 
        {
			if (curDoubleDelim != 0)
			{
				pos = str.find(curDoubleDelim, start);
			}
			else
			{
				pos = str.find_first_of(delims, start);
			}

            if (pos == start)
            {
				char curDelim = str.at(pos);
				if (doubleDelims.find_first_of(curDelim) != String::npos)
				{
					curDoubleDelim = curDelim;
				}
                // Do nothing
                start = pos + 1;
            }
            else if (pos == String::npos || (maxSplits && numSplits == maxSplits))
            {
				if (curDoubleDelim != 0)
				{
					//Missing closer. Warn or throw exception?
				}
                // Copy the rest of the string
                ret.push_back( str.substr(start) );
                break;
            }
            else
            {
				if (curDoubleDelim != 0)
				{
					curDoubleDelim = 0;
				}

				// Copy up to delimiter
				ret.push_back( str.substr(start, pos - start) );
				start = pos + 1;
            }
			if (curDoubleDelim == 0)
			{
				// parse up to next real data
				start = str.find_first_not_of(singleDelims, start);
			}
            
            ++numSplits;

        } while (pos != String::npos);

        return ret;
    }
예제 #25
0
/*!
* Parses lines for function/method names.
*
* \param line line to be processed
* \param lastline last line processed
* \param functionStack stack of functions
* \param functionName function name found
*
* \return 1 if function name is found
*/
int CCJavaCsCounter::ParseFunctionName(const string &line, string &lastline, StringVector &functionStack, string &functionName)
{
	string tline, str;
	size_t idx, tidx, cnt, cnt2;
	unsigned int cyclomatic_cnt = 0;
	string exclude = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_$";

	tline = CUtil::TrimString(line);
	idx = tline.find('{');
	if (idx != string::npos)
	{
		// check whether it is at first index, if yes then function name is at above line
		if (idx == 0)
		{
			functionStack.push_back(lastline);
			lastline.erase();
		}
		else
		{
			str = tline.substr(0, idx);
			tidx = cnt = cnt2 = 0;
			if (str[0] != '(' && str[0] != ':' && (lastline.length() < 1 || lastline[lastline.length() - 1] != ':'))
			{
				while (tidx != string::npos)
				{
					tidx = str.find('(', tidx);
					if (tidx != string::npos)
					{
						cnt++;
						tidx++;
					}
				}
				if (cnt > 0)
				{
					tidx = 0;
					while (tidx != string::npos)
					{
						tidx = str.find(')', tidx);
						if (tidx != string::npos)
						{
							cnt2++;
							tidx++;
						}
					}
				}
			}
			// make sure parentheses are closed and no parent class listed
			if ((cnt > 0 && cnt == cnt2) || (lastline.length() > 0 && lastline[lastline.length() - 1] == ';'))
				lastline = str;
			else
				lastline += " " + str;
			functionStack.push_back(CUtil::TrimString(lastline));
			lastline.erase();
		}
	}
	else if (tline.length() > 0 && tline[tline.length() - 1] != ';' &&
		lastline.length() > 0 && lastline[lastline.length() - 1] != ';')
	{
		// append until all parentheses are closed
		tidx = lastline.find('(');
		if (tidx != string::npos)
		{
			cnt = 1;
			while (tidx != string::npos)
			{
				tidx = lastline.find('(', tidx + 1);
				if (tidx != string::npos)
					cnt++;
			}
			tidx = lastline.find(')');
			while (tidx != string::npos)
			{
				cnt++;
				tidx = lastline.find(')', tidx + 1);
			}
			if (cnt % 2 != 0)
				lastline += " " + tline;
			else
				lastline = tline;
		}
		else
			lastline = tline;
	}
	else
		lastline = tline;

	idx = line.find('}');
	if (idx != string::npos && !functionStack.empty())
	{
		str = functionStack.back();
		functionStack.pop_back();
		idx = str.find('(');

		if (idx != string::npos)
		{
			// search for cyclomatic complexity keywords and other possible keywords
			CUtil::CountTally(str, cmplx_cyclomatic_list, cyclomatic_cnt, 1, exclude, "", "", 0, casesensitive);
			if (cyclomatic_cnt <= 0 && CUtil::FindKeyword(str, "switch") == string::npos &&
				CUtil::FindKeyword(str, "try") == string::npos && CUtil::FindKeyword(str, "finally") == string::npos &&
				CUtil::FindKeyword(str, "return") == string::npos && str.find('=') == string::npos)
			{
				functionName = CUtil::ClearRedundantSpaces(str.substr(0, idx));
				lastline.erase();
				return 1;
			}
		}
		lastline.erase();
	}
	return 0;
}
예제 #26
0
파일: rstream.cpp 프로젝트: kindex/Steel
void addDataSearchDirectories(const std::string& newDataDir)
{
	dataSearchDirectories.push_back(newDataDir);
}
/*!
* 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 openBrackets number of open brackets (no matching close bracket)
* \param loopLevel nested loop level
*/
void CJavascriptCounter::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,
							   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_$:";
	unsigned int cnt = 0;
	unsigned int loopCnt = 0;
	StringVector::iterator lit;

	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 (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
				if (found_forifwhile)
				{
					found_forifwhile = false;
					start = i + 1;
					break;
				}

				// check if 'do' precedes '{'
				if (!found_do && !found_try && !found_else)
				{
					// find for 'do' in string before tmp string
					tmp = CUtil::TrimString(line.substr(start, i - start));
					found_do = (tmp == "do");		// found 'do' statement
					found_try = (tmp == "try");		// found 'try' statement
					// same as else
					found_else = (tmp == "else");	// found 'else' statement
				}
				if (found_do || found_try || found_else)
				{
					if (found_do && print_cmplx)
					{
						if (loopLevel.size() > 0)
							loopLevel.pop_back();
						loopLevel.push_back("do");
					}
					found_do = false;
					found_try = false;
					if (!found_else)
					{
						// everything before 'do', 'try' are cleared
						strLSLOC = "";
						strLSLOCBak = "";
						start = i + 1;
					}
					break; // do not store '{' following 'do'
				}
			}

			// wrong, e.g., a[]={1,2,3};
			if (line[i] == ';' && prev_char == '}')
			{
				// check if in array declaration or not
				// if no, skip, otherwise, complete the SLOC containing array declaration
				if (!inArrayDec)
				{
					start = i + 1;
					break; 
				}
			}

			inArrayDec = false;

			// check for empty statement (=1 LSLOC)
			if (CUtil::TrimString(line.substr(start, i + 1 - start)) == ";" && strLSLOC.length() < 1)
			{
				strLSLOC = ";";
				strLSLOCBak = ";";
			}
			else
			{
				strSize = CUtil::TruncateLine(i + 1 - start, strLSLOC.length(), this->lsloc_truncate, trunc_flag);
				if (strSize > 0)
				{
					strLSLOC += line.substr(start, strSize);
					strLSLOCBak += lineBak.substr(start, strSize);
				}
			}
			if (result->addSLOC(strLSLOCBak, lineNumber, trunc_flag))
			{
				cnt = 0;
				CUtil::CountTally(strLSLOC, data_name_list, cnt, 1, exclude, "", "", &result->data_name_count);

				temp_lines++;
				if (data_continue == true && line[i] == ';')
				{
					result->data_lines[LOG]++;
					phys_data_lines = temp_lines;
				}
				else
				{
					if (cnt > 0 && line[i] == ';')
					{
						result->data_lines[LOG]++;
						phys_data_lines = temp_lines;
					}
					else
					{
						result->exec_lines[LOG]++;
						phys_exec_lines = temp_lines;
					}
				}
			}
			else if (data_continue == true && line[i] == ';')
				phys_data_lines = temp_lines;
			else
				phys_exec_lines = temp_lines;
			data_continue = false;
			temp_lines = 0;
			strLSLOC = strLSLOCBak = "";
			start = i + 1;

			break;
		case '(':
			if (forflag)
				paren_cnt++;
			else
			{
				// handle 'for', 'foreach', 'while', 'if' the same way
				tmp = CUtil::TrimString(line.substr(start,i));
				if (CUtil::FindKeyword(tmp, "for") != string::npos
					|| CUtil::FindKeyword(tmp, "foreach") != string::npos
					|| CUtil::FindKeyword(tmp, "while")!= string::npos
					|| CUtil::FindKeyword(tmp, "if") != string::npos)
				{
					forflag = true;
					paren_cnt++;

					if (print_cmplx && (unsigned int)loopLevel.size() > openBrackets && openBrackets > 0)
						loopLevel.pop_back();

					if (CUtil::FindKeyword(tmp, "while")!= string::npos)
					{
						if (print_cmplx)
							loopLevel.push_back("while");
						found_while = true;
					}
					else if (print_cmplx)
					{
						if (CUtil::FindKeyword(tmp, "for") != string::npos)
							loopLevel.push_back("for");
						else if (CUtil::FindKeyword(tmp, "foreach") != string::npos)
							loopLevel.push_back("foreach");

						// record nested loop level
						if (CUtil::FindKeyword(tmp, "if") == string::npos)
						{
							loopCnt = 0;
							for (lit = loopLevel.begin(); lit < loopLevel.end(); lit++)
							{
								if ((*lit) != "")
									loopCnt++;
							}
							if ((unsigned int)result->cmplx_nestloop_count.size() < loopCnt)
								result->cmplx_nestloop_count.push_back(1);
							else
								result->cmplx_nestloop_count[loopCnt-1]++;
						}
					}
				}
			}
			break;
		case ')':
			if (forflag)
			{
				if (paren_cnt > 0)
					paren_cnt--;
				if (paren_cnt == 0) 
				{
					// handle 'for', 'foreach', 'while', 'if'
					strSize = CUtil::TruncateLine(i + 1 - start, strLSLOC.length(), this->lsloc_truncate, trunc_flag);
					if (strSize > 0)
					{
						strLSLOC += line.substr(start, strSize);
						strLSLOCBak += lineBak.substr(start, strSize);
					}
					if (result->addSLOC(strLSLOCBak, lineNumber, trunc_flag))
						result->exec_lines[LOG]++;
					strLSLOCBak = strLSLOC = "";
					phys_exec_lines = temp_lines;
					temp_lines = 0;
					start = i + 1;
					found_forifwhile = true;	
					forflag = false;
				}
			}
			break;
		case '}':
			// skip '}' when found ';' and then '}' because '{' is counted already
			// also, {} is also skipped, counted
			if (prev_char == ';' || prev_char == '{' || prev_char == '}')
				if (!inArrayDec) start = i + 1;

			// record close bracket for nested loop processing
			if (print_cmplx)
			{
				if (openBrackets > 0)
					openBrackets--;
				if (loopLevel.size() > 0)
					loopLevel.pop_back();
			}
			break;
		}

		if (line[i] != ' ' && line[i] != '\t')
		{
			// if ;}}} --> don't count }}} at all
			// also, if {}}} --> don't count }}} at all
			// if ( !(line[i] == '}' && (prev_char == ';' || prev_char == '{'))) // see case '}' above
			prev_char = line[i];

			// change to not found if a char appears before
			if (line[i] != ')' && found_forifwhile)
				found_forifwhile = false;
		}

		i++;
	}

	tmp = CUtil::TrimString(line.substr(start, i - start));
	strSize = CUtil::TruncateLine(tmp.length(), strLSLOC.length(), this->lsloc_truncate, trunc_flag);
	if (strSize > 0)
	{
		strLSLOC += tmp.substr(0, strSize);
		tmp = CUtil::TrimString(lineBak.substr(start, i - start));
		strLSLOCBak += tmp.substr(0, strSize);

		// drop continuation symbol
		if (strLSLOC[strLSLOC.length()-1] == '\\')
		{
			strLSLOC = strLSLOC.substr(0, strLSLOC.length()-1);
			strLSLOCBak = strLSLOCBak.substr(0, strLSLOCBak.length()-1);
		}
	}
	
	// make sure that we are not beginning to process a new data line
	cnt = 0;
	CUtil::CountTally(strLSLOC, data_name_list, cnt, 1, exclude, "", "", NULL);

	if (cnt > 0)
		data_continue = true;
	if (data_continue)
		temp_lines++;
	if (temp_lines == 0 && phys_data_lines == 0 && phys_exec_lines == 0)
		phys_exec_lines = 1;
}
예제 #28
0
// Run dindel on a pair of samples
DindelReturnCode DindelUtil::runDindelPairMatePair(const std::string& id,
                                                   const StringVector& base_haplotypes,
                                                   const StringVector& variant_haplotypes,
                                                   const GraphCompareParameters& parameters,
                                                   std::ostream& baseOut,
                                                   std::ostream& variantOut,
                                                   std::ostream& callsOut,
                                                   DindelReadReferenceAlignmentVector* pReadAlignments)
{
    PROFILE_FUNC("runDindelPairMatePair")

    StringVector inHaplotypes;
    inHaplotypes.insert(inHaplotypes.end(), base_haplotypes.begin(), base_haplotypes.end());
    inHaplotypes.insert(inHaplotypes.end(), variant_haplotypes.begin(), variant_haplotypes.end());

    //
    // First, extract the reads from the normal and variant data sets that match each haplotype
    //
    assert(inHaplotypes.size() > 0);

    // Get canidate alignments for the input haplotypes
    HapgenAlignmentVector candidateAlignments;

    // Choose the kmer size for alignment
    size_t align_kmer = 31;
    for(size_t i = 0; i < inHaplotypes.size(); ++i)
    {
        HapgenAlignmentVector thisCandidateAlignments;
        HapgenUtil::alignHaplotypeToReferenceKmer(align_kmer,
                                                  inHaplotypes[i],
                                                  parameters.referenceIndex,
                                                  parameters.pRefTable,
                                                  thisCandidateAlignments);

        candidateAlignments.insert(candidateAlignments.end(), thisCandidateAlignments.begin(), thisCandidateAlignments.end());
    }
   
    // Remove duplicate or bad alignment pairs
    HapgenUtil::coalesceAlignments(candidateAlignments);

    if(Verbosity::Instance().getPrintLevel() > 3)
        printf("runDindel -- %zu candidate alignments found\n", candidateAlignments.size());
    
    size_t MAX_ALIGNMENTS = 10;
    if(candidateAlignments.size() > MAX_ALIGNMENTS)
        return DRC_AMBIGUOUS_ALIGNMENT;

    // Join each haplotype with flanking sequence from the reference genome for each alignment
    // This function also adds a haplotype (with flanking sequence) for the piece of the reference
    int FLANKING_SIZE = 0;
    if (parameters.dindelRealignParameters.realignMatePairs)
        FLANKING_SIZE = 1000;
    StringVector flankingHaplotypes;

    // This vector contains the internal portion of the haplotypes, without the flanking sequence
    // It is used to extract reads
    StringVector candidateHaplotypes;
    for(size_t i = 0; i < candidateAlignments.size(); ++i)
    {
        HapgenUtil::makeFlankingHaplotypes(candidateAlignments[i],
                                           parameters.pRefTable,
                                           FLANKING_SIZE,
                                           inHaplotypes,
                                           flankingHaplotypes,
                                           candidateHaplotypes);
    
    }

    if(Verbosity::Instance().getPrintLevel() > 3)
        printf("runDindel -- made %zu flanking haplotypes\n", candidateHaplotypes.size());

    // Normal reads
    SeqRecordVector normalReads;
    SeqRecordVector normalRCReads;

    // Remove non-unique candidate haplotypes
    std::sort(candidateHaplotypes.begin(), candidateHaplotypes.end());
    StringVector::iterator haplotype_iterator = std::unique(candidateHaplotypes.begin(), candidateHaplotypes.end());
    candidateHaplotypes.resize(haplotype_iterator - candidateHaplotypes.begin());

    // Set the value to use for extracting reads that potentially match the haplotype
    // Do not use a kmer for extraction greater than this value
    size_t KMER_CEILING = 31;
    size_t extractionKmer = parameters.kmer < KMER_CEILING ? parameters.kmer : KMER_CEILING;
    
    bool extractOK = true;
    if(!parameters.bReferenceMode)
    {
        // Reads on the same strand as the haplotype
        extractOK = HapgenUtil::extractHaplotypeReads(candidateHaplotypes, parameters.baseIndex, extractionKmer, 
                                                      false, parameters.maxReads, parameters.maxExtractionIntervalSize, &normalReads, NULL);

        if(!extractOK)
            return DRC_OVER_DEPTH;

        // Reads on the reverse strand
        extractOK = HapgenUtil::extractHaplotypeReads(candidateHaplotypes, parameters.baseIndex, extractionKmer, 
                                                      true, parameters.maxReads, parameters.maxExtractionIntervalSize, &normalRCReads, NULL);

        if(!extractOK)
            return DRC_OVER_DEPTH;
    }

    // Variant reads
    SeqRecordVector variantReads;
    SeqRecordVector variantRCReads;

    extractOK = HapgenUtil::extractHaplotypeReads(candidateHaplotypes, parameters.variantIndex, extractionKmer, 
                                                  false, parameters.maxReads, parameters.maxExtractionIntervalSize, &variantReads, NULL);

    if(!extractOK)
        return DRC_OVER_DEPTH;

    extractOK = HapgenUtil::extractHaplotypeReads(candidateHaplotypes, parameters.variantIndex, extractionKmer, 
                                                  true, parameters.maxReads, parameters.maxExtractionIntervalSize, &variantRCReads, NULL);

    if(!extractOK)
        return DRC_OVER_DEPTH;

    size_t normal_reads = normalReads.size() + normalRCReads.size();
    size_t variant_reads = variantReads.size() + variantRCReads.size();
    size_t total_reads = normal_reads + variant_reads;
    
    if(Verbosity::Instance().getPrintLevel() > 3)
        printf("Extracted %zu normal reads, %zu variant reads\n", normal_reads, variant_reads);

    if(total_reads > parameters.maxReads)
        return DRC_OVER_DEPTH;

    if (total_reads == 0)
        return DRC_UNDER_DEPTH;

    // Generate the input haplotypes for dindel
    // We need at least 2 haplotypes (one is the reference)
    size_t totFlankingHaplotypes = flankingHaplotypes.size();

    if(totFlankingHaplotypes < 2)
        return DRC_NO_ALIGNMENT;

    // Ensure the reference haplotype is a non-empty string
    if(flankingHaplotypes[0].size() == 0)
        return DRC_NO_ALIGNMENT;

    // Make Dindel referenceMappings
    StringVector dindelHaplotypes;
    std::set<DindelReferenceMapping> refMappings;

    //
    for(size_t i = 0; i < candidateAlignments.size(); ++i)
    {
        std::string upstream, defined, downstream;
        std::string refName = parameters.pRefTable->getRead(candidateAlignments[i].referenceID).id;

        HapgenUtil::extractReferenceSubstrings(candidateAlignments[i],parameters.pRefTable, 
                                               FLANKING_SIZE, upstream, defined, downstream);

        std::string refSeq = upstream + defined + downstream;
     
        int refStart = candidateAlignments[i].position - int(upstream.size()) + 1;

        // Here the score is used as an estimate of how unique "defined" is in the reference sequence.
        // "defined" is not the reference sequence but a candidate haplotype.
        // It is conservative because the flanking sequence is not used in this estimation.
    	DindelReferenceMapping rm(refName, 
                                  refSeq, 
                                  refStart, 
                                  candidateAlignments[i].score+2*FLANKING_SIZE, 
                                  candidateAlignments[i].isRC);

        std::set<DindelReferenceMapping>::iterator rmit = refMappings.find(rm);
        if(rmit == refMappings.end())
        {
            refMappings.insert(rm);
        }
	    else
        {
            if(rm.referenceAlignmentScore > rmit->referenceAlignmentScore) 
                rmit->referenceAlignmentScore = rm.referenceAlignmentScore;
        }
    }
    
    // RESET MAPPING SCORES
    for(std::set<DindelReferenceMapping>::iterator it = refMappings.begin(); it != refMappings.end(); it++) 
        it->referenceAlignmentScore = 1000;
    
    // make flankingHaplotypes unique
    std::set< std::string > setFlanking(flankingHaplotypes.begin(), flankingHaplotypes.end());

    for(std::set< std::string >::const_iterator it = setFlanking.begin(); it != setFlanking.end(); it++)
    {
        dindelHaplotypes.push_back(*it);
        //dindelRefMappings[i] = std::vector<DindelReferenceMapping>(refMappings.begin(),refMappings.end());
    }

    std::vector<DindelReferenceMapping> dRefMappings(refMappings.begin(),refMappings.end());
    DindelWindow dWindow(dindelHaplotypes, dRefMappings);

    //
    // Run Dindel
    //
    
    // Initialize VCF collections
    VCFCollection vcfCollections[2];

    // If in multisample mode, load the sample names into the VCFCollection
    if(parameters.variantIndex.pPopIdx != NULL)
    {
        for(size_t i = 0; i <= 1; ++i)
            vcfCollections[i].samples = parameters.variantIndex.pPopIdx->getSamples();
    }

    size_t start_i = parameters.bReferenceMode ? 1 : 0;

    DindelRealignWindowResult *pThisResult = NULL;
    DindelRealignWindowResult *pPreviousResult = NULL;

    for(size_t i = start_i; i <= 1; ++i)
    {
        SeqRecordVector& fwdReads = (i == 0) ? normalReads : variantReads;
        SeqRecordVector& rcReads = (i == 0) ? normalRCReads : variantRCReads;
        const BWTIndexSet* indices = &parameters.variantIndex;

        // Create dindel reads
        // Mates must be at the end of the array.
        std::vector<DindelRead> dReads;
        for(size_t j = 0; j < fwdReads.size(); ++j)
            dReads.push_back(convertToDindelRead(indices, fwdReads[j], true));

        for(size_t j = 0; j < rcReads.size(); ++j)
        {
            rcReads[j].seq.reverseComplement();
            std::reverse(rcReads[j].qual.begin(), rcReads[j].qual.end());
            dReads.push_back(convertToDindelRead(indices, rcReads[j], false));
        }

        pThisResult = new DindelRealignWindowResult();

        std::stringstream out_ss;
        try
        {
            DindelRealignWindow dRealignWindow(&dWindow, dReads, parameters.dindelRealignParameters);
            dRealignWindow.run("hmm", vcfCollections[i], pReadAlignments, id, pThisResult, pPreviousResult, parameters.pRefTable);
        }
        catch(std::string e)
        {
            std::cerr << "Dindel Exception: " << e << "\n";
            exit(DRC_EXCEPTION);
        }


        if(i == 0)
            pPreviousResult = pThisResult;
    }

    // Copy raw VCFRecords to output
    for(size_t i = 0; i <= 1; ++i)
    {
        std::ostream& curr_out = i == 0 ? baseOut : variantOut;
        for(size_t j = 0; j < vcfCollections[i].records.size(); ++j)
            curr_out << vcfCollections[i].records[j] << "\n";
    }

    // Make comparative calls
    size_t VARIANT_IDX = 1;
    size_t BASE_IDX = 0;
    bool has_base_calls = !vcfCollections[BASE_IDX].records.empty();
    for(size_t i = 0; i < vcfCollections[1].records.size(); ++i)
    {
        bool not_called_in_base = true;
        if(has_base_calls)
            not_called_in_base = vcfCollections[BASE_IDX].records[i].passStr == "NoCall" ||
                                 vcfCollections[BASE_IDX].records[i].passStr == "NoSupp";

        bool called_in_variant = vcfCollections[VARIANT_IDX].records[i].passStr == "PASS";
        if(called_in_variant && not_called_in_base)
            callsOut << vcfCollections[VARIANT_IDX].records[i] << "\n";
    }

    baseOut.flush();
    variantOut.flush();

    delete pThisResult;
    delete pPreviousResult;

    return DRC_OK;
}
void MatLabUdmTruthTable::setupTruthTable( void ) {
	State udmTruthTable = getUdmTruthTable();

	udmTruthTable.Name() = udmTruthTable.name() = getUniqueName().c_str();
	udmTruthTable.RefId() = getRefId();
	udmTruthTable.Decomposition() = "FUNC_STATE";
	udmTruthTable.Order() = "-2";

	udmTruthTable.EnterAction() = RegexCommon::eliminateContinuations(  MatLabEngine::globalEngine().getMxStringValue( getMatLabObject() + ".LabelString" )  );

	std::string conditionTable = MatLabEngine::globalEngine().getData( getMatLabObject() + ".ConditionTable" );
	StringVectorManager conditionSTM = getStringVectorManager( conditionTable );

	std::string actionTable = MatLabEngine::globalEngine().getData( getMatLabObject() + ".ActionTable" );
	StringVectorManager actionSTM = getStringVectorManager( actionTable );

	std::string functionBody;

	StringMatrix conditionStringMatrix = conditionSTM.getStringMatrix();
	int noConditions = (int) conditionStringMatrix[0]->size() - 2;
	int noConditionTerms = (int) conditionStringMatrix.size() - 1;

	static boost::regex crnlPattern( "\\r|\\n", boost::regex_constants::perl );

	for( int ix = 0 ; ix < noConditions ; ++ix ) {

		if ( ix != 0 ) functionBody += "else";
		functionBody += "if ";

		std::string condition;
		for( int jx = 0 ; jx < noConditionTerms ; ++jx ) {
			StringVector &stringVector = *conditionStringMatrix[ jx ];
			std::string tf = stringVector[ ix + 2 ];

			std::string rawCondition = "(" + boost::regex_replace( stringVector[1], crnlPattern, " " ) + ")";

			if (  tf.find( '-' ) != std::string::npos  ) continue;
			if (  tf.find( 'F' ) != std::string::npos  ) rawCondition = "!" + rawCondition;

			if ( !condition.empty() ) condition += " && ";
			condition += rawCondition;
		}
		if ( condition.empty() ) condition = "1";
		functionBody += condition + "\n";

		StringVector actionVector;
		std::string actions = ( *conditionStringMatrix.back() )[ ix + 2 ];

		static boost::regex actionPattern( "[0-9]+|[A-Za-z_][A-Za-z_0-9]*" );
		boost::match_results< std::string::const_iterator > results;
		while (  boost::regex_search( actions, results, actionPattern )  ) {
			actionVector.push_back( results[0] );
			actions = results.suffix();
		}

		static boost::regex newlinePattern( "\n" );
		for( StringVector::iterator stvItr = actionVector.begin() ; stvItr != actionVector.end() ; ++stvItr ) {
			std::string actionSpec = *stvItr;
			if (  isdigit( actionSpec[0] )  ) {
				int actionNo = boost::lexical_cast< int >( actionSpec ) - 1;
				std::string action = (*actionSTM.getStringMatrix()[ actionNo ])[ 1 ];
				action = boost::regex_replace( action, newlinePattern, "\n  " );
				functionBody += "  " + action + "\n";
			} else {
				std::string action = (*actionSTM.getStringVectorMap()[ actionSpec ])[ 1 ];
				action = boost::regex_replace( action, newlinePattern, "\n  " );
				functionBody += "  " + action + "\n";
			}
		}

	}

	functionBody += "end\n";

	udmTruthTable.DuringAction() = functionBody;
}
//-----------------------------------------------------------------------
void GLSLProgramWriter::writeForwardDeclarations(std::ostream& os, Program* program)
{
	os << "//-----------------------------------------------------------------------------" << std::endl;
	os << "//                         FORWARD DECLARATIONS" << std::endl;
	os << "//-----------------------------------------------------------------------------" << std::endl;

	StringVector forwardDecl; // holds all generated function declarations 
	const ShaderFunctionList& functionList = program->getFunctions();
	ShaderFunctionConstIterator itFunction;

	// Iterate over all functions in the current program (in our case this is always the main() function)
	for ( itFunction = functionList.begin(); itFunction != functionList.end(); ++itFunction)
	{
		Function* curFunction = *itFunction;
		const FunctionAtomInstanceList& atomInstances = curFunction->getAtomInstances();
		FunctionAtomInstanceConstIterator itAtom = atomInstances.begin();
		FunctionAtomInstanceConstIterator itAtomEnd = atomInstances.end();

		// Now iterate over all function atoms
		for ( ; itAtom != itAtomEnd; ++itAtom)
		{	
			// Skip non function invocation atoms.
			if ((*itAtom)->getFunctionAtomType() != FunctionInvocation::Type)
				continue;

			FunctionInvocation* pFuncInvoc = static_cast<FunctionInvocation*>(*itAtom);			
			FunctionInvocation::OperandVector::iterator itOperator = pFuncInvoc->getOperandList().begin();
			FunctionInvocation::OperandVector::iterator itOperatorEnd = pFuncInvoc->getOperandList().end();

			// Start with function declaration 
			String funcDecl = pFuncInvoc->getReturnType() + " " + pFuncInvoc->getFunctionName() + "(";

			// Now iterate overall operands
			for (; itOperator != itOperatorEnd; )
			{
				ParameterPtr pParam = (*itOperator).getParameter();				
				Operand::OpSemantic opSemantic = (*itOperator).getSemantic();
				int opMask = (*itOperator).getMask();
				GpuConstantType gpuType = GCT_UNKNOWN;

				// Write the semantic in, out, inout
				switch(opSemantic)
				{
				case Operand::OPS_IN:
					funcDecl += "in ";
					break;

				case Operand::OPS_OUT:
					funcDecl += "out ";
					break;

				case Operand::OPS_INOUT:
					funcDecl += "inout ";
					break;

				default:
					break;
				}				
				
				//  Swizzle masks are only defined for types like vec2, vec3, vec4.
				if (opMask == Operand::OPM_ALL)
				{
					gpuType = pParam->getType();
				}
				else 
				{
					// Now we have to convert the mask to operator
					gpuType = Operand::getGpuConstantType(opMask);
				}

				// We need a valid type otherwise glsl compilation will not work
				if (gpuType == GCT_UNKNOWN)
				{
					OGRE_EXCEPT( Exception::ERR_INTERNAL_ERROR, 
						"Can not convert Operand::OpMask to GpuConstantType", 
						"GLSLProgramWriter::writeForwardDeclarations" );	
				}

				// Write the operand type.
				funcDecl += mGpuConstTypeMap[gpuType];

				++itOperator;
				//move over all operators with indirection
				while ((itOperator != itOperatorEnd) && (itOperator->getIndirectionLevel() != 0)) 
				{
					++itOperator;
				}

				// Prepare for the next operand
				if (itOperator != itOperatorEnd)
				{
					funcDecl += ", ";
				}
			}
			// Write function call closer.
			funcDecl += ");\n";

			// Push the generated declaration into the vector
			// duplicate declarations will be removed later.
			forwardDecl.push_back(funcDecl);
		}
	}

	// Now remove duplicate declaration, first we have to sort the vector.
	std::sort(forwardDecl.begin(), forwardDecl.end());
	StringVector::iterator endIt = std::unique(forwardDecl.begin(), forwardDecl.end()); 

	// Finally write all function declarations to the shader file
	for (StringVector::iterator it = forwardDecl.begin(); it != endIt; it++)
	{
		os << *it;
	}
}