示例#1
0
文件: ctype.c 项目: DeforaOS/libc
/* tolower */
int tolower(int c)
{
	if(isupper(c))
		return c + 'a' - 'A';
	return c;
}
示例#2
0
文件: top.c 项目: AnthraX1/rk
int main(int argc, char **argv)
{
    /* For select(2). */
    struct timeval tv;
    fd_set in;
    /* For parsing arguments. */
    char *cp;
    /* The key read in. */
    char c;

    get_options();
    /*
     * Parse arguments.
     */
    argv++;
    while (*argv) {
	cp = *argv++;
	while (*cp) {
	    switch (*cp) {
	      case 'd':
	        if (cp[1]) {
		    if (sscanf(++cp, "%f", &Sleeptime) != 1) {
			fprintf(stderr, PROGNAME ": Bad delay time `%s'\n", cp);
			exit(1);
		    }
		    goto breakargv;
		} else if (*argv) { /* last char in an argv, use next as arg */
		    if (sscanf(cp = *argv++, "%f", &Sleeptime) != 1) {
			fprintf(stderr, PROGNAME ": Bad delay time `%s'\n", cp);
			exit(1);
		    }
		    goto breakargv;
		} else {
		    fprintf(stderr, "-d requires an argument\n");
		    exit(1);
		}
		break;
	      case 'q':
		if (!getuid())
		    /* set priority to -10 in order to stay above kswapd */
		    if (setpriority(PRIO_PROCESS, getpid(), -10)) {
			/* We check this just for paranoia.  It's not
			   fatal, and shouldn't happen. */
			perror(PROGNAME ": setpriority() failed");
		    }
		Sleeptime = 0;
		break;
	      case 'c':
	        show_cmd = !show_cmd;
		break;
	      case 'S':
		Cumulative = 1;
		break;
	      case 'i':
		Noidle = 1;
		break;
	      case 's':
		Secure = 1;
		break;
	      case '-':
		break;		/* Just ignore it */
#if defined (SHOWFLAG)
              case '/': showall++;
#endif
	      default:
		fprintf(stderr, PROGNAME ": Unknown argument `%c'\n", *cp);
		exit(1);
	    }
	    cp++;
	}
    breakargv:
    }
    
    /* set to PCPU sorting */
    register_sort_function( -1, (cmp_t)pcpu_sort);
    
    /* for correct handling of some fields, we have to do distinguish 
  * between kernel versions */
    set_linux_version();
    /* get kernel symbol table, if needed */
    if (!CL_wchan_nout) {
	if (open_psdb()) {
	    CL_wchan_nout = 1;
	} else {
	    psdbsucc = 1;
	}
    }

    setup_terminal();
    window_size();
    /*
     * calculate header size, length of cmdline field ...
     */
    Numfields = make_header();
    /*
     * Set up signal handlers.
     */
    signal(SIGHUP, (void *) (int) end);
    signal(SIGINT, (void *) (int) end);
    signal(SIGQUIT, (void *) (int) end);
    signal(SIGTSTP, (void *) (int) stop);
    signal(SIGWINCH, (void *) (int) window_size);

    /* loop, collecting process info and sleeping */
    while (1) {
	if (setjmp(redraw_jmp))
	    clear_screen();

	/* display the tasks */
	show_procs();
	/* sleep & wait for keyboard input */
	tv.tv_sec = Sleeptime;
	tv.tv_usec = (Sleeptime - (int) Sleeptime) * 1000000;
	FD_ZERO(&in);
	FD_SET(0, &in);
	if (select(16, &in, 0, 0, &tv) > 0 && read(0, &c, 1) == 1)
	    do_key(c);
    }
}

/*#######################################################################
 *#### Signal handled routines: error_end, end, stop, window_size     ###
 *#### Small utilities: make_header, getstr, getint, getfloat, getsig ###
 *#######################################################################
 */


	/*
	 *  end when exiting with an error.
	 */
void error_end(int rno)
{
    if (psdbsucc)
        close_psdb();
    ioctl(0, TCSETAF, &Savetty);
    PUTP(tgoto(cm, 0, Lines - 1));
    fputs("\r\n", stdout);
    exit(rno);
}
/*
	 * Normal end of execution.
	 */
void end(void)
{
    if (psdbsucc)
	close_psdb();
    ioctl(0, TCSETAF, &Savetty);
    PUTP(tgoto(cm, 0, Lines - 1));
    fputs("\r\n", stdout);
    exit(0);
}

/*
	 * SIGTSTP catcher.
	 */
void stop(void)
{
    /* Reset terminal. */
    if (psdbsucc)
	close_psdb();
    ioctl(0, TCSETAF, &Savetty);
    PUTP(tgoto(cm, 0, Lines - 3));
    fflush(stdout);
    raise(SIGTSTP);
    /* Later... */
    ioctl(0, TCSETAF, &Rawtty);
    signal(SIGTSTP, (void *) (int) stop);
    longjmp(redraw_jmp, 1);
}

/*
       * Reads the window size and clear the window.  This is called on setup,
       * and also catches SIGWINCHs, and adjusts Maxlines.  Basically, this is
       * the central place for window size stuff.
       */
void window_size(void)
{
    struct winsize ws;

    if (ioctl(1, TIOCGWINSZ, &ws) != -1) {
	Cols = ws.ws_col;
	Lines = ws.ws_row;
    } else {
	Cols = tgetnum("co");
	Lines = tgetnum("li");
    }
    clear_screen();
}
/*
       * this adjusts the lines needed for the header to the current value
       */
int make_header(void)
{
    int i, j;

    j = 0;
    for (i = 0; i < strlen(Fields); i++) {
	if (isupper(Fields[i])) {
	    pflags[j++] = Fields[i] - 'A';
	}
    }
    strcpy(Header, "");
    for (i = 0; i < j; i++)
	strcat(Header, headers[pflags[i]]);
    /* readjust window size ... */
    Maxcmd = Cols - strlen(Header) + 7;
    Maxlines = Display_procs ? Display_procs : Lines - header_lines;
    if (Maxlines > Lines - header_lines)
	Maxlines = Lines - header_lines;
    return (j);
}
示例#3
0
ACPI_STATUS
stroul64 (
    char                    *String,
    UINT32                  Base,
    UINT64                  *RetInteger)
{
    UINT32                  Index;
    UINT32                  Sign;
    UINT64                  ReturnValue = 0;
    ACPI_STATUS             Status = AE_OK;


    *RetInteger = 0;

    switch (Base)
    {
    case 0:
    case 8:
    case 10:
    case 16:

        break;

    default:
        /*
         * The specified Base parameter is not in the domain of
         * this function:
         */
        return (AE_BAD_PARAMETER);
    }

    /* Skip over any white space in the buffer: */

    while (isspace ((int) *String) || *String == '\t')
    {
        ++String;
    }

    /*
     * The buffer may contain an optional plus or minus sign.
     * If it does, then skip over it but remember what is was:
     */
    if (*String == '-')
    {
        Sign = ACPI_SIGN_NEGATIVE;
        ++String;
    }
    else if (*String == '+')
    {
        ++String;
        Sign = ACPI_SIGN_POSITIVE;
    }
    else
    {
        Sign = ACPI_SIGN_POSITIVE;
    }

    /*
     * If the input parameter Base is zero, then we need to
     * determine if it is octal, decimal, or hexadecimal:
     */
    if (Base == 0)
    {
        if (*String == '0')
        {
            if (tolower ((int) *(++String)) == 'x')
            {
                Base = 16;
                ++String;
            }
            else
            {
                Base = 8;
            }
        }
        else
        {
            Base = 10;
        }
    }

    /*
     * For octal and hexadecimal bases, skip over the leading
     * 0 or 0x, if they are present.
     */
    if (Base == 8 && *String == '0')
    {
        String++;
    }

    if (Base == 16 &&
        *String == '0' &&
        tolower ((int) *(++String)) == 'x')
    {
        String++;
    }

    /* Main loop: convert the string to an unsigned long */

    while (*String)
    {
        if (isdigit ((int) *String))
        {
            Index = ((UINT8) *String) - '0';
        }
        else
        {
            Index = (UINT8) toupper ((int) *String);
            if (isupper ((int) Index))
            {
                Index = Index - 'A' + 10;
            }
            else
            {
                goto ErrorExit;
            }
        }

        if (Index >= Base)
        {
            goto ErrorExit;
        }

        /* Check to see if value is out of range: */

        if (ReturnValue > ((ACPI_UINT64_MAX - (UINT64) Index) /
            (UINT64) Base))
        {
            goto ErrorExit;
        }
        else
        {
            ReturnValue *= Base;
            ReturnValue += Index;
        }

        ++String;
    }


    /* If a minus sign was present, then "the conversion is negated": */

    if (Sign == ACPI_SIGN_NEGATIVE)
    {
        ReturnValue = (ACPI_UINT32_MAX - ReturnValue) + 1;
    }

    *RetInteger = ReturnValue;
    return (Status);


ErrorExit:
    switch (Base)
    {
    case 8:

        Status = AE_BAD_OCTAL_CONSTANT;
        break;

    case 10:

        Status = AE_BAD_DECIMAL_CONSTANT;
        break;

    case 16:

        Status = AE_BAD_HEX_CONSTANT;
        break;

    default:

        /* Base validated above */

        break;
    }

    return (Status);
}
示例#4
0
bool f_ctype_upper(CVarRef text) {
    return ctype(text, [] (int i) -> int { return isupper(i); });
}
示例#5
0
/* return non-negative on success; -1 on error; 
   non-negative is the length of string parsed by f2_parse.
 */
