Пример #1
0
//devuelve la suma de los elementos de 'mi_multimap' que usan 'llave' como llave
int sumaElementosMultimap(multimap<string, int> mi_multimap, string llave)
{
    int cont = 0; // Creo una variable cont
   while(mi_multimap.count(llave) != 0) //mientras el conteo de las llaves no sea cero
        {
           int c = mi_multimap.find(llave)-> second; //La variable c toma el valor del segundo elemento de la llave
            cont = cont + c; //Suma los valores

            mi_multimap.erase(mi_multimap.find(llave)); //se borra el ultimo elemento
        }
    return cont; //devuelve la suma


}
Пример #2
0
//handle login requests
int logoutReq(struct request_logout *rl)
{
    string username = getUserOfCurrAddr();
    multimap<string, struct sockaddr_in>::iterator sockIt = userToAddrStrct.find(username);
    userToAddrStrct.erase(sockIt);
    map<string,vector<string> >::iterator git;
    git = usrTlkChan.find(username);
    if(git != usrTlkChan.end()) {
        usrTlkChan.erase(username);
    }
    //erase user on channels in chanTlkUser
    //for(int ick=0; ick<channels.size(); ick++) {
    map<string,vector<pair<string,struct sockaddr_in> > >::iterator sat;
    for(sat=chanTlkUser.begin(); sat != chanTlkUser.end(); sat++) {
        map<string,vector<pair<string,struct sockaddr_in> > >::iterator itck = chanTlkUser.find(sat->first);
        vector<pair<string,struct sockaddr_in> > usersC = itck->second;
        for(int j=0; j<usersC.size(); j++) {
            if(usersC[j].first == username) {
                usersC.erase(usersC.begin()+j);
            }
        }
        chanTlkUser.erase(itck);
        chanTlkUser.insert(pair<string,vector<pair<string,struct sockaddr_in> > >(sat->first,usersC));
    }
    return 0;
}
Пример #3
0
/* Look for mime handler in pool */
static RecollFilter *getMimeHandlerFromCache(const string& key)
{
    PTMutexLocker locker(o_handlers_mutex);
    string xdigest;
    MD5HexPrint(key, xdigest);
    LOGDEB(("getMimeHandlerFromCache: %s cache size %u\n", 
	    xdigest.c_str(), o_handlers.size()));

    multimap<string, RecollFilter *>::iterator it = o_handlers.find(key);
    if (it != o_handlers.end()) {
	RecollFilter *h = it->second;
	hlruit_tp it1 = find(o_hlru.begin(), o_hlru.end(), it);
	if (it1 != o_hlru.end()) {
	    o_hlru.erase(it1);
	} else {
	    LOGERR(("getMimeHandlerFromCache: lru position not found\n"));
	}
	o_handlers.erase(it);
	LOGDEB(("getMimeHandlerFromCache: %s found size %u\n", 
		xdigest.c_str(), o_handlers.size()));
	return h;
    }
    LOGDEB(("getMimeHandlerFromCache: %s not found\n", xdigest.c_str()));
    return 0;
}
Пример #4
0
// Maps highest frequency of codons to each amino acid
vector<float> CodonFrequency::createMaxMap(multimap<char, pair<int, float> > AAtoCodonMap){

//	cout << "------maxFreq------" << endl;

	vector<float> maxMap;
	float maxFreq;

	// Loops through all amino acids
	// If char rep of AA exists
	// Calculate highest frequency to maxMap
	for (char AA = 'A'; AA <= 'Z'; AA++) {
		
		int addressAA = AA - 65;
		
		if (AA == 'B' || AA == 'J' || AA == 'O' || AA == 'U' || AA == 'X') {
		maxMap.push_back(-1);
//		continue;
		}

		else if (AAtoCodonMap.count(AA) > 1) {
			
			maxFreq = findMax(AAtoCodonMap, AA);
			maxMap.push_back(maxFreq);
//			continue;
			
		} else if (AAtoCodonMap.count(AA) == 1) {
			maxMap.push_back(AAtoCodonMap.find(AA)->second.second);
		}
//		to print values: comment out the continues in if statements
//		cout << addressAA << " " << AA << " " << maxMap[addressAA] << endl;
	}
	return maxMap;
}
Пример #5
0
        int get(int key){ 
            multimap<int, V2C>::iterator it = key2Value2Count.find(key);
            if(it != key2Value2Count.end())
            {
                V2C& tmp = it->second;
#if 0
                pair <multimap<int,int>::iterator, multimap<int,int>::iterator> ret;
                ret = count2Key.equal_range(tmp.count);
                for(multimap<int,int>::iterator it=ret.first; it!=ret.second;++it)
                {
                    if(it->second == key)
                    {
                        count2Key.erase(it);
                        tmp.count++;
                        count2Key.insert(pair<int, int>(tmp.count, key));
                        break;
                    }
                }
#endif
                count2Key.erase(tmp.it);
                list<int>::iterator iit = count2Key.insert(count2Key.end(),key);
                tmp.it=iit;
#if 0
                cout << "cache hit" << key << endl;
#endif
                return tmp.value;
            }
            else
            {
        //        cout << "cache miss" << key << endl;
                return -1;
            }
        }
