int Database::GetRecordByFields(const string tableName, map<string, string> fieldValues, vector< map<string, string> >* out, string sortField, bool bAsc) const
{
	if (!Util::IsLetterNumberDash(tableName) || !Util::IsLetterNumberDash(sortField))
		return 2;

	string order = " ORDER BY " + sortField + (bAsc ? " ASC;" : " DSC;");
	string sql = "SELECT * FROM " + tableName + " WHERE ";

	auto it = fieldValues.cbegin();
	while (it != fieldValues.cend())
	{
		if (!Util::IsLetterNumberDash((*it).first))
			return 2;
		sql.append(Util::ToUpper((*it).first + "='"));
		//*TODO: Check value
		sql.append((*it).second + "'");

		++it;
		if (it != fieldValues.cend())
			sql.append(" AND ");
	}

	sql += order;

	return Exec(sql, out);
}
Example #2
0
void map_intersection(map<Key, Value>& lhs, map<Key, Value> const& rhs)
{
    typedef typename map<Key, Value>::iterator input_iterator1;
    typedef typename map<Key, Value>::const_iterator input_iterator2;

    input_iterator1 it1 = lhs.begin();
    input_iterator2 it2 = rhs.cbegin();
    input_iterator1 end1 = lhs.end();
    input_iterator2 end2 = rhs.cend();
    while (it1 != end1 && it2 != end2) {
        if (it1->first == it2->first) {
            it1->second += it2->second;
            ++it1;
            ++it2;
        }
        else {
            if (it1->first < it2->first) {
                ++it1;
            }
            else {
                ++it2;
            }
        }
    }
}
void grouped_vocabulary_tree<Point, K>::merge_maps(map<int, int>& map1, const map<int, int>& map2)
{
    using iter = map<int, int>::iterator;
    using citer = map<int, int>::const_iterator;

    iter it1 = map1.begin();
    citer it2 = map2.cbegin();
    iter end1 = map1.end();
    citer end2 = map2.cend();
    while (it2 != end2) {
        bool done1 = it1 == end1;
        if (!done1 && it1->first == it2->first) { // element already in 1, just increase count
            it1->second += it2->second;
            ++it1;
            ++it2;
        }
        else {
            if (done1 || it1->first > it2->first) {
                // from c++11 docs:
                // The function optimizes its insertion time if position points to the element
                // that will follow the inserted element (or to the end, if it would be the last).
                map1.insert(it1, *it2);
                ++it2;
            }
            else {
                ++it1; // if map1 is large while map2 is small this will not give better than const time insertion
            }
        }
    }
}
Example #4
0
void EulerUtils::Display::printMap ( string itemName, const map<string, int>& data ) {
	cout << "in printMap" << endl;
	cout << "Printing " << itemName << "..." << endl;
	for ( auto i = data.cbegin(); i != data.cend(); i++ )
        cout << i->first << ": " << i->second << endl;
    cout << endl;
}
Example #5
0
/*! \brief          Convert the name of a colour to a colour
    \param  str     name of a colour
    \return         the colour corresponding to <i>str</i>
*/
const int string_to_colour(const string& str)
{ static const map<string, int> colour_map { { "BLACK",   COLOUR_BLACK },
                                             { "BLUE",    COLOUR_BLUE },
                                             { "CYAN",    COLOUR_CYAN },
                                             { "GREEN",   COLOUR_GREEN },
                                             { "MAGENTA", COLOUR_MAGENTA },
                                             { "RED",     COLOUR_RED },
                                             { "WHITE",   COLOUR_WHITE },
                                             { "YELLOW",  COLOUR_YELLOW }
                                           };

  const string s = to_upper(remove_peripheral_spaces(str));
  const auto cit = colour_map.find(s);

  if (cit != colour_map.cend())
    return cit->second;

// should change this so it works with a colour name and not just a number
  if (begins_with(s, "COLOUR_"))
    return (from_string<int>(substring(s, 7)));

  if (begins_with(s, "COLOR_"))
    return (from_string<int>(substring(s, 6)));

  if (s.find_first_not_of(DIGITS) == string::npos)  // if all digits
    return from_string<int>(s);

  return COLOUR_BLACK;    // default
}
string Story::toString (const map<int, string> &glossary) const
{
	string result = "";
	result += this->timeStamp;
	for (const int wordID : this->words)
		if (glossary.find (wordID) != glossary.cend ())
			result += " " + glossary.find (wordID)->second;
	return result;
}
int Database::AddRecord(const string tableName, const map<string, string> newEntry)
{
	if (!Util::IsLetterNumberDash(tableName))
		return 2;

	string sql = "INSERT INTO " + tableName + " (";
	
	auto it = newEntry.cbegin();
	while(it != newEntry.cend())
	{
		if (!Util::IsLetterNumberDash((*it).first))
			return 2;

		if (Util::ToUpper((*it).first).compare("ID") == 0)
		{
			++it;
			continue;
		}

		sql.append(Util::ToUpper((*it).first));

		++it;
		if (it != newEntry.cend())
			sql.append(",");
		else
			sql.append(") ");
	}

	sql.append("VALUES(");
	it = newEntry.cbegin();
	while (it != newEntry.cend())
	{
		//*TODO: Check values
		sql.append("'" + (*it).second + "'");

		++it;
		if (it != newEntry.cend())
			sql.append(",");
		else
			sql.append(");");
	}

	return Exec(sql);
}
 Id getOrCreateId(const Name& u) {
   auto u_it = names.find(u);
   if( u_it != names.cend() )
     return u_it->second;
   else {
     Id u_id = (unsigned) nodes.size();
     nodes.push_back(Node(u));
     names.insert(make_pair(u, u_id));
     return u_id;
   }
 }