int
f2_parse(const Uchar *file, size_t line, Uchar *lp, struct f2 *f2p, Uchar **psu_sense, struct sig_context *scp)
{
  Uchar *tmp = NULL, *err_lp = NULL,
    *disambig = NULL, *ampamp = NULL, 
    *orig_lp = lp, field = '\0', *psu_tmp = NULL;
  int ret = 0;
  const char *saved_phase = phase;
  int square, saved_with_textid = with_textid;

  if (!lp)
    return 1;
  /* err_lp = npool_copy(lp, scp->pool); */
  err_lp = (Uchar*)strdup((char*)lp);

  phase = "f2";
  with_textid = 0;

  /* skip the old shadow lem codes */
  if (*lp == '`')
    {
      vwarning2((char*)file,line,"%s: please remove deprecated shadow lem sequence '`' or '`?'",err_lp);      
      lp += 1 + (lp[1] == '?');
    }

  if ((ampamp = (unsigned char*)strstr((char*)lp, "&&")))
    {
      f2_parse_cof(file, line, lp, f2p, psu_sense, ampamp, scp);
      goto ret;
    }

  /* if the sig starts with @ parse the admin fields @PROJ%LANG:FORM=
   * first.
   *
   * N.B.: % and : are not recognized by field_end() as this causes
   * problems parsing morphology.
   */
  if ('@' == *lp)
    {
      f2p->project = lp+1;
      lp = (Uchar*)strchr((char*)lp,'%');
      if (lp)
	{
	  *lp++ = '\0';
	  f2p->lang = lp;
	  f2p->core = langcore_of((const char*)lp);
	  lp = (Uchar*)strchr((char*)lp,':');
	  if (lp)
	    {
	      *lp++ = '\0';
	      f2p->form = lp;
	      lp = (Uchar*)strchr((char*)lp,'=');
	      *lp++ = '\0';
	    }
	}
    }

  if ('[' == *lp)
    {
      /* FIXME: this needs to be more rigorous and check for CF-legal char in initial position */
      vwarning2((char*)file,line,"%s: lemmatization cannot begin with '['",err_lp);
      goto ret;
    }

  if (!strchr((const char *)lp,'['))
    {
      /* f2p->cf = "X"; */
      f2p->gw = (unsigned char *)"X";
      if (*lp == 'n')
	{
	  f2p->pos = "n";
	  ++lp;
	}
      else if (*lp == 'u')
	{
	  f2p->pos = "u";
	  ++lp;
	}
      goto pos_parse;
    }

  /* parse the CF[GW/SENSE]POS'EPOS which are constant: */
  f2p->cf = lp;
  if (*lp == '"')
    {
      ++lp;
      f2p->cf = lp; /* don't include quotes in the CF; 
		       WATCHME: what happens in post-cache
		       retrieval parse?
		     */
      BIT_SET(f2p->flags,F2_FLAGS_CF_QUOTED);
      /*  fp->explicit |= NEW_CF; */ 
      /* have to do something here, i.e., suppress charset translation */
    }

  while (*lp && (*lp != '[' || lp[-1] == '\\'))
    ++lp;

  if (BIT_ISSET(f2p->flags,F2_FLAGS_CF_QUOTED))
    {
      if (lp[-1] == '"')
	lp[-1] = '\0';
      else
	{
	  vwarning2((char*)file,line,"%s: '\"' missing on quoted CF",err_lp);
	  ret = -1;
	}
    }

  if (lp)
    *lp = '\0';
  else
    goto ret;

  if (lp[-1] == ')' && lp[-2] != '\\')
    {
      char *oparen = strchr((char*)f2p->cf,'(');
      if (oparen && oparen[-1] != '\\')
	{
	  *oparen++ = '\0';
	  f2p->restrictor = (unsigned char*)oparen;
	  lp[-1] = '\0';
	}
      else
	{
	  vwarning2((char*)file,line,"%s: '(' missing on restrictor",err_lp);
	  ret = -1;
	  goto ret;
	}
    }
  else if ((tmp = (unsigned char*)strchr((char*)f2p->cf,'(')) && tmp[-1] != '\\')
    {
      vwarning2((char*)file,line,"%s: ')' missing on restrictor",err_lp);
      ret = -1;
      goto ret;
    }

  f2p->gw = ++lp;
  if ((psu_tmp = (Uchar *)strstr(cc(lp),"+=")))
    {
      *psu_tmp = '\0';
      psu_tmp += 2;
      if (psu_sense)
	*psu_sense = psu_tmp;
      psu_tmp = (Uchar *)strchr((const char *)psu_tmp,']');
    }

  /* make SENSE optional here to support inline lem parsing */
  square = 0;
  while (*lp && (*lp != '/' || lp[1] != '/'))
    {
      if (*lp == '[' && lp[-1] != '\\')
	++square;
      else if (*lp == ']' && lp[-1] != '\\')
	{
	  if (square)
	    --square;
	  else
	    break;
	}
      ++lp;
    }

  /* If we didn't find ] but had a psu_sense with +=,
     reset lp to the closing square bracket after the
     psu_sense */
  if (!*lp && psu_tmp)
    lp = psu_tmp;

  if (*lp)
    {
      if ('/' == *lp)
	{
	  *lp++ = '\0';
	  ++lp;
	  f2p->sense = lp;
	  square = 0;
	  while (*lp)
	    {
	      if (*lp == '[' && lp[-1] != '\\')
		++square;
	      else if (*lp == ']' && lp[-1] != '\\')
		{
		  if (square)
		    --square;
		  else
		    break;
		}
	      ++lp;
	    }
	}
      if (*lp) /* lp is at closing square bracket of CF[GW] */
	{
	  *lp++ = '\0';
	  
	  /* This is either a POS or something
	     that starts with a field char */

	pos_parse:
	  if (isupper(*lp))
	    {
	      Uchar *end = NULL;
	      Uchar *epos = NULL;
	      for (end = lp; *end && !isspace(*end); ++end)
		;
	      epos = (Uchar*)strchr((const char *)lp,'\'');
	      f2p->pos = lp;
	      if (epos && epos < end)
		lp = epos;
	      else
		lp = field_end(lp);
	      if (*f2p->pos == 'V' && '/' == *lp && (lp[1] == 't' || lp[1] == 'i'))
		{
		  ++lp;
		  epos = (Uchar*)strchr((const char *)lp,'\'');
		  if (epos && epos < end)
		    lp = epos;
		  else
		    lp = field_end(lp);
		}
	      field = *lp;
	      if (field == '\'')
		{
		  *lp++ = '\0';
		  f2p->epos = lp;
		  lp = field_end(lp);
		  if (*f2p->epos == 'V' && '/' == *lp && (lp[1] == 't' || lp[1] == 'i'))
		    {
		      ++lp;
		      lp = field_end(lp);
		    }
		  field = *lp;
		  *lp++ = '\0';
		}
	      else
		*lp++ = '\0';
	    }
	  else if (*lp == '\'')
	    {
	      *lp++ = '\0';
	      f2p->epos = lp;
	      lp = field_end(lp);
	      field = *lp;
	      *lp++ = '\0';
	    }
	  else if (*lp)
	    {
	      field = *lp;
	      *lp++ = '\0';
	    }

	  /* Now we are at a variable set of instance
	     fields; parse as though they can be in any
	     order, though in principle the order should
	     always be fixed. */
	  while (*lp)
	    {
	      switch (field)
		{
#if 0
		  /* this must follow POS and ' is no longer a field
		   * ender because of conflict with ' in M1
		   */
		case '\'':
		  f2p->epos = lp;
		  break;
#endif
		case '@':
		  f2p->project = lp;
		  break;
		case '%':
		  f2p->lang = lp;
		  break;
		case ':':
		  f2p->form = lp;
		  break;
		case '$':
		  if (!BIT_ISSET(f2p->flags, F2_FLAGS_LEM_BY_NORM))
		    f2p->norm = lp;
		  /* else ignore normalization because we got it from the "FORM" */
		  break;
		case '/':
		  f2p->base = lp;
		  break;
		case '+':
		  if (*lp == '-')
		    f2p->cont = lp;
		  else if (*lp == '.')
		    f2p->augment = lp;
		  else
		    vwarning2((char*)file,line,"%s: '+' in signature should be followed by '-' or '.'", err_lp);
		  ++lp;
		  break;
		case '#':
		  if (*lp == '#')
		    {
		      ++lp;
		      f2p->morph2 = lp;
		    }
		  else
		    f2p->morph = lp;
		  break;
		case '*':
		  f2p->stem = lp;
		  break;
		case '\\':
		  disambig = lp;
		  while (isalnum(*lp) || '\\' == *lp)
		    ++lp;
		  break;
		case '<':
		case ' ':
		case '\t':
		case 0:
		  goto break_switch_loop;
		default:
		  vwarning2((char*)file,line,"%s: parse error at '%c'", err_lp, field);
		  ++ret;
		  goto ret;
		}
	      lp = field_end(lp);
	      if (*lp)
		{
		  field = *lp;
		  *lp++ = '\0';
		}
	    }
	}
    }

 break_switch_loop:

  validate_pos((const char *)file, line, f2p->pos);
  validate_pos((const char *)file, line, f2p->epos);
  if (f2p->base)
    validate_base((const char *)file, line, f2p->base);

#if 0
  /* If lp is non-zero we didn't manage to parse the entire form: */
  if (*lp)
    {
      vwarning2((char*)file,line,"%s: bad tense designator: only allowed with verb POS",err_lp);
      ret = -1;
      goto ret;
    }
#endif

  /* field == '$' occurs when $ is the end of the lem, e.g., ana[to]PRP$ */
  /* FIXME: THIS IS A POOR TEST BECAUSE IT FAILS ON ]N$#M1 */
  if (field == '$')
    {
      if (!f2p->norm || !*f2p->norm)
	f2p->norm = f2p->cf;
    }
  
  if (BIT_ISSET(f2p->flags, F2_FLAGS_LEM_BY_NORM))
    {
      if (f2p->norm && f2p->cf && !strcmp((char*)f2p->cf,(char*)f2p->norm))
	{
	  BIT_SET(f2p->flags, F2_FLAGS_NORM_IS_CF);
	  f2p->cf = NULL;
	}
    }

  if (f2p->gw)
    {
      char *bs = strchr((char*)f2p->gw, '\\');
      if (bs)
	{
	  unsigned char *gwtmp = npool_copy(f2p->gw, f2_pool);
	  bs = (char *)(gwtmp + (bs - (char*)f2p->gw));
	  *bs++ = '\0';
	  f2p->gw = gwtmp;
	  if (*bs == 'i' || *bs == 't')
	    {
	      if ((!f2p->pos || *f2p->pos == 'V')
		  && (!f2p->epos || *f2p->epos == 'V'))
		{
		  if (*bs == 'i')
		    f2p->epos = npool_copy((unsigned char *)"V/i",f2_pool);
		  else
		    f2p->epos = npool_copy((unsigned char *)"V/t",f2_pool);
		}
	      else
		{
		  vwarning2((char*)file,line,"%s: bad designator: only allowed with verb POS",err_lp);
		  ret = -1;
		  goto ret;
		}
	    }
	  else
	    {
	      vwarning2((char*)file,line,"%s: bad designator: only 'i' or 't' allowed",err_lp);
	      ret = -1;
	      goto ret;
	    }
	}
    }
 
 ret:
  free(err_lp);
  /* '<' == *lp must be dealt with by caller */
  if (isspace(*lp))
    *lp++ = '\0';

  if (!f2p->gw || !*f2p->gw)
    {
      if (f2p->sense && *f2p->sense)
	f2p->gw = f2p->sense;
      else
	f2p->gw = (unsigned char *)"1";
    }

  clean_cf((char*)file, line, (unsigned char *)f2p->cf);

  clean_gw_sense((char*)file, line, (unsigned char *)f2p->gw);
  if (f2p->sense)
    clean_gw_sense((char*)file, line, (unsigned char *)f2p->sense);

  if (f2p->augment)
    {
      char buf[1024];
      sprintf(buf,"%s%s%s",f2p->form,AUGMENT_STR,f2p->augment);
      f2p->form = npool_copy((unsigned char *)buf,f2_pool);
    }

  if (disambig)
    {
      char buf[1024];
      if (*disambig == *(DISAMBIG_STR))
	sprintf(buf,"%s%s",f2p->form,disambig);
      else
	sprintf(buf,"%s%s%s",f2p->form,DISAMBIG_STR,disambig);
      f2p->form = npool_copy((unsigned char *)buf,f2_pool);
    }

  if (f2p->cf && strchr((char*)f2p->cf,' '))
    BIT_SET(f2p->flags, F2_FLAGS_IS_PSU);
  phase = saved_phase;
  with_textid = saved_with_textid;

  return (ret < 0) ? -1 : (lp - orig_lp);
}
示例#6
0
int lc_evpprintf(const lc_arg_env_t *env, lc_appendable_t *app, const char *fmt,
                 va_list args)
{
	(void)args;

	int         res  = 0;
	const char *last = fmt + strlen(fmt);

	/* Find the first % */
	const char *s = strchr(fmt, '%');

	/* Emit the text before the first % was found */
	size_t addlen = (s ? s : last) - fmt;
	lc_appendable_snadd(app, fmt, addlen);
	res += addlen;

	while (s != NULL) {
		lc_arg_value_t val;

		/* We must be at a '%' */
		assert(*s == '%');

		/* Reset the occurrence structure */
		lc_arg_occ_t occ;
		memset(&occ, 0, sizeof(occ));

		/* Eat all flags and set the corresponding flags in the occ struct */
		for (++s; strchr("#0-+", *s); ++s) {
			switch (*s) {
				case '#':
					occ.flag_hash = 1;
					break;
				case '0':
					occ.flag_zero = 1;
					break;
				case '-':
					occ.flag_minus = 1;
					break;
				case '+':
					occ.flag_plus = 1;
					break;
				case ' ':
					occ.flag_space = 1;
					break;
			}
		}

		/* Read the width if given */
		s = read_int(s, &occ.width);

		occ.precision = -1;

		/* read the precision if given */
		if (*s == '.') {
			int precision;
			s = read_int(s + 1, &precision);

			/* Negative or lacking precision after a '.' is treated as
			 * precision 0. */
			occ.precision = MAX(0, precision);
		}

		/*
		 * Now, we can either have:
		 * - a named argument like {node}
		 * - some modifiers followed by a conversion specifier
		 * - or some other character, which ends this format invalidly
		 */
		char            ch  = *s;
		const lc_arg_t *arg = NULL;
		switch (ch) {
			case '%':
				s++;
				lc_appendable_chadd(app, '%');
				++res;
				break;
			case '{': {
				const char *named = ++s;

				/* Read until the closing brace or end of the string. */
				for (ch = *s; ch != '}' && ch != '\0'; ch = *++s) {
				}

				if (s - named) {
					size_t n = s - named;
					char *name;
					lc_arg_t tmp;

					name = (char*) malloc(sizeof(char) * (n + 1));
					MEMCPY(name, named, n);
					name[n] = '\0';
					tmp.name = name;

					arg = set_find(lc_arg_t, env->args, &tmp, sizeof(tmp), hash_str(named));
					occ.modifier = "";
					occ.modifier_length = 0;

					/* Set the conversion specifier of the occurrence to the
					 * letter specified in the argument description. */
					if (arg)
						occ.conversion = arg->letter;

					free(name);

					/* If we ended with a closing brace, move the current
					 * pointer after it, since it is not to be dumped. */
					if (ch == '}')
						s++;
				}
				break;
			}

			default: {
				const char *mod = s;

				/* Read, as long there are letters */
				while (isalpha((unsigned char)ch) && !arg) {
					int              base = 'a';
					lc_arg_t *const *map  = env->lower;

					/* If uppercase, select the uppercase map from the
					 * environment */
					if (isupper((unsigned char)ch)) {
						base = 'A';
						map = env->upper;
					}

					if (map[ch - base] != NULL) {
						occ.modifier = mod;
						occ.modifier_length = s - mod;
						occ.conversion = ch;
						arg = map[ch - base];
					}

					ch = *++s;
				}
			}
		}

		/* Call the handler if an argument was determined */
		if (arg != NULL && arg->handler != NULL) {
			const lc_arg_handler_t *handler = arg->handler;

			/* Let the handler determine the type of the argument based on the
			 * information gathered. */
			occ.lc_arg_type = handler->get_lc_arg_type(&occ);

			/* Store the value according to argument information */
			switch (occ.lc_arg_type) {
#define LC_ARG_TYPE(type,name,va_type) \
			case lc_arg_type_ ## name: val.v_ ## name = va_arg(args, va_type); break;
#include "lc_printf_arg_types.def"
#undef LC_ARG_TYPE
			}

			/* Finally, call the handler. */
			res += handler->emit(app, &occ, &val);
		}

		const char *old = s;
		s = strchr(s, '%');
		size_t addlen = (s ? s : last) - old;
		lc_appendable_snadd(app, old, addlen);
		res += addlen;
	}

	return res;
}
示例#7
0
int streambuf::vscan(char const *fmt0,
		     _G_va_list ap,
		     ios *stream /* = NULL */)
{
	register const u_char *fmt = (const u_char *)fmt0;
	register int c;		/* character from format, or conversion */
	register size_t width;	/* field width, or 0 */
	register char *p;	/* points into all kinds of strings */
	register int n;		/* handy integer */
	register int flags;	/* flags as defined above */
	register char *p0;	/* saves original value of p when necessary */
	int nassigned;		/* number of fields assigned */
	int nread;		/* number of characters consumed from fp */
	// Assignments to base and ccfn are just to suppress warnings from gcc.
	int base = 0;		/* base argument to strtol/strtoul */
	typedef u_long (*strtoulfn)(const char*, char**, int);
	strtoulfn ccfn = 0;
	// conversion function (strtol/strtoul)
	char ccltab[256];	/* character class table for %[...] */
	char buf[BUF];		/* buffer for numeric conversions */
	int seen_eof = 0;

	/* `basefix' is used to avoid `if' tests in the integer scanner */
	static short basefix[17] =
		{ 10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 };

	nassigned = 0;
	nread = 0;
	for (;;) {
		c = *fmt++;
		if (c == 0)
			goto done;
		if (isspace(c)) {
			for (;;) {
			        c = sbumpc();
				if (c == EOF)
				    goto eof_failure;
				if (!isspace(c)) {
				    sputbackc(c);
				    break;
				}
				nread++;
			}
			continue;
		}
		if (c != '%')
			goto literal;
		width = 0;
		flags = 0;
		/*
		 * switch on the format.  continue if done;
		 * break once format type is derived.
		 */
again:		c = *fmt++;
		switch (c) {
		case '%':
literal:
		        n = sbumpc();
			if (n == EOF)
			    goto eof_failure;
			if (n != c) {
			    sputbackc(n);
			    goto match_failure;
			}
			nread++;
			continue;

		case '*':
			flags |= SUPPRESS;
			goto again;
		case 'l':
			flags |= LONG;
			goto again;
		case 'L':
			flags |= LONGDBL;
			goto again;
		case 'h':
			flags |= SHORT;
			goto again;

		case '0': case '1': case '2': case '3': case '4':
		case '5': case '6': case '7': case '8': case '9':
			width = width * 10 + c - '0';
			goto again;

		/*
		 * Conversions.
		 * Those marked `compat' are for 4.[123]BSD compatibility.
		 *
		 * (According to ANSI, E and X formats are supposed
		 * to the same as e and x.  Sorry about that.)
		 */
		case 'D':	/* compat */
			flags |= LONG;
			/* FALLTHROUGH */
		case 'd':
			c = CT_INT;
			ccfn = (strtoulfn)strtol;
			base = 10;
			break;

		case 'i':
			c = CT_INT;
			ccfn = (strtoulfn)strtol;
			base = 0;
			break;

		case 'O':	/* compat */
			flags |= LONG;
			/* FALLTHROUGH */
		case 'o':
			c = CT_INT;
			ccfn = strtoul;
			base = 8;
			break;

		case 'u':
			c = CT_INT;
			ccfn = strtoul;
			base = 10;
			break;

		case 'X':
		case 'x':
			flags |= PFXOK;	/* enable 0x prefixing */
			c = CT_INT;
			ccfn = strtoul;
			base = 16;
			break;

#ifdef FLOATING_POINT
		case 'E': case 'F':
		case 'e': case 'f': case 'g':
			c = CT_FLOAT;
			break;
#endif

		case 's':
			c = CT_STRING;
			break;

		case '[':
			fmt = __sccl(ccltab, fmt);
			flags |= NOSKIP;
			c = CT_CCL;
			break;

		case 'c':
			flags |= NOSKIP;
			c = CT_CHAR;
			break;

		case 'p':	/* pointer format is like hex */
			flags |= POINTER | PFXOK;
			c = CT_INT;
			ccfn = strtoul;
			base = 16;
			break;

		case 'n':
			if (flags & SUPPRESS)	/* ??? */
				continue;
			if (flags & SHORT)
				*va_arg(ap, short *) = nread;
			else if (flags & LONG)
				*va_arg(ap, long *) = nread;
			else
				*va_arg(ap, int *) = nread;
			continue;

		/*
		 * Disgusting backwards compatibility hacks.	XXX
		 */
		case '\0':	/* compat */
		        nassigned = EOF;
			goto done;

		default:	/* compat */
			if (isupper(c))
				flags |= LONG;
			c = CT_INT;
			ccfn = (strtoulfn)strtol;
			base = 10;
			break;
		}

		/*
		 * We have a conversion that requires input.
		 */
		if (sgetc() == EOF)
			goto eof_failure;

		/*
		 * Consume leading white space, except for formats
		 * that suppress this.
		 */
		if ((flags & NOSKIP) == 0) {
		    n = (unsigned char)*_gptr;
		    while (isspace(n)) {
			_gptr++;
			nread++;
			n = sgetc();
			if (n == EOF)
			    goto eof_failure;
		    }
		    // Note that there is at least one character in
		    // the buffer, so conversions that do not set NOSKIP
		    // can no longer result in an input failure.
		}

		/*
		 * Do the conversion.
		 */
		switch (c) {

		case CT_CHAR:
			/* scan arbitrary characters (sets NOSKIP) */
			if (width == 0) // FIXME!
				width = 1;
			if (flags & SUPPRESS) {
			    size_t sum = 0;
			    for (;;) {
				if ((n = _egptr - _gptr) < (int)width) {
				    sum += n;
				    width -= n;
				    _gptr += n;
				    if (underflow() == EOF)
					if (sum == 0)
					    goto eof_failure;
					else {
					    seen_eof++;
					    break;
					}
				} else {
				    sum += width;
				    _gptr += width;
				    break;
				}
			    }
			    nread += sum;
			} else {
			    size_t r = sgetn((char*)va_arg(ap, char*),
						 width);
			    if (r != width)
				goto eof_failure;
			    nread += r;
			    nassigned++;
			}
			break;

		case CT_CCL:
			/* scan a (nonempty) character class (sets NOSKIP) */
			if (width == 0)
				width = ~0;	/* `infinity' */
			/* take only those things in the class */
			if (flags & SUPPRESS) {
				n = 0;
				while (ccltab[(unsigned char)*_gptr]) {
				    n++, _gptr++;
				    if (--width == 0)
					break;
				    if (sgetc() == EOF) {
					if (n == 0)
					    goto eof_failure;
					seen_eof++;
					break;
				    }
				}
				if (n == 0)
					goto match_failure;
			} else {
			    p0 = p = va_arg(ap, char *);
			    while (ccltab[(unsigned char)*_gptr]) {
				*p++ = *_gptr++;
				if (--width == 0)
				    break;
				if (sgetc() == EOF) {
				    if (p == p0)
					goto eof_failure;
				    seen_eof++;
				    break;
				}
			    }
			    n = p - p0;
			    if (n == 0)
				goto match_failure;
			    *p = 0;
			    nassigned++;
			}
			nread += n;
			break;

		case CT_STRING:
			/* like CCL, but zero-length string OK, & no NOSKIP */
			if (width == 0)
				width = ~0;
			if (flags & SUPPRESS) {
				n = 0;
				while (!isspace((unsigned char)*_gptr)) {
					n++, _gptr++;
					if (--width == 0)
						break;
					if (sgetc() == EOF) {
					    seen_eof++;
					    break;
					}
				}
				nread += n;
			} else {
				p0 = p = va_arg(ap, char *);
				while (!isspace((unsigned char)*_gptr)) {
					*p++ = *_gptr++;
					if (--width == 0)
						break;
					if (sgetc() == EOF) {
					    seen_eof++;
					    break;
					}
				}
				*p = 0;
				nread += p - p0;
				nassigned++;
			}
			continue;

		case CT_INT:
			/* scan an integer as if by strtol/strtoul */
			if (width == 0 || width > sizeof(buf) - 1)
				width = sizeof(buf) - 1;
			flags |= SIGNOK | NDIGITS | NZDIGITS;
			for (p = buf; width; width--) {
				c = (unsigned char)*_gptr;
				/*
				 * Switch on the character; `goto ok'
				 * if we accept it as a part of number.
				 */
				switch (c) {

				/*
				 * The digit 0 is always legal, but is
				 * special.  For %i conversions, if no
				 * digits (zero or nonzero) have been
				 * scanned (only signs), we will have
				 * base==0.  In that case, we should set
				 * it to 8 and enable 0x prefixing.
				 * Also, if we have not scanned zero digits
				 * before this, do not turn off prefixing
				 * (someone else will turn it off if we
				 * have scanned any nonzero digits).
				 */
				case '0':
					if (base == 0) {
						base = 8;
						flags |= PFXOK;
					}
					if (flags & NZDIGITS)
					    flags &= ~(SIGNOK|NZDIGITS|NDIGITS);
					else
					    flags &= ~(SIGNOK|PFXOK|NDIGITS);
					goto ok;

				/* 1 through 7 always legal */
				case '1': case '2': case '3':
				case '4': case '5': case '6': case '7':
					base = basefix[base];
					flags &= ~(SIGNOK | PFXOK | NDIGITS);
					goto ok;

				/* digits 8 and 9 ok iff decimal or hex */
				case '8': case '9':
					base = basefix[base];
					if (base <= 8)
						break;	/* not legal here */
					flags &= ~(SIGNOK | PFXOK | NDIGITS);
					goto ok;

				/* letters ok iff hex */
				case 'A': case 'B': case 'C':
				case 'D': case 'E': case 'F':
				case 'a': case 'b': case 'c':
				case 'd': case 'e': case 'f':
					/* no need to fix base here */
					if (base <= 10)
						break;	/* not legal here */
					flags &= ~(SIGNOK | PFXOK | NDIGITS);
					goto ok;

				/* sign ok only as first character */
				case '+': case '-':
					if (flags & SIGNOK) {
						flags &= ~SIGNOK;
						goto ok;
					}
					break;

				/* x ok iff flag still set & 2nd char */
				case 'x': case 'X':
					if (flags & PFXOK && p == buf + 1) {
						base = 16;	/* if %i */
						flags &= ~PFXOK;
						goto ok;
					}
					break;
				}

				/*
				 * If we got here, c is not a legal character
				 * for a number.  Stop accumulating digits.
				 */
				break;
		ok:
				/*
				 * c is legal: store it and look at the next.
				 */
				*p++ = c;
				_gptr++;
				if (sgetc() == EOF) {
				    seen_eof++;
				    break;		/* EOF */
				}
		        }
			/*
			 * If we had only a sign, it is no good; push
			 * back the sign.  If the number ends in `x',
			 * it was [sign] '0' 'x', so push back the x
			 * and treat it as [sign] '0'.
			 */
			if (flags & NDIGITS) {
				if (p > buf)
					(void) sputbackc(*(u_char *)--p);
				goto match_failure;
			}
			c = ((u_char *)p)[-1];
			if (c == 'x' || c == 'X') {
				--p;
				(void) sputbackc(c);
			}
			if ((flags & SUPPRESS) == 0) {
				u_long res;

				*p = 0;
				res = (*ccfn)(buf, (char **)NULL, base);
				if (flags & POINTER)
					*va_arg(ap, void **) = (void *)res;
				else if (flags & SHORT)
					*va_arg(ap, short *) = res;
				else if (flags & LONG)
					*va_arg(ap, long *) = res;
				else
					*va_arg(ap, int *) = res;
				nassigned++;
			}
			nread += p - buf;
			break;

#ifdef FLOATING_POINT
		case CT_FLOAT:
			/* scan a floating point number as if by strtod */
			if (width == 0 || width > sizeof(buf) - 1)
				width = sizeof(buf) - 1;
			flags |= SIGNOK | NDIGITS | DPTOK | EXPOK;
			for (p = buf; width; width--) {
				c = (unsigned char)*_gptr;
				/*
				 * This code mimicks the integer conversion
				 * code, but is much simpler.
				 */
				switch (c) {

				case '0': case '1': case '2': case '3':
				case '4': case '5': case '6': case '7':
				case '8': case '9':
					flags &= ~(SIGNOK | NDIGITS);
					goto fok;

				case '+': case '-':
					if (flags & SIGNOK) {
						flags &= ~SIGNOK;
						goto fok;
					}
					break;
				case '.':
					if (flags & DPTOK) {
						flags &= ~(SIGNOK | DPTOK);
						goto fok;
					}
					break;
				case 'e': case 'E':
					/* no exponent without some digits */
					if ((flags&(NDIGITS|EXPOK)) == EXPOK) {
						flags =
						    (flags & ~(EXPOK|DPTOK)) |
						    SIGNOK | NDIGITS;
						goto fok;
					}
					break;
				}
				break;
		fok:
				*p++ = c;
				_gptr++;
				if (sgetc() == EOF) {
				    seen_eof++;
				    break;	/* EOF */
				}
			}
			/*
			 * If no digits, might be missing exponent digits
			 * (just give back the exponent) or might be missing
			 * regular digits, but had sign and/or decimal point.
			 */
			if (flags & NDIGITS) {
				if (flags & EXPOK) {
					/* no digits at all */
					while (p > buf)
					    sputbackc(*(u_char *)--p);
					goto match_failure;
				}
				/* just a bad exponent (e and maybe sign) */
				c = *(u_char *)--p;
				if (c != 'e' && c != 'E') {
					(void)sputbackc(c);/* sign */
					c = *(u_char *)--p;
				}
				(void) sputbackc(c);
			}
			if ((flags & SUPPRESS) == 0) {
				double res;
				*p = 0;
#ifdef USE_DTOA
				res = strtod(buf, NULL);
#else
				res = atof(buf);
#endif
				if (flags & LONG)
					*va_arg(ap, double *) = res;
				else
					*va_arg(ap, float *) = res;
				nassigned++;
			}
			nread += p - buf;
			break;
#endif /* FLOATING_POINT */
		}
	}
eof_failure:
	seen_eof++;
input_failure:
	if (nassigned == 0)
	    nassigned = -1;
match_failure:
	if (stream)
	    stream->set(ios::failbit);
done:
	if (stream && seen_eof)
		stream->set(ios::eofbit);
	return (nassigned);
}
示例#8
0
/************************************************************************
 *                        os_tolower                        *
 ************************************************************************
DESCRIPTION: wrapper to the OS tolower fucntion

CONTEXT:  
************************************************************************/
S32 os_isupper(S32 c)
{
    return isupper(c);
}
示例#9
0
文件: strtoul.c 项目: iliak/68kOS
/*
* Convert a string to an unsigned long integer.
*
*/
unsigned long strtoul(const char *nptr, const char ** endptr, int base)
{
	const char *s = nptr;
	unsigned long acc;
	int c;
	unsigned long cutoff;
	int neg = 0, any, cutlim;

	/*
	 * See strtol for comments as to the logic used.
	 */
	do 
	{
		c = *s++;
	} while(isspace(c));
	
	if(c == '-')
	{
		neg = 1;
		c = *s++;
	} 
	else if(c == '+')
		c = *s++;
	if((base == 0 || base == 16) && c == '0' &&(*s == 'x' || *s == 'X')) 
	{
		c = s[1];
		s += 2;
		base = 16;
	} 
	else if((base == 0 || base == 2) && c == '0' &&(*s == 'b' || *s == 'B')) 
	{
		c = s[1];
		s += 2;
		base = 2;
	}

	if(base == 0)
		base = c == '0' ? 8 : 10;

	cutoff =(unsigned long)ULONG_MAX /(unsigned long)base;
	cutlim =(unsigned long)ULONG_MAX %(unsigned long)base;

	for(acc = 0, any = 0;; c = *s++) 
	{
		if(isdigit(c))
			c -= '0';
		else if(isalpha(c))
			c -= isupper(c) ? 'A' - 10 : 'a' - 10;
		else
			break;
		if(c >= base)
			break;
		if(any < 0 || acc > cutoff || acc == cutoff && c > cutlim)
			any = -1;
		else 
		{
			any = 1;
			acc *= base;
			acc += c;
		}
	}
	if(any < 0)
	{
		acc = ULONG_MAX;
//		errno = ERANGE;
	} 
	else if(neg)
		acc = -acc;

	if(endptr != 0)
		*endptr =(char *)(any ? s - 1 : nptr);

	return(acc);
}
示例#10
0
bool
HangulInstance::process_key_event (const KeyEvent& rawkey)
{
    SCIM_DEBUG_IMENGINE(1) << "process_key_event.\n";

    KeyEvent key = rawkey.map_to_layout(SCIM_KEYBOARD_Default);

    m_prev_key = key;

    if (use_ascii_mode() && !is_hangul_mode()) {
	if (is_hangul_key(key)) {
	    toggle_hangul_mode();
	    return true;
	}

	return false;
    }

    /* ignore key release. */
    if (key.is_key_release ())
        return false;

    /* mode change */
    if (use_ascii_mode() && is_hangul_key(key)) {
	toggle_hangul_mode();
	return true;
    }

    /* hanja mode */
    if (is_hanja_mode_key (key)) {
	toggle_hanja_mode();
    }

    /* toggle candidate table */
    if (is_hanja_key (key)) {
	if (is_hanja_mode()) {
	    update_candidates ();
	} else {
	    if (m_lookup_table.number_of_candidates ())
		delete_candidates ();
	    else
		update_candidates ();
	}

        return true;
    }

    /* ignore shift keys */
    if (key.code == SCIM_KEY_Shift_L || key.code == SCIM_KEY_Shift_R)
        return false;

    /* flush on modifier-on keys */
    if (key.is_control_down() || key.is_alt_down()) {
	flush ();
        return false;
    }

    /* candidate keys */
    if (m_lookup_table.number_of_candidates ()) {
        if (candidate_key_event(key))
	    return true;
    }

    /* change to ascii mode on ESCAPE key, for vi users.
     * We should process this key after processing candidate keys,
     * or input mode will be changed to non-hangul mode when the user presses
     * escape key to close candidate window. */
    if (use_ascii_mode() && !is_hanja_mode()) {
	if (key.code == SCIM_KEY_Escape) {
	    toggle_hangul_mode();
	}
    }

    /* backspace */
    if (is_backspace_key(key)) {
        bool ret = hangul_ic_backspace(m_hic);
        if (ret) {
	    hangul_update_preedit_string ();
	} else if (m_preedit.length() > 0) {
	    ret = true;
	    m_preedit.erase(m_preedit.length() - 1, 1);
	    hangul_update_preedit_string();
	} else {
	    if (m_surrounding_text.length() > 0) {
		m_surrounding_text.erase(m_surrounding_text.length() - 1, 1);
		if (m_surrounding_text.empty()) {
		    delete_candidates();
		    return ret;
		}
	    }
	}

	if (is_hanja_mode() && m_lookup_table.number_of_candidates()) {
	    update_candidates();
	}

        return ret;
    }

    if (key.code >= SCIM_KEY_exclam && key.code <= SCIM_KEY_asciitilde) {
	/* main hangul composing process */
	int ascii = key.get_ascii_code();
	if (key.is_caps_lock_down()) {
	    if (isupper(ascii))
		ascii = tolower(ascii);
	    else if (islower(ascii))
		ascii = toupper(ascii);
	}

	bool ret = hangul_ic_process(m_hic, ascii);

	WideString wstr;
	wstr = get_commit_string ();
	if (wstr.length ()) {
	    /* Before commit, we set preedit string to null to work arround
	     * some buggy IM implementation, ex) Qt, Evolution */
	    hide_preedit_string ();
	    if (is_hanja_mode() || m_factory->m_commit_by_word) {
		m_preedit += wstr;
	    } else {
		commit_string(wstr);
	    }
	}

	if (is_hanja_mode() || m_factory->m_commit_by_word) {
	    if (hangul_ic_is_empty(m_hic)) {
		flush();
	    }
	}

	hangul_update_preedit_string ();

	if (is_hanja_mode()) {
	    update_candidates();
	}

	return ret;
    }

    flush();
    return false;
}
示例#11
0
void database::init_genesis(const genesis_allocation& initial_allocation)
{ try {
   _undo_db.disable();

   fc::ecc::private_key genesis_private_key = fc::ecc::private_key::regenerate(fc::sha256::hash(string("genesis")));
   const key_object& genesis_key =
      create<key_object>( [&genesis_private_key](key_object& k) {
         k.key_data = public_key_type(genesis_private_key.get_public_key());
      });
   const account_statistics_object& genesis_statistics =
      create<account_statistics_object>( [&](account_statistics_object& b){
      });
   create<account_balance_object>( [](account_balance_object& b) {
      b.balance = GRAPHENE_INITIAL_SUPPLY;
   });
   const account_object& genesis_account =
      create<account_object>( [&](account_object& n) {
         n.name = "genesis";
         n.owner.add_authority(genesis_key.get_id(), 1);
         n.owner.weight_threshold = 1;
         n.active = n.owner;
         n.memo_key = genesis_key.id;
         n.statistics = genesis_statistics.id;
      });

   vector<delegate_id_type> init_delegates;
   vector<witness_id_type> init_witnesses;
   flat_set<witness_id_type> init_witness_set;

   auto delegates_and_witnesses = std::max(GRAPHENE_MIN_WITNESS_COUNT, GRAPHENE_MIN_DELEGATE_COUNT);
   for( int i = 0; i < delegates_and_witnesses; ++i )
   {
      const account_statistics_object& stats_obj =
         create<account_statistics_object>( [&](account_statistics_object&){
         });
      const account_object& delegate_account =
         create<account_object>( [&](account_object& a) {
            a.active = a.owner = genesis_account.owner;
            a.name = string("init") + fc::to_string(i);
            a.statistics = stats_obj.id;
         });
      const delegate_object& init_delegate = create<delegate_object>( [&](delegate_object& d) {
         d.delegate_account = delegate_account.id;
         d.vote_id = i * 2;
      });
      init_delegates.push_back(init_delegate.id);

      const witness_object& init_witness = create<witness_object>( [&](witness_object& d) {
            d.witness_account = delegate_account.id;
            d.vote_id = i * 2 + 1;
            secret_hash_type::encoder enc;
            fc::raw::pack( enc, genesis_private_key );
            fc::raw::pack( enc, d.last_secret );
            d.next_secret = secret_hash_type::hash(enc.result());
      });
      init_witnesses.push_back(init_witness.id);
      init_witness_set.insert(init_witness.id);

   }
   create<block_summary_object>( [&](block_summary_object& p) {
   });

   const witness_schedule_object& wso =
   create<witness_schedule_object>( [&]( witness_schedule_object& _wso )
   {
      memset( _wso.rng_seed.begin(), 0, _wso.rng_seed.size() );

      witness_scheduler_rng rng( _wso.rng_seed.begin(), GRAPHENE_NEAR_SCHEDULE_CTR_IV );

      _wso.scheduler = witness_scheduler();
      _wso.scheduler._min_token_count = init_witnesses.size() / 2;
      _wso.scheduler.update( init_witness_set );

      for( int i=0; i<init_witnesses.size(); i++ )
         _wso.scheduler.produce_schedule( rng );

      _wso.last_scheduling_block = 0;
   } ) ;
   assert( wso.id == witness_schedule_id_type() );

   const global_property_object& properties =
      create<global_property_object>( [&](global_property_object& p) {
         p.active_delegates = init_delegates;
         for( const witness_id_type& wit : init_witnesses )
            p.active_witnesses.insert( wit );
         p.next_available_vote_id = delegates_and_witnesses * 2;
         p.chain_id = fc::digest(initial_allocation);
      });
   (void)properties;

   create<dynamic_global_property_object>( [&](dynamic_global_property_object& p) {
      p.time = fc::time_point_sec( GRAPHENE_GENESIS_TIMESTAMP );
      });

   const asset_dynamic_data_object& dyn_asset =
      create<asset_dynamic_data_object>( [&]( asset_dynamic_data_object& a ) {
         a.current_supply = GRAPHENE_INITIAL_SUPPLY;
      });

   const asset_object& core_asset =
     create<asset_object>( [&]( asset_object& a ) {
         a.symbol = GRAPHENE_SYMBOL;
         a.options.max_supply = GRAPHENE_INITIAL_SUPPLY;
         a.precision = GRAPHENE_BLOCKCHAIN_PRECISION_DIGITS;
         a.options.flags = 0;
         a.options.issuer_permissions = 0;
         a.issuer = genesis_account.id;
         a.options.core_exchange_rate.base.amount = 1;
         a.options.core_exchange_rate.base.asset_id = 0;
         a.options.core_exchange_rate.quote.amount = 1;
         a.options.core_exchange_rate.quote.asset_id = 0;
         a.dynamic_asset_data_id = dyn_asset.id;
      });
   assert( asset_id_type(core_asset.id) == asset().asset_id );
   assert( get_balance(account_id_type(), asset_id_type()) == asset(dyn_asset.current_supply) );
   (void)core_asset;

   if( !initial_allocation.empty() )
   {
      share_type total_allocation = 0;
      for( const auto& handout : initial_allocation )
         total_allocation += handout.second;

      auto mangle_to_name = [](const fc::static_variant<public_key_type, address>& key) {
         string addr = string(key.which() == std::decay<decltype(key)>::type::tag<address>::value? key.get<address>()
                                                                                                 : key.get<public_key_type>());
         string result = "bts";
         string key_string = string(addr).substr(sizeof(GRAPHENE_ADDRESS_PREFIX)-1);
         for( char c : key_string )
         {
            if( isupper(c) )
               result += string("-") + char(tolower(c));
            else
               result += c;
         }
         return result;
      };

      fc::time_point start_time = fc::time_point::now();

      for( const auto& handout : initial_allocation )
      {
         asset amount(handout.second);
         amount.amount = ((fc::uint128(amount.amount.value) * GRAPHENE_INITIAL_SUPPLY)/total_allocation.value).to_uint64();
         if( amount.amount == 0 )
         {
            wlog("Skipping zero allocation to ${k}", ("k", handout.first));
            continue;
         }

         signed_transaction trx;
         trx.operations.emplace_back(key_create_operation({asset(), genesis_account.id, handout.first}));
         relative_key_id_type key_id(0);
         authority account_authority(1, key_id, 1);
         account_create_operation cop;
         cop.name = mangle_to_name(handout.first);
         cop.registrar = account_id_type(1);
         cop.active = account_authority;
         cop.owner = account_authority;
         cop.memo_key = key_id;
         trx.operations.push_back(cop);
         trx.validate();
         auto ptrx = apply_transaction(trx, ~0);
         trx = signed_transaction();
         account_id_type account_id(ptrx.operation_results.back().get<object_id_type>());
         trx.operations.emplace_back(transfer_operation({  asset(),
                                                           genesis_account.id,
                                                           account_id,
                                                           amount,
                                                           memo_data()//vector<char>()
                                                        }));
         trx.validate();
         apply_transaction(trx, ~0);
      }

      asset leftovers = get_balance(account_id_type(), asset_id_type());
      if( leftovers.amount > 0 )
      {
         modify(*get_index_type<account_balance_index>().indices().get<by_balance>().find(boost::make_tuple(account_id_type(), asset_id_type())),
                [](account_balance_object& b) {
            b.adjust_balance(-b.get_balance());
         });
         modify(core_asset.dynamic_asset_data_id(*this), [&leftovers](asset_dynamic_data_object& d) {
            d.accumulated_fees += leftovers.amount;
         });
      }

      fc::microseconds duration = fc::time_point::now() - start_time;
      ilog("Finished allocating to ${n} accounts in ${t} milliseconds.",
           ("n", initial_allocation.size())("t", duration.count() / 1000));
   }

   _undo_db.enable();
} FC_LOG_AND_RETHROW() }
示例#12
0
const unsigned char *
pcre32_maketables(void)
#endif
{
unsigned char *yield, *p;
int i;

#ifndef DFTABLES
yield = (unsigned char*)(PUBL(malloc))(tables_length);
#else
yield = (unsigned char*)malloc(tables_length);
#endif

if (yield == NULL) return NULL;
p = yield;

/* First comes the lower casing table */

for (i = 0; i < 256; i++) *p++ = tolower(i);

/* Next the case-flipping table */

for (i = 0; i < 256; i++) *p++ = islower(i)? toupper(i) : tolower(i);

/* Then the character class tables. Don't try to be clever and save effort on
exclusive ones - in some locales things may be different.

Note that the table for "space" includes everything "isspace" gives, including
VT in the default locale. This makes it work for the POSIX class [:space:].
From release 8.34 is is also correct for Perl space, because Perl added VT at
release 5.18.

Note also that it is possible for a character to be alnum or alpha without
being lower or upper, such as "male and female ordinals" (\xAA and \xBA) in the
fr_FR locale (at least under Debian Linux's locales as of 12/2005). So we must
test for alnum specially. */

memset(p, 0, cbit_length);
for (i = 0; i < 256; i++)
  {
  if (isdigit(i)) p[cbit_digit  + i/8] |= 1 << (i&7);
  if (isupper(i)) p[cbit_upper  + i/8] |= 1 << (i&7);
  if (islower(i)) p[cbit_lower  + i/8] |= 1 << (i&7);
  if (isalnum(i)) p[cbit_word   + i/8] |= 1 << (i&7);
  if (i == '_')   p[cbit_word   + i/8] |= 1 << (i&7);
  if (isspace(i)) p[cbit_space  + i/8] |= 1 << (i&7);
  if (isxdigit(i))p[cbit_xdigit + i/8] |= 1 << (i&7);
  if (isgraph(i)) p[cbit_graph  + i/8] |= 1 << (i&7);
  if (isprint(i)) p[cbit_print  + i/8] |= 1 << (i&7);
  if (ispunct(i)) p[cbit_punct  + i/8] |= 1 << (i&7);
  if (iscntrl(i)) p[cbit_cntrl  + i/8] |= 1 << (i&7);
  }
p += cbit_length;

/* Finally, the character type table. In this, we used to exclude VT from the
white space chars, because Perl didn't recognize it as such for \s and for
comments within regexes. However, Perl changed at release 5.18, so PCRE changed
at release 8.34. */

for (i = 0; i < 256; i++)
  {
  int x = 0;
  if (isspace(i)) x += ctype_space;
  if (isalpha(i)) x += ctype_letter;
  if (isdigit(i)) x += ctype_digit;
  if (isxdigit(i)) x += ctype_xdigit;
  if (isalnum(i) || i == '_') x += ctype_word;

  /* Note: strchr includes the terminating zero in the characters it considers.
  In this instance, that is ok because we want binary zero to be flagged as a
  meta-character, which in this sense is any character that terminates a run
  of data characters. */

  if (strchr("\\*+?{^.$|()[", i) != 0) x += ctype_meta;
  *p++ = x;
  }

return yield;
}
示例#13
0
/*
 * processSQLNamePattern
 *
 * Scan a wildcard-pattern string and generate appropriate WHERE clauses
 * to limit the set of objects returned.  The WHERE clauses are appended
 * to the already-partially-constructed query in buf.  Returns whether
 * any clause was added.
 *
 * conn: connection query will be sent to (consulted for escaping rules).
 * buf: output parameter.
 * pattern: user-specified pattern option, or NULL if none ("*" is implied).
 * have_where: true if caller already emitted "WHERE" (clauses will be ANDed
 * onto the existing WHERE clause).
 * force_escape: always quote regexp special characters, even outside
 * double quotes (else they are quoted only between double quotes).
 * schemavar: name of query variable to match against a schema-name pattern.
 * Can be NULL if no schema.
 * namevar: name of query variable to match against an object-name pattern.
 * altnamevar: NULL, or name of an alternative variable to match against name.
 * visibilityrule: clause to use if we want to restrict to visible objects
 * (for example, "pg_catalog.pg_table_is_visible(p.oid)").  Can be NULL.
 *
 * Formatting note: the text already present in buf should end with a newline.
 * The appended text, if any, will end with one too.
 */