Пример #6
0
        void set(int key, int value)
        {
            multimap<int, V2C>::iterator it = key2Value2Count.find(key);

          if(it != key2Value2Count.end())
          {
              V2C& tmp = it->second;
              tmp.value = value;
              get(key);
                
           }
          else
            {
                if(count >= max)
                {
                    list<int>::iterator cit=count2Key.begin();

    //                cout << "cache eviction: " << *cit << endl;
                    key2Value2Count.erase(*cit);
                    count2Key.erase(cit);
                    count--;
                }
                
                list<int>::iterator iit = count2Key.insert(count2Key.end(),key);

                V2C tmp;
                tmp.value = value;
                tmp.it = iit;
      //          cout << "xxxx" <<*iit<<endl;
                    
                key2Value2Count.insert(pair<int, V2C>(key, tmp));
                count++;
            }
        }
Пример #7
0
//handle login requests
int whoReq(struct request_who *rw)
{
    string username = getUserOfCurrAddr();
    struct sockaddr_in address; 
    string chaNel = (string)(rw->req_channel);
    multimap<string, struct sockaddr_in>::iterator ui = userToAddrStrct.find(username);
    map<string,vector<pair<string,struct sockaddr_in> > >::iterator vi;
    if((vi = chanTlkUser.find(chaNel)) == chanTlkUser.end()) {
        return -1;
    }
    int numCHAN = (vi->second).size();
    vector<pair<string,struct sockaddr_in> > v = vi->second;
    address = ui->second;
    struct text_who *msg = (struct text_who*)malloc(sizeof(struct text_who)+(numCHAN* sizeof(struct user_info)));
    msg->txt_type= TXT_WHO;
    msg->txt_nusernames = numCHAN;
    const char* str = chaNel.c_str();
    strcpy(msg->txt_channel, str);
    for (int i = 0; i<v.size(); i++) {
        const char* tstr = v[i].first.c_str();
        strcpy(((msg->txt_users)+i)->us_username, tstr);
    }
    int size = sizeof(struct sockaddr);
    int res= sendto(sockfd, msg,  (sizeof(struct text_who)+(numCHAN* sizeof(struct user_info))), 0, (struct sockaddr*)&address, size);
    if (res == -1) {
        return -1;
    }
    free(msg);
    return 0;
}
Пример #8
0
void eliminate_left_recursion(multimap<string,string> &rules)
{
    //cout<<"Left Recurse"<<endl;
    multimap<string,string>::iterator it;
    multimap<string,string>::iterator it1;
    string non_term,non_term_1;
    string RHS,leftmost,RHS1,remaining;
    const char *rhs;
    //string tok_rhs;
    char *tok_rhs;
    char r[1000];
    string new_rhs;
    for(int i=0;i<n_t.size();i++)
    {
        for(int j=0;j<i;j++)
        {
            it=rules.find(n_t[i]);
            non_term=(*it).first;
            for(;it!=rules.end() && (((*it).first.compare(non_term))==0);it++)
            {
                RHS=(*it).second;
                rhs=RHS.c_str();
                strcpy(r,rhs);
                tok_rhs=strtok(r," ");
                remaining.copy(r,strlen(r));
                leftmost.copy(tok_rhs,strlen(tok_rhs));
                if(leftmost.compare(n_t[j])==0)
                {
                    new_rhs.clear();
                    it1=rules.find(n_t[j]);
                    non_term_1=(*it1).first;
                    for(;it1!=rules.end() && (((*it1).first.compare(non_term_1))==0);it1++)
                    {
                        RHS1=(*it1).second;
                        new_rhs.append(RHS1).append(remaining);
                        rules.erase(it);
                        rules.insert(pair<string,string>(non_term,new_rhs));
                    }

                }
            }
        }
        eliminate_immediate_left_recursion(rules,i);
    }
}
void copyrandom(struct node *newnode,struct node *root)
{
	if(root==NULL)
		return;
	multimap<struct node *,struct node *>::iterator i;
	i=m.find(root->random);
	newnode->random=i->second;
	copyrandom(newnode->left,root->left);
	copyrandom(newnode->right,root->right);
}
Пример #10
0
static void removeFromTickQueue(EventHandler getRidOf) {
    for ( auto j = tickQueue.find(getRidOf.freq); j != tickQueue.end(); ) {
        if ( (*j).first > getRidOf.freq )
            break;
        if ( (*j).second != getRidOf ) {
            j++;
            continue;
        }
        j = tickQueue.erase(j);
    }
}
Пример #11
0
void eraseName(multimap<string, string>& m_map)
{
	string authorname;
	cout << "Which author do you want to delete ?" << endl;
	cin >> authorname;
	multimap<string, string>::iterator it = m_map.find(authorname);
	if (it != m_map.end())
		m_map.erase(authorname);
	else
		cout << "Can't find the author !" << endl;
}
Пример #12
0
void printmultimap(multimap <string, string> &authors)
{
	typedef multimap <string, string>::size_type sz_type;
	sz_type co = authors.count("Barth, John");
	//cout << count;
	multimap <string, string>::iterator iter = authors.find("Barth, John");
	for (sz_type cnt = 0; cnt != co; ++cnt,++iter)
	{
		cout << iter->first << ":--->" << iter->second << endl;
	}
}
Пример #13
0
//O(logn)
void Library::markRead(string titleToMark){
    map<string,string>::iterator it = unreadKeyTitle.find(titleToMark);
    string toFind = it->second;
    multimap<string,string>::iterator i = unreadKeyAuth.find(toFind);

    if (it!=unreadKeyTitle.end()){
            read.insert(pair<string, string>(it->second, it->first));
            cout << "You've read " << '\"' << it->first << "!" << '\"' << endl;
            unreadKeyAuth.erase(i);
            unreadKeyTitle.erase(it);
        }
}
Пример #14
0
//check if current request address is valid or exist in map
int checkValidAddr(struct request *r) 
{
    string realAddrString = getAddr_string();
    string smiAddrString = getSemiAddr_string();
    map<pair<string,string>,string>::iterator it = addrToUser.find(pair<string,string>(realAddrString,smiAddrString));
    if(it == addrToUser.end()) {
        cout << "super baddd addressss mann\n";
        cout << realAddrString << " that THING\n";
        return -1;
    } 
    return 0;
}
Пример #15
0
void solve(multimap<string, string>& dic, string seq, string ans)
{
  for (unsigned int i = 1; i <= seq.size(); ++i) {
    string h = seq.substr(0, i), rem = seq.substr(i);
    for (multimap<string, string>::iterator it = dic.find(h); it != dic.end() && (*it).first == h; ++it) {
      if (rem.empty()) 
	cout << ans << (*it).second << "." << endl;
      else
	solve(dic, rem, ans + (*it).second + " ");
    }
  }
  return;
}
Пример #16
0
// Maps average frequency of codons to each amino acid
vector<float> CodonFrequency::createAvgMap(multimap<char, pair<int, float> > AAtoCodonMap) {
	
//	cout << "------avgFreq------" << endl;
	
	int addressAA;
	int codonPerAA;	// Numbers of codons that code for an amino acid
	float sumFreq;	// Sum of codon frequencies for an amino acid
	float avgFreq;	// sumFreq/codonPerAA to calculate average frequency for an amino acid
	vector<float> avgMap;
	
	for (char AA = 'A'; AA <= 'Z'; AA++) {

		addressAA = AA-65;
		codonPerAA = 0;
		sumFreq = 0;
		avgFreq = 0;

		if (AA == 'B' || AA == 'J' || AA == 'O' || AA == 'U' || AA == 'X') { 
			avgMap.push_back(-1);
//			continue;
		}

		else if (AAtoCodonMap.count(AA) > 1) {
		
			pair< multimap<char, pair<int, float> >::iterator, 
			multimap<char, pair<int, float> >::iterator> ret;
	
			ret = AAtoCodonMap.equal_range(AA);
			
			for (multimap<char, pair<int, float> >::iterator it = ret.first; it != ret.second; ++it) {
//				cout << AA << " " << it->second.second << endl;
				sumFreq += it->second.second;
				codonPerAA++;
			}

			avgFreq = sumFreq/codonPerAA;
//			cout << sumFreq << " / " << codonPerAA << " = " << avgFreq << endl;
			avgMap.push_back(avgFreq);
//			continue;
			
		} else if (AAtoCodonMap.count(AA) == 1) {
			avgMap.push_back(AAtoCodonMap.find(AA)->second.second);
//			continue;
		}
//		cout << addressAA << " " << AA << " " << avgMap[addressAA] << endl;
	}
	return avgMap;
}
Пример #17
0
void CCacheThread::SetOnlyValueProcess(const multimap<unsigned int, string> &mapRequestValue, multimap<unsigned int, string> &mapStoredValue)
{
	CVS_XLOG(XLOG_DEBUG, "CCacheThread::%s\n", __FUNCTION__);
	multimap<unsigned int, string>::iterator itr;
	multimap<unsigned int, string>::const_iterator citr; 
	for (citr = mapRequestValue.begin(); citr != mapRequestValue.end(); ++citr)
	{
		itr = mapStoredValue.find(citr->first);
		if (itr == mapStoredValue.end())
		{
			mapStoredValue.insert(make_pair(citr->first, citr->second));
		}
		else
		{
			itr->second = citr->second;
		}
	}
}
Пример #18
0
TImage* TImageManager::loadImage (const string& rktNAME, const string& rktFORMAT)
{

  string        tFileName;
  TImageData*   ptImageData;
  TImage*       ptImage = NULL;

  cout << "Loading image : " << rktNAME << endl;

  bool   gAbsolutePath = ( rktNAME[0] == '/' );

  if ( gAbsolutePath )
  {
    ptImage = TImageManager::_load (rktNAME, rktFORMAT);
  }
  else
  {
    multimap<string, string>::const_iterator   iter;

    iter = tConfigData.find ("TexturePath");
    while ( ( iter != tConfigData.end() ) && ( (*iter).first == "TexturePath" ) )
    {
      if ( FileExists ((*iter).second + "/" + rktNAME) )
      {
        ptImage = TImageManager::_load ((*iter).second + "/" + rktNAME, rktFORMAT);
        break;
      }
      iter++;
    }
  }

  if ( ptImage )
  {
    ptImageData = new TImageData();

    ptImageData->ptImage    = ptImage;
    ptImageData->gLoaded    = true;
    tImageDataMap [rktNAME] = ptImageData;
  }

  return ptImage;

}  /* loadImage() */
Пример #19
0
//handle login requests
int listReq(struct request_list *rl)
{
    string username = getUserOfCurrAddr();
    struct sockaddr_in address; 
    multimap<string, struct sockaddr_in>::iterator ui = userToAddrStrct.find(username);
    int numCHAN = channels.size();
    address = ui->second;
    struct text_list *msg = (struct text_list*)malloc((sizeof(struct text_list)+(numCHAN *sizeof(struct channel_info))));
    msg->txt_type= TXT_LIST;
    msg->txt_nchannels = numCHAN;
    for (int i = 0; i<channels.size(); i++) {
        const char* tstr = channels[i].c_str();
        strcpy(((msg->txt_channels)+i)->ch_channel, tstr);
    }
    int size = sizeof(struct sockaddr);
    int res= sendto(sockfd, msg,  (sizeof(struct text_list)+(numCHAN *sizeof(struct channel_info))), 0, (struct sockaddr*)&address, size);
    if (res == -1) {
        return -1;
    }
    free(msg);
    return 0;
}
Пример #20
0
//handle login requests
int leaveReq(struct request_leave *rl)
{
    string username = getUserOfCurrAddr();
    struct sockaddr_in reqAddr = getAddrStruct();
    string chaNel = (string)(rl->req_channel);
    multimap<string, struct sockaddr_in>::iterator ui = userToAddrStrct.find(username);
    struct sockaddr_in address = ui->second;
    map<string,vector<pair<string,struct sockaddr_in> > >::iterator vi;
    if((vi = chanTlkUser.find(chaNel)) == chanTlkUser.end()) {
        return -1;
    }
    vector<pair<string,struct sockaddr_in> > v = vi->second;
    for(int vecI=0; vecI<v.size(); vecI++) {
        if(v[vecI].first == username) {
            if(checkAddrEq(v[vecI].second, reqAddr) == 0) {
                v.erase (v.begin()+vecI);
            } 
        }
    }
    chanTlkUser.erase(vi);
    if(v.size() != 0) {
        chanTlkUser.insert(pair<string,vector<pair<string,struct sockaddr_in> > >(chaNel,v));
        return 0;
    } else {
        for(int i=0; i<channels.size(); i++) {
            if(channels[i] == chaNel) {
                channels.erase(channels.begin()+i);
            }
        }
    }
    vector<string> chanTlk = usrTlkChan[username];
    for(int vv=0; vv<chanTlk.size(); vv++) {
        if(chanTlk[vv] == chaNel) {
            chanTlk.erase(chanTlk.begin()+vv);
        }
    }
    usrTlkChan[username] = chanTlk;
    return 0;
}
Пример #21
0
	void preprocess() {
		for (int i = 0; i < raw_heads.size(); i++) {
			raw_head_to_body.insert(pair<int,int>(toInt((Lit) raw_heads[i]), i));
		}

		for (int i = 0; i < raw_heads.size(); i++) {
			if (raw_posb[i].size() == 1 && raw_negb[i].size() == 0) {
				if (raw_head_to_body.count(toInt((Lit) raw_posb[i][0])) == 1) {
					int r = raw_head_to_body.find(toInt((Lit) raw_posb[i][0]))->second;
					raw_bl[i] = raw_posb[i][0];
					raw_posb[r].copyTo(raw_posb[i]);
					raw_negb[r].copyTo(raw_negb[i]);
					raw_heads[r] = bv_false;
				}
			}
		}

		for (int i = 0; i < raw_heads.size(); i++) {
			if (raw_heads[i] == bv_false) continue;
			getId(raw_heads[i]);
		}

	}
