コード例 #1
0
ファイル: OptionContainer.cpp プロジェクト: janosvitok/ffado
OptionContainer::Option OptionContainer::getOption(std::string name) {
    int i=findOption(name);
    if (i<0) {
        return Option();
    } else {
        return m_Options.at(i);
    }
}
コード例 #2
0
ファイル: OptionContainer.cpp プロジェクト: janosvitok/ffado
bool OptionContainer::removeOption(std::string name) {
    int i=findOption(name);
    if (i<0) {
        return false;
    } else {
        m_Options.erase(m_Options.begin()+i);
        return true;
    }
}
コード例 #3
0
ファイル: OptionContainer.cpp プロジェクト: janosvitok/ffado
bool OptionContainer::removeOption(Option o) {
    int i=findOption(o);
    if (i<0) {
        return false;
    } else {
        m_Options.erase(m_Options.begin()+i);
        return true;
    }
}
コード例 #4
0
ファイル: OptionContainer.cpp プロジェクト: janosvitok/ffado
bool OptionContainer::setOption(Option o) {
    int i=findOption(o);
    if (i<0) {
        return false;
    } else {
        m_Options.erase(m_Options.begin()+i);
        m_Options.push_back(o);
        return true;
    }
}
コード例 #5
0
ファイル: sqUnixSocket.c プロジェクト: mohamedfarag/RoarVM
/* set the given option for the socket.  the option comes in as a
 * String.  (why on earth we might think this a good idea eludes me
 * ENTIRELY, so... if the string doesn't smell like an integer then we
 * copy it verbatim, assuming it's really a ByteArray pretending to be
 * a struct.  caveat hackor.)
 */
sqInt sqSocketSetOptionsoptionNameStartoptionNameSizeoptionValueStartoptionValueSizereturnedValue(SocketPtr s, char *optionName, sqInt optionNameSize, char *optionValue, sqInt optionValueSize, sqInt *result)
{
  if (socketValid(s))
    {
      socketOption *opt= findOption(optionName, (size_t)optionNameSize);
      if (opt != 0)
	{
	  int   val= 0;
	  char  buf[32];
	  char *endptr;
	  /* this is JUST PLAIN WRONG (I mean the design in the image rather
	     than the implementation here, which is probably correct
	     w.r.t. the broken design) */
	  if (optionValueSize > sizeof(buf) - 1)
	    goto barf;

	  memset((void *)buf, 0, sizeof(buf));
	  memcpy((void *)buf, optionValue, optionValueSize);
	  if (optionValueSize == 1)	/* character `1' or `0' */
	    {
	      val= strtol(buf, &endptr, 0);
	      if (endptr != buf)
		{
		  memcpy((void *)buf, (void *)&val, sizeof(val));
		  optionValueSize= sizeof(val);
		}
	    }
	  if ((setsockopt(PSP(s)->s, opt->optlevel, opt->optname,
			  (const void *)buf, optionValueSize)) < 0)
	    {
	      perror("setsockopt");
	      goto barf;
	    }
	  /* it isn't clear what we're supposed to return here, since
	     setsockopt isn't supposed to have any value-result parameters
	     (go grok that `const' on the buffer argument if you don't
	     believe me).  the image says "the result of the negotiated
	     value".  what the f**k is there to negotiate?  either
	     setsockopt sets the value or it barfs.  and i'm not about to go
	     calling getsockopt just to see if the value got changed or not
	     (the image should send getOption: to the Socket if it really
	     wants to know).  if the following is wrong then I could
	     probably care (a lot) less...  fix the logic in the image and
	     then maybe i'll care about fixing the logic in here.  (i know
	     that isn't very helpful, but it's 05:47 in the morning and i'm
	     severely grumpy after fixing several very unpleasant bugs that
	     somebody introduced into this file while i wasn't looking.)  */
	  *result= val;
	  return 0;
	}
    }
 barf:
  interpreterProxy->success(false);
  return false;
}
コード例 #6
0
ファイル: commandline.cpp プロジェクト: Robbbert/store1
	bool CommandLine::hasArg(uint32_t& _value, const char _short, const char* _long) const
	{
		const char* arg = findOption(_short, _long, 1);
		if (NULL != arg)
		{
			_value = atoi(arg);
			return true;
		}

		return false;
	}
コード例 #7
0
ファイル: commandline.cpp プロジェクト: Robbbert/store1
	bool CommandLine::hasArg(float& _value, const char _short, const char* _long) const
	{
		const char* arg = findOption(_short, _long, 1);
		if (NULL != arg)
		{
			_value = float(atof(arg));
			return true;
		}

		return false;
	}
コード例 #8
0
ファイル: commandline.cpp プロジェクト: ImJezze/mame
	bool CommandLine::hasArg(double& _value, const char _short, const char* _long) const
	{
		const char* arg = findOption(_short, _long, 1);
		if (NULL != arg)
		{
			fromString(&_value, arg);
			return true;
		}

		return false;
	}
コード例 #9
0
ファイル: driver.cpp プロジェクト: serghei/kde3-kdelibs
void DrMain::removeOptionGlobally(const QString &name)
{
    DrGroup *grp(0);
    DrBase *opt = findOption(name, &grp);

    if(opt && grp)
    {
        grp->removeOption(name);
        if(grp->isEmpty())
            removeGroup(grp);
    }
}
コード例 #10
0
ファイル: popt.c プロジェクト: FabrizioFabbe/silc
static const struct poptOption * findOption(const struct poptOption * table,
					    const char * longName,
					    char shortName,
					    poptCallbackType * callback,
					    void ** callbackData,
					    int singleDash) {
    const struct poptOption * opt = table;
    const struct poptOption * opt2;
    const struct poptOption * cb = NULL;

    /* This happens when a single - is given */
    if (singleDash && !shortName && !*longName)
	shortName = '-';

    while (opt->longName || opt->shortName || opt->arg) {
	if ((opt->argInfo & POPT_ARG_MASK) == POPT_ARG_INCLUDE_TABLE) {
	    opt2 = findOption(opt->arg, longName, shortName, callback, 
			      callbackData, singleDash);
	    if (opt2) {
		if (*callback && !*callbackData)
		    *callbackData = opt->descrip;
		return opt2;
	    }
	} else if ((opt->argInfo & POPT_ARG_MASK) == POPT_ARG_CALLBACK) {
	    cb = opt;
	} else if (longName && opt->longName && 
		   (!singleDash || (opt->argInfo & POPT_ARGFLAG_ONEDASH)) &&
		   !strcmp(longName, opt->longName)) {
	    break;
	} else if (shortName && shortName == opt->shortName) {
	    break;
	}
	opt++;
    }

    if (!opt->longName && !opt->shortName) return NULL;
    *callbackData = NULL;
    *callback = NULL;
    if (cb) {
	*callback = (poptCallbackType)cb->arg;
	if (!(cb->argInfo & POPT_CBFLAG_INC_DATA))
	    *callbackData = cb->descrip;
    }

    return opt;
}
コード例 #11
0
ファイル: commandline.cpp プロジェクト: ImJezze/mame
	bool CommandLine::hasArg(bool& _value, const char _short, const char* _long) const
	{
		const char* arg = findOption(_short, _long, 1);
		if (NULL != arg)
		{
			if ('0' == *arg || (0 == strCmpI(arg, "false") ) )
			{
				_value = false;
			}
			else if ('0' != *arg || (0 == strCmpI(arg, "true") ) )
			{
				_value = true;
			}

			return true;
		}

		return false;
	}