// --------------------------------------------------------------------------
inline
std::string
provider::realm () const
// --------------------------------------------------------------------------
{
  map::const_iterator it = m_req.find("realm");

  if (it != m_req.cend())
  {
    return it->second;
  }

  return "";
}
Example #10
0
void Model::AddFeasCat(map<string, int> feaofcat, string catname,int threshold)
{
	auto itfc = feaofcat.cbegin();
	int count = 1;
	while (itfc != feaofcat.cend())
	{
		if (itfc->second <= threshold)
		{
			++itfc;
			continue;
		}
		stringstream query;
		query<< "insert into fc (feature,cat,count) values ('" << itfc->first << "','" << catname << "'," << itfc->second << ")";
		this->ExecuteSQL(query.str().c_str());
		++itfc;
	}
}
Example #11
0
std::string RelationManager::showMap(const map<const Class *, set<const Class *> > &map, std::string msg) const
{
	std::string s;

	if (map.empty()) return "";

	if (msg != "")
		s.append(msg + "\n");
	for (auto i = map.cbegin(); i != map.cend(); i++) {
		s.append(i->first->getName() + ": ");
		for (auto j = i->second.cbegin(); j != i->second.cend(); j++)
			s.append((*j)->getName() + " ");
		s.append("\n");
	}

	return s.append("\n");
}
Example #12
0
double getOpValue(const string &token){
	//cout<<"GetOpValue="<<token<<endl;
	switch(checkOpType(token)){
		case pure_number:
			return stod(token);
		case identifier:
			{
				auto it=variable.find(token);
				if(it==variable.cend()){
					variable[token]=0.0;
					return 0.0;
				}else
					return it->second;
			}
		case syntax_error:;
	}
}
Example #13
0
	bool evaluate(const Point& inputPos, const Direction* inputDir, Point& outputPos, const Direction*& outputDir) const
	{
		if (inputDir == nullptr)
		{
			return false;
		}
		FlowConstIterator it = flows_.find(inputDir);
		if (it != flows_.cend())
		{
			outputDir = &(it->second->opposite());
			outputPos = inputPos + *it->second;
			return true;
		}
		else
		{
			return false;
		}
	}
