void ModificationDefinitionsSet::setModifications(const StringList & fixed_modifications, const StringList & variable_modifications)
{
    fixed_mods_.clear();
    variable_mods_.clear();

    if (!fixed_modifications.empty())
    {
        for (StringList::const_iterator it = fixed_modifications.begin(); it != fixed_modifications.end(); ++it)
        {
            ModificationDefinition def;
            def.setModification(*it);
            def.setFixedModification(true);
            fixed_mods_.insert(def);
        }
    }

    if (!variable_modifications.empty())
    {
        for (StringList::const_iterator it = variable_modifications.begin(); it != variable_modifications.end(); ++it)
        {
            ModificationDefinition def;
            def.setModification(*it);
            def.setFixedModification(false);
            variable_mods_.insert(def);
        }
    }
}
// Attempts to instance a decorator into a given list.
bool ElementDefinition::InstanceDecorator(const String& name, const String& type, const PropertyDictionary& properties, const StringList& pseudo_classes)
{
	Decorator* decorator = Factory::InstanceDecorator(type, properties);
	if (decorator == NULL)
	{
		Log::Message(Log::LT_WARNING, "Failed to instance decorator '%s' of type '%s'.", name.CString(), type.CString());
		return false;
	}

	if (pseudo_classes.empty())
	{
		if (decorator != NULL)
			decorators[name] = decorator;
	}
	else
	{
		PseudoClassDecoratorMap::iterator i = pseudo_class_decorators.find(pseudo_classes);
		if (i == pseudo_class_decorators.end())
		{
			DecoratorMap decorators;
			decorators[name] = decorator;

			pseudo_class_decorators[pseudo_classes] = decorators;
		}
		else
			(*i).second[name] = decorator;
	}

	return true;
}
Example #3
0
 /// set the file path to the primary MS run (usually the mzML file obtained after data conversion from raw files)
 void FeatureMap::setPrimaryMSRunPath(const StringList& s)
 {
   if (!s.empty())
   {
     this->setMetaValue("spectra_data", DataValue(s));
   }
 }
Example #4
0
	api_return ShareApi::handleFindDupePaths(ApiRequest& aRequest) {
		const auto& reqJson = aRequest.getRequestBody();

		json ret;

		StringList paths;
		auto path = JsonUtil::getOptionalField<string>("path", reqJson, false, false);
		if (path) {
			paths = ShareManager::getInstance()->getDirPaths(Util::toNmdcFile(*path));
		} else {
			auto tth = Deserializer::deserializeTTH(reqJson);
			paths = ShareManager::getInstance()->getRealPaths(tth);
		}

		if (!paths.empty()) {
			for (const auto& p : paths) {
				ret.push_back(p);
			}
		} else {
			ret = json::array();
		}

		aRequest.setResponseBody(ret);
		return websocketpp::http::status_code::ok;
	}
