Ejemplo n.º 1
0
QString TheGamesDB::parseXMLforId(QString game_name, QNetworkReply* reply)
{
    QXmlStreamReader reader(reply);

    QString id;

    while (!reader.atEnd()) {
        reader.readNext();
        if (reader.isStartElement()) {
            QString element = reader.name().toString();
            if (element == "id") {
                QString game_id = reader.readElementText();
                id = game_id;
            }
            else if (element == "GameTitle") {
                QString text = reader.readElementText();
                QString cleaned_title = cleanString(text);
                if (cleaned_title.indexOf(cleanString(game_name)) != -1) {
                    break;
                }
            }
        }
    }

    return id;
}
Ejemplo n.º 2
0
void ConfigFile::flush() 
{
    Layout::iterator sec;
    Section::iterator var;
    std::string secName;

    //in case the filename is already cleared
    if(filename_.empty())
    {
        throw PreconditionException("No filename in ConfigFile::flush");
    }

    //open the file blanked out, to not duplicate entries
    std::ofstream file(filename_.c_str(), std::ios::out|std::ios::trunc);

    if(!file)
    {
        throw Error("Unable to open " + filename_ +
                    " for writing in ConfigFile::flush");
    }

    //iteration through sections
    for(sec = layout_.begin(); sec != layout_.end(); ++sec)
    {
        //ensure that section is valid
        secName = cleanString(sec->first);
        if(secName[0] == '[' && secName[secName.length()-1] == ']')
        {
            file << sec->first << std::endl;    //write out raw section title

            //for each variable in section, write out variable=value
            for(var = sec->second.begin(); var != sec->second.end(); ++var)
            {
                if(var->first[0] == '_')    //special values start with _
                {
                    if(var->first.substr(1) == "comment")
                    {
                        file << var->second << std::endl;
                    }
                    else if(var->first.substr(1) == "newline")
                    {
                        file << std::endl;
                    }
                }
                else if(!cleanString(var->first).empty())   //a variable
                {
                    file << var->first << '=' << var->second << std::endl;
                }
            }
        }
    }
    file.close();
}
Ejemplo n.º 3
0
/**
 * DBInterface::writeToDataBase
 * @brief writeToDataBase writes content of dataBuffer_ to database
 * @param dataBuffer_ data which is written to database
 */
void DBInterface::writeToDataBase(DataBuffer& dataBuffer_) {
    if (readStatusOK()) {

        stringstream httpRequestUrl;

        httpRequestUrl << URL_OF_DATABASE << "/write?db=" << NAME_OF_DATBASE << "&precision=s";
        stringstream httpRequestPostFields;
        if (!dataBuffer_.useDataSource) {
            log << SLevel(ERROR) << "Aborted writing to database because there was either no DataSource specified" <<
             " or the useDataSource-flag was not set to true." << endl;
        } else {
            string dataSource = cleanString(dataBuffer_.dataSource);
            httpRequestPostFields << "point,DataSource=" << dataSource << " ";

            bool printComma = false;
            typedef std::map<string, double>::iterator it_type;
            for(it_type iterator = dataBuffer_.data.begin(); iterator != dataBuffer_.data.end(); iterator++) {
                if (printComma) {
                    httpRequestPostFields << ",";
                } else {
                    printComma = true;
                }
                string name = cleanString(iterator->first);
                double value = cutValueToInfluxDBRange(iterator->second);
                httpRequestPostFields << name << "=" << value;
            }
            // create datetime-string
            if (dataBuffer_.useDateTimes) {
                if (dataBuffer_.startDateTime.tm_year <= 1971) {
                    log << SLevel(ERROR) << "Aborted writing to database because of invalid datetime. " <<
                    "Please use only years bigger than 1971." << endl;
                    setDBFailure(true);
                    return;
                } else {
                    string startDateTime = cTimeToString(dataBuffer_.startDateTime,true);
                    httpRequestPostFields << " " << startDateTime;
                }
            } else {
                // if no date-time is specified use local time (cut down to current hour)
                int currentLocalDateTime = getCurrentDateTimeAsUnixTime();
                string startDateTime = to_string(currentLocalDateTime);
                httpRequestPostFields << " " << startDateTime;
            }
            HTTPRequest req;
            bool noFailure = req.post(httpRequestUrl.str(),httpRequestPostFields.str());
            setDBFailure(!noFailure);
        }
    } else {
        log << SLevel(ERROR) << "Aborted writing to database because of status not OK" << endl;
    }
}
Ejemplo n.º 4
0
	std::string RemoveHtmlTag( const std::string & strSource )
	{
		std::string cleanString(strSource);
		static boost::regex regularExpression("<(.|\n)*?>"); //Ajouter code vérification balise incomplète
		cleanString=boost::regex_replace(cleanString, regularExpression , "", boost::match_default | boost::format_sed);
		return cleanString;
	}
