Example #1
0
void gui_screen_t::backspace() {
	output = output.substr(0, output.length() - 1);
	paint_uptodate = false;
}
Example #2
0
std::string stripExtension(std::string const& path)
{
    return path.substr(0, path.rfind('.'));
}
Example #3
0
void CppCheck::checkFile(const std::string &code, const char FileName[])
{
    if (_settings.terminated() || _settings.checkConfiguration)
        return;

    Tokenizer _tokenizer(&_settings, this);
    bool result;

    // Tokenize the file
    std::istringstream istr(code);

    Timer timer("Tokenizer::tokenize", _settings._showtime, &S_timerResults);
    result = _tokenizer.tokenize(istr, FileName, cfg);
    timer.Stop();
    if (!result)
    {
        // File had syntax errors, abort
        return;
    }

    Timer timer2("Tokenizer::fillFunctionList", _settings._showtime, &S_timerResults);
    _tokenizer.fillFunctionList();
    timer2.Stop();

    // call all "runChecks" in all registered Check classes
    for (std::list<Check *>::iterator it = Check::instances().begin(); it != Check::instances().end(); ++it)
    {
        if (_settings.terminated())
            return;

        Timer timerRunChecks((*it)->name() + "::runChecks", _settings._showtime, &S_timerResults);
        (*it)->runChecks(&_tokenizer, &_settings, this);
    }

    Timer timer3("Tokenizer::simplifyTokenList", _settings._showtime, &S_timerResults);
    result = _tokenizer.simplifyTokenList();
    timer3.Stop();
    if (!result)
        return;

    Timer timer4("Tokenizer::fillFunctionList", _settings._showtime, &S_timerResults);
    _tokenizer.fillFunctionList();
    timer4.Stop();

    if (_settings.isEnabled("unusedFunctions") && _settings._jobs == 1)
        _checkUnusedFunctions.parseTokens(_tokenizer);

    // call all "runSimplifiedChecks" in all registered Check classes
    for (std::list<Check *>::iterator it = Check::instances().begin(); it != Check::instances().end(); ++it)
    {
        if (_settings.terminated())
            return;

        Timer timerSimpleChecks((*it)->name() + "::runSimplifiedChecks", _settings._showtime, &S_timerResults);
        (*it)->runSimplifiedChecks(&_tokenizer, &_settings, this);
    }

#ifdef HAVE_RULES
    // Are there extra rules?
    if (!_settings.rules.empty())
    {
        std::ostringstream ostr;
        for (const Token *tok = _tokenizer.tokens(); tok; tok = tok->next())
            ostr << " " << tok->str();
        const std::string str(ostr.str());
        for (std::list<Settings::Rule>::const_iterator it = _settings.rules.begin(); it != _settings.rules.end(); ++it)
        {
            const Settings::Rule &rule = *it;
            if (rule.pattern.empty() || rule.id.empty() || rule.severity.empty())
                continue;

            const char *error = 0;
            int erroffset = 0;
            pcre *re = pcre_compile(rule.pattern.c_str(),0,&error,&erroffset,NULL);
            if (!re && error)
            {
                ErrorLogger::ErrorMessage errmsg(std::list<ErrorLogger::ErrorMessage::FileLocation>(),
                                                 Severity::error,
                                                 error,
                                                 "pcre_compile",
                                                 false);

                reportErr(errmsg);
            }
            if (!re)
                continue;

            int pos = 0;
            int ovector[30];
            while (0 <= pcre_exec(re, NULL, str.c_str(), (int)str.size(), pos, 0, ovector, 30))
            {
                unsigned int pos1 = (unsigned int)ovector[0];
                unsigned int pos2 = (unsigned int)ovector[1];

                // jump to the end of the match for the next pcre_exec
                pos = (int)pos2;

                // determine location..
                ErrorLogger::ErrorMessage::FileLocation loc;
                loc.setfile(_tokenizer.getFiles()->front());
                loc.line = 0;

                unsigned int len = 0;
                for (const Token *tok = _tokenizer.tokens(); tok; tok = tok->next())
                {
                    len = len + 1 + tok->str().size();
                    if (len > pos1)
                    {
                        loc.setfile(_tokenizer.getFiles()->at(tok->fileIndex()));
                        loc.line = tok->linenr();
                        break;
                    }
                }

                const std::list<ErrorLogger::ErrorMessage::FileLocation> callStack(1, loc);

                // Create error message
                std::string summary;
                if (rule.summary.empty())
                    summary = "found '" + str.substr(pos1, pos2 - pos1) + "'";
                else
                    summary = rule.summary;
                const ErrorLogger::ErrorMessage errmsg(callStack, Severity::fromString(rule.severity), summary, rule.id, false);

                // Report error
                reportErr(errmsg);
            }

            pcre_free(re);
        }
    }
#endif
}
Example #4
0
void CodeBlocksProvider::createProjectFile(const std::string &name, const std::string &, const BuildSetup &setup, const std::string &moduleDir,
                                           const StringList &includeList, const StringList &excludeList) {

	const std::string projectFile = setup.outputDir + '/' + name + getProjectExtension();
	std::ofstream project(projectFile.c_str());
	if (!project)
		error("Could not open \"" + projectFile + "\" for writing");

	project << "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\" ?>\n"
	           "<CodeBlocks_project_file>\n"
	           "\t<FileVersion major=\"1\" minor=\"6\" />\n"
	           "\t<Project>\n"
	           "\t\t<Option title=\"" << name << "\" />\n"
	           "\t\t<Option pch_mode=\"2\" />\n"
	           "\t\t<Option compiler=\"gcc\" />\n"
	           "\t\t<Build>\n";

	if (name == setup.projectName) {
		std::string libraries;

		for (StringList::const_iterator i = setup.libraries.begin(); i != setup.libraries.end(); ++i)
			libraries += processLibraryName(*i) + ".a;";

		project << "\t\t\t<Target title=\"default\">\n"
		           "\t\t\t\t<Option output=\"" << setup.projectName << "\\" << setup.projectName << "\" prefix_auto=\"1\" extension_auto=\"1\" />\n"
		           "\t\t\t\t<Option object_output=\"" << setup.projectName << "\" />\n"
		           "\t\t\t\t<Option external_deps=\"" << libraries /* + list of engines engines\name\name.a */ << "\" />\n"
		           "\t\t\t\t<Option type=\"1\" />\n"
		           "\t\t\t\t<Option compiler=\"gcc\" />\n"
		           "\t\t\t\t<Option parameters=\"-d 8 --debugflags=parser\" />\n"
		           "\t\t\t\t<Option projectIncludeDirsRelation=\"2\" />\n";

		//////////////////////////////////////////////////////////////////////////
		// Compiler
		project << "\t\t\t\t<Compiler>\n";

		writeWarnings(name, project);
		writeDefines(setup.defines, project);

		project << "\t\t\t\t\t<Add directory=\"$(" << LIBS_DEFINE << ")include\" />\n"
		           "\t\t\t\t\t<Add directory=\"$(" << LIBS_DEFINE << ")include\\SDL\" />\n"
		           "\t\t\t\t\t<Add directory=\"..\\..\\engines\" />\n"
		           "\t\t\t\t\t<Add directory=\"..\\..\\common\" />\n"
		           "\t\t\t\t\t<Add directory=\"..\\..\" />\n"
		           "\t\t\t\t</Compiler>\n";

		//////////////////////////////////////////////////////////////////////////
		// Linker
		project << "\t\t\t\t<Linker>\n";

		for (StringList::const_iterator i = setup.libraries.begin(); i != setup.libraries.end(); ++i)
			project << "\t\t\t\t\t<Add library=\"" << processLibraryName(*i) << "\" />\n";

		for (UUIDMap::const_iterator i = _uuidMap.begin(); i != _uuidMap.end(); ++i) {
			if (i->first == setup.projectName)
				continue;

			project << "\t\t\t\t\t<Add library=\"" << setup.projectName << "\\engines\\" << i->first << "\\lib" << i->first << ".a\" />\n";
		}

		project << "\t\t\t\t\t<Add directory=\"$(" << LIBS_DEFINE << ")lib\\mingw\" />\n"
		           "\t\t\t\t\t<Add directory=\"$(" << LIBS_DEFINE << ")lib\" />\n"
		           "\t\t\t\t</Linker>\n";

		//////////////////////////////////////////////////////////////////////////
		// Resource compiler
		project << "\t\t\t\t<ResourceCompiler>\n"
		           "\t\t\t\t\t<Add directory=\"..\\..\\dists\" />\n"
		           "\t\t\t\t\t<Add directory=\"..\\..\\..\\" << setup.projectName << "\" />\n"
		           "\t\t\t\t</ResourceCompiler>\n"
		           "\t\t\t</Target>\n"
		           "\t\t</Build>\n";



	} else {
		project << "\t\t\t<Target title=\"default\">\n"
		           "\t\t\t\t<Option output=\"" << setup.projectName << "\\engines\\" << name << "\\lib" << name << "\" prefix_auto=\"1\" extension_auto=\"1\" />\n"
		           "\t\t\t\t<Option working_dir=\"\" />\n"
		           "\t\t\t\t<Option object_output=\"" << setup.projectName << "\" />\n"
		           "\t\t\t\t<Option type=\"2\" />\n"
		           "\t\t\t\t<Option compiler=\"gcc\" />\n"
		           "\t\t\t\t<Option createDefFile=\"1\" />\n"
		           "\t\t\t\t<Compiler>\n";

		writeWarnings(name, project);
		writeDefines(setup.defines, project);

		project << "\t\t\t\t\t<Add option=\"-g\" />\n"
		           "\t\t\t\t\t<Add directory=\"..\\..\\engines\" />\n"
		           "\t\t\t\t\t<Add directory=\"..\\..\\..\\" << setup.projectName << "\" />\n";

		// Sword2.5 engine needs theora and vorbis includes
		if (name == "sword25")
			project << "\t\t\t\t\t<Add directory=\"$(" << LIBS_DEFINE << ")include\" />\n";

		project << "\t\t\t\t</Compiler>\n"
		           "\t\t\t</Target>\n"
		           "\t\t</Build>\n";
	}

	std::string modulePath;
	if (!moduleDir.compare(0, setup.srcDir.size(), setup.srcDir)) {
		modulePath = moduleDir.substr(setup.srcDir.size());
		if (!modulePath.empty() && modulePath.at(0) == '/')
			modulePath.erase(0, 1);
	}

	if (modulePath.size())
		addFilesToProject(moduleDir, project, includeList, excludeList, setup.filePrefix + '/' + modulePath);
	else
		addFilesToProject(moduleDir, project, includeList, excludeList, setup.filePrefix);


	project << "\t\t<Extensions>\n"
	           "\t\t\t<code_completion />\n"
	           "\t\t\t<debugger />\n"
	           "\t\t</Extensions>\n"
	           "\t</Project>\n"
	           "</CodeBlocks_project_file>";

}
bool LLTextureCacheLocalFileWorker::doRead()
{
	S32 local_size = LLAPRFile::size(mFileName);

	if (local_size > 0 && mFileName.size() > 4)
	{
		mDataSize = local_size; // Only a complete file is valid

		std::string extension = mFileName.substr(mFileName.size() - 3, 3);

		mImageFormat = LLImageBase::getCodecFromExtension(extension);

		if (mImageFormat == IMG_CODEC_INVALID)
		{
// 			llwarns << "Unrecognized file extension " << extension << " for local texture " << mFileName << llendl;
			mDataSize = 0; // no data
			return true;
		}
	}
	else
	{
		// file doesn't exist
		mDataSize = 0; // no data
		return true;
	}

#if USE_LFS_READ
	if (mFileHandle == LLLFSThread::nullHandle())
	{
		mImageLocal = TRUE;
		mImageSize = local_size;
		if (!mDataSize || mDataSize + mOffset > local_size)
		{
			mDataSize = local_size - mOffset;
		}
		if (mDataSize <= 0)
		{
			// no more data to read
			mDataSize = 0;
			return true;
		}
		mReadData = new U8[mDataSize];
		mBytesRead = -1;
		mBytesToRead = mDataSize;
		setPriority(LLWorkerThread::PRIORITY_LOW | mPriority);
		mFileHandle = LLLFSThread::sLocal->read(local_filename, mReadData, mOffset, mDataSize,
												new ReadResponder(mCache, mRequestHandle));
		return false;
	}
	else
	{
		if (mBytesRead >= 0)
		{
			if (mBytesRead != mBytesToRead)
			{
// 				llwarns << "Error reading file from local cache: " << local_filename
// 						<< " Bytes: " << mDataSize << " Offset: " << mOffset
// 						<< " / " << mDataSize << llendl;
				mDataSize = 0; // failed
				delete[] mReadData;
				mReadData = NULL;
			}
			return true;
		}
		else
		{
			return false;
		}
	}
#else
	if (!mDataSize || mDataSize > local_size)
	{
		mDataSize = local_size;
	}
	mReadData = new U8[mDataSize];
	
	S32 bytes_read = LLAPRFile::readEx(mFileName, mReadData, mOffset, mDataSize);

	if (bytes_read != mDataSize)
	{
// 		llwarns << "Error reading file from local cache: " << mFileName
// 				<< " Bytes: " << mDataSize << " Offset: " << mOffset
// 				<< " / " << mDataSize << llendl;
		mDataSize = 0;
		delete[] mReadData;
		mReadData = NULL;
	}
	else
	{
		mImageSize = local_size;
		mImageLocal = TRUE;
	}
	return true;
#endif
}
Example #6
0
std::string FileUtils::fullPathFromRelativeFile(const std::string &filename, const std::string &relativeFile)
{
    return relativeFile.substr(0, relativeFile.rfind('/')+1) + getNewFilename(filename);
}
Example #7
0
bool ConfigManager::loadFile(const std::string& _filename)
{
	if(L)
		lua_close(L);

	L = lua_open();

	if(!L) return false;

	if(luaL_dofile(L, _filename.c_str()))
	{
		lua_close(L);
		L = NULL;
		return false;
	}

	// parse config
	if(!m_isLoaded) // info that must be loaded one time (unless we reset the modules involved)
	{
		m_confString[CONFIG_FILE] = _filename;

		// These settings might have been set from command line
		if(m_confString[IP] == "")
			m_confString[IP] = getGlobalString(L, "ip", "127.0.0.1");
		if(m_confInteger[GAME_PORT] == 0)
			m_confInteger[GAME_PORT] = getGlobalNumber(L, "game_port");
		if(m_confInteger[ADMIN_PORT] == 0)
			m_confInteger[ADMIN_PORT] = getGlobalNumber(L, "admin_port");
		if(m_confInteger[LOGIN_PORT] == 0)
			m_confInteger[LOGIN_PORT] = getGlobalNumber(L, "login_port");
		if(m_confInteger[STATUS_PORT] == 0)
			m_confInteger[STATUS_PORT] = getGlobalNumber(L, "status_port");

#if defined __CONFIG_V2__
		unsigned int pos = _filename.rfind("/");
		std::string configPath = "";
		if(pos != std::string::npos)
			configPath = _filename.substr(0, pos+1);

		m_confString[DATA_DIRECTORY] = configPath + getGlobalString(L, "datadir", "data/");
		m_confString[MAP_FILE] = m_confString[DATA_DIRECTORY] + getGlobalString(L, "map");
		m_confString[MAP_STORE_FILE] = m_confString[DATA_DIRECTORY] + getGlobalString(L, "mapstore");
		m_confString[HOUSE_STORE_FILE] = m_confString[DATA_DIRECTORY] + getGlobalString(L, "housestore");
#else
		m_confString[DATA_DIRECTORY] = getGlobalString(L, "datadir");
		m_confString[MAP_FILE] = getGlobalString(L, "map");
		m_confString[MAP_STORE_FILE] = getGlobalString(L, "mapstore");
		m_confString[HOUSE_STORE_FILE] = getGlobalString(L, "housestore");
#endif
		m_confString[HOUSE_RENT_PERIOD] = getGlobalString(L, "houserentperiod", "monthly");
		m_confString[MAP_KIND] = getGlobalString(L, "mapkind");
		if(getGlobalString(L, "md5passwords") != ""){
			std::cout << "Warning: [ConfigManager] md5passwords is deprecated. Use passwordtype instead." << std::endl;
		}
		m_confString[PASSWORD_TYPE_STR] = getGlobalString(L, "passwordtype");
		m_confString[PASSWORD_SALT] = getGlobalString(L, "passwordsalt", "");
		m_confString[WORLD_TYPE] = getGlobalString(L, "worldtype");
		m_confString[SQL_HOST] = getGlobalString(L, "sql_host");
		m_confString[SQL_USER] = getGlobalString(L, "sql_user");
		m_confString[SQL_PASS] = getGlobalString(L, "sql_pass");
		m_confString[SQL_DB] = getGlobalString(L, "sql_db");
		m_confString[SQL_TYPE] = getGlobalString(L, "sql_type");
		m_confInteger[SQL_PORT] = getGlobalNumber(L, "sql_port");
		m_confInteger[PASSWORD_TYPE] = PASSWORD_TYPE_PLAIN;
	}

	m_confString[LOGIN_MSG] = getGlobalString(L, "loginmsg", "Welcome.");
	m_confString[SERVER_NAME] = getGlobalString(L, "servername");
	m_confString[WORLD_NAME] = getGlobalString(L, "worldname", "Gameworld");
	m_confString[OWNER_NAME] = getGlobalString(L, "ownername");
	m_confString[OWNER_EMAIL] = getGlobalString(L, "owneremail");
	m_confString[URL] = getGlobalString(L, "url");
	m_confString[LOCATION] = getGlobalString(L, "location");
	m_confString[MAP_STORAGE_TYPE] = getGlobalString(L, "map_store_type", "relational");
	m_confInteger[LOGIN_TRIES] = getGlobalNumber(L, "logintries", 5);
	m_confInteger[RETRY_TIMEOUT] = getGlobalNumber(L, "retrytimeout", 30 * 1000);
	m_confInteger[LOGIN_TIMEOUT] = getGlobalNumber(L, "logintimeout", 5 * 1000);
	m_confString[MOTD] = getGlobalString(L, "motd");
	m_confInteger[MOTD_NUM] = getGlobalNumber(L, "motdnum");
	m_confInteger[MAX_PLAYERS] = getGlobalNumber(L, "maxplayers");
	m_confInteger[EXHAUSTED] = getGlobalNumber(L, "exhausted", 30000);
	m_confInteger[EXHAUSTED_ADD] = getGlobalNumber(L, "exhaustedadd", 5000);
	m_confInteger[COMBAT_EXHAUSTED] = getGlobalNumber(L, "fightexhausted", 2000);
	m_confInteger[HEAL_EXHAUSTED] = getGlobalNumber(L, "healexhausted", 1000);
	m_confInteger[STAIRHOP_EXHAUSTED] = getGlobalNumber(L, "stairhop_exhausted", 2*1000);
	m_confInteger[IN_FIGHT_DURATION] = getGlobalNumber(L, "in_fight_duration", 60 * 1000);
	m_confInteger[HUNTING_KILL_DURATION] = getGlobalNumber(L, "hunting_kill_duration", 60 * 1000);
	m_confInteger[FIELD_OWNERSHIP_DURATION] = getGlobalNumber(L, "field_ownership_duration", 5 * 1000);
	m_confInteger[MIN_ACTIONTIME] = getGlobalNumber(L, "minactioninterval", 200);
	m_confInteger[MIN_ACTIONEXTIME] = getGlobalNumber(L, "minactionexinterval", 1000);
	m_confInteger[DEFAULT_DESPAWNRANGE] = getGlobalNumber(L, "despawnrange", 2);
	m_confInteger[DEFAULT_DESPAWNRADIUS] = getGlobalNumber(L, "despawnradius", 50);
	m_confInteger[ALLOW_CLONES] = getGlobalBoolean(L, "allowclones", false);
	m_confInteger[PARTY_MEMBER_EXP_BONUS] = getGlobalNumber(L, "party_exp_mul", 5);
	m_confInteger[RATE_EXPERIENCE] = getGlobalNumber(L, "rate_exp", 1);
	m_confInteger[RATE_SKILL] = getGlobalNumber(L, "rate_skill", 1);
	m_confInteger[RATE_LOOT] = getGlobalNumber(L, "rate_loot", 1);
	m_confInteger[RATE_MAGIC] = getGlobalNumber(L, "rate_mag", 1);
	m_confInteger[RATE_SPAWN] = getGlobalNumber(L, "rate_spawn", 1);
	m_confInteger[MAX_MESSAGEBUFFER] = getGlobalNumber(L, "maxmessagebuffer", 4);
	m_confInteger[SAVE_CLIENT_DEBUG_ASSERTIONS] = getGlobalBoolean(L, "saveclientdebug", true);
	m_confInteger[CHECK_ACCOUNTS] = getGlobalBoolean(L, "checkaccounts", true);
	m_confInteger[USE_BALANCE_HOUSE_PAYING] = getGlobalBoolean(L, "use_balance_house_paying", true);
	m_confInteger[PREMIUM_ONLY_BEDS] = getGlobalBoolean(L, "premonlybeds", true);
	m_confInteger[UNJUST_SKULL_DURATION] = getGlobalNumber(L, "unjust_skull_duration", 15*60*1000);
	m_confInteger[KILLS_PER_DAY_RED_SKULL] = getGlobalNumber(L, "kills_per_day_red_skull", 3);
	m_confInteger[KILLS_PER_WEEK_RED_SKULL] = getGlobalNumber(L, "kills_per_week_red_skull", 5);
	m_confInteger[KILLS_PER_MONTH_RED_SKULL] = getGlobalNumber(L, "kills_per_month_red_skull", 10);
	m_confInteger[RED_SKULL_DURATION] = getGlobalNumber(L, "red_skull_duration", 30*24*60*60);
	m_confInteger[REMOVE_AMMUNITION] = getGlobalBoolean(L, "remove_ammunition", true);
	m_confInteger[REMOVE_RUNE_CHARGES] = getGlobalBoolean(L, "remove_rune_charges", true);
	m_confInteger[REMOVE_WEAPON_CHARGES] = getGlobalBoolean(L, "remove_weapon_charges", true);
	m_confInteger[LOGIN_ATTACK_DELAY] = getGlobalNumber(L, "login_attack_delay", 10*1000);
	m_confInteger[IDLE_TIME] = getGlobalNumber(L, "max_idle_time", 16*60*1000);
	m_confInteger[IDLE_TIME_WARNING] = getGlobalNumber(L, "max_idle_time_warning", 15*60*1000);
	m_confInteger[HOUSE_ONLY_PREMIUM] = getGlobalBoolean(L, "house_only_premium", true);
	m_confInteger[HOUSE_LEVEL] = getGlobalNumber(L, "house_level", 1);
	m_confInteger[HOUSE_TILE_PRICE] = getGlobalNumber(L, "house_tile_price", 100);
	m_confInteger[SHOW_HOUSE_PRICES] = getGlobalBoolean(L, "show_house_prices", false);
	m_confInteger[BROADCAST_BANISHMENTS] = getGlobalBoolean(L, "broadcast_banishments", false);
	m_confInteger[NOTATIONS_TO_BAN] = getGlobalNumber(L, "notations_to_banishment", 3);
	m_confInteger[WARNINGS_TO_FINALBAN] = getGlobalNumber(L, "warnings_to_final_banishment", 4);
	m_confInteger[WARNINGS_TO_DELETION] = getGlobalNumber(L, "warnings_to_deletion", 5);
	m_confInteger[BAN_LENGTH] = getGlobalNumber(L, "banishment_length", 7 * 86400);
	m_confInteger[FINALBAN_LENGTH] = getGlobalNumber(L, "final_banishment_length", 30 * 86400);
	m_confInteger[IPBANISHMENT_LENGTH] = getGlobalNumber(L, "ip_banishment_length", 86400);
	m_confInteger[ALLOW_GAMEMASTER_MULTICLIENT] = getGlobalBoolean(L, "allow_gamemaster_multiclient", false);
	m_confInteger[DEATH_ASSIST_COUNT] = getGlobalNumber(L, "death_assist_count", 1);
	m_confInteger[LAST_HIT_PZBLOCK_ONLY] = getGlobalBoolean(L, "last_hit_pzblock_only", true);
	m_confInteger[DEFENSIVE_PZ_LOCK] = getGlobalBoolean(L, "defensive_pz_lock", false);
	m_confInteger[DISTANCE_WEAPON_INTERRUPT_SWING] = getGlobalBoolean(L, "distance_weapon_interrupt_swing", true);
	m_confInteger[RATES_FOR_PLAYER_KILLING] = getGlobalBoolean(L, "rates_for_player_killing", false);
	m_confInteger[RATE_EXPERIENCE_PVP] = getGlobalNumber(L, "rate_exp_pvp", 0);
	m_confInteger[FIST_STRENGTH] = getGlobalNumber(L, "fist_strength", 7);
	m_confInteger[STATUSQUERY_TIMEOUT] = getGlobalNumber(L, "statustimeout", 30 * 1000);
	m_confInteger[CAN_ROPE_CREATURES] = getGlobalBoolean(L, "can_rope_creatures", true);
	m_confString[DEATH_MSG] = getGlobalString(L, "death_msg", "You are dead.");
	m_confInteger[CAN_ATTACK_INVISIBLE] = getGlobalBoolean(L, "can_attack_invisible", false);
	m_confInteger[MIN_PVP_LEVEL] = getGlobalNumber(L, "min_pvp_level", 0);
	#ifdef __MIN_PVP_LEVEL_APPLIES_TO_SUMMONS__
	m_confInteger[MIN_PVP_LEVEL_APPLIES_TO_SUMMONS] = getGlobalBoolean(L, "min_pvp_level_applies_to_summons", true);
	#endif
	m_confInteger[HEIGHT_MINIMUM_FOR_IDLE] = getGlobalNumber(L, "height_minimum_for_idle", 3);
	m_confInteger[EXPERIENCE_STAGES] = getGlobalBoolean(L, "experience_stages", false);
	m_confInteger[PUSH_INTERVAL] = getGlobalNumber(L, "push_interval", 2000);
	m_confInteger[MOVEITEM_TIME] = getGlobalNumber(L, "move_item_interval", 500);
	m_confInteger[MAX_STACK_SIZE] = getGlobalNumber(L, "max_stack_size", 1000);
	m_confInteger[PVP_DAMAGE] = getGlobalNumber(L, "pvp_damage", 50);
	m_confInteger[WANDS_INTERRUPT_SWING] = getGlobalBoolean(L, "wands_interrupt_swing", true);
	m_confInteger[PLAYER_QUERYDESTINATION_DEEPNESS] = getGlobalNumber(L, "player_querydestination_deepness", -1);
	m_confInteger[TILE_LIMIT] = getGlobalNumber(L, "tile_limit", 0);
	m_confInteger[PROTECTION_TILE_LIMIT] = getGlobalNumber(L, "protection_tile_limit", 0);
	m_confInteger[HOUSE_TILE_LIMIT]	= getGlobalNumber(L, "house_tile_limit", 0);
	m_confInteger[LUA_EXCEPTED_TYPE_ERRORS_ENABLED]	= getGlobalBoolean(L, "lua_excepted_type_errors_enabled", false);
	m_confInteger[MAX_AMOUNT_ITEMS_INSIDE_CONTAINERS] = getGlobalNumber(L, "max_amount_items_inside_containers", 2000);
	m_confInteger[MAX_DEEPNESS_OF_CHAIN_OF_CONTAINERS] = getGlobalNumber(L, "max_deepness_of_chain_of_containers", 500);
	m_confInteger[BIND_ONLY_GLOBAL_ADDRESS]	= getGlobalBoolean(L, "bind_only_global_address", false);
	m_confInteger[MAX_CONTAINERS_INSIDE_PLAYER_INVENTORY] = getGlobalNumber(L, "max_containers_inside_player_inventory", 100);
	m_confInteger[USE_RUNE_LEVEL_REQUIREMENTS] = getGlobalBoolean(L, "use_rune_level_requirements", true);
	m_confInteger[CONTAINER_ITEMS_AUTO_STACK] = getGlobalBoolean(L, "container_items_auto_stack", false);
	m_confString[SERVER_PRIORITY] = getGlobalString(L, "serverPriority", "aboveNormal");
	m_confInteger[KILLS_TO_BAN] = getGlobalNumber(L, "kills_to_ban", 20);
	
	// 7.81
	m_confInteger[HOTKEYS] = getGlobalBoolean(L, "enablehotkeys", false);
	
	//Stamina
	m_confInteger[RATE_STAMINA_LOSS] = getGlobalNumber(L, "rate_stamina_loss", 1);
	m_confInteger[RATE_STAMINA_GAIN] = getGlobalNumber(L, "rate_stamina_gain", 334);
	m_confInteger[SLOW_RATE_STAMINA_GAIN] = getGlobalNumber(L, "slow_rate_stamina_gain", 84);
	m_confInteger[STAMINA_EXTRA_EXPERIENCE_DURATION] = getGlobalNumber(L, "stamina_extra_experience_duration", 60 * 60 * 1000);
	m_confInteger[STAMINA_EXTRA_EXPERIENCE_ONLYPREM] = getGlobalBoolean(L, "stamina_extra_experience_onlyprem", true);
	m_confFloat[STAMINA_EXTRA_EXPERIENCE_RATE] = getGlobalFloat(L, "stamina_extra_experience_rate", 0.5);
	m_confInteger[HUNTING_KILL_DURATION] = getGlobalNumber(L, "hunting_kill_duration", 60 * 1000);	
	
	m_isLoaded = true;
	return true;
}
Example #8
0
  void SOCKS5BytestreamServer::handleReceivedData( const ConnectionBase* connection,
                                                   const std::string& data )
  {
    m_mutex.lock();
    ConnectionMap::iterator it = m_connections.find( const_cast<ConnectionBase*>( connection ) );
    if( it == m_connections.end() )
    {
      m_mutex.unlock();
      return;
    }
    m_mutex.unlock();

    switch( (*it).second.state )
    {
      case StateDisconnected:
        (*it).first->disconnect();
        break;
      case StateUnnegotiated:
      {
        char c[2];
        c[0] = 0x05;
        c[1] = (char)(unsigned char)0xFF;
        (*it).second.state = StateDisconnected;

        if( data.length() >= 3 && data[0] == 0x05 )
        {
          unsigned int sz = ( data.length() - 2 < static_cast<unsigned int>( data[1] ) )
                              ? static_cast<unsigned int>( data.length() - 2 )
                              : static_cast<unsigned int>( data[1] );
          for( unsigned int i = 2; i < sz + 2; ++i )
          {
            if( data[i] == 0x00 )
            {
              c[1] = 0x00;
              (*it).second.state = StateAuthAccepted;
              break;
            }
          }
        }
        (*it).first->send( std::string( c, 2 ) );
        break;
      }
      case StateAuthmethodAccepted:
        // place to implement any future auth support
        break;
      case StateAuthAccepted:
      {
        std::string reply = data;
        if( reply.length() < 2 )
          reply.resize( 2 );

        reply[0] = 0x05;
        reply[1] = 0x01; // general SOCKS server failure
        (*it).second.state = StateDisconnected;

        if( data.length() == 47 && data[0] == 0x05 && data[1] == 0x01 && data[2] == 0x00
            && data[3] == 0x03 && data[4] == 0x28 && data[45] == 0x00 && data[46] == 0x00 )
        {
          const std::string hash = data.substr( 5, 40 );

          m_mutex.lock();
          HashMap::const_iterator ith = m_hashes.begin();
          for( ; ith != m_hashes.end() && (*ith) != hash; ++ith )
            ;

          if( ith != m_hashes.end() )
          {
            reply[1] = 0x00;
            (*it).second.hash = hash;
            (*it).second.state = StateDestinationAccepted;
          }
          m_mutex.unlock();
        }
        (*it).first->send( reply );
        break;
      }
      case StateDestinationAccepted:
      case StateActive:
        // should not happen
        break;
    }
  }