Example #5
0
bool AdcCommand::getParam(const char* name, size_t start, StringList& ret) const {
	for(string::size_type i = start; i < getParameters().size(); ++i) {
		if(toCode(name) == toCode(getParameters()[i].c_str())) {
			ret.push_back(getParameters()[i].substr(2));
		}
	}
	return !ret.empty();
}
Example #6
0
void WenboxPlugin::switchCurrentAudioDeviceToWenbox() {
	Config & config = ConfigManager::getInstance().getCurrentConfig();

	//Looks for the Wenbox audio device from the list of devices from the OS
	StringList wenboxAudioDeviceId = getWenboxOutputAudioDeviceId();
	if (!wenboxAudioDeviceId.empty()) {
		//Changes audio settings
		config.set(Config::WENBOX_AUDIO_OUTPUT_DEVICEID_KEY, wenboxAudioDeviceId);
		config.set(Config::WENBOX_AUDIO_RINGER_DEVICEID_KEY, wenboxAudioDeviceId);
	}

	wenboxAudioDeviceId = getWenboxInputAudioDeviceId();
	if (!wenboxAudioDeviceId.empty()) {
		//Changes audio settings
		config.set(Config::WENBOX_AUDIO_INPUT_DEVICEID_KEY, wenboxAudioDeviceId);
	}
}
Example #7
0
QString WulforUtil::getHubNames(const dcpp::CID &cid){
    StringList hubs = ClientManager::getInstance()->getHubNames(cid, "");

    if (hubs.empty())
        return tr("Offline");
    else
        return _q(Util::toString(hubs));
}
Example #8
0
void EntitiesEntity::getChildsStatement(const shared_ptr<IPortalDatabase> &database, const ObjectsTypes &types, const RangeUint32 &range, bool count, bool includeSystem, bool includeInvisible, shared_ptr<DbSqlSelect> &statement) const
{
	OS_LOCK(m_cs);

	// Nota: qui bisogna specificare sempre la tabella perch dall'esterno la select pu essere messa in join con altre tabelle

	shared_ptr<DbSqlSelect> select(OS_NEW DbSqlSelect(DBTABLES::SNAPSHOT_OBJECTS_TABLE));
	if(count)
		select->count = true;
	else
		select->fields.add(DbSqlField(DBTABLES::SNAPSHOT_OBJECTS::ENTITY, DBTABLES::SNAPSHOT_OBJECTS_TABLE));

	database->getPortal()->getSnapshotManager()->ensureChilds(database, getEntityID());
	select->where.add(DbSqlField(DBTABLES::SNAPSHOT_OBJECTS::PARENT, DBTABLES::SNAPSHOT_OBJECTS_TABLE), Convert::toSQL(getEntityID()));

	// Genera il filtro sui tipi di figli
	StringList childsTypes;
	for(ObjectsTypes::const_iterator i = types.begin(); i != types.end(); ++i)
	{
		if((*i) != portalObjectTypeUnknown)
			childsTypes.push_back(Convert::toSQL(static_cast<uint32>(*i)));
	}

	// Se  stato specificato un filtro sul tipo di figli lo applica
	if(childsTypes.empty() == false)
	{
		select->where.add(DbSqlField(DBTABLES::SNAPSHOT_OBJECTS::TYPE, DBTABLES::SNAPSHOT_OBJECTS_TABLE), childsTypes);
	}

	// Includi le sezioni di sistema (virtuali)?
	// Sono figlie della root, per cui la condizione ha senso solo in quel caso
	if(getEntityID() == ObjectsSystem::instance()->getRootID())
	{
		if(includeSystem == true)
		{
			// Salta la root stessa
			select->where.add(DbSqlField(DBTABLES::SNAPSHOT_OBJECTS::ENTITY, DBTABLES::SNAPSHOT_OBJECTS_TABLE), Convert::toSQL(ObjectsSystem::instance()->getRootID()), DbSqlCondition::cfDifferent | DbSqlCondition::cfAnd);
		}
		else
		{
			// VERYURGENT: Le classi statement non hanno una "not in"... poco male, ma userebbe meglio l'indice.
			select->where.add(DbSqlField(DBTABLES::SNAPSHOT_OBJECTS::INSERT_DATE, DBTABLES::SNAPSHOT_OBJECTS_TABLE), Convert::toSQL(DateTime::EMPTY), DbSqlCondition::cfDifferent | DbSqlCondition::cfAnd);
		}
	}

	if(includeInvisible == false)
		select->where.add(DbSqlField(DBTABLES::SNAPSHOT_OBJECTS::VISIBLE, DBTABLES::SNAPSHOT_OBJECTS_TABLE), Convert::toSQL(true));

	uint32 size = range.size();
	if(size != 0)
		select->limit.setCount(size);

	uint32 start = range.start();
	if(start != 0)
		select->limit.setOffset(start);

	statement = select;
}
Example #9
0
// Get user channels.
void meth::GetUserChannels(LogicalConnections::iterator conn, String &response) {
	StringList channels = ::GetUserChannels(GetConnectionUserName(conn));

	if (!channels.empty()) {
		response = "[" + implode(channels) + "]";
	} else {
		response = "null";
	}
}
 String AbstractFileManager::joinComponents(const StringList& pathComponents) {
     if (pathComponents.empty())
         return "";
     StringStream result;
     for (unsigned int i = 0; i < pathComponents.size() - 1; i++)
         result << pathComponents[i] << pathSeparator();
     result << pathComponents.back();
     
     return result.str();
 }