bool
processSQLNamePattern(PGconn *conn, PQExpBuffer buf, const char *pattern,
					  bool have_where, bool force_escape,
					  const char *schemavar, const char *namevar,
					  const char *altnamevar, const char *visibilityrule)
{
	PQExpBufferData schemabuf;
	PQExpBufferData namebuf;
	int			encoding = PQclientEncoding(conn);
	bool		inquotes;
	const char *cp;
	int			i;
	bool		added_clause = false;

#define WHEREAND() \
	(appendPQExpBufferStr(buf, have_where ? "  AND " : "WHERE "), \
	 have_where = true, added_clause = true)

	if (pattern == NULL)
	{
		/* Default: select all visible objects */
		if (visibilityrule)
		{
			WHEREAND();
			appendPQExpBuffer(buf, "%s\n", visibilityrule);
		}
		return added_clause;
	}

	initPQExpBuffer(&schemabuf);
	initPQExpBuffer(&namebuf);

	/*
	 * Parse the pattern, converting quotes and lower-casing unquoted letters.
	 * Also, adjust shell-style wildcard characters into regexp notation.
	 *
	 * We surround the pattern with "^(...)$" to force it to match the whole
	 * string, as per SQL practice.  We have to have parens in case the string
	 * contains "|", else the "^" and "$" will be bound into the first and
	 * last alternatives which is not what we want.
	 *
	 * Note: the result of this pass is the actual regexp pattern(s) we want
	 * to execute.  Quoting/escaping into SQL literal format will be done
	 * below using appendStringLiteralConn().
	 */
	appendPQExpBufferStr(&namebuf, "^(");

	inquotes = false;
	cp = pattern;

	while (*cp)
	{
		char		ch = *cp;

		if (ch == '"')
		{
			if (inquotes && cp[1] == '"')
			{
				/* emit one quote, stay in inquotes mode */
				appendPQExpBufferChar(&namebuf, '"');
				cp++;
			}
			else
				inquotes = !inquotes;
			cp++;
		}
		else if (!inquotes && isupper((unsigned char) ch))
		{
			appendPQExpBufferChar(&namebuf,
								  pg_tolower((unsigned char) ch));
			cp++;
		}
		else if (!inquotes && ch == '*')
		{
			appendPQExpBufferStr(&namebuf, ".*");
			cp++;
		}
		else if (!inquotes && ch == '?')
		{
			appendPQExpBufferChar(&namebuf, '.');
			cp++;
		}
		else if (!inquotes && ch == '.')
		{
			/* Found schema/name separator, move current pattern to schema */
			resetPQExpBuffer(&schemabuf);
			appendPQExpBufferStr(&schemabuf, namebuf.data);
			resetPQExpBuffer(&namebuf);
			appendPQExpBufferStr(&namebuf, "^(");
			cp++;
		}
		else if (ch == '$')
		{
			/*
			 * Dollar is always quoted, whether inside quotes or not. The
			 * reason is that it's allowed in SQL identifiers, so there's a
			 * significant use-case for treating it literally, while because
			 * we anchor the pattern automatically there is no use-case for
			 * having it possess its regexp meaning.
			 */
			appendPQExpBufferStr(&namebuf, "\\$");
			cp++;
		}
		else
		{
			/*
			 * Ordinary data character, transfer to pattern
			 *
			 * Inside double quotes, or at all times if force_escape is true,
			 * quote regexp special characters with a backslash to avoid
			 * regexp errors.  Outside quotes, however, let them pass through
			 * as-is; this lets knowledgeable users build regexp expressions
			 * that are more powerful than shell-style patterns.
			 */
			if ((inquotes || force_escape) &&
				strchr("|*+?()[]{}.^$\\", ch))
				appendPQExpBufferChar(&namebuf, '\\');
			i = PQmblen(cp, encoding);
			while (i-- && *cp)
			{
				appendPQExpBufferChar(&namebuf, *cp);
				cp++;
			}
		}
	}

	/*
	 * Now decide what we need to emit.  Note there will be a leading "^(" in
	 * the patterns in any case.
	 */
	if (namebuf.len > 2)
	{
		/* We have a name pattern, so constrain the namevar(s) */

		appendPQExpBufferStr(&namebuf, ")$");
		/* Optimize away a "*" pattern */
		if (strcmp(namebuf.data, "^(.*)$") != 0)
		{
			WHEREAND();
			if (altnamevar)
			{
				appendPQExpBuffer(buf, "(%s ~ ", namevar);
				appendStringLiteralConn(buf, namebuf.data, conn);
				appendPQExpBuffer(buf, "\n        OR %s ~ ", altnamevar);
				appendStringLiteralConn(buf, namebuf.data, conn);
				appendPQExpBufferStr(buf, ")\n");
			}
			else
			{
				appendPQExpBuffer(buf, "%s ~ ", namevar);
				appendStringLiteralConn(buf, namebuf.data, conn);
				appendPQExpBufferChar(buf, '\n');
			}
		}
	}

	if (schemabuf.len > 2)
	{
		/* We have a schema pattern, so constrain the schemavar */

		appendPQExpBufferStr(&schemabuf, ")$");
		/* Optimize away a "*" pattern */
		if (strcmp(schemabuf.data, "^(.*)$") != 0 && schemavar)
		{
			WHEREAND();
			appendPQExpBuffer(buf, "%s ~ ", schemavar);
			appendStringLiteralConn(buf, schemabuf.data, conn);
			appendPQExpBufferChar(buf, '\n');
		}
	}
	else
	{
		/* No schema pattern given, so select only visible objects */
		if (visibilityrule)
		{
			WHEREAND();
			appendPQExpBuffer(buf, "%s\n", visibilityrule);
		}
	}

	termPQExpBuffer(&schemabuf);
	termPQExpBuffer(&namebuf);

	return added_clause;
#undef WHEREAND
}
示例#14
0
文件: ctype.c 项目: DeforaOS/libc
/* isalpha */
int isalpha(int c)
{
	return islower(c) || isupper(c);
}
示例#15
0
文件: spread.c 项目: AkaBlood/ogs5
/* ---------------------------------------------------------------------- */
int
spread_row_to_solution (struct spread_row *heading, struct spread_row *units,
			struct spread_row *data, struct defaults defaults)