Ejemplo n.º 5
0
// Сверяем пароль
int verifyPassword(struct PassPair *pair, char *password) {
    char *result = cleanString(password);
    if (strncmp(pair->pass, result, strlen(pair->pass)) != 0) {
        fprintf(stderr, "Login: %s\nWrong password: %s\n", pair->login, result);
        return -1;
    }
    return 0;
}
Ejemplo n.º 6
0
const Instruction & Lexer::tokenize(const std::string & instruction, Machine & machine)
{
    static Instruction tokens;

    tokens.clear();
    if (instruction.size() == 0) return tokens;

    std::string cleanString(removeWhitespace(instruction));

    {
        size_t colonPos = cleanString.find_first_of(':');
        if (colonPos != std::string::npos)
        {
            char label[Label::length + 1];
            strncpy(label, cleanString.substr(0, colonPos).c_str(), Label::length);
            if (!isalpha(label[0])) throw(std::runtime_error("Lexer::tokenize: Labels must start with a letter"));
            tokens.label.setLabelData(label);
            if (colonPos == cleanString.size() - 1) return tokens;

            cleanString = removeWhitespace(cleanString.substr(colonPos + 1, cleanString.size() - colonPos));
            if (cleanString.find_first_of(':') != std::string::npos)
                throw(std::runtime_error("Lexer::tokenize: Only one label per line allowed"));
        }
    }

    if (cleanString.size() == 0) return tokens;

    size_t spacePos = cleanString.find_first_of(' ');
    if (spacePos == std::string::npos)
    {
        tokens.opcode = getOpcodeToken(cleanString);
        return tokens;
    }
    tokens.opcode = getOpcodeToken(cleanString.substr(0, spacePos));

    cleanString = removeWhitespace(cleanString.substr(spacePos, cleanString.size() - spacePos));
    if (cleanString.size() == 0) return tokens;
    spacePos = cleanString.find_first_of(' ');
    if (spacePos == std::string::npos)
    {
        tokens.operand1 = getOperandToken(cleanString, machine);
        return tokens;
    }
    tokens.operand1 = getOperandToken(cleanString.substr(0, spacePos), machine);

    cleanString = removeWhitespace(cleanString.substr(spacePos, cleanString.size() - spacePos));
    if (cleanString.size() == 0) return tokens;
    spacePos = cleanString.find_first_of(' ');
    if (spacePos == std::string::npos)
    {
        tokens.operand2 = getOperandToken(cleanString, machine);
        return tokens;
    }
    tokens.operand2 = getOperandToken(cleanString.substr(0, spacePos), machine);

    return tokens;
}
Ejemplo n.º 7
0
bool UnbufferedFileStream::open() {
	Statistics::getInstance()->filesOpened++;
	LPWSTR fileName = new WCHAR[MAX_PATH_LENGTH];
	file->copyName(cleanString(fileName));
	hFile = CreateFile(fileName, GENERIC_READ, FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_FLAG_NO_BUFFERING | FILE_FLAG_SEQUENTIAL_SCAN, NULL);
	delete fileName;
	if (hFile == INVALID_HANDLE_VALUE) Statistics::getInstance()->fileOpenProblems++;
	return hFile != INVALID_HANDLE_VALUE;
}
Ejemplo n.º 8
0
// Получаем пару логин-пароль по логину
struct PassPair *getPair(char *login) {
    char *result = cleanString(login);
    for (int i = 0; i < lengthPassPairs; i++) {
        if (strncmp(passPairs[i].login, result, strlen(passPairs[i].login)) == 0) {
            return &passPairs[i];
        }
    }
    fprintf(stderr, "Wrong login: %s\n", result);
    return NULL;
}
Ejemplo n.º 9
0
//finds book from book name
BookNode* BookTracker::findBook(string bookName) {
    if (head == nullptr) {
        throw invalid_argument("Inventory is empty!");
    } else {
        //sanatize bookName
        bookName = cleanString(bookName);
        BookNode *itorator = head;
        while (itorator != nullptr) {
            //sanitize the itorator's bookName
            if (cleanString(itorator->getBookName()) == bookName) {
                return itorator;
            } else {
                itorator = itorator->getNext();
            }
        }
    }

    throw invalid_argument(bookName + " could not be found");
}
Ejemplo n.º 10
0
category_t *processLine(char *line, category_t *head)
{ 
  char *recipe = NULL, *token = NULL, s[2] = "[";
  if(strcmp(line, "") == 0)
    return head;
  
  token = strtok(line, s);
  cleanString(token);
  recipe = strdup(token);
  token = strtok(NULL, s);
  while(token != NULL)
  {
    cleanString(token);
    head = dataHandling(recipe, token, head);
    token = strtok(NULL, s);
  }
  free(recipe);
  return head;
}
Ejemplo n.º 11
0
std::string ConfigFile::bracketString(const std::string& str)
{
    std::string ret( cleanString(str) );
    
    //add brackets if they do not exist, unless the string is empty
    if(!ret.empty() && ret[0] != '[' || ret[ret.length()-1] != ']')
    {
        ret = "["+ret+"]";
    }
    
    return ret;
}
Ejemplo n.º 12
0
//remove a book from the list of books
//after correcting strings;
bool BookTracker::remove(string bookName) {
    if (head == nullptr) {
        return false;
    } else {
        bookName = cleanString(bookName);
        BookNode *itorator = head;
        while (itorator->getNext() != nullptr) {
            string nextBookName = cleanString(itorator->getNext()->getBookName());
            if (nextBookName == bookName) {
                BookNode *patch = itorator;
                itorator = itorator->getNext();
                patch->setNext(itorator->getNext());
                delete itorator;
                return true;
            } else {
                itorator = itorator->getNext();
            }
        }
    }

    return false;
}
Ejemplo n.º 13
0
bool UserDao::putMatch(User user, User userToMatch){
	/**Actualizo los matchs del usuario que invoco la peticion**/
	Json::Value root;
	Json::Value data;
	vector<string> idUserMatchs = user.getIdUserMatchs();
	idUserMatchs.push_back(userToMatch.getId());
	for(string id : idUserMatchs){
		data.append(id);
	}
	user.setIdUserMatchs(idUserMatchs);

	root["idUserMatchs"] = data;
	DBtuple keyIdUserMatchs(user.getId() + "_idUserMatchs");
	keyIdUserMatchs.value = jsonParser.valueToString(root);
	bool userMatchOk = this->dataBase->put(keyIdUserMatchs);

	//Actualizo los matchs del candidato
	Json::Value rootCandidate;
	Json::Value dataCandidate;
	vector<string> idUserToMatchs = userToMatch.getIdUserMatchs();
	idUserToMatchs.push_back(user.getId());
	for(string id : idUserToMatchs){
		dataCandidate.append(id);
	}

	rootCandidate["idUserMatchs"] = dataCandidate;
	DBtuple keyIdUserToMatchs(userToMatch.getId() + "_idUserMatchs");
	keyIdUserToMatchs.value = jsonParser.valueToString(rootCandidate);
	bool userToMatchOk = this->dataBase->put(keyIdUserToMatchs);

	//Saco el usuario desde el candidato
	Json::Value rootUserCandidate;
	Json::Value dataUserCandidate;
	for(string id : userToMatch.getIdUserCandidatesMatchs()){
		id = cleanString(id);
		if(user.getId().compare(id.c_str()) != 0){
			dataUserCandidate.append(id);
		}
	}
	rootUserCandidate["idUserCandidatesMatchs"] = dataUserCandidate;
	DBtuple keyIdUserCandidateMatchs(userToMatch.getId() + "_idUserCandidatesMatchs");
	keyIdUserCandidateMatchs.value = jsonParser.valueToString(rootUserCandidate);
	bool userToMatchCandidateOk = this->dataBase->put(keyIdUserCandidateMatchs);

	if(userMatchOk && userToMatchOk && userToMatchCandidateOk){
		return true;
	}

	return false;
}
Ejemplo n.º 14
0
void ConfigFile::open(const std::string& filename)
{
    filename_ = filename;
    if(filename_.empty())
    {
        throw PreconditionException("Empty filename in ConfigFile::open");
    }

    std::string section, var, val, str, clean;
    std::ifstream file(filename_.c_str());
    
    if(!file)
    {
        throw Error("Unable to open " + filename_ +
                    " for reading in ConfigFile::open");
    }

    layout_.clear();    //clear layout, just in case

    while(file)  //parses entire file
    {
        std::getline(file,str);    //read in a line
        clean = cleanString(str);    //get a clean version
        

        //if std::string is bracketed it is a section
        if(clean[0] == '[' && clean[clean.length()-1] == ']')
        {
            section = str;
        }
        else if(std::isalpha(clean[0]))   //variables must start with a letter
        {
            //split at the equals sign
            var = str.substr(0,str.find('='));
            val = str.substr(str.find('=')+1);
            setVariable(section,var,val);
        }
        else if(clean[0] == '#' || clean[0] == ';') //comments
        {
            setVariable(section,"_comment",str);
        }
        else if(clean.length() == 0 && !file.eof())  //save blank lines
        {
            setVariable(section,"_newline",str);
        }

    }
    file.close();
}
Ejemplo n.º 15
0
bool FileReader::readLine(std::vector<std::string> * strings){
	if(!this->good()){
		return false;
	}
	std::string line;
	std::getline(*file,line);
	if(!this->good()){
		return false;
	}
	
	if(line.length() == 0) return true;
	
	line = cleanString(line);
	
	FileReader::splitString(line," ",strings);

	return true;
}
Ejemplo n.º 16
0
bool Color::FromString(const String &str)
{
	String s = str;
	cleanString(s);
	if(s.GetLength() >= 6){
		Float val[3];
		bool valid = true;
		for(Int32 i=0;i<3;i++){
			val[i] = (findHexChar(s[i*2],valid)*16.0 + findHexChar(s[i*2+1],valid))/255.0;
		}
		if(valid){
			for(Int32 i=0;i<3;i++){
				m_val[i] = val[i];
			}
		}
		return valid;
	}
	return false;
}
string CQueryResult::cleanUpResult(string &result, string remove) {
	if (result.size() <= 2) {
		return string("");
	}
	string cleanString(" ");
	int removeLength = remove.size();
	
	int firstPos = result.find(remove, 0);
	if (firstPos == -1) {
		return cleanString.append(result.substr(2, result.size()));
	}
	int nextPos = result.find(remove, firstPos + 1);
	while (nextPos != -1) {
		cleanString.append(result.substr(
					firstPos + removeLength, 
					nextPos - (firstPos + removeLength)));
		firstPos = nextPos;
		nextPos = result.find(remove, nextPos+1);
	} 			
	cleanString.append(result.substr(firstPos + removeLength));
	return cleanString;
}
Ejemplo n.º 18
0
/**
 * DBInterface::readFromDataBase
 * @brief readFromDataBase reads the data which is requested by dataBuffer_ from database
 * @param dataBuffer_ requested data (is only filled with requested strings)
 * @return returns the requested dataBuffer_ which now contains requested data
 */
vector<DataBuffer> DBInterface::readFromDataBase(DataBuffer& dataBuffer_) {
    // create empty result
    vector<DataBuffer> result;

    if (readStatusOK()) {

        // create url-string for select ... from ...
        stringstream httpRequestUrl;
        httpRequestUrl << URL_OF_DATABASE << "/query?pretty=true&db=" << NAME_OF_DATBASE << "&q=SELECT+"; // << "&precision=s";

        // iterate all requested fields
        bool printComma = false;
        typedef std::map<string, double>::iterator it_type;
        for(it_type iterator = dataBuffer_.data.begin(); iterator != dataBuffer_.data.end(); iterator++) {
            if (printComma) {
                httpRequestUrl << ",";
            } else {
                printComma = true;
            }
            string name = cleanString(iterator->first);
            httpRequestUrl << name << "+";
        }

        // add requested datasource
        if (!dataBuffer_.useDataSource) {
            log << SLevel(ERROR) << "Aborted reading from database because there was either no DataSource specified" <<
            " or the useDataSource-flag was not set to true." << endl;
        } else {
            string dataSource = cleanString(dataBuffer_.dataSource);
            httpRequestUrl << "FROM+point+where+DataSource+=+'" << dataSource << "'";

            // add requested datetime-range
            if (dataBuffer_.useDateTimes) {
                if ( (dataBuffer_.startDateTime.tm_year <= 1971) ||
                     (dataBuffer_.endDateTime.tm_year   <= 1971) ){
                    log << SLevel(ERROR) << "Aborted reading from database because of invalid datetime. " <<
                    "Please use only years bigger than 1971." << endl;
                    setDBFailure(true);
                    return result;
                }
                string startDateTime = cTimeToString(dataBuffer_.startDateTime,false);
                string   endDateTime = cTimeToString(  dataBuffer_.endDateTime,false);
                httpRequestUrl << "+and+time+>=+'" << startDateTime << "'";
                httpRequestUrl << "+and+time+<=+'" <<   endDateTime << "'";
            } else {
                // if no date-time is specified use local time (cut down to current hour)
                struct tm currentLocalDateTime = getCurrentDateTime();
                string startDateTime = cTimeToString(currentLocalDateTime,false);
                string   endDateTime = startDateTime;
                httpRequestUrl << "+and+time+>=+'" << startDateTime << "'";
                httpRequestUrl << "+and+time+<=+'" <<   endDateTime << "'";
            }


            // execute request
            HTTPRequest req;
            string answerJSON = req.get(httpRequestUrl.str());
            setDBFailure(answerJSON == "");

            // convert json to vector of DataBuffer
            result = jsonToDataBufferVector(answerJSON,dataBuffer_.dataSource);

        }
    } else {
        log << SLevel(ERROR) << "Aborted reading from database because of status not OK" << endl;
    }

    // return
    return result;
}
Ejemplo n.º 19
0
//Vocabulary richness (distinct words/totalNumberOfWords) & total Number of short Words
void FeatureSet::getVocabularyRichness()
{
	map<string, uint> uniqueWords;
	uint wordBeginAdress = 0;
	string word;
	bool wordFlag = false; //true, if i is inside a word
	uint i;

	for (i = 0; i < text.length(); i++)
	{
		if (text[i] == '\n' || text[i] == ' ' || text[i] == '\t' || text[i] == '\r' || i == text.length() - 1)
		{
			if (wordFlag)
			{
				//numberOfWords++;
				word = text.substr(wordBeginAdress, i - wordBeginAdress);

				if (cleanString(word))
				{
					if (word.length() < MAX_WORD_LENGTH)
					{
						wordLengthFrequencyDistribution[word.length() - 1]++;

						map<string, uint>::iterator it = functionWords.find(word);
						if (it != functionWords.end())
						{
							it->second++;
							totalNumberOfFunctionWords++;
						}
						it = uniqueWords.find(word);
						if (it != uniqueWords.end())
						{
							it->second++;
						}
						else
						{
							uniqueWords.insert(pair<string, uint>(word, 0));
						}
					}
				}
				wordFlag = false;
			}
		}
		else if (wordFlag == false)
		{
			numberOfWords++;
			wordBeginAdress = i;
			wordFlag = true;
		}
	}
	numberOfShortWords = wordLengthFrequencyDistribution[0] + wordLengthFrequencyDistribution[1] + wordLengthFrequencyDistribution[2];

	//count hapaxLegomena
	for (map<string, uint>::iterator it = uniqueWords.begin(); it != uniqueWords.end(); it++)
	{
		if (it->second == 0)
		{
			hapaxLegomena++;
		}
	}
	numberOfDistinctWords = uniqueWords.size();

	if (numberOfWords)
	{
		vocabularyRichness = numberOfDistinctWords / (double)numberOfWords;
	}
	vocabularyRichness = 0;
}
Ejemplo n.º 20
0
void CBot::preprocess_input() 
{
	cleanString(m_sInput);
	UpperCase(m_sInput);
	insert_space(m_sInput);
}
Ejemplo n.º 21
0
/**
 * DBInterface::jsonToDataBufferVector
 * @brief iterate through JSON and return data inside json_ as vector of DataBuffer
 * @param json_ JSON string to convert
 * @return returns a vector of DataBuffer which contains the data inside json_
 *
 * This function can convert a json received from either InfluxDB or TODO
 * to a vector of DataBuffers.
 * If the JSONs origin was InfluxDB, the return values contains a DataBuffer for
 * every DateTime which was requested from InfluxDB.
 */