Example #11
0
Program::Pointer ProgramFactory::loadProgram(const std::string& file, ObjectsCache& cache,
	const StringList& defines)
{
	auto cachedPrograms = cache.findObjects(file);
	for (Program::Pointer cached : cachedPrograms)
	{
		if (cached.valid())
		{
			if (cached->defines().size() == defines.size())
			{
				bool same = true;
				for (auto& inDefine : defines)
				{
					for (auto& cDefine : cached->defines())
					{
						if (inDefine != cDefine)
						{
							same = false;
							break;
						}
						
						if (!same)
							break;
					}
				}
				if (same)
					return cached;
			}
		}
	}
	
	std::string vertex_shader;
	std::string geom_shader;
	std::string frag_shader;

	StringList sourceFiles = loadProgramSources(file, vertex_shader, geom_shader, frag_shader);
	
	if (sourceFiles.empty())
		return Program::Pointer::create(renderContext());
	
	std::string workFolder = getFilePath(file);
	
	parseSourceCode(ShaderType_Vertex, vertex_shader, defines, workFolder);
	parseSourceCode(ShaderType_Geometry, geom_shader, defines, workFolder);
	parseSourceCode(ShaderType_Fragment, frag_shader, defines, workFolder);
	
	Program::Pointer program = Program::Pointer::create(renderContext(), vertex_shader, geom_shader,
		frag_shader, getFileName(file), file, defines);
	
	for (auto& s : sourceFiles)
		program->addOrigin(s);
	
	cache.manage(program, _private->loader);
	return program;
}
Example #12
0
void Transfer::getParams(const UserConnection& aSource, StringMap& params) {
    params["userCID"] = aSource.getUser()->getCID().toBase32();
    params["userNI"] = Util::toString(ClientManager::getInstance()->getNicks(aSource.getUser()->getCID(), aSource.getHubUrl()));
    params["userI4"] = aSource.getRemoteIp();
    StringList hubNames = ClientManager::getInstance()->getHubNames(aSource.getUser()->getCID(), aSource.getHubUrl());
    if(hubNames.empty())
        hubNames.push_back(_("Offline"));
    params["hub"] = Util::toString(hubNames);
    StringList hubs = ClientManager::getInstance()->getHubs(aSource.getUser()->getCID(), aSource.getHubUrl());
    if(hubs.empty())
        hubs.push_back(_("Offline"));
    params["hubURL"] = Util::toString(hubs);
    params["fileSI"] = Util::toString(getSize());
    params["fileSIshort"] = Util::formatBytes(getSize());
    params["fileSIactual"] = Util::toString(getActual());
    params["fileSIactualshort"] = Util::formatBytes(getActual());
    params["speed"] = str(F_("%1%/s") % Util::formatBytes(getAverageSpeed()));
    params["time"] = Util::formatSeconds((GET_TICK() - getStart()) / 1000);
    params["fileTR"] = getTTH().toBase32();
}
Example #13
0
void
herschel::xml::displayStringList(Port<Octet>& port,
                                zstring outerTagName, zstring tagName,
                                const StringList& strlist)
{
  if (!strlist.empty())
    displayOpenTag(port, outerTagName);

  for (StringList::const_iterator it = strlist.begin();
       it != strlist.end();
       it++)
  {
    String str = (*it);
    displayOpenTag(port, tagName, !K(newline));
    herschel::display(port, str);
    displayCloseTag(port, tagName);
  }

  if (!strlist.empty())
    displayCloseTag(port, outerTagName);
}
Example #14
0
  ExitCodes main_(int, const char**) override
  {
    StringList in  = getStringList_("in");
    StringList out = getStringList_("out");
    bool inplace = getFlag_("i");

    // consistency checks
    if (out.empty() && !inplace)
    {
      writeLog_("Cannot write output files, as neither -out nor -i are given. Use either of them, but not both!");
      printUsage_();
      return ILLEGAL_PARAMETERS;
    }
    if (out.size() > 0 && inplace)
    {
      writeLog_("Two incompatible arguments given (-out and -i). Use either of them, but not both!");
      printUsage_();
      return ILLEGAL_PARAMETERS;
    }

    if (!inplace && out.size() != in.size())
    {
      writeLog_("Output and input file list length must be equal!");
      printUsage_();
      return ILLEGAL_PARAMETERS;
    }

    // do the conversion!
    FileHandler fh;
    for (Size i = 0; i < in.size(); ++i)
    {
      FileTypes::Type f_type = fh.getType(in[i]);
      if (f_type == FileTypes::INI) updateINI(in[i], inplace ? "" : out[i]);
      else if (f_type == FileTypes::TOPPAS) updateTOPPAS(in[i], inplace ? "" : out[i]);
    }

    for (Size i = 0; i < tmp_files_.size(); ++i)
    {
      // clean up
      File::remove(tmp_files_[i]);
    }


    if (failed_.size() > 0)
    {
      writeLog_("The following INI/TOPPAS files could not be updated:\n  " + ListUtils::concatenate(failed_, "\n  "));
      return INPUT_FILE_CORRUPT;
    }

    return EXECUTION_OK;

  }
 StringList AbstractFileManager::resolvePath(const StringList& pathComponents) {
     StringList cleanComponents;
     for (unsigned int i = 0; i < pathComponents.size(); i++) {
         const String& component = pathComponents[i];
         if (component != ".") {
             if (component == ".." && !cleanComponents.empty())
                 cleanComponents.pop_back();
             else
                 cleanComponents.push_back(component);
         }
     }
     return cleanComponents;
 }
