Esempio n. 1
0
void testPeek()
{
  AFile_AString strfile;
  ARope rope(ASWNL("0123456789"), 4);

  size_t r;
  r = rope.peek(strfile, 3);
  std::cout << r << ":" << strfile << std::endl;

  AString str;
  r = rope.peek(str);
  std::cout << r << ":" << str << std::endl;

  str.clear();
  r = rope.peek(str, 7, 2);
  std::cout << r << ":" << str << std::endl;

  str.clear();
  r = rope.peek(str, 7, 0);
  std::cout << r << ":" << str << std::endl;

  str.clear();
  r = rope.peek(str, 1, 50);
  std::cout << r << ":" << str << std::endl;

  str.clear();
  r = rope.peek(str, 10, 1);
  std::cout << r << ":" << str << std::endl;
}
Esempio n. 2
0
void ATemplateNodeHandler_DADA::_loadStaticData()
{
  AXmlElement::CONST_CONTAINER nodes;

  m_Services.useConfiguration().getConfigRoot().find("AOS_DadaData/dataset", nodes);
  AXmlElement::CONST_CONTAINER::iterator it;
  for (it = nodes.begin(); it != nodes.end(); ++it)
  {
    AString strSet;
    (*it)->getAttributes().get(ASW("name",4), strSet);
    if (strSet.isEmpty())
      ATHROW_EX(*it, AException::InvalidData, ASWNL("AOS_DadaData/dataset missing 'name' parameter"));

    ADadaDataHolder *pddh = new ADadaDataHolder();
    pddh->readData(m_Services, *it);
    m_Objects.insert(strSet, pddh, true);
  }

  nodes.clear();
  m_Services.useConfiguration().getConfigRoot().find(ASW("AOS_DadaData/template",21), nodes);
  it = nodes.begin();
  while (it != nodes.end())
  {
    AString str;
    (*it)->emitContent(str);
    
    AString strName;
    if ((*it)->getAttributes().get(ASW("name",4), strName))
    {
      AFilename filename(m_Services.useConfiguration().getAosBaseDataDirectory(), str, false);
      if (AFileSystem::exists(filename))
      {
        AFile_Physical file(filename, ASW("r", 1));
        file.open();

        str.clear();
        while (AConstant::npos != file.readLine(str))
        {
          if ('#' != str.at(0, '\x0'))
          {
            m_Templates[strName].push_back(str);
          }
          str.clear();
        }
      }
      else
        m_Services.useLog().add(ARope("AOS_DadaData: Missing file: ")+filename, ALog::EVENT_WARNING);
    }
    else
      m_Services.useLog().add(ASWNL("AOS_DadaData: AOS_DadaData/template missing 'name' attribute"), ALog::EVENT_FAILURE);

    ++it;
  }
}
Esempio n. 3
0
int ut_AFragmentString_General(void)
{
  int iRet = 0x0;

  std::cerr << "ut_AFragmentString_General" << std::endl;

	AFragmentString fstr("foo-[1c]\\\\(4,3,1)");
	AString str;
  fstr.next(str);
	int i;
  ASSERT_UNIT_TEST(fstr.getPermutations() == 6, "AFragmentString getPermutations", "0", iRet);

  for (i=0; i<4; ++i) {
		str.clear();
    fstr.next(str);
	}
  ASSERT_UNIT_TEST(str.equals("foo-c\\0002"), "AFragmentString next", "0", iRet);

  //
	fstr.clear();
	fstr.parse("<4>");
  ASSERT_UNIT_TEST(fstr.getPermutations() == 10000, "AFragmentString getPermutations", "1", iRet);

  //
	fstr.clear();
	fstr.parse("(2)");
  ASSERT_UNIT_TEST(fstr.getPermutations() == 100, "AFragmentString getPermutations", "2", iRet);

	//
  fstr.clear();
	fstr.parse("(4,100,112,-3)");
  ASSERT_UNIT_TEST(fstr.getPermutations() == 5, "AFragmentString getPermutations", "3", iRet);
  str.clear();
	fstr.next(str);
  ASSERT_UNIT_TEST(str.equals("0112"), "AFragmentString next", "1", iRet);
	for (i=0; i<2; ++i) {
		str.clear();
    fstr.next(str);
	}
  ASSERT_UNIT_TEST(str.equals("0106"), "AFragmentString next", "2", iRet);
	for (i=0; i<2; ++i) {
		str.clear();
    fstr.next(str);
	}
  ASSERT_UNIT_TEST(str.equals("0100"), "AFragmentString next", "3", iRet);
	
	return iRet;
}
Esempio n. 4
0
void cSHA1Checksum::DigestToJava(const Checksum & a_Digest, AString & a_Out)
{
	Checksum Digest;
	memcpy(Digest, a_Digest, sizeof(Digest));
	
	bool IsNegative = (Digest[0] >= 0x80);
	if (IsNegative)
	{
		// Two's complement:
		bool carry = true;  // Add one to the whole number
		for (int i = 19; i >= 0; i--)
		{
			Digest[i] = ~Digest[i];
			if (carry)
			{
				carry = (Digest[i] == 0xff);
				Digest[i]++;
			}
		}
	}
	a_Out.clear();
	a_Out.reserve(40);
	for (int i = 0; i < 20; i++)
	{
		AppendPrintf(a_Out, "%02x", Digest[i]);
	}
	while ((a_Out.length() > 0) && (a_Out[0] == '0'))
	{
		a_Out.erase(0, 1);
	}
	if (IsNegative)
	{
		a_Out.insert(0, "-");
	}
}
Esempio n. 5
0
bool cByteBuffer::ReadString(AString & a_String, int a_Count)
{
	CHECK_THREAD;
	CheckValid();
	ASSERT(a_Count >= 0);
	NEEDBYTES(a_Count);
	a_String.clear();
	a_String.reserve(a_Count);
	int BytesToEndOfBuffer = m_BufferSize - m_ReadPos;
	ASSERT(BytesToEndOfBuffer >= 0);  // Sanity check
	if (BytesToEndOfBuffer <= a_Count)
	{
		// Reading across the ringbuffer end, read the first part and adjust parameters:
		if (BytesToEndOfBuffer > 0)
		{
			a_String.assign(m_Buffer + m_ReadPos, BytesToEndOfBuffer);
			a_Count -= BytesToEndOfBuffer;
		}
		m_ReadPos = 0;
	}

	// Read the rest of the bytes in a single read (guaranteed to fit):
	if (a_Count > 0)
	{
		a_String.append(m_Buffer + m_ReadPos, a_Count);
		m_ReadPos += a_Count;
	}
	return true;
}
Esempio n. 6
0
int ut_ATextGenerator_General()
{
  std::cerr << "ut_ATextGenerator_General" << std::endl;

  int iRet = 0x0;

  AString str;
  bool errorOccured = false;
  for (int iX=0; iX < 666; ++iX)
  {
    u4 sizeNeeded = ARandomNumberGenerator::get().nextRange(300, 16);
    //std::cerr << "ATextGenerator::generateUniqueId size: " << sizeNeeded << std::endl;
    ATextGenerator::generateUniqueId(str, sizeNeeded);
    if (str.getSize() != sizeNeeded)
    {
      std::cerr << "ATextGenerator::generateUniqueId failed for size: " << sizeNeeded << std::endl;
      iRet++;
      errorOccured = true;
      break;
    }
    str.clear();
  }
  if (!errorOccured)
    std::cerr << "." << std::flush;

  return iRet;
}
Esempio n. 7
0
// Converts a raw 160-bit SHA1 digest into a Java Hex representation
// According to http://wiki.vg/wiki/index.php?title=Protocol_Encryption&oldid=2802
static void DigestToJava(byte a_Digest[20], AString & a_Out)
{
	bool IsNegative = (a_Digest[0] >= 0x80);
	if (IsNegative)
	{
		// Two's complement:
		bool carry = true;  // Add one to the whole number
		for (int i = 19; i >= 0; i--)
		{
			a_Digest[i] = ~a_Digest[i];
			if (carry)
			{
				carry = (a_Digest[i] == 0xff);
				a_Digest[i]++;
			}
		}
	}
	a_Out.clear();
	a_Out.reserve(40);
	for (int i = 0; i < 20; i++)
	{
		AppendPrintf(a_Out, "%02x", a_Digest[i]);
	}
	while ((a_Out.length() > 0) && (a_Out[0] == '0'))
	{
		a_Out.erase(0, 1);
	}
	if (IsNegative)
	{
		a_Out.insert(0, "-");
	}
}
Esempio n. 8
0
bool AMySQLServer::convert(MYSQL_ROW row, int index, AString& result)
{
  const char *p = row[index];
  result.clear();
  if (p)
    result = p;

  return true;
}
Esempio n. 9
0
int main()
{
  AFile_IOStream iosfile;
  AString str;
  while (AString::npos != iosfile.readLine(str))
  {
    std::cout << "'" << str << "'=" << str.getHash() << "\t" << str.getHash(0xff) << "\t" << str.getHash(0xf) << std::endl;
    str.clear();
  }
}
Esempio n. 10
0
void testXml(int& iRet)
{
  //a_XML value parsing
  AString str;
  ANameValuePair nvPair(ANameValuePair::XML);
  size_t pos = 0;

  nvPair.parse("  \t \t   \n \r \r\n  iam   \r = \n \t  \"a'b'c'\" \r\n ", pos);
  nvPair.emit(str);
  ASSERT_UNIT_TEST(str == "iam=\"a'b'c'\"", "Handling of single quote in double quote error", "0", iRet);

  pos = 0;
  str.clear();
  nvPair.parse("  \t \t   \n \r \r\n  iam   \r = \t  \"Myvalue's value\"  ", pos);
  nvPair.emit(str);
  ASSERT_UNIT_TEST(str == "iam=\"Myvalue's value\"", "Handling of single quote in double quote error", "1", iRet);

  pos = 0;
  str.clear();
  nvPair.parse("iam = 'is \"quoted\" often'", pos);
  nvPair.emit(str);
  ASSERT_UNIT_TEST(str == "iam='is \"quoted\" often'", "Handling of double quote in single quote error", "", iRet);
}
Esempio n. 11
0
void testSelect(ADatabase& db)
{
  AString error;
  AResultSet rs;
  
  u4 rows = db.executeSQL("SELECT * from global", rs, error);
  if (AString::npos == rows)
  {
    std::cerr << error << std::endl;
  }
  else
  {
    std::cout << "Selected " << rows << " rows." << std::endl;
    
    AXmlElement root("root");
    rs.emit(root);
    ARope rope;
    root.emitXml(rope, 0);
    std::cout << rope << std::endl;
  }

  u4 myNameCol = rs.getFieldIndex("name");
  u4 myValueCol = rs.getFieldIndex("value");
  for (u4 row=0; row<rs.getRowCount(); ++row)
  {
    const AString& name = rs.getData(row, myNameCol);
    if (name.equals("test_query"))
    {
      AQueryString qs(rs.getData(row, myValueCol));
      AString str;
      qs.emit(str);
      std::cout << "Query string detected: " << str << std::endl;
    }
    else if (name.equals("flags"))
    {
      ABitArray flags(rs.getData(row, myValueCol));
      AString str;
      flags.emit(str);
      std::cout << "Flags found: " << str << std::endl;

      str.clear();
      flags.setOutputMode(ABitArray::Binary);
      flags.emit(str);
      std::cout << "Flags found: " << str << std::endl;
    }
  }
}
Esempio n. 12
0
/*!
Uses the model to emit content for a path

thisfunction("<path to the AXmlElement to emit>", separate)

lua namespace: model
lua param: Path to emit
lua param: if non-nil then each element found will be returned by itself
lua return: Content at the given path or nil if element does not exist
*/
static int alibrary_Objects_Model_emitContentFromPath(lua_State *L)
{
    ATemplateContext *pLuaContext = static_cast<ATemplateContext *>(L->acontext);
    AASSERT(NULL, pLuaContext);

    size_t len = AConstant::npos;
    const char *s = luaL_checklstring(L, 1, &len);
    const AString& xmlpath = AString::wrap(s, len);

    int mode = 0;
    if (lua_gettop(L) > 1)
        mode = luaL_checkint(L, 2);

    AXmlElement::CONST_CONTAINER nodes;
    size_t ret = pLuaContext->useModel().useRoot().find(xmlpath, nodes);

    if (mode)
    {
        //a_Return each as separate values
        AString str;
        for (AXmlElement::CONST_CONTAINER::const_iterator cit = nodes.begin(); cit != nodes.end(); ++cit)
        {
            (*cit)->emitContent(str);
            lua_pushlstring(L, str.c_str(), str.getSize());
            str.clear();
        }
        return (int)ret;
    }
    else
    {
        if (ret > 0)
        {
            //a_Return content concatinated
            ARope rope;
            for (AXmlElement::CONST_CONTAINER::const_iterator cit = nodes.begin(); cit != nodes.end(); ++cit)
                (*cit)->emitContent(rope);

            const AString& str = rope.toAString();
            lua_pushlstring(L, str.c_str(), str.getSize());

            return 1;
        }
        else
            return 0;
    }
}
int main(int argc, char* argv[])
{
  if (argc < 2)
  {
    std::cout << "Usage: this <database name> <query>" << std::endl;
    std::cout << "If <query> is omitted, database metadata is dumped" << std::endl;
    return -1;
  }

  AMySQLServer server(argv[1]);
  AString strError;
  if (!server.init(strError))
  {
    std::cout << strError << std::endl;
    return -1;
  }
  
  AString strQuery("select * from item where id=2");
  ADatabaseObject qr("myquery");
  if (!server.executeSQL(qr, strQuery, strError))
  {
    std::cout << strError << std::endl;
    return -1;
  }

  AElement element;
  AString result;
  qr.publish(&element);
  element.asXml(result);
  std::cout << result << std::endl;

  std::cout << "Only row 0" << std::endl;
  result.clear();
  const AObjectContainer& ns = qr.getRow(0);
  std::cout <<
    "id=" <<
    ns.getAs<AString>("id") <<
    " name=" <<
    ns.getAs<AString>("name") << 
    " weight=" << 
    ns.getAs<AString>("creator") << 
    std::endl;

  return 0;
}
Esempio n. 14
0
bool cSocketInputStream::GetLineInternal(AString & a_OutLine)
{
	a_OutLine.clear();
	for (;;)
	{
		char c;
		if (recv(m_Socket, &c, 1, 0) != 1)
		{
			return false;
		}
		if (c == 10)
		{
			return true;
		}
		else if (c != 13)
		{
			a_OutLine.push_back(c);
		}
	}
}
Esempio n. 15
0
String8 InitDataParser::generateRequest(const Vector<const uint8_t*>& keyIds) {
    const String8 kRequestPrefix("{\"kids\":[");
    const String8 kRequestSuffix("],\"type\":\"temporary\"}");
    const String8 kBase64Padding("=");

    String8 request(kRequestPrefix);
    AString encodedId;
    for (size_t i = 0; i < keyIds.size(); ++i) {
        encodedId.clear();
        android::encodeBase64Url(keyIds[i], kKeyIdSize, &encodedId);
        if (i != 0) {
            request.append(",");
        }
        request.appendFormat("\"%s\"", encodedId.c_str());
    }
    request.append(kRequestSuffix);

    // Android's Base64 encoder produces padding. EME forbids padding.
    request.removeAll(kBase64Padding);
    return request;
}
Esempio n. 16
0
AFramework::uint8 AFramework::MTempMaster::readTemp(AString &addr, const uint32 ms){

    AString str;
    AStringList *list;
    bool    flag = false;
    if(!m_xbee){
    
        return 0;
    }
    addr += _MTEMP_SEP;
    addr += _MTEMP_TEMPGET;
    m_xbee->send(addr);
    if(m_xbee->receive(_MTEMP_BOARD_OK, ms)){
        
        m_xbee->read(str); 
        list = str.split(_MTEMP_SEP);
        str.clear();
        str = list->at(1);
        delete list;
        return static_cast<uint8>(str.toInt32(flag));
    }
    return 0;
}
Esempio n. 17
0
bool AFramework::MTempMaster::programsManager(const bool read){                                                //da fare
    
    ADateTime currentClk;
    Program prg;
    AString str;
    
    if(!m_flag){
        
        return false;
    }
    
    if(read){
        for(uint8 i = 0; i < _MTEMP_ROOM_VEC_SIZE; i++){
            
            if(m_rooms[i].currentTemperature() != 0){           //se il sensore è vivo
                
                str.clear();
                str = m_rooms[i].sensorAddress();
                m_rooms[i].setTemperature(readTemp(str, 1000));      //aggiorno la temperatura
            }
        }
    }
    if(m_clk->isGood()){
        
        currentClk = m_clk->currentTime();

        for(uint8 i=0; i < _MTEMP_ROOM_VEC_SIZE; i++){

            prg = m_rooms[i].program(currentClk.Weekday());
            
            if(m_rooms[i].isAuto()){
                
                if(prg.isEnabled()){
                    
                    if( ((prg.startHours() == currentClk.hours() && prg.startMinutes() <= currentClk.minutes())
                                                             ||
                                           (prg.startHours() < currentClk.hours()))    
                                                             &&
                    ((prg.endHours() == currentClk.hours() && prg.endMinutes() >= currentClk.minutes())
                                                             ||
                                            (prg.endHours() > currentClk.hours()))) {
                        
                        if(m_rooms[i].currentTemperature() <= prg.targetTemperature()){
                           
                            m_rooms[i].on();
                        }else{
                            
                            m_rooms[i].off();
                        }    
                    }else{
                    
                        m_rooms[i].off();
                    }   
                }else{
                
                    m_rooms[i].off();
                }
            }
            
            if(m_rooms[i].isForcedOff()){           //se lo spegnimento è forzato

                m_rooms[i].off();               //metto off la porta
            }
            
            if(m_rooms[i].isForcedOn()){            

                m_rooms[i].on();                //metto on la porta

            }
        }
    }else{
        
        m_lcd->clear();
        m_lcd->write("Errore ora");
        System::delay(1000);
    }
    return false;
}
Esempio n. 18
0
int main(int argc, char **argv)
{
  bool bRun = true;
  
  u4 iteration = 0;
  AThread thread(threadProc);
  thread.setParameter((void *)&iteration);

  AString cmd;
  AFile_IOStream io;
  while (bRun)
  {
    std::cout << ">";
    io.readLine(cmd);
    if (!cmd.compareNoCase("status"))
    {
      if (thread.isThreadActive())
      {
        u4 id = thread.getId();
        u4 iter = *(u4 *)thread.getParameter();
        std::cout << "Thread active, id=" << id << " iteration=" << iter << std::endl;
      }
      else if (thread.wasStarted())
      {
        u4 exitCode = thread.getExitCode();
        u4 iter = *(u4 *)thread.getParameter();
        std::cout << "Thread exited, return=" << exitCode << " iteration=" << iter << std::endl;
      }
      else
      {
        std::cout << "Thread has never started." << std::endl;
      }
    }
    else if (!cmd.compareNoCase("start"))
    {
      if (!thread.isThreadActive())
      {
        thread.clearFlag(ATHREAD_STOP);
        thread.start();  
      }
      else
      {
        std::cout << "Thread already running." << std::endl;
      }
    }
    else if (!cmd.compareNoCase("pause"))
    {
      thread.setFlag(ATHREAD_PAUSE);
    }
    else if (!cmd.compareNoCase("resume"))
    {
      thread.clearFlag(ATHREAD_PAUSE);
    }
    else if (!cmd.compareNoCase("stop"))
    {  
      if (thread.isThreadActive())
      {
        thread.setFlag(ATHREAD_STOP);
        std::cout << "Trying to stop" << std::flush;
        while (thread.isThreadActive())
        {
          AThread::sleep(100);
          std::cout << "." << std::flush;
        }
        std::cout << std::endl;
      }
    }
    else if (!cmd.compareNoCase("exit"))
    {
      if (thread.isThreadActive())
      {
        thread.setFlag(ATHREAD_STOP);
        std::cout << "Trying to stop" << std::flush;
        while (thread.isThreadActive())
        {
          AThread::sleep(100);
          std::cout << "." << std::flush;
        }
        std::cout << std::endl;
      }

      bRun = false;
    }

    cmd.clear();
  }

  return 0;
}
Esempio n. 19
0
void cCompositeChat::ParseText(const AString & a_ParseText)
{
	size_t len = a_ParseText.length();
	size_t first = 0;  // First character of the currently parsed block
	AString CurrentStyle;
	AString CurrentText;
	for (size_t i = 0; i < len; i++)
	{
		switch (a_ParseText[i])
		{
			case '@':
			{
				// Color code
				i++;
				if (i >= len)
				{
					// Not enough following text
					break;
				}
				if (a_ParseText[i] == '@')
				{
					// "@@" escape, just put a "@" into the current text and keep parsing as text
					if (i > first + 1)
					{
						CurrentText.append(a_ParseText.c_str() + first, i - first - 1);
					}
					first = i + 1;
					continue;
				}
				else
				{
					// True color code. Create a part for the CurrentText and start parsing anew:
					if (i >= first)
					{
						CurrentText.append(a_ParseText.c_str() + first, i - first - 1);
						first = i + 1;
					}
					if (!CurrentText.empty())
					{
						m_Parts.push_back(new cTextPart(CurrentText, CurrentStyle));
						CurrentText.clear();
					}
					AddStyle(CurrentStyle, a_ParseText.substr(i - 1, 2));
				}
				break;
			}

			case ':':
			{
				const char * LinkPrefixes[] =
				{
					"http",
					"https"
				};
				for (size_t Prefix = 0; Prefix < ARRAYCOUNT(LinkPrefixes); Prefix++)
				{
					size_t PrefixLen = strlen(LinkPrefixes[Prefix]);
					if (
						(i >= first + PrefixLen) &&  // There is enough space in front of the colon for the prefix
						(strncmp(a_ParseText.c_str() + i - PrefixLen, LinkPrefixes[Prefix], PrefixLen) == 0)  // the prefix matches
					)
					{
						// Add everything before this as a text part:
						if (i > first + PrefixLen)
						{
							CurrentText.append(a_ParseText.c_str() + first, i - first - PrefixLen);
							first = i - PrefixLen;
						}
						if (!CurrentText.empty())
						{
							AddTextPart(CurrentText, CurrentStyle);
							CurrentText.clear();
						}

						// Go till the last non-whitespace char in the text:
						for (; i < len; i++)
						{
							if (isspace(a_ParseText[i]))
							{
								break;
							}
						}
						AddUrlPart(a_ParseText.substr(first, i - first), a_ParseText.substr(first, i - first), CurrentStyle);
						first = i;
						break;
					}
				}  // for Prefix - LinkPrefix[]
				break;
			}  // case ':'
		}  // switch (a_ParseText[i])
	}  // for i - a_ParseText[]
	if (first < len)
	{
		AddTextPart(a_ParseText.substr(first, len - first), CurrentStyle);
	}
}
Esempio n. 20
0
void AWordUtility::getSoundexForm(const AString& source, AString& result, size_t minSize)
{
  result.clear();
  if (source.isEmpty())
    return;

  //a_First character appended as is
  AString str(source);
  str.makeLower();
  size_t sourceSize = str.getSize();

  size_t pos = 0;
  while (pos < sourceSize)
  {
    switch(str.at(pos))
    {
      case 'a':
      case 'e':
      case 'i':
      case 'o':
      case 'u':
      case 'h':
      case 'w':
      case 'y':
        break;
//---      
      case 'p':
        if (pos == 0 && sourceSize > 2)
        {
          if ('s' == str.at(pos+1))
          {
            break;  //a_ps => s at word start
          }
          else if ('h' == str.at(pos+1))
          {
            ++pos; //a_pf => f, fallthrough
          }
        }
      case 'b':
      case 'f':
      case 'v':
        if (!result.isEmpty())
        {
          if (str.at(pos) != result.at(result.getSize()-1))
            result.append('1');
        }
        else
            result.append('1');
        break;
//---      
      case 'd':
        if (pos+1 < sourceSize)
        {
          if ('g' == str.at(pos+1))
            break;        //a_dg => g
        }                 //a_Fallthough from d to t
      case 't':
        if (pos+1 < sourceSize && 'c' == str.at(pos+1))
        {
          if (pos+2 < sourceSize && 'h' == str.at(pos+2))
          {
            ++pos;
            break;  //a_tch => ch
          }
        }
        if (!result.isEmpty())
        {
          if (str.at(pos) != result.at(result.getSize()-1))
            result.append('3');
        }
        else
            result.append('3');
        break;
//---      
      case 'g':
        if (pos+1 < sourceSize)
        {
          if ('h' == str.at(pos+1))
          {
            if (pos+2 < sourceSize)
            {
              if ('t' == str.at(pos+2))
              {
                ++pos;
                break;   //a_ght => t
              }
              else
                break;   //a_gh => h
            }
          }
          else if ('n' == str.at(pos+1))
          {
            break;       //a_gn => n
          }
        } //a_Fallthrough

      case 'k':
        if (pos+1 < sourceSize && 'n' == str.at(pos+1))
        {
          break;       //a_kn => n
        }  //a_Fallthrough

      case 'c':
      case 'j':
      case 'q':
      case 's':
      case 'x':
      case 'z':
        if (!result.isEmpty())
        {
          if (str.at(pos) != result.at(result.getSize()-1))
            result.append('2');
        }
        else
            result.append('2');
        break;
//---      
      case 'l':
        if (!result.isEmpty())
        {
          if (str.at(pos) != result.at(result.getSize()-1))
            result.append('4');
        }
        else
            result.append('4');
        break;
//---      
      case 'm':
        if ('b' == str.at(pos+1, '\x0'))
        {
          ++pos;  //a_mb => m
        } //a_ Fallthrough
      case 'n':
        if (!result.isEmpty())
        {
          if (str.at(pos) != result.at(result.getSize()-1))
            result.append('5');
        }
        else
            result.append('5');
//---      
      case 'r':
        if (!result.isEmpty())
        {
          if (str.at(pos) != result.at(result.getSize()-1))
            result.append('6');
        }
        else
            result.append('6');
        break;
    }
    ++pos;
  }

  if (result.getSize() < minSize)
    result.setSize(minSize, '0');
}
Esempio n. 21
0
bool AFramework::MTempMaster::run(){
    
    AString currentCmd;
    AString str;
    AString sensAdd;
    uint8 temp = 0;
    
    if(!m_flag){
        
        return false;
    }
    if(joinNetwork()){
            
            /* joinNetwork da direttamente l'output                             */
        if(!loadAll()){
            
            msg("Errore\nCaricamento", 0);
            while(1);
        }
        
            //cerco per due volte i sensori vicini
            readTemp(str);
            for(uint8 i = 0; i < _MTEMP_ROOM_VEC_SIZE; i++){

                str.clear();
                str = m_rooms[i].sensorAddress();
                sensAdd = "Ricerco\nSensore ";
                sensAdd += m_rooms[i].sensorAddress();
                msg(sensAdd);
                temp = 0;
                temp = readTemp(str);
                m_rooms[i].setTemperature(temp);
                if(temp != 0){
                    sensAdd.clear();
                    sensAdd += "Sensore ";
                    sensAdd += m_rooms[i].sensorAddress();
                    sensAdd += "\nTrovato";
                    msg(sensAdd);
                }else{
                    sensAdd.clear();
                    sensAdd += "Sensore ";
                    sensAdd += m_rooms[i].sensorAddress();
                    sensAdd += "\nNon trovato";
                    msg(sensAdd);
                }
            }
            
            msg("In ascolto...", 0);
            m_wifi->prepareForReceive();
            PortA.write(bit7, Hi);
            System::delay(1000);
            PortA.write(bit7, Lo);
            ATime time = System::aliveTime();
            time.addMinutes(1);
            while(1){
                
                if(m_wifi->waitForData(currentCmd, 0)){
                    
                    PortA.write(bit7, Hi);
                    commandExec(currentCmd);
                    PortA.write(bit7, Lo);
                    currentCmd.clear();
                }else{
                    if(System::aliveTime() <= time){
                        
                        programsManager(false);
                    }else{
                        
                        programsManager(true);
                        time.addMinutes(1);
                    }
                }
            }
    }else{
        /*  joinNetwork da direttamente l'output                                */
        while(1);
    }
}
Esempio n. 22
0
int main(int argc, char **argv)
{
  if (argc < 2)
  {
    std::cout << "Usage: this [SQLite database URL]" << std::endl;
    std::cout << "e.g. this sqlite://q:/mydata.db" << std::endl;
    return -1;
  }
  
  AUrl url(argv[1]);
  ASQLiteServer db(url);
  AString error;

  if (!db.init(error))
  {
    std::cerr << error << std::endl;
    return -1;
  }
  
  AString input;
  AFile_IOStream iof;
  std::cout << "\r\nsqlite [?=help]>" << std::flush;
  while(AString::npos != iof.readLine(input))
  {
    if (input.equals("createAOSTables"))
    {
      if (AString::npos == createAOSTables(db, error))
        std::cerr << error << std::endl;
      else
        std::cout << "AOS tables created." << std::endl;
    }
    else if (input.equals("?"))
    {
      std::cout << "Enter SQL query or use one of the following built in functions:\r\n";
      std::cout << "  createAOSTables - create databases used by base AOS server modules\r\n";
      std::cout << std::endl;
    }
    else if (input.equals("exit"))
    {
      return 0;
    }
    else
    {
      AResultSet rs;
      u4 rows = db.executeSQL(input, rs, error);
      if (AString::npos == rows)
      {
        std::cerr << error << std::endl;
        error.clear();
      }
      else
      {
        std::cout << "Success, rows affected=" << rows << std::endl;
        ARope rope;
        rs.emit(rope);
        std::cout << rope << std::endl;
      }
    }
    input.clear();
    std::cout << "\r\nsqlite>" << std::flush;
  }

  return 0;
}
Esempio n. 23
0
int ut_ATextConverter_General()
{
  std::cerr << "ut_ATextConverter_General" << std::endl;

  int iRet = 0x0;

  AString result;
  AString str("!<HTML>&...");
  ATextConverter::makeHtmlSafe(str, result);
  ASSERT_UNIT_TEST(result.equals("!&lt;HTML&gt;&amp;..."), "ATextConverter::makeHtmlSafe", "0", iRet);

  result.clear();
  str.assign("<><HTML>&...&");
  ATextConverter::makeHtmlSafe(str, result);
  ASSERT_UNIT_TEST(result.equals("&lt;&gt;&lt;HTML&gt;&amp;...&amp;"), "ATextConverter::makeHtmlSafe", "1", iRet);

  //a_Round trips
  AString strR;
  str = "±(S3t¯th3~co^tro|$~f0r~the~he@rt~of~the¯sµ^!)²÷exit`";
  result.clear();
  ATextConverter::encodeHEX(str, strR);
  ATextConverter::decodeHEX(strR, result);
  ASSERT_UNIT_TEST(result.equals(str), "HEX roudtrip", "", iRet);
  
  strR.clear();
  result.clear();
  ATextConverter::encodeURL(str, strR);
  ATextConverter::decodeURL(strR, result);
  ASSERT_UNIT_TEST(result.equals(str), "URL roudtrip", "", iRet);

  strR.clear();
  result.clear();
  ATextConverter::encodeBase64(str, strR);
  ATextConverter::decodeBase64(strR, result);
  ASSERT_UNIT_TEST(result.equals(str), "Base64 roudtrip", "", iRet);

  strR.clear();
  result.clear();
  ATextConverter::encode64(str, strR);
  ATextConverter::decode64(strR, result);
  ASSERT_UNIT_TEST(result.equals(str), "encode64 roudtrip", "", iRet);

  //a_Base64
  result.clear();
  ATextConverter::encodeBase64("foo:bar", result);
  ASSERT_UNIT_TEST(result.equals("Zm9vOmJhcg=="), "Base64 encode", "", iRet);
  result.clear();
  ATextConverter::decodeBase64("Zm9vOmJhcg==", result);
  ASSERT_UNIT_TEST(result.equals("foo:bar"), "Base64 decode", "", iRet);

  //a_CData safe
  str.assign("!INVALID]]> CData string! ]]> !");
  strR.assign("!INVALID%5d%5d%3e CData string! %5d%5d%3e !");
  result.clear();
  ATextConverter::makeCDataSafe(str, result);
  ASSERT_UNIT_TEST(result.equals(strR), "makeCDataSafe", "", iRet);

  return iRet;
}
Esempio n. 24
0
void AFramework::MTempMaster::commandExec(const AString &cmd){
    
    AStringList *   list;
    AString         str;
    ADateTime       time;
    bool            flag = false;
    uint8           index = 0;
    uint8           index1 = 0;
    
    list = cmd.split(_MTEMP_SEP);
    
    if(list && cmd.good()){
        
        if(list->at(0) == m_username && list->at(1) == m_password){
            
            str = list->at(list->size() - 1);
            
            if(str == _MTEMP_TIMESET){
                //*  (CLIENT)        username*password*AA*MM*GG*WD*HH*MM*SS*[TIMESET]
                if(time.setYear(list->at(2).toInt32(flag)) && flag){
                    
                    if(time.setMonth(static_cast<ADateTime::Months>(list->at(3).toInt32(flag))) && flag){
                        
                        if(time.setDayOfMonth(list->at(4).toInt32(flag)) && flag){
                            
                            if(time.setWeekday(static_cast<ADateTime::Weekdays>(list->at(5).toInt32(flag))) && flag){
                                
                                if(time.setHours(list->at(6).toInt32(flag)) && flag){
                                    
                                    if(time.setMinutes(list->at(7).toInt32(flag)) && flag){
                                        
                                        if(time.setSeconds(list->at(8).toInt32(flag)) && flag){
                                            
                                            if(m_clk->setTime(time)){
                                                
                                                if(m_wifi->send(_MTEMP_BOARD_OK)){
                                                    
                                                    str.clear();
                                                    str = m_clk->currentTime().timeToString();
                                                    str.prepend("Ora settata\n");
                                                    msg(str, 0);
                                                    delete list;
                                                    return;
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }

            }else if(str == _MTEMP_TIMEGET){
                
                //*  (CLIENT)        username*password*[TIMEGET]
                //*  (SERVER)        (AA*MM*GG*WD*HH*MM*SS*[OK] || [FAIL] || [ERROR])
                
                if(m_clk->isGood()){
                    str.clear();
                    time = m_clk->currentTime();
                    str += AString(time.year());
                    str += _MTEMP_SEP;
                    str += AString(static_cast<uint8>(time.month()));
                    str += _MTEMP_SEP;
                    str += AString(time.dayOfMonth());
                    str += _MTEMP_SEP;
                    str += AString(static_cast<uint8>(time.Weekday()));
                    str += _MTEMP_SEP;
                    str += AString(time.hours());
                    str += _MTEMP_SEP;
                    str += AString(time.minutes());
                    str += _MTEMP_SEP;
                    str += AString(time.seconds());
                    str += _MTEMP_SEP;
                    str += _MTEMP_BOARD_OK;
                    m_wifi->send(str);
                    delete list;
                    return;
                }else{
                    
                    m_wifi->send(_MTEMP_BOARD_FAIL);
                    msg("Errore...\nOrologio");
                    delete list;
                    return;
                }
                delete list;
                return;
            }else if(str == _MTEMP_TEMPGET){
                
                //(CLIENT)        username*password*R*[TEMPGET]
                //(SERVER)        R*TT*([OK] || [FAIL] || [ERROR])
                index = list->at(2).toInt32(flag);
                if(flag && index < _MTEMP_ROOM_VEC_SIZE){
                    
                    str.clear();
                    str += list->at(2);
                    str += _MTEMP_SEP;
                    
                    /////////////////////////////////////////////////////////////////////////////////////////
                    //AString prova = m_rooms[index].sensorAddress();
                    //str += AString(readTemp(prova, 500));
                    
                    str += AString(m_rooms[index].currentTemperature());                ///////////da fare per casa
                    
                    /////////////////////////////////////////////////////////////////////////////////////////////
                    str += _MTEMP_SEP;
                    str += _MTEMP_BOARD_OK;
                    m_wifi->send(str);
                    delete list;
                    return;
                }else{
                    
                    m_wifi->send(_MTEMP_BOARD_FAIL);
                    delete list;
                    return;
                }
                delete list;
                return;
            }else if(str == _MTEMP_ROOMSTAT){
                
                //(CLIENT)    username*password*R*[ROOMSTAT]
                //(SERVER)    (R*NAME*STATE*ISFORCEDON*ISFORCEDOFF*TT*[OK] || [FAIL] || [ERROR])
                index = list->at(2).toInt32(flag);
                if(flag && index < _MTEMP_ROOM_VEC_SIZE){
                
                    str.clear();
                    str += list->at(2);         
                    str += _MTEMP_SEP;
                    str += m_rooms[index].roomName();
                    str += _MTEMP_SEP;
                    str += (m_rooms[index].isOn() ? _MTEMP_ENABLED : _MTEMP_DISABLED);
                    str += _MTEMP_SEP;
                    str += (m_rooms[index].isForcedOn() ? _MTEMP_ENABLED : _MTEMP_DISABLED);
                    str += _MTEMP_SEP;
                    str += (m_rooms[index].isForcedOff() ? _MTEMP_ENABLED : _MTEMP_DISABLED);
                    str += _MTEMP_SEP;
                    ///////////////////////////////////////////////////////////////////////////////////////////
                    //AString prova = m_rooms[index].sensorAddress();
                    //str += AString(readTemp(prova, 1000));
                    str += AString(m_rooms[index].currentTemperature());
                    //////////////////////////////////////////////////////////////////////////////////////////
                    
                    str += _MTEMP_SEP;
                    str += _MTEMP_BOARD_OK;
                    m_wifi->send(str);
                }else{
                    
                    m_wifi->send(_MTEMP_BOARD_FAIL);
                }
                delete list;
                return;
            }else if(str == _MTEMP_ROOMSET){
                
                //username*password*R*NAME*FORCEON*FORCEOFF*AUTO*[ROOMSET]
                //([OK] || [FAIL] || [ERROR])
                
                index = list->at(2).toInt32(flag);          //numero stanza                 
                if(flag && index < _MTEMP_ROOM_VEC_SIZE){
                
                    if(m_rooms[index].setRoomName(list->at(3))){

                        if(m_rooms[index].forceOn(list->at(4) == _MTEMP_ENABLED)){

                            if(m_rooms[index].forceOff(list->at(5) == _MTEMP_ENABLED)){

                                if(m_rooms[index].setAuto(list->at(6) == _MTEMP_ENABLED)){

                                    if(m_rooms[index].saveRoom()){

                                        m_wifi->send(_MTEMP_BOARD_OK);
                                        delete list;
                                        return;
                                    }
                                }
                            }
                        }
                    }
                }
                m_wifi->send(_MTEMP_BOARD_FAIL);
                delete list;
                return;
            }else if(str == _MTEMP_PROGGET){
                
                //(CLIENT)    username*password*R*D*[PROGGET]                           
                //(SERVER)    (R*D*HS*MS*HE*ME*TT*E*[OK] || [FAIL] || [ERROR])
                index = list->at(2).toInt32(flag);          //numero stanza                 
                if(flag && index < _MTEMP_ROOM_VEC_SIZE){
                    
                    index1 = list->at(3).toInt32(flag);      //numero programma   
                    if(flag && index1 > 0 && index1 <= _MTEMP_WEEKPROGRAM_VEC_SIZE){
                        
                        str.clear();
                        str += list->at(2);
                        str += _MTEMP_SEP;
                        str += m_rooms[index].program(static_cast<ADateTime::Weekdays>(index1)).toString();
                        str += _MTEMP_SEP;
                        str += _MTEMP_BOARD_OK;
                        m_wifi->send(str);
                        delete list;
                        return;
                    }
                }
                m_wifi->send(_MTEMP_BOARD_FAIL);
                delete list;
                return;
            }else if(str == _MTEMP_PROGSET){
                
                //(CLIENT)    username*password*R*D*HS*MS*HE*ME*TT*E*[PROGSET]
                //(SERVER)    ([OK] || [FAIL] || [ERROR])
                index = list->at(2).toInt32(flag);          //numero stanza
                if(flag && index < _MTEMP_ROOM_VEC_SIZE){
                    
                    index1 = list->at(3).toInt32(flag);      //numero programma   
                    if(flag && index1 > 0 && index1 <= _MTEMP_WEEKPROGRAM_VEC_SIZE){                
                        
                        str.clear();
                        for(uint8 i = 3; i < 9; i++){
                            
                            str += list->at(i);
                            str += _MTEMP_SEP;   
                        }
                        str += list->at(9);
                        if(m_rooms[index].setProgram((static_cast<ADateTime::Weekdays>(index1)), str)){
                            
                            if(m_rooms[index].saveProgram(static_cast<ADateTime::Weekdays>(index1))){
                                
                                m_wifi->send(_MTEMP_BOARD_OK);
                                delete list;
                                return;
                            }
                        }
                    }
                }
                m_wifi->send(_MTEMP_BOARD_FAIL);
                delete list;
                return;
            }else if(str == _MTEMP_FORCEON){
                
                //(CLIENT)    username*password*R*[FORCEON]
                //(SERVER)    ([OK] || [FAIL] || [ERROR])
                index = list->at(2).toInt32(flag);
                if(flag && index < _MTEMP_ROOM_VEC_SIZE){
                    
                    m_rooms[index].forceOn(true);
                    m_wifi->send(_MTEMP_BOARD_OK);
                }else{
                    
                    m_wifi->send(_MTEMP_BOARD_FAIL);
                }
                delete list;
                return;
            }else if(str == _MTEMP_FORCEOFF){
                
                //(CLIENT)    username*password*R*[FORCEOFF]
                //(SERVER)    ([OK] || [FAIL] || [ERROR])
                index = list->at(2).toInt32(flag);
                if(flag && index < _MTEMP_ROOM_VEC_SIZE){
                    
                    m_rooms[index].forceOff(true);
                    m_wifi->send(_MTEMP_BOARD_OK);
                }else{
                    
                    m_wifi->send(_MTEMP_BOARD_FAIL);
                }
                delete list;
                return;    
            }else{      //altro comando 
                
                m_wifi->send(_MTEMP_BOARD_FAIL);
                delete list;
                return;
            }
        }else{              //login fallito
            
            m_wifi->send(_MTEMP_BOARD_ERROR);
            delete list;
            return;
        }
    }       //split fallita
    
    if(list){
        
        delete list;
        msg("Errore\nCmd Handler");
        m_wifi->send(_MTEMP_BOARD_ERROR);
    }
    return;
}
Esempio n. 25
0
void ATemplateNodeHandler_DADA::Node::_appendWordType(ADadaDataHolder *pddh, MAP_AString_AString& globals, const AString& strType, AOutputBuffer& target)
{
  //a_First remove control tags "TYPE:controltag1,controltag2,..."
  AString strTypeName, strControl;
  LIST_AString listControlNames;
  size_t pos = strType.find(':');
  if (AConstant::npos != pos)
  {
    strType.peek(strTypeName, 0, pos);
    strTypeName.makeLower();

    strType.peek(strControl, pos+1);
    strControl.makeLower();
    strControl.split(listControlNames, ',', AConstant::ASTRING_WHITESPACE);
  }
  else
  {
    strTypeName.assign(strType);
    strTypeName.makeLower();
  }

  ADadaDataHolder::WORDMAP::iterator it = pddh->useWordMap().find(strTypeName);
  if (pddh->useWordMap().end() != it)
  {
    VECTOR_AString& vec = (*it).second;
    u4 index = ARandomNumberGenerator::get().nextRange((int)vec.size());
    
    AString strSaveVariable;
    AString str(vec.at(index));
    
    //a_Apply control code actions
    LIST_AString::iterator itN = listControlNames.begin();
    while (itN != listControlNames.end())
    {
      if ('$' == (*itN).at(0, '\x0'))
      {
        //a_Add variable to global map
        (*itN).peek(strSaveVariable, 1);
        globals[strSaveVariable] = str;
        strSaveVariable.clear();
      }
      else if (!strTypeName.compare("verb"))
      {
        //a_Verb only control
        if (!(*itN).compare("present", 7))
        {
          if (AConstant::npos != AWordUtility::sstr_Vowels.find(str.last()))
          {
            //a_Vowel at the end is removed and replaced with "ing"
            str.rremove(1);
          }
          str.append("ing", 3);
        }
        else if (!(*itN).compare("past", 4))
        {
          if (AConstant::npos == AWordUtility::sstr_Vowels.find(str.last()))
          {
            str.append("ed", 2);
          }
          else
          {
            str.append("d", 1);
          }
        }
      }

      if (!(*itN).compare("article", 7))
      {
        AString strTemp(str);
        if (AConstant::npos == AWordUtility::sstr_Vowels.find(str.at(0)))
        {
          str.assign("a ", 2);
        }
        else
        {
          str.assign("an ", 3);
        }
        str.append(strTemp);
      }

      if (!(*itN).compare("plural", 6))
      {
        AString strTemp;
        AWordUtility::getPlural(str, strTemp);
        str.assign(strTemp);
      }

      if (!(*itN).compare("uppercase", 9))
      {
        str.makeUpper();
      }

      if (!(*itN).compare("lowercase", 9))
      {
        str.makeLower();
      }

      if (!(*itN).compare("proper", 6))
      {
        str.use(0) = (u1)toupper(str.at(0));

        size_t nextStart;
        size_t nextSpace = str.find(' ', 1);
        while (AConstant::npos != nextSpace)
        {
          nextStart = nextSpace + 1;
          if (nextStart < str.getSize())
            str.use(nextStart) = (u1)toupper(str.at(nextStart));
          else
            break;

          nextSpace = str.find(' ', nextStart);
        }
      }

      ++itN;
    }
    
    target.append(str);
  }
  else
  {
    //a_Unknown type, pass through as is.
    target.append('%');
    target.append(strType);
    target.append('%');
  }
}
Esempio n. 26
0
void SmartMote::work(){
    while(1){
        /*  se l'ora corrente è di scansione                                    */
        if(!(RTCC.hours() % 6) && (RTCC.minutes() >= 0x00 && RTCC.minutes() <= 0x05)){
            AString data;
            AString message;
            AString answer;
            /*  abilito il core timer (la prima volta è già abilitato)          */
            System::wakeCoreTimer();
            /*  accendo il led verde                                            */
            turnOnGreen();
            /*  accendo la seriale                                              */
            openUART();
            /*  accendo l'i2c                                                   */
            openI2C();
            /*  prendo le misure                                                */
            data += mac();
            data += luminosity();
            data += ambientTempAndHum();
            data += groundTemp();
            data += groundHum();
            data += battey();
            /*  compongo la stringa                                             */
            message += _PHP_CHUNK1;
            /*  inserisco l'hostname                                            */
            message += getHost();
            /*  inserisco la seconda parte di richiesta http                    */
            message += _PHP_CHUNK2;
            /*  inserisco la lunghezza dei dati                                 */
            message += AString(static_cast<sint32>(data.size()));
            /*  inserisco la terza parte di richiesta http                      */
            message += _PHP_CHUNK3;
            /*  inserisco i dati                                                */
            message += data;

            /*  se fallisce l'inizializzazione dell'esp                         */
            if(!m_net.initialize()){
                /*  notifico l'errore                                           */
                error();
            }
            /*  se fallisce l'avvio del dhcp                                    */
            if(!m_net.setDhcp(true)){
                /*  notifico l'errore                                           */
                error();
            }
            /*  se fallisce la connessione alla rete                            */
            if(!m_net.joinAP(getSSID(), getKey())){
                /*  notifico l'errore                                           */
                error();
            }
            /*  se fallisce la connessione al server                            */
            if(!m_net.connectToHost(getHost(), 80)){
                /*  notifico l'errore                                           */
                error();
            }
            /*  invio i dati                                                    */
            m_net.send(message);
            /*  aspetto l'ok                                                    */
            m_net.waitForData(answer);
            /*  notifico l'ok o lerrore dell'invio                              */
            wasSuccess(answer);
            /*  lascio l'ap                                                     */
            m_net.leaveAP();
            /*  libero la memoria occupata dalle stringhe                       */
            message.clear();
            data.clear();
            answer.clear();
        }
        /*  calcolo del tempo di sleep per il wifi                              */
        m_net.sleep(getSleepTime());
        /*  punto la prossima sveglia                                           */
        setNextAlarm();
        /*  spengo il led verde                                                 */
        turnOffGreen();
        /*  spengo l'uart                                                       */
        closeUART();
        /*  chiudo l'i2c                                                        */
        closeI2C();
        /*  spengo il core timer                                                */
        System::stopCoreTimer();
        /*  vado a dormire                                                      */
        System::sleep();
            
    }
}
Esempio n. 27
0
int ut_AString_Access()
{
  std::cerr << "ut_AString_Access" << std::endl;

  int iRet = 0x0;

  //a_Peeking
  AString strPeek;
  AString str0 = "SomethingNew";
  str0.peek(strPeek, 0);
  ASSERT_UNIT_TEST(strPeek == "SomethingNew", "AString::peek", "0", iRet);

  strPeek.clear();
  str0.peek(strPeek, 0, 9);
  ASSERT_UNIT_TEST(strPeek == "Something", "AString::peek", "1", iRet);

  strPeek.clear();
  str0.peek(strPeek, 9, 3);
  ASSERT_UNIT_TEST(strPeek == "New", "AString::peek", "2", iRet);
  ASSERT_UNIT_TEST(str0.peek(4) == 't', "AString::peek", "3", iRet);

  int pos0 = 0;
  str0 = "path0/path1/path2";
  strPeek.clear();
  pos0 = str0.peekUntil(strPeek, pos0, '/');
  ASSERT_UNIT_TEST(strPeek.equals("path0"), "AString::peekUntil", "0", iRet);

  strPeek.clear();
  pos0 = str0.peekUntil(strPeek, pos0+1, '/');
  ASSERT_UNIT_TEST(strPeek.equals("path1"), "AString::peekUntil", "1", iRet);

  strPeek.clear();
  pos0 = str0.peekUntil(strPeek, pos0+1, '/');
  ASSERT_UNIT_TEST(strPeek.equals("path2"), "AString::peekUntil", "2", iRet);
  ASSERT_UNIT_TEST(AConstant::npos == pos0, "AString::peekUntil", "3", iRet);

  //a_Set
  AString strSource0 = AString("New"), strSource1("Newer"), strSource2("123Now");
  str0 = "This is old";
  str0.set(strSource0, 8);
  ASSERT_UNIT_TEST(str0.equals("This is New"), "AString::set", "0", iRet);

  str0.set(strSource1, 8);
  ASSERT_UNIT_TEST(str0.equals("This is Newer"), "AString::set", "1", iRet);

  str0.set(strSource2, 8, 3, 3);
  ASSERT_UNIT_TEST(str0.equals("This is Now"), "AString::set", "2", iRet);

  str0.set('n', 8);
  ASSERT_UNIT_TEST(str0.equals("This is now"), "AString::set", "3", iRet);

  //a_Use
  str0.use(10) = 't';
  ASSERT_UNIT_TEST(str0.peek(10) == 't', "AString::use", "0", iRet);

  //a_Get
  AString strGet;
  str0 = "YetMoreStuff!";
  str0.get(strGet, 0, 3);
  ASSERT_UNIT_TEST(strGet.equals("Yet"), "AString::get", "0", iRet);

  str0.get(strGet, 0, 4);
  ASSERT_UNIT_TEST(strGet.equals("More"), "AString::get", "1", iRet);

  str0.get(strGet, 0, 5);
  ASSERT_UNIT_TEST(strGet.equals("Stuff"), "AString::get", "2", iRet);

  str0.get(strGet, 0, 0);
  ASSERT_UNIT_TEST(strGet.isEmpty(), "AString::get", "3", iRet);

  char cX = str0.get();
  ASSERT_UNIT_TEST(cX == '!', "AString::get", "4", iRet);
  ASSERT_UNIT_TEST(strGet.isEmpty(), "AString::get", "5", iRet);

  str0 = "SomeMoreStuff!";
  str0.get(strGet, 0);
  ASSERT_UNIT_TEST(strGet.equals("SomeMoreStuff!"), "AString::get", "6", iRet);
  ASSERT_UNIT_TEST(str0.isEmpty(), "AString::get", "7", iRet);
 
  str0 = "SomeMoreStuff!";
  str0.get(strGet, 0, 0);
  ASSERT_UNIT_TEST(str0.equals("SomeMoreStuff!"), "AString::get", "8", iRet);
  ASSERT_UNIT_TEST(strGet.isEmpty(), "AString::get", "9", iRet);

  str0 = "path0/path1/path2";
  str0.getUntil(strGet, '/');
  ASSERT_UNIT_TEST(strGet.equals("path0"), "AString::getUntil", "0", iRet);

  str0.getUntil(strGet, '/');
  ASSERT_UNIT_TEST(strGet.equals("path1"), "AString::getUntil", "1", iRet);

  str0.getUntil(strGet, '/');
  ASSERT_UNIT_TEST(strGet.equals("path2"), "AString::getUntil", "2", iRet);

  str0.getUntil(strGet, '/');
  ASSERT_UNIT_TEST(str0.isEmpty(), "AString::getUntil", "3", iRet);

  AString str1;
  str0="find_file_1";
  str0.peekUntil(str1, 2, "1");
  ASSERT_UNIT_TEST(!str1.compare("nd_file_"), "AString::peekUntil", "0", iRet);

  str0.getUntil(str1, "_", true);
  ASSERT_UNIT_TEST((!str1.compare("find") && !str0.compare("file_1")), "AString::getUntil", "4", iRet);

  str0="find_file_1";
  str0.getUntilOneOf(str1, ASW("_",1), false);
  ASSERT_UNIT_TEST((!str1.compare("find") && !str0.compare("_file_1")), "AString::getUntil", "5", iRet);

  str0.remove(1);
  str1.clear();
  str0.getUntil(str1, ASW("_",1));
  ASSERT_UNIT_TEST((!str1.compare("file") && !str0.compare("1")), "AString::getUntil", "6", iRet);

  return iRet;
}
Esempio n. 28
0
/*
Distinct sound groups
  bfpvw
  mn
  sxz
  ckq
  gj
  dt
  l
  r

Vowels and ignored
  aeiouyh
*/
void AWordUtility::getSoundsLikeForm(const AString& source, AString& result)
{
  result.clear();
  if (source.isEmpty())
    return;

  //a_First character appended as is
  AString work(source);
  work.makeLower();
  size_t workSize = work.getSize();

  size_t pos = 0;
  while (pos < workSize)
  {
    switch(work.at(pos))
    {
      case 'b':
      case 'f':
      case 'p':
        result.append('p');
      break;

      case 'm':
      case 'n':
        result.append('m');
      break;

      case 's':
      case 'x':
      case 'z':
        result.append('s');
      break;

      case 'c':
      case 'k':
      case 'q':
        result.append('k');
      break;

      case 'g':
      case 'j':
        result.append('g');
      break;

      case 'd':
      case 't':
        result.append('d');
      break;

      case 'l':
        result.append('l');
      break;

      case 'r':
        result.append('r');
      break;

      case 'v':
      case 'w':
        result.append('v');
      break;
    }
    ++pos;
  }
}
Esempio n. 29
0
/*
  Sound conversions
Pre-process
  Before   After
  ght      t

Process ending
  Before   After
  e        (remove)
  es       s
  ie       i
  ies      s
  ng       n
  y        i
  eau      o

Process
  Before   After
  ch       C
  ck       k
  ea       I
  gh       g
  gn       n
  ie       i
  kh       k
  kn       n
  ks       x
  mb       m
  nc       nk
  oo       U
  ou       u
  ph       f
  ps       s
  q(~u)    k    (q without u)
  qu       kw
  sh       S
  tia      Sa
  th       Z
  wh       w
  ugh      f
  zh       Z

Post-process (@-any vowel)
  ang@     anj@


Phonetics:
 ch = C  (chair = Cair)
 sh = S  (bash = baS)
 zh = Z  (zhivago = Zivago)
 oo = U  (boot = bUt)
*/
void AWordUtility::getPhoneticForm(const AString& source, AString& result)
{
  AString work(source);
  work.makeLower();

  const char IGNORE_CHAR = '_';
  result.clear();
  size_t workSize = work.getSize();
  if (!workSize)
    return;
  
  //a_STEP 1
  //a_Preprocess (before and after data must be same size)
  //a_These replacements take precedence
  int i;
  const int iiPreCount = 1;
  const AString preBefore[iiPreCount] = { "ght" };
  const AString preAfter[iiPreCount]  = { "t__" };
  for (i=0; i<iiPreCount; ++i)
    work.replace(preBefore[i], preAfter[i]);

  //a_STEP 2
  //a_Ending (data in reverse) (before and after data must be same size)
  const int iiEndingCount = 9;
  const AString endBefore[iiEndingCount] = {  "e", "se", "sei", "ei", "yc", "gn", "uae", "y", "eu" };
  const AString endAfter[iiEndingCount]  = {  "_", "s_", "s_i", "_i", "is", "_n", "__o", "i", "_i" };
  work.reverse();
  for (i=0; i<iiEndingCount; ++i)
  {
    if (0 == work.find(endBefore[i]))
    {
      work.overwrite(0, endAfter[i]);
    }
  }
  work.reverse();


  //a_STEP 4
  //a_Iterate and process sounds
  AString temp;
  u4 pos = 0;
  while(pos < workSize)
  {
    switch(work.at(pos))
    {
      //a_ ch->C
      case 'c':
        if ('h' == work.at(pos+1, '\x0'))
        {
          temp.append('C');
          ++pos;
        }
        else if ('k' == work.at(pos+1, '\x0'))
        {
          temp.append('k');
          ++pos;
        }
        else
          temp.append('c');

      break;

      //a_ ea->I
      case 'e':
        if ('a' == work.at(pos+1, '\x0'))
        {
          temp.append('I');
          ++pos;
        }
        else
          temp.append('e');

      break;

      //a_ gh->g, ght->t, gn->n
      case 'g':
        if ('n' == work.at(pos+1, '\x0'))
        {
          temp.append('n');
          ++pos;
        }
        else if ('h' == work.at(pos+1, '\x0'))
        {
          temp.append('g');
          ++pos;
        }
        else
          temp.append('g');
      break;

      //a_ ie->i
      case 'i':
        if ('e' == work.at(pos+1, '\x0'))
        {
          temp.append('i');
          ++pos;
        }
        else
          temp.append('i');

      break;

      //a_kh->k, kn->n, ks->x
      case 'k':
        if ('h' == work.at(pos+1, '\x0'))
        {
          temp.append('k');
          ++pos;
        }
        else if ('n' == work.at(pos+1, '\x0'))
        {
          temp.append('n');
          ++pos;
        }
        else if ('s' == work.at(pos+1, '\x0'))
        {
          temp.append('x');
          ++pos;
        }
        else
          temp.append('k');
      break;

      //a_nc->nk
      case 'n':
        if ('c' == work.at(pos+1, '\x0'))
        {
          temp.append("nk");
          ++pos;
        }
        else
          temp.append('n');
      break;

      //a_ qu->kw
      case 'm':
        if ('b' == work.at(pos+1, '\x0'))
        {
          temp.append('m');
          ++pos;
        }
        else
          temp.append('m');
      break;

      //a_ oo->U
      case 'o':
        if ('o' == work.at(pos+1, '\x0'))
        {
          temp.append('U');
          ++pos;
        }
        else if ('u' == work.at(pos+1, '\x0'))
        {
          temp.append('u');
          ++pos;
        }
        else
          temp.append('o');
      break;

      //a_ ph->f, ps->s
      case 'p':
        if ('h' == work.at(pos+1, '\x0'))
        {
          temp.append('f');
          ++pos;
        }
        else if ('s' == work.at(pos+1, '\x0'))
        {
          temp.append('s');
          ++pos;
        }
        else
          temp.append('p');
      break;

      //a_ qu->kw
      case 'q':
        if ('u' == work.at(pos+1, '\x0'))
        {
          temp.append("kw", 2);
          ++pos;
        }
        else
          temp.append('k');
      break;

      //a_ sh->S
      case 's':
        if ('h' == work.at(pos+1, '\x0'))
        {
          temp.append('S');
          ++pos;
        }
        else
          temp.append('s');
      break;

      //a_ th->s, tia->Sa
      case 't':
        if ('h' == work.at(pos+1, '\x0'))
        {
          temp.append('Z');
          ++pos;
        }
        else if ('i' == work.at(pos+1, '\x0') && 'o' == work.at(pos+2, '\x0'))
        {
          temp.append("Su");
          pos += 2;
        }
        else
          temp.append('t');
      break;

      //a_ wh->w
      case 'w':
        if ('h' == work.at(pos+1, '\x0'))
        {
          temp.append('w');
          ++pos;
        }
        else
          temp.append('w');
      break;

      //a_ zh->Z
      case 'z':
        if ('h' == work.at(pos+1, '\x0'))
        {
          temp.append('Z');
          ++pos;
        }
        else
          temp.append('z');
      break;

      //a_Skip underscores
      case IGNORE_CHAR:
        break;

      default:
        temp.append(work.at(pos));
    }
    
    ++pos;
  }

  //a_STEP 4
  //a_Remove duplicates (by insering underscore which will be ignored later)
  workSize = temp.getSize();
  pos = 0;
  while(pos < workSize)
  {
    if (temp.at(pos) == temp.at(pos+1, '\x0'))
      temp.use(pos) = IGNORE_CHAR;
    ++pos;
  }

  //a_STEP 6
  //a_Post process
  pos = 0;
  workSize = temp.getSize();
  while(pos < workSize)
  {
    switch(temp.at(pos))
    {
      case 'a':
        if ('n' == temp.at(pos+1, '\x0') && 'g' == temp.at(pos+2, '\x0'))
        {
          char c = temp.at(pos+3,'\x0');
          if (c && AConstant::npos != msstr_SoundVowels.find(c))
          {
            result.append("anj", 3);
            pos += 2;
          }
        }
        else
          result.append('a');
      break;

      case IGNORE_CHAR:
        break;

      default:
        result.append(temp.at(pos));
    }

    ++pos;
  }
}
Esempio n. 30
0
void AWordUtility::getPlural(const AString& one, AString& many)
{
  many.clear();
  
  //a_Words of size 1 or 2, just append s and return
  if (one.getSize() < 3)
  {
    many.assign(one);
    many.append('s');
    return;
  }
  
  switch(one.last())
  {
    case 's':
    {
      char c = one.at(one.getSize()-2);
      if ('i' == c)
      {
        //a_"is" -> "es"
        many.assign(one);
        many.set('i', many.getSize()-2);
      }
      else if ('u' == c)
      {
        //a_"us" -> "ii"
        one.peek(many, 0, one.getSize()-2);
        many.append("ii", 2);
      }
      else
      {
        many.assign(one);
        many.append("es", 2);
      }
    }
    break;
    
    case 'z':
    case 'x':
      many.assign(one);
      many.append("es", 2);
    break;

    case 'h':
    {
      char c = one.at(one.getSize()-2);
      if ('s' == c || 'c' == c)
      {
        many.assign(one);
        many.append("es", 2);
      }
      else
      {
        many.assign(one);
        many.append('s');
      }
    }
    break;

    case 'y':
    {
      char c = one.at(one.getSize()-2);
      if (AConstant::npos != sstr_Vowels.find(c))
      {
        //a_vowel+'y', add 's'
        many.assign(one);
        many.append('s');
      }
      else
      {
        //a_consonant+'y', convert 'y' to 'ies'
        one.peek(many, 0, one.getSize()-1);
        many.append("ies", 3);
      }
    }
    break;

    default:
      many.assign(one);
      many.append('s');
    break;
  }
  
}