コード例 #1
0
ファイル: Assembler.c プロジェクト: cool91788/OpenComputer
AsmCode* AsmCodeNew(char *line) {
  AsmCode* code = ObjNew(AsmCode,1);
	char head[MAX_LEN];
	strCut(line, "/", head, NULL);
	Array* tokens = split(head, " \t+[],", REMOVE_SPLITER);
	if (tokens->count == 0) { 
       ArrayFree(tokens, strFree);
       ObjFree(code);
       return NULL; 
    }
	code->line = strNew(head);
  strTrim(code->line, code->line, SPACE);
  code->tokens = tokens;
  int tokenIdx = 0;
  if (strTail(tokens->item[0], ":")) {
      code->label = ArrayGet(tokens, tokenIdx++);
      strTrim(code->label, code->label, ":");
  } else
      code->label = NULL;
  code->op = ArrayGet(tokens, tokenIdx++);
  code->opCode = OP_NULL;
  code->argStart = tokenIdx;
  code->arg[0] = ArrayGet(tokens, tokenIdx++);
  code->arg[1] = ArrayGet(tokens, tokenIdx++);
  code->arg[2] = ArrayGet(tokens, tokenIdx++);
//	AsmCodePrintln(code);
  return code;
}
コード例 #2
0
ファイル: myutil.c プロジェクト: schwehr/degrib
/*****************************************************************************
 * mySplit() --
 *
 * Arthur Taylor / MDL
 *
 * PURPOSE
 *   Split a character array according to a given symbol.
 *   Responsibility of caller to free the memory.
 *
 * ARGUMENTS
 *   data = character string to look through. (Input)
 * symbol = character to split based on. (Input)
 *   argc = number of groupings found. (Output)
 *   argv = characters in each grouping. (Output)
 * f_trim = True if we should white space trim each element in list. (Input)
 *
 * RETURNS: void
 *
 * HISTORY
 *  5/2004 Arthur Taylor (MDL/RSIS): Created.
 *
 * NOTES
 *****************************************************************************
 */
void mySplit (const char *data, char symbol, size_t *Argc, char ***Argv,
              char f_trim)
{
   const char *head;    /* The head of the current string */
   const char *ptr;     /* a pointer to walk over the data. */
   size_t argc = 0;     /* Local copy of Argc */
   char **argv = NULL;  /* Local copy of Argv */
   size_t len;          /* length of current string. */

   myAssert (*Argc == 0);
   myAssert (*Argv == NULL);
   myAssert (sizeof (char) == 1);

   head = data;
   while (head != NULL) {
      argv = (char **) realloc ((void *) argv, (argc + 1) * sizeof (char *));
      ptr = strchr (head, symbol);
      if (ptr != NULL) {
         len = ptr - head;
         argv[argc] = (char *) malloc (len + 1);
         strncpy (argv[argc], head, len);
         argv[argc][len] = '\0';
         if (f_trim) {
            strTrim (argv[argc]);
         }
         argc++;
         head = ptr + 1;
         /* The following head != NULL is in case data is not '\0' terminated 
          */
         if ((head != NULL) && (*head == '\0')) {
            /* Handle a break character just before the \0 */
            /* This results in not adding a "" to end of list. */
            head = NULL;
         }
      } else {
         /* Handle from here to end of text. */
         len = strlen (head);
         argv[argc] = (char *) malloc (len + 1);
         strcpy (argv[argc], head);
         if (f_trim) {
            strTrim (argv[argc]);
         }
         argc++;
         head = NULL;
      }
   }
   *Argc = argc;
   *Argv = argv;
}
コード例 #3
0
ファイル: settings.cpp プロジェクト: samkusin/bx
const char* Settings::get(const StringView& _name) const
{
	ini_t* ini = INI_T(m_ini);

	FilePath uri(_name);
	const StringView  path(strTrim(uri.getPath(), "/") );
	const StringView& fileName(uri.getFileName() );
	int32_t section = INI_GLOBAL_SECTION;

	if (!path.isEmpty() )
	{
		section = ini_find_section(ini, path.getPtr(), path.getLength() );
		if (INI_NOT_FOUND == section)
		{
			section = INI_GLOBAL_SECTION;
		}
	}

	int32_t property = ini_find_property(ini, section, fileName.getPtr(), fileName.getLength() );
	if (INI_NOT_FOUND == property)
	{
		return NULL;
	}

	return ini_property_value(ini, section, property);
}
コード例 #4
0
ファイル: settings.cpp プロジェクト: samkusin/bx
void Settings::remove(const StringView& _name) const
{
	ini_t* ini = INI_T(m_ini);

	FilePath uri(_name);
	const StringView  path     = strTrim(uri.getPath(), "/");
	const StringView& fileName = uri.getFileName();

	int32_t section = INI_GLOBAL_SECTION;

	if (!path.isEmpty() )
	{
		section = ini_find_section(ini, path.getPtr(), path.getLength() );
		if (INI_NOT_FOUND == section)
		{
			section = INI_GLOBAL_SECTION;
		}
	}

	int32_t property = ini_find_property(ini, section, fileName.getPtr(), fileName.getLength() );
	if (INI_NOT_FOUND == property)
	{
		return;
	}

	ini_property_remove(ini, section, property);

	if (INI_GLOBAL_SECTION != section
	&&  0 == ini_property_count(ini, section) )
	{
		ini_section_remove(ini, section);
	}
}
コード例 #5
0
ファイル: ootrace.c プロジェクト: liyang051/ooh323c
static void hexDumpToFileEx
(FILE* fp, const OOUCHAR* data, OOUINT32 numocts, int bytesPerUnit)
{
   OOUINT32 i;
   OOUINT32 val;
   OOUCHAR  b, dumpstr = 1;
   char     hexstr[49], ascstr[17], buf[20], *pbuf;
   int      k, unitsPerLine = 16 / bytesPerUnit, ai, shift;

   memset (hexstr, ' ', 48); hexstr[48] = '\0';
   memset (ascstr, ' ', 16); ascstr[16] = '\0';
   ai = 0;

   if (bytesPerUnit > 4) bytesPerUnit = 4;

   for (i = 0; i < numocts / bytesPerUnit; i++)
   {
      pbuf = (char*)buf;
      buf [bytesPerUnit * 2] = 0;
      if (bytesPerUnit == 1) {
         val = *data++;
         shift = 0;
      }
      else if (bytesPerUnit == 2) {
         val = *((OOUINT16*)data);
         data += sizeof (OOUINT16);
         shift = 8;
      }
      else { /* greater than 2 */
         val = *((OOUINT32*)data);
         data += sizeof (OOUINT32);
         shift = (sizeof (OOUINT32) - 1) * 8;
      }
      for (k = 0; k < bytesPerUnit; k++, pbuf += 2, shift -= 8) {
         b = (OOUCHAR)((val >> shift) & 0xFF);
         sprintf (pbuf, "%02x", b);
         ascstr[ai++] = (char) (isprint(b) ? b : '.');
      }
      *pbuf = 0;

      k = i % unitsPerLine * (bytesPerUnit * 2 + 1);
      memcpy (&hexstr[k], buf, bytesPerUnit * 2);

      if ((dumpstr = (OOUCHAR) ((i + 1) % unitsPerLine == 0)) != 0)
      {
         fprintf (fp, "%48s %16s\n", hexstr, ascstr);
         if (i < (numocts - 1)) {
            memset (hexstr, ' ', 48);
            memset (ascstr, ' ', 16);
            ai = 0;
         }
      }
   }

   if (!dumpstr) fprintf (fp, "%48s %s\n", hexstr, strTrim(ascstr));
}
コード例 #6
0
ファイル: strlib.cpp プロジェクト: vohac/genex
void vstring::strReflow (char * & target, strSizeType width, const char * preString, const char * postString, int align)
{
   strRemoveWhiteSpace (target);        // zunaechst mal alle vorhandenen CR und LF loeschen, um dann neue einzufuegen
   strTrim (target);
   strSizeType n = strLength (target);
   char * result = 0x0000;              // hierin speichern wir den ganzen neu gestalteten Absatz zwischen
   if (n > width && width > 0)          // nur dann was tun, wenn der ganze String nicht in eine Zeile passt
   {
      char * line = 0x0000;             // hierin speichern wir eine einzelne Zeile zwischen
      strSizeType a = 0;                // Position, bis zu der bisher der absatz abgearbeitet wurde
      strSizeType b = 0;                // Position bis zu der die neue naechste Zeile geht
      while (b < n)                     // Den ganzen String abarbeiten, bis alles in einzelne Zeilen aufgeteilt wurde
      {
         b = a + width;                 // zunaechst das optimale Ende der naechsten Zeile setzen
         if (b < n)                     // Feststellen, ob der ganze reststring ueberhaupt noch aufgeteilt werden muss
         {
            while (b > a && target[b] != ' ')  // nach vorne suchen, bis wir eine Trennstelle finden
            {
               b--;
            }
            if (b == a)                 // Wenn keine Trennstelle gefunden, dann muessen wir doch nach hinten suchen
            {
               b = a + width;           // Wieder den ausgangswert setzen
               while (b < n && target[b] != ' ')  // und erstes leerzeichen nach hinten suchen
               {
                  b++;
               }
            }
         }
         else
         {
            b = n;                      // Eine weitere Aufteilung ist nicht notwendig, also den ganzen reststring einfach nehmen
         }
         strCopy (line, target, a, b);  // Kopiere jetzt die Zeile aus dem ganzen String heraus
         if (!(align == 3 && b == n))   // die letze Zeile wird beim Blocksatz nicht mehr formatiert
         {
            strReflowLine (line, width, align);  // fuege jetzt je nach ausrichtung vorne oder zwischen drin Leerzeichen ein
         }
         strCopy (result, result, preString);  // kopiere prefix dran
         strCopy (result, result, line);  // kopiere nun die eigentliche Zeile an
         strCopy (result, result, postString);  // kopiere nun den Suffix hinten dran (das LF)
         a = b + 1;                     // und setze nun den beginn des reststring hinter das leerzeichen, an dem wir grade getrennt haben
      }
      strFree (line);                   // und loesche die temporaeren zwiscehnspeicher
   }
   else
   {
      strCopy (result, result, preString);  // kopiere prefix dran
      strCopy (result, result, target);  // kopiere nun die eigentliche Zeile an
      strCopy (result, result, postString);  // kopiere nun den Suffix hinten dran (das LF)
   }
   strCopy (target, result);            // kopiere nun das gesamtergebnis in den uebergebenen String
   strFree (result);
}
コード例 #7
0
ファイル: readCfg.c プロジェクト: dnsmichi/DNX
int parseLine (char *szFile, int lineNo, char *szLine)
{
   char *szVar, *szVal;
   char *cp;

   // Strip comments
   if ((cp = strchr(szLine, '#')) != NULL)
      *cp = '\0';

   // Strip trailing whitespace
   strTrim(szLine);

   // Check for blank lines
   if (!*szLine)
      return 0;

   // Look for equivalence delimiter
   if ((cp = strchr(szLine, '=')) == NULL)
   {
      fprintf(stderr, "parseLine: Missing '=' equivalence operator\n");
      return 1;   // Parse error: no delimiter
   }
   *cp++ = '\0';

   for (szVar = szLine; *szVar && *szVar <= ' '; szVar++);
   if (strTrim(szVar) < 1)
   {
      fprintf(stderr, "%s: Line %d: Missing or invalid variable\n", szFile, lineNo);
      return 1;
   }

   for (szVal = cp; *szVal && *szVal <= ' '; szVal++);
   if (strTrim(szVal) < 1)
   {
      fprintf(stderr, "%s: Line %d: Missing or invalid assignment value\n", szFile, lineNo);
      return 1;
   }

   // Validate the variable and its value
   return validateVariable(szVar, szVal);
}
コード例 #8
0
ファイル: check_str.c プロジェクト: kayahr/kaytils
END_TEST