Example #16
0
void SearchManager::onRES(const AdcCommand& cmd, const UserPtr& from, const string& remoteIp) {
    int freeSlots = -1;
    int64_t size = -1;
    string file;
    string tth;
    string token;

    for(StringIterC i = cmd.getParameters().begin(); i != cmd.getParameters().end(); ++i) {
        const string& str = *i;
        if(str.compare(0, 2, "FN") == 0) {
            file = Util::toNmdcFile(str.substr(2));
        } else if(str.compare(0, 2, "SL") == 0) {
            freeSlots = Util::toInt(str.substr(2));
        } else if(str.compare(0, 2, "SI") == 0) {
            size = Util::toInt64(str.substr(2));
        } else if(str.compare(0, 2, "TR") == 0) {
            tth = str.substr(2);
        } else if(str.compare(0, 2, "TO") == 0) {
            token = str.substr(2);
        }
    }

    if(!file.empty() && freeSlots != -1 && size != -1) {

        /// @todo get the hub this was sent from, to be passed as a hint? (eg by using the token?)
        StringList names = ClientManager::getInstance()->getHubNames(from->getCID(), Util::emptyString);
        string hubName = names.empty() ? _("Offline") : Util::toString(names);
        StringList hubs = ClientManager::getInstance()->getHubs(from->getCID(), Util::emptyString);
        string hub = hubs.empty() ? _("Offline") : Util::toString(hubs);

        SearchResult::Types type = (file[file.length() - 1] == '\\' ? SearchResult::TYPE_DIRECTORY : SearchResult::TYPE_FILE);
        if(type == SearchResult::TYPE_FILE && tth.empty())
            return;
        /// @todo Something about the slots
        SearchResultPtr sr(new SearchResult(from, type, 0, freeSlots, size,
            file, hubName, hub, remoteIp, TTHValue(tth), token));
        fire(SearchManagerListener::SR(), sr);
    }
}
Example #17
0
void Transfer::getParams(const UserConnection& aSource, StringMap& params) const {
	params["userCID"] = aSource.getUser()->getCID().toBase32();
	params["userNI"] = Util::toString(ClientManager::getInstance()->getNicks(aSource.getUser()->getCID(), aSource.getHubUrl()));
	params["userI4"] = aSource.getRemoteIp();
	StringList hubNames = ClientManager::getInstance()->getHubNames(aSource.getUser()->getCID(), aSource.getHubUrl());
	if(hubNames.empty())
		hubNames.push_back(STRING(OFFLINE));
	params["hub"] = Util::toString(hubNames);
	StringList hubs = ClientManager::getInstance()->getHubs(aSource.getUser()->getCID(), aSource.getHubUrl());
	if(hubs.empty())
		hubs.push_back(STRING(OFFLINE));
	params["hubURL"] = Util::toString(hubs);
	params["fileSI"] = Util::toString(getSize());
	params["fileSIshort"] = Util::formatBytes(getSize());
	params["fileSIchunk"] = Util::toString(getPos());
	params["fileSIchunkshort"] = Util::formatBytes(getPos());
	params["fileSIactual"] = Util::toString(getActual());
	params["fileSIactualshort"] = Util::formatBytes(getActual());
	params["speed"] = Util::formatBytes(static_cast<int64_t>(getAverageSpeed())) + "/s";
	params["time"] = Text::fromT(Util::formatSeconds((GET_TICK() - getStart()) / 1000));
	params["fileTR"] = getTTH().toBase32();
}
Example #18
0
int main(int argc, char *argv[]) {
	StringList excludeGlobalFunctions;
	StringList luaFiles;
	std::string globalExcludeFunctionFileName;
	std::string tocFileName;
	std::string addonDir;
	stObfuscatorSetting settings;

	srand(static_cast<unsigned int>(time(NULL)));

	parseArguments(argc, argv, tocFileName, addonDir, globalExcludeFunctionFileName, luaFiles, settings);

	print("Addon dir: %s\n", addonDir.c_str());
	print("Work dir: %s\n", getWorkDir());

	LuaObfuscator::readAddonGlobalExcludeFunctions(globalExcludeFunctionFileName.c_str(), excludeGlobalFunctions);

	LuaObfuscator::readAddonTocFile(tocFileName.c_str(), luaFiles);

	// add absolute path name, if need
	//validateFileNames(luaFiles, addonDir.c_str());

	if (luaFiles.empty()) {
		printHelp();
		printf("\nNo a files for an obfuscating\n");
		return -1;
	}

	try {
		LuaObfuscator obfuscator(luaFiles, excludeGlobalFunctions, addonDir);

		print("create bak file:        %d\n", settings.bCreateBakFile);
		print("create one file:        %d\n", settings.bCreateOneFile);
		print("obfuscate const int:    %d\n", settings.ObfuscateConstInt);
		print("obfuscate const float:  %d\n", settings.ObfuscateConstFloat);
		print("obfuscate const string: %d\n", settings.ObfuscateConstString);
		print("obfuscate local vars:   %d\n", settings.ObfuscateLocalVasAndParam);
		print("obfuscate global fucntions: %d\n", settings.ObfuscateGlobalFunctionName);

		obfuscator.obfuscate(settings);
	}
	catch (std::exception) {
		print("ERROR: obfuscator creating fail\n");
	}

#ifdef _DEBUG
	getchar();
#endif

	return 0;
}
Example #19
0
/**
 * Note: intended to be used with fsck only
 */