コード例 #12
0
ファイル: fts3view.c プロジェクト: mingodad/sqlite
/*
** Print the content of a segment or of the root of a segdir.  The segment
** or root is identified by azExtra[0].  If the first character of azExtra[0]
** is 'r' then the remainder is the integer rowid of the %_segdir entry.
** If the first character of azExtra[0] is not 'r' then, then all of
** azExtra[0] is an integer which is the block number.
**
** If the --raw option is present in azExtra, then a hex dump is provided.
** Otherwise a decoding is shown.
*/
static void showSegment(sqlite3 *db, const char *zTab) {
    const unsigned char *aData;
    int nData;
    sqlite3_stmt *pStmt;

    pStmt = prepareToGetSegment(db, zTab, azExtra[0]);
    if( sqlite3_step(pStmt)!=SQLITE_ROW ) {
        sqlite3_finalize(pStmt);
        return;
    }
    nData = sqlite3_column_bytes(pStmt, 0);
    aData = sqlite3_column_blob(pStmt, 0);
    printf("Segment %s of size %d bytes:\n", azExtra[0], nData);
    if( findOption("raw", 0, 0)!=0 ) {
        printBlob(aData, nData);
    } else {
        decodeSegment(aData, nData);
    }
    sqlite3_finalize(pStmt);
}
コード例 #13
0
void RKRadio::propertyChanged (RKComponentPropertyBase *property) {
	RK_TRACE (PLUGIN);

	if (updating) return;

	int new_id = -1;
	if (property == string) {
		new_id = findOption (string->value ());
	} else if (property == number) {
		new_id = number->intValue ();
	} else {
		RK_ASSERT (false);
	}

	updating = true;
	group->setButton (new_id);
	buttonClicked (new_id);		// unfortunately, this slot is not called when the option is changed programatically!
	updating = false;

	changed ();
}
コード例 #14
0
ファイル: fts3view.c プロジェクト: mingodad/sqlite
/*
** Show the top N largest segments
*/
static void listBigSegments(sqlite3 *db, const char *zTab) {
    int nTop, i;
    sqlite3_stmt *pStmt;
    sqlite3_int64 sz;
    sqlite3_int64 id;

    nTop = atoi(findOption("top", 1, "25"));
    printf("The %d largest segments:\n", nTop);
    pStmt = prepare(db,
                    "SELECT blockid, length(block) AS len FROM '%q_segments'"
                    " ORDER BY 2 DESC, 1"
                    " LIMIT %d", zTab, nTop);
    i = 0;
    while( sqlite3_step(pStmt)==SQLITE_ROW ) {
        i++;
        id = sqlite3_column_int64(pStmt, 0);
        sz = sqlite3_column_int64(pStmt, 1);
        printf("  %2d. %9lld size %lld\n", i, id, sz);
    }
    sqlite3_finalize(pStmt);
}
コード例 #15
0
ファイル: sqUnixSocket.c プロジェクト: mohamedfarag/RoarVM
/* query the socket for the given option.  */
sqInt sqSocketGetOptionsoptionNameStartoptionNameSizereturnedValue(SocketPtr s, char *optionName, sqInt optionNameSize, sqInt *result)
{
  if (socketValid(s))
    {
      socketOption *opt= findOption(optionName, (size_t)optionNameSize);
      if (opt != 0)
	{
	  int optval;	/* NOT sqInt */
	  socklen_t optlen= sizeof(optval);
	  if ((getsockopt(PSP(s)->s, opt->optlevel, opt->optname, (void *)&optval, &optlen)) < 0)
	    goto barf;
	  if (optlen != sizeof(optval))
	    goto barf;
	  *result= optval;
	  return 0;
	}
    }
 barf:
  interpreterProxy->success(false);
  return errno;
}
コード例 #16
0
ファイル: fts3view.c プロジェクト: 0xr0ot/sqlcipher
/*
** Print the content of a doclist.  The segment or segdir-root is
** identified by azExtra[0].  If the first character of azExtra[0]
** is 'r' then the remainder is the integer rowid of the %_segdir entry.
** If the first character of azExtra[0] is not 'r' then, then all of
** azExtra[0] is an integer which is the block number.  The offset
** into the segment is identified by azExtra[1].  The size of the doclist
** is azExtra[2].
**
** If the --raw option is present in azExtra, then a hex dump is provided.
** Otherwise a decoding is shown.
*/
static void showDoclist(sqlite3 *db, const char *zTab){
  const unsigned char *aData;
  sqlite3_int64 offset, nData;
  sqlite3_stmt *pStmt;

  offset = atoi64(azExtra[1]);
  nData = atoi64(azExtra[2]);
  pStmt = prepareToGetSegment(db, zTab, azExtra[0]);
  if( sqlite3_step(pStmt)!=SQLITE_ROW ){
    sqlite3_finalize(pStmt);
    return;
  }
  aData = sqlite3_column_blob(pStmt, 0);
  printf("Doclist at %s offset %lld of size %lld bytes:\n",
         azExtra[0], offset, nData);
  if( findOption("raw", 0, 0)!=0 ){
    printBlob(aData+offset, nData);
  }else{
    decodeDoclist(aData+offset, nData);
  }
  sqlite3_finalize(pStmt);
}
コード例 #17
0
ファイル: commandline.cpp プロジェクト: ImJezze/mame
	bool CommandLine::hasArg(const char*& _value, const char _short, const char* _long) const
	{
		const char* arg = findOption(_short, _long, 1);
		_value = arg;
		return NULL != arg;
	}
コード例 #18
0
ファイル: commandline.cpp プロジェクト: ImJezze/mame
	bool CommandLine::hasArg(const char* _long) const
	{
		const char* arg = findOption('\0', _long, int32_t(0) );
		return NULL != arg;
	}