/* Set 'tfidf', based on corpus */
void Story::setTFIDFBasedOnCorpus (const vector<Story> &corpus,
								   const map<int, set<int>> &storiesIndexWithCertainWord)
{
	if (this->termFrequency.empty ())
		this->setTermFrequency ();

	this->tfidf = this->termFrequency;
	for (map<int, double>::iterator iter = this->tfidf.begin ();
		 iter != this->tfidf.end (); ++iter) {
		if (storiesIndexWithCertainWord.find (iter->first) != storiesIndexWithCertainWord.cend ()) {
			double idf = 0.0;
			double storiesWithWord = 0.0;
			storiesWithWord = storiesIndexWithCertainWord.find (iter->first)->second.size ();
			idf = log (corpus.size () / storiesWithWord);
			iter->second *= idf;
		}
	}
}
bool compatibleVM(solution antSol,int i,ll n,int j,Server s,map<ll,qualifiedVM> omega)
{
    ll remCPU=s.ThreshCPU,remMEM=s.ThreshMEM;
	if(antSol.array[i]==-1 && (omega.find((ll)i)==omega.cend()))
	{
		for(register int k=0;k<n;k++)
		{
			if(antSol.array[k]!=-1 && antSol.array[k]==j)
			{
				remCPU-=(vm[k].CPU);
				remMEM-=(vm[k].MEM);
			}
		}
		if(remCPU>vm[i].CPU && remMEM>vm[i].MEM)
		{
			return true;
		}
		else return false;
	}
	return false;
}
Example #16
0
void DelayedRule::notifyHeadFired(const Lit& head, const ElementTuple& tuple, GroundTranslator* translator, map<DefId, GroundDefinition*>& tempdefs) {
	Assert(tuple.size()==_rule->getHeadVarContainers().size());
	if (grounded.find(tuple) != grounded.cend()) { // Already grounded for this tuple
		return;
	}
	if (getOption(VERBOSE_GROUNDING) > 3) {
		clog << "Head literal " << translator->printLit(head) << " of rule " << toString(_rule->getRule()) << " fired \n";
	}
	for (uint i = 0; i < tuple.size(); ++i) {
		*_rule->getHeadVarContainers()[i] = tuple[i];
	}
	grounded.insert(tuple);

	auto it = tempdefs.find(construction);
	if (it == tempdefs.cend()) {
		tempdefs[construction] = new GroundDefinition(construction, translator);
	}

	tempdefs[construction]->addPCRule(head, { }, false, false); // NOTE: important: add default false rule!
	_rule->groundForSetHeadInstance(*tempdefs[construction], head, tuple);
}
Example #17
0
bool Model::contained_in( map<unsigned int, shared_ptr<list< shared_ptr<pair_sc> > > > &m, 
   const shared_ptr<pair_sc> & sc, bool opt, bool debug) {

  for( auto iitm = m.cbegin(); iitm != m.cend(); iitm ++) {

          if (sc->signature != (sc->signature | iitm->first)) continue;

	  for ( auto il = iitm->second->begin(); il != iitm->second->end(); il++) { 
	      if( (*il)->contains(sc, fpfp_sim))
		      return true;	    
          }
  }

  if ( !opt) return false;

  for( auto iitm = m.begin(); iitm != m.end(); iitm ++) {

          if (iitm->first != (sc->signature | iitm->first)) continue;

          auto ed = iitm->second;

	  //for ( unsigned i = 0; i < ed->size(); i++) { 
	  for ( auto il = ed->begin(); il != ed->end(); il++) { 
              if ( ! (*il)->valid) {
                if (!debug)
                  ed->erase(il++);
                continue;
              }
	      if( sc->contains(*il, fpfp_sim)) {
                (*il)->clean_children();
                if (debug)
                  (*il)->valid = false;
                else
                  ed->erase(il++);
              }
	  }
  }
  return false;
}
Example #18
0
void Book::addTransactions(map<float, int>& _transactions)
{
    if (_transactions.size() > 0)
        addTransactions(_transactions.cbegin(), _transactions.cend());
}
Example #19
0
static int size(const map<unsigned int, shared_ptr<list<shared_ptr<pair_sc> > > > &m) {
  int s = 0;
  for( auto iitm = m.cbegin(); iitm != m.cend(); iitm ++)
    s += iitm->second->size();
  return s;
}
Example #20
0
	bool canEnter(const Direction* dir) const
	{
		return flows_.find(dir) != flows_.cend();
	}
