int main( int argc, char * argv[]) { int buf[Chunk / IntSize]; int bufindex; int chars[256]; int child; char * dir; int html = 0; int fd; double first_start; double last_stop; int lseek_count = 0; char * machine; char name[Chunk]; int next; int seek_control[2]; int seek_feedback[2]; char seek_tickets[Seeks + SeekProcCount]; double seeker_report[3]; off_t size; FILE * stream; off_t words; fd = -1; basetime = (int) time((time_t *) NULL); // BAM! //size = 100; size = 64; dir = "."; machine = ""; /* pick apart args */ for (next = 1; next < argc; next++) if (strcmp(argv[next], "-d") == 0) dir = argv[++next]; else if (strcmp(argv[next], "-s") == 0) size = atol(argv[++next]); else if (strcmp(argv[next], "-m") == 0) machine = argv[++next]; else if (strcmp(argv[next], "-html") == 0) html = 1; else usage(); if (size < 1) usage(); /* sanity check - 32-bit machines can't handle more than 2047 Mb */ if (sizeof(off_t) <= 4 && size > 2047) { fprintf(stderr, "File too large for 32-bit machine, sorry\n"); exit(1); } sprintf(name, "%s/Bonnie.%d", dir, getpid()); /* size is in meg, rounded down to multiple of Chunk */ // !BAM // Change so filesize is only 64KB // size *= (1024 * 1024); // size *= (64); // size = Chunk * (size / Chunk); fprintf(stderr, "File '%s', size: %ld\n", name, size); /* Fill up a file, writing it a char at a time with the stdio putc() call */ fprintf(stderr, "Writing with putc()..."); newfile(name, &fd, &stream, 1); timestamp(); for (words = 0; words < size; words++) // BAM! //if (putc(words & 0x7f, stream) == EOF) if (putc(words, stream) == EOF) io_error("putc"); /* * note that we always close the file before measuring time, in an * effort to force as much of the I/O out as we can */ if (fclose(stream) == -1) io_error("fclose after putc"); get_delta_t(Putc); fprintf(stderr, "done\n"); /* Now read & rewrite it using block I/O. Dirty one word in each block */ newfile(name, &fd, &stream, 0); if (lseek(fd, (off_t) 0, 0) == (off_t) -1) io_error("lseek(2) before rewrite"); fprintf(stderr, "Rewriting..."); timestamp(); bufindex = 0; if ((words = read(fd, (char *) buf, Chunk)) == -1) io_error("rewrite read"); while (words == Chunk) { /* while we can read a block */ if (bufindex == Chunk / IntSize) bufindex = 0; buf[bufindex++]++; if (lseek(fd, (off_t) -words, 1) == -1) io_error("relative lseek(2)"); if (write(fd, (char *) buf, words) == -1) io_error("re write(2)"); if ((words = read(fd, (char *) buf, Chunk)) == -1) io_error("rwrite read"); } /* while we can read a block */ if (close(fd) == -1) io_error("close after rewrite"); get_delta_t(ReWrite); fprintf(stderr, "done\n"); /* Write the whole file from scratch, again, with block I/O */ newfile(name, &fd, &stream, 1); fprintf(stderr, "Writing intelligently..."); for (words = 0; words < Chunk / IntSize; words++) buf[words] = 0; timestamp(); for (words = bufindex = 0; words < (size / Chunk); words++) { /* for each word */ if (bufindex == (Chunk / IntSize)) bufindex = 0; buf[bufindex++]++; if (write(fd, (char *) buf, Chunk) == -1) io_error("write(2)"); } /* for each word */ if (close(fd) == -1) io_error("close after fast write"); get_delta_t(FastWrite); fprintf(stderr, "done\n"); /* read them all back with getc() */ newfile(name, &fd, &stream, 0); for (words = 0; words < 256; words++) chars[words] = 0; fprintf(stderr, "Reading with getc()..."); timestamp(); for (words = 0; words < size; words++) { /* for each byte */ if ((next = getc(stream)) == EOF) io_error("getc(3)"); /* just to fool optimizers */ chars[next]++; } /* for each byte */ if (fclose(stream) == -1) io_error("fclose after getc"); get_delta_t(Getc); fprintf(stderr, "done\n"); /* use the frequency count */ for (words = 0; words < 256; words++) sprintf((char *) buf, "%d", chars[words]); /* Now suck it in, Chunk at a time, as fast as we can */ newfile(name, &fd, &stream, 0); if (lseek(fd, (off_t) 0, 0) == -1) io_error("lseek before read"); fprintf(stderr, "Reading intelligently..."); timestamp(); do { /* per block */ if ((words = read(fd, (char *) buf, Chunk)) == -1) io_error("read(2)"); chars[buf[abs(buf[0]) % (Chunk / IntSize)] & 0x7f]++; } /* per block */ while (words); if (close(fd) == -1) io_error("close after read"); get_delta_t(FastRead); fprintf(stderr, "done\n"); /* use the frequency count */ for (words = 0; words < 256; words++) sprintf((char *) buf, "%d", chars[words]); // !BAM #if 0 /* * Now test random seeks; first, set up for communicating with children. * The object of the game is to do "Seeks" lseek() calls as quickly * as possible. So we'll farm them out among SeekProcCount processes. * We'll control them by writing 1-byte tickets down a pipe which * the children all read. We write "Seeks" bytes with val 1, whichever * child happens to get them does it and the right number of seeks get * done. * The idea is that since the write() of the tickets is probably * atomic, the parent process likely won't get scheduled while the * children are seeking away. If you draw a picture of the likely * timelines for three children, it seems likely that the seeks will * overlap very nicely with the process scheduling with the effect * that there will *always* be a seek() outstanding on the file. * Question: should the file be opened *before* the fork, so that * all the children are lseeking on the same underlying file object? */ if (pipe(seek_feedback) == -1 || pipe(seek_control) == -1) io_error("pipe"); for (next = 0; next < Seeks; next++) seek_tickets[next] = 1; for ( ; next < (Seeks + SeekProcCount); next++) seek_tickets[next] = 0; /* launch some parallel seek processes */ for (next = 0; next < SeekProcCount; next++) { /* for each seek proc */ if ((child = fork()) == -1) io_error("fork"); else if (child == 0) { /* child process */ /* set up and wait for the go-ahead */ close(seek_feedback[0]); close(seek_control[1]); newfile(name, &fd, &stream, 0); srandom(getpid()); fprintf(stderr, "Seeker %d...", next + 1); /* wait for the go-ahead */ if (read(seek_control[0], seek_tickets, 1) != 1) io_error("read ticket"); timestamp(); seeker_report[StartTime] = time_so_far(); /* loop until we read a 0 ticket back from our parent */ while(seek_tickets[0]) { /* until Mom says stop */ doseek((long) (random() % (size / Chunk)), fd, ((lseek_count++ % UpdateSeek) == 0)); if (read(seek_control[0], seek_tickets, 1) != 1) io_error("read ticket"); } /* until Mom says stop */ if (close(fd) == -1) io_error("close after seek"); /* report to parent */ get_delta_t(Lseek); seeker_report[EndTime] = time_so_far(); seeker_report[CPU] = delta[(int) Lseek][CPU]; if (write(seek_feedback[1], seeker_report, sizeof(seeker_report)) != sizeof(seeker_report)) io_error("pipe write"); exit(0); } /* child process */ } /* for each seek proc */ /* * Back in the parent; in an effort to ensure the children get an even * start, wait a few seconds for them to get scheduled, open their * files & so on. */ close(seek_feedback[1]); close(seek_control[0]); sleep(5); fprintf(stderr, "start 'em..."); if (write(seek_control[1], seek_tickets, sizeof(seek_tickets)) != sizeof(seek_tickets)) io_error("write tickets"); /* read back from children */ for (next = 0; next < SeekProcCount; next++) { /* for each child */ if (read(seek_feedback[0], (char *) seeker_report, sizeof(seeker_report)) != sizeof(seeker_report)) io_error("pipe read"); /* * each child writes back its CPU, start & end times. The elapsed time * to do all the seeks is the time the first child started until the * time the last child stopped */ delta[(int) Lseek][CPU] += seeker_report[CPU]; if (next == 0) { /* first time */ first_start = seeker_report[StartTime]; last_stop = seeker_report[EndTime]; } /* first time */ else { /* not first time */ first_start = (first_start < seeker_report[StartTime]) ? first_start : seeker_report[StartTime]; last_stop = (last_stop > seeker_report[EndTime]) ? last_stop : seeker_report[EndTime]; } /* not first time */ if (wait(&child) == -1) io_error("wait"); fprintf(stderr, "done..."); } /* for each child */ fprintf(stderr, "\n"); delta[(int) Lseek][Elapsed] = last_stop - first_start; #endif if (html) write_html(machine, size); else report(machine, size); unlink(name); return 0; }
int main() { int idx, idx2; int cnt[10] = {100, 100, 100, 100, 100, 100, 100, 100, 100, 100}; srandom(time(NULL)); /* reset counter */ TotalAlloc = 0; TotalFree = 0; NullAlloc = 0; NullFree = 0; TotalAllocSize = 0; TITLE(Test Start); for (idx = 0 ; idx < DESTROY_COUNT ; idx ++) { int i; /* Init mm spool */ for (i = 0 ; i < 10 ; i ++) cnt [i] = (random() % 100); /* Init */ upnp_mm_init(cnt); SUBSUBTITLE(Start Round......); /* Dump */ upnp_mm_dump(); for (idx2 = 0 ; idx2 < REINIT_COUNT ; idx2 ++) { int i; SUBSUBTITLE(Reinit mm system......); bzero(my_alloc, (sizeof(void *) * MAX_ALLOC)); for (i = 0 ; i < MAX_TEST_COUNT ; i ++) { allo(); callo(); reallo(); sdup(); hybrid(); ran(); } /* Reinit */ upnp_mm_reinit(); } SUBSUBTITLE(One Round Complete......); /* Dump */ upnp_mm_dump(); /* Destroy */ upnp_mm_destroy(); } /* Dump counter */ TITLE(Test Complete); printf("\tTotalAlloc\t(Total Allocation Count)\t:\t%u\n", TotalAlloc); printf("\tTotalFree\t(Total Free Count)\t\t:\t%u\n", TotalFree); printf("\tNullAlloc\t(Total Count of out-of-memory)\t:\t%u", NullAlloc); if (NullAlloc) printf("\t(This COULD cause daemon stop!)\n"); else printf("\n"); printf("\tNullFree\t(Free with the NULL pointer)\t:\t%u\n", NullFree); printf("\tTotalAllocSize\t(Total Allocated memory size)\t:\t%u\n", TotalAllocSize); printf("\n"); return 0; }
/*------------------------------------------------------------------- * Function: Thread_work * Purpose: Run BARRIER_COUNT barriers * In arg: rank * Global var: barrier * Return val: Ignored */ void *Thread_work(void* rank) { long my_rank = (long) rank; int i, j, seed, index, offset, local_chunk_size, local_sample_size; int local_pointer, s_index, my_segment, col_sum; int *local_data; local_chunk_size = list_size / thread_count; local_sample_size = sample_size / thread_count; // printf("Hi this is thread %ld, I have %d chunks and should do %d samples. \n", my_rank, local_chunk_size, local_sample_size); // Get sample keys randomly from original list srandom(my_rank + 1); offset = my_rank * local_sample_size; for (i = offset; i < (offset + local_sample_size); i++) { do { // If while returns 1, you'll be repeating this seed = (my_rank * local_chunk_size) + (random() % local_chunk_size); } while (Is_used(seed, offset, local_sample_size)); // If the loop breaks (while returns 0), data is clean, assignment sample_keys[i] = list[seed]; index = offset + i; // printf("T%ld, seed = %d\n", my_rank, seed); // printf("T%ld, index = %d, i = %d, key = %d, LCS = %d\n\n", my_rank, index, i, list[seed], local_sample_size); } // Ensure all threads have reached this point, and then let continue pthread_barrier_wait(&barrier); // Parallel count sort the sample keys for (i = offset; i < (offset + local_sample_size); i++) { int mykey = sample_keys[i]; int myindex = 0; for (j = 0; j < sample_size; j++) { if (sample_keys[j] < mykey) { myindex++; } else if (sample_keys[j] == mykey && j < i) { myindex++; } else { } } // printf("##### P%ld Got in FINAL, index = %d, mykey = %d, myindex = %d\n", my_rank, i, mykey, myindex); sorted_keys[myindex] = mykey; } // Ensure all threads have reached this point, and then let continue pthread_barrier_wait(&barrier); // Besides thread 0, every thread generates a splitter // splitters[0] should always be zero if (my_rank != 0) { splitters[my_rank] = (sorted_keys[offset] + sorted_keys[offset-1]) / 2; } // Ensure all threads have reached this point, and then let continue pthread_barrier_wait(&barrier); // Using block partition to retrieve and sort local chunk local_pointer = my_rank * local_chunk_size; local_data = malloc(local_chunk_size * sizeof(int)); j = 0; for (i = local_pointer; i < (local_pointer + local_chunk_size); i++) { local_data[j] = list[i]; j++; } // Quick sort on local data before splitting into buckets qsort(local_data, local_chunk_size, sizeof(int), Int_comp); // index in the splitter array s_index = 1; // starting point of this thread's segment in dist arrays my_segment = my_rank * thread_count; // Generate the original distribution array, loop through each local entry for (i = 0; i < local_chunk_size; i++) { if (local_data[i] < splitters[s_index]) { // If current elem lesser than current splitter // That means it's within this bucket's range, keep looping } else { // Elem is out of bucket's range, time to increase splitter // Keep increasing until you find one that fits // Also make sure if equals we still increment while (s_index < thread_count && local_data[i] >= splitters[s_index]) { s_index++; } } // Add to the raw distribution array, -1 because splitter[0] = 0 raw_dist[my_segment + s_index-1]++; } // Ensure all threads have reached this point, and then let continue pthread_barrier_wait(&barrier); // Generate prefix sum distribution array // (NOTE: does not need to wait for the whole raw_dist to finish, thus no barrier) // For the specific section that this thread is in charge of... // +1 initially because we don't process the first element at all for (i = my_segment; i < (my_segment + thread_count); i++) { if (i == my_segment) { prefix_dist[i] = raw_dist[i]; // printf("Thread %ld ### i = %d, prefix_dist[i] = %d, raw_dist[i] = %d\n", my_rank, i, prefix_dist[i], raw_dist[i]); } else { prefix_dist[i] = raw_dist[i] + prefix_dist[i - 1]; // printf("Thread %ld ### i = %d, prefix_dist[i] = %d, raw_dist[i] = %d , raw_dist[i-1] = %d\n", my_rank, i, prefix_dist[i], raw_dist[i], raw_dist[i - 1]); } } // Ensure all threads have reached this point, and then let continue pthread_barrier_wait(&barrier); // Generate column distribution array // For the specific section that this thread is in charge of... // +1 initially because we don't process the first element at all for (i = my_segment; i < (my_segment + thread_count); i++) { if (i == my_segment) { prefix_dist[i] = raw_dist[i]; // printf("Thread %ld ### i = %d, prefix_dist[i] = %d, raw_dist[i] = %d\n", my_rank, i, prefix_dist[i], raw_dist[i]); } else { prefix_dist[i] = raw_dist[i] + prefix_dist[i - 1]; // printf("Thread %ld ### i = %d, prefix_dist[i] = %d, raw_dist[i] = %d , raw_dist[i-1] = %d\n", my_rank, i, prefix_dist[i], raw_dist[i], raw_dist[i - 1]); } } // Ensure all threads have reached this point, and then let continue pthread_barrier_wait(&barrier); // Generate column sum distribution, each thread responsible for one column col_sum = 0; for (i = 0; i < thread_count; i++) { col_sum += raw_dist[my_rank + i * thread_count]; } col_dist[my_rank] = col_sum; // Ensure all threads have reached this point, and then let continue pthread_barrier_wait(&barrier); // Generate prefix column sum distribution, each thread responsible for one column // This step is very risky to conduct parallelly, I decided to not do that if (my_rank == 0) { for (i = 0; i < thread_count; i++) { if (i == 0) { prefix_col_dist[i] = col_dist[i]; } else { prefix_col_dist[i] = col_dist[i] + prefix_col_dist[i - 1]; } } } // Reassemble the partially sorted list, prepare for retrieval for (i = 0; i < local_chunk_size; i++) { tmp_list[local_pointer + i] = local_data[i]; } // Ensure all threads have reached this point, and then let continue pthread_barrier_wait(&barrier); // Reassemble each thread's partially sorted list based on buckets // Allocate an array based on the column sum of this specific bucket int my_first_D = col_dist[my_rank]; int *my_D = malloc(my_first_D * sizeof(int)); printf("~~~ Thread %ld got here, my_first_D = %d\n", my_rank, my_first_D); int b_index = 0; // int i_manual = 0; // For each thread in the column... for (i = 0; i < thread_count; i++) { // offset = i * local_chunk_size + prefix_dist[i, my_rank-1]; // offset = (i_manual * local_chunk_size) + prefix_dist[i*thread_count + my_rank-1]; if (my_rank == 0) { offset = (i * local_chunk_size); printf("@@@ Thread %ld, prefix_dist = %d, i = %d, offset = %d\n", my_rank, prefix_dist[i*thread_count + my_rank-1], i, offset); } else { offset = (i * local_chunk_size) + prefix_dist[i*thread_count + my_rank-1]; } if (raw_dist[i*thread_count + my_rank] != 0) { // If this row doesn't have anything belong to this bucket // Do not increase i_manual // i_manual++; for (j = 0; j < raw_dist[i*thread_count + my_rank]; j++) { if (my_rank == 0) { printf("### Thread %ld, raw_index = %d, b_index = %d, offset = %d, j = %d, offset+j = %d, elem = %d\n", my_rank, raw_dist[i*thread_count + my_rank], b_index, offset, j, offset + j, tmp_list[offset + j]); } my_D[b_index] = tmp_list[offset + j]; b_index++; } } } // Quick sort on local bucket qsort(my_D, my_first_D, sizeof(int), Int_comp); // Print_list(my_D, my_first_D, "Thread list"); // Ensure all threads have reached this point, and then let continue // pthread_barrier_wait(&barrier); // Merge thread bucket data into final sorted list if (my_rank == 0) { for (i = 0; i < my_first_D; i++) { // printf("~~~ Thread %ld, sorted_list[%d] = %d\n", my_rank, i, my_D[i]); sorted_list[i] = my_D[i]; } } else { offset = prefix_col_dist[my_rank-1]; for (i = 0; i < my_first_D; i++) { // printf("~~~ Thread %ld, offset = %d, sorted_list[%d] = %d\n", my_rank, offset, offset+i, my_D[i]); sorted_list[offset + i] = my_D[i]; } } return NULL; } /* Thread_work */
int main(int ac, char **av) { int i = 1; const char *name; struct stat tmpstat; if (ac > i && av[i][0] == '-') { switch (av[i++][1]) { case 'o': input_mode = ask_new; break; case 's': input_mode = ask_silent; valid_stdin = isatty(0) && isatty(1) && isatty(2); break; case 'd': input_mode = set_default; break; case 'D': input_mode = set_default; defconfig_file = av[i++]; if (!defconfig_file) { printf("%s: No default config file specified\n", av[0]); exit(1); } break; case 'n': input_mode = set_no; break; case 'm': input_mode = set_mod; break; case 'y': input_mode = set_yes; break; case 'r': input_mode = set_random; srandom(time(NULL)); break; case 'h': case '?': printf("%s [-o|-s] config\n", av[0]); exit(0); } } name = av[i]; if (!name) { printf("%s: configuration file missing\n", av[0]); } conf_parse(name); //zconfdump(stdout); switch (input_mode) { case set_default: if (!defconfig_file) /* Freetz: We don't have .defconfig file, create config from defaults */ /* defconfig_file = conf_get_default_confname(); */ break; case ask_silent: if (stat(".config", &tmpstat)) { printf("***\n" "*** You have not yet configured Freetz!\n" "***\n" "*** Please run some configurator (e.g. \"make oldconfig\" or\n" "*** \"make menuconfig\" or \"make config\").\n" "***\n"); exit(1); } case ask_all: case ask_new: conf_read(NULL); break; default: break; } if (input_mode != ask_silent) { rootEntry = &rootmenu; conf(&rootmenu); if (input_mode == ask_all) { input_mode = ask_silent; valid_stdin = 1; } } do { conf_cnt = 0; check_conf(&rootmenu); } while (conf_cnt); if (conf_write(NULL)) { fprintf(stderr, "\n*** Error during writing of the Freetz configuration.\n\n"); return 1; } return 0; }
int main() { int status = 0; srandom(17); status += test_pluq_structured(37, 37); status += test_pluq_structured(63, 63); status += test_pluq_structured(64, 64); status += test_pluq_structured(65, 65); status += test_pluq_structured(128, 128); status += test_pluq_structured(37, 137); status += test_pluq_structured(65, 5); status += test_pluq_structured(128, 18); status += test_pluq_full_rank(13, 13); status += test_pluq_full_rank(37, 37); status += test_pluq_full_rank(63, 63); status += test_pluq_full_rank(64, 64); status += test_pluq_full_rank(65, 65); status += test_pluq_full_rank(97, 97); status += test_pluq_full_rank(128, 128); status += test_pluq_full_rank(150, 150); status += test_pluq_full_rank(256, 256); status += test_pluq_full_rank(1024, 1024); status += test_pluq_full_rank(13, 11); status += test_pluq_full_rank(37, 39); status += test_pluq_full_rank(64, 164); status += test_pluq_full_rank(97, 92); status += test_pluq_full_rank(128, 121); status += test_pluq_full_rank(150, 153); status += test_pluq_full_rank(256, 258); status += test_pluq_full_rank(1024, 1023); status += test_pluq_half_rank(64, 64); status += test_pluq_half_rank(65, 65); status += test_pluq_half_rank(66, 66); status += test_pluq_half_rank(127, 127); status += test_pluq_half_rank(129, 129); status += test_pluq_half_rank(148, 148); status += test_pluq_half_rank(132, 132); status += test_pluq_half_rank(256, 256); status += test_pluq_half_rank(1024, 1024); status += test_pluq_half_rank(129, 127); status += test_pluq_half_rank(132, 136); status += test_pluq_half_rank(256, 251); status += test_pluq_half_rank(1024, 2100); status += test_pluq_random(63, 63); status += test_pluq_random(64, 64); status += test_pluq_random(65, 65); status += test_pluq_random(128, 128); status += test_pluq_random(128, 131); status += test_pluq_random(132, 731); status += test_pluq_random(150, 150); status += test_pluq_random(252, 24); status += test_pluq_random(256, 256); status += test_pluq_random(1024, 1022); status += test_pluq_random(1024, 1024); status += test_pluq_random(128, 1280); status += test_pluq_random(128, 130); status += test_pluq_random(132, 132); status += test_pluq_random(150, 151); status += test_pluq_random(252, 2); status += test_pluq_random(256, 251); status += test_pluq_random(1024, 1025); status += test_pluq_random(1024, 1021); if (!status) { printf("All tests passed.\n"); return 0; } else { return -1; } }
int main(int argc, char **argv) { int opt; int fd; int max_blocks = 0; char *endptr; unsigned int seed = 123; int reboot = 0; int direct_io = 0; long int test = 1; long int tmp; int ret = 0; int flags = O_RDWR|O_CREAT|O_TRUNC; if (argc < 2) usage(); fd = open("/dev/urandom", O_RDONLY); if (fd >= 0) { read(fd, &seed, sizeof(seed)); close(fd); } while ((opt = getopt(argc, argv, "s:rdt:")) != -1) { switch (opt) { case 's': tmp = strtol(optarg, &endptr, 10); if (tmp == LONG_MAX || endptr == optarg) usage(); seed = tmp; break; case 'r': reboot = 1; break; case 'd': direct_io = 1; break; case 't': test = strtol(optarg, &endptr, 10); if (test == LONG_MAX || endptr == optarg) usage(); break; default: usage(); } } if (optind >= argc) usage(); fname = argv[optind]; if (!fname) usage(); printf("Random seed is %u\n", seed); srandom(seed); if (direct_io) { flags |= O_DIRECT; ret = posix_memalign((void **)&buf, getpagesize(), 4096); if (ret) buf = NULL; } else { buf = malloc(4096); } if (!buf) { fprintf(stderr, "Error allocating buf: %d\n", errno); return 1; } test_fd = open(fname, flags, 0644); if (test_fd < 0) { fprintf(stderr, "Error opening file %d (%s)\n", errno, strerror(errno)); return 1; } switch (test) { case 1: ret = test_one(&max_blocks); break; case 2: ret = test_two(&max_blocks); break; case 3: ret = test_three(&max_blocks, 0, 0, 0, 0); break; case 4: ret = test_three(&max_blocks, 1, 0, 0, 0); break; case 5: ret = test_three(&max_blocks, 0, 1, 0, 0); break; case 6: ret = test_three(&max_blocks, 1, 1, 0, 0); break; case 7: ret = test_three(&max_blocks, 0, 0, 1, 0); break; case 8: ret = test_three(&max_blocks, 1, 0, 1, 0); break; case 9: ret = test_three(&max_blocks, 0, 1, 1, 0); break; case 10: ret = test_three(&max_blocks, 1, 1, 1, 0); break; case 11: ret = test_three(&max_blocks, 0, 0, 0, 1); break; case 12: ret = test_three(&max_blocks, 0, 1, 0, 1); break; case 13: ret = test_three(&max_blocks, 0, 0, 1, 1); break; case 14: ret = test_three(&max_blocks, 0, 1, 1, 1); break; case 15: ret = test_three(&max_blocks, 1, 0, 0, 1); break; case 16: ret = test_three(&max_blocks, 1, 1, 0, 1); break; case 17: ret = test_three(&max_blocks, 1, 0, 1, 1); break; case 18: ret = test_three(&max_blocks, 1, 1, 1, 1); break; case 19: ret = test_five(); break; case 20: ret = test_six(); break; case 21: /* * This is just a perf test, keep moving it down so it's always * the last test option. */ reboot = 0; ret = test_four(&max_blocks); goto out; default: usage(); } if (ret) goto out; if (fsync(test_fd)) { fprintf(stderr, "Fsync failed, test results will be invalid: " "%d\n", errno); return 1; } if (reboot) system("reboot -fn"); out: free(buf); close(test_fd); return ret; }
int main(int argc, char **argv) { if(argc < 4) { printf("Usage\n"); printf(" test random <heap> <vertices> [seed] [edgechance] [maxweight] [source]\n"); printf(" test dkmax <heap> <vertices>\n"); printf(" test dkmax2 <heap> <vertices>\n"); printf(" Heaptypes: bin, fib, pq\n"); exit(1); } char *heap_name = malloc(10*sizeof(char)); unsigned int (*dijkstra)(unsigned int num_vertices, unsigned int source, unsigned int * w, unsigned int ** edges, unsigned int *bops); if(strcmp(argv[2], "bin") == 0) { heap_name = "Binary"; dijkstra = dijkstra_bin; } else if(strcmp(argv[2], "fib") == 0) { heap_name = "Fibonacci"; dijkstra = dijkstra_fib; } else if(strcmp(argv[2], "pq") == 0) { heap_name = "Primitive"; dijkstra = dijkstra_pq; } else { printf("Unknown heap type '%s'\n", argv[2]); exit(2); } unsigned int vertices = (unsigned int)strtoul(argv[3], NULL, 10); unsigned int source = 0; unsigned int *weights; unsigned int **edges = malloc(vertices * sizeof(unsigned int *)); if(strcmp(argv[1], "random") == 0) { unsigned int seed; if(argc > 4 && argv[4]) { seed = (unsigned int)strtoul(argv[4], NULL, 10); srandom(seed); } else { srandom(time(NULL)); seed = random()%99999999; } unsigned int edge_chance = 15; if(argc > 5) edge_chance = (unsigned int)strtoul(argv[5], NULL, 10); unsigned int max_weight = 20; if(argc > 6) max_weight = (unsigned int)strtoul(argv[6], NULL, 10); source = random()%vertices; if(argc > 7) source = (unsigned int)strtoul(argv[7], NULL, 10); weights = generate_graph(vertices, edge_chance, max_weight, seed); printf("Reticulating splines.\n"); unsigned int *t_edges = malloc(vertices * sizeof(unsigned int)); int i, j; for (i = 0; i < vertices; i++) { unsigned int count = 0; for (j = 0; j < vertices; j++) if (weights[(i * vertices) + j]) t_edges[++count] = j; edges[i] = malloc((count+1) * sizeof(unsigned int)); edges[i][0] = count; for (j = 1; j <= count; j++) edges[i][j] = t_edges[j]; } free(t_edges); } else if(strcmp(argv[1], "dkmax") == 0) { weights = generate_decrease_key_max(vertices); printf("Reticulating splines.\n"); unsigned int *t_edges = malloc(vertices * sizeof(unsigned int)); int i, j; for (i = 0; i < vertices; i++) { unsigned int count = 0; for (j = 0; j < vertices; j++) if (weights[(i * vertices) + j]) t_edges[++count] = j; edges[i] = malloc((count+1) * sizeof(unsigned int)); edges[i][0] = count; for (j = 1; j <= count; j++) edges[i][j] = t_edges[j]; } //free(t_edges); } else if (strcmp(argv[1], "dkmax2") == 0){ weights = generate_decrease_key_max2(vertices); printf("Reticulating splines.\n"); unsigned int *t_edges = malloc(vertices * sizeof(unsigned int)); edges = malloc(vertices * sizeof(unsigned int *)); int i, j; for (i = 0; i < vertices; i++) { unsigned int count = 0; for (j = 0; j < vertices; j++){ if (weights[(i * vertices) + j]) t_edges[++count] = j; } edges[i] = malloc((count+1) * sizeof(unsigned int)); edges[i][0] = count; for (j = 1; j <= count; j++) edges[i][j] = t_edges[j]; } //free(t_edges); } else { printf("Unknown graph algorithm '%s'\n", argv[1]); exit(3); } clock_t start; clock_t end; unsigned int decrease_key_calls; printf("Calculating distances.\n"); printf(" Heap: %10s Source: %8d\n", heap_name, source); start = clock(); decrease_key_calls = dijkstra(vertices, source, weights, edges, NULL); end = clock(); double running_time = (double) (end-start) / (double) CLOCKS_PER_SEC; printf(" Time: %10gs dec. key calls: %8d\n", running_time, decrease_key_calls); log_results(heap_name, argv[1], vertices, decrease_key_calls, running_time); }
static void login_query() { char uid [IDLEN + 1], passbuf[PASSLEN]; int attempts; char genbuf [200]; resolve_utmp(); attempts = utmpshm->number; clear(); #ifdef CAMERA film_out(time(0) % 5, 0); #else show_file("etc/Welcome0", 0, 20, ONLY_COLOR); #endif if (attempts >= MAXACTIVE) { pressanykey("目前站上人數已達上限,請您稍後再來。"); oflush(); sleep(1); exit(1); } attempts = 0; while (1) { if (attempts++ >= LOGINATTEMPTS) { more("etc/goodbye", NA); pressanykey_old("錯誤太多次,掰掰~~~~~"); exit(1); } uid[0] = '\0'; getdata(22, 2, "您的代號:", uid, IDLEN + 1, DOECHO, 0); if (strcasecmp(uid, str_new) == 0) { #ifdef LOGINASNEW DL_func("SO/register.so:va_new_register", 0); break; #else pressanykey("本系統目前無法以 new 註冊, 請用 guest 進入"); continue; #endif } else if (uid[0] == '\0' /* || !dosearchuser(uid) */ ) pressanykey(err_uid); else if (belong(FN_DISABLED, uid)) { pressanykey("該 ID 為本站禁止上站之 ID"); logattempt(uid, '*'); } else if (strcmp(uid, STR_GUEST)) { getdata(22, 30, "您的密碼:", passbuf, PASSLEN, PASS, 0); passbuf[8] = '\0'; if (!dosearchuser(uid)) { logattempt(uid, '!'); pressanykey(ERR_PASSWD); } else if (!chkpasswd(cuser.passwd, passbuf)) { logattempt(cuser.userid, '-'); pressanykey(ERR_PASSWD); } else { /* SYSOP gets all permission bits */ if (!strcasecmp(cuser.userid, str_sysop)) cuser.userlevel = ~0; logattempt(cuser.userid, ' '); break; } } else { /* guest 的話 */ #ifdef LOGINASGUEST cuser.userlevel = 0; cuser.uflag = COLOR_FLAG | PAGER_FLAG | BRDSORT_FLAG | MOVIE_FLAG; break; #else pressanykey("本站不提供 guest 上站"); continue; #endif } } multi_user_check(); sethomepath(genbuf, cuser.userid); mkdir(genbuf, 0755); srand(time(0) ^ getpid() ^ (getpid() << 10)); srandom(time(0) ^ getpid() ^ (getpid() << 10)); }
void build_connectivity_graph( void ) { int i, j, k, l, n_op, n_ef, na, nd, ef, ef_, m, l_; Action *a; int *same_effects, sn; Bool *had_effects; ActionEffect *e, *e_, *e__; struct timeb tp; ftime( &tp ); srandom( tp.millitm ); gnum_ft_conn = gnum_relevant_facts; gnum_op_conn = gnum_actions; gft_conn = ( FtConn * ) calloc( gnum_ft_conn, sizeof( FtConn ) ); gop_conn = ( OpConn * ) calloc( gnum_op_conn, sizeof( OpConn ) ); gef_conn = ( EfConn * ) calloc( lnum_effects, sizeof( EfConn ) ); gnum_ef_conn = 0; same_effects = ( int * ) calloc( lnum_effects, sizeof( int ) ); had_effects = ( Bool * ) calloc( lnum_effects, sizeof( Bool ) ); for ( i = 0; i < gnum_ft_conn; i++ ) { gft_conn[i].num_PC = 0; gft_conn[i].num_A = 0; gft_conn[i].num_D = 0; gft_conn[i].rand = random() % BIG_INT; } for ( i = 0; i < gnum_op_conn; i++ ) { gop_conn[i].num_E = 0; } for ( i = 0; i < lnum_effects; i++ ) { gef_conn[i].num_PC = 0; gef_conn[i].num_A = 0; gef_conn[i].num_D = 0; gef_conn[i].num_I = 0; gef_conn[i].removed = FALSE; } n_op = 0; n_ef = 0; for ( a = gactions; a; a = a->next ) { gop_conn[n_op].action = a; gop_conn[n_op].E = ( int * ) calloc( a->num_effects, sizeof( int ) ); for ( i = 0; i < a->num_effects; i++ ) { had_effects[i] = FALSE; } for ( i = 0; i < a->num_effects; i++ ) { if ( had_effects[i] ) { continue; } had_effects[i] = TRUE; e = &(a->effects[i]); gop_conn[n_op].E[gop_conn[n_op].num_E++] = n_ef; gef_conn[n_ef].op = n_op; gef_conn[n_ef].PC = ( int * ) calloc( e->num_conditions + a->num_preconds, sizeof( int ) ); for ( j = 0; j < a->num_preconds; j++ ) { for ( k = 0; k < gef_conn[n_ef].num_PC; k++ ) { if ( gef_conn[n_ef].PC[k] == a->preconds[j] ) break; } if ( k < gef_conn[n_ef].num_PC ) continue; gef_conn[n_ef].PC[gef_conn[n_ef].num_PC++] = a->preconds[j]; } for ( j = 0; j < e->num_conditions; j++ ) { for ( k = 0; k < gef_conn[n_ef].num_PC; k++ ) { if ( gef_conn[n_ef].PC[k] == e->conditions[j] ) break; } if ( k < gef_conn[n_ef].num_PC ) continue; gef_conn[n_ef].PC[gef_conn[n_ef].num_PC++] = e->conditions[j]; } sn = 0; for ( j = i + 1; j < a->num_effects; j++ ) { if ( had_effects[j] ) { continue; } e_ = &(a->effects[j]); /* check conditions */ for ( k = 0; k < e_->num_conditions; k++ ) { for ( l = 0; l < e->num_conditions; l++ ) { if ( e_->conditions[k] == e->conditions[l] ) { break; } } if ( l == e->num_conditions ) { break; } } if ( k < e_->num_conditions ) { continue; } if ( e->num_conditions == e_->num_conditions ) { same_effects[sn++] = j; } } na = e->num_adds; nd = e->num_dels; for ( j = 0; j < sn; j++ ) { na += a->effects[same_effects[j]].num_adds; nd += a->effects[same_effects[j]].num_dels; } gef_conn[n_ef].A = ( int * ) calloc( na, sizeof( int ) ); gef_conn[n_ef].D = ( int * ) calloc( nd, sizeof( int ) ); for ( j = 0; j < e->num_adds; j++ ) { for ( k = 0; k < gef_conn[n_ef].num_A; k++ ) { if ( gef_conn[n_ef].A[k] == e->adds[j] ) break; } if ( k < gef_conn[n_ef].num_A ) continue; /* exclude already true adds */ for ( k = 0; k < gef_conn[n_ef].num_PC; k++ ) { if ( gef_conn[n_ef].PC[k] == e->adds[j] ) break; } if ( k < gef_conn[n_ef].num_PC ) continue; gef_conn[n_ef].A[gef_conn[n_ef].num_A++] = e->adds[j]; } for ( j = 0; j < e->num_dels; j++ ) { for ( k = 0; k < gef_conn[n_ef].num_D; k++ ) { if ( gef_conn[n_ef].D[k] == e->dels[j] ) break; } if ( k < gef_conn[n_ef].num_D ) continue; /* exclude re-added dels; check against *all* * adds to be integrated. */ for ( k = 0; k < e->num_adds; k++ ) { if ( e->adds[k] == e->dels[j] ) break; } if ( k < e->num_adds ) continue; for ( l = 0; l < sn; l++ ) { e_ = &(a->effects[same_effects[l]]); for ( k = 0; k < e_->num_adds; k++ ) { if ( e_->adds[k] == e->dels[j] ) break; } if ( k < e_->num_adds ) break; } if ( l < sn ) continue; gef_conn[n_ef].D[gef_conn[n_ef].num_D++] = e->dels[j]; } for ( j = 0; j < sn; j++ ) { e_ = &(a->effects[same_effects[j]]); for ( l = 0; l < e_->num_adds; l++ ) { for ( k = 0; k < gef_conn[n_ef].num_A; k++ ) { if ( gef_conn[n_ef].A[k] == e_->adds[l] ) break; } if ( k < gef_conn[n_ef].num_A ) continue; for ( k = 0; k < gef_conn[n_ef].num_PC; k++ ) { if ( gef_conn[n_ef].PC[k] == e_->adds[l] ) break; } if ( k < gef_conn[n_ef].num_PC ) continue; gef_conn[n_ef].A[gef_conn[n_ef].num_A++] = e_->adds[l]; } for ( l = 0; l < e_->num_dels; l++ ) { for ( k = 0; k < gef_conn[n_ef].num_D; k++ ) { if ( gef_conn[n_ef].D[k] == e_->dels[l] ) break; } if ( k < gef_conn[n_ef].num_D ) continue; /* exclude re-added dels; check against *all* * adds to be integrated. */ for ( k = 0; k < e->num_adds; k++ ) { if ( e->adds[k] == e_->dels[l] ) break; } if ( k < e->num_adds ) continue; for ( l_ = 0; l_ < sn; l_++ ) { e__ = &(a->effects[same_effects[l_]]); for ( k = 0; k < e__->num_adds; k++ ) { if ( e__->adds[k] == e_->dels[l] ) break; } if ( k < e__->num_adds ) break; } if ( l_ < sn ) continue; gef_conn[n_ef].D[gef_conn[n_ef].num_D++] = e_->dels[l]; } } for ( j = 0; j < sn; j++ ) { had_effects[same_effects[j]] = TRUE; } n_ef++; gnum_ef_conn++; }/* ende all a->effects */ if ( gop_conn[n_op].num_E >= 1 ) { /* CHECK EMPTY EFFECTS! * * two step process --- first, remove all effects that are entirely empty. * second, check if all remaining effects are illegal * or only delete: * in that case, the op will never do any good so we * remove all its effects. */ i = 0; while ( i < gop_conn[n_op].num_E ) { if ( gef_conn[gop_conn[n_op].E[i]].num_A != 0 || gef_conn[gop_conn[n_op].E[i]].num_D != 0 ) { i++; continue; } /* we keep it in the gef_conn (seems easier), * but mark it as removed, which will exclude it from everything. */ gef_conn[gop_conn[n_op].E[i]].removed = TRUE; for ( j = i; j < gop_conn[n_op].num_E - 1; j++ ) { gop_conn[n_op].E[j] = gop_conn[n_op].E[j+1]; } gop_conn[n_op].num_E--; } m = 0; for ( i = 0; i < gop_conn[n_op].num_E; i++ ) { if ( gef_conn[gop_conn[n_op].E[i]].num_A == 0 ) { m++; } } if ( m == gop_conn[n_op].num_E ) { /* all remaining effects solely-deleters. */ for ( i = 0; i < gop_conn[n_op].num_E; i++ ) { gef_conn[gop_conn[n_op].E[i]].removed = TRUE; } gop_conn[n_op].num_E = 0; } } /* setup implied effects info */ if ( gop_conn[n_op].num_E > 1 ) { for ( i = 0; i < gop_conn[n_op].num_E; i++ ) { ef = gop_conn[n_op].E[i]; gef_conn[ef].I = ( int * ) calloc( gop_conn[n_op].num_E, sizeof( int ) ); gef_conn[ef].num_I = 0; } for ( i = 0; i < gop_conn[n_op].num_E - 1; i++ ) { ef = gop_conn[n_op].E[i]; for ( j = i+1; j < gop_conn[n_op].num_E; j++ ) { ef_ = gop_conn[n_op].E[j]; /* ef ==> ef_ ? */ for ( k = 0; k < gef_conn[ef_].num_PC; k++ ) { for ( l = 0; l < gef_conn[ef].num_PC; l++ ) { if ( gef_conn[ef].PC[l] == gef_conn[ef_].PC[k] ) break; } if ( l == gef_conn[ef].num_PC ) break; } if ( k == gef_conn[ef_].num_PC ) { gef_conn[ef].I[gef_conn[ef].num_I++] = ef_; } /* j ==> i ? */ for ( k = 0; k < gef_conn[ef].num_PC; k++ ) { for ( l = 0; l < gef_conn[ef_].num_PC; l++ ) { if ( gef_conn[ef_].PC[l] == gef_conn[ef].PC[k] ) break; } if ( l == gef_conn[ef_].num_PC ) break; } if ( k == gef_conn[ef].num_PC ) { gef_conn[ef_].I[gef_conn[ef_].num_I++] = ef; } } } } /* first sweep: only count the space we need for the fact arrays ! */ if ( gop_conn[n_op].num_E > 0 ) { for ( i = 0; i < gop_conn[n_op].num_E; i++ ) { ef = gop_conn[n_op].E[i]; for ( j = 0; j < gef_conn[ef].num_PC; j++ ) { gft_conn[gef_conn[ef].PC[j]].num_PC++; } for ( j = 0; j < gef_conn[ef].num_A; j++ ) { gft_conn[gef_conn[ef].A[j]].num_A++; } for ( j = 0; j < gef_conn[ef].num_D; j++ ) { gft_conn[gef_conn[ef].D[j]].num_D++; } } } n_op++; } for ( i = 0; i < gnum_ft_conn; i++ ) { if ( gft_conn[i].num_PC > 0 ) { gft_conn[i].PC = ( int * ) calloc( gft_conn[i].num_PC, sizeof( int ) ); } gft_conn[i].num_PC = 0; if ( gft_conn[i].num_A > 0 ) { gft_conn[i].A = ( int * ) calloc( gft_conn[i].num_A, sizeof( int ) ); } gft_conn[i].num_A = 0; if ( gft_conn[i].num_D > 0 ) { gft_conn[i].D = ( int * ) calloc( gft_conn[i].num_D, sizeof( int ) ); } gft_conn[i].num_D = 0; gft_conn[i].is_global_goal = FALSE; } for ( i = 0; i < ggoal_state.num_F; i++ ) { gft_conn[ggoal_state.F[i]].is_global_goal = TRUE; } for ( i = 0; i < gnum_ef_conn; i++ ) { if ( gef_conn[i].removed ) continue; for ( j = 0; j < gef_conn[i].num_PC; j++ ) { gft_conn[gef_conn[i].PC[j]].PC[gft_conn[gef_conn[i].PC[j]].num_PC++] = i; } for ( j = 0; j < gef_conn[i].num_A; j++ ) { gft_conn[gef_conn[i].A[j]].A[gft_conn[gef_conn[i].A[j]].num_A++] = i; } for ( j = 0; j < gef_conn[i].num_D; j++ ) { gft_conn[gef_conn[i].D[j]].D[gft_conn[gef_conn[i].D[j]].num_D++] = i; } } free( same_effects ); free( had_effects ); if ( gcmd_line.display_info == 121 ) { printf("\n\ncreated connectivity graph as follows:"); printf("\n\n------------------OP ARRAY:-----------------------"); for ( i = 0; i < gnum_op_conn; i++ ) { printf("\n\nOP: "); print_op_name( i ); printf("\n----------EFFS:"); for ( j = 0; j < gop_conn[i].num_E; j++ ) { printf("\neffect %d", gop_conn[i].E[j]); } } printf("\n\n-------------------EFFECT ARRAY:----------------------"); for ( i = 0; i < gnum_ef_conn; i++ ) { printf("\n\neffect %d of op %d: ", i, gef_conn[i].op); print_op_name( gef_conn[i].op ); if ( gef_conn[i].removed ) { printf(" --- REMOVED "); continue; } printf("\n----------PCS:"); for ( j = 0; j < gef_conn[i].num_PC; j++ ) { printf("\n"); print_ft_name( gef_conn[i].PC[j] ); } printf("\n----------ADDS:"); for ( j = 0; j < gef_conn[i].num_A; j++ ) { printf("\n"); print_ft_name( gef_conn[i].A[j] ); } printf("\n----------DELS:"); for ( j = 0; j < gef_conn[i].num_D; j++ ) { printf("\n"); print_ft_name( gef_conn[i].D[j] ); } printf("\n----------IMPLIEDS:"); for ( j = 0; j < gef_conn[i].num_I; j++ ) { printf("\nimplied effect %d of op %d: ", gef_conn[i].I[j], gef_conn[gef_conn[i].I[j]].op); print_op_name( gef_conn[gef_conn[i].I[j]].op ); } } printf("\n\n----------------------FT ARRAY:-----------------------------"); for ( i = 0; i < gnum_ft_conn; i++ ) { printf("\n\nFT: "); print_ft_name( i ); printf(" rand: %d", gft_conn[i].rand); printf("\n----------PRE COND OF:"); for ( j = 0; j < gft_conn[i].num_PC; j++ ) { printf("\neffect %d", gft_conn[i].PC[j]); } printf("\n----------ADD BY:"); for ( j = 0; j < gft_conn[i].num_A; j++ ) { printf("\neffect %d", gft_conn[i].A[j]); } printf("\n----------DEL BY:"); for ( j = 0; j < gft_conn[i].num_D; j++ ) { printf("\neffect %d", gft_conn[i].D[j]); } } } }
static ngx_int_t ngx_tcp_check_init_process(ngx_cycle_t *cycle) { ngx_str_t shm_name; ngx_uint_t i; ngx_msec_t t, delay; check_conf_t *cf; ngx_shm_zone_t *shm_zone; ngx_tcp_check_peer_shm_t *peer_shm; ngx_tcp_check_peers_shm_t *peers_shm; ngx_tcp_check_peer_conf_t *peer_conf; ngx_tcp_check_peers_conf_t *peers_conf; ngx_tcp_upstream_srv_conf_t *uscf; if (ngx_tcp_check_get_shm_name(&shm_name, cycle->pool) == NGX_ERROR) { return NGX_ERROR; } shm_zone = ngx_shared_memory_find(cycle, &shm_name, &ngx_tcp_upstream_module); if (shm_zone == NULL || shm_zone->data == NULL) { return NGX_OK; } peers_conf = shm_zone->data; peers_shm = peers_conf->peers_shm; ngx_log_debug2(NGX_LOG_DEBUG_TCP, cycle->log, 0, "tcp check upstream init_process, shm_name: %V, " "peer number: %ud", &shm_name, peers_conf->peers.nelts); srandom(ngx_pid); peer_conf = peers_conf->peers.elts; peer_shm = peers_shm->peers; for (i = 0; i < peers_conf->peers.nelts; i++) { peer_conf[i].shm = &peer_shm[i]; peer_conf[i].check_ev.handler = ngx_tcp_check_begin_handler; peer_conf[i].check_ev.log = cycle->log; peer_conf[i].check_ev.data = &peer_conf[i]; peer_conf[i].check_ev.timer_set = 0; peer_conf[i].check_timeout_ev.handler = ngx_tcp_check_timeout_handler; peer_conf[i].check_timeout_ev.log = cycle->log; peer_conf[i].check_timeout_ev.data = &peer_conf[i]; peer_conf[i].check_timeout_ev.timer_set = 0; uscf = peer_conf[i].conf; cf = uscf->check_type_conf; if (cf->need_pool) { peer_conf[i].pool = ngx_create_pool(ngx_pagesize, cycle->log); if (peer_conf[i].pool == NULL) { return NGX_ERROR; } } peer_conf[i].send_handler = cf->send_handler; peer_conf[i].recv_handler = cf->recv_handler; peer_conf[i].init = cf->init; peer_conf[i].parse = cf->parse; peer_conf[i].reinit = cf->reinit; /* Default delay interval is 1 second. I don't want to trigger the check event too close. */ delay = uscf->check_interval > 1000 ? uscf->check_interval : 1000; t = ngx_random() % delay; ngx_add_timer(&peer_conf[i].check_ev, t); } return NGX_OK; }
static void IndexKVFile(const char* kvPath, const char* backIndexPath, const char* indexPath, couchstore_json_reducer reducer) { couchstore_error_t errcode; CouchStoreIndex* index = NULL; try(couchstore_create_index(indexPath, &index)); try(couchstore_index_add(kvPath, COUCHSTORE_VIEW_PRIMARY_INDEX, reducer, index)); try(couchstore_index_add(backIndexPath, COUCHSTORE_VIEW_BACK_INDEX, 0, index)); try(couchstore_close_index(index)); cleanup: assert(errcode == 0); } static void ReadIndexFile(const char *indexPath) { // See write_index_header in couch_index.c FILE *file = fopen(indexPath, "rb"); fseek(file, 0, SEEK_END); long eof = ftell(file); long headerPos = eof - (eof % 4096); // go to last 4KB boundary printf("Index header is at 0x%lx\n", headerPos); fseek(file, headerPos, SEEK_SET); // Header starts with a "1" byte, a length, and a CRC checksum: uint8_t flag; check_read(fread(&flag, 1, 1, file)); assert_eq(flag, 1); uint32_t headerLength, headerChecksum; check_read(fread(&headerLength, sizeof(headerLength), 1, file)); headerLength = ntohl(headerLength); check_read(fread(&headerChecksum, sizeof(headerChecksum), 1, file)); headerChecksum = htonl(headerChecksum); assert_eq(headerPos + headerLength + 1 + 4, eof); // Next is the root count: uint32_t nRoots; check_read(fread(&nRoots, sizeof(nRoots), 1, file)); nRoots = ntohl(nRoots); assert_eq(nRoots, 2); for (uint32_t root = 0; root < nRoots; ++root) { // The root has a type, size, node pointer, subtree size, and reduce data: uint8_t indexType; // really a couchstore_index_type check_read(fread(&indexType, 1, 1, file)); assert_eq(indexType, root); // i.e. first root is type 0, second is type 1 uint16_t rootSize; check_read(fread(&rootSize, sizeof(rootSize), 1, file)); rootSize = ntohs(rootSize); assert(rootSize >= 12); assert(rootSize < headerLength); uint64_t pointer = 0; uint64_t subtreesize = 0; check_read(fread((char*)&pointer + 2, 6, 1, file)); check_read(fread((char*)&subtreesize + 2, 6, 1, file)); pointer = ntohll(pointer); subtreesize = ntohll(subtreesize); sized_buf reduce = {NULL, rootSize - 12}; reduce.buf = malloc(reduce.size); check_read(fread(reduce.buf, reduce.size, 1, file)); printf("\tRoot: type=%d, pointer=%llu, subtreesize=%llu, reduce=%llu bytes\n", indexType, pointer, subtreesize, (uint64_t)reduce.size); assert((cs_off_t)pointer < headerPos); assert((cs_off_t)subtreesize < headerPos); // Examine the reduce values in the root node: assert(reduce.size >= 5 + 1024/8); uint64_t subtreeCount = 0; memcpy((uint8_t*)&subtreeCount + 3, reduce.buf, 5); subtreeCount = ntohll(subtreeCount); printf("\t SubTreeCount = %llu\n", subtreeCount); assert_eq(subtreeCount, 1000); printf("\t Bitmap = <"); for (int i = 0; i < 128; ++i) { printf("%.02x", (uint8_t)reduce.buf[5 + i]); if (i % 4 == 3) printf(" "); } printf(">\n"); if (indexType == COUCHSTORE_VIEW_PRIMARY_INDEX) { // JSON reductions: assert(reduce.size > 5 + 1024/8 + 2); char* jsonReduceStart = reduce.buf + 5 + 1024/8; sized_buf jsonReduce = {jsonReduceStart + 2, ntohs(*(uint16_t*)jsonReduceStart)}; assert(jsonReduce.size < 1000); printf("\t JSONReduction = '%.*s'\n", (int)jsonReduce.size, jsonReduce.buf); const char* expectedReduce = "{\"count\":1000,\"max\":99.51,\"min\":0.18,\"sum\":49547.93,\"sumsqr\":3272610.9289}"; assert_eq(jsonReduce.size, strlen(expectedReduce)); assert(strncmp(jsonReduce.buf, expectedReduce, strlen(expectedReduce)) == 0); } } assert_eq(ftell(file), eof); fclose(file); } void TestCouchIndexer(void) { fprintf(stderr, "Indexer: "); srandom(42); // to get a consistent sequence of random numbers GenerateKVFile(KVPATH, 1000); srandom(42); // to get a consistent sequence of random numbers GenerateBackIndexKVFile(KVBACKPATH, 1000); IndexKVFile(KVPATH, KVBACKPATH, INDEXPATH, COUCHSTORE_REDUCE_STATS); ReadIndexFile(INDEXPATH); unlink(KVPATH); unlink(INDEXPATH); fprintf(stderr, "OK\n"); }
int newPhoton (PhotonMap* pmap, const RAY* ray) { unsigned i; Photon photon; COLOR photonFlux; /* Account for distribution ratio */ if (!pmap || pmapRandom(pmap -> randState) > pmap -> distribRatio) return -1; /* Don't store on sources */ if (ray -> robj > -1 && islight(objptr(ray -> ro -> omod) -> otype)) return -1; /* if modifier in include/exclude set */ if (ambincl != -1 && ray -> ro && ambincl != inset(ambset, ray -> ro -> omod)) return -1; if (pmapNumROI && pmapROI) { unsigned inROI = 0; /* Store photon if within a region of interest (for ze Ecksperts!) */ for (i = 0; !inROI && i < pmapNumROI; i++) inROI = (ray -> rop [0] >= pmapROI [i].min [0] && ray -> rop [0] <= pmapROI [i].max [0] && ray -> rop [1] >= pmapROI [i].min [1] && ray -> rop [1] <= pmapROI [i].max [1] && ray -> rop [2] >= pmapROI [i].min [2] && ray -> rop [2] <= pmapROI [i].max [2]); if (!inROI) return -1; } /* Adjust flux according to distribution ratio and ray weight */ copycolor(photonFlux, ray -> rcol); scalecolor(photonFlux, ray -> rweight / (pmap -> distribRatio ? pmap -> distribRatio : 1)); setPhotonFlux(&photon, photonFlux); /* Set photon position and flags */ VCOPY(photon.pos, ray -> rop); photon.flags = 0; photon.caustic = PMAP_CAUSTICRAY(ray); /* Set contrib photon's primary ray and subprocess index (the latter * to linearise the primary ray indices after photon distribution is * complete). Also set primary ray's source index, thereby marking it * as used. */ if (isContribPmap(pmap)) { photon.primary = pmap -> numPrimary; photon.proc = PMAP_GETRAYPROC(ray); pmap -> lastPrimary.srcIdx = ray -> rsrc; } else photon.primary = 0; /* Set normal */ for (i = 0; i <= 2; i++) photon.norm [i] = 127.0 * (isVolumePmap(pmap) ? ray -> rdir [i] : ray -> ron [i]); if (!pmap -> heapBuf) { /* Lazily allocate heap buffa */ #if NIX /* Randomise buffa size to temporally decorellate flushes in * multiprocessing mode */ srandom(randSeed + getpid()); pmap -> heapBufSize = PMAP_HEAPBUFSIZE * (0.5 + frandom()); #else /* Randomisation disabled for single processes on WIN; also useful * for reproducability during debugging */ pmap -> heapBufSize = PMAP_HEAPBUFSIZE; #endif if (!(pmap -> heapBuf = calloc(pmap -> heapBufSize, sizeof(Photon)))) error(SYSTEM, "failed heap buffer allocation in newPhoton"); pmap -> heapBufLen = 0; } /* Photon initialised; now append to heap buffa */ memcpy(pmap -> heapBuf + pmap -> heapBufLen, &photon, sizeof(Photon)); if (++pmap -> heapBufLen >= pmap -> heapBufSize) /* Heap buffa full, flush to heap file */ flushPhotonHeap(pmap); pmap -> numPhotons++; return 0; }
int main(int argc, char *argv[]) { struct tms usage; FILE *finp; int i,j, ticks; int numinfirst; char chkfile[255]; i=0; dump_file=NULL; do_cluster=do_pairwise_cluster; srandom(563573); bzero(&prog_opts,sizeof(ProgOptionsType)); outf=stdout; // set default distance function dist = d2; distpair= d2pair; #ifdef MPI MPI_Init(&argc, &argv); MPI_Errhandler_set(MPI_COMM_WORLD, MPI_ERRORS_RETURN); MPI_Comm_size(MPI_COMM_WORLD, &numprocs); MPI_Comm_rank(MPI_COMM_WORLD, &myid); #endif if(myid==0) { // Master process_options(argc, argv); } else { process_slave_options(argc, argv); } if (prog_opts.show_version || (argc==1)) { if (myid==0) printf("Version \n%s\n",version); #ifdef MPI MPI_Finalize(); #endif exit(0); } // Allocate space for the RC table for big words rc_big = calloc(BIG_WORD_TSIZE, sizeof(SeqElt)); // work is an array of work blocks. If non-parallel, there'll only // be one. work[0] acts a template work = (WorkPtr) calloc(num_threads,sizeof(WorkBlock)); work->filename = argv[optind]; work->index = NULL; if(prog_opts.do_dump) dump_file = fopen(prog_opts.dname,"w"); #ifdef MPI if (numprocs > 1) if (myid>0) { // slaves if (prog_opts.split) { MPI_Finalize(); return 0; } handleMPISlaveSetup(&num_seqs); initialise(work, prog_opts.edfile); internalTest(); perform_clustering(work); transmitMPISlaveResponse(work); if (prog_opts.show_perf) show_performance(outf); MPI_Finalize(); exit(0); } #else if (numprocs > 1) { printf("This version of wcd is not compiled with MPI\n"); printf("You cannot run it with a multiple processes\n"); printf("Either only run it with one process or do a \n"); printf(" ./configure --enable-mpi\n"); printf(" make clean\n"); printf(" make \n"); exit(5); } #endif // work out number of sequences // if the user has specified a value for num_seqs then // use that, else use the number of sequences in the file num_seqs = count_seqs(argv[optind], &data_size)+reindex_value; seq = (SeqPtr *) calloc(num_seqs,sizeof(SeqPtr)); seqInfo = (SeqInfoPtr) calloc(num_seqs,sizeof(SeqInfoStruct)); tree= (UnionFindPtr) calloc(num_seqs,sizeof(UnionFindStruct)); data= (SeqPtr) calloc(data_size,sizeof(SeqElt)); init_dummy_sequences(); #ifndef AUXINFO seqID = (SeqIDPtr) calloc(num_seqs,sizeof(SeqIDStruct)); #endif if (seq == NULL) { perror("SeqStruct allocation"); exit(50); } numinfirst = global_i_end = num_seqs; global_j_beg = 0; // if merging, need to check the other file too if (prog_opts.domerge || prog_opts.doadd ) { global_j_beg = global_i_end; num_seqs = handleMerge(argv[optind+2], num_seqs); if (prog_opts.doadd) global_i_end = num_seqs; } initialise(work, prog_opts.edfile); if (data == NULL) { sprintf(chkfile,"Main data store (%d bytes)",data_size); perror(chkfile); exit(51); } for(i=0; i<num_seqs; i++) seqInfo[i].flag=0; // reopen sequence file for reading finp = fopen(argv[optind],"r"); if (finp == NULL) { perror(argv[optind]); exit(51); } // Some messy stuff to hande auxiliary options // Skip to next comment on first reading if (prog_opts.pairwise==1) { sscanf(argv[optind+1], "%d", &i); sscanf(argv[optind+2], "%d", &j); show_pairwise(finp,i,j); return 0; } if (prog_opts.statgen) { compared2nummatches(finp,prog_opts.statgen); return 0; } if (prog_opts.range) { sscanf(argv[optind+1], "%d", &global_i_beg); sscanf(argv[optind+2], "%d", &global_i_end); } if (prog_opts.show_comp==41) { char * fname; fname = malloc(255); sscanf(argv[optind+1], "%s", fname); read_sequences(finp,reindex_value,num_seqs); checkfile = fopen(fname,"r"); sscanf(argv[optind+2], "%d", &j); while (fscanf(checkfile,"%d", &i) != -1) { do_compare(finp,i,j,1); } return 0; } if (prog_opts.show_comp) { sscanf(argv[optind+1], "%d", &i); sscanf(argv[optind+2], "%d", &j); //printf("Comparing %d and %d of %d flag %d\n",i,j,num_seqs,prog_opts.flag); read_sequences(finp,reindex_value,num_seqs); do_compare(finp,i,j,prog_opts.flag); return 0; } if (prog_opts.show_index) { show_sequence(finp, prog_opts.index,prog_opts.flag); return 0; } // Now read in the sequences if (do_cluster == do_pairwise_cluster||do_cluster==do_MPImaster_cluster||do_cluster == do_suffix_cluster) read_sequences(finp,reindex_value,numinfirst); else init_sequences(finp,reindex_value,numinfirst); fclose(finp); //printf("%d Allocated %d, start=%d, last=%d\n",num_seqs,data_size,data,seq[num_seqs-1].seq); if (prog_opts.split) { process_split(prog_opts.clfname1, prog_opts.split); #ifdef MPI MPI_Finalize(); #endif return 0; } if (prog_opts.consfname1) process_constraints(prog_opts.consfname1,0); if (prog_opts.clustercomp) { cluster_compare(argv[optind+1]); return 0; } // If merging or adding need to open the second sequence file if (prog_opts.domerge || prog_opts.doadd) { finp = fopen(argv[optind+2], "r"); if (finp == NULL) { perror(argv[optind]); exit(1); } if (do_cluster == do_pairwise_cluster) read_sequences(finp,numinfirst+reindex_value,num_seqs); else init_sequences(finp,numinfirst+reindex_value,num_seqs); get_clustering(argv[optind+1],0); if (prog_opts.domerge) get_clustering(argv[optind+3],numinfirst); } if (prog_opts.init_cluster) get_clustering(prog_opts.clfname1, 0); if (prog_opts.recluster) reclustering(work,prog_opts.clfname2); else { // This really assumes there is only one thread for suffix if (prog_opts.pairwise==2) { matrix_compare(finp); return 0; } work->workflag = prog_opts.noninterleavednlc;//kludge for suffixarray global_j_end = num_seqs; perform_clustering(work); #ifdef MPI if (myid>0) transmitMPISlaveResponse(work); #endif } if (prog_opts.show_ext) show_EXT(outf); if (prog_opts.show_histo) show_histogram(work); if (prog_opts.show_clust&1) show_clusters(outf); if (prog_opts.show_clust&8) produce_clusters(prog_opts.clthresh,prog_opts.dirname); if (prog_opts.show_perf) show_performance(outf); if (prog_opts.do_dump) { strcpy(chkfile,prog_opts.dname); strcat(chkfile,"-FIN"); fclose(dump_file); dump_file = fopen(chkfile,"w"); times(&usage); ticks = sysconf(_SC_CLK_TCK); fprintf(dump_file,"Completed %ld %ld", usage.tms_utime/ticks, usage.tms_stime*1000/ticks); fclose(dump_file); } if (prog_opts.show_version) fprintf(outf,"\n%s\n",version); fclose(outf); #ifdef MPI MPI_Finalize(); #endif exit(0); }
/** Read the global config file * * @param filename a name of a file. * @return new rc_handle on success, NULL when failure. */ rc_handle *rc_read_config(char const *filename) { FILE *configfd; char buffer[512], *p; OPTION *option; int line; size_t pos; rc_handle *rh; srandom((unsigned int)(time(NULL)+getpid())); rh = rc_new(); if (rh == NULL) return NULL; rh->config_options = malloc(sizeof(config_options_default)); if (rh->config_options == NULL) { rc_log(LOG_CRIT, "rc_read_config: out of memory"); rc_destroy(rh); return NULL; } memcpy(rh->config_options, &config_options_default, sizeof(config_options_default)); if ((configfd = fopen(filename,"r")) == NULL) { rc_log(LOG_ERR,"rc_read_config: can't open %s: %s", filename, strerror(errno)); rc_destroy(rh); return NULL; } line = 0; while ((fgets(buffer, sizeof(buffer), configfd) != NULL)) { line++; p = buffer; if ((*p == '\n') || (*p == '#') || (*p == '\0')) continue; p[strlen(p)-1] = '\0'; if ((pos = strcspn(p, "\t ")) == 0) { rc_log(LOG_ERR, "%s: line %d: bogus format: %s", filename, line, p); fclose(configfd); rc_destroy(rh); return NULL; } p[pos] = '\0'; if ((option = find_option(rh, p, OT_ANY)) == NULL) { rc_log(LOG_ERR, "%s: line %d: unrecognized keyword: %s", filename, line, p); fclose(configfd); rc_destroy(rh); return NULL; } if (option->status != ST_UNDEF) { rc_log(LOG_ERR, "%s: line %d: duplicate option line: %s", filename, line, p); fclose(configfd); rc_destroy(rh); return NULL; } p += pos+1; while (isspace(*p)) p++; pos = strlen(p) - 1; while(pos != 0 && isspace(p[pos])) pos--; p[pos + 1] = '\0'; switch (option->type) { case OT_STR: if (set_option_str(filename, line, option, p) < 0) { fclose(configfd); rc_destroy(rh); return NULL; } break; case OT_INT: if (set_option_int(filename, line, option, p) < 0) { fclose(configfd); rc_destroy(rh); return NULL; } break; case OT_SRV: if (set_option_srv(filename, line, option, p) < 0) { fclose(configfd); rc_destroy(rh); return NULL; } break; case OT_AUO: if (set_option_auo(filename, line, option, p) < 0) { fclose(configfd); rc_destroy(rh); return NULL; } break; default: rc_log(LOG_CRIT, "rc_read_config: impossible case branch!"); abort(); } } fclose(configfd); if (test_config(rh, filename) == -1) { rc_destroy(rh); return NULL; } return rh; }
void zhash_test (int verbose) { int rc, testmax, testnbr, iteration; void *item; zhash_t *hash; zhash_testset testset[200]; printf (" * zhash: "); // @selftest hash = zhash_new (); assert (hash); assert (zhash_size (hash) == 0); // Insert some items rc = zhash_insert (hash, "DEADBEEF", (void *) 0xDEADBEEF); assert (rc == 0); rc = zhash_insert (hash, "ABADCAFE", (void *) 0xABADCAFE); assert (rc == 0); rc = zhash_insert (hash, "C0DEDBAD", (void *) 0xC0DEDBAD); assert (rc == 0); rc = zhash_insert (hash, "DEADF00D", (void *) 0xDEADF00D); assert (rc == 0); assert (zhash_size (hash) == 4); // Look for existing items item = zhash_lookup (hash, "DEADBEEF"); assert (item == (void *) 0xDEADBEEF); item = zhash_lookup (hash, "ABADCAFE"); assert (item == (void *) 0xABADCAFE); item = zhash_lookup (hash, "C0DEDBAD"); assert (item == (void *) 0xC0DEDBAD); item = zhash_lookup (hash, "DEADF00D"); assert (item == (void *) 0xDEADF00D); // Look for non-existent items item = zhash_lookup (hash, "0xF0000000"); assert (item == NULL); // Try to insert duplicate items rc = zhash_insert (hash, "DEADBEEF", (void *) 0xF0000000); assert (rc == -1); item = zhash_lookup (hash, "DEADBEEF"); assert (item == (void *) 0xDEADBEEF); // Rename an item rc = zhash_rename (hash, "DEADBEEF", "LIVEBEEF"); assert (rc == 0); rc = zhash_rename (hash, "WHATBEEF", "LIVEBEEF"); assert (rc == -1); // Delete a item zhash_delete (hash, "LIVEBEEF"); item = zhash_lookup (hash, "LIVEBEEF"); assert (item == NULL); assert (zhash_size (hash) == 3); // Check that the queue is robust against random usage //struct { // char name [100]; // Bool exists; //} testset [200]; memset (testset, 0, sizeof (testset)); testmax = 200, testnbr, iteration; srandom ((unsigned) time (NULL)); for (iteration = 0; iteration < 25000; iteration++) { testnbr = randof (testmax); if (testset [testnbr].exists) { item = zhash_lookup (hash, testset [testnbr].name); assert (item); zhash_delete (hash, testset [testnbr].name); testset [testnbr].exists = FALSE; } else { sprintf (testset [testnbr].name, "%x-%x", rand (), rand ()); if (zhash_insert (hash, testset [testnbr].name, "") == 0) testset [testnbr].exists = TRUE; } } // Test 10K lookups for (iteration = 0; iteration < 10000; iteration++) item = zhash_lookup (hash, "DEADBEEFABADCAFE"); // Destructor should be safe to call twice zhash_destroy (&hash); zhash_destroy (&hash); assert (hash == NULL); // @end printf ("OK\n"); }
int main(int argc, char ** argv) { int numthreads = 1; // default to 1 int c, i, rv; pthread_t *tinfo; int stress_squatting = 0; // Read options from command line: // # clients from command line, as well as seed file // Simulation length // Block if a name is already taken ("Squat") // Stress test "squatting" while ((c = getopt (argc, argv, "c:hl:qt")) != -1) { switch (c) { case 'c': numthreads = atoi(optarg); break; case 'h': help(); return 0; case 'l': simulation_length = atoi(optarg); break; case 'q': allow_squatting = 1; break; case 't': stress_squatting = 1; break; default: printf ("Unknown option\n"); help(); return 1; } } // Create initial data structure, populate with initial entries // Note: Each variant of the tree has a different init function, statically compiled in init(numthreads); srandom(time(0)); // Run the self-tests if we are in debug mode #ifdef DEBUG self_tests(); #endif // Launch client threads tinfo = calloc(numthreads, sizeof(pthread_t)); for (i = 0; i < numthreads; i++) { if (stress_squatting) { rv = pthread_create(&tinfo[i], NULL, &squatter_stress, &i); } else { rv = pthread_create(&tinfo[i], NULL, &client, NULL); } if (rv != 0) { printf ("Thread creation failed %d\n", rv); return rv; } } // After the simulation is done, shut it down sleep (simulation_length); finished = 1; //if(allow_squatting) //char* const* qq="lol"; //char* const* wow[]={qq,NULL}; // char ** args = {"lol",NULL}; //execlp("echo","lol",NULL); printf("Times up, have a great day.\n"); // Wait for all clients to exit. If we are allowing blocking, // cancel the threads, since they may hang forever if (allow_squatting) { for (i = 0; i < numthreads; i++) { int rv = pthread_cancel(tinfo[i]); if (rv != 0) printf ("Uh oh. pthread_cancel failed %d\n", rv); } } if(!allow_squatting){ for (i = 0; i < numthreads; i++) { int rv = pthread_join(tinfo[i], NULL); if (rv != 0) printf ("Uh oh. pthread_join failed %d\n", rv); } } #ifdef DEBUG /* Print the final tree for fun */ print(); #endif return 0; }
int main(int argc,char * argv[]) { int i = 0, j = 0, rc; MDB_env *env; MDB_dbi dbi; MDB_val key, data; MDB_txn *txn; MDB_stat mst; MDB_cursor *cursor; int count; int *values; char sval[32]; char kval[sizeof(int)]; srandom(time(NULL)); memset(sval, 0, sizeof(sval)); count = (random()%384) + 64; values = (int *)malloc(count*sizeof(int)); for(i = 0;i<count;i++) { values[i] = random()%1024; } E(mdb_env_create(&env)); E(mdb_env_set_mapsize(env, 10485760)); E(mdb_env_set_maxdbs(env, 4)); E(mdb_env_open(env, "./testdb", MDB_FIXEDMAP|MDB_NOSYNC, 0664)); E(mdb_txn_begin(env, NULL, 0, &txn)); E(mdb_open(txn, "id2", MDB_CREATE|MDB_DUPSORT, &dbi)); key.mv_size = sizeof(int); key.mv_data = kval; data.mv_size = sizeof(sval); data.mv_data = sval; printf("Adding %d values\n", count); for (i=0;i<count;i++) { if (!(i & 0x0f)) sprintf(kval, "%03x", values[i]); sprintf(sval, "%03x %d foo bar", values[i], values[i]); if (RES(MDB_KEYEXIST, mdb_put(txn, dbi, &key, &data, MDB_NODUPDATA))) j++; } if (j) printf("%d duplicates skipped\n", j); E(mdb_txn_commit(txn)); E(mdb_env_stat(env, &mst)); E(mdb_txn_begin(env, NULL, 1, &txn)); E(mdb_cursor_open(txn, dbi, &cursor)); while ((rc = mdb_cursor_get(cursor, &key, &data, MDB_NEXT)) == 0) { printf("key: %p %.*s, data: %p %.*s\n", key.mv_data, (int) key.mv_size, (char *) key.mv_data, data.mv_data, (int) data.mv_size, (char *) data.mv_data); } CHECK(rc == MDB_NOTFOUND, "mdb_cursor_get"); mdb_cursor_close(cursor); mdb_txn_abort(txn); j=0; for (i= count - 1; i > -1; i-= (random()%5)) { j++; txn=NULL; E(mdb_txn_begin(env, NULL, 0, &txn)); sprintf(kval, "%03x", values[i & ~0x0f]); sprintf(sval, "%03x %d foo bar", values[i], values[i]); key.mv_size = sizeof(int); key.mv_data = kval; data.mv_size = sizeof(sval); data.mv_data = sval; if (RES(MDB_NOTFOUND, mdb_del(txn, dbi, &key, &data))) { j--; mdb_txn_abort(txn); } else { E(mdb_txn_commit(txn)); } } free(values); printf("Deleted %d values\n", j); E(mdb_env_stat(env, &mst)); E(mdb_txn_begin(env, NULL, 1, &txn)); E(mdb_cursor_open(txn, dbi, &cursor)); printf("Cursor next\n"); while ((rc = mdb_cursor_get(cursor, &key, &data, MDB_NEXT)) == 0) { printf("key: %.*s, data: %.*s\n", (int) key.mv_size, (char *) key.mv_data, (int) data.mv_size, (char *) data.mv_data); } CHECK(rc == MDB_NOTFOUND, "mdb_cursor_get"); printf("Cursor prev\n"); while ((rc = mdb_cursor_get(cursor, &key, &data, MDB_PREV)) == 0) { printf("key: %.*s, data: %.*s\n", (int) key.mv_size, (char *) key.mv_data, (int) data.mv_size, (char *) data.mv_data); } CHECK(rc == MDB_NOTFOUND, "mdb_cursor_get"); mdb_cursor_close(cursor); mdb_close(env, dbi); mdb_txn_abort(txn); mdb_env_close(env); return 0; }
void init_random(void) { srandom(time(NULL)); }
int main(int argc,char * argv[]) { int i = 0, j = 0, rc; MDB_env *env; MDB_dbi dbi; MDB_val key, data; MDB_txn *txn; MDB_stat mst; MDB_cursor *cursor, *cur2; int count; int *values; char sval[32] = ""; srandom(time(NULL)); count = (random()%384) + 64; values = (int *)malloc(count*sizeof(int)); for(i = 0;i<count;i++) { values[i] = random()%1024; } rc = mdb_env_create(&env); rc = mdb_env_set_mapsize(env, 10485760); rc = mdb_env_open(env, "./testdb", MDB_FIXEDMAP /*|MDB_NOSYNC*/, 0664); rc = mdb_txn_begin(env, NULL, 0, &txn); rc = mdb_open(txn, NULL, 0, &dbi); key.mv_size = sizeof(int); key.mv_data = sval; data.mv_size = sizeof(sval); data.mv_data = sval; printf("Adding %d values\n", count); for (i=0;i<count;i++) { sprintf(sval, "%03x %d foo bar", values[i], values[i]); rc = mdb_put(txn, dbi, &key, &data, MDB_NOOVERWRITE); if (rc) { j++; data.mv_size = sizeof(sval); data.mv_data = sval; } } if (j) printf("%d duplicates skipped\n", j); rc = mdb_txn_commit(txn); rc = mdb_env_stat(env, &mst); rc = mdb_txn_begin(env, NULL, 1, &txn); rc = mdb_cursor_open(txn, dbi, &cursor); while ((rc = mdb_cursor_get(cursor, &key, &data, MDB_NEXT)) == 0) { printf("key: %p %.*s, data: %p %.*s\n", key.mv_data, (int) key.mv_size, (char *) key.mv_data, data.mv_data, (int) data.mv_size, (char *) data.mv_data); } mdb_cursor_close(cursor); mdb_txn_abort(txn); j=0; key.mv_data = sval; for (i= count - 1; i > -1; i-= (random()%5)) { j++; txn=NULL; rc = mdb_txn_begin(env, NULL, 0, &txn); sprintf(sval, "%03x ", values[i]); rc = mdb_del(txn, dbi, &key, NULL); if (rc) { j--; mdb_txn_abort(txn); } else { rc = mdb_txn_commit(txn); } } free(values); printf("Deleted %d values\n", j); rc = mdb_env_stat(env, &mst); rc = mdb_txn_begin(env, NULL, 1, &txn); rc = mdb_cursor_open(txn, dbi, &cursor); printf("Cursor next\n"); while ((rc = mdb_cursor_get(cursor, &key, &data, MDB_NEXT)) == 0) { printf("key: %.*s, data: %.*s\n", (int) key.mv_size, (char *) key.mv_data, (int) data.mv_size, (char *) data.mv_data); } printf("Cursor last\n"); rc = mdb_cursor_get(cursor, &key, &data, MDB_LAST); printf("key: %.*s, data: %.*s\n", (int) key.mv_size, (char *) key.mv_data, (int) data.mv_size, (char *) data.mv_data); printf("Cursor prev\n"); while ((rc = mdb_cursor_get(cursor, &key, &data, MDB_PREV)) == 0) { printf("key: %.*s, data: %.*s\n", (int) key.mv_size, (char *) key.mv_data, (int) data.mv_size, (char *) data.mv_data); } printf("Cursor last/prev\n"); rc = mdb_cursor_get(cursor, &key, &data, MDB_LAST); printf("key: %.*s, data: %.*s\n", (int) key.mv_size, (char *) key.mv_data, (int) data.mv_size, (char *) data.mv_data); rc = mdb_cursor_get(cursor, &key, &data, MDB_PREV); printf("key: %.*s, data: %.*s\n", (int) key.mv_size, (char *) key.mv_data, (int) data.mv_size, (char *) data.mv_data); mdb_txn_abort(txn); printf("Deleting with cursor\n"); rc = mdb_txn_begin(env, NULL, 0, &txn); rc = mdb_cursor_open(txn, dbi, &cur2); for (i=0; i<50; i++) { rc = mdb_cursor_get(cur2, &key, &data, MDB_NEXT); if (rc) break; printf("key: %p %.*s, data: %p %.*s\n", key.mv_data, (int) key.mv_size, (char *) key.mv_data, data.mv_data, (int) data.mv_size, (char *) data.mv_data); rc = mdb_del(txn, dbi, &key, NULL); } printf("Restarting cursor in txn\n"); rc = mdb_cursor_get(cur2, &key, &data, MDB_FIRST); printf("key: %p %.*s, data: %p %.*s\n", key.mv_data, (int) key.mv_size, (char *) key.mv_data, data.mv_data, (int) data.mv_size, (char *) data.mv_data); for (i=0; i<32; i++) { rc = mdb_cursor_get(cur2, &key, &data, MDB_NEXT); if (rc) break; printf("key: %p %.*s, data: %p %.*s\n", key.mv_data, (int) key.mv_size, (char *) key.mv_data, data.mv_data, (int) data.mv_size, (char *) data.mv_data); } mdb_cursor_close(cur2); rc = mdb_txn_commit(txn); printf("Restarting cursor outside txn\n"); rc = mdb_txn_begin(env, NULL, 0, &txn); rc = mdb_cursor_open(txn, dbi, &cursor); rc = mdb_cursor_get(cursor, &key, &data, MDB_FIRST); printf("key: %p %.*s, data: %p %.*s\n", key.mv_data, (int) key.mv_size, (char *) key.mv_data, data.mv_data, (int) data.mv_size, (char *) data.mv_data); for (i=0; i<32; i++) { rc = mdb_cursor_get(cursor, &key, &data, MDB_NEXT); if (rc) break; printf("key: %p %.*s, data: %p %.*s\n", key.mv_data, (int) key.mv_size, (char *) key.mv_data, data.mv_data, (int) data.mv_size, (char *) data.mv_data); } mdb_cursor_close(cursor); mdb_close(env, dbi); mdb_txn_abort(txn); mdb_env_close(env); return 0; }
void send_frame(union sigval sv_data) { int i; IplImage *image; CvMat *encoded; send_frame_data_t *data = sv_data.sival_ptr; printf("speed: %d\n",data->speed); printf("client_fd: %d\n",data->client_fd); for(i=0; i < data->speed; i++) { image = cvQueryFrame(data->video); if (!image) { printf("%s\n","Could not get image!"); } } if(!image) { puts("could not get frame"); return; } // set the size of the thumb printf("%s\n","Is thumb this the failure?"); CvMat* thumb = cvCreateMat(250, 250, CV_8UC3); printf("%s\n","Is image this the failure?"); cvResize(image, thumb, CV_INTER_AREA); printf("%s\n","Is encodeParams this the failure?"); // Encode the frame in JPEG format with JPEG quality 30%. const static int encodeParams[] = { CV_IMWRITE_JPEG_QUALITY, 30 }; printf("%s\n","Is encoded this the failure?"); encoded = cvEncodeImage(".jpeg", thumb, encodeParams); unsigned short int seq_num = data-> frame_num; //unsigned int time_stamp = (data->speed *40) + data->time_stamp; unsigned int time_stamp = 40 + data->time_stamp; srandom((unsigned)time(NULL)); unsigned int ssrc = random(); unsigned short int payloadlength = encoded->cols; unsigned short int packet_len = 12 + payloadlength; //12 byte header // Create the rtp_packet unsigned char *rtp_packet = malloc(packet_len+4); // need to add 4 to the prefix if(rtp_packet == NULL) { printf("%s\n", "Error allocating memory to rtp_packet"); return; } // prefix data rtp_packet[0] = 0x24; // $ sign rtp_packet[1] = 0x00; rtp_packet[2] = (packet_len & 0xFF00) >> 8; rtp_packet[3] = packet_len & 0x00FFF; // header rtp_packet[4] = head_first & 0xFF; rtp_packet[5] = head_second & 0xFF; rtp_packet[6] = (seq_num & 0xFF00) >> 8; rtp_packet[7] = seq_num & 0x00FF; rtp_packet[8] = time_stamp & 0xFF000000; rtp_packet[9] = time_stamp & 0x00FF0000; rtp_packet[10] = time_stamp & 0x0000FF00; rtp_packet[11] = time_stamp & 0x000000FF; rtp_packet[12] = ssrc & 0xFF000000; rtp_packet[13] = ssrc & 0x00FF0000; rtp_packet[14] = ssrc & 0x0000FF00; rtp_packet[15] = ssrc & 0x000000FF; //payload printf("1\n"); printf("rtp_packet length: %d, payloadlength: %d, encoded length: %d\n", (sizeof rtp_packet), payloadlength, encoded->cols); memcpy(rtp_packet+16, encoded->data.ptr, payloadlength); // return the packet if(send(data->client_fd, rtp_packet, packet_len+4,0) == -1) { puts("error sending packet"); perror("send"); } free(rtp_packet); printf("%d\n",data->frame_num); printf("%d\n",data->time_stamp); data->frame_num = data->frame_num + data->speed; data->time_stamp = time_stamp; }
/* 初始化环境 */ void do_init() { int i, j; srandom(time(NULL)); for (i = 0; i < MASTER_PAGE_SUM; i++) { masterPageTable[i].pages = pageTable + i * PAGE_SUM / MASTER_PAGE_SUM; } for (i = 0; i < PAGE_SUM; i++) { pageTable[i].pageNum = i; pageTable[i].filled = FALSE; pageTable[i].edited = FALSE; pageTable[i].count = 0; /* 使用随机数设置该页的保护类型 */ switch (random() % 7) { case 0: { pageTable[i].proType = READABLE; break; } case 1: { pageTable[i].proType = WRITABLE; break; } case 2: { pageTable[i].proType = EXECUTABLE; break; } case 3: { pageTable[i].proType = READABLE | WRITABLE; break; } case 4: { pageTable[i].proType = READABLE | EXECUTABLE; break; } case 5: { pageTable[i].proType = WRITABLE | EXECUTABLE; break; } case 6: { pageTable[i].proType = READABLE | WRITABLE | EXECUTABLE; break; } default: break; } /* 设置该页对应的辅存地址 */ pageTable[i].auxAddr = i * PAGE_SIZE; } for (j = 0; j < BLOCK_SUM; j++) { /* 随机选择一些物理块进行页面装入 */ if (random() % 2 == 0) { do_page_in(&pageTable[j], j); pageTable[j].blockNum = j; pageTable[j].filled = TRUE; blockStatus[j] = TRUE; pageTable[j].count += 128; } else { blockStatus[j] = FALSE; } } }
unsigned char part_random(void) { static char s; if (!s) { s = 1; srandom(time(NULL)); } return random() %2; }
static char * readpass(FILE *ifp, FILE *ofp, int with_echo, int max_asterisks) { static char input[MAXLEN + 1], asterix[MAXLEN + 1]; static char once; char *cp, *ap, c; int i; if (max_asterisks < 0) { /* traditional code using fgets() */ if (fgets(input, sizeof input, ifp) != input) return NULL; cp = strrchr(input, '\n'); if (cp) *cp = '\0'; else input[sizeof input - 1] = '\0'; return input; } if (!once) { srandom(time(0)*getpid()); once = 1; } cp = input; ap = asterix; while (read(fileno(ifp), &c, 1)) { switch (c) { case '\n': case '\r': goto endwhile; case '\b': case 127: if (cp > input) { cp--; ap--; for (i = *ap; i > 0; i--) fputs("\b \b", ofp); *cp = '\0'; *ap = 0; } else { putc('\a', ofp); /* BEL */ } break; case '\025': /* Ctrl-U = erase everything typed so far */ if (cp == input) { putc('\a', ofp); /* BEL */ } else while (cp > input) { cp--; ap--; for (i = *ap; i > 0; i--) fputs("\b \b", ofp); *cp = '\0'; *ap = 0; } break; default: *cp++ = c; if (with_echo) { *ap = 1; putc(c, ofp); } else if (max_asterisks > 0) { *ap = (random() % max_asterisks) + 1; for (i = *ap; i > 0; i--) putc('*', ofp); } else { *ap = 0; } ap++; break; } fflush(ofp); if (cp >= input + MAXLEN) { putc('\a', ofp); /* BEL */ break; } } endwhile: *cp = '\0'; putc('\n', ofp); return input; }
void dt_simulate_init(void) { srandom(time(NULL)); }
int main(int argc, char **argv) { /* These variables are for command-line options. */ double mag = 1.0, etol = 10e-3, detol = 10e-8; double rate = 0.1, moment = 0.9, subsamp = 0, decay = 0.9; int seed = 0, minepochs = 10, maxepochs = 100; char *afunc = "tanh"; void *linealg = opt_lnsrch_golden, *optalg = opt_conjgrad_pr; OPTION_SET_MEMBER optsetm[] = { { "cgpr", opt_conjgrad_pr }, { "cgfr", opt_conjgrad_fr }, { "qndfp", opt_quasinewton_dfp }, { "qnbfgs", opt_quasinewton_bfgs }, { "lm", opt_levenberg_marquardt }, { "gd", opt_gradient_descent }, { NULL, NULL } }; OPTION_SET_MEMBER linesetm[] = { { "golden", opt_lnsrch_golden }, { "hybrid", opt_lnsrch_hybrid }, { "cubic", opt_lnsrch_cubic }, { "stc", nn_lnsrch_search_then_converge }, { "none", NULL }, { NULL, NULL } }; OPTION_SET lineset = { &linealg, linesetm }; OPTION_SET optset = { &optalg, optsetm }; /* The OPTION array is used to easily parse command-line options. */ OPTION opts[] = { { "-seed", OPT_INT, &seed, "random number seed" }, { "-minepochs", OPT_INT, &minepochs, "minimum # of training steps" }, { "-maxepochs", OPT_INT, &maxepochs, "maximum # of training steps" }, { "-afunc", OPT_STRING, &afunc, "act. function for hidden node"}, { "-mag", OPT_DOUBLE, &mag, "max size of initial weights" }, { "-etol", OPT_DOUBLE, &etol, "error tolerance" }, { "-detol", OPT_DOUBLE, &detol, "delta error tolerance" }, { "-rate", OPT_DOUBLE, &rate, "learning rate" }, { "-moment", OPT_DOUBLE, &moment, "momentum rate" }, { "-alg", OPT_SET, &optset, "training algorithm" }, { "-subsamp", OPT_DOUBLE, &subsamp, "subsample value" }, { "-decay", OPT_DOUBLE, &decay, "stochastic decay" }, { "-srch", OPT_SET, &lineset, "line search" }, { NULL, OPT_NULL, NULL, NULL } }; /* The DATASET and the NN that we will use. */ DATASET *data; NN *nn; /* Get the command-line options. */ get_options(argc, argv, opts, help_string, NULL, 0); /* Set the random seed. */ srandom(seed); /* Create the neural network. This one has two inputs, one hidden node, * and a single output. The input are connected to the hidden node * and the outputs, while the hidden node is just connected to the * outputs. */ nn = nn_create("2 1 1"); /* 2-1-1 architecture. */ nn_link(nn, "0 -l-> 1"); /* Inputs to hidden link. */ nn_link(nn, "1 -l-> 2"); /* Hidden to output link. */ nn_link(nn, "0 -l-> 2"); /* Input to output short-circuit link. */ /* Set the Activation functions of the hidden and output layers and * initialize the weights to uniform random values between -/+mag. */ nn_set_actfunc(nn, 1, 0, afunc); nn_set_actfunc(nn, 2, 0, "logistic"); nn_init(nn, mag); /* Convert the C matrix into a DATASET. There are two inputs, one * output, and four patterns total. */ data = dataset_create(&dsm_matrix_method, dsm_c_matrix(&xor_data[0][0], 2, 1, 4)); /* Tell the NN how to train itself. */ nn->info.train_set = data; nn->info.opt.min_epochs = minepochs; nn->info.opt.max_epochs = maxepochs; nn->info.opt.error_tol = etol; nn->info.opt.delta_error_tol = detol; nn->info.opt.hook = training_hook; nn->info.opt.rate = rate; nn->info.opt.momentum = moment; nn->info.opt.decay = decay; nn->info.subsample = subsamp; if(subsamp != 0) { nn->info.subsample = subsamp; nn->info.opt.stochastic = 1; } nn->info.opt.stepf = linealg; nn->info.opt.engine = optalg; nn->info.stc_eta_0 = 1; nn->info.stc_tau = 100; /* Do the training. This will print out the epoch number and * The error level until trianing halts via one of the stopping * criterion. */ nn_train(nn); nn->info.subsample = 0; /* Print out each input training pattern and the respective * NN output. */ printf("--------------------\n"); nn_offline_test(nn, data, testing_hook); /* Free up everything. */ nn_destroy(nn); dsm_destroy_matrix(dataset_destroy(data)); nn_shutdown(); /* Bye. */ exit(0); }
void server_startup(server_startup_st *construct) { unsigned int x; if ((construct->server_list= getenv("MEMCACHED_SERVERS"))) { printf("servers %s\n", construct->server_list); construct->servers= memcached_servers_parse(construct->server_list); construct->server_list= NULL; construct->count= 0; } else { { char server_string_buffer[8096]; char *end_ptr; end_ptr= server_string_buffer; for (x= 0; x < construct->count; x++) { char buffer[1024]; /* Nothing special for number */ int count; int status; if (construct->udp){ if(x == 0) { sprintf(buffer, "memcached -d -P /tmp/%umemc.pid -t 1 -U %u -m 128", x, x+ TEST_PORT_BASE); } else { sprintf(buffer, "memcached -d -P /tmp/%umemc.pid -t 1 -U %u", x, x+ TEST_PORT_BASE); } } else{ if(x == 0) { sprintf(buffer, "memcached -d -P /tmp/%umemc.pid -t 1 -p %u -m 128", x, x+ TEST_PORT_BASE); } else { sprintf(buffer, "memcached -d -P /tmp/%umemc.pid -t 1 -p %u", x, x+ TEST_PORT_BASE); } } status= system(buffer); count= sprintf(end_ptr, "localhost:%u,", x + TEST_PORT_BASE); end_ptr+= count; } *end_ptr= 0; construct->server_list= strdup(server_string_buffer); } printf("servers %s\n", construct->server_list); construct->servers= memcached_servers_parse(construct->server_list); } assert(construct->servers); srandom(time(NULL)); for (x= 0; x < memcached_server_list_count(construct->servers); x++) { printf("\t%s : %u\n", construct->servers[x].hostname, construct->servers[x].port); assert(construct->servers[x].fd == -1); assert(construct->servers[x].cursor_active == 0); } printf("\n"); }
int main(int argc, char *argv[]) { FILE *fp; char *line; size_t linecap; int i, n; srandom(0); printf("1..6\n"); /* * Test multiple times with different buffer sizes * and different _reader() return values. */ errno = 0; for (i = 0; i < 8; i++) { fp = mkfilebuf(); linecap = i; line = malloc(i); /* First line: the full apothegm */ assert(getline(&line, &linecap, fp) == sizeof(apothegm) - 1); assert(memcmp(line, apothegm, sizeof(apothegm)) == 0); assert(linecap >= sizeof(apothegm)); /* Second line: the NUL terminator following the newline */ assert(getline(&line, &linecap, fp) == 1); assert(line[0] == '\0' && line[1] == '\0'); /* Third line: EOF */ line[0] = 'X'; assert(getline(&line, &linecap, fp) == -1); assert(line[0] == '\0'); free(line); line = NULL; assert(feof(fp)); assert(!ferror(fp)); fclose(fp); } assert(errno == 0); printf("ok 1 - getline basic\n"); /* Make sure read errors are handled properly. */ linecap = 0; errno = 0; assert(getline(&line, &linecap, stdout) == -1); assert(errno == EBADF); errno = 0; assert(getdelim(&line, &linecap, 'X', stdout) == -1); assert(errno == EBADF); assert(ferror(stdout)); printf("ok 2 - stream error\n"); /* Make sure NULL linep or linecapp pointers are handled. */ fp = mkfilebuf(); assert(getline(NULL, &linecap, fp) == -1); assert(errno == EINVAL); assert(getline(&line, NULL, fp) == -1); assert(errno == EINVAL); assert(ferror(fp)); fclose(fp); printf("ok 3 - invalid params\n"); /* Make sure getline() allocates memory as needed if fp is at EOF. */ errno = 0; fp = mkfilebuf(); while (!feof(fp)) /* advance to EOF; can't fseek this stream */ getc(fp); free(line); line = NULL; linecap = 0; assert(getline(&line, &linecap, fp) == -1); assert(line[0] == '\0'); assert(linecap > 0); assert(errno == 0); assert(feof(fp)); assert(!ferror(fp)); fclose(fp); printf("ok 4 - eof\n"); /* Make sure a NUL delimiter works. */ fp = mkfilebuf(); n = strlen(apothegm); assert(getdelim(&line, &linecap, '\0', fp) == n + 1); assert(strcmp(line, apothegm) == 0); assert(line[n + 1] == '\0'); assert(linecap > n + 1); n = strlen(apothegm + n + 1); assert(getdelim(&line, &linecap, '\0', fp) == n + 1); assert(line[n + 1] == '\0'); assert(linecap > n + 1); assert(errno == 0); assert(!ferror(fp)); fclose(fp); printf("ok 5 - nul\n"); /* Make sure NULL *linep and zero *linecapp are handled. */ fp = mkfilebuf(); free(line); line = NULL; linecap = 42; assert(getline(&line, &linecap, fp) == sizeof(apothegm) - 1); assert(memcmp(line, apothegm, sizeof(apothegm)) == 0); fp = mkfilebuf(); free(line); line = malloc(100); linecap = 0; assert(getline(&line, &linecap, fp) == sizeof(apothegm) - 1); assert(memcmp(line, apothegm, sizeof(apothegm)) == 0); free(line); assert(!ferror(fp)); fclose(fp); printf("ok 6 - empty/NULL initial buffer\n"); exit(0); }
int main(int argc, char *argv[]) { int j; char *to_move; int opcnt, maxops; char path[PATH_MAX]; char tfile[PATH_MAX]; char target[PATH_MAX]; char spath[PATH_MAX]; char *p; int nslashes; int opt; int usecs; char *stopFile; int scnt; opcnt = 0; srandom(0); stopFile = NULL; maxops = 0; usecs = 1; while ((opt = getopt(argc, argv, "l:m:s:z:")) != -1) { switch (opt) { case 's': usecs = atoi(optarg); break; case 'z': stopFile = optarg; break; case 'm': maxops = atoi(optarg); break; case 'l': logfp = fopen(optarg, "w+"); if (logfp == NULL) errExit("fopen"); setbuf(logfp, NULL); break; default: usageError(argv[0]); } } if (optind + 1 >= argc) usageError(argv[0]); opcnt = 0; for (;;) { getDirList(argv[optind]); switch (argv[optind + 1][0]) { case 'c': snprintf(path, sizeof(path), "%s/%ld%s%s_%d", dirList[random() % dcnt], (long) getpid() % 100, MARKER_STRING, "cr", opcnt); if (strlen(path) > DLIM) continue; nslashes = 0; for (p = path; *p; p++) if (*p == '/') nslashes++; if (nslashes > 1) if (random() % nslashes > 0) continue; if (mkdir(path, 0700) == 0) logMessage("mkdir: %s\n", path); scnt = 1; while ((random() % 3) < 2) { snprintf(spath, sizeof(path), "%s/%ld%s%s%d_%d", path, (long) getpid() % 100, MARKER_STRING, "scr", scnt, opcnt); if (strlen(spath) > DLIM) break; if (mkdir(spath, 0700) == 0) logMessage("mkdir: %s\n", spath); strncpy(path, spath, PATH_MAX); path[PATH_MAX - 1] = '\0'; scnt++; } break; case 'd': if (dcnt == 0) continue; snprintf(path, sizeof(path), "%s", dirList[random() % dcnt]); while (strstr(path, MARKER_STRING) != NULL) { if (rmdir(path) == -1) break; logMessage("rmdir: %s\n", path); p = strrchr(path, '/'); if (p == NULL) break; *p = '\0'; } break; case 'm': if (dcnt < 3) continue; to_move = dirList[random() % dcnt]; if (strstr(to_move, MARKER_STRING) != NULL) { p = strrchr(to_move, '/'); snprintf(tfile, sizeof(tfile), "%s", p + 1); p = strstr(tfile, "__ren"); if (p != NULL) *p = '\0'; snprintf(target, sizeof(target), "%s/%s__ren%04d-%ld", dirList[random() % dcnt], tfile, opcnt, (long) getpid()); if (strlen(target) > DLIM) break; if (rename(to_move, target) == 0) logMessage("rename: %s ==> %s\n", to_move, target); } break; } for (j = 0; j < dcnt; j++) { free(dirList[j]); dirList[j] = NULL; } opcnt++; usleep(usecs); if (maxops > 0 && opcnt >= maxops) break; if (access(stopFile, F_OK) == 0) break; } exit(EXIT_SUCCESS); }
int main() { srandom(time(NULL)); int ch, row, col, i, status; pthread_t score_thread, player_thread; Enemy *enemy_list[20]; pthread_mutex_init (&mutex, NULL); initscr(); // start curses mode // raw(); // line buffering disabled, control character gotten cbreak(); noecho(); // we dont want what the user type to get out // start_color(); curs_set(0); keypad(stdscr, TRUE); // we get f1, f2, etc. getmaxyx(stdscr, row, col); // get the number of rows and columns battle_win = newwin(22, 32, 0, 0); box(battle_win, 0, 0); score_win = newwin(1, 30, 22, 0); mvwaddch(battle_win, 10, 15, '@'); refresh(); wrefresh(score_win); lose = 1; // now we create the threads pthread_create(&score_thread, NULL, move_score, NULL); pthread_create(&player_thread, NULL, move_player, NULL); // main thread will control the enemies for (i = 0; i < 20; i++) { enemy_list[i] = new Asteroid; } while (lose) { for (i = 0; (i < 20) && (lose); i++) { status = enemy_list[i]->move_enemy(); if (status == -1) { lose = 0; } else if (status == 1) { delete enemy_list[i]; enemy_list[i] = new Asteroid; } } usleep(100000); } pthread_cancel(score_thread); pthread_join(score_thread, NULL); pthread_cancel(player_thread); pthread_join(player_thread, NULL); mvwaddch(battle_win, playerposy, playerposx, 'O'); mvwaddch(battle_win, playerposy-1, playerposx-1, '\\'); mvwaddch(battle_win, playerposy-1, playerposx, '|'); mvwaddch(battle_win, playerposy-1, playerposx+1, '/'); mvwaddch(battle_win, playerposy, playerposx-1, '-'); mvwaddch(battle_win, playerposy, playerposx+1, '-'); mvwaddch(battle_win, playerposy+1, playerposx-1, '/'); mvwaddch(battle_win, playerposy+1, playerposx, '|'); mvwaddch(battle_win, playerposy+1, playerposx+1, '\\'); wrefresh(battle_win); getch(); // wait for user input endwin(); // end curses mode printf("Your score is: %d\n", score); return 0; }
/* ºÚ½Ü¿ËÓÎÏ· */ int BlackJack() { int num[52] = {11, 11, 11, 11, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10}; int cardlist[52] = {0}; int i, j, m, tmp = 0, tmp2, ch; int win = 2, win_jack = 5; /* win ΪӮʱµÄ±¶ÂÊ, win_jack * 1 µã±¶ÂÊ */ int six = 10, seven = 20, aj = 10, super_jack = 20; /* 777, A+J, spade A+J µÄ±¶ÂÊ */ int host_count = 2, guest_count = 1, card_count = 3, A_count = 0, AA_count = 0; int host_point = 0, guest_point = 0, mov_y = 4; int host_card[12] = {0}, guest_card[12] = {0}; long int money; int CHEAT = 0; /* ×ö±×²ÎÊý, 1 ¾Í×÷±×, 0 ¾Í²»×÷ */ modify_user_mode(M_BLACKJACK); money = get_money(0,"game/blackjack.welcome"); if(!money) return 0; move(1, 0); prints("¡¾ºÚ½Ü¿Ë¡¿ÓÎÏ· [°´ y ÐøÅÆ, n ²»ÐøÅÆ, d double, q ÈÏÊäÍ˳ö]"); move(0, 0); clrtoeol(); srandom(time(0)); for (i = 1; i <= 52; i++) { m = 0; do { j = random() % 52; if (cardlist[j] == 0) { cardlist[j] = i; m = 1; } } while (m == 0); }; for (i = 0; i < 52; i++) cardlist[i]--; /* Ï´ÅÆ */ if (money >= 20000) CHEAT = 1; if (CHEAT == 1) { if (cardlist[1] <= 3) { tmp2 = cardlist[50]; cardlist[50] = cardlist[1]; cardlist[1] = tmp2; } } /* ×÷±×Âë */ host_card[0] = cardlist[0]; if (host_card[0] < 4) AA_count++; guest_card[0] = cardlist[1]; if (guest_card[0] < 4) A_count++; host_card[1] = cardlist[2]; if (host_card[1] < 4) AA_count++; /* ·¢Ç°ÈýÕÅÅÆ */ move(5, 0); prints("¨q©¤©¤©¤¨r"); move(6, 0); prints("©¦ ©¦"); move(7, 0); prints("©¦ ©¦"); move(8, 0); prints("©¦ ©¦"); move(9, 0); prints("©¦ ©¦"); move(10, 0); prints("©¦ ©¦"); move(11, 0); prints("¨t©¤©¤©¤¨s"); print_card(host_card[1], 5, 4); print_card(guest_card[0], 15, 0); /* Ó¡³öÇ°ÈýÕÅÅÆ */ host_point = num[host_card[1]]; guest_point = num[guest_card[0]]; do { m = 1; guest_card[guest_count] = cardlist[card_count]; if (guest_card[guest_count] < 4) A_count++; print_card(guest_card[guest_count], 15, mov_y); guest_point += num[guest_card[guest_count]]; if ((guest_card[0] >= 24 && guest_card[0] <= 27) && (guest_card[1] >= 24 && guest_card[1] <= 27) && (guest_card[2] >= 24 && guest_card[2] <= 27)) { move(18, 3); prints("[1;41;33m £·£·£· [m"); move(3, 0); sprintf(genbuf,"[1;41;33m£·£·£· !!! µÃ½±½ð %d ÒøÁ½[m", money * seven); prints(genbuf); inmoney(money * seven); gamelog(genbuf); pressanykey(); return 0; } if ((guest_card[0] == 40 && guest_card[1] == 0) || (guest_card[0] == 0 && guest_card[1] == 40)) { move(18, 3); prints("[1;41;33m ³¬¼¶Õýͳ BLACK JACK [m"); move(3, 0); sprintf(genbuf,"[1;41;33m³¬¼¶Õýͳ BLACK JACK !!! µÃ½±½ð %d ÒøÁ½[m", money * super_jack); prints(genbuf); inmoney(money * super_jack); gamelog(genbuf); pressanykey(); return 0; } if ((guest_card[0] <= 3 && guest_card[0] >= 0) && (guest_card[1] <= 43 && guest_card[1] >= 40)) tmp = 1; if ((tmp == 1) || ((guest_card[1] <= 3 && guest_card[1] >= 0) && (guest_card[0] <= 43 && guest_card[0] >= 40))) { move(18, 3); prints("[1;41;33m SUPER BLACK JACK [m"); move(3, 0); sprintf(genbuf,"[1;41;33mSUPER BLACK JACK !!! µÃ½±½ð %d ÒøÁ½[m", money * aj); prints(genbuf); inmoney(money * aj); gamelog(genbuf); pressanykey(); return 0; } if (guest_point == 21 && guest_count == 1) { move(18, 3); prints("[1;41;33m BLACK JACK [m"); move(3, 0); sprintf(genbuf,"[1;41;33mBLACK JACK !!![44m µÃ½±½ð %d ÒøÁ½[m", money * win_jack); prints(genbuf); inmoney(money * win_jack); gamelog(genbuf); pressanykey(); return 0; } /* Ç°Á½ÕÅ¾Í 21 µã */ if (guest_point > 21) { if (A_count > 0) { guest_point -= 10; A_count--; }; } move(19, 0); //clrtoeol(); prints("[1;32mµãÊý: [33m%d[m", host_point); move(20, 0); //clrtoeol(); prints("[1;32mµãÊý: [33m%d[m", guest_point); if (guest_point > 21) { move(20, 0); //clrtoeol(); prints(" ±¬µôÀ²~~~ "); pressanykey(); return 0; } if (guest_count == 5) { move(18, 3); prints("[1;41;33m ¹ýÁù¹Ø [m"); move(3, 0); sprintf(genbuf,"[1;41;33m¹ýÁù¹Ø !!! µÃ½±½ð %d ÒøÁ½[m", money * six); prints(genbuf); inmoney(money * six); gamelog(genbuf); pressanykey(); return 0; } guest_count++; card_count++; mov_y += 4; do { if (ch == 'd') m = 0; if (m != 0) ch = egetch(); } while (ch != 'y' && ch != 'Y' && ch != 'n' && ch != 'N' && ch != 'd' && ch != 'D' && ch != 'q' && ch != 'Q' && m != 0 ); /* ×¥ key */ if (ch == 'd' && m != 0 && guest_count == 2) { if (currentuser.money >= money) { demoney(money); money *= 2; } else ch = 'n'; } /* double */ if (ch == 'd' && guest_count > 2) ch = 'n'; if (ch == 'q' || ch == 'Q') return ; if (guest_point == 21) ch = 'n'; } while (ch != 'n' && m != 0); mov_y = 8; print_card(host_card[0], 5, 0); print_card(host_card[1], 5, 4); host_point += num[host_card[0]]; do { if (host_point < guest_point) { host_card[host_count] = cardlist[card_count]; print_card(host_card[host_count], 5, mov_y); if (host_card[host_count] < 4) AA_count++; host_point += num[host_card[host_count]]; } if (host_point > 21) { if (AA_count > 0) { host_point -= 10; AA_count--; }; } move(19, 0); //clrtoeol(); prints("[1;32mµãÊý: [33m%d[m", host_point); move(20, 0); //clrtoeol(); prints("[1;32mµãÊý: [33m%d[m", guest_point); if (host_point > 21) { move(20, 0); //clrtoeol(); prints("[1;32mµãÊý: [33m%d [1;41;33m WINNER [m", guest_point); move(3, 0); sprintf(genbuf,"Ó®ÁË~~~~ µÃ½±½ð %d ÒøÁ½", money * win); prints(genbuf); gamelog(genbuf); inmoney(money * win); pressanykey(); return 0; } host_count++; card_count++; mov_y += 4; } while (host_point < guest_point); sprintf(genbuf,"ÊäÁË~~~~ ûÊÕ %d ÒøÁ½!", money); prints(genbuf); gamelog(genbuf); pressanykey(); return 0; }