Example #9
0
void Compositor::content_request(std::string request) {
	std::string::size_type extPos;
	std::string ext;
	std::string baseFile;
	uint extGroup = 0;
	
	// setup our extention mapping
	const std::vector<Renderable> extMap = {
		{},
		{"html", "md"},
		{"htm", "md"}
	};
	
	if (request[0] != '/')
		request.insert(0, "/");
	
	// check for file ext
	extPos = request.rfind(".");

	if (extPos == std::string::npos) { // no extention, check to see if is a directory
		// check dir
			// check for index 
				// do file map
	}

	// map file to pre render format
	baseFile = request.substr(0, extPos);
	ext = request.substr(extPos + 1);
	for (uint i = 0; i < extMap.size(); ++i) {
		if (extMap[i].to == ext) {
			extGroup = i;
		}
		if (extGroup) { break; }
	}
	// if we have a render group check both files
	if (extGroup) {
		// get the file details
		FileStat rendered = (FileStat(this->webRoot + baseFile + "." + extMap[extGroup].to));
		FileStat data = (FileStat(this->dataRoot + baseFile + "." + extMap[extGroup].from));
		log_message("Testing for file: " + rendered.path);
		log_message("Testing for file: " + data.path);
		this->file_check(rendered);
		this->file_check(data);
		// check change times
		if (rendered.modified && rendered.modified >= data.modified) {
			// serve the exisiting
			log_message("serving " + rendered.path);
			this->serve_existing(rendered.path);
		} else if (data.modified) {
			// render and serve
			std::string render;
			this->read_file(data.path, render);
			// TODO: make this easier to extend render types, adding scss atleast would be nice
			// TODO: how could i account for a context to render mstch also? 
			render = this->render_md(render);
			log_message("serving: " + data.path);
			if (render != "") {
				this->context_emplace("content", render);
				this->renderedPage = this->render_mstch(this->pageTemplate, this->pageContext);
				this->write_file(rendered.path, this->renderedPage);
				this->serve_existing(rendered.path, &this->renderedPage);
			}// else TODO: there was prolly an error in the syntax of the md file
		}
		// if we get here neither file should exist
		// just returning should force a 404 due to default values
	} else {
		// no ext group check for an existing file		
		FileStat rendered(this->webRoot + baseFile);
		if (this->file_check(rendered)) {
			this->serve_existing(rendered.path);
		} // else file should not exist, return to force 404
	}
}
    virtual ReadResult readNode(const std::string& uri, const Options* options) const
    {
        static int s_tileCount = 0;
        static double s_tileTime = 0.0;
        static osg::Timer_t s_startTime;

        if ( "osgearth_engine_mp_tile" == osgDB::getFileExtension(uri) )
        {
            if ( s_tileCount == 0 )
                s_startTime = osg::Timer::instance()->tick();

            // See if the filename starts with server: and strip it off.  This will trick OSG
            // into passing in the filename to our plugin instead of using the CURL plugin if
            // the filename contains a URL.  So, if you want to read a URL, you can use the
            // following format: osgDB::readNodeFile("server:http://myserver/myearth.earth").
            // This should only be necessary for the first level as the other files will have
            // a tilekey prepended to them.
            if ((uri.length() > 7) && (uri.substr(0, 7) == "server:"))
                return readNode(uri.substr(7), options);

            // parse the tile key and engine ID:
            std::string tileDef = osgDB::getNameLessExtension(uri);
            unsigned int lod, x, y, engineID;
            sscanf(tileDef.c_str(), "%d/%d/%d.%d", &lod, &x, &y, &engineID);

            // find the appropriate engine:
            osg::ref_ptr<MPTerrainEngineNode> engineNode;
            MPTerrainEngineNode::getEngineByUID( (UID)engineID, engineNode );
            if ( engineNode.valid() )
            {
                osg::Timer_t start = osg::Timer::instance()->tick();

                // assemble the key and create the node:
                const Profile* profile = engineNode->getMap()->getProfile();
                TileKey key( lod, x, y, profile );
                osg::ref_ptr< osg::Node > node = engineNode->createNode( key );
                
                // Blacklist the tile if we couldn't load it
                if ( !node.valid() )
                {
                    OE_DEBUG << LC << "Blacklisting " << uri << std::endl;
                    osgEarth::Registry::instance()->blacklist( uri );
                    return ReadResult::FILE_NOT_FOUND;
                }
                else
                {   
                    // make safe ref/unref so we can reference from multiple threads
                    node->setThreadSafeRefUnref( true );

                    // notify the Terrain interface of a new tile
                    osg::Timer_t start = osg::Timer::instance()->tick();
                    engineNode->getTerrain()->notifyTileAdded(key, node.get());
                    osg::Timer_t end = osg::Timer::instance()->tick();

                    //OE_DEBUG << "Took " << osg::Timer::instance()->delta_m(start, end) << "ms to fire terrain callbacks" << std::endl;
                }

                return ReadResult( node.get(), ReadResult::FILE_LOADED );
            }
            else
            {
                return ReadResult::FILE_NOT_FOUND;
            }
        }
        else
        {
            return ReadResult::FILE_NOT_HANDLED;
        }
    }