Example #21
0
/** translate output table derived accumulator into sql subquery. */
const string ModelAccumulatorSql::translateDerivedAccExpr(
    const string & i_accName, const string & i_expr, const map<string, string> & i_nativeMap
) const
{
    // find native accumulators in source expression and substitute with sql subquery
    string sql;
    bool isLeftDelim = true;

    for (size_t nPos = 0; nPos < i_expr.length(); nPos++) {

        // skip until end of "quotes" or 'apostrophes'
        size_t nSkip = skipIfQuoted(nPos, i_expr);
        if (nSkip != nPos) {
            if (nSkip < i_expr.length()) {      // append to output
                sql += i_expr.substr(nPos, (nSkip + 1) - nPos);
                nPos = nSkip;
                isLeftDelim = false;    // "quotes" or 'apostrophes' is not left delimiter
                continue;               // move to the next char after "quotes" or 'apostrophes'
            }
            else { 
                sql += i_expr.substr(nPos);
                break;      // skipped until end of string
            }
        }

        // if previous char was name left delimiter then check for accumulator name in current position
        if (isLeftDelim) {

            // check for each accumulator name
            bool isAcc = false;
            size_t nLen = 0;
            int accPos;
            for (accPos = 0; accPos < (int)accNameVec.size(); accPos++) {
                
                nLen = accNameVec[accPos].length();
                isAcc = equalNoCase(accNameVec[accPos].c_str(), i_expr.c_str() + nPos, nLen);

                // check if accumulator name end with right delimiter
                if (isAcc && nPos + nLen < i_expr.length()) {

                    char chEnd = i_expr[nPos + nLen];
                    isAcc =
                        isspace<char>(chEnd, locale::classic()) ||
                        std::any_of(
                        rightDelimArr,
                        rightDelimArr + rightDelimSize,
                        [chEnd](const char i_delim) -> bool { return chEnd == i_delim; }
                    );
                }

                if (isAcc) break;   // accumulator found
            }

            // accumulator found: replace with subquery
            if (isAcc) {

                // validate: it must be native accumulator
                const map<string, string>::const_iterator it = i_nativeMap.find(accNameVec[accPos]);
                if (it == i_nativeMap.cend()) 
                    throw DbException("error in derived accumulator: %s invalid name: %s in: %s", i_accName.c_str(), accNameVec[accPos].c_str(), i_expr.c_str());

                sql += "(" + it->second +")";   // append subquery

                nPos += nLen - 1;   // skip accumulator in source expression
                isLeftDelim = false;
                continue;           // done with accumulator
            }
        }

        // append current char to output
        char chNow = i_expr[nPos];
        sql += chNow;

        // check if current char is a name delimiter
        isLeftDelim = 
            isspace<char>(chNow, locale::classic()) || 
            std::any_of(
                leftDelimArr, 
                leftDelimArr + leftDelimSize, 
                [chNow](const char i_delim) -> bool { return chNow == i_delim; }
            );
    }

    return sql;
}
int getprec(char c)
{
    auto pprec = precs.find(c);
    return pprec != precs.cend() ? pprec->second : -1;
}