Пример #22
0
//handle login requests
int listReq(struct request_list *rl)
{
    struct sockaddr* address; 
    multimap<string, pair<string,string> >::iterator ui = userToAddr.find(getUserOfCurrAddr());
    pair<string,string> tad = ui->second;
    string ad = tad.second;
    char *s= (char*) malloc(sizeof(char)*BUFLEN);
    strncpy(s, ad.c_str(), strlen(ad.c_str()));
    inet_pton(AF_INET, s, &address);
    struct text_list *msg= (struct text_list*) malloc(sizeof(struct text_list) + BUFLEN);
    msg->txt_type= htonl(TXT_LIST);
    msg->txt_nchannels = htonl(channels.size());
    for (int i = 0; i < channels.size(); i++) {
        strncpy(msg->txt_channels[i].ch_channel, channels[i].c_str(), CHANNEL_MAX);
    }
    int size = sizeof(struct sockaddr);
    int res= sendto(sockfd, msg, sizeof(struct text_list), 0, address, size);
    if (res == -1) {
        cout << "sendto very badd \n";
        //return -1;
    }
    free(msg);
    return 0;
}
Пример #23
0
void CCacheThread::CasValueProcess(const multimap<unsigned int, string> &mapRequestValue, multimap<unsigned int, string> &mapStoredValue)
{
	CVS_XLOG(XLOG_DEBUG, "CCacheThread::%s\n", __FUNCTION__);
	multimap<unsigned int, string>::iterator itr;
	multimap<unsigned int, string>::const_iterator citr;
	for (citr=mapRequestValue.begin(); citr!=mapRequestValue.end(); ++citr)
	{
		itr = mapStoredValue.find(citr->first);
		if(itr==mapStoredValue.end()) 
		{
			mapStoredValue.insert(make_pair(citr->first, citr->second));
		}
		else
		{
			unsigned int dwStoreValue = atoi(itr->second.c_str());
			unsigned int dwNeedAddValue = atoi(citr->second.c_str());
			dwStoreValue += dwNeedAddValue;

			char szTemp[32] = {0};
			snprintf(szTemp, sizeof(szTemp), "%d", dwStoreValue);
			itr->second = szTemp;
		}
	}
}
Пример #24
0
bool hasOpt(multimap<string,string>&optmap,const string& key){
	return !(optmap.find(key)==optmap.end());	
}
Пример #25
0
set<string> calc_first(string symbol)
{
    //cout<<"Symbol: "<<symbol<<endl;
    if(symbol.compare("$")==0)
    {
        set<string> ftemp;
        ftemp.insert("$");
        vector<string>::iterator ite=find(first_recursed.begin(),first_recursed.end(),symbol);
        if(ite!=first_recursed.end())
            first_recursed.erase(ite);
        return ftemp;
    }
    else if(find(t.begin(),t.end(),symbol)!=t.end())
    {
        set<string> ftemp;
        ftemp.insert(symbol);
        vector<string>::iterator ite=find(first_recursed.begin(),first_recursed.end(),symbol);
        if(ite!=first_recursed.end())
            first_recursed.erase(ite);
        return ftemp;
    }
    set<string> final_set;
    multimap<string,string>::iterator it;
    it = rules.find(symbol);
    string token;
    vector<string> tokens;
    while(it!=rules.end() && (it->first).compare(symbol)==0)
    {
        token.clear();
        tokens.clear();
        for(int i = 0; i < (it->second).size(); i++)
        {
            if((it->second)[i]!=' ' && i!=(it->second).size()-1)
            {
                token.push_back((it->second)[i]);
            }
            else
            {
                if(i==(it->second).size()-1)
                    token.push_back((it->second)[i]);
                tokens.push_back(token);
                token.clear();
            }
        }
        set<string> returned_fset;
        //cout<<"token-0: "<<tokens[0]<<" "<<tokens.size()<<endl;
        vector<string>::iterator ite=find(first_recursed.begin(),first_recursed.end(),tokens[0]);
        if(ite!=first_recursed.end())
        {

        }
        else
        {
            first_recursed.push_back(tokens[0]);
            returned_fset = calc_first(tokens[0]);
        }
        int j=0;
        int cnt=0;
        for(j = 1; j  < tokens.size(); j++)
        {
            //cout<<j<<" "<<tokens[j]<<endl;
            nullable_recursed.push_back(tokens[j-1]);
            if(is_nullable(tokens[j-1]))
            {
                cnt++;
                vector<string>::iterator ite=find(first_recursed.begin(),first_recursed.end(),tokens[j]);
                if(ite!=first_recursed.end())
                {

                }
                else
                {
                    first_recursed.push_back(tokens[j]);
                    Union(returned_fset,calc_first(tokens[j]),returned_fset);
                }
            }
            else
                break;
        }
        if(cnt==tokens.size())
        {
            returned_fset.insert("$");
        }
        Union(returned_fset,final_set,final_set);
        //cout<<"Inc it"<<endl;
        it++;
    }
    //cout<<"returning"<<endl;
    map< string,set<string> > :: iterator iter = first_sets.find(symbol);
    if(iter!=first_sets.end())
    {
        Union(final_set,first_sets[symbol],final_set);
        first_sets[symbol] = final_set;
    }
    else
    {
        first_sets[symbol] = final_set;
    }
    vector<string>::iterator ite=find(first_recursed.begin(),first_recursed.end(),symbol);
    if(ite!=first_recursed.end())
        first_recursed.erase(ite);
    return final_set;
}
Пример #26
0
void left_factor()
{
    /*************************************/
    /* Algorithm
    /* Generate all the prefixes of
       all the rules.
    /* Take each prefix one by one
    /* Check if it is the common
    /* prefix of atleast two of the
    /* rules.
    /* Update the longest common prefix.*/
    /*************************************/
    bool non_terminal_used;
    string RHS;
    string pre;
    multimap<string,string>::iterator it;
    string new_left_rule;

//    for(int i=0;i<prefixes.size();i++)
//    {
//        cout<<"Prefix:"<<prefixes[i]<<endl;
//    }
    string prefix_of_rhs;
    int len_of_prefix;
    int len_of_longest_prefix;
    string longest_prefix; // keeps track of what is the longest prefix.
    int longest_prefix_index=-1;
    int count_of_matches; // keeps track of how many rules match for a given prefix.
    string left,remaining; // left holds the prefix. // remaining holds the remaining RHS.
    string new_non_terminal;
    for(int n=0;n<n_t.size();n++)
    {
        memset(is_considered,0,sizeof(is_considered));
        memset(is_matched,0,sizeof(is_matched));
        prefixes.clear();
        current_non_term_rules.clear();
        it=rules.find(n_t[n]);
        for(;it!=rules.end() && ((*it).first.compare(n_t[n])==0);it++)
        {
            current_non_term_rules.insert(pair<string,string>((*it).first,(*it).second));
        }
        for(it=current_non_term_rules.begin();it!=current_non_term_rules.end();it++)
        {
            pre.clear();
            RHS=(*it).second;
            //cout<<(*it).first<<"-->"<<(*it).second<<endl;
            //cout<<RHS.size();
            for(int i=0;i<RHS.size();i++)
            {
                pre.clear();
                for(int j=0;j<=i;j++)
                {
                    pre.push_back(RHS[j]);
                }
                if(find(prefixes.begin(),prefixes.end(),pre)==prefixes.end())
                    prefixes.push_back(pre);
            }
        }
//        for(it=current_non_term_rules.begin();it!=current_non_term_rules.end();it++)
//        {
//            cout<<(*it).first<<"-->"<<(*it).second;
//        }
        for(int m=0;m<current_non_term_rules.size();m++)
        {
            //cout<<"Round "<<m<<endl;
            longest_prefix.clear();
            for(int i=0;i<prefixes.size();i++)
            {
                //cout<<"Current Prefix:"<<prefixes[i]<<endl;
                len_of_prefix=prefixes[i].size();
                count_of_matches=0;
                for(it=current_non_term_rules.begin();it!=current_non_term_rules.end();it++)
                {
        //            if(is_matched[it-rules.begin()])
        //                continue;
                    prefix_of_rhs.clear();
                    RHS.clear();
                    RHS=(*it).second;
                    //cout<<(*it).first<<"-->"<<(*it).second<<endl;
                    if(RHS.size()<len_of_prefix|| is_considered[distance(current_non_term_rules.begin(),it)])
                        continue;
                    for(int j=0;j<len_of_prefix;j++)
                    {
                        prefix_of_rhs.push_back(RHS[j]);
                    }
                    //cout<<"Prefix of RHS:"<<prefix_of_rhs<<endl;
                    if(prefix_of_rhs.compare(prefixes[i])==0)
                    {
                        //cout<<prefix_of_rhs<<"matched with "<<prefixes[i]<<endl;
                        //cout<<"Rule No:"<<distance(rules.begin(),it)<<endl;
                        is_matched[i][distance(current_non_term_rules.begin(),it)]=true;
                        count_of_matches++;
                    }
                }
    //            cout<<"RUles after longest prefix"<<endl;
    //            for(it=rules.begin();it!=rules.end();it++)
    //            {
    //                cout<<"Rule No:"<<<<"-"<<(*it).first<<"-->"<<(*it).second<<endl;
    //            }
                //cout<<"Prefix is:"<<prefixes[i]<<" has count:"<<count_of_matches<<endl;
                if(count_of_matches>1 && prefixes[i].size()>=1)
                {
                    if(longest_prefix.size()<prefixes[i].size())
                    {
                        longest_prefix.clear();
                        longest_prefix=prefixes[i];
                        longest_prefix_index=i;
                    }
                }
            }
            //cout<<"Index:"<<longest_prefix_index<<"and longest prefix is :"<<longest_prefix<<"!"<<endl;
            if(longest_prefix_index!=-1 && longest_prefix.size()>=1)
            {
                /* Get rules which matched the longest prefix.*/
                non_terminal_used=false;
                new_non_terminal=next_nt_string();
                for(int j=0;j<current_non_term_rules.size();j++)
                {
                    if(is_matched[longest_prefix_index][j] && !is_considered[j])
                    {
                        non_terminal_used=true;
                        it=current_non_term_rules.begin();
                        advance(it,j);
                        RHS=(*it).second;
                        //cout<<"Rule No:"<<j<<"-"<<(*it).first<<"-->"<<(*it).second<<endl;
                        len_of_longest_prefix=longest_prefix.size();
                        left.clear();
                        remaining.clear();
                        for(int k=0;k<len_of_longest_prefix;k++)
                        {
                            left.push_back(RHS[k]);
                        }
                        if(RHS[len_of_longest_prefix]==' ')
                            len_of_longest_prefix++;
                        for(int k=len_of_longest_prefix;k<RHS.size();k++)
                        {
                            remaining.push_back(RHS[k]);
                        }
                        if(remaining.size()==0)
                            remaining="$"; //epsilon.
                        //cout<<"Remaining:"<<remaining<<" and new non terminal: "<<new_non_terminal<<endl;
                        /* Erase the current rule an push back the new rule in rules.*/
                        assert(left.compare(longest_prefix)==0);
                        //cout<<"Prefix:"<<left<<"and remaining: "<<remaining<<endl;
                        new_left_rule.clear();
                        if(longest_prefix[longest_prefix.size()-1]!=' ')
                            new_left_rule.append(longest_prefix).append(" ").append(new_non_terminal);
                        else
                            new_left_rule.append(longest_prefix).append(new_non_terminal);
                        left_factored_rules.insert(pair<string,string>(new_non_terminal,remaining));
                        is_considered[distance(current_non_term_rules.begin(),it)]=true;
                        //rules.erase(it);
                    }
                }
                if(non_terminal_used)
                {
                    left_factored_rules.insert(pair<string,string>((*it).first,new_left_rule));
                    left_fact_n_t.push_back(new_non_terminal);
                }
            }
        }
        update_rules(is_considered);
    }
    multimap<string,string>::iterator iter;
    for(iter=left_factored_rules.begin();iter!=left_factored_rules.end();iter++)
    {
        cout<<(*iter).first<<"-->"<<(*iter).second<<endl;
    }
}
Пример #27
0
/// insert binary operator specified by oit into Shunting-Yard
void insert_binaryoper(postfix_t &out, stack<token_t> &s, decltype(opers)::iterator oit)
{
	while (!s.empty())
	{
		bool found = false; // stack top element is operator
		int tprec; // prec of stack top element
		auto range = opers.equal_range(s.top().first);
		for (auto oit2 = range.first; oit2 != range.second; ++oit2)
		{
			if (s.top().second == (oit2->second.unary ? 1 : 2)) // find the correct arity version of the operator
			{
				tprec = oit2->second.prec;
				found = true;
				break;
			}
		}

		if ((found && ((!oit->second.right && oit->second.prec == tprec) || (oit->second.prec < tprec))) || (!found && funcs.find(s.top().first) != funcs.end()))
			out.push_back(pop(s));
		else
			break;
	}
	s.push(token_t(oit->first, 2));
}
Пример #28
0
bool ProcessConfigFile (const string& rktCONFIG, multimap<string, string>& rtMAP)
{

  string     tOptionName, tOptionValue;
  ifstream   tConfigFile;
  char*      pcBuffer = new char[200];

  tConfigFile.open (rktCONFIG.c_str());
  if ( !tConfigFile )
  {
    return false;
  }

  // Reads configuration file line by line
  while ( !tConfigFile.eof() )
  {
    Byte   J;
    bool   gAppend;
    
    tOptionName  = "";
    tOptionValue = "";
    gAppend      = false;
    
    tConfigFile.getline (pcBuffer, 200);

    // Checks for an empty line
    if ( strlen (pcBuffer) == 0 )
    {
      continue;
    }
    
    // Checks for a comment
    if ( pcBuffer[0] == '#' )
    {
      continue;
    }
    
    // Gets option name (until the first occurrence of character '=')
    for (J = 0; ( ( J < strlen (pcBuffer) ) && ( pcBuffer[J] != '=' ) ) ;J++)
    {
      tOptionName += pcBuffer[J];
    }

    // Checks if the line contains no '=' character
    if ( J == strlen (pcBuffer) )
    {
      continue;
    }
    
    // Checks if we are adding a new value for that option, or substituting previous ones
    if ( ( J > 0 ) && ( pcBuffer[J - 1] == '+' ) )
    {
      tOptionName = tOptionName.substr (0, J - 1);
      gAppend     = true;
    }
         
    // Gets option value (until the end of the line)
    for (J++; ( J < strlen (pcBuffer) ) ;J++)
    {
      tOptionValue += pcBuffer[J];
    }

    if ( !gAppend )
    {
      // Removes every previous option with the same name
      multimap<string, string>::iterator   iter;
      
      while ( (iter = rtMAP.find (tOptionName)) != rtMAP.end() )
      {
        rtMAP.erase (iter);
      }
    }

    if( tOptionValue[0] != '/' )
    {
      tOptionValue = _tLocalPath + tOptionValue;
    }

    // Inserts a new option entry in the map
    rtMAP.insert (pair<const string, string> (tOptionName, tOptionValue));
  }

  tConfigFile.close();
  delete pcBuffer;
  
  return true;
  
}  /* ProcessConfigFile() */
Пример #29
0
int main (int argc, char *argv[])
{

  ofstream   tLogFile;
  TScene*    ptScene;
  char       acTimeString [30];
  time_t     tBaseTime, tInitTime, tRenderTime, tPostProcessTime;

  GlobalClassManager = new TClassManager();

  _tProgramName = "render";

  ProcessCommandLine (argc, argv);

  SetPaths();

  if ( !FileExists (_tLocalPath + "config") )
  {
		 cerr << "WARNING: No configuration file in " << _tLocalPath << endl;
  }
  else
  {
    if ( !ProcessConfigFile (_tLocalPath + "config", tConfigData) )
    {
      cerr << "ERROR: Couldn't read configuration file." << endl;
      exit (1);
    }
  }

//  for (multimap<string, string>::const_iterator iter = tConfigData.begin(); ( iter != tConfigData.end() ) ;iter++)
//  {
//    cout << (*iter).first << " = " << (*iter).second << endl;
//  }
  
  multimap<string, string>::const_iterator   iter = tConfigData.find ("PluginConfigFile");
  string   tPluginConfigFile = ( iter != tConfigData.end() ) ? (*iter).second : _tLocalPath + "pluginrc";

  if ( !FileExists (tPluginConfigFile) )
  {
    cerr << "ERROR: Plugin configuration file '" << tPluginConfigFile << "' does not exist." << endl;
    exit (1);
  }

  cout << "Loading plugins..." << endl;
  tPluginManager.initialize (tPluginConfigFile, 0);

  TGradient::_initialize();
  TImageManager::_initialize();
  TSceneManager::_initialize();
  tImageManager.initialize();

  if ( !TSceneManager::_knownFormat (_tInputFileFormat) )
  {
    cout << "ERROR: Scene format not supported" << endl;
    exit (1);
  }
  
  cout << "Parsing..." << endl;
  ptScene = TSceneManager::_load (_tInputFileName, _tInputFileFormat);

  if ( !ptScene )
  {
    cerr << "Error parsing input file" << endl;
    exit (1);
  }

  //
  // Uncomment next line for debug information on the whole scene.
  //
//  ptScene->printDebug();

  tBaseTime = time (NULL);

  cout << "Initializing..." << endl;
  if(!ptScene->initialize())
  {
    cerr << "Initialization failed!" << endl;
    exit (1);
  }    
  tInitTime = time (NULL);

  cout << "Rendering..." << endl;
  ptScene->render (&FinishedLine);
  tRenderTime = time (NULL);
  
  cout << "Postprocessing..." << endl;
  ptScene->postprocess();
  tPostProcessTime = time (NULL);
  
  cout << "Saving..." << endl;
  if ( !ptScene->saveImage() )
  {
    cout << "Could not save image file" << endl;
  }
  
  ptScene->finalize();

  cout << endl;
  cout << " Total ellapsed time : " << difftime (tPostProcessTime, tBaseTime) << " secs" << endl;
  cout << " - Initialization . . . " << difftime (tInitTime, tBaseTime) << " secs" << endl;
  cout << " - Render         . . . " << difftime (tRenderTime, tInitTime) << " secs" << endl;
  cout << " - Postprocessing . . . " << difftime (tPostProcessTime, tRenderTime) << " secs" << endl;
  cout << "";

  if ( _gKeepLog )
  {
    strftime (acTimeString, 30, "%b %d %H:%M:%S", localtime (&tBaseTime));
    
    tLogFile.open (_tLogFileName.c_str(), ios::out | ios::binary | ios::app);

    tLogFile << acTimeString << " " << _tInputFileName << ", " << difftime (tPostProcessTime, tBaseTime) << " seconds" << endl;

    tLogFile.close();
  }

  delete GlobalClassManager;

  return 0;

}  /* main() */
Пример #30
0
/// convert infix string into postfix token list
postfix_t infix2postfix(string in)
{
	postfix_t out;
	stack<token_t> s;

	token_t lasttok;
	for (auto it = in.cbegin(); it != in.cend();)
	{
		const unsigned int i = it - in.cbegin(); // index of current character for parse_error purposes

		static const string spaces = " \t\r\n";
		if (spaces.find(*it) != string::npos)
		{
			++it;
			continue;
		}

		/*cout << string(it, in.cend()) << endl;
		cout << lasttok.first << "/" << lasttok.second << endl;
		if (!s.empty())
			cout << s.top().first << "/" << s.top().second << endl;*/

		// try to parse number
		static const string numbers = "0123456789.";
		auto it2 = it;
		for (; it2 != in.cend() && numbers.find(*it2) != string::npos; ++it2); // TODO: find_first_not_of
		if (it2 != it)
		{
			if (lasttok.first == ")" || (opers.find(lasttok.first) == opers.end() && funcs.find(lasttok.first) != funcs.end()) || lasttok.second == -1)
				throw parse_error("Missing operator", i);

			out.push_back(lasttok = token_t(string(it, it2), -1));
			it = it2;
			continue;
		}


		// try to parse operator
		auto lastoper = opers.find(lasttok.first);
		bool lunary = lasttok.first == "" || lasttok.first == "(" || lasttok.first == "," || (lastoper != opers.end() && !(lastoper->second.unary && lastoper->second.right)); // true if operator at current location would be left unary
		/*cout << unary << endl;
		cout << endl;*/

		auto oit = opers.begin();
		for (; oit != opers.end(); ++oit)
		{
			if (equal(oit->first.begin(), oit->first.end(), it) && (oit->second.unary == lunary || (oit->second.unary && oit->second.right)))
				break;
		}
		if (oit != opers.end())
		{
			if (lunary)
			{
				s.push(lasttok = token_t(oit->first, 1));
			}
			else if (oit->second.unary && oit->second.right) // right unary operator
			{
				// allow right unary operators to be used on constants and apply higher prec operators before
				while (!s.empty())
				{
					token_t tok = s.top();

					auto oit2 = find_oper(tok.first, true);
					if ((oit2 != opers.end() && oit2->second.prec > oit->second.prec) || (oit2 == opers.end() && funcs.find(tok.first) != funcs.end()))
						out.push_back(pop(s));
					else
						break;
				}
				out.push_back(lasttok = token_t(oit->first, 1)); // needs stack popping before?
			}
			else
			{
				insert_binaryoper(out, s, oit);
				lasttok = token_t(oit->first, 2);
			}
			it += oit->first.size();
			continue;
		}


		// try to parse function
		auto fit = funcs.begin();
		for (; fit != funcs.end(); ++fit)
		{
			if (opers.find(fit->first) == opers.end() && equal(fit->first.begin(), fit->first.end(), it))
				break;
		}
		if (fit != funcs.end())
		{
			if (lasttok.first == ")" || (opers.find(lasttok.first) == opers.end() && funcs.find(lasttok.first) != funcs.end()))
				throw parse_error("Missing operator", i);
			else if (lasttok.second == -1)
				insert_implicitmult(out, s);

			s.push(lasttok = token_t(fit->first, 0));
			it += fit->first.size();
			continue;
		}

		// try to parse function argument separator
		if (*it == ',')
		{
			if (lasttok.first == "(" || lasttok.first == ",")
				throw parse_error("Missing argument", i);

			bool found = false;
			while (!s.empty())
			{
				token_t tok = s.top();

				if (tok.first == "(")
				{
					found = true;
					break;
				}
				else
				{
					out.push_back(tok);
					s.pop();
				}
			}

			if (!found)
				throw parse_error("Found ',' not inside function arguments", i);

			s.top().second++; // increase number of arguments in current parenthesis
			lasttok = token_t(",", 0);
			++it;
			continue;
		}

		if (*it == '(')
		{
			if (lasttok.second == -1 || lasttok.first == ")")
				insert_implicitmult(out, s);

			s.push(lasttok = token_t("(", 1));
			++it;
			continue;
		}

		if (*it == ')')
		{
			if (lasttok.first == "(" || lasttok.first == ",")
				throw parse_error("Missing argument", i);

			bool found = false;
			while (!s.empty())
			{
				token_t tok = s.top();
				if (tok.first == "(")
				{
					found = true;
					break;
				}
				else
				{
					out.push_back(tok);
					s.pop();
				}
			}

			if (!found)
				throw parse_error("Found excess '('", i);

			token_t tok = pop(s); // pop '('

			if (!s.empty() && opers.find(s.top().first) == opers.end() && funcs.find(s.top().first) != funcs.end()) // if parenthesis part of function arguments
				out.push_back(token_t(pop(s).first, tok.second));

			lasttok = token_t(")", 0);
			++it;
			continue;
		}

		throw parse_error("Unknown token found", i);
	}

	while (!s.empty())
	{
		token_t tok = pop(s);
		if (tok.first == "(")
			throw parse_error("Found unclosed '('", in.size());
		out.push_back(tok);
	}

	return out;
}