START_TEST(test_strTrim)
{
    char *string;

    string = strCreate();
    strCopy(string, " \n\r\tfoobar");
    strTrim(string);
    fail_unless(strEquals(string, "foobar"), NULL);
    strCopy(string, "foobar \n\r\t");
    strTrim(string);
    fail_unless(strEquals(string, "foobar"), NULL);
    strCopy(string, "foobar");
    strTrim(string);
    fail_unless(strEquals(string, "foobar"), NULL);
    strCopy(string, " \n\r\tfoobar \r\t\n");
    strTrim(string);
    fail_unless(strEquals(string, "foobar"), NULL);
    strCopy(string, " \n\r\tfoo\t \n\rbar \r\t\n");
    strTrim(string);
    fail_unless(strEquals(string, "foo\t \n\rbar"), NULL);
}
コード例 #9
0
ファイル: settings.cpp プロジェクト: samkusin/bx
void Settings::set(const StringView& _name, const StringView& _value)
{
	ini_t* ini = INI_T(m_ini);

	FilePath uri(_name);
	const StringView  path(strTrim(uri.getPath(), "/") );
	const StringView& fileName(uri.getFileName() );

	int32_t section = INI_GLOBAL_SECTION;

	if (!path.isEmpty() )
	{
		section = ini_find_section(ini, path.getPtr(), path.getLength() );
		if (INI_NOT_FOUND == section)
		{
			section = ini_section_add(ini, path.getPtr(), path.getLength() );
		}
	}

	int32_t property = ini_find_property(ini, section, fileName.getPtr(), fileName.getLength() );
	if (INI_NOT_FOUND == property)
	{
		ini_property_add(
			  ini
			, section
			, fileName.getPtr()
			, fileName.getLength()
			, _value.getPtr()
			, _value.getLength()
			);
	}
	else
	{
		ini_property_value_set(
			  ini
			, section
			, property
			, _value.getPtr()
			, _value.getLength()
			);
	}
}
コード例 #10
0
ファイル: out.cpp プロジェクト: joshua-meng/Util
void setTraceLevelStr(const std::string& str)
{
    std::string lower_lstr = strTrim(strToLower(str));
    if (kTraceVerbose == lower_lstr)
        setTraceLevel(Trace::Verbose);
    else if (kTraceDebug == lower_lstr)
        setTraceLevel(Trace::Debug);
    else if (kTraceInfo == lower_lstr)
        setTraceLevel(Trace::Info);
    else if (kTraceWarn == lower_lstr)
        setTraceLevel(Trace::Warn);
    else if (kTraceError == lower_lstr)
        setTraceLevel(Trace::Error);
    else if (kTraceFatal == lower_lstr)
        setTraceLevel(Trace::Fatal);
    else if (kTraceAssert == lower_lstr)
        setTraceLevel(Trace::Assert);
    else if (kTraceSilent == lower_lstr)
        setTraceLevel(Trace::Silent);
    else
        setTraceLevel(Trace::Info);
}
コード例 #11
0
ファイル: coder.c プロジェクト: rockmetoo/rumi
listtable* parseQueries(listtable* tbl, const char* query, char equalchar, char sepchar, int* count) {

	if (tbl == NULL && (tbl = listTable(0)) == NULL) {
		return NULL;
	}

	if (query == NULL) {
		return tbl;
	}

	int cnt			= 0;
	char* newquery	= strdup(query);

	while (newquery && *newquery) {

		char* value	= makeword(newquery, sepchar);
		char* name	= strTrim(makeword(value, equalchar));

		urlDecode(name);
		urlDecode(value);

		if (tbl->putstr(tbl, name, value) == true) {
			cnt++;
		}

		free(name);
		free(value);
	}

	if (count != NULL) {
		*count = cnt;
	}

	free(newquery);

	return tbl;
}
コード例 #12
0
ファイル: uORBManager.cpp プロジェクト: muyangren499/Firmware
int uORB::Manager::readPublisherRulesFromFile(const char *file_name, PublisherRule &rule)
{
	FILE *fp;
	static const int line_len = 1024;
	int ret = PX4_OK;
	char *line = new char[line_len];

	if (!line) {
		return -ENOMEM;
	}

	fp = fopen(file_name, "r");

	if (fp == NULL) {
		delete[](line);
		return -errno;
	}

	const char *restrict_topics_str = "restrict_topics:";
	const char *module_str = "module:";
	const char *ignore_others = "ignore_others:";

	rule.ignore_other_topics = false;
	rule.module_name = nullptr;
	rule.topics = nullptr;

	while (fgets(line, line_len, fp) && ret == PX4_OK) {

		if (strlen(line) < 2 || line[0] == '#') {
			continue;
		}

		if (startsWith(restrict_topics_str, line)) {
			//read topics list
			char *start = line + strlen(restrict_topics_str);
			strTrim((const char **)&start);
			char *topics = strdup(start);
			int topic_len = 0, num_topics = 0;

			for (int i = 0; topics[i]; ++i) {
				if (topics[i] == ',' || topics[i] == '\n') {
					if (topic_len > 0) {
						topics[i] = 0;
						++num_topics;
					}

					topic_len = 0;

				} else {
					++topic_len;
				}
			}

			if (num_topics > 0) {
				rule.topics = new const char *[num_topics + 1];
				int topic = 0;
				strTrim((const char **)&topics);
				rule.topics[topic++] = topics;

				while (topic < num_topics) {
					if (*topics == 0) {
						++topics;
						strTrim((const char **)&topics);
						rule.topics[topic++] = topics;

					} else {
						++topics;
					}
				}

				rule.topics[num_topics] = nullptr;
			}

		} else if (startsWith(module_str, line)) {
			//read module name
			char *start = line + strlen(module_str);
			strTrim((const char **)&start);
			int len = strlen(start);

			if (len > 0 && start[len - 1] == '\n') {
				start[len - 1] = 0;
			}

			rule.module_name = strdup(start);

		} else if (startsWith(ignore_others, line)) {
			const char *start = line + strlen(ignore_others);
			strTrim(&start);

			if (startsWith("true", start)) {
				rule.ignore_other_topics = true;
			}

		} else {
			PX4_ERR("orb rules file: wrong format: %s", line);
			ret = -EINVAL;
		}
	}

	if (ret == PX4_OK && (!rule.module_name || !rule.topics)) {
		PX4_ERR("Wrong format in orb publisher rules file");
		ret = -EINVAL;
	}

	delete[](line);
	fclose(fp);
	return ret;
}
コード例 #13
0
ファイル: kernel.c プロジェクト: johngarbi/Q-Operating-System
void launchShell() {
    //allocate some memory for command string buffer. 1kB should be enough for now
    const int bufSize = 128;
    char bufStr[bufSize];

    

   
    while (true)
    {
        print("\nQ-Kernel>  ", 0x08);
        typingCmd = true;
        newCmd = true;
        readStr(bufStr, bufSize);
        typingCmd = false;

        if (strEql(strTrim(bufStr), ""))
        {
            print(COMMAND_HELP, 0x0F);
        }
        else if(strEql(bufStr, "help"))
        {
            kbHelp();
            println(PRO_TIP, 0x0F);
            print(COMMAND_HELP, 0x0F);
        }
        else if(strEql(bufStr, "reboot"))
        {
            //reboots the computer
            reboot();
        }
        else if(strEql(bufStr, "skip"))
        {
            // It literally does nothing... (Useful at callback) 
        }
        else if(strEql(bufStr, "hi"))
        {
            print("\nHello!", 0x3F);
        }
        else if(strEql(bufStr, "files"))
        {
            newline();
            listTree();
        }
        else if(strEql(bufStr, "cat"))
        {
            print("\nFile Name>  ", 0x0F);
            readStr(bufStr, bufSize);
            ASSERT(strlength(bufStr) < MAX_FNAME_LEN);
            catFile(finddir_fs(fs_root, bufStr));
        }
        else if(strEql(bufStr,"execute"))
        {
            execute();
        }
        else if(strEql(bufStr,"switch"))
        {
            	print("\nThe specified directory was not found ", 0x0F);
        }
	else if(strEql(bufStr,"writer")) { writer(); }
	else if(strEql(bufStr, "writer -h")) { writerHelp(); }
	
	else if(strEql(bufStr, "calc")){ calc(); }
        else if(strEql(bufStr, "calc -h")){ calcHelp(); }

        else if(strEql(bufStr, "clear"))
        {
           	 clearScreen();
           	 cursorX = 0;
           	 cursorY = 0;
           	 updateCursor();
        }
        else if(strEql(bufStr, "clear -i"))
        {
            	clearScreen();
            	printIntro();
        }
        else if(strEql(bufStr, "newdir"))
        {
            	print("\nReserved", 0x0F);
        }
        else if(strEql(bufStr, "erase"))
        {
            	print("\nReserved", 0x0F);
        }
        else
        {
            	print("\nCommand Not Found ", 0x0F);
        }
        newline();
    }
}
コード例 #14
0
void launchShell() {
    initialize_calc();

    //allocate some memory for command string buffer. 1kB should be enough for now
    const int bufSize = 128;
    char bufStr[bufSize];//Store sanitized user command (no arguments)
    char rawCommand[bufSize];//Gets user raw command from command line
    char arguments[bufSize/2][bufSize/2];//Store command arguments
    int fs = 1;//First space (first word means actual command)
    int ay = -1;//Y location for arguments
    int ax = 0;//X location for argumetns

    //prepare variable
    for(int i = 0; i < bufSize; ++i){
	bufStr[i] = 0;
    }
    for(int y = 0; y < bufSize; ++y){
	for(int x = 0; x < bufSize; ++x){
		arguments[y][x] = 0;
    	}
    }

    #define TIP print("\nTip: If enter key does not work, it might mean that the input is too long",0x0F);
    #define HELP print("\nWorking Commands in Q OS: \nwriter\nclear\nexecute\nhi\nskip (the no action)\nfiles\ncat\nreboot\ncalc", 0x0F);
    #define BIGHELP kbHelp(); TIP; HELP;
    #define SYSTEMMAN system(arguments);
    #define SAYHI print("\nHello!", 0x3F);
    #define CATFILE print("\nFile Name>  ", 0x0F); readStr(bufStr, bufSize); ASSERT(strlength(bufStr) < MAX_FNAME_LEN); cat(finddir_fs(fs_root, bufStr));
    #define SWITCHDIR print("\nThe specified directory was not found ", 0x0F);
    #define CALCULATE calc(arguments);
    #define BIGCLEAR clearScreen(); printIntro();
    #define MKDIR print("\nThis Command is Reserved for when we have a FAT32 or better FileSystem...", 0x3F);
    #define RMFILE print("\nThis Command is Reserved for when we have a FAT32 or better FileSystem...", 0x3F);
    #define SKIP skip(rawCommand);
    #define FILEMAN files(arguments);
    #define WRITE writer(arguments);
    #define ME me(rawCommand);
    #define CMDNOTFOUND print("\n", 0x0F); print(bufStr, 0x0F); print(": Command Not Found ", 0x0F);

    while (true) {
        print("\nQ-Kernel>  ", 0x08);
        typingCmd = true;
        newCmd = true;
        readStr(rawCommand, bufSize);
        typingCmd = false;

    	for(int i = 0; i < bufSize; ++i){
    	    bufStr[i] = 0;
    	}
    	for(int y = 0; y < bufSize; ++y){
                for(int x = 0; x < bufSize; ++x){
    		arguments[y][x] = 0;
    	    }
    	}
    	fs = 1;
        ay = -1;
        ax = 0;
        if(MULTI_ARG_DEBUG == true) {
            //Sanitize raw input. Move first word to bufStr and move the rest of the word to arguments
            for(int i = 0; i < bufSize; ++i) {
                if(rawCommand[i] != 0 || rawCommand[i] != 10) {
                    if(fs == 1)
                        bufStr[i] = rawCommand[i];
                    else if(fs == 0)
                        arguments[ay][ax] = rawCommand[i];

                    if(i < bufSize && rawCommand[i+1] == 32) {
          		        fs = 0;
          		        ay++;
          		    }
    	        }
                else break;
    	    }
        } else {
            //Sanitize raw input. Move first word to bufStr and move the rest of the word to arguments
            for(int i = 0; i < bufSize; ++i) {
                if(rawCommand[i] != 0 || rawCommand[i] != 10) {
                    if(fs == 1)
                        bufStr[i] = rawCommand[i];
                    if(i < bufSize && rawCommand[i+1] == 32) {
                        fs = 0;
                        ay++;
                        ax = 0;
                    } else if(fs == 0) {
                        arguments[ay][ax] = rawCommand[i];
                        ax++;
                    }
                } else break;
            }
        }

        if (strEql(strTrim(bufStr), ""))        {   HELP;             }
        else if(strEql(bufStr, "help"))         {   BIGHELP;          }
        else if(strEql(bufStr, "system"))       {   SYSTEMMAN;        }
        else if(strEql(bufStr, "skip"))         {   SKIP;             }
        else if(strEql(bufStr, "hi"))           {   SAYHI;            }
        else if(strEql(bufStr, "files"))        {   FILEMAN;          }
        else if(strEql(bufStr, "cat"))          {   CATFILE;          }
        else if(strEql(bufStr,"execute"))       {   execute();        }
        else if(strEql(bufStr,"switch"))        {   SWITCHDIR;        }
        else if(strEql(bufStr,"writer"))        {   WRITE;            }
        else if(strEql(bufStr, "calc"))         {   CALCULATE;        }
        else if(strEql(bufStr, "clear"))        {   clearScreen();    }
        else if(strEql(bufStr, "clear -i"))     {   BIGCLEAR;         }
        else if(strEql(bufStr, "newdir"))       {   MKDIR;            }
        else if(strEql(bufStr, "erase"))        {   RMFILE;           }
	else if(strEql(bufStr, "me"))           {   ME;               }
        else                                    {   CMDNOTFOUND;      }

        newline();
    }
}
コード例 #15
0
ファイル: ehTranslate.c プロジェクト: ferrasrl/easyHand
//
// ehTranslate()
//
UTF8 * ehTranslate(	ET_PARAM	enParam,
					UTF8 *		pszSource,
					CHAR *		pszLangSource,
					CHAR *		pszLangDest,
					CHAR *		pszJsonParams,	// {googlekey:"asda", bingkey:"asd"}
					ET_REPORT * psReport,
					void *		(* extAssist)(EN_MESSAGE enMess,LONG lParam,void *pVoid),
					EH_LST		lstBlackKey
					)

