QPrinter::QPrinter(PrinterMode m) : QPaintDevice(QInternal::Printer | QInternal::ExternalDevice)
{
    d = new QPrinterPrivate;
    if(PMCreateSession(&psession) != noErr)
        psession = NULL;

    switch(m) {
    case Compatible:
        devFlags |= QInternal::CompatibilityMode;
    // fall through
    case PrinterResolution:
    case HighResolution: {
        bool found = FALSE;
        PMPrinter printer = 0;
        if(psession && PMSessionGetCurrentPrinter(psession, &printer) == noErr) {
            PMResolution pres;
            UInt32 count = 0, maxRes = 0;
            if (PMPrinterGetPrinterResolutionCount( printer, &count ) == noErr && count)
                for( ; count > 0; --count )
                    if (PMPrinterGetIndexedPrinterResolution( printer, count, &pres ) == noErr) {
                        found = TRUE;
                        maxRes = QMAX( (uint)pres.vRes, maxRes );
                        res = maxRes;
                    }
        }
        if(!found)
            res = 600; //just to have something
        break;
    }
    case ScreenResolution: {
        short vr, hr;
        ScreenRes(&hr, &vr);
        res = vr;
        break;
    }
    }

    if (PMCreatePageFormat(&pformat) == noErr &&
            PMSessionDefaultPageFormat(psession, pformat) == noErr)
        page_size = carbonSize2QPrinterSize(pformat);
    else
        page_size = A4;

    //other
    orient = Portrait;

    page_order = FirstPageFirst;
    paper_source = OnlyOne;
    color_mode = GrayScale;
    ncopies = 1;
    from_pg = to_pg = min_pg = max_pg = 0;
    state = PST_IDLE;
    output_file = FALSE;
    to_edge     = FALSE;

    //mac specific
    pformat = kPMNoPageFormat;
    psettings = kPMNoPrintSettings;
    prepare(&pformat);
    prepare(&psettings);
    interpret(&pformat);
    interpret(&psettings);

    d->printerOptions = 0;
    setPrintRange( AllPages );
}
Example #2
0
int main(int argc, char* argv[])
{
    // a global variable defined in errno.h that's "set by system 
    // calls and some library functions [to a nonzero value]
    // in the event of an error to indicate what went wrong"
    errno = 0;

    // default to port 8080
    int port = 8080;

    // usage
    const char* usage = "Usage: server [-p port] /path/to/root";

    // parse command-line arguments
    int opt;
    while ((opt = getopt(argc, argv, "hp:")) != -1)
    {
        switch (opt)
        {
            // -h
            case 'h':
                printf("%s\n", usage);
                return 0;

            // -p port
            case 'p':
                port = atoi(optarg);
                break;
        }
    }

    // ensure port is a non-negative short and path to server's root is specified
    if (port < 0 || port > SHRT_MAX || argv[optind] == NULL || strlen(argv[optind]) == 0)
    {
        // announce usage
        printf("%s\n", usage);

        // return 2 just like bash's builtins
        return 2;
    }

    // start server
    start(port, argv[optind]);

    // listen for SIGINT (aka control-c)
    struct sigaction act;
    act.sa_handler = handler;
    act.sa_flags = 0;
    sigemptyset(&act.sa_mask);
    sigaction(SIGINT, &act, NULL);

    // a message and its length
    char* message = NULL;
    size_t length = 0;

    // path requested
    char* path = NULL;

    // accept connections one at a time
    while (true)
    {
        // free last path, if any
        if (path != NULL)
        {
            free(path);
            path = NULL;
        }

        // free last message, if any
        if (message != NULL)
        {
            free(message);
            message = NULL;
        }
        length = 0;

        // close last client's socket, if any
        if (cfd != -1)
        {
            close(cfd);
            cfd = -1;
        }

        // check for control-c
        if (signaled)
        {
            stop();
        }

        // check whether client has connected
        if (connected())
        {
            // check for request
            if (request(&message, &length))
            {
                // extract message's request-line
                // http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html
                const char* haystack = message;
                const char* needle = strstr(haystack, "\r\n");
                if (needle == NULL)
                {
                    error(500);
                    continue;
                }
                char line[needle - haystack + 2 + 1];
                strncpy(line, haystack, needle - haystack + 2);
                line[needle - haystack + 2] = '\0';

                // log request-line
                printf("%s", line);

                // parse request-line
                char abs_path[LimitRequestLine + 1];
                char query[LimitRequestLine + 1];
                if (parse(line, abs_path, query))
                {
                    // URL-decode absolute-path
                    char* p = urldecode(abs_path);
                    if (p == NULL)
                    {
                        error(500);
                        continue;
                    }

                    // resolve absolute-path to local path
                    path = malloc(strlen(root) + strlen(p) + 1);
                    if (path == NULL)
                    {
                        error(500);
                        continue;
                    }
                    strcpy(path, root);
                    strcat(path, p);
                    free(p);

                    // ensure path exists
                    if (access(path, F_OK) == -1)
                    {
                        error(404);
                        continue;
                    }

                    // if path to directory
                    struct stat sb;
                    if (stat(path, &sb) == 0 && S_ISDIR(sb.st_mode))
                    {
                        // redirect from absolute-path to absolute-path/
                        if (abs_path[strlen(abs_path) - 1] != '/')
                        {
                            char uri[strlen(abs_path) + 1 + 1];
                            strcpy(uri, abs_path);
                            strcat(uri, "/");
                            redirect(uri);
                            continue;
                        }

                        // use path/index.php or path/index.html, if present, instead of directory's path
                        char* index = indexes(path);
                        if (index != NULL)
                        {
                            free(path);
                            path = index;
                        }

                        // list contents of directory
                        else
                        {
                            list(path);
                            continue;
                        }
                    }

                    // look up MIME type for file at path
                    const char* type = lookup(path);
                    if (type == NULL)
                    {
                        error(501);
                        continue;
                    }

                    // interpret PHP script at path
                    if (strcasecmp("text/x-php", type) == 0)
                    {
                        interpret(path, query);
                    }

                    // transfer file at path
                    else
                    {
                        transfer(path, type);
                    }
                }
            }
        }
    }
}
Example #3
0
void do_account( CHAR_DATA *ch, char *argument )
{
    BANK_DATA              *bank;
    CHAR_DATA              *banker;
    char                    arg1[MAX_INPUT_LENGTH];
    char                    arg2[MAX_INPUT_LENGTH];
    char                    arg3[MAX_INPUT_LENGTH];
    char                    buf[MSL],
                           *pwdnew,
                           *p;
    int                     currtime = time( 0 );

    /*
     * arg1 == account name
     * arg2 == password (if none, close it)
     */

    if ( !( banker = find_banker( ch ) ) ) {
        send_to_char( "You're not in a bank!\r\n", ch );
        return;
    }

    if ( IS_NPC( ch ) || IS_IMMORTAL( ch ) ) {
        snprintf( buf, MSL, "say Sorry, %s, we don't do business with mobs, or 6D STAFF.",
                  ch->name );
        interpret( banker, buf );
        return;
    }

    if ( argument[0] == '\0' ) {
        send_to_char( "Syntax: account [account name] [account password]\n", ch );
        send_to_char( "Syntax: account [account name] [account password] [create/delete]\n", ch );
        send_to_char( "Syntax: account [account name]\n", ch );
        interpret( banker, ( char * ) "say if you need help type &WHELP BANK&D." );
        return;
    }

    argument = one_argument( argument, arg1 );
    argument = one_argument( argument, arg2 );
    argument = one_argument( argument, arg3 );

    bank = find_bank( arg1 );

    if ( !str_cmp( arg3, "create" ) ) {
        if ( strlen( arg1 ) < 4 ) {
            send_to_char( "Account name must be at least 4 characters.\r\n", ch );
            return;
        }

        if ( strlen( arg2 ) < 5 ) {
            send_to_char( "Invalid Password.  Must be at least 5 characters in length.\r\n", ch );
            return;
        }
        if ( arg2[0] == '!' ) {
            send_to_char( "Password cannot begin with the '!' character.\r\n", ch );
            return;
        }

        if ( bank ) {
            send_to_char( "There is already an account with that name!\r\n", ch );
            return;
        }

        if ( ( currtime - ch->pcdata->lastaccountcreated ) < 3600 ) {
            send_to_char
                ( "Please wait at least one hour from previous creation time to make a new account.\r\n",
                  ch );
            return;
        }

        pwdnew = crypt( arg2, arg1 );
        for ( p = pwdnew; *p != '\0'; p++ ) {
            if ( *p == '~' ) {
                send_to_char( "Password not acceptable, try again.\r\n", ch );
                return;
            }
        }

        CREATE( bank, BANK_DATA, 1 );
        bank->lastused = current_time;
        bank->name = STRALLOC( arg1 );
        bank->password = STRALLOC( pwdnew );
        bank->bronze = 0;
        bank->copper = 0;
        bank->gold = 0;
        bank->silver = 0;
        add_bank( bank );
        save_bank(  );
        ch->pcdata->lastaccountcreated = currtime;
        save_char_obj( ch );
        saving_char = NULL;
        send_to_char( "Your account has been added.\r\n", ch );
        return;
    }
    else if ( !str_cmp( arg3, "delete" ) ) {
        if ( !bank ) {
            send_to_char( "There is no account with that name!\r\n", ch );
            return;
        }

        if ( strcmp( crypt( arg2, bank->password ), bank->password ) ) {
            send_to_char( "Invalid password.\r\n", ch );
            return;
        }

        GET_MONEY( ch, CURR_GOLD ) += bank->gold;
        GET_MONEY( ch, CURR_SILVER ) += bank->silver;
        GET_MONEY( ch, CURR_BRONZE ) += bank->bronze;
        GET_MONEY( ch, CURR_COPPER ) += bank->copper;
        ch_printf( ch, "Deleting... (%s)\r\n", bank->name );
        free_bank_to_chars( bank );
        unlink_bank( bank );
        free_bank( bank );
        save_bank(  );
        ch->pcdata->lastaccountcreated = 0;
        save_char_obj( ch );
        saving_char = NULL;
        send_to_char( "Your account has successfully been deleted.\r\n", ch );
        return;
    }

    if ( !bank ) {
        send_to_char( "There is no account by that name!\r\n", ch );
        return;
    }

    if ( !str_cmp( arg2, "" ) ) {
        if ( ch->pcdata->bank == NULL ) {
            send_to_char( "You don't have any bank account open now.\r\n", ch );
            return;
        }
        snprintf( buf, MSL, "You have closed the account %s.\r\n", ch->pcdata->bank->name );
        send_to_char( buf, ch );
        ch->pcdata->bank = NULL;
        return;
    }

    if ( strcmp( crypt( arg2, bank->password ), bank->password ) ) {
        send_to_char( "Invalid password.\r\n", ch );
        return;
    }

    snprintf( buf, MSL, "You have opened the account %s.\r\n", bank->name );
    send_to_char( buf, ch );
    ch->pcdata->bank = bank;
}
int main(int argc, char *argv[])
{
 
  char name_buf[20];
  srand48(time(NULL));

 /* define a non-point as zull */
  zull.x = -23.0;
  zull.y = -33.0;
  zull.z = -10.0;
  /* define zero */
  zero.re = 0.0; zero.i = 0.0 ; zero.j = 0.0 ; zero.k = 0.0 ;

  /* define some units */
  one.re = 1.0 ; one.i = 0.0 ; one.j = 0.0 ; one.k = 0.0;

  i.re   = 0.0 ; i.i = 1.0   ; i.j = 0.0   ; i.k = 0.0;

  j.re   = 0.0 ; j.i = 0.0   ; j.j = 1.0   ; j.k = 0.0;

  k.re   = 0.0 ; k.i = 0.0   ; k.j = 0.0   ; k.k = 1.0;

  /* negate them */
  mone   = negative(one);
  mi     = negative(i);
  mj     = negative(j);
  mk     = negative(k);

  /* now define the unscaled roots */
  w1 = threeadd(i,j,k);
  w2 = threeadd(mi,mj,k);
  w3 = threeadd(i,mj,mk);
  w4 = threeadd(mi,j,mk);
 
  /* rescale the unscaled roots so that they're on the unit sphere */
  w1 = normscale(w1);
  w2 = normscale(w2);
  w3 = normscale(w3);
  w4 = normscale(w4);

  printf("constants defined\n");

  quaternion constant;
  constant.re = -0.450;
  constant.i = -0.477;
  constant.j = 0.181;
  constant.k = 0.306;
  /* define the polynomial */
  quaternion julia(quaternion m)
  {
    return add(square(m),constant);
  }

  printf("newton's method defined\n");

  /* linear point array 256^3 = 16777216 */
  firechar = malloc( 27270901* sizeof(point));

  printf("storage array generated\n");
  /* clear the display array */
  tol = 0.001;


  for(A=0;A<301;A++)
    {
      for(B=0;B<301;B++)
  {
	  for(C=0;C<301;C++)
	    {
	      current.re = ((double) (A - 151))/150.0 + 0.001* (drand48()-1);
	      current.i = ((double) (B - 151))/150.0 + 0.001* (drand48()-1);
	      current.j = ((double) (C - 151))/150.0; + 0.001* (drand48()-1);
	      current.k = 0.001* (drand48()-1);
	      store = interpret(current);
	      firechar[90601*A+301*B+C].x=store.x;
	      firechar[90601*A+301*B+C].y=store.y;
	      firechar[90601*A+301*B+C].z=store.z;
	    }
	}
    }

  /* generate the data array */
  for(A=0;A<301;A++)
    {
      for(B=0;B<301;B++)
	{
	  for(C=0;C<301;C++)
	    {
	      /* printf("I got this far, no really! A=%d B=%d C=%d\n",A,B,C); */

              current.re = ((double) (A - 151))/150.0 + 0.001* (drand48()-1);
	      current.i = ((double) (B - 151))/150.0 + 0.001* (drand48()-1);
	      current.j = ((double) (C - 151))/150.0 + 0.001* (drand48()-1);
	      current.k = 0.001* (drand48()-1);
	      store = interpret(current);
	      iter = 0;
	      do
		{	     
		  next=julia(current);
		  current=next;
		  iter=iter+1;
		} while ((norm(current)<2)&&(iter<30));
	      /* printf("%d, %.10f\n", iter, norm(current)); */
	      if(norm(current)>2)
		{
		  firechar[90601*A+301*B+C] = zull;
		  /* printf("setting a zull\n"); */
		}
	    }
	}
    }

  zullcount=0;
  for(n=0;n<27270901;n++)
    {
      if(firechar[n].x==-23.0)
	{
	  zullcount=zullcount+1;
	}

    }
  printf("total cells occuped %d out of \n", 27270901-zullcount);
  printf("percentage occupied = %f\n", ((double)(27270901-zullcount))/27270901);


  for (level = 0; level < 1024; level++) 
    {
      theta = 6.283185307179586 * ((double) (level))/1024.0;
      costheta = cos(theta);
      sintheta = sin(theta);
      vranj = 2.718281828459045 * theta;
      cosvranj = cos(vranj);
      sinvranj = sin(vranj);
      /* define the zero point for reference purposes */
      
      /* white the display arraw */

        for(vba=0;vba<512;vba++)
	{
	  for(vbb=0;vbb<512;vbb++)
	    {
	      display[vba][vbb]=0;
	    }
	}


      for(n=0;n<27270901;n++)
	{
	  if(firechar[n].x!=-23.0)
	    {
	      tx=firechar[n].x;
	      ty=firechar[n].y;
	      tz=firechar[n].z;
	      ax = tx * cosvranj - tz * sinvranj;
	      az = tx * sinvranj + tz * cosvranj; 
	      rz = az;

	      rx = ax * costheta - ty * sintheta;
	      ry = ax * sintheta + ty * costheta;
	      /* printf("I got this far, no really!\n");     */ 	      
	      TX=1.61*rx+0.00010394;
	      TY=1.61*rz+0.00010394;
	      
	      m = (int) ((TX + 2) / 4 * 511);
	      l = (int) ((TY + 2) / 4 * 511);
	      

	      /* printf("m=%d l=%d\n", m,l); */
	      /* display[m][l]=0; */
	      if(display[l][m]<255)
	      	{
	      	  display[l][m]=display[l][m]+1;
	      	}
	      /* if(display[l][m]>0) */
	      /* 	{ */
	      /* 	  if((m>0)&&(m<512)) */
	      /* 	    { */
	      /* 	      if((l=0)&&(l<512)) */
	      /* 		{ */
	      /* 		  display[l][m]=0; */
	      /* 		} */
	      /* 	    } */
	      /* 	} */
	    }
	}

  
      sprintf(name_buf,"%04d.pnm", level);
      file = fopen(name_buf, "w");
      fprintf(file, "P2\n512 512\n255\n");
      for(vba=0;vba<512;vba++)
	{
	  for(vbb=0;vbb<512;vbb++)
	    {
	      fprintf(file,"%u\n", display[vba][vbb]);
	    }
	}
      fclose(file);
    }






  return 0;
}
Example #5
0
/* i've never learned cases before so i'm pretty much leaving this one
 * alone, except for taking out the one_arguement() function */
