コード例 #1
0
ファイル: tools.cpp プロジェクト: 081421/otxserver
bool parseIntegerVec(std::string str, IntegerVec& intVector)
{
	StringVec strVector = explodeString(str, ";");
	IntegerVec tmpIntVector;
	for(StringVec::iterator it = strVector.begin(); it != strVector.end(); ++it)
	{
		tmpIntVector = vectorAtoi(explodeString((*it), "-"));
		if(!tmpIntVector[0] && it->substr(0, 1) != "0")
			continue;

		intVector.push_back(tmpIntVector[0]);
		if(tmpIntVector.size() > 1)
		{
			while(tmpIntVector[0] < tmpIntVector[1])
				intVector.push_back(++tmpIntVector[0]);
		}
	}

	return true;
}
コード例 #2
0
ファイル: StringUtils.cpp プロジェクト: legersun/Novus-Engine
//---------------------------------------------------------------------------------------------------------------------
// This is basically like the Perl split() function.  It splits str into substrings by cutting it at each delimiter.  
// The result is stored in vec.
//---------------------------------------------------------------------------------------------------------------------
void Split(const string& str, StringVec& vec, char delimiter)
{
	vec.clear();
	size_t strLen = str.size();
	if (strLen == 0)
		return;

	size_t startIndex = 0;
	size_t indexOfDel = str.find_first_of(delimiter, startIndex);
	while (indexOfDel != string::npos)
	{
		vec.push_back(str.substr(startIndex, indexOfDel - startIndex));
		startIndex = indexOfDel + 1;
		if (startIndex >= strLen)
			break;
		indexOfDel = str.find_first_of(delimiter, startIndex);
	}
	if (startIndex < strLen)
		vec.push_back(str.substr(startIndex));
}
コード例 #3
0
ファイル: BuildSettingsInfo.cpp プロジェクト: bbowman/WinObjC
static String expandRecursivePath(const String& path, const String& prefix, const VariableCollectionHierarchy& vch) {
    // Check if recursive expansion is necessary
    if (!strEndsWith(path, "/**"))
        return addPrefixQuoted(path, prefix, vch);

    // Remove the pesky /** ending
    String fixedPath = path.substr(0, path.length() - 3);

    // Expand the path and get an absolute project path
    String expandedPath = vch.expand(fixedPath);
    String projectPath = vch.getValue("PROJECT_DIR");

    // Make an absolute path
    String absPath = joinPaths(projectPath, expandedPath);

    // Get a list of subdirectories to ignore
    StringVec ignoreList;
    vch.getValue("EXCLUDED_RECURSIVE_SEARCH_PATH_SUBDIRECTORIES", ignoreList);

    // Get recursive paths
    StringVec dirVec;
    getRecursiveDirList(absPath, dirVec, ignoreList);

    // Sort the paths such that they are in breadth-first, alphabetic order
    std::sort(dirVec.begin(), dirVec.end(), compare_nocase_breadth_first);

    // Substitute back the original form of the path (which likely contains variables)
    String ret;
    for (unsigned i = 0; i < dirVec.size(); i++) {
        dirVec[i].replace(0, absPath.length(), fixedPath);
        ret += addPrefixQuoted(dirVec[i], prefix, vch);
    }

    // Check that the recursive expansion succeeded
    if (dirVec.empty()) {
        SBLog::info() << "Failed recursive expansion of \"" << absPath << "\". Path does not exist." << std::endl;
        return "";
    } else {
        return ret;
    }
}
コード例 #4
0
ファイル: suggest.cpp プロジェクト: unhammer/divvun-suggest
const std::tuple<bool, std::string, StringVec> proc_tags(const std::string& tags) {
	bool suggest = false;
	std::string errtype;
	StringVec gentags;
	for(auto& tag : split(tags)) {
		std::match_results<const char*> result;
		std::regex_match(tag.c_str(), result, CG_SKIP_TAG);
		if (result.empty()) {
			gentags.push_back(tag);
		}
		else if(result[2].length() != 0) {
			if(tag == CG_SUGGEST_TAG) {
				suggest = true;
			}
			else {
				errtype = result[2];
			}
		}
	}
	return std::make_tuple(suggest, errtype, gentags);
}
コード例 #5
0
ファイル: ParameterNBest.cpp プロジェクト: awildfox/moses
/** check whether a file exists */
bool ParameterNBest::FilesExist(const string &paramName, size_t tokenizeIndex,std::vector<std::string> const& extensions)
{
	typedef std::vector<std::string> StringVec;
	StringVec::const_iterator iter;

	PARAM_MAP::const_iterator iterParam = m_setting.find(paramName);
	if (iterParam == m_setting.end())
	{ // no param. therefore nothing to check
		return true;
	}
	const StringVec &pathVec = (*iterParam).second;
	for (iter = pathVec.begin() ; iter != pathVec.end() ; ++iter)
	{
		StringVec vec = Tokenize(*iter);
		if (tokenizeIndex >= vec.size())
		{
			stringstream errorMsg("");
			errorMsg << "Expected at least " << (tokenizeIndex+1) << " tokens per emtry in '"
							<< paramName << "', but only found "
							<< vec.size();
			UserMessage::Add(errorMsg.str());
			return false;
		}
		const string &pathStr = vec[tokenizeIndex];

		bool fileFound=0;
		for(size_t i=0;i<extensions.size() && !fileFound;++i)
			{
				fileFound|=FileExists(pathStr + extensions[i]);
			}
		if(!fileFound)
			{
				stringstream errorMsg("");
				errorMsg << "File " << pathStr << " does not exist";
				UserMessage::Add(errorMsg.str());
				return false;
			}		
	}
	return true;
}
コード例 #6
0
ファイル: tools.cpp プロジェクト: AhmedWaly/CastOnly
std::string parseVocationString(StringVec vocStringVec)
{
	std::string str = "";
	if(!vocStringVec.empty())
	{
		for(StringVec::iterator it = vocStringVec.begin(); it != vocStringVec.end(); ++it)
		{
			if((*it) != vocStringVec.front())
			{
				if((*it) != vocStringVec.back())
					str += ", ";
				else
					str += " and ";
			}

			str += (*it);
			str += "s";
		}
	}

	return str;
}
コード例 #7
0
ファイル: tools.cpp プロジェクト: 081421/otxserver
StringVec explodeString(const std::string& string, const std::string& separator, bool trim/* = true*/, uint16_t limit/* = 0*/)
{
	StringVec returnVector;
	size_t start = 0, end = 0;

	uint16_t i = 1;
	while((end = string.find(separator, start)) != std::string::npos)
	{
		std::string t = string.substr(start, end - start);
		if(trim)
			trimString(t);

		returnVector.push_back(t);
		start = end + separator.size();

		++i;
		if(limit > 0 && i > limit)
			break;
	}

	returnVector.push_back(string.substr(start));
	return returnVector;
}
コード例 #8
0
ファイル: spectators.cpp プロジェクト: Azuen/RealOTX-7.72
void Spectators::ban(StringVec _bans)
{
	StringVec::const_iterator it;
	for(DataList::iterator bit = bans.begin(); bit != bans.end(); )
	{
		it = std::find(_bans.begin(), _bans.end(), bit->first);
		if(it == _bans.end())
			bans.erase(bit++);
		else
			++bit;
	}

	for(it = _bans.begin(); it != _bans.end(); ++it)
	{
		for(SpectatorList::const_iterator sit = spectators.begin(); sit != spectators.end(); ++sit)
		{
			if(asLowerCaseString(sit->second.first) != *it)
				continue;

			bans[*it] = sit->first->getIP();
			sit->first->disconnect();
		}
	}
}
コード例 #9
0
ファイル: clangoptparser.cpp プロジェクト: bbowman/WinObjC
// "Expand" -Wl and -Xlinker tokens
// This is OK to do since we're interested in a small subset of flags.
// Preserving correctness is not important.
static void replaceWlArgs(const StringVec& inArgs, StringVec& outArgs) {
    for (auto arg : inArgs) {
        if (strBeginsWith(arg, "-Wl,")) {
            StringVec tokens;
            tokenize(arg, tokens, ",", "", "", "", "");
            outArgs.insert(outArgs.end(), tokens.begin() + 1, tokens.end());
        } else if (arg != "-Xlinker") {
            outArgs.push_back(arg);
        }
    }
}
コード例 #10
0
ファイル: MountInfo.cpp プロジェクト: max-silent/easytc
MountInfoVec getMountInfo()
{
    int exitCode;
    
    StringVec tcOutput = splitToLines(executeCommand("truecrypt", "-l", exitCode));

    if(exitCode != 0)
    {
        if(tcOutput.size() > 0)
        {
            throw std::runtime_error(tcOutput[0]);
        }
        else
        {
            throw std::runtime_error("unknown error while querying mounted images");
        }
    }
    
    StringVec mntOutput = splitToLines(executeCommand("mount", exitCode));
    MountInfoVec info;
    
    for(StringVec::const_iterator tcIt = tcOutput.begin(); tcIt != tcOutput.end(); ++tcIt)
    {
        StringVec tcWords = splitToWords(*tcIt);
        
        std::string device = tcWords[0];
        std::string image = tcWords[1];
        
        for(StringVec::const_iterator mntIt = mntOutput.begin(); mntIt != mntOutput.end(); ++mntIt) 
        {
            StringVec mntWords = splitToWords(*mntIt);
            
            std::string mntDev = mntWords[0];
            std::string mntPoint = mntWords[2];
            
            if(mntDev == device)
            {
                info.push_back(MountInfo(image, mntPoint));
                break;
            }
        }
    }

    return info;
}
コード例 #11
0
ファイル: stepA_mal.cpp プロジェクト: 1989tianlong/mal
malValuePtr EVAL(malValuePtr ast, malEnvPtr env)
{
    if (!env) {
        env = replEnv;
    }
    while (1) {
        const malList* list = DYNAMIC_CAST(malList, ast);
        if (!list || (list->count() == 0)) {
            return ast->eval(env);
        }

        ast = macroExpand(ast, env);
        list = DYNAMIC_CAST(malList, ast);
        if (!list || (list->count() == 0)) {
            return ast->eval(env);
        }

        // From here on down we are evaluating a non-empty list.
        // First handle the special forms.
        if (const malSymbol* symbol = DYNAMIC_CAST(malSymbol, list->item(0))) {
            String special = symbol->value();
            int argCount = list->count() - 1;

            if (special == "def!") {
                checkArgsIs("def!", 2, argCount);
                const malSymbol* id = VALUE_CAST(malSymbol, list->item(1));
                return env->set(id->value(), EVAL(list->item(2), env));
            }

            if (special == "defmacro!") {
                checkArgsIs("defmacro!", 2, argCount);

                const malSymbol* id = VALUE_CAST(malSymbol, list->item(1));
                malValuePtr body = EVAL(list->item(2), env);
                const malLambda* lambda = VALUE_CAST(malLambda, body);
                return env->set(id->value(), mal::macro(*lambda));
            }

            if (special == "do") {
                checkArgsAtLeast("do", 1, argCount);

                for (int i = 1; i < argCount; i++) {
                    EVAL(list->item(i), env);
                }
                ast = list->item(argCount);
                continue; // TCO
            }

            if (special == "fn*") {
                checkArgsIs("fn*", 2, argCount);

                const malSequence* bindings =
                    VALUE_CAST(malSequence, list->item(1));
                StringVec params;
                for (int i = 0; i < bindings->count(); i++) {
                    const malSymbol* sym =
                        VALUE_CAST(malSymbol, bindings->item(i));
                    params.push_back(sym->value());
                }

                return mal::lambda(params, list->item(2), env);
            }

            if (special == "if") {
                checkArgsBetween("if", 2, 3, argCount);

                bool isTrue = EVAL(list->item(1), env)->isTrue();
                if (!isTrue && (argCount == 2)) {
                    return mal::nilValue();
                }
                ast = list->item(isTrue ? 2 : 3);
                continue; // TCO
            }

            if (special == "let*") {
                checkArgsIs("let*", 2, argCount);
                const malSequence* bindings =
                    VALUE_CAST(malSequence, list->item(1));
                int count = checkArgsEven("let*", bindings->count());
                malEnvPtr inner(new malEnv(env));
                for (int i = 0; i < count; i += 2) {
                    const malSymbol* var =
                        VALUE_CAST(malSymbol, bindings->item(i));
                    inner->set(var->value(), EVAL(bindings->item(i+1), inner));
                }
                ast = list->item(2);
                env = inner;
                continue; // TCO
            }

            if (special == "macroexpand") {
                checkArgsIs("macroexpand", 1, argCount);
                return macroExpand(list->item(1), env);
            }

            if (special == "quasiquote") {
                checkArgsIs("quasiquote", 1, argCount);
                ast = quasiquote(list->item(1));
                continue; // TCO
            }

            if (special == "quote") {
                checkArgsIs("quote", 1, argCount);
                return list->item(1);
            }

            if (special == "try*") {
                checkArgsIs("try*", 2, argCount);
                malValuePtr tryBody = list->item(1);
                const malList* catchBlock = VALUE_CAST(malList, list->item(2));

                checkArgsIs("catch*", 2, catchBlock->count() - 1);
                MAL_CHECK(VALUE_CAST(malSymbol,
                    catchBlock->item(0))->value() == "catch*",
                    "catch block must begin with catch*");

                // We don't need excSym at this scope, but we want to check
                // that the catch block is valid always, not just in case of
                // an exception.
                const malSymbol* excSym =
                    VALUE_CAST(malSymbol, catchBlock->item(1));

                malValuePtr excVal;

                try {
                    ast = EVAL(tryBody, env);
                }
                catch(String& s) {
                    excVal = mal::string(s);
                }
                catch (malEmptyInputException&) {
                    // Not an error, continue as if we got nil
                    ast = mal::nilValue();
                }
                catch(malValuePtr& o) {
                    excVal = o;
                };

                if (excVal) {
                    // we got some exception
                    env = malEnvPtr(new malEnv(env));
                    env->set(excSym->value(), excVal);
                    ast = catchBlock->item(2);
                }
                continue; // TCO
            }
        }

        // Now we're left with the case of a regular list to be evaluated.
        std::unique_ptr<malValueVec> items(list->evalItems(env));
        malValuePtr op = items->at(0);
        if (const malLambda* lambda = DYNAMIC_CAST(malLambda, op)) {
            ast = lambda->getBody();
            env = lambda->makeEnv(items->begin()+1, items->end());
            continue; // TCO
        }
        else {
            return APPLY(op, items->begin()+1, items->end());
        }
    }
}
コード例 #12
0
void SBSourcesBuildPhase::writeVCProjectFiles(VCProject& proj) const
{
  // We don't support source compilation when building bundles
  TargetProductType productType = m_parentTarget.getProductType();
  if (productType == TargetBundle)
  {
    if (!m_phase->getBuildFileList().empty()) {
      SBLog::warning() << "Ignoring all source files in \"" << m_parentTarget.getName() << "\" bundle target." << std::endl;
    }
    return;
  }

  SBBuildPhase::writeVSFileDescriptions(proj, "Text");

  String xcProjectDir = m_parentTarget.getProject().getProjectDir();
  String vsProjectDir = sb_dirname(proj.getPath());
  StringSet prefixHeaders;
  for (auto bs : m_parentTarget.getBuildSettings()) {
    VCProjectConfiguration* config = proj.addConfiguration(bs.first);

    // Prefix header (recalculate relative path)
    String prefixHeader = bs.second->getValue("GCC_PREFIX_HEADER");
    if (!prefixHeader.empty()) {
      String absHeaderPath = m_parentTarget.makeAbsolutePath(prefixHeader);
      String relHeaderPath = m_parentTarget.makeRelativePath(prefixHeader, vsProjectDir);;
      relHeaderPath = winPath(relHeaderPath);
      config->setItemDefinition("ClangCompile", "PrefixHeader", relHeaderPath);

      // Add plist file to project (only once)
      if (prefixHeaders.find(absHeaderPath) == prefixHeaders.end()) {
        addRelativeFilePathToVS("ClInclude", absHeaderPath, "", proj, *bs.second);
        prefixHeaders.insert(absHeaderPath);
      }
    }

    // Preprocessor definitions
    StringVec preprocessorTokens;
    bs.second->getValue("GCC_PREPROCESSOR_DEFINITIONS", preprocessorTokens);
    String preprocessorDefs = joinStrings(preprocessorTokens, ";");
    if (!preprocessorDefs.empty()) {
      config->setItemDefinition("ClangCompile", "PreprocessorDefinitions", preprocessorDefs);
    }

    // Optimization level
    String optimizationLevel = bs.second->getValue("GCC_OPTIMIZATION_LEVEL");
    if (!optimizationLevel.empty()) {
      String vsOptimizationLevel;
      if (optimizationLevel == "s") {
        vsOptimizationLevel = "MinSpace";
      } else if (optimizationLevel == "0") {
        vsOptimizationLevel = "Disabled";
      } else {
        vsOptimizationLevel = "MaxSpeed";
      }
      config->setItemDefinition("ClangCompile", "OptimizationLevel", vsOptimizationLevel);
    }

    // ARC
    String enableARC = bs.second->getValue("CLANG_ENABLE_OBJC_ARC");
    if (enableARC == "YES") {
      config->setItemDefinition("ClangCompile", "ObjectiveCARC", "true");
    }

    // Modules
    String enableModules = bs.second->getValue("CLANG_ENABLE_MODULES");
    if (enableModules == "YES") {
        config->setItemDefinition("ClangCompile", "ObjectiveCModules", "true");
    }

    // Header search paths (make them relative)
    StringVec includePaths;
    bs.second->getValue("HEADER_SEARCH_PATHS", includePaths);
    for (auto &cur : includePaths) {
      cur = m_parentTarget.makeRelativePath(cur, vsProjectDir);
      cur = winPath(cur);
    }
    includePaths.insert(includePaths.begin(), "$(SolutionPublicHeadersDir)");
    config->setItemDefinition("ClangCompile", "IncludePaths", joinStrings(includePaths, ";"));

    // User header search paths (make them relative)
    StringVec userIncludePaths;
    bs.second->getValue("USER_HEADER_SEARCH_PATHS", userIncludePaths);
    for (auto &cur : userIncludePaths) {
      cur = m_parentTarget.makeRelativePath(cur, vsProjectDir);
      cur = winPath(cur);
    }
    if (!userIncludePaths.empty()) {
      config->setItemDefinition("ClangCompile", "UserIncludePaths", joinStrings(userIncludePaths, ";"));
    }

    // Exclude search path subdirectories
    StringVec excludeSubDirectories;
    bs.second->getValue("EXCLUDED_RECURSIVE_SEARCH_PATH_SUBDIRECTORIES", excludeSubDirectories);
    if (!excludeSubDirectories.empty()) {
        config->setItemDefinition("ClangCompile", "ExcludedSearchPathSubdirectories", joinStrings(excludeSubDirectories, ";"));
    }

    // Header map
    if (bs.second->getValue("USE_HEADERMAP") == "YES") {
      if (bs.second->getValue("ALWAYS_SEARCH_USER_PATHS") == "YES") {
        config->setItemDefinition("ClangCompile", "HeaderMap", "Combined");
      } else if (bs.second->getValue("HEADERMAP_INCLUDES_PROJECT_HEADERS") == "YES") {
        config->setItemDefinition("ClangCompile", "HeaderMap", "Project");
      }
    }

    // Other C flags
    String otherCFlags = bs.second->getValue("OTHER_CFLAGS");
    processClangFlags(otherCFlags, xcProjectDir, vsProjectDir);
    if (!otherCFlags.empty()) {
      config->setItemDefinition("ClangCompile", "OtherCFlags", otherCFlags);
    }

    // Other C++ flags
    String otherCPlusPlusFlags = bs.second->getValue("OTHER_CPLUSPLUSFLAGS");
    processClangFlags(otherCPlusPlusFlags, xcProjectDir, vsProjectDir);
    if (!otherCPlusPlusFlags.empty()) {
      config->setItemDefinition("ClangCompile", "OtherCPlusPlusFlags", otherCPlusPlusFlags);
    }

    // CRT
    String configNameUpper = strToUpper(bs.first);
    if (configNameUpper.find("DEBUG") != String::npos) {
      config->setItemDefinition("ClangCompile", "RuntimeLibrary", "MultiThreadedDebugDLL");
    }
  }
}
コード例 #13
0
ファイル: ext_debugger.cpp プロジェクト: Sydney-o9/hiphop-php
Variant c_DebuggerClient::t_processcmd(CVarRef cmdName, CVarRef args) {
  INSTANCE_METHOD_INJECTION_BUILTIN(DebuggerClient, DebuggerClient::processcmd);
  if (!m_client ||
      m_client->getClientState() < DebuggerClient::StateReadyForCommand) {
    raise_warning("client is not initialized");
    return null;
  }
  if (m_client->getClientState() != DebuggerClient::StateReadyForCommand) {
    raise_warning("client is not ready to take command");
    return null;
  }
  if (!cmdName.isString()) {
    raise_warning("cmdName must be string");
    return null;
  }
  if (!args.isNull() && !args.isArray()) {
    raise_warning("args must be null or array");
    return null;
  }

  static const char *s_allowedCmds[] = {
    "break", "continue", "down", "exception", "frame", "global",
    "help", "info", "konstant", "next", "out", "print", "quit", "step",
    "up", "variable", "where", "bt", "set", "inst", "=", "@", NULL
  };

  bool allowed = false;
  for (int i = 0; ; i++) {
    const char *cmd = s_allowedCmds[i];
    if (cmd == NULL) {
      break;
    }
    if (cmdName.same(cmd)) {
      allowed = true;
      break;
    }
  }
  if (!allowed) {
    raise_warning("unsupported command %s", cmdName.toString().data());
    return null;
  }

  m_client->setCommand(cmdName.toString().data());
  StringVec *clientArgs = m_client->args();
  clientArgs->clear();
  if (!args.isNull()) {
    for (ArrayIter iter(args.toArray()); iter; ++iter) {
      CStrRef arg = iter.second().toString();
      clientArgs->push_back(std::string(arg.data(), arg.size()));
    }
  }
  try {
    if (!m_client->process()) {
      raise_warning("command \"%s\" not found", cmdName.toString().data());
    }
  } catch (DebuggerConsoleExitException &e) {
    // Flow-control command goes here
    Logger::Info("wait for debugger client to stop");
    m_client->setTakingInterrupt();
    m_client->setClientState(DebuggerClient::StateBusy);
    DebuggerCommandPtr cmd = m_client->waitForNextInterrupt();
    if (!cmd) {
      raise_warning("not getting a command");
    } else if (cmd->is(DebuggerCommand::KindOfInterrupt)) {
      CmdInterruptPtr cmdInterrupt = dynamic_pointer_cast<CmdInterrupt>(cmd);
      cmdInterrupt->onClientD(m_client);
    } else {
      // Previous pending commands
      cmd->handleReply(m_client);
      cmd->setClientOutput(m_client);
    }
    Logger::Info("debugger client ready for command");
  } catch (DebuggerClientExitException &e) {
    const std::string& nameStr = m_client->getNameApi();
    Logger::Info("client %s disconnected", nameStr.c_str());
    s_dbgCltMap.erase(nameStr);
    delete m_client;
    m_client = NULL;
    return true;
  } catch (DebuggerProtocolException &e) {
    raise_warning("DebuggerProtocolException");
    return null;
  }

  return m_client->getOutputArray();
}
コード例 #14
0
ファイル: tools.cpp プロジェクト: AhmedWaly/CastOnly
bool parseVocationNode(xmlNodePtr vocationNode, VocationMap& vocationMap, StringVec& vocStringVec, std::string& errorStr)
{
	if(xmlStrcmp(vocationNode->name,(const xmlChar*)"vocation"))
		return true;

	int32_t vocationId = -1;
	std::string strValue, tmpStrValue;
	if(readXMLString(vocationNode, "name", strValue))
	{
		vocationId = Vocations::getInstance()->getVocationId(strValue);
		if(vocationId != -1)
		{
			vocationMap[vocationId] = true;
			int32_t promotedVocation = Vocations::getInstance()->getPromotedVocation(vocationId);
			if(promotedVocation != -1)
				vocationMap[promotedVocation] = true;
		}
		else
		{
			errorStr = "Wrong vocation name: " + strValue;
			return false;
		}
	}
	else if(readXMLString(vocationNode, "id", strValue))
	{
		IntegerVec intVector;
		if(!parseIntegerVec(strValue, intVector))
		{
			errorStr = "Invalid vocation id - '" + strValue + "'";
			return false;
		}

		size_t size = intVector.size();
		for(size_t i = 0; i < size; ++i)
		{
			Vocation* vocation = Vocations::getInstance()->getVocation(intVector[i]);
			if(vocation && vocation->getName() != "")
			{
				vocationId = vocation->getId();
				strValue = vocation->getName();

				vocationMap[vocationId] = true;
				int32_t promotedVocation = Vocations::getInstance()->getPromotedVocation(vocationId);
				if(promotedVocation != -1)
					vocationMap[promotedVocation] = true;
			}
			else
			{
				std::stringstream ss;
				ss << "Wrong vocation id: " << intVector[i];

				errorStr = ss.str();
				return false;
			}
		}
	}

	if(vocationId != -1 && (!readXMLString(vocationNode, "showInDescription", tmpStrValue) || booleanString(tmpStrValue)))
		vocStringVec.push_back(asLowerCaseString(strValue));

	return true;
}
コード例 #15
0
ファイル: MacAddrSuite.cpp プロジェクト: thanhtphung/cppware
void MacAddrSuite::testVec00()
{
    bool ok = true;
    MacAddr macAddr;
    MacAddrVec vec0;
    String mac;
    StringVec macs;
    for (unsigned int i = 0; i < NUM_SAMPLES; ++i)
    {
        const sample_t& r = SAMPLE[i];
        if (r.isValid)
        {
            macAddr = r.addr;
            unsigned int foundAt = vec0.numItems();
            if ((!vec0.add(macAddr)) || (vec0.findIndex(macAddr) != foundAt))
            {
                ok = false;
                break;
            }
            mac = macAddr;
            macs.add(mac);
        }
    }
    CPPUNIT_ASSERT(ok);

    MacAddrVec vec1(vec0);
    ok = (vec1 == vec0);
    CPPUNIT_ASSERT(ok);
    vec1.reset();
    ok = (vec1 != vec0) && (vec1.numItems() == 0);
    CPPUNIT_ASSERT(ok);

    ok = vec1.reset(macs) && (vec1 == vec0);
    CPPUNIT_ASSERT(ok);
    mac = "not-a-mac";
    macs.add(mac);
    ok = (!vec1.reset(macs)) && (vec1 == vec0);
    CPPUNIT_ASSERT(ok);

    bool reverseOrder = false;
    vec0.sort(reverseOrder);
    ok = vec1.find(vec0.peek(0));
    CPPUNIT_ASSERT(ok);
    for (size_t i = 1, numItems = vec0.numItems(); i < numItems; ++i)
    {
        if ((!vec1.find(vec0.peek(i))) || (vec0.peek(i - 1) > vec0.peek(i)))
        {
            ok = false;
            break;
        }
    }
    CPPUNIT_ASSERT(ok);

    reverseOrder = true;
    vec0.sort(reverseOrder);
    ok = vec1.find(vec0.peek(0));
    CPPUNIT_ASSERT(ok);
    for (size_t i = 1, numItems = vec0.numItems(); i < numItems; ++i)
    {
        if ((!vec1.find(vec0.peek(i))) || (vec0.peek(i - 1) < vec0.peek(i)))
        {
            ok = false;
            break;
        }
    }
    CPPUNIT_ASSERT(ok);
}
void SBFrameworksBuildPhase::writeVCProjectFiles(VCProject& proj) const
{
  // We don't support linking with frameworks when building bundles
  TargetProductType productType = m_parentTarget.getProductType();
  if (productType == TargetBundle) {
    if (!m_phase->getBuildFileList().empty()) {
      SBLog::warning() << "Ignoring all frameworkss in \"" << m_parentTarget.getName() << "\" bundle target." << std::endl;
    }
    return;
  }

  String linkTarget;
  if (productType == TargetApplication)
    linkTarget = "Link";
  else if (productType == TargetStaticLib)
    linkTarget = "Lib";

  // Get paths to all the build files (frameworks)
  StringVec buildFilePaths;
  if (m_phase) {
    const BuildFileList& buildFiles = m_phase->getBuildFileList();
    sbAssert(buildFiles.size() == m_buildFileTargets.size());
    for (size_t i = 0; i < buildFiles.size(); i++) {
      const PBXFile* file = buildFiles[i]->getFile();
      // Ignore any frameworks build from source (they will be added as project references)
      if (file && !m_buildFileTargets[i])
        buildFilePaths.push_back(file->getFullPath());
    }
  }

  for (auto bs : m_parentTarget.getBuildSettings()) {
    VCProjectConfiguration* config = proj.addConfiguration(bs.first);

    // Extrace libs/frameworks from OTHER_LDFLAGS
    StringVec buildFilePaths(buildFilePaths);
    processLDFlags(bs.second->getValue("OTHER_LDFLAGS"), buildFilePaths);

    // Construct a list of libraries to link against
    StringSet linkedLibs;
    linkedLibs.insert("%(AdditionalDependencies)");
    for (auto filePath : buildFilePaths) {
      if (productType == TargetStaticLib && !strEndsWith(filePath, ".a"))
        continue;

      String winLibName = sb_fname(sb_basename(filePath)) + ".lib";

      // If the library is blocked then add the replacement library to our additional dependencies 
      auto it = s_blockedLibraries.find(winLibName);
      while (it != s_blockedLibraries.end())
      {
          // get the replacement library.
          winLibName = it->second;

          // follow any transitive replacement.
          it = s_blockedLibraries.find(winLibName);
      }

      if (!winLibName.empty())
      {
          linkedLibs.insert(winLibName);
      }
    }

    // AdditionalDependencies
    String additionalDeps = joinStrings(linkedLibs, ";");
    if (!additionalDeps.empty()) {
      config->setItemDefinition(linkTarget, "AdditionalDependencies", additionalDeps);
    }
  }
}
コード例 #17
0
ファイル: step7_quote.cpp プロジェクト: BlinkD/mal
malValuePtr EVAL(malValuePtr ast, malEnvPtr env)
{
    while (1) {
        const malList* list = DYNAMIC_CAST(malList, ast);
        if (!list || (list->count() == 0)) {
            return ast->eval(env);
        }

        // From here on down we are evaluating a non-empty list.
        // First handle the special forms.
        if (const malSymbol* symbol = DYNAMIC_CAST(malSymbol, list->item(0))) {
            String special = symbol->value();
            int argCount = list->count() - 1;

            if (special == "def!") {
                checkArgsIs("def!", 2, argCount);
                const malSymbol* id = VALUE_CAST(malSymbol, list->item(1));
                return env->set(id->value(), EVAL(list->item(2), env));
            }

            if (special == "do") {
                checkArgsAtLeast("do", 1, argCount);

                for (int i = 1; i < argCount; i++) {
                    EVAL(list->item(i), env);
                }
                ast = list->item(argCount);
                continue; // TCO
            }

            if (special == "fn*") {
                checkArgsIs("fn*", 2, argCount);

                const malSequence* bindings =
                    VALUE_CAST(malSequence, list->item(1));
                StringVec params;
                for (int i = 0; i < bindings->count(); i++) {
                    const malSymbol* sym =
                        VALUE_CAST(malSymbol, bindings->item(i));
                    params.push_back(sym->value());
                }

                return mal::lambda(params, list->item(2), env);
            }

            if (special == "if") {
                checkArgsBetween("if", 2, 3, argCount);

                bool isTrue = EVAL(list->item(1), env)->isTrue();
                if (!isTrue && (argCount == 2)) {
                    return mal::nilValue();
                }
                ast = list->item(isTrue ? 2 : 3);
                continue; // TCO
            }

            if (special == "let*") {
                checkArgsIs("let*", 2, argCount);
                const malSequence* bindings =
                    VALUE_CAST(malSequence, list->item(1));
                int count = checkArgsEven("let*", bindings->count());
                malEnvPtr inner(new malEnv(env));
                for (int i = 0; i < count; i += 2) {
                    const malSymbol* var =
                        VALUE_CAST(malSymbol, bindings->item(i));
                    inner->set(var->value(), EVAL(bindings->item(i+1), inner));
                }
                ast = list->item(2);
                env = inner;
                continue; // TCO
            }

            if (special == "quasiquote") {
                checkArgsIs("quasiquote", 1, argCount);
                ast = quasiquote(list->item(1));
                continue; // TCO
            }

            if (special == "quote") {
                checkArgsIs("quote", 1, argCount);
                return list->item(1);
            }
        }

        // Now we're left with the case of a regular list to be evaluated.
        std::unique_ptr<malValueVec> items(list->evalItems(env));
        malValuePtr op = items->at(0);
        if (const malLambda* lambda = DYNAMIC_CAST(malLambda, op)) {
            ast = lambda->getBody();
            env = lambda->makeEnv(items->begin()+1, items->end());
            continue; // TCO
        }
        else {
            return APPLY(op, items->begin()+1, items->end(), env);
        }
    }
}
コード例 #18
0
ファイル: otserv.cpp プロジェクト: novasdream/OpenTibia-EPVP
bool argumentsHandler(StringVec args)
{
	StringVec tmp;
	for(StringVec::iterator it = args.begin(); it != args.end(); ++it)
	{
		if((*it) == "--help")
		{
			std::cout << "Usage:\n"
			"\n"
			"\t--config=$1\t\tAlternate configuration file path.\n"
			"\t--data-directory=$1\tAlternate data directory path.\n"
			"\t--ip=$1\t\t\tIP address of gameworld server.\n"
			"\t\t\t\tShould be equal to the global IP.\n"
			"\t--login-port=$1\tPort for login server to listen on.\n"
			"\t--game-port=$1\tPort for game server to listen on.\n"
			"\t--admin-port=$1\tPort for admin server to listen on.\n"
			"\t--status-port=$1\tPort for status server to listen on.\n";
#ifndef WINDOWS
			std::cout << "\t--runfile=$1\t\tSpecifies run file. Will contain the pid\n"
			"\t\t\t\tof the server process as long as it is running.\n";
#endif
			std::cout << "\t--output-log=$1\t\tAll standard output will be logged to\n"
			"\t\t\t\tthis file.\n"
			"\t--error-log=$1\t\tAll standard errors will be logged to\n"
			"\t\t\t\tthis file.\n";
			return false;
		}

		if((*it) == "--version")
		{
			std::cout << STATUS_SERVER_NAME << ", version " << STATUS_SERVER_VERSION << " (" << STATUS_SERVER_CODENAME << ")\n"
			"Compiled with " << BOOST_COMPILER << " at " << __DATE__ << ", " << __TIME__ << ".\n"
			"A server developed by Elf, slawkens, Talaturen, Lithium, KaczooH, Kiper, Kornholijo.\n"
			"Visit our forum for updates, support and resources: http://otland.net.\n";
			return false;
		}

		tmp = explodeString((*it), "=");
		if(tmp[0] == "--config")
			g_config.setString(ConfigManager::CONFIG_FILE, tmp[1]);
		else if(tmp[0] == "--data-directory")
			g_config.setString(ConfigManager::DATA_DIRECTORY, tmp[1]);
		else if(tmp[0] == "--ip")
			g_config.setString(ConfigManager::IP, tmp[1]);
		else if(tmp[0] == "--login-port")
			g_config.setNumber(ConfigManager::LOGIN_PORT, atoi(tmp[1].c_str()));
		else if(tmp[0] == "--game-port")
			g_config.setNumber(ConfigManager::GAME_PORT, atoi(tmp[1].c_str()));
		else if(tmp[0] == "--admin-port")
			g_config.setNumber(ConfigManager::ADMIN_PORT, atoi(tmp[1].c_str()));
		else if(tmp[0] == "--status-port")
			g_config.setNumber(ConfigManager::STATUS_PORT, atoi(tmp[1].c_str()));
#ifndef WINDOWS
		else if(tmp[0] == "--runfile")
			g_config.setString(ConfigManager::RUNFILE, tmp[1]);
#endif
		else if(tmp[0] == "--output-log")
			g_config.setString(ConfigManager::OUT_LOG, tmp[1]);
		else if(tmp[0] == "--error-log")
			g_config.setString(ConfigManager::ERROR_LOG, tmp[1]);
	}

	return true;
}
コード例 #19
0
ファイル: StringTable.hpp プロジェクト: HPCToolkit/hpctoolkit
 long size()
 {
   return m_vec.size();
 }