Example #11
0
// Some Helper Fuctions
//! Extracts the MoC and the process constructor name from a ForSyDe kind.
void get_moc_and_pc(const std::string& kind, std::string& moc, std::string& pc)
{
    moc = kind.substr(0, kind.find(':'));
    pc = kind.substr(kind.rfind(':')+1, kind.length());
}
void CCDataReaderHelper::addDataFromJsonCache(const char *fileContent)
{
    cs::CSJsonDictionary json;
    json.initWithDescription(fileContent);

    // Decode armatures
    int length = json.getArrayItemCount(ARMATURE_DATA);
    for (int i = 0; i < length; i++)
    {
        cs::CSJsonDictionary *armatureDic = json.getSubItemFromArray(ARMATURE_DATA, i);
        CCArmatureData *armatureData = decodeArmature(*armatureDic);
        CCArmatureDataManager::sharedArmatureDataManager()->addArmatureData(armatureData->name.c_str(), armatureData);

        delete armatureDic;
    }

    // Decode animations
    length = json.getArrayItemCount(ANIMATION_DATA);
    for (int i = 0; i < length; i++)
    {
        cs::CSJsonDictionary *animationDic = json.getSubItemFromArray(ANIMATION_DATA, i);
        CCAnimationData *animationData = decodeAnimation(*animationDic);
        CCArmatureDataManager::sharedArmatureDataManager()->addAnimationData(animationData->name.c_str(), animationData);

        delete animationDic;
    }

    // Decode textures
    length = json.getArrayItemCount(TEXTURE_DATA);
    for (int i = 0; i < length; i++)
    {
        cs::CSJsonDictionary *textureDic = json.getSubItemFromArray(TEXTURE_DATA, i);
        CCTextureData *textureData = decodeTexture(*textureDic);
        CCArmatureDataManager::sharedArmatureDataManager()->addTextureData(textureData->name.c_str(), textureData);

        delete textureDic;
    }

	// Auto load sprite file
	if (CCArmatureDataManager::sharedArmatureDataManager()->isAutoLoadSpriteFile())
	{
		length = json.getArrayItemCount(CONFIG_FILE_PATH);
		for (int i = 0; i < length; i++)
		{
			const char *path = json.getStringValueFromArray(CONFIG_FILE_PATH, i);
			if (path == NULL)
			{
				CCLOG("load CONFIG_FILE_PATH error.");
				return;
			}

			std::string filePath = path;

			std::string plistPath = filePath;
			std::string pngPath = filePath.erase(filePath.find_last_of(".")) + ".png";

			
			size_t pos = s_filePath.find_last_of("/");
			if (pos != std::string::npos)
			{
				filePath = s_filePath.substr(0, pos+1);
			}

			CCArmatureDataManager::sharedArmatureDataManager()->addSpriteFrameFromFile((filePath + plistPath).c_str(), (filePath + pngPath).c_str());
		}
	}
}
//---------------------------------------------------------------------------
//From http://www.richelbilderbeek.nl/CppRemoveExtension.htm
const std::string RemoveExtension(const std::string& filename)
{
  const int dot_index = filename.rfind(".",filename.size());
  assert(dot_index != -1 && "No dot found in filename");
  return filename.substr(0,dot_index);
}
Example #14
0
int ModelerUserInterface::loadFile(std::string& buffer,
								   const bool save,
								   const char* title,
								   const char* filter,
								   const char* extensions) {
	while (true) {
		// Ask user
		const char* fileName = fileDialog(
			save ? Fl_Native_File_Chooser::BROWSE_SAVE_FILE :
				Fl_Native_File_Chooser::BROWSE_FILE,
			filter, title);

		if (fileName == NULL) {
			return 0;
		}
		buffer = std::string(fileName);

		// Get desired file type
		int fileType = m_nativeChooser->filter_value();
		int retVal = fileType + 1;

		if (save) {
			// Get the extension for the file type
			const char* ext = extensions - 1;
			while (ext && fileType) {
				fileType--;
				ext = strchr(ext + 1, '\t');
			}

			// Append extension if the file name is missing one.
			if (ext) {
				ext++;
				int end = strlen(ext);
				const char* extEnd = strchr(ext, '\t');
				if (extEnd != NULL) {
					end -= strlen(extEnd);
				}
				std::string realExt(ext, end);

				unsigned int pos = buffer.find_last_of('.');
				if (pos == buffer.npos || buffer.find_last_of("\\/") > pos) {
					buffer.append(".");
					buffer.append(realExt);
				} else {
					std::string bufferExt = buffer.substr(pos + 1);
					// Make sure the extension matches the file type.
					if (bufferExt.compare(realExt) != 0) {
						switch (fl_choice("You selected the file type %s, but your "
							"file name's extension is %s.\n\nDo you want to fix "
							"the extension, or save with a different name?",
							"Cancel", "Fix Extension", "Different Name",
							realExt.c_str(), bufferExt.c_str())) {
						case 0:
							return 0;
						case 1:
							buffer = buffer.substr(0, pos + 1);
							buffer += realExt;
							break;
						case 2:
							continue;
						}
					}
				}
			}
		}

		return retVal;
	}
}
Example #15
0
std::string Client::buildOAuthParameterString(
    ParameterStringType string_type,
    const Http::RequestType eType,
    const std::string& rawUrl,
    const std::string& rawData,
    const bool includeOAuthVerifierPin)
{
    KeyValuePairs rawKeyValuePairs;
    std::string rawParams;
    std::string oauthSignature;
    std::string paramsSeperator;
    std::string pureUrl( rawUrl );

    std::string separator;
    bool do_urlencode;
    if (string_type == AuthorizationHeaderString) {
        separator = ",";
        do_urlencode = false;
    }
    else if (string_type == QueryStringString) {
        separator = "&";
        do_urlencode = true;
    }

    /* Clear header string initially */
    rawKeyValuePairs.clear();

    /* If URL itself contains ?key=value, then extract and put them in map */
    size_t nPos = rawUrl.find_first_of( "?" );
    if( std::string::npos != nPos )
    {
        /* Get only URL */
        pureUrl = rawUrl.substr( 0, nPos );

        /* Get only key=value data part */
        std::string dataPart = rawUrl.substr( nPos + 1 );
        rawKeyValuePairs = ParseKeyValuePairs(dataPart);
    }

    // NOTE: We always request URL encoding on the first pass so that the
    // signature generation works properly. This *relies* on
    // buildOAuthTokenKeyValuePairs overwriting values when we do the second
    // pass to get the values in the form we actually want. The signature and
    // rawdata are the only things that change, but the signature is only used
    // in the second pass and the rawdata is already encoded, regardless of
    // request type.

    /* Build key-value pairs needed for OAuth request token, without signature */
    buildOAuthTokenKeyValuePairs( includeOAuthVerifierPin, rawData, std::string( "" ), rawKeyValuePairs, true, true );

    /* Get url encoded base64 signature using request type, url and parameters */
    getSignature( eType, pureUrl, rawKeyValuePairs, oauthSignature );

    /* Now, again build key-value pairs with signature this time */
    buildOAuthTokenKeyValuePairs( includeOAuthVerifierPin, std::string( "" ), oauthSignature, rawKeyValuePairs, do_urlencode, false );

    /* Get OAuth header in string format. If we're getting the Authorization
     * header, we need to filter out other parameters.
     */
    if (string_type == AuthorizationHeaderString) {
        KeyValuePairs oauthKeyValuePairs;
        std::vector<std::string> oauth_keys;
        oauth_keys.push_back(Defaults::CONSUMERKEY_KEY);
        oauth_keys.push_back(Defaults::NONCE_KEY);
        oauth_keys.push_back(Defaults::SIGNATURE_KEY);
        oauth_keys.push_back(Defaults::SIGNATUREMETHOD_KEY);
        oauth_keys.push_back(Defaults::TIMESTAMP_KEY);
        oauth_keys.push_back(Defaults::TOKEN_KEY);
        oauth_keys.push_back(Defaults::VERIFIER_KEY);
        oauth_keys.push_back(Defaults::VERSION_KEY);

        for(size_t i = 0; i < oauth_keys.size(); i++) {
            assert(rawKeyValuePairs.count(oauth_keys[i]) <= 1);
            KeyValuePairs::iterator oauth_key_it = rawKeyValuePairs.find(oauth_keys[i]);
            if (oauth_key_it != rawKeyValuePairs.end())
                ReplaceOrInsertKeyValuePair(oauthKeyValuePairs, oauth_keys[i], oauth_key_it->second);
        }
        getStringFromOAuthKeyValuePairs( oauthKeyValuePairs, rawParams, separator );
    }
    else if (string_type == QueryStringString) {
        getStringFromOAuthKeyValuePairs( rawKeyValuePairs, rawParams, separator );
    }

    /* Build authorization header */
    return rawParams;
}
Example #16
0
bool endsWith(const std::string& s, const std::string& f) {
    auto end = s.substr(s.size() - f.size());
    return (end == f);
}
std::string SqlError::formatMessage(const std::string &sql_query) const {
  CHECK(!sql_query.empty()) << "SQL query is empty";
  CHECK_LT(sql_query.size(), static_cast<std::size_t>(std::numeric_limits<int>::max()));

  int error_line_number = line_number_;
  int error_column_number = column_number_;

  if (error_line_number == -1) {
    // If the error location is not available,
    // just append the error message directly.
    return std::string("ERROR: ").append(error_stream_.str()).append("\n");
  }

  DCHECK_GT(error_column_number, -1) << "Invalid column number";

  int current_line_number = 0;
  int current_line_begin_pos = 0;
  int current_line_end_pos = -1;

  // Find the ending index of the (<error_line_number>-1)-th line
  // of <sql_query>.
  if (current_line_number < error_line_number) {
    while (current_line_number < error_line_number) {
      current_line_begin_pos = sql_query.find('\n', current_line_begin_pos);
      DCHECK_GE(current_line_begin_pos, 0) << "Invalid line number";
      ++current_line_number;
      ++current_line_begin_pos;
    }
  }

  /*
   * The BISON may point the error to a position beyond the last line of
   * the SQL query. We move it to the position to the end of the last line.
   */
  if (current_line_begin_pos == static_cast<int>(sql_query.size()) && column_number_ == 0) {
    current_line_end_pos = current_line_begin_pos - 1;
    current_line_begin_pos = sql_query.rfind('\n', current_line_end_pos - 1) + 1;

    // Move the error line to the previous line.
    --error_line_number;
    error_column_number = current_line_end_pos - current_line_begin_pos;
  } else {
    current_line_end_pos = sql_query.find('\n', current_line_begin_pos);
    if (current_line_end_pos == -1) {
      current_line_end_pos = sql_query.size() - 1;
    }
    DCHECK(current_line_end_pos - current_line_begin_pos + 1 > column_number_) << "Invalid line and column number";
  }

  std::ostringstream error_stream;
  const int start_pos = getStartErrorPos(error_column_number + current_line_begin_pos, sql_query);
  const int end_pos = getEndErrorPos(error_column_number + current_line_begin_pos, sql_query);

  DCHECK_LE(start_pos, error_column_number + current_line_begin_pos);
  DCHECK_LE(error_column_number + current_line_begin_pos, end_pos);

  error_stream << "ERROR: " << getErrorMessage();
  error_stream << " (" << error_line_number + 1 << " : " << error_column_number + 1 << ")\n";

  // Append the snippet text.
  bool has_omitted_text = false;
  if (start_pos > current_line_begin_pos) {
    error_stream << "...";
    has_omitted_text = true;
  }
  error_stream << sql_query.substr(start_pos, end_pos - start_pos);
  if (end_pos < current_line_end_pos) {
    error_stream << "...";
  }
  error_stream << "\n";

  // Append a caret.
  if (has_omitted_text) {
    error_stream << "   ";
  }
  for (int i = start_pos; i < error_column_number + current_line_begin_pos; ++i) {
    if (sql_query.at(i) == '\t') {
      error_stream << "\t";
    } else {
      error_stream << " ";
    }
  }
  error_stream << "^\n";

  return error_stream.str();
}
Example #18
0
void ABCShell::processCommand(std::string command)
{
    //Push command on the history stack
    pushHistory(command);

    if(command == "history")
        printHistory();
    else if(command.find("path") == 0 && command.length() > 4)
    {
        path = command.substr(5, command.length()-5);
    }
    else if(command.find("path") == 0 && command.length() == 4)
    {
        std::cout << path << std::endl;
    }
    else
    {
    #ifdef LINUX
            int child, childStatus;

            if((child = fork())==0)
            {    
    #endif

    #ifdef WINDOWS
            Process myprocess;
	        ProcessStartInfo^ proc1 = new ProcessStartInfo;
    #endif

                size_t i=-1, l=0, s=0;
                std::vector<std::string> args;
                std::string arg_final[5];
                for(int i = 0; i < 5; i++)
                    arg_final[i] = "";
                int count = 0;
                do 
                {
                    i = command.find(" ", i+1);
                    if ( i == std::string::npos )
                        s = std::string::npos;
                    else
                        s = i - l;
                    args.push_back(command.substr(l, s));
                    l = i + 1;
                    #ifdef DEBUG
                        std::cout << args.back() << std::endl;
                    #endif
                    arg_final[count] = args.back();
                    count++;
                } while ( i != std::string::npos );

                #ifdef DEBUG
                    for(int i = 0; i < 5; i++)
                        std::cout << arg_final[i] << std::endl;
                #endif

                //Parse for abcshell commands

                //List all
                if(arg_final[0] == "a")
                {
                    arg_final[4] = arg_final[3];
                    arg_final[3] = arg_final[2];

                    arg_final[0] = "ls";
                    arg_final[1] = "-l";
                    arg_final[2] = "-a";
                    if(count == 1)
                        count = 3;
                    else
                        count += 3;
                }
                //Concatenate
                else if(arg_final[0] == "c")
                {
                    arg_final[0] = "cat";
                }
                //Diff
                else if(arg_final[0] == "d")
                {
                    arg_final[0] = "diff";
                }
                //Help
                else if(arg_final[0] == "h")
                {
                    arg_final[0] = "man";
                }
                //List
                else if(arg_final[0] == "l")
                {
                    #ifdef LINUX
                        arg_final[0] = "ls";
                    #endif
                    #ifdef WINDOWS
                        arg_final[0] = "dir";
                    #endif
                }
                //Print
                else if(arg_final[0] == "p")
                {
                    arg_final[0] = "echo";
                }
                //Move
                else if(arg_final[0] == "m")
                {
                    arg_final[0] = "mv";
                }
                //Remove
                else if(arg_final[0] == "r")
                {
                    arg_final[0] = "rm";
                }
                //Touch
                else if(arg_final[0] == "t")
                {
                    arg_final[0] = "touch";
                }
                //Copy
                else if(arg_final[0] == "v")
                {
                    arg_final[0] = "cp";
                }

                //Execute command
            #ifdef LINUX
                if(count == 1)
                    execlp(arg_final[0].c_str(), arg_final[0].c_str(), NULL);
                else if(count == 2)
                    execlp(arg_final[0].c_str(), arg_final[0].c_str(), arg_final[1].c_str(), NULL);
                else if(count == 3)
                    execlp(arg_final[0].c_str(), arg_final[0].c_str(), arg_final[1].c_str(), arg_final[2].c_str(), NULL);
                else if(count == 4)
                    execlp(arg_final[0].c_str(), arg_final[0].c_str(), arg_final[1].c_str(), arg_final[2].c_str(), arg_final[3].c_str(), NULL);
                else if(count >= 5)
                    execlp(arg_final[0].c_str(), arg_final[0].c_str(), arg_final[1].c_str(), arg_final[2].c_str(), arg_final[3].c_str(), arg_final[4].c_str(), NULL);

                exit(0);
            }
            else
            {
                waitpid(child, &childStatus, 0);
            }
            #endif
            #ifdef WINDOWS
                std::string finalCommand = "";
                for(int i = 0; i < 5; i++)
                    finalCommand += arg_final[i];
                proc1->FileName = finalCommand;
                myprocess.StartInfo = proc1;
                myprocess.Start();
            #endif
    }
}
void CSpawnScript::Update(void)
{
	switch(gs->frameNum){
	case 0:
		LoadSpawns();

		CSunParser p;
		p.LoadFile("gamedata\\sidedata.tdf");
		string s0=p.SGetValueDef("armcom","side0\\commander");
		string s1=p.SGetValueDef("corcom","side1\\commander");

		CSunParser p2;
		p2.LoadFile(string("maps\\")+stupidGlobalMapname.substr(0,stupidGlobalMapname.find('.'))+".smd");

		float x0,z0;
		p2.GetDef(x0,"1000","MAP\\TEAM0\\StartPosX");
		p2.GetDef(z0,"1000","MAP\\TEAM0\\StartPosZ");

		unitLoader.LoadUnit(s0,float3(x0,80,z0),0,false);

		p2.GetDef(x0,"1000","MAP\\TEAM1\\StartPosX");
		p2.GetDef(z0,"1000","MAP\\TEAM1\\StartPosZ");		
		spawnPos.push_back(float3(x0,80,z0));

		p2.GetDef(x0,"1000","MAP\\TEAM2\\StartPosX");
		p2.GetDef(z0,"1000","MAP\\TEAM2\\StartPosZ");		
		spawnPos.push_back(float3(x0,80,z0));

		p2.GetDef(x0,"1000","MAP\\TEAM3\\StartPosX");
		p2.GetDef(z0,"1000","MAP\\TEAM3\\StartPosZ");		
		spawnPos.push_back(float3(x0,80,z0));
	}

	if(!spawns.empty()){
		while(curSpawn->frame+frameOffset<gs->frameNum){
			int num=spawnPos.size()*0.99*gs->randFloat();

			CUnit* u=unitLoader.LoadUnit(curSpawn->name,spawnPos[num]+gs->randVector()*200,1,false);

			Unit unit;
			unit.id=u->id;
			unit.target=-1;
			myUnits.push_back(unit);
			if(myUnits.size()==1)
				curUnit=myUnits.begin();

			++curSpawn;
			if(curSpawn==spawns.end()){
				curSpawn=spawns.begin();
				frameOffset+=spawns.back().frame;
			}
		}
	}
	
	if(!myUnits.empty() && !gs->teams[0]->units.empty()){
		if(uh->units[curUnit->id]){
			if(curUnit->target<0 || uh->units[curUnit->target]==0){
				int num=gs->randFloat()*0.99*gs->teams[0]->units.size();
				std::set<CUnit*>::iterator tu=gs->teams[0]->units.begin();
				for(int a=0;a<num;++a)
					++tu;
				curUnit->target=(*tu)->id;
				curUnit->lastTargetPos.x=-500;
			}
			float3 pos=uh->units[curUnit->target]->pos;
			if(pos.distance2D(curUnit->lastTargetPos)>100){
				curUnit->lastTargetPos=pos;
				Command c;
				c.id=CMD_PATROL;
				c.options=0;
				c.params.push_back(pos.x);
				c.params.push_back(pos.y);
				c.params.push_back(pos.z);
				uh->units[curUnit->id]->commandAI->GiveCommand(c);
			}
			curUnit++;
		} else {
			curUnit=myUnits.erase(curUnit);
		}
		if(curUnit==myUnits.end())
			curUnit=myUnits.begin();
	}
}
Example #20
0
    //=================================================================
    bool TileAssembler::readRawFile(std::string& pModelFilename,  ModelPosition& pModelPosition, AABSPTree<SubModel *> *pMainTree)
    {
        std::string filename = iSrcDir;
        if(filename.length() >0)
            filename.append("/");
        filename.append(pModelFilename);
        FILE *rf = fopen(filename.c_str(), "rb");
        if(!rf)
        {
            // depending on the extractor version, the data could be located in the root dir
            std::string baseModelFilename = pModelFilename.substr((pModelFilename.find_first_of("/")+1),pModelFilename.length());
            filename = iSrcDir;
            if(filename.length() >0)
                filename.append("/");
            filename.append(baseModelFilename);
            rf = fopen(filename.c_str(), "rb");
        }

        if(!rf)
        {
            printf("ERROR: Can't open model file in form: %s",pModelFilename.c_str());
            printf("...                          or form: %s",filename.c_str() );
            return false;
        }

        char ident[8];

        int trianglecount =0;

        #ifdef _ASSEMBLER_DEBUG
        int startgroup = 0;                     //2;
        int endgroup = INT_MAX;                 //2;
        fprintf(::g_df,"-------------------------------------------------\n");
        fprintf(::g_df,"%s\n", pModelFilename.c_str());
        fprintf(::g_df,"-------------------------------------------------\n");
        #else
        int startgroup = 0;
        int endgroup = INT_MAX;
        #endif

        // temporary use defines to simplify read/check code (close file and return at fail)
        #define READ_OR_RETURN(V,S) if(fread((V), (S), 1, rf) != 1) { \
                                        fclose(rf); return(false); }
        #define CMP_OR_RETURN(V,S)  if(strcmp((V),(S)) != 0)        { \
                                        fclose(rf); return(false); }

        READ_OR_RETURN(&ident, 8);
        if(strcmp(ident, "VMAP001") == 0)
        {
            // OK, do nothing
        }
        else if(strcmp(ident, "VMAP002") == 0)
        {
            // we have to read one int. This is needed during the export and we have to skip it here
            int tempNVectors;
            READ_OR_RETURN(&tempNVectors, sizeof(int));

        }
        else
        {
            // wrong version
            fclose(rf);
            return(false);
        }
        G3D::uint32 groups;
        char blockId[5];
        blockId[4] = 0;
        int blocksize;

        READ_OR_RETURN(&groups, sizeof(G3D::uint32));

        for(int g=0;g<(int)groups;g++)
        {
            // group MUST NOT have more then 65536 indexes !! Array will have a problem with that !! (strange ...)
            Array<int> tempIndexArray;
            Array<Vector3> tempVertexArray;

            AABSPTree<Triangle> *gtree = new AABSPTree<Triangle>();

            // add free gtree at fail
            #undef READ_OR_RETURN
            #undef CMP_OR_RETURN
            #define READ_OR_RETURN(V,S) if(fread((V), (S), 1, rf) != 1) { \
                                            fclose(rf); delete gtree; return(false); }
            #define CMP_OR_RETURN(V,S)  if(strcmp((V),(S)) != 0)        { \
                                            fclose(rf); delete gtree; return(false); }

            G3D::uint32 flags;
            READ_OR_RETURN(&flags, sizeof(G3D::uint32));

            G3D::uint32 branches;
            READ_OR_RETURN(&blockId, 4);
            CMP_OR_RETURN(blockId, "GRP ");
            READ_OR_RETURN(&blocksize, sizeof(int));
            READ_OR_RETURN(&branches, sizeof(G3D::uint32));
            for(int b=0;b<(int)branches; b++)
            {
                G3D::uint32 indexes;
                // indexes for each branch (not used jet)
                READ_OR_RETURN(&indexes, sizeof(G3D::uint32));
            }

            // ---- indexes
            READ_OR_RETURN(&blockId, 4);
            CMP_OR_RETURN(blockId, "INDX");
            READ_OR_RETURN(&blocksize, sizeof(int));
            unsigned int nindexes;
            READ_OR_RETURN(&nindexes, sizeof(G3D::uint32));
            if(nindexes >0)
            {
                unsigned short *indexarray = new unsigned short[nindexes*sizeof(unsigned short)];
                READ_OR_RETURN(indexarray, nindexes*sizeof(unsigned short));
                for(int i=0;i<(int)nindexes; i++)
                {
                    unsigned short val = indexarray[i];
                    tempIndexArray.append(val);
                }
                delete[] indexarray;
            }

            // ---- vectors
            READ_OR_RETURN(&blockId, 4);
            CMP_OR_RETURN(blockId, "VERT");
            READ_OR_RETURN(&blocksize, sizeof(int));
            unsigned int nvectors;
            READ_OR_RETURN(&nvectors, sizeof(int));

            float *vectorarray = 0;

            // add vectorarray free
            #undef READ_OR_RETURN
            #undef CMP_OR_RETURN
            #define READ_OR_RETURN(V,S) if(fread((V), (S), 1, rf) != 1) { \
                                            fclose(rf); delete gtree; delete[] vectorarray; return(false); }
            #define CMP_OR_RETURN(V,S)  if(strcmp((V),(S)) != 0)        { \
                                            fclose(rf); delete gtree; delete[] vectorarray; return(false); }

            if(nvectors >0)
            {
                vectorarray = new float[nvectors*sizeof(float)*3];
                READ_OR_RETURN(vectorarray, nvectors*sizeof(float)*3);
            }
            // ----- liquit
            if(flags & 1)
            {
                // we have liquit -> not handled yet ... skip
                READ_OR_RETURN(&blockId, 4);
                CMP_OR_RETURN(blockId, "LIQU");
                READ_OR_RETURN(&blocksize, sizeof(int));
                fseek(rf, blocksize, SEEK_CUR);
            }


            for(unsigned int i=0, indexNo=0; indexNo<nvectors; indexNo++)
            {
                Vector3 v = Vector3(vectorarray[i+2], vectorarray[i+1], vectorarray[i+0]);
                i+=3;
                v = pModelPosition.transform(v);

                float swapy = v.y;
                v.y = v.x;
                v.x = swapy;

                tempVertexArray.append(v);
            }

            // ---- calculate triangles
            int rest = nindexes%3;
            if(rest != 0)
            {
                nindexes -= rest;
            }

            for(unsigned int i=0;i<(nindexes);)
            {
                Triangle t = Triangle(tempVertexArray[tempIndexArray[i+2]], tempVertexArray[tempIndexArray[i+1]], tempVertexArray[tempIndexArray[i+0]] );
                i+=3;
                ++trianglecount;
                if(g>= startgroup && g <= endgroup)
                {
                    gtree->insert(t);
                }
            }

            // drop of temporary use defines
            #undef READ_OR_RETURN
            #undef CMP_OR_RETURN

            if(vectorarray != 0)
            {
                delete[] vectorarray;
            }

            if(gtree->size() >0)
            {
                gtree->balance();
                SubModel *sm = new SubModel(gtree);
                #ifdef _ASSEMBLER_DEBUG
                if(::g_df) fprintf(::g_df,"group trianglies: %d, Tris: %d, Nodes: %d, gtree.triangles: %d\n", g, sm->getNTriangles(), sm->getNNodes(), gtree->memberTable.size());
                if(sm->getNTriangles() !=  gtree->memberTable.size())
                {
                    if(::g_df) fprintf(::g_df,"ERROR !!!! group trianglies: %d, Tris: %d, Nodes: %d, gtree.triangles: %d\n", g, sm->getNTriangles(), sm->getNNodes(), gtree->memberTable.size());
                }
                #endif
                sm->setBasePosition(pModelPosition.iPos);
                pMainTree->insert(sm);
            }
            delete gtree;
        }
        fclose(rf);
        return true;
    }