void int_combat_handler( CHAR_DATA * ch, CHAR_DATA * victim )
{
    /*
     * Called from fight.c during combat to enable mobs to use spells and
     * skills.  ACT_INTELLIGENT mobs can call cast() now.
     * --Stephen
     */

    char arg[MAX_STRING_LENGTH];
    char buf[MAX_STRING_LENGTH];
    CHAR_DATA *vch;
    int sn;
    int counter = 1;

    if ( number_percent(  ) < 65 )
        return;

    for ( vch = ch->in_room->first_person; vch != NULL; vch = vch->next_in_room )
    {
        if ( vch == victim )
        {
            snprintf( buf, MSL, "%d.%s", counter, vch->name.c_str() );
            break;
        }

        counter = counter + 1;
    }

    switch ( number_range( 0, 5 ) )  /* Pick a skill or a spell */
    {
        case 0:
        case 1:
        case 2:
        case 3:
            /*
             * Use a skill
             */
            switch ( number_range( 0, 5 ) )
            {
                case 0:
                    snprintf( arg, MSL, "frenzy" );
                    break;
                case 1:
                    snprintf( arg, MSL, "punch %s", buf );
                    break;
                case 2:
                    snprintf( arg, MSL, "knee %s", buf );
                    break;
                case 3:
                    snprintf( arg, MSL, "headbutt %s", buf );
                    break;
                case 4:
                    snprintf( arg, MSL, "punch %s", buf );
                    break;
                case 5:
                    snprintf( arg, MSL, "dirt %s", buf );
                    break;
            }
            interpret( ch, arg );
            do_say( ch, buf );
            break;
        default:
            sn = find_spell( ch, TAR_CHAR_OFFENSIVE );
            if ( ( sn != -1 ) && ( ch->mana > mana_cost( ch, sn ) ) )
            {
                snprintf( arg, MSL, "cast '%s' %s", skill_table[sn].name, buf );
                interpret( ch, arg );
            }
    }
    return;
}
void evalStack(const char *line)
{
	DLOG("%s\n", line);
	interpret(getStack(), line);	
}
Example #7
0
File: optimize.c Project: jkm/dmd
Expression *CallExp::optimize(int result, bool keepLvalue)
{
    //printf("CallExp::optimize(result = %d) %s\n", result, toChars());
    Expression *e = this;

    // Optimize parameters with keeping lvalue-ness
    if (arguments)
    {
        Type *t1 = e1->type->toBasetype();
        if (t1->ty == Tdelegate) t1 = t1->nextOf();
        assert(t1->ty == Tfunction);
        TypeFunction *tf = (TypeFunction *)t1;
        size_t pdim = Parameter::dim(tf->parameters) - (tf->varargs == 2 ? 1 : 0);
        for (size_t i = 0; i < arguments->dim; i++)
        {
            bool keepLvalue = false;
            if (i < pdim)
            {
                Parameter *p = Parameter::getNth(tf->parameters, i);
                keepLvalue = ((p->storageClass & (STCref | STCout)) != 0);
            }
            Expression *e = (*arguments)[i];
            e = e->optimize(WANTvalue, keepLvalue);
            (*arguments)[i] = e;
        }
    }

    e1 = e1->optimize(result);
    if (keepLvalue)
        return this;

#if 1
    if (result & WANTinterpret)
    {
        Expression *eresult = interpret(NULL);
        if (eresult == EXP_CANT_INTERPRET)
            return e;
        if (eresult && eresult != EXP_VOID_INTERPRET)
            e = eresult;
        else
            error("cannot evaluate %s at compile time", toChars());
    }
#else
    if (e1->op == TOKvar)
    {
        FuncDeclaration *fd = ((VarExp *)e1)->var->isFuncDeclaration();
        if (fd)
        {
            enum BUILTIN b = fd->isBuiltin();
            if (b)
            {
                e = eval_builtin(b, arguments);
                if (!e)                 // failed
                    e = this;           // evaluate at runtime
            }
            else if (result & WANTinterpret)
            {
                Expression *eresult = fd->interpret(NULL, arguments);
                if (eresult && eresult != EXP_VOID_INTERPRET)
                    e = eresult;
                else
                    error("cannot evaluate %s at compile time", toChars());
            }
        }
    }
    else if (e1->op == TOKdotvar && result & WANTinterpret)
    {   DotVarExp *dve = (DotVarExp *)e1;
        FuncDeclaration *fd = dve->var->isFuncDeclaration();
        if (fd)
        {
            Expression *eresult = fd->interpret(NULL, arguments, dve->e1);
            if (eresult && eresult != EXP_VOID_INTERPRET)
                e = eresult;
            else
                error("cannot evaluate %s at compile time", toChars());
        }
    }
#endif
    return e;
}
void interpretPrompt(References* r, CPUStatus* cpu, int* status)
{
    // show prompt ready
    printf("> ");
    fflush(stdout);

    // get new command
    char* line = (char*) calloc(MAX_STRING_LENGTH, sizeof(char));
    if (line == NULL)
    {
        perror("calloc error in interpretPrompt\n");
        exit(EXIT_FAILURE);
    }
    if (fgets(line, MAX_STRING_LENGTH, stdin) == NULL)
    {
        perror("fgets error in interpretPrompt\n");
        exit(EXIT_FAILURE);
    }

    // remove endline
    removeEndLine(line);

    int assembleCode = 0;

    // interpreter commands
    if (stringEquals(line, "regs") == 0)
    {
        printRegisters(cpu);
        *status = RUN_COMMAND;
        free(line);
        return;
    } else if (stringEquals(line, "mem") == 0)
    {
        printMemory(cpu);
        *status = RUN_COMMAND;
        free(line);
        return;
    } else if (stringEquals(line, "exit") == 0)
    {
        *status = EXECUTE_HALT;
        free(line);
        return;
    } else if (stringEquals(line, "show") == 0)
    {
        printInstructions(r);
        *status = RUN_COMMAND;
        free(line);
        return;
    } else
    {
        // assemble One Pass
        assembleCode = onePass(r, cpu, line);
    }

    // execute interpreter
    if (assembleCode == ASSEMBLE_OK ||
        (assembleCode == ASSEMBLE_LABEL && r->currentAddress > 4))
    {
        interpret(r, cpu, status);
    }

    free(line);
}
Example #9
0
void DB_Set::input(string s)
{
	token t = p.parse(s);
	interpret(t);
}
/*
 * This function will cycle through a single record and lookup each field's
 * value that it finds. 
 */
