Esempio n. 1
0
//native regex_replace(Regex:pattern, string[], maxLen, const replace[], flags = REGEX_FORMAT_DEFAULT, &errcode = 0);
static cell AMX_NATIVE_CALL regex_replace(AMX *amx, cell *params)
{
	int id = params[1] - 1;
	if (id >= (int)PEL.length() || id < 0 || PEL[id]->isFree())
	{
		MF_LogError(amx, AMX_ERR_NATIVE, "Invalid regex handle %d", id);
		return 0;
	}

	int textLen, replaceLen;
	char *text = MF_GetAmxString(amx, params[2], 0, &textLen);
	const char *replace = MF_GetAmxString(amx, params[4], 1, &replaceLen);

	cell *erroCode = MF_GetAmxAddr(amx, params[6]);

	RegEx *x = PEL[id]; 
	int e = x->Replace(text, params[3] + 1, replace, replaceLen, params[5]);

	if (e == -1)
	{
		*erroCode = x->mErrorOffset;
		x->ClearMatch();
		return -2;
	}
	else if (e == 0)
	{
		*erroCode = 0;
		x->ClearMatch();
		return 0;
	}

	MF_SetAmxString(amx, params[2], text, params[3]);

	return e;
}
Esempio n. 2
0
void RegexHandler::OnHandleDestroy(HandleType_t type, void *object)
{
	RegEx *x = (RegEx *)object;

	x->Clear();
	delete x;
}
Esempio n. 3
0
/**
*  @brief
*    Reads memory information from the '/proc/meminfo'-file
*/
bool SystemLinux::GetMemoryInformation(MemoryInformation &sMemoryInformation) const
{
	// Initialize memory information
	sMemoryInformation.nTotalPhysicalMemory	= 0;
	sMemoryInformation.nFreePhysicalMemory	= 0;
	sMemoryInformation.nTotalSwapMemory		= 0;
	sMemoryInformation.nFreeSwapMemory		= 0;

	// Parse kernel information file
	File cFile("/proc/meminfo");
	if (cFile.Open(File::FileRead | File::FileText)) {
		static RegEx cRegEx("^\\s*(MemTotal|MemFree|SwapTotal|SwapFree):\\s*(\\d+).*$");
		while (!cFile.IsEof()) {
			const String sLine = cFile.GetS();
			if (cRegEx.Match(sLine)) {
				const String sName   = cRegEx.GetResult(0);
				const String sResult = cRegEx.GetResult(1);
				if (sName == "MemTotal")
					sMemoryInformation.nTotalPhysicalMemory = sResult.GetInt() * 1024;
				if (sName == "MemFree")
					sMemoryInformation.nFreePhysicalMemory = sResult.GetInt() * 1024;
				if (sName == "SwapTotal")
					sMemoryInformation.nTotalSwapMemory = sResult.GetInt() * 1024;
				if (sName == "SwapFree")
					sMemoryInformation.nFreeSwapMemory = sResult.GetInt() * 1024;
			}
		}

		// Done
		return true;
	}

	// Error!
	return false;
}
Esempio n. 4
0
static cell_t CompileRegex(IPluginContext *pCtx, const cell_t *params)
{
	char *regex;
	pCtx->LocalToString(params[1], &regex);

	RegEx *x = new RegEx();
	
	if (x->Compile(regex, params[2]) == 0)
	{
		cell_t *eError;
		pCtx->LocalToPhysAddr(params[5], &eError);
		const char *err = x->mError;
		// Convert error code to posix error code but use pcre's error string since it is more detailed.
		*eError = pcre_posix_compile_error_map[x->mErrorCode];
		pCtx->StringToLocal(params[3], params[4], err ? err:"unknown");
		delete x;
		return 0;
	}

	HandleError error = HandleError_None;
	Handle_t regexHandle = g_pHandleSys->CreateHandle(g_RegexHandle, (void*)x, pCtx->GetIdentity(), myself->GetIdentity(), &error);
	if (!regexHandle || error != HandleError_None)
	{
		delete x;
		pCtx->ReportError("Allocation of regex handle failed, error code #%d", error);
		return 0;
	}
	
	return regexHandle;
}
Esempio n. 5
0
// native regex_substr(Regex:id, str_id, buffer[], maxLen);
static cell AMX_NATIVE_CALL regex_substr(AMX *amx, cell *params)
{
	int id = params[1]-1;
	if (id >= (int)PEL.length() || id < 0 || PEL[id]->isFree())
	{
		MF_LogError(amx, AMX_ERR_NATIVE, "Invalid regex handle %d", id);
		return 0;
	}

	RegEx *x = PEL[id];
	static char buffer[16384]; // Same as AMXX buffer.

	size_t length;
	size_t maxLength = ke::Min<size_t>(params[4], sizeof(buffer) - 1);

	const char *ret = x->GetSubstring(params[2], buffer, maxLength, &length);

	if (ret == NULL)
	{
		return 0;
	}

	if (length >= maxLength && ret[length - 1] & 1 << 7)
	{
		maxLength -= UTIL_CheckValidChar((char *)ret + length - 1);
	}

	MF_SetAmxString(amx, params[3], ret, maxLength);

	return 1;
}
UtlBoolean
ValidateMailboxCGIHelper::isNumeric( const UtlString& mailboxIdentity ) const
{
    UtlString userid ;
    getUserId( mailboxIdentity, userid ) ;

    static RegEx sAllDigits("^\\d+$");

    return sAllDigits.Search(userid.data());
}
Esempio n. 7
0
static cell_t MatchRegexAll(IPluginContext *pCtx, const cell_t *params)
{
	Handle_t hndl = static_cast<Handle_t>(params[1]);
	HandleError err;
	HandleSecurity sec;
	sec.pOwner = NULL;
	sec.pIdentity = myself->GetIdentity();

	RegEx *x;

	if ((err = g_pHandleSys->ReadHandle(hndl, g_RegexHandle, &sec, (void **)&x)) != HandleError_None)
	{
		return pCtx->ThrowNativeError("Invalid regex handle %x (error %d)", hndl, err);
	}

	if (!x)
	{
		pCtx->ThrowNativeError("Regex data not found\n");

		return 0;
	}

	char *str;
	pCtx->LocalToString(params[2], &str);

	int e = x->MatchAll(str);

	if (e == -1)
	{
		/* there was a match error.  move on. */
		cell_t *res;
		pCtx->LocalToPhysAddr(params[3], &res);
		*res = x->mErrorCode;
		/* only clear the match results, since the regex object
		may still be referenced later */
		x->ClearMatch();

		return -1;
	}
	else if (e == 0)
	{
		/* only clear the match results, since the regex object
		may still be referenced later */
		x->ClearMatch();

		return 0;
	}
	else
	{
		return x->mMatchCount;
	}
}
Esempio n. 8
0
String EmotHandler::parse(const StringRef& body) {
  RegEx reg;
  reg.setSubject(prepareBody(body));

  for (tPackages::iterator it = _packages.begin(); it != _packages.end(); it++) {
    parseSet(reg, (eMSet&) **it);
  }

  reg.replaceItself("#<kiev2:emot:insertion id=\"([0-9]+)\" />#", &EmotHandler::replaceEmot, 0, (void*) this);
  emotInsertions.clear();

  return prepareBody(reg.getSubject(), false);
}
Esempio n. 9
0
void EmotHandler::parseSet(RegEx& reg, eMSet& set) {
  if (!set.isEnabled()) return;

  for (eMSet::tEmots::iterator it = set.getEmots().begin(); it != set.getEmots().end(); it++) {
    sEmotInsertion ei(emotInsertions.size(), &*it, &set);
    try {
      reg.setPattern(prepareBody(!it->isPreg() ? "/" + reg.addSlashes(it->getText()) + "/i" : it->getText(), true, false));
      reg.replaceItself(&EmotHandler::emotInsertion, 0, (void*) &ei);
    } catch (const RegEx::CompileException& e) {
      IMLOG("[EmotHandler::parseSet()] B³¹d definicji emotikony: %s, pos %i", e.error, e.pos);
      continue;
    }
    emotInsertions.push_back(ei);
  }
}
Esempio n. 10
0
static cell AMX_NATIVE_CALL regex_free(AMX *amx, cell *params)
{
	cell *c = MF_GetAmxAddr(amx, params[1]);
	int id = *c;
	*c = 0;
	id -= 1;
	if (id >= (int)PEL.length() || id < 0 || PEL[id]->isFree())
	{
		MF_LogError(amx, AMX_ERR_NATIVE, "Invalid regex handle %d", id);
		return 0;
	}

	RegEx *x = PEL[id];
	x->Clear();

	return 1;
}
Esempio n. 11
0
iPackage* GGParser::parse(const FindFile::Found& defFile) {
    ifstream file(defFile.getFilePath().c_str());
    string buff;

    if (!file.is_open()) {
        throw CannotOpen("Cannot open file " + defFile.getFilePath());
    }

    bool inMenu;
    eMSet result;
    RegEx reg;

    while (!file.eof()) {
        getline(file, buff);
        eMSet::tEmots emots;

        if (buff[0] == '*') {
            inMenu = false;
            buff.erase(0);
        } else {
            inMenu = true;
        }

        reg.setSubject(buff);
        reg.setPattern("/,?\"(.+?)\",?/");

        while (reg.match_global()) {
            eM emot(inMenu, reg[1][0] == '/');
            emot.setText(reg[1].c_str());
            emots.push_back(emot);

            if (reg.getSubject()[reg.getStart()] == ')' || buff[0] != '(') {
                string img_path;
                string menu_img_path;

                if (reg.match_global()) {
                    img_path = reg[1];
                    menu_img_path = reg.match_global() ? reg[1] : "";

                    for (eMSet::tEmots::iterator it = emots.begin(); it != emots.end(); it++) {
                        if (menu_img_path.length()) it->setMenuImgPath(defFile.getDirectory() + menu_img_path);
                        it->setImgPath(defFile.getDirectory() + img_path);
                    }
                } else {
                    throw WrongFormat("Brak œcie¿ki do obrazka");
                }
                break;
            }
        }
        result.getEmots().insert(result.getEmots().end(), emots.begin(), emots.end());
    }
    file.close();

    return new eMSet(result);
}
Esempio n. 12
0
// native Regex:regex_compile_ex(const pattern[], flags = 0, error[] = "", maxLen = 0, &errcode = 0);
static cell AMX_NATIVE_CALL regex_compile_ex(AMX *amx, cell *params)
{
	int len;
	const char *regex = MF_GetAmxString(amx, params[1], 0, &len);

	int id = GetPEL();
	RegEx *x = PEL[id];

	if (x->Compile(regex, params[2]) == 0)
	{
		const char *err = x->mError;
		*MF_GetAmxAddr(amx, params[5]) = x->mErrorOffset;
		MF_SetAmxString(amx, params[3], err ? err : "unknown", params[4]);
		return -1;
	}

	return id + 1;
}
Esempio n. 13
0
UtlBoolean
SubscriptionAuth::isTargetExemptedFromAuthentication(const UtlString& targetUser) const
{
   UtlBoolean targetExempted = FALSE;
   UtlSListIterator nextTargetRegEx(mTargetsExemptedFromAuthentication);

   RegEx* targetRegEx;
   
   while((targetRegEx = dynamic_cast<RegEx*>(nextTargetRegEx())))
   {
      if(targetRegEx->Search(targetUser.data()))
      {
         targetExempted = TRUE;
         break;
      }
   }

   return targetExempted;
}
Esempio n. 14
0
uint32 SystemLinux::GetCPUMhz() const
{
	// Initialize
	uint32 nMhz = 0;

	// Parse kernel information file
	File cFile("/proc/cpuinfo");
	if (cFile.Open(File::FileRead | File::FileText)) {
		static RegEx cRegEx("^\\s*cpu MHz\\s*:\\s*(\\d+(\\.\\d+)).*$");
		while (!cFile.IsEof()) {
			const String sLine = cFile.GetS();
			if (cRegEx.Match(sLine)) {
				const String sResult = cRegEx.GetResult(0);
				nMhz = sResult.GetInt();
			}
		}
	}

	// Done
	return nMhz;
}
Esempio n. 15
0
/**
*  @brief
*    Parse next parameter
*/
bool ParamsParser::Next()
{
	// Parse next expression
	if (m_nParsePos > -1 && m_cRegEx.Match(m_sParameters, m_nParsePos)) {
		// Get expression and new parse position
		m_nParsePos			= m_cRegEx.GetPosition();
		String sExpression	= m_cRegEx.GetResult(0);

		// Process the found expression
		if (sExpression[sExpression.GetLength()-1] == '\'') {
			static RegEx cRegEx("\\s*(\\w*)\\s*=\\s*'?\\s*([^\']*)\\s*'?");
			if (cRegEx.Match(sExpression)) {
				// Get name and value
				m_sName  = cRegEx.GetResult(0);
				m_sValue = cRegEx.GetResult(1);
				return true;
			}
		} else {
			static RegEx cRegEx("\\s*(\\w*)\\s*=\\s*\"?\\s*([^\"]*)\\s*\"?");
			if (cRegEx.Match(sExpression)) {
				// Get name and value
				m_sName  = cRegEx.GetResult(0);
				m_sValue = cRegEx.GetResult(1);
				return true;
			}
		}
	}

	// Error, could not parse next expression
	m_sName		= "";
	m_sValue	= "";
	m_nParsePos	= -1;
	return false;
}
Esempio n. 16
0
/**
*  @brief
*    From string
*/
bool Color3::FromString(const String &sString)
{
	if (sString.GetLength()) {
		// Parse components
		uint32 nParsePos  = 0;
		uint32 nComponent = 0;
		static RegEx cRegEx("\\s*(\\S+)");
		while (nComponent < 3 && cRegEx.Match(sString, nParsePos)) {
			fColor[nComponent++] = cRegEx.GetResult(0).GetFloat();
			nParsePos = cRegEx.GetPosition();
		}

		// Set unused components to 0
		while (nComponent < 3)
			fColor[nComponent++] = 0.0f;

		// Done
		return true;
	} else {
		// Error!
		r = g = b = 0.0f;
		return false;
	}
}
Esempio n. 17
0
/**
*  @brief
*    From string
*/
bool Vector2i::FromString(const String &sString)
{
	if (sString.GetLength()) {
		// Parse components
		uint32 nParsePos  = 0;
		uint32 nComponent = 0;
		static RegEx cRegEx("\\s*(\\S+)");
		while (nComponent < 2 && cRegEx.Match(sString, nParsePos)) {
			nV[nComponent++] = cRegEx.GetResult(0).GetInt();
			nParsePos = cRegEx.GetPosition();
		}

		// Set unused components to 0
		while (nComponent < 2)
			nV[nComponent++] = 0;

		// Done
		return true;
	} else {
		// Error!
		x = y = 0;
		return false;
	}
}
Esempio n. 18
0
static cell_t GetRegexSubString(IPluginContext *pCtx, const cell_t *params)
{
	Handle_t hndl=static_cast<Handle_t>(params[1]);
	HandleError err;
	HandleSecurity sec;
	sec.pOwner=NULL;
	sec.pIdentity=myself->GetIdentity();

	int match = 0;

	RegEx *x;

	if ((err=g_pHandleSys->ReadHandle(hndl, g_RegexHandle, &sec, (void **)&x)) != HandleError_None)
	{
		return pCtx->ThrowNativeError("Invalid regex handle %x (error %d)", hndl, err);
	}

	if (!x)
	{
		pCtx->ThrowNativeError("Regex data not found\n");
		return 0;
	}

	if (params[0] >= 5)
	{
		match = params[5];
	}

	if(match >= x->mMatchCount || match < 0)
		return pCtx->ThrowNativeError("Invalid match index passed.\n");

	char *buffer;
	pCtx->LocalToString(params[3], &buffer);
	
	return x->GetSubstring(params[2], buffer, params[4], match);
}
Esempio n. 19
0
cell match_c(AMX *amx, cell *params, bool all)
{
	int id = params[2] - 1;

	if (id >= (int)PEL.length() || id < 0 || PEL[id]->isFree())
	{
		MF_LogError(amx, AMX_ERR_NATIVE, "Invalid regex handle %d", id);
		return 0;
	}

	int len;
	const char *str = MF_GetAmxString(amx, params[1], 0, &len);
	cell *errorCode = MF_GetAmxAddr(amx, params[3]);

	RegEx *x = PEL[id];

	int e;
	if (all)
		e = x->MatchAll(str);
	else
		e = x->Match(str);

	if (e == -1)
	{
		/* there was a match error.  move on. */
		*errorCode = x->mErrorOffset;

		/* only clear the match results, since the regex object
		may still be referenced later */
		x->ClearMatch();
		return -2;
	}
	else if (e == 0) 
	{
		*errorCode = 0;

		/* only clear the match results, since the regex object
		may still be referenced later */
		x->ClearMatch();
		return 0;
	}
	else 
	{
		*errorCode = x->Count();
		return x->Count();
	}
}
Esempio n. 20
0
/**
*  @brief
*    Writes the flexible scene node variables
*/
void PLSceneNode::WriteVariables(XmlElement &cNodeElement) const
{
	// Export variables?
	if (g_SEOptions.bUserPropVariables) {
		// Is there a 3ds Max node (No 3ds Max node, no properties)
		INode *pMaxNode = GetMaxNode();
		if (pMaxNode) {
			// Check for variables
			TSTR s3dsMaxString;
			if (pMaxNode->GetUserPropString(_T("Vars"), s3dsMaxString)) {
				// Get all expressions
				static RegEx cExpressionRegEx("\\s*((\\w*\\s*=\\s*\"[^\"]*\")|(\\w*\\s*=\\s*[\\w|]*))");
				const String sString = s3dsMaxString;
				uint32 nExpressionParsePos = 0;
				while (cExpressionRegEx.Match(sString, nExpressionParsePos)) {
					// Get expression
								 nExpressionParsePos = cExpressionRegEx.GetPosition();
					const String sExpression		 = cExpressionRegEx.GetResult(0);

					// Process the found expression
					static RegEx cRegEx("\\s*(\\w*)\\s*=\\s*\"?\\s*([^\"]*)\\s*\"?");
					if (cRegEx.Match(sExpression)) {
						// Get name and value
						const String sName  = cRegEx.GetResult(0);
						const String sValue = cRegEx.GetResult(1);

						// Flags variable?
						if (sName == "Flags") {
							// Update attribute
							String sFlags = cNodeElement.GetAttribute(sName);
							if (sFlags.GetLength())
								sFlags += '|' + sValue;
							else
								sFlags = sValue;
							sFlags.Trim();
							cNodeElement.SetAttribute(sName, sFlags);
						} else {
							// Set attribute
							cNodeElement.SetAttribute(sName, sValue);
						}
					}
				}
			}
		}
	}
}
Esempio n. 21
0
void cpp_hl_tests(RegEx& e, bool recurse = true)
{
   if(flags[4] & REG_MERGE)
      return;

   if(e.error_code())
   {
      if(search_text != BOOST_RE_STR("!"))
      {
         begin_error();
         cout << "Expression did not compile with class RegEx" << endl;
      }
      return;
   }

   if(recurse)
   {
      // copy and assign test:
      RegEx e2(e);
      cpp_hl_tests(e2, false);
      e2 = e;
      cpp_hl_tests(e2, false);
   }

   if(flags[4] & REG_GREP)
   {
      // try to do grep:
      hl_match_id = 0;
      GrepCallback cb = hl_grep_test_proc;
      e.Grep(cb, search_text.c_str(), flags[3]);
   }
   else
   {
      if(e.Search(search_text.c_str(), flags[3]))
      {
         unsigned int i = 0;
         unsigned int j = 0;
         while(matches[j] != -2)
         {
            if( (matches[j] != (int)e.Position(i))
               || ((matches[j] != -1) && ((matches[j+1] - matches[j] != (int)e.Length(i)))) )
            {
               begin_error();
               cout << "RegEx::Search error in subexpression " << i << ": found [" << e.Position(i) << "," << (e.Position(i) + e.Length(i)) << "] expected [" << matches[j] << "," << matches[j+1] << "]" << endl;
            }
            ++i;
            j += 2;
         }
      }
      else
      {
         if(matches[0] != -1)
         {
            begin_error();
            cout << "match expected but not found with RexEx::Search" << endl;
         }
      }

      //
      // test RegEx::Match only if we expect to match all of the input:
      //
      if((matches[0] == 0) && (matches[1] == search_text.size()))
      {
         if(e.Match(search_text.c_str(), flags[3]))
         {
            unsigned int i = 0;
            unsigned int j = 0;
            while(matches[j] != -2)
            {
               if( (matches[j] != (int)e.Position(i))
                  || ((matches[j] != -1) && ((matches[j+1] - matches[j] != (int)e.Length(i)))) )
               {
                  begin_error();
                  cout << "RegEx::Match error in subexpression " << i << ": found [" << e.Position(i) << "," << (e.Position(i) + e.Length(i)) << "] expected [" << matches[j] << "," << matches[j+1] << "]" << endl;
               }
               ++i;
               j += 2;
            }
         }
         else
         {
            begin_error();
            cout << "Match expected but not found with RegEx::Match" << endl;
         }
      }
   }
}
Esempio n. 22
0
int main( int argc, char **argv ) {
	RegEx re;
	re.Compile("abcd");
	assert ( true == re.Match("abcd"));
	assert ( true == re.Match("abcde"));
	assert ( true == re.Match("acde"));

	re.Compile("ab*");
	assert ( true == re.Match("ac"));
	assert ( true == re.Match("abc"));
	assert ( true == re.Match("abbc"));
	assert ( true == re.Match("acbb"));
	assert ( false == re.Match("xcbb"));

	re.Compile("ab+");
	assert ( true == re.Match("abc"));
	assert ( true == re.Match("abbc"));
	assert ( false == re.Match ("ac"));

	re.Compile("ab?");
	assert ( true == re.Match("ac"));
	assert ( true == re.Match("abc"));
	assert ( true == re.Match ("abbc"));

	re.Compile("a|b*");
	assert ( true == re.Match("a"));
	assert ( true == re.Match("b"));
	assert ( true == re.Match ("bbb"));
	assert ( true == re.Match ("bb"));
		
	re.Compile("(a|b)*");
	assert ( true == re.Match("a"));
	assert ( true == re.Match("b"));
	assert ( true == re.Match ("aa"));
	assert ( true == re.Match ("ab"));
	assert ( true == re.Match ("ba"));
	assert ( true == re.Match ("bb"));
	assert ( true == re.Match ("aaa"));

	re.Compile("a*b");
	assert ( false == re.Match("a"));
	assert ( true == re.Match("ab"));
	assert ( true == re.Match("aaaabbbcccb"));
	assert ( false == re.Match("a12344b"));
	assert ( false == re.Match("a@#$@#$b"));
	assert ( true == re.Match("b"));

	re.Compile("(a|b)*abb");
	assert ( true == re.Match("abb"));
	assert ( true == re.Match("aabb"));
	assert ( true == re.Match("babb"));
	assert ( true == re.Match("aaabb"));
	assert ( true == re.Match("bbabb"));
	assert ( true == re.Match("ababb"));
	assert ( true == re.Match("aababb"));

	re.Compile("ab[0-9]");
	assert ( true == re.Match("ab0"));
	assert ( true == re.Match("ab1"));
	assert ( true == re.Match("ab2"));
	assert ( true == re.Match("ab3"));
	assert ( true == re.Match("ab4"));
	assert ( true == re.Match("ab5"));
	assert ( true == re.Match("ab6"));
	assert ( true == re.Match("ab7"));
	assert ( true == re.Match("ab8"));
	assert ( true == re.Match("ab9"));
	assert ( true == re.Match("ab199"));

	re.Compile("XYZ[aeiou]");
	assert ( true == re.Match("XYZa"));
	assert ( true == re.Match("XYZe"));
	assert ( true == re.Match("XYZi"));
	assert ( true == re.Match("XYZo"));
	assert ( true == re.Match("XYZu"));
	assert ( false == re.Match("XYZb"));

	return 0;
}
Esempio n. 23
0
void reportSequenceMotifMetrics(System &_sys, Options &_opt){ 

  if (_opt.prosite == "") return;

  System ref;
  if (_opt.ref != ""){
    ref.readPdb(_opt.ref);
  }

  // Prosite Reader
  PrositeReader prosite;
  prosite.open(_opt.prosite);
  prosite.read();
  prosite.close();

  map<string,map<string,string> > prosite_data = prosite.getPrositeData();
  map<string,map<string,string> >::iterator proIt;
  map<string,string>::iterator proIt2;

  // Regular expression object
  RegEx re;
	//vector<pair<int,int> > matches = re.getResidueRanges(ch,"N.[ST]");	

  // For each chain
  for (uint c = 0; c < _sys.chainSize();c++){
    Chain &ch = _sys.getChain(c);

    int prositePatternFoundIndex = 1;
    for (proIt = prosite_data.begin();proIt != prosite_data.end();proIt++){
      for (proIt2 = proIt->second.begin();proIt2 != proIt->second.end();proIt2++){
	
	vector<pair<int,int> > matches;
        matches = re.getResidueRanges(ch,proIt2->second);

        for (uint m = 0; m < matches.size();m++){

	  string seq = "";
	  string selection = MslTools::stringf("chain %1s and resi %5d-%-5d",ch.getChainId().c_str(),ch.getResidue(matches[m].first).getResidueNumber(),ch.getResidue(matches[m].second).getResidueNumber());
	  string refSeq = "";

	  for (uint r = matches[m].first; r <= matches[m].second;r++){
	    seq += MslTools::getOneLetterCode(ch.getResidue(r).getResidueName());

	    if (_opt.ref != ""){
	      if (ref.positionExists(ch.getResidue(r).getPositionId())){
		refSeq += MslTools::getOneLetterCode(ref.getResidue(ch.getResidue(r).getPositionId()).getResidueName());
	      }
	    }
	  }
	  
	  // Skip if reference structure has same sequence motif
	  if (_opt.ref != "" && seq == refSeq){
	    string refStr = "**** IN REF STRUCTURE ****";
	    fprintf(stdout,"%-40s %20s %3s %s\n", proIt2->first.substr(0,40).c_str(), selection.c_str(),seq.c_str(),refStr.c_str());
	    continue;
	  }

	  fprintf(stdout,"%-40s %20s %3s\n", proIt2->first.substr(0,40).c_str(), selection.c_str(),seq.c_str());

	  string selStr = MslTools::stringf("%s and chain %1s and resi %d-%-d", MslTools::getFileName(_opt.pdb).c_str(),ch.getResidue(matches[m].first).getChainId().c_str(), ch.getResidue(matches[m].first).getResidueNumber(),ch.getResidue(matches[m].second).getResidueNumber());
	  if (ch.getResidue(matches[m].first).getChainId() == "" || ch.getResidue(matches[m].first).getChainId() == " "){
	    selStr = MslTools::stringf("%s and resi %d-%-d",MslTools::getFileName(_opt.pdb).c_str(),ch.getResidue(matches[m].first).getResidueNumber(),ch.getResidue(matches[m].second).getResidueNumber());
	  }

	  string selName = MslTools::stringf("%s-%s-%-d",MslTools::getFileName(_opt.pdb).c_str(),proIt->first.c_str(),prositePatternFoundIndex++);
	  _opt.pymol.createSelection(selName,selStr);

	} // FOR EACH MATCHES

      }// FOR EACH PROSITE2      
    } // FOR EACH PROSITE

  } // FOR EACH CHAIN

}
Esempio n. 24
0
CStdString GG::htmlToMsg(CStdString msgIn , void * formats , int & length) {
	int max_len = length;
	length = 0;
	CStdString msg;
	SXML XML;
	RegEx preg;
	msgIn = preg.replace("#\\r|\\n#" , "" , msgIn);
	msgIn = preg.replace("#<br/?>#i" , "\n" , msgIn.c_str());
	XML.loadSource(msgIn);
	SXML::NodeWalkInfo ni;
	size_t last = 0;
	void * formats_start = formats;
	gg_msg_richtext * rt = (gg_msg_richtext*) formats;
	formats = rt+1;
	void * formats_last = formats;
	memset(formats , 0 , sizeof(gg_msg_richtext_format));
/*
bleeeee<b>bold<b><font color="#FF0000">gnie�<u>d�ony</u></font></b>i <i>jesz</i>cze</b>koniec
*/
	FormatState state;
	stack <FormatState> spanStack;

	while (length < max_len - 20 && XML.nodeWalk(ni)) {
		XML.pos.start = XML.pos.end;
		XML.pos.start_end = XML.pos.end_end;
		msg += Stamina::decodeEntities(msgIn.substr(last , ni.start - last));
		last = ni.end;
		CStdString token = ni.path.substr(ni.path.find_last_of('/')+1);
		token.MakeLower();
		int oper = (ni.state == SXML::NodeWalkInfo::opened)? 1 : -1;
		if (token == "b" || token == "strong") {
			state.bold+=oper;
		} else if (token == "i") {
			state.italic+=oper;
		} else if (token == "u") {
			state.under+=oper;
		} else if (token == "font") {
			// Kolor musimy "zamkn��"
			if (oper > 0) state.color++;
			int c = chtoint(XML.getAttrib("color").c_str() , -1);
			state.rgb[0] = (c & 0xFF0000) >> 16;
			state.rgb[1] = (c & 0xFF00) >> 8;
			state.rgb[2] = (c & 0xFF);
		} else if (token == "span") {
			if (oper > 0) {
				spanStack.push(state);
				using Stamina::RegEx;
				static RegEx::oCompiled rcWeight(new RegEx::Compiled("/font-weight:bold/i"));
				//static RegEx::oCompiled rcSize = new RegEx::Compiled("/font-size:(\\d+)/i");
				static RegEx::oCompiled rcColor(new RegEx::Compiled("/color:([a-z]+|#[0-9A-F]+)/i"));
				static RegEx::oCompiled rcItalic(new RegEx::Compiled("/font-style:italic/i"));
				static RegEx::oCompiled rcUnderline(new RegEx::Compiled("/text-decoration:underline/i"));
				CStdString style = XML.getAttrib("style");
				if (RegEx::doMatch(rcWeight, style)) {
					state.bold += oper;
				}
				if (RegEx::doMatch(rcItalic, style)) {
					state.italic += oper;
				}
				if (RegEx::doMatch(rcUnderline, style)) {
					state.under += oper;
				}
				CStdString colorStr = RegEx::doGet(rcColor, style, 1);
				if (!colorStr.empty()) {
					int color = -1;
					if (colorStr[0] == '#') {
						color = Stamina::chtoint(colorStr , -1);
					} else if (colorStr == "red") {
						color = 0xFF0000;
					} else if (colorStr == "blue") {
						color = 0x0000FF;
					} else if (colorStr == "green") {
						color = 0x00FF00;
					}
					if (color > 0) {
						state.color++;
						state.rgb[0] = (color & 0xFF0000) >> 16;
						state.rgb[1] = (color & 0xFF00) >> 8;
						state.rgb[2] = (color & 0xFF);
					}
				}
Esempio n. 25
0
CStdString GG::msgToHtml(CStdString msg , void * formats , int formats_length) {
	/* Zamiast znacznik�w wstawia:
	 < - 1
	 > - 2
	 " - 3
	*/
	str_tr((char*)msg.c_str() , "\1\2\3" , "   ");
	// Przegl�damy list� i modyfikujemy...
	void * formats_end = (char*)formats + formats_length;
	CStdString msg2 = "";
	struct cOpened {
		unsigned int bold :1;
		unsigned int italic : 1;
		unsigned int under : 1;
		unsigned int color: 1;
		void finish(CStdString & txt , int type) {
			if (color) {txt+="\1/font\2"; color = 0;}
			if (!(type & GG_FONT_UNDERLINE) && under) {txt+="\1/u\2"; under = 0;}
			if (!(type & GG_FONT_ITALIC) && italic) {txt+="\1/i\2"; italic = 0;}
			if (!(type & GG_FONT_BOLD) && bold) {txt+="\1/b\2";bold = 0;}
		}
	} opened;
	opened.bold = opened.italic = opened.under = opened.color = 0;
	size_t pos = 0;
	while (formats < formats_end) {
		gg_msg_richtext_format * rf = (gg_msg_richtext_format*)formats;
		if (rf->position >= msg.size())
			break; // b��d
		msg2+= msg.substr(pos , rf->position - pos);
		pos = rf->position;
		opened.finish(msg2 , rf->font);
		if ((rf->font & GG_FONT_BOLD) && !opened.bold) {
			msg2+="\1b\2";
			opened.bold=1;
		}
		if ((rf->font & GG_FONT_ITALIC) && !opened.italic) {
			msg2+="\1i\2";
			opened.italic=1;
		}
		if ((rf->font & GG_FONT_UNDERLINE) && !opened.under) {
			msg2+="\1u\2";
			opened.under=1;
		}
		formats = rf+1;
		if (rf->font & GG_FONT_COLOR) {
			gg_msg_richtext_color * rc = (gg_msg_richtext_color*) formats;
			if (rc->red || rc->green || rc->blue) {
				opened.color=1;
				msg2+="\1font color=\3#";
				msg2+=inttostr(rc->red , 16 , 2 , true);
				msg2+=inttostr(rc->green , 16 , 2 , true);
				msg2+=inttostr(rc->blue , 16 , 2 , true);
				msg2+="\3\2";
			} else opened.color = 0;
			formats = rc+1;
		}
	}
	msg2 += msg.substr(pos);
	opened.finish(msg2 , 0);
	msg = msg2;
	msg2.clear();
	// Ko�cowy efekt "enkodujemy"
	RegEx pr;
	msg = pr.replace("/[^ a-z0-9\1\2\3\\!\\@\\#\\$\\%\\*\\(\\)\\-_=+\\.\\,\\;':\\\\[\\]\\{\\}\\/\\?����󜟿��ʣ�ӌ��]/i" , Stamina::encodeCallback , msg);
	msg = pr.replace("/\\n/" , "<br/>" , msg);
	// Zamieniamy znaki kontrolne w znaczniki HTML
	str_tr((char*)msg.c_str() , "\1\2\3" , "<>\"");
	return msg;
};
Esempio n. 26
0
void run_tests()
{
#ifndef TEST_UNICODE
   if(flags[4] & REG_UNICODE_ONLY)
      return;
#endif
#ifndef NO_CPP_TEST
#ifndef BOOST_NO_EXCEPTIONS
   try
   {
#endif
      unsigned int f = flags[2] & ~regbase::use_except;
      if(flags[0] & REG_ICASE)
         f |= regbase::icase;
      re_type e(expression.c_str(), f);
      cpp_tests(e, true);
#ifndef BOOST_NO_EXCEPTIONS
   }
   catch(const std::exception& e)
   {
      //
      // this is only an error if the expression is expected to be valid:
      if(search_text != BOOST_RE_STR("!"))
      {
         begin_error();
         cout << "Unexpected exception thrown from C++ library: " << e.what() << endl;
      }
   }
   catch(...)
   {
      begin_error();
      cout << "Unexpected exception thrown from C++ library" << endl;
   }
#endif // BOOST_NO_EXCEPTIONS
#endif

#if !defined(TEST_UNICODE)
#ifndef BOOST_NO_EXCEPTIONS
   try
   {
#endif
      if(((flags[3] & match_partial) == 0) && (flags[2] == regbase::normal) && (has_nulls(search_text.begin(), search_text.end()) == false))
      {
         RegEx e;
         e.SetExpression(expression.c_str(), flags[0] & REG_ICASE);
         cpp_hl_tests(e, true);
      }
#ifndef BOOST_NO_EXCEPTIONS
   }
   catch(const std::exception& )
   {
      if(search_text != BOOST_RE_STR("!"))
      {
         begin_error();
         cout << "Expression did not compile with class RegEx" << endl;
      }
   }
   catch(...)
   {
      begin_error();
      cout << "Unexpected exception thrown from RegEx::SetExpression" << endl;
   }
#endif // BOOST_NO_EXCEPTIONS
#endif

   if(flags[4] & (REG_NO_POSIX_TEST | REG_GREP | REG_MERGE | REG_MERGE_COPY))
      return;
   regex_t posix_expression;
   regmatch_t m[MAX_MATCHES];
   if(regcomp(&posix_expression, expression.c_str(), flags[0]) == 0)
   {
      if(flags[1] & REG_STARTEND)
      {
         m[0].rm_so = 0;
         m[0].rm_eo = search_text.size();
      }
      if(regexec(&posix_expression, search_text.c_str(), MAX_MATCHES, m, flags[1]))
      {
         // match not found
         if(matches[0] != -1)
         {
            begin_error();
            cout << "Match expected but not found using POSIX API" << endl;
         }
      }
      else
      {
         // match found compare what matched with what we expect:
         int j = 0;
         for(unsigned int i = 0; i <= posix_expression.re_nsub; ++i, j += 2)
         {
            if((m[i].rm_so != matches[j]) || (m[i].rm_eo != matches[j+1]))
            {
               begin_error();
               cout << "POSIX API result mismatch in sub-expression " << i << ", found (" << m[i].rm_so << "," << m[i].rm_eo <<
                        ") expected (" << matches[j] << "," << matches[j+1] << ")" << endl;
            }
         }
      }
      regfree(&posix_expression);
   }
   else
   {
      // expression did not compile
      if(search_text != BOOST_RE_STR("!"))
      {
         begin_error();
         cout << "Expression did not compile using POSIX API" << endl;
      }
   }
}
Esempio n. 27
0
RedirectPlugin::LookUpStatus
SipRedirectorRegDB::lookUp(
   const SipMessage& message,
   const UtlString& requestString,
   const Url& requestUri,
   const UtlString& method,
   ContactList& contactList,
   RequestSeqNo requestSeqNo,
   int redirectorNo,
   SipRedirectorPrivateStorage*& privateStorage,
   ErrorDescriptor& errorDescriptor)
{
   unsigned long timeNow = OsDateTime::getSecsSinceEpoch();
   
   // Local copy of requestUri
   Url requestUriCopy = requestUri;

   // Look for any grid parameter and remove it.
   UtlString gridParameter;
   UtlBoolean gridPresent =
      requestUriCopy.getUrlParameter("grid", gridParameter, 0);
   if (gridPresent)
   {
      requestUriCopy.removeUrlParameter("grid");
   }
   if (Os::Logger::instance().willLog(FAC_SIP, PRI_DEBUG))
   {
      UtlString temp;
      requestUriCopy.getUri(temp);
      Os::Logger::instance().log(FAC_SIP, PRI_DEBUG,
                    "%s::lookUp gridPresent = %d, gridParameter = '%s', "
                    "requestUriCopy after removing grid = '%s'",
                    mLogName.data(), gridPresent, gridParameter.data(),
                    temp.data());
   }

   RegDB::Bindings registrations;

   // Give the ~~in~ URIs separate processing.
   UtlString user;
   requestUriCopy.getUserId(user);
   if (user.index(URI_IN_PREFIX) == 0)
   {
      // This is a ~~in~ URI.
      // Check for an '&' separator.
      ssize_t s = user.last('&');
      if (s != UTL_NOT_FOUND)
      {
         // This is a ~~in~[user]&[instrument] URI.
         const char* instrumentp = user.data() + s + 1;
         UtlString u;
         u.append(user,
                  sizeof (URI_IN_PREFIX) - 1,
                  s - (sizeof (URI_IN_PREFIX) - 1));
         requestUriCopy.setUserId(u);

         //regDB->
         //   getUnexpiredContactsUserInstrument(requestUriCopy, instrumentp, timeNow, registrations);
         UtlString identity;
         requestUriCopy.getIdentity(identity);
         _dataStore.regDB().getUnexpiredContactsUserInstrument(identity.str(), instrumentp, timeNow, registrations);
      }
      else
      {
         // This is a ~~in~[instrument] URI.
         const char* instrumentp = user.data() + sizeof (URI_IN_PREFIX) - 1;

          _dataStore.regDB().getUnexpiredContactsInstrument(instrumentp, timeNow, registrations);
      }         
   }
   else
   {
      // Note that getUnexpiredContactsUser will reduce the requestUri to its
      // identity (user/host/port) part before searching in the
      // database.  The requestUri identity is matched against the
      // "identity" column of the database, which is the identity part of
      // the "uri" column which is stored in registration.xml.

      UtlString identity;
     requestUriCopy.getIdentity(identity);
     _dataStore.regDB().getUnexpiredContactsUser(identity.str(), timeNow, registrations);

   }

   int numUnexpiredContacts = registrations.size();

   Os::Logger::instance().log(FAC_SIP, PRI_DEBUG,
                 "%s::lookUp got %d unexpired contacts",
                 mLogName.data(), numUnexpiredContacts);

   // Check for a per-user call forward timer.
   // Don't set timer if we're not going to forward to voicemail.
   std::ostringstream userCfwdTimer;
   bool foundUserCfwdTimer = false;

   if (method.compareTo(SIP_INVITE_METHOD) == 0)
   {
      UtlString noRoute;
      requestUriCopy.getUrlParameter("sipx-noroute", noRoute);

      if ((!noRoute.isNull()) && (noRoute.compareTo("Voicemail") == 0))
      {
          // This is not a call scenerio controlled by this users "forward to voicemail" timer
      }
      else
      {
          UtlString identity;
          requestUriCopy.getIdentity(identity);
          EntityRecord entity;

          foundUserCfwdTimer = _dataStore.entityDB().findByIdentity(identity.str(), entity);
          if (foundUserCfwdTimer)
            userCfwdTimer << entity.callForwardTime();
      }
   }

   for (RegDB::Bindings::const_iterator iter = registrations.begin(); iter != registrations.end(); iter++)
   {
      // Query the Registration DB for the contact, expires and qvalue columns.

      Os::Logger::instance().log(FAC_SIP, PRI_DEBUG,
                    "%s::lookUp contact = '%s', qvalue = '%s', path = '%s'",
                    mLogName.data(), iter->getContact().c_str(), iter->getQvalue().c_str(), iter->getPath().c_str() );
      Url contactUri(iter->getContact().c_str());

      // If available set the per-user call forward timer.
      if (foundUserCfwdTimer)
      {
          contactUri.setHeaderParameter("expires", userCfwdTimer.str().c_str());
      }

      // If the contact URI is the same as the request URI, ignore it.
      if (!contactUri.isUserHostPortEqual(requestUriCopy))
      {
         // Check if the q-value from the database is valid, and if so,
         // add it into contactUri.
         if (!iter->getQvalue().empty())
         {
            // :TODO: (XPL-3) need a RegEx copy constructor here
            // Check if q value is numeric and between the range 0.0 and 1.0.
            static RegEx qValueValid("^(0(\\.\\d{0,3})?|1(\\.0{0,3})?)$");
            if (qValueValid.Search(iter->getQvalue().c_str()))
            {
               contactUri.setFieldParameter(SIP_Q_FIELD, iter->getQvalue().c_str());
            }
         }

         // Re-apply any grid parameter.
         if (gridPresent)
         {
            contactUri.setUrlParameter("grid", gridParameter);
         }

         contactUri.setUrlParameter(SIP_SIPX_CALL_DEST_FIELD, "INT");
         // Check if database contained a Path value.  If so, add a Route
         // header parameter to the contact with the Path vector taken from
         // the registration data.
         if (!iter->getPath().empty())
         {
            UtlString existingRouteValue;
            std::string pathVector = iter->getPath();
            if ( contactUri.getHeaderParameter(SIP_ROUTE_FIELD, existingRouteValue))
            {
               // there is already a Route header parameter in the contact; append it to the
               // Route derived from the Path vector.
                pathVector += SIP_MULTIFIELD_SEPARATOR;
                pathVector += existingRouteValue.str();
            }
            contactUri.setHeaderParameter(SIP_ROUTE_FIELD, pathVector.c_str());
         }

         // Add the contact.
         contactList.add( contactUri, *this );
      }
   }

   return RedirectPlugin::SUCCESS;
}
Esempio n. 28
0
bool 
#if defined(__BORLANDC__) || defined(BOOST_MSVC)
__cdecl
#endif
hl_grep_test_proc(const RegEx& e)
{
   std::ptrdiff_t start, end;

   start = e.Position(0);
   end = start + e.Length();
   if((matches[hl_match_id] != start) || (matches[hl_match_id + 1] != end))
   {
      begin_error();
      cout << "class RegEx grep match error: found [" << start << "," << end << "] expected [" << matches[hl_match_id] << "," << matches[hl_match_id+1] << "]" << endl;
   }
   if(0 == (flags[4] & REG_GREP))
   {
      for(unsigned int sub = 1; sub < e.Marks(); ++sub)
      {
         start = e.Position(sub);
         end = start + e.Length(sub);
         if((matches[2*sub] != start) || (matches[2*sub + 1] != end))
         {
            begin_error();
            cout << "class RegEx grep match error: found in sub " << sub << " [" << start << "," << end << "] expected [" << matches[2*sub] << "," << matches[2*sub+1] << "]" << endl;
         }
      }
   }

   //
   // check $`:
   start = e.Position(-1);
   end = start + e.Length(-1);
   if(start == -1)
   {
      if(hl_match_id && 
         ( matches[hl_match_id] != matches[hl_match_id - 1] )
      )
      {
         begin_error();
         cout << "class RegEx grep error in $`: found [" << start << "," << end << "] expected [" << matches[hl_match_id-1] << "," << matches[hl_match_id] << "]" << endl;
      }
      else if((!hl_match_id) && (0 != matches[0]))
      {
         begin_error();
         cout << "class RegEx grep error in $`: found [" << start << "," << end << "] expected [" << 0 << "," << matches[0] << "]" << endl;
      }
   }
   else
   {
      if(hl_match_id && 
         ( (end != matches[hl_match_id]) || (start != matches[hl_match_id - 1]) )
      )
      {
         begin_error();
         cout << "class RegEx grep error in $`: found [" << start << "," << end << "] expected [" << matches[hl_match_id-1] << "," << matches[hl_match_id] << "]" << endl;
      }
      else if((!hl_match_id) && ((start != 0) || (end != matches[0])))
      {
         begin_error();
         cout << "class RegEx grep error in $`: found [" << start << "," << end << "] expected [" << 0 << "," << matches[0] << "]" << endl;
      }
   }

   //
   // check $':
   start = e.Position(-2);
   end = start + e.Length(-2);
   if(start == -1)
   {
      if(matches[hl_match_id + 1] != (int)search_text.size())
      {
         begin_error();
         cout << "class RegEx grep error in $': found [" << start << "," << end << "] expected [" << matches[hl_match_id + 1] << "," << (search_text.size()) << "]" << endl;
      }
   }
   else if((start != matches[hl_match_id + 1]) || (end != (int)search_text.size()))
   {
      begin_error();
      cout << "class RegEx grep error in $': found [" << start << "," << end << "] expected [" << matches[hl_match_id + 1] << "," << (search_text.size()) << "]" << endl;
   }

   hl_match_id += 2;
   return true;
}
Esempio n. 29
0
cell match(AMX *amx, cell *params, bool all)
{
	int len;
	const char *str = MF_GetAmxString(amx, params[1], 0, &len);
	const char *regex = MF_GetAmxString(amx, params[2], 1, &len);

	int id = GetPEL();
	RegEx *x = PEL[id];

	char *flags = NULL;
	cell *errorCode;
	int result = 0;

	if (!all)
	{
		if (*params / sizeof(cell) >= 6) // compiled with 1.8's extra parameter
		{
			flags = MF_GetAmxString(amx, params[6], 2, &len);
		}

		result = x->Compile(regex, flags);
		errorCode = MF_GetAmxAddr(amx, params[3]);
	}
	else
	{
		result = x->Compile(regex, params[3]);
		errorCode = MF_GetAmxAddr(amx, params[6]);
	}

	if (!result)
	{
		const char *err = x->mError;
		*errorCode = x->mErrorOffset;
		MF_SetAmxString(amx, params[4], err ? err : "unknown", params[5]);
		return -1;
	}

	int e;

	if (all)
		e = x->MatchAll(str);
	else
		e = x->Match(str);

	if (e == -1)
	{
		/* there was a match error.  destroy this and move on. */
		*errorCode = x->mErrorOffset;
		x->Clear();
		return -2;
	}
	else if (e == 0) 
	{
		*errorCode = 0;
		x->Clear();
		return 0;
	}
	else 
	{
		*errorCode = x->Count();
		if (all)
			return x->Count();
	}

	return id + 1;
}
Esempio n. 30
0
void ListBinCommand::Execute()
{
	SNZBListRequest ListRequest;
	if (!ReceiveRequest(&ListRequest, sizeof(ListRequest)))
	{
		return;
	}

	SNZBListResponse ListResponse;
	memset(&ListResponse, 0, sizeof(ListResponse));
	ListResponse.m_MessageBase.m_iSignature = htonl(NZBMESSAGE_SIGNATURE);
	ListResponse.m_MessageBase.m_iStructSize = htonl(sizeof(ListResponse));
	ListResponse.m_iEntrySize = htonl(sizeof(SNZBListResponseFileEntry));
	ListResponse.m_bRegExValid = 0;

	char* buf = NULL;
	int bufsize = 0;

	if (ntohl(ListRequest.m_bFileList))
	{
		eRemoteMatchMode eMatchMode = (eRemoteMatchMode)ntohl(ListRequest.m_iMatchMode);
		bool bMatchGroup = ntohl(ListRequest.m_bMatchGroup);
		const char* szPattern = ListRequest.m_szPattern;

		RegEx *pRegEx = NULL;
		if (eMatchMode == eRemoteMatchModeRegEx)
		{
			pRegEx = new RegEx(szPattern);
			ListResponse.m_bRegExValid = pRegEx->IsValid();
		}

		// Make a data structure and copy all the elements of the list into it
		DownloadQueue* pDownloadQueue = g_pQueueCoordinator->LockQueue();

		// calculate required buffer size for nzbs
		int iNrNZBEntries = pDownloadQueue->GetNZBInfoList()->size();
		int iNrPPPEntries = 0;
		bufsize += iNrNZBEntries * sizeof(SNZBListResponseNZBEntry);
		for (NZBInfoList::iterator it = pDownloadQueue->GetNZBInfoList()->begin(); it != pDownloadQueue->GetNZBInfoList()->end(); it++)
		{
			NZBInfo* pNZBInfo = *it;
			bufsize += strlen(pNZBInfo->GetFilename()) + 1;
			bufsize += strlen(pNZBInfo->GetName()) + 1;
			bufsize += strlen(pNZBInfo->GetDestDir()) + 1;
			bufsize += strlen(pNZBInfo->GetCategory()) + 1;
			bufsize += strlen(pNZBInfo->GetQueuedFilename()) + 1;
			// align struct to 4-bytes, needed by ARM-processor (and may be others)
			bufsize += bufsize % 4 > 0 ? 4 - bufsize % 4 : 0;

			// calculate required buffer size for pp-parameters
			for (NZBParameterList::iterator it = pNZBInfo->GetParameters()->begin(); it != pNZBInfo->GetParameters()->end(); it++)
			{
				NZBParameter* pNZBParameter = *it;
				bufsize += sizeof(SNZBListResponsePPPEntry);
				bufsize += strlen(pNZBParameter->GetName()) + 1;
				bufsize += strlen(pNZBParameter->GetValue()) + 1;
				// align struct to 4-bytes, needed by ARM-processor (and may be others)
				bufsize += bufsize % 4 > 0 ? 4 - bufsize % 4 : 0;
				iNrPPPEntries++;
			}
		}

		// calculate required buffer size for files
		int iNrFileEntries = pDownloadQueue->GetFileQueue()->size();
		bufsize += iNrFileEntries * sizeof(SNZBListResponseFileEntry);
		for (FileQueue::iterator it = pDownloadQueue->GetFileQueue()->begin(); it != pDownloadQueue->GetFileQueue()->end(); it++)
		{
			FileInfo* pFileInfo = *it;
			bufsize += strlen(pFileInfo->GetSubject()) + 1;
			bufsize += strlen(pFileInfo->GetFilename()) + 1;
			// align struct to 4-bytes, needed by ARM-processor (and may be others)
			bufsize += bufsize % 4 > 0 ? 4 - bufsize % 4 : 0;
		}

		buf = (char*) malloc(bufsize);
		char* bufptr = buf;

		// write nzb entries
		for (NZBInfoList::iterator it = pDownloadQueue->GetNZBInfoList()->begin(); it != pDownloadQueue->GetNZBInfoList()->end(); it++)
		{
			unsigned long iSizeHi, iSizeLo;
			NZBInfo* pNZBInfo = *it;
			SNZBListResponseNZBEntry* pListAnswer = (SNZBListResponseNZBEntry*) bufptr;
			Util::SplitInt64(pNZBInfo->GetSize(), &iSizeHi, &iSizeLo);
			pListAnswer->m_iSizeLo				= htonl(iSizeLo);
			pListAnswer->m_iSizeHi				= htonl(iSizeHi);
			pListAnswer->m_bMatch				= htonl(bMatchGroup && (!pRegEx || pRegEx->Match(pNZBInfo->GetName())));
			pListAnswer->m_iFilenameLen			= htonl(strlen(pNZBInfo->GetFilename()) + 1);
			pListAnswer->m_iNameLen				= htonl(strlen(pNZBInfo->GetName()) + 1);
			pListAnswer->m_iDestDirLen			= htonl(strlen(pNZBInfo->GetDestDir()) + 1);
			pListAnswer->m_iCategoryLen			= htonl(strlen(pNZBInfo->GetCategory()) + 1);
			pListAnswer->m_iQueuedFilenameLen	= htonl(strlen(pNZBInfo->GetQueuedFilename()) + 1);
			bufptr += sizeof(SNZBListResponseNZBEntry);
			strcpy(bufptr, pNZBInfo->GetFilename());
			bufptr += ntohl(pListAnswer->m_iFilenameLen);
			strcpy(bufptr, pNZBInfo->GetName());
			bufptr += ntohl(pListAnswer->m_iNameLen);
			strcpy(bufptr, pNZBInfo->GetDestDir());
			bufptr += ntohl(pListAnswer->m_iDestDirLen);
			strcpy(bufptr, pNZBInfo->GetCategory());
			bufptr += ntohl(pListAnswer->m_iCategoryLen);
			strcpy(bufptr, pNZBInfo->GetQueuedFilename());
			bufptr += ntohl(pListAnswer->m_iQueuedFilenameLen);
			// align struct to 4-bytes, needed by ARM-processor (and may be others)
			if ((size_t)bufptr % 4 > 0)
			{
				pListAnswer->m_iQueuedFilenameLen = htonl(ntohl(pListAnswer->m_iQueuedFilenameLen) + 4 - (size_t)bufptr % 4);
				memset(bufptr, 0, 4 - (size_t)bufptr % 4); //suppress valgrind warning "uninitialized data"
				bufptr += 4 - (size_t)bufptr % 4;
			}
		}

		// write ppp entries
		int iNZBIndex = 1;
		for (NZBInfoList::iterator it = pDownloadQueue->GetNZBInfoList()->begin(); it != pDownloadQueue->GetNZBInfoList()->end(); it++, iNZBIndex++)
		{
			NZBInfo* pNZBInfo = *it;
			for (NZBParameterList::iterator it = pNZBInfo->GetParameters()->begin(); it != pNZBInfo->GetParameters()->end(); it++)
			{
				NZBParameter* pNZBParameter = *it;
				SNZBListResponsePPPEntry* pListAnswer = (SNZBListResponsePPPEntry*) bufptr;
				pListAnswer->m_iNZBIndex	= htonl(iNZBIndex);
				pListAnswer->m_iNameLen		= htonl(strlen(pNZBParameter->GetName()) + 1);
				pListAnswer->m_iValueLen	= htonl(strlen(pNZBParameter->GetValue()) + 1);
				bufptr += sizeof(SNZBListResponsePPPEntry);
				strcpy(bufptr, pNZBParameter->GetName());
				bufptr += ntohl(pListAnswer->m_iNameLen);
				strcpy(bufptr, pNZBParameter->GetValue());
				bufptr += ntohl(pListAnswer->m_iValueLen);
				// align struct to 4-bytes, needed by ARM-processor (and may be others)
				if ((size_t)bufptr % 4 > 0)
				{
					pListAnswer->m_iValueLen = htonl(ntohl(pListAnswer->m_iValueLen) + 4 - (size_t)bufptr % 4);
					memset(bufptr, 0, 4 - (size_t)bufptr % 4); //suppress valgrind warning "uninitialized data"
					bufptr += 4 - (size_t)bufptr % 4;
				}
			}
		}

		// write file entries
		for (FileQueue::iterator it = pDownloadQueue->GetFileQueue()->begin(); it != pDownloadQueue->GetFileQueue()->end(); it++)
		{
			unsigned long iSizeHi, iSizeLo;
			FileInfo* pFileInfo = *it;
			SNZBListResponseFileEntry* pListAnswer = (SNZBListResponseFileEntry*) bufptr;
			pListAnswer->m_iID = htonl(pFileInfo->GetID());

			int iNZBIndex = 0;
			for (unsigned int i = 0; i < pDownloadQueue->GetNZBInfoList()->size(); i++)
			{
				iNZBIndex++;
				if (pDownloadQueue->GetNZBInfoList()->at(i) == pFileInfo->GetNZBInfo())
				{
					break;
				}
			}
			pListAnswer->m_iNZBIndex		= htonl(iNZBIndex);

			if (pRegEx && !bMatchGroup)
			{
				char szFilename[MAX_PATH];
				snprintf(szFilename, sizeof(szFilename) - 1, "%s/%s", pFileInfo->GetNZBInfo()->GetName(), Util::BaseFileName(pFileInfo->GetFilename()));
				pListAnswer->m_bMatch = htonl(pRegEx->Match(szFilename));
			}

			Util::SplitInt64(pFileInfo->GetSize(), &iSizeHi, &iSizeLo);
			pListAnswer->m_iFileSizeLo		= htonl(iSizeLo);
			pListAnswer->m_iFileSizeHi		= htonl(iSizeHi);
			Util::SplitInt64(pFileInfo->GetRemainingSize(), &iSizeHi, &iSizeLo);
			pListAnswer->m_iRemainingSizeLo	= htonl(iSizeLo);
			pListAnswer->m_iRemainingSizeHi	= htonl(iSizeHi);
			pListAnswer->m_bFilenameConfirmed = htonl(pFileInfo->GetFilenameConfirmed());
			pListAnswer->m_bPaused			= htonl(pFileInfo->GetPaused());
			pListAnswer->m_iActiveDownloads	= htonl(pFileInfo->GetActiveDownloads());
			pListAnswer->m_iPriority		= htonl(pFileInfo->GetPriority());
			pListAnswer->m_iSubjectLen		= htonl(strlen(pFileInfo->GetSubject()) + 1);
			pListAnswer->m_iFilenameLen		= htonl(strlen(pFileInfo->GetFilename()) + 1);
			bufptr += sizeof(SNZBListResponseFileEntry);
			strcpy(bufptr, pFileInfo->GetSubject());
			bufptr += ntohl(pListAnswer->m_iSubjectLen);
			strcpy(bufptr, pFileInfo->GetFilename());
			bufptr += ntohl(pListAnswer->m_iFilenameLen);
			// align struct to 4-bytes, needed by ARM-processor (and may be others)
			if ((size_t)bufptr % 4 > 0)
			{
				pListAnswer->m_iFilenameLen = htonl(ntohl(pListAnswer->m_iFilenameLen) + 4 - (size_t)bufptr % 4);
				memset(bufptr, 0, 4 - (size_t)bufptr % 4); //suppress valgrind warning "uninitialized data"
				bufptr += 4 - (size_t)bufptr % 4;
			}
		}

		g_pQueueCoordinator->UnlockQueue();

		if (pRegEx)
		{
			delete pRegEx;
		}

		ListResponse.m_iNrTrailingNZBEntries = htonl(iNrNZBEntries);
		ListResponse.m_iNrTrailingPPPEntries = htonl(iNrPPPEntries);
		ListResponse.m_iNrTrailingFileEntries = htonl(iNrFileEntries);
		ListResponse.m_iTrailingDataLength = htonl(bufsize);
	}

	if (htonl(ListRequest.m_bServerState))
	{
		unsigned long iSizeHi, iSizeLo;
		ListResponse.m_iDownloadRate = htonl((int)(g_pQueueCoordinator->CalcCurrentDownloadSpeed() * 1024));
		Util::SplitInt64(g_pQueueCoordinator->CalcRemainingSize(), &iSizeHi, &iSizeLo);
		ListResponse.m_iRemainingSizeHi = htonl(iSizeHi);
		ListResponse.m_iRemainingSizeLo = htonl(iSizeLo);
		ListResponse.m_iDownloadLimit = htonl((int)(g_pOptions->GetDownloadRate() * 1024));
		ListResponse.m_bDownloadPaused = htonl(g_pOptions->GetPauseDownload());
		ListResponse.m_bDownload2Paused = htonl(g_pOptions->GetPauseDownload2());
		ListResponse.m_bPostPaused = htonl(g_pOptions->GetPausePostProcess());
		ListResponse.m_bScanPaused = htonl(g_pOptions->GetPauseScan());
		ListResponse.m_iThreadCount = htonl(Thread::GetThreadCount() - 1); // not counting itself
		PostQueue* pPostQueue = g_pQueueCoordinator->LockQueue()->GetPostQueue();
		ListResponse.m_iPostJobCount = htonl(pPostQueue->size());
		g_pQueueCoordinator->UnlockQueue();

		int iUpTimeSec, iDnTimeSec;
		long long iAllBytes;
		bool bStandBy;
		g_pQueueCoordinator->CalcStat(&iUpTimeSec, &iDnTimeSec, &iAllBytes, &bStandBy);
		ListResponse.m_iUpTimeSec = htonl(iUpTimeSec);
		ListResponse.m_iDownloadTimeSec = htonl(iDnTimeSec);
		ListResponse.m_bDownloadStandBy = htonl(bStandBy);
		Util::SplitInt64(iAllBytes, &iSizeHi, &iSizeLo);
		ListResponse.m_iDownloadedBytesHi = htonl(iSizeHi);
		ListResponse.m_iDownloadedBytesLo = htonl(iSizeLo);
	}

	// Send the request answer
	send(m_iSocket, (char*) &ListResponse, sizeof(ListResponse), 0);

	// Send the data
	if (bufsize > 0)
	{
		send(m_iSocket, buf, bufsize, 0);
	}

	if (buf)
	{
		free(buf);
	}
}