コード例 #20
0
ファイル: StringTable.hpp プロジェクト: HPCToolkit/hpctoolkit
 // delete each string individually
 ~StringTable()
 {
   for (long i = 0; i < (long) m_vec.size(); i++) {
     delete m_vec[i];
   }
 }
コード例 #21
0
ファイル: chat.cpp プロジェクト: Codex-NG/thecrystalserver
bool Chat::talkToChannel(Player* player, MessageClasses type, const std::string& text, uint16_t channelId)
{
	if(text.empty())
		return false;

	ChatChannel* channel = getChannel(player, channelId);
	if(!channel)
		return false;

	if(!player->hasFlag(PlayerFlag_CannotBeMuted))
	{
		if(!channel->hasFlag(CHANNELFLAG_ACTIVE))
		{
			player->sendTextMessage(MSG_STATUS_SMALL, "You may not speak into this channel.");
			return true;
		}

		if(player->getLevel() < channel->getLevel())
		{
			char buffer[100];
			sprintf(buffer, "You may not speak into this channel as long as you are on level %d.", channel->getLevel());
			player->sendCancel(buffer);
			return true;
		}

		if(channel->getConditionId() >= 0 && player->hasCondition(CONDITION_MUTED, channel->getConditionId()))
		{
			player->sendCancel(channel->getConditionMessage().c_str());
			return true;
		}
	}

	if(isPublicChannel(channelId))
		Manager::getInstance()->talk(player->getID(), channelId, type, text);

	if(channelId != CHANNEL_GUILD || !g_config.getBool(ConfigManager::INGAME_GUILD_MANAGEMENT)
		|| (text[0] != '!' && text[0] != '/'))
	{
		if(channelId == CHANNEL_GUILD)
		{
			switch(player->getGuildLevel())
			{
				case GUILDLEVEL_VICE:
					return channel->talk(player, MSG_CHANNEL_HIGHLIGHT, text); // SPEAK_CHANNEL_O
				case GUILDLEVEL_LEADER:
					return channel->talk(player, MSG_GAMEMASTER_CHANNEL, text); // SPEAK_CHANNEL_RN
				default:
					break;
			}
		}

		return channel->talk(player, type, text);
	}

	if(!player->getGuildId())
	{
		player->sendCancel("You are not in a guild.");
		return true;
	}

	if(!IOGuild::getInstance()->guildExists(player->getGuildId()))
	{
		player->sendCancel("It seems like your guild does not exist anymore.");
		return true;
	}

	char buffer[350];
	if(text.substr(1) == "disband")
	{
		if(player->getGuildLevel() == GUILDLEVEL_LEADER)
		{
			IOGuild::getInstance()->disbandGuild(player->getGuildId());
			channel->talk(player, MSG_CHANNEL, "The guild has been disbanded.");
		}
		else
			player->sendCancel("You are not the leader of your guild.");
	}
	else if(text.substr(1, 6) == "invite")
	{
		if(player->getGuildLevel() > GUILDLEVEL_MEMBER)
		{
			if(text.length() > 7)
			{
				std::string param = text.substr(8);
				trimString(param);

				Player* paramPlayer = NULL;
				if(g_game.getPlayerByNameWildcard(param, paramPlayer) == RET_NOERROR)
				{
					if(paramPlayer->getGuildId() == 0)
					{
						if(!paramPlayer->isGuildInvited(player->getGuildId()))
						{
							sprintf(buffer, "%s has invited you to join the guild, %s. You may join this guild by writing: !joinguild %s", player->getName().c_str(), player->getGuildName().c_str(), player->getGuildName().c_str());
							paramPlayer->sendTextMessage(MSG_INFO_DESCR, buffer);
	
							sprintf(buffer, "%s has invited %s to the guild.", player->getName().c_str(), paramPlayer->getName().c_str());
							channel->talk(player, MSG_CHANNEL, buffer);
							paramPlayer->invitationsList.push_back(player->getGuildId());
						}
						else
							player->sendCancel("A player with that name has already been invited to your guild.");
					}
					else
						player->sendCancel("A player with that name is already in a guild.");
				}
				else if(IOLoginData::getInstance()->playerExists(param))
				{
					uint32_t guid;
					IOLoginData::getInstance()->getGuidByName(guid, param);
					if(!IOGuild::getInstance()->hasGuild(guid))
					{
						if(!IOGuild::getInstance()->isInvited(player->getGuildId(), guid))
						{
							if(IOGuild::getInstance()->guildExists(player->getGuildId()))
							{
								IOGuild::getInstance()->invitePlayer(player->getGuildId(), guid);
								sprintf(buffer, "%s has invited %s to the guild.", player->getName().c_str(), param.c_str());
								channel->talk(player, MSG_CHANNEL, buffer);
							}
							else
								player->sendCancel("Your guild does not exist anymore.");
						}
						else
							player->sendCancel("A player with that name has already been invited to your guild.");
					}
					else
						player->sendCancel("A player with that name is already in a guild.");
				}
				else
					player->sendCancel("A player with that name does not exist.");
			}
			else
				player->sendCancel("Invalid guildcommand parameters.");
		}
		else
			player->sendCancel("You don't have rights to invite players to your guild.");
	}
	else if(text.substr(1, 5) == "leave")
	{
		if(player->getGuildLevel() < GUILDLEVEL_LEADER)
		{
#ifdef __WAR_SYSTEM__
			if(!player->hasEnemy())
			{
#endif
				sprintf(buffer, "%s has left the guild.", player->getName().c_str());
				channel->talk(player, MSG_CHANNEL, buffer);
				player->leaveGuild();
#ifdef __WAR_SYSTEM__
			}
			else
				player->sendCancel("Your guild is currently at war, you cannot leave it right now.");
#endif
		}
		else
			player->sendCancel("You cannot leave your guild because you are the leader of it, you have to pass the leadership to another member of your guild or disband the guild.");
	}
	else if(text.substr(1, 6) == "revoke")
	{
		if(player->getGuildLevel() > GUILDLEVEL_MEMBER)
		{
			if(text.length() > 7)
			{
				std::string param = text.substr(8);
				trimString(param);

				Player* paramPlayer = NULL;
				if(g_game.getPlayerByNameWildcard(param, paramPlayer) == RET_NOERROR)
				{
					if(paramPlayer->getGuildId() == 0)
					{
						InvitationsList::iterator it = std::find(paramPlayer->invitationsList.begin(), paramPlayer->invitationsList.end(), player->getGuildId());
						if(it != paramPlayer->invitationsList.end())
						{
							sprintf(buffer, "%s has revoked your invite to %s guild.", player->getName().c_str(), (player->getSex(false) ? "his" : "her"));
							paramPlayer->sendTextMessage(MSG_INFO_DESCR, buffer);

							sprintf(buffer, "%s has revoked the guildinvite of %s.", player->getName().c_str(), paramPlayer->getName().c_str());
							channel->talk(player, MSG_CHANNEL, buffer);

							paramPlayer->invitationsList.erase(it);
							return true;
						}
						else
							player->sendCancel("A player with that name is not invited to your guild.");
					}
					else
						player->sendCancel("A player with that name is already in a guild.");
				}
				else if(IOLoginData::getInstance()->playerExists(param))
				{
					uint32_t guid;
					IOLoginData::getInstance()->getGuidByName(guid, param);
					if(IOGuild::getInstance()->isInvited(player->getGuildId(), guid))
					{
						if(IOGuild::getInstance()->guildExists(player->getGuildId()))
						{
							sprintf(buffer, "%s has revoked the guildinvite of %s.", player->getName().c_str(), param.c_str());
							channel->talk(player, MSG_CHANNEL, buffer);
							IOGuild::getInstance()->revokeInvite(player->getGuildId(), guid);
						}
						else
							player->sendCancel("It seems like your guild does not exist anymore.");
					}
					else
						player->sendCancel("A player with that name is not invited to your guild.");
				}
				else
					player->sendCancel("A player with that name does not exist.");
			}
			else
				player->sendCancel("Invalid guildcommand parameters.");
		}
		else
			player->sendCancel("You don't have rights to revoke an invite of someone in your guild.");
	}
	else if(text.substr(1, 7) == "promote" || text.substr(1, 6) == "demote" || text.substr(1, 14) == "passleadership" || text.substr(1, 4) == "kick")
	{
		if(player->getGuildLevel() == GUILDLEVEL_LEADER)
		{
			std::string param;
			uint32_t length = 0;
			if(text[2] == 'r')
				length = 9;
			else if(text[2] == 'e')
				length = 7;
			else if(text[2] == 'a')
				length = 16;
			else
				length = 6;

			if(text.length() < length)
			{
				player->sendCancel("Invalid guildcommand parameters.");
				return true;
			}

			param = text.substr(length);
			trimString(param);

			Player* paramPlayer = NULL;
			if(g_game.getPlayerByNameWildcard(param, paramPlayer) == RET_NOERROR)
			{
				if(paramPlayer->getGuildId())
				{
					if(IOGuild::getInstance()->guildExists(paramPlayer->getGuildId()))
					{
						if(player->getGuildId() == paramPlayer->getGuildId())
						{
							if(text[2] == 'r')
							{
								if(paramPlayer->getGuildLevel() == GUILDLEVEL_MEMBER)
								{
									if(paramPlayer->isPremium())
									{
										paramPlayer->setGuildLevel(GUILDLEVEL_VICE);
										sprintf(buffer, "%s has promoted %s to %s.", player->getName().c_str(), paramPlayer->getName().c_str(), paramPlayer->getRankName().c_str());
										channel->talk(player, MSG_CHANNEL, buffer);
									}
									else
										player->sendCancel("A player with that name does not have a premium account.");
								}
								else
									player->sendCancel("You can only promote Members to Vice-Leaders.");
							}
							else if(text[2] == 'e')
							{
								if(paramPlayer->getGuildLevel() == GUILDLEVEL_VICE)
								{
									paramPlayer->setGuildLevel(GUILDLEVEL_MEMBER);
									sprintf(buffer, "%s has demoted %s to %s.", player->getName().c_str(), paramPlayer->getName().c_str(), paramPlayer->getRankName().c_str());
									channel->talk(player, MSG_CHANNEL, buffer);
								}
								else
									player->sendCancel("You can only demote Vice-Leaders to Members.");
							}
							else if(text[2] == 'a')
							{
								if(paramPlayer->getGuildLevel() == GUILDLEVEL_VICE)
								{
									const uint32_t levelToFormGuild = g_config.getNumber(ConfigManager::LEVEL_TO_FORM_GUILD);
									if(paramPlayer->getLevel() >= levelToFormGuild)
									{
										paramPlayer->setGuildLevel(GUILDLEVEL_LEADER);
										player->setGuildLevel(GUILDLEVEL_VICE);

										IOGuild::getInstance()->updateOwnerId(paramPlayer->getGuildId(), paramPlayer->getGUID());
										sprintf(buffer, "%s has passed the guild leadership to %s.", player->getName().c_str(), paramPlayer->getName().c_str());
										channel->talk(player, MSG_CHANNEL, buffer);
									}
									else
									{
										sprintf(buffer, "The new guild leader has to be at least Level %d.", levelToFormGuild);
										player->sendCancel(buffer);
									}
								}
								else
									player->sendCancel("A player with that name is not a Vice-Leader.");
							}
							else
							{
								if(player->getGuildLevel() > paramPlayer->getGuildLevel())
								{
#ifdef __WAR_SYSTEM__
									if(!player->hasEnemy())
									{
#endif
										sprintf(buffer, "%s has been kicked from the guild by %s.", paramPlayer->getName().c_str(), player->getName().c_str());
										channel->talk(player, MSG_CHANNEL, buffer);
										paramPlayer->leaveGuild();
#ifdef __WAR_SYSTEM__
									}
									else
										player->sendCancel("Your guild is currently at war, you cannot kick right now.");
#endif
								}
								else
									player->sendCancel("You may only kick players with a guild rank below your.");
							}
						}
						else
							player->sendCancel("You are not in the same guild as a player with that name.");
					}
					else
						player->sendCancel("Could not find the guild of a player with that name.");
				}
				else
					player->sendCancel("A player with that name is not in a guild.");
			}
			else if(IOLoginData::getInstance()->playerExists(param))
			{
				uint32_t guid;
				IOLoginData::getInstance()->getGuidByName(guid, param);
				if(IOGuild::getInstance()->hasGuild(guid))
				{
					if(player->getGuildId() == IOGuild::getInstance()->getGuildId(guid))
					{
						if(text[2] == 'r')
						{
							if(IOGuild::getInstance()->getGuildLevel(guid) == GUILDLEVEL_MEMBER)
							{
								if(IOLoginData::getInstance()->isPremium(guid))
								{
									IOGuild::getInstance()->setGuildLevel(guid, GUILDLEVEL_VICE);
									sprintf(buffer, "%s has promoted %s to %s.", player->getName().c_str(), param.c_str(), IOGuild::getInstance()->getRank(guid).c_str());
									channel->talk(player, MSG_CHANNEL, buffer);
								}
								else
									player->sendCancel("A player with that name does not have a premium account.");
							}
							else
								player->sendCancel("You can only promote Members to Vice-Leaders.");
						}
						else if(text[2] == 'e')
						{
							if(IOGuild::getInstance()->getGuildLevel(guid) == GUILDLEVEL_VICE)
							{
								IOGuild::getInstance()->setGuildLevel(guid, GUILDLEVEL_MEMBER);
								sprintf(buffer, "%s has demoted %s to %s.", player->getName().c_str(), param.c_str(), IOGuild::getInstance()->getRank(guid).c_str());
								channel->talk(player, MSG_CHANNEL, buffer);
							}
							else
								player->sendCancel("You can only demote Vice-Leaders to Members.");
						}
						else if(text[2] == 'a')
						{
							if(IOGuild::getInstance()->getGuildLevel(guid) == GUILDLEVEL_VICE)
							{
								const uint32_t levelToFormGuild = g_config.getNumber(ConfigManager::LEVEL_TO_FORM_GUILD);
								if(IOLoginData::getInstance()->getLevel(guid) >= levelToFormGuild)
								{
									IOGuild::getInstance()->setGuildLevel(guid, GUILDLEVEL_LEADER);
									player->setGuildLevel(GUILDLEVEL_VICE);

									sprintf(buffer, "%s has passed the guild leadership to %s.", player->getName().c_str(), param.c_str());
									channel->talk(player, MSG_CHANNEL, buffer);
								}
								else
								{
									sprintf(buffer, "The new guild leader has to be at least Level %d.", levelToFormGuild);
									player->sendCancel(buffer);
								}
							}
							else
								player->sendCancel("A player with that name is not a Vice-Leader.");
						}
						else
						{
							sprintf(buffer, "%s has been kicked from the guild by %s.", param.c_str(), player->getName().c_str());
							channel->talk(player, MSG_CHANNEL, buffer);
							IOLoginData::getInstance()->resetGuildInformation(guid);
						}
					}
				}
				else
					player->sendCancel("A player with that name is not in a guild.");
			}
			else
				player->sendCancel("A player with that name does not exist.");
		}
		else
			player->sendCancel("You are not the leader of your guild.");
	}
	else if(text.substr(1, 4) == "nick" && text.length() > 5)
	{
		StringVec params = explodeString(text.substr(6), ",");
		if(params.size() >= 2)
		{
			std::string param1 = params[0], param2 = params[1];
			trimString(param1);
			trimString(param2);

			Player* paramPlayer = NULL;
			if(g_game.getPlayerByNameWildcard(param1, paramPlayer) == RET_NOERROR)
			{
				if(paramPlayer->getGuildId())
				{
					if(param2.length() > 2)
					{
						if(param2.length() < 21)
						{
							if(isValidName(param2, false))
							{
								if(IOGuild::getInstance()->guildExists(paramPlayer->getGuildId()))
								{
									if(player->getGuildId() == paramPlayer->getGuildId())
									{
										if(paramPlayer->getGuildLevel() < player->getGuildLevel() || (player == paramPlayer && player->getGuildLevel() > GUILDLEVEL_MEMBER))
										{
											paramPlayer->setGuildNick(param2);
											if(player != paramPlayer)
												sprintf(buffer, "%s has set the guildnick of %s to \"%s\".", player->getName().c_str(), paramPlayer->getName().c_str(), param2.c_str());
											else
												sprintf(buffer, "%s has set %s guildnick to \"%s\".", player->getName().c_str(), (player->getSex(false) ? "his" : "her"), param2.c_str());

											channel->talk(player, MSG_CHANNEL, buffer);
										}
										else
											player->sendCancel("You may only change the guild nick of players that have a lower rank than you.");
									}
									else
										player->sendCancel("A player with that name is not in your guild.");
								}
								else
									player->sendCancel("A player with that name's guild could not be found.");
							}
							else
								player->sendCancel("That guildnick is not valid.");
						}
						else
							player->sendCancel("That guildnick is too long, please select a shorter one.");
					}
					else
						player->sendCancel("That guildnick is too short, please select a longer one.");
				}
				else
					player->sendCancel("A player with that name is not in a guild.");
			}
			else if(IOLoginData::getInstance()->playerExists(param1))
			{
				uint32_t guid;
				IOLoginData::getInstance()->getGuidByName(guid, (std::string&)param1);
				if(IOGuild::getInstance()->hasGuild(guid))
				{
					if(param2.length() > 2)
					{
						if(param2.length() < 21)
						{
							if(isValidName(param2, false))
							{
								if(IOGuild::getInstance()->guildExists(guid))
								{
									if(player->getGuildId() == IOGuild::getInstance()->getGuildId(guid))
									{
										if(IOGuild::getInstance()->getGuildLevel(guid) < player->getGuildLevel())
										{
											IOGuild::getInstance()->setGuildNick(guid, param2);
											sprintf(buffer, "%s has set the guildnick of %s to \"%s\".", player->getName().c_str(), param1.c_str(), param2.c_str());
											channel->talk(player, MSG_CHANNEL, buffer);
										}
										else
											player->sendCancel("You may only change the guild nick of players that have a lower rank than you.");
									}
									else
										player->sendCancel("A player with that name is not in your guild.");
								}
								else
									player->sendCancel("A player with that name's guild could not be found.");
							}
							else
								player->sendCancel("That guildnick is not valid.");
						}
						else
							player->sendCancel("That guildnick is too long, please select a shorter one.");
					}
					else
						player->sendCancel("That guildnick is too short, please select a longer one.");
				}
				else
					player->sendCancel("A player with that name is not in any guild.");
			}
			else
				player->sendCancel("A player with that name does not exist.");
		}
		else
			player->sendCancel("Invalid guildcommand parameters.");
	}
	else if(text.substr(1, 11) == "setrankname" && text.length() > 12)
	{
		StringVec params = explodeString(text.substr(13), ",");
		if(params.size() >= 2)
		{
			std::string param1 = params[0], param2 = params[1];
			trimString(param1);
			trimString(param2);

			if(player->getGuildLevel() == GUILDLEVEL_LEADER)
			{
				if(param2.length() > 2)
				{
					if(param2.length() < 21)
					{
						if(isValidName(param2, false))
						{
							if(IOGuild::getInstance()->getRankIdByName(player->getGuildId(), param1))
							{
								if(!IOGuild::getInstance()->getRankIdByName(player->getGuildId(), param2))
								{
									IOGuild::getInstance()->changeRank(player->getGuildId(), param1, param2);
									sprintf(buffer, "%s has renamed the guildrank: \"%s\", to: \"%s\".", player->getName().c_str(), param1.c_str(), param2.c_str());
									channel->talk(player, MSG_CHANNEL, buffer);
								}
								else
									player->sendCancel("There is already a rank in your guild with that name.");
							}
							else
								player->sendCancel("There is no such rankname in your guild.");
						}
						else
							player->sendCancel("The new guildrank contains invalid characters.");
					}
					else
						player->sendCancel("The new rankname is too long.");
				}
				else
					player->sendCancel("The new rankname is too short.");
			}
			else
				player->sendCancel("You are not the leader of your guild.");
		}
		else
			player->sendCancel("Invalid guildcommand parameters");
	}
	else if(text.substr(1, 7) == "setmotd")
	{
		if(player->getGuildLevel() == GUILDLEVEL_LEADER)
		{
			if(text.length() > 8)
			{
				std::string param = text.substr(9);
				trimString(param);
				if(param.length() > 2)
				{
					if(param.length() < 225)
					{
						IOGuild::getInstance()->setMotd(player->getGuildId(), param);
						sprintf(buffer, "%s has set the Message of the Day to: %s", player->getName().c_str(), param.c_str());
						channel->talk(player, MSG_CHANNEL, buffer);
					}
					else
						player->sendCancel("That motd is too long.");
				}
				else
					player->sendCancel("That motd is too short.");
			}
			else
				player->sendCancel("Invalid guildcommand parameters.");
		}
		else
			player->sendCancel("Only the leader of your guild can set the guild motd.");
	}
	else if(text.substr(1, 9) == "cleanmotd")
	{
		if(player->getGuildLevel() == GUILDLEVEL_LEADER)
		{
			IOGuild::getInstance()->setMotd(player->getGuildId(), "");
			sprintf(buffer, "%s has cleaned the Message of the Day.", player->getName().c_str());
			channel->talk(player, MSG_CHANNEL, buffer);
		}
		else
			player->sendCancel("Only the leader of your guild can clean the guild motd.");
	}
	else if(text.substr(1, 8) == "commands")
		player->sendToChannel(player, MSG_CHANNEL, "Guild commands with parameters: disband, invite[name], leave, kick[name], revoke[name], demote[name], promote[name], passleadership[name], nick[name, nick], setrankname[oldName, newName], setmotd[text] and cleanmotd.", CHANNEL_GUILD);
	else
		return false;

	return true;
}
コード例 #22
0
ファイル: interactive.cpp プロジェクト: UIKit0/aqsis
//------------------------------------------------------------------------------
int main(int argc, char* argv[])
{
	QApplication app(argc, argv);

    typedef std::vector<std::string> StringVec;
    namespace po = boost::program_options;
    // optional options
    po::options_description optionsDesc("options");
    optionsDesc.add_options()
        ("help,h", "help message")
        ("stats,s", po::value<int>()->default_value(0),
         "frame statistics verbosity")
        ("threads,t", po::value<int>()->default_value(-1),
         "number of threads to use (-1 = auto)")
        ("opts", po::value<std::string>()->default_value(""),
         "frame render options")
    ;
    // options + positional parameters
    po::options_description allArgs("All arguments");
    allArgs.add(optionsDesc);
    allArgs.add_options()
        ("rib_files", po::value<StringVec>(), "RIB files to render")
    ;
    po::positional_options_description params;
    params.add("rib_files", -1);
    // Parse options
    po::variables_map opts;
    po::store(po::command_line_parser(argc, argv)
              .options(allArgs).positional(params).run(), opts);
    po::notify(opts);

    if(opts.count("help") || opts.count("rib_files") == 0)
    {
        std::cout
            << "Usage: " << argv[0] << " [options] model.rib\n\n"
            << optionsDesc;
        return 0;
    }

    boost::shared_ptr<Ri::RendererServices> renderer(createRenderer());

    // Command line options
    Ri::Renderer& ri = renderer->firstFilter();
    ri.Option("statistics", ParamListBuilder()
              ("endofframe", opts["stats"].as<int>()));
    ri.Option("limits", ParamListBuilder()
              ("threads", opts["threads"].as<int>()));

    // Default hard-coded frame options.
    ri.PixelSamples(2, 2);
    ri.PixelFilter(renderer->getFilterFunc("sinc"), 3, 3);
    ri.ShadingRate(1);
    ri.Option("limits", ParamListBuilder()("eyesplits", 6));
    ri.Clipping(0.3, FLT_MAX);

	// Build a list of all ribFiles specified, expanding wildcards where necessary
	StringVec allFiles;
	const StringVec& ribFiles = opts["rib_files"].as<StringVec>();
	for(StringVec::const_iterator rf = ribFiles.begin(), rfEnd = ribFiles.end(); rf != rfEnd; ++rf)
	{
		std::vector<std::string> files = cliGlob(*rf);
		for(std::vector<std::string>::iterator f = files.begin(), fend = files.end(); f != fend; ++f)
			allFiles.push_back(*f);
	}

    RenderWindow win(640, 480, *renderer, opts["opts"].as<std::string>(),
                     allFiles);

	QObject::connect(&win, SIGNAL(exitApplication()), &app, SLOT(quit()));

    win.show();
	win.adjustSize();

    return app.exec();
}
コード例 #23
0
ファイル: ProfileDlg.cpp プロジェクト: christau/xp-AntiSpy
void ProfileDlg::OnImportProfile() 
{
	CString name;
	CString tmp;
	tmp.LoadString(IDS_PROFILE_FILEDIALOG);
	CFileDialog fd( TRUE, _T("prf"), NULL, OFN_ENABLESIZING|OFN_FILEMUSTEXIST, tmp + _T(" (*.xpas)|*.xpas||"), this);
	tmp.LoadString(IDS_PROFILE_LOAD);
	fd.m_ofn.lpstrTitle = tmp;
	if(fd.DoModal() == IDOK)
	{
		StringVec profiles = GetExistingProfiles();
		for(int i = 0; i < profiles.size(); ++i)
		{
			profiles[i].MakeLower();
			fd.GetFileName().MakeLower();
			if(profiles[i] == fd.GetFileTitle())
			{
				CString tmp;
				tmp.LoadString(IDS_PROFILE_EXISTS);
				if(MessageBox(tmp, NULL, MB_YESNO) == IDNO)
				{
					return;
				}
				else
				{
					DeleteProfile(fd.GetFileTitle());
				}
			}
		}

		CFile file(fd.GetPathName(), CFile::modeRead);
		SettingVec vec;
		
		CArchive* ar=new CArchive(&file,CArchive::load);
		try
		{
			while(1)
			{
				SETTING set;
				*ar>>set.settingID;
				*ar>>set.checked;
				if((set.settingID <= ITEMCOUNT && set.settingID >= 0)
					|| (set.checked >= 0 && set.checked <= 1))
				{
					vec.push_back(set);
				}
			}
		}
		catch(CArchiveException* e)
		{
			e->Delete();
			if(vec.size() > 0)
				CreateProfile(fd.GetFileTitle(),vec);
			else
			{
				CString tmp;
				tmp.LoadString(IDS_PROFILE_ERROR);
				AfxMessageBox(tmp);
			}
		}
		ar->Close();
		if(ar) delete ar;
		file.Close();
	}
コード例 #24
0
bool SpeckleyElements::writeToSilo(DBfile* dbfile, const string& siloPath,
                                 const StringVec& labels,
                                 const StringVec& units, bool writeMeshData)
{
#ifdef ESYS_HAVE_SILO
    if (numElements == 0)
        return true;

    int ret;

    if (siloPath != "") {
        ret = DBSetDir(dbfile, siloPath.c_str());
        if (ret != 0)
            return false;
    }

    // write out the full mesh in any case
    nodeMesh->setSiloPath(siloPath);
    string siloMeshNameStr = nodeMesh->getFullSiloName();
    const char* siloMeshName = siloMeshNameStr.c_str();
    int arraylen = numElements * nodesPerElement;
    int eltype = toSiloElementType(type);

    string varName = name + string("_zones");
    ret = DBPutZonelist2(dbfile, varName.c_str(), numElements,
            nodeMesh->getNumDims(), &nodes[0], arraylen, 0, 0,
            numGhostElements, &eltype, &nodesPerElement, &numElements, 1, NULL);

    if (ret == 0) {
        CoordArray& coordbase = const_cast<CoordArray&>(nodeMesh->getCoords());
        DBoptlist* optList = NULL;
        int nOpts = labels.size()+units.size();
        if (nOpts>0) {
            optList = DBMakeOptlist(nOpts);
            if (labels.size()>0)
                DBAddOption(optList, DBOPT_XLABEL, (void*)labels[0].c_str());
            if (labels.size()>1)
                DBAddOption(optList, DBOPT_YLABEL, (void*)labels[1].c_str());
            if (labels.size()>2)
                DBAddOption(optList, DBOPT_ZLABEL, (void*)labels[2].c_str());
            if (units.size()>0)
                DBAddOption(optList, DBOPT_XUNITS, (void*)units[0].c_str());
            if (units.size()>1)
                DBAddOption(optList, DBOPT_YUNITS, (void*)units[1].c_str());
            if (units.size()>2)
                DBAddOption(optList, DBOPT_ZUNITS, (void*)units[2].c_str());
        }
        ret = DBPutUcdmesh(dbfile, siloMeshName,
                nodeMesh->getNumDims(), NULL, &coordbase[0],
                nodeMesh->getNumNodes(), numElements, varName.c_str(),
                /*"facelist"*/NULL, DB_FLOAT, optList);

        if (optList)
            DBFreeOptlist(optList);
    }
    
    if (ret != 0)
        return false;

    // write out the element-centered variables if enabled
    if (writeMeshData) {
        varName = name + string("_Id");
        ret = DBPutUcdvar1(dbfile, varName.c_str(), siloMeshName,
                (float*)&ID[0], numElements, NULL, 0, DB_INT, DB_ZONECENT,
                NULL);
        if (ret == 0) {
            varName = name + string("_Owner");
            ret = DBPutUcdvar1(dbfile, varName.c_str(), siloMeshName,
                (float*)&owner[0], numElements, NULL, 0, DB_INT, DB_ZONECENT,
                NULL);
        }
    }

    // "Elements" is a special case
    if (writeMeshData && name == "Elements") {
        nodeMesh->writeToSilo(dbfile);
    }

    return (ret == 0);

#else // !ESYS_HAVE_SILO
    return false;
#endif
}
コード例 #25
0
ファイル: argument.cpp プロジェクト: AMPedGames/libgdl
Argument* Argument::ConstructArgument(const std::string& str,
                                      StrVarMap& v_map,
                                      SymbolTable& symbol_table,
                                      bool isRel,
                                      Log log)
{
  if(str[0] != '(')
  {
    if(str[0] == '?')
    {
      StrVarMap::iterator it;
      if((it = v_map.find(str)) != v_map.end())
        return it->second;
      else
      {
        Argument* out = new Argument();
        out->t = Argument::Var;
        out->val = str;
        v_map[str] = out;
        return out;
      }
    }

    Symbol* sym;
    size_t id = symbol_table.CheckEntry(str, 0, isRel, sym);

    if(sym == NULL) id = symbol_table.AddEntry(str, Location(), 0, isRel);

    Argument* out = new Argument();
    if(isRel)
      out->t = Argument::Relation;
    else out->t = Argument::Function;
    out->value = id;
    return out;
  }

  std::string cmd;
  StringVec args;
  if(!SeparateCommand(str, cmd, args, log))
  {
    log.Fatal << "Unable to construct argument from " << str << std::endl;
    return NULL;
  }

  Symbol* sym;
  size_t id = symbol_table.CheckEntry(cmd, args.size(), isRel, sym);

  if(sym == NULL)
    id = symbol_table.AddEntry(cmd, Location(), args.size(), isRel);

  Argument* out = new Argument();

  if(isRel)
    out->t = Argument::Relation;
  else out->t = Argument::Function;
  out->value = id;

  for(size_t i = 0;i < args.size();i++)
  {
    Argument* arg;
    if(id == SymbolTable::NotID || id == SymbolTable::OrID)
      arg = ConstructArgument(args[i], v_map, symbol_table, true, log);
    else
      arg = ConstructArgument(args[i], v_map, symbol_table, false, log);
    if(arg != NULL) out->args.push_back(arg);
  }
  return out;
}
コード例 #26
0
int main( int argc, char *argv[] ) {
	if ( argc < 3 ) {
		std::cout << "Usage: ./compileSHE <domain.pddl> <task.pddl>\n";
		std::cout << "Writes domain file to standard output and instance file to standard error\n";
		exit( 1 );
	}

	d = new Domain( argv[1] );
	ins = new Instance( *d, argv[2] );

	// Generate dependency graph among actions and identify durations and depths

	graph g( d->actions.size() );
	for ( unsigned i = 0; i < d->actions.size(); ++i ) {
		for ( unsigned j = 0; j < d->actions.size(); ++j )
			if ( i != j )
				detectDependency( i, j, g );
	}
	g.computeDurations();
	g.computeDepths();

	// Identify contexts that are threatened by contents
	// RIGHT NOW PRE & EFF ASSUME POSITIVE PRECONDITIONS !!!

	int maxCount = 0;
	for ( unsigned i = 0; i < d->actions.size(); ++i ) {
		maxCount = MAX( maxCount, *g.depths[i].rbegin() );
		for ( unsigned j = 0; j < get( i )->pre_o->conds.size(); ++j ) {
			Ground * pre = dynamic_cast< Ground * >( get( i )->pre_o->conds[j] );
			if ( pre ) {
				int k = d->preds.index( pre->name );
				if ( k >= 0 && isPre( i, k, g ) )
					pres.insert( k );
			}
		}
	}

	// Create classical domain
	cd = new Domain;
	cd->name = d->name;
	cd->equality = d->equality;
	cd->condeffects = cd->typed = true;
	cd->cons = d->cons || ( maxCount && pres.size() ) || g.subtractionPairs.size();
	cd->equality = d->equality;

	// Add types
	cd->setTypes( d->copyTypes() );
	if ( maxCount && pres.size() ) cd->createType( "COUNT" );
	if ( g.subtractionPairs.size() ) cd->createType( "TIME" );

	// Add constants
	StringVec counts;
	for ( int i = 0; maxCount && pres.size() && i <= maxCount; ++i ) {
		std::stringstream ss;
		ss << "COUNT" << i;
		counts.push_back( ss.str() );
		cd->createConstant( counts[i], "COUNT" );
	}
	StringVec times;
	for ( unsigned i = 0; g.subtractionPairs.size() && i < g.durationMap.size(); ++i ) {
		std::stringstream ss;
		ss << "TIME" << i;
		times.push_back( ss.str() );
		cd->createConstant( times[i], "TIME" );
	}

	// Add predicates
	for ( unsigned i = 0; i < d->preds.size(); ++i ) {
		StringVec pars = d->typeList( d->preds[i] );
		cd->createPredicate( d->preds[i]->name, pars );
		if ( pres.find( i ) != pres.end() ) {
			pars.push_back( "COUNT" );
			cd->createPredicate( "COUNT-" + d->preds[i]->name, pars );
		}
	}

	StringVec stacks( 1, "EMPTYSTACK" );
	cd->createPredicate( stacks[0] );
	for ( int i = 1; i <= maxCount; ++i ) {
		std::stringstream ss;
		ss << "STACK" << i;
		stacks.push_back( ss.str() );
		cd->createPredicate( stacks[i] );
		cd->createPredicate( stacks[i] + "-REMAINING", StringVec( 1, "TIME" ) );
		cd->createPredicate( stacks[i] + "-INCREASE", StringVec( 1, "TIME" ) );
		cd->createPredicate( stacks[i] + "-DECREASE" );
		cd->createPredicate( stacks[i] + "-CONTINUE", StringVec( 1, "TIME" ) );
	}

	for ( unsigned i = 0; i < d->actions.size(); ++i )
		for ( IntSet::iterator j = g.depths[i].begin(); g.outgoing( i ) && j != g.depths[i].end(); ++j ) {
			std::stringstream ss;
			ss << "STACK" << *j + 1 << "-" << d->actions[i]->name;
			cd->createPredicate( ss.str(), d->typeList( d->actions[i] ) );
		}

	if ( counts.size() )
		cd->createPredicate( "CONSECUTIVE", StringVec( 2, "COUNT" ) );

	if ( times.size() )
		cd->createPredicate( "SUBTRACT", StringVec( 3, "TIME" ) );

	// Currently does NOT add functions
//	for ( unsigned i = 0; i < d->funcs.size(); ++i )
//		cd->createFunction( d->funcs[i]->name, d->funcs[i]->returnType, d->typeList( d->funcs[i] ) );

	// Add actions
	for ( unsigned i = 0; i < d->actions.size(); ++i )
		// DOES NOT CURRENTLY IMPLEMENT COUNT MECHANISM !!!
		for ( IntSet::iterator j = g.depths[i].begin(); j != g.depths[i].end(); ++j )
			if ( g.outgoing( i ) ) {
				// Action is an envelope: compile into push and pop action

				// Push action
				std::string name = "PUSH-" + d->actions[i]->name;
				unsigned size = d->actions[i]->params.size();
				Action * push = cd->createAction( name, d->typeList( d->actions[i] ) );

				//std::cout << "Creating action " << name << "\n";

				// ONLY DEALS WITH POSITIVE PRECONDITIONS HERE !!!
				cd->setPre( name, d->actions[i]->pre );
				for ( unsigned k = 0; k < get( i )->pre_o->conds.size(); ++k ) {
					Ground * pre = dynamic_cast< Ground * >( get( i )->pre_o->conds[k] );
					if ( pre && !includes( 0, pre, ( And * )get( i )->pre ) &&
					            !includes( 0, pre, ( And * )get( i )->eff ) )
						cd->addPre( 0, name, pre->name, pre->params );
					// if precon is not positive, just copy it
					if ( !pre ) ( ( And * )push->pre )->add( get( i )->pre_o->conds[k]->copy( *cd ) );
				}
				cd->addPre( 0, name, stacks[*j] );

				cd->setEff( name, d->actions[i]->eff );
				cd->addEff( 1, name, stacks[*j] );
				if ( *j ) cd->addEff( 0, name, stacks[*j] + "-INCREASE", IntVec( 1, cd->constantIndex( times[g.durationMap[d->actions[i]->duration()]], "TIME" ) ) );
				else cd->addEff( 0, name, stacks[1] );
				cd->addEff( 0, name, stacks[*j + 1] + "-" + d->actions[i]->name, incvec( 0, size ) );
				cd->addEff( 0, name, stacks[*j + 1] + "-REMAINING", IntVec( 1, cd->constantIndex( times[g.durationMap[d->actions[i]->duration()]], "TIME" ) ) );

				// Pop action
				name = "POP-" + d->actions[i]->name;
				cd->createAction( name, d->typeList( d->actions[i] ) );

				//std::cout << "Creating action " << name << "\n";

				// ONLY DEALS WITH POSITIVE PRECONDITIONS HERE !!!
				cd->setPre( name, get( i )->pre_e );
				for ( unsigned k = 0; k < get( i )->pre_o->conds.size(); ++k ) {
					Ground * h = dynamic_cast< Ground * >( get( i )->pre_o->conds[k] );
					if ( h && !includes( 0, h, get( i )->pre_e ) )
						cd->addPre( 0, name, h->name, h->params );
				}
				cd->addPre( 0, name, stacks[*j + 1] );
				cd->addPre( 0, name, stacks[*j + 1] + "-" + d->actions[i]->name, incvec( 0, size ) );

				cd->setEff( name, get( i )->eff_e );
				cd->addEff( 0, name, stacks[*j + 1] + "-DECREASE" );
				cd->addEff( 1, name, stacks[*j + 1] );
				cd->addEff( 1, name, stacks[*j + 1] + "-" + d->actions[i]->name, incvec( 0, size ) );
			}
			else {
				// Action is not an envelope: compile into compressed action
				std::string name = "DO-" + d->actions[i]->name;
				Action * doit = cd->createAction( name, d->typeList( d->actions[i] ) );

				//std::cout << "Creating action " << name << "\n";

				// ONLY DEALS WITH POSITIVE PRECONDITIONS HERE !!!
				cd->setPre( name, d->actions[i]->pre );
				for ( unsigned k = 0; k < get( i )->pre_o->conds.size(); ++k ) {
					Ground * pre = dynamic_cast< Ground * >( get( i )->pre_o->conds[k] );
					if ( pre && !includes( 0, pre, ( And * )get( i )->pre ) &&
					            !includes( 0, pre, ( And * )get( i )->eff ) )
						cd->addPre( 0, name, pre->name, pre->params );
					// if precon is not positive, just copy it
					if ( !pre ) ( ( And * )doit->pre )->add( get( i )->pre_o->conds[k]->copy( *cd ) );
				}
				for ( unsigned k = 0; k < get( i )->pre_e->conds.size(); ++k ) {
					Ground * h = ( Ground * )get( i )->pre_e->conds[k];
					if ( !includes( 0, h, ( And * )get( i )->pre ) &&
					     !includes( 0, h, ( And * )get( i )->eff ) )
						cd->addPre( 0, name, h->name, h->params );
				}
				cd->addPre( 0, name, stacks[*j] );

				cd->setEff( name, get( i )->eff_e );
				GroundVec add = get( i )->addEffects();
				for ( unsigned k = 0; k < add.size(); ++k )
					if ( !includes( 1, add[k], get( i )->eff_e ) )
						cd->addEff( 0, name, add[k]->name, add[k]->params );
				GroundVec del = get( i )->deleteEffects();
				for ( unsigned k = 0; k < del.size(); ++k )
					if ( !includes( 0, del[k], get( i )->eff_e ) )
						cd->addEff( 1, name, del[k]->name, del[k]->params );
				if ( *j ) {
					cd->addEff( 1, name, stacks[*j] );
					cd->addEff( 0, name, stacks[*j] + "-CONTINUE", IntVec( 1, cd->constantIndex( times[g.durationMap[d->actions[i]->duration()]], "TIME" ) ) );
				}
			}

	for ( int i = 1; i <= maxCount; ++i ) {
		if ( i < maxCount ) {
			// Increase action
			std::stringstream ss;
			ss << "INCREASE" << i;
			std::string name = ss.str();
			cd->createAction( name, StringVec( 3, "TIME" ) );

			cd->addPre( 0, name, stacks[i] + "-REMAINING", incvec( 0, 1 ) );
			cd->addPre( 0, name, stacks[i] + "-INCREASE", incvec( 2, 3 ) );
			cd->addPre( 0, name, "SUBTRACT", incvec( 0, 3 ) );

			cd->addEff( 0, name, stacks[i + 1] );
			cd->addEff( 1, name, stacks[i] + "-REMAINING", incvec( 0, 1 ) );
			cd->addEff( 0, name, stacks[i] + "-REMAINING", incvec( 1, 2 ) );
			cd->addEff( 1, name, stacks[i] + "-INCREASE", incvec( 2, 3 ) );
		}
		
		// Decrease action
		std::stringstream ss;
		ss << "DECREASE" << i;
		std::string name = ss.str();
		cd->createAction( name, StringVec( 1, "TIME" ) );

		cd->addPre( 0, name, stacks[i] + "-REMAINING", incvec( 0, 1 ) );
		cd->addPre( 0, name, stacks[i] + "-DECREASE" );

		cd->addEff( 0, name, stacks[i - 1] );
		cd->addEff( 1, name, stacks[i] + "-REMAINING", incvec( 0, 1 ) );
		cd->addEff( 1, name, stacks[i] + "-DECREASE" );

		// Continue action
		std::stringstream ss2;
		ss2 << "CONTINUE" << i;
		name = ss2.str();
		cd->createAction( name, StringVec( 3, "TIME" ) );

		cd->addPre( 0, name, stacks[i] + "-REMAINING", incvec( 0, 1 ) );
		cd->addPre( 0, name, stacks[i] + "-CONTINUE", incvec( 2, 3 ) );
		cd->addPre( 0, name, "SUBTRACT", incvec( 0, 3 ) );
		
		cd->addEff( 0, name, stacks[i] );
		cd->addEff( 1, name, stacks[i] + "-REMAINING", incvec( 0, 1 ) );
		cd->addEff( 0, name, stacks[i] + "-REMAINING", incvec( 1, 2 ) );
		cd->addEff( 1, name, stacks[i] + "-CONTINUE", incvec( 2, 3 ) );
	}

	cd->PDDLPrint( std::cout );

	cins = new Instance( *cd );
	cins->name = ins->name;

	// create initial state
	for ( unsigned i = 0; i < ins->init.size(); ++i )
		if ( d->preds.index( ins->init[i]->name ) >= 0 )
			cins->addInit( ins->init[i]->name, d->objectList( ins->init[i] ) );
	cins->addInit( stacks[0] );

	for ( unsigned i = 1; i < counts.size(); ++i ) {
		StringVec pars( 1, counts[i - 1] );
		pars.push_back( counts[i] );
		cins->addInit( "CONSECUTIVE", pars );
	}
	for ( DoublePairSet::iterator i = g.subtractionPairs.begin(); i != g.subtractionPairs.end(); ++i ) {
		StringVec pars( 1, times[g.durationMap[i->first]] );
		pars.push_back( times[g.durationMap[i->first - i->second]] );
		pars.push_back( times[g.durationMap[i->second]] );
		cins->addInit( "SUBTRACT", pars );
	}

	// create goal state
	for ( unsigned i = 0; i < ins->goal.size(); ++i )
		cins->addGoal( ins->goal[i]->name, d->objectList( ins->goal[i] ) );
	cins->addGoal( stacks[0] );

	cins->PDDLPrint( std::cerr );

	delete cins;
	delete cd;
	delete ins;
	delete d;
}
コード例 #27
0
ファイル: otserv.cpp プロジェクト: 081421/otxserver
bool argumentsHandler(StringVec args)
{
	StringVec tmp;
	for(StringVec::iterator it = args.begin(); it != args.end(); ++it)
	{
		if((*it) == "--help")
		{
			std::clog << "Usage:\n"
			"\n"
			"\t--config=$1\t\tAlternate configuration file path.\n"
			"\t--data-directory=$1\tAlternate data directory path.\n"
			"\t--ip=$1\t\t\tIP address of the server.\n"
			"\t\t\t\tShould be equal to the global IP.\n"
			"\t--login-port=$1\tPort for login server to listen on.\n"
			"\t--game-port=$1\tPort for game server to listen on.\n"
			"\t--admin-port=$1\tPort for admin server to listen on.\n"
			"\t--manager-port=$1\tPort for manager server to listen on.\n"
			"\t--status-port=$1\tPort for status server to listen on.\n";
#ifndef WINDOWS
			std::clog << "\t--runfile=$1\t\tSpecifies run file. Will contain the pid\n"
			"\t\t\t\tof the server process as long as run status.\n";
#endif
			std::clog << "\t--log=$1\t\tWhole standard output will be logged to\n"
			"\t\t\t\tthis file.\n"
			"\t--closed\t\t\tStarts the server as closed.\n"
			"\t--no-script\t\t\tStarts the server without script system.\n";
			return false;
		}

		if((*it) == "--version" || (*it) == "-v")
		{
			std::clog << "The " << SOFTWARE_NAME << " Version: (" << SOFTWARE_VERSION << "." << MINOR_VERSION << PATCH_VERSION << " - " << REVISION_VERSION << ") - Codename: (" << SOFTWARE_CODENAME << ")\n"
			"Compilied with " << BOOST_COMPILER << " for arch "
			#if defined(__amd64__) || defined(_M_X64)
			"64 Bits"
			#elif defined(__i386__) || defined(_M_IX86) || defined(_X86_)
			"32 Bits"
			#else
			"unk"
			#endif
			" at " << __DATE__ << " " << __TIME__ << "\n"

			"\n"
			"A server developed by: "SOFTWARE_DEVELOPERS".\n"
			"Visit our forums for updates, support, and resources:\n"
			""FORUMS"\n";
			return false;
		}

		tmp = explodeString((*it), "=");
		if(tmp[0] == "--config")
			g_config.setString(ConfigManager::CONFIG_FILE, tmp[1]);
		else if(tmp[0] == "--data-directory")
			g_config.setString(ConfigManager::DATA_DIRECTORY, tmp[1]);
		else if(tmp[0] == "--logs-directory")
			g_config.setString(ConfigManager::LOGS_DIRECTORY, tmp[1]);
		else if(tmp[0] == "--ip")
			g_config.setString(ConfigManager::IP, tmp[1]);
		else if(tmp[0] == "--login-port")
			g_config.setNumber(ConfigManager::LOGIN_PORT, atoi(tmp[1].c_str()));
		else if(tmp[0] == "--game-port")
			g_config.setNumber(ConfigManager::GAME_PORT, atoi(tmp[1].c_str()));
		else if(tmp[0] == "--status-port")
			g_config.setNumber(ConfigManager::STATUS_PORT, atoi(tmp[1].c_str()));
#ifndef WINDOWS
		else if(tmp[0] == "--runfile" || tmp[0] == "--run-file" || tmp[0] == "--pidfile" || tmp[0] == "--pid-file")
			g_config.setString(ConfigManager::RUNFILE, tmp[1]);
#endif
		else if(tmp[0] == "--log")
			g_config.setString(ConfigManager::OUTPUT_LOG, tmp[1]);
#ifndef WINDOWS
		else if(tmp[0] == "--daemon" || tmp[0] == "-d")
			g_config.setBool(ConfigManager::DAEMONIZE, true);
#endif
		else if(tmp[0] == "--closed")
			g_config.setBool(ConfigManager::START_CLOSED, true);
		else if(tmp[0] == "--no-script" || tmp[0] == "--noscript")
			g_config.setBool(ConfigManager::SCRIPT_SYSTEM, false);
	}

	return true;
}
コード例 #28
0
ファイル: 01_login.cpp プロジェクト: marcbowes/mxitc
/****************************************************************************
**
** Author: Marc Bowes
** Author: Tim Sjoberg
**
** Extracts variable information from the login packet
** FIXME: Poll data looks fishy
**
****************************************************************************/
VariableHash Login::handle(const QByteArray &packet)
{
  /*
  == PACKET FORMAT
  ***************************************************************************
  **
  **  1\0
  **  errorCode[\1errorMessage]\0
  **  sesid\0
  **  deprecated\1loginname\1dateTime\1URL\1
  **  maxSupportedVer\1pricePlan\1flags
  **  [\0Poll data]
  **
  ***************************************************************************
  
  == DEFINITIONS
  ***************************************************************************
  **
  **  sesid               the session ID (>1 for HTTP connections and 0 for
  **                      TCP connections)
  **  deprecated          deprecated functionality (expect an empty string)
  **  loginname           the user's loginname
  **  dateTime            the date and time in number of seconds since
  **                      1 January 1970 (UTC)
  **  URL                 is the URL of the proxy handling your current
  **                      session. Use this URL to reconnect to if
  **                      disconnected.
  **  maxSupportedVer     maximum protocol version supported by the server
  **                      (major*10+minor)
  **  pricePlan           the price plan the user is on:
  **                      1 - free
  **                      2 - premium
  **  flags               contains specific flags for this user. At the
  **                      moment only indicates if session is encrypted or not.
  **  poll data           if getContacts was set to 1, this will contain the
  **                      user's contacts as well as their presence information
  **                      and all new messages;
  **
  ***************************************************************************
  
  == ERRORS
  ***************************************************************************
  **
  **  3                   Invalid password
  **  16                  Redirect[1] to new proxy
  **  99                  Something went wrong
  **
  ***************************************************************************
  
  == NOTES
  ***************************************************************************
  **
  **  [1] Redirect
  **    The client is requested to redirect to the URL specified in the
  **    errorMessage field. The URL will be in the following format:
  **    protocol://host:port;type[;msg]
  **
  ***************************************************************************
  */
  
  /* setup */
  StringVec variables;
  
  /* first break up packet by \0 into variable sections */
  variables.append("sesid");                /* sesid\0 */
  variables.append("data");                 /* deprecated..flags\0 */
  
  /* extract \0 seperated values */
  VariableHash pass1 = hashVariables(packet, variables, '\0');

  /* need to expand data section */
  variables.clear();
  variables.append("deprecated");
  variables.append("loginname");
  variables.append("dateTime");
  variables.append("URL");
  variables.append("maxSuppertedVer");
  variables.append("pricePlan");
  variables.append("flags");
  
  /* extract \1 seperated values */
  VariableHash pass2 = hashVariables(pass1["data"], variables, '\1');
  
  /* no clean-up needed, just return the variables */
  return pass1.unite(pass2);
}
コード例 #29
0
ファイル: StringTable.hpp プロジェクト: HPCToolkit/hpctoolkit
 StringTable()
 {
   m_map.clear();
   m_vec.clear();
   m_invalid = "invalid-string";
 }
コード例 #30
0
ファイル: Path.cpp プロジェクト: AndreCAndersen/nupic
  Path::StringVec Path::split(const std::string & path)
  {
    /**
     * Don't use boost::tokenizer because we need to handle the prefix specially.
     * Handling the prefix is messy on windows, but this is the only place we have 
     * to do it
     */
    StringVec parts;
    std::string::size_type curpos = 0;
    if (path.size() == 0)
      return parts;

#ifndef WIN32
    // only possible prefix is "/"
    if (path[0] == '/') 
    {
      parts.push_back("/");
      curpos++;
    }
#else
    // prefix may be 1) "\", 2) "\\", 3) "[a-z]:", 4) "[a-z]:\"
    if (path.size() == 1) 
    {
      // captures both "\" and "a"
      parts.push_back(path);
      return parts;
    }
    if (path[0] == '\\') 
    {
      if (path[1] == '\\') 
      {
        // case 2
        parts.push_back("\\\\");
        curpos = 2;
      } 
      else 
      {
        // case 1
        parts.push_back("\\");
        curpos = 1;
      }
    } 
    else 
    {
      if (path[1] == ':') 
      {
        if (path.size() > 2 && path[2] == '\\') 
        {
          // case 4
          parts.push_back(path.substr(0, 3));
          curpos = 3;
        } 
        else 
        {
          parts.push_back(path.substr(0, 2));
          curpos = 2;
        }
      }
    }          
#endif

    // simple tokenization based on separator. Note that "foo//bar" -> "foo", "", "bar"
    std::string::size_type newpos;
    while (curpos < path.size() && curpos != std::string::npos) 
    {
      // Be able to split on either separator including mixed separators on Windows
    #ifdef WIN32
      std::string::size_type p1 = path.find("\\", curpos);
      std::string::size_type p2 = path.find("/", curpos);
      newpos = p1 < p2 ? p1 : p2;
    #else
      newpos = path.find(Path::sep, curpos);
    #endif
    
      if (newpos == std::string::npos) 
      {
        parts.push_back(path.substr(curpos));
        curpos = newpos;
      } 
      else 
      {
        // note: if we have a "//" then newpos == curpos and this string is empty
        if (newpos != curpos) 
        {
          parts.push_back(path.substr(curpos, newpos - curpos));
        }
        curpos = newpos + 1;
      }
    }
    
    return parts;

  }