bool StorageTkEx::getNextContDirID(unsigned hashDirNum, int64_t lastOffset, std::string* outID,
   int64_t* outNewOffset)
{
   *outID = "";
   StringList outIDs;
   FhgfsOpsErr retVal = getContDirIDsIncremental(hashDirNum, lastOffset, 1, &outIDs,
      outNewOffset);
   if ( ( outIDs.empty() ) ||  ( retVal != FhgfsOpsErr_SUCCESS ) )
      return false;
   else
   {
      *outID = outIDs.front();
      return true;
   }
}
Example #20
0
void SearchManager::onRES(const AdcCommand& cmd, const UserPtr& from, const string& remoteIp) {
	int freeSlots = -1;
	int64_t size = -1;
	string file;
	string tth;
	string token;

	for(auto& str: cmd.getParameters()) {
		if(str.compare(0, 2, "FN") == 0) {
			file = Util::toNmdcFile(str.substr(2));
		} else if(str.compare(0, 2, "SL") == 0) {
			freeSlots = Util::toInt(str.substr(2));
		} else if(str.compare(0, 2, "SI") == 0) {
			size = Util::toInt64(str.substr(2));
		} else if(str.compare(0, 2, "TR") == 0) {
			tth = str.substr(2);
		} else if(str.compare(0, 2, "TO") == 0) {
			token = str.substr(2);
		}
	}

	if(file.empty() || freeSlots == -1 || size == -1) { return; }

	auto type = (*(file.end() - 1) == '\\' ? SearchResult::TYPE_DIRECTORY : SearchResult::TYPE_FILE);
	if(type == SearchResult::TYPE_FILE && tth.empty()) { return; }

	string hubUrl;

	// token format: [per-hub unique id] "/" [per-search actual token] (see AdcHub::search)
	auto slash = token.find('/');
	if(slash == string::npos) { return; }
	{
		auto uniqueId = Util::toUInt32(token.substr(0, slash));
		auto lock = ClientManager::getInstance()->lock();
		auto& clients = ClientManager::getInstance()->getClients();
		auto i = boost::find_if(clients, [uniqueId](const Client* client) { return client->getUniqueId() == uniqueId; });
		if(i == clients.end()) { return; }
		hubUrl = (*i)->getHubUrl();
	}
	token.erase(0, slash + 1);

	StringList names = ClientManager::getInstance()->getHubNames(from->getCID());
	string hubName = names.empty() ? _("Offline") : Util::toString(names);

	/// @todo Something about the slots
	fire(SearchManagerListener::SR(), SearchResultPtr(new SearchResult(HintedUser(from, hubUrl),
		type, 0, freeSlots, size, file, hubName, remoteIp, TTHValue(tth), token)));
}
Example #21
0
void MsgHelperRepair::createDefDirInodes(Node* node, StringList* inodeIDs,
   FsckDirInodeList* createdInodes)
{
   const char* logContext = "MsgHelperRepair (createDefDirInodes)";

   StringList failedInodeIDs;

   bool commRes;
   char *respBuf = NULL;
   NetMessage *respMsg = NULL;

   CreateDefDirInodesMsg createDefDirInodesMsgEx(inodeIDs);

   commRes = MessagingTk::requestResponse(node, &createDefDirInodesMsgEx,
      NETMSGTYPE_CreateDefDirInodesResp, &respBuf, &respMsg);

   if ( commRes )
   {
      CreateDefDirInodesRespMsg* createDefDirInodesRespMsg = (CreateDefDirInodesRespMsg*) respMsg;

      // parse failed creates
      createDefDirInodesRespMsg->parseFailedInodeIDs(&failedInodeIDs);

      // parse created inodes
      createDefDirInodesRespMsg->parseCreatedInodes(createdInodes);

      SAFE_FREE(respBuf);
      SAFE_DELETE(respMsg);
   }
   else
   {
      SAFE_FREE(respBuf);
      SAFE_DELETE(respMsg);

      failedInodeIDs = *inodeIDs;

      LogContext(logContext).logErr("Communication error occured with node: " + node->getID());
   }

   if (! failedInodeIDs.empty())
   {
      for (StringListIter iter = failedInodeIDs.begin(); iter != failedInodeIDs.end(); iter++)
      {
         LogContext(logContext).log(Log_CRITICAL, "Failed to create default directory inode on "
            "metadata node: " + node->getID() + " entryID: " + *iter);
      }
   }
}
Example #22
0
void ProgramFactory::reloadObject(LoadableObject::Pointer obj, ObjectsCache&)
{
	std::string vertex_shader;
	std::string geom_shader;
	std::string frag_shader;
	
	StringList sourceFiles = loadProgramSources(obj->origin(), vertex_shader, geom_shader, frag_shader);
	if (sourceFiles.empty()) return;
	
	// TODO: handle defines
	std::string workFolder = getFilePath(obj->origin());
	parseSourceCode(ShaderType_Vertex, vertex_shader, StringList(), workFolder);
	parseSourceCode(ShaderType_Geometry, geom_shader, StringList(), workFolder);
	parseSourceCode(ShaderType_Fragment, frag_shader, StringList(), workFolder);
	
	Program::Pointer(obj)->buildProgram(vertex_shader, geom_shader, frag_shader);
}
Example #23
0
 String DefParser::typeNames(unsigned int types) {
     StringList names;
     if ((types & Integer) != 0)
         names.push_back("integer number");
     if ((types & Decimal) != 0)
         names.push_back("decimal number");
     if ((types & QuotedString) != 0)
         names.push_back("string");
     if ((types & OParenthesis) != 0)
         names.push_back("opening parenthesis");
     if ((types & CParenthesis) != 0)
         names.push_back("closing parenthesis");
     if ((types & OBrace) != 0)
         names.push_back("opening brace");
     if ((types & CBrace) != 0)
         names.push_back("closing brace");
     if ((types & Word) != 0)
         names.push_back("word");
     if ((types & Question) != 0)
         names.push_back("question mark");
     if ((types & ODefinition) != 0)
         names.push_back("definition start ('/*')");
     if ((types & CDefinition) != 0)
         names.push_back("definition end ('*/')");
     if ((types & Semicolon) != 0)
         names.push_back("semicolon");
     if ((types & Newline) != 0)
         names.push_back("newline");
     if ((types & Comma) != 0)
         names.push_back("comma");
     if ((types & Equality) != 0)
         names.push_back("equality sign");
     
     if (names.empty())
         return "unknown token type";
     if (names.size() == 1)
         return names[0];
     
     StringStream str;
     str << names[0];
     for (unsigned int i = 1; i < names.size() - 1; i++)
         str << ", " << names[i];
     str << ", or " << names[names.size() - 1];
     return str.str();
 }