{
	WCHAR *pw;
	BYTE *pTradotto=NULL;
	S_PHRASES * psPh=NULL;
	S_PHSTR * psPhs;
	//INT f;
	BOOL bError=FALSE;
	INT iLen;
	INT iCharsBad;
	BYTE *pUtf;
	CHAR szLangDetect[20]="";
	double dRap;
	INT iWords;
	ET_REPORT sReportTemp;
	EH_JSON * psJson=NULL;
	CHAR * pszUserIp=NULL;
	INT		iMaxPhrases=0;
	ET_BLACK_ITEM sBlack;
	
	if (lstBlackKey) {
	
		if (lstBlackKey->iSize!=sizeof(ET_BLACK_ITEM)) ehExit("Usare transBlackListCreate();");
	}

	if (!_s.bReady) {_(_s); _s.bReady=true; ehAddExit(_transEndPoint);} // <-- Resetto la struttura Privata

	if (!psReport) psReport=&sReportTemp;
	memset(psReport,0,sizeof(ET_REPORT));

	if (!(enParam&ET_TRY_LOCAL)) extAssist=NULL;

	if (!pszLangSource) ehError();
	strcpy(psReport->szLangSource,pszLangSource);
	if (!pszLangDest) ehError();
	strcpy(psReport->szLangDest,pszLangDest);

	//
	// Assistente: ricerco prima in cache la frase completa
	//
	strTrim(pszSource);
	if (!*pszSource) {
		return strDup("");
	}

	if (enParam&ET_STAT) {
		psReport->dwChars=strlen(pszSource);
		psReport->dwWords=strWordCount(pszSource);
	}
	if (!(enParam&ET_TRANS)&&!(enParam&ET_LANGDETECT)) return NULL; // Nessun servizio richiesto

	if (pszJsonParams) {
		CHAR * psz;
		psJson=jsonCreate(pszJsonParams);
		psz=jsonGet(psJson,"maxPhrases");
		if (psz) iMaxPhrases=atoi(psz);
	}

	//
	// PREPARAZIONE FRASI DA RICHIEDERE
	// A seconda del servizio esterno di traduzione creo le frasi richieste
	//
	psPh=_phraseCreate(pszSource,iMaxPhrases);//,TTE_BING); 
	
	if (!psPh) {
		psReport->etError=GE_STRING_TOO_LONG;
		return NULL;
	}

	//
	// Richiesta traduzioni frasi
	//
	if (enParam&ET_OUTPUTDETT) {
		if (psPh->iPhraseToTrans>1) 
			printf("%s|%d}",pszLangDest,psPh->iPhraseToTrans);
			else
			printf("%s}",pszLangDest);
	}

	if (iMaxPhrases&&psPh->iPhraseToTrans>iMaxPhrases) {
	
		psReport->etError=GE_TOO_PHRASES;
		_phraseDestroy(psPh);
		jsonDestroy(psJson);
		return NULL;

	}
	if (enParam&ET_OUTPUTDETT) printf("|Phrase: total %d, problems %d, html:%d|" CRLF,psPh->iPhraseToTrans,psPh->iPhraseProblems,psPh->psTag->bHtml);
	if (enParam&ET_DOT_PROGRESS) printf("%d",psPh->iPhraseToTrans);

	//for (f=0;psPh->arPhrase[f];f++)
	for (lstLoop(psPh->lstPhrase,psPhs))
	{
		CHAR *	pszPhrase;
		CHAR *	pszPrefix=NULL;

		if (!psPhs->bTranslate) continue;

		// strTrim(psPhs->pszStr); 
		pszPhrase=psPhs->pszStr;
		if (strEmpty(pszPhrase)) continue;
		iLen=strlen(pszPhrase); if (iLen<2) continue; // Non traduco frasi con meno di 2 caratteri

		//
		// a. Controllo se è un numero
		//
 		if (!_isNaN(pszPhrase)) {ehFreePtr(&pszPrefix); continue;}

		//
		// b. Conto le parole
		//
		iWords=0; iCharsBad=0; dRap=0;
		if (enParam&ET_LANGDETECT) {

			iWords=strWordCount(pszPhrase);

			// Precontrollo stringa
			// Proporzione: iCharsBad:iLen=x:100
			iCharsBad=strCount(pszPhrase,".()[],-*_");
			dRap=iCharsBad*100/iLen;
			if (dRap>50) // Frase composta da oltre il 50% di simboli e non di lettere
			{
				psReport->etError=GE_STRING_SUSPECT; // L'indicazione della lingua sorgente è errata
				psPh->iPhraseProblems++;
				if (enParam&ET_OUTPUTDETT) printf("?");
				ehFreePtr(&pszPrefix); 
				continue;
			}
		}

		//
		// Local request ###########################################################################################
		//
		pUtf=NULL;

		if (extAssist) {

			S_TRANSLATION sTrans;

			sTrans.pszLangSource=pszLangSource;
			sTrans.pszLangDest=pszLangDest;
			sTrans.utfSource=pszPhrase;
			sTrans.utfDest=NULL;
			if (extAssist(WS_FIND,0,&sTrans)) {
				psReport->iLocalResponse++;
				if (enParam&ET_STAT) {
					psReport->dwLocalChars+=strlen(pszPhrase);
					psReport->dwLocalWords+=strWordCount(pszPhrase);
				}
				pUtf=sTrans.utfDest;
				if (pUtf) {
					psReport->enTech=ET_LOCAL;
					if (enParam&ET_SERVICE_CALL) printf("l$");
					if (enParam&ET_OUTPUTDETT) printf("l");
				}
			}
		}

		
		//
		// BING request ###########################################################################################
		//
		if (!pUtf&&
			psJson&&
			enParam&ET_TRY_BING) {
			
			CHAR * pszBingApp;
			INT iRequestDone=0;
			EH_LST lstKey;
			
			// Cerco Appi o multi Appid
			lstKey=lstNew();
			pszBingApp=jsonGet(psJson,"bingAppId");
			if (pszBingApp) lstPush(lstKey,pszBingApp);
			else {
			
				pszBingApp=jsonGet(psJson,"arBingAppId.length");
				if (pszBingApp) {
					INT a,iLen=atoi(pszBingApp);
					for (a=0;a<iLen;a++) {

						lstPush(lstKey,jsonGetf(psJson,"arBingAppId[%d]",a));

					}
				
				}
			}

			if (enParam&ET_OUTPUTDETT) printf("|pszBingApp:%s|" CRLF,pszBingApp);
			if (lstKey->iLength) {

				CHAR * pszAppId;
				if (enParam&ET_STAT) {

					psReport->dwBingChars+=strlen(pszPhrase);
					psReport->dwBingWords+=strWordCount(pszPhrase);

				}
				for (lstLoop(lstKey,pszAppId)) {

					if (_isBlackList(lstBlackKey,ET_BING,pszAppId)) continue;

					pUtf=_bingCall(		enParam,
										pszPhrase,
										pszLangSource,
										pszLangDest,
										pszAppId,
										&iRequestDone,
 										&psReport->etError); 

					if (enParam&ET_OUTPUTDETT) {
						printf("(%s) > (%s) #%d",pszPhrase,pUtf,psReport->etError);
					}
					psReport->iBingRequest+=iRequestDone;
					if (!strEmpty(pUtf)) 
						{	
							psReport->enTech=ET_BING;
							psReport->iBingResponse++; 
							if (enParam&ET_OUTPUTDETT) printf("B");
							break;
						}
						else
						{
							psReport->iBingErrors++; if (enParam&ET_OUTPUTDETT) printf("Bx");
							ehSleep(1000);
						}

					//
					// Abuso + BlackList
					//
					if (psReport->etError==GE_ABUSE&&
						lstBlackKey) {
					
							_(sBlack);
							sBlack.enTech=ET_BING;
							sBlack.pszAppId=strDup(pszAppId);
							lstPush(lstBlackKey,&sBlack);
					}
				}
			}
			lstDestroy(lstKey);
		}
コード例 #16
0
ファイル: myutil.c プロジェクト: schwehr/degrib
int main (int argc, char **argv)
{
   char buffer[] = "Hello , World, This, is, a , test\n";
   char buffer2[] = "";
   size_t listLen = 0;
   char **List = NULL;
   size_t i;
   size_t j;
   char ans;
   double value;
   char *tail;

/*
   printf ("1 :: %f\n", clock() / (double) (CLOCKS_PER_SEC));
   for (j = 0; j < 25000; j++) {
      mySplit (buffer, ',', &listLen, &List, 1);
      for (i = 0; i < listLen; i++) {
         free (List[i]);
      }
      free (List);
      List = NULL;
      listLen = 0;
   }
   printf ("1 :: %f\n", clock() / (double) (CLOCKS_PER_SEC));
*/
   mySplit (buffer, ',', &listLen, &List, 1);
   for (i = 0; i < listLen; i++) {
      printf ("%d:'%s'\n", i, List[i]);
      free (List[i]);
   }
   free (List);
   List = NULL;
   listLen = 0;

   mySplit (buffer2, ',', &listLen, &List, 1);
   for (i = 0; i < listLen; i++) {
      printf ("%d:'%s'\n", i, List[i]);
      free (List[i]);
   }
   free (List);
   List = NULL;
   listLen = 0;

   strcpy (buffer, "  0.95");
   ans = myAtoF (buffer, &value);
   printf ("%d %f : ", ans, value);
   ans = myIsReal_old (buffer, &value);
   printf ("%d %f : '%s'\n", ans, value, buffer);

   strcpy (buffer, "0.95");
   ans = myAtoF (buffer, &value);
   printf ("%d %f : ", ans, value);
   ans = myIsReal_old (buffer, &value);
   printf ("%d %f : '%s'\n", ans, value, buffer);

   strcpy (buffer, "+0.95");
   ans = myAtoF (buffer, &value);
   printf ("%d %f : ", ans, value);
   ans = myIsReal_old (buffer, &value);
   printf ("%d %f : '%s'\n", ans, value, buffer);

   strcpy (buffer, "0.95,  ");
   ans = myAtoF (buffer, &value);
   printf ("%d %f : ", ans, value);
   ans = myIsReal_old (buffer, &value);
   printf ("%d %f : '%s'\n", ans, value, buffer);

   strcpy (buffer, "0.95,");
   ans = myAtoF (buffer, &value);
   printf ("%d %f : ", ans, value);
   ans = myIsReal_old (buffer, &value);
   printf ("%d %f : '%s'\n", ans, value, buffer);

   strcpy (buffer, "0.9.5");
   ans = myAtoF (buffer, &value);
   printf ("%d %f : ", ans, value);
   ans = myIsReal_old (buffer, &value);
   printf ("%d %f : '%s'\n", ans, value, buffer);

   strcpy (buffer, "  alph 0.9.5");
   ans = myAtoF (buffer, &value);
   printf ("%d %f : ", ans, value);
   ans = myIsReal_old (buffer, &value);
   printf ("%d %f : '%s'\n", ans, value, buffer);

   strcpy (buffer, "  ");
   ans = myAtoF (buffer, &value);
   printf ("%d %f : ", ans, value);
   ans = myIsReal_old (buffer, &value);
   printf ("%d %f : '%s'\n", ans, value, buffer);

   strcpy (buffer, "");
   ans = myAtoF (buffer, &value);
   printf ("%d %f : ", ans, value);
   ans = myIsReal_old (buffer, &value);
   printf ("%d %f : '%s'\n", ans, value, buffer);

   tail = NULL;
   FileTail ("test\\me/now", &tail);
   printf ("%s \n", tail);
   free (tail);
   tail = NULL;
   FileTail ("test/me\\now", &tail);
   printf ("%s \n", tail);
   free (tail);

   strcpy (buffer, "  here  ");
   strTrim (buffer);
   printf ("%s\n", buffer);

   strcpy (buffer, "  here  ");
   strCompact (buffer, ' ');
   printf ("'%s'\n", buffer);
   return 0;
}
コード例 #17
0
ファイル: vox_main.cpp プロジェクト: coolpds/voxel
void VoxMain::run()
{
    int modesw = 3;
    uint64_t cnt = 0;
    timeval tvchk = {0, 0};
    timeval tvcur = {0, 0};
    std::string datastr = "";

    INFORMATION("(MAIN) start of loop");

    pinMode(modesw, INPUT);
    pullUpDnControl(modesw, PUD_UP); 
    gettimeofday(&tvchk, NULL);

    while(!m_exit)
    {
        int onoff = digitalRead(modesw);

        gettimeofday(&tvcur, NULL);

        if(onoff == LOW)
        {
            std::string retstr = "";

            if(m_mode > MD5)
                --m_mode;
            else
                m_mode = MD1;

            NOTICE("mode changed: mode=%d", m_mode);

            if(m_mode == MD1)  // control
            {
            }
            else if(m_mode == MD2) // vision
            {
                //if(!createProcess("/home/pi/mjpg-streamer/stop_mjpg.sh", retstr))
                //    ERROR("(MAIN) failed to stop mjpg-streamer");
            }
            else if(m_mode == MD3) // voice
            {
            }

            Servo* servo = VoxControl::getInstance().getServo();
            servo->setNeutral();
            VoxPlayer::getInstance().play("", false);

            delay(300);
        }

        if(timeSpan(tvchk, tvcur) >= 1.0f)
        {
            cpuUsage();
            tvchk.tv_sec = tvcur.tv_sec;
            tvchk.tv_usec = tvcur.tv_usec;
        }

        if((cnt % 100) == 0)
        {
            std::vector<std::string> addrs;
            getLocalIPString(addrs);

            m_myip = "";
            for(size_t i = 0; i < addrs.size(); i++)
            {
                std::string acls = "";
                extractSubString(acls, addrs[i].c_str(), 0, '.');

                if(isPositiveNumber(acls))
                {
                    if(acls != "127")
                        m_myip += addrs[i] + ", ";
                }
            }

            m_myip = strTrim(m_myip, " ,");

            std::string retstr = "";
            
            if(createProcess("/usr/bin/vcgencmd measure_temp", retstr))
            {
                strRemove(retstr, "temp=");
                strRemove(retstr, "'C");
                m_cputemp = atof(retstr.c_str());
            }

            m_appmem = getRss();
        }

        if((cnt % 2) == 0)
        {
            bool voice = VoxVoice::getInstance().isRunning();

            datastr = strFormat("%s|%d|%d|%d|%.1f|%.1f|%.1f|%.1f|%.1f|%.1f|%.1f|%.1f|%.1f|%d|%d|%d|%.1f|%d|%d|%s|%s",
                m_myip.c_str(),
                abs(MD1 - m_mode) + 1,
                m_stat,
                VoxSensor::getInstance().isFreeze(),
                VoxSensor::getInstance().getTemperature(),
                VoxSensor::getInstance().getHumidity(),
                VoxSensor::getInstance().getDistF(),
                VoxSensor::getInstance().getDistB(),
                VoxSensor::getInstance().getDistL(),
                VoxSensor::getInstance().getDistR(),
                m_cpuusage,
                m_cputemp,
                (float)(m_appmem / 1024.0 / 1024.0),
                VoxVision::getInstance().isFollowing(),
                VoxVision::getInstance().getPosX(),
                VoxVision::getInstance().getPosY(),
                VoxVision::getInstance().getRadius(),
                VoxVision::getInstance().getBallCount(),
                (voice) ? VoxVoice::getInstance().readyToGo() : 0,
                (voice) ? VoxVoice::getInstance().getReq().c_str() : "",
                (voice) ? VoxVoice::getInstance().getRsp().c_str() : ""
                );

            writeDataFile(datastr);
        }

        delay(150);
        ++cnt;
    }

    pinMode(modesw, OUTPUT);
    digitalWrite(modesw, LOW);

    INFORMATION("(MAIN) end of loop");
}
コード例 #18
0
ファイル: sqlLiteScroll.c プロジェクト: ferrasrl/easyHand
//
// Driver Odbc
//
void *	sqlLiteScroll(struct OBJ *objCalled,EN_MESSAGE cmd,LONG info,CHAR *str)
{
	static struct WINSCR rit,*PtScr;
	EH_DISPEXT *psExt;
	
    S_SCR_INFO * psSI,sSqlInfo;
	INT   a;//,b;
//	INT   ptClient;
//	SQLRETURN sqlReturn;

	//
	// Inizializzazione
	//
	if (_local.bReset)
	{
		_local.lstScr=lstCreate(sizeof(S_SCR_INFO));
		 FTIME_on(_SqlThreadRefresh,1);
		_local.bReset=false;
	}

	// Oggetto buono ?
	if ((objCalled->tipo!=OW_SCR)&&(objCalled->tipo!=OW_SCRDB)) return 0;

	psSI=objCalled->pOther;
	if (cmd==WS_INF) return &psSI->ws;

	switch (cmd) 
	{
	// -----------------------------------
	// APERTURA DEL DRIVER               |
	// -----------------------------------

		case WS_CREATE: //break;

#ifdef OS_DEBUG
			printf("OdbcScroll: Create" CRLF);
#endif

			_(sSqlInfo);
			objCalled->pOther=lstPush(_local.lstScr,&sSqlInfo);
			psSI=objCalled->pOther;
			psSI->ObjClient=objCalled;
			psSI->ObjClient->bFreeze=TRUE; // Blocco la gestione dell'oggetto
			psSI->bDrawLineDiv=TRUE;
#ifdef EH_SQL_SQLITE
			psSI->enPlatform=_SQL_SQLITE;
#endif
#ifdef EH_SQL_MYSQL
			psSI->enPlatform=_SQL_MYSQL;
#endif

			//
			// Alla prima chiamata creo thread e "finestrame" necessario 
			// 

			// Tecnologia sqlLite
			//		- La connessione deve essere inizializzata
			//
			if (!psSI->hThread)
			{
				memset(&psSI->csSqdStruct,0,sizeof(CRITICAL_SECTION));
				memset(&psSI->csSqdQuery,0,sizeof(CRITICAL_SECTION));
				InitializeCriticalSection(&psSI->csSqdStruct); 
				InitializeCriticalSection(&psSI->csSqdQuery); 
/*
			
				// 
				// Alloco lo stantment clone ( Si libererà con WS_DESTROY)
				//
				sqlReturn=SQLAllocHandle(SQL_HANDLE_STMT, sOdbcSection.hConn, &psSI->hStmtScroll);
				if (sqlReturn!=SQL_SUCCESS&&sqlReturn!=SQL_SUCCESS_WITH_INFO) ehExit("OdbcScroll:hStmt Clone impossible %d",sqlReturn);

				// Bho ?
				SQLSetStmtAttr(psSI->hStmtScroll, SQL_ATTR_CONCURRENCY, (SQLPOINTER) SQL_CONCUR_READ_ONLY, 0);

				sqlReturn=SQLSetStmtAttr(psSI->hStmtScroll, SQL_ATTR_CURSOR_SCROLLABLE, (SQLPOINTER) SQL_SCROLLABLE , 0);
				if (sqlReturn==SQL_ERROR)  
				// Altro metodo
				{
					sqlReturn=SQLSetStmtAttr( psSI->hStmtScroll,SQL_ATTR_CURSOR_TYPE,  (SQLPOINTER) SQL_CURSOR_STATIC, 0);
					if (sqlReturn==SQL_ERROR) win_infoarg("errore in assegnazione cursore");
					sqlReturn=SQLSetStmtAttr( psSI->hStmtScroll, SQL_ATTR_USE_BOOKMARKS, (SQLPOINTER) SQL_UB_VARIABLE, 0);
					if (sqlReturn==SQL_ERROR) win_infoarg("SQL_ATTR_USE_BOOKMARKS");
				}

				//sprintf(szCursor,"SQD%d",ptClient);
				//SQLTRY(SQL_HANDLE_STMT,"SQD->",psSI->hStmtScroll,SQLSetCursorName(psSI->hStmtScroll, szCursor, SQL_NTS));
				//SQLTRY("ASYNC",psSI->hStmtScroll,SQLSetStmtAttr(psSI->hStmtScroll, SQL_ATTR_ASYNC_ENABLE, (SQLPOINTER) SQL_ASYNC_ENABLE_ON , 0));


				//
				// 4) Creo il Thread (SQLExecuteThread) per l'elaborazione delle query
				//
				*/
				for (a=0;a<ESQL_MAXEVENTLOAD;a++) psSI->arhEvent[a]=CreateEvent(NULL,true,FALSE,NULL); 
				psSI->hThread = CreateThread(NULL, 
											  0, 
											  _sqlExecuteThread, 
											  (LPDWORD) psSI,
											  0, 
											  &psSI->dwThread);
				psSI->bAutoRowSelect=TRUE; // <-- 2010 - Inserito auto select in partenza
				SetThreadPriority(psSI->hThread,THREAD_PRIORITY_NORMAL);
			}
			break;

		case WS_OPEN:

		//
		//	Inizializzazione della finestra
		//	
			if (info<3) {ehExit("Field ? " __FUNCTION__);}
			psSI->ws.numcam=info;// Assegna il numero di campi da visualizzare
			psSI->ws.selez=-1; 
			psSI->ws.maxcam=0;
			psSI->ObjClient->tipo=OW_SCR;
			psSI->lRowsTotal=0;
			psSI->fChanged=0;
			psSI->ObjClient->bFreeze=FALSE;

			if (psSI->funcNotify) psSI->funcNotify(_adaptor(objCalled,WS_OPEN,0,NULL,NULL));//objCalled,NULL,0,NULL,WS_OPEN,NULL,NULL);
			psSI->ws.bExtSelection=TRUE; // Gestione esterna della selezione
			psSI->ws.fNoBlankLine=TRUE;
			

		case WS_LOAD:  
			break;

	// -----------------------------------
	// Richiesta di refresh
	// -----------------------------------
	case WS_RELOAD: 
			if (info)
				_queryExecute(psSI,__LINE__); 
				else
				_fetch(psSI); 
				
			return NULL; // Non serve stampare

	// -----------------------------------
	// WS_CLOSE IL DRIVER                  |
	// -----------------------------------
	case WS_CLOSE:
			sqlLiteScroll(objCalled,WS_PROCESS,STOP,NULL); // Chiedo di fermare il processo in corso
			psSI->ObjClient->bFreeze=true;
			if (psSI->funcNotify) (psSI->funcNotify)(_adaptor(objCalled,WS_CLOSE,0,NULL,NULL));
			break;

	// -----------------------------------
	// CHIUSURA DEFINITIVA DEL GESTORE (chiamato in obj_close());
	// -----------------------------------
	case WS_DESTROY: 

			//
			// Notifico la chiusura alla funzione esterna
			//
			if (psSI->funcNotify) (psSI->funcNotify)(_adaptor(objCalled,WS_DESTROY,0,NULL,NULL));

			// Fermo il Thread
			SetEvent(psSI->arhEvent[ESQL_STOP]); // Segnalo che siamo in chiusura
			if (WaitForSingleObject(psSI->hThread,5000)) 
			 {
				//_dx_(0,20,"Entro qui");
				//SQLFetchScroll(psSI->hStmtScroll,SQL_FETCH_FIRST,0);
				//SQLFreeHandle(SQL_HANDLE_STMT,psSI->hStmtScroll); psSI->hStmtScroll=0;
				//_dx_(0,40,"Terminate %d",TerminateThread(psSI->hThread,0));
			 }

			/*
			 if (psSI->hStmtScroll) {SQLFreeHandle(SQL_HANDLE_STMT,psSI->hStmtScroll); psSI->hStmtScroll=0;}
			 if (psSI->rsSet) {odbc_QueryResultDestroy(psSI->rsSet); ehFree(psSI->rsSet);}
			 psSI->rsSet=NULL;

			 // Libero la memoria usata per la Query
			 ehFreePtr(&psSI->pQueryActive);
			 ehFreePtr(&psSI->pszQueryCount);
			 ehFreePtr(&psSI->pLastErrorText);

			 // Libero la memoria usata per la WhereAdd
			 ehFreePtr(&psSI->pQuerySelect);

			 ehFreePtr(&psSI->pszKeyCode);
			 ARDestroy(psSI->arKeyCodeFld);
			 ehFreePtr(&psSI->pCodeFocused);
			 ehFreePtr(&psSI->pCodeSelected);
			 ehFreePtr(&psSI->pCodeReturn);

			 // Libero gli Handle degli eventi
			 for (a=0;a<ESQL_MAXEVENTLOAD;a++) CloseHandle(psSI->arhEvent[a]);

			 // 1.2.3. Liberi tutti !!
			 DeleteCriticalSection(&psSI->csSqdStruct); 
			 DeleteCriticalSection(&psSI->csSqdQuery); 
			 // Azzero la struttura di riferimento
			 memset(psSI,0,sizeof(S_SCR_INFO));
			 */
			{
				EH_LST_I * psi;
				psi=lstSearch(_local.lstScr,objCalled->pOther);
				lstRemoveI(_local.lstScr,psi);
			}
			 ehFreePtr(&objCalled->pOther);
			 break;

	// -----------------------------------
	// PRESSIONE DI UN TASTO/MOUSE       |
	// -----------------------------------
	case WS_KEYPRESS:
			if (key_press2(KEY_F9)) {strcpy(str,"ESC:F9"); break;}
			if (psSI->funcNotify) (psSI->funcNotify)(_adaptor(objCalled,cmd,info,str,NULL)); 
			break;

	// -----------------------------------
	// SETTA SELEZIONE RECORD            |
	// -----------------------------------
	case WS_SEL: 
			if (!psSI->funcNotify) break;//ehExit(SdbDriver32 ":No ext/disp function");
			// if (!psSI->rsSet) break;
			// printf("%d",psSI->rsSet->iCurrentRow);
			//if (psSI->ws.selez==-1) break;
			break;

	// -------------------------------------
	// SETTA L'OFFSET  (Solo Modo O_SCROLL |
	// -------------------------------------
	case WS_OFF: break;

	// -------------------------------------
	// 
	// -------------------------------------
	case WS_PTREC : //			  			Restituisce pt alla chiave selezionata
	case WS_GET_SELECTED:

			_(rit);
			rit.record=-1;

			if (strEmpty(psSI->pszKeyCode)) {efx2(); return NULL;}
			/*
			//
			// Selezione in scroll
			//
			if (psSI->rsSet&&psSI->ws.selez>-1)
			{
				psSI->rsSet->iCurrentRow=psSI->ws.selez;
				if (strEmpty(psSI->pszKeyCode)) ehExit("%s:%d manca assegnazione pszKeyCode",__FILE__,__LINE__);
				_keyCodeBuilder(&psSI->pCodeReturn,psSI);

				rit.record=psSI->ws.selez;
				rit.keypt=psSI->pCodeReturn;
				if (psSI->bAutoRowSelect)
				{
					strAssign(&psSI->pCodeSelected,psSI->pCodeReturn);
					InvalidateRect(objCalled->hWnd,NULL,FALSE);
				}
			}
			//
			// Pre-selezione (non entrao in scroll
			//
			else if (!strEmpty(psSI->pCodeSelected)) {

				rit.record=psSI->ws.selez;
				rit.keypt=psSI->pCodeSelected;
			}
			if (cmd==WS_GET_SELECTED) return retCreate(_ALFA,rit.record,rit.keypt);
			*/
			return &rit;

	// -------------------------------------
	// RITORNA Selez ??????????            |
	// -------------------------------------
	case WS_REALGET:
			 break;

	// -------------------------------------
	// Refresh a ON                        |
	// -------------------------------------
	case WS_REFON : psSI->ws.refre=ON; break;
	case WS_REFOFF : psSI->ws.refre=OFF; break;

	case WS_PROCESS:
		if (info==STOP&&!str)
		 {
			// SQLCancel(psSI->hStmtScroll); // Cancello il processo nello stantment
			 printf("> cancellare processo in corso");
			EnterCriticalSection(&psSI->csSqdStruct);
			psSI->fBreak=true;
			LeaveCriticalSection(&psSI->csSqdStruct);
			while (TRUE) {if (!psSI->fInProcess) break; else Sleep(50);}
			//win_infoarg("SQL stop");
		}
		// Controllo se l'elaborazione è in corso
		if ((info==0)&&(*str=='?'))
		{
		  if (psSI->fInProcess) return "!"; else return NULL;
		}
		break;

	
	// 
	// Chiedo di cambiare il la Where di ricerca
	//
	case WS_SETFILTER:

		EnterCriticalSection(&psSI->csSqdStruct);
		ehFreePtr(&psSI->pQuerySelect); 
	 	psSI->pQuerySelect=strDup(str);
		psSI->ws.selez=-1;
		psSI->ws.maxcam=0;
		psSI->lRowsReady=0;
		psSI->lRowsTotal=0;
		LeaveCriticalSection(&psSI->csSqdStruct);
		if (info)
		{
			InvalidateRect(objCalled->hWnd,NULL,TRUE);
			_message(psSI,TRUE,"Attendere\nRichiesta al server ...");
			OsEventLoop(5);
		}
		psSI->fQueryToExecute=true;
		// _queryExecute(psSI,__LINE__); // Me ne arriva uno dopo
		break;

	case WS_SETFLAG:
		objCalled->pOtherEx=str; // Assegno un puntatore esterno
		if (psSI->funcNotify) (psSI->funcNotify)(_adaptor(objCalled,WS_SETFLAG,info,NULL,NULL)); 
		break;

	// -------------------------------------
	// Richiesta di Stampa dei Dati        |
	// -------------------------------------
	case WS_DISPLAY : //			  			Richiesta buffer
			 
			psExt=(EH_DISPEXT *) str;

			if (!psSI->funcNotify) {
				Tboxp(	psExt->rClientArea.left,
						psExt->rClientArea.top,
						psExt->rClientArea.right,
						psExt->rClientArea.bottom-1,
						RGB(255,128,0),SET);
//						arError=ARCreate(psSI->pLastErrorText,"\n",&iRow);
				dispf(psExt->px+1,psExt->py+1,RGB(255,255,255),-1,STYLE_NORMAL,"SMALL F",3,"-Not func for Display-");
				break;
			}

			//
			// Richiesta di stampa del titolo
			//
			if (psExt->ncam==-10) 
			{
				psSI->funcNotify(_adaptor(objCalled,WS_DISPLAY,0,psExt,NULL));//psSI->Hdb,psSI->iIndex); 
				break;
			}
/*
			if (!psSI->rsSet) 
			{
				if (psSI->bSqlError)
				{
					Tboxp(psExt->px,psExt->py,psExt->px+psExt->lx-1,psExt->py+psExt->ly-1,sys.Color3DShadow,SET);
					if (psSI->pLastErrorText)
					{
						EH_AR arError;
						INT iRow;
						arError=ARCreate(psSI->pLastErrorText,"\n",&iRow);
						if (psExt->ncam<iRow) dispf(psExt->px+1,psExt->py+1,RGB(255,255,255),-1,STYLE_NORMAL,"SMALL F",3,arError[psExt->ncam]);
						ARDestroy(arError);
					}
				}
				else
				Tboxp(psExt->px,psExt->py,psExt->px+psExt->lx-1,psExt->py+psExt->ly-1,sys.Color3DLight,SET);
				break;
			 }

			 psExt->col1=GetSysColor(COLOR_MENUTEXT); 
			 psExt->col2=GetSysColor(COLOR_WINDOW);

			 if (psExt->bFocus) // selezione con il mouse
				{
					psExt->col1=GetSysColor(COLOR_HIGHLIGHTTEXT); 
					psExt->col2=ColorLum(GetSysColor(COLOR_HIGHLIGHT),30);
				} 

			 if (psExt->bSelected) // Selezionato fisso
				{
					psExt->col1=GetSysColor(COLOR_HIGHLIGHTTEXT); 
					psExt->col2=GetSysColor(COLOR_HIGHLIGHT); 
				} 

			Tboxp(psExt->px,psExt->py,psExt->px+psExt->lx-1,psExt->py+psExt->ly-2,psExt->col2,SET); //Sleep(100);

			psSI->rsSet->iCurrentRow=info;
			psSI->rsSet->iOffset=psSI->iSQLOffset;

			// Non ho ancora le linee da visualizzare
			if (psExt->ncam>=psSI->lRowsReady||
				(psSI->rsSet->iCurrentRow<psSI->iSQLOffset)||
				((psSI->rsSet->iCurrentRow-psSI->iSQLOffset)>=psSI->rsSet->iRowsLimit)) 
			{
				boxBrush(psExt->px,psExt->py,psExt->rClientArea.right,psExt->rClientArea.bottom,HS_VERTICAL,sys.Color3DLight,ColorLum(sys.Color3DHighLight,-10));
				Tline(psExt->px,psExt->rClientArea.bottom,psExt->rClientArea.right,psExt->rClientArea.bottom,sys.Color3DShadow,SET);
				break;
			}

			// RIchiedo stampa della riga
			psSI->funcNotify(	_adaptor(objCalled,WS_DISPLAY,info,psExt, psSI->rsSet));

			if (psSI->bDrawLineDiv) line(psExt->px,psExt->rClientArea.bottom,psExt->rClientArea.right,psExt->rClientArea.bottom,sys.colScrollDiv,SET);
			if (psExt->bFocus) 
			{
				boxFocus(psExt->px,psExt->py,psExt->px+psExt->lx-1,psExt->py+psExt->ly-2);
			}
			*/
			break;

	// --------------------------------------------------------------------------
	// SET della funzione esterna
	// --------------------------------------------------------------------------
	case WS_EXTNOTIFY: 
			 psSI->funcNotify=(LRESULT (*)(EH_NOTIFYPARAMS)) str;//(INT (*)(struct OBJ *,INT ,LONG  ,void  *str,EH_ODBC_RS )) str;
			 psSI->funcNotify(_adaptor(objCalled,WS_CREATE,0,NULL,NULL));
			 break;

	case WS_LINEVIEW: //	 
		psSI->ws.numcam=info;
		break;

	case WS_LINEEDIT: //	 
		psSI->ws.Enumcam=info;
		break;

	case WS_SIZE: break;
	case WS_MOVE: break;

	case WS_SETTITLE: break;
	case WS_CODENAME: 
		
		strAssign(&psSI->pszKeyCode,str); strTrim(psSI->pszKeyCode); 
		ARDestroy(psSI->arKeyCodeFld);
		psSI->arKeyCodeFld=ARCreate(psSI->pszKeyCode,"+",&psSI->iKeyCodePart);
		break;

	//
	// Riga in FOCUS
	//
		/*
	case WS_SET_ROWFOCUS: 
			if (!str) // Dal gestore oggetti
			{
				 if (info<0) {strAssign(&psSI->pCodeFocused,NULL); break;}
				 if (psSI->pCodeName&&psSI->rsSet)
				 {
					psSI->rsSet->iCurrentRow=info;
					psSI->rsSet->iOffset=psSI->ws.offset;

					// psSI->rsSet->iCurrentRow riga della query

					if (psSI->rsSet->iCurrentRow>=psSI->iSQLOffset&&
						psSI->rsSet->iCurrentRow<(psSI->iSQLOffset+psSI->lRowsReady))
					{
						strAssign(&psSI->pCodeFocused,sql_ptr(psSI->rsSet,psSI->pCodeName));
						strTrim(psSI->pCodeFocused);
					}
					else
					{
						strAssign(&psSI->pCodeFocused,NULL); // Non ho la selezione richiesta in memoria
					}
					dispxEx(0,80,"%d,%d = %s          ",
							psSI->rsSet->iCurrentRow,
							psSI->iSQLOffset+psSI->lRowsReady,
							psSI->pCodeFocused);
				 }
				return NULL;
			}
			else // Esterno
			{
				strAssign(&psSI->pCodeFocused,str);
				InvalidateRect(objCalled->hWnd,NULL,FALSE);
			}
			break;

	case WS_GET_ROWFOCUS: 
			 if (psSI->pCodeName&&psSI->pCodeFocused&&psSI->rsSet)
			 {
				CHAR *p;
				if (info<0) return NULL;
				psSI->rsSet->iCurrentRow=info;
				psSI->rsSet->iOffset=psSI->ws.offset;

				p=sql_ptr(psSI->rsSet,psSI->pCodeName); strTrimRight(p);
				if (!strcmp(p,psSI->pCodeFocused)) break;
			 }
			 return NULL;
*/

	//
	// Riga in SELECTED
	//
	case WS_SET_ROWSELECTED: 
			printf("qui");
		/*
			 if (!str) // Dal gestore oggetti
			 {
				 if (info<0) {strAssign(&psSI->pCodeSelected,NULL); InvalidateRect(objCalled->hWnd,NULL,FALSE); break;}
				 if (psSI->pszKeyCode&&psSI->rsSet)
				 {
					psSI->rsSet->iCurrentRow=info;
					psSI->rsSet->iOffset=psSI->ws.offset;
					_keyCodeBuilder(&psSI->pCodeSelected,psSI); //if (!strEmpty(p)) break;
				 }
				InvalidateRect(objCalled->hWnd,NULL,FALSE);
				return NULL;
			}
			else // Esterno
			{
				strAssign(&psSI->pCodeSelected,str);
				InvalidateRect(objCalled->hWnd,NULL,FALSE);
			}
			*/
			break;

	case WS_GET_ROWSELECTED: 

			//
			// Controllo di selezione
			// 
			if (psSI->pszKeyCode&&!strEmpty(psSI->pCodeSelected)&&psSI->rsSet)
			 {
				 CHAR * p;
				if (info<0) return NULL;

				//psSI->rsSet->iCurrent=info;
				p=_keyCodeBuilder(psSI,info); // Può ritornare Null in p se sto chiedendo una riga che non c'è (in fase di ingrandimento)
				if (!strCmp(p,psSI->pCodeSelected)) {ehFreeNN(p); break;}
				ehFreeNN(p); 
			 }
			 return NULL;

	case WS_EVENT:
		/*
			if (!psSI->rsSet) break;
			psSI->rsSet->iCurrentRow=info;
			psSI->rsSet->iOffset=psSI->iSQLOffset;
			if (psSI->funcNotify) 
			{
				BYTE *ptr=(BYTE *) (psSI->funcNotify)(_adaptor(objCalled,cmd,info,str,psSI->rsSet));
				return ptr;
			}
			*/
			printf("qui");
			break;

	case WS_BUF:
			break;

	default:
/*
		if (psSI->funcNotify) 
			(psSI->funcNotify)(_adaptor(objCalled,cmd,info,str,psSI->rsSet));
			else
			printf(__FUNCTION__ "Event ? [%d][%s]" CRLF,cmd,objCalled->nome); 
			*/
			break;
	}

	//PtScr=psSI->WinScr; 
	PtScr=NULL;
	if (!PtScr) PtScr=&rit;
	return PtScr;
}
コード例 #19
0
ファイル: typeStringTest.c プロジェクト: cmwshang/pgbackrest
/***********************************************************************************************************************************
Test Run
***********************************************************************************************************************************/
void
testRun(void)
{
    FUNCTION_HARNESS_VOID();

    // *****************************************************************************************************************************
    if (testBegin("strNew(), strNewBuf(), strNewN(), strEmpty(), strPtr(), strSize(), and strFree()"))
    {
        // We don't want this struct to grow since there are generally a lot of strings, so make sure it doesn't grow without us
        // knowing about it
        TEST_RESULT_UINT(sizeof(StringConst), TEST_64BIT() ? 16 : 12, "check StringConst struct size");

        // Test the size macro
        TEST_RESULT_VOID(CHECK_SIZE(555), "valid size");
        TEST_ERROR(CHECK_SIZE(STRING_SIZE_MAX + 1), AssertError, "string size must be <= 1073741824 bytes");

        String *string = strNew("static string");
        TEST_RESULT_STR(strPtr(string), "static string", "new with static string");
        TEST_RESULT_INT(strSize(string), 13, "check size");
        TEST_RESULT_BOOL(strEmpty(string), false, "is not empty");
        TEST_RESULT_INT(strlen(strPtr(string)), 13, "check size with strlen()");
        TEST_RESULT_CHAR(strPtr(string)[2], 'a', "check character");

        TEST_RESULT_VOID(strFree(string), "free string");

        // -------------------------------------------------------------------------------------------------------------------------
        TEST_RESULT_STR(strPtr(strNewN("testmorestring", 4)), "test", "new string with size limit");

        // -------------------------------------------------------------------------------------------------------------------------
        Buffer *buffer = bufNew(8);
        memcpy(bufPtr(buffer), "12345678", 8);
        bufUsedSet(buffer, 8);

        TEST_RESULT_STR(strPtr(strNewBuf(buffer)), "12345678", "new string from buffer");

        // -------------------------------------------------------------------------------------------------------------------------
        string = strNewFmt("formatted %s %04d", "string", 1);
        TEST_RESULT_STR(strPtr(string), "formatted string 0001", "new with formatted string");
        TEST_RESULT_PTR(strPtr(NULL), NULL, "null string pointer");

        TEST_RESULT_VOID(strFree(string), "free string");
        TEST_RESULT_VOID(strFree(NULL), "free null string");
    }

    // *****************************************************************************************************************************
    if (testBegin("STRING_STATIC()"))
    {
        TEST_RESULT_STR(strPtr(TEST_STRING), "a very interesting string!", "check static string");
        TEST_RESULT_STR(strPtr(strSubN(TEST_STRING, 0, 6)), "a very", "read-only strSub() works");
    }

    // *****************************************************************************************************************************
    if (testBegin("strBase() and strPath()"))
    {
        TEST_RESULT_STR(strPtr(strBase(STRDEF(""))), "", "empty string");
        TEST_RESULT_STR(strPtr(strBase(STRDEF("/"))), "", "/ only");
        TEST_RESULT_STR(strPtr(strBase(STRDEF("/file"))), "file", "root file");
        TEST_RESULT_STR(strPtr(strBase(STRDEF("/dir1/dir2/file"))), "file", "subdirectory file");

        TEST_RESULT_STR(strPtr(strPath(STRDEF(""))), "", "empty string");
        TEST_RESULT_STR(strPtr(strPath(STRDEF("/"))), "/", "/ only");
        TEST_RESULT_STR(strPtr(strPath(STRDEF("/file"))), "/", "root path");
        TEST_RESULT_STR(strPtr(strPath(STRDEF("/dir1/dir2/file"))), "/dir1/dir2", "subdirectory file");
    }

    // *****************************************************************************************************************************
    if (testBegin("strCat(), strCatChr(), and strCatFmt()"))
    {
        String *string = strNew("XXXX");
        String *string2 = strNew("ZZZZ");

        TEST_RESULT_STR(strPtr(strCat(string, "YYYY")), "XXXXYYYY", "cat string");
        TEST_RESULT_SIZE(string->extra, 4, "check extra");
        TEST_RESULT_STR(strPtr(strCatFmt(string, "%05d", 777)), "XXXXYYYY00777", "cat formatted string");
        TEST_RESULT_SIZE(string->extra, 6, "check extra");
        TEST_RESULT_STR(strPtr(strCatChr(string, '!')), "XXXXYYYY00777!", "cat chr");
        TEST_RESULT_SIZE(string->extra, 5, "check extra");

        TEST_RESULT_STR(strPtr(string2), "ZZZZ", "check unaltered string");
    }

    // *****************************************************************************************************************************
    if (testBegin("strDup()"))
    {
        const String *string = STRDEF("duplicated string");
        String *stringDup = strDup(string);
        TEST_RESULT_STR(strPtr(stringDup), strPtr(string), "duplicated strings match");

        TEST_RESULT_PTR(strDup(NULL), NULL, "duplicate null string");
    }

    // *****************************************************************************************************************************
    if (testBegin("strBeginsWith() and strBeginsWithZ()"))
    {
        TEST_RESULT_BOOL(strBeginsWith(STRDEF(""), STRDEF("aaa")), false, "empty string");
        TEST_RESULT_BOOL(strBeginsWith(STRDEF("astring"), STRDEF("")), true, "empty begins with");
        TEST_RESULT_BOOL(strBeginsWithZ(STRDEF("astring"), "astr"), true, "partial begins with");
        TEST_RESULT_BOOL(strBeginsWithZ(STRDEF("astring"), "astring"), true, "equal strings");
    }

    // *****************************************************************************************************************************
    if (testBegin("strEndsWith() and strEndsWithZ()"))
    {
        TEST_RESULT_BOOL(strEndsWith(STRDEF(""), STRDEF(".doc")), false, "empty string");
        TEST_RESULT_BOOL(strEndsWith(STRDEF("astring"), STRDEF("")), true, "empty ends with");
        TEST_RESULT_BOOL(strEndsWithZ(STRDEF("astring"), "ing"), true, "partial ends with");
        TEST_RESULT_BOOL(strEndsWithZ(STRDEF("astring"), "astring"), true, "equal strings");
    }

    // *****************************************************************************************************************************
    if (testBegin("strEq(), strEqZ(), strCmp(), strCmpZ()"))
    {
        TEST_RESULT_BOOL(strEq(STRDEF("equalstring"), STRDEF("equalstring")), true, "strings equal");
        TEST_RESULT_BOOL(strEq(STRDEF("astring"), STRDEF("anotherstring")), false, "strings not equal");
        TEST_RESULT_BOOL(strEq(STRDEF("astring"), STRDEF("bstring")), false, "equal length strings not equal");

        TEST_RESULT_INT(strCmp(STRDEF("equalstring"), STRDEF("equalstring")), 0, "strings equal");
        TEST_RESULT_INT(strCmp(STRDEF("a"), STRDEF("b")), -1, "a < b");
        TEST_RESULT_INT(strCmp(STRDEF("b"), STRDEF("a")), 1, "b > a");

        TEST_RESULT_BOOL(strEqZ(STRDEF("equalstring"), "equalstring"), true, "strings equal");
        TEST_RESULT_BOOL(strEqZ(STRDEF("astring"), "anotherstring"), false, "strings not equal");
        TEST_RESULT_BOOL(strEqZ(STRDEF("astring"), "bstring"), false, "equal length strings not equal");

        TEST_RESULT_INT(strCmpZ(STRDEF("equalstring"), "equalstring"), 0, "strings equal");
        TEST_RESULT_INT(strCmpZ(STRDEF("a"), "b"), -1, "a < b");
        TEST_RESULT_INT(strCmpZ(STRDEF("b"), "a"), 1, "b > a");
    }

    // *****************************************************************************************************************************
    if (testBegin("strFirstUpper(), strFirstLower(), strUpper(), strLower()"))
    {
        TEST_RESULT_STR(strPtr(strFirstUpper(strNew(""))), "", "empty first upper");
        TEST_RESULT_STR(strPtr(strFirstUpper(strNew("aaa"))), "Aaa", "first upper");
        TEST_RESULT_STR(strPtr(strFirstUpper(strNew("Aaa"))), "Aaa", "first already upper");

        TEST_RESULT_STR(strPtr(strFirstLower(strNew(""))), "", "empty first lower");
        TEST_RESULT_STR(strPtr(strFirstLower(strNew("AAA"))), "aAA", "first lower");
        TEST_RESULT_STR(strPtr(strFirstLower(strNew("aAA"))), "aAA", "first already lower");

        TEST_RESULT_STR(strPtr(strLower(strNew("K123aBc"))), "k123abc", "all lower");
        TEST_RESULT_STR(strPtr(strLower(strNew("k123abc"))), "k123abc", "already lower");
        TEST_RESULT_STR(strPtr(strLower(strNew("C"))), "c", "char lower");
        TEST_RESULT_STR(strPtr(strLower(strNew(""))), "", "empty lower");

        TEST_RESULT_STR(strPtr(strUpper(strNew("K123aBc"))), "K123ABC", "all upper");
        TEST_RESULT_STR(strPtr(strUpper(strNew("K123ABC"))), "K123ABC", "already upper");
        TEST_RESULT_STR(strPtr(strUpper(strNew("c"))), "C", "char upper");
        TEST_RESULT_STR(strPtr(strUpper(strNew(""))), "", "empty upper");
    }

    // *****************************************************************************************************************************
    if (testBegin("strQuote()"))
    {
        TEST_RESULT_STR(strPtr(strQuote(STRDEF("abcd"), STRDEF("'"))), "'abcd'", "quote string");
    }

    // *****************************************************************************************************************************
    if (testBegin("strReplaceChr()"))
    {
        TEST_RESULT_STR(strPtr(strReplaceChr(strNew("ABCD"), 'B', 'R')), "ARCD", "replace chr");
    }

    // *****************************************************************************************************************************
    if (testBegin("strSub() and strSubN()"))
    {
        TEST_RESULT_STR(strPtr(strSub(STRDEF("ABCD"), 2)), "CD", "sub string");
        TEST_RESULT_STR(strPtr(strSubN(STRDEF("ABCD"), 1, 2)), "BC", "sub string with length");
    }

    // *****************************************************************************************************************************
    if (testBegin("strTrim()"))
    {
        TEST_RESULT_STR(strPtr(strTrim(strNew(""))), "", "trim empty");
        TEST_RESULT_STR(strPtr(strTrim(strNew("X"))), "X", "no trim (one char)");
        TEST_RESULT_STR(strPtr(strTrim(strNew("no-trim"))), "no-trim", "no trim (string)");
        TEST_RESULT_STR(strPtr(strTrim(strNew(" \t\r\n"))), "", "all whitespace");
        TEST_RESULT_STR(strPtr(strTrim(strNew(" \tbegin-only"))), "begin-only", "trim begin");
        TEST_RESULT_STR(strPtr(strTrim(strNew("end-only\t "))), "end-only", "trim end");
        TEST_RESULT_STR(strPtr(strTrim(strNew("\n\rboth\r\n"))), "both", "trim both");
        TEST_RESULT_STR(strPtr(strTrim(strNew("begin \r\n\tend"))), "begin \r\n\tend", "ignore whitespace in middle");
    }

    // *****************************************************************************************************************************
    if (testBegin("strChr() and strTrunc()"))
    {
        TEST_RESULT_INT(strChr(STRDEF("abcd"), 'c'), 2, "c found");
        TEST_RESULT_INT(strChr(STRDEF("abcd"), 'C'), -1, "capital C not found");
        TEST_RESULT_INT(strChr(STRDEF("abcd"), 'i'), -1, "i not found");
        TEST_RESULT_INT(strChr(STRDEF(""), 'x'), -1, "empty string - x not found");

        String *val = strNew("abcdef");
        TEST_ERROR(
            strTrunc(val, (int)(strSize(val) + 1)), AssertError,
            "assertion 'idx >= 0 && (size_t)idx <= this->size' failed");
        TEST_ERROR(strTrunc(val, -1), AssertError, "assertion 'idx >= 0 && (size_t)idx <= this->size' failed");

        TEST_RESULT_STR(strPtr(strTrunc(val, strChr(val, 'd'))), "abc", "simple string truncated");
        strCat(val, "\r\n to end");
        TEST_RESULT_STR(strPtr(strTrunc(val, strChr(val, 'n'))), "abc\r\n to e", "complex string truncated");
        TEST_RESULT_STR(strPtr(strTrunc(val, strChr(val, 'a'))), "", "complete string truncated - empty string");

        TEST_RESULT_INT(strSize(val), 0, "0 size");
        TEST_RESULT_STR(strPtr(strTrunc(val, 0)), "", "test coverage of empty string - no error thrown for index 0");
    }

    // *****************************************************************************************************************************
    if (testBegin("strToLog() and strObjToLog()"))
    {
        TEST_RESULT_STR(strPtr(strToLog(STRDEF("test"))), "{\"test\"}", "format string");
        TEST_RESULT_STR(strPtr(strToLog(NULL)), "null", "format null string");

        char buffer[256];
        TEST_RESULT_UINT(strObjToLog(NULL, (StrObjToLogFormat)strToLog, buffer, sizeof(buffer)), 4, "format null string");
        TEST_RESULT_STR(buffer, "null", "check null string");

        TEST_RESULT_UINT(strObjToLog(STRDEF("teststr"), (StrObjToLogFormat)strToLog, buffer, sizeof(buffer)), 11, "format string");
        TEST_RESULT_STR(buffer, "{\"teststr\"}", "check string");
    }

    // *****************************************************************************************************************************
    if (testBegin("strSizeFormat()"))
    {
        TEST_RESULT_STR(strPtr(strSizeFormat(0)), "0B", "zero bytes");
        TEST_RESULT_STR(strPtr(strSizeFormat(1023)), "1023B", "1023 bytes");
        TEST_RESULT_STR(strPtr(strSizeFormat(1024)), "1KB", "1 KB");
        TEST_RESULT_STR(strPtr(strSizeFormat(2200)), "2.1KB", "2.1 KB");
        TEST_RESULT_STR(strPtr(strSizeFormat(1048576)), "1MB", "1 MB");
        TEST_RESULT_STR(strPtr(strSizeFormat(20162900)), "19.2MB", "19.2 MB");
        TEST_RESULT_STR(strPtr(strSizeFormat(1073741824)), "1GB", "1 GB");
        TEST_RESULT_STR(strPtr(strSizeFormat(1073741824 + 107374183)), "1.1GB", "1.1 GB");
        TEST_RESULT_STR(strPtr(strSizeFormat(UINT64_MAX)), "17179869183GB", "uint64 max");
    }

    // *****************************************************************************************************************************
    if (testBegin("strLstNew(), strLstAdd*(), strLstGet(), strLstMove(), strLstSize(), and strLstFree()"))
    {
        // Add strings to the list
        // -------------------------------------------------------------------------------------------------------------------------
        StringList *list = NULL;

        MEM_CONTEXT_TEMP_BEGIN()
        {
            list = strLstNew();

            for (int listIdx = 0; listIdx <= LIST_INITIAL_SIZE; listIdx++)
            {
                if (listIdx == 0)
                {
                    TEST_RESULT_PTR(strLstAdd(list, NULL), list, "add null item");
                }
                else
                    TEST_RESULT_PTR(strLstAdd(list, strNewFmt("STR%02d", listIdx)), list, "add item %d", listIdx);
            }

            strLstMove(list, MEM_CONTEXT_OLD());
        }
        MEM_CONTEXT_TEMP_END();

        TEST_RESULT_INT(strLstSize(list), 9, "list size");

        // Read them back and check values
        // -------------------------------------------------------------------------------------------------------------------------
        for (unsigned int listIdx = 0; listIdx < strLstSize(list); listIdx++)
        {
            if (listIdx == 0)
            {
                TEST_RESULT_PTR(strLstGet(list, listIdx), NULL, "check null item");
            }
            else
                TEST_RESULT_STR(strPtr(strLstGet(list, listIdx)), strPtr(strNewFmt("STR%02u", listIdx)), "check item %u", listIdx);
        }

        TEST_RESULT_VOID(strLstFree(list), "free string list");
        TEST_RESULT_VOID(strLstFree(NULL), "free null string list");
    }
コード例 #20
0
ファイル: main.cpp プロジェクト: lalalaring/stateviewer
void load_trace_txt ( char* fname ) 
{
	std::string str, word;
	char buf[1024];

	unsigned long totalBytes = getFileSize ( fname );
	unsigned long currBytes = 0;

	FILE* fp = fopen ( fname, "rt" );
	int c;
	std::vector<std::string> changestates;
	changestates.push_back ( "x" );			// 0 = BIN_NOTUSED
	changestates.push_back ( "c" );			// 1 = BIN_CREATE
	changestates.push_back ( "u" );			// 2 = BIN_CHANGE
	changestates.push_back ( "s" );			// 3 = BIN_SWITCH
	changestates.push_back ( "-" );			// 4 = BIN_REUSE
	changestates.push_back ( "D" );

	Call cl;
	Event e;
	int lin = 0;
	int max_lin = 5000;
	std::string szstr;
	int sz;
	unsigned long cstart = 0;
	int cnum = 0;

	while (!feof(fp) && lin < max_lin) {
		
		currBytes = getFilePos ( fp );
		printf ( "%d (%.2f%%)\n", currBytes, currBytes*100.0f/totalBytes );

		fgets ( buf, 1024, fp );
		str = buf;
		int bin = 0;		
		str = strTrim ( str );

		e.name = word;
		
		if ( str.compare (0, 2, "C:") == 0 ) {
			/*word = strSplit ( str, " " );	
			word = strSplit ( str, " " );	cl.bin_id = strToI(word);
			word = strSplit ( str, " " );	cl.size = strToI(word); 
			word = strSplit ( str, " " );	cl.obj_id = strToLI(word);
			word = strSplit ( str, " " );	cl.val_id = strToLI(word);
			word = strSplit ( str, " " );	cl.name = word;
			mCalls.push_back ( cl );*/
			cnum++;			
		} else if ( str.compare ( 0, 2, "FR" ) == 0 ) {
			e.count = 1;
			for (int n=0; n < NUM_BIN; n++ ) {
				e.bin_id[n] = -1;
				e.bin_change[n] = -1;
			}			
			mEvents.push_back ( e );
		} else if ( str.compare ( 0, 2, "Dr" ) == 0 ) {
			e.count = 1;
			int bin = 0;
			word = strLeft ( str, 8 );
			str = strTrim ( str );			
			while ( str.length() > 0 ) {
				word = strSplit ( str, " " );				
				c = strExtract ( word, changestates );
				szstr = strParse ( word, "[", "]" );
				e.bin_id[bin] = strToI ( word );
				e.bin_change[bin] = c;		
				e.bin_size[bin] = strToI ( szstr );
				bin++;				
			}	
			e.call_start = cstart;
			e.call_num = cnum;
			if ( e.bin_size[BIN_DRAW] > mMaxSize ) mMaxSize = e.bin_size[BIN_DRAW];
			mEvents.push_back ( e );			
			cstart += cnum;
		}	
		
		lin++;
	}

	fclose ( fp );
}
コード例 #21
0
bool config_read(Config *config) {
  int iniSection = INI_SECTION_UNKNOWN;
  char buffer[100];
  char* name;
  char* value;

  memset(config, 0, sizeof(Config));
  strcpy(config->general.name, "doorbell01");
  strcpy(config->button0.name, "Front");
  strcpy(config->button1.name, "Back");
  strcpy(config->cloud.baseUrl, "http://zzzzzzzzz"); // TODO fill me in

  FILE* pFile = fopen("/mnt/sdcard/config.ini", "r");
  if (pFile == NULL) {
    printf("Failed to open config.ini\n");
    return false;
  }

  printf("reading config\n");
  while (fgets(buffer, sizeof(buffer), pFile) != NULL) {
    strTrim(buffer);
    printf("config: %s\n", buffer);
    name = NULL;
    if ((value = strchr(buffer, '='))) {
      name = buffer;
      *value = '\0';
      value++;
    }

    if (strncmp(buffer, "[general]", strlen("[general]")) == 0) {
      iniSection = INI_SECTION_GENERAL;
    } else if (strncmp(buffer, "[wifi]", strlen("[wifi]")) == 0) {
      iniSection = INI_SECTION_WIFI;
    } else if (strncmp(buffer, "[cloud]", strlen("[cloud]")) == 0) {
      iniSection = INI_SECTION_CLOUD;
    } else if (strncmp(buffer, "[button0]", strlen("[button0]")) == 0) {
      iniSection = INI_SECTION_BUTTON0;
    } else if (strncmp(buffer, "[button1]", strlen("[button1]")) == 0) {
      iniSection = INI_SECTION_BUTTON1;
    } else if (name && value) {
      if (iniSection == INI_SECTION_GENERAL) {
        if (strcmp(name, "name") == 0) {
          strcpy(config->general.name, value);
        } else {
          printf("Unknown name %s in section general\n", name);
        }
      } else if (iniSection == INI_SECTION_WIFI) {
        if (strcmp(name, "ssid") == 0) {
          strcpy(config->wifi.ssid, value);
        } else if (strcmp(name, "password") == 0) {
          strcpy(config->wifi.password, value);
        } else if (strcmp(name, "security") == 0) {
          config->wifi.security = _config_stringToWlanSecurity(value);
          if (config->wifi.security == -1) {
            printf("invalid wifi security %s\n", value);
            goto fail;
          }
        } else {
          printf("Unknown name %s in section wifi\n", name);
        }
      } else if (iniSection == INI_SECTION_CLOUD) {
        if (strcmp(name, "baseUrl") == 0) {
          strcpy(config->cloud.baseUrl, value);
        } else {
          printf("Unknown name %s in section cloud\n", name);
        }
      } else if (iniSection == INI_SECTION_BUTTON0) {
        if (strcmp(name, "name") == 0) {
          strcpy(config->button0.name, value);
        } else {
          printf("Unknown name %s in section button0\n", name);
        }
      } else if (iniSection == INI_SECTION_BUTTON1) {
        if (strcmp(name, "name") == 0) {
          strcpy(config->button1.name, value);
        } else {
          printf("Unknown name %s in section button1\n", name);
        }
      } else {
        printf("Unknown name %s in section %d\n", name, iniSection);
      }
    }
  }
  fclose(pFile);
  return true;

fail:
  fclose(pFile);
  return false;
}