bool DatabasePostgre::Initialize(const char *infoString) { if(!Database::Initialize(infoString)) return false; tranThread = NULL; InitDelayThread(); Tokens tokens = StrSplit(infoString, ";"); Tokens::iterator iter; std::string host, port_or_socket_dir, user, password, database; iter = tokens.begin(); if(iter != tokens.end()) host = *iter++; if(iter != tokens.end()) port_or_socket_dir = *iter++; if(iter != tokens.end()) user = *iter++; if(iter != tokens.end()) password = *iter++; if(iter != tokens.end()) database = *iter++; if (host == ".") mPGconn = PQsetdbLogin(NULL, port_or_socket_dir == "." ? NULL : port_or_socket_dir.c_str(), NULL, NULL, database.c_str(), user.c_str(), password.c_str()); else mPGconn = PQsetdbLogin(host.c_str(), port_or_socket_dir.c_str(), NULL, NULL, database.c_str(), user.c_str(), password.c_str()); /* check to see that the backend connection was successfully made */ if (PQstatus(mPGconn) != CONNECTION_OK) { sLog.outError( "Could not connect to Postgre database at %s: %s", host.c_str(), PQerrorMessage(mPGconn)); PQfinish(mPGconn); mPGconn = NULL; return false; } else { sLog.outDetail( "Connected to Postgre database at %s", host.c_str()); sLog.outString( "PostgreSQL server ver: %d",PQserverVersion(mPGconn)); return true; } }
/// Check if the string is a valid ip address representation bool IsIPAddress(char const* ipaddress) { if(!ipaddress) return false; // FG: support IP ranges to be valid IP addresses, e.g. 192.168.0.%, 127.%.%.%, 1.2.3.4 Tokens tok = StrSplit(ipaddress, "."); if(tok.size() != 4) return false; for(Tokens::iterator it = tok.begin(); it != tok.end(); it++) { // must not be empty and not more then 3 chars per part if(it->empty() || it->size() > 3) return false; // must contain digits only or % (mysql wildcard) for(uint32 pos = 0; pos < it->size(); ++pos) if( !(isdigit((*it)[pos]) ||(*it)[pos] == '%') ) return false; // if its a number, it must be < 255 to be valid ip part if(atoi(it->c_str()) >= 255) return false; } return true; // -end- // Let the big boys do it. // Drawback: all valid ip address formats are recognized e.g.: 12.23,121234,0xABCD) //return ACE_OS::inet_addr(ipaddress) != INADDR_NONE; }
// ============================================================================ StatusCode Tuples::TupleObj::fill( const char* format ... ) { // check the underlying tuple if ( invalid() ) { return InvalidTuple ; } // decode format string into tokens Tokens tokens ; tokenize( format , tokens , " ,;" ); if ( tokens.empty() ) { return StatusCode::SUCCESS ; } /// decode arguments va_list valist ; va_start( valist , format ) ; // loop over all tokens StatusCode status = StatusCode::SUCCESS ; for( Tokens::const_iterator token = tokens.begin() ; tokens.end() != token && status.isSuccess() ; ++token ) { const double val = va_arg( valist , double ); status = column( *token , val ); if( status.isFailure() ) { Error ( "fill(): Can not add column '" + *token + "' " ) ; } } // mandatory !!! va_end( valist ); // return status ; }
int Bayes::Categorize(const string& item) { Tokens tokens; Tokenize(item, tokens); vector<double> probs; int i = 0; for(TokensIter it = tokens.begin(); it != tokens.end(); it++) if(prob.count(*it) > 0) probs.push_back(prob[*it]); else probs.push_back(0.4); sort(probs.begin(), probs.end()); double mult = 1, comb = 1; i = 0; for(vector<double>::reverse_iterator it = probs.rbegin(); it != probs.rend(); it++) { double p = *it; mult *= p; comb *= (1 - p); if(++i > 15) break; } double result = mult / (mult + comb); if(result >= 0.9) return -1; else if(result >= 0.3) return 1; else return 0; }
void Bayes::AddHam(const string& item, bool recalculate) { time(&tm); Tokens tokens; Tokenize(item, tokens); for(TokensIter it = tokens.begin(); it != tokens.end(); it++) ham[*it]++; if(recalculate) CalcProbabilities(); }
Master::tSet Master::allStates() { MyDB::Stmt s(mDB); s << "SELECT DISTINCT " << fields.state() << " FROM " << fields.table() << ";"; MyDB::tStrings result(s.queryStrings()); tSet a; for (MyDB::tStrings::const_iterator it(result.begin()), et(result.end()); it != et; ++it) { const Tokens toks(*it); a.insert(toks.begin(), toks.end()); } return a; }
void CommandLineEngine::doMacros(Tokens & tk) { for( Tokens::iterator it = tk.begin(); it != tk.end(); ++it) { String & v = it; if( v[0] == '$' ) { String macro = v.substring(1); UserMacros::iterator it = findMacro(macro); if( it == mUserMacros.end() ) continue; else v = it->value; } } }
bool HttpContentNegociation::Apply(const std::string& accept) { // http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.1 // https://en.wikipedia.org/wiki/Content_negotiation // http://www.newmediacampaigns.com/blog/browser-rest-http-accept-headers Tokens mediaRanges; Toolbox::TokenizeString(mediaRanges, accept, ','); std::auto_ptr<Reference> bestMatch; for (Tokens::const_iterator it = mediaRanges.begin(); it != mediaRanges.end(); ++it) { Tokens parameters; Toolbox::TokenizeString(parameters, *it, ';'); if (parameters.size() > 0) { float quality = GetQuality(parameters); std::string type, subtype; if (SplitPair(type, subtype, parameters[0], '/')) { for (Handlers::const_iterator it2 = handlers_.begin(); it2 != handlers_.end(); ++it2) { if (it2->IsMatch(type, subtype)) { SelectBestMatch(bestMatch, *it2, type, subtype, quality); } } } } } if (bestMatch.get() == NULL) // No match was found { return false; } else { bestMatch->handler_.Call(); return true; } }
void RealmList::UpdateRealm( uint32 ID, const std::string& name, const std::string& address, uint32 port, uint8 icon, RealmFlags realmflags, uint8 timezone, AccountTypes allowedSecurityLevel, float popu, const char* builds) { // Create new if not exist or update existed Realm& realm = m_realms[name]; realm.m_ID = ID; realm.icon = icon; realm.realmflags = realmflags; realm.timezone = timezone; realm.allowedSecurityLevel = allowedSecurityLevel; realm.populationLevel = popu; Tokens tokens = StrSplit(builds, " "); Tokens::iterator iter; for (iter = tokens.begin(); iter != tokens.end(); ++iter) { uint32 build = atol((*iter).c_str()); realm.realmbuilds.insert(build); } uint16 first_build = !realm.realmbuilds.empty() ? *realm.realmbuilds.begin() : 0; realm.realmBuildInfo.build = first_build; realm.realmBuildInfo.major_version = 0; realm.realmBuildInfo.minor_version = 0; realm.realmBuildInfo.bugfix_version = 0; realm.realmBuildInfo.hotfix_version = ' '; if (first_build) if (RealmBuildInfo const* bInfo = FindBuildInfo(first_build)) if (bInfo->build == first_build) realm.realmBuildInfo = *bInfo; // Append port to IP address. std::ostringstream ss; ss << address << ":" << port; realm.address = ss.str(); }
bool DatabaseMysql::Initialize(const char *infoString) { if (!Database::Initialize(infoString)) return false; tranThread = NULL; MYSQL *mysqlInit; mysqlInit = mysql_init(NULL); if (!mysqlInit) { sLog.outError("Could not initialize Mysql connection"); return false; } InitDelayThread(); Tokens tokens = StrSplit(infoString, ";"); Tokens::iterator iter; std::string host, port_or_socket, user, password, database; int port; char const* unix_socket; iter = tokens.begin(); if (iter != tokens.end()) host = *iter++; if (iter != tokens.end()) port_or_socket = *iter++; if (iter != tokens.end()) user = *iter++; if (iter != tokens.end()) password = *iter++; if (iter != tokens.end()) database = *iter++; mysql_options(mysqlInit, MYSQL_SET_CHARSET_NAME, "utf8"); #ifdef WIN32 if (host==".") // named pipe use option (Windows) { unsigned int opt = MYSQL_PROTOCOL_PIPE; mysql_options(mysqlInit, MYSQL_OPT_PROTOCOL, (char const*)&opt); port = 0; unix_socket = 0; } else // generic case { port = atoi(port_or_socket.c_str()); unix_socket = 0; } #else if (host==".") // socket use option (Unix/Linux) { unsigned int opt = MYSQL_PROTOCOL_SOCKET; mysql_options(mysqlInit, MYSQL_OPT_PROTOCOL, (char const*)&opt); host = "localhost"; port = 0; unix_socket = port_or_socket.c_str(); } else // generic case { port = atoi(port_or_socket.c_str()); unix_socket = 0; } #endif mMysql = mysql_real_connect(mysqlInit, host.c_str(), user.c_str(), password.c_str(), database.c_str(), port, unix_socket, 0); if (mMysql) { sLog.outDetail("Connected to MySQL database at %s", host.c_str()); sLog.outString("MySQL client library: %s", mysql_get_client_info()); sLog.outString("MySQL server ver: %s ", mysql_get_server_info( mMysql)); if (!mysql_autocommit(mMysql, 1)) sLog.outDetail("AUTOCOMMIT SUCCESSFULLY SET TO 1"); else sLog.outDetail("AUTOCOMMIT NOT SET TO 1"); // set connection properties to UTF8 to properly handle locales for different // server configs - core sends data in UTF8, so MySQL must expect UTF8 too PExecute("SET NAMES `utf8`"); PExecute("SET CHARACTER SET `utf8`"); #if MYSQL_VERSION_ID >= 50003 my_bool my_true = (my_bool)1; if (mysql_options(mMysql, MYSQL_OPT_RECONNECT, &my_true)) sLog.outDetail("Failed to turn on MYSQL_OPT_RECONNECT."); else sLog.outDetail("Successfully turned on MYSQL_OPT_RECONNECT."); #else #warning "Your mySQL client lib version does not support reconnecting after a timeout.\nIf this causes you any trouble we advice you to upgrade your mySQL client libs to at least mySQL 5.0.13 to resolve this problem." #endif return true; } else { sLog.outError("Could not connect to MySQL database at %s: %s\n", host.c_str(),mysql_error(mysqlInit)); mysql_close(mysqlInit); return false; } }
bool MySQLConnection::Initialize(const char* infoString) { MYSQL* mysqlInit = mysql_init(NULL); if (!mysqlInit) { sLog.outError("Could not initialize Mysql connection"); return false; } Tokens tokens = StrSplit(infoString, ";"); Tokens::iterator iter; std::string host, port_or_socket, user, password, database; int port; char const* unix_socket; iter = tokens.begin(); if (iter != tokens.end()) host = *iter++; if (iter != tokens.end()) port_or_socket = *iter++; if (iter != tokens.end()) user = *iter++; if (iter != tokens.end()) password = *iter++; if (iter != tokens.end()) database = *iter++; mysql_options(mysqlInit, MYSQL_SET_CHARSET_NAME, "utf8"); #ifdef WIN32 if (host == ".") // named pipe use option (Windows) { unsigned int opt = MYSQL_PROTOCOL_PIPE; mysql_options(mysqlInit, MYSQL_OPT_PROTOCOL, (char const*)&opt); port = 0; unix_socket = 0; } else // generic case { port = atoi(port_or_socket.c_str()); unix_socket = 0; } #else if (host == ".") // socket use option (Unix/Linux) { unsigned int opt = MYSQL_PROTOCOL_SOCKET; mysql_options(mysqlInit, MYSQL_OPT_PROTOCOL, (char const*)&opt); host = "localhost"; port = 0; unix_socket = port_or_socket.c_str(); } else // generic case { port = atoi(port_or_socket.c_str()); unix_socket = 0; } #endif mMysql = mysql_real_connect(mysqlInit, host.c_str(), user.c_str(), password.c_str(), database.c_str(), port, unix_socket, 0); if (!mMysql) { sLog.outError("Could not connect to MySQL database at %s: %s\n", host.c_str(), mysql_error(mysqlInit)); mysql_close(mysqlInit); return false; } DETAIL_LOG("Connected to MySQL database %s@%s:%s/%s", user.c_str(), host.c_str(), port_or_socket.c_str(), database.c_str()); sLog.outString("MySQL client library: %s", mysql_get_client_info()); sLog.outString("MySQL server ver: %s ", mysql_get_server_info(mMysql)); /*----------SET AUTOCOMMIT ON---------*/ // It seems mysql 5.0.x have enabled this feature // by default. In crash case you can lose data!!! // So better to turn this off // --- // This is wrong since mangos use transactions, // autocommit is turned of during it. // Setting it to on makes atomic updates work // --- // LEAVE 'AUTOCOMMIT' MODE ALWAYS ENABLED!!! // W/O IT EVEN 'SELECT' QUERIES WOULD REQUIRE TO BE WRAPPED INTO 'START TRANSACTION'<>'COMMIT' CLAUSES!!! if (!mysql_autocommit(mMysql, 1)) DETAIL_LOG("AUTOCOMMIT SUCCESSFULLY SET TO 1"); else DETAIL_LOG("AUTOCOMMIT NOT SET TO 1"); /*-------------------------------------*/ // set connection properties to UTF8 to properly handle locales for different // server configs - core sends data in UTF8, so MySQL must expect UTF8 too Execute("SET NAMES `utf8`"); Execute("SET CHARACTER SET `utf8`"); return true; }
Channel::Channel(const std::string& name, uint32 channel_id, uint32 Team) : m_name(name), m_announce(true), m_moderate(false), m_channelId(channel_id), m_ownerGUID(0), m_password(""), m_flags(0) { m_Team = Team; // set special flags if built-in channel ChatChannelsEntry const* ch = GetChannelEntryFor(channel_id); if(ch) // it's built-in channel { channel_id = ch->ChannelID; // built-in channel m_announce = false; // no join/leave announces m_flags |= CHANNEL_FLAG_GENERAL; // for all built-in channels if(ch->flags & CHANNEL_DBC_FLAG_TRADE) // for trade channel m_flags |= CHANNEL_FLAG_TRADE; if(ch->flags & CHANNEL_DBC_FLAG_CITY_ONLY2) // for city only channels m_flags |= CHANNEL_FLAG_CITY; if(ch->flags & CHANNEL_DBC_FLAG_LFG) // for LFG channel m_flags |= CHANNEL_FLAG_LFG; else // for all other channels m_flags |= CHANNEL_FLAG_NOT_LFG; m_IsSaved = false; } else // it's custom channel { m_flags |= CHANNEL_FLAG_CUSTOM; //load not built in channel if saved QueryResult *result = CharacterDatabase.PQuery("SELECT m_name, m_team, m_announce, m_moderate, m_password, BannedList FROM channels WHERE m_name = '%s' AND m_team = '%u'", name.c_str(), m_Team); if (result)//load { Field *fields = result->Fetch(); const char* db_name = fields[0].GetString(); uint32 db_team = fields[1].GetUInt32(); m_announce = fields[2].GetBool(); m_moderate = fields[3].GetBool(); m_password = fields[4].GetString(); const char* db_BannedList = fields[5].GetString(); m_IsSaved = true; if(db_BannedList) { Tokens tokens = StrSplit(db_BannedList, " "); Tokens::iterator iter; for (iter = tokens.begin();iter != tokens.end(); ++iter) { uint64 banned_guid = atol((*iter).c_str()); if(banned_guid) { sLog.outDebug("Channel(%s) loaded banned guid: %u",name.c_str(), banned_guid); banned.insert(banned_guid); } } } }else{//save std::ostringstream ss; ss << "INSERT INTO channels (m_name,m_team,m_announce,m_moderate,m_password) VALUES ('" << name.c_str() << "','" << m_Team << "','1','0','')"; if(CharacterDatabase.PExecute( ss.str( ).c_str( ) )) { sLog.outDebug("New Channel(%s) saved", name.c_str()); m_IsSaved = true; } } } }
void Editor::autoCalc() { if( !d->autoCalcEnabled ) return; QString str = Evaluator::autoFix( text() ); if( str.isEmpty() ) return; // too short? do not bother... Tokens tokens = Evaluator::scan( str ); if( tokens.count() < 2 ) return; // If we're using set for a function don't try. QRegExp setFn("\\s*set.*\\(.*="); if( str.find(setFn) != -1 ) return; // strip off assignment operator, e.g. "x=1+2" becomes "1+2" only // the reason is that we want only to evaluate (on the fly) the expression, // not to update (put the result in) the variable if( tokens.count() > 2 && tokens[0].isIdentifier() && tokens[1].asOperator() == Token::Equal ) { Tokens::const_iterator it = tokens.begin(); ++it; ++it; // Skip first two tokens. // Reconstruct string to evaluate using the tokens. str = ""; while(it != tokens.end()) { str += (*it).text(); str += ' '; ++it; } } Abakus::number_t result = parseString(str.latin1()); if( Result::lastResult()->type() == Result::Value ) { QString ss = i18n("Result: <b>%2</b>", result.toString()); d->autoCalcLabel->setText( ss ); d->autoCalcLabel->adjustSize(); // reposition nicely QPoint pos = mapToGlobal( QPoint( 0, 0 ) ); pos.setY( pos.y() - d->autoCalcLabel->height() - 1 ); d->autoCalcLabel->move( pos ); d->autoCalcLabel->show(); d->autoCalcLabel->raise(); // do not show it forever QTimer::singleShot( 5000, d->autoCalcLabel, SLOT( hide()) ); } else { // invalid expression d->autoCalcLabel->hide(); } }
bool DatabaseMysql::Initialize(const char *infoString) { if(!Database::Initialize(infoString)) return false; tranThread = NULL; MYSQL *mysqlInit; mysqlInit = mysql_init(NULL); if (!mysqlInit) { sLog.outError( "Could not initialize Mysql connection" ); return false; } InitDelayThread(); Tokens tokens = StrSplit(infoString, ";"); Tokens::iterator iter; std::string host, port_or_socket, user, password, database; int port; char const* unix_socket; iter = tokens.begin(); if(iter != tokens.end()) host = *iter++; if(iter != tokens.end()) port_or_socket = *iter++; if(iter != tokens.end()) user = *iter++; if(iter != tokens.end()) password = *iter++; if(iter != tokens.end()) database = *iter++; mysql_options(mysqlInit,MYSQL_SET_CHARSET_NAME,"utf8"); #ifdef WIN32 if(host==".") // named pipe use option (Windows) { unsigned int opt = MYSQL_PROTOCOL_PIPE; mysql_options(mysqlInit,MYSQL_OPT_PROTOCOL,(char const*)&opt); port = 0; unix_socket = 0; } else // generic case { port = atoi(port_or_socket.c_str()); unix_socket = 0; } #else if(host==".") // socket use option (Unix/Linux) { unsigned int opt = MYSQL_PROTOCOL_SOCKET; mysql_options(mysqlInit,MYSQL_OPT_PROTOCOL,(char const*)&opt); host = "localhost"; port = 0; unix_socket = port_or_socket.c_str(); } else // generic case { port = atoi(port_or_socket.c_str()); unix_socket = 0; } #endif mMysql = mysql_real_connect(mysqlInit, host.c_str(), user.c_str(), password.c_str(), database.c_str(), port, unix_socket, 0); if (mMysql) { sLog.outDetail( "Connected to MySQL database at %s\r\n", host.c_str()); sLog.outString( "MySQL client library: %s", mysql_get_client_info()); sLog.outString( "MySQL server ver: %s ", mysql_get_server_info( mMysql)); /*----------SET AUTOCOMMIT ON---------*/ // It seems mysql 5.0.x have enabled this feature // by default. In crash case you can lose data!!! // So better to turn this off // --- // This is wrong since mangos use transactions, // autocommit is turned of during it. // Setting it to on makes atomic updates work if (!mysql_autocommit(mMysql, 1)) sLog.outDetail("AUTOCOMMIT SUCCESSFULLY SET TO 1"); else sLog.outDetail("AUTOCOMMIT NOT SET TO 1"); /*-------------------------------------*/ return true; } else { sLog.outError( "Could not connect to MySQL database at %s: %s\n", host.c_str(),mysql_error(mysqlInit)); mysql_close(mysqlInit); return false; } }
bool MySQLConnection::Initialize(const char *infoString) { MYSQL * mysqlInit = mysql_init(NULL); if (!mysqlInit) { sLog.outLog(LOG_DEFAULT, "ERROR: Could not initialize Mysql connection"); return false; } Tokens tokens = StrSplit(infoString, ";"); Tokens::iterator iter; std::string host, port_or_socket, user, password, database; int port; char const* unix_socket; iter = tokens.begin(); if(iter != tokens.end()) host = *iter++; if(iter != tokens.end()) port_or_socket = *iter++; if(iter != tokens.end()) user = *iter++; if(iter != tokens.end()) password = *iter++; if(iter != tokens.end()) database = *iter++; mysql_options(mysqlInit,MYSQL_SET_CHARSET_NAME,"utf8"); #ifdef WIN32 if(host==".") // named pipe use option (Windows) { unsigned int opt = MYSQL_PROTOCOL_PIPE; mysql_options(mysqlInit,MYSQL_OPT_PROTOCOL,(char const*)&opt); port = 0; unix_socket = 0; } else // generic case { port = atoi(port_or_socket.c_str()); unix_socket = 0; } #else if(host==".") // socket use option (Unix/Linux) { unsigned int opt = MYSQL_PROTOCOL_SOCKET; mysql_options(mysqlInit,MYSQL_OPT_PROTOCOL,(char const*)&opt); host = "localhost"; port = 0; unix_socket = port_or_socket.c_str(); } else // generic case { port = atoi(port_or_socket.c_str()); unix_socket = 0; } #endif mMysql = mysql_real_connect(mysqlInit, host.c_str(), user.c_str(), password.c_str(), database.c_str(), port, unix_socket, 0); if (mMysql) { //sLog.outString( "Connected to MySQL database at %s", // host.c_str()); //sLog.outString( "MySQL client library: %s", mysql_get_client_info()); //sLog.outString( "MySQL server ver: %s ", mysql_get_server_info( mMysql)); /*----------SET AUTOCOMMIT ON---------*/ // It seems mysql 5.0.x have enabled this feature // by default. In crash case you can lose data!!! // So better to turn this off // --- // This is wrong since mangos use transactions, // autocommit is turned of during it. // Setting it to on makes atomic updates work // --- // LEAVE 'AUTOCOMMIT' MODE ALWAYS ENABLED!!! // W/O IT EVEN 'SELECT' QUERIES WOULD REQUIRE TO BE WRAPPED INTO 'START TRANSACTION'<>'COMMIT' CLAUSES!!! if (!mysql_autocommit(mMysql, 1)) sLog.outDetail("AUTOCOMMIT SUCCESSFULLY SET TO 1"); else sLog.outDetail("AUTOCOMMIT NOT SET TO 1"); /*-------------------------------------*/ // set connection properties to UTF8 to properly handle locales for different // server configs - core sends data in UTF8, so MySQL must expect UTF8 too Execute("SET NAMES `utf8`"); Execute("SET CHARACTER SET `utf8`"); #if MYSQL_VERSION_ID >= 50003 my_bool my_true = (my_bool)1; if (mysql_options(mMysql, MYSQL_OPT_RECONNECT, &my_true)) sLog.outDetail("Failed to turn on MYSQL_OPT_RECONNECT."); else sLog.outDetail("Successfully turned on MYSQL_OPT_RECONNECT."); #else #warning "Your mySQL client lib version does not support reconnecting after a timeout.\nIf this causes you any trouble we advice you to upgrade your mySQL client libs to at least mySQL 5.0.13 to resolve this problem." #endif return true; } else { sLog.outLog(LOG_DEFAULT, "Could not connect to MySQL database at %s\n", host.c_str()); mysql_close(mysqlInit); return false; } }