String sanitizePath(const String &path)
{
  // Standardize slashes to POSIX style
  String fixedPath = posixPath(path);

  // Check if path is absolute
  bool isAbsolute = isAbsolutePath(fixedPath);

  // Tokenize path
  StringList pathComponents;
  std::size_t start = 0;
  do {
    std::size_t separator = (std::min)(fixedPath.find('/', start), fixedPath.length());
    String token = fixedPath.substr(start, separator - start);
    if (token.empty() || token == ".") {
      // a/./b -> a/b and a//b -> a/b
    } else if (token == "..") {
      if (pathComponents.empty()) {
        // ../a -> ../a
        // /../a -> /a
        if (!isAbsolute)
          pathComponents.push_back(token);
      } else {
        // ../../a -> ../../a
        // a/../c -> c
        if (pathComponents.back() == "..")
          pathComponents.push_back(token);
        else
          pathComponents.pop_back();
      }
    } else {
      pathComponents.push_back(token);
    }

    start = separator + 1;
  } while (start < path.length());

  // Figure out if we need to add a leading slash
  String prefix;
  if (strBeginsWith(fixedPath, "/"))
    prefix = "/";

  // Return reassembled path
  return prefix + joinStrings(pathComponents, "/");
}
// Registers a shorthand property definition.
bool PropertySpecification::RegisterShorthand(const String& shorthand_name, const String& property_names, ShorthandType type)
{
	StringList properties;
	StringUtilities::ExpandString(properties, property_names.ToLower());

	if (properties.empty())
		return false;

	String lower_case_name = shorthand_name.ToLower();

	// Construct the new shorthand definition and resolve its properties.
	PropertyShorthandDefinition* property_shorthand = new PropertyShorthandDefinition();
	for (size_t i = 0; i < properties.size(); i++)
	{
		const PropertyDefinition* property = GetProperty(properties[i]);
		if (property == NULL)
		{
			Log::Message(Log::LT_ERROR, "Shorthand property '%s' was registered with invalid property '%s'.", shorthand_name.CString(), properties[i].CString());
			delete property_shorthand;

			return false;
		}

		property_shorthand->properties.push_back(PropertyShorthandDefinition::PropertyDefinitionList::value_type(properties[i], property));
	}

	if (type == AUTO)
	{
		if (properties.size() == 4 &&
			properties[0].Find("-top") != String::npos &&
			properties[1].Find("-right") != String::npos &&
			properties[2].Find("-bottom") != String::npos &&
			properties[3].Find("-left") != String::npos)
			property_shorthand->type = BOX;
		else
			property_shorthand->type = FALL_THROUGH;
	}
	else
		property_shorthand->type = type;

	shorthands[lower_case_name] = property_shorthand;
	return true;
}
Example #26
0
 String SimpleAutomatonParser::tokenName(const SimpleAutomatonToken::Type typeMask) const {
     StringList names;
     
     if (typeMask | SimpleAutomatonToken::Comma)
         names.push_back("','");
     if (typeMask | SimpleAutomatonToken::Semicolon)
         names.push_back("';'");
     if (typeMask | SimpleAutomatonToken::Identifier)
         names.push_back("identifier");
     
     for (size_t i = 0; i < 11; ++i)
         if (typeMask | SimpleAutomatonTokenMappings[i].type)
             names.push_back("'" + String(SimpleAutomatonTokenMappings[i].str, SimpleAutomatonTokenMappings[i].len) + "'");
     if (names.empty())
         return "unknown token type";
     if (names.size() == 1)
         return names[0];
     
     return StringUtils::join(names, ", ");
 }