Example #21
0
//------------------------------------------------------------------------------
// void Add(const std::string &type, Gmat::ObjectType objectType, ...)
//------------------------------------------------------------------------------
void ParameterInfo::Add(const std::string &type, Gmat::ObjectType objectType,
                        Gmat::ObjectType ownedObjType, const std::string &name,
                        GmatParam::DepObject depType, bool isPlottable,
                        bool isReportable, bool isSettable, bool isTimeParam,
                        const std::string &desc)
{
   #ifdef DEBUG_PARAM_INFO
   MessageInterface::ShowMessage
      ("ParameterInfo::Add() entered, type='%s', objectType=%d, ownedObjType=%d"
       "\n   name='%s', depType=%d, isPlottable=%d, isReportable=%d, isSettable=%d, "
       "isTimeParam=%d, desc='%s'\n", type.c_str(), objectType, ownedObjType,
       name.c_str(), depType, isPlottable, isReportable, isSettable, isTimeParam,
       desc.c_str());
   #endif
   
   // Check for dot first
   std::string::size_type pos = name.find_last_of(".");
   if (pos == name.npos)
   {
      #ifdef DEBUG_PARAM_INFO
      MessageInterface::ShowMessage
         ("ParameterInfo::Add() leaving, '%s' was not added, it's not a System Parameter\n",
          type.c_str());
      #endif
      return;
   }
   
   // Check for the same property
   if (mOwnerTypeMap.find(type) != mOwnerTypeMap.end())
   {
      #ifdef DEBUG_PARAM_INFO
      MessageInterface::ShowMessage
         ("ParameterInfo::Add() leaving, '%s' was not added, it's been already added\n",
          type.c_str());
      #endif
      return;
   }
   
   std::string depTypeStr = Parameter::GetDependentTypeString(depType);
   if (GmatGlobal::Instance()->IsWritingParameterInfo())
   {
      std::string objTypeStr = GmatBase::GetObjectTypeString(objectType);
      std::string ownedObjTypeStr = "          ";
      std::string plottableStr = "N";
      std::string reportableStr = "N";
      std::string settableStr = "N";
      if (isPlottable)  plottableStr  = "Y";
      if (isReportable) reportableStr = "Y";
      if (isSettable)   settableStr   = "Y";
      if (depTypeStr == "OwnedObject" || depTypeStr == "AttachedObject")
         ownedObjTypeStr = "(" + GmatBase::GetObjectTypeString(ownedObjType) + ")";
      if (mNumParams == 0)
      {
         MessageInterface::ShowMessage
            ("\n================================================================================================\n"
             "====================================== GMAT Parameter List =====================================\n"
             "================================================================================================\n"
             "(R = Reportable, P = Plottable, S = Settable)\n"
             "No   ParameterType              ObjectType     DependencyType                        R  P  S  Description\n"
             "---  ----------------           -------------  --------------------------------      -  -  -  -----------\n");
      }
      MessageInterface::ShowMessage
         ("%3d  %-25s  %-13s  %-16s%20s  %s  %s  %s  %s\n", mNumParams+1, type.c_str(),
          objTypeStr.c_str(), depTypeStr.c_str(), ownedObjTypeStr.c_str(), reportableStr.c_str(),
          plottableStr.c_str(), settableStr.c_str(), desc.c_str());
   }
   
   // Add property objectType
   mOwnerTypeMap[type] = objectType;
   
   // Add property name
   std::string propertyName = name.substr(pos+1, name.npos-pos);
   
   mDepObjMap[propertyName] = depType;
   
   // Add plottable Parameters
   if (isPlottable)
      mIsPlottableMap[type] = isPlottable;
   
   // Add reportable Parameters
   if (isReportable)
      mIsReportableMap[type] = isReportable;
   
   // Add settable Parameters
   if (isSettable)
      mIsSettableMap[type] = isSettable;
   
   // Add time Parameters
   if (isTimeParam)
      mIsTimeParamMap[type] = isTimeParam;

   // Set Requires BodyFixed CS flag to false
   mRequiresBodyFixedCSMap[type] = false;
   
   // Set Requires CelestialBody CS Origin flag to false
   mRequiresCelestialBodyCSOriginMap[type] = false;

   // Add owned object dep paramters
   if (depType == GmatParam::OWNED_OBJ)
   {
      mIsForOwnedObjMap[type] = true;
      mOwnedObjTypeMap[type] = ownedObjType;
   }
   
   // Add attached object dep paramters
   if (depType == GmatParam::ATTACHED_OBJ)
   {
      mIsForAttachedObjMap[type] = true;
      mOwnedObjTypeMap[type] = ownedObjType;
   }
   
   mNumParams = mDepObjMap.size();
   
   #ifdef DEBUG_PARAM_INFO
   MessageInterface::ShowMessage
      ("ParameterInfo::Add() leaving, propertyName:'%s' was added. There are "
       "total %d Parameters\n", propertyName.c_str(), mNumParams);
   #endif
}
Example #22
0
// tries to match the extension ext to the end of the file name
inline bool extensionMatches(const std::string& file, const std::string& ext)
{
    if (file.size() < ext.size()) return false;
    return (tolcstr(file.substr(file.size() - ext.size())) == ext);
}
Example #23
0
void myMessage::newMessage(const mail::folder *folderPtr,
			   myServer *serverPtr,
			   std::string mailtoUrl)
{
	string fromhdr="";
	string replytohdr="";

	string from="", replyto="";
	string fcc;
	string customheaders="";

	if (!getDefaultHeaders(folderPtr, serverPtr, from, replyto, fcc,
			       customheaders))
		return;

	clearAttFiles();

	string messagetxt=myServer::getConfigDir() + "/message.txt";
	string messagetmp=myServer::getConfigDir() + "/message.tmp";

	{
		ofstream o(messagetmp.c_str());

		if (serverPtr)
			o << "X-Server: "
			  << (string)mail::rfc2047::encode(serverPtr->url,
							   "iso-8859-1")
			  << "\n";
		if (folderPtr)
			o << "X-Folder: "
			  << (string)mail::rfc2047::encode(folderPtr
							   ->getPath(),
							   "iso-8859-1")
			  << "\n";

		{
			string n;

			if (serverPtr && folderPtr &&
			    (n=folderPtr->isNewsgroup()).size() > 0)
				o << "Newsgroups: " << n << "\n";
		}

		if (fcc.size() > 0)
			o << "X-Fcc: "
			  << (string)mail::rfc2047::encode(fcc, "UTF-8")
			  << "\n";

		if (customheaders.size() > 0)
			o << customheaders << "\n";

		o << "From: " << from << "\n"
		  << "Reply-To: " << replyto << "\n\n";

		if (mailtoUrl.size() > 0)
		{
			std::string params;

			size_t p=mailtoUrl.find('?');

			if (p != std::string::npos)
			{
				params=mailtoUrl.substr(p+1);
				mailtoUrl=mailtoUrl.substr(0, p);
			}

			newMessageAddressHdr(mailtoUrl, "To: ", o);

			map<string, u32string > args;

			{
				u32string uparams;

				htmlParser::urlDecode(params, uparams);

				htmlParser::cgiDecode(uparams, args);
			}

			u32string &s=args["subject"];

			string ss=unicode::iconvert::convert(s, "utf-8");

			if (ss.size() > 0)
			{
				ss=mail::rfc2047::encode(ss, "utf-8");

				o << "Subject: " <<
					ss.c_str() << "\n";
			}
		}

		o.flush();

		if (o.bad() || o.fail() ||
		    (o.close(), rename(messagetmp.c_str(), messagetxt.c_str())
		     ) < 0)
		{
			statusBar->clearstatus();
			statusBar->status(strerror(errno));
			statusBar->beepError();
			return;
		}
	}

	Curses::keepgoing=false;
	myServer::nextScreen=editScreen;
	myServer::nextScreenArg=NULL;
}
void user_settings_io::import_settings(const std::string& file_path)
{
  YAML::Node node;
  try
  {
    node = YAML::LoadFile(file_path);
    settings_file_name_ = file_path;
  }
  catch(YAML::Exception& e)
  {
    const std::string& error = "Failed to load user settings file from \"" + file_path + "\".\n\tError: " + e.what();
    LOG(logger::critical, error);
    throw std::runtime_error(error);
  }

  /// Check input file structure validity
  check_input_validity(node);

  settings_.set_fs(node[usc::fs].as<double>());
  settings_.set_excitation_time(node[usc::excitation_time].as<std::size_t>());
  settings_.set_excitation_time_step(node[usc::excitation_time_step].as<double>());
  YAML::Node spec_node = node[usc::rtss::self];
  relaxation_time_step_spec spec(spec_node[usc::rtss::initial_step].as<double>(), spec_node[usc::rtss::time_delta].as<std::size_t>(), spec_node[usc::rtss::coefficient].as<double>());
  settings_.set_relaxation_time_step_spec(spec);
  settings_.set_simulations_count(node[usc::simulations_count].as<std::size_t>());

  if(node[usc::force_application_nodes])
  {
    const YAML::Node& force_node = node[usc::force_application_nodes];
    std::vector<std::size_t> nodes;
    for(std::size_t i = 0; i < force_node.size(); ++i)
    {
      std::size_t node = force_node[i].as<std::size_t>();
      nodes.push_back(node);
    }
    settings_.set_force_application_nodes(nodes);
  }
  settings_.set_forces_dynamic(node[usc::forces_dynamic].as<bool>());

  if(node[usc::visualization_nodes])
  {
    const YAML::Node& visualization_node = node[usc::visualization_nodes];
    std::vector<std::size_t> nodes;
    for(std::size_t i = 0; i < visualization_node.size(); ++i)
    {
      std::size_t node = visualization_node[i].as<std::size_t>();
      nodes.push_back(node);
    }
    settings_.set_visualization_nodes(nodes);
  }

  if(node[usc::nodes])
  {
    settings_.set_network(read_network_from_yaml(node));
  }
  else
  {
    std::string absolute_path = node[usc::network_file_path].as<std::string>();
    if(!absolute_path.empty())
    {
      if(absolute_path[0] != '/')
      {
        //This is relative path, need to attach current YAML file's directory to path
        absolute_path.insert(0, file_path.substr(0, file_path.find_last_of("/") + 1));
      }
      network_file_name_ = absolute_path;
      import_network_from_external_file(absolute_path);
    }
  }

  if(node[usc::l0])
  {
    double cutoff = node[usc::l0].as<double>();
    settings_.set_cutoff_distance(cutoff);
    network net = settings_.get_network();
    net.set_cutoff_distance(cutoff);
    settings_.set_network(net);
  }

  std::cout << settings_ << std::endl;
}
void CTextHelper::parseText(const std::string& line)
{
	std::string buff = "";
	std::string varName = "";
	std::string varValue = "";
	std::string lang = currLang;

	size_t commentPos = line.find("//");
	size_t delimPos = line.find_first_of('=');
	if (delimPos == std::string::npos || delimPos == 0 || delimPos == line.length() - 1)
	{		
		return;
	}

	bool isVarName  = true;
	bool isLangName = false;
	size_t lineEnd = line.length();
	if (commentPos != std::string::npos) lineEnd = commentPos;
	for (size_t pos = 0; pos < lineEnd; ++pos)
	{
		char currChar = line[pos];
		if (currChar < ' ') continue;
		
		if(currChar == '=')
		{
			if (isLangName)
			{
				lang = buff;
				buff = "";
				isVarName = false;
				isLangName = false;
				varValue = line.substr(pos + 1);
				pos = lineEnd;
			}
			if (isVarName)
			{
				varName = buff;
				buff = "";
				isVarName  = false;
				isLangName = false;
				varValue = line.substr(pos + 1);
				pos = lineEnd;
			}
		
		}
		else
		if(currChar == '|')
		{
			if (isVarName)
			{
				varName = buff;
				buff = "";
				isVarName  = false;
				isLangName = true;
				continue;
			}			
		}
		else
		{
			if ((isVarName || isLangName) && currChar == ' ') continue;
			buff += currChar;
		}
	}
	
	if (varName.length() > (size_t)0 && varValue.length() > (size_t)0)
	{
		addText(varName, varValue, lang);
	}
	else
	{		
		return;
	}
}
Example #26
0
void PartyHandler::create(const std::string &name) const
{
    createOutPacket(CMSG_PARTY_CREATE);
    outMsg.writeString(name.substr(0, 23), 24, "party name");
}
Example #27
0
OCLutil::OCLutil(cl_device_type type,std::string arq,std::string buildOptions,std::string nomeRot,int n)
{

    VECTOR_CLASS<cl::Platform> platforms;
    cl::Platform::get(&platforms);

    if(platforms.size() == 0){
        std::cout<<"No OpenCL platforms were found"<<std::endl;
    }

    int platformID = -1;

    for(unsigned int i = 0; i < platforms.size(); i++) {
        try {
            VECTOR_CLASS<cl::Device> devices;
            platforms[i].getDevices(type, &devices);
            platformID = i;
            break;
        } catch(std::exception e) {
            std::cout<<"Error ao ler plataforma: "<<std::endl;
            continue;
        }
    }


    if(platformID == -1){
        std::cout<<"No compatible OpenCL platform found"<<std::endl;
    }

    cl::Platform platform = platforms[platformID];
    std::cout << "Using platform vendor: " << platform.getInfo<CL_PLATFORM_VENDOR>() << std::endl;


    // Use the preferred platform and create a context
    cl_context_properties cps[] = {
        CL_CONTEXT_PLATFORM,
        (cl_context_properties)(platform)(),
        0
    };

    try {
        context = cl::Context(type, cps);
    } catch(std::exception e) {
        std::cout<<"Failed to create an OpenCL context!"<<std::endl;
    }

    std::string filename = arq;
    std::ifstream sourceFile(filename.c_str());
    if(sourceFile.fail())
        std::cout<<"Failed to open OpenCL source file"<<std::endl;

    std::string sourceCode(
                std::istreambuf_iterator<char>(sourceFile),
                (std::istreambuf_iterator<char>()));
    cl::Program::Sources source(1, std::make_pair(sourceCode.c_str(), sourceCode.length()+1));

    // Make program of the source code in the context
    cl::Program program = cl::Program(context, source);

    VECTOR_CLASS<cl::Device> devices = context.getInfo<CL_CONTEXT_DEVICES>();
    std::string deviceInfo;
    cl_ulong memInfo;
    size_t tam;
    cl_uint clUnit;
    int indexDev = 0;
    int maxU = 0;
    for (int i = 0; i < devices.size(); ++i)
    {
        devices[i].getInfo((cl_device_info) CL_DEVICE_NAME, &deviceInfo);
        std::cout << "Device info: " << deviceInfo << std::endl;
        devices[i].getInfo((cl_device_info) CL_DEVICE_VERSION, &deviceInfo);
        std::cout << "Versão CL: " << deviceInfo << std::endl;
        devices[i].getInfo((cl_device_info) CL_DRIVER_VERSION, &deviceInfo);
        std::cout << "Versão Driver: " << deviceInfo << std::endl;
        devices[i].getInfo((cl_device_info) CL_DEVICE_GLOBAL_MEM_SIZE, &memInfo);
        std::cout << "Memoria Global: " << memInfo << std::endl;
        devices[i].getInfo((cl_device_info) CL_DEVICE_LOCAL_MEM_SIZE, &memInfo);
        std::cout << "Memoria Local: " << memInfo << std::endl;
        devices[i].getInfo((cl_device_info) CL_DEVICE_LOCAL_MEM_SIZE, &tam);
        std::cout << "Max tamanho Work-group: " << tam << std::endl;
        devices[i].getInfo((cl_device_info) CL_DEVICE_MAX_WORK_ITEM_DIMENSIONS, &clUnit);
        std::cout << "Max dimensao: " << clUnit << std::endl;
        devices[i].getInfo((cl_device_info) CL_DEVICE_MAX_COMPUTE_UNITS, &clUnit);
        std::cout << "Unidades CL: " << clUnit << std::endl;
        std::cout << "*********************************" << std::endl;

        if((int)clUnit>maxU){
            indexDev = i;
            maxU = (int)clUnit;
        }
    }

    // Build program for these specific devices
    cl_int error = program.build(devices, buildOptions.c_str());
    if(error != 0) {
        std::cout << "Build log:" << std::endl << program.getBuildInfo<CL_PROGRAM_BUILD_LOG>(devices[0]) << std::endl;
    }

    std::cout << "Index Dispositino selecionado: " << indexDev << std::endl;
    queue = cl::CommandQueue(context, devices[indexDev]);

    int posi = 0;
    int posf = 0;
    for(int i = 0; i < n; i++){

        posf = nomeRot.find(",",posi);
        std::string nomeRoti;
        if(posf != -1){
            nomeRoti = nomeRot.substr(posi,posf-posi);
        }else{
            nomeRoti = nomeRot.substr(posi);
        }
        std::cout<<"Nome rotina["<<i<<"]: "<<nomeRoti.data()<<std::endl;
        rotina.push_back(cl::Kernel(program, nomeRoti.data()));
        posi = posf + 1;
    }
}
Example #28
0
/*++
* @method: Client::buildOAuthTokenKeyValuePairs
*
* @description: this method prepares key-value pairs required for OAuth header
*               and signature generation.
*
* @input: includeOAuthVerifierPin - flag to indicate whether oauth_verifer key-value
*                                   pair needs to be included. oauth_verifer is only
*                                   used during exchanging request token with access token.
*         rawData - url encoded data. this is used during signature generation.
*         oauthSignature - base64 and url encoded OAuth signature.
*         generateTimestamp - If true, then generate new timestamp for nonce.
*
* @input: urlEncodeValues - if true, URLEncode the values inserted into the
*         output keyValueMap
* @output: keyValueMap - map in which key-value pairs are populated
*
* @remarks: internal method
*
*--*/
bool Client::buildOAuthTokenKeyValuePairs( const bool includeOAuthVerifierPin,
                                          const std::string& rawData,
                                          const std::string& oauthSignature,
                                          KeyValuePairs& keyValueMap,
                                          const bool urlEncodeValues,
                                          const bool generateTimestamp )
{
    // Encodes value part of key-value pairs depending on type of output (query
    // string vs. HTTP headers.
    StringConvertFunction value_encoder = (urlEncodeValues ? HttpEncodeQueryValue : PassThrough);

    /* Generate nonce and timestamp if required */
    if( generateTimestamp )
    {
        generateNonceTimeStamp();
    }

    /* Consumer key and its value */
    ReplaceOrInsertKeyValuePair(keyValueMap, Defaults::CONSUMERKEY_KEY, value_encoder(mConsumer->key()));

    /* Nonce key and its value */
    ReplaceOrInsertKeyValuePair(keyValueMap, Defaults::NONCE_KEY, value_encoder(m_nonce));

    /* Signature if supplied */
    if( oauthSignature.length() )
    {
        // Signature is exempt from encoding. The procedure for
        // computing it already percent-encodes it as required by the
        // spec for both query string and Auth header
        // methods. Therefore, it's pass-through in both cases.
        ReplaceOrInsertKeyValuePair(keyValueMap, Defaults::SIGNATURE_KEY, oauthSignature);
    }

    /* Signature method, only HMAC-SHA1 as of now */
    ReplaceOrInsertKeyValuePair(keyValueMap, Defaults::SIGNATUREMETHOD_KEY, std::string( "HMAC-SHA1" ));

    /* Timestamp */
    ReplaceOrInsertKeyValuePair(keyValueMap, Defaults::TIMESTAMP_KEY, value_encoder(m_timeStamp));

    /* Token */
    if( mToken && mToken->key().length() )
    {
        ReplaceOrInsertKeyValuePair(keyValueMap, Defaults::TOKEN_KEY, value_encoder(mToken->key()));
    }

    /* Verifier */
    if( includeOAuthVerifierPin && mToken && mToken->pin().length() )
    {
        ReplaceOrInsertKeyValuePair(keyValueMap, Defaults::VERIFIER_KEY, value_encoder(mToken->pin()));
    }

    /* Version */
    ReplaceOrInsertKeyValuePair(keyValueMap, Defaults::VERSION_KEY, std::string( "1.0" ));

    /* Data if it's present */
    if( rawData.length() )
    {
        /* Data should already be urlencoded once */
        std::string dummyStrKey;
        std::string dummyStrValue;
        size_t nPos = rawData.find_first_of( "=" );
        if( std::string::npos != nPos )
        {
            dummyStrKey = rawData.substr( 0, nPos );
            dummyStrValue = rawData.substr( nPos + 1 );
            ReplaceOrInsertKeyValuePair(keyValueMap, dummyStrKey, dummyStrValue);
        }
    }

    return ( keyValueMap.size() ) ? true : false;
}
bool CNotificationKodi::SendMessageImplementation(const std::string &Subject, const std::string &Text, const std::string &ExtraData, const int Priority, const std::string &Sound, const bool bFromNotification)
{
	std::string	sSubject("Domoticz");
	if (Subject != Text)
	{
		sSubject = Subject;
	}
	else
	{
		size_t	posDevice = ExtraData.find("|Name=");
		if (posDevice != std::string::npos)
		{
			posDevice+=6;
			sSubject = ExtraData.substr(posDevice, ExtraData.find("|", posDevice)-posDevice);
		}
	}

	std::string	sIconFile = GetIconFile(ExtraData);

	// Loop through semi-colon separated IP Addresses
	std::vector<std::string> results;
	StringSplit(_IPAddress, ";", results);
	for (int i=0; i < (int)results.size(); i++)
	{
		std::stringstream logline;
		logline << "Kodi Notification (" << results[i] << ":" << _Port << ", TTL " << _TTL << "): " << sSubject << ", " << Text << ", Icon " << sIconFile;
		_log.Log(LOG_NORM, "%s", logline.str().c_str());

		CAddress	_Address;
		int			_Sock;
		bool		bMulticast = (results[i].substr(0,4) >= "224.") && (results[i].substr(0,4) <= "239.");

		CAddress my_addr(results[i].c_str(), _Port);
		_Address = my_addr;
		_Sock = -1;
		if (bMulticast) {
			_Sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
			setsockopt(_Sock, IPPROTO_IP, IP_MULTICAST_TTL, (const char*)&_TTL, sizeof(_TTL));
			u_char loop = 1;
			setsockopt(_Sock, IPPROTO_IP, IP_MULTICAST_LOOP, (const char*) &loop, sizeof(loop));
		}
		else {
			_Sock = socket(AF_INET, SOCK_DGRAM, 0);
		}
		
		if (_Sock < 0)
		{
			logline << "Error creating socket: " << results[i] << ":" << _Port;
			_log.Log(LOG_ERROR, "%s", logline.str().c_str());
			return false;
		}

		_Address.Bind(_Sock);

		CPacketNOTIFICATION packet(sSubject.c_str(), Text.c_str(), ICON_PNG, (!sIconFile.empty())?sIconFile.c_str():NULL);
		if (!packet.Send(_Sock, _Address)) {
			std::stringstream logline;
			logline << "Error sending notification: " << results[i] << ":" << _Port;
			_log.Log(LOG_ERROR, "%s", logline.str().c_str());
			return false;
		}
	}
	return true;
}
Example #30
0
/*++
* @method: Client::buildOAuthTokenKeyValuePairs
*
* @description: this method prepares key-value pairs required for OAuth header
*               and signature generation.
*
* @input: includeOAuthVerifierPin - flag to indicate whether oauth_verifer key-value
*                                   pair needs to be included. oauth_verifer is only
*                                   used during exchanging request token with access token.
*         rawData - url encoded data. this is used during signature generation.
*         oauthSignature - base64 and url encoded OAuth signature.
*         generateTimestamp - If true, then generate new timestamp for nonce.
*
* @input: urlEncodeValues - if true, URLEncode the values inserted into the
*         output keyValueMap
* @output: keyValueMap - map in which key-value pairs are populated
*
* @remarks: internal method
*
*--*/
bool Client::buildOAuthTokenKeyValuePairs( const bool includeOAuthVerifierPin,
                                          const std::string& rawData,
                                          const std::string& oauthSignature,
                                          KeyValuePairs& keyValueMap,
                                          const bool urlEncodeValues,
                                          const bool generateTimestamp )
{
    StringConvertFunction encoder = (urlEncodeValues ? URLEncode : PassThrough);

    /* Generate nonce and timestamp if required */
    if( generateTimestamp )
    {
        generateNonceTimeStamp();
    }

    /* Consumer key and its value */
    keyValueMap[Defaults::CONSUMERKEY_KEY] = encoder(mConsumer->key());

    /* Nonce key and its value */
    keyValueMap[Defaults::NONCE_KEY] = encoder(m_nonce);

    /* Signature if supplied */
    if( oauthSignature.length() )
    {
        keyValueMap[Defaults::SIGNATURE_KEY] = encoder(oauthSignature);
    }

    /* Signature method, only HMAC-SHA1 as of now */
    keyValueMap[Defaults::SIGNATUREMETHOD_KEY] = std::string( "HMAC-SHA1" );

    /* Timestamp */
    keyValueMap[Defaults::TIMESTAMP_KEY] = encoder(m_timeStamp);

    /* Token */
    if( mToken && mToken->key().length() )
    {
        keyValueMap[Defaults::TOKEN_KEY] = encoder(mToken->key());
    }

    /* Verifier */
    if( includeOAuthVerifierPin && mToken && mToken->pin().length() )
    {
        keyValueMap[Defaults::VERIFIER_KEY] = encoder(mToken->pin());
    }

    /* Version */
    keyValueMap[Defaults::VERSION_KEY] = std::string( "1.0" );

    /* Data if it's present */
    if( rawData.length() )
    {
        /* Data should already be urlencoded once */
        std::string dummyStrKey;
        std::string dummyStrValue;
        size_t nPos = rawData.find_first_of( "=" );
        if( std::string::npos != nPos )
        {
            dummyStrKey = rawData.substr( 0, nPos );
            dummyStrValue = rawData.substr( nPos + 1 );
            keyValueMap[dummyStrKey] = dummyStrValue;
        }
    }

    return ( keyValueMap.size() ) ? true : false;
}