vector<DataBuffer> DBInterface::jsonToDataBufferVector(const string &json_, const string& dataSource_) {
    vector<DataBuffer> result;
    QString jsonQString(json_.c_str());
    QJsonDocument jsonDocument = QJsonDocument::fromJson(jsonQString.toUtf8());
    QJsonObject jsonObject = jsonDocument.object();

    // parse json from influxdb
    if (jsonObject.contains(QString("results"))) {
        QJsonArray tempArray = jsonObject["results"].toArray();
        QJsonObject tempObject = tempArray.first().toObject();
        if (tempObject.contains(QString("series"))) {
            tempArray = tempObject["series"].toArray();
            tempObject = tempArray.first().toObject();
            if (tempObject.contains(QString("columns")) &&
                tempObject.contains(QString("values" )) ){
                QJsonArray names  = tempObject["columns"].toArray();
                QJsonArray values = tempObject["values" ].toArray();

                // iterate through all datasets
                typedef QJsonArray::iterator it_type;
                for(it_type iterator = values.begin(); iterator != values.end(); iterator++) {
                    QJsonArray dataSet = values.at(iterator.i).toArray();
                    DataBuffer tempDataBuffer;
                    // iterate to all names/values in a dataset
                    for(it_type iterator2 = dataSet.begin(); iterator2 != dataSet.end(); iterator2++) {

                        // get name
                        string name = names.at(iterator2.i).toString().toStdString();
                        // get value
                        QJsonValue valueJSON = dataSet.at(iterator2.i);

                        // set time
                        if (name == "time") {
                            struct tm time = stringToCTime(valueJSON.toString().toStdString());
                            tempDataBuffer.useDateTimes = true;
                            tempDataBuffer.startDateTime = time;
                            tempDataBuffer.endDateTime   = time;
                        } else {
                            // set values
                            double valueDouble = valueJSON.toDouble();
                            tempDataBuffer.data[name] = cutValueToInfluxDBRange(valueDouble);
                        }
                    }
                    // add DataSource;
                    tempDataBuffer.useDataSource = true;
                    tempDataBuffer.dataSource = cleanString(dataSource_);

                    // add data buffer to vector
                    result.push_back(tempDataBuffer);

                }
            } else {
                log << SLevel(ERROR) << "Aborted parsing InfluxDB-Json to databuffer. Unable to find 'columns and/or 'values' in JSON" << endl;
            }
        } else {
            log << SLevel(ERROR) << "Aborted parsing InfluxDB-Json to databuffer. Unable to find 'series' in JSON" << endl;
        }
    }


    return result;
}
Ejemplo n.º 22
0
std::vector<std::string>
LSFParser::convertScriptIntoArgv(const char* pathTofile,
                                 const std::string& BATCH_PREFIX) {
    std::ifstream fileStream;
    std::string line;

    fileStream.open (pathTofile);

    std::string cmd;
    std::vector<std::string> tokens;
    std::string tmpLine="";
    size_t escapePos;
    bool escapeFound = false;

    if (fileStream.is_open()) {
        while (!fileStream.eof()) {

            getline(fileStream, line);

            //Treating of the escape character int the script content
            if (boost::algorithm::ends_with(boost::algorithm::erase_all_copy(line, " "),"\\")) {
                escapePos = line.rfind("\\");
                if (escapePos!=std::string::npos) {
                    tmpLine += line.substr(0, escapePos);
                    escapeFound = true;
                    continue;
                }
            }

            if (escapeFound) {
                tmpLine +=line;
                line = tmpLine;
                escapeFound = false;
                tmpLine = "";
            }

            // erase all white space until # (excluded)
            while(boost::algorithm::starts_with(line, " ")) {
                line.erase(0,1);
            };

            /*search # character*/
            size_t pos = line.find('#');
            if (pos == std::string::npos) {
                continue;
            }

            if (boost::algorithm::starts_with(boost::algorithm::erase_all_copy(line," "), BATCH_PREFIX)) {

                pos = line.find(BATCH_PREFIX.substr(1));//skip the character # in  BATCH_PREFIX
                line = line.substr(pos+BATCH_PREFIX.size()-1);

                //To skip a comment on the line
                pos = line.find('#');
                if (pos != std::string::npos) {
                    if (pos-1 >=0) {
                        std::string tmp = line.substr(pos-1);
                        if (boost::algorithm::starts_with(boost::algorithm::erase_all_copy(tmp, " "), "#")) {
                            line = line.substr(0, pos);
                        }
                    } else {
                        line = line.substr(0, pos);
                    }
                }
                //verify quote characters in line
                verifyQuotaCharacter(line, '\"');
                verifyQuotaCharacter(line, '\'');
                //add line to cmd
                cmd = cmd+" "+line;
            }
        }
        fileStream.close();

        std::istringstream iss(cmd);
        std::copy(std::istream_iterator<std::string>(iss),
                  std::istream_iterator<std::string>(),
                  std::back_inserter<std::vector<std::string> >(tokens));

    }

    std::string argvStr;
    std::vector<std::string>::iterator iter;
    std::vector<std::string>::iterator end = tokens.end();
    std::vector<std::string> tokensArgs;
    char quote = '\0';
    for(iter=tokens.begin(); iter!=end; ++iter) {
        argvStr = *iter;
        if (isStartByQuote(argvStr, '\"')) {
            quote = '\"';
        } else if (isStartByQuote(argvStr, '\'')) {
            quote = '\'';
        }
        if (quote!='\0') {
            std::vector<std::string>::iterator found_iter;
            std::vector<std::string>::iterator beg_iter=iter;
            found_iter = std::find_if(beg_iter, end, IsEndByQuote(quote));
            if (found_iter!=end) {
                while(beg_iter!=found_iter) {
                    ++beg_iter;
                    argvStr = argvStr+" "+*beg_iter;
                }
                iter=beg_iter;
            } else {
                std::string errorMsg = "Error: invalid argument "+argvStr;
                errorMsg +=". It must be closed by the character quote character (\' or \")";
                throw UMSVishnuException(ERRCODE_INVALID_PARAM, errorMsg);
            }
        }
        quote='\0';
        if (!cleanString(argvStr, '\"')) {
            cleanString(argvStr, '\'');
        }
        tokensArgs.push_back(argvStr);
    }

    return tokensArgs;
}
Ejemplo n.º 23
0
/* 
    Read ASCII file with point IDs and measurements.
    Store ID and X/Y/Z coordinates in the global double array 'pointTable'.
    Sort the array into a tree-like structure: first by skeleton ID, then all points
    of the same skeleton ID by bone ID, so the points are always "skull to toe" for
    each coherent skeleton.
    Any line the parser can make no sense of will be read as an invalid point.
*/
void createTable()
{
    int num_lines = 0;
    FILE *fp;
    char *line, *copy;
    int i, j;
    char *token;
    int num_tokens;
    char *id = NULL;
    char *id_token;
    char *clean_token;
    int skipped;
    
    
    fp = fopen ( file->answer, "r" );
    if ( fp == NULL ) {
        G_fatal_error ("Unable to open ASCII input file for reading");
    }
    
    line = G_malloc ( sizeof (char) * MAXSTR );
    
    while ( fgets ( line, MAXSTR, fp ) ) {
        num_lines ++;
    }
    
    if ( num_lines < 2 ) {
        G_fatal_error ("Input file too short (need at least two points)");
    }
    
    rewind ( fp );
    
    /* now that we know how many points to expect, 
       we can allocate the array to store the points */
    pointTable = G_malloc ( sizeof ( Point ) * num_lines );
    for ( i = 0; i < num_lines; i ++ ) {
        pointTable[i].ID = NULL;
        pointTable[i].invalid = 0;
    }
    
    G_message (_("Importing %i lines from input file:"), num_lines );
        
    /* split input lines into tokens and save data */
    i = -1;
    while ( fgets ( line, MAXSTR, fp ) ) {    	
        i ++;
    	num_tokens = 0;
	j = 1;
	G_squeeze ( line );
	/* skip empty lines and commented lines */
	if ( strlen ( line  ) > 0 && line[0] != '#' ) {
    	    token = strtok ( line, delimiter );
	    skipped = 0;	    
	} else {
	    token = NULL;
	    skipped = 1;
	}
	while ( token != NULL ) {
	    num_tokens ++;
	    /* point ID ? */
	    if ( j == ID_COL_POS ) { 
	    	if ( id != NULL ) {
		    free ( id );
		}
		clean_token = cleanString ( token );
		if ( clean_token == NULL ) {
                    G_warning (_("Invalid ID field on line %i"), i + 1);
                    pointTable[i].invalid = 1;		
		} else {
	    	    pointTable[i].ID = strdup ( clean_token );
		    G_free ( clean_token );
		}
	    }
	    /* X coordinate (Easting) ? */
	    if ( j == X_COL_POS ) {
	        clean_token = cleanString ( token );
		if ( clean_token == NULL ) {
                    G_warning ("Invalid X coordinate on line %i", i + 1);
                    pointTable[i].invalid = 1;		
		} else {
	            pointTable[i].X = atof ( clean_token );
		    G_free ( clean_token );
		    if ( pointTable[i].X == 0.0 ) {
                        G_warning (_("Invalid X coordinate (0.0) on line %i"), i + 1);
                        pointTable[i].invalid = 1;
                    }	    
		}
	    }
	    /* Y coordinate (Northing) ? */
	    if ( j == Y_COL_POS ) {
	        clean_token = cleanString ( token );
		if ( clean_token == NULL ) {
                    G_warning (_("Invalid Y coordinate on line %i"), i + 1);
                    pointTable[i].invalid = 1;		
		} else {
	            pointTable[i].Y = atof ( clean_token );
		    G_free ( clean_token );
		    if ( pointTable[i].Y == 0.0 ) {
                        G_warning (_("Invalid Y coordinate (0.0) on line %i"), i + 1);
                        pointTable[i].invalid = 1;
                    }
		} 
	    }
	    /* Z coordinate (Elevation) ? */
	    if ( j == Z_COL_POS ) {
	        clean_token = cleanString ( token );
		if ( clean_token == NULL ) {
                    G_warning (_("Invalid Z coordinate on line %i"), i + 1);
                    pointTable[i].invalid = 1;				
		} else {
	            pointTable[i].Z = atof ( clean_token );
		    G_free ( clean_token );
		    if ( pointTable[i].Z == 0.0 ) {
                        G_warning (_("Invalid Z coordinate (0.0) on line %i"), i + 1);
                        pointTable[i].invalid = 1;
                    }
		}
	    }	    
	    /* next field */
	    token = strtok ( NULL, delimiter );	    
	    j ++;
	}
	/* we need EXACTLY four fields in pre-defined order */
	if ( num_tokens < 4 ) {
	    if ( skipped == 0 ) {
	        G_warning (_("Wrong field count (needed 4, got %i) on line %i"), num_tokens, i + 1);
	    }
	    pointTable[i].invalid = 1;
	}
        G_free ( line );
        line = G_malloc ( sizeof (char) * MAXSTR );
	
	G_percent ( i, num_lines - 1, 10 );
    }
    numPoints = num_lines;

    /* split ID into BONE_ID and SKEL_ID */
    
    for ( i = 0; i < numPoints; i ++ ) {
        if ( pointTable[i].invalid == 0 ) {
            id = strdup ( pointTable[i].ID );
	    id_token = strtok ( id, "." );
	    if ( id_token == NULL ) {
	        G_warning (_("Invalid point ID on line %i"),i + 1);
	        pointTable[i].invalid = 1;
	    }
	    pointTable[i].SKEL_ID = atoi ( id_token );
	    if ( pointTable[i].SKEL_ID < 0 ) {
	        G_warning (_("Invalid (negative) point ID on line %i"),i + 1);
	        pointTable[i].invalid = 1;	
	    }
	    id_token = strtok ( NULL, "." );
	    if ( id_token == NULL ) {
	        G_warning (_("Invalid point ID on line %i"),i + 1);
	        pointTable[i].invalid = 1;
	    }
	    pointTable[i].BONE_ID = atoi ( id_token );
	    if ( pointTable[i].BONE_ID < 0 ) {
	        G_warning (_("Invalid (negative) point ID on line %i"),i + 1);
	        pointTable[i].invalid = 1;	
	    }	
	    id_token = strtok ( NULL, "." );
	    if ( id_token != NULL ) {
	        G_warning (_("Invalid point ID on line %i"),i + 1);
	        pointTable[i].invalid = 1;
	    }
            G_free ( id );
        }
    }

    if ( DEBUG ) {
        fprintf ( stderr, "createTable() DONE.\n" );
	dumpPts();
    }    
    
    fclose ( fp );
    
    G_message ("Sorting points and deleting duplicates:");
    
    /* prune invalid point records */
    pointTable = cleanPts();

    G_percent ( 1, 4, 1 );
    
    if ( DEBUG ) {
        fprintf ( stderr, "Prune invalid input file records DONE.\n" );
	dumpPts();
    }    
    
    /* sort global points array to make it a tree-like structure */
    qsort ( pointTable, numPoints, sizeof ( Point ), comparePts );

    G_percent ( 2, 4, 1 );

    if ( DEBUG ) {
        fprintf ( stderr, "Sort points DONE.\n" );
	dumpPts();
    }    

    /* prune invalid point records */
    pointTable = cleanPts();
    if ( DEBUG ) {
        fprintf ( stderr, "Pruning duplicate points DONE.\n" );
	dumpPts();
    }
    
    G_percent ( 3, 4, 1 );
    
    /* get max bone ID from remaining valid points */
    if ( numPoints > 0 ) {
        MAX_BONE_ID = pointTable[0].BONE_ID;
        for ( i = 0; i < numPoints; i ++ ) {
	    if ( pointTable[i].BONE_ID > MAX_BONE_ID ) {
	        MAX_BONE_ID = pointTable[i].BONE_ID;
	    }
        }
	MAX_BONE_ID = MAX_BONE_ID / 2;	
        /* map bone possible bone IDs to RGB values */ 
	if ( MAX_BONE_ID > 0 ) {
	    RGB_MAPPER_COLOUR = G_malloc ( sizeof ( int ) * MAX_BONE_ID );
            for ( i = 0; i < MAX_BONE_ID; i ++ ) {
		RGB_MAPPER_COLOUR[i] = RGBNUM_BONE;
		RGBNUM_BONE ++;
		if ( RGBNUM_BONE == RGBMAX ) {
		    RGBNUM_BONE = 0;
		}
            }	    	    
	}
    }
    
    G_percent ( 4, 4, 1 );

}
Ejemplo n.º 24
0
void preprocess_input(std::string &str) {
	cleanString(str);
	UpperCase(str);
}
Ejemplo n.º 25
0
/*!

*/
bool
RCSSParamParser::init( const char * msg )
{
    char buf[32];
    int n_read = 0;
    if ( std::sscanf( msg, " ( %31s %n", buf, &n_read ) != 1 )
    {
        std::cerr << "***ERROR*** RCSSParamParser. "
                  << "Failed to parse parameter type name. "
                  << msg
                  << std::endl;
        return false;
    }

    M_param_name = buf;

    const std::string msg_str( msg );

    for ( std::string::size_type pos = msg_str.find_first_of( '(', n_read );
          pos != std::string::npos;
          pos = msg_str.find_first_of( '(', pos ) )
    {
        std::string::size_type end_pos = msg_str.find_first_of( ' ', pos );
        if ( end_pos == std::string::npos )
        {
            std::cerr << "***ERROR*** RCSSParamParser. "
                      << "Failed to parse parameter name. "
                      << msg
                      << std::endl;
            return false;
        }

        pos += 1;
        const std::string name_str( msg_str, pos, end_pos - pos );

        pos = end_pos;
        // search end paren or double quatation
        end_pos = msg_str.find_first_of( ")\"", end_pos ); //"
        if ( end_pos == std::string::npos )
        {
            std::cerr << "***ERROR*** RCSSParamParser. "
                      << "Failed to parse parameter value for ["
                      << name_str << "] in "
                      << msg
                      << std::endl;
            return false;
        }

        // found string type value
        if ( msg_str[end_pos] == '\"' ) // "
        {
            pos = end_pos;
            end_pos = msg_str.find_first_of( '\"', end_pos + 1 ); //"
            if ( end_pos == std::string::npos )
            {
                std::cerr << "***ERROR*** RCSSParamParser. "
                          << "Failed to parse string parameter value for ["
                          << name_str << "] in "
                          << msg
                          << std::endl;
                return false;
            }
            end_pos += 1; // skip double quatation
        }
        else
        {
            pos += 1; // skip white space
        }

        std::string value_str( msg_str, pos, end_pos - pos );
        value_str = cleanString( value_str );

        M_str_pairs.push_back( std::make_pair( name_str, value_str ) );

        pos = end_pos;
    }

    return true;
}
Ejemplo n.º 26
0
void SslServer::process(const PeerData &pd)
{
    QByteArray data = pd.data;

    if (data.isEmpty())
        return;

    quint8 command = getValue<quint8>(data.mid(0, 1));
    data.remove(0, 1);

    QSslSocket *socket = m_socket_hash[pd.descriptor];

    if (!socket)
        return;

    switch (command)
    {
    case ServerCommand::PeerTryConnect:
    {
        if (data.size() != 20)
        {
            removeSocket(socket);
            return;
        }

        QByteArray peer_id = data;

        peer_id = cleanString(QLatin1String(peer_id)).toLatin1().leftJustified(peer_id.length(), char(0), true);

        if (m_unavailable_list.contains(peer_id))
        {
            DEBUG_FUNCTION("IP:" << qPrintable(socket->peerAddress().toString()) << "User origin:" << qPrintable(m_id_hash.value(socket))
                           << "User target:" << qPrintable(peer_id) << "Attempt to connect to unavailable user!");
            writeWarning(socket, "You're trying to connect to a unavailable user!");
            return;
        }

        if (peer_id == m_id_hash[socket])
        {
            DEBUG_FUNCTION("IP:" << qPrintable(socket->peerAddress().toString()) << "User origin:" << qPrintable(m_id_hash.value(socket))
                           << "User target:" << qPrintable(peer_id) << "Attempt to connect to itself!");
            writeWarning(socket, "You're trying to connect to itself!");
            return;
        }

        if (!m_id_list.contains(peer_id))
        {
            DEBUG_FUNCTION("IP:" << qPrintable(socket->peerAddress().toString()) << "User origin:" << qPrintable(m_id_hash.value(socket))
                           << "User target:" << qPrintable(peer_id) << "Attempt to connect to non connected user!");
            writeWarning(socket, "You're trying to connect to a non connected user!");
            return;
        }

        QSslSocket *target_socket = m_id_hash.key(peer_id);

        if (m_connecting_connected_list.contains(target_socket))
        {
            DEBUG_FUNCTION("IP:" << qPrintable(socket->peerAddress().toString()) << "User origin:" << qPrintable(m_id_hash.value(socket))
                           << "User target:" << qPrintable(peer_id) << "Attempt to connect to already connected user!");
            writeWarning(socket, "User already connected!");
            return;
        }

        m_connecting_connected_list.append(socket);
        m_connecting_connected_list.append(target_socket);

        QByteArray data;
        data.append(getBytes<quint8>(ServerCommand::ConnectionRequested));
        data.append(getBytes<quint32>(socket->localAddress().toIPv4Address()));
        data.append(m_id_hash[socket]);

        m_accept_hash.insert(target_socket, socket);

        DEBUG_FUNCTION("IP:" << qPrintable(socket->peerAddress().toString()) << "User origin:" << qPrintable(m_id_hash.value(socket))
                       << "User target:" << qPrintable(peer_id) << "Trying to connect to peer!");

        target_socket->write(getBytes<qint32>(data.size()));
        target_socket->write(data);

        break;
    }
    case ServerCommand::ConnectionAnswer:
    {
        if (data.size() != 1)
        {
            removeSocket(socket);
            return;
        }

        QSslSocket *socket_starter = m_accept_hash[socket];

        bool accepted = getValue<bool>(data.mid(0, 1));

        if (!socket_starter)
        {
            m_connecting_connected_list.removeAll(socket_starter);
            m_connecting_connected_list.removeAll(socket);

            if (accepted)
            {
                DEBUG_FUNCTION("IP:" << qPrintable(socket->peerAddress().toString()) << "User origin:" << qPrintable(m_id_hash.value(socket))
                               << "User disconnected or canceled operation!");
                writeWarning(socket, "Can't connect to user because it's disconnected or canceled operation!");
            }

            return;
        }

        if (!accepted)
        {
            QSslSocket *socket1 = socket_starter;
            QSslSocket *socket2 = socket;

            m_accept_hash.remove(socket1);
            m_accept_hash.remove(socket2);

            m_connecting_connected_list.removeAll(socket1);
            m_connecting_connected_list.removeAll(socket2);

            DEBUG_FUNCTION("IP:" << qPrintable(socket->peerAddress().toString()) << "User origin:" << qPrintable(m_id_hash.value(socket))
                           << "User target:" << qPrintable(m_id_hash.value(socket_starter)) << "User refused connection!");
            writeWarning(socket_starter, "User refused connection!");

            return;
        }

        QSslSocket *socket1 = socket;
        QSslSocket *socket2 = socket_starter;

        m_connected_1.insert(socket1, socket2);
        m_connected_2.insert(socket2, socket1);

        QByteArray data1;
        QByteArray data2;

        data1.append(getBytes<quint8>(ServerCommand::ConnectedToPeer));
        data2.append(getBytes<quint8>(ServerCommand::ConnectedToPeer));

        QByteArray password = OpenSslLib::RANDbytes(32);

        data1.append(m_id_hash[socket1]);
        data1.append(password);

        data2.append(m_id_hash[socket2]);
        data2.append(password);

        socket1->write(getBytes<qint32>(data2.size()));
        socket1->write(data2);

        socket2->write(getBytes<qint32>(data1.size()));
        socket2->write(data1);

        DEBUG_FUNCTION("IP:" << qPrintable(socket->peerAddress().toString()) << "User origin:" << qPrintable(m_id_hash.value(socket_starter))
                       << "User target:" << qPrintable(m_id_hash.value(socket)) << "Connected!");

        break;
    }
    case ServerCommand::DisconnectedFromPeer:
    {
        QSslSocket *target_socket = m_connected_1.value(socket);

        if (!target_socket)
            target_socket = m_connected_2.value(socket);

        DEBUG_FUNCTION("IP:" << qPrintable(socket->peerAddress().toString()) << "User origin:" << qPrintable(m_id_hash.value(socket))
                       << "User target:" << qPrintable(m_id_hash.value(target_socket)) << "Disconnected from peer!");

        disconnectedFromPeer(socket);

        break;
    }
    case ServerCommand::P2PData:
    {
        QSslSocket *target_socket = m_connected_1.value(socket);

        if (!target_socket)
            target_socket = m_connected_2.value(socket);

        if (!target_socket)
            break;

        data.prepend(getBytes<quint8>(ServerCommand::P2PData));

        target_socket->write(getBytes<qint32>(data.size()));
        target_socket->write(data);

        m_alive_hash[socket].restart();

        m_alive_hash[target_socket].restart();

        break;
    }
    case ServerCommand::Alive:
    {
        m_alive_hash[socket].restart();

        break;
    }
    case ServerCommand::XML:
    {
        processCommandXML(socket, data);

        break;
    }
    default:
    {
        removeSocket(socket);
        return;
    }
    }
}
Ejemplo n.º 27
0
void initialize(char * helpFileName, char * dataFileName,
				char * macroFileName,
				char * dataPath, char * macroPath, char * homePath,
				promptType prompt)
{
	long            i;
	Symbolhandle    symh, symh1;
	long            length, nMacroFiles = 0, nPaths = 0;
	long            nBuiltins = 0;
	char           *dataPathName = (char *) 0, *macroPathName = (char *) 0;
	char           *macroFileNames[NMACROFILES+1];
	char           *place;
	char            completePath[PATHSIZE+1];
	char           *pathName;
	double          value;
#ifdef READLINE
#if defined(INPUTRCFILE) || defined(DEFAULTINPUTRC)
	Keymap           keymap; /* current keymap */
	char            *backwardkillword = "\033\010"; /*Esc-Backspace*/
	FILE            *readlineBindings = (FILE *) 0;
	Symbolhandle     symhPath = (Symbolhandle) 0;
#endif /*defined(INPUTRCFILE) || defined(DEFAULTINPUTRC)*/
#endif /*READLINE*/
	WHERE("initialize");

	getElapsedTime((double *) 0); /* save current time */
	getElapsedTime((double *) 0); /* do it twice for good measure */


#if defined(MSDOS)
	pathName = get_dataPath();
	for (i = 0; pathName[i] != '\0'; i++)
	{ /* make sure all path separators are '\\' */
		if (pathName[i] == '/')
		{
			pathName[i] = DIRSEPARATOR[0];
		}
	} /*for (i == 0; pathName[i] != '\0'; i++)*/
#elif defined(MACINTOSH)
	/* macGetPath() returns address of completePath */
	pathName = macGetPath(completePath, HomeVolume, HomeDirectory);
#elif defined(UNIX)
	pathName = getenv("HOME");
#elif defined(VMS)
	pathName = getenv("ANOVA$HOME");
	dataPathName = 	macroPathName = pathName;
#endif

	if (pathName == (char *) 0)
	{
		completePath[0] = '\0';
	} /*if (pathName == (char *) 0)*/
	else
	{		
		if (pathName != completePath)
		{
			strncpy(completePath, pathName, PATHSIZE);
			completePath[PATHSIZE] = '\0';
		}
		length = strlen(completePath);
#ifndef NOSEPARATOR
		if (completePath[length-1] != DIRSEPARATOR[0] && length < PATHSIZE)
		{
			strcat(completePath, DIRSEPARATOR);
		}
#endif /*NOSEPARATOR*/
	} /*if (pathName == (char *) 0){}else{}*/

	homePath = (homePath != (char *) 0) ? homePath : completePath ;

#if !defined(UNIX) && !defined(VMS)
	if (completePath[0] != '\0')
	{
		dataPathName = (dataPath != (char *) 0) ? dataPath : completePath;
		macroPathName = (macroPath != (char *) 0) ? macroPath : completePath;
	}
	else
#endif /*UNIX*/
/* use defined values on Unix which should have trailing '/' */
	{
		dataPathName = (dataPath != (char *) 0) ? dataPath : DATAPATHNAME;
		macroPathName = (macroPath != (char *) 0) ? macroPath : MACROPATHNAME;
	}
	
/*  initialized math constants */
	MV_E    = exp(1);
	MV_PI_4 = atan(1.0);
	MV_PI_2 = 2.0*MV_PI_4;
	MV_PI   = 4.0*MV_PI_4;

#ifdef M_E
	MV_LOG2E    =       M_LOG2E;
	MV_LOG10E   =      M_LOG10E;
	MV_LN2      =         M_LN2;
	MV_LN10     =        M_LN10;
	MV_1_PI     =        M_1_PI;
	MV_2_PI     =        M_2_PI;
	MV_2_SQRTPI =    M_2_SQRTPI;
	MV_SQRT2    =       M_SQRT2;
#ifdef M_SQRT1_2
	MV_SQRT1_2  =     M_SQRT1_2;
#else /*M_SQRT1_2*/
	MV_SQRT1_2  =      M_SQRT_2; /*Borland math.h name of constant */
#endif /*M_SQRT1_2*/
#else /*M_E*/
	MV_LOG2E    =  1.4426950408889634074;
	MV_LOG10E   = 0.43429448190325182765;
	MV_LN2      = 0.69314718055994530942;
	MV_LN10     = 2.30258509299404568402;
	MV_1_PI     = 0.31830988618379067154;
	MV_2_PI     = 0.63661977236758134308;
	MV_2_SQRTPI = 1.12837916709551257390;
	MV_SQRT2    = 1.41421356237309504880;
	MV_SQRT1_2  = 0.70710678118654752440;
#endif /*M_E*/

	if (!inputInit())
	{ /* allocate space for INPUTSTRINGS and ISTRCHARS*/
		goto fatalError;
	}

	/*
	  Allocate space for globals, BATCHECHO, INPUTFILE, INPUTFILENAMES,
	  LASTINPUTWASCR, PROMPTS
	  */
	if (!batchInit())
	{
		goto fatalError;
	}
	
	if(!Symbolinit())
	{ /* create size TABLESIZE symbol table and zero it out*/
		goto fatalError;
	}

	if(!glmInit())
	{ /* allocate glm related globals */
		goto fatalError;
	}

	/* create fake handles for function symbols */
	for (nBuiltins = 0; builtins[nBuiltins].name; nBuiltins++)
	{ /* count builtins */
		;
	}
	FunctionPointers = (Symbol **) mygetpointer(nBuiltins * sizeof(Symbol *));
	FunctionSymbols = (FunctionSymbol *) mygetpointer(nBuiltins*
													  sizeof(FunctionSymbol));
	if(FunctionPointers == (Symbol **) 0 ||
	   FunctionSymbols == (FunctionSymbol *) 0)
	{
		goto fatalError;
	}

	for (i = 0;i<nBuiltins; i++)
	{ /* make fake Symbolhandle for each builtin function */
		symh = FunctionPointers + i;
		*symh = (Symbol *) (FunctionSymbols+i);
		setTYPE(symh, BLTIN);
		markFakeSymbol(symh); /* indicates it's fake if we ever need to know */
		setNDIMS(symh, 1);
		setDIM(symh, 1, 1);
		setPREV(symh, (Symbolhandle) 0);
		setNEXT(symh, (Symbolhandle) 0);
		setFPTR(symh, builtins[i].function);
		setNAME(symh, builtins[i].name);
		Addsymbol(symh);
	} /*for (i = 0;i<nBuiltins; i++)*/

	/* now install pre-defined constants */
	for (i = 0; constants[i].name; i++)
	{
		symh = RInstall(constants[i].name, 1L);
		if(symh == (Symbolhandle) 0)
		{
			goto fatalError;
		}
		if(strcmp(NAME(symh),"PI") == 0)
		{
			value = MV_PI;
		}
		else if(strcmp(NAME(symh),"E") == 0)
		{
			value = MV_E;
		}
		else if(strcmp(NAME(symh),"DEGPERRAD") == 0)
		{
			value = 45.0/MV_PI_4;
		}
		else
		{
			value = constants[i].value;
		}
		DATAVALUE(symh,0) = value;
	} /*for (i = 0; constants[i].name; i++)*/

	/*
	  Create NULLSYMBOL (value returned by print(), etc.
	  Note that it is *not* installed in the symbol table
	*/
	NULLSYMBOL = Makesymbol(NULLSYM);
	if(NULLSYMBOL == (Symbolhandle) 0)
	{
		goto fatalError;
	}
	setNAME(NULLSYMBOL, "NULLSYMBOL");

	 /* initialize special symbol CLIPBOARD */
	if (!iniClipboard(CLIPBOARDNAME))
	{
		goto fatalError;
	}

#ifdef HASSELECTION
	 /* initialize special symbol SELECTION */
	if (!iniClipboard(SELECTIONNAME))
	{
		goto fatalError;
	}
#endif /*HASSELECTION*/
	/* install pre-defined macros */
	if (!iniMacros())
	{
		goto fatalError;
	}
	
	/* install pre-defined string variables (they must all be scalar) */

	for (i = 0; stringvars[i].name; i++)
	{
		
		symh = CInstall(stringvars[i].name, strlen(stringvars[i].string) + 1);
		if(symh == (Symbolhandle) 0)
		{
			goto fatalError;
		}
		strcpy(STRINGPTR(symh), stringvars[i].string);
		cleanString(STRINGPTR(symh));
	} /*for (i = 0; stringvars[i].name; i++)*/

	/*
	   set value for MISSING and infinities
	*/

#if LONGSPERDOUBLE == 2
	setBdouble(Missing, HIMISSING, LOWMISSING);
#ifdef HASINFINITY
	setBdouble(PlusInfinity, HIPLUSINFINITY, LOWPLUSINFINITY);
	setBdouble(MinusInfinity, HIMINUSINFINITY, LOWMINUSINFINITY);
#endif /*HASINFINITY*/
#else /*LONGSPERDOUBLE == 2*/
	MISSING = MISSINGVALUE; /* may have to do something fancier than this */
#ifdef HASINFINITY
	PLUSINFINITY = 1.0/0.0;
	MINUSINFINITY = -1.0/0.0;
#endif /*HASINFINITY*/
#endif /*LONGSPERDOUBLE == 2*/

/*
  TOOBIGVALUE should be HUGE_VAL which may be infinite
*/
#ifndef NOSTRTOD
	TOOBIGVALUE = mystrtod(TOOBIGVALUESTRING,(char **) 0);
#else /*NOSTRTOD*/
#ifdef HUGE_VAL
	TOOBIGVALUE = HUGE_VAL;
#else /*HUGE_VAL*/
	TOOBIGVALUE = exp(1e200);
#endif /*HUGE_VAL*/
#endif /*NOSTRTOD*/

	OLDMISSING = OLDMISSINGVALUE;  /* -99999.9999 */
	
	setDefaultOptions(); /* set default options */
	if (prompt[0] != '\0')
	{
		strcpy((char *) DEFAULTPROMPTS[0], (char *) prompt);
	}
	strcpy((char *) PROMPTS[0], (char *) DEFAULTPROMPTS[0]);
	
#ifdef VERSION
	sprintf(OUTSTR,"MacAnova %s ",VERSION);
#ifdef TODAY
	strcat(OUTSTR,TODAY);
#endif /*TODAY*/
	symh = CInstall("VERSION", strlen(OUTSTR) + 1);
	if(symh == (Symbolhandle) 0)
	{
		goto fatalError;
	}
	strcpy(STRINGPTR(symh),OUTSTR);
	*OUTSTR = '\0';
	VERSION_ID = myduphandle(STRING(symh));
	if(VERSION_ID == (char **) 0)
	{
		goto fatalError;
	}
#endif /*VERSION*/

	/* Create global HELPFILENAME*/
	if(helpFileName == (char *) 0)
	{
		helpFileName = HELPNAME;
#ifdef UNIX
		pathName = HELPPATHNAME;
#elif	defined(VMS)
		pathName = getenv("ANOVA$HOME");
#else /*UNIX*/
		pathName = completePath;
#endif /*UNIX*/
	}
	else
	{
		pathName = NullString;
	}
	length = strlen(pathName) + strlen(helpFileName);
	
	HELPFILENAME = mygethandle(length + 1);
	if(HELPFILENAME == (char **) 0)
	{
		goto fatalError;
	}
	strcpy(*HELPFILENAME,pathName);
	strcat(*HELPFILENAME,helpFileName);

/*   Install CHARACTER scalar DATAPATH containing dataPathName */
	length = strlen(dataPathName);
#ifndef NOSEPARATOR
	if (dataPathName[length-1] != DIRSEPARATOR[0])
	{
		length++;
	}
#endif /*NOSEPARATOR*/
	symh = CInstall("DATAPATH",length + 1);
	if (symh == (Symbolhandle) 0)
	{
		goto fatalError;
	}
	strcpy(STRINGPTR(symh),dataPathName);
#ifndef NOSEPARATOR
	STRINGVALUE(symh, length-1) = DIRSEPARATOR[0];
	STRINGVALUE(symh, length) = '\0';
#endif /*NOSEPARATOR*/
/* 
   Install CHARACTER vector DATAPATHS containing dataPathName and
   macroPathName.  If they are the same, they are not duplicated
*/
	nPaths = 1;
	if (strcmp(macroPathName, dataPathName) != 0 &&
		strcmp(macroPathName, STRINGPTR(symh)) != 0)
	{
		long      length2 = strlen(macroPathName);
		
		length++; /* account for trailing null of dataPathName */
		nPaths = 2;
#ifndef NOSEPARATOR
		if (macroPathName[length2-1] != DIRSEPARATOR[0])
		{
			length2++;
		}
#endif /*NOSEPARATOR*/
		length += length2;
	}
	
	symh1 = CInstall("DATAPATHS",length + 1);
	if (symh1 == (Symbolhandle) 0)
	{
		goto fatalError;
	}
	strcpy(STRINGPTR(symh1),STRINGPTR(symh));
	if (nPaths > 1)
	{
		strcpy(skipStrings(STRINGPTR(symh1), 1), macroPathName);
#ifndef NOSEPARATOR
		STRINGVALUE(symh1,length-1) = DIRSEPARATOR[0];
		STRINGVALUE(symh1,length) = '\0';
#endif /*NOSEPARATOR*/
	}
	setDIM(symh1, 1, nPaths);
	
	/* pre-install CHARACTER scalar HOME */
	length = strlen(homePath);

	if(length > 0)
	{
#ifndef NOSEPARATOR
		if (homePath[length-1] != DIRSEPARATOR[0])
		{ /* make room for terminating separator */
			length++;
		}
#endif /*NOSEPARATOR*/
		symh = CInstall("HOME",length + 1);
		if (symh == (Symbolhandle) 0)
		{
			goto fatalError;
		}
		strcpy(STRINGPTR(symh),homePath);
#ifndef NOSEPARATOR
		/* make sure HOME terminates with DIRSEPARATOR[0]*/
		STRINGVALUE(symh, length-1) = DIRSEPARATOR[0];
		STRINGVALUE(symh, length) = '\0';
#endif /*NOSEPARATOR*/
#ifdef MSDOS
		{
			char       *pc;
		
			for (pc = STRINGPTR(symh); *pc != '\0'; pc++)
			{ /* ensure all separators are standard backslashes*/
				if (*pc == '/')
				{
					*pc = DIRSEPARATOR[0];
				}
			} /*for (pc = STRINGPTR(symh); *pc != '\0'; pc++)*/
		}
#endif /*MSDOS*/
	} /*if(length > 0)*/

	/* install CHARACTER scalar DATAFILE */
	if(dataFileName == (char *) 0)
	{
		dataFileName = DATAFILENAME;
	}
	
	length = strlen(dataFileName);

	symh = CInstall("DATAFILE", length + 1);
	if (symh == (Symbolhandle) 0)
	{
		goto fatalError;
	}

	strcpy(STRINGPTR(symh), dataFileName);

	/* Install CHARACTER scalar MACROFILE and CHARACTER vector MACROFILES*/
	for (i = 0; i < NMACROFILES + 1; i++)
	{
		macroFileNames[i] = NullString;
	}
	if (macroFileName != (char *) 0)
	{
		macroFileNames[nMacroFiles++] = macroFileName;
	}
	macroFileNames[nMacroFiles++] = MACROFILENAME;
	macroFileNames[nMacroFiles++] = TSMACROFILENAME;
	macroFileNames[nMacroFiles++] = DESIGNMACROFILENAME;
	macroFileNames[nMacroFiles++] = ARIMAMACROFILENAME;

	length = strlen(macroFileNames[0]) + 1;

	symh = CInstall("MACROFILE",length);
	if(symh == (Symbolhandle) 0)
	{
		goto fatalError;
	}
	strcpy(STRINGPTR(symh), macroFileNames[0]);
	
	length = 0;
	for (i = 0; i < nMacroFiles; i++)
	{
		length += strlen(macroFileNames[i]) + 1;
	}
	symh = CInstall("MACROFILES", length);
	if (symh == (Symbolhandle) 0)
	{
		goto fatalError;
	}
	setDIM(symh, 1, nMacroFiles);
	place = STRINGPTR(symh);
	for (i = 0; i < nMacroFiles; i++)
	{
		place = copyStrings(macroFileNames[i], place, 1);
	}
	
#ifdef READLINE
	/* Initialize line editing and history */
#if defined(INPUTRCFILE) || defined(DEFAULTINPUTRC)
	using_history(); /*added 980108*/
	rl_initialize(); /*added 980106 */
	rl_initialize_funmap();
	keymap = rl_get_keymap();
	if (keymap != (Keymap) 0)
	{ /* this binding is standard but not the default in readline 1.1 */
		rl_set_key (backwardkillword, rl_backward_kill_word, keymap);
	} /*if (keymap != (Keymap) 0)*/
#ifndef INPUTRCFILE
	pathName = OUTSTR;
	strcpy(pathName, dataPathName);
	strcat(pathName, DEFAULTINPUTRC);
#else /*INPUTRCFILE*/
	pathName = INPUTRCFILE;
#endif /*INPUTRCFILE*/
	if (pathName[0] != '\0')
	{
		readlineBindings = fmyopen(pathName, TEXTREADMODE);
		if (readlineBindings != (FILE *) 0)
		{
			fclose(readlineBindings);
			rl_read_init_file(pathName);
		} /*if (readlineBindings != (FILE *) 0)*/
	} /*if (pathName[0] != '\0')*/
#endif /*defined(INPUTRCFILE) || defined(DEFAULTINPUTRC)*/
#endif /*READLINE*/

/*
   initialize or clear virtually everything in sight
*/
	*OUTSTR = '\0';
	for (i = 0;i < MAXWDEPTH;i++)
	{
		WHILELIMITS[i] = MAXWHILE;
		FORVECTORS[i] = (double **) 0;
	}
	clearGlobals();

	INPUTFILE[0] = STDIN;
	INPUTFILENAMES[0] = &StdinName;

	for (i=1;i<MAXBDEPTH;i++)
	{
		INPUTFILE[i] = (FILE *) 0;
		INPUTFILENAMES[i] = (char **) 0;
	}

	TMPHANDLE = mygethandle(sizeof(double)); /*warehouseable length*/
	if(TMPHANDLE == (char **) 0)
	{
		goto fatalError;
	}
	INPUTSTRING = ThisInputstring = (unsigned char **) TMPHANDLE;
	(*INPUTSTRING)[0] = '\0';

	GUBED = 0; /* this is here to make it easy to change for debugging */

#ifdef DJGPP
	INTERRUPT = INTSET;
	(void) interrupted(0); /* to get DJGPP started */
	INTERRUPT = INTNOTSET;
#endif /*DJGPP*/
#if defined(BCPP) || defined (wx_msw)
	(void) _control87(EM_OVERFLOW,EM_OVERFLOW);
#endif /*BCPP||wxmsw*/

#ifdef wx_motif
#if (0) /* inititalization now done in base frame initializer */
	initializePSPrinter();
#endif
#endif /*wx_motif*/
	return ;

  fatalError:
	FatalError = 1;
	
} /*initialize()*/
Ejemplo n.º 28
0
void * clientHandler(void * arg) {
	threadStruct *inArg = (threadStruct *) arg;
	int sockfd = inArg->sockfd;
	free(inArg);

	char *msg = malloc(sizeof(char)*CMD_MAX_SIZE);
	*msg = '\0';
	msgHeader header;
	User user;

	// Agregar usuario
	readBytes(sockfd, (void *) &header,sizeof(header));
	readBytes(sockfd, (void *) msg, header.msgSize);
	cleanString(msg);

	user.sockfd = sockfd;
	strncpy(user.name,msg,NAMES_SIZE);
	*(user.name + NAMES_SIZE -1) = '\0';

	list_append(&Users,(void *) &user);

	// Agregar a la sala default #!

	while (1) {

		// Leer un mensaje del cliente
		readBytes(sockfd, (void *) &header,sizeof(header));
		readBytes(sockfd, (void *) msg, header.msgSize);
		cleanString(msg);

		switch (header.code) {

		case MSG_CODE_SHUT:
			break; // #! NOT DONE

		case MSG_CODE_SAL:
			sal(sockfd);
			break;
		case MSG_CODE_USU:
			usu(sockfd);
			break;
		case MSG_CODE_MEN:
			men(sockfd,msg);
			break;
		case MSG_CODE_SUS:
			sus(sockfd,msg);
			break;
		case MSG_CODE_DES:
			des(sockfd);
			break;
		case MSG_CODE_CRE:
			cre(sockfd,msg);
			break;
		case MSG_CODE_ELI:
			// eli() #!
			break;
		case MSG_CODE_FUE:
			fue(sockfd);
			free(msg);
			pthread_exit(NULL);
			break;
		}

		*msg = '\0';
	}
	return NULL;
}
Ejemplo n.º 29
0
void SslServer::processCommandXML(QSslSocket *socket, const QByteArray &data)
{
    qint32 argc;

    QString cmd;

    QByteArray arg1, arg2, arg3, arg4, arg5,
            arg6, arg7, arg8, arg9, arg10;

    if (!XMLReader(data, &argc, &cmd,
                   &arg1, &arg2, &arg3, &arg4, &arg5,
                   &arg6, &arg7, &arg8, &arg9, &arg10))
    {
        writeWarning(socket, "Invalid XML", true);
        return;
    }

    if (cmd == "LOGIN")
    {
        if (arg1.isEmpty() || arg2.isEmpty()
                || arg3.isEmpty() || arg4.isEmpty()
                || arg5.isEmpty())
        {
            writeWarning(socket, "Invalid XML", true);
            return;
        }

        QByteArray peer_negotiation_string = arg1;
        QByteArray peer_id = arg2;
        QByteArray password = arg3;
        bool user_unavailable = getValue<bool>(arg4);
        bool new_user = getValue<bool>(arg5);
        QString code = QLatin1String(arg6);

        if (peer_negotiation_string != NEGOTIATION_STRING)
        {
            DEBUG_FUNCTION("IP:" << qPrintable(socket->peerAddress().toString()) << "User origin:" << qPrintable(peer_id)
                           << "Invalid NEGOTIATION STRING!");
            writeWarning(socket, "Invalid NEGOTIATION STRING!", true);
            return;
        }

        if (m_id_list.contains(peer_id))
        {
            DEBUG_FUNCTION("IP:" << qPrintable(socket->peerAddress().toString()) << "User origin:" << qPrintable(peer_id)
                           << "This user is already connected!");
            writeWarning(socket, "This user is already connected!", true);
            return;
        }

        if (new_user)
        {
            if (m_sql.userExists("root"))
            {
                if (!m_code_list.contains(code))
                {
                    DEBUG_FUNCTION("IP:" << qPrintable(socket->peerAddress().toString()) << "User origin:" << qPrintable(peer_id)
                                   << "Invalid code!");
                    writeWarning(socket, "Invalid code!", true);
                    return;
                }
                else
                {
                    m_code_list.removeAll(code);
                }
            }
            else if (cleanString(QLatin1String(peer_id)) != "root")
            {
                DEBUG_FUNCTION("IP:" << qPrintable(socket->peerAddress().toString()) << "User origin:" << qPrintable(peer_id)
                               << "Need to create root account first!");
                writeWarning(socket, "Need to create root account first!", true);
                return;
            }

            if (m_sql.userExists(cleanString(QLatin1String(peer_id))))
            {
                DEBUG_FUNCTION("IP:" << qPrintable(socket->peerAddress().toString()) << "User origin:" << qPrintable(peer_id)
                               << "User already exists!");
                writeWarning(socket, "User already exists!", true);
                return;
            }
            else if (!m_sql.createUser(cleanString(QLatin1String(peer_id)), cleanString(QLatin1String(password))))
            {
                DEBUG_FUNCTION("IP:" << qPrintable(socket->peerAddress().toString()) << "User origin:" << qPrintable(peer_id)
                               << "Can't create new user!");
                writeWarning(socket, "Can't create new user!", true);
                return;
            }
        }

        if (!m_sql.loginUser(cleanString(QLatin1String(peer_id)), cleanString(QLatin1String(password))))
        {
            DEBUG_FUNCTION("IP:" << qPrintable(socket->peerAddress().toString()) << "User origin:" << qPrintable(peer_id)
                           << "Can't login with this user and password!");
            writeWarning(socket, "Can't login with this user and password!", true);
            return;
        }

        DEBUG_FUNCTION("IP:" << qPrintable(socket->peerAddress().toString()) << "User origin:" << qPrintable(peer_id)
                       << "User logged in!");

        m_id_list.append(peer_id);
        m_id_hash.insert(socket, peer_id);

        if (user_unavailable)
            m_unavailable_list.append(peer_id);

        QByteArray data;
        data.append(getBytes<quint8>(ServerCommand::LoggedIn));

        socket->write(getBytes<qint32>(data.size()));
        socket->write(data);
    }
    else if (cmd == "REQUEST_SETTINGS")
    {
        QString ui_path;
        QString js_path;

        QString id = QLatin1String(m_id_hash[socket]);

        if (id != "root")
        {
            ui_path = "../data/settings.ui";
            js_path = "../data/settings.js";
        }
        else
        {
            ui_path = "../data/settings_root.ui";
            js_path = "../data/settings_root.js";
        }

        QFile ui_file(ui_path);
        QFile js_file(js_path);

        if (!ui_file.open(QFile::ReadOnly) || !js_file.open(QFile::ReadOnly))
        {
            DEBUG_FUNCTION("Can't send settings file");
            writeWarning(socket, "Can't send settings file", true);
            return;
        }

        QByteArray ui_data = ui_file.readAll();
        QByteArray js_data = js_file.readAll();

        QByteArray xml_data = XMLWriter("SETTINGS", ui_data, js_data);
        writeCommandXML(socket, xml_data);
    }
    else if (cmd == "DELETE_ACCOUNT")
    {
        QString id = QLatin1String(m_id_hash[socket]);

        if (id == "root")
        {
            DEBUG_FUNCTION("IP:" << qPrintable(socket->peerAddress().toString()) << "User origin:" << qPrintable(m_id_hash.value(socket))
                           << "Invalid operation!");
            writeWarning(socket, "Invalid operation!", true);
            return;
        }

        if (m_sql.deleteUser(id))
        {
            DEBUG_FUNCTION("IP:" << qPrintable(socket->peerAddress().toString()) << "User origin:" << qPrintable(m_id_hash.value(socket))
                           << "User deleted sucessfully!");
            writeWarning(socket, "User deleted sucessfully!", true);
        }
        else
        {
            DEBUG_FUNCTION("IP:" << qPrintable(socket->peerAddress().toString()) << "User origin:" << qPrintable(m_id_hash.value(socket))
                           << "Error deleting user!");
            writeWarning(socket, "Error deleting user!", true);
        }
    }
    else if (cmd == "CHANGE_ACCOUNT_PASSWORD")
    {
        if (arg1.isEmpty())
        {
            writeWarning(socket, "Invalid XML", true);
            return;
        }

        QByteArray password = arg1;

        if (m_sql.changePassword(m_id_hash[socket], cleanString(QLatin1String(password))))
        {
            DEBUG_FUNCTION("IP:" << qPrintable(socket->peerAddress().toString()) << "User origin:" << qPrintable(m_id_hash.value(socket))
                           << "User password changed sucessfully!");
            writeWarning(socket, "User password changed sucessfully!", true);
        }
        else
        {
            DEBUG_FUNCTION("IP:" << qPrintable(socket->peerAddress().toString()) << "User origin:" << qPrintable(m_id_hash.value(socket))
                           << "Error changing user password!");
            writeWarning(socket, "Error changing user password!", true);
        }
    }
    else if (cmd == "REQUEST_CODE")
    {
        QByteArray id = m_id_hash[socket];

        if (QLatin1String(id) != "root")
        {
            DEBUG_FUNCTION("IP:" << qPrintable(socket->peerAddress().toString()) << "User origin:" << qPrintable(m_id_hash.value(socket))
                           << "Invalid operation!");
            writeWarning(socket, "Invalid operation!", true);
            return;
        }

        QString code;

        do
        {
            code = QString(OpenSslLib::RANDbytes(4).toHex());
            code.prepend("#");
        }
        while (m_code_list.contains(code));

        m_code_list.append(code);

        QTimer::singleShot(60 * 60 * 1000, [=]{
            m_code_list.removeAll(code);
        });

        DEBUG_FUNCTION("IP:" << qPrintable(socket->peerAddress().toString()) << "User origin:" << qPrintable(m_id_hash.value(socket))
                       << "Sending code!");

        QByteArray xml_data = XMLWriter("CODE", "edit_code", code.toLatin1());
        writeCommandXML(socket, xml_data);
    }
    else
    {
        DEBUG_FUNCTION("IP:" << qPrintable(socket->peerAddress().toString()) << "User origin:" << qPrintable(m_id_hash.value(socket))
                       << "Invalid operation!");
        writeWarning(socket, "Invalid operation!", true);
    }
}
bool MailboxPostgreSQL::sendMail( unsigned int userID, MailboxContent& mailcontent )
{
    try
    {
        pqxx::result res;
        pqxx::work        transaction( *_p_databaseConnection, "mail_send" );
        std::string       query;
        std::stringstream userid;
        userid << userID;
        std::stringstream attr;
        attr << mailcontent._header._attributes;

        // strip out white spaces from names
        std::string to, cc;
        for ( std::size_t cnt = 0; cnt < mailcontent._header._to.size(); cnt++ )
        {
            if ( mailcontent._header._to[ cnt ] != ' ' )
                to += mailcontent._header._to[ cnt ];
        }
        for ( std::size_t cnt = 0; cnt < mailcontent._header._cc.size(); cnt++ )
        {
            if ( mailcontent._header._cc[ cnt ] != ' ' )
                cc += mailcontent._header._cc[ cnt ];
        }

        // make sure that the names are not repeated in the cc and to fields
        std::map< std::string, std::string > tomap;
        std::map< std::string, std::string > ccmap;
        std::vector< std::string > names;
        yaf3d::explode( to, ",", &names );

        for ( std::size_t cnt = 0; cnt < names.size(); cnt++ )
        {
            tomap[ names[ cnt ] ] = names[ cnt ];
        }

        names.clear();
        yaf3d::explode( cc, ",", &names );
        for ( std::size_t cnt = 0; cnt < names.size(); cnt++ )
        {
            if ( tomap.find( names[ cnt ] ) == tomap.end() )
                ccmap[ names[ cnt ] ] = names[ cnt ];
        }

        // re-assemble the cc and to fields via comma separation
        to.clear();
        cc.clear();
        std::map< std::string, std::string >::iterator p_to = tomap.begin(), p_toend = tomap.end();
        std::map< std::string, std::string >::iterator p_cc = ccmap.begin(), p_ccend = ccmap.end();;
        for ( std::size_t cnt = 0; p_to != p_toend; ++p_to, cnt++ )
        {
            to += "'" + p_to->first + "'";
            if ( cnt != tomap.size() - 1 )
                to += ",";
        }
        // consider also empty cc
        if ( p_cc == p_ccend )
        {
            cc = "''";
        }
        else
        {
            for ( std::size_t cnt = 0; p_cc != p_ccend; ++p_cc, cnt++ )
            {
                cc += "'" + p_cc->first + "'";
                if ( cnt != ccmap.size() - 1 )
                    cc += ",";
            }
        }

        // call the function for user login
        query = std::string( "SELECT " FCN_MAIL_SEND "(" + userid.str() + "," + attr.str() + ",ARRAY[" + to + "], ARRAY[" + cc + "], '" + cleanString( mailcontent._header._subject ) + "', '" +  cleanString( mailcontent._body ) + "');" );

        res = transaction.exec( query );

        // empty folder?
        if ( !res.size() )
        {
            log_error << "MailboxPostgreSQL: problem on sending mail " << userID << std::endl;
            return false;
        }

        int retvalue;
        res[ 0 ][ FCN_MAIL_SEND ].to( retvalue );
        if ( retvalue < 0 )
        {
            log_error << "MailboxPostgreSQL: problem on sending mail " << userID << ", error code: " << retvalue  << std::endl;
            return false;
        }

        // commit the transaction
        transaction.commit();
    }
    catch( const std::exception& e )
    {
        // store the error code into mail body in case of error
        mailcontent._body = e.what();
        log_error << "MailboxPostgreSQL: problem on sending mail " << userID << ", reason: " << e.what()  << std::endl;
        return false;
    }

    return true;
}