Example #27
0
void DefaultHttpHeader::set(const std::string& name, const StringList& values) {
    if (values.empty()) {
        return;
    }

    validateHeaderName(name);

    int h = hash(name);
    int i = index(h);

    removeHeader(h, i, name);

    for (size_t i = 0; i < values.size(); ++i) {
        if (values[i].empty()) {
            break;
        }

        HttpCodecUtil::validateHeaderValue(values[i]);
        addHeader(h, i, name, values[i]);
    }
}
Example #28
0
Path& Path::normalize()
{
	StringTokenizer tokenizer(_path);
	tokenizer.onCharset("/");

	std::string elem;

	StringList parts;

	while(tokenizer.next(elem))
	{
		if(elem == ".." && ! parts.empty())
			parts.pop();
		else if(elem != ".")
			parts << elem;
	}

	_path = parts.join('/');

	return *this;
}
Example #29
0
ParseV2::ParseV2(const char* file_name) :
file_(file_name)
{
	// For each line in the file, read it in and try to make sense of it
	// based on the indent level and the leading verb.
	//cout << "TRACE: parsing SSQLS v2 file " << file_name << '.' << endl;
	string line;
	bool subdirective;
	while (file_.read_line(line, subdirective)) {
		// Skip empty lines
		if (line.empty()) continue;

		// Break line up into whitespace-separated tokens
		StringList tokens;
		tokenize(tokens, line);
		if (tokens.empty()) continue;		// shouldn't happen

		// Try to interpret token list
		Line* line = Line::parse(tokens, subdirective, file_);
		assert(line != 0);	// errors should be signalled with exceptions
		Include* iline = dynamic_cast<Include*>(line);
		if (iline) {
			// Include lines are a special case: we hoist the parsed
			// lines from the included file up into our line list.
			lines_.reserve(lines_.size() + (iline->end() - iline->begin()));
			for (LineListIt it = iline->begin(); it != iline->end(); ++it) {
				lines_.push_back(*it);
			}
			delete iline;
		}
		else {
			// Normal case: add line to our line list
			lines_.push_back(line);
		}
	}
}
Example #30
0
static void
generate(const UnitPtr& un, bool all, bool checksum, bool ns, const vector<string>& includePaths, Output& out)
{
    if(!all)
    {
        vector<string> paths = includePaths;
        for(vector<string>::iterator p = paths.begin(); p != paths.end(); ++p)
        {
            *p = fullPath(*p);
        }

        StringList includes = un->includeFiles();
        if(!includes.empty())
        {
            if(ns)
            {
                out << sp;
                out << nl << "namespace";
                out << sb;
            }
            for(StringList::const_iterator q = includes.begin(); q != includes.end(); ++q)
            {
                string file = changeInclude(*q, paths);
                out << nl << "require_once '" << file << ".php';";
            }
            if(ns)
            {
                out << eb;
            }
        }
    }

    CodeVisitor codeVisitor(out, ns);
    un->visit(&codeVisitor, false);

    if(checksum)
    {
        ChecksumMap checksums = createChecksums(un);
        if(!checksums.empty())
        {
            out << sp;
            if(ns)
            {
                out << "namespace"; // Global namespace.
                out << sb;
            }
            for(ChecksumMap::const_iterator p = checksums.begin(); p != checksums.end(); ++p)
            {
                out << nl << "$Ice_sliceChecksums[\"" << p->first << "\"] = \"";
                ostringstream str;
                str.flags(ios_base::hex);
                str.fill('0');
                for(vector<unsigned char>::const_iterator q = p->second.begin(); q != p->second.end(); ++q)
                {
                    str << (int)(*q);
                }
                out << str.str() << "\";";
            }
            if(ns)
            {
                out << eb;
            }
        }
    }

    out << nl; // Trailing newline.
}