static void output_interpreted_record(const lnode *n, const event *e)
{
	char *ptr, *str = n->message;
	int found, comma = 0;
	int num = n->type;
	struct tm *btm;
	char tmp[32];

	// Reset these because each record could be different
	machine = -1;
	cur_syscall = -1;

	/* Check and see if we start with a node
 	 * If we do, and there is a space in the line
 	 * move the pointer to the first character past
 	 * the space
  	 */
	if (e->node) {
		if ((ptr=strchr(str, ' ')) != NULL) {
			str = ptr+1;
		}
	}

	// First locate time stamp.
	ptr = strchr(str, '(');
	if (ptr == NULL) {
		fprintf(stderr, "can't find time stamp\n");
		return;
	}

	*ptr++ = 0;	/* move to the start of the timestamp */

	// print everything up to it.
	if (num >= 0) {
		const char	* bptr;
		bptr = audit_msg_type_to_name(num);
		if (bptr) {
			if (e->node)
				printf("node=%s ", e->node);
			printf("type=%s msg=audit(", bptr);
			goto no_print;
		}
	} 
	if (e->node)
		printf("node=%s ", e->node);
	printf("%s(", str);
no_print:

	str = strchr(ptr, ')');
	if(str == NULL)
		return;
	*str++ = 0;
	btm = localtime(&e->sec);
	if (btm)
		strftime(tmp, sizeof(tmp), "%x %T", btm);
	else
		strcpy(tmp, "?");
	printf("%s", tmp);
	printf(".%03u:%lu) ", e->milli, e->serial);

	if (n->type == AUDIT_SYSCALL) { 
		a0 = n->a0;
		a1 = n->a1;
	}

	// for each item.
	ausearch_load_interpretations(n);
	found = 0;
	while (str && *str && (ptr = strchr(str, '='))) {
		char *name, *val;
		comma = 0;
		found = 1;

		// look back to last space - this is name
		name = ptr;
		while (*name != ' ' && name > str)
			--name;
		*ptr++ = 0;

		// print everything up to the '='
		printf("%s=", str);

		// Some user messages have msg='uid=500   in this case
		// skip the msg= piece since the real stuff is the uid=
		if (strcmp(name, "msg") == 0) {
			str = ptr;
			continue;
		}

		// In the above case, after msg= we need to trim the ' from uid
		if (*name == '\'')
			name++;

		// get string after = to the next space or end - this is value
		if (*ptr == '\'' || *ptr == '"') {
			str = strchr(ptr+1, *ptr);
			if (str) {
				str++;
				if (*str)
					*str++ = 0;
			}
		} else {
			str = strchr(ptr, ',');
			val = strchr(ptr, ' ');
			if (str && val && (str < val)) {
			// Value side  has commas and another field exists
			// Known: LABEL_LEVEL_CHANGE banners=none,none
			// Known: ROLL_ASSIGN new-role=r,r
			// Known: any MAC LABEL can potentially have commas
				int ftype = auparse_interp_adjust_type(n->type,
								name, val);
				if (ftype == AUPARSE_TYPE_MAC_LABEL) {
					str = val;
					*str++ = 0;
				} else {
					*str++ = 0;
					comma = 1;
				}
			} else if (str && (val == NULL)) {
			// Goes all the way to the end. Done parsing
			// Known: MCS context in PATH rec obj=u:r:t:s0:c2,c7
				int ftype = auparse_interp_adjust_type(n->type,
								name, ptr);
				if (ftype == AUPARSE_TYPE_MAC_LABEL)
					str = NULL;
				else {
					*str++ = 0;
					comma = 1;
				}
			} else if (val) {
			// There is another field, point to next (normal path)
				str = val;
				*str++ = 0;
			}
		}
		// val points to begin & str 1 past end
		val = ptr;
		
		// print interpreted string
		interpret(name, val, comma, n->type);
	}
	ausearch_free_interpretations();

	// If nothing found, just print out as is
	if (!found && ptr == NULL && str)
		safe_print_string(str, 1);

	// If last field had comma, output the rest
	else if (comma)
		safe_print_string(str, 1);
	printf("\n");
}
//*****************************************************************************
//
// Play the Colossal Cave Adventure game using either an Ethernet telnet
// connection or a USB CDC serial connection.
//
//*****************************************************************************
int
main(void)
{
    //
    // Set the clocking to run from the PLL at 80 MHz.
    //
    ROM_SysCtlClockSet(SYSCTL_SYSDIV_2_5 | SYSCTL_USE_PLL | SYSCTL_OSC_MAIN |
                       SYSCTL_XTAL_16MHZ);

    //
    // Enable the UART.
    //
    ROM_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOA);
    GPIOPinConfigure(GPIO_PA0_U0RX);
    GPIOPinConfigure(GPIO_PA1_U0TX);
    ROM_GPIOPinTypeUART(GPIO_PORTA_BASE, GPIO_PIN_0 | GPIO_PIN_1);
    UARTStdioInit(0);

    //
    // Print out a greeting.
    //
    UARTprintf("\033[2JColossal Cave Adventure\n");
    UARTprintf("-----------------------\n");
    UARTprintf("Connect to either the USB virtual COM port or\n");
    UARTprintf("telnet into the Ethernet port in order to play.\n\n");

    //
    // Enable the GPIO that is used for the on-board push button.
    //
    ROM_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOB);
    ROM_GPIOPinTypeGPIOInput(GPIO_PORTB_BASE, GPIO_PIN_4);
    ROM_GPIOPadConfigSet(GPIO_PORTB_BASE, GPIO_PIN_4, GPIO_STRENGTH_2MA,
                         GPIO_PIN_TYPE_STD_WPU);

    //
    // Enable the GPIO that is used for the on-board LED.
    //
    ROM_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOD);
    ROM_GPIOPinTypeGPIOOutput(GPIO_PORTD_BASE, GPIO_PIN_0);
    ROM_GPIOPinWrite(GPIO_PORTD_BASE, GPIO_PIN_0, 0);

    //
    // Configure SysTick for a periodic interrupt.
    //
    ROM_SysTickPeriodSet(ROM_SysCtlClockGet() / SYSTICKHZ);
    ROM_SysTickEnable();
    ROM_SysTickIntEnable();

    //
    // Enable processor interrupts.
    //
    ROM_IntMasterEnable();

    //
    // Initialize the Ethernet and USB interfaces.
    //
    EnetIFInit();
    USBIFInit();

    //
    // Provide a working area to the memory allocator.
    //
    bpool(g_pucPool, sizeof(g_pucPool));

    //
    // Configure the Z-machine interpreter.
    //
    configure(V1, V5);

    //
    // Initialize the Z-machine screen interface.
    //
    initialize_screen();

    //
    // Pre-fill the Z-machine interpreter's cache.
    //
    load_cache();

    //
    // Loop forever.
    //
    while(1)
    {
        //
        // Wait until a connection has been made via either the Ethernet or USB
        // interfaces.
        //
        while(g_ulGameIF == GAME_IF_NONE)
        {
        }

        //
        // Turn on the LED to indicate that the game is in progress.
        //
        ROM_GPIOPinWrite(GPIO_PORTD_BASE, GPIO_PIN_0, GPIO_PIN_0);

        //
        // Loop until the game has been exited.  Repeat this loop if the game
        // exited because the restart button was pressed.
        //
        do
        {
            //
            // Take the Z-machine interpreter out of the halt state.
            //
            halt = 0;

            //
            // Set the restart flag to zero.
            //
            g_ulRestart = 0;

            //
            // Restart the Z-machine interpreter.
            //
            restart();

            //
            // Run the Z-machine interpreter until it halts.
            //
            interpret();
        }
        while(g_ulRestart);

        //
        // Turn off the LED to indicate that the game has finished.
        //
        ROM_GPIOPinWrite(GPIO_PORTD_BASE, GPIO_PIN_0, 0);

        //
        // Close down the Ethernet connection if it was being used to play the
        // game.
        //
        if(g_ulGameIF == GAME_IF_ENET)
        {
            EnetIFClose();
        }

        //
        // Forget the interface used to play the game so that the selection
        // process will be repeated.
        //
        g_ulGameIF = GAME_IF_NONE;
    }
}
Example #12
0
int main(int argc, char const *argv[]) {
    FILE *fp;
    int num_lines;

    script_arr = malloc(sizeof(int) * ARR_LENGTH);
    srand(time(NULL));

    if (argc == 1 || (argc == 2 && argv[1][1] == 'r')) {
        // REPL mode
        REPL = 1;
        if (argc == 2 && argv[1][1] == 'r') REPL = 2;
        fp = stdin;
        num_lines = REPL_LENGTH;
    } else {
        // normal mode
        fp = fopen(argv[1], "r");
        if (!fp) {
            printf("File %s could not be opened :/\n", argv[1]);
            return 1;
        }

        num_lines = count_lines(fp);
    }

    script = (char**)calloc(num_lines, sizeof(char*));

    while (1) {

        // If we're out of preallocated memory for lines, double our memory
        //    Only applies in REPL mode, as memory is allocated beforehad in
        //    file mode
        if (REPL && current_line == num_lines) {
            num_lines *= 2;
            script = (char**)realloc(script, num_lines);
            if (script == NULL) {
                fputs("Out of memory :(", stderr);
                return 1;
            }
            for (int i = num_lines/2; i < num_lines; i++) {
                script[i] = NULL;
            }
        }

        // check for null so that we don't write over old lines in jump commands
        if (script[current_line] == NULL) {
            if (REPL == 1) {
                if (nest_count) {
                    fputs(".. ", stdout);
                } else {
                    fputs(">> ", stdout);
                }
                for (int i = 0; i < nest_count; i++) {
                    fputs("  ", stdout);
                }
            }
            script[current_line] = readLine(fp);
        }

        interpret(script[current_line]);
        current_line++;
    }

    return 0;
}
Example #13
0
void do_buy( CHAR_DATA * ch, char *argument )
{
  char arg[MAX_INPUT_LENGTH];
  int maxgold = 0;

  argument = one_argument( argument, arg );

  if( arg[0] == '\0' )
  {
    send_to_char( "Buy what?\r\n", ch );
    return;
  }

  /* in case of different shop types */
  {
    CHAR_DATA *keeper = NULL;
    OBJ_DATA *obj = NULL;
    int cost = 0;
    int noi = 1;		/* Number of items */
    short mnoi = 20;		/* Max number of items to be bought at once */

    if( ( keeper = find_keeper( ch ) ) == NULL )
      return;

    maxgold = keeper->top_level * 10;

    if( is_number( arg ) )
    {
      noi = atoi( arg );
      argument = one_argument( argument, arg );

      if( noi > mnoi )
      {
	act( AT_TELL, "$n tells you 'I don't sell that many items at"
	    " once.'", keeper, NULL, ch, TO_VICT );
	ch->reply = keeper;
	return;
      }
    }

    obj = get_obj_carry( keeper, arg );

    if( !obj && arg[0] == '#' )
    {
      int onum = 0, oref = atoi( arg + 1 );
      bool ofound = FALSE;

      for( obj = keeper->last_carrying; obj; obj = obj->prev_content )
      {
	if( obj->wear_loc == WEAR_NONE && can_see_obj( ch, obj ) )
	  onum++;

	if( onum == oref )
	{
	  ofound = TRUE;
	  break;
	}
	else if( onum > oref )
	  break;
      }
      if( !ofound )
	obj = NULL;
    }

    cost = ( get_cost( ch, keeper, obj, TRUE ) * noi );
    if( cost <= 0 || !can_see_obj( ch, obj ) )
    {
      act( AT_TELL, "$n tells you 'I don't sell that -- try 'list'.'",
	  keeper, NULL, ch, TO_VICT );
      ch->reply = keeper;
      return;
    }

    if( !IS_OBJ_STAT( obj, ITEM_INVENTORY ) && ( noi > 1 ) )
    {
      char buf[MAX_STRING_LENGTH];
      snprintf( buf, MAX_STRING_LENGTH, "%s", "laugh" );
      interpret( keeper, buf );
      act( AT_TELL, "$n tells you 'I don't have enough of those in stock"
	  " to sell more than one at a time.'", keeper, NULL, ch,
	  TO_VICT );
      ch->reply = keeper;
      return;
    }

    if( ch->gold < cost )
    {
      act( AT_TELL, "$n tells you 'You can't afford to buy $p.'",
	  keeper, obj, ch, TO_VICT );
      ch->reply = keeper;
      return;
    }

    if( IS_SET( obj->extra_flags, ITEM_PROTOTYPE ) && IS_IMMORTAL( ch ) )
    {
      act( AT_TELL,
	  "$n tells you 'This is a only a prototype!  I can't sell you that...'",
	  keeper, NULL, ch, TO_VICT );
      ch->reply = keeper;
      return;
    }

    if( ch->carry_number + get_obj_number( obj ) > can_carry_n( ch ) )
    {
      send_to_char( "You can't carry that many items.\r\n", ch );
      return;
    }

    if( ch->carry_weight + ( get_obj_weight( obj ) * noi )
	+ ( noi > 1 ? 2 : 0 ) > can_carry_w( ch ) )
    {
      send_to_char( "You can't carry that much weight.\r\n", ch );
      return;
    }

    if( noi == 1 )
    {
      if( !IS_OBJ_STAT( obj, ITEM_INVENTORY ) )
	separate_obj( obj );
      act( AT_ACTION, "$n buys $p.", ch, obj, NULL, TO_ROOM );
      act( AT_ACTION, "You buy $p.", ch, obj, NULL, TO_CHAR );
    }
    else
    {
      sprintf( arg, "$n buys %d $p%s.", noi,
	  ( obj->short_descr[strlen( obj->short_descr ) - 1] == 's'
	    ? "" : "s" ) );
      act( AT_ACTION, arg, ch, obj, NULL, TO_ROOM );
      sprintf( arg, "You buy %d $p%s.", noi,
	  ( obj->short_descr[strlen( obj->short_descr ) - 1] == 's'
	    ? "" : "s" ) );
      act( AT_ACTION, arg, ch, obj, NULL, TO_CHAR );
      act( AT_ACTION, "$N puts them into a bag and hands it to you.",
	  ch, NULL, keeper, TO_CHAR );
    }

    ch->gold -= cost;
    keeper->gold += cost;

    if( keeper->gold > maxgold )
    {
      keeper->gold = maxgold / 2;
      act( AT_ACTION, "$n puts some credits into a large safe.", keeper,
	  NULL, NULL, TO_ROOM );
    }

    if( IS_OBJ_STAT( obj, ITEM_INVENTORY ) )
    {
      OBJ_DATA *buy_obj = create_object( obj->pIndexData );
      OBJ_DATA *bag = NULL;

      /*
       * Due to grouped objects and carry limitations in SMAUG
       * The shopkeeper gives you a bag with multiple-buy,
       * and also, only one object needs be created with a count
       * set to the number bought.                -Thoric
       */
      if( noi > 1 )
      {
	bag = create_object( get_obj_index( OBJ_VNUM_SHOPPING_BAG ) );
	/* perfect size bag ;) */
	bag->value[0] = bag->weight + ( buy_obj->weight * noi );
	buy_obj->count = noi;
	obj->pIndexData->count += ( noi - 1 );
	numobjsloaded += ( noi - 1 );
	obj_to_obj( buy_obj, bag );
	obj_to_char( bag, ch );
      }
      else
	obj_to_char( buy_obj, ch );
    }
    else
    {
      obj_from_char( obj );
      obj_to_char( obj, ch );
    }

    return;
  }
}
Example #14
0
File: main.c Project: gvlx/gawk
int
main(int argc, char **argv)
{
	/*
	 * The + on the front tells GNU getopt not to rearrange argv.
	 */
	const char *optlist = "+F:f:v:W;m:bcCd::D::e:E:gh:i:l:L:nNo::Op::MPrStVY";
	bool stopped_early = false;
	int old_optind;
	int i;
	int c;
	char *scan, *src;
	char *extra_stack;
	int have_srcfile = 0;
	SRCFILE *s;

	/* do these checks early */
	if (getenv("TIDYMEM") != NULL)
		do_flags |= DO_TIDY_MEM;

#ifdef HAVE_MCHECK_H
#ifdef HAVE_MTRACE
	if (do_tidy_mem)
		mtrace();
#endif /* HAVE_MTRACE */
#endif /* HAVE_MCHECK_H */

#if defined(LC_CTYPE)
	setlocale(LC_CTYPE, "");
#endif
#if defined(LC_COLLATE)
	setlocale(LC_COLLATE, "");
#endif
#if defined(LC_MESSAGES)
	setlocale(LC_MESSAGES, "");
#endif
#if defined(LC_NUMERIC) && defined(HAVE_LOCALE_H)
	/*
	 * Force the issue here.  According to POSIX 2001, decimal
	 * point is used for parsing source code and for command-line
	 * assignments and the locale value for processing input,
	 * number to string conversion, and printing output.
	 *
	 * 10/2005 --- see below also; we now only use the locale's
	 * decimal point if do_posix in effect.
	 *
	 * 9/2007:
	 * This is a mess. We need to get the locale's numeric info for
	 * the thousands separator for the %'d flag.
	 */
	setlocale(LC_NUMERIC, "");
	init_locale(& loc);
	setlocale(LC_NUMERIC, "C");
#endif
#if defined(LC_TIME)
	setlocale(LC_TIME, "");
#endif

#if MBS_SUPPORT
	/*
	 * In glibc, MB_CUR_MAX is actually a function.  This value is
	 * tested *a lot* in many speed-critical places in gawk. Caching
	 * this value once makes a speed difference.
	 */
	gawk_mb_cur_max = MB_CUR_MAX;
	/* Without MBS_SUPPORT, gawk_mb_cur_max is 1. */

	/* init the cache for checking bytes if they're characters */
	init_btowc_cache();
#endif

	(void) bindtextdomain(PACKAGE, LOCALEDIR);
	(void) textdomain(PACKAGE);

	(void) signal(SIGFPE, catchsig);
#ifdef SIGBUS
	(void) signal(SIGBUS, catchsig);
#endif

	(void) sigsegv_install_handler(catchsegv);
#define STACK_SIZE (16*1024)
	emalloc(extra_stack, char *, STACK_SIZE, "main");
	(void) stackoverflow_install_handler(catchstackoverflow, extra_stack, STACK_SIZE);
#undef STACK_SIZE

	myname = gawk_name(argv[0]);
	os_arg_fixup(&argc, &argv); /* emulate redirection, expand wildcards */

	if (argc < 2)
		usage(EXIT_FAILURE, stderr);

	/* initialize the null string */
	Nnull_string = make_string("", 0);

	/* Robustness: check that file descriptors 0, 1, 2 are open */
	init_fds();

	/* init array handling. */
	array_init();

	/* init the symbol tables */
	init_symbol_table();

	output_fp = stdout;

	/* we do error messages ourselves on invalid options */
	opterr = false;

	/* copy argv before getopt gets to it; used to restart the debugger */  
	save_argv(argc, argv);

	/* initialize global (main) execution context */
	push_context(new_context());

	/* option processing. ready, set, go! */
	for (optopt = 0, old_optind = 1;
	     (c = getopt_long(argc, argv, optlist, optab, NULL)) != EOF;
	     optopt = 0, old_optind = optind) {
		if (do_posix)
			opterr = true;

		switch (c) {
		case 'F':
			add_preassign(PRE_ASSIGN_FS, optarg);
			break;

		case 'E':
			disallow_var_assigns = true;
			/* fall through */
		case 'f':
			/*
			 * Allow multiple -f options.
			 * This makes function libraries real easy.
			 * Most of the magic is in the scanner.
			 *
			 * The following is to allow for whitespace at the end
			 * of a #! /bin/gawk line in an executable file
			 */
			scan = optarg;
			if (argv[optind-1] != optarg)
				while (isspace((unsigned char) *scan))
					scan++;
			src = (*scan == '\0' ? argv[optind++] : optarg);
			(void) add_srcfile((src && src[0] == '-' && src[1] == '\0') ?
					SRC_STDIN : SRC_FILE,
					src, srcfiles, NULL, NULL);

			break;

		case 'v':
			add_preassign(PRE_ASSIGN, optarg);
			break;

		case 'm':
			/*
			 * BWK awk extension.
			 *	-mf nnn		set # fields, gawk ignores
			 *	-mr nnn		set record length, ditto
			 *
			 * As of at least 10/2007, BWK awk also ignores it.
			 */
			if (do_lint)
				lintwarn(_("`-m[fr]' option irrelevant in gawk"));
			if (optarg[0] != 'r' && optarg[0] != 'f')
				warning(_("-m option usage: `-m[fr] nnn'"));
			break;

		case 'b':
			do_binary = true;
			break;

		case 'c':
			do_flags |= DO_TRADITIONAL;
			break;

		case 'C':
			copyleft();
			break;

		case 'd':
			do_flags |= DO_DUMP_VARS;
			if (optarg != NULL && optarg[0] != '\0')
				varfile = optarg;
			break;

		case 'D':
			do_flags |= DO_DEBUG;
			if (optarg != NULL && optarg[0] != '\0')
				command_file = optarg;
			break;

		case 'e':
			if (optarg[0] == '\0')
				warning(_("empty argument to `-e/--source' ignored"));
			else
				(void) add_srcfile(SRC_CMDLINE, optarg, srcfiles, NULL, NULL);
			break;

		case 'g':
			do_flags |= DO_INTL;
			break;

		case 'h':
			/* write usage to stdout, per GNU coding stds */
			usage(EXIT_SUCCESS, stdout);
			break;

		case 'i':
			(void) add_srcfile(SRC_INC, optarg, srcfiles, NULL, NULL);
			break;

		case 'l':
			(void) add_srcfile(SRC_EXTLIB, optarg, srcfiles, NULL, NULL);
			break;

		case 'L':
#ifndef NO_LINT
			do_flags |= DO_LINT_ALL;
			if (optarg != NULL) {
				if (strcmp(optarg, "fatal") == 0)
					lintfunc = r_fatal;
				else if (strcmp(optarg, "invalid") == 0) {
					do_flags &= ~DO_LINT_ALL;
					do_flags |= DO_LINT_INVALID;
				}
			}
			break;

		case 't':
			do_flags |= DO_LINT_OLD;
			break;
#else
		case 'L':
		case 't':
			break;
#endif

		case 'n':
			do_flags |= DO_NON_DEC_DATA;
			break;

		case 'N':
			use_lc_numeric = true;
			break;

		case 'O':
			do_optimize++;
			break;

		case 'p':
			do_flags |= DO_PROFILE;
			/* fall through */
		case 'o':
			do_flags |= DO_PRETTY_PRINT;
			if (optarg != NULL)
				set_prof_file(optarg);
			else
				set_prof_file(DEFAULT_PROFILE);
			break;

		case 'M':
#ifdef HAVE_MPFR
			do_flags |= DO_MPFR;
#endif
			break;

		case 'P':
			do_flags |= DO_POSIX;
			break;

		case 'r':
			do_flags |= DO_INTERVALS;
 			break;
 
		case 'S':
			do_flags |= DO_SANDBOX;
  			break;

		case 'V':
			do_version = true;
			break;

		case 'W':       /* gawk specific options - now in getopt_long */
			fprintf(stderr, _("%s: option `-W %s' unrecognized, ignored\n"),
				argv[0], optarg);
			break;

		case 0:
			/*
			 * getopt_long found an option that sets a variable
			 * instead of returning a letter. Do nothing, just
			 * cycle around for the next one.
			 */
			break;

		case 'Y':
#if defined(YYDEBUG) || defined(GAWKDEBUG)
			if (c == 'Y') {
				yydebug = 2;
				break;
			}
#endif
			/* if not debugging, fall through */
		case '?':
		default:
			/*
			 * If not posix, an unrecognized option stops argument
			 * processing so that it can go into ARGV for the awk
			 * program to see. This makes use of ``#! /bin/gawk -f''
			 * easier.
			 *
			 * However, it's never simple. If optopt is set,
			 * an option that requires an argument didn't get the
			 * argument. We care because if opterr is 0, then
			 * getopt_long won't print the error message for us.
			 */
			if (! do_posix
			    && (optopt == '\0' || strchr(optlist, optopt) == NULL)) {
				/*
				 * can't just do optind--. In case of an
				 * option with >= 2 letters, getopt_long
				 * won't have incremented optind.
				 */
				optind = old_optind;
				stopped_early = true;
				goto out;
			} else if (optopt != '\0') {
				/* Use POSIX required message format */
				fprintf(stderr,
					_("%s: option requires an argument -- %c\n"),
					myname, optopt);
				usage(EXIT_FAILURE, stderr);
			}
			/* else
				let getopt print error message for us */
			break;
		}
		if (c == 'E')	/* --exec ends option processing */
			break;
	}
out:

	if (do_nostalgia)
		nostalgia();

	/* check for POSIXLY_CORRECT environment variable */
	if (! do_posix && getenv("POSIXLY_CORRECT") != NULL) {
		do_flags |= DO_POSIX;
		if (do_lint)
			lintwarn(
	_("environment variable `POSIXLY_CORRECT' set: turning on `--posix'"));
	}

	if (do_posix) {
		use_lc_numeric = true;
		if (do_traditional)	/* both on command line */
			warning(_("`--posix' overrides `--traditional'"));
		else
			do_flags |= DO_TRADITIONAL;
			/*
			 * POSIX compliance also implies
			 * no GNU extensions either.
			 */
	}

	if (do_traditional && do_non_decimal_data) {
		do_flags &= ~DO_NON_DEC_DATA;
		warning(_("`--posix'/`--traditional' overrides `--non-decimal-data'"));
	}

	if (do_lint && os_is_setuid())
		warning(_("running %s setuid root may be a security problem"), myname);

#if MBS_SUPPORT
	if (do_binary) {
		if (do_posix)
			warning(_("`--posix' overrides `--characters-as-bytes'"));
		else
			gawk_mb_cur_max = 1;	/* hands off my data! */
#if defined(LC_ALL)
		setlocale(LC_ALL, "C");
#endif
	}
#endif

	if (do_debug)	/* Need to register the debugger pre-exec hook before any other */
		init_debug();

#ifdef HAVE_MPFR
	/* Set up MPFR defaults, and register pre-exec hook to process arithmetic opcodes */ 
	if (do_mpfr)
		init_mpfr(DEFAULT_PREC, DEFAULT_ROUNDMODE);
#endif

	/* load group set */
	init_groupset();

#ifdef HAVE_MPFR
	if (do_mpfr) {
		mpz_init(Nnull_string->mpg_i);
		Nnull_string->flags = (MALLOC|STRCUR|STRING|MPZN|NUMCUR|NUMBER);
	} else
#endif
	{
		Nnull_string->numbr = 0.0;
		Nnull_string->flags = (MALLOC|STRCUR|STRING|NUMCUR|NUMBER);
	}

	/*
	 * Tell the regex routines how they should work.
	 * Do this before initializing variables, since
	 * they could want to do a regexp compile.
	 */
	resetup();

	/* Set up the special variables */
	init_vars();

	/* Set up the field variables */
	init_fields();

	/* Now process the pre-assignments */
	for (i = 0; i <= numassigns; i++) {
		if (preassigns[i].type == PRE_ASSIGN)
			(void) arg_assign(preassigns[i].val, true);
		else	/* PRE_ASSIGN_FS */
			cmdline_fs(preassigns[i].val);
		efree(preassigns[i].val);
	}

	if (preassigns != NULL)
		efree(preassigns);

	if ((BINMODE & 1) != 0)
		if (os_setbinmode(fileno(stdin), O_BINARY) == -1)
			fatal(_("can't set binary mode on stdin (%s)"), strerror(errno));
	if ((BINMODE & 2) != 0) {
		if (os_setbinmode(fileno(stdout), O_BINARY) == -1)
			fatal(_("can't set binary mode on stdout (%s)"), strerror(errno));
		if (os_setbinmode(fileno(stderr), O_BINARY) == -1)
			fatal(_("can't set binary mode on stderr (%s)"), strerror(errno));
	}

#ifdef GAWKDEBUG
	setbuf(stdout, (char *) NULL);	/* make debugging easier */
#endif
	if (os_isatty(fileno(stdout)))
		output_is_tty = true;

	/* initialize API before loading extension libraries */
	init_ext_api();

	/* load extension libs */
        for (s = srcfiles->next; s != srcfiles; s = s->next) {
                if (s->stype == SRC_EXTLIB)
			load_ext(s->fullpath);
		else if (s->stype != SRC_INC)
			have_srcfile++;
        }

	/* do version check after extensions are loaded to get extension info */
	if (do_version)
		version();

	/* No -f or --source options, use next arg */
	if (! have_srcfile) {
		if (optind > argc - 1 || stopped_early) /* no args left or no program */
			usage(EXIT_FAILURE, stderr);
		(void) add_srcfile(SRC_CMDLINE, argv[optind], srcfiles, NULL, NULL);
		optind++;
	}

	/* Select the interpreter routine */
	init_interpret();

	init_args(optind, argc,
			do_posix ? argv[0] : myname,
			argv);

#if defined(LC_NUMERIC)
	/*
	 * FRAGILE!  CAREFUL!
	 * Pre-initing the variables with arg_assign() can change the
	 * locale.  Force it to C before parsing the program.
	 */
	setlocale(LC_NUMERIC, "C");
#endif
	/* Read in the program */
	if (parse_program(& code_block) != 0)
		exit(EXIT_FAILURE);
	
	if (do_intl)
		exit(EXIT_SUCCESS);

	if (do_lint)
		shadow_funcs();

	if (do_lint && code_block->nexti->opcode == Op_atexit)
		lintwarn(_("no program text at all!"));

	load_symbols();

	if (do_profile)
		init_profiling_signals();

#if defined(LC_NUMERIC)
	/*
	 * See comment above about using locale's decimal point.
	 *
	 * 10/2005:
	 * Bitter experience teaches us that most people the world over
	 * use period as the decimal point, not whatever their locale
	 * uses.  Thus, only use the locale's decimal point if being
	 * posixly anal-retentive.
	 *
	 * 7/2007:
	 * Be a little bit kinder. Allow the --use-lc-numeric option
	 * to also use the local decimal point. This avoids the draconian
	 * strictness of POSIX mode if someone just wants to parse their
	 * data using the local decimal point.
	 */
	if (use_lc_numeric)
		setlocale(LC_NUMERIC, "");
#endif
	
	init_io();
	output_fp = stdout;

	if (do_debug)
		debug_prog(code_block);
	else
		interpret(code_block);

	if (do_pretty_print) {
		dump_prog(code_block);
		dump_funcs();
	}

	if (do_dump_vars)
		dump_vars(varfile);

	if (do_tidy_mem)
		release_all_vars();
	
	/* keep valgrind happier */
	if (extra_stack)
		efree(extra_stack);

	final_exit(exit_val);
	return exit_val;	/* to suppress warnings */
}
Example #15
0
void program_flow( 
        sh_int pvnum,  /* For diagnostic purposes */
	char *source,  /* the actual MOBprog code */
	CHAR_DATA *mob, CHAR_DATA *ch, const void *arg1, const void *arg2 )
{
    CHAR_DATA *rch = NULL;
    char *code, *line;
    char buf[MAX_STRING_LENGTH];
    char control[MAX_INPUT_LENGTH], data[MAX_STRING_LENGTH];

    static int call_level; /* Keep track of nested "mpcall"s */

    int level, eval, check;
    int state[MAX_NESTED_LEVEL], /* Block state (BEGIN,IN,END) */
	cond[MAX_NESTED_LEVEL];  /* Boolean value based on the last if-check */

    sh_int mvnum = mob->pIndexData->vnum;

    if( ++call_level > MAX_CALL_LEVEL )
    {
	bug( "MOBprogs: MAX_CALL_LEVEL exceeded, vnum %d", mob->pIndexData->vnum );
	return;
    }

    /*
     * Reset "stack"
     */
    for ( level = 0; level < MAX_NESTED_LEVEL; level++ )
    {
    	state[level] = IN_BLOCK;
        cond[level]  = TRUE;
    }
    level = 0;

    code = source;
    /*
     * Parse the MOBprog code
     */
    while ( *code )
    {
	bool first_arg = TRUE;
	char *b = buf, *c = control, *d = data;
	/*
	 * Get a command line. We sneakily get both the control word
	 * (if/and/or) and the rest of the line in one pass.
	 */
	while( isspace( *code ) && *code ) code++;
	while ( *code )
	{
	    if ( *code == '\n' || *code == '\r' )
		break;
	    else if ( isspace(*code) )
	    {
		if ( first_arg )
		    first_arg = FALSE;
		else
		    *d++ = *code;
	    }
	    else
	    {
		if ( first_arg )
		   *c++ = *code;
		else
		   *d++ = *code;
	    }
	    *b++ = *code++;
	}
	*b = *c = *d = '\0';

	if ( buf[0] == '\0' )
	    break;
	if ( buf[0] == '*' ) /* Comment */
	    continue;

        line = data;
	/* 
	 * Match control words
	 */
	if ( !str_cmp( control, "if" ) )
	{
	    if ( state[level] == BEGIN_BLOCK )
	    {
		sprintf( buf, "Mobprog: misplaced if statement, mob %d prog %d",
			mvnum, pvnum );
		bug( buf, 0 );
		return;
	    }
	    state[level] = BEGIN_BLOCK;
            if ( ++level >= MAX_NESTED_LEVEL )
            {
		sprintf( buf, "Mobprog: Max nested level exceeded, mob %d prog %d",
			mvnum, pvnum );
		bug( buf, 0 );
		return;
	    }
	    if ( level && cond[level-1] == FALSE ) 
	    {
		cond[level] = FALSE;
		continue;
	    }
	    line = one_argument( line, control );
	    if ( ( check = keyword_lookup( fn_keyword, control ) ) >= 0 )
	    {
		cond[level] = cmd_eval( pvnum, line, check, mob, ch, arg1, arg2, rch );
	    }
	    else
	    {
		sprintf( buf, "Mobprog: invalid if_check (if), mob %d prog %d",
			mvnum, pvnum );
		bug( buf, 0 );
		return;
	    }
	    state[level] = END_BLOCK;
    	}
	else if ( !str_cmp( control, "or" ) )
	{
	    if ( !level || state[level-1] != BEGIN_BLOCK )
	    {
		sprintf( buf, "Mobprog: or without if, mob %d prog %d",
			mvnum, pvnum );
		bug( buf, 0 );
		return;
	    }
	    if ( level && cond[level-1] == FALSE ) continue;
	    line = one_argument( line, control );
	    if ( ( check = keyword_lookup( fn_keyword, control ) ) >= 0 )
	    {
		eval = cmd_eval( pvnum, line, check, mob, ch, arg1, arg2, rch );
	    }
	    else
            {
		sprintf( buf, "Mobprog: invalid if_check (or), mob %d prog %d",
			mvnum, pvnum );
		bug( buf, 0 );
		return;
            }
            cond[level] = (eval == TRUE) ? TRUE : cond[level];
    	}
	else if ( !str_cmp( control, "and" ) )
	{
	    if ( !level || state[level-1] != BEGIN_BLOCK )
	    {
		sprintf( buf, "Mobprog: and without if, mob %d prog %d",
			mvnum, pvnum );
		bug( buf, 0 );
		return;
	    }
	    if ( level && cond[level-1] == FALSE ) continue;
	    line = one_argument( line, control );
	    if ( ( check = keyword_lookup( fn_keyword, control ) ) >= 0 )
	    {
		eval = cmd_eval( pvnum, line, check, mob, ch, arg1, arg2, rch );
	    }
	    else
	    {
		sprintf( buf, "Mobprog: invalid if_check (and), mob %d prog %d",
			mvnum, pvnum );
		bug( buf, 0 );
		return;
	    }
	    cond[level] = (cond[level] == TRUE) && (eval == TRUE) ? TRUE : FALSE;
    	}
	else if ( !str_cmp( control, "endif" ) )
	{
	    if ( !level || state[level-1] != BEGIN_BLOCK )
	    {
		sprintf( buf, "Mobprog: endif without if, mob %d prog %d",
			mvnum, pvnum );
		bug( buf, 0 );
		return;
	    }
	    cond[level] = TRUE;
	    state[level] = IN_BLOCK;
            state[--level] = END_BLOCK;
        }
	else if ( !str_cmp( control, "else" ) )
	{
	    if ( !level || state[level-1] != BEGIN_BLOCK )
	    {
		sprintf( buf, "Mobprog: else without if, mob %d prog %d",
			mvnum, pvnum );
		bug( buf, 0 );
		return;
	    }
	    if ( level && cond[level-1] == FALSE ) continue;
            state[level] = IN_BLOCK;
            cond[level] = (cond[level] == TRUE) ? FALSE : TRUE;
        }
    	else if ( cond[level] == TRUE
	&& ( !str_cmp( control, "break" ) || !str_cmp( control, "end" ) ) )
	{
	    call_level--;
            return;
	}
	else if ( (!level || cond[level] == TRUE) && buf[0] != '\0' )
	{
	    state[level] = IN_BLOCK;
            expand_arg( data, buf, mob, ch, arg1, arg2, rch );
	    if ( !str_cmp( control, "mob" ) )
	    {
		/* 
		 * Found a mob restricted command, pass it to mob interpreter
		 */
		line = one_argument( data, control );
		mob_interpret( mob, line );
	    }
	    else
	    {
		/* 
		 * Found a normal mud command, pass it to interpreter
		 */
		interpret( mob, data );
	    }
	}
    }
    call_level--;
}
Example #16
0
/*======================================================================*/
void printMessage(MsgKind msg)      /* IN - message number */
{
  interpret(msgs[msg].stms);
}
Example #17
0
int main(int argc, char ** argv) {
	long i;
	for (i = 0; i < 256; i++) {
		ssym[i] = nul;
	}
	strcpy(word[0], "begin     ");
	strcpy(word[1], "call      ");
	strcpy(word[2], "const     ");
	strcpy(word[3], "do        ");
	strcpy(word[4], "end       ");
	strcpy(word[5], "if        ");
	strcpy(word[6], "odd       ");
	strcpy(word[7], "procedure ");
	strcpy(word[8], "then      ");
	strcpy(word[9], "var       ");
	strcpy(word[10], "while     ");
	wsym[0] = beginsym;
	wsym[1] = callsym;
	wsym[2] = constsym;
	wsym[3] = dosym;
	wsym[4] = endsym;
	wsym[5] = ifsym;
	wsym[6] = oddsym;
	wsym[7] = procsym;
	wsym[8] = thensym;
	wsym[9] = varsym;
	wsym[10] = whilesym;
	ssym['+'] = plus;
	ssym['-'] = minus;
	ssym['*'] = times;
	ssym['/'] = slash;
	ssym['('] = lparen;
	ssym[')'] = rparen;
	ssym['='] = eql;
	ssym[','] = comma;
	ssym['.'] = period;
	ssym[';'] = semicolon;
	strcpy(mnemonic[lit], "lit");
	strcpy(mnemonic[opr], "opr");
	strcpy(mnemonic[lod], "lod");
	strcpy(mnemonic[sto], "sto");
	strcpy(mnemonic[cal], "cal");
	strcpy(mnemonic[Int], "int");
	strcpy(mnemonic[jmp], "jmp");
	strcpy(mnemonic[jpc], "jpc");
	declbegsys = constsym | varsym | procsym;
	statbegsys = beginsym | callsym | ifsym | whilesym;
	facbegsys = ident | number | lparen;

	if (argc < 2)
		printf("F**k no input file");
	else
	{
		infilename = argv[1];
	}
	if ((infile = fopen(infilename, "r")) == NULL) {
		printf("File %s can't be opened.\n", infilename);
		exit(1);
	}

	err = 0;
	cc = 0; cx = 0; ll = 0; ch = ' '; kk = al; getsym();
	lev = 0; tx = 0;
	block(declbegsys | statbegsys | period);
	if (sym != period) {
		error(9);
	}
	if (err == 0) {
		interpret();
	}
	else {
		printf("errors in PL/0 program\n");
	}
	fclose(infile);
}
Example #18
0
void KSpellConfig::getAvailDictsIspell () {

  langfnames.clear();
  dictcombo->clear();
  langfnames.append(""); // Default
  dictcombo->insertItem( i18n("ISpell Default") );

  // dictionary path
  TQFileInfo dir ("/usr/lib" KDELIBSUFF "/ispell");
  if (!dir.exists() || !dir.isDir())
    dir.setFile ("/usr/local/lib" KDELIBSUFF "/ispell");
  if (!dir.exists() || !dir.isDir())
    dir.setFile ("/usr/local/share/ispell");
  if (!dir.exists() || !dir.isDir())
    dir.setFile ("/usr/share/ispell");
  if (!dir.exists() || !dir.isDir())
    dir.setFile ("/usr/pkg/lib");
  /* TODO get them all instead of just one of them.
   * If /usr/local/lib exists, it skips the rest
  if (!dir.exists() || !dir.isDir())
    dir.setFile ("/usr/local/lib");
  */
  if (!dir.exists() || !dir.isDir()) return;

  kdDebug(750) << "KSpellConfig::getAvailDictsIspell "
	       << dir.filePath() << " " << dir.dirPath() << endl;

  const TQDir thedir (dir.filePath(),"*.hash");
  const TQStringList entryList = thedir.entryList();

  kdDebug(750) << "KSpellConfig" << thedir.path() << "\n" << endl;
  kdDebug(750) << "entryList().count()="
	       << entryList.count() << endl;

  TQStringList::const_iterator entryListItr = entryList.constBegin();
  const TQStringList::const_iterator entryListEnd = entryList.constEnd();

  for ( ; entryListItr != entryListEnd; ++entryListItr)
  {
    TQString fname, lname, hname;
    fname = *entryListItr;

    // remove .hash
    if (fname.endsWith(".hash")) fname.remove (fname.length()-5,5);

    if (interpret (fname, lname, hname) && langfnames.first().isEmpty())
    { // This one is the KDE default language
      // so place it first in the lists (overwrite "Default")

      langfnames.remove ( langfnames.begin() );
      langfnames.prepend ( fname );

      hname=i18n("default spelling dictionary"
                 ,"Default - %1 [%2]").arg(hname).arg(fname);

      dictcombo->changeItem (hname,0);
    }
    else
    {
      langfnames.append (fname);
      hname=hname+" ["+fname+"]";

      dictcombo->insertItem (hname);
    }
  }
}
Example #19
0
void update_links( void )
{
  char_data*            ch;
  link_data*          link;
  text_data*       receive;
  fd_set          read_set;
  fd_set         write_set;
  fd_set          exec_set;
  struct timeval     start;  
  struct timeval   timeout;  

  gettimeofday( &start, NULL );

  timeout.tv_sec  = 1;
  timeout.tv_usec = 0;

  FD_ZERO( &read_set );
  FD_ZERO( &write_set );
  FD_ZERO( &exec_set );

  FD_SET( socket_one, &read_set );
  FD_SET( socket_two, &read_set );

  for( link = link_list; link != NULL; link = link->next ) {
    FD_SET( link->channel, &read_set  );
    FD_SET( link->channel, &write_set );
    FD_SET( link->channel, &exec_set );
    }

  if( (int) select( FD_SETSIZE, &read_set, &write_set, &exec_set,
    &timeout ) < 0 ) 
    panic( "Update links: select" );

  if( FD_ISSET( socket_one, &read_set ) )
    open_link( socket_one );

  if( FD_ISSET( socket_two, &read_set ) )
    open_link( socket_two );

  for( link = link_list; link != NULL; link = link_next ) {
    link_next = link->next;
  
    if( FD_ISSET( link->channel, &exec_set ) ) {
      write( link->player );
      close_socket( link );
      continue;
      }
  
    if( FD_ISSET( link->channel, &read_set ) ) {
      link->idle = 0;
      if( link->player != NULL )
        link->player->timer = current_time;
      if( !read_link( link ) ) {
        write( link->player );
        close_socket( link );
        continue;
        }
      }

    if( link->idle++ > 10000 && link->connected != CON_PLAYING ) {
      send( link, "\n\r\n\r-- CONNECTION TIMEOUT --\n\r" );
      close_socket( link, TRUE );
      }
    }

  pulse_time[ TIME_READ_INPUT ] = stop_clock( start );  
  gettimeofday( &start, NULL );

  for( link = link_list; link != NULL; link = link_next ) {
    link_next = link->next;
    if( link->command = ( ( receive = link->receive ) != NULL ) ) {
      ampersand( receive );
      link->receive  = receive->next;
      link->idle     = 0; 
      if( link->connected == CON_PLAYING ) {
        stop_idling( ch = link->character );
        interpret( link->character, receive->message.text );
        }  
      else
        nanny( link, receive->message.text );
      delete receive;
      }
    }

  pulse_time[ TIME_COMMANDS ] = stop_clock( start );  
  gettimeofday( &start, NULL );

  for( link = link_list; link != NULL; link = link_next ) {
    link_next = link->next;
    if( link->idle%25 == 0 && FD_ISSET( link->channel, &write_set )
      && !process_output( link ) ) {
      write( link->player );
      close_socket( link );
      }
    }  
  
  pulse_time[ TIME_WRITE_OUTPUT ] = stop_clock( start );  

  return;
}
Example #20
0
void KSpellConfig::getAvailDictsAspell () {

  langfnames.clear();
  dictcombo->clear();

  langfnames.append(""); // Default
  dictcombo->insertItem (i18n("ASpell Default"));

  // Aspell now have /usr/lib/aspell as
  // ASPELL_DATADIR default.
  TQFileInfo dir ( ASPELL_DATADIR );
  if (!dir.exists() || !dir.isDir())
    dir.setFile ("/usr/lib" KDELIBSUFF "/aspell-0.60");
  if (!dir.exists() || !dir.isDir())
    dir.setFile ("/usr/local/lib" KDELIBSUFF "/aspell");
  if (!dir.exists() || !dir.isDir())
    dir.setFile ("/usr/share/aspell");
  if (!dir.exists() || !dir.isDir())
    dir.setFile ("/usr/local/share/aspell");
  if (!dir.exists() || !dir.isDir())
    dir.setFile ("/usr/pkg/lib/aspell");
  if (!dir.exists() || !dir.isDir()) return;

  kdDebug(750) << "KSpellConfig::getAvailDictsAspell "
	       << dir.filePath() << " " << dir.dirPath() << endl;

  const TQDir thedir (dir.filePath(),"*");
  const TQStringList entryList = thedir.entryList();

  kdDebug(750) << "KSpellConfig" << thedir.path() << "\n" << endl;
  kdDebug(750) << "entryList().count()="
	       << entryList.count() << endl;

  TQStringList::const_iterator entryListItr = entryList.constBegin();
  const TQStringList::const_iterator entryListEnd = entryList.constEnd();

  for ( ; entryListItr != entryListEnd; ++entryListItr)
  {
    TQString fname, lname, hname;
    fname = *entryListItr;

    // consider only simple dicts without '-' in the name
    // FIXME: may be this is wrong an the list should contain
    // all *.multi files too, to allow using special dictionaries

    // Well, KSpell2 has a better way to do this, but this code has to be
    // cleaned up somehow: since aspell 0.6 we have quite a lot of files in the
    // aspell dictionary that are not dictionaries. These must not be presented as "languages"
    // We only keep
    // *.rws: dictionary
    // *.multi: definition file to load several subdictionaries
    if ( !( fname.endsWith(".rws") || fname.endsWith(".multi") ) ) {
        // remove noise from the language list
      continue;
    }
    if (fname[0] != '.')
    {

      // remove .multi
      if (fname.endsWith(".multi")) fname.remove (fname.length()-6,6);
      // remove .rws
      if (fname.endsWith(".rws")) fname.remove (fname.length()-4,4);

      if (interpret (fname, lname, hname) && langfnames.first().isEmpty())
      { // This one is the KDE default language
        // so place it first in the lists (overwrite "Default")

        langfnames.remove ( langfnames.begin() );
        langfnames.prepend ( fname );

        hname=i18n("default spelling dictionary"
                   ,"Default - %1").arg(hname);

        dictcombo->changeItem (hname,0);
      }
      else
      {
        langfnames.append (fname);
        dictcombo->insertItem (hname);
      }
    }
  }
}
Example #21
0
Expression *CallExp::optimize(int result)
{
    //printf("CallExp::optimize(result = %d) %s\n", result, toChars());
    Expression *e = this;

    // Optimize parameters
    if (arguments)
    {
        for (size_t i = 0; i < arguments->dim; i++)
        {   Expression *e = (*arguments)[i];

            e = e->optimize(WANTvalue);
            (*arguments)[i] = e;
        }
    }

    e1 = e1->optimize(result);
#if 1
    if (result & WANTinterpret)
    {
        Expression *eresult = interpret(NULL);
        if (eresult == EXP_CANT_INTERPRET)
            return e;
        if (eresult && eresult != EXP_VOID_INTERPRET)
            e = eresult;
        else
            error("cannot evaluate %s at compile time", toChars());
    }
#else
    if (e1->op == TOKvar)
    {
        FuncDeclaration *fd = ((VarExp *)e1)->var->isFuncDeclaration();
        if (fd)
        {
            enum BUILTIN b = fd->isBuiltin();
            if (b)
            {
                e = eval_builtin(b, arguments);
                if (!e)                 // failed
                    e = this;           // evaluate at runtime
            }
            else if (result & WANTinterpret)
            {
                Expression *eresult = fd->interpret(NULL, arguments);
                if (eresult && eresult != EXP_VOID_INTERPRET)
                    e = eresult;
                else
                    error("cannot evaluate %s at compile time", toChars());
            }
        }
    }
    else if (e1->op == TOKdotvar && result & WANTinterpret)
    {   DotVarExp *dve = (DotVarExp *)e1;
        FuncDeclaration *fd = dve->var->isFuncDeclaration();
        if (fd)
        {
            Expression *eresult = fd->interpret(NULL, arguments, dve->e1);
            if (eresult && eresult != EXP_VOID_INTERPRET)
                e = eresult;
            else
                error("cannot evaluate %s at compile time", toChars());
        }
    }
#endif
    return e;
}
Example #22
0
void
KSpellConfig::fillDicts( TQComboBox* box, TQStringList* dictionaries )
{
  langfnames.clear();
  if ( box ) {
    if ( iclient == KS_CLIENT_ISPELL ) {
      box->clear();
      langfnames.append(""); // Default
      box->insertItem( i18n("ISpell Default") );

      // dictionary path
      TQFileInfo dir ("/usr/lib/ispell");
      if (!dir.exists() || !dir.isDir())
        dir.setFile ("/usr/local/lib/ispell");
      if (!dir.exists() || !dir.isDir())
        dir.setFile ("/usr/local/share/ispell");
      if (!dir.exists() || !dir.isDir())
        dir.setFile ("/usr/share/ispell");
      if (!dir.exists() || !dir.isDir())
        dir.setFile ("/usr/pkg/lib");
      /* TODO get them all instead of just one of them.
       * If /usr/local/lib exists, it skips the rest
       if (!dir.exists() || !dir.isDir())
       dir.setFile ("/usr/local/lib");
      */
      if (!dir.exists() || !dir.isDir()) return;

      kdDebug(750) << "KSpellConfig::getAvailDictsIspell "
                   << dir.filePath() << " " << dir.dirPath() << endl;

      const TQDir thedir (dir.filePath(),"*.hash");
      const TQStringList entryList = thedir.entryList();

      kdDebug(750) << "KSpellConfig" << thedir.path() << "\n" << endl;
      kdDebug(750) << "entryList().count()="
                   << entryList.count() << endl;

      TQStringList::const_iterator entryListItr = entryList.constBegin();
      const TQStringList::const_iterator entryListEnd = entryList.constEnd();

      for ( ; entryListItr != entryListEnd; ++entryListItr)
      {
        TQString fname, lname, hname;
        fname = *entryListItr;

        // remove .hash
        if (fname.endsWith(".hash")) fname.remove (fname.length()-5,5);

        if (interpret (fname, lname, hname) && langfnames.first().isEmpty())
        { // This one is the KDE default language
          // so place it first in the lists (overwrite "Default")

          langfnames.remove ( langfnames.begin() );
          langfnames.prepend ( fname );

          hname=i18n("default spelling dictionary"
                     ,"Default - %1 [%2]").arg(hname).arg(fname);

          box->changeItem (hname,0);
        }
        else
        {
          langfnames.append (fname);
          hname=hname+" ["+fname+"]";

          box->insertItem (hname);
        }
      }
    } else if ( iclient == KS_CLIENT_HSPELL ) {
      box->clear();
      box->insertItem( i18n("Hebrew") );
      langfnames.append(""); // Default
      sChangeEncoding( KS_E_CP1255 );
    } else if ( iclient == KS_CLIENT_ZEMBEREK ) {
      box->clear();
      box->insertItem( i18n("Turkish") );
      langfnames.append("");
      sChangeEncoding( KS_E_UTF8 );
    }
    else {
      box->clear();
      langfnames.append(""); // Default
      box->insertItem (i18n("ASpell Default"));

      // dictionary path
      // FIXME: use "aspell dump config" to find out the dict-dir
      TQFileInfo dir ("/usr/lib" KDELIBSUFF "/aspell");
      if (!dir.exists() || !dir.isDir())
        dir.setFile ("/usr/lib" KDELIBSUFF "/aspell-0.60");
      if (!dir.exists() || !dir.isDir())
        dir.setFile ("/usr/local/lib" KDELIBSUFF "/aspell");
      if (!dir.exists() || !dir.isDir())
        dir.setFile ("/usr/share/aspell");
      if (!dir.exists() || !dir.isDir())
        dir.setFile ("/usr/local/share/aspell");
      if (!dir.exists() || !dir.isDir())
        dir.setFile ("/usr/pkg/lib/aspell");
      if (!dir.exists() || !dir.isDir()) return;

      kdDebug(750) << "KSpellConfig::getAvailDictsAspell "
                   << dir.filePath() << " " << dir.dirPath() << endl;

      const TQDir thedir (dir.filePath(),"*");
      const TQStringList entryList = thedir.entryList();

      kdDebug(750) << "KSpellConfig" << thedir.path() << "\n" << endl;
      kdDebug(750) << "entryList().count()="
                   << entryList.count() << endl;

      TQStringList::const_iterator entryListItr = entryList.constBegin();
      const TQStringList::const_iterator entryListEnd = entryList.constEnd();

      for ( ; entryListItr != entryListEnd; ++entryListItr)
      {
        TQString fname, lname, hname;
        fname = *entryListItr;

        // consider only simple dicts without '-' in the name
        // FIXME: may be this is wrong an the list should contain
        // all *.multi files too, to allow using special dictionaries

        // Well, KSpell2 has a better way to do this, but this code has to be
        // cleaned up somehow: since aspell 0.6 we have quite a lot of files in the
        // aspell dictionary that are not dictionaries. These must not be presented as "languages"
        // We only keep
        // *.rws: dictionary
        // *.multi: definition file to load several subdictionaries
        if ( !( fname.endsWith(".rws") || fname.endsWith(".multi") ) ) {
            // remove noise from the language list
          continue;
        }
        if (fname[0] != '.')
        {

          // remove .multi
          if (fname.endsWith(".multi")) fname.remove (fname.length()-6,6);
          // remove .rws
          if (fname.endsWith(".rws")) fname.remove (fname.length()-4,4);

          if (interpret (fname, lname, hname) && langfnames.first().isEmpty())
          { // This one is the KDE default language
            // so place it first in the lists (overwrite "Default")

            langfnames.remove ( langfnames.begin() );
            langfnames.prepend ( fname );

            hname=i18n("default spelling dictionary"
                       ,"Default - %1").arg(hname);

            box->changeItem (hname,0);
          }
          else
          {
            langfnames.append (fname);
            box->insertItem (hname);
          }
        }
      }
    }
    int whichelement = langfnames.findIndex(qsdict);
    if ( whichelement >= 0 ) {
      box->setCurrentItem( whichelement );
    }
    if ( dictionaries )
      *dictionaries = langfnames;
  }
}
Example #23
0
File: pl_bf.c Project: jeltz/pl-bf
Datum pl_bf_call_handler(PG_FUNCTION_ARGS)
{
    FmgrInfo flinfo;
    Datum retval, proc_source_datum;
    Form_pg_proc procStruct;
    Form_pg_type typeStruct;
    HeapTuple procTup;
    HeapTuple typeTup;
    bool isnull;
    Oid resultTypeIOParam, returnTypeOID;
    char *proc_source;
    char *a, *p;
    int i;

    // Get the function tuple
    procTup = SearchSysCache(PROCOID, ObjectIdGetDatum(fcinfo->flinfo->fn_oid),
                             0, 0, 0);
    if (!HeapTupleIsValid(procTup)) {
        elog(ERROR, "Cache lookup failed for procedure %u",
             fcinfo->flinfo->fn_oid);
    }
    procStruct = (Form_pg_proc)GETSTRUCT(procTup);
    
    // Get the function source
    proc_source_datum = SysCacheGetAttr(PROCOID, procTup,
                                        Anum_pg_proc_prosrc, &isnull);
    if (isnull) {
        elog(ERROR, "Function source is null");
    }
    proc_source = DatumGetCString(DirectFunctionCall1(textout,
                                                      proc_source_datum));

    // Get the return type tuple
    typeTup = SearchSysCache(TYPEOID, ObjectIdGetDatum(procStruct->prorettype),
                             0, 0, 0);
    if (!HeapTupleIsValid(typeTup)) {
        elog(ERROR, "Cache lookup failed for type %u", procStruct->prorettype);
    }
    typeStruct = (Form_pg_type)GETSTRUCT(typeTup);
    
    resultTypeIOParam = getTypeIOParam(typeTup);
    returnTypeOID = procStruct -> prorettype;

    a = calloc(5000, 1);
    if (!a) {
        elog(ERROR, "BAD A!");
    }

    p = a;
    for (i = 0; i < procStruct->pronargs; i++) {
        p += append_datum(p, fcinfo->arg[i], fcinfo->argnull[i],
                          procStruct->proargtypes.values[i]);
    }
    
    interpret(a, 0, proc_source);

    fmgr_info_cxt(typeStruct->typinput, &flinfo, TopMemoryContext);

    if (returnTypeOID != VOIDOID) {
        if (returnTypeOID == INT4OID) {
            retval = Int32GetDatum(*((int*)a));
        } else {
            SPI_push();
            if (returnTypeOID == BOOLOID)
                retval = InputFunctionCall(&flinfo, a[0] ? "TRUE" : "FALSE",
                                           resultTypeIOParam, -1);
            else {
                retval = InputFunctionCall(&flinfo, pstrdup(a),
                                           resultTypeIOParam, -1);
            }
            SPI_pop();
        }
    }

    ReleaseSysCache(procTup);
    ReleaseSysCache(typeTup);
    free(a);

    SPI_finish();
    
    return retval;
}
static struct rpcent *__get_next_rpcent(struct rpcdata *d)
{
	if (fgets(d->line, BUFSIZ, d->rpcf) == NULL)
		return NULL;
	return interpret(d);
}
Example #25
0
void do_order( CHAR_DATA *ch, char *argument )
{
    char arg[MAX_INPUT_LENGTH];
    CHAR_DATA *victim;
    CHAR_DATA *och;
    CHAR_DATA *och_next;
    bool found;
    bool fAll;

    argument = one_argument( argument, arg );

    if ( arg[0] == '\0' || argument[0] == '\0' )
    {
	send_to_char( "Order whom to do what?\n\r", ch );
	return;
    }

/*
    if ( IS_AFFECTED( ch, AFF_CHARM ) )
    {
	send_to_char( "You feel like taking, not giving, orders.\n\r", ch );
	return;
    }
*/

    act( "$n issues the order '$t'", ch, NULL, NULL, argument, NULL, TO_NOTVICT, SENSE_HEARING );

    if ( !str_cmp( arg, "all" ) )
    {
	fAll   = TRUE;
	victim = NULL;
    }
    else
    {
	fAll   = FALSE;
	if ( ( victim = get_char_room( ch, arg ) ) == NULL )
	{
	    send_to_char( "They aren't here.\n\r", ch );
	    return;
	}

	if ( victim == ch )
	{
	    send_to_char( "Uh, brilliant, ordering yourself?\n\r", ch );
	    return;
	}

	if ( !IS_AFFECTED(victim, AFF_CHARM) || victim->master != ch )
	{
	    send_to_char( "Do it yourself!\n\r", ch );
	    return;
	}
    }

    found = FALSE;
    for ( och = ch->in_room->people; och != NULL; och = och_next )
    {
	och_next = och->next_in_room;

	if ( IS_AFFECTED(och, AFF_CHARM)
	&&   och->master == ch
	&& ( fAll || och == victim ) )
	{
	    found = TRUE;
	    act( "$n orders you to '$t'", ch, och, NULL, argument, NULL, TO_VICT, SENSE_HEARING );
	    interpret( och, argument );
	}
    }

    if ( found )
	send_to_char( "Ok.\n\r", ch );
    else
	send_to_char( "You have no followers here.\n\r", ch );
    return;
}
Example #26
0
int
NetStream::read_stuff()
{

   const unsigned int BUFSIZE= 666666;
   char buff[BUFSIZE];
   int  num_read = 0;

   if (Config::get_var_bool("PRINT_ERRS",false,true)) cerr << "NetStream: ReadStuff called\n";

   // If we do not have a message size (msgSize_), read it from the network
   if (msgSize_ == -1) {

      char packbuf_space[sizeof(int) + 1];
      char *packbuf = packbuf_space;
      int nread = read_from_net(packbuf, sizeof(int));
      if (nread < 0)
         return nread;
      int count = 0;
      UGA_UNPACK_INTEGER(msgSize_, packbuf, count);
      if (Config::get_var_bool("PRINT_ERRS",false,true)) cerr << "NetStream: msgSize is " << msgSize_ << endl;
   }

   // After we know the message size, we read everything that is available on
   // the network, in blocks of BUFSIZE bytes
   do {
      int nread = read_from_net(buff, BUFSIZE);
      if (nread <= 0) 
           return nread;
      else num_read = nread;
      if (msgSize_ > (int)BUFSIZE) {
         //XXX - Better error checking... (I hope)
         if (num_read != (int)BUFSIZE) return num_read;
         _in_queue.put((UGAptr)buff, BUFSIZE);
         msgSize_ -= BUFSIZE;
         if (Config::get_var_bool("PRINT_ERRS",false,true)) cerr << "NetStream: Big message, storing first BUFSIZE bytes (msgSize = " << msgSize_ << endl;
         num_read  = 0;
      }
   } while (num_read == 0);

   // If we have read at least one full message...
   char *tbuf = buff; 
   if (Config::get_var_bool("PRINT_ERRS",false,true)) cerr << "NetStream: processing num_read " << num_read << endl;
   if (num_read >= msgSize_) {
      // For each full message...
      while (num_read && num_read >= msgSize_) {
        _in_queue.put((UGAptr)tbuf, msgSize_); // Stuff the message onto queue
        num_read -= msgSize_;                  // skip to end of this message
        tbuf     += msgSize_;

        if (Config::get_var_bool("PRINT_ERRS",false,true)) cerr << "NetStream: processing full_message " << msgSize_ << " (num_read = " << num_read << endl;

        if (interpret() != 0)                  // Let app decode message
           return 1;  // this flag terminates this NetStream connection

        // If we still have more data to process read the next message size
        if (num_read > 0) {
           int count = 0;
           UGA_UNPACK_INTEGER(msgSize_, tbuf, count); // tbuf is updated
           num_read -= count;
           if (Config::get_var_bool("PRINT_ERRS",false,true)) cerr << "NetStream: next message" << msgSize_ << " (num_read = " << num_read << endl;
        } else
           msgSize_ = -1; // Otherwise, clear the message size
      }
   }
   // Anything left over is less than a complete message, so we store it
   // away in _in_queue and decrease our msgSize_ request accordingly
   _in_queue.put(tbuf, num_read);
   msgSize_ -= num_read;
   if (Config::get_var_bool("PRINT_ERRS",false,true)) cerr << "NetStream: saved for next time " << num_read << " (msgSize = " << msgSize_ << endl;
   return 0;
}
Example #27
0
void char_leaving( char_data * ch, int howleft )
{
   auth_data *old_auth = NULL;

   /*
    * new auth 
    */
   old_auth = get_auth_name( ch->name );
   if( old_auth != NULL )
      if( old_auth->state == AUTH_ONLINE )
         old_auth->state = AUTH_OFFLINE;  /* Logging off */

   ch->pcdata->camp = howleft;

   if( howleft == 0 )   /* Rented at an inn */
   {
      switch ( ch->in_room->area->continent )
      {
         case ACON_ONE:
            ch->pcdata->one = ch->in_room->vnum;
            break;
         default:
            break;
      }
   }

   /*
    * Get 'em dismounted until we finish mount saving -- Blodkai, 4/97 
    */
   if( ch->position == POS_MOUNTED )
      interpret( ch, "dismount" );

   if( ch->morph )
      interpret( ch, "revert" );

   if( ch->desc )
   {
      if( ch->timer > 24 )
         update_connhistory( ch->desc, CONNTYPE_IDLE );
      else
         update_connhistory( ch->desc, CONNTYPE_QUIT );
   }

   list < obj_data * >::iterator iobj;
   for( iobj = ch->carrying.begin(  ); iobj != ch->carrying.end(  ); )
   {
      obj_data *obj = *iobj;
      ++iobj;

      inventory_scan( ch, obj );
   }
   quotes( ch );
   quitting_char = ch;
   ch->save(  );

   if( sysdata->save_pets )
   {
      list < char_data * >::iterator pet;

      for( pet = ch->pets.begin(  ); pet != ch->pets.end(  ); )
      {
         char_data *cpet = *pet;
         ++pet;

         cpet->extract( true );
      }
   }

   /*
    * Synch clandata up only when clan member quits now. --Shaddai 
    */
   if( ch->pcdata->clan )
      save_clan( ch->pcdata->clan );

   saving_char = NULL;
   ch->extract( true );

   for( int x = 0; x < MAX_WEAR; ++x )
      for( int y = 0; y < MAX_LAYERS; ++y )
         save_equipment[x][y] = NULL;
}
Example #28
0
///////////////
// FUNCTIONS //
///////////////
void interpret(CREATURE *crit, char *buf)
{
	CREATURE *xcrit=0;
	OBJECT *obj=0;
	SOCIAL *social=0;
	EXIT *exit=0;
	ROOM *room=0;
	char command[MAX_BUFFER];
	char temp[MAX_BUFFER];
	char *pbuf = command;
	char **arguments;
	char **editargs;
	long i = 0, x = 0;
	long string = 0;
	bool found = 0;
	bool command_ok = 0;
	bool social_ok = 0;

	strcpy(temp,buf);

	while( isspace(*buf) )
		buf++;

	// check for one character commands without spaces to 
	// seperate arguments. - i.e. chat yo = .yo | pip
	if(ispunct(*buf))
		*pbuf++ = *buf++;
	else
	{
		while( !isspace(*buf) && *buf != '\0' )
			*pbuf++ = *buf++;
	}
	*pbuf = '\0';

	while( isspace(*buf) )
		buf++;

	// moved exits before other commands - pip.
	// insert full exit name for abbreviated one.
	for( i = 0; directions[i].abbr; i++)
	{
		if (directions[i].abbr[0] != '\0' && !strcasecmp(command,directions[i].abbr))
		{
			sprintf(command,"%s",directions[i].name);
			break;
		}
	}

	if(!IsDisabled(crit))
	{
		for(exit = crit->in_room->exits; exit; exit = exit->next )
		{
			if( !strindex(exit->name, command) )
			{
				if((room = hashfind_room(exit->to_vnum)) == 0)
				{
					sendcrit(crit,"That exit enters into a domain far too powerful for you to handle.");
					mudlog("exit(%s) in room(%s:%d) has bad to_vnum(%d)!",
						exit->name, crit->in_room->name, crit->in_room->vnum,
						exit->to_vnum);
					continue;
				}

				if (exit->door >= DOOR_CLOSED && !IsImmortal(crit))
				{
					sendcritf(crit,"The %s door is closed.",exit->name);
					return;
				}
				if (crit->rider)
				{
					sendcritf(crit,"You can't move on your own until %s dismounts you.",crit->rider->name);
					return;
				}
				// adding mounts!
				if (crit->mount)
					message("$n ride$x $p on $N.",crit,crit->mount,exit->name);
				else					
					message("$n leave$x $p.",crit,0,exit->name);
				trans(crit,room);
				if (crit->mount)
				{
					trans(crit->mount,crit);
					message("$n arrive$x riding $N.",crit,crit->mount,crit->in_room);
				}
				message("$n $v arrived.",crit,crit->in_room,0);
				interpret(crit,"look");
				return;
			}
		}
	}

	// check if they in editor and get a successful return (edited something)
	// otherwise let them use normal commands
	if(IsEditing(crit))
	{
		if(crit->socket->string)
		{
			if(!(string = string_editor(crit,temp)))
				return;
			
			str_dup(&(*crit->socket->variable), crit->socket->string);
			DeleteObject(crit->socket->string)
			return;
		}
		else
			temp[0] = '\0';

		if(!ValidString(command))
			strcat(temp,"");
		else
			sprintf(temp,"%s %s",command,buf);

		editargs = make_arguments(temp);
		if(editor(crit,editargs))
		{
			free_arguments(editargs);
			return;
		}
		free_arguments(editargs);
	}
Example #29
0
void do_deposit( CHAR_DATA *ch, char *argument )
{
    BANK_DATA              *bank;
    CHAR_DATA              *banker;
    char                    arg1[MAX_INPUT_LENGTH];
    char                    arg2[MAX_INPUT_LENGTH];
    char                    buf[MAX_STRING_LENGTH];
    int                     type = DEFAULT_CURR;
    int                     amount = 0,
        x;
    bool                    dall = FALSE,
        ssave = FALSE;

    /*
     * arg1 == amount
     * arg2 == currency
     */
    if ( !( banker = find_banker( ch ) ) ) {
        send_to_char( "You're not in a bank!\r\n", ch );
        return;
    }

    if ( IS_NPC( ch ) ) {
        snprintf( buf, MSL, "say Sorry, %s, we don't do business with mobs.", ch->name );
        interpret( banker, buf );
        return;
    }

    if ( !argument || argument[0] == '\0' ) {
        send_to_char( "Syntax: deposit [amount] [currency]\n", ch );
        interpret( banker, ( char * ) "say if you need help type &WHELP BANK&D." );
        return;
    }

    if ( !ch->pcdata->bank ) {
        send_to_char( "You don't have any bank account open now.\r\n", ch );
        return;
    }

    /*
     * Just to make sure that we are retrieving the latest bank info, not relying on the
     * stale bank info in pcdata struct 
     */
    bank = find_bank( ch->pcdata->bank->name );
    if ( !bank ) {
        send_to_char( "There is no account by that name!\r\n", ch );
        return;
    }

    argument = one_argument( argument, arg1 );
    argument = one_argument( argument, arg2 );

    if ( arg1 && !str_cmp( arg1, "all" ) )
        dall = TRUE;

    if ( dall && ( !arg2 || arg2[0] == '\0' ) ) {
        for ( x = 0; x < MAX_CURR_TYPE; x++ ) {
            if ( GET_MONEY( ch, x ) > 0 ) {
                ssave = TRUE;
                amount = GET_MONEY( ch, x );

                GET_MONEY( ch, x ) -= amount;
                ch_printf( ch, "You put %d %s coins in the bank.\r\n", amount, curr_types[x] );
                if ( x == CURR_BRONZE ) {
                    bank->bronze += amount;
                    ch_printf( ch, "This brings your account's bronze balance to %d.\r\n",
                               bank->bronze );
                }
                else if ( x == CURR_COPPER ) {
                    bank->copper += amount;
                    ch_printf( ch, "This brings your account's copper balance to %d.\r\n",
                               bank->copper );
                }
                else if ( x == CURR_GOLD ) {
                    bank->gold += amount;
                    ch_printf( ch, "This brings your account's gold balance to %d.\r\n",
                               bank->gold );
                }
                else if ( x == CURR_SILVER ) {
                    bank->silver += amount;
                    ch_printf( ch, "This brings your account's silver balance to %d.\r\n",
                               bank->silver );
                }
            }
        }
        if ( ssave ) {
            save_char_obj( ch );
            bank->lastused = current_time;
            save_bank(  );
        }
        return;
    }

    if ( !dall && !is_number( arg1 ) ) {
        send_to_char( "How much do you wish to deposit.\r\n", ch );
        return;
    }

    if ( !dall )
        amount = atoi( arg1 );

    if ( arg2 )
        type = get_currency_type( arg2 );

    if ( dall )
        amount = GET_MONEY( ch, type );

    if ( amount <= 0 ) {
        send_to_char( "You can't do that.\r\n", ch );
        return;
    }

    if ( amount > GET_MONEY( ch, type ) ) {
        send_to_char( "You don't have that much.\r\n", ch );
        return;
    }

    if ( type != CURR_BRONZE && type != CURR_COPPER && type != CURR_GOLD && type != CURR_SILVER ) {
        send_to_char( "No such currency.\r\n", ch );
        return;
    }

    GET_MONEY( ch, type ) -= amount;
    ch_printf( ch, "You put %d %s coins in the bank.\r\n", amount, curr_types[type] );

    if ( type == CURR_BRONZE ) {
        bank->bronze += amount;
        ch_printf( ch, "This brings your account's bronze balance to %d.\r\n", bank->bronze );
    }
    else if ( type == CURR_COPPER ) {
        bank->copper += amount;
        ch_printf( ch, "This brings your account's copper balance to %d.\r\n", bank->copper );
    }
    else if ( type == CURR_GOLD ) {
        bank->gold += amount;
        ch_printf( ch, "This brings your account's gold balance to %d.\r\n", bank->gold );
    }
    else if ( type == CURR_SILVER ) {
        bank->silver += amount;
        ch_printf( ch, "This brings your account's silver balance to %d.\r\n", bank->silver );
    }
    save_char_obj( ch );
    bank->lastused = current_time;
    save_bank(  );
}
Example #30
0
/*main function*/
int main(void){
    interpret();
    return 0;
}