コード例 #19
0
ファイル: popt.c プロジェクト: FabrizioFabbe/silc
/* returns 'val' element, -1 on last item, POPT_ERROR_* on error */
int poptGetNextOpt(poptContext con) {
    char * optString, * chptr, * localOptString;
    char * longArg = NULL;
    char * origOptString, *dup;
    long aLong;
    char * end;
    const struct poptOption * opt = NULL;
    int done = 0;
    int i;
    poptCallbackType cb;
    void * cbData;
    int singleDash;

    dup = NULL;
    while (!done) {
        if (dup) {
            g_free(dup);
            dup = NULL;
        }
	while (!con->os->nextCharArg && con->os->next == con->os->argc 
		&& con->os > con->optionStack)
	    con->os--;
	if (!con->os->nextCharArg && con->os->next == con->os->argc) {
	    invokeCallbacks(con, con->options, 1);
	    if (con->doExec) execCommand(con);
	    return -1;
	}

	if (!con->os->nextCharArg) {
		
	    origOptString = con->os->argv[con->os->next++];

	    if (con->restLeftover || *origOptString != '-') {
		con->leftovers[con->numLeftovers++] = origOptString;
		if (con->flags & POPT_CONTEXT_POSIXMEHARDER)
		    con->restLeftover = 1;
		continue;
	    }

	    /* Make a copy we can hack at */
	    dup = localOptString = optString =
			g_strdup(origOptString);

            if (!optString[0]) {
                g_free(dup);
		return POPT_ERROR_BADOPT;
            }

	    if (optString[1] == '-' && !optString[2]) {
		con->restLeftover = 1;
		continue;
	    } else {
		optString++;
		if (*optString == '-')
		    singleDash = 0, optString++;
		else
		    singleDash = 1;

		if (handleAlias(con, optString, '\0', NULL))
		    continue;
		if (handleExec(con, optString, '\0'))
		    continue;

		chptr = optString;
		while (*chptr && *chptr != '=') chptr++;
		if (*chptr == '=') {
		    longArg = origOptString + (chptr - localOptString) + 1;
		    *chptr = '\0';
		}

		opt = findOption(con->options, optString, '\0', &cb, &cbData,
				 singleDash);
                if (!opt && !singleDash) {
                    g_free(dup);
                    return POPT_ERROR_BADOPT;
                }
	    }

	    if (!opt)
		con->os->nextCharArg = origOptString + 1;
	}

	if (con->os->nextCharArg) {
	    origOptString = con->os->nextCharArg;

	    con->os->nextCharArg = NULL;

	    if (handleAlias(con, NULL, *origOptString,
			    origOptString + 1)) {
		origOptString++;
		continue;
	    }
	    if (handleExec(con, NULL, *origOptString))
		continue;

	    opt = findOption(con->options, NULL, *origOptString, &cb, 
			     &cbData, 0);
            if (!opt) {
                g_free(dup);
                return POPT_ERROR_BADOPT;
            }
	    origOptString++;
	    if (*origOptString)
		con->os->nextCharArg = origOptString;
	}

	if (opt->arg && (opt->argInfo & POPT_ARG_MASK) == POPT_ARG_NONE) {
	    *((int *)opt->arg) = 1;
	} else if ((opt->argInfo & POPT_ARG_MASK) == POPT_ARG_VAL) {
	    if (opt->arg) *((int *) opt->arg) = opt->val;
	} else if ((opt->argInfo & POPT_ARG_MASK) != POPT_ARG_NONE) {
	    if (longArg) {
		con->os->nextArg = longArg;
	    } else if (con->os->nextCharArg) {
		con->os->nextArg = con->os->nextCharArg;
		con->os->nextCharArg = NULL;
	    } else { 
		while (con->os->next == con->os->argc && 
		       con->os > con->optionStack)
		    con->os--;
                if (con->os->next == con->os->argc) {
                    g_free(dup);
		    return POPT_ERROR_NOARG;
                }

		con->os->nextArg = con->os->argv[con->os->next++];
	    }

	    if (opt->arg) {
		switch (opt->argInfo & POPT_ARG_MASK) {
		  case POPT_ARG_STRING:
		    *((char **) opt->arg) = con->os->nextArg;
		    break;

		  case POPT_ARG_INT:
		  case POPT_ARG_LONG:
		    aLong = strtol(con->os->nextArg, &end, 0);
                    if (!(end && *end == '\0')) {
                        g_free(dup);
			return POPT_ERROR_BADNUMBER;
                    }

                    if (aLong == LONG_MIN || aLong == LONG_MAX) {
                        g_free(dup);
			return POPT_ERROR_OVERFLOW;
                    }
		    if ((opt->argInfo & POPT_ARG_MASK) == POPT_ARG_LONG) {
			*((long *) opt->arg) = aLong;
		    } else {
                        if (aLong > INT_MAX || aLong < INT_MIN) {
                            g_free(dup);
			    return POPT_ERROR_OVERFLOW;
                        }
			*((int *) opt->arg) =aLong;
		    }
		    break;

		  default:
		    fprintf(stdout, POPT_("option type (%d) not implemented in popt\n"),
		      opt->argInfo & POPT_ARG_MASK);
		    exit(1);
		}
	    }
	}

	if (cb)
	    cb(con, POPT_CALLBACK_REASON_OPTION, opt, con->os->nextArg, cbData);
	else if (opt->val && ((opt->argInfo & POPT_ARG_MASK) != POPT_ARG_VAL))
	    done = 1;

	if ((con->finalArgvCount + 2) >= (con->finalArgvAlloced)) {
	    con->finalArgvAlloced += 10;
	    con->finalArgv = realloc(con->finalArgv,
			    sizeof(*con->finalArgv) * con->finalArgvAlloced);
	}

	i = con->finalArgvCount++;
	con->finalArgv[i] = 
		malloc((opt->longName ? strlen(opt->longName) : 0) + 3);
	if (opt->longName)
	    sprintf(con->finalArgv[i], "--%s", opt->longName);
	else 
	    sprintf(con->finalArgv[i], "-%c", opt->shortName);

	if (opt->arg && (opt->argInfo & POPT_ARG_MASK) != POPT_ARG_NONE
		     && (opt->argInfo & POPT_ARG_MASK) != POPT_ARG_VAL) 
	    con->finalArgv[con->finalArgvCount++] =
	        strcpy(malloc(strlen(con->os->nextArg)+1), con->os->nextArg);
    }

    if (dup) g_free(dup);
    return opt->val;
}
コード例 #20
0
ファイル: mptest.c プロジェクト: xluoly/raw-os_sqlite
int sqlite_test()
{
  const char *zClient;
  int iClient;
  int n, i;
  int openFlags = SQLITE_OPEN_READWRITE;
  int rc;
  char *zScript;
  int taskId;
  const char *zTrace;
  const char *zCOption;

  g.argv0 = argv[0];
  g.iTrace = 1;
  if( argc<2 ) usage(argv[0]);
  g.zDbFile = argv[1];
  if( strglob("*.test", g.zDbFile) ) usage(argv[0]);
  if( strcmp(sqlite3_sourceid(), SQLITE_SOURCE_ID)!=0 ){
    fprintf(stderr, "SQLite library and header mismatch\n"
                    "Library: %s\n"
                    "Header:  %s\n",
                    sqlite3_sourceid(), SQLITE_SOURCE_ID);
    exit(1);
  }
  n = argc-2;
  sqlite3_snprintf(sizeof(g.zName), g.zName, "%05d.mptest", GETPID());
  g.zVfs = findOption(argv+2, &n, "vfs", 1);
  zClient = findOption(argv+2, &n, "client", 1);
  g.zErrLog = findOption(argv+2, &n, "errlog", 1);
  g.zLog = findOption(argv+2, &n, "log", 1);
  zTrace = findOption(argv+2, &n, "trace", 1);
  if( zTrace ) g.iTrace = atoi(zTrace);
  if( findOption(argv+2, &n, "quiet", 0)!=0 ) g.iTrace = 0;
  g.bSqlTrace = findOption(argv+2, &n, "sqltrace", 0)!=0;
  g.bSync = findOption(argv+2, &n, "sync", 0)!=0;
  if( g.zErrLog ){
    g.pErrLog = fopen(g.zErrLog, "a");
  }else{
    g.pErrLog = stderr;
  }
  if( g.zLog ){
    g.pLog = fopen(g.zLog, "a");
  }else{
    g.pLog = stdout;
  }
  
  sqlite3_config(SQLITE_CONFIG_LOG, sqlErrorCallback, 0);
  if( zClient ){
    iClient = atoi(zClient);
    if( iClient<1 ) fatalError("illegal client number: %d\n", iClient);
    sqlite3_snprintf(sizeof(g.zName), g.zName, "%05d.client%02d",
                     GETPID(), iClient);
  }else{
    if( g.iTrace>0 ){
      printf("With SQLite " SQLITE_VERSION " " SQLITE_SOURCE_ID "\n" );
      for(i=0; (zCOption = sqlite3_compileoption_get(i))!=0; i++){
        printf("-DSQLITE_%s\n", zCOption);
      }
      fflush(stdout);
    }
    iClient =  0;
    unlink(g.zDbFile);
    openFlags |= SQLITE_OPEN_CREATE;
  }
  rc = sqlite3_open_v2(g.zDbFile, &g.db, openFlags, g.zVfs);
  if( rc ) fatalError("cannot open [%s]", g.zDbFile);
  sqlite3_enable_load_extension(g.db, 1);
  sqlite3_busy_handler(g.db, busyHandler, 0);
  sqlite3_create_function(g.db, "vfsname", 0, SQLITE_UTF8, 0,
                          vfsNameFunc, 0, 0);
  sqlite3_create_function(g.db, "eval", 1, SQLITE_UTF8, 0,
                          evalFunc, 0, 0);
  g.iTimeout = DEFAULT_TIMEOUT;
  if( g.bSqlTrace ) sqlite3_trace(g.db, sqlTraceCallback, 0);
  if( !g.bSync ) trySql("PRAGMA synchronous=OFF");
  if( iClient>0 ){
    if( n>0 ) unrecognizedArguments(argv[0], n, argv+2);
    if( g.iTrace ) logMessage("start-client");
    while(1){
      char *zTaskName = 0;
      rc = startScript(iClient, &zScript, &taskId, &zTaskName);
      if( rc==SQLITE_DONE ) break;
      if( g.iTrace ) logMessage("begin %s (%d)", zTaskName, taskId);
      runScript(iClient, taskId, zScript, zTaskName);
      if( g.iTrace ) logMessage("end %s (%d)", zTaskName, taskId);
      finishScript(iClient, taskId, 0);
      sqlite3_free(zTaskName);
      sqlite3_sleep(10);
    }
    if( g.iTrace ) logMessage("end-client");
  }else{
    sqlite3_stmt *pStmt;
    int iTimeout;
    if( n==0 ){
      fatalError("missing script filename");
    }
    if( n>1 ) unrecognizedArguments(argv[0], n, argv+2);
    runSql(
      "CREATE TABLE task(\n"
      "  id INTEGER PRIMARY KEY,\n"
      "  name TEXT,\n"
      "  client INTEGER,\n"
      "  starttime DATE,\n"
      "  endtime DATE,\n"
      "  script TEXT\n"
      ");"
      "CREATE INDEX task_i1 ON task(client, starttime);\n"
      "CREATE INDEX task_i2 ON task(client, endtime);\n"
      "CREATE TABLE counters(nError,nTest);\n"
      "INSERT INTO counters VALUES(0,0);\n"
      "CREATE TABLE client(id INTEGER PRIMARY KEY, wantHalt);\n"
    );
    zScript = readFile(argv[2]);
    if( g.iTrace ) logMessage("begin script [%s]\n", argv[2]);
    runScript(0, 0, zScript, argv[2]);
    sqlite3_free(zScript);
    if( g.iTrace ) logMessage("end script [%s]\n", argv[2]);
    waitForClient(0, 2000, "during shutdown...\n");
    trySql("UPDATE client SET wantHalt=1");
    sqlite3_sleep(10);
    g.iTimeout = 0;
    iTimeout = 1000;
    while( ((rc = trySql("SELECT 1 FROM client"))==SQLITE_BUSY
        || rc==SQLITE_ROW) && iTimeout>0 ){
      sqlite3_sleep(10);
      iTimeout -= 10;
    }
    sqlite3_sleep(100);
    pStmt = prepareSql("SELECT nError, nTest FROM counters");
    iTimeout = 1000;
    while( (rc = sqlite3_step(pStmt))==SQLITE_BUSY && iTimeout>0 ){
      sqlite3_sleep(10);
      iTimeout -= 10;
    }
    if( rc==SQLITE_ROW ){
      g.nError += sqlite3_column_int(pStmt, 0);
      g.nTest += sqlite3_column_int(pStmt, 1);
    }
    sqlite3_finalize(pStmt);
  }
  sqlite3_close(g.db);  
  maybeClose(g.pLog);
  maybeClose(g.pErrLog);
  if( iClient==0 ){
    printf("Summary: %d errors in %d tests\n", g.nError, g.nTest);
  }
  return g.nError>0;
}
コード例 #21
0
/* returns 'val' element, -1 on last item, POPT_ERROR_* on error */
int poptGetNextOpt(poptContext con)
{
    const struct poptOption * opt = NULL;
    int done = 0;

    if (con == NULL)
	return -1;
    while (!done) {
	const char * origOptString = NULL;
	poptCallbackType cb = NULL;
	const void * cbData = NULL;
	const char * longArg = NULL;
	int canstrip = 0;
	int shorty = 0;

	while (!con->os->nextCharArg && con->os->next == con->os->argc
		&& con->os > con->optionStack) {
	    cleanOSE(con->os--);
	}
	if (!con->os->nextCharArg && con->os->next == con->os->argc) {
	    /*@-internalglobs@*/
	    invokeCallbacksPOST(con, con->options);
	    /*@=internalglobs@*/
	    if (con->doExec) return execCommand(con);
	    return -1;
	}

	/* Process next long option */
	if (!con->os->nextCharArg) {
	    char * localOptString, * optString;
	    int thisopt;

	    /*@-sizeoftype@*/
	    if (con->os->argb && PBM_ISSET(con->os->next, con->os->argb)) {
		con->os->next++;
		continue;
	    }
	    /*@=sizeoftype@*/
	    thisopt = con->os->next;
	    if (con->os->argv != NULL)	/* XXX can't happen */
	    origOptString = con->os->argv[con->os->next++];

	    if (origOptString == NULL)	/* XXX can't happen */
		return POPT_ERROR_BADOPT;

	    if (con->restLeftover || *origOptString != '-') {
		if (con->flags & POPT_CONTEXT_POSIXMEHARDER)
		    con->restLeftover = 1;
		if (con->flags & POPT_CONTEXT_ARG_OPTS) {
		    con->os->nextArg = xstrdup(origOptString);
		    return 0;
		}
		if (con->leftovers != NULL)	/* XXX can't happen */
		    con->leftovers[con->numLeftovers++] = origOptString;
		continue;
	    }

	    /* Make a copy we can hack at */
	    localOptString = optString =
		strcpy((char *)alloca(strlen(origOptString) + 1),
		       origOptString);

	    if (optString[0] == '\0')
		return POPT_ERROR_BADOPT;

	    if (optString[1] == '-' && !optString[2]) {
		con->restLeftover = 1;
		continue;
	    } else {
		char *oe;
		int singleDash;

		optString++;
		if (*optString == '-')
		    singleDash = 0, optString++;
		else
		    singleDash = 1;

		/* XXX aliases with arg substitution need "--alias=arg" */
		if (handleAlias(con, optString, '\0', NULL))
		    continue;

		if (handleExec(con, optString, '\0'))
		    continue;

		/* Check for "--long=arg" option. */
		for (oe = optString; *oe && *oe != '='; oe++)
		    {};
		if (*oe == '=') {
		    *oe++ = '\0';
		    /* XXX longArg is mapped back to persistent storage. */
		    longArg = origOptString + (oe - localOptString);
		}

		opt = findOption(con->options, optString, '\0', &cb, &cbData,
				 singleDash);
		if (!opt && !singleDash)
		    return POPT_ERROR_BADOPT;
	    }

	    if (!opt) {
		con->os->nextCharArg = origOptString + 1;
	    } else {
		if (con->os == con->optionStack &&
		   opt->argInfo & POPT_ARGFLAG_STRIP)
		{
		    canstrip = 1;
		    poptStripArg(con, thisopt);
		}
		shorty = 0;
	    }
	}

	/* Process next short option */
	/*@-branchstate@*/		/* FIX: W2DO? */
	if (con->os->nextCharArg) {
	    origOptString = con->os->nextCharArg;

	    con->os->nextCharArg = NULL;

	    if (handleAlias(con, NULL, *origOptString, origOptString + 1))
		continue;

	    if (handleExec(con, NULL, *origOptString)) {
		/* Restore rest of short options for further processing */
		origOptString++;
		if (*origOptString != '\0')
		    con->os->nextCharArg = origOptString;
		continue;
	    }

	    opt = findOption(con->options, NULL, *origOptString, &cb,
			     &cbData, 0);
	    if (!opt)
		return POPT_ERROR_BADOPT;
	    shorty = 1;

	    origOptString++;
	    if (*origOptString != '\0')
		con->os->nextCharArg = origOptString;
	}
	/*@=branchstate@*/

	if (opt == NULL) return POPT_ERROR_BADOPT;	/* XXX can't happen */
	if (opt->arg && (opt->argInfo & POPT_ARG_MASK) == POPT_ARG_NONE) {
	    if (poptSaveInt((int *)opt->arg, opt->argInfo, 1L))
		return POPT_ERROR_BADOPERATION;
	} else if ((opt->argInfo & POPT_ARG_MASK) == POPT_ARG_VAL) {
	    if (opt->arg) {
		if (poptSaveInt((int *)opt->arg, opt->argInfo, (long)opt->val))
		    return POPT_ERROR_BADOPERATION;
	    }
	} else if ((opt->argInfo & POPT_ARG_MASK) != POPT_ARG_NONE) {
	    con->os->nextArg = (const char *)_free(con->os->nextArg);
	    /*@-usedef@*/	/* FIX: W2DO? */
	    if (longArg) {
	    /*@=usedef@*/
		longArg = expandNextArg(con, longArg);
		con->os->nextArg = longArg;
	    } else if (con->os->nextCharArg) {
		longArg = expandNextArg(con, con->os->nextCharArg);
		con->os->nextArg = longArg;
		con->os->nextCharArg = NULL;
	    } else {
		while (con->os->next == con->os->argc &&
		       con->os > con->optionStack) {
		    cleanOSE(con->os--);
		}
		if (con->os->next == con->os->argc) {
		    if (!(opt->argInfo & POPT_ARGFLAG_OPTIONAL))
			/*@-compdef@*/	/* FIX: con->os->argv not defined */
			return POPT_ERROR_NOARG;
			/*@=compdef@*/
		    con->os->nextArg = NULL;
		} else {

		    /*
		     * Make sure this isn't part of a short arg or the
		     * result of an alias expansion.
		     */
		    if (con->os == con->optionStack &&
			(opt->argInfo & POPT_ARGFLAG_STRIP) &&
			canstrip) {
			poptStripArg(con, con->os->next);
		    }
		
		    if (con->os->argv != NULL) {	/* XXX can't happen */
			/* XXX watchout: subtle side-effects live here. */
			longArg = con->os->argv[con->os->next++];
			longArg = expandNextArg(con, longArg);
			con->os->nextArg = longArg;
		    }
		}
	    }
	    longArg = NULL;

	    if (opt->arg) {
		switch (opt->argInfo & POPT_ARG_MASK) {
		case POPT_ARG_STRING:
		    /* XXX memory leak, hard to plug */
		    *((const char **) opt->arg) = (con->os->nextArg)
			? xstrdup(con->os->nextArg) : NULL;
		    /*@switchbreak@*/ break;

		case POPT_ARG_INT:
		case POPT_ARG_LONG:
		{   long aLong = 0;
		    char *end;

		    if (con->os->nextArg) {
			aLong = strtol(con->os->nextArg, &end, 0);
			if (!(end && *end == '\0'))
			    return POPT_ERROR_BADNUMBER;
		    }

		    if ((opt->argInfo & POPT_ARG_MASK) == POPT_ARG_LONG) {
			if (aLong == LONG_MIN || aLong == LONG_MAX)
			    return POPT_ERROR_OVERFLOW;
			if (poptSaveLong((long *)opt->arg, opt->argInfo, aLong))
			    return POPT_ERROR_BADOPERATION;
		    } else {
			if (aLong > INT_MAX || aLong < INT_MIN)
			    return POPT_ERROR_OVERFLOW;
			if (poptSaveInt((int *)opt->arg, opt->argInfo, aLong))
			    return POPT_ERROR_BADOPERATION;
		    }
		}   /*@switchbreak@*/ break;

		case POPT_ARG_FLOAT:
		case POPT_ARG_DOUBLE:
		{   double aDouble = 0.0;
		    char *end;

		    if (con->os->nextArg) {
			/*@-mods@*/
			int saveerrno = errno;
			errno = 0;
			aDouble = strtod(con->os->nextArg, &end);
			if (errno == ERANGE)
			    return POPT_ERROR_OVERFLOW;
			errno = saveerrno;
			/*@=mods@*/
			if (*end != '\0')
			    return POPT_ERROR_BADNUMBER;
		    }

		    if ((opt->argInfo & POPT_ARG_MASK) == POPT_ARG_DOUBLE) {
			*((double *) opt->arg) = aDouble;
		    } else {
#ifndef _ABS
#define _ABS(a)	((((a) - 0.0) < 0xff) ? -(a) : (a))
#endif
		    }
		}   /*@switchbreak@*/ break;
		default:
		    fprintf(stdout,
			POPT_("option type (%d) not implemented in popt\n"),
			(opt->argInfo & POPT_ARG_MASK));
		    exit(EXIT_FAILURE);
		    /*@notreached@*/ /*@switchbreak@*/ break;
		}
	    }
	}

	if (cb) {
	    /*@-internalglobs@*/
	    invokeCallbacksOPTION(con, con->options, opt, cbData, shorty);
	    /*@=internalglobs@*/
	} else if (opt->val && ((opt->argInfo & POPT_ARG_MASK) != POPT_ARG_VAL))
	    done = 1;

	if ((con->finalArgvCount + 2) >= (con->finalArgvAlloced)) {
	    con->finalArgvAlloced += 10;
	    con->finalArgv = (const char **)realloc(con->finalArgv,
			    sizeof(*con->finalArgv) * con->finalArgvAlloced);
	}

	if (con->finalArgv != NULL)
	{   char *s = (char *)malloc(
		(opt->longName ? strlen(opt->longName) : 0) + 3);
	    if (s != NULL) {	/* XXX can't happen */
		if (opt->longName)
		    sprintf(s, "%s%s",
			((opt->argInfo & POPT_ARGFLAG_ONEDASH) ? "-" : "--"),
			opt->longName);
		else
		    sprintf(s, "-%c", opt->shortName);
		con->finalArgv[con->finalArgvCount++] = s;
	    } else
		con->finalArgv[con->finalArgvCount++] = NULL;
	}

	if (opt->arg && (opt->argInfo & POPT_ARG_MASK) == POPT_ARG_NONE)
	    /*@-ifempty@*/ ; /*@=ifempty@*/
	else if ((opt->argInfo & POPT_ARG_MASK) == POPT_ARG_VAL)
	    /*@-ifempty@*/ ; /*@=ifempty@*/
	else if ((opt->argInfo & POPT_ARG_MASK) != POPT_ARG_NONE) {
	    if (con->finalArgv != NULL && con->os->nextArg)
	        con->finalArgv[con->finalArgvCount++] =
			/*@-nullpass@*/	/* LCL: con->os->nextArg != NULL */
			xstrdup(con->os->nextArg);
			/*@=nullpass@*/
	}
    }

    return (opt ? opt->val : -1);	/* XXX can't happen */
}
コード例 #22
0
/*@-boundswrite@*/
/*@observer@*/ /*@null@*/ static const struct poptOption *
findOption(const struct poptOption * opt, /*@null@*/ const char * longName,
		char shortName,
		/*@null@*/ /*@out@*/ poptCallbackType * callback,
		/*@null@*/ /*@out@*/ const void ** callbackData,
		int singleDash)
	/*@modifies *callback, *callbackData */
{
    const struct poptOption * cb = NULL;

    /* This happens when a single - is given */
    if (singleDash && !shortName && (longName && *longName == '\0'))
	shortName = '-';

    for (; opt->longName || opt->shortName || opt->arg; opt++) {

	if ((opt->argInfo & POPT_ARG_MASK) == POPT_ARG_INCLUDE_TABLE) {
	    const struct poptOption * opt2;

	    /* Recurse on included sub-tables. */
	    if (opt->arg == NULL) continue;	/* XXX program error */
	    opt2 = findOption((const struct poptOption *)opt->arg, longName,
			      shortName, callback,
			      callbackData, singleDash);
	    if (opt2 == NULL) continue;
	    /* Sub-table data will be inheirited if no data yet. */
	    if (!(callback && *callback)) return opt2;
	    if (!(callbackData && *callbackData == NULL)) return opt2;
	    /*@-observertrans -dependenttrans @*/
	    *callbackData = opt->descrip;
	    /*@=observertrans =dependenttrans @*/
	    return opt2;
	} else if ((opt->argInfo & POPT_ARG_MASK) == POPT_ARG_CALLBACK) {
	    cb = opt;
	} else if (longName && opt->longName &&
		   (!singleDash || (opt->argInfo & POPT_ARGFLAG_ONEDASH)) &&
		/*@-nullpass@*/		/* LCL: opt->longName != NULL */
		   !strcmp(longName, opt->longName))
		/*@=nullpass@*/
	{
	    break;
	} else if (shortName && shortName == opt->shortName) {
	    break;
	}
    }

    if (!opt->longName && !opt->shortName)
	return NULL;
    /*@-modobserver -mods @*/
    if (callback) *callback = NULL;
    if (callbackData) *callbackData = NULL;
    if (cb) {
	if (callback)
	/*@-castfcnptr@*/
	    *callback = (poptCallbackType)cb->arg;
	/*@=castfcnptr@*/
	if (!(cb->argInfo & POPT_CBFLAG_INC_DATA)) {
	    if (callbackData)
		/*@-observertrans@*/	/* FIX: typedef double indirection. */
		*callbackData = cb->descrip;
		/*@=observertrans@*/
	}
    }
    /*@=modobserver =mods @*/

    return opt;
}
コード例 #23
0
ファイル: kcmdlineargs.cpp プロジェクト: fluxer/kdelibs
int
KCmdLineArgsStatic::findOption(const KCmdLineOptions &options, QByteArray &opt,
                               QByteArray &opt_name, QString &def, bool &enabled)
{
   for (int i = 0; i < options.d->names.size(); i++)
   {
      int result = 0;
      bool inverse = false;
      opt_name = options.d->names[i];
      if (opt_name.startsWith(':') || opt_name.isEmpty())
      {
         continue;
      }
      if (opt_name.startsWith('!'))
      {
         opt_name = opt_name.mid(1);
         result = 4;
      }
      if (opt_name.startsWith("no") && !opt_name.contains('<')) // krazy:exclude=strings
      {
         opt_name = opt_name.mid(2);
         inverse = true;
      }

      int len = opt.length();
      if (opt == opt_name.left(len))
      {
         opt_name = opt_name.mid(len);
         if (opt_name.isEmpty())
         {
            if (inverse)
               return result+2;

            if (options.d->descriptions[i].isEmpty())
            {
               i++;
               if (i >= options.d->names.size())
                  return result+0;
               QByteArray nextOption = options.d->names[i];
               int p = nextOption.indexOf(' ');
               if (p > 0)
                  nextOption = nextOption.left(p);
               if (nextOption.startsWith('!'))
                  nextOption = nextOption.mid(1);
               if (nextOption.startsWith("no") && !nextOption.contains('<')) // krazy:exclude=strings
               {
                  nextOption = nextOption.mid(2);
                  enabled = !enabled;
               }
               result = findOption(options, nextOption, opt_name, def, enabled);
               Q_ASSERT(result);
               opt = nextOption;
               return result;
            }

            return 1;
         }
         if (opt_name.startsWith(' '))
         {
            opt_name = opt_name.mid(1);
            def = options.d->defaults[i];
            return result+3;
         }
      }
   }
   return 0;
}
コード例 #24
0
int
tr_getopt( const char *      usage,
           int               argc,
           const char **     argv,
           const tr_option * opts,
           const char **     setme_optarg )
{
    int               i;
    const char *      arg = NULL;
    const tr_option * o = NULL;

    *setme_optarg = NULL;

    /* handle the builtin 'help' option */
    for( i = 1; i < argc; ++i )
    {
        if( !strcmp( argv[i], "-h" ) || !strcmp( argv[i], "--help" ) )
        {
            tr_getopt_usage( argv[0], usage, opts );
            exit( 0 );
        }
    }

    /* out of options? */
    if( argc == 1 || tr_optind >= argc )
        return TR_OPT_DONE;

    o = findOption( opts, argv[tr_optind], &arg );
    if( !o )
    {
        /* let the user know we got an unknown option... */
        *setme_optarg = argv[tr_optind++];
        return TR_OPT_UNK;
    }

    if( !o->has_arg )
    {
        /* no argument needed for this option, so we're done */
        if( arg )
            return TR_OPT_ERR;
        *setme_optarg = NULL;
        ++tr_optind;
        return o->val;
    }

    /* option needed an argument, and it was embedded in this string */
    if( arg )
    {
        *setme_optarg = arg;
        ++tr_optind;
        return o->val;
    }

    /* throw an error if the option needed an argument but didn't get one */
    if( ++tr_optind >= argc )
        return TR_OPT_ERR;
    if( findOption( opts, argv[tr_optind], NULL ) )
        return TR_OPT_ERR;

    *setme_optarg = argv[tr_optind++];
    return o->val;
}
コード例 #25
0
QString CommandLine::processOneParam(QStringList* params)
{
    QString err;

    QString p = params->at(0);
    bool nameFound = false;
    bool valueFound = false;
    QString name;
    QString value;

    if (p == "--" || p == "-") {
        err = QString(QObject::tr("Missing option name: %1")).arg(p);
    } else if (p.startsWith("--")) {
        int pos = p.indexOf("=");
        if (pos == 2) {
            err = QString(QObject::tr("Option name expected: %1")).arg(p);
        } else if (pos >= 0) {
            name = p.mid(2, pos - 2);
            value = p.right(p.length() - pos - 1);
            nameFound = true;
            valueFound = true;
            params->removeAt(0);
        } else {
            name = p.right(p.length() - 2);
            nameFound = true;
            params->removeAt(0);
        }
    } else if (p.startsWith("-")) {
        int pos = p.indexOf("=");
        if (pos == 1) {
            err = QString(QObject::tr("Option name cannot start with the equality sign: %1")).
                    arg(p);
        } else if (pos > 2) {
            err = QString(QObject::tr("Only one-letter options can start with a minus sign: %1")).
                    arg(p);
        } else if (pos == 2) {
            name = p.mid(1, 1);
            value = p.right(p.length() - 3);
            nameFound = true;
            valueFound = true;
            params->removeAt(0);
        } else {
            if (p.length() > 2) {
                err = QString(QObject::tr("Only one-letter options can start with a minus sign: %1")).
                        arg(p);
            } else {
                name = p.mid(1, 1);
                nameFound = true;
                params->removeAt(0);
            }
        }
    }

    // WPMUtils::outputTextConsole << name) << " --> " << value) <<
    //        " : " << err) << nameFound << valueFound << std::endl;

    if (err.isEmpty()) {
        if (nameFound) {
            // WPMUtils::outputTextConsole << "Searching: " << name) << std::endl;
            Option* opt = findOption(name);
            if (!opt) {
                err = QString(QObject::tr("Unknown option: %1")).arg(name);
            } else {
                if (opt->valueDescription.isEmpty() && valueFound) {
                    err = QString(QObject::tr("Unexpected value for the option %1")).arg(name);
                } else {
                    ParsedOption* po = new ParsedOption();
                    po->opt = opt;
                    this->parsedOptions.append(po);
                    if (valueFound)
                        po->value = value;
                    else {
                        if (!opt->valueDescription.isEmpty()) {
                            if (params->count() == 0) {
                                err = QString(QObject::tr("Missing value for the option %1")).
                                        arg(name);
                            } else {
                                po->value = params->at(0);
                                params->removeAt(0);
                            }
                        }
                    }
                }
            }
        } else {
            this->freeArguments.append(p);
            params->removeAt(0);
        }
    }

    return err;
}
コード例 #26
0
ファイル: fts3view.c プロジェクト: mingodad/sqlite
/*
** Report on the vocabulary.  This creates an fts4aux table with a random
** name, but deletes it in the end.
*/
static void showVocabulary(sqlite3 *db, const char *zTab) {
    char *zAux;
    sqlite3_uint64 r;
    sqlite3_stmt *pStmt;
    int nDoc = 0;
    int nToken = 0;
    int nOccurrence = 0;
    int nTop;
    int n, i;

    sqlite3_randomness(sizeof(r), &r);
    zAux = sqlite3_mprintf("viewer_%llx", zTab, r);
    runSql(db, "BEGIN");
    pStmt = prepare(db, "SELECT count(*) FROM %Q", zTab);
    while( sqlite3_step(pStmt)==SQLITE_ROW ) {
        nDoc = sqlite3_column_int(pStmt, 0);
    }
    sqlite3_finalize(pStmt);
    printf("Number of documents...................... %9d\n", nDoc);

    runSql(db, "CREATE VIRTUAL TABLE %s USING fts4aux(%Q)", zAux, zTab);
    pStmt = prepare(db,
                    "SELECT count(*), sum(occurrences) FROM %s WHERE col='*'",
                    zAux);
    while( sqlite3_step(pStmt)==SQLITE_ROW ) {
        nToken = sqlite3_column_int(pStmt, 0);
        nOccurrence = sqlite3_column_int(pStmt, 1);
    }
    sqlite3_finalize(pStmt);
    printf("Total tokens in all documents............ %9d\n", nOccurrence);
    printf("Total number of distinct tokens.......... %9d\n", nToken);
    if( nToken==0 ) goto end_vocab;

    n = 0;
    pStmt = prepare(db, "SELECT count(*) FROM %s"
                    " WHERE col='*' AND occurrences==1", zAux);
    while( sqlite3_step(pStmt)==SQLITE_ROW ) {
        n = sqlite3_column_int(pStmt, 0);
    }
    sqlite3_finalize(pStmt);
    printf("Tokens used exactly once................. %9d %5.2f%%\n",
           n, n*100.0/nToken);

    n = 0;
    pStmt = prepare(db, "SELECT count(*) FROM %s"
                    " WHERE col='*' AND documents==1", zAux);
    while( sqlite3_step(pStmt)==SQLITE_ROW ) {
        n = sqlite3_column_int(pStmt, 0);
    }
    sqlite3_finalize(pStmt);
    printf("Tokens used in only one document......... %9d %5.2f%%\n",
           n, n*100.0/nToken);

    if( nDoc>=2000 ) {
        n = 0;
        pStmt = prepare(db, "SELECT count(*) FROM %s"
                        " WHERE col='*' AND occurrences<=%d", zAux, nDoc/1000);
        while( sqlite3_step(pStmt)==SQLITE_ROW ) {
            n = sqlite3_column_int(pStmt, 0);
        }
        sqlite3_finalize(pStmt);
        printf("Tokens used in 0.1%% or less of docs...... %9d %5.2f%%\n",
               n, n*100.0/nToken);
    }

    if( nDoc>=200 ) {
        n = 0;
        pStmt = prepare(db, "SELECT count(*) FROM %s"
                        " WHERE col='*' AND occurrences<=%d", zAux, nDoc/100);
        while( sqlite3_step(pStmt)==SQLITE_ROW ) {
            n = sqlite3_column_int(pStmt, 0);
        }
        sqlite3_finalize(pStmt);
        printf("Tokens used in 1%% or less of docs........ %9d %5.2f%%\n",
               n, n*100.0/nToken);
    }

    nTop = atoi(findOption("top", 1, "25"));
    printf("The %d most common tokens:\n", nTop);
    pStmt = prepare(db,
                    "SELECT term, documents FROM %s"
                    " WHERE col='*'"
                    " ORDER BY documents DESC, term"
                    " LIMIT %d", zAux, nTop);
    i = 0;
    while( sqlite3_step(pStmt)==SQLITE_ROW ) {
        i++;
        n = sqlite3_column_int(pStmt, 1);
        printf("  %2d. %-30s %9d docs %5.2f%%\n", i,
               sqlite3_column_text(pStmt, 0), n, n*100.0/nDoc);
    }
    sqlite3_finalize(pStmt);

end_vocab:
    runSql(db, "ROLLBACK");
    sqlite3_free(zAux);
}
コード例 #27
0
void processArgs(int argc, char** argv)
{
   MyOption* o;
   int n=0;
   int i;
   struct option* opts;
   char* sArgs;
   int c;

   if ( ! myargs) return;
   o = myargs;
   while(o)
   {n++,o=nextOption(o);}

   o = myargs;
   sArgs= (char*)comdCalloc(2*(n+2),sizeof(char));
   opts = (struct option*)comdCalloc(n,sizeof(struct option));
   for (i=0; i<n; i++)
   {
      opts[i].name = o->longArg;
      opts[i].has_arg = o->argFlag;
      opts[i].flag    = 0;
      opts[i].val     = o->shortArg[0];

      strcat(sArgs,(char*) o->shortArg);
      if(o->argFlag) strcat(sArgs,":");
      o = nextOption(o);
   }

   while(1)
   {

      int option_index = 0;

      c = getopt_long (argc, argv, sArgs, opts, &option_index);
      if ( c == -1) break;
      o = findOption(myargs,c);
      if ( ! o )
      {
         fprintf(screenOut,"\n\n"
            "    invalid switch : -%c in getopt()\n"
            "\n\n",
            c);
         break;
      }      
      if(! o->argFlag)
      {
         int* i = (int*)o->ptr;
         *i = 1;
      }
      else 
      {
         switch(o->type)
         {
            case 'i':
               sscanf(optarg,"%d",(int*)o->ptr);
               break;
            case 'f':
               sscanf(optarg,"%f",(float*)o->ptr);
               break;
            case 'd':
               sscanf(optarg,"%lf",(double*)o->ptr);
               break;
            case 's':
               strncpy((char*)o->ptr,(char*)optarg,o->sz);
               ((char*)o->ptr)[o->sz-1] = '\0';
               break;
            case 'c':
               sscanf(optarg,"%c",(char*)o->ptr);
               break;
            default:
               fprintf(screenOut,"\n\n"
                  "    invalid type : %c in getopt()\n"
                  "    valid values are 'e', 'z'. 'i','d','f','s', and 'c'\n"
                  "\n\n",
                  c);      
         }
      }
   }

   free(opts);
   free(sArgs);

   return;
}
コード例 #28
0
ファイル: main.cpp プロジェクト: ajacksified/breeze
int main( int argc, char** argv )
{

    signal( SIGSEGV, sigSegvHandler );

    options.push_back( CmdOption( "", "--port", "\t\tlistening port", "port", true ) );
    options.push_back( CmdOption( "-h", "--help", "\t\tprints help", "help" ) );
    options.push_back( CmdOption( "-v", "--version", "\t\tprints version", "version" ) );
    options.push_back( CmdOption( "", "--connectionThreads", "\tconnection threads", "connectionThreads", true ) );
    options.push_back( CmdOption( "", "--poolThreads", "\tpool threads", "poolThreads", true ) );
    
    //
    //  parse command line
    //
    std::string script;
    unsigned int port = 8080;
    unsigned int connectionThreads = 0;
    unsigned int poolThreads = 0;
    
    try
    {
        for ( int i = 1; i < argc; i++ )
        {
            if ( CmdOption::isOption( argv[i] ) )
            {
                const CmdOption* option = findOption( argv[i] );

                if ( !option )
                {
                    printf( "Unrecognized option %s \n", argv[i] );
                    throw argv[i];
                }

                if ( option->name( ) == "help" )
                {
                    usage( true );
                }
                
                if ( option->name( ) == "version" )
                {
                    printf( "%s \n",  BREEZE_VERSION );
                    exit(1);
                }

                if ( option->name( ) == "port" )
                {
                    port = atoi( option->value( ) );
                }
                
                if ( option->name( ) == "connectionThreads" )
                {
                    connectionThreads = atoi( option->value( ) );
                }
                
                
             }
            else
            {
                script = argv[i];
            }

        }
    }
    catch ( ... )
    {
        usage();
    }

    if ( !script.size() )
    {
        usage( true );
    }
    

    Breeze* breeze = Breeze::create( port );
    
    breeze->setEnvironment( getenv("BREEZE_ENV") );
    
    
    //      
    //  add paths to locate lua files
    //
    breeze->addPath( BREEZE_PATH );
    std::string path;
    size_t lastSlash = script.rfind( '/' );
        
    
    if ( lastSlash != std::string::npos )
    {
        path = script.substr( 0, lastSlash );
        script = script.substr( lastSlash + 1 );
    }
        
    //
    //  get script path
    //
    if ( script[0] != '/' )
    {
        char buffer[256] = "/0";
        getcwd( buffer, sizeof( buffer ) );
        
        if ( path != "." )
        {
            std::string temp = path;
            path = buffer;
            
            if ( temp.size() )
            {
                path = path + "/" + temp;
            }
        }
    }
    
    //
    //  set working directory
    //
    chdir( path.c_str() );
    
    breeze->addPath( path );
    breeze->setScript( script );
    
    try
    {
        printf( "starting server on port %d \n", port );
        breeze->run();
    }
    catch( ... )
    {
        return 1;
    }
    
    return 0;
}
コード例 #29
0
ファイル: kcmdlineargs.cpp プロジェクト: fluxer/kdelibs
void
KCmdLineArgsStatic::findOption(const QByteArray &optv, const QByteArray &_opt,
                               int &i, bool _enabled, bool &moreOptions)
{
   KCmdLineArgsList::Iterator args = s->argsList->begin();
   QByteArray opt = _opt;
   QByteArray opt_name;
   QString def;
   QByteArray argument;
   int j = opt.indexOf('=');
   if (j != -1)
   {
      argument = opt.mid(j+1);
      opt = opt.left(j);
   }

   bool enabled = true;
   int result = 0;
   while (args != s->argsList->end())
   {
      enabled = _enabled;
      result = findOption((*args)->d->options, opt, opt_name, def, enabled);
      if (result) break;
      ++args;
   }
   if ((args == s->argsList->end()) &&
       (optv.startsWith('-') && !optv.startsWith("--"))) // krazy:exclude=strings
   {
      // Option not found check if it is a valid option
      // in the style of -Pprinter1 or ps -aux
      int p = 1;
      while (true)
      {
         QByteArray singleCharOption = " "; // krazy:exclude=doublequote_chars
         singleCharOption[0] = optv[p];
         args = s->argsList->begin();
         while (args != s->argsList->end())
         {
            enabled = _enabled;
            result = findOption((*args)->d->options, singleCharOption,
			          opt_name, def, enabled);
            if (result) break;
            ++args;
         }
         if (args == s->argsList->end())
            break; // Unknown argument

         p++;
         if (result == 1) // Single option
         {
            (*args)->d->setOption(singleCharOption, enabled);
            if (p < optv.length())
               continue; // Next option
            else
               return; // Finished
         }
         else if (result == 3) // This option takes an argument
         {
            if (argument.isEmpty())
            {
               argument = optv.mid(p);
            }
            (*args)->d->setOption(singleCharOption, argument);
            return;
         }
         break; // Unknown argument
      }
      args = s->argsList->end();
      result = 0;
   }

   if (args == s->argsList->end() || !result)
   {
      if (s->ignoreUnknown)
         return;
      KCmdLineArgs::enable_i18n();
      KCmdLineArgs::usageError( i18n("Unknown option '%1'.", QString::fromLocal8Bit(_opt)));
   }

   if ((result & 4) != 0)
   {
      result &= ~4;
      moreOptions = false;
   }

   if (result == 3) // This option takes an argument
   {
      if (!enabled)
      {
         if (s->ignoreUnknown)
            return;
         KCmdLineArgs::enable_i18n();
         KCmdLineArgs::usageError( i18n("Unknown option '%1'.", QString::fromLocal8Bit(_opt)));
      }
      if (argument.isEmpty())
      {
         i++;
         if (i >= s->all_argc)
         {
            KCmdLineArgs::enable_i18n();
            KCmdLineArgs::usageError( i18nc("@info:shell %1 is cmdoption name","'%1' missing.",  QString::fromLocal8Bit(opt_name)));
         }
         argument = s->all_argv[i];
      }
      (*args)->d->setOption(opt, argument);
   }
   else
   {
      (*args)->d->setOption(opt, enabled);
   }
}
コード例 #30
0
/**
 * We bind lease for client till it continue with it on DHCPREQUEST.
 */
Lease ConfigurationManager::allocateLease4Client(const Client& client, PCRTNETBOOTP pDhcpMsg, size_t cbDhcpMsg)
{
    {
        /**
         * This mean that client has already bound or commited lease.
         * If we've it happens it means that we received DHCPDISCOVER twice.
         */
        const Lease l = client.lease();
        if (l != Lease::NullLease)
        {
            /* Here we should take lease from the m_allocation which was feed with leases
             *  on start
             */
            if (l.isExpired())
            {
                expireLease4Client(const_cast<Client&>(client));
                if (!l.isExpired())
                    return l;
            }
            else
            {
                AssertReturn(l.getAddress().u != 0, Lease::NullLease);
                return l;
            }
        }
    }

    RTNETADDRIPV4 hintAddress;
    RawOption opt;
    NetworkConfigEntity *pNetCfg;

    Client cl(client);
    AssertReturn(g_RootConfig->match(cl, (BaseConfigEntity **)&pNetCfg) > 0, Lease::NullLease);

    /* DHCPDISCOVER MAY contain request address */
    hintAddress.u = 0;
    int rc = findOption(RTNET_DHCP_OPT_REQ_ADDR, pDhcpMsg, cbDhcpMsg, opt);
    if (RT_SUCCESS(rc))
    {
        hintAddress.u = *(uint32_t *)opt.au8RawOpt;
        if (   RT_H2N_U32(hintAddress.u) < RT_H2N_U32(pNetCfg->lowerIp().u)
            || RT_H2N_U32(hintAddress.u) > RT_H2N_U32(pNetCfg->upperIp().u))
            hintAddress.u = 0; /* clear hint */
    }

    if (   hintAddress.u
        && !isAddressTaken(hintAddress))
    {
        Lease l(cl);
        l.setConfig(pNetCfg);
        l.setAddress(hintAddress);
        m->m_allocations.insert(MapLease2Ip4AddressPair(l, hintAddress));
        return l;
    }

    uint32_t u32 = 0;
    for(u32 = RT_H2N_U32(pNetCfg->lowerIp().u);
        u32 <= RT_H2N_U32(pNetCfg->upperIp().u);
        ++u32)
    {
        RTNETADDRIPV4 address;
        address.u = RT_H2N_U32(u32);
        if (!isAddressTaken(address))
        {
            Lease l(cl);
            l.setConfig(pNetCfg);
            l.setAddress(address);
            m->m_allocations.insert(MapLease2Ip4AddressPair(l, address));
            return l;
        }
    }

    return Lease::NullLease;
}