/* ---------------------------------------------------------------------- */
{
  int i, j, n, l, next_keyword_save;
  int n_user, n_user_end;
  int default_pe, alk;
  int count_isotopes;
  int max_mass_balance, count_mass_balance;
  char *ptr, *ptr1;
  char *description;
  char token[MAX_LENGTH], token1[MAX_LENGTH];
  char string[2 * MAX_LENGTH];
  LDBLE dummy;

  int return_value, opt;
  char *next_char;
  const char *opt_list[] = {
    "temp",			/* 0 */
    "temperature",		/* 1 */
    "dens",			/* 2 */
    "density",			/* 3 */
    "units",			/* 4 */
    "redox",			/* 5 */
    "ph",			/* 6 */
    "pe",			/* 7 */
    "unit",			/* 8 */
    "isotope",			/* 9 */
    "water",			/* 10 */
    "description",		/* 11 */
    "desc",			/* 12 */
    "descriptor"		/* 13 */
  };
  int count_opt_list = 14;

/*
 *      look for solution number
 */
  n_user = -1;
  n_user_end = -1;
  description = string_duplicate ("");
  for (i = 0; i < heading->count; i++)
  {
    if (strcmp_nocase (heading->char_vector[i], "number") == 0)
    {
      break;
    }
  }
  if (i == heading->count || data->type_vector[i] == EMPTY
      || data->count <= i)
  {
    n_user = -1;
#ifdef SKIP
    for (i = 0; i < count_solution; i++)
    {
      if (n_user <= solution[i]->n_user)
      {
	n_user = solution[i]->n_user + 1;
      }
    }
#endif
  }
  else if (data->type_vector[i] == STRING)
  {
    input_error++;
    sprintf (error_string,
	     "Expected solution number or number range in 'number' column, found:  %s.",
	     data->char_vector[i]);
    error_msg (error_string, CONTINUE);
  }
  else
  {
    strcpy (string, "solution_s ");
    strcat (string, data->char_vector[i]);
    ptr = string;
    description = (char *) free_check_null (description);
    next_keyword_save = next_keyword;
    next_keyword = 42;
    read_number_description (ptr, &n_user, &n_user_end, &description);
    next_keyword = next_keyword_save;
  }
/*
 *   set up solution
 */

  if (n_user >= 0 && solution_bsearch (n_user, &n, FALSE) != NULL)
  {
    solution_free (solution[n]);
  }
  else
  {
    n = count_solution++;
    if (count_solution >= max_solution)
    {
      space ((void **) ((void *) &(solution)), count_solution, &max_solution,
	     sizeof (struct solution *));
    }
  }
  solution[n] = solution_alloc ();

  solution[n]->n_user = n_user;
  solution[n]->n_user_end = n_user_end;
  if (use.solution_in == FALSE)
  {
    use.solution_in = TRUE;
    use.n_solution_user = n_user;
  }
  max_mass_balance = MAX_MASS_BALANCE;
/*
 *   Set default ph, temp, density, pe, units
 */
  solution[n]->description = description;
  solution[n]->tc = defaults.temp;
  solution[n]->ph = defaults.ph;
  solution[n]->density = defaults.density;
  solution[n]->solution_pe = defaults.pe;
  solution[n]->mass_water = defaults.water;
  solution[n]->ah2o = 1.0;
  solution[n]->mu = 1e-7;
  solution[n]->cb = 0.0;
  default_pe = 0;
  solution[n]->units = defaults.units;
  solution[n]->totals[0].description = NULL;
  count_mass_balance = 0;
  count_isotopes = 0;
  default_pe = pe_data_store (&(solution[n]->pe), defaults.redox);
/*
 *   Read concentration data
 */
  return_value = UNKNOWN;
  for (i = 0; i < heading->count; i++)
  {
    if (strcmp_nocase (heading->char_vector[i], "number") == 0)
      continue;
    if (strcmp_nocase (heading->char_vector[i], "uncertainty") == 0)
      continue;
    if (strcmp_nocase (heading->char_vector[i], "uncertainties") == 0)
      continue;
    if (strcmp_nocase (heading->char_vector[i], "isotope_uncertainty") == 0)
      continue;
    /*
     *  Copy in element name
     */
    if (heading->type_vector[i] == EMPTY)
      continue;
    strcpy (string, heading->char_vector[i]);
    strcat (string, " ");
    /*
     *  Copy in concentration data
     */
    if (i >= data->count || data->type_vector[i] == EMPTY)
      continue;
    strcat (string, data->char_vector[i]);
    strcat (string, " ");
    /*
     *  Copy in concentration data
     */
    if (units != NULL && i < units->count && units->type_vector[i] != EMPTY)
    {
      strcat (string, units->char_vector[i]);
    }
/*
 *   Parse string just like read_solution input 
 */
    next_char = string;
    opt = get_option_string (opt_list, count_opt_list, &next_char);
    if (opt == OPTION_DEFAULT && heading->type_vector[i] == NUMBER)
    {
      opt = 9;
    }
    switch (opt)
    {
    case OPTION_EOF:		/* end of file */
      return_value = EOF;
      break;
    case OPTION_KEYWORD:	/* keyword */
      return_value = KEYWORD;
      break;
    case OPTION_ERROR:
      input_error++;
      error_msg ("Unknown input in SOLUTION keyword.", CONTINUE);
      error_msg (line_save, CONTINUE);
      break;
    case 0:			/* temperature */
    case 1:
      sscanf (next_char, SCANFORMAT, &(solution[n]->tc));
      break;
    case 2:			/* density */
    case 3:
      sscanf (next_char, SCANFORMAT, &(solution[n]->density));
      break;
    case 4:			/* units */
    case 8:			/* unit */
      if (copy_token (token, &next_char, &l) == EMPTY)
	break;
      if (check_units (token, FALSE, FALSE, solution[n]->units, TRUE) == OK)
      {
	solution[n]->units = string_hsave (token);
      }
      else
      {
	input_error++;
      }
      break;
    case 5:			/* redox */
      if (copy_token (token, &next_char, &l) == EMPTY)
	break;
      if (parse_couple (token) == OK)
      {
	default_pe = pe_data_store (&(solution[n]->pe), token);
      }
      else
      {
	input_error++;
      }
      break;
    case 6:			/* ph */
      next_char = string;
      if (read_conc (n, count_mass_balance, next_char) == ERROR)
      {
	input_error++;
	break;
      }
      solution[n]->ph = solution[n]->totals[count_mass_balance].input_conc;
      if (solution[n]->totals[count_mass_balance].equation_name == NULL)
      {
	break;
      }
      solution[n]->totals[count_mass_balance].description =
	string_hsave ("H(1)");
      count_mass_balance++;
      break;
    case 7:			/* pe */
      next_char = string;
      if (read_conc (n, count_mass_balance, next_char) == ERROR)
      {
	input_error++;
	break;
      }
      solution[n]->solution_pe =
	solution[n]->totals[count_mass_balance].input_conc;
      if (solution[n]->totals[count_mass_balance].equation_name == NULL)
      {
	break;
      }
      solution[n]->totals[count_mass_balance].description =
	string_hsave ("E");
      count_mass_balance++;
      break;
    case 9:			/* isotope */
      next_char = string;
      if (copy_token (token, &next_char, &l) != DIGIT)
      {
	input_error++;
	sprintf (error_string, "Expected isotope name to"
		 " begin with an isotopic number.");
	error_msg (error_string, CONTINUE);
	continue;
      }
      solution[n]->isotopes =
	(struct isotope *) PHRQ_realloc (solution[n]->isotopes,
					 (size_t) (count_isotopes +
						   1) *
					 sizeof (struct isotope));
      if (solution[n]->isotopes == NULL)
	malloc_error ();
      /* read and save element name */
      ptr1 = token;
      get_num (&ptr1,
	       &(solution[n]->isotopes[count_isotopes].isotope_number));
      if (ptr1[0] == '\0' || isupper ((int) ptr1[0]) == FALSE)
      {
	error_msg ("Expecting element name.", CONTINUE);
	error_msg (line_save, CONTINUE);
	input_error++;
	return (ERROR);
      }
      solution[n]->isotopes[count_isotopes].elt_name = string_hsave (ptr1);

      /* read and store isotope ratio */
      if (copy_token (token, &next_char, &l) != DIGIT)
      {
	input_error++;
	sprintf (error_string, "Expected numeric value for isotope ratio.");
	error_msg (error_string, CONTINUE);
	continue;
      }
      sscanf (token, SCANFORMAT,
	      &(solution[n]->isotopes[count_isotopes].ratio));

      /* read and store isotope ratio uncertainty */
      /* first choice is next column */
      if ((i + 1) < heading->count &&
	  (strcmp_nocase (heading->char_vector[i + 1], "uncertainty") == 0 ||
	   strcmp_nocase (heading->char_vector[i + 1],
			  "isotope_uncertainty") == 0
	   || strcmp_nocase (heading->char_vector[i + 1],
			     "uncertainties") == 0) && (i + 1) < data->count
	  && data->type_vector[i + 1] == NUMBER)
      {
	solution[n]->isotopes[count_isotopes].ratio_uncertainty =
	  data->d_vector[i + 1];
      }
      else
      {
	next_char = string;
	copy_token (token, &next_char, &l);
	for (j = 0; j < defaults.count_iso; j++)
	{
	  if (strcmp (token, defaults.iso[j].name) == 0)
	  {
	    solution[n]->isotopes[count_isotopes].ratio_uncertainty =
	      defaults.iso[j].uncertainty;
	    break;
	  }
	}
	if (j == defaults.count_iso)
	{
	  solution[n]->isotopes[count_isotopes].ratio_uncertainty = NAN;
	}
      }
      count_isotopes++;
      break;
    case 10:			/* water */
      j = copy_token (token, &next_char, &l);
      if (j == EMPTY)
      {
	solution[n]->mass_water = 1.0;
      }
      else if (j != DIGIT)
      {
	input_error++;
	sprintf (error_string,
		 "Expected numeric value for mass of water in solution.");
	error_msg (error_string, CONTINUE);
      }
      else
      {
	sscanf (token, SCANFORMAT, &dummy);
	solution[n]->mass_water = (LDBLE) dummy;
      }
      break;
    case 11:			/* description */
    case 12:			/* desc */
    case 13:			/* descriptor */
      solution[n]->description =
	(char *) free_check_null (solution[n]->description);
      solution[n]->description = string_duplicate (next_char);
      break;
    case OPTION_DEFAULT:
/*
 *   Read concentration
 */
      next_char = string;
      if (copy_token (token, &next_char, &l) == LOWER)
	continue;
      next_char = string;
      if (read_conc (n, count_mass_balance, next_char) == ERROR)
      {
#ifdef SKIP
	input_error++;
	break;
#endif
      }
      count_mass_balance++;
      break;
    }
    if (count_mass_balance + 1 >= max_mass_balance)
    {
      space ((void **) ((void *) &(solution[n]->totals)), count_mass_balance + 1,
	     &max_mass_balance, sizeof (struct conc));
    }
    if (return_value == EOF || return_value == KEYWORD)
      break;
  }
/*
 *   Sort totals by description
 */
  qsort (solution[n]->totals,
	 (size_t) count_mass_balance,
	 (size_t) sizeof (struct conc), conc_compare);
/*
 *   fix up default units and default pe
 */
  for (i = 0; i < count_mass_balance; i++)
  {
    strcpy (token, solution[n]->totals[i].description);
    str_tolower (token);
    if (solution[n]->totals[i].units == NULL)
    {
      solution[n]->totals[i].units = solution[n]->units;
    }
    else
    {
      alk = FALSE;
      if (strstr (token, "alk") == token)
	alk = TRUE;
      strcpy (token1, solution[n]->totals[i].units);
      if (check_units (token1, alk, TRUE, solution[n]->units, TRUE) == ERROR)
      {
	input_error++;
      }
      else
      {
	solution[n]->totals[i].units = string_hsave (token1);
      }
    }
    if (solution[n]->totals[i].n_pe < 0)
    {
      solution[n]->totals[i].n_pe = default_pe;
    }
  }
  solution[n]->default_pe = default_pe;
/*
 *   Mark end of solution
 */
  solution[n]->totals[count_mass_balance].description = NULL;
  solution[n]->count_isotopes = count_isotopes;
  if (count_isotopes > 0)
  {
    qsort (solution[n]->isotopes,
	   (size_t) count_isotopes,
	   (size_t) sizeof (struct isotope), isotope_compare);
  }
  else
  {
    solution[n]->isotopes =
      (struct isotope *) free_check_null (solution[n]->isotopes);
  }
  return (return_value);
}
示例#16
0
void FR_DrawText3(const char* text, const Point2Raw* _origin, int alignFlags, short _textFlags)
{
    fontid_t origFont = FR_Font();
    float cx, cy, extraScale;
    drawtextstate_t state;
    const char* fragment;
    int pass, curCase;
    Point2Raw origin;
    Size2Raw textSize;
    size_t charCount;
    float origColor[4];
    char* str, *end;
    boolean escaped = false;

    errorIfNotInited("FR_DrawText");

    if(!text || !text[0]) return;

    origin.x = _origin? _origin->x : 0;
    origin.y = _origin? _origin->y : 0;

    _textFlags &= ~(DTF_INTERNAL_MASK);

    // If we aren't aligning to top-left we need to know the dimensions.
    if(alignFlags & ALIGN_RIGHT)
        FR_TextSize(&textSize, text);

    DENG_ASSERT_IN_MAIN_THREAD();
    DENG_ASSERT_GL_CONTEXT_ACTIVE();

    // We need to change the current color, so remember for restore.
    glGetFloatv(GL_CURRENT_COLOR, origColor);

    for(pass = ((_textFlags & DTF_NO_SHADOW)  != 0? 1 : 0);
        pass < ((_textFlags & DTF_NO_GLITTER) != 0? 2 : 3); ++pass)
    {
        short textFlags = 0;

        // Configure the next pass.
        cx = (float) origin.x;
        cy = (float) origin.y;
        curCase = -1;
        charCount = 0;
        switch(pass)
        {
        case 0: textFlags = _textFlags | (DTF_NO_GLITTER|DTF_NO_CHARACTER); break;
        case 1: textFlags = _textFlags | (DTF_NO_SHADOW |DTF_NO_GLITTER);   break;
        case 2: textFlags = _textFlags | (DTF_NO_SHADOW |DTF_NO_CHARACTER); break;
        }

        // Apply defaults.
        initDrawTextState(&state, textFlags);

        str = (char*)text;
        while(*str)
        {
            if(*str == FR_FORMAT_ESCAPE_CHAR)
            {
                escaped = true;
                ++str;
                continue;
            }
            if(!escaped && *str == '{') // Paramaters included?
            {
                fontid_t lastFont = state.fontNum;
                int lastTracking = state.tracking;
                float lastLeading = state.leading;
                float lastShadowStrength = state.shadowStrength;
                float lastGlitterStrength = state.glitterStrength;
                boolean lastCaseScale = state.caseScale;
                float lastRGBA[4];
                int numBreaks = 0;

                lastRGBA[CR] = state.rgba[CR];
                lastRGBA[CG] = state.rgba[CG];
                lastRGBA[CB] = state.rgba[CB];
                lastRGBA[CA] = state.rgba[CA];

                parseParamaterBlock(&str, &state, &numBreaks);

                if(numBreaks != 0)
                {
                    do
                    {
                        cx = (float) origin.x;
                        cy += state.lastLineHeight * (1+lastLeading);
                    } while(--numBreaks > 0);
                }

                if(state.fontNum != lastFont)
                    FR_SetFont(state.fontNum);
                if(state.tracking != lastTracking)
                    FR_SetTracking(state.tracking);
                if(state.leading != lastLeading)
                    FR_SetLeading(state.leading);
                if(state.rgba[CR] != lastRGBA[CR] || state.rgba[CG] != lastRGBA[CG] || state.rgba[CB] != lastRGBA[CB] || state.rgba[CA] != lastRGBA[CA])
                    FR_SetColorAndAlphav(state.rgba);
                if(state.shadowStrength != lastShadowStrength)
                    FR_SetShadowStrength(state.shadowStrength);
                if(state.glitterStrength != lastGlitterStrength)
                    FR_SetGlitterStrength(state.glitterStrength);
                if(state.caseScale != lastCaseScale)
                    FR_SetCaseScale(state.caseScale);
            }

            for(end = str; *end && *end != FR_FORMAT_ESCAPE_CHAR && (escaped || *end != '{');)
            {
                int newlines = 0, fragmentAlignFlags;
                float alignx = 0;

                // Find the end of the next fragment.
                if(FR_CaseScale())
                {
                    curCase = -1;
                    // Select a substring with characters of the same case (or whitespace).
                    for(; *end && *end != FR_FORMAT_ESCAPE_CHAR && (escaped || *end != '{') &&
                        *end != '\n'; end++)
                    {
                        escaped = false;

                        // We can skip whitespace.
                        if(isspace(*end))
                            continue;

                        if(curCase < 0)
                            curCase = (isupper(*end) != 0);
                        else if(curCase != (isupper(*end) != 0))
                            break;
                    }
                }
                else
                {
                    curCase = 0;
                    for(; *end && *end != FR_FORMAT_ESCAPE_CHAR && (escaped || *end != '{') &&
                        *end != '\n'; end++) { escaped = false; }
                }

                // No longer escaped.
                escaped = false;

                { char* buffer = enlargeTextBuffer(end - str);
                memcpy(buffer, str, end - str);
                buffer[end - str] = '\0';
                fragment = buffer;
                }

                while(*end == '\n')
                {
                    newlines++;
                    end++;
                }

                // Continue from here.
                str = end;

                if(!(alignFlags & (ALIGN_LEFT|ALIGN_RIGHT)))
                {
                    fragmentAlignFlags = alignFlags;
                }
                else
                {
                    // We'll take care of horizontal positioning of the fragment so align left.
                    fragmentAlignFlags = (alignFlags & ~(ALIGN_RIGHT)) | ALIGN_LEFT;
                    if(alignFlags & ALIGN_RIGHT)
                        alignx = -textSize.width * state.scaleX;
                }

                // Setup the scaling.
                glMatrixMode(GL_MODELVIEW);
                glPushMatrix();

                // Rotate.
                if(state.angle != 0)
                {
                    // The origin is the specified (x,y) for the patch.
                    // We'll undo the aspect ratio (otherwise the result would be skewed).
                    /// @todo Do not assume the aspect ratio and therefore whether
                    // correction is even needed.
                    glTranslatef((float)origin.x, (float)origin.y, 0);
                    glScalef(1, 200.0f / 240.0f, 1);
                    glRotatef(state.angle, 0, 0, 1);
                    glScalef(1, 240.0f / 200.0f, 1);
                    glTranslatef(-(float)origin.x, -(float)origin.y, 0);
                }

                glTranslatef(cx + state.offX + alignx, cy + state.offY + (FR_CaseScale() ? state.caseMod[curCase].offset : 0), 0);
                extraScale = (FR_CaseScale() ? state.caseMod[curCase].scale : 1);
                glScalef(state.scaleX, state.scaleY * extraScale, 1);

                // Draw it.
                if(fr.fontNum)
                {
                    textFragmentDrawer(fragment, 0, 0, fragmentAlignFlags, textFlags, state.typeIn ? (int) charCount : DEFAULT_INITIALCOUNT);
                }
                charCount += strlen(fragment);

                // Advance the current position?
                if(newlines == 0)
                {
                    cx += ((float) textFragmentWidth(fragment) + currentAttribs()->tracking) * state.scaleX;
                }
                else
                {
                    if(strlen(fragment) > 0)
                        state.lastLineHeight = textFragmentHeight(fragment);

                    cx = (float) origin.x;
                    cy += newlines * (float) state.lastLineHeight * (1+FR_Leading());
                }

                glMatrixMode(GL_MODELVIEW);
                glPopMatrix();
            }
        }

        FR_PopAttrib();
    }

    freeTextBuffer();

    FR_SetFont(origFont);
    glColor4fv(origColor);
}
示例#17
0
文件: lexer.c 项目: IvanLogvinov/soar
void determine_possible_symbol_types_for_string (char *s,
                                                 int length_of_s,
                                                 bool *possible_id,
                                                 bool *possible_var,
                                                 bool *possible_sc,
                                                 bool *possible_ic,
                                                 bool *possible_fc,
                                                 bool *rereadable) {
  char *ch;
  bool rereadability_dead, rereadability_questionable;

  *possible_id = FALSE;
  *possible_var = FALSE;
  *possible_sc = FALSE;
  *possible_ic = FALSE;
  *possible_fc = FALSE;
  *rereadable = FALSE;

  /* --- check if it's an integer or floating point number --- */
  if (number_starters[(unsigned char)(*s)]) {
    ch = s;
    if ((*ch=='+')||(*ch=='-')) ch++;  /* optional leading + or - */
    while (isdigit(*ch)) ch++;         /* string of digits */
    if ((*ch==0)&&(isdigit(*(ch-1))))
      *possible_ic = TRUE;
    if (*ch=='.') {
      ch++;                              /* decimal point */
      while (isdigit(*ch)) ch++;         /* string of digits */
      if ((*ch=='e')||(*ch=='E')) {
        ch++;                              /* E */
        if ((*ch=='+')||(*ch=='-')) ch++;  /* optional leading + or - */
        while (isdigit(*ch)) ch++;         /* string of digits */
      }
      if (*ch==0) *possible_fc = TRUE;
    }
  }

  /* --- make sure it's entirely constituent characters --- */
  for (ch=s; *ch!=0; ch++)
    if (! constituent_char[(unsigned char)(*ch)]) return;

  /* --- check for rereadability --- */
  rereadability_questionable = FALSE;
  rereadability_dead = FALSE;
  for (ch=s; *ch!=0; ch++) {
    if (islower(*ch) || isdigit(*ch)) continue; /* these guys are fine */
    if (isupper(*ch)) { rereadability_dead = TRUE; break; }
    rereadability_questionable = TRUE;
  }
  if (! rereadability_dead) {
    if ((! rereadability_questionable) ||
        (length_of_s >= LENGTH_OF_LONGEST_SPECIAL_LEXEME) ||
        ((length_of_s==1)&&(*s=='*')))
      *rereadable = TRUE;
  }

  /* --- any string of constituents could be a sym constant --- */
  *possible_sc = TRUE;
  
  /* --- check whether it's a variable --- */
  if ((*s=='<')&&(*(s+length_of_s-1)=='>')) *possible_var = TRUE;

  /* --- check if it's an identifier --- */
  if (isalpha(*s)) {
    /* --- is the rest of the string an integer? --- */
    ch = s+1;
    while (isdigit(*ch)) ch++;         /* string of digits */
    if ((*ch==0)&&(isdigit(*(ch-1)))) *possible_id = TRUE;
  }
}
示例#18
0
int main(){
	printf("OpenSSL version: %s\n", OPENSSL_VERSION_TEXT);
	printf("Enter the number of keys: ");
	fflush(stdout);
	char stringMatch[31];
	getLine(stringMatch);
	unsigned long int i = strtol(stringMatch, NULL, 0);
	printf("Enter a string of text for the key (30 max): ");
	fflush(stdout);
	getLine(stringMatch);
	printf("Waiting for entropy... Move the cursor around...\n");
	fflush(stdout);
	char entropy[32];
	FILE * f = fopen("/dev/random", "r");
	if (fread(entropy, 32, 1, f) != 1){
		printf("FAILURING GETTING ENTROPY!");
		return 1;
	}
	RAND_add(entropy, 32, 32);
	fclose(f);
	printf("Making %lu addresses for \"%s\"\n\n", i, stringMatch);
	EC_KEY * key = EC_KEY_new_by_curve_name(NID_secp256k1);
	uint8_t * pubKey = NULL;
	int pubSize = 0;
	uint8_t * privKey = NULL;
	int privSize = 0;
	uint8_t * shaHash = malloc(32);
	uint8_t * ripemdHash = malloc(20);
	for (unsigned int x = 0; x < i;) {
		if(! EC_KEY_generate_key(key)){
			printf("GENERATE KEY FAIL\n"); 
			return 1;
		}
		int pubSizeNew = i2o_ECPublicKey(key, NULL);
		if(! pubSizeNew){
			printf("PUB KEY TO DATA ZERO\n"); 
			return 1;
		}
		if (pubSizeNew != pubSize) {
			pubSize = pubSizeNew;
			pubKey = realloc(pubKey, pubSize);
		}
		uint8_t * pubKey2 = pubKey;
		if(i2o_ECPublicKey(key, &pubKey2) != pubSize){
			printf("PUB KEY TO DATA FAIL\n");
			return 1;
		}
		SHA256(pubKey, pubSize, shaHash);
		RIPEMD160(shaHash, 32, ripemdHash);
		CBAddress * address = CBNewAddressFromRIPEMD160Hash(ripemdHash, CB_PRODUCTION_NETWORK_BYTE, false, err);
		CBByteArray * string = CBChecksumBytesGetString(CBGetChecksumBytes(address));
		CBReleaseObject(address);
		bool match = true;
		uint8_t offset = 1;
		size_t matchSize = strlen(stringMatch);
		for (uint8_t y = 0; y < matchSize;) {
			char other = islower(stringMatch[y]) ? toupper(stringMatch[y]) : (isupper(stringMatch[y])? tolower(stringMatch[y]) : '\0');
			if (CBByteArrayGetByte(string, y+offset) != stringMatch[y] && CBByteArrayGetByte(string, y+offset) != other) {
				offset++;
				y = 0;
				if (string->length < matchSize + offset) {
					match = false;
					break;
				}
			}else y++;
		}
		if (match) {
			// Get private key
			const BIGNUM * privKeyNum = EC_KEY_get0_private_key(key);
			if (! privKeyNum) {
				printf("PRIV KEY TO BN FAIL\n");
			}
			int privSizeNew = BN_num_bytes(privKeyNum);
			if (privSizeNew != privSize) {
				privSize = privSizeNew;
				privKey = realloc(privKey, privSize);
			}
			int res = BN_bn2bin(privKeyNum, privKey);
			if (res != privSize) {
				printf("PRIV KEY TO DATA FAIL\n");
			}
			// Print data to stdout
			printf("Private key (hex): ");
			for (int x = 0; x < privSize; x++) {
				printf(" %.2X", privKey[x]);
			}
			printf("\nPublic key (hex): ");
			for (int x = 0; x < pubSize; x++) {
				printf(" %.2X", pubKey[x]);
			}
			printf("\nAddress (base-58): %s\n\n", CBByteArrayGetData(string));
			x++; // Move to next
		}
		CBReleaseObject(string);
	}
	free(shaHash);
	free(ripemdHash);
	EC_KEY_free(key);
	return 0;
}
示例#19
0
/*
 * Convert a string to a quad integer.
 *
 * Ignores `locale' stuff.  Assumes that the upper and lower case
 * alphabets and digits are each contiguous.
 */
quad_t
strtoq(const char *nptr, char **endptr, int base)
{
	const char *s;
	u_quad_t acc;
	unsigned char c;
	u_quad_t qbase, cutoff;
	int neg, any, cutlim;

	/*
	 * Skip white space and pick up leading +/- sign if any.
	 * If base is 0, allow 0x for hex and 0 for octal, else
	 * assume decimal; if base is already 16, allow 0x.
	 */
	s = nptr;
	do {
		c = *s++;
	} while (isspace(c));
	if (c == '-') {
		neg = 1;
		c = *s++;
	} else {
		neg = 0;
		if (c == '+')
			c = *s++;
	}
	if ((base == 0 || base == 16) &&
	    c == '0' && (*s == 'x' || *s == 'X')) {
		c = s[1];
		s += 2;
		base = 16;
	}
	if (base == 0)
		base = c == '0' ? 8 : 10;

	/*
	 * Compute the cutoff value between legal numbers and illegal
	 * numbers.  That is the largest legal value, divided by the
	 * base.  An input number that is greater than this value, if
	 * followed by a legal input character, is too big.  One that
	 * is equal to this value may be valid or not; the limit
	 * between valid and invalid numbers is then based on the last
	 * digit.  For instance, if the range for quads is
	 * [-9223372036854775808..9223372036854775807] and the input base
	 * is 10, cutoff will be set to 922337203685477580 and cutlim to
	 * either 7 (neg==0) or 8 (neg==1), meaning that if we have
	 * accumulated a value > 922337203685477580, or equal but the
	 * next digit is > 7 (or 8), the number is too big, and we will
	 * return a range error.
	 *
	 * Set any if any `digits' consumed; make it negative to indicate
	 * overflow.
	 */
	qbase = (unsigned)base;
	cutoff = neg ? (u_quad_t)-(QUAD_MIN + QUAD_MAX) + QUAD_MAX : QUAD_MAX;
	cutlim = cutoff % qbase;
	cutoff /= qbase;
	for (acc = 0, any = 0;; c = *s++) {
		if (!isascii(c))
			break;
		if (isdigit(c))
			c -= '0';
		else if (isalpha(c))
			c -= isupper(c) ? 'A' - 10 : 'a' - 10;
		else
			break;
		if (c >= base)
			break;
		if (any < 0 || acc > cutoff || (acc == cutoff && c > cutlim))
			any = -1;
		else {
			any = 1;
			acc *= qbase;
			acc += c;
		}
	}
	if (any < 0) {
		acc = neg ? QUAD_MIN : QUAD_MAX;
	} else if (neg)
		acc = -acc;
	if (endptr != 0)
		*((const char **)endptr) = any ? s - 1 : nptr;
	return (acc);
}
示例#20
0
文件: load.c 项目: pavlog/cgminer
static int lex_scan(lex_t *lex, json_error_t *error)
{
    char c;

    strbuffer_clear(&lex->saved_text);

    if(lex->token == TOKEN_STRING) {
        free(lex->value.string);
        lex->value.string = NULL;
    }

    c = lex_get(lex, error);
    while(c == ' ' || c == '\t' || c == '\n' || c == '\r')
    {
        if(c == '\n')
            lex->line++;

        c = lex_get(lex, error);
    }

    if(c == (char)EOF) {
        if(lex_eof(lex))
            lex->token = TOKEN_EOF;
        else
            lex->token = TOKEN_INVALID;
        goto out;
    }

    lex_save(lex, c);

    if(c == '{' || c == '}' || c == '[' || c == ']' || c == ':' || c == ',')
        lex->token = c;

    else if(c == '"')
        lex_scan_string(lex, error);

    else if(isdigit(c) || c == '-') {
        if(lex_scan_number(lex, c, error))
            goto out;
    }

    else if(isupper(c) || islower(c)) {
        /* eat up the whole identifier for clearer error messages */
        const char *saved_text;

        c = lex_get_save(lex, error);
        while(isupper(c) || islower(c))
            c = lex_get_save(lex, error);
        lex_unget_unsave(lex, c);

        saved_text = strbuffer_value(&lex->saved_text);

        if(strcmp(saved_text, "true") == 0)
            lex->token = TOKEN_TRUE;
        else if(strcmp(saved_text, "false") == 0)
            lex->token = TOKEN_FALSE;
        else if(strcmp(saved_text, "null") == 0)
            lex->token = TOKEN_NULL;
        else
            lex->token = TOKEN_INVALID;
    }

    else {
        /* save the rest of the input UTF-8 sequence to get an error
           message of valid UTF-8 */
        lex_save_cached(lex);
        lex->token = TOKEN_INVALID;
    }

out:
    return lex->token;
}
示例#21
0
const char *
parse_thing (Thing thing, char **line, const char *type)
{
  const char *value;

  while (*line && ! **line)
    *line = read_line ();

  if (! *line) {
    print_error ("%s expected", type);
    return NULL;
  }

  value = *line;

  if (thing != STRING && thing != STRING_OR_NULL
      && (thing != STRING_OR_IDENTIFIER || **line != '"')) {
    do {
      int expected_character;

      switch (thing) {
      case IDENTIFIER:
      case STRING_OR_IDENTIFIER:
	expected_character = (isalpha (**line) || **line == '_'
			      || (*line != value && isdigit (**line)));
	break;

      case PROPERTY_IDENTIFIER:
	expected_character = isupper (**line);
	break;

      case FIELD_NAME:
	expected_character = (isalpha (**line)
			      || **line == '_' || ** line == '['
			      || (*line != value && (isdigit (**line)
						     || **line == '.'
						     || **line == ']')));
	break;

      case INTEGER_NUMBER:
	expected_character = isdigit (**line);
	break;

      case FLOATING_POINT_NUMBER:
	expected_character = isdigit (**line) || **line == '.';
	break;

      case TIME_VALUE:
	expected_character = (isdigit (**line)
			      || **line == ':' || **line == '.');
	break;

      default:
	assert (0);
      }

      if (!expected_character) {
	print_error ("unexpected character '%c' in %s", **line, type);
	return NULL;
      }

      (*line)++;
    } while (**line && !isspace (**line));
  }
  else {
    if (thing == STRING_OR_NULL) {
      char *possible_null = *line;

      if (looking_at ("NULL", line)) {
	*(possible_null + 4) = 0;
	return possible_null;
      }
    }

    if (**line != '"') {
      print_error ("string%s expected",
		   (thing == STRING ? "" : (thing == STRING_OR_NULL
					    ? " or NULL" : "or identifier")));
      return NULL;
    }

    while (1) {
      (*line)++;

      if (! **line || (**line == '\\' && ! *(*line + 1))) {
	print_error ("unterminated string");
	return NULL;
      }

      if (**line == '"') {
	(*line)++;
	break;
      }

      if (**line == '\\')
	(*line)++;
    }
  }

  if (**line) {
    **line = 0;
    do
      (*line)++;
    while (isspace (**line));
  }

  return value;
}
示例#22
0
void 
SDL_EVDEV_Poll(void)
{
    struct input_event events[32];
    int i, len;
    SDL_evdevlist_item *item;
    SDL_Scancode scan_code;
    int mouse_button;
    SDL_Mouse *mouse;
#ifdef SDL_INPUT_LINUXKD
    Uint16 modstate;
    struct kbentry kbe;
    static char keysym[8];
    char *end;
    Uint32 kval;
#endif

    if (!_this) {
        return;
    }

#if SDL_USE_LIBUDEV
    SDL_UDEV_Poll();
#endif

    mouse = SDL_GetMouse();

    for (item = _this->first; item != NULL; item = item->next) {
        while ((len = read(item->fd, events, (sizeof events))) > 0) {
            len /= sizeof(events[0]);
            for (i = 0; i < len; ++i) {
                switch (events[i].type) {
                case EV_KEY:
                    if (events[i].code >= BTN_MOUSE && events[i].code < BTN_MOUSE + SDL_arraysize(EVDEV_MouseButtons)) {
                        mouse_button = events[i].code - BTN_MOUSE;
                        if (events[i].value == 0) {
                            SDL_SendMouseButton(mouse->focus, mouse->mouseID, SDL_RELEASED, EVDEV_MouseButtons[mouse_button]);
                        } else if (events[i].value == 1) {
                            SDL_SendMouseButton(mouse->focus, mouse->mouseID, SDL_PRESSED, EVDEV_MouseButtons[mouse_button]);
                        }
                        break;
                    }

                    /* Probably keyboard */
                    scan_code = SDL_EVDEV_translate_keycode(events[i].code);
                    if (scan_code != SDL_SCANCODE_UNKNOWN) {
                        if (events[i].value == 0) {
                            SDL_SendKeyboardKey(SDL_RELEASED, scan_code);
                        } else if (events[i].value == 1 || events[i].value == 2 /* Key repeated */) {
                            SDL_SendKeyboardKey(SDL_PRESSED, scan_code);
#ifdef SDL_INPUT_LINUXKD
                            if (_this->console_fd >= 0) {
                                kbe.kb_index = events[i].code;
                                /* Convert the key to an UTF-8 char */
                                /* Ref: http://www.linuxjournal.com/article/2783 */
                                modstate = SDL_GetModState();
                                kbe.kb_table = 0;
                                
                                /* Ref: http://graphics.stanford.edu/~seander/bithacks.html#ConditionalSetOrClearBitsWithoutBranching */
                                kbe.kb_table |= -((modstate & KMOD_LCTRL) != 0) & (1 << KG_CTRLL | 1 << KG_CTRL);
                                kbe.kb_table |= -((modstate & KMOD_RCTRL) != 0) & (1 << KG_CTRLR | 1 << KG_CTRL);
                                kbe.kb_table |= -((modstate & KMOD_LSHIFT) != 0) & (1 << KG_SHIFTL | 1 << KG_SHIFT);
                                kbe.kb_table |= -((modstate & KMOD_RSHIFT) != 0) & (1 << KG_SHIFTR | 1 << KG_SHIFT);
                                kbe.kb_table |= -((modstate & KMOD_LALT) != 0) & (1 << KG_ALT);
                                kbe.kb_table |= -((modstate & KMOD_RALT) != 0) & (1 << KG_ALTGR);

                                if (ioctl(_this->console_fd, KDGKBENT, (unsigned long)&kbe) == 0 && 
                                    ((KTYP(kbe.kb_value) == KT_LATIN) || (KTYP(kbe.kb_value) == KT_ASCII) || (KTYP(kbe.kb_value) == KT_LETTER))) 
                                {
                                    kval = KVAL(kbe.kb_value);
                                    
                                    /* While there's a KG_CAPSSHIFT symbol, it's not useful to build the table index with it
                                     * because 1 << KG_CAPSSHIFT overflows the 8 bits of kb_table 
                                     * So, we do the CAPS LOCK logic here. Note that isalpha depends on the locale!
                                     */
                                    if (modstate & KMOD_CAPS && isalpha(kval)) {
                                        if (isupper(kval)) {
                                            kval = tolower(kval);
                                        } else {
                                            kval = toupper(kval);
                                        }
                                    }
                                     
                                    /* Convert to UTF-8 and send */
                                    end = SDL_UCS4ToUTF8(kval, keysym);
                                    *end = '\0';
                                    SDL_SendKeyboardText(keysym);
                                }
                            }
#endif /* SDL_INPUT_LINUXKD */
                        }
                    }
                    break;
                case EV_ABS:
                    switch(events[i].code) {
                    case ABS_X:
                        SDL_SendMouseMotion(mouse->focus, mouse->mouseID, SDL_FALSE, events[i].value, mouse->y);
                        break;
                    case ABS_Y:
                        SDL_SendMouseMotion(mouse->focus, mouse->mouseID, SDL_FALSE, mouse->x, events[i].value);
                        break;
                    default:
                        break;
                    }
                    break;
                case EV_REL:
                    switch(events[i].code) {
                    case REL_X:
                        SDL_SendMouseMotion(mouse->focus, mouse->mouseID, SDL_TRUE, events[i].value, 0);
                        break;
                    case REL_Y:
                        SDL_SendMouseMotion(mouse->focus, mouse->mouseID, SDL_TRUE, 0, events[i].value);
                        break;
                    case REL_WHEEL:
                        SDL_SendMouseWheel(mouse->focus, mouse->mouseID, 0, events[i].value, SDL_MOUSEWHEEL_NORMAL);
                        break;
                    case REL_HWHEEL:
                        SDL_SendMouseWheel(mouse->focus, mouse->mouseID, events[i].value, 0, SDL_MOUSEWHEEL_NORMAL);
                        break;
                    default:
                        break;
                    }
                    break;
                case EV_SYN:
                    switch (events[i].code) {
                    case SYN_DROPPED:
                        SDL_EVDEV_sync_device(item);
                        break;
                    default:
                        break;
                    }
                    break;
                }
            }
        }    
    }
}
示例#23
0
bool HHVM_FUNCTION(ctype_upper, const Variant& text) {
  return ctype(text, [] (int i) -> int { return isupper(i); });
}
示例#24
0
static int
isconsonant(char chr)
{
  return (isupper((int)chr) && !isvowel(chr));
}
/*
 * ============================================================
 */
int countLetter(char * file1, char * file2)
/*
 * The function counts the occurrences of the twenty sixe English
 * characters and write the results to another file.  
 *
 * file1: name of the input file
 * file2: name of the output file
 *
 * All upper-case letters are converted to lower-case letters. 'A' and
 * 'a' are both counted as 'a'.
 *
 * file1: name of the input file
 * file2: name of the output file
 *
 * This function returns EXIT_SUCCESS if it finishes without any
 * problem. The function returns EXIT_FAILURE if there is a problem in
 * opening the file, reading from the input file, or writing to the
 * output file.
 */
/*
 * You should NOT write anything like the following. You will lose
 * 20% points if you do so.
 *
 * if (c == 'a') ...
 * if (c == 'b') ...
 * if (c == 'c') ...
 * if (c == 'd') ...
 * 
 *
 * You should not write anything like the following, either.
 * switch (c)
 * {
 *  case 'a':
 *  ...
 *  case 'b':
 *  ...
 *  case 'c':
 *  ...
 *  }
 *
 * This is error-prone (what happens if you forget to change one
 * place?).  You should find a general method that is applicable to
 * all 26 characters.
 *
 * Whenever you copy-paste code, you have a higher chance of mistakes.
 *
 * Hint: create an array to store the counts.  Remember to initialize
 * the array's elements.
 *
 * Hint: C has several functions that can be useful.  Check isalpha,
 * isupper, islower.
 * 
 */
{
  FILE *fin = fopen(file1, "r");
  if(fin == NULL)
  {
    return EXIT_FAILURE;
  }

  FILE *fout = fopen(file2, "w");
  if(fout == NULL)
  {
    fclose(fin);
    return EXIT_FAILURE;
  }

  int counts[NUM_CHAR] = {0};
  int c;
  while((c = fgetc(fin)) != EOF)
  {
    if(isupper(c))
    {
      counts[c - 'A']++;
    }
    else if (islower(c))
    {
      counts[c-'a']++;
    }
  }
  int i;
  for(i=0; i< NUM_CHAR; i++)
  {
    fprintf(fout, "%c: %d\n", i+'a', counts[i]);
  }
  
  fclose(fin);
  fclose(fout);


  return EXIT_SUCCESS;
}
unsigned int Password_Test(char * str)
{
     unsigned int score = 0;
     unsigned int Upper_Count = 0;  // NmA 1
     unsigned int Lower_Count = 0;  // NmA 2
     unsigned int Number_Count = 0; // NmA 3
     unsigned int Symbol_Count = 0; // NmA 4

     unsigned int Num_middle_Alpha = 0;    
     unsigned int Num_middle_Alpha_prev = 0;
      
     unsigned int passwd_mid = 0;
     
     unsigned int Upper_repeat = 0;
     unsigned int Lower_repeat = 0;
     unsigned int Number_repeat = 0;
     unsigned int Symbol_repeat = 0;
     unsigned int Ascii_repeat = 0;    
     unsigned int CTT_repeat = 0;

     unsigned int AsciiCode_prev,AsciiCode_current;

     unsigned int len;
         
     
     AsciiCode_prev = -1;
     AsciiCode_current = -1;  
  
     len = strlen(str);  

     char * buffer = (char*)malloc(sizeof(char)*(len+1));
     strcpy(buffer,str);
            
     
    while((*str)!='\0'){
      if( isupper(*str)){
          
           Upper_Count++; 

           Num_middle_Alpha_prev = Num_middle_Alpha;
           Num_middle_Alpha = 1;

           AsciiCode_prev = AsciiCode_current;
           AsciiCode_current = (unsigned int)(*str);
         }
     else if( islower(*str)){
           
              Lower_Count++;
             
              Num_middle_Alpha_prev = Num_middle_Alpha;    
              Num_middle_Alpha = 2;

             AsciiCode_prev = AsciiCode_current;
           AsciiCode_current = (unsigned int)(*str);
         
         }
     else if( isdigit(*str)){
              Number_Count++;
             
              Num_middle_Alpha_prev = Num_middle_Alpha;
              Num_middle_Alpha = 3;

              AsciiCode_prev = AsciiCode_current;
           AsciiCode_current = (unsigned int)(*str);
        }
     else if( issymbol(*str)){
         Symbol_Count++;
         Num_middle_Alpha_prev = Num_middle_Alpha;
         Num_middle_Alpha = 4;

         AsciiCode_prev = AsciiCode_current;
           AsciiCode_current = (unsigned int)(*str);

        }
     

      /*--------------------------------------------------------------------*/
     if(Number_middle_Alpha(Num_middle_Alpha,Num_middle_Alpha_prev)){passwd_mid++;}

     /*--------------------Decersing Score------------------------------*/


     if(UpperAlpha(Num_middle_Alpha_prev,Num_middle_Alpha)){
         //  printf("Upper\n");
           Upper_repeat++;
     }
     if(LowerAlpha(Num_middle_Alpha_prev,Num_middle_Alpha)){
         //  printf("Lower\n");
          Lower_repeat++; 
      }    
     if(NumberRpt(Num_middle_Alpha_prev,Num_middle_Alpha)){
         Number_repeat++;
      }
     if(SymbolRpt(Num_middle_Alpha_prev,Num_middle_Alpha)){
         Symbol_repeat++;
      }

     Ascii_repeat = AsciiRpt(buffer);
      
      
      
     unsigned int end_or_not = *(str+1) == '\0' ? -1  : (unsigned int)(*(str+1));
     if( Continue_Three_Time(AsciiCode_prev,AsciiCode_current,end_or_not) ){
           CTT_repeat++;
      }
      str++;
    }



  /* printf("%u:%u:%u:%u:%u\n  %u:%u:%u:%u:%u:%u\n",Upper_Count,Lower_Count,Number_Count,Symbol_Count,passwd_mid,
                                                     Upper_repeat,Lower_repeat,Number_repeat,Symbol_repeat,Ascii_repeat,CTT_repeat);       */
     
   //------------------------------------day to Crack------------------------------------------------------//
   if(Upper_Count !=0 && Lower_Count!=0 && Number_Count!=0 && Symbol_Count!=0){my_pow(95,len);}

   else if(Upper_Count != 0 && Lower_Count != 0 && Number_Count!=0){my_pow(63,len);}
  
   else if(Upper_Count != 0 && Lower_Count != 0 && Symbol_Count!=0){my_pow(85,len);}
   
   else if(Upper_Count != 0 && Number_Count != 0 && Symbol_Count !=0){my_pow(69,len);}
   
   else if(Lower_Count != 0 && Number_Count != 0 && Symbol_Count!=0 ){my_pow(69,len);}

   else if(Upper_Count != 0 && Lower_Count !=0){my_pow(52,len);}
 
   else if(Upper_Count != 0 && Number_Count !=0){my_pow(36,len);}
   
   else if(Upper_Count !=0 && Symbol_Count!=0){my_pow(58,len);}

   else if(Lower_Count != 0 && Number_Count!=0){my_pow(36,len);}
   
   else if(Lower_Count != 0 && Symbol_Count!=0){my_pow(58,len);}
  
   else if(Symbol_Count != 0 && Number_Count!=0){my_pow(42,len);}

   else if(Upper_Count!=0){my_pow(26,len);}
   
   else if(Lower_Count!=0){my_pow(26,len);}

   else if(Symbol_Count!=0){my_pow(32,len);}

   else if(Number_Count!=0){my_pow(10,len);}
    
}
示例#27
0
long strtol(const char* number_string, char** end_pointer, int base)
{
    unsigned long acc, cutoff;
    int c, any, cutlim;
    const char* s = number_string;
    bool is_negative = false;

    //Skip empty spaces
    do
    {
        c = *s++;
    }while(isspace(c));
    
    //Check for negative sign
    if( c == '-' )
    {
        c = *s++;
        is_negative = true;
    }
    //Advamce  a char
    else if( c == '+' )
        c = *s++;
    
    //If no base is specified chack for 0x -> (base = 16) and 0 -> octal
    if( c == '0' && (base == 0 || base == 16) && (*s == 'x' || *s == 'X') )
    {
        c = s[1];
        s += 2;
        base = 16;
    }
    if(base == 0)
        base = c == '0' ? 8 : 10;


    /*
     * The cutoff value is the largest legal value divided by the base
     * any is set if any digit is found or is -1 if a overflow occur
    */
    cutoff = is_negative? -(unsigned long)INT32_MIN: INT32_MAX;
    cutlim = cutoff % (unsigned long)base;
    cutoff /= base;

    for(acc = 0, any = 0;; c = *s++)
    {
        if(isdigit(c))
            c -= '0';
        else if(isalpha(c))
            c -= isupper(c) ? 'A' - 10 : 'a' - 10;
        else
            break;
        
        if( c >= base)
            break;
        if(any < 0 || acc > cutoff || (acc == cutoff && c > cutlim))
            any = -1;
        else
        {
            any = 1;
            acc *= base;
            acc += c;
        }
    }
    if( any < 0)
        acc = is_negative ? INT32_MIN : INT32_MAX;
    else if(is_negative)
        acc = -acc;
    
    if(end_pointer != 0)
        *end_pointer = (char*)(any ? s - 1 : number_string);

    return acc;
}
示例#28
0
文件: spread.c 项目: AkaBlood/ogs5
/* ---------------------------------------------------------------------- */
int
copy_token_tab (char *token_ptr, char **ptr, int *length)
/* ---------------------------------------------------------------------- */
{
/*
 *   Copies from **ptr to *token_ptr until first tab is encountered.
 *
 *   Arguments:
 *      *token_ptr  output, place to store token
 *
 *     **ptr        input, character string to read token from
 *                  output, next position after token
 *
 *       length     output, length of token
 *
 *   Returns:
 *      UPPER,
 *      LOWER,
 *      DIGIT,
 *      EMPTY,
 *      EOL,
 *      UNKNOWN.
 */
  int i, j, return_value;
  char c;
/*
 *   Strip leading spaces
 */
  while ((c = **ptr) == ' ')
    (*ptr)++;
/*
 *   Check what we have
 */
  if (isupper ((int) c))
  {
    return_value = UPPER;
  }
  else if (islower ((int) c))
  {
    return_value = LOWER;
  }
  else if (isdigit ((int) c) || c == '.' || c == '-')
  {
    return_value = DIGIT;
  }
  else if (c == '\0')
  {
    return_value = EOL;
    return (return_value);
  }
  else if (c == '\t')
  {
    return_value = EMPTY;
  }
  else
  {
    return_value = UNKNOWN;
  }
/*
 *   Begin copying to token
 */
  i = 0;
#ifdef SKIP
  while ((c = **ptr) != '\t' && c != '\0')
  {
    token_ptr[i] = c;
    (*ptr)++;
    i++;
  }
#endif
  for (;;)
  {
    c = **ptr;
    if (c == '\t')
    {
      (*ptr)++;
      break;
    }
    else if (c == '\0')
    {
      break;
    }
    else
    {
      token_ptr[i] = c;
      (*ptr)++;
      i++;
    }
  }
  token_ptr[i] = '\0';
  *length = i;
/*
 *   Strip trailing spaces
 */
  for (j = i - 1; j >= 0; j--)
  {
    if (j != ' ')
      break;
  }
  if (j != i - 1)
  {
    token_ptr[j + 1] = '\0';
    *length = j + 1;
  }
  return (return_value);
}
示例#29
0
文件: mark.c 项目: NOLFXceptMe/neovim
/*
 * Set named mark "c" to position "pos".
 * When "c" is upper case use file "fnum".
 * Returns OK on success, FAIL if bad name given.
 */
int setmark_pos(int c, pos_T *pos, int fnum)
{
  int i;

  /* Check for a special key (may cause islower() to crash). */
  if (c < 0)
    return FAIL;

  if (c == '\'' || c == '`') {
    if (pos == &curwin->w_cursor) {
      setpcmark();
      /* keep it even when the cursor doesn't move */
      curwin->w_prev_pcmark = curwin->w_pcmark;
    } else
      curwin->w_pcmark = *pos;
    return OK;
  }

  if (c == '"') {
    curbuf->b_last_cursor = *pos;
    return OK;
  }

  /* Allow setting '[ and '] for an autocommand that simulates reading a
   * file. */
  if (c == '[') {
    curbuf->b_op_start = *pos;
    return OK;
  }
  if (c == ']') {
    curbuf->b_op_end = *pos;
    return OK;
  }

  if (c == '<' || c == '>') {
    if (c == '<')
      curbuf->b_visual.vi_start = *pos;
    else
      curbuf->b_visual.vi_end = *pos;
    if (curbuf->b_visual.vi_mode == NUL)
      /* Visual_mode has not yet been set, use a sane default. */
      curbuf->b_visual.vi_mode = 'v';
    return OK;
  }

  if (c > 'z')              /* some islower() and isupper() cannot handle
                                characters above 127 */
    return FAIL;
  if (islower(c)) {
    i = c - 'a';
    curbuf->b_namedm[i] = *pos;
    return OK;
  }
  if (isupper(c)) {
    i = c - 'A';
    namedfm[i].fmark.mark = *pos;
    namedfm[i].fmark.fnum = fnum;
    free(namedfm[i].fname);
    namedfm[i].fname = NULL;
    return OK;
  }
  return FAIL;
}
示例#30
0
文件: tkOption.c 项目: das/tcltk
void
Tk_AddOption(
    Tk_Window tkwin,		/* Window token; option will be associated
				 * with main window for this window. */
    const char *name,		/* Multi-element name of option. */
    const char *value,		/* String value for option. */
    int priority)		/* Overall priority level to use for this
				 * option, such as TK_USER_DEFAULT_PRIO or
				 * TK_INTERACTIVE_PRIO. Must be between 0 and
				 * TK_MAX_PRIO. */
{
    TkWindow *winPtr = ((TkWindow *) tkwin)->mainPtr->winPtr;
    register ElArray **arrayPtrPtr;
    register Element *elPtr;
    Element newEl;
    register const char *p;
    const char *field;
    int count, firstField;
    ptrdiff_t length;
#define TMP_SIZE 100
    char tmp[TMP_SIZE+1];
    ThreadSpecificData *tsdPtr =
	    Tcl_GetThreadData(&dataKey, sizeof(ThreadSpecificData));

    if (winPtr->mainPtr->optionRootPtr == NULL) {
	OptionInit(winPtr->mainPtr);
    }
    tsdPtr->cachedWindow = NULL;/* Invalidate the cache. */

    /*
     * Compute the priority for the new element, including both the overall
     * level and the serial number (to disambiguate with the level).
     */

    if (priority < 0) {
	priority = 0;
    } else if (priority > TK_MAX_PRIO) {
	priority = TK_MAX_PRIO;
    }
    newEl.priority = (priority << 24) + tsdPtr->serial;
    tsdPtr->serial++;

    /*
     * Parse the option one field at a time.
     */

    arrayPtrPtr = &(((TkWindow *) tkwin)->mainPtr->optionRootPtr);
    p = name;
    for (firstField = 1; ; firstField = 0) {
	/*
	 * Scan the next field from the name and convert it to a Tk_Uid. Must
	 * copy the field before calling Tk_Uid, so that a terminating NULL
	 * may be added without modifying the source string.
	 */

	if (*p == '*') {
	    newEl.flags = WILDCARD;
	    p++;
	} else {
	    newEl.flags = 0;
	}
	field = p;
	while ((*p != 0) && (*p != '.') && (*p != '*')) {
	    p++;
	}
	length = p - field;
	if (length > TMP_SIZE) {
	    length = TMP_SIZE;
	}
	strncpy(tmp, field, (size_t) length);
	tmp[length] = 0;
	newEl.nameUid = Tk_GetUid(tmp);
	if (isupper(UCHAR(*field))) {
	    newEl.flags |= CLASS;
	}

	if (*p != 0) {
	    /*
	     * New element will be a node. If this option can't possibly apply
	     * to this main window, then just skip it. Otherwise, add it to
	     * the parent, if it isn't already there, and descend into it.
	     */

	    newEl.flags |= NODE;
	    if (firstField && !(newEl.flags & WILDCARD)
		    && (newEl.nameUid != winPtr->nameUid)
		    && (newEl.nameUid != winPtr->classUid)) {
		return;
	    }
	    for (elPtr = (*arrayPtrPtr)->els, count = (*arrayPtrPtr)->numUsed;
		    ; elPtr++, count--) {
		if (count == 0) {
		    newEl.child.arrayPtr = NewArray(5);
		    *arrayPtrPtr = ExtendArray(*arrayPtrPtr, &newEl);
		    arrayPtrPtr = &((*arrayPtrPtr)
			    ->nextToUse[-1].child.arrayPtr);
		    break;
		}
		if ((elPtr->nameUid == newEl.nameUid)
			&& (elPtr->flags == newEl.flags)) {
		    arrayPtrPtr = &(elPtr->child.arrayPtr);
		    break;
		}
	    }
	    if (*p == '.') {
		p++;
	    }
	} else {
	    /*
	     * New element is a leaf. Add it to the parent, if it isn't
	     * already there. If it exists already, keep whichever value has
	     * highest priority.
	     */

	    newEl.child.valueUid = Tk_GetUid(value);
	    for (elPtr = (*arrayPtrPtr)->els, count = (*arrayPtrPtr)->numUsed;
		    ; elPtr++, count--) {
		if (count == 0) {
		    *arrayPtrPtr = ExtendArray(*arrayPtrPtr, &newEl);
		    return;
		}
		if ((elPtr->nameUid == newEl.nameUid)
			&& (elPtr->flags == newEl.flags)) {
		    if (elPtr->priority < newEl.priority) {
			elPtr->priority = newEl.priority;
			elPtr->child.valueUid = newEl.child.valueUid;
		    }
		    return;
		}
	    }
	}
    }
}