file
stringlengths
18
26
data
stringlengths
3
1.04M
the_stack_data/230349.c
/* Public domain. */ #include <time.h> #include <sys/time.h> #include <utmp.h> int main(void) { struct utmp ut = {0}; return ut.ut_pid; }
the_stack_data/98575998.c
#include <stdio.h> #include <stdlib.h> int chars_to_int(char s[]) { int acc=0; int i=0; while ( s[i] >= '0' && s[i] <= '9' ) { acc = acc*10 + (s[i]-'0'); i++; } return acc; } int int_to_chars(int n, char s[], int m) { int i=m-1; s[m]=0; do { s[i] = '0'+n%10; n = n/10; i = i-1; } while ( n != 0 ); return i+1; } int main(int argc, char **argv) { int n, m, i; char *s; if ( argc != 3 || sscanf(argv[1], "%d", &m) != 1 ) { printf("Usage: %s <ndigits> <string>\n", argv[0]); return 1; } n = chars_to_int(argv[2]); s = (char *)malloc(m+1); i = int_to_chars(n, s, m); printf("conv(%s)=%d=\"%s\"\n", argv[2], n, s+i); return 0; }
the_stack_data/1066888.c
#include<stdio.h> #include<stdlib.h> struct Node { int data; struct Node *next; } *firstNode = NULL; void createNodes(int array[], int numberOfNodes) { struct Node *tempNode, *lastNode; firstNode = (struct Node *) malloc(sizeof(struct Node)); firstNode->data = array[0]; firstNode->next = NULL; lastNode = firstNode; for(int i = 1; i < numberOfNodes; i++) { tempNode = (struct Node *) malloc(sizeof(struct Node)); tempNode->data = array[i]; tempNode->next = NULL; lastNode->next = tempNode; lastNode = tempNode; } } void displayNodes(struct Node *pointNode) { printf("\nDisplaying Linked List Values:\n\n"); while(pointNode != NULL) { printf("%d ", pointNode->data); pointNode = pointNode->next; } printf("\n"); } int main() { int array [] = {10, 23, 24, 11, 1, 2, 6, 7, 3}; createNodes(array, 9); displayNodes(firstNode); return 0; }
the_stack_data/206392057.c
void matmult_kmn(int M, int N, int K, double **A, double **B, double **C) { for (int l = 0; l < M*N; l++) { C[0][l] = 0; } for (int k = 0; k < K; k++) { for (int m = 0; m < M; m++) { for (int n = 0; n < N; n++) { C[m][n] += A[m][k] * B[k][n]; } } } }
the_stack_data/56399.c
/*Exercise 4 - Functions Implement the three functions minimum(), maximum() and multiply() below the main() function. Do not change the code given in the main() function when you are implementing your solution.*/ #include <stdio.h> //function prototype int minimum(int x, int y); int maximum(int x, int y); int multiply(int x, int y); //function main begins program execution int main() { int no1, no2; printf("Enter a value for no 1 : "); scanf("%d", &no1); printf("Enter a value for no 2 : "); scanf("%d", &no2); printf("%d ", minimum(no1, no2)); printf("%d ", maximum(no1, no2)); printf("%d ", multiply(no1, no2)); return 0; }//end function main //function implementation //function to find the minimum int minimum(int x, int y) { if( x > y ) { return y; } else { return x; } } //function to find the maximim int maximum(int x, int y) { if( x > y ) { return x; } else { return y; } } //function to multiply the two numbers int multiply(int x, int y) { return x * y; }
the_stack_data/90211.c
#include <stdio.h> #include <string.h> int main() { FILE *fp; fp = fopen("/dev/scull0","r+"); if(fp == NULL){ printf("open scull error\n"); return -1; } return 0; }
the_stack_data/218893810.c
// RUN: %clang_cc1 -w -triple i386-pc-elfiamcu -mfloat-abi soft -emit-llvm -o - %s | FileCheck %s // CHECK-LABEL: define{{.*}} void @ints(i32 %a, i32 %b, i32 %c, i32 %d) void ints(int a, int b, int c, int d) {} // CHECK-LABEL: define{{.*}} void @floats(float %a, float %b, float %c, float %d) void floats(float a, float b, float c, float d) {} // CHECK-LABEL: define{{.*}} void @mixed(i32 %a, float %b, i32 %c, float %d) void mixed(int a, float b, int c, float d) {} // CHECK-LABEL: define{{.*}} void @doubles(double %d1, double %d2) void doubles(double d1, double d2) {} // CHECK-LABEL: define{{.*}} void @mixedDoubles(i32 %a, double %d1) void mixedDoubles(int a, double d1) {} typedef struct st3_t { char a[3]; } st3_t; typedef struct st4_t { int a; } st4_t; typedef struct st5_t { int a; char b; } st5_t; typedef struct st12_t { int a; int b; int c; } st12_t; // CHECK-LABEL: define{{.*}} void @smallStructs(i32 %st1.coerce, i32 %st2.coerce, i32 %st3.coerce) void smallStructs(st4_t st1, st4_t st2, st4_t st3) {} // CHECK-LABEL: define{{.*}} void @paddedStruct(i32 %i1, i32 %st.coerce0, i32 %st.coerce1, i32 %st4.0) void paddedStruct(int i1, st5_t st, st4_t st4) {} // CHECK-LABEL: define{{.*}} void @largeStructBegin(%struct.st12_t* byval(%struct.st12_t) align 4 %st) void largeStructBegin(st12_t st) {} // CHECK-LABEL: define{{.*}} void @largeStructMiddle(i32 %i1, %struct.st12_t* byval(%struct.st12_t) align 4 %st, i32 %i2, i32 %i3) void largeStructMiddle(int i1, st12_t st, int i2, int i3) {} // CHECK-LABEL: define{{.*}} void @largeStructEnd(i32 %i1, i32 %i2, i32 %i3, i32 %st.0, i32 %st.1, i32 %st.2) void largeStructEnd(int i1, int i2, int i3, st12_t st) {} // CHECK-LABEL: define{{.*}} i24 @retNonPow2Struct(i32 %r.coerce) st3_t retNonPow2Struct(st3_t r) { return r; } // CHECK-LABEL: define{{.*}} i32 @retSmallStruct(i32 %r.coerce) st4_t retSmallStruct(st4_t r) { return r; } // CHECK-LABEL: define{{.*}} i64 @retPaddedStruct(i32 %r.coerce0, i32 %r.coerce1) st5_t retPaddedStruct(st5_t r) { return r; } // CHECK-LABEL: define{{.*}} void @retLargeStruct(%struct.st12_t* noalias sret(%struct.st12_t) align 4 %agg.result, i32 %i1, %struct.st12_t* byval(%struct.st12_t) align 4 %r) st12_t retLargeStruct(int i1, st12_t r) { return r; } // CHECK-LABEL: define{{.*}} i32 @varArgs(i32 %i1, ...) int varArgs(int i1, ...) { return i1; } // CHECK-LABEL: define{{.*}} double @longDoubleArg(double %ld1) long double longDoubleArg(long double ld1) { return ld1; }
the_stack_data/134139.c
/* * Copyright (C) 2009, 2010 Nick Johnson <nickbjohnson4224 at gmail.com> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include <locale.h> #include <errno.h> /**************************************************************************** * setlocale * * XXX - stub. */ char *setlocale(int category, const char *locale) { errno = ENOSYS; return NULL; }
the_stack_data/200143266.c
#include <assert.h> #include <stdio.h> typedef struct { unsigned rest : 31; unsigned sign : 1; } float_t; typedef struct { unsigned long long rest : 63; unsigned long long sign : 1; } double_t; float copy_sign_f(float from, float to) { float res = to; ((float_t*)&res)->sign = ((float_t*)&from)->sign; return res; } double copy_sign_d(double from, double to) { double res = to; ((double_t*)&res)->sign = ((double_t*)&from)->sign; return res; } void print_f(float f) { printf("%f %x %x\n", f, *(int*)&f, 0x80000000 & *(int*)&f); } void print_d(double f) { printf("%f %llx %llx\n", f, *(long long*)&f, 0x8000000000000000LL & *(long long*)&f); } int main() { int z32 = 0; int n1_32 = 1UL << 31; long long z64 = 0; long long n1_64 = 1ULL << 63; float fz = *(float*)&z32; double dz = *(double*)&z64; float fn1 = *(float*)&n1_32; double dn1 = *(double*)&n1_64; float data[] = {1,-1,2,-2,1000.1123,-1000.123e12 }; unsigned i; print_f(0); print_f(1); print_f(-1); print_d(0); print_d(1); print_d(-1); /* assert(fz >= 0); assert(dz >= 0); assert(fn1 < 0); assert(dn1 < 0); */ for (i = 0; i < sizeof(data)/sizeof(data[0]); ++i) { float f = data[i]; double d = data[i]; printf("%f\n", f); printf("%f\n", copy_sign_f(fz, f)); printf("%f\n", copy_sign_f(fn1, f)); printf("%f\n", copy_sign_d(dz, d)); printf("%f\n\n", copy_sign_d(dn1, d)); assert(copy_sign_f(fz, f) >= 0); assert(copy_sign_f(fn1, f) < 0); assert(copy_sign_d(dz, d) >= 0); assert(copy_sign_d(dn1, d) < 0); } return 0; }
the_stack_data/572415.c
/* $Id$ */ /* * %ISC_START_LICENSE% * --------------------------------------------------------------------- * Copyright 2007-2018, Pittsburgh Supercomputing Center * All rights reserved. * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the * above copyright notice and this permission notice appear in all * copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL * WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE * AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR * PERFORMANCE OF THIS SOFTWARE. * -------------------------------------------------------------------- * %END_LICENSE% */ #include <sys/param.h> #include <stdint.h> #include <stdio.h> /* * Display the hexadecimal representation of some data. * @ptr: data to display. * @len: number of bytes to display. * @buf: buffer to place representation in; must be at least 2 * @len + * 1 (for NUL); */ void pfl_unpack_hex(const void *ptr, size_t len, char buf[]) { const unsigned char *p = ptr; const char tab[] = "0123456789abcdef"; char *t = buf; size_t n; for (n = 0; n < len; p++, n++) { *t++ = tab[*p >> 4]; *t++ = tab[*p & 0xf]; } *t = '\0'; } /* * Display the hexadecimal representation of some data. * @ptr: data to display. * @len: number of bytes to display. */ void fprinthex(FILE *fp, const void *ptr, size_t len) { const unsigned char *p = ptr; size_t n; flockfile(fp); for (n = 0; n < len; p++, n++) { if (n) { if (n % 32 == 0) fprintf(fp, "\n"); else { if (n % 8 == 0) fprintf(fp, " "); fprintf(fp, " "); } } fprintf(fp, "%02x", *p); } fprintf(fp, "\n------------------------------------------\n"); funlockfile(fp); } /* * Display the bit representation of some data in reverse. * @ptr: data to display. * @len: number of bytes to display. */ void printvbinr(const void *ptr, size_t len) { const unsigned char *p; size_t n; int i; flockfile(stdout); for (n = 0, p = (const unsigned char *)ptr + len - 1; n < len; p--, n++) { if (n && n % 8 == 0) printf("\n"); for (i = NBBY - 1; i >= 0; i--) putchar((*p & (1 << i)) ? '1': '0'); if (n % 8 != 7 && n != len - 1) putchar(' '); } putchar('\n'); funlockfile(stdout); } /* * Display the bit representation of some data. * @ptr: data to display. * @len: number of bytes to display. */ void printvbin(const void *ptr, size_t len) { const unsigned char *p = ptr; size_t n; int i; flockfile(stdout); for (n = 0, p = ptr; n < len; p++, n++) { if (n && n % 8 == 0) printf("\n"); for (i = 0; i < NBBY; i++) putchar((*p & (1 << i)) ? '1': '0'); if (n % 8 != 7 && n != len - 1) putchar(' '); } putchar('\n'); funlockfile(stdout); }
the_stack_data/103266593.c
/* Copyright 2019 @foostan Copyright 2020 Drashna Jaelre <@drashna> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifdef OLED_DRIVER_ENABLE oled_rotation_t oled_init_user(oled_rotation_t rotation) { if (!is_master) { return OLED_ROTATION_180; // flips the display 180 degrees if offhand } return rotation; } #define L_BASE 0 #define L_LOWER 2 #define L_RAISE 4 #define L_ADJUST 8 void oled_render_layer_state(void) { oled_write_P(PSTR("Layer: "), false); switch (layer_state) { case L_BASE: oled_write_ln_P(PSTR("Default"), false); break; case L_LOWER: oled_write_ln_P(PSTR("Lower"), false); break; case L_RAISE: oled_write_ln_P(PSTR("Raise"), false); break; case L_ADJUST: case L_ADJUST|L_LOWER: case L_ADJUST|L_RAISE: case L_ADJUST|L_LOWER|L_RAISE: oled_write_ln_P(PSTR("Adjust"), false); break; } } char keylog_str[24] = {}; const char code_to_name[60] = { ' ', ' ', ' ', ' ', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', 'R', 'E', 'B', 'T', '_', '-', '=', '[', ']', '\\', '#', ';', '\'', '`', ',', '.', '/', ' ', ' ', ' '}; void set_keylog(uint16_t keycode, keyrecord_t *record) { char name = ' '; if ((keycode >= QK_MOD_TAP && keycode <= QK_MOD_TAP_MAX) || (keycode >= QK_LAYER_TAP && keycode <= QK_LAYER_TAP_MAX)) { keycode = keycode & 0xFF; } if (keycode < 60) { name = code_to_name[keycode]; } // update keylog snprintf(keylog_str, sizeof(keylog_str), "%dx%d, k%2d : %c", record->event.key.row, record->event.key.col, keycode, name); } void oled_render_keylog(void) { oled_write(keylog_str, false); } void render_bootmagic_status(bool status) { /* Show Ctrl-Gui Swap options */ static const char PROGMEM logo[][2][3] = { {{0x97, 0x98, 0}, {0xb7, 0xb8, 0}}, {{0x95, 0x96, 0}, {0xb5, 0xb6, 0}}, }; if (status) { oled_write_ln_P(logo[0][0], false); oled_write_ln_P(logo[0][1], false); } else { oled_write_ln_P(logo[1][0], false); oled_write_ln_P(logo[1][1], false); } } void oled_render_logo(void) { static const char PROGMEM crkbd_logo[] = { 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, 0x90, 0x91, 0x92, 0x93, 0x94, 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0}; oled_write_P(crkbd_logo, false); } void oled_task_user(void) { if (is_master) { oled_render_layer_state(); oled_render_keylog(); } else { oled_render_logo(); } } bool process_record_user(uint16_t keycode, keyrecord_t *record) { if (record->event.pressed) { set_keylog(keycode, record); } return true; } #endif // OLED_DRIVER_ENABLE
the_stack_data/26699794.c
// gcc -O4 -c vm1.c && gcc -o vm1 vm1.o && time ./vm1 // clang -O4 -c vm1.c && clang -o vm1 vm1.o && time ./vm1 // // gcc -O2 -fprofile-generate -c vm1.c && gcc -fprofile-generate -o vm1 vm1.o && time ./vm1 && gcc -O2 -fprofile-use -c vm1.c && gcc -o vm1 vm1.o && time ./vm1 // gcc -O3 -fprofile-generate -c vm1.c && gcc -fprofile-generate -o vm1 vm1.o && time ./vm1 && gcc -O3 -fprofile-use -c vm1.c && gcc -o vm1 vm1.o && time ./vm1 // gcc -O4 -fprofile-generate -c vm1.c && gcc -fprofile-generate -o vm1 vm1.o && time ./vm1 && gcc -O4 -fprofile-use -c vm1.c && gcc -o vm1 vm1.o && time ./vm1 #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdint.h> #define INLINE __inline__ #define DUMMY UINT64_MAX #define D DUMMY #define DISPATCH inst++; goto *inst->op #define DISPATCH_JUMP(dist) inst += dist; goto *inst->op // array factory #define MAKE_ARRAY(prefix, type) \ struct prefix ## _array_t; \ \ typedef struct prefix ## _array_t { \ size_t cap; \ size_t len; \ type * items; \ } prefix ## _array_t; \ \ prefix ## _array_t * prefix ## _array_new(void) { \ prefix ## _array_t * s = (prefix ## _array_t *) malloc(sizeof(prefix ## _array_t)); \ s->cap = 32u; \ s->len = 0u; \ s->items = (type *) malloc(s->cap * sizeof(type)); \ return s; \ } \ \ void prefix ## _array_del(prefix ## _array_t * s) { \ free(s->items); \ free(s); \ } \ \ INLINE type prefix ## _array_getitem(prefix ## _array_t * s, size_t index) { \ return s->items[index]; \ } \ \ INLINE void prefix ## _array_setitem(prefix ## _array_t * s, size_t index, type value) { \ s->items[index] = value; \ } \ \ INLINE void prefix ## _array_append(prefix ## _array_t * s, type value) { \ s->items[s->len++] = value; \ } \ \ INLINE type prefix ## _array_pop(prefix ## _array_t * s) { \ return s->items[--s->len]; \ } typedef struct inst_t { void * op; int64_t a; int64_t b; int64_t c; } inst_t; MAKE_ARRAY(int64, int64_t); MAKE_ARRAY(inst, inst_t); void f() { // instructions and registers inst_array_t * insts = inst_array_new(); int64_array_t * regs = int64_array_new(); #define insts_append(op, a, b, c) \ inst_array_append(insts, (inst_t){&&op, a, b, c}) // insttructions insts_append(int_const, 0, 10, D); // a = 10 insts_append(int_const, 1, 2, D); // b = 2 insts_append(int_const, 2, 200000000, D);// c = 200000000 insts_append(int_const, 3, 7, D); // d = 7 insts_append(int_const, 4, 1, D); // e = 1 insts_append(int_const, 5, 0, D); // f = 0 insts_append(mov, 6, 0, D); // i = a insts_append(jlt, 6, 2, 16); // while (i < c) { insts_append(mod, 7, 6, 3); // r7 = i % d insts_append(jeq, 7, 5, 10); // if (r7 == f) { insts_append(jlt, 6, 2, 7); // while (i < c) { insts_append(add, 6, 6, 4); // i += e insts_append(mod, 8, 6, 3); // r8 = i % d insts_append(jeq, 8, 5, 2); // if (r8 == f) { insts_append(jmp, 3, D, D); // break insts_append(nop, D, D, D); // } insts_append(jmp, -6, D, D); // insts_append(nop, D, D, D); // } insts_append(jmp, 3, D, D); // insts_append(nop, D, D, D); // } else { insts_append(add, 6, 6, 1); // i += b insts_append(nop, D, D, D); // } insts_append(jmp, -15, D, D); // insts_append(end, D, D, D); // } // goto first inst inst_t * inst = insts->items; goto *inst->op; int_const: regs->items[inst->a] = inst->b; DISPATCH; mov: regs->items[inst->a] = regs->items[inst->b]; DISPATCH; jmp: DISPATCH_JUMP(inst->a); jlt: if (regs->items[inst->a] < regs->items[inst->b]) { DISPATCH; } else { DISPATCH_JUMP(inst->c); } jeq: if (regs->items[inst->a] == regs->items[inst->b]) { DISPATCH; } else { DISPATCH_JUMP(inst->c); } add: regs->items[inst->a] = regs->items[inst->b] + regs->items[inst->c]; DISPATCH; mod: regs->items[inst->a] = regs->items[inst->b] % regs->items[inst->c]; DISPATCH; nop: DISPATCH; end: ; printf("i: %ld\n", regs->items[6]); // cleanup int64_array_del(regs); inst_array_del(insts); } int main(int argc, char ** argv) { f(); return 0; }
the_stack_data/592153.c
/* This function decrypts an encrypted text given a key. Logic is the very same as the encrypting function. The only difference, is that additions and subtractions are reversed. */ void decifratura(char testo_criptato[], char chiave[], char *testo_decriptato) { char temp; int i,j=0, size_testo; size_testo=strlen(testo_criptato); for (i=0;i<=size_testo;i++) { if (chiave[j] > 90 || chiave[j] < 65) j=0; temp = chiave[j] - 65; if (testo_criptato[i] - temp < 65) testo_decriptato[i] = testo_criptato[i] - temp + 26; else testo_decriptato[i] = testo_criptato[i] - temp; j++; } }
the_stack_data/75138701.c
/* * Here is a very simple set of routines to write an Excel worksheet * Microsoft BIFF format. The Excel version is set to 2.0 so that it * will work with all versions of Excel. * * Author: Don Capps */ /* * Note: rows and colums should not exceed 255 or this code will * act poorly */ #ifdef Windows #include <Windows.h> #endif #include <sys/types.h> #include <stdio.h> #include <sys/file.h> #if defined(__AIX__) || defined(__FreeBSD__) || defined(__DragonFly__) #include <fcntl.h> #else #include <sys/fcntl.h> #endif #if defined(OSV5) || defined(linux) || defined (__FreeBSD__) || defined(__OpenBSD__) || defined(__bsdi__) || defined(__APPLE__) || defined(__DragonFly__) || defined(__NetBSD__) #include <string.h> #endif #if defined(linux) || defined(__DragonFly__) || defined(IOZ_macosx) || defined(__NetBSD__) #include <unistd.h> #include <stdlib.h> #endif #if (defined(solaris) && defined( __LP64__ )) || defined(__s390x__) || defined(FreeBSD) /* If we are building for 64-bit Solaris, all functions that return pointers * must be declared before they are used; otherwise the compiler will assume * that they return ints and the top 32 bits of the pointer will be lost, * causing segmentation faults. The following includes take care of this. * It should be safe to add these for all other OSs too, but we're only * doing it for Solaris now in case another OS turns out to be a special case. */ #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <stdlib.h> #include <string.h> #endif /* Little Endian */ #define ENDIAN_1 1 /* Big Endian */ #define ENDIAN_2 2 /* Middle Endian */ #define ENDIAN_3 3 /* Middle Endian */ #define ENDIAN_4 4 int junk, *junkp; #ifdef HAVE_ANSIC_C /************************************************************************/ /* Here is the API... Enjoy */ /************************************************************************/ /* Create worksheet */ int create_xls(char *); /* Args: Filename */ /* */ /* Close worksheet */ void close_xls(int); /* Args: file descriptor */ /* */ /* Put a 16 bit integer in worksheet */ void do_int(int,int,int,int); /* Args: file descriptor, */ /* value, */ /* row, */ /* column */ /* Put a double in 8 byte float */ void do_float(int,double,int,int); /* Args: file descriptor, */ /* value, */ /* row, */ /* column */ /* Put a string in worksheet */ void do_label(int,char *,int,int); /* Args: file descriptor, */ /* string, */ /* row, */ /* column */ /************************************************************************/ char libbif_version[] = "Libbif Version $Revision: 3.27 $"; void do_eof(int ); /* Used internally */ void do_header(int ); /* Used internally */ int endian(void); #endif #define BOF 0x9 #define INTEGER 0x2 #define FLOAT 0x3 #define LABEL 0x4 #define EXCEL_VERS 0x2 #define WORKSHEET 0x10 struct bof_record{ /* Beginning of file */ char hi_opcode; char lo_opcode; char hi_length; char lo_length; char hi_version; /* Excel version */ char lo_version; char hi_filetype; char lo_filetype; }; struct int_record { char hi_opcode; /* Type 2 of record */ char lo_opcode; char hi_length; char lo_length; char hi_row; char lo_row; char hi_column; char lo_column; char rgbhi; char rgbmed; char rgblo; char hi_data; char lo_data; }; struct label_record { char hi_opcode; /* Type 4 of record */ char lo_opcode; char hi_length; char lo_length; char hi_row; char lo_row; char hi_column; char lo_column; char rgbhi; char rgbmed; char rgblo; char string_length; char str_array[256]; }; struct float_record { /* Type 3 record */ char hi_opcode; char lo_opcode; char hi_length; char lo_length; char hi_row; char lo_row; char hi_column; char lo_column; char rgbhi; char rgbmed; char rgblo; double data; }; /* * Write the EOF and close the file */ #ifdef HAVE_ANSIC_C void close_xls(int fd) { #else close_xls(fd) int fd; { #endif do_eof(fd); close(fd); } /* * Create xls worksheet. Create file and put the BOF record in it. */ #ifdef HAVE_ANSIC_C int create_xls(char *name) { #else create_xls(name) char *name; { #endif int fd; unlink(name); #ifdef Windows fd=open(name,O_BINARY|O_CREAT|O_RDWR,0666); #else fd=open(name,O_CREAT|O_RDWR,0666); #endif if(fd<0) { printf("Error opening file %s\n",name); exit(-1); } do_header(fd); return(fd); } #ifdef HAVE_ANSIC_C void do_header(int fd) /* Stick the BOF at the beginning of the file */ { #else do_header(fd) int fd; { #endif struct bof_record bof; bof.hi_opcode=BOF; bof.lo_opcode = 0x0; bof.hi_length=0x4; bof.lo_length=0x0; bof.hi_version=EXCEL_VERS; bof.lo_version=0x0; bof.hi_filetype=WORKSHEET; bof.lo_filetype=0x0; junk=write(fd,&bof,sizeof(struct bof_record)); } /* * Put an integer (16 bit) in the worksheet */ #ifdef HAVE_ANSIC_C void do_int(int fd,int val, int row, int column) { #else do_int(fd,val,row,column) int fd,val,row,column; { #endif struct int_record intrec; short s_row,s_column; s_row=(short)row; s_column=(short)column; intrec.hi_opcode=INTEGER; intrec.lo_opcode=0x00; intrec.hi_length=0x09; intrec.lo_length=0x00; intrec.rgbhi=0x0; intrec.rgbmed=0x0; intrec.rgblo=0x0; intrec.hi_row=(char)s_row&0xff; intrec.lo_row=(char)(s_row>>8)&0xff; intrec.hi_column=(char)(s_column&0xff); intrec.lo_column=(char)(s_column>>8)&0xff; intrec.hi_data=(val & 0xff); intrec.lo_data=(val & 0xff00)>>8; junk=write(fd,&intrec,13); } /* Note: This routine converts Big Endian to Little Endian * and writes the record out. */ /* * Put a double in the worksheet as 8 byte float in IEEE format. */ #ifdef HAVE_ANSIC_C void do_float(int fd, double value, int row, int column) { #else do_float(fd, value, row, column) int fd; double value; int row,column; { #endif struct float_record floatrec; short s_row,s_column; unsigned char *sptr,*dptr; s_row=(short)row; s_column=(short)column; floatrec.hi_opcode=FLOAT; floatrec.lo_opcode=0x00; floatrec.hi_length=0xf; floatrec.lo_length=0x00; floatrec.rgbhi=0x0; floatrec.rgbmed=0x0; floatrec.rgblo=0x0; floatrec.hi_row=(char)(s_row&0xff); floatrec.lo_row=(char)((s_row>>8)&0xff); floatrec.hi_column=(char)(s_column&0xff); floatrec.lo_column=(char)((s_column>>8)&0xff); sptr =(unsigned char *) &value; dptr =(unsigned char *) &floatrec.data; if(endian()==ENDIAN_2) /* Big Endian */ { dptr[0]=sptr[7]; /* Convert to Little Endian */ dptr[1]=sptr[6]; dptr[2]=sptr[5]; dptr[3]=sptr[4]; dptr[4]=sptr[3]; dptr[5]=sptr[2]; dptr[6]=sptr[1]; dptr[7]=sptr[0]; } if(endian()==ENDIAN_3) /* Middle Endian */ { dptr[0]=sptr[4]; /* 16 bit swapped ARM */ dptr[1]=sptr[5]; dptr[2]=sptr[6]; dptr[3]=sptr[7]; dptr[4]=sptr[0]; dptr[5]=sptr[1]; dptr[6]=sptr[2]; dptr[7]=sptr[3]; } if(endian()==ENDIAN_1) /* Little Endian */ { dptr[0]=sptr[0]; /* Do not convert to Little Endian */ dptr[1]=sptr[1]; dptr[2]=sptr[2]; dptr[3]=sptr[3]; dptr[4]=sptr[4]; dptr[5]=sptr[5]; dptr[6]=sptr[6]; dptr[7]=sptr[7]; } if(endian()==-1) /* Unsupported architecture */ { dptr[0]=0; dptr[1]=0; dptr[2]=0; dptr[3]=0; dptr[4]=0; dptr[5]=0; dptr[6]=0; dptr[7]=0; printf("Excel output not supported on this architecture.\n"); } junk=write(fd,&floatrec,11); /* Don't write floatrec. Padding problems */ junk=write(fd,&floatrec.data,8); /* Write value seperately */ } /* * Put a string as a label in the worksheet. */ #ifdef HAVE_ANSIC_C void do_label(int fd, char *string, int row, int column) { #else do_label(fd, string, row, column) int fd; char *string; int row,column; { #endif struct label_record labelrec; short s_row,s_column; int i; for(i=0;i<255;i++) labelrec.str_array[i]=0; s_row=(short)row; s_column=(short)column; i=strlen(string); labelrec.hi_opcode=LABEL; labelrec.lo_opcode=0x00; labelrec.hi_length=0x08; /* 264 total bytes */ labelrec.lo_length=0x01; labelrec.rgblo=0x0; labelrec.rgbmed=0x0; labelrec.rgbhi=0x0; labelrec.hi_row=(char)(s_row&0xff); labelrec.lo_row=(char)((s_row>>8)&0xff); labelrec.hi_column=(char)(s_column&0xff); labelrec.lo_column=(char)((s_column>>8)&0xff); labelrec.string_length=i; if(i > 255) /* If too long then terminate it early */ string[254]=0; i=strlen(string); strcpy(labelrec.str_array,string); junk=write(fd,&labelrec,sizeof(struct label_record)); } /* * Write the EOF in the file */ #ifdef HAVE_ANSIC_C void do_eof(int fd) { #else do_eof(fd) int fd; { #endif char buf[]={0x0a,0x00,0x00,0x00}; junk=write(fd,buf,4); } /* * Routine to determine the Endian-ness of the system. This * is needed for Iozone to convert doubles (floats) into * Little-endian format. This is needed for Excel to be * able to interpret the file */ int endian(void) { long long foo = 0x0102030405060708LL; long foo1 = 0x012345678; unsigned char *c,c1,c2,c3,c4,c5,c6,c7,c8; c=(unsigned char *)&foo; c1=*c++; c2=*c++; c3=*c++; c4=*c++; c5=*c++; c6=*c++; c7=*c++; c8=*c; /*--------------------------------------------------------------*/ /* printf("%x %x %x %x %x %x %x %x\n",c1,c2,c3,c4,c5,c6,c7,c8); */ /*--------------------------------------------------------------*/ /* Little Endian format ? ( Intel ) */ if( (c1==0x08) && (c2==0x07) && (c3==0x06) && (c4==0x05) && (c5==0x04) && (c6==0x03) && (c7==0x02) && (c8==0x01) ) return(ENDIAN_1); /* Big Endian format ? ( Sparc, Risc... */ if( (c1==0x01) && (c2==0x02) && (c3==0x03) && (c4==0x04) && (c5==0x05) && (c6==0x06) && (c7==0x07) && (c8==0x08) ) return(ENDIAN_2); /* Middle Endian format ? ( ARM ... ) */ if( (c1==0x04) && (c2==0x03) && (c3==0x02) && (c4==0x01) && (c5==0x08) && (c6==0x07) && (c7==0x06) && (c8==0x05) ) return(ENDIAN_3); c=(unsigned char *)&foo1; c1=*c++; c2=*c++; c3=*c++; c4=*c++; /* Another middle endian format ? ( PDP-11 ... ) */ if( (c1==0x34) && (c2==0x12) && (c3==0x78) && (c4==0x56)) return(ENDIAN_4); return(-1); }
the_stack_data/37636515.c
/* { dg-do run } */ /* { dg-skip-if "" { *-*-* } { "*" } { "-O2" } } */ /* { dg-set-target-env-var ASAN_OPTIONS "strip_path_prefix='/'" } */ /* { dg-options "-fno-builtin-malloc -fno-builtin-free" } */ /* { dg-shouldfail "asan" } */ #include <stdlib.h> int main() { char *x = (char*)malloc(10); free(x); return x[5]; } /* { dg-output "heap-use-after-free.*(\n|\r\n|\r)" } */ /* { dg-output " #0 0x\[0-9a-f\]+ \[(\]?\[^/\]\[^\n\r]*(\n|\r\n|\r)" } */
the_stack_data/182952070.c
/* * 输入一个链表,从尾到头打印链表每个节点的值。 * 用栈实现更好,不建议下面这个实现 */ #include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct ListNode { int val; struct ListNode *next; } ListNode_t; void printListFromTailToHead(ListNode_t *head) { ListNode_t *next_node = head; int length = 0; int i = 0; while (next_node != NULL) { next_node = next_node->next; length += 1; } int value[length]; memset(value, 0, length); next_node = head; while (i < length) { value[i] = next_node->val; next_node = next_node->next; i++; } for (i = length - 1; i >= 0; i--) { printf("%d\n", value[i]); } } int main(void) { ListNode_t *head, *node, *prev; int i; prev = NULL; head = NULL; for (i = 0; i < 10; i++) { node = (ListNode_t *)malloc(sizeof(ListNode_t)); if (node == NULL) { break; } node->val = i; node->next = NULL; if (prev != NULL) { prev->next = node; } if (head == NULL) { head = node; } prev = node; } if (head != NULL) { printListFromTailToHead(head); } node = head; while (node) { prev = node; free(node); node = prev->next; } }
the_stack_data/151706583.c
#include <stdio.h> #include <stdlib.h> #include <string.h> #define max 2000 struct contas{ char nome[14]; char tipo; float credito, debito; int ordem; }; struct contas conta[max]; int main(){ int n=1,i,a,tam,j; char b; while(n){ printf("Quantidades de contas a serem inseridas: "); scanf("%i", &n); for(i=0;i<n;i++){ printf("\nCódigo da Conta com 14 dígitos: "); scanf("%s",&conta[i].nome); printf("Tipo da Conta (A/S): "); scanf("%s",&conta[i].tipo); if(conta[i].tipo == 'S'){ printf("Credito:"); scanf("%f",&conta[i].credito); printf("Debito:"); scanf("%f",&conta[i].debito); }else{ conta[i].credito = conta[i].debito = 0; } } for(i=0;i<n;i++){ a = atoi(conta[i].nome); tam = strlen(conta[i].nome); for(j=0;j<tam;j++){ if(a%10==0) a=a/10; } sprintf(conta[i].nome, "%i", a); } for(i=0;i<n;i++){ a = atoi(conta[i].nome); tam = strlen(conta[i].nome); for(j=0;j<tam;j++){ a--; if(a%10==0){ a/=10; break; } } conta[i].ordem = a; } for(i=n-1;i>=0;i--){ if(conta[i].tipo == 'S') continue; for(j=i+1;j<n;j++){ if(atoi(conta[i].nome)==conta[j].ordem){ conta[i].credito+=conta[j].credito; conta[i].debito+=conta[j].debito; } } } for(i=0;i<n;i++){ printf("\nConta Nº: %s ",conta[i].nome); printf("Crédito: %.2f ",conta[i].credito); printf("Débito: %.2f \n",conta[i].debito); } printf("\n"); } return 0; }
the_stack_data/181393140.c
/* ACM 231 Testing the CATCHER * mythnc * 2012/01/15 21:19:58 * run time: 0.004 */ #include <stdio.h> #define MAXM 10000 void input(void); int lds(void); void binsearch(int, int, int); int n; int v[MAXM]; int catcher[MAXM]; int main(void) { int set, data; set = 0; while (scanf("%d", &data) && data != -1) { catcher[0] = data; if (set > 0) putchar('\n'); printf("Test #%d:\n", ++set); input(); printf(" maximum possible interceptions: %d\n", lds()); } return 0; } /* input: receive input data * and return the number of missile */ void input(void) { n = 1; while (scanf("%d", &catcher[n]) && catcher[n] != -1) n++; } /* lds: return the longest decrement subsequence length */ int lds(void) { int len, i, j; len = 0; v[len++] = catcher[n - 1]; for (i = n - 2; i > -1; i--) if (catcher[i] > v[len - 1]) v[len++] = catcher[i]; else binsearch(0, len, i); return len; } void binsearch(int begin, int end, int index) { int mid; while (begin <= end) { mid = (begin + end) / 2; if (v[mid] == catcher[index]) return; else if (v[mid] > catcher[index]) end = mid - 1; else begin = mid + 1; } mid = (begin + end) / 2; if (mid == 0 && index == n - 2) v[0] = catcher[index]; else v[mid + 1] = catcher[index]; }
the_stack_data/92329017.c
/* { dg-do compile } */ int a, b, c, d, e, g; short f; void fn1 () { int i; f = a - b; e = (c && (i = d = (unsigned) f - 1)) || i; g = (unsigned) f - 1; c && (d = 0); }
the_stack_data/198580183.c
/* Example code for Exercises in C. Copyright 2016 Allen Downey License: Creative Commons Attribution-ShareAlike 3.0 */ #include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct { int num_rows, num_cols; double **rows; } Matrix; /* Make a matrix. */ Matrix *make_matrix(int num_rows, int num_cols) { Matrix *matrix = malloc(sizeof(Matrix)); matrix->num_rows = num_rows; matrix->num_cols = num_cols; matrix->rows = malloc(num_rows * sizeof(double*)); for (int i=0; i<num_rows; i++) { matrix->rows[i] = calloc(num_cols, sizeof(double)); } return matrix; } /* Free a matrix. */ void free_matrix(Matrix *matrix) { // TODO: Fill this in. for (int i=0; i<matrix->num_rows; i++) { free(matrix->rows[i]); } free(matrix->rows); free(matrix); } /* Print a row of a matrix. */ void print_matrix_row(double *row, int num_cols) { for (int j=0; j<num_cols; j++) { printf("%f ", row[j]); } } /* Print a matrix. */ void print_matrix(Matrix *matrix) { for (int i=0; i<matrix->num_rows; i++) { print_matrix_row(matrix->rows[i], matrix->num_cols); printf("\n"); } } /* Perform row reduction. Subtract a multiple of row j from row i so that the first element of row i is 0. */ void reduce_matrix_rows(Matrix *matrix, int i, int j) { double* ri = matrix->rows[i]; double* rj = matrix->rows[j]; double factor = ri[0] / rj[0]; for (int k = 0; k < matrix->num_cols; k++) { ri[k] = ri[k] - factor*rj[k]; } } int main () { Matrix *matrix = make_matrix(3, 4); for (int i=0; i<matrix->num_rows; i++) { for (int j=0; j<matrix->num_cols; j++) { matrix->rows[i][j] = i + j + 1; } } print_matrix(matrix); printf("reducing...\n"); reduce_matrix_rows(matrix, 1, 0); reduce_matrix_rows(matrix, 2, 0); print_matrix(matrix); free_matrix(matrix); }
the_stack_data/92326001.c
#include <stdio.h> int max(int a, int b){ return a > b ? a : b; } int min(int a, int b){ return a < b ? a: b; } int main() { long long int a, b, c, x, y, z; scanf("%lld %lld %lld", &a, &b, &c); x = max(a, max(b, c)); z = min(a, min(b, c)); y = a + b + c - x - z; if(x >= y + z) printf("Invalido\n"); else { if(x == y && y == z) printf("Valido-Equilatero\n"); else if(x != y && y != z && x != z) printf("Valido-Escaleno\n"); else printf("Valido-Isoceles\n"); if(x*x == (y*y + z*z)) printf("Retangulo: S\n"); else printf("Retangulo: N\n"); } return 0; }
the_stack_data/232955405.c
//숫자를 한번에 스캔 받아서 arr에 넣은 다음 arr와 stack을 비교해가면서 결과를 도출 //stack[top]이 arr[idx] 보다 낮으면 push, 같으면 pop, 크면 "NO" #include <stdio.h> #define MAX 100000 int stack[MAX]; char res[MAX*2]; int top=-1; int main(void) { int n,num=0,idx=0,res_idx=0; scanf("%d",&n); int arr[n]; for(int i=0;i<n;i++) scanf("%d",&arr[i]); int k=n*2; while(k--) //while(0)이 되면 바로 멈춤 { //stack[top]이 arr[idx]보다 낮은 경우 (push) if(top==-1 || stack[top]<arr[idx]) { stack[++top]=++num; //push res[res_idx++]='+'; } //stack[top]이 arr[idx]와 같은 경우 (pop) else if(stack[top] == arr[idx]) { top--; //pop res[res_idx++]='-'; idx++; //배열의 다음 숫자로 넘어감 } //stack[top]이 arr[idx]보다 큰 경우 ("NO") else { printf("NO"); //수열을 만들 수가 없음 return 0; } } for(int i=0;i<res_idx;i++) printf("%c\n",res[i]); return 0; }
the_stack_data/103725.c
/* f2c.h -- Standard Fortran to C header file */ /** barf [ba:rf] 2. "He suggested using FORTRAN, and everybody barfed." - From The Shogakukan DICTIONARY OF NEW ENGLISH (Second edition) */ #ifndef F2C_INCLUDE #define F2C_INCLUDE #include <math.h> #include <stdlib.h> #include <string.h> #include <stdio.h> #include <complex.h> #ifdef complex #undef complex #endif #ifdef I #undef I #endif #if defined(_WIN64) typedef long long BLASLONG; typedef unsigned long long BLASULONG; #else typedef long BLASLONG; typedef unsigned long BLASULONG; #endif #ifdef LAPACK_ILP64 typedef BLASLONG blasint; #if defined(_WIN64) #define blasabs(x) llabs(x) #else #define blasabs(x) labs(x) #endif #else typedef int blasint; #define blasabs(x) abs(x) #endif typedef blasint integer; typedef unsigned int uinteger; typedef char *address; typedef short int shortint; typedef float real; typedef double doublereal; typedef struct { real r, i; } complex; typedef struct { doublereal r, i; } doublecomplex; static inline _Complex float Cf(complex *z) {return z->r + z->i*_Complex_I;} static inline _Complex double Cd(doublecomplex *z) {return z->r + z->i*_Complex_I;} static inline _Complex float * _pCf(complex *z) {return (_Complex float*)z;} static inline _Complex double * _pCd(doublecomplex *z) {return (_Complex double*)z;} #define pCf(z) (*_pCf(z)) #define pCd(z) (*_pCd(z)) typedef int logical; typedef short int shortlogical; typedef char logical1; typedef char integer1; #define TRUE_ (1) #define FALSE_ (0) /* Extern is for use with -E */ #ifndef Extern #define Extern extern #endif /* I/O stuff */ typedef int flag; typedef int ftnlen; typedef int ftnint; /*external read, write*/ typedef struct { flag cierr; ftnint ciunit; flag ciend; char *cifmt; ftnint cirec; } cilist; /*internal read, write*/ typedef struct { flag icierr; char *iciunit; flag iciend; char *icifmt; ftnint icirlen; ftnint icirnum; } icilist; /*open*/ typedef struct { flag oerr; ftnint ounit; char *ofnm; ftnlen ofnmlen; char *osta; char *oacc; char *ofm; ftnint orl; char *oblnk; } olist; /*close*/ typedef struct { flag cerr; ftnint cunit; char *csta; } cllist; /*rewind, backspace, endfile*/ typedef struct { flag aerr; ftnint aunit; } alist; /* inquire */ typedef struct { flag inerr; ftnint inunit; char *infile; ftnlen infilen; ftnint *inex; /*parameters in standard's order*/ ftnint *inopen; ftnint *innum; ftnint *innamed; char *inname; ftnlen innamlen; char *inacc; ftnlen inacclen; char *inseq; ftnlen inseqlen; char *indir; ftnlen indirlen; char *infmt; ftnlen infmtlen; char *inform; ftnint informlen; char *inunf; ftnlen inunflen; ftnint *inrecl; ftnint *innrec; char *inblank; ftnlen inblanklen; } inlist; #define VOID void union Multitype { /* for multiple entry points */ integer1 g; shortint h; integer i; /* longint j; */ real r; doublereal d; complex c; doublecomplex z; }; typedef union Multitype Multitype; struct Vardesc { /* for Namelist */ char *name; char *addr; ftnlen *dims; int type; }; typedef struct Vardesc Vardesc; struct Namelist { char *name; Vardesc **vars; int nvars; }; typedef struct Namelist Namelist; #define abs(x) ((x) >= 0 ? (x) : -(x)) #define dabs(x) (fabs(x)) #define f2cmin(a,b) ((a) <= (b) ? (a) : (b)) #define f2cmax(a,b) ((a) >= (b) ? (a) : (b)) #define dmin(a,b) (f2cmin(a,b)) #define dmax(a,b) (f2cmax(a,b)) #define bit_test(a,b) ((a) >> (b) & 1) #define bit_clear(a,b) ((a) & ~((uinteger)1 << (b))) #define bit_set(a,b) ((a) | ((uinteger)1 << (b))) #define abort_() { sig_die("Fortran abort routine called", 1); } #define c_abs(z) (cabsf(Cf(z))) #define c_cos(R,Z) { pCf(R)=ccos(Cf(Z)); } #define c_div(c, a, b) {pCf(c) = Cf(a)/Cf(b);} #define z_div(c, a, b) {pCd(c) = Cd(a)/Cd(b);} #define c_exp(R, Z) {pCf(R) = cexpf(Cf(Z));} #define c_log(R, Z) {pCf(R) = clogf(Cf(Z));} #define c_sin(R, Z) {pCf(R) = csinf(Cf(Z));} //#define c_sqrt(R, Z) {*(R) = csqrtf(Cf(Z));} #define c_sqrt(R, Z) {pCf(R) = csqrtf(Cf(Z));} #define d_abs(x) (fabs(*(x))) #define d_acos(x) (acos(*(x))) #define d_asin(x) (asin(*(x))) #define d_atan(x) (atan(*(x))) #define d_atn2(x, y) (atan2(*(x),*(y))) #define d_cnjg(R, Z) { pCd(R) = conj(Cd(Z)); } #define r_cnjg(R, Z) { pCf(R) = conj(Cf(Z)); } #define d_cos(x) (cos(*(x))) #define d_cosh(x) (cosh(*(x))) #define d_dim(__a, __b) ( *(__a) > *(__b) ? *(__a) - *(__b) : 0.0 ) #define d_exp(x) (exp(*(x))) #define d_imag(z) (cimag(Cd(z))) #define r_imag(z) (cimag(Cf(z))) #define d_int(__x) (*(__x)>0 ? floor(*(__x)) : -floor(- *(__x))) #define r_int(__x) (*(__x)>0 ? floor(*(__x)) : -floor(- *(__x))) #define d_lg10(x) ( 0.43429448190325182765 * log(*(x)) ) #define r_lg10(x) ( 0.43429448190325182765 * log(*(x)) ) #define d_log(x) (log(*(x))) #define d_mod(x, y) (fmod(*(x), *(y))) #define u_nint(__x) ((__x)>=0 ? floor((__x) + .5) : -floor(.5 - (__x))) #define d_nint(x) u_nint(*(x)) #define u_sign(__a,__b) ((__b) >= 0 ? ((__a) >= 0 ? (__a) : -(__a)) : -((__a) >= 0 ? (__a) : -(__a))) #define d_sign(a,b) u_sign(*(a),*(b)) #define r_sign(a,b) u_sign(*(a),*(b)) #define d_sin(x) (sin(*(x))) #define d_sinh(x) (sinh(*(x))) #define d_sqrt(x) (sqrt(*(x))) #define d_tan(x) (tan(*(x))) #define d_tanh(x) (tanh(*(x))) #define i_abs(x) abs(*(x)) #define i_dnnt(x) ((integer)u_nint(*(x))) #define i_len(s, n) (n) #define i_nint(x) ((integer)u_nint(*(x))) #define i_sign(a,b) ((integer)u_sign((integer)*(a),(integer)*(b))) #define pow_dd(ap, bp) ( pow(*(ap), *(bp))) #define pow_si(B,E) spow_ui(*(B),*(E)) #define pow_ri(B,E) spow_ui(*(B),*(E)) #define pow_di(B,E) dpow_ui(*(B),*(E)) #define pow_zi(p, a, b) {pCd(p) = zpow_ui(Cd(a), *(b));} #define pow_ci(p, a, b) {pCf(p) = cpow_ui(Cf(a), *(b));} #define pow_zz(R,A,B) {pCd(R) = cpow(Cd(A),*(B));} #define s_cat(lpp, rpp, rnp, np, llp) { ftnlen i, nc, ll; char *f__rp, *lp; ll = (llp); lp = (lpp); for(i=0; i < (int)*(np); ++i) { nc = ll; if((rnp)[i] < nc) nc = (rnp)[i]; ll -= nc; f__rp = (rpp)[i]; while(--nc >= 0) *lp++ = *(f__rp)++; } while(--ll >= 0) *lp++ = ' '; } #define s_cmp(a,b,c,d) ((integer)strncmp((a),(b),f2cmin((c),(d)))) #define s_copy(A,B,C,D) { int __i,__m; for (__i=0, __m=f2cmin((C),(D)); __i<__m && (B)[__i] != 0; ++__i) (A)[__i] = (B)[__i]; } #define sig_die(s, kill) { exit(1); } #define s_stop(s, n) {exit(0);} static char junk[] = "\n@(#)LIBF77 VERSION 19990503\n"; #define z_abs(z) (cabs(Cd(z))) #define z_exp(R, Z) {pCd(R) = cexp(Cd(Z));} #define z_sqrt(R, Z) {pCd(R) = csqrt(Cd(Z));} #define myexit_() break; #define mycycle() continue; #define myceiling(w) {ceil(w)} #define myhuge(w) {HUGE_VAL} //#define mymaxloc_(w,s,e,n) {if (sizeof(*(w)) == sizeof(double)) dmaxloc_((w),*(s),*(e),n); else dmaxloc_((w),*(s),*(e),n);} #define mymaxloc(w,s,e,n) {dmaxloc_(w,*(s),*(e),n)} /* procedure parameter types for -A and -C++ */ #define F2C_proc_par_types 1 #ifdef __cplusplus typedef logical (*L_fp)(...); #else typedef logical (*L_fp)(); #endif static float spow_ui(float x, integer n) { float pow=1.0; unsigned long int u; if(n != 0) { if(n < 0) n = -n, x = 1/x; for(u = n; ; ) { if(u & 01) pow *= x; if(u >>= 1) x *= x; else break; } } return pow; } static double dpow_ui(double x, integer n) { double pow=1.0; unsigned long int u; if(n != 0) { if(n < 0) n = -n, x = 1/x; for(u = n; ; ) { if(u & 01) pow *= x; if(u >>= 1) x *= x; else break; } } return pow; } static _Complex float cpow_ui(_Complex float x, integer n) { _Complex float pow=1.0; unsigned long int u; if(n != 0) { if(n < 0) n = -n, x = 1/x; for(u = n; ; ) { if(u & 01) pow *= x; if(u >>= 1) x *= x; else break; } } return pow; } static _Complex double zpow_ui(_Complex double x, integer n) { _Complex double pow=1.0; unsigned long int u; if(n != 0) { if(n < 0) n = -n, x = 1/x; for(u = n; ; ) { if(u & 01) pow *= x; if(u >>= 1) x *= x; else break; } } return pow; } static integer pow_ii(integer x, integer n) { integer pow; unsigned long int u; if (n <= 0) { if (n == 0 || x == 1) pow = 1; else if (x != -1) pow = x == 0 ? 1/x : 0; else n = -n; } if ((n > 0) || !(n == 0 || x == 1 || x != -1)) { u = n; for(pow = 1; ; ) { if(u & 01) pow *= x; if(u >>= 1) x *= x; else break; } } return pow; } static integer dmaxloc_(double *w, integer s, integer e, integer *n) { double m; integer i, mi; for(m=w[s-1], mi=s, i=s+1; i<=e; i++) if (w[i-1]>m) mi=i ,m=w[i-1]; return mi-s+1; } static integer smaxloc_(float *w, integer s, integer e, integer *n) { float m; integer i, mi; for(m=w[s-1], mi=s, i=s+1; i<=e; i++) if (w[i-1]>m) mi=i ,m=w[i-1]; return mi-s+1; } static inline void cdotc_(complex *z, integer *n_, complex *x, integer *incx_, complex *y, integer *incy_) { integer n = *n_, incx = *incx_, incy = *incy_, i; _Complex float zdotc = 0.0; if (incx == 1 && incy == 1) { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += conjf(Cf(&x[i])) * Cf(&y[i]); } } else { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += conjf(Cf(&x[i*incx])) * Cf(&y[i*incy]); } } pCf(z) = zdotc; } static inline void zdotc_(doublecomplex *z, integer *n_, doublecomplex *x, integer *incx_, doublecomplex *y, integer *incy_) { integer n = *n_, incx = *incx_, incy = *incy_, i; _Complex double zdotc = 0.0; if (incx == 1 && incy == 1) { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += conj(Cd(&x[i])) * Cd(&y[i]); } } else { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += conj(Cd(&x[i*incx])) * Cd(&y[i*incy]); } } pCd(z) = zdotc; } static inline void cdotu_(complex *z, integer *n_, complex *x, integer *incx_, complex *y, integer *incy_) { integer n = *n_, incx = *incx_, incy = *incy_, i; _Complex float zdotc = 0.0; if (incx == 1 && incy == 1) { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += Cf(&x[i]) * Cf(&y[i]); } } else { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += Cf(&x[i*incx]) * Cf(&y[i*incy]); } } pCf(z) = zdotc; } static inline void zdotu_(doublecomplex *z, integer *n_, doublecomplex *x, integer *incx_, doublecomplex *y, integer *incy_) { integer n = *n_, incx = *incx_, incy = *incy_, i; _Complex double zdotc = 0.0; if (incx == 1 && incy == 1) { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += Cd(&x[i]) * Cd(&y[i]); } } else { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += Cd(&x[i*incx]) * Cd(&y[i*incy]); } } pCd(z) = zdotc; } #endif /* -- translated by f2c (version 20000121). You must link the resulting object file with the libraries: -lf2c -lm (in that order) */ /* > \brief \b SLARTV applies a vector of plane rotations with real cosines and real sines to the elements of a pair of vectors. */ /* =========== DOCUMENTATION =========== */ /* Online html documentation available at */ /* http://www.netlib.org/lapack/explore-html/ */ /* > \htmlonly */ /* > Download SLARTV + dependencies */ /* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.tgz?format=tgz&filename=/lapack/lapack_routine/slartv. f"> */ /* > [TGZ]</a> */ /* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.zip?format=zip&filename=/lapack/lapack_routine/slartv. f"> */ /* > [ZIP]</a> */ /* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.txt?format=txt&filename=/lapack/lapack_routine/slartv. f"> */ /* > [TXT]</a> */ /* > \endhtmlonly */ /* Definition: */ /* =========== */ /* SUBROUTINE SLARTV( N, X, INCX, Y, INCY, C, S, INCC ) */ /* INTEGER INCC, INCX, INCY, N */ /* REAL C( * ), S( * ), X( * ), Y( * ) */ /* > \par Purpose: */ /* ============= */ /* > */ /* > \verbatim */ /* > */ /* > SLARTV applies a vector of real plane rotations to elements of the */ /* > real vectors x and y. For i = 1,2,...,n */ /* > */ /* > ( x(i) ) := ( c(i) s(i) ) ( x(i) ) */ /* > ( y(i) ) ( -s(i) c(i) ) ( y(i) ) */ /* > \endverbatim */ /* Arguments: */ /* ========== */ /* > \param[in] N */ /* > \verbatim */ /* > N is INTEGER */ /* > The number of plane rotations to be applied. */ /* > \endverbatim */ /* > */ /* > \param[in,out] X */ /* > \verbatim */ /* > X is REAL array, */ /* > dimension (1+(N-1)*INCX) */ /* > The vector x. */ /* > \endverbatim */ /* > */ /* > \param[in] INCX */ /* > \verbatim */ /* > INCX is INTEGER */ /* > The increment between elements of X. INCX > 0. */ /* > \endverbatim */ /* > */ /* > \param[in,out] Y */ /* > \verbatim */ /* > Y is REAL array, */ /* > dimension (1+(N-1)*INCY) */ /* > The vector y. */ /* > \endverbatim */ /* > */ /* > \param[in] INCY */ /* > \verbatim */ /* > INCY is INTEGER */ /* > The increment between elements of Y. INCY > 0. */ /* > \endverbatim */ /* > */ /* > \param[in] C */ /* > \verbatim */ /* > C is REAL array, dimension (1+(N-1)*INCC) */ /* > The cosines of the plane rotations. */ /* > \endverbatim */ /* > */ /* > \param[in] S */ /* > \verbatim */ /* > S is REAL array, dimension (1+(N-1)*INCC) */ /* > The sines of the plane rotations. */ /* > \endverbatim */ /* > */ /* > \param[in] INCC */ /* > \verbatim */ /* > INCC is INTEGER */ /* > The increment between elements of C and S. INCC > 0. */ /* > \endverbatim */ /* Authors: */ /* ======== */ /* > \author Univ. of Tennessee */ /* > \author Univ. of California Berkeley */ /* > \author Univ. of Colorado Denver */ /* > \author NAG Ltd. */ /* > \date December 2016 */ /* > \ingroup realOTHERauxiliary */ /* ===================================================================== */ /* Subroutine */ int slartv_(integer *n, real *x, integer *incx, real *y, integer *incy, real *c__, real *s, integer *incc) { /* System generated locals */ integer i__1; /* Local variables */ integer i__, ic, ix, iy; real xi, yi; /* -- LAPACK auxiliary routine (version 3.7.0) -- */ /* -- LAPACK is a software package provided by Univ. of Tennessee, -- */ /* -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..-- */ /* December 2016 */ /* ===================================================================== */ /* Parameter adjustments */ --s; --c__; --y; --x; /* Function Body */ ix = 1; iy = 1; ic = 1; i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { xi = x[ix]; yi = y[iy]; x[ix] = c__[ic] * xi + s[ic] * yi; y[iy] = c__[ic] * yi - s[ic] * xi; ix += *incx; iy += *incy; ic += *incc; /* L10: */ } return 0; /* End of SLARTV */ } /* slartv_ */
the_stack_data/162642063.c
#include <stdio.h> #include <stdlib.h> int main() { int n; scanf("%d",&n); // talvez tenha que tracar o malloc para calloc para iniciar com 0 int **matriz = malloc(n * sizeof(int*)); for (int i = 0; i < n; i++) matriz[i] = malloc(2 * sizeof(int)); // salva os valores e ordena for (int i = 0; i < n; i++) { // salva os valores e conta scanf("%d",&matriz[0][i]); // fazer algoritmo para percorrer vetor de maneira eficiente for (int j = 0; j <= i; j++) { if (matriz[0][i] == matriz[0][j]) { matriz[1][i] += 1 ; } } // limitador para funcionamento da ordenação if (i > 0) { // ordenador for (int j = 0; j < i; j++) { if (matriz[0][i] < matriz[0][j]) { // troca dos valores primários comparativos int aux = matriz[0][j]; matriz[0][j] = matriz[0][i]; matriz[0][i] = aux; // troca dos valores segundarios de contagem aux = matriz[1][j]; matriz[1][j] = matriz[1][i]; matriz[1][i] = aux; } } } } return 0; }
the_stack_data/92327389.c
#include <assert.h> #include <stddef.h> #include <string.h> #include <unistd.h> #include <sys/wait.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> int main(void) { static const char data[] = "data"; const size_t size = sizeof(data) - 1; struct sockaddr_in addr; socklen_t len = sizeof(addr); pid_t pid; memset(&addr, 0, sizeof(addr)); addr.sin_family = AF_INET; addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK); close(0); close(1); assert(socket(PF_INET, SOCK_STREAM, 0) == 0); assert(bind(0, (struct sockaddr *) &addr, len) == 0); assert(listen(0, 5) == 0); memset(&addr, 0, sizeof(addr)); assert(getsockname(0, (struct sockaddr *) &addr, &len) == 0); assert((pid = fork()) >= 0); if (pid) { char buf[sizeof(data)]; int status; assert(accept(0, (struct sockaddr *) &addr, &len) == 1); assert(close(0) == 0); assert(recv(1, buf, sizeof(buf), MSG_WAITALL) == (int) size); assert(waitpid(pid, &status, 0) == pid); assert(status == 0); assert(close(1) == 0); } else { assert(close(0) == 0); assert(socket(PF_INET, SOCK_STREAM, 0) == 0); assert(connect(0, (struct sockaddr *) &addr, len) == 0); assert(send(0, data, size, MSG_DONTROUTE) == (int) size); assert(close(0) == 0); } return 0; }
the_stack_data/124063.c
/*** * This code is a part of EvoApproxLib library (ehw.fit.vutbr.cz/approxlib) distributed under The MIT License. * When used, please cite the following article(s): PRABAKARAN B. S., MRAZEK V., VASICEK Z., SEKANINA L., SHAFIQUE M. ApproxFPGAs: Embracing ASIC-based Approximate Arithmetic Components for FPGA-Based Systems. DAC 2020. ***/ // MAE% = 0.0017 % // MAE = 2.2 // WCE% = 0.0046 % // WCE = 6.0 // WCRE% = 300.00 % // EP% = 87.50 % // MRE% = 0.0046 % // MSE = 7.0 // FPGA_POWER = 0.47 // FPGA_DELAY = 8.9 // FPGA_LUT = 17 #include <stdint.h> #include <stdlib.h> uint64_t add16u_04Z(uint64_t a, uint64_t b) { int wa[16]; int wb[16]; uint64_t y = 0; wa[0] = (a >> 0) & 0x01; wb[0] = (b >> 0) & 0x01; wa[1] = (a >> 1) & 0x01; wb[1] = (b >> 1) & 0x01; wa[2] = (a >> 2) & 0x01; wb[2] = (b >> 2) & 0x01; wa[3] = (a >> 3) & 0x01; wb[3] = (b >> 3) & 0x01; wa[4] = (a >> 4) & 0x01; wb[4] = (b >> 4) & 0x01; wa[5] = (a >> 5) & 0x01; wb[5] = (b >> 5) & 0x01; wa[6] = (a >> 6) & 0x01; wb[6] = (b >> 6) & 0x01; wa[7] = (a >> 7) & 0x01; wb[7] = (b >> 7) & 0x01; wa[8] = (a >> 8) & 0x01; wb[8] = (b >> 8) & 0x01; wa[9] = (a >> 9) & 0x01; wb[9] = (b >> 9) & 0x01; wa[10] = (a >> 10) & 0x01; wb[10] = (b >> 10) & 0x01; wa[11] = (a >> 11) & 0x01; wb[11] = (b >> 11) & 0x01; wa[12] = (a >> 12) & 0x01; wb[12] = (b >> 12) & 0x01; wa[13] = (a >> 13) & 0x01; wb[13] = (b >> 13) & 0x01; wa[14] = (a >> 14) & 0x01; wb[14] = (b >> 14) & 0x01; wa[15] = (a >> 15) & 0x01; wb[15] = (b >> 15) & 0x01; int sig_38 = 0; int sig_39 = wa[2]; int sig_40 = ~((int)0); int sig_42 = !sig_39; int sig_43 = sig_40 & wa[2]; int sig_44 = wa[3] ^ wb[3]; int sig_45 = wa[3] & wb[3]; int sig_46 = sig_44 & sig_43; int sig_47 = sig_44 ^ sig_43; int sig_48 = sig_45 | sig_46; int sig_49 = wa[4] ^ wb[4]; int sig_50 = wa[4] & wb[4]; int sig_51 = sig_49 & sig_48; int sig_52 = sig_49 ^ sig_48; int sig_53 = sig_50 | sig_51; int sig_54 = wa[5] ^ wb[5]; int sig_55 = wa[5] & wb[5]; int sig_56 = sig_54 & sig_53; int sig_57 = sig_54 ^ sig_53; int sig_58 = sig_55 | sig_56; int sig_59 = wa[6] ^ wb[6]; int sig_60 = wa[6] & wb[6]; int sig_61 = sig_59 & sig_58; int sig_62 = sig_59 ^ sig_58; int sig_63 = sig_60 | sig_61; int sig_64 = wa[7] ^ wb[7]; int sig_65 = wa[7] & wb[7]; int sig_66 = sig_64 & sig_63; int sig_67 = sig_64 ^ sig_63; int sig_68 = sig_65 | sig_66; int sig_69 = wa[8] ^ wb[8]; int sig_70 = wa[8] & wb[8]; int sig_71 = sig_69 & sig_68; int sig_72 = sig_69 ^ sig_68; int sig_73 = sig_70 | sig_71; int sig_74 = wa[9] ^ wb[9]; int sig_75 = wa[9] & wb[9]; int sig_76 = sig_74 & sig_73; int sig_77 = sig_74 ^ sig_73; int sig_78 = sig_75 | sig_76; int sig_79 = wa[10] ^ wb[10]; int sig_80 = wa[10] & wb[10]; int sig_81 = sig_79 & sig_78; int sig_82 = sig_79 ^ sig_78; int sig_83 = sig_80 | sig_81; int sig_84 = wa[11] ^ wb[11]; int sig_85 = wa[11] & wb[11]; int sig_86 = sig_84 & sig_83; int sig_87 = sig_84 ^ sig_83; int sig_88 = sig_85 | sig_86; int sig_89 = wa[12] ^ wb[12]; int sig_90 = wa[12] & wb[12]; int sig_91 = sig_89 & sig_88; int sig_92 = sig_89 ^ sig_88; int sig_93 = sig_90 | sig_91; int sig_94 = wa[13] ^ wb[13]; int sig_95 = wa[13] & wb[13]; int sig_96 = sig_94 & sig_93; int sig_97 = sig_94 ^ sig_93; int sig_98 = sig_95 | sig_96; int sig_99 = wa[14] ^ wb[14]; int sig_100 = wa[14] & wb[14]; int sig_101 = sig_99 & sig_98; int sig_102 = sig_99 ^ sig_98; int sig_103 = sig_100 | sig_101; int sig_104 = wa[15] ^ wb[15]; int sig_105 = wa[15] & wb[15]; int sig_106 = sig_104 & sig_103; int sig_107 = sig_104 ^ sig_103; int sig_108 = sig_105 | sig_106; y |= (sig_53 & 0x01) << 0; // default output y |= (sig_38 & 0x01) << 1; // default output y |= (sig_42 & 0x01) << 2; // default output y |= (sig_47 & 0x01) << 3; // default output y |= (sig_52 & 0x01) << 4; // default output y |= (sig_57 & 0x01) << 5; // default output y |= (sig_62 & 0x01) << 6; // default output y |= (sig_67 & 0x01) << 7; // default output y |= (sig_72 & 0x01) << 8; // default output y |= (sig_77 & 0x01) << 9; // default output y |= (sig_82 & 0x01) << 10; // default output y |= (sig_87 & 0x01) << 11; // default output y |= (sig_92 & 0x01) << 12; // default output y |= (sig_97 & 0x01) << 13; // default output y |= (sig_102 & 0x01) << 14; // default output y |= (sig_107 & 0x01) << 15; // default output y |= (sig_108 & 0x01) << 16; // default output return y; }
the_stack_data/104827899.c
/* Copyright 1992-2014 Free Software Foundation, Inc. This file is part of GDB. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* Simple little program that just generates a core dump from inside some nested function calls. Keep this as self contained as possible, I.E. use no environment resources other than possibly abort(). */ #ifndef __STDC__ #define const /**/ #endif #ifndef HAVE_ABORT #define HAVE_ABORT 1 #endif #if HAVE_ABORT #include <stdlib.h> #define ABORT abort() #else #define ABORT {char *invalid = 0; *invalid = 0xFF;} #endif #ifdef USE_RLIMIT # include <sys/resource.h> # ifndef RLIM_INFINITY # define RLIM_INFINITY -1 # endif #endif /* USE_RLIMIT */ /* Don't make these automatic vars or we will have to walk back up the stack to access them. */ char *buf1; char *buf2; int coremaker_data = 1; /* In Data section */ int coremaker_bss; /* In BSS section */ const int coremaker_ro = 201; /* In Read-Only Data section */ void func2 (int x) { int coremaker_local[5]; int i; static int y; #ifdef USE_RLIMIT { struct rlimit rlim = { RLIM_INFINITY, RLIM_INFINITY }; setrlimit (RLIMIT_CORE, &rlim); } #endif /* Make sure that coremaker_local doesn't get optimized away. */ for (i = 0; i < 5; i++) coremaker_local[i] = i; coremaker_bss = 0; for (i = 0; i < 5; i++) coremaker_bss += coremaker_local[i]; coremaker_data = coremaker_ro + 1; y = 10 * x; ABORT; } void func1 (int x) { func2 (x * 2); } int main () { func1 (10); return 0; }
the_stack_data/364231.c
#include <stdio.h> #include <stdlib.h> #include <string.h> #ifndef PTR_HDR_H #define PTR_HDR_H #include <assert.h> #if 1 struct IntStruct{ unsigned int* ptr2obj; unsigned int *L; unsigned int *H; }; #endif struct IntStruct malloc_wrap(unsigned int size) { struct IntStruct ptr; ptr.ptr2obj = (unsigned int*)malloc(size); ptr.L = (ptr.ptr2obj); ptr.H = (ptr.L + size); return ptr; } unsigned int* Deref_Overload(struct IntStruct ptr) { return ptr.ptr2obj; } struct IntStruct Cast_Overload(struct IntStruct ptr) { return ptr; } #if 0 IntStruct(int* buffer) { ptr2obj = buffer; } IntStruct(IntStruct& other) { ptr2obj = other.ptr2obj; } #endif #endif
the_stack_data/73575143.c
#include<stdio.h> int main() { int sum=0,j,low,up,i,k,dig,f,count=0; printf("enter limits lower and upper"); scanf("%d%d",&low,&up); for(j=low;j<=up;j++) { k=j; while(k>0) { dig=k%10; f=1; for(i=1;i<=dig;i++) f=f*i; sum=sum+f; k=k/10; } if(sum==j) printf("it is strong num -%d",j); sum=0; } }
the_stack_data/50136870.c
/* $XFree86: xc/programs/Xserver/hw/xfree86/drivers/ati/atiload.c,v 1.26 2008/01/01 00:40:00 tsi Exp $ */ /* * Copyright 2000 through 2008 by Marc Aurele La France (TSI @ UQV), [email protected] * * Permission to use, copy, modify, distribute, and sell this software and its * documentation for any purpose is hereby granted without fee, provided that * the above copyright notice appear in all copies and that both that copyright * notice and this permission notice appear in supporting documentation, and * that the name of Marc Aurele La France not be used in advertising or * publicity pertaining to distribution of the software without specific, * written prior permission. Marc Aurele La France makes no representations * about the suitability of this software for any purpose. It is provided * "as-is" without express or implied warranty. * * MARC AURELE LA FRANCE DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO * EVENT SHALL MARC AURELE LA FRANCE BE LIABLE FOR ANY SPECIAL, INDIRECT OR * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, * DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR * PERFORMANCE OF THIS SOFTWARE. */ #ifdef XFree86LOADER #include "ati.h" #include "aticursor.h" #include "atiload.h" #include "atistruct.h" #include "vbe.h" /* * All symbol lists belong here. They are externalised so that they can be * referenced elsewhere. Note the naming convention for these things... */ const char *ATIint10Symbols[] = { "xf86FreeInt10", "xf86InitInt10", "xf86int10Addr", NULL }; const char *ATIddcSymbols[] = { "xf86PrintEDID", "xf86SetDDCproperties", NULL }; const char *ATIvbeSymbols[] = { "VBEInit", "vbeDoEDID", "vbeFree", NULL }; const char *ATIxf1bppSymbols[] = { "xf1bppScreenInit", NULL }; const char *ATIxf4bppSymbols[] = { "xf4bppScreenInit", NULL }; const char *ATIfbSymbols[] = { "fbPictureInit", "fbPictureSetSubpixelOrder", "fbScreenInit", NULL }; const char *ATIshadowfbSymbols[] = { "ShadowFBInit", NULL }; const char *ATIxaaSymbols[] = { "XAACreateInfoRec", "XAADestroyInfoRec", "XAAInit", NULL }; const char *ATIramdacSymbols[] = { "xf86CreateCursorInfoRec", "xf86DestroyCursorInfoRec", "xf86InitCursor", NULL }; const char *ATIi2cSymbols[] = { "xf86CreateI2CBusRec", "xf86DestroyI2CBusRec", "xf86I2CBusInit", "xf86I2CDevInit", "xf86I2CFindDev", "xf86I2CGetScreenBuses", NULL }; /* * ATILoadSubModule -- * * Load a specific module and register with the loader those of its entry * points that are referenced by this driver. */ ModuleDescPtr ATILoadSubModule ( ScrnInfoPtr pScreenInfo, const char *Module, const char **SymbolList ) { ModuleDescPtr pModule = xf86LoadSubModule(pScreenInfo, Module); if (pModule) xf86LoaderModReqSymLists(pModule, SymbolList, NULL); return pModule; } /* * ATILoadVBEModule -- * * A variant of ATILoadSubModule() specifically for loading the 'vbe' module. */ ModuleDescPtr ATILoadVBEModule ( ScrnInfoPtr pScreenInfo ) { ModuleDescPtr pModule = xf86LoadVBEModule(pScreenInfo); if (pModule) xf86LoaderModReqSymLists(pModule, ATIvbeSymbols, NULL); return pModule; } /* * ATILoadSubModules -- * * This function loads other modules required for a screen. */ ModuleDescPtr ATILoadSubModules ( ScrnInfoPtr pScreenInfo, ATIPtr pATI ) { /* Load shadow frame buffer code if needed */ if (pATI->OptionShadowFB && !ATILoadSubModule(pScreenInfo, "shadowfb", ATIshadowfbSymbols)) return NULL; /* Load XAA if needed */ if (pATI->OptionAccel && !ATILoadSubModule(pScreenInfo, "xaa", ATIxaaSymbols)) return NULL; /* Load ramdac module if needed */ if ((pATI->Cursor > ATI_CURSOR_SOFTWARE) && !ATILoadSubModule(pScreenInfo, "ramdac", ATIramdacSymbols)) return NULL; /* Load depth-specific entry points */ switch (pATI->bitsPerPixel) { case 1: return ATILoadSubModule(pScreenInfo, "xf1bpp", ATIxf1bppSymbols); case 4: return ATILoadSubModule(pScreenInfo, "xf4bpp", ATIxf4bppSymbols); case 8: case 16: case 24: case 32: return ATILoadSubModule(pScreenInfo, "fb", ATIfbSymbols); default: return NULL; } } #endif /* XFree86LOADER */
the_stack_data/231394535.c
#include <stdio.h> #include <stdlib.h> #include <string.h> #define LEN (50) void print_image(char *img); void draw(char *image,char ch, int ch_w, int ch_h, int pairs[2]); int main(int argc, char *argv[]) { char *image = malloc(LEN*LEN); memset(image, ' ', LEN * LEN); draw(image, '@', 4, 4, (int[2]){0,0}); draw(image, '@', 4, 4, (int[2]){15,2}); print_image(image); free(image); return 0; } void draw(char *image, char ch, int ch_w, int ch_h, int coor[2]) { for (int i = coor[1]; i < coor[1] + ch_h && i < LEN; i++) { for (int j = coor[0]; j < coor[0] + ch_w && j < LEN; j++) { *(image + i*LEN +j) = ch; } } } void print_image(char *img) { for (int i = 0; i < LEN; i++) { putchar('-'); } for (int i = 0; i < LEN; i++) { for (int j = 0; j < LEN; j++) { putchar(*(img+i*LEN+j)); } putchar(10); } for (int i = 0; i < LEN; i++) { putchar('-'); } }
the_stack_data/15050.c
#include<stdio.h> int getWeekDay(int year,int month,int day); int getMonthDays(int year,int month); void printMonthCalender(int startDay,int days); int main(void) { int year,month,startDay,monthDays; printf("Please input the year (and month):"); scanf("%d",&year); printf("\nThe result is:"); if(getchar()=='\n') for(int month=1;month<13;month++) { startDay=getWeekDay(year,month,1);//计算出该月第一天是星期几。返回值为0~6,分别代表周日,周一~周六 monthDays=getMonthDays(year,month);//计算出该月共有几天 printf("\n\t\t\t%d-%d\n",year,month); printMonthCalender(startDay,monthDays); } else { scanf("%d",&month); startDay=getWeekDay(year,month,1);//计算出该月第一天是星期几。返回值为0~6,分别代表周日,周一~周六 monthDays=getMonthDays(year,month);//计算出该月共有几天 printf("\n\t\t\t%d-%d\n",year,month); printMonthCalender(startDay,monthDays); } return 0; } int getWeekDay(int year,int month,int day) { int daysY=(year-1)*365+(year-1)/400+(year-1)/4-(year-1)/100;;//从0001年到year-1年共有几天 int daysM=0;//从year年1月到month-1月共有几天 for(int i=1;i<month;i++) daysM+=getMonthDays(year,i);//第二次用到该函数 return (daysY+daysM+day)%7;//公元第一天是周一 } int getMonthDays(int year,int month) { switch(month) { case 1:case 3:case 5:case 7:case 8:case 10:case 12: return 31; case 4:case 6:case 9:case 11: return 30; case 2: if ((year%100)?!(year%4):!(year%400)) return 29;//闰年 else return 28; default: break; } } void printMonthCalender(int startDay,int days) { int i,count=startDay;//控制换行 printf("Sun\tMon\tTue\tWed\tThu\tFri\tSat\n");//打印表头 for(i=0;i<startDay;i++)//打印前面空格 printf("\t"); for(i=1;i<=days;i++) { printf("%d",i); count++; if(count%7!=0) printf("\t"); else printf("\n"); } printf("\n"); }
the_stack_data/192330387.c
/* fmt.c */ /* usage: fmt [-width] [files]... * * Fmt rearrages text in order to make each line have roughly the * same width. Indentation and word spacing is preserved. * * The default width is 72 characters, but you can override that via -width. * If no files are given on the command line, then it reads stdin. */ #include <stdio.h> #ifndef TRUE # define TRUE 1 # define FALSE 0 #endif int width = 72; /* the desired line width */ int isblank; /* is the current output line blank? */ int indent; /* width of the indentation */ char ind[512]; /* indentation text */ char word[1024]; /* word buffer */ /* This function displays a usage message and quits */ void usage() { fprintf(stderr, "usage: fmt [-width] [files]...\n"); exit(2); } /* This function outputs a single word. It takes care of spacing and the * newlines within a paragraph. */ void putword() { int i; /* index into word[], or whatever */ int ww; /* width of the word */ int sw; /* width of spacing after word */ static int psw; /* space width of previous word */ static int tab; /* the width of text already written */ /* separate the word and its spacing */ for (ww = 0; word[ww] && word[ww] != ' '; ww++) { } sw = strlen(word) - ww; word[ww] = '\0'; /* if no spacing (that is, the word was at the end of the line) then * assume 1 space unless the last char of the word was punctuation */ if (sw == 0) { sw = 1; if (word[ww - 1] == '.' || word[ww - 1] == '?' || word[ww - 1] == '!') sw = 2; } /* if this is the first word on the line... */ if (isblank) { /* output the indentation first */ fputs(ind, stdout); tab = indent; } else /* text has already been written to this output line */ { /* will the word fit on this line? */ if (psw + ww + tab <= width) { /* yes - so write the previous word's spacing */ for (i = 0; i < psw; i++) { putchar(' '); } tab += psw; } else { /* no, so write a newline and the indentation */ putchar('\n'); fputs(ind, stdout); tab = indent; } } /* write the word itself */ fputs(word, stdout); tab += ww; /* remember this word's spacing */ psw = sw; /* this output line isn't blank anymore. */ isblank = FALSE; } /* This function reformats text. */ void fmt(in) FILE *in; /* the name of the input stream */ { int ch; /* character from input stream */ int prevch; /* the previous character in the loop */ int i; /* index into ind[] or word[] */ int inword; /* boolean: are we between indent & newline? */ /* for each character in the stream... */ for (indent = -1, isblank = TRUE, inword = FALSE, i = 0, prevch = '\n'; (ch = getc(in)) != EOF; prevch = ch) { /* is this the end of a line? */ if (ch == '\n') { /* if end of last word in the input line */ if (inword) { /* if it really is a word */ if (i > 0) { /* output it */ word[i] = '\0'; putword(); } } else /* blank line in input */ { /* finish the previous paragraph */ if (!isblank) { putchar('\n'); isblank = TRUE; } /* output a blank line */ putchar('\n'); } /* continue with next input line... */ indent = -1; i = 0; inword = FALSE; continue; } /* if we're expecting indentation now... */ if (indent < 0) { /* if this is part of the indentation... */ if (ch == ' ' || ch == '\t') { /* remember it */ ind[i++] = ch; } else /* end of indentation */ { /* mark the end of the indentation string */ ind[i] = '\0'; /* calculate the width of the indentation */ for (i = indent = 0; ind[i]; i++) { if (ind[i] == '\t') indent = (indent | 7) + 1; else indent++; } /* reset the word index */ i = 0; /* reprocess that last character */ ungetc(ch, in); } /* continue in the for-loop */ continue; } /* if we get here, we're either in a word or in the space * after a word. */ inword = TRUE; /* is this the start of a new word? */ if (ch != ' ' && prevch == ' ') { /* yes! output the previous word */ word[i] = '\0'; putword(); /* reset `i' to the start of the word[] buffer */ i = 0; } word[i++] = ch; } /* if necessary, write a final newline */ if (!isblank) { putchar('\n'); isblank = TRUE; } } int main(argc, argv) int argc; char **argv; { FILE *in; /* an input stream */ int error; /* if non-zero, then an error occurred */ int i; /* handle the -width flag, if given */ if (argc > 1 && argv[1][0] == '-') { width = atoi(argv[1] + 1); if (width <= 0) { usage(); } argc--; argv++; } /* if no filenames given, then process stdin */ if (argc == 1) { fmt(stdin); } else /* one or more filenames given */ { for (error = 0, i = 1; i < argc; i++) { in = fopen(argv[i], "r"); if (!in) { perror(argv[i]); error = 3; } else { fmt(in); fclose(in); } } } /* exit, possibly indicating an error */ exit(error); /*NOTREACHED*/ }
the_stack_data/32716.c
#include <stdio.h> int main() { int a = 1, b = 1, c = 1; printf("%d,%d,%d\n",a,b,c); a += b += ++c; printf("%d,%d,%d\n",a,b,c); a = a > b, b = (a < b || b > c), c++; printf("%d,%d,%d\n",a,b,c); }
the_stack_data/75137717.c
#include <stdio.h> #include <stdlib.h> #include <time.h> int main(void) { srand(time(NULL)); int iRand = (rand() % 10 + 1); // generate a random number between 1 and 10 printf("\nI generated the number (%d)\n", iRand); return 0; }
the_stack_data/89201193.c
/** * @file target_flash.c * @brief Implementation of target_flash.h * * DAPLink Interface Firmware * Copyright (c) 2009-2019, ARM Limited, All Rights Reserved * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #if defined(DRAG_N_DROP_SUPPORT) || defined(MESHEVEN_FLASH_SUPPORT) #include "string.h" #include "target_config.h" #include "target_reset.h" #include "gpio.h" #include "target_config.h" #include "intelhex.h" #include "swd_host.h" #include "flash_intf.h" #include "util.h" #include "settings.h" #include "target_family.h" #include "target_board.h" typedef enum { STATE_CLOSED, STATE_OPEN, STATE_ERROR } state_t; static error_t target_flash_init(void); static error_t target_flash_uninit(void); static error_t target_flash_program_page(uint32_t adr, const uint8_t *buf, uint32_t size); static error_t target_flash_erase_sector(uint32_t addr); static error_t target_flash_erase_chip(void); static uint32_t target_flash_program_page_min_size(uint32_t addr); static uint32_t target_flash_erase_sector_size(uint32_t addr); static uint8_t target_flash_busy(void); static const flash_intf_t flash_intf = { target_flash_init, target_flash_uninit, target_flash_program_page, target_flash_erase_sector, target_flash_erase_chip, target_flash_program_page_min_size, target_flash_erase_sector_size, target_flash_busy, }; static state_t state = STATE_CLOSED; const flash_intf_t *const flash_intf_target = &flash_intf; static error_t target_flash_init() { if (g_board_info.target_cfg) { const program_target_t *const flash = g_board_info.target_cfg->flash_algo; if (0 == target_set_state(RESET_PROGRAM)) { return ERROR_RESET; } // Download flash programming algorithm to target and initialise. if (0 == swd_write_memory(flash->algo_start, (uint8_t *)flash->algo_blob, flash->algo_size)) { return ERROR_ALGO_DL; } if (0 == swd_flash_syscall_exec(&flash->sys_call_s, flash->init, g_board_info.target_cfg->flash_start, 0, 0, 0)) { return ERROR_INIT; } state = STATE_OPEN; return ERROR_SUCCESS; } else { return ERROR_FAILURE; } } static error_t target_flash_uninit(void) { if (g_board_info.target_cfg) { if (config_get_auto_rst()) { // Resume the target if configured to do so target_set_state(RESET_RUN); } else { // Leave the target halted until a reset occurs target_set_state(RESET_PROGRAM); } // Check to see if anything needs to be done after programming. // This is usually a no-op for most targets. target_set_state(POST_FLASH_RESET); state = STATE_CLOSED; swd_off(); return ERROR_SUCCESS; } else { return ERROR_FAILURE; } } static error_t target_flash_program_page(uint32_t addr, const uint8_t *buf, uint32_t size) { if (g_board_info.target_cfg) { const program_target_t *const flash = g_board_info.target_cfg->flash_algo; // check if security bits were set if (g_target_family && g_target_family->security_bits_set){ if (1 == g_target_family->security_bits_set(addr, (uint8_t *)buf, size)) { return ERROR_SECURITY_BITS; } } while (size > 0) { uint32_t write_size = MIN(size, flash->program_buffer_size); // Write page to buffer if (!swd_write_memory(flash->program_buffer, (uint8_t *)buf, write_size)) { return ERROR_ALGO_DATA_SEQ; } // Run flash programming if (!swd_flash_syscall_exec(&flash->sys_call_s, flash->program_page, addr, write_size, flash->program_buffer, 0)) { return ERROR_WRITE; } if (config_get_automation_allowed()) { // Verify data flashed if in automation mode if (flash->verify != 0) { if (!swd_flash_syscall_exec(&flash->sys_call_s, flash->verify, addr, write_size, flash->program_buffer, 0)) { return ERROR_WRITE; } } else { while (write_size > 0) { uint8_t rb_buf[16]; uint32_t verify_size = MIN(write_size, sizeof(rb_buf)); if (!swd_read_memory(addr, rb_buf, verify_size)) { return ERROR_ALGO_DATA_SEQ; } if (memcmp(buf, rb_buf, verify_size) != 0) { return ERROR_WRITE; } addr += verify_size; buf += verify_size; size -= verify_size; write_size -= verify_size; } continue; } } addr += write_size; buf += write_size; size -= write_size; } return ERROR_SUCCESS; } else { return ERROR_FAILURE; } } static error_t target_flash_erase_sector(uint32_t addr) { if (g_board_info.target_cfg) { const program_target_t *const flash = g_board_info.target_cfg->flash_algo; // Check to make sure the address is on a sector boundary if ((addr % target_flash_erase_sector_size(addr)) != 0) { return ERROR_ERASE_SECTOR; } if (0 == swd_flash_syscall_exec(&flash->sys_call_s, flash->erase_sector, addr, 0, 0, 0)) { return ERROR_ERASE_SECTOR; } return ERROR_SUCCESS; } else { return ERROR_FAILURE; } } static error_t target_flash_erase_chip(void) { if (g_board_info.target_cfg){ error_t status = ERROR_SUCCESS; const program_target_t *const flash = g_board_info.target_cfg->flash_algo; if (0 == swd_flash_syscall_exec(&flash->sys_call_s, flash->erase_chip, 0, 0, 0, 0)) { return ERROR_ERASE_ALL; } // Reset and re-initialize the target after the erase if required if (g_board_info.target_cfg->erase_reset) { status = target_flash_init(); } return status; } else { return ERROR_FAILURE; } } static uint32_t target_flash_program_page_min_size(uint32_t addr) { if (g_board_info.target_cfg){ uint32_t size = 256; if (size > target_flash_erase_sector_size(addr)) { size = target_flash_erase_sector_size(addr); } return size; } else { return 0; } } static uint32_t target_flash_erase_sector_size(uint32_t addr) { if (g_board_info.target_cfg){ if(g_board_info.target_cfg->sector_info_length > 0) { int sector_index = g_board_info.target_cfg->sector_info_length - 1; for (; sector_index >= 0; sector_index--) { if (addr >= g_board_info.target_cfg->sectors_info[sector_index].start) { return g_board_info.target_cfg->sectors_info[sector_index].size; } } } return g_board_info.target_cfg->sector_size; } else { return 0; } } static uint8_t target_flash_busy(void){ return (state == STATE_OPEN); } #endif
the_stack_data/613162.c
/*************************************************************************** OpenMP-3.0 Example Codes Beta-v1.0 File : task-construct-alg-openmp3x.c Date : Aug 2011 Description : Simple example program to demonstrates the use of openmp new feature "task" and "taskwait" construct for the parllelization of recursive algorithum ( Fibnacci series) OpenMP pragma/ Directive used : #pragma omp parallel #pragma omp single #pragma omp task Input : - Number of threads to use , - Number to specify the upper limit to find the sum fibnacci numbers in the range 1-Number. Output : Sum of the Fibnacci numbers in the specified range **************************************************************************/ /* Header file inclusion */ #include <stdio.h> #include <omp.h> #include<stdlib.h> /* Description : Function to generate the fibnacci series for given range in parallel using the openmp new feature "task" and perform the synchronization using "taskwait" construct. @param [n] : Number */ int fib(int n) { int x, y; if (n<2) return n; else { /* creating the two tasks per recursion level */ #pragma omp task shared(x) firstprivate(n) //printf("\n My Thread ID %d",omp_get_thread_num()); x=fib(n-1); #pragma omp task shared(y) firstprivate(n) //printf("\n My Thread ID %d",omp_get_thread_num()); y=fib(n-2); /*The taskwait directive ensures that the two tasks generated in an invocation of fib() are completed (that is. the tasks compute x and y before that invocation of fib() returns.*/ #pragma omp taskwait return x+y; } }/* End of the Function */ /* main function */ int main(int argc , char **argv) { int number,numThreads; /* Checking for command line arguments */ if( argc != 3 ){ printf("\t\t Very Few Arguments\n "); printf("\t\t Syntax : exec <Number> <No. of Threads>\n"); exit(-1); } /* Initalizing number of threads & upper limit of fibnacci series */ number=atoi(argv[1]); numThreads=atoi(argv[2]); /* Setting the execution environment */ omp_set_dynamic(0); omp_set_num_threads(numThreads); /* Parallel Region will create the team of threads that will eventually execute all the Tasks */ #pragma omp parallel shared(number) { /* Restricting single thread to do the work i.e Create the tasks */ #pragma omp single { printf ("\n Total Threads %d ",omp_get_num_threads()); printf ("\n Fibnacci Number fib(%d) = %d\n\n", number, fib(number)); } } }/* End of main */
the_stack_data/29825906.c
#ifdef CS333_P4 #include "types.h" #include "user.h" #include "pdx.h" int main(int argc, char *argv[]) { int pid, max; unsigned long x = 0; if(argc == 1){ printf(2, "Enter number of processes to create!\n"); exit(); } max = atoi(argv[1]); for (int i = 0; i < max; i++){ sleep(2 * TPS); pid = fork(); if(pid < 0) { printf(2, "Fork failed! \n"); exit(); } if(pid == 0) { sleep(getpid() * TPS); do { x += 1; } while (1); printf(1, "Child %d exiting\n", getpid()); exit(); } } pid = fork(); if(pid == 0) { sleep(5); do { x = x + 1; }while(1); } sleep(200 * TPS); wait(); printf(1, "Parent exiting!\n"); exit(); } #endif //CS333_P4 //Source: https://web.cecs.pdx.edu/~markem/CS333/handouts`
the_stack_data/1288.c
#include <stdarg.h> #include <stdlib.h> extern char *getenv(const char *name); struct s2 { char *t1; char *ut1; int a; }; struct s1 { int a; int b; va_list vas; }; void foo(va_list args) { struct s2 s; s.a = va_arg(args, int); s.ut1 = va_arg(args, char *); s.t1 = va_arg(args, char *); } int forwarder(int n, ...) { struct s1 s; va_start(s.vas, n); foo(s.vas); va_end(s.vas); return 0; } int main() { int rc = forwarder(3, 1, "hello", getenv("gude")); return rc; }
the_stack_data/18887748.c
#include<stdio.h> void mp(char s[],int n); int main() { char a[10]; int i; for(i=0;i<10;i++) scanf("%c",&a[i]); mp(a,10); for(i=0;i<10;i++) printf("%c",a[i]); } void mp(char s[],int n) { int i,j; char t; for(i=0;i<n-1;i++) for(j=0;j<n-i-1;j++) if(s[j]>s[j+1]) { t=s[j]; s[j]=s[j+1]; s[j+1]=t; } }
the_stack_data/58007.c
#include <string.h> #include <stdint.h> static char *twobyte_strstr(const unsigned char *h, const unsigned char *n) { uint16_t nw = n[0]<<8 | n[1], hw = h[0]<<8 | h[1]; for (h++; *h && hw != nw; hw = hw<<8 | *++h); return *h ? (char *)h-1 : 0; } static char *threebyte_strstr(const unsigned char *h, const unsigned char *n) { uint32_t nw = (uint32_t)n[0]<<24 | n[1]<<16 | n[2]<<8; uint32_t hw = (uint32_t)h[0]<<24 | h[1]<<16 | h[2]<<8; for (h+=2; *h && hw != nw; hw = (hw|*++h)<<8); return *h ? (char *)h-2 : 0; } static char *fourbyte_strstr(const unsigned char *h, const unsigned char *n) { uint32_t nw = (uint32_t)n[0]<<24 | n[1]<<16 | n[2]<<8 | n[3]; uint32_t hw = (uint32_t)h[0]<<24 | h[1]<<16 | h[2]<<8 | h[3]; for (h+=3; *h && hw != nw; hw = hw<<8 | *++h); return *h ? (char *)h-3 : 0; } #define MAX(a,b) ((a)>(b)?(a):(b)) #define MIN(a,b) ((a)<(b)?(a):(b)) #define BITOP(a,b,op) \ ((a)[(size_t)(b)/(8*sizeof *(a))] op (size_t)1<<((size_t)(b)%(8*sizeof *(a)))) static char *twoway_strstr(const unsigned char *h, const unsigned char *n) { const unsigned char *z; size_t l, ip, jp, k, p, ms, p0, mem, mem0; size_t byteset[32 / sizeof(size_t)] = { 0 }; size_t shift[256]; /* Computing length of needle and fill shift table */ for (l=0; n[l] && h[l]; l++) BITOP(byteset, n[l], |=), shift[n[l]] = l+1; if (n[l]) return 0; /* hit the end of h */ /* Compute maximal suffix */ ip = -1; jp = 0; k = p = 1; while (jp+k<l) { if (n[ip+k] == n[jp+k]) { if (k == p) { jp += p; k = 1; } else k++; } else if (n[ip+k] > n[jp+k]) { jp += k; k = 1; p = jp - ip; } else { ip = jp++; k = p = 1; } } ms = ip; p0 = p; /* And with the opposite comparison */ ip = -1; jp = 0; k = p = 1; while (jp+k<l) { if (n[ip+k] == n[jp+k]) { if (k == p) { jp += p; k = 1; } else k++; } else if (n[ip+k] < n[jp+k]) { jp += k; k = 1; p = jp - ip; } else { ip = jp++; k = p = 1; } } if (ip+1 > ms+1) ms = ip; else p = p0; /* Periodic needle? */ if (memcmp(n, n+p, ms+1)) { mem0 = 0; p = MAX(ms, l-ms-1) + 1; } else mem0 = l-p; mem = 0; /* Initialize incremental end-of-haystack pointer */ z = h; /* Search loop */ for (;;) { /* Update incremental end-of-haystack pointer */ if (z-h < l) { /* Fast estimate for MIN(l,63) */ size_t grow = l | 63; const unsigned char *z2 = memchr(z, 0, grow); if (z2) { z = z2; if (z-h < l) return 0; } else z += grow; } /* Check last byte first; advance by shift on mismatch */ if (BITOP(byteset, h[l-1], &)) { k = l-shift[h[l-1]]; if (k) { if (k < mem) k = mem; h += k; mem = 0; continue; } } else { h += l; mem = 0; continue; } /* Compare right half */ for (k=MAX(ms+1,mem); n[k] && n[k] == h[k]; k++); if (n[k]) { h += k-ms; mem = 0; continue; } /* Compare left half */ for (k=ms+1; k>mem && n[k-1] == h[k-1]; k--); if (k <= mem) return (char *)h; h += p; mem = mem0; } } char *strstr(const char *h, const char *n) { /* Return immediately on empty needle */ if (!n[0]) return (char *)h; /* Use faster algorithms for short needles */ h = strchr(h, *n); if (!h || !n[1]) return (char *)h; if (!h[1]) return 0; if (!n[2]) return twobyte_strstr((void *)h, (void *)n); if (!h[2]) return 0; if (!n[3]) return threebyte_strstr((void *)h, (void *)n); if (!h[3]) return 0; if (!n[4]) return fourbyte_strstr((void *)h, (void *)n); return twoway_strstr((void *)h, (void *)n); }
the_stack_data/125141257.c
#include <string.h> int main () { char * pch; char str[] = "Example string"; pch = (char*) memchr (str, 'p', strlen(str)); assert((pch - str + 1) == 5); return 0; }
the_stack_data/215769578.c
#define WINDEBUG #include<stdio.h> #include<string.h> #include<stdlib.h> #ifndef WINDEBUG #include<unistd.h> #endif #define M_IN(arg, l, r) ((arg) >= (l) && (arg) <= (r)) #define M_SP(arg) ((arg) == ' ' || (arg) == '\r' || (arg) == '\t' || (arg) == '\n' || (arg) == '\f' || (arg) == '\v') typedef unsigned int uint; int mstrcmp(const char * str1, const char * str2, int f) { int i, j, f1, f2, n1, n2; if (f == 0) return strcmp(str1, str2); if (f == 1) { i = 0; while (str1[i] != 0 && str2[i] != 0 && (str1[i] == str2[i] || (M_IN(str1[i], 'A', 'Z') && M_IN(str2[i], 'a', 'z') && (str1[i] - 'A' == str2[i] - 'a')) || (M_IN(str1[i], 'a', 'z') && M_IN(str2[i], 'A', 'Z') && (str1[i] - 'a' == str2[i] - 'A')))) ++i; return str1[i] - ((int) str2[i]); } if (f == -1) { i = 0; j = 0; f = 0; while (str1[i] != 0 && M_SP(str1[i])) ++i; while (str2[j] != 0 && M_SP(str2[j])) ++j; i += n1 = str1[i] == '-'; j += n2 = str2[j] == '-'; while (str1[i] == '0' || M_SP(str1[i])) ++i; while (str2[j] == '0' || M_SP(str2[j])) ++j; f1 = M_IN(str1[i], '0', '9'); f2 = M_IN(str2[j], '0', '9'); if (!(f1 && f2)) return (n1 ? -f1 : f1) - (n2 ? -f2 : f2); if (n1 ^ n2) return n2 - n1; f1 = 0; f2 = 0; while (str1[i] != 0 && str2[j] != 0) { if (M_SP(str1[i])) { ++i; continue; } if (M_SP(str2[j])) { ++j; continue; } if (M_IN(str1[i], '0', '9') && M_IN(str2[j], '0', '9')) (f) ? 0 : (f = (str1[i] - str2[j])), ++f1, ++f2, ++i, ++j; else return f1 += M_IN(str1[i], '0', '9'), f2 += M_IN(str2[j], '0', '9'), (((n2 = f1 - f2)) ? 0 : (n2 = f)), (n1 ? -n2 : n2); } return f1 += M_IN(str1[i], '0', '9'), f2 += M_IN(str2[j], '0', '9'), (((n2 = f1 - f2)) ? 0 : (n2 = f)), (n1 ? -n2 : n2); } return 0; } char * mfgets(char ** str, uint * count, FILE * stream) { int ptr = 0; *(*str) = 0; while (fgets((*str) + ptr, *count + 1, stream) && strlen((*str) + ptr) == *count - ptr && (*str)[*count - 1] != '\n') ptr = *count, *count <<= 1, (*str) = (char *) realloc((*str), *count + 1); if (!(*(*str))) return NULL; return (*str); } int sortfile(const char * inp, const char * out, const char * tmp1, const char * tmp2, int f) { uint iter, count = 0, i, j, n, k, c, len; FILE * input, * output; FILE * merge[2]; char * str1, * str2; int choose; len = 1000; str1 = (char *) malloc(len + 1); input = fopen(inp, "r"); output = fopen(out, "w"); merge[0] = fopen(tmp1, "w"); merge[1] = fopen(tmp2, "w"); while (mfgets(&str1, &len, input)) { fputs(str1, merge[count++ & 1]); } fputc('\n', merge[!(count & 1)]); fclose(input); fclose(merge[0]); fclose(merge[1]); merge[0] = fopen(tmp1, "r"); merge[1] = fopen(tmp2, "r"); str2 = (char *) malloc(len + 1); for (iter = 0; (count - 1) >> iter > 0; ++iter) { n = (1 << iter); k = count >> (iter + 1); for (c = 0; c < k; ++c) { for (i = 0, j = 0, fgets(str1, len, merge[0]), fgets(str2, len, merge[1]); i < n && j < n;) { choose = mstrcmp(str1, str2, f); if (choose <= 0) { fputs(str1, output); ++i; if (i < n) fgets(str1, len, merge[0]); } else { fputs(str2, output); ++j; if (j < n) fgets(str2, len, merge[1]); } } if (i < n) { fputs(str1, output); for (++i; i < n; ++i) { fgets(str1, len, merge[0]); fputs(str1, output); } } if (j < n) { fputs(str2, output); for (++j; j < n; ++j) { fgets(str2, len, merge[1]); fputs(str2, output); } } } k = count & ((1 << iter) - 1); c = count & (1 << iter); if (!(c && k)) { c += k; for (i = 0; i < c; ++i) { fgets(str1, len, merge[0]); fputs(str1, output); } } else { for (i = 0, j = 0, fgets(str1, len, merge[0]), fgets(str2, len, merge[1]); i < n && j < k;) { choose = mstrcmp(str1, str2, f); if (choose <= 0) { fputs(str1, output); ++i; if (i < n) fgets(str1, len, merge[0]); } else { fputs(str2, output); ++j; if (j < k) fgets(str2, len, merge[1]); } } if (i < n) { fputs(str1, output); for (++i; i < n; ++i) { fgets(str1, len, merge[0]); fputs(str1, output); } } if (j < k) { fputs(str2, output); for (++j; j < k; ++j) { fgets(str2, len, merge[1]); fputs(str2, output); } } } fclose(output); fclose(merge[0]); fclose(merge[1]); if ((count - 1) >> iter == 1) break; output = fopen(out, "r"); merge[0] = fopen(tmp1, "w"); merge[1] = fopen(tmp2, "w"); k = ((count - 1) / (n <<= 1)) + 1; for (c = 0; c < k; ++c) { i = 0; while (i++ < n && fgets(str1, len, output)) { fputs(str1, merge[c & 1]); } } fclose(output); fclose(merge[0]); fclose(merge[1]); output = fopen(out, "w"); merge[0] = fopen(tmp1, "r"); merge[1] = fopen(tmp2, "r"); } free(str1); free(str2); return (int) count; } int mergefiles(const char * in1, const char * in2, const char * out, int f, int bn) { uint len1, len2; char * str1, * str2, * tmp1, * tmp2; FILE * input1, * input2, * output; int choose; len1 = len2 = 1000; str1 = (char *) malloc(len1 + 1); str2 = (char *) malloc(len2 + 1); input1 = fopen(in1, "r"); input2 = fopen(in2, "r"); output = fopen(out, "w"); tmp1 = mfgets(&str1, &len1, input1); tmp2 = mfgets(&str2, &len2, input2); while (tmp1 && tmp2) { choose = mstrcmp(str1, str2, f); if (choose <= 0) { fputs(str1, output); tmp1 = mfgets(&str1, &len1, input1); } else { fputs(str2, output); tmp2 = mfgets(&str2, &len2, input2); } } if (!tmp1) { if (bn && tmp2) str2[strlen(str2) - 1] = 0; if (tmp2) fputs(str2, output); while (mfgets(&str2, &len2, input2)) { if (bn) { str2[strlen(str2) - 1] = 0; fputc('\n', output); } fputs(str2, output); } tmp2 = NULL; } if (!tmp2) { if (bn && tmp1) str1[strlen(str1) - 1] = 0; if (tmp1) fputs(str1, output); while (mfgets(&str1, &len1, input1)) { if (bn) { str1[strlen(str1) - 1] = 0; fputc('\n', output); } fputs(str1, output); } tmp1 = NULL; } free(str1); free(str2); fclose(input1); fclose(input2); fclose(output); return 0; } int check (const char * filename) { uint len1, len2, t; FILE * file; char * str1, * str2, * tmp; len1 = len2 = 1000; str1 = (char *) malloc(len1 + 1); str2 = (char *) malloc(len2 + 1); file = fopen(filename, "r"); tmp = mfgets(&str1, &len1, file); if (!tmp) { free(str1); free(str2); return 0; } while (mfgets(&str2, &len2, file)) { if (strcmp(str1, str2) > 0) { free(str1); free(str2); return 1; } tmp = str1, str1 = str2, str2 = tmp; t = len1, len1 = len2, len2 = t; } free(str1); free(str2); return 0; } int main(int argc, char * argv[]) { int iter, f, i, e, j, o; char files[4][257]; char output[257]; FILE * tmp; if (argc == 1) return 0; *output = 0; iter = 1; f = 0; o = 0; while (*(argv[iter]) == '-') { if (argv[iter][1] == 'c') f = 2; if (argv[iter][1] == 'n') f = -1; if (argv[iter][1] == 'f') f = (f) ? f : 1; if (argv[iter][1] == 'o') strcpy(output, argv[++iter]), o = 1; ++iter; } if (f == 2) { tmp = fopen(argv[iter], "r"); if (!tmp) { printf("Check failed"); return 2; } fclose(tmp); printf("Check file %s - result is %d", argv[iter], e = check(argv[iter])); return e; } /* There are very retarded filenames*/ j = 1; files[0][0] = '.'; files[0][1] = 'a' - 1; files[0][2] = 0; for (i = 0; i < 4; ++i) { if (i) strcpy(files[i], files[i - 1]); e = 1; while (e) { if ((++files[i][j]) > 'z') { if (j == 255) { printf("WUTFACE 26 * 255 files here, cant work in this directory"); return 1; } for (e = 1; e <= j; ++e) files[i][e] = 'a'; files[i][++j] = 'a'; files[i][j + 1] = 0; } #ifdef WINDEBUG e = 0; #else e = 0; /*e = access(files[i], F_OK);*/ #endif } } tmp = fopen(files[0], "w"); fclose(tmp); tmp = fopen(files[1], "w"); fclose(tmp); tmp = fopen(files[2], "w"); fclose(tmp); tmp = fopen(files[3], "w"); fclose(tmp); e = 0; for (i = iter; i < argc; ++i) { tmp = fopen(argv[i], "r"); if (!tmp) { if (o) { tmp = fopen(files[2], "w"); fclose(tmp); mergefiles(files[e], files[2], output, f, 1); } else { tmp = fopen(files[e], "r"); while ((f = fgetc(tmp)) != EOF) putchar(f); fclose(tmp); } remove(files[0]); remove(files[1]); remove(files[2]); remove(files[3]); printf("File number %d does not exist", i - iter + 1); return 1; } fclose(tmp); sortfile(argv[i], files[3], files[2], files[!e], f); mergefiles(files[e], files[3], files[!e], f, 0); e = !e; } if (o) { tmp = fopen(files[2], "w"); fclose(tmp); mergefiles(files[e], files[2], output, f, 1); } else { tmp = fopen(files[e], "r"); while ((f = fgetc(tmp)) != EOF) putchar(f); fclose(tmp); } remove(files[0]); remove(files[1]); remove(files[2]); remove(files[3]); printf("%d file(s) sorted successfully", i - iter); return 0; }
the_stack_data/122014349.c
#include <stdio.h> #include <stdlib.h> void sort(int *ptr,int n) { int i,j,temp; for(i=0;i<n;i++) { for(j=0;j<n-i-1;j++) { if(*(ptr+j)>*(ptr+j+1)) { temp=*(ptr+j); *(ptr+j)=*(ptr+j+1); *(ptr+j+1)=temp; } } } } int main() { int n,i,*p; printf("Enter the number of elemenets\n"); scanf("%d",&n); p=(int *)malloc(n*sizeof(int)); printf("Enter the elements\n"); for(i=0;i<n;i++) { scanf("%d",p+i); } printf("Array\n"); for(i=0;i<n;i++) printf("%d\n",*(p+i)); //Calling sort function sort(p,n); printf("Sorted array\n"); for(i=0;i<n;i++) printf("%d\n",*(p+i)); return 0; }
the_stack_data/168894485.c
int power(int x, int y) { if (y < 0) return (-1); else if (y == 1) return (x); else if (y == 0) return (1); else if ((x * power(x, y-1)) < 0) return (-1); else if ((x * power(x, y-1)) > 2147483647) return (-1); else return (x * power(x, y-1)); }
the_stack_data/329266.c
/** * This is the most basic form of hello world you can write * Some machines may complain that main has a non-integer return type * But our machine will not * * To compile, compile as gcc basic.c * To compile to a specific name, compile as gcc basic.c -o binary_name * To compile with debugging, compile as gcc -g basic.c -o debuggable_binary */ /** * in Java, to receieve input and output, we use System.in and System.out * in C, we also have standard input and standard output, but the libraries * to use them aren't included by default, so we must manually include the * header files. We’ll understand header files in the next few weeks. * In C, printf function is used to send text to the standard output stream. */ #include <stdio.h> void main() { /* similar to System.out.printf */ printf("Hello world! (basic.c)\n"); }
the_stack_data/61585.c
//Q2.Wap input a string and display in reverse order #include<stdio.h> #include<string.h> int main() { char str[100]; printf("Enter the string: "); gets(str); printf("The revrse string is: "); for(int i=strlen(str)-1;i>=0;i--)printf("%c",str[i]); return 0; }
the_stack_data/126703626.c
// RUN: %clang_cc1 -fsyntax-only -verify %s struct foo { int a; }; int main(void) { int a; float b; double d; struct foo s; static int ary[__builtin_classify_type(a)]; static int ary2[(__builtin_classify_type)(a)]; static int ary3[(*__builtin_classify_type)(a)]; // expected-error{{builtin functions must be directly called}} int result; result = __builtin_classify_type(a); result = __builtin_classify_type(b); result = __builtin_classify_type(d); result = __builtin_classify_type(s); }
the_stack_data/154830551.c
/// 3.11. Să se scrie un program care citește numerele întregi a, b, c, d și afișează valoarea cea mai mare dintre fracțiile a/b și c/d. #include <stdio.h> #include <stdlib.h> int main() { int a, b, c, d; printf("Introduceti valoarea pentru a: "); scanf("%d", &a); printf("Introduceti valoarea pentru b: "); scanf("%d", &b); printf("Introduceti valoarea pentru c: "); scanf("%d", &c); printf("Introduceti valoarea pentru d: "); scanf("%d", &d); if((double)a/b > (double)c/d) printf("%d/%d", a, b); else printf("%d/%d", c, d); return 0; }
the_stack_data/211080795.c
#include <math.h> #include <float.h> #include <stdlib.h> #include <stdint.h> #include <limits.h> #include <stdio.h> #define check_d1(func, param, expected) \ do { \ int err; hex_union ur; hex_union up; \ double result = func(param); up.f = param; ur.f = result; \ errors += (err = (result != (expected))); \ err \ ? printf("FAIL: %s(%g/"HEXFMT")=%g/"HEXFMT" (expected %g)\n", \ #func, (double)(param), (long long)up.hex, result, (long long)ur.hex, (double)(expected)) \ : printf("PASS: %s(%g)=%g\n", #func, (double)(param), result); \ } while (0) #define check_i1(func, param, expected) \ do { \ int err; hex_union up; \ long long result = func(param); up.f = param; \ errors += (err = (result != (expected))); \ err \ ? printf("FAIL: %s(%g/"HEXFMT")=%lld/%llu (expected %llu)\n", \ #func, (double)(param), (long long)up.hex, result, result, (long long)(expected)) \ : printf("PASS: %s(%g)=%lld/%llu\n", #func, (double)(param), result, result); \ } while (0) #define HEXFMT "%08llx" typedef union { double f; uint64_t hex; } hex_union; double nan_value = 0.0; int errors = 0; int main(void) { nan_value /= nan_value; check_i1(ilogb, 0.0, FP_ILOGB0); check_i1(ilogb, HUGE_VAL, INT_MAX); check_i1(ilogb, nan_value, FP_ILOGBNAN); check_i1(ilogbf, 0.0, FP_ILOGB0); check_i1(ilogbf, HUGE_VALF, INT_MAX); check_i1(ilogbf, nan_value, FP_ILOGBNAN); printf("Errors: %d\n", errors); return errors; }
the_stack_data/1237808.c
#ifdef __APPLE__ #include "frida-gumjs.h" #include "lib.h" #include "util.h" extern mach_port_t mach_task_self(); extern void gum_darwin_enumerate_modules(mach_port_t task, GumFoundModuleFunc func, gpointer user_data); static guint64 text_base = 0; static guint64 text_limit = 0; static gboolean lib_get_main_module(const GumModuleDetails *details, gpointer user_data) { GumDarwinModule **ret = (GumDarwinModule **)user_data; GumDarwinModule * module = gum_darwin_module_new_from_memory( details->path, mach_task_self(), details->range->base_address, GUM_DARWIN_MODULE_FLAGS_NONE, NULL); FVERBOSE("Found main module: %s", module->name); *ret = module; return FALSE; } gboolean lib_get_text_section(const GumDarwinSectionDetails *details, gpointer user_data) { UNUSED_PARAMETER(user_data); static size_t idx = 0; char text_name[] = "__text"; FVERBOSE("\t%2lu - base: 0x%016" G_GINT64_MODIFIER "X size: 0x%016" G_GINT64_MODIFIER "X %s", idx++, details->vm_address, details->vm_address + details->size, details->section_name); if (memcmp(details->section_name, text_name, sizeof(text_name)) == 0 && text_base == 0) { text_base = details->vm_address; text_limit = details->vm_address + details->size; } FVERBOSE(".text\n"); FVERBOSE("\taddr: 0x%016" G_GINT64_MODIFIER "X", text_base); FVERBOSE("\tlimit: 0x%016" G_GINT64_MODIFIER "X", text_limit); return TRUE; } void lib_config(void) { } void lib_init(void) { GumDarwinModule *module = NULL; gum_darwin_enumerate_modules(mach_task_self(), lib_get_main_module, &module); FVERBOSE("Sections:"); gum_darwin_module_enumerate_sections(module, lib_get_text_section, NULL); } guint64 lib_get_text_base(void) { if (text_base == 0) FFATAL("Lib not initialized"); return text_base; } guint64 lib_get_text_limit(void) { if (text_limit == 0) FFATAL("Lib not initialized"); return text_limit; } #endif
the_stack_data/93887605.c
/* Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <stdio.h> #include <string.h> #include <stdlib.h> #include <sys/stat.h> #include <sys/types.h> #if !defined(__MINGW32__) #include <sys/wait.h> #endif #include <unistd.h> #include <dirent.h> #include <errno.h> #include <assert.h> #ifdef __EMX__ # define SHELL_CMD "sh" # define GEN_EXPORTS "emxexp" # define DEF2IMPLIB_CMD "emximp" # define SHARE_SW "-Zdll -Zmtd" # define USE_OMF 1 # define TRUNCATE_DLL_NAME # define DYNAMIC_LIB_EXT "dll" # define EXE_EXT ".exe" # if USE_OMF /* OMF is the native format under OS/2 */ # define STATIC_LIB_EXT "lib" # define OBJECT_EXT "obj" # define LIBRARIAN "emxomfar" # define LIBRARIAN_OPTS "cr" # else /* but the alternative, a.out, can fork() which is sometimes necessary */ # define STATIC_LIB_EXT "a" # define OBJECT_EXT "o" # define LIBRARIAN "ar" # define LIBRARIAN_OPTS "cr" # endif #endif #if defined(__APPLE__) # define SHELL_CMD "/bin/sh" # define DYNAMIC_LIB_EXT "dylib" # define MODULE_LIB_EXT "bundle" # define STATIC_LIB_EXT "a" # define OBJECT_EXT "o" # define LIBRARIAN "ar" # define LIBRARIAN_OPTS "cr" /* man libtool(1) documents ranlib option of -c. */ # define RANLIB "ranlib" # define PIC_FLAG "-fPIC -fno-common" # define SHARED_OPTS "-dynamiclib" # define MODULE_OPTS "-bundle -dynamic" # define DYNAMIC_LINK_OPTS "-flat_namespace" # define DYNAMIC_LINK_UNDEFINED "-undefined suppress" # define dynamic_link_version_func darwin_dynamic_link_function # define DYNAMIC_INSTALL_NAME "-install_name" # define DYNAMIC_LINK_NO_INSTALL "-dylib_file" # define HAS_REALPATH /*-install_name /Users/jerenk/apache-2.0-cvs/lib/libapr.0.dylib -compatibility_version 1 -current_version 1.0 */ # define LD_LIBRARY_PATH "DYLD_LIBRARY_PATH" #endif #if defined(__linux__) || defined(__FreeBSD__) || defined(__NetBSD__) # define SHELL_CMD "/bin/sh" # define DYNAMIC_LIB_EXT "so" # define MODULE_LIB_EXT "so" # define STATIC_LIB_EXT "a" # define OBJECT_EXT "o" # define LIBRARIAN "ar" # define LIBRARIAN_OPTS "cr" # define RANLIB "ranlib" # define PIC_FLAG "-fPIC" # define RPATH "-rpath" # define SHARED_OPTS "-shared" # define MODULE_OPTS "-shared" # define DYNAMIC_LINK_OPTS "-export-dynamic" # define LINKER_FLAG_PREFIX "-Wl," # define ADD_MINUS_L # define LD_RUN_PATH "LD_RUN_PATH" # define LD_LIBRARY_PATH "LD_LIBRARY_PATH" #endif #if defined(sun) # define SHELL_CMD "/bin/sh" # define DYNAMIC_LIB_EXT "so" # define MODULE_LIB_EXT "so" # define STATIC_LIB_EXT "a" # define OBJECT_EXT "o" # define LIBRARIAN "ar" # define LIBRARIAN_OPTS "cr" # define RANLIB "ranlib" # define PIC_FLAG "-KPIC" # define RPATH "-R" # define SHARED_OPTS "-G" # define MODULE_OPTS "-G" # define DYNAMIC_LINK_OPTS "" # define LINKER_FLAG_NO_EQUALS # define ADD_MINUS_L # define HAS_REALPATH # define LD_RUN_PATH "LD_RUN_PATH" # define LD_LIBRARY_PATH "LD_LIBRARY_PATH" #endif #if defined(_OSD_POSIX) # define SHELL_CMD "/usr/bin/sh" # define DYNAMIC_LIB_EXT "so" # define MODULE_LIB_EXT "so" # define STATIC_LIB_EXT "a" # define OBJECT_EXT "o" # define LIBRARIAN "ar" # define LIBRARIAN_OPTS "cr" # define SHARED_OPTS "-G" # define MODULE_OPTS "-G" # define LINKER_FLAG_PREFIX "-Wl," # define NEED_SNPRINTF #endif #if defined(sinix) && defined(mips) && defined(__SNI_TARG_UNIX) # define SHELL_CMD "/usr/bin/sh" # define DYNAMIC_LIB_EXT "so" # define MODULE_LIB_EXT "so" # define STATIC_LIB_EXT "a" # define OBJECT_EXT "o" # define LIBRARIAN "ar" # define LIBRARIAN_OPTS "cr" # define RPATH "-Brpath" # define SHARED_OPTS "-G" # define MODULE_OPTS "-G" # define DYNAMIC_LINK_OPTS "-Wl,-Blargedynsym" # define LINKER_FLAG_PREFIX "-Wl," # define NEED_SNPRINTF # define LD_RUN_PATH "LD_RUN_PATH" # define LD_LIBRARY_PATH "LD_LIBRARY_PATH" #endif #if defined(__MINGW32__) # define SHELL_CMD "sh" # define DYNAMIC_LIB_EXT "dll" # define MODULE_LIB_EXT "dll" # define STATIC_LIB_EXT "a" # define OBJECT_EXT "o" # define LIBRARIAN "ar" # define LIBRARIAN_OPTS "cr" # define RANLIB "ranlib" # define LINKER_FLAG_PREFIX "-Wl," # define SHARED_OPTS "-shared" # define MODULE_OPTS "-shared" # define MKDIR_NO_UMASK # define EXE_EXT ".exe" #endif #ifndef SHELL_CMD #error Unsupported platform: Please add defines for SHELL_CMD etc. for your platform. #endif #ifdef NEED_SNPRINTF #include <stdarg.h> #endif #ifdef __EMX__ #include <process.h> #endif #ifndef PATH_MAX #define PATH_MAX 1024 #endif /* We want to say we are libtool 1.4 for shlibtool compatibility. */ #define VERSION "1.4" enum tool_mode_t { mUnknown, mCompile, mLink, mInstall, }; enum output_t { otGeneral, otObject, otProgram, otLibrary, otStaticLibraryOnly, otDynamicLibraryOnly, otModule, }; enum pic_mode_e { pic_UNKNOWN, pic_PREFER, pic_AVOID, }; enum shared_mode_e { share_UNSET, share_STATIC, share_SHARED, }; enum lib_type { type_UNKNOWN, type_DYNAMIC_LIB, type_STATIC_LIB, type_MODULE_LIB, type_OBJECT, }; typedef struct { const char **vals; int num; } count_chars; typedef struct { const char *normal; const char *install; } library_name; typedef struct { count_chars *normal; count_chars *install; count_chars *dependencies; } library_opts; typedef struct { int silent; enum shared_mode_e shared; int export_all; int dry_run; enum pic_mode_e pic_mode; int export_dynamic; int no_install; } options_t; typedef struct { enum tool_mode_t mode; enum output_t output; options_t options; char *output_name; char *fake_output_name; char *basename; const char *install_path; const char *compiler; const char *program; count_chars *program_opts; count_chars *arglist; count_chars *tmp_dirs; count_chars *obj_files; count_chars *dep_rpaths; count_chars *rpaths; library_name static_name; library_name shared_name; library_name module_name; library_opts static_opts; library_opts shared_opts; const char *version_info; const char *undefined_flag; } command_t; #ifdef RPATH void add_rpath(count_chars *cc, const char *path); #endif #if defined(NEED_SNPRINTF) /* Write at most n characters to the buffer in str, return the * number of chars written or -1 if the buffer would have been * overflowed. * * This is portable to any POSIX-compliant system has /dev/null */ static FILE *f=NULL; static int vsnprintf( char *str, size_t n, const char *fmt, va_list ap ) { int res; if (f == NULL) f = fopen("/dev/null","w"); if (f == NULL) return -1; setvbuf( f, str, _IOFBF, n ); res = vfprintf( f, fmt, ap ); if ( res > 0 && res < n ) { res = vsprintf( str, fmt, ap ); } return res; } static int snprintf( char *str, size_t n, const char *fmt, ... ) { va_list ap; int res; va_start( ap, fmt ); res = vsnprintf( str, n, fmt, ap ); va_end( ap ); return res; } #endif void init_count_chars(count_chars *cc) { cc->vals = (const char**)malloc(PATH_MAX*sizeof(char*)); cc->num = 0; } void clear_count_chars(count_chars *cc) { int i; for (i = 0; i < cc->num; i++) { cc->vals[i] = 0; } cc->num = 0; } void push_count_chars(count_chars *cc, const char *newval) { cc->vals[cc->num++] = newval; } void pop_count_chars(count_chars *cc) { cc->num--; } void insert_count_chars(count_chars *cc, const char *newval, int position) { int i; for (i = cc->num; i > position; i--) { cc->vals[i] = cc->vals[i-1]; } cc->vals[position] = newval; cc->num++; } void append_count_chars(count_chars *cc, count_chars *cctoadd) { int i; for (i = 0; i < cctoadd->num; i++) { if (cctoadd->vals[i]) { push_count_chars(cc, cctoadd->vals[i]); } } } const char *flatten_count_chars(count_chars *cc, int space) { int i, size; char *newval; size = 0; for (i = 0; i < cc->num; i++) { if (cc->vals[i]) { size += strlen(cc->vals[i]) + 1; if (space) { size++; } } } newval = (char*)malloc(size + 1); newval[0] = 0; for (i = 0; i < cc->num; i++) { if (cc->vals[i]) { strcat(newval, cc->vals[i]); if (space) { strcat(newval, " "); } } } return newval; } char *shell_esc(const char *str) { int in_quote = 0; char *cmd; unsigned char *d; const unsigned char *s; cmd = (char *)malloc(2 * strlen(str) + 3); d = (unsigned char *)cmd; s = (const unsigned char *)str; #ifdef __MINGW32__ *d++ = '\"'; #endif for (; *s; ++s) { if (*s == '"') { *d++ = '\\'; in_quote++; } else if (*s == '\\' || (*s == ' ' && (in_quote % 2))) { *d++ = '\\'; } *d++ = *s; } #ifdef __MINGW32__ *d++ = '\"'; #endif *d = '\0'; return cmd; } int external_spawn(command_t *cmd, const char *file, const char **argv) { if (!cmd->options.silent) { const char **argument = argv; printf("Executing: "); while (*argument) { printf("%s ", *argument); argument++; } puts(""); } if (cmd->options.dry_run) { return 0; } #if defined(__EMX__) || defined(__MINGW32__) return spawnvp(P_WAIT, argv[0], argv); #else { pid_t pid; pid = fork(); if (pid == 0) { return execvp(argv[0], (char**)argv); } else { int statuscode; waitpid(pid, &statuscode, 0); if (WIFEXITED(statuscode)) { return WEXITSTATUS(statuscode); } return 0; } } #endif } int run_command(command_t *cmd_data, count_chars *cc) { char *command; const char *spawn_args[4]; count_chars tmpcc; init_count_chars(&tmpcc); if (cmd_data->program) { push_count_chars(&tmpcc, cmd_data->program); } append_count_chars(&tmpcc, cmd_data->program_opts); append_count_chars(&tmpcc, cc); command = shell_esc(flatten_count_chars(&tmpcc, 1)); spawn_args[0] = SHELL_CMD; spawn_args[1] = "-c"; spawn_args[2] = command; spawn_args[3] = NULL; return external_spawn(cmd_data, spawn_args[0], (const char**)spawn_args); } /* * print configuration * shlibpath_var is used in configure. */ void print_config() { #ifdef LD_RUN_PATH printf("runpath_var=%s\n", LD_RUN_PATH); #endif #ifdef LD_LIBRARY_PATH printf("shlibpath_var=%s\n", LD_LIBRARY_PATH); #endif #ifdef SHELL_CMD printf("SHELL=\"%s\"\n", SHELL_CMD); #endif } /* * Add a directory to the runtime library search path. */ void add_runtimedirlib(char *arg, command_t *cmd_data) { #ifdef RPATH add_rpath(cmd_data->shared_opts.dependencies, arg); #else #endif } int parse_long_opt(char *arg, command_t *cmd_data) { char *equal_pos = strchr(arg, '='); char var[50]; char value[500]; if (equal_pos) { strncpy(var, arg, equal_pos - arg); var[equal_pos - arg] = 0; strcpy(value, equal_pos + 1); } else { strcpy(var, arg); } if (strcmp(var, "silent") == 0) { cmd_data->options.silent = 1; } else if (strcmp(var, "mode") == 0) { if (strcmp(value, "compile") == 0) { cmd_data->mode = mCompile; cmd_data->output = otObject; } if (strcmp(value, "link") == 0) { cmd_data->mode = mLink; cmd_data->output = otLibrary; } if (strcmp(value, "install") == 0) { cmd_data->mode = mInstall; } } else if (strcmp(var, "shared") == 0) { if (cmd_data->mode == mLink) { cmd_data->output = otDynamicLibraryOnly; } cmd_data->options.shared = share_SHARED; } else if (strcmp(var, "export-all") == 0) { cmd_data->options.export_all = 1; } else if (strcmp(var, "dry-run") == 0) { printf("Dry-run mode on!\n"); cmd_data->options.dry_run = 1; } else if (strcmp(var, "version") == 0) { printf("Version " VERSION "\n"); } else if (strcmp(var, "help") == 0) { printf("Sorry. No help available.\n"); } else if (strcmp(var, "config") == 0) { print_config(); } else if (strcmp(var, "tag") == 0) { if (strcmp(value, "CC") == 0) { /* Do nothing. */ } if (strcmp(value, "CXX") == 0) { /* Do nothing. */ } } else { return 0; } return 1; } /* Return 1 if we eat it. */ int parse_short_opt(char *arg, command_t *cmd_data) { if (strcmp(arg, "export-dynamic") == 0) { cmd_data->options.export_dynamic = 1; return 1; } if (strcmp(arg, "module") == 0) { cmd_data->output = otModule; return 1; } if (strcmp(arg, "shared") == 0) { if (cmd_data->mode == mLink) { cmd_data->output = otDynamicLibraryOnly; } cmd_data->options.shared = share_SHARED; return 1; } if (strcmp(arg, "Zexe") == 0) { return 1; } if (strcmp(arg, "avoid-version") == 0) { return 1; } if (strcmp(arg, "prefer-pic") == 0) { cmd_data->options.pic_mode = pic_PREFER; return 1; } if (strcmp(arg, "prefer-non-pic") == 0) { cmd_data->options.pic_mode = pic_AVOID; return 1; } if (strcmp(arg, "static") == 0) { cmd_data->options.shared = share_STATIC; return 1; } if (cmd_data->mode == mLink) { if (strcmp(arg, "no-install") == 0) { cmd_data->options.no_install = 1; return 1; } if (arg[0] == 'L' || arg[0] == 'l') { /* Hack... */ arg--; push_count_chars(cmd_data->shared_opts.dependencies, arg); return 1; } else if (arg[0] == 'R' && arg[1]) { /* -Rdir Add dir to runtime library search path. */ add_runtimedirlib(&arg[1], cmd_data); return 1; } } return 0; } char *truncate_dll_name(char *path) { /* Cut DLL name down to 8 characters after removing any mod_ prefix */ char *tmppath = strdup(path); char *newname = strrchr(tmppath, '/') + 1; char *ext = strrchr(tmppath, '.'); int len; if (ext == NULL) return tmppath; len = ext - newname; if (strncmp(newname, "mod_", 4) == 0) { strcpy(newname, newname + 4); len -= 4; } if (len > 8) { strcpy(newname + 8, strchr(newname, '.')); } return tmppath; } long safe_strtol(const char *nptr, const char **endptr, int base) { long rv; errno = 0; rv = strtol(nptr, (char**)endptr, 10); if (errno == ERANGE) { return 0; } return rv; } void safe_mkdir(const char *path) { mode_t old_umask; old_umask = umask(0); umask(old_umask); #ifdef MKDIR_NO_UMASK mkdir(path); #else mkdir(path, ~old_umask); #endif } /* returns just a file's name without the path */ const char *jlibtool_basename(const char *fullpath) { const char *name = strrchr(fullpath, '/'); if (name == NULL) { name = strrchr(fullpath, '\\'); } if (name == NULL) { name = fullpath; } else { name++; } return name; } /* returns just a file's name without path or extension */ const char *nameof(const char *fullpath) { const char *name; const char *ext; name = jlibtool_basename(fullpath); ext = strrchr(name, '.'); if (ext) { char *trimmed; trimmed = malloc(ext - name + 1); strncpy(trimmed, name, ext - name); trimmed[ext-name] = 0; return trimmed; } return name; } /* version_info is in the form of MAJOR:MINOR:PATCH */ const char *darwin_dynamic_link_function(const char *version_info) { char *newarg; long major, minor, patch; major = 0; minor = 0; patch = 0; if (version_info) { major = safe_strtol(version_info, &version_info, 10); if (version_info) { if (version_info[0] == ':') { version_info++; } minor = safe_strtol(version_info, &version_info, 10); if (version_info) { if (version_info[0] == ':') { version_info++; } patch = safe_strtol(version_info, &version_info, 10); } } } /* Avoid -dylib_compatibility_version must be greater than zero errors. */ if (major == 0) { major = 1; } newarg = (char*)malloc(100); snprintf(newarg, 99, "-compatibility_version %ld -current_version %ld.%ld", major, major, minor); return newarg; } /* genlib values * 0 - static * 1 - dynamic * 2 - module */ char *gen_library_name(const char *name, int genlib) { char *newarg, *newext; newarg = (char *)malloc(strlen(name) + 11); strcpy(newarg, ".libs/"); if (genlib == 2 && strncmp(name, "lib", 3) == 0) { name += 3; } if (genlib == 2) { strcat(newarg, jlibtool_basename(name)); } else { strcat(newarg, name); } newext = strrchr(newarg, '.') + 1; switch (genlib) { case 0: strcpy(newext, STATIC_LIB_EXT); break; case 1: strcpy(newext, DYNAMIC_LIB_EXT); break; case 2: strcpy(newext, MODULE_LIB_EXT); break; } return newarg; } /* genlib values * 0 - static * 1 - dynamic * 2 - module */ char *gen_install_name(const char *name, int genlib) { struct stat sb; char *newname; int rv; newname = gen_library_name(name, genlib); /* Check if it exists. If not, return NULL. */ rv = stat(newname, &sb); if (rv) { return NULL; } return newname; } char *check_object_exists(command_t *cmd, const char *arg, int arglen) { char *newarg, *ext; int pass, rv; newarg = (char *)malloc(arglen + 10); memcpy(newarg, arg, arglen); newarg[arglen] = 0; ext = newarg + arglen; pass = 0; do { struct stat sb; switch (pass) { case 0: strcpy(ext, OBJECT_EXT); break; /* case 1: strcpy(ext, NO_PIC_EXT); break; */ default: break; } if (!cmd->options.silent) { printf("Checking (obj): %s\n", newarg); } rv = stat(newarg, &sb); } while (rv != 0 && ++pass < 1); if (rv == 0) { if (pass == 1) { cmd->options.pic_mode = pic_AVOID; } return newarg; } return NULL; } /* libdircheck values: * 0 - no .libs suffix * 1 - .libs suffix */ char *check_library_exists(command_t *cmd, const char *arg, int pathlen, int libdircheck, enum lib_type *libtype) { char *newarg, *ext; int pass, rv, newpathlen; newarg = (char *)malloc(strlen(arg) + 10); strcpy(newarg, arg); newarg[pathlen] = 0; newpathlen = pathlen; if (libdircheck) { strcat(newarg, ".libs/"); newpathlen += sizeof(".libs/") - 1; } strcpy(newarg+newpathlen, arg+pathlen); ext = strrchr(newarg, '.') + 1; pass = 0; do { struct stat sb; switch (pass) { case 0: if (cmd->options.pic_mode != pic_AVOID && cmd->options.shared != share_STATIC) { strcpy(ext, DYNAMIC_LIB_EXT); *libtype = type_DYNAMIC_LIB; break; } pass = 1; /* Fall through */ case 1: strcpy(ext, STATIC_LIB_EXT); *libtype = type_STATIC_LIB; break; case 2: strcpy(ext, MODULE_LIB_EXT); *libtype = type_MODULE_LIB; break; case 3: strcpy(ext, OBJECT_EXT); *libtype = type_OBJECT; break; default: *libtype = type_UNKNOWN; break; } if (!cmd->options.silent) { printf("Checking (lib): %s\n", newarg); } rv = stat(newarg, &sb); } while (rv != 0 && ++pass < 4); if (rv == 0) { return newarg; } return NULL; } char * load_install_path(const char *arg) { FILE *f; char *path; path = malloc(PATH_MAX); f = fopen(arg,"r"); if (f == NULL) { return NULL; } fgets(path, PATH_MAX, f); fclose(f); if (path[strlen(path)-1] == '\n') { path[strlen(path)-1] = '\0'; } /* Check that we have an absolute path. * Otherwise the file could be a GNU libtool file. */ if (path[0] != '/') { return NULL; } return path; } char * load_noinstall_path(const char *arg, int pathlen) { char *newarg, *expanded_path; int newpathlen; newarg = (char *)malloc(strlen(arg) + 10); strcpy(newarg, arg); newarg[pathlen] = 0; newpathlen = pathlen; strcat(newarg, ".libs"); newpathlen += sizeof(".libs") - 1; newarg[newpathlen] = 0; #ifdef HAS_REALPATH expanded_path = malloc(PATH_MAX); expanded_path = realpath(newarg, expanded_path); /* Uh, oh. There was an error. Fall back on our first guess. */ if (!expanded_path) { expanded_path = newarg; } #else /* We might get ../ or something goofy. Oh, well. */ expanded_path = newarg; #endif return expanded_path; } void add_dynamic_link_opts(command_t *cmd_data, count_chars *args) { #ifdef DYNAMIC_LINK_OPTS if (cmd_data->options.pic_mode != pic_AVOID) { if (!cmd_data->options.silent) { printf("Adding: %s\n", DYNAMIC_LINK_OPTS); } push_count_chars(args, DYNAMIC_LINK_OPTS); if (cmd_data->undefined_flag) { push_count_chars(args, "-undefined"); #if defined(__APPLE__) /* -undefined dynamic_lookup is used by the bundled Python in * 10.4, but if we don't set MACOSX_DEPLOYMENT_TARGET to 10.3+, * we'll get a linker error if we pass this flag. */ if (strcasecmp(cmd_data->undefined_flag, "dynamic_lookup") == 0) { insert_count_chars(cmd_data->program_opts, "MACOSX_DEPLOYMENT_TARGET=10.3", 0); } #endif push_count_chars(args, cmd_data->undefined_flag); } else { #ifdef DYNAMIC_LINK_UNDEFINED if (!cmd_data->options.silent) { printf("Adding: %s\n", DYNAMIC_LINK_UNDEFINED); } push_count_chars(args, DYNAMIC_LINK_UNDEFINED); #endif } } #endif } /* Read the final install location and add it to runtime library search path. */ #ifdef RPATH void add_rpath(count_chars *cc, const char *path) { int size = 0; char *tmp; #ifdef LINKER_FLAG_PREFIX size = strlen(LINKER_FLAG_PREFIX); #endif size = size + strlen(path) + strlen(RPATH) + 2; tmp = malloc(size); if (tmp == NULL) { return; } #ifdef LINKER_FLAG_PREFIX strcpy(tmp, LINKER_FLAG_PREFIX); strcat(tmp, RPATH); #else strcpy(tmp, RPATH); #endif #ifndef LINKER_FLAG_NO_EQUALS strcat(tmp, "="); #endif strcat(tmp, path); push_count_chars(cc, tmp); } void add_rpath_file(count_chars *cc, const char *arg) { const char *path; path = load_install_path(arg); if (path) { add_rpath(cc, path); } } void add_rpath_noinstall(count_chars *cc, const char *arg, int pathlen) { const char *path; path = load_noinstall_path(arg, pathlen); if (path) { add_rpath(cc, path); } } #endif #ifdef DYNAMIC_LINK_NO_INSTALL void add_dylink_noinstall(count_chars *cc, const char *arg, int pathlen, int extlen) { const char *install_path, *current_path, *name; char *exp_argument; int i_p_len, c_p_len, name_len, dyext_len, cur_len; install_path = load_install_path(arg); current_path = load_noinstall_path(arg, pathlen); if (!install_path || !current_path) { return; } push_count_chars(cc, DYNAMIC_LINK_NO_INSTALL); i_p_len = strlen(install_path); c_p_len = strlen(current_path); name = arg+pathlen; name_len = extlen-pathlen; dyext_len = sizeof(DYNAMIC_LIB_EXT) - 1; /* No, we need to replace the extension. */ exp_argument = (char *)malloc(i_p_len + c_p_len + (name_len*2) + (dyext_len*2) + 2); cur_len = 0; strcpy(exp_argument, install_path); cur_len += i_p_len; exp_argument[cur_len++] = '/'; strncpy(exp_argument+cur_len, name, extlen-pathlen); cur_len += name_len; strcpy(exp_argument+cur_len, DYNAMIC_LIB_EXT); cur_len += dyext_len; exp_argument[cur_len++] = ':'; strcpy(exp_argument+cur_len, current_path); cur_len += c_p_len; exp_argument[cur_len++] = '/'; strncpy(exp_argument+cur_len, name, extlen-pathlen); cur_len += name_len; strcpy(exp_argument+cur_len, DYNAMIC_LIB_EXT); cur_len += dyext_len; push_count_chars(cc, exp_argument); } #endif /* use -L -llibname to allow to use installed libraries */ void add_minus_l(count_chars *cc, const char *arg) { char *newarg; char *name = strrchr(arg, '/'); char *file = strrchr(arg, '.'); char *lib = strstr(name, "lib"); if (name !=NULL && file != NULL && lib == name+1) { *name = '\0'; *file = '\0'; file = name; file = file+4; push_count_chars(cc, "-L"); push_count_chars(cc, arg); /* we need one argument like -lapr-1 */ newarg = malloc(strlen(file) + 3); strcpy(newarg, "-l"); strcat(newarg, file); push_count_chars(cc, newarg); } else { push_count_chars(cc, arg); } } void add_linker_flag_prefix(count_chars *cc, const char *arg) { #ifndef LINKER_FLAG_PREFIX push_count_chars(cc, arg); #else char *newarg; newarg = (char*)malloc(strlen(arg) + sizeof(LINKER_FLAG_PREFIX) + 1); strcpy(newarg, LINKER_FLAG_PREFIX); strcat(newarg, arg); push_count_chars(cc, newarg); #endif } int explode_static_lib(command_t *cmd_data, const char *lib) { count_chars tmpdir_cc, libname_cc; const char *tmpdir, *libname; char savewd[PATH_MAX]; const char *name; DIR *dir; struct dirent *entry; const char *lib_args[4]; /* Bah! */ if (cmd_data->options.dry_run) { return 0; } name = jlibtool_basename(lib); init_count_chars(&tmpdir_cc); push_count_chars(&tmpdir_cc, ".libs/"); push_count_chars(&tmpdir_cc, name); push_count_chars(&tmpdir_cc, ".exploded/"); tmpdir = flatten_count_chars(&tmpdir_cc, 0); if (!cmd_data->options.silent) { printf("Making: %s\n", tmpdir); } safe_mkdir(tmpdir); push_count_chars(cmd_data->tmp_dirs, tmpdir); getcwd(savewd, sizeof(savewd)); if (chdir(tmpdir) != 0) { if (!cmd_data->options.silent) { printf("Warning: could not explode %s\n", lib); } return 1; } if (lib[0] == '/') { libname = lib; } else { init_count_chars(&libname_cc); push_count_chars(&libname_cc, "../../"); push_count_chars(&libname_cc, lib); libname = flatten_count_chars(&libname_cc, 0); } lib_args[0] = LIBRARIAN; lib_args[1] = "x"; lib_args[2] = libname; lib_args[3] = NULL; external_spawn(cmd_data, LIBRARIAN, lib_args); chdir(savewd); dir = opendir(tmpdir); while ((entry = readdir(dir)) != NULL) { #if defined(__APPLE__) && defined(RANLIB) /* Apple inserts __.SYMDEF which isn't needed. * Leopard (10.5+) can also add '__.SYMDEF SORTED' which isn't * much fun either. Just skip them. */ if (strstr(entry->d_name, "__.SYMDEF") != NULL) { continue; } #endif if (entry->d_name[0] != '.') { push_count_chars(&tmpdir_cc, entry->d_name); name = flatten_count_chars(&tmpdir_cc, 0); if (!cmd_data->options.silent) { printf("Adding: %s\n", name); } push_count_chars(cmd_data->obj_files, name); pop_count_chars(&tmpdir_cc); } } closedir(dir); return 0; } int parse_input_file_name(char *arg, command_t *cmd_data) { char *ext = strrchr(arg, '.'); char *name = strrchr(arg, '/'); int pathlen; enum lib_type libtype; char *newarg; if (!ext) { return 0; } ext++; if (name == NULL) { name = strrchr(arg, '\\'); if (name == NULL) { name = arg; } else { name++; } } else { name++; } pathlen = name - arg; if (strcmp(ext, "lo") == 0) { newarg = check_object_exists(cmd_data, arg, ext - arg); if (!newarg) { printf("Can not find suitable object file for %s\n", arg); exit(1); } if (cmd_data->mode != mLink) { push_count_chars(cmd_data->arglist, newarg); } else { push_count_chars(cmd_data->obj_files, newarg); } return 1; } if (strcmp(ext, "la") == 0) { switch (cmd_data->mode) { case mLink: /* Try the .libs dir first! */ newarg = check_library_exists(cmd_data, arg, pathlen, 1, &libtype); if (!newarg) { /* Try the normal dir next. */ newarg = check_library_exists(cmd_data, arg, pathlen, 0, &libtype); if (!newarg) { printf("Can not find suitable library for %s\n", arg); exit(1); } } /* It is not ok to just add the file: a library may added with: 1 - -L path library_name. (For *.so in Linux). 2 - library_name. */ #ifdef ADD_MINUS_L if (libtype == type_DYNAMIC_LIB) { add_minus_l(cmd_data->shared_opts.dependencies, newarg); } else if (cmd_data->output == otLibrary && libtype == type_STATIC_LIB) { explode_static_lib(cmd_data, newarg); } else { push_count_chars(cmd_data->shared_opts.dependencies, newarg); } #else if (cmd_data->output == otLibrary && libtype == type_STATIC_LIB) { explode_static_lib(cmd_data, newarg); } else { push_count_chars(cmd_data->shared_opts.dependencies, newarg); } #endif if (libtype == type_DYNAMIC_LIB) { if (cmd_data->options.no_install) { #ifdef RPATH add_rpath_noinstall(cmd_data->shared_opts.dependencies, arg, pathlen); #endif #ifdef DYNAMIC_LINK_NO_INSTALL /* * This doesn't work as Darwin's linker has no way to * override at link-time the search paths for a * non-installed library. */ /* add_dylink_noinstall(cmd_data->shared_opts.dependencies, arg, pathlen, ext - arg); */ #endif } else { #ifdef RPATH add_rpath_file(cmd_data->shared_opts.dependencies, arg); #endif } } break; case mInstall: /* If we've already recorded a library to install, we're most * likely getting the .la file that we want to install as. * The problem is that we need to add it as the directory, * not the .la file itself. Otherwise, we'll do odd things. */ if (cmd_data->output == otLibrary) { arg[pathlen] = '\0'; push_count_chars(cmd_data->arglist, arg); } else { cmd_data->output = otLibrary; cmd_data->output_name = arg; cmd_data->static_name.install = gen_install_name(arg, 0); cmd_data->shared_name.install = gen_install_name(arg, 1); cmd_data->module_name.install = gen_install_name(arg, 2); } break; default: break; } return 1; } if (strcmp(ext, "c") == 0) { /* If we don't already have an idea what our output name will be. */ if (cmd_data->basename == NULL) { cmd_data->basename = (char *)malloc(strlen(arg) + 4); strcpy(cmd_data->basename, arg); strcpy(strrchr(cmd_data->basename, '.') + 1, "lo"); cmd_data->fake_output_name = strrchr(cmd_data->basename, '/'); if (cmd_data->fake_output_name) { cmd_data->fake_output_name++; } else { cmd_data->fake_output_name = cmd_data->basename; } } } return 0; } int parse_output_file_name(char *arg, command_t *cmd_data) { char *name = strrchr(arg, '/'); char *ext = strrchr(arg, '.'); char *newarg = NULL; int pathlen; cmd_data->fake_output_name = arg; if (name) { name++; } else { name = strrchr(arg, '\\'); if (name == NULL) { name = arg; } else { name++; } } #ifdef EXE_EXT if (!ext || strcmp(ext, EXE_EXT) == 0) { #else if (!ext) { #endif cmd_data->basename = arg; cmd_data->output = otProgram; #if defined(_OSD_POSIX) cmd_data->options.pic_mode = pic_AVOID; #endif newarg = (char *)malloc(strlen(arg) + 5); strcpy(newarg, arg); #ifdef EXE_EXT if (!ext) { strcat(newarg, EXE_EXT); } #endif cmd_data->output_name = newarg; return 1; } ext++; pathlen = name - arg; if (strcmp(ext, "la") == 0) { assert(cmd_data->mode == mLink); cmd_data->basename = arg; cmd_data->static_name.normal = gen_library_name(arg, 0); cmd_data->shared_name.normal = gen_library_name(arg, 1); cmd_data->module_name.normal = gen_library_name(arg, 2); cmd_data->static_name.install = gen_install_name(arg, 0); cmd_data->shared_name.install = gen_install_name(arg, 1); cmd_data->module_name.install = gen_install_name(arg, 2); #ifdef TRUNCATE_DLL_NAME if (shared) { arg = truncate_dll_name(arg); } #endif cmd_data->output_name = arg; return 1; } if (strcmp(ext, "lo") == 0) { cmd_data->basename = arg; cmd_data->output = otObject; newarg = (char *)malloc(strlen(arg) + 2); strcpy(newarg, arg); ext = strrchr(newarg, '.') + 1; strcpy(ext, OBJECT_EXT); cmd_data->output_name = newarg; return 1; } return 0; } void parse_args(int argc, char *argv[], command_t *cmd_data) { int a; char *arg; int argused; for (a = 1; a < argc; a++) { arg = argv[a]; argused = 1; if (arg[0] == '-') { if (arg[1] == '-') { argused = parse_long_opt(arg + 2, cmd_data); } else { argused = parse_short_opt(arg + 1, cmd_data); } /* We haven't done anything with it yet, try some of the * more complicated short opts... */ if (argused == 0 && a + 1 < argc) { if (arg[1] == 'o' && !arg[2]) { arg = argv[++a]; argused = parse_output_file_name(arg, cmd_data); } else if (strcmp(arg+1, "MT") == 0) { if (!cmd_data->options.silent) { printf("Adding: %s\n", arg); } push_count_chars(cmd_data->arglist, arg); arg = argv[++a]; if (!cmd_data->options.silent) { printf(" %s\n", arg); } push_count_chars(cmd_data->arglist, arg); argused = 1; } else if (strcmp(arg+1, "rpath") == 0) { /* Aha, we should try to link both! */ cmd_data->install_path = argv[++a]; argused = 1; } else if (strcmp(arg+1, "release") == 0) { /* Store for later deciphering */ cmd_data->version_info = argv[++a]; argused = 1; } else if (strcmp(arg+1, "version-info") == 0) { /* Store for later deciphering */ cmd_data->version_info = argv[++a]; argused = 1; } else if (strcmp(arg+1, "export-symbols-regex") == 0) { /* Skip the argument. */ ++a; argused = 1; } else if (strcmp(arg+1, "release") == 0) { /* Skip the argument. */ ++a; argused = 1; } else if (strcmp(arg+1, "undefined") == 0) { cmd_data->undefined_flag = argv[++a]; argused = 1; } else if (arg[1] == 'R' && !arg[2]) { /* -R dir Add dir to runtime library search path. */ add_runtimedirlib(argv[++a], cmd_data); argused = 1; } } } else { argused = parse_input_file_name(arg, cmd_data); } if (!argused) { if (!cmd_data->options.silent) { printf("Adding: %s\n", arg); } push_count_chars(cmd_data->arglist, arg); } } } #ifdef GEN_EXPORTS void generate_def_file(command_t *cmd_data) { char def_file[1024]; char implib_file[1024]; char *ext; FILE *hDef; char *export_args[1024]; int num_export_args = 0; char *cmd; int cmd_size = 0; int a; if (cmd_data->output_name) { strcpy(def_file, cmd_data->output_name); strcat(def_file, ".def"); hDef = fopen(def_file, "w"); if (hDef != NULL) { fprintf(hDef, "LIBRARY '%s' INITINSTANCE\n", nameof(cmd_data->output_name)); fprintf(hDef, "DATA NONSHARED\n"); fprintf(hDef, "EXPORTS\n"); fclose(hDef); for (a = 0; a < cmd_data->num_obj_files; a++) { cmd_size += strlen(cmd_data->obj_files[a]) + 1; } cmd_size += strlen(GEN_EXPORTS) + strlen(def_file) + 3; cmd = (char *)malloc(cmd_size); strcpy(cmd, GEN_EXPORTS); for (a=0; a < cmd_data->num_obj_files; a++) { strcat(cmd, " "); strcat(cmd, cmd_data->obj_files[a] ); } strcat(cmd, ">>"); strcat(cmd, def_file); puts(cmd); export_args[num_export_args++] = SHELL_CMD; export_args[num_export_args++] = "-c"; export_args[num_export_args++] = cmd; export_args[num_export_args++] = NULL; external_spawn(cmd_data, export_args[0], (const char**)export_args); cmd_data->arglist[cmd_data->num_args++] = strdup(def_file); /* Now make an import library for the dll */ num_export_args = 0; export_args[num_export_args++] = DEF2IMPLIB_CMD; export_args[num_export_args++] = "-o"; strcpy(implib_file, ".libs/"); strcat(implib_file, cmd_data->basename); ext = strrchr(implib_file, '.'); if (ext) *ext = 0; strcat(implib_file, "."); strcat(implib_file, STATIC_LIB_EXT); export_args[num_export_args++] = implib_file; export_args[num_export_args++] = def_file; export_args[num_export_args++] = NULL; external_spawn(cmd_data, export_args[0], (const char**)export_args); } } } #endif const char* expand_path(const char *relpath) { char foo[PATH_MAX], *newpath; getcwd(foo, PATH_MAX-1); newpath = (char*)malloc(strlen(foo)+strlen(relpath)+2); strcpy(newpath, foo); strcat(newpath, "/"); strcat(newpath, relpath); return newpath; } void link_fixup(command_t *c) { /* If we were passed an -rpath directive, we need to build * shared objects too. Otherwise, we should only create static * libraries. */ if (!c->install_path && (c->output == otDynamicLibraryOnly || c->output == otModule || c->output == otLibrary)) { c->output = otStaticLibraryOnly; } if (c->output == otDynamicLibraryOnly || c->output == otModule || c->output == otLibrary) { push_count_chars(c->shared_opts.normal, "-o"); if (c->output == otModule) { push_count_chars(c->shared_opts.normal, c->module_name.normal); } else { char *tmp; push_count_chars(c->shared_opts.normal, c->shared_name.normal); #ifdef DYNAMIC_INSTALL_NAME push_count_chars(c->shared_opts.normal, DYNAMIC_INSTALL_NAME); tmp = (char*)malloc(PATH_MAX); strcpy(tmp, c->install_path); strcat(tmp, strrchr(c->shared_name.normal, '/')); push_count_chars(c->shared_opts.normal, tmp); #endif } append_count_chars(c->shared_opts.normal, c->obj_files); append_count_chars(c->shared_opts.normal, c->shared_opts.dependencies); if (c->options.export_all) { #ifdef GEN_EXPORTS generate_def_file(c); #endif } } if (c->output == otLibrary || c->output == otStaticLibraryOnly) { push_count_chars(c->static_opts.normal, "-o"); push_count_chars(c->static_opts.normal, c->output_name); } if (c->output == otProgram) { if (c->output_name) { push_count_chars(c->arglist, "-o"); push_count_chars(c->arglist, c->output_name); append_count_chars(c->arglist, c->obj_files); append_count_chars(c->arglist, c->shared_opts.dependencies); add_dynamic_link_opts(c, c->arglist); } } } void post_parse_fixup(command_t *cmd_data) { switch (cmd_data->mode) { case mCompile: #ifdef PIC_FLAG if (cmd_data->options.pic_mode != pic_AVOID) { push_count_chars(cmd_data->arglist, PIC_FLAG); } #endif if (cmd_data->output_name) { push_count_chars(cmd_data->arglist, "-o"); push_count_chars(cmd_data->arglist, cmd_data->output_name); } break; case mLink: link_fixup(cmd_data); break; case mInstall: if (cmd_data->output == otLibrary) { link_fixup(cmd_data); } default: break; } #if USE_OMF if (cmd_data->output == otObject || cmd_data->output == otProgram || cmd_data->output == otLibrary || cmd_data->output == otDynamicLibraryOnly) { push_count_chars(cmd_data->arglist, "-Zomf"); } #endif if (cmd_data->options.shared && (cmd_data->output == otObject || cmd_data->output == otLibrary || cmd_data->output == otDynamicLibraryOnly)) { #ifdef SHARE_SW push_count_chars(cmd_data->arglist, SHARE_SW); #endif } } int run_mode(command_t *cmd_data) { int rv; count_chars *cctemp; cctemp = (count_chars*)malloc(sizeof(count_chars)); init_count_chars(cctemp); switch (cmd_data->mode) { case mCompile: rv = run_command(cmd_data, cmd_data->arglist); if (rv) { return rv; } break; case mInstall: /* Well, we'll assume it's a file going to a directory... */ /* For brain-dead install-sh based scripts, we have to repeat * the command N-times. install-sh should die. */ if (!cmd_data->output_name) { rv = run_command(cmd_data, cmd_data->arglist); if (rv) { return rv; } } if (cmd_data->output_name) { append_count_chars(cctemp, cmd_data->arglist); insert_count_chars(cctemp, cmd_data->output_name, cctemp->num - 1); rv = run_command(cmd_data, cctemp); if (rv) { return rv; } clear_count_chars(cctemp); } if (cmd_data->static_name.install) { append_count_chars(cctemp, cmd_data->arglist); insert_count_chars(cctemp, cmd_data->static_name.install, cctemp->num - 1); rv = run_command(cmd_data, cctemp); if (rv) { return rv; } #if defined(__APPLE__) && defined(RANLIB) /* From the Apple libtool(1) manpage on Tiger/10.4: * ---- * With the way libraries used to be created, errors were possible * if the library was modified with ar(1) and the table of * contents was not updated by rerunning ranlib(1). Thus the * link editor, ld, warns when the modification date of a library * is more recent than the creation date of its table of * contents. Unfortunately, this means that you get the warning * even if you only copy the library. * ---- * * This means that when we install the static archive, we need to * rerun ranlib afterwards. */ const char *lib_args[3], *static_lib_name; char *tmp; size_t len1, len2; len1 = strlen(cmd_data->arglist->vals[cmd_data->arglist->num - 1]); static_lib_name = jlibtool_basename(cmd_data->static_name.install); len2 = strlen(static_lib_name); tmp = malloc(len1 + len2 + 2); snprintf(tmp, len1 + len2 + 2, "%s/%s", cmd_data->arglist->vals[cmd_data->arglist->num - 1], static_lib_name); lib_args[0] = RANLIB; lib_args[1] = tmp; lib_args[2] = NULL; external_spawn(cmd_data, RANLIB, lib_args); free(tmp); #endif clear_count_chars(cctemp); } if (cmd_data->shared_name.install) { append_count_chars(cctemp, cmd_data->arglist); insert_count_chars(cctemp, cmd_data->shared_name.install, cctemp->num - 1); rv = run_command(cmd_data, cctemp); if (rv) { return rv; } clear_count_chars(cctemp); } if (cmd_data->module_name.install) { append_count_chars(cctemp, cmd_data->arglist); insert_count_chars(cctemp, cmd_data->module_name.install, cctemp->num - 1); rv = run_command(cmd_data, cctemp); if (rv) { return rv; } clear_count_chars(cctemp); } break; case mLink: if (!cmd_data->options.dry_run) { /* Check first to see if the dir already exists! */ safe_mkdir(".libs"); } if (cmd_data->output == otStaticLibraryOnly || cmd_data->output == otLibrary) { #ifdef RANLIB const char *lib_args[3]; #endif /* Removes compiler! */ cmd_data->program = LIBRARIAN; push_count_chars(cmd_data->program_opts, LIBRARIAN_OPTS); push_count_chars(cmd_data->program_opts, cmd_data->static_name.normal); rv = run_command(cmd_data, cmd_data->obj_files); if (rv) { return rv; } #ifdef RANLIB lib_args[0] = RANLIB; lib_args[1] = cmd_data->static_name.normal; lib_args[2] = NULL; external_spawn(cmd_data, RANLIB, lib_args); #endif } if (cmd_data->output == otDynamicLibraryOnly || cmd_data->output == otModule || cmd_data->output == otLibrary) { cmd_data->program = NULL; clear_count_chars(cmd_data->program_opts); append_count_chars(cmd_data->program_opts, cmd_data->arglist); if (cmd_data->output == otModule) { #ifdef MODULE_OPTS push_count_chars(cmd_data->program_opts, MODULE_OPTS); #endif } else { #ifdef SHARED_OPTS push_count_chars(cmd_data->program_opts, SHARED_OPTS); #endif #ifdef dynamic_link_version_func push_count_chars(cmd_data->program_opts, dynamic_link_version_func(cmd_data->version_info)); #endif } add_dynamic_link_opts(cmd_data, cmd_data->program_opts); rv = run_command(cmd_data, cmd_data->shared_opts.normal); if (rv) { return rv; } } if (cmd_data->output == otProgram) { rv = run_command(cmd_data, cmd_data->arglist); if (rv) { return rv; } } break; default: break; } return 0; } void cleanup_tmp_dir(const char *dirname) { DIR *dir; struct dirent *entry; char fullname[1024]; dir = opendir(dirname); if (dir == NULL) return; while ((entry = readdir(dir)) != NULL) { if (entry->d_name[0] != '.') { strcpy(fullname, dirname); strcat(fullname, "/"); strcat(fullname, entry->d_name); remove(fullname); } } rmdir(dirname); } void cleanup_tmp_dirs(command_t *cmd_data) { int d; for (d = 0; d < cmd_data->tmp_dirs->num; d++) { cleanup_tmp_dir(cmd_data->tmp_dirs->vals[d]); } } int ensure_fake_uptodate(command_t *cmd_data) { /* FIXME: could do the stat/touch here, but nah... */ const char *touch_args[3]; if (cmd_data->mode == mInstall) { return 0; } if (!cmd_data->fake_output_name) { return 0; } touch_args[0] = "touch"; touch_args[1] = cmd_data->fake_output_name; touch_args[2] = NULL; return external_spawn(cmd_data, "touch", touch_args); } /* Store the install path in the *.la file */ int add_for_runtime(command_t *cmd_data) { if (cmd_data->mode == mInstall) { return 0; } if (cmd_data->output == otDynamicLibraryOnly || cmd_data->output == otLibrary) { FILE *f=fopen(cmd_data->fake_output_name,"w"); if (f == NULL) { return -1; } fprintf(f,"%s\n", cmd_data->install_path); fclose(f); return(0); } else { return(ensure_fake_uptodate(cmd_data)); } } int main(int argc, char *argv[]) { int rc; command_t cmd_data; memset(&cmd_data, 0, sizeof(cmd_data)); cmd_data.options.pic_mode = pic_UNKNOWN; cmd_data.program_opts = (count_chars*)malloc(sizeof(count_chars)); init_count_chars(cmd_data.program_opts); cmd_data.arglist = (count_chars*)malloc(sizeof(count_chars)); init_count_chars(cmd_data.arglist); cmd_data.tmp_dirs = (count_chars*)malloc(sizeof(count_chars)); init_count_chars(cmd_data.tmp_dirs); cmd_data.obj_files = (count_chars*)malloc(sizeof(count_chars)); init_count_chars(cmd_data.obj_files); cmd_data.dep_rpaths = (count_chars*)malloc(sizeof(count_chars)); init_count_chars(cmd_data.dep_rpaths); cmd_data.rpaths = (count_chars*)malloc(sizeof(count_chars)); init_count_chars(cmd_data.rpaths); cmd_data.static_opts.normal = (count_chars*)malloc(sizeof(count_chars)); init_count_chars(cmd_data.static_opts.normal); cmd_data.shared_opts.normal = (count_chars*)malloc(sizeof(count_chars)); init_count_chars(cmd_data.shared_opts.normal); cmd_data.shared_opts.dependencies = (count_chars*)malloc(sizeof(count_chars)); init_count_chars(cmd_data.shared_opts.dependencies); cmd_data.mode = mUnknown; cmd_data.output = otGeneral; parse_args(argc, argv, &cmd_data); post_parse_fixup(&cmd_data); if (cmd_data.mode == mUnknown) { exit(0); } rc = run_mode(&cmd_data); if (!rc) { add_for_runtime(&cmd_data); } cleanup_tmp_dirs(&cmd_data); return rc; }
the_stack_data/1218977.c
char *ghc_rts_opts = "-K30M";
the_stack_data/307091.c
#include<stdio.h> int main() { long long int i,n; scanf("%lld", &n); if(n<9) goto here; for(i=0;n>0;i++) { if(n%10!=4 && n%10!=7) goto here; n/=10; } printf("YES"); goto there; here: printf("NO"); there: return 0; }
the_stack_data/68034.c
// Example 14-1. Calculating the sum of array elements in several parallel threads // parallelSum.c // ---------------------------------------------------------------------------- #include <stdbool.h> #include <threads.h> #define MAX_THREADS 8 // 1, 2, 4, 8 ... Maximum number // of threads to create. #define MIN_BLOCK_SIZE 100 // Minimum size of an array block. typedef struct // Arguments for the parallel_sum() function. { float *start; // Start and length of the int len; // array block passed to parallel_sum(). int block_size; // Size of the smallest blocks. double sum; // The result. } Sum_arg; int parallel_sum(void *arg); // Prototype of the thread function. // --------------------------------------------------------------- // Calculate the sum of array elements and write it to *sumPtr. // sum() calls the function parallel_sum() for parallel processing. // Return value: true if no error occurs, otherwise false. bool sum(float arr[], int len, double* sumPtr) { int block_size = len / MAX_THREADS; if (block_size < MIN_BLOCK_SIZE) block_size = len; Sum_arg args = { arr, len, block_size, 0.0 }; if (parallel_sum(&args)) { *sumPtr = args.sum; return true; } else return false; } // --------------------------------------------------------------- // Recursive helper function to divide the work among several threads. int parallel_sum(void *arg) { Sum_arg *argp = (Sum_arg*)arg; // A pointer to the arguments. if (argp->len <= argp->block_size) // If length <= block_size, { // add up the elements. for (int i = 0; i < argp->len; ++i) argp->sum += argp->start[i]; return 1; } else // If length > block_size, { // divide the array. int mid = argp->len / 2; Sum_arg arg2 = { argp->start+mid, argp->len-mid, argp->block_size, 0}; // Specifies 2nd half argp->len = mid; // Length of first half thrd_t th; // Process 1st half in a new thread. int res = 0; if (thrd_create(&th, parallel_sum, arg) != thrd_success) return 0; // Couldn't spawn a thread if (!parallel_sum(&arg2)) // Process 2nd half by recursion // in the current thread. { thrd_detach(th); return 0; // Recursive call failed } thrd_join(th, &res); if (!res) return 0; // Sibling thread reported failure argp->sum += arg2.sum; return 1; } }
the_stack_data/237642636.c
#include <stdio.h> #define MAX_LENGTH 10 int main(int argc, char *argv[]) { int a[MAX_LENGTH] = {}; int i = 0; int j = 0; printf("Please input %d numbers:\n", MAX_LENGTH); for(i=0; i<MAX_LENGTH; ++i) { scanf("%d", &a[i]); } for(i=0; i<MAX_LENGTH; ++i) { for(j=0; j<MAX_LENGTH-1; ++j) { int tmp = 0; if(a[j] > a[j+1]) { tmp = a[j]; a[j] = a[j+1]; a[j+1] = tmp; } } } printf("after bubble sort:\n"); for(j=0; j<MAX_LENGTH; ++j) { printf("%d ", a[j]); } printf("\n"); return 0; }
the_stack_data/175142631.c
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <CL/cl.h> unsigned char *read_buffer(char *file_name, size_t *size_ptr) { FILE *f; unsigned char *buf; size_t size; /* Open file */ f = fopen(file_name, "rb"); if (!f) return NULL; /* Obtain file size */ fseek(f, 0, SEEK_END); size = ftell(f); fseek(f, 0, SEEK_SET); /* Allocate and read buffer */ buf = malloc(size + 1); fread(buf, 1, size, f); buf[size] = '\0'; /* Return size of buffer */ if (size_ptr) *size_ptr = size; /* Return buffer */ return buf; } void write_buffer(char *file_name, const char *buffer, size_t buffer_size) { FILE *f; /* Open file */ f = fopen(file_name, "w+"); /* Write buffer */ if(buffer) fwrite(buffer, 1, buffer_size, f); /* Close file */ fclose(f); } int main(int argc, char const *argv[]) { /* Get platform */ cl_platform_id platform; cl_uint num_platforms; cl_int ret = clGetPlatformIDs(1, &platform, &num_platforms); if (ret != CL_SUCCESS) { printf("error: call to 'clGetPlatformIDs' failed\n"); exit(1); } printf("Number of platforms: %d\n", num_platforms); printf("platform=%p\n", platform); /* Get platform name */ char platform_name[100]; ret = clGetPlatformInfo(platform, CL_PLATFORM_NAME, sizeof(platform_name), platform_name, NULL); if (ret != CL_SUCCESS) { printf("error: call to 'clGetPlatformInfo' failed\n"); exit(1); } printf("platform.name='%s'\n\n", platform_name); /* Get device */ cl_device_id device; cl_uint num_devices; ret = clGetDeviceIDs(platform, CL_DEVICE_TYPE_GPU, 1, &device, &num_devices); if (ret != CL_SUCCESS) { printf("error: call to 'clGetDeviceIDs' failed\n"); exit(1); } printf("Number of devices: %d\n", num_devices); printf("device=%p\n", device); /* Get device name */ char device_name[100]; ret = clGetDeviceInfo(device, CL_DEVICE_NAME, sizeof(device_name), device_name, NULL); if (ret != CL_SUCCESS) { printf("error: call to 'clGetDeviceInfo' failed\n"); exit(1); } printf("device.name='%s'\n", device_name); printf("\n"); /* Create a Context Object */ cl_context context; context = clCreateContext(NULL, 1, &device, NULL, NULL, &ret); if (ret != CL_SUCCESS) { printf("error: call to 'clCreateContext' failed\n"); exit(1); } printf("context=%p\n", context); /* Create a Command Queue Object*/ cl_command_queue command_queue; command_queue = clCreateCommandQueue(context, device, 0, &ret); if (ret != CL_SUCCESS) { printf("error: call to 'clCreateCommandQueue' failed\n"); exit(1); } printf("command_queue=%p\n", command_queue); printf("\n"); /* Program source */ unsigned char *source_code; size_t source_length; /* Read program from 'abs_diff_char16char16.cl' */ source_code = read_buffer("abs_diff_char16char16.cl", &source_length); /* Create a program */ cl_program program; program = clCreateProgramWithSource(context, 1, (const char **)&source_code, &source_length, &ret); if (ret != CL_SUCCESS) { printf("error: call to 'clCreateProgramWithSource' failed\n"); exit(1); } printf("program=%p\n", program); /* Build program */ ret = clBuildProgram(program, 1, &device, NULL, NULL, NULL); if (ret != CL_SUCCESS ) { size_t size; char *log; /* Get log size */ clGetProgramBuildInfo(program, device, CL_PROGRAM_BUILD_LOG,0, NULL, &size); /* Allocate log and print */ log = malloc(size); clGetProgramBuildInfo(program, device, CL_PROGRAM_BUILD_LOG,size, log, NULL); printf("error: call to 'clBuildProgram' failed:\n%s\n", log); /* Free log and exit */ free(log); exit(1); } printf("program built\n"); printf("\n"); /* Create a Kernel Object */ cl_kernel kernel; kernel = clCreateKernel(program, "abs_diff_char16char16", &ret); if (ret != CL_SUCCESS) { printf("error: call to 'clCreateKernel' failed\n"); exit(1); } /* Create and allocate host buffers */ size_t num_elem = 10; /* Create and init host side src buffer 0 */ cl_char16 *src_0_host_buffer; src_0_host_buffer = malloc(num_elem * sizeof(cl_char16)); for (int i = 0; i < num_elem; i++) src_0_host_buffer[i] = (cl_char16){{2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2}}; /* Create and init device side src buffer 0 */ cl_mem src_0_device_buffer; src_0_device_buffer = clCreateBuffer(context, CL_MEM_READ_ONLY, num_elem * sizeof(cl_char16), NULL, &ret); if (ret != CL_SUCCESS) { printf("error: could not create source buffer\n"); exit(1); } ret = clEnqueueWriteBuffer(command_queue, src_0_device_buffer, CL_TRUE, 0, num_elem * sizeof(cl_char16), src_0_host_buffer, 0, NULL, NULL); if (ret != CL_SUCCESS) { printf("error: call to 'clEnqueueWriteBuffer' failed\n"); exit(1); } /* Create and init host side src buffer 1 */ cl_char16 *src_1_host_buffer; src_1_host_buffer = malloc(num_elem * sizeof(cl_char16)); for (int i = 0; i < num_elem; i++) src_1_host_buffer[i] = (cl_char16){{2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2}}; /* Create and init device side src buffer 1 */ cl_mem src_1_device_buffer; src_1_device_buffer = clCreateBuffer(context, CL_MEM_READ_ONLY, num_elem * sizeof(cl_char16), NULL, &ret); if (ret != CL_SUCCESS) { printf("error: could not create source buffer\n"); exit(1); } ret = clEnqueueWriteBuffer(command_queue, src_1_device_buffer, CL_TRUE, 0, num_elem * sizeof(cl_char16), src_1_host_buffer, 0, NULL, NULL); if (ret != CL_SUCCESS) { printf("error: call to 'clEnqueueWriteBuffer' failed\n"); exit(1); } /* Create host dst buffer */ cl_uchar16 *dst_host_buffer; dst_host_buffer = malloc(num_elem * sizeof(cl_uchar16)); memset((void *)dst_host_buffer, 1, num_elem * sizeof(cl_uchar16)); /* Create device dst buffer */ cl_mem dst_device_buffer; dst_device_buffer = clCreateBuffer(context, CL_MEM_WRITE_ONLY, num_elem *sizeof(cl_uchar16), NULL, &ret); if (ret != CL_SUCCESS) { printf("error: could not create dst buffer\n"); exit(1); } /* Set kernel arguments */ ret = CL_SUCCESS; ret |= clSetKernelArg(kernel, 0, sizeof(cl_mem), &src_0_device_buffer); ret |= clSetKernelArg(kernel, 1, sizeof(cl_mem), &src_1_device_buffer); ret |= clSetKernelArg(kernel, 2, sizeof(cl_mem), &dst_device_buffer); if (ret != CL_SUCCESS) { printf("error: call to 'clSetKernelArg' failed\n"); exit(1); } /* Launch the kernel */ size_t global_work_size = num_elem; size_t local_work_size = num_elem; ret = clEnqueueNDRangeKernel(command_queue, kernel, 1, NULL, &global_work_size, &local_work_size, 0, NULL, NULL); if (ret != CL_SUCCESS) { printf("error: call to 'clEnqueueNDRangeKernel' failed\n"); exit(1); } /* Wait for it to finish */ clFinish(command_queue); /* Read results from GPU */ ret = clEnqueueReadBuffer(command_queue, dst_device_buffer, CL_TRUE,0, num_elem * sizeof(cl_uchar16), dst_host_buffer, 0, NULL, NULL); if (ret != CL_SUCCESS) { printf("error: call to 'clEnqueueReadBuffer' failed\n"); exit(1); } /* Dump dst buffer to file */ char dump_file[100]; sprintf((char *)&dump_file, "%s.result", argv[0]); write_buffer(dump_file, (const char *)dst_host_buffer, num_elem * sizeof(cl_uchar16)); printf("Result dumped to %s\n", dump_file); /* Free host dst buffer */ free(dst_host_buffer); /* Free device dst buffer */ ret = clReleaseMemObject(dst_device_buffer); if (ret != CL_SUCCESS) { printf("error: call to 'clReleaseMemObject' failed\n"); exit(1); } /* Free host side src buffer 0 */ free(src_0_host_buffer); /* Free device side src buffer 0 */ ret = clReleaseMemObject(src_0_device_buffer); if (ret != CL_SUCCESS) { printf("error: call to 'clReleaseMemObject' failed\n"); exit(1); } /* Free host side src buffer 1 */ free(src_1_host_buffer); /* Free device side src buffer 1 */ ret = clReleaseMemObject(src_1_device_buffer); if (ret != CL_SUCCESS) { printf("error: call to 'clReleaseMemObject' failed\n"); exit(1); } /* Release kernel */ ret = clReleaseKernel(kernel); if (ret != CL_SUCCESS) { printf("error: call to 'clReleaseKernel' failed\n"); exit(1); } /* Release program */ ret = clReleaseProgram(program); if (ret != CL_SUCCESS) { printf("error: call to 'clReleaseProgram' failed\n"); exit(1); } /* Release command queue */ ret = clReleaseCommandQueue(command_queue); if (ret != CL_SUCCESS) { printf("error: call to 'clReleaseCommandQueue' failed\n"); exit(1); } /* Release context */ ret = clReleaseContext(context); if (ret != CL_SUCCESS) { printf("error: call to 'clReleaseContext' failed\n"); exit(1); } return 0; }
the_stack_data/88572.c
/* Author: Yuriy Sverchkov File: ydarrays.c Description: Implements dynamic integer and double arrays. */ #include <stdlib.h> /***INTEGER ARRAYS***/ typedef struct { unsigned int real_length;/*Real length of the array (ammount allocated)*/ unsigned int length;/*Length of array being used*/ int * contents;/*Contains the data*/ } IntArray; IntArray iaCreate( const int array[], const unsigned int size ) /* Creates an IntArray out of the int[] of the specified size. */ { unsigned int i, real_size = size + (size == 0); IntArray result; result.contents = (int *) malloc( real_size * sizeof(int) ); result.real_length = real_size; result.length = size; if( array != NULL ) for( i = 0; i < size; i++ ) result.contents[i] = array[i]; else for( i = 0; i < size; i++ ) result.contents[i] = 0; return result; } void iaDestroy( IntArray a ) /* Deallocates an IntArray's dynamic contents. */ { free(a.contents); return; } int iaSet( IntArray * ptr, unsigned int index, int value ){ /* Repeatedly doubles the length of the array (if needed) to accomodate the new value. */ while( index >= ptr->real_length ) ptr->contents = (int *) realloc( ptr->contents, ( ptr->real_length *= 2 ) * sizeof(int) ); /* Increases the effective ("user-visible") size of the array and fills unused cells with zeros (if needed). */ while( ptr->length <= index ){ ptr->contents[ptr->length] = 0; ++ ptr->length; } return ( ptr->contents[index] = value ); } int iaGet( IntArray a, unsigned int index ) { if( index < a.length ) return a.contents[index]; return 0; } /***DOUBLE ARRAYS***/ typedef struct { unsigned int real_length;/*Real length of the array (ammount allocated)*/ unsigned int length;/*Length of array being used*/ double * contents;/*Contains the data*/ } DoubleArray; DoubleArray daCreate( const double array[], const unsigned int size ) /* Creates an DoubleArray out of the double[] of the specified size. */ { unsigned int i, real_size = size + (size == 0); DoubleArray result; result.contents = (double *) malloc( real_size * sizeof(double) ); result.real_length = real_size; result.length = size; if( array != NULL ) for( i = 0; i < size; i++ ) result.contents[i] = array[i]; else for( i = 0; i < size; i++ ) result.contents[i] = 0; return result; } void daDestroy( DoubleArray a ) /* Deallocates an DoubleArray's dynamic contents. */ { free(a.contents); return; } double daSet( DoubleArray * ptr, unsigned int index, double value ){ /* Repeatedly doubles the length of the array (if needed) to accomodate the new value. */ while( index >= ptr->real_length ) ptr->contents = (double *) realloc( ptr->contents, ( ptr->real_length *= 2 ) * sizeof(double) ); /* Increases the effective ("user-visible") size of the array and fills unused cells with zeros (if needed). */ while( ptr->length <= index ){ ptr->contents[ptr->length] = 0; ++ ptr->length; } return ( ptr->contents[index] = value ); } double daGet( DoubleArray a, unsigned int index ) { if( index < a.length ) return a.contents[index]; return 0; }
the_stack_data/61075534.c
//Reverse a linked list #include <stdio.h> #include <stdlib.h> struct node { int data; struct node* next; }*head=NULL,*prev,*temp,*nextnode; void display(); //reverse function------------------------------------------------------ void reverse() { prev=NULL; temp=nextnode=head; while(nextnode != NULL) { nextnode= nextnode->next; temp->next=prev; prev=temp; temp=nextnode; } display(); } //display function------------------------------------------------------ void display() { temp= prev; printf("reversed Linked List:"); while(temp!=NULL) { printf("->%d",temp->data); temp=temp->next; } } //main function------------------------------------------------------ int main() { int i,n; struct node *newnode; printf("Number of elements in Linked List:"); scanf("%d",&n); for(i = 0;i < n;i++) { newnode=(struct node *)(malloc(sizeof(struct node))); printf("Enter element number %d:",i+1); scanf("%d",&newnode->data); newnode->next=NULL; if(head==NULL) { head = temp = newnode; } else { temp->next = newnode; temp=temp->next; } } //display of normal linked list temp=head; while (temp!=NULL) { printf("->%d",temp->data); temp=temp->next; } printf("\n"); reverse(); return 0; }
the_stack_data/1139112.c
/** * This file has no copyright assigned and is placed in the Public Domain. * This file is part of the mingw-w64 runtime package. * No warranty is given; refer to the file DISCLAIMER.PD within this package. */ #include <math.h> long lrintf (float x) { long retval = 0l; #if defined(_AMD64_) || defined(__x86_64__) || defined(_X86_) || defined(__i386__) __asm__ __volatile__ ("fistpl %0" : "=m" (retval) : "t" (x) : "st"); #elif defined(__arm__) || defined(_ARM_) __asm__ __volatile__ ( "vcvtr.s32.f32 %[src], %[src]\n\t" "fmrs %[dst], %[src]\n\t" : [dst] "=r" (retval), [src] "+w" (x)); #elif defined(__aarch64__) || defined(_ARM64_) __asm__ __volatile__ ( "frintx %s1, %s1\n\t" "fcvtzs %w0, %s1\n\t" : "=r" (retval), "+w" (x)); #endif return retval; }
the_stack_data/212643951.c
#include <inttypes.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #define MAXSTRING 50 /* max no. of strings */ #define MAXLEN 80 /* max length. of strings */ void print_arr(const char **p_array); void sort_arr(const char **p_array); char *next_string(); int main(int argc, char *argv[]) { const char **p_array = (const char **)malloc(sizeof(char * [MAXSTRING + 1])); if (p_array == 0) { printf("No memory\n"); exit(EXIT_FAILURE); } size_t nstrings = 0; /* count of strings read */ while (nstrings < MAXSTRING && (p_array[nstrings] = next_string()) != 0) { nstrings++; } /* terminate p_array */ p_array[nstrings] = 0; sort_arr(p_array); print_arr(p_array); exit(EXIT_SUCCESS); } void print_arr(const char **p_array) { while (*p_array) printf("%s\n", *p_array++); } void sort_arr(const char **p_array) { for (const char **lo_p = p_array; *lo_p != 0 && *(lo_p + 1) != 0; lo_p++) { for (const char **hi_p = lo_p + 1; *hi_p != 0; hi_p++) { if (strcmp(*hi_p, *lo_p) >= 0) continue; /* swap strings */ const char *tmp = *hi_p; *hi_p = *lo_p; *lo_p = tmp; } } } char *next_string() { char *destination = (char *)malloc(MAXLEN); if (destination != 0) { char *cp = destination; char c; while ((c = getchar()) != '\n' && c != EOF) { if (cp - destination < MAXLEN - 1) *cp++ = c; } *cp = 0; if (c == EOF && cp == destination) return 0; } return destination; }
the_stack_data/154827224.c
/***************************************************************************** * * \file * * \brief Basic TFTP Server for AVR32 UC3. * * Copyright (c) 2014 Atmel Corporation. All rights reserved. * * \asf_license_start * * \page License * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name of Atmel may not be used to endorse or promote products derived * from this software without specific prior written permission. * * 4. This software may only be redistributed and used in connection with an * Atmel microcontroller product. * * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * \asf_license_stop * *****************************************************************************/ /* Implements a simplistic TFTP server. */ /** * Support and FAQ: visit <a href="http://www.atmel.com/design-support/">Atmel Support</a> */ #if (TFTP_USED == 1) /* Scheduler includes. */ #include "FreeRTOS.h" #include "task.h" #include "BasicTFTP.h" portTASK_FUNCTION( vBasicTFTPServer, pvParameters ) { for (;;) { vTaskDelay(1000); } } #endif
the_stack_data/150143956.c
/* f2c.h -- Standard Fortran to C header file */ /** barf [ba:rf] 2. "He suggested using FORTRAN, and everybody barfed." - From The Shogakukan DICTIONARY OF NEW ENGLISH (Second edition) */ #ifndef F2C_INCLUDE #define F2C_INCLUDE #include <math.h> #include <stdlib.h> #include <string.h> #include <stdio.h> #include <complex.h> #ifdef complex #undef complex #endif #ifdef I #undef I #endif #if defined(_WIN64) typedef long long BLASLONG; typedef unsigned long long BLASULONG; #else typedef long BLASLONG; typedef unsigned long BLASULONG; #endif #ifdef LAPACK_ILP64 typedef BLASLONG blasint; #if defined(_WIN64) #define blasabs(x) llabs(x) #else #define blasabs(x) labs(x) #endif #else typedef int blasint; #define blasabs(x) abs(x) #endif typedef blasint integer; typedef unsigned int uinteger; typedef char *address; typedef short int shortint; typedef float real; typedef double doublereal; typedef struct { real r, i; } complex; typedef struct { doublereal r, i; } doublecomplex; static inline _Complex float Cf(complex *z) {return z->r + z->i*_Complex_I;} static inline _Complex double Cd(doublecomplex *z) {return z->r + z->i*_Complex_I;} static inline _Complex float * _pCf(complex *z) {return (_Complex float*)z;} static inline _Complex double * _pCd(doublecomplex *z) {return (_Complex double*)z;} #define pCf(z) (*_pCf(z)) #define pCd(z) (*_pCd(z)) typedef int logical; typedef short int shortlogical; typedef char logical1; typedef char integer1; #define TRUE_ (1) #define FALSE_ (0) /* Extern is for use with -E */ #ifndef Extern #define Extern extern #endif /* I/O stuff */ typedef int flag; typedef int ftnlen; typedef int ftnint; /*external read, write*/ typedef struct { flag cierr; ftnint ciunit; flag ciend; char *cifmt; ftnint cirec; } cilist; /*internal read, write*/ typedef struct { flag icierr; char *iciunit; flag iciend; char *icifmt; ftnint icirlen; ftnint icirnum; } icilist; /*open*/ typedef struct { flag oerr; ftnint ounit; char *ofnm; ftnlen ofnmlen; char *osta; char *oacc; char *ofm; ftnint orl; char *oblnk; } olist; /*close*/ typedef struct { flag cerr; ftnint cunit; char *csta; } cllist; /*rewind, backspace, endfile*/ typedef struct { flag aerr; ftnint aunit; } alist; /* inquire */ typedef struct { flag inerr; ftnint inunit; char *infile; ftnlen infilen; ftnint *inex; /*parameters in standard's order*/ ftnint *inopen; ftnint *innum; ftnint *innamed; char *inname; ftnlen innamlen; char *inacc; ftnlen inacclen; char *inseq; ftnlen inseqlen; char *indir; ftnlen indirlen; char *infmt; ftnlen infmtlen; char *inform; ftnint informlen; char *inunf; ftnlen inunflen; ftnint *inrecl; ftnint *innrec; char *inblank; ftnlen inblanklen; } inlist; #define VOID void union Multitype { /* for multiple entry points */ integer1 g; shortint h; integer i; /* longint j; */ real r; doublereal d; complex c; doublecomplex z; }; typedef union Multitype Multitype; struct Vardesc { /* for Namelist */ char *name; char *addr; ftnlen *dims; int type; }; typedef struct Vardesc Vardesc; struct Namelist { char *name; Vardesc **vars; int nvars; }; typedef struct Namelist Namelist; #define abs(x) ((x) >= 0 ? (x) : -(x)) #define dabs(x) (fabs(x)) #define f2cmin(a,b) ((a) <= (b) ? (a) : (b)) #define f2cmax(a,b) ((a) >= (b) ? (a) : (b)) #define dmin(a,b) (f2cmin(a,b)) #define dmax(a,b) (f2cmax(a,b)) #define bit_test(a,b) ((a) >> (b) & 1) #define bit_clear(a,b) ((a) & ~((uinteger)1 << (b))) #define bit_set(a,b) ((a) | ((uinteger)1 << (b))) #define abort_() { sig_die("Fortran abort routine called", 1); } #define c_abs(z) (cabsf(Cf(z))) #define c_cos(R,Z) { pCf(R)=ccos(Cf(Z)); } #define c_div(c, a, b) {pCf(c) = Cf(a)/Cf(b);} #define z_div(c, a, b) {pCd(c) = Cd(a)/Cd(b);} #define c_exp(R, Z) {pCf(R) = cexpf(Cf(Z));} #define c_log(R, Z) {pCf(R) = clogf(Cf(Z));} #define c_sin(R, Z) {pCf(R) = csinf(Cf(Z));} //#define c_sqrt(R, Z) {*(R) = csqrtf(Cf(Z));} #define c_sqrt(R, Z) {pCf(R) = csqrtf(Cf(Z));} #define d_abs(x) (fabs(*(x))) #define d_acos(x) (acos(*(x))) #define d_asin(x) (asin(*(x))) #define d_atan(x) (atan(*(x))) #define d_atn2(x, y) (atan2(*(x),*(y))) #define d_cnjg(R, Z) { pCd(R) = conj(Cd(Z)); } #define r_cnjg(R, Z) { pCf(R) = conj(Cf(Z)); } #define d_cos(x) (cos(*(x))) #define d_cosh(x) (cosh(*(x))) #define d_dim(__a, __b) ( *(__a) > *(__b) ? *(__a) - *(__b) : 0.0 ) #define d_exp(x) (exp(*(x))) #define d_imag(z) (cimag(Cd(z))) #define r_imag(z) (cimag(Cf(z))) #define d_int(__x) (*(__x)>0 ? floor(*(__x)) : -floor(- *(__x))) #define r_int(__x) (*(__x)>0 ? floor(*(__x)) : -floor(- *(__x))) #define d_lg10(x) ( 0.43429448190325182765 * log(*(x)) ) #define r_lg10(x) ( 0.43429448190325182765 * log(*(x)) ) #define d_log(x) (log(*(x))) #define d_mod(x, y) (fmod(*(x), *(y))) #define u_nint(__x) ((__x)>=0 ? floor((__x) + .5) : -floor(.5 - (__x))) #define d_nint(x) u_nint(*(x)) #define u_sign(__a,__b) ((__b) >= 0 ? ((__a) >= 0 ? (__a) : -(__a)) : -((__a) >= 0 ? (__a) : -(__a))) #define d_sign(a,b) u_sign(*(a),*(b)) #define r_sign(a,b) u_sign(*(a),*(b)) #define d_sin(x) (sin(*(x))) #define d_sinh(x) (sinh(*(x))) #define d_sqrt(x) (sqrt(*(x))) #define d_tan(x) (tan(*(x))) #define d_tanh(x) (tanh(*(x))) #define i_abs(x) abs(*(x)) #define i_dnnt(x) ((integer)u_nint(*(x))) #define i_len(s, n) (n) #define i_nint(x) ((integer)u_nint(*(x))) #define i_sign(a,b) ((integer)u_sign((integer)*(a),(integer)*(b))) #define pow_dd(ap, bp) ( pow(*(ap), *(bp))) #define pow_si(B,E) spow_ui(*(B),*(E)) #define pow_ri(B,E) spow_ui(*(B),*(E)) #define pow_di(B,E) dpow_ui(*(B),*(E)) #define pow_zi(p, a, b) {pCd(p) = zpow_ui(Cd(a), *(b));} #define pow_ci(p, a, b) {pCf(p) = cpow_ui(Cf(a), *(b));} #define pow_zz(R,A,B) {pCd(R) = cpow(Cd(A),*(B));} #define s_cat(lpp, rpp, rnp, np, llp) { ftnlen i, nc, ll; char *f__rp, *lp; ll = (llp); lp = (lpp); for(i=0; i < (int)*(np); ++i) { nc = ll; if((rnp)[i] < nc) nc = (rnp)[i]; ll -= nc; f__rp = (rpp)[i]; while(--nc >= 0) *lp++ = *(f__rp)++; } while(--ll >= 0) *lp++ = ' '; } #define s_cmp(a,b,c,d) ((integer)strncmp((a),(b),f2cmin((c),(d)))) #define s_copy(A,B,C,D) { int __i,__m; for (__i=0, __m=f2cmin((C),(D)); __i<__m && (B)[__i] != 0; ++__i) (A)[__i] = (B)[__i]; } #define sig_die(s, kill) { exit(1); } #define s_stop(s, n) {exit(0);} static char junk[] = "\n@(#)LIBF77 VERSION 19990503\n"; #define z_abs(z) (cabs(Cd(z))) #define z_exp(R, Z) {pCd(R) = cexp(Cd(Z));} #define z_sqrt(R, Z) {pCd(R) = csqrt(Cd(Z));} #define myexit_() break; #define mycycle_() continue; #define myceiling_(w) ceil(w) #define myhuge_(w) HUGE_VAL //#define mymaxloc_(w,s,e,n) {if (sizeof(*(w)) == sizeof(double)) dmaxloc_((w),*(s),*(e),n); else dmaxloc_((w),*(s),*(e),n);} #define mymaxloc_(w,s,e,n) {dmaxloc_(w,*(s),*(e),n)} /* procedure parameter types for -A and -C++ */ #define F2C_proc_par_types 1 #ifdef __cplusplus typedef logical (*L_fp)(...); #else typedef logical (*L_fp)(); #endif static float spow_ui(float x, integer n) { float pow=1.0; unsigned long int u; if(n != 0) { if(n < 0) n = -n, x = 1/x; for(u = n; ; ) { if(u & 01) pow *= x; if(u >>= 1) x *= x; else break; } } return pow; } static double dpow_ui(double x, integer n) { double pow=1.0; unsigned long int u; if(n != 0) { if(n < 0) n = -n, x = 1/x; for(u = n; ; ) { if(u & 01) pow *= x; if(u >>= 1) x *= x; else break; } } return pow; } static _Complex float cpow_ui(_Complex float x, integer n) { _Complex float pow=1.0; unsigned long int u; if(n != 0) { if(n < 0) n = -n, x = 1/x; for(u = n; ; ) { if(u & 01) pow *= x; if(u >>= 1) x *= x; else break; } } return pow; } static _Complex double zpow_ui(_Complex double x, integer n) { _Complex double pow=1.0; unsigned long int u; if(n != 0) { if(n < 0) n = -n, x = 1/x; for(u = n; ; ) { if(u & 01) pow *= x; if(u >>= 1) x *= x; else break; } } return pow; } static integer pow_ii(integer x, integer n) { integer pow; unsigned long int u; if (n <= 0) { if (n == 0 || x == 1) pow = 1; else if (x != -1) pow = x == 0 ? 1/x : 0; else n = -n; } if ((n > 0) || !(n == 0 || x == 1 || x != -1)) { u = n; for(pow = 1; ; ) { if(u & 01) pow *= x; if(u >>= 1) x *= x; else break; } } return pow; } static integer dmaxloc_(double *w, integer s, integer e, integer *n) { double m; integer i, mi; for(m=w[s-1], mi=s, i=s+1; i<=e; i++) if (w[i-1]>m) mi=i ,m=w[i-1]; return mi-s+1; } static integer smaxloc_(float *w, integer s, integer e, integer *n) { float m; integer i, mi; for(m=w[s-1], mi=s, i=s+1; i<=e; i++) if (w[i-1]>m) mi=i ,m=w[i-1]; return mi-s+1; } static inline void cdotc_(complex *z, integer *n_, complex *x, integer *incx_, complex *y, integer *incy_) { integer n = *n_, incx = *incx_, incy = *incy_, i; _Complex float zdotc = 0.0; if (incx == 1 && incy == 1) { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += conjf(Cf(&x[i])) * Cf(&y[i]); } } else { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += conjf(Cf(&x[i*incx])) * Cf(&y[i*incy]); } } pCf(z) = zdotc; } static inline void zdotc_(doublecomplex *z, integer *n_, doublecomplex *x, integer *incx_, doublecomplex *y, integer *incy_) { integer n = *n_, incx = *incx_, incy = *incy_, i; _Complex double zdotc = 0.0; if (incx == 1 && incy == 1) { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += conj(Cd(&x[i])) * Cd(&y[i]); } } else { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += conj(Cd(&x[i*incx])) * Cd(&y[i*incy]); } } pCd(z) = zdotc; } static inline void cdotu_(complex *z, integer *n_, complex *x, integer *incx_, complex *y, integer *incy_) { integer n = *n_, incx = *incx_, incy = *incy_, i; _Complex float zdotc = 0.0; if (incx == 1 && incy == 1) { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += Cf(&x[i]) * Cf(&y[i]); } } else { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += Cf(&x[i*incx]) * Cf(&y[i*incy]); } } pCf(z) = zdotc; } static inline void zdotu_(doublecomplex *z, integer *n_, doublecomplex *x, integer *incx_, doublecomplex *y, integer *incy_) { integer n = *n_, incx = *incx_, incy = *incy_, i; _Complex double zdotc = 0.0; if (incx == 1 && incy == 1) { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += Cd(&x[i]) * Cd(&y[i]); } } else { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += Cd(&x[i*incx]) * Cd(&y[i*incy]); } } pCd(z) = zdotc; } #endif /* -- translated by f2c (version 20000121). You must link the resulting object file with the libraries: -lf2c -lm (in that order) */ /* Table of constant values */ static complex c_b1 = {0.f,0.f}; static complex c_b2 = {1.f,0.f}; static integer c__2 = 2; static integer c__1 = 1; static integer c__3 = 3; /* > \brief \b CLAQR5 performs a single small-bulge multi-shift QR sweep. */ /* =========== DOCUMENTATION =========== */ /* Online html documentation available at */ /* http://www.netlib.org/lapack/explore-html/ */ /* > \htmlonly */ /* > Download CLAQR5 + dependencies */ /* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.tgz?format=tgz&filename=/lapack/lapack_routine/claqr5. f"> */ /* > [TGZ]</a> */ /* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.zip?format=zip&filename=/lapack/lapack_routine/claqr5. f"> */ /* > [ZIP]</a> */ /* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.txt?format=txt&filename=/lapack/lapack_routine/claqr5. f"> */ /* > [TXT]</a> */ /* > \endhtmlonly */ /* Definition: */ /* =========== */ /* SUBROUTINE CLAQR5( WANTT, WANTZ, KACC22, N, KTOP, KBOT, NSHFTS, S, */ /* H, LDH, ILOZ, IHIZ, Z, LDZ, V, LDV, U, LDU, NV, */ /* WV, LDWV, NH, WH, LDWH ) */ /* INTEGER IHIZ, ILOZ, KACC22, KBOT, KTOP, LDH, LDU, LDV, */ /* $ LDWH, LDWV, LDZ, N, NH, NSHFTS, NV */ /* LOGICAL WANTT, WANTZ */ /* COMPLEX H( LDH, * ), S( * ), U( LDU, * ), V( LDV, * ), */ /* $ WH( LDWH, * ), WV( LDWV, * ), Z( LDZ, * ) */ /* > \par Purpose: */ /* ============= */ /* > */ /* > \verbatim */ /* > */ /* > CLAQR5 called by CLAQR0 performs a */ /* > single small-bulge multi-shift QR sweep. */ /* > \endverbatim */ /* Arguments: */ /* ========== */ /* > \param[in] WANTT */ /* > \verbatim */ /* > WANTT is LOGICAL */ /* > WANTT = .true. if the triangular Schur factor */ /* > is being computed. WANTT is set to .false. otherwise. */ /* > \endverbatim */ /* > */ /* > \param[in] WANTZ */ /* > \verbatim */ /* > WANTZ is LOGICAL */ /* > WANTZ = .true. if the unitary Schur factor is being */ /* > computed. WANTZ is set to .false. otherwise. */ /* > \endverbatim */ /* > */ /* > \param[in] KACC22 */ /* > \verbatim */ /* > KACC22 is INTEGER with value 0, 1, or 2. */ /* > Specifies the computation mode of far-from-diagonal */ /* > orthogonal updates. */ /* > = 0: CLAQR5 does not accumulate reflections and does not */ /* > use matrix-matrix multiply to update far-from-diagonal */ /* > matrix entries. */ /* > = 1: CLAQR5 accumulates reflections and uses matrix-matrix */ /* > multiply to update the far-from-diagonal matrix entries. */ /* > = 2: Same as KACC22 = 1. This option used to enable exploiting */ /* > the 2-by-2 structure during matrix multiplications, but */ /* > this is no longer supported. */ /* > \endverbatim */ /* > */ /* > \param[in] N */ /* > \verbatim */ /* > N is INTEGER */ /* > N is the order of the Hessenberg matrix H upon which this */ /* > subroutine operates. */ /* > \endverbatim */ /* > */ /* > \param[in] KTOP */ /* > \verbatim */ /* > KTOP is INTEGER */ /* > \endverbatim */ /* > */ /* > \param[in] KBOT */ /* > \verbatim */ /* > KBOT is INTEGER */ /* > These are the first and last rows and columns of an */ /* > isolated diagonal block upon which the QR sweep is to be */ /* > applied. It is assumed without a check that */ /* > either KTOP = 1 or H(KTOP,KTOP-1) = 0 */ /* > and */ /* > either KBOT = N or H(KBOT+1,KBOT) = 0. */ /* > \endverbatim */ /* > */ /* > \param[in] NSHFTS */ /* > \verbatim */ /* > NSHFTS is INTEGER */ /* > NSHFTS gives the number of simultaneous shifts. NSHFTS */ /* > must be positive and even. */ /* > \endverbatim */ /* > */ /* > \param[in,out] S */ /* > \verbatim */ /* > S is COMPLEX array, dimension (NSHFTS) */ /* > S contains the shifts of origin that define the multi- */ /* > shift QR sweep. On output S may be reordered. */ /* > \endverbatim */ /* > */ /* > \param[in,out] H */ /* > \verbatim */ /* > H is COMPLEX array, dimension (LDH,N) */ /* > On input H contains a Hessenberg matrix. On output a */ /* > multi-shift QR sweep with shifts SR(J)+i*SI(J) is applied */ /* > to the isolated diagonal block in rows and columns KTOP */ /* > through KBOT. */ /* > \endverbatim */ /* > */ /* > \param[in] LDH */ /* > \verbatim */ /* > LDH is INTEGER */ /* > LDH is the leading dimension of H just as declared in the */ /* > calling procedure. LDH >= MAX(1,N). */ /* > \endverbatim */ /* > */ /* > \param[in] ILOZ */ /* > \verbatim */ /* > ILOZ is INTEGER */ /* > \endverbatim */ /* > */ /* > \param[in] IHIZ */ /* > \verbatim */ /* > IHIZ is INTEGER */ /* > Specify the rows of Z to which transformations must be */ /* > applied if WANTZ is .TRUE.. 1 <= ILOZ <= IHIZ <= N */ /* > \endverbatim */ /* > */ /* > \param[in,out] Z */ /* > \verbatim */ /* > Z is COMPLEX array, dimension (LDZ,IHIZ) */ /* > If WANTZ = .TRUE., then the QR Sweep unitary */ /* > similarity transformation is accumulated into */ /* > Z(ILOZ:IHIZ,ILOZ:IHIZ) from the right. */ /* > If WANTZ = .FALSE., then Z is unreferenced. */ /* > \endverbatim */ /* > */ /* > \param[in] LDZ */ /* > \verbatim */ /* > LDZ is INTEGER */ /* > LDA is the leading dimension of Z just as declared in */ /* > the calling procedure. LDZ >= N. */ /* > \endverbatim */ /* > */ /* > \param[out] V */ /* > \verbatim */ /* > V is COMPLEX array, dimension (LDV,NSHFTS/2) */ /* > \endverbatim */ /* > */ /* > \param[in] LDV */ /* > \verbatim */ /* > LDV is INTEGER */ /* > LDV is the leading dimension of V as declared in the */ /* > calling procedure. LDV >= 3. */ /* > \endverbatim */ /* > */ /* > \param[out] U */ /* > \verbatim */ /* > U is COMPLEX array, dimension (LDU,2*NSHFTS) */ /* > \endverbatim */ /* > */ /* > \param[in] LDU */ /* > \verbatim */ /* > LDU is INTEGER */ /* > LDU is the leading dimension of U just as declared in the */ /* > in the calling subroutine. LDU >= 2*NSHFTS. */ /* > \endverbatim */ /* > */ /* > \param[in] NV */ /* > \verbatim */ /* > NV is INTEGER */ /* > NV is the number of rows in WV agailable for workspace. */ /* > NV >= 1. */ /* > \endverbatim */ /* > */ /* > \param[out] WV */ /* > \verbatim */ /* > WV is COMPLEX array, dimension (LDWV,2*NSHFTS) */ /* > \endverbatim */ /* > */ /* > \param[in] LDWV */ /* > \verbatim */ /* > LDWV is INTEGER */ /* > LDWV is the leading dimension of WV as declared in the */ /* > in the calling subroutine. LDWV >= NV. */ /* > \endverbatim */ /* > \param[in] NH */ /* > \verbatim */ /* > NH is INTEGER */ /* > NH is the number of columns in array WH available for */ /* > workspace. NH >= 1. */ /* > \endverbatim */ /* > */ /* > \param[out] WH */ /* > \verbatim */ /* > WH is COMPLEX array, dimension (LDWH,NH) */ /* > \endverbatim */ /* > */ /* > \param[in] LDWH */ /* > \verbatim */ /* > LDWH is INTEGER */ /* > Leading dimension of WH just as declared in the */ /* > calling procedure. LDWH >= 2*NSHFTS. */ /* > \endverbatim */ /* > */ /* Authors: */ /* ======== */ /* > \author Univ. of Tennessee */ /* > \author Univ. of California Berkeley */ /* > \author Univ. of Colorado Denver */ /* > \author NAG Ltd. */ /* > \date January 2021 */ /* > \ingroup complexOTHERauxiliary */ /* > \par Contributors: */ /* ================== */ /* > */ /* > Karen Braman and Ralph Byers, Department of Mathematics, */ /* > University of Kansas, USA */ /* > */ /* > Lars Karlsson, Daniel Kressner, and Bruno Lang */ /* > */ /* > Thijs Steel, Department of Computer science, */ /* > KU Leuven, Belgium */ /* > \par References: */ /* ================ */ /* > */ /* > K. Braman, R. Byers and R. Mathias, The Multi-Shift QR */ /* > Algorithm Part I: Maintaining Well Focused Shifts, and Level 3 */ /* > Performance, SIAM Journal of Matrix Analysis, volume 23, pages */ /* > 929--947, 2002. */ /* > */ /* > Lars Karlsson, Daniel Kressner, and Bruno Lang, Optimally packed */ /* > chains of bulges in multishift QR algorithms. */ /* > ACM Trans. Math. Softw. 40, 2, Article 12 (February 2014). */ /* > */ /* ===================================================================== */ /* Subroutine */ int claqr5_(logical *wantt, logical *wantz, integer *kacc22, integer *n, integer *ktop, integer *kbot, integer *nshfts, complex *s, complex *h__, integer *ldh, integer *iloz, integer *ihiz, complex * z__, integer *ldz, complex *v, integer *ldv, complex *u, integer *ldu, integer *nv, complex *wv, integer *ldwv, integer *nh, complex *wh, integer *ldwh) { /* System generated locals */ integer h_dim1, h_offset, u_dim1, u_offset, v_dim1, v_offset, wh_dim1, wh_offset, wv_dim1, wv_offset, z_dim1, z_offset, i__1, i__2, i__3, i__4, i__5, i__6, i__7, i__8, i__9, i__10, i__11; real r__1, r__2, r__3, r__4, r__5, r__6, r__7, r__8, r__9, r__10; complex q__1, q__2, q__3, q__4, q__5, q__6, q__7, q__8; /* Local variables */ complex beta; logical bmp22; integer jcol, jlen, jbot, mbot, jtop, jrow, mtop, j, k, m; complex alpha; logical accum; extern /* Subroutine */ int cgemm_(char *, char *, integer *, integer *, integer *, complex *, complex *, integer *, complex *, integer *, complex *, complex *, integer *); integer ndcol, incol, krcol, nbmps, i2, k1, i4; extern /* Subroutine */ int claqr1_(integer *, complex *, integer *, complex *, complex *, complex *); real h11, h12, h21, h22; integer m22; extern /* Subroutine */ int slabad_(real *, real *), clarfg_(integer *, complex *, complex *, integer *, complex *); integer ns, nu; extern real slamch_(char *); complex vt[3]; extern /* Subroutine */ int clacpy_(char *, integer *, integer *, complex *, integer *, complex *, integer *), claset_(char *, integer *, integer *, complex *, complex *, complex *, integer *); real safmin, safmax; complex refsum; real smlnum, scl; integer kdu, kms; real ulp; real tst1, tst2; /* -- LAPACK auxiliary routine (version 3.7.1) -- */ /* -- LAPACK is a software package provided by Univ. of Tennessee, -- */ /* -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..-- */ /* June 2016 */ /* ================================================================ */ /* ==== If there are no shifts, then there is nothing to do. ==== */ /* Parameter adjustments */ --s; h_dim1 = *ldh; h_offset = 1 + h_dim1 * 1; h__ -= h_offset; z_dim1 = *ldz; z_offset = 1 + z_dim1 * 1; z__ -= z_offset; v_dim1 = *ldv; v_offset = 1 + v_dim1 * 1; v -= v_offset; u_dim1 = *ldu; u_offset = 1 + u_dim1 * 1; u -= u_offset; wv_dim1 = *ldwv; wv_offset = 1 + wv_dim1 * 1; wv -= wv_offset; wh_dim1 = *ldwh; wh_offset = 1 + wh_dim1 * 1; wh -= wh_offset; /* Function Body */ if (*nshfts < 2) { return 0; } /* ==== If the active block is empty or 1-by-1, then there */ /* . is nothing to do. ==== */ if (*ktop >= *kbot) { return 0; } /* ==== NSHFTS is supposed to be even, but if it is odd, */ /* . then simply reduce it by one. ==== */ ns = *nshfts - *nshfts % 2; /* ==== Machine constants for deflation ==== */ safmin = slamch_("SAFE MINIMUM"); safmax = 1.f / safmin; slabad_(&safmin, &safmax); ulp = slamch_("PRECISION"); smlnum = safmin * ((real) (*n) / ulp); /* ==== Use accumulated reflections to update far-from-diagonal */ /* . entries ? ==== */ accum = *kacc22 == 1 || *kacc22 == 2; /* ==== clear trash ==== */ if (*ktop + 2 <= *kbot) { i__1 = *ktop + 2 + *ktop * h_dim1; h__[i__1].r = 0.f, h__[i__1].i = 0.f; } /* ==== NBMPS = number of 2-shift bulges in the chain ==== */ nbmps = ns / 2; /* ==== KDU = width of slab ==== */ kdu = nbmps << 2; /* ==== Create and chase chains of NBMPS bulges ==== */ i__1 = *kbot - 2; i__2 = nbmps << 1; for (incol = *ktop - (nbmps << 1) + 1; i__2 < 0 ? incol >= i__1 : incol <= i__1; incol += i__2) { /* JTOP = Index from which updates from the right start. */ if (accum) { jtop = f2cmax(*ktop,incol); } else if (*wantt) { jtop = 1; } else { jtop = *ktop; } ndcol = incol + kdu; if (accum) { claset_("ALL", &kdu, &kdu, &c_b1, &c_b2, &u[u_offset], ldu); } /* ==== Near-the-diagonal bulge chase. The following loop */ /* . performs the near-the-diagonal part of a small bulge */ /* . multi-shift QR sweep. Each 4*NBMPS column diagonal */ /* . chunk extends from column INCOL to column NDCOL */ /* . (including both column INCOL and column NDCOL). The */ /* . following loop chases a 2*NBMPS+1 column long chain of */ /* . NBMPS bulges 2*NBMPS columns to the right. (INCOL */ /* . may be less than KTOP and and NDCOL may be greater than */ /* . KBOT indicating phantom columns from which to chase */ /* . bulges before they are actually introduced or to which */ /* . to chase bulges beyond column KBOT.) ==== */ /* Computing MIN */ i__4 = incol + (nbmps << 1) - 1, i__5 = *kbot - 2; i__3 = f2cmin(i__4,i__5); for (krcol = incol; krcol <= i__3; ++krcol) { /* ==== Bulges number MTOP to MBOT are active double implicit */ /* . shift bulges. There may or may not also be small */ /* . 2-by-2 bulge, if there is room. The inactive bulges */ /* . (if any) must wait until the active bulges have moved */ /* . down the diagonal to make room. The phantom matrix */ /* . paradigm described above helps keep track. ==== */ /* Computing MAX */ i__4 = 1, i__5 = (*ktop - krcol) / 2 + 1; mtop = f2cmax(i__4,i__5); /* Computing MIN */ i__4 = nbmps, i__5 = (*kbot - krcol - 1) / 2; mbot = f2cmin(i__4,i__5); m22 = mbot + 1; bmp22 = mbot < nbmps && krcol + (m22 - 1 << 1) == *kbot - 2; /* ==== Generate reflections to chase the chain right */ /* . one column. (The minimum value of K is KTOP-1.) ==== */ if (bmp22) { /* ==== Special case: 2-by-2 reflection at bottom treated */ /* . separately ==== */ k = krcol + (m22 - 1 << 1); if (k == *ktop - 1) { claqr1_(&c__2, &h__[k + 1 + (k + 1) * h_dim1], ldh, &s[( m22 << 1) - 1], &s[m22 * 2], &v[m22 * v_dim1 + 1]) ; i__4 = m22 * v_dim1 + 1; beta.r = v[i__4].r, beta.i = v[i__4].i; clarfg_(&c__2, &beta, &v[m22 * v_dim1 + 2], &c__1, &v[m22 * v_dim1 + 1]); } else { i__4 = k + 1 + k * h_dim1; beta.r = h__[i__4].r, beta.i = h__[i__4].i; i__4 = m22 * v_dim1 + 2; i__5 = k + 2 + k * h_dim1; v[i__4].r = h__[i__5].r, v[i__4].i = h__[i__5].i; clarfg_(&c__2, &beta, &v[m22 * v_dim1 + 2], &c__1, &v[m22 * v_dim1 + 1]); i__4 = k + 1 + k * h_dim1; h__[i__4].r = beta.r, h__[i__4].i = beta.i; i__4 = k + 2 + k * h_dim1; h__[i__4].r = 0.f, h__[i__4].i = 0.f; } /* ==== Perform update from right within */ /* . computational window. ==== */ /* Computing MIN */ i__5 = *kbot, i__6 = k + 3; i__4 = f2cmin(i__5,i__6); for (j = jtop; j <= i__4; ++j) { i__5 = m22 * v_dim1 + 1; i__6 = j + (k + 1) * h_dim1; i__7 = m22 * v_dim1 + 2; i__8 = j + (k + 2) * h_dim1; q__3.r = v[i__7].r * h__[i__8].r - v[i__7].i * h__[i__8] .i, q__3.i = v[i__7].r * h__[i__8].i + v[i__7].i * h__[i__8].r; q__2.r = h__[i__6].r + q__3.r, q__2.i = h__[i__6].i + q__3.i; q__1.r = v[i__5].r * q__2.r - v[i__5].i * q__2.i, q__1.i = v[i__5].r * q__2.i + v[i__5].i * q__2.r; refsum.r = q__1.r, refsum.i = q__1.i; i__5 = j + (k + 1) * h_dim1; i__6 = j + (k + 1) * h_dim1; q__1.r = h__[i__6].r - refsum.r, q__1.i = h__[i__6].i - refsum.i; h__[i__5].r = q__1.r, h__[i__5].i = q__1.i; i__5 = j + (k + 2) * h_dim1; i__6 = j + (k + 2) * h_dim1; r_cnjg(&q__3, &v[m22 * v_dim1 + 2]); q__2.r = refsum.r * q__3.r - refsum.i * q__3.i, q__2.i = refsum.r * q__3.i + refsum.i * q__3.r; q__1.r = h__[i__6].r - q__2.r, q__1.i = h__[i__6].i - q__2.i; h__[i__5].r = q__1.r, h__[i__5].i = q__1.i; /* L30: */ } /* ==== Perform update from left within */ /* . computational window. ==== */ if (accum) { jbot = f2cmin(ndcol,*kbot); } else if (*wantt) { jbot = *n; } else { jbot = *kbot; } i__4 = jbot; for (j = k + 1; j <= i__4; ++j) { r_cnjg(&q__2, &v[m22 * v_dim1 + 1]); i__5 = k + 1 + j * h_dim1; r_cnjg(&q__5, &v[m22 * v_dim1 + 2]); i__6 = k + 2 + j * h_dim1; q__4.r = q__5.r * h__[i__6].r - q__5.i * h__[i__6].i, q__4.i = q__5.r * h__[i__6].i + q__5.i * h__[i__6] .r; q__3.r = h__[i__5].r + q__4.r, q__3.i = h__[i__5].i + q__4.i; q__1.r = q__2.r * q__3.r - q__2.i * q__3.i, q__1.i = q__2.r * q__3.i + q__2.i * q__3.r; refsum.r = q__1.r, refsum.i = q__1.i; i__5 = k + 1 + j * h_dim1; i__6 = k + 1 + j * h_dim1; q__1.r = h__[i__6].r - refsum.r, q__1.i = h__[i__6].i - refsum.i; h__[i__5].r = q__1.r, h__[i__5].i = q__1.i; i__5 = k + 2 + j * h_dim1; i__6 = k + 2 + j * h_dim1; i__7 = m22 * v_dim1 + 2; q__2.r = refsum.r * v[i__7].r - refsum.i * v[i__7].i, q__2.i = refsum.r * v[i__7].i + refsum.i * v[i__7] .r; q__1.r = h__[i__6].r - q__2.r, q__1.i = h__[i__6].i - q__2.i; h__[i__5].r = q__1.r, h__[i__5].i = q__1.i; /* L40: */ } /* ==== The following convergence test requires that */ /* . the tradition small-compared-to-nearby-diagonals */ /* . criterion and the Ahues & Tisseur (LAWN 122, 1997) */ /* . criteria both be satisfied. The latter improves */ /* . accuracy in some examples. Falling back on an */ /* . alternate convergence criterion when TST1 or TST2 */ /* . is zero (as done here) is traditional but probably */ /* . unnecessary. ==== */ if (k >= *ktop) { i__4 = k + 1 + k * h_dim1; if (h__[i__4].r != 0.f || h__[i__4].i != 0.f) { i__4 = k + k * h_dim1; i__5 = k + 1 + (k + 1) * h_dim1; tst1 = (r__1 = h__[i__4].r, abs(r__1)) + (r__2 = r_imag(&h__[k + k * h_dim1]), abs(r__2)) + (( r__3 = h__[i__5].r, abs(r__3)) + (r__4 = r_imag(&h__[k + 1 + (k + 1) * h_dim1]), abs( r__4))); if (tst1 == 0.f) { if (k >= *ktop + 1) { i__4 = k + (k - 1) * h_dim1; tst1 += (r__1 = h__[i__4].r, abs(r__1)) + ( r__2 = r_imag(&h__[k + (k - 1) * h_dim1]), abs(r__2)); } if (k >= *ktop + 2) { i__4 = k + (k - 2) * h_dim1; tst1 += (r__1 = h__[i__4].r, abs(r__1)) + ( r__2 = r_imag(&h__[k + (k - 2) * h_dim1]), abs(r__2)); } if (k >= *ktop + 3) { i__4 = k + (k - 3) * h_dim1; tst1 += (r__1 = h__[i__4].r, abs(r__1)) + ( r__2 = r_imag(&h__[k + (k - 3) * h_dim1]), abs(r__2)); } if (k <= *kbot - 2) { i__4 = k + 2 + (k + 1) * h_dim1; tst1 += (r__1 = h__[i__4].r, abs(r__1)) + ( r__2 = r_imag(&h__[k + 2 + (k + 1) * h_dim1]), abs(r__2)); } if (k <= *kbot - 3) { i__4 = k + 3 + (k + 1) * h_dim1; tst1 += (r__1 = h__[i__4].r, abs(r__1)) + ( r__2 = r_imag(&h__[k + 3 + (k + 1) * h_dim1]), abs(r__2)); } if (k <= *kbot - 4) { i__4 = k + 4 + (k + 1) * h_dim1; tst1 += (r__1 = h__[i__4].r, abs(r__1)) + ( r__2 = r_imag(&h__[k + 4 + (k + 1) * h_dim1]), abs(r__2)); } } i__4 = k + 1 + k * h_dim1; /* Computing MAX */ r__3 = smlnum, r__4 = ulp * tst1; if ((r__1 = h__[i__4].r, abs(r__1)) + (r__2 = r_imag(& h__[k + 1 + k * h_dim1]), abs(r__2)) <= f2cmax( r__3,r__4)) { /* Computing MAX */ i__4 = k + 1 + k * h_dim1; i__5 = k + (k + 1) * h_dim1; r__5 = (r__1 = h__[i__4].r, abs(r__1)) + (r__2 = r_imag(&h__[k + 1 + k * h_dim1]), abs( r__2)), r__6 = (r__3 = h__[i__5].r, abs( r__3)) + (r__4 = r_imag(&h__[k + (k + 1) * h_dim1]), abs(r__4)); h12 = f2cmax(r__5,r__6); /* Computing MIN */ i__4 = k + 1 + k * h_dim1; i__5 = k + (k + 1) * h_dim1; r__5 = (r__1 = h__[i__4].r, abs(r__1)) + (r__2 = r_imag(&h__[k + 1 + k * h_dim1]), abs( r__2)), r__6 = (r__3 = h__[i__5].r, abs( r__3)) + (r__4 = r_imag(&h__[k + (k + 1) * h_dim1]), abs(r__4)); h21 = f2cmin(r__5,r__6); i__4 = k + k * h_dim1; i__5 = k + 1 + (k + 1) * h_dim1; q__2.r = h__[i__4].r - h__[i__5].r, q__2.i = h__[ i__4].i - h__[i__5].i; q__1.r = q__2.r, q__1.i = q__2.i; /* Computing MAX */ i__6 = k + 1 + (k + 1) * h_dim1; r__5 = (r__1 = h__[i__6].r, abs(r__1)) + (r__2 = r_imag(&h__[k + 1 + (k + 1) * h_dim1]), abs(r__2)), r__6 = (r__3 = q__1.r, abs( r__3)) + (r__4 = r_imag(&q__1), abs(r__4)) ; h11 = f2cmax(r__5,r__6); i__4 = k + k * h_dim1; i__5 = k + 1 + (k + 1) * h_dim1; q__2.r = h__[i__4].r - h__[i__5].r, q__2.i = h__[ i__4].i - h__[i__5].i; q__1.r = q__2.r, q__1.i = q__2.i; /* Computing MIN */ i__6 = k + 1 + (k + 1) * h_dim1; r__5 = (r__1 = h__[i__6].r, abs(r__1)) + (r__2 = r_imag(&h__[k + 1 + (k + 1) * h_dim1]), abs(r__2)), r__6 = (r__3 = q__1.r, abs( r__3)) + (r__4 = r_imag(&q__1), abs(r__4)) ; h22 = f2cmin(r__5,r__6); scl = h11 + h12; tst2 = h22 * (h11 / scl); /* Computing MAX */ r__1 = smlnum, r__2 = ulp * tst2; if (tst2 == 0.f || h21 * (h12 / scl) <= f2cmax(r__1, r__2)) { i__4 = k + 1 + k * h_dim1; h__[i__4].r = 0.f, h__[i__4].i = 0.f; } } } } /* ==== Accumulate orthogonal transformations. ==== */ if (accum) { kms = k - incol; /* Computing MAX */ i__4 = 1, i__5 = *ktop - incol; i__6 = kdu; for (j = f2cmax(i__4,i__5); j <= i__6; ++j) { i__4 = m22 * v_dim1 + 1; i__5 = j + (kms + 1) * u_dim1; i__7 = m22 * v_dim1 + 2; i__8 = j + (kms + 2) * u_dim1; q__3.r = v[i__7].r * u[i__8].r - v[i__7].i * u[i__8] .i, q__3.i = v[i__7].r * u[i__8].i + v[i__7] .i * u[i__8].r; q__2.r = u[i__5].r + q__3.r, q__2.i = u[i__5].i + q__3.i; q__1.r = v[i__4].r * q__2.r - v[i__4].i * q__2.i, q__1.i = v[i__4].r * q__2.i + v[i__4].i * q__2.r; refsum.r = q__1.r, refsum.i = q__1.i; i__4 = j + (kms + 1) * u_dim1; i__5 = j + (kms + 1) * u_dim1; q__1.r = u[i__5].r - refsum.r, q__1.i = u[i__5].i - refsum.i; u[i__4].r = q__1.r, u[i__4].i = q__1.i; i__4 = j + (kms + 2) * u_dim1; i__5 = j + (kms + 2) * u_dim1; r_cnjg(&q__3, &v[m22 * v_dim1 + 2]); q__2.r = refsum.r * q__3.r - refsum.i * q__3.i, q__2.i = refsum.r * q__3.i + refsum.i * q__3.r; q__1.r = u[i__5].r - q__2.r, q__1.i = u[i__5].i - q__2.i; u[i__4].r = q__1.r, u[i__4].i = q__1.i; /* L50: */ } } else if (*wantz) { i__6 = *ihiz; for (j = *iloz; j <= i__6; ++j) { i__4 = m22 * v_dim1 + 1; i__5 = j + (k + 1) * z_dim1; i__7 = m22 * v_dim1 + 2; i__8 = j + (k + 2) * z_dim1; q__3.r = v[i__7].r * z__[i__8].r - v[i__7].i * z__[ i__8].i, q__3.i = v[i__7].r * z__[i__8].i + v[ i__7].i * z__[i__8].r; q__2.r = z__[i__5].r + q__3.r, q__2.i = z__[i__5].i + q__3.i; q__1.r = v[i__4].r * q__2.r - v[i__4].i * q__2.i, q__1.i = v[i__4].r * q__2.i + v[i__4].i * q__2.r; refsum.r = q__1.r, refsum.i = q__1.i; i__4 = j + (k + 1) * z_dim1; i__5 = j + (k + 1) * z_dim1; q__1.r = z__[i__5].r - refsum.r, q__1.i = z__[i__5].i - refsum.i; z__[i__4].r = q__1.r, z__[i__4].i = q__1.i; i__4 = j + (k + 2) * z_dim1; i__5 = j + (k + 2) * z_dim1; r_cnjg(&q__3, &v[m22 * v_dim1 + 2]); q__2.r = refsum.r * q__3.r - refsum.i * q__3.i, q__2.i = refsum.r * q__3.i + refsum.i * q__3.r; q__1.r = z__[i__5].r - q__2.r, q__1.i = z__[i__5].i - q__2.i; z__[i__4].r = q__1.r, z__[i__4].i = q__1.i; /* L60: */ } } } /* ==== Normal case: Chain of 3-by-3 reflections ==== */ i__6 = mtop; for (m = mbot; m >= i__6; --m) { k = krcol + (m - 1 << 1); if (k == *ktop - 1) { claqr1_(&c__3, &h__[*ktop + *ktop * h_dim1], ldh, &s[(m << 1) - 1], &s[m * 2], &v[m * v_dim1 + 1]); i__4 = m * v_dim1 + 1; alpha.r = v[i__4].r, alpha.i = v[i__4].i; clarfg_(&c__3, &alpha, &v[m * v_dim1 + 2], &c__1, &v[m * v_dim1 + 1]); } else { /* ==== Perform delayed transformation of row below */ /* . Mth bulge. Exploit fact that first two elements */ /* . of row are actually zero. ==== */ i__4 = m * v_dim1 + 1; i__5 = m * v_dim1 + 3; q__2.r = v[i__4].r * v[i__5].r - v[i__4].i * v[i__5].i, q__2.i = v[i__4].r * v[i__5].i + v[i__4].i * v[ i__5].r; i__7 = k + 3 + (k + 2) * h_dim1; q__1.r = q__2.r * h__[i__7].r - q__2.i * h__[i__7].i, q__1.i = q__2.r * h__[i__7].i + q__2.i * h__[i__7] .r; refsum.r = q__1.r, refsum.i = q__1.i; i__4 = k + 3 + k * h_dim1; q__1.r = -refsum.r, q__1.i = -refsum.i; h__[i__4].r = q__1.r, h__[i__4].i = q__1.i; i__4 = k + 3 + (k + 1) * h_dim1; q__2.r = -refsum.r, q__2.i = -refsum.i; r_cnjg(&q__3, &v[m * v_dim1 + 2]); q__1.r = q__2.r * q__3.r - q__2.i * q__3.i, q__1.i = q__2.r * q__3.i + q__2.i * q__3.r; h__[i__4].r = q__1.r, h__[i__4].i = q__1.i; i__4 = k + 3 + (k + 2) * h_dim1; i__5 = k + 3 + (k + 2) * h_dim1; r_cnjg(&q__3, &v[m * v_dim1 + 3]); q__2.r = refsum.r * q__3.r - refsum.i * q__3.i, q__2.i = refsum.r * q__3.i + refsum.i * q__3.r; q__1.r = h__[i__5].r - q__2.r, q__1.i = h__[i__5].i - q__2.i; h__[i__4].r = q__1.r, h__[i__4].i = q__1.i; /* ==== Calculate reflection to move */ /* . Mth bulge one step. ==== */ i__4 = k + 1 + k * h_dim1; beta.r = h__[i__4].r, beta.i = h__[i__4].i; i__4 = m * v_dim1 + 2; i__5 = k + 2 + k * h_dim1; v[i__4].r = h__[i__5].r, v[i__4].i = h__[i__5].i; i__4 = m * v_dim1 + 3; i__5 = k + 3 + k * h_dim1; v[i__4].r = h__[i__5].r, v[i__4].i = h__[i__5].i; clarfg_(&c__3, &beta, &v[m * v_dim1 + 2], &c__1, &v[m * v_dim1 + 1]); /* ==== A Bulge may collapse because of vigilant */ /* . deflation or destructive underflow. In the */ /* . underflow case, try the two-small-subdiagonals */ /* . trick to try to reinflate the bulge. ==== */ i__4 = k + 3 + k * h_dim1; i__5 = k + 3 + (k + 1) * h_dim1; i__7 = k + 3 + (k + 2) * h_dim1; if (h__[i__4].r != 0.f || h__[i__4].i != 0.f || (h__[i__5] .r != 0.f || h__[i__5].i != 0.f) || h__[i__7].r == 0.f && h__[i__7].i == 0.f) { /* ==== Typical case: not collapsed (yet). ==== */ i__4 = k + 1 + k * h_dim1; h__[i__4].r = beta.r, h__[i__4].i = beta.i; i__4 = k + 2 + k * h_dim1; h__[i__4].r = 0.f, h__[i__4].i = 0.f; i__4 = k + 3 + k * h_dim1; h__[i__4].r = 0.f, h__[i__4].i = 0.f; } else { /* ==== Atypical case: collapsed. Attempt to */ /* . reintroduce ignoring H(K+1,K) and H(K+2,K). */ /* . If the fill resulting from the new */ /* . reflector is too large, then abandon it. */ /* . Otherwise, use the new one. ==== */ claqr1_(&c__3, &h__[k + 1 + (k + 1) * h_dim1], ldh, & s[(m << 1) - 1], &s[m * 2], vt); alpha.r = vt[0].r, alpha.i = vt[0].i; clarfg_(&c__3, &alpha, &vt[1], &c__1, vt); r_cnjg(&q__2, vt); i__4 = k + 1 + k * h_dim1; r_cnjg(&q__5, &vt[1]); i__5 = k + 2 + k * h_dim1; q__4.r = q__5.r * h__[i__5].r - q__5.i * h__[i__5].i, q__4.i = q__5.r * h__[i__5].i + q__5.i * h__[ i__5].r; q__3.r = h__[i__4].r + q__4.r, q__3.i = h__[i__4].i + q__4.i; q__1.r = q__2.r * q__3.r - q__2.i * q__3.i, q__1.i = q__2.r * q__3.i + q__2.i * q__3.r; refsum.r = q__1.r, refsum.i = q__1.i; i__4 = k + 2 + k * h_dim1; q__3.r = refsum.r * vt[1].r - refsum.i * vt[1].i, q__3.i = refsum.r * vt[1].i + refsum.i * vt[1] .r; q__2.r = h__[i__4].r - q__3.r, q__2.i = h__[i__4].i - q__3.i; q__1.r = q__2.r, q__1.i = q__2.i; q__5.r = refsum.r * vt[2].r - refsum.i * vt[2].i, q__5.i = refsum.r * vt[2].i + refsum.i * vt[2] .r; q__4.r = q__5.r, q__4.i = q__5.i; i__5 = k + k * h_dim1; i__7 = k + 1 + (k + 1) * h_dim1; i__8 = k + 2 + (k + 2) * h_dim1; if ((r__1 = q__1.r, abs(r__1)) + (r__2 = r_imag(&q__1) , abs(r__2)) + ((r__3 = q__4.r, abs(r__3)) + ( r__4 = r_imag(&q__4), abs(r__4))) > ulp * (( r__5 = h__[i__5].r, abs(r__5)) + (r__6 = r_imag(&h__[k + k * h_dim1]), abs(r__6)) + (( r__7 = h__[i__7].r, abs(r__7)) + (r__8 = r_imag(&h__[k + 1 + (k + 1) * h_dim1]), abs( r__8))) + ((r__9 = h__[i__8].r, abs(r__9)) + ( r__10 = r_imag(&h__[k + 2 + (k + 2) * h_dim1]) , abs(r__10))))) { /* ==== Starting a new bulge here would */ /* . create non-negligible fill. Use */ /* . the old one with trepidation. ==== */ i__4 = k + 1 + k * h_dim1; h__[i__4].r = beta.r, h__[i__4].i = beta.i; i__4 = k + 2 + k * h_dim1; h__[i__4].r = 0.f, h__[i__4].i = 0.f; i__4 = k + 3 + k * h_dim1; h__[i__4].r = 0.f, h__[i__4].i = 0.f; } else { /* ==== Starting a new bulge here would */ /* . create only negligible fill. */ /* . Replace the old reflector with */ /* . the new one. ==== */ i__4 = k + 1 + k * h_dim1; i__5 = k + 1 + k * h_dim1; q__1.r = h__[i__5].r - refsum.r, q__1.i = h__[ i__5].i - refsum.i; h__[i__4].r = q__1.r, h__[i__4].i = q__1.i; i__4 = k + 2 + k * h_dim1; h__[i__4].r = 0.f, h__[i__4].i = 0.f; i__4 = k + 3 + k * h_dim1; h__[i__4].r = 0.f, h__[i__4].i = 0.f; i__4 = m * v_dim1 + 1; v[i__4].r = vt[0].r, v[i__4].i = vt[0].i; i__4 = m * v_dim1 + 2; v[i__4].r = vt[1].r, v[i__4].i = vt[1].i; i__4 = m * v_dim1 + 3; v[i__4].r = vt[2].r, v[i__4].i = vt[2].i; } } } /* ==== Apply reflection from the right and */ /* . the first column of update from the left. */ /* . These updates are required for the vigilant */ /* . deflation check. We still delay most of the */ /* . updates from the left for efficiency. ==== */ /* Computing MIN */ i__5 = *kbot, i__7 = k + 3; i__4 = f2cmin(i__5,i__7); for (j = jtop; j <= i__4; ++j) { i__5 = m * v_dim1 + 1; i__7 = j + (k + 1) * h_dim1; i__8 = m * v_dim1 + 2; i__9 = j + (k + 2) * h_dim1; q__4.r = v[i__8].r * h__[i__9].r - v[i__8].i * h__[i__9] .i, q__4.i = v[i__8].r * h__[i__9].i + v[i__8].i * h__[i__9].r; q__3.r = h__[i__7].r + q__4.r, q__3.i = h__[i__7].i + q__4.i; i__10 = m * v_dim1 + 3; i__11 = j + (k + 3) * h_dim1; q__5.r = v[i__10].r * h__[i__11].r - v[i__10].i * h__[ i__11].i, q__5.i = v[i__10].r * h__[i__11].i + v[ i__10].i * h__[i__11].r; q__2.r = q__3.r + q__5.r, q__2.i = q__3.i + q__5.i; q__1.r = v[i__5].r * q__2.r - v[i__5].i * q__2.i, q__1.i = v[i__5].r * q__2.i + v[i__5].i * q__2.r; refsum.r = q__1.r, refsum.i = q__1.i; i__5 = j + (k + 1) * h_dim1; i__7 = j + (k + 1) * h_dim1; q__1.r = h__[i__7].r - refsum.r, q__1.i = h__[i__7].i - refsum.i; h__[i__5].r = q__1.r, h__[i__5].i = q__1.i; i__5 = j + (k + 2) * h_dim1; i__7 = j + (k + 2) * h_dim1; r_cnjg(&q__3, &v[m * v_dim1 + 2]); q__2.r = refsum.r * q__3.r - refsum.i * q__3.i, q__2.i = refsum.r * q__3.i + refsum.i * q__3.r; q__1.r = h__[i__7].r - q__2.r, q__1.i = h__[i__7].i - q__2.i; h__[i__5].r = q__1.r, h__[i__5].i = q__1.i; i__5 = j + (k + 3) * h_dim1; i__7 = j + (k + 3) * h_dim1; r_cnjg(&q__3, &v[m * v_dim1 + 3]); q__2.r = refsum.r * q__3.r - refsum.i * q__3.i, q__2.i = refsum.r * q__3.i + refsum.i * q__3.r; q__1.r = h__[i__7].r - q__2.r, q__1.i = h__[i__7].i - q__2.i; h__[i__5].r = q__1.r, h__[i__5].i = q__1.i; /* L70: */ } /* ==== Perform update from left for subsequent */ /* . column. ==== */ r_cnjg(&q__2, &v[m * v_dim1 + 1]); i__4 = k + 1 + (k + 1) * h_dim1; r_cnjg(&q__6, &v[m * v_dim1 + 2]); i__5 = k + 2 + (k + 1) * h_dim1; q__5.r = q__6.r * h__[i__5].r - q__6.i * h__[i__5].i, q__5.i = q__6.r * h__[i__5].i + q__6.i * h__[i__5].r; q__4.r = h__[i__4].r + q__5.r, q__4.i = h__[i__4].i + q__5.i; r_cnjg(&q__8, &v[m * v_dim1 + 3]); i__7 = k + 3 + (k + 1) * h_dim1; q__7.r = q__8.r * h__[i__7].r - q__8.i * h__[i__7].i, q__7.i = q__8.r * h__[i__7].i + q__8.i * h__[i__7].r; q__3.r = q__4.r + q__7.r, q__3.i = q__4.i + q__7.i; q__1.r = q__2.r * q__3.r - q__2.i * q__3.i, q__1.i = q__2.r * q__3.i + q__2.i * q__3.r; refsum.r = q__1.r, refsum.i = q__1.i; i__4 = k + 1 + (k + 1) * h_dim1; i__5 = k + 1 + (k + 1) * h_dim1; q__1.r = h__[i__5].r - refsum.r, q__1.i = h__[i__5].i - refsum.i; h__[i__4].r = q__1.r, h__[i__4].i = q__1.i; i__4 = k + 2 + (k + 1) * h_dim1; i__5 = k + 2 + (k + 1) * h_dim1; i__7 = m * v_dim1 + 2; q__2.r = refsum.r * v[i__7].r - refsum.i * v[i__7].i, q__2.i = refsum.r * v[i__7].i + refsum.i * v[i__7].r; q__1.r = h__[i__5].r - q__2.r, q__1.i = h__[i__5].i - q__2.i; h__[i__4].r = q__1.r, h__[i__4].i = q__1.i; i__4 = k + 3 + (k + 1) * h_dim1; i__5 = k + 3 + (k + 1) * h_dim1; i__7 = m * v_dim1 + 3; q__2.r = refsum.r * v[i__7].r - refsum.i * v[i__7].i, q__2.i = refsum.r * v[i__7].i + refsum.i * v[i__7].r; q__1.r = h__[i__5].r - q__2.r, q__1.i = h__[i__5].i - q__2.i; h__[i__4].r = q__1.r, h__[i__4].i = q__1.i; /* ==== The following convergence test requires that */ /* . the tradition small-compared-to-nearby-diagonals */ /* . criterion and the Ahues & Tisseur (LAWN 122, 1997) */ /* . criteria both be satisfied. The latter improves */ /* . accuracy in some examples. Falling back on an */ /* . alternate convergence criterion when TST1 or TST2 */ /* . is zero (as done here) is traditional but probably */ /* . unnecessary. ==== */ if (k < *ktop) { mycycle_(); } i__4 = k + 1 + k * h_dim1; if (h__[i__4].r != 0.f || h__[i__4].i != 0.f) { i__4 = k + k * h_dim1; i__5 = k + 1 + (k + 1) * h_dim1; tst1 = (r__1 = h__[i__4].r, abs(r__1)) + (r__2 = r_imag(& h__[k + k * h_dim1]), abs(r__2)) + ((r__3 = h__[ i__5].r, abs(r__3)) + (r__4 = r_imag(&h__[k + 1 + (k + 1) * h_dim1]), abs(r__4))); if (tst1 == 0.f) { if (k >= *ktop + 1) { i__4 = k + (k - 1) * h_dim1; tst1 += (r__1 = h__[i__4].r, abs(r__1)) + (r__2 = r_imag(&h__[k + (k - 1) * h_dim1]), abs( r__2)); } if (k >= *ktop + 2) { i__4 = k + (k - 2) * h_dim1; tst1 += (r__1 = h__[i__4].r, abs(r__1)) + (r__2 = r_imag(&h__[k + (k - 2) * h_dim1]), abs( r__2)); } if (k >= *ktop + 3) { i__4 = k + (k - 3) * h_dim1; tst1 += (r__1 = h__[i__4].r, abs(r__1)) + (r__2 = r_imag(&h__[k + (k - 3) * h_dim1]), abs( r__2)); } if (k <= *kbot - 2) { i__4 = k + 2 + (k + 1) * h_dim1; tst1 += (r__1 = h__[i__4].r, abs(r__1)) + (r__2 = r_imag(&h__[k + 2 + (k + 1) * h_dim1]), abs(r__2)); } if (k <= *kbot - 3) { i__4 = k + 3 + (k + 1) * h_dim1; tst1 += (r__1 = h__[i__4].r, abs(r__1)) + (r__2 = r_imag(&h__[k + 3 + (k + 1) * h_dim1]), abs(r__2)); } if (k <= *kbot - 4) { i__4 = k + 4 + (k + 1) * h_dim1; tst1 += (r__1 = h__[i__4].r, abs(r__1)) + (r__2 = r_imag(&h__[k + 4 + (k + 1) * h_dim1]), abs(r__2)); } } i__4 = k + 1 + k * h_dim1; /* Computing MAX */ r__3 = smlnum, r__4 = ulp * tst1; if ((r__1 = h__[i__4].r, abs(r__1)) + (r__2 = r_imag(&h__[ k + 1 + k * h_dim1]), abs(r__2)) <= f2cmax(r__3,r__4) ) { /* Computing MAX */ i__4 = k + 1 + k * h_dim1; i__5 = k + (k + 1) * h_dim1; r__5 = (r__1 = h__[i__4].r, abs(r__1)) + (r__2 = r_imag(&h__[k + 1 + k * h_dim1]), abs(r__2)), r__6 = (r__3 = h__[i__5].r, abs(r__3)) + ( r__4 = r_imag(&h__[k + (k + 1) * h_dim1]), abs(r__4)); h12 = f2cmax(r__5,r__6); /* Computing MIN */ i__4 = k + 1 + k * h_dim1; i__5 = k + (k + 1) * h_dim1; r__5 = (r__1 = h__[i__4].r, abs(r__1)) + (r__2 = r_imag(&h__[k + 1 + k * h_dim1]), abs(r__2)), r__6 = (r__3 = h__[i__5].r, abs(r__3)) + ( r__4 = r_imag(&h__[k + (k + 1) * h_dim1]), abs(r__4)); h21 = f2cmin(r__5,r__6); i__4 = k + k * h_dim1; i__5 = k + 1 + (k + 1) * h_dim1; q__2.r = h__[i__4].r - h__[i__5].r, q__2.i = h__[i__4] .i - h__[i__5].i; q__1.r = q__2.r, q__1.i = q__2.i; /* Computing MAX */ i__7 = k + 1 + (k + 1) * h_dim1; r__5 = (r__1 = h__[i__7].r, abs(r__1)) + (r__2 = r_imag(&h__[k + 1 + (k + 1) * h_dim1]), abs( r__2)), r__6 = (r__3 = q__1.r, abs(r__3)) + ( r__4 = r_imag(&q__1), abs(r__4)); h11 = f2cmax(r__5,r__6); i__4 = k + k * h_dim1; i__5 = k + 1 + (k + 1) * h_dim1; q__2.r = h__[i__4].r - h__[i__5].r, q__2.i = h__[i__4] .i - h__[i__5].i; q__1.r = q__2.r, q__1.i = q__2.i; /* Computing MIN */ i__7 = k + 1 + (k + 1) * h_dim1; r__5 = (r__1 = h__[i__7].r, abs(r__1)) + (r__2 = r_imag(&h__[k + 1 + (k + 1) * h_dim1]), abs( r__2)), r__6 = (r__3 = q__1.r, abs(r__3)) + ( r__4 = r_imag(&q__1), abs(r__4)); h22 = f2cmin(r__5,r__6); scl = h11 + h12; tst2 = h22 * (h11 / scl); /* Computing MAX */ r__1 = smlnum, r__2 = ulp * tst2; if (tst2 == 0.f || h21 * (h12 / scl) <= f2cmax(r__1,r__2) ) { i__4 = k + 1 + k * h_dim1; h__[i__4].r = 0.f, h__[i__4].i = 0.f; } } } /* L80: */ } /* ==== Multiply H by reflections from the left ==== */ if (accum) { jbot = f2cmin(ndcol,*kbot); } else if (*wantt) { jbot = *n; } else { jbot = *kbot; } i__6 = mtop; for (m = mbot; m >= i__6; --m) { k = krcol + (m - 1 << 1); /* Computing MAX */ i__4 = *ktop, i__5 = krcol + (m << 1); i__7 = jbot; for (j = f2cmax(i__4,i__5); j <= i__7; ++j) { r_cnjg(&q__2, &v[m * v_dim1 + 1]); i__4 = k + 1 + j * h_dim1; r_cnjg(&q__6, &v[m * v_dim1 + 2]); i__5 = k + 2 + j * h_dim1; q__5.r = q__6.r * h__[i__5].r - q__6.i * h__[i__5].i, q__5.i = q__6.r * h__[i__5].i + q__6.i * h__[i__5] .r; q__4.r = h__[i__4].r + q__5.r, q__4.i = h__[i__4].i + q__5.i; r_cnjg(&q__8, &v[m * v_dim1 + 3]); i__8 = k + 3 + j * h_dim1; q__7.r = q__8.r * h__[i__8].r - q__8.i * h__[i__8].i, q__7.i = q__8.r * h__[i__8].i + q__8.i * h__[i__8] .r; q__3.r = q__4.r + q__7.r, q__3.i = q__4.i + q__7.i; q__1.r = q__2.r * q__3.r - q__2.i * q__3.i, q__1.i = q__2.r * q__3.i + q__2.i * q__3.r; refsum.r = q__1.r, refsum.i = q__1.i; i__4 = k + 1 + j * h_dim1; i__5 = k + 1 + j * h_dim1; q__1.r = h__[i__5].r - refsum.r, q__1.i = h__[i__5].i - refsum.i; h__[i__4].r = q__1.r, h__[i__4].i = q__1.i; i__4 = k + 2 + j * h_dim1; i__5 = k + 2 + j * h_dim1; i__8 = m * v_dim1 + 2; q__2.r = refsum.r * v[i__8].r - refsum.i * v[i__8].i, q__2.i = refsum.r * v[i__8].i + refsum.i * v[i__8] .r; q__1.r = h__[i__5].r - q__2.r, q__1.i = h__[i__5].i - q__2.i; h__[i__4].r = q__1.r, h__[i__4].i = q__1.i; i__4 = k + 3 + j * h_dim1; i__5 = k + 3 + j * h_dim1; i__8 = m * v_dim1 + 3; q__2.r = refsum.r * v[i__8].r - refsum.i * v[i__8].i, q__2.i = refsum.r * v[i__8].i + refsum.i * v[i__8] .r; q__1.r = h__[i__5].r - q__2.r, q__1.i = h__[i__5].i - q__2.i; h__[i__4].r = q__1.r, h__[i__4].i = q__1.i; /* L90: */ } /* L100: */ } /* ==== Accumulate orthogonal transformations. ==== */ if (accum) { /* ==== Accumulate U. (If needed, update Z later */ /* . with an efficient matrix-matrix */ /* . multiply.) ==== */ i__6 = mtop; for (m = mbot; m >= i__6; --m) { k = krcol + (m - 1 << 1); kms = k - incol; /* Computing MAX */ i__7 = 1, i__4 = *ktop - incol; i2 = f2cmax(i__7,i__4); /* Computing MAX */ i__7 = i2, i__4 = kms - (krcol - incol) + 1; i2 = f2cmax(i__7,i__4); /* Computing MIN */ i__7 = kdu, i__4 = krcol + (mbot - 1 << 1) - incol + 5; i4 = f2cmin(i__7,i__4); i__7 = i4; for (j = i2; j <= i__7; ++j) { i__4 = m * v_dim1 + 1; i__5 = j + (kms + 1) * u_dim1; i__8 = m * v_dim1 + 2; i__9 = j + (kms + 2) * u_dim1; q__4.r = v[i__8].r * u[i__9].r - v[i__8].i * u[i__9] .i, q__4.i = v[i__8].r * u[i__9].i + v[i__8] .i * u[i__9].r; q__3.r = u[i__5].r + q__4.r, q__3.i = u[i__5].i + q__4.i; i__10 = m * v_dim1 + 3; i__11 = j + (kms + 3) * u_dim1; q__5.r = v[i__10].r * u[i__11].r - v[i__10].i * u[ i__11].i, q__5.i = v[i__10].r * u[i__11].i + v[i__10].i * u[i__11].r; q__2.r = q__3.r + q__5.r, q__2.i = q__3.i + q__5.i; q__1.r = v[i__4].r * q__2.r - v[i__4].i * q__2.i, q__1.i = v[i__4].r * q__2.i + v[i__4].i * q__2.r; refsum.r = q__1.r, refsum.i = q__1.i; i__4 = j + (kms + 1) * u_dim1; i__5 = j + (kms + 1) * u_dim1; q__1.r = u[i__5].r - refsum.r, q__1.i = u[i__5].i - refsum.i; u[i__4].r = q__1.r, u[i__4].i = q__1.i; i__4 = j + (kms + 2) * u_dim1; i__5 = j + (kms + 2) * u_dim1; r_cnjg(&q__3, &v[m * v_dim1 + 2]); q__2.r = refsum.r * q__3.r - refsum.i * q__3.i, q__2.i = refsum.r * q__3.i + refsum.i * q__3.r; q__1.r = u[i__5].r - q__2.r, q__1.i = u[i__5].i - q__2.i; u[i__4].r = q__1.r, u[i__4].i = q__1.i; i__4 = j + (kms + 3) * u_dim1; i__5 = j + (kms + 3) * u_dim1; r_cnjg(&q__3, &v[m * v_dim1 + 3]); q__2.r = refsum.r * q__3.r - refsum.i * q__3.i, q__2.i = refsum.r * q__3.i + refsum.i * q__3.r; q__1.r = u[i__5].r - q__2.r, q__1.i = u[i__5].i - q__2.i; u[i__4].r = q__1.r, u[i__4].i = q__1.i; /* L110: */ } /* L120: */ } } else if (*wantz) { /* ==== U is not accumulated, so update Z */ /* . now by multiplying by reflections */ /* . from the right. ==== */ i__6 = mtop; for (m = mbot; m >= i__6; --m) { k = krcol + (m - 1 << 1); i__7 = *ihiz; for (j = *iloz; j <= i__7; ++j) { i__4 = m * v_dim1 + 1; i__5 = j + (k + 1) * z_dim1; i__8 = m * v_dim1 + 2; i__9 = j + (k + 2) * z_dim1; q__4.r = v[i__8].r * z__[i__9].r - v[i__8].i * z__[ i__9].i, q__4.i = v[i__8].r * z__[i__9].i + v[ i__8].i * z__[i__9].r; q__3.r = z__[i__5].r + q__4.r, q__3.i = z__[i__5].i + q__4.i; i__10 = m * v_dim1 + 3; i__11 = j + (k + 3) * z_dim1; q__5.r = v[i__10].r * z__[i__11].r - v[i__10].i * z__[ i__11].i, q__5.i = v[i__10].r * z__[i__11].i + v[i__10].i * z__[i__11].r; q__2.r = q__3.r + q__5.r, q__2.i = q__3.i + q__5.i; q__1.r = v[i__4].r * q__2.r - v[i__4].i * q__2.i, q__1.i = v[i__4].r * q__2.i + v[i__4].i * q__2.r; refsum.r = q__1.r, refsum.i = q__1.i; i__4 = j + (k + 1) * z_dim1; i__5 = j + (k + 1) * z_dim1; q__1.r = z__[i__5].r - refsum.r, q__1.i = z__[i__5].i - refsum.i; z__[i__4].r = q__1.r, z__[i__4].i = q__1.i; i__4 = j + (k + 2) * z_dim1; i__5 = j + (k + 2) * z_dim1; r_cnjg(&q__3, &v[m * v_dim1 + 2]); q__2.r = refsum.r * q__3.r - refsum.i * q__3.i, q__2.i = refsum.r * q__3.i + refsum.i * q__3.r; q__1.r = z__[i__5].r - q__2.r, q__1.i = z__[i__5].i - q__2.i; z__[i__4].r = q__1.r, z__[i__4].i = q__1.i; i__4 = j + (k + 3) * z_dim1; i__5 = j + (k + 3) * z_dim1; r_cnjg(&q__3, &v[m * v_dim1 + 3]); q__2.r = refsum.r * q__3.r - refsum.i * q__3.i, q__2.i = refsum.r * q__3.i + refsum.i * q__3.r; q__1.r = z__[i__5].r - q__2.r, q__1.i = z__[i__5].i - q__2.i; z__[i__4].r = q__1.r, z__[i__4].i = q__1.i; /* L130: */ } /* L140: */ } } /* ==== End of near-the-diagonal bulge chase. ==== */ /* L145: */ } /* ==== Use U (if accumulated) to update far-from-diagonal */ /* . entries in H. If required, use U to update Z as */ /* . well. ==== */ if (accum) { if (*wantt) { jtop = 1; jbot = *n; } else { jtop = *ktop; jbot = *kbot; } /* Computing MAX */ i__3 = 1, i__6 = *ktop - incol; k1 = f2cmax(i__3,i__6); /* Computing MAX */ i__3 = 0, i__6 = ndcol - *kbot; nu = kdu - f2cmax(i__3,i__6) - k1 + 1; /* ==== Horizontal Multiply ==== */ i__3 = jbot; i__6 = *nh; for (jcol = f2cmin(ndcol,*kbot) + 1; i__6 < 0 ? jcol >= i__3 : jcol <= i__3; jcol += i__6) { /* Computing MIN */ i__7 = *nh, i__4 = jbot - jcol + 1; jlen = f2cmin(i__7,i__4); cgemm_("C", "N", &nu, &jlen, &nu, &c_b2, &u[k1 + k1 * u_dim1], ldu, &h__[incol + k1 + jcol * h_dim1], ldh, &c_b1, & wh[wh_offset], ldwh); clacpy_("ALL", &nu, &jlen, &wh[wh_offset], ldwh, &h__[incol + k1 + jcol * h_dim1], ldh); /* L150: */ } /* ==== Vertical multiply ==== */ i__6 = f2cmax(*ktop,incol) - 1; i__3 = *nv; for (jrow = jtop; i__3 < 0 ? jrow >= i__6 : jrow <= i__6; jrow += i__3) { /* Computing MIN */ i__7 = *nv, i__4 = f2cmax(*ktop,incol) - jrow; jlen = f2cmin(i__7,i__4); cgemm_("N", "N", &jlen, &nu, &nu, &c_b2, &h__[jrow + (incol + k1) * h_dim1], ldh, &u[k1 + k1 * u_dim1], ldu, &c_b1, &wv[wv_offset], ldwv); clacpy_("ALL", &jlen, &nu, &wv[wv_offset], ldwv, &h__[jrow + ( incol + k1) * h_dim1], ldh); /* L160: */ } /* ==== Z multiply (also vertical) ==== */ if (*wantz) { i__3 = *ihiz; i__6 = *nv; for (jrow = *iloz; i__6 < 0 ? jrow >= i__3 : jrow <= i__3; jrow += i__6) { /* Computing MIN */ i__7 = *nv, i__4 = *ihiz - jrow + 1; jlen = f2cmin(i__7,i__4); cgemm_("N", "N", &jlen, &nu, &nu, &c_b2, &z__[jrow + ( incol + k1) * z_dim1], ldz, &u[k1 + k1 * u_dim1], ldu, &c_b1, &wv[wv_offset], ldwv); clacpy_("ALL", &jlen, &nu, &wv[wv_offset], ldwv, &z__[ jrow + (incol + k1) * z_dim1], ldz); /* L170: */ } } } /* L180: */ } /* ==== End of CLAQR5 ==== */ return 0; } /* claqr5_ */
the_stack_data/8739.c
/* / _____) _ | | ( (____ _____ ____ _| |_ _____ ____| |__ \____ \| ___ | (_ _) ___ |/ ___) _ \ _____) ) ____| | | || |_| ____( (___| | | | (______/|_____)_|_|_| \__)_____)\____)_| |_| (C)2019 Semtech Description: LoRa concentrator HAL auxiliary functions License: Revised BSD License, see LICENSE.TXT file include in the project */ /* -------------------------------------------------------------------------- */ /* --- DEPENDANCIES --------------------------------------------------------- */ /* fix an issue between POSIX and C99 */ #if __STDC_VERSION__ >= 199901L #define _XOPEN_SOURCE 600 #else #define _XOPEN_SOURCE 500 #endif #include <stdio.h> /* printf fprintf */ #include <time.h> /* clock_nanosleep */ /* -------------------------------------------------------------------------- */ /* --- PRIVATE MACROS ------------------------------------------------------- */ #if DEBUG_AUX == 1 #define DEBUG_MSG(str) fprintf(stderr, str) #define DEBUG_PRINTF(fmt, args...) fprintf(stderr,"%s:%d: "fmt, __FUNCTION__, __LINE__, args) #else #define DEBUG_MSG(str) #define DEBUG_PRINTF(fmt, args...) #endif /* -------------------------------------------------------------------------- */ /* --- PUBLIC FUNCTIONS DEFINITION ------------------------------------------ */ /* This implementation is POSIX-pecific and require a fix to be compatible with C99 */ void wait_ms(unsigned long a) { struct timespec dly; struct timespec rem; dly.tv_sec = a / 1000; dly.tv_nsec = ((long)a % 1000) * 1000000; DEBUG_PRINTF("NOTE dly: %ld sec %ld ns\n", dly.tv_sec, dly.tv_nsec); if((dly.tv_sec > 0) || ((dly.tv_sec == 0) && (dly.tv_nsec > 100000))) { clock_nanosleep(CLOCK_MONOTONIC, 0, &dly, &rem); DEBUG_PRINTF("NOTE remain: %ld sec %ld ns\n", rem.tv_sec, rem.tv_nsec); } return; } /* --- EOF ------------------------------------------------------------------ */
the_stack_data/62637145.c
extern void __VERIFIER_error() __attribute__ ((__noreturn__)); void __VERIFIER_assert(int cond) { if(!(cond)) { ERROR: __VERIFIER_error(); } } #define N 200 int main( ) { int A[N]; int i; for (i = 0; i < N/2 ; i++ ) { A[i] = A[N-i-1]; } int x; for ( x = 0 ; x < N/2 ; x++ ) { __VERIFIER_assert( A[x] == A[N - x - 1] ); } return 0; }
the_stack_data/77178.c
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> int main(void) { printf("Hi welcome to Tock. This test makes sure that a greater than 64 byte message can be printed.\n"); printf("And a short message.\n"); return 0; }
the_stack_data/220456197.c
// REQUIRES: x86-registered-target // Make sure opt-bisect works through both pass managers // // RUN: %clang_cc1 -triple x86_64-linux-gnu -O1 %s -mllvm -opt-bisect-limit=-1 -emit-obj -o /dev/null 2>&1 | FileCheck %s // CHECK: BISECT: running pass (1) // CHECK-NOT: BISECT: running pass (1) // Make sure that legacy pass manager is running // CHECK: Instruction Selection int func(int a) { return a; }
the_stack_data/23574876.c
#include <stdio.h> int func(int n) { return n == 0 ? 1 : func(n - 1) - n; } int main() { int a; printf("Digite um valor inteiro: "); scanf("%d", &a); printf("%d\n", func(a)); int n = a; int temp = 1; while (1) { temp -= n; n--; if (n == 0) break; } printf("%d\n", temp); } //https://pt.stackoverflow.com/q/347752/101
the_stack_data/210220.c
/* My dwmstatus bar - Network monitoring - colors + should just display "Network down" in red if not connected - Memory usage - colors - CPU usage - colors - CPU temperatures - colors - Battery indicator - colors - Date and time - Automatically detect time zone */ #define _DEFAULT_SOURCE #include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <stdarg.h> #include <string.h> #include <strings.h> #include <err.h> #include <errno.h> #include <time.h> #include <ifaddrs.h> #include <fcntl.h> #include <sys/time.h> #include <sys/types.h> #include <sys/wait.h> #include <sys/ioctl.h> #include <sys/statvfs.h> #include <linux/wireless.h> #include <X11/Xlib.h> static Display *dpy; /* C string utilities */ char * smprintf(char *fmt, ...) { va_list fmtargs; char *ret; int len; va_start(fmtargs, fmt); len = vsnprintf(NULL, 0, fmt, fmtargs); va_end(fmtargs); ret = malloc(++len); if (ret == NULL) { warn("malloc failed in smprintf"); exit(1); } va_start(fmtargs, fmt); vsnprintf(ret, len, fmt, fmtargs); va_end(fmtargs); return ret; } int readvaluesfromfile(char *fn, char *fmt, ...) { va_list fmtargs; FILE* fp = NULL; int rval = 1; if ((fp = fopen(fn, "r"))) { va_start(fmtargs, fmt); vfscanf(fp, fmt, fmtargs); va_end(fmtargs); fclose(fp); rval = 0; } else { warn("Error opening %s", fn); } return rval; } /* Network info */ #define WIFICARD "wlp1s0" //#define WIREDCARD "" #define NETDEV_FILE "/proc/net/dev" #define WIFI_OPERSTATE_FILE "/sys/class/net/"WIFICARD"/operstate" #define WIRED_OPERSTATE_FILE "/sys/class/net/"WIFICARD"/operstate" #define WIRELESS_FILE "/proc/net/wireless" int parsenetdev(unsigned long long *receivedabs, unsigned long long *sentabs) { const int bufsize = 255; char buf[bufsize]; char *datastart; FILE *fp = NULL; int rval = 1; unsigned long long receivedacc, sentacc; if ((fp = fopen(NETDEV_FILE, "r"))) { // Ignore the first two lines of the file fgets(buf, bufsize, fp); fgets(buf, bufsize, fp); while (fgets(buf, bufsize, fp)) { if ((datastart = strstr(buf, "lo:")) == NULL) { datastart = strstr(buf, ":"); // With thanks to the conky project at http://conky.sourceforge.net/ sscanf(datastart + 1, "%llu %*d %*d %*d %*d %*d %*d %*d %llu", &receivedacc, &sentacc); *receivedabs += receivedacc; *sentabs += sentacc; } } fclose(fp); rval = 0; } else { warn("Error opening "NETDEV_FILE); } return rval; } int getbandwidth(double *downbw, double *upbw) { static unsigned long long rec, sent; unsigned long long newrec, newsent; newrec = newsent = 0; int rval = 1; if (parsenetdev(&newrec, &newsent)) return rval; *downbw = (newrec - rec) / 1024.0; *upbw = (newsent - sent) / 1024.0; rec = newrec; sent = newsent; rval = 0; return rval; } int getwifistrength(int *strength) { char buf[255]; char *datastart; FILE *fp = NULL; int rval = 1; if ((fp = fopen(WIRELESS_FILE, "r"))) { fgets(buf, sizeof(buf), fp); fgets(buf, sizeof(buf), fp); fgets(buf, sizeof(buf), fp); fclose(fp); } else { warn("Error opening "WIRELESS_FILE); return rval; } datastart = strstr(buf, WIFICARD":"); if (datastart != NULL) { datastart = strstr(buf, ":"); sscanf(datastart + 1, " %*d %d %*d %*d %*d %*d %*d %*d %*d %*d", strength); rval = 0; } return rval; } int getwifiessid(char *id) { int sockfd = socket(AF_INET, SOCK_DGRAM, 0); struct iwreq wreq; int rval = 1; memset(&wreq, 0, sizeof(struct iwreq)); wreq.u.essid.length = IW_ESSID_MAX_SIZE+1; sprintf(wreq.ifr_name, WIFICARD); if (sockfd == -1) { warn("Cannot open socket for interface: %s", WIFICARD); return rval; } wreq.u.essid.pointer = id; if (ioctl(sockfd,SIOCGIWESSID, &wreq) == -1) { warn("Get ESSID ioctl failed for interface %s", WIFICARD); } else { rval = 0; } close(sockfd); return rval; } char * bwstr(double bw) { if (bw > 1024.0) { bw /= 1024.0; return smprintf("%.1fmbps", bw); } else { return smprintf("%.0fkbps", bw); } } char * getconnection(void) { char status[5]; int eth0, wifi; char essid[IW_ESSID_MAX_SIZE+1]; char *conntype; int strength; double downbw, upbw; char *downstr, *upstr; char *connection; if (readvaluesfromfile(WIRED_OPERSTATE_FILE, "%s\n", status)) return smprintf(""); eth0 = !strcmp(status, "up"); if (readvaluesfromfile(WIFI_OPERSTATE_FILE, "%s\n", status)) return smprintf(""); wifi = !strcmp(status, "up"); if (wifi) { if (getwifiessid(essid)) { warn("Failed to obtain WiFi ESSID"); sprintf(essid, "N/A"); } if (getwifistrength(&strength)) { warn("Failed to obtain WiFi strength"); } } if (eth0) { if (wifi) { // conntype = smprintf("  %s  %d%%"); // conntype = smprintf("⚼"); conntype = smprintf("📶 %d%%", strength); } else { // conntype = smprintf("⚼"); conntype = smprintf("📶 %d%%", strength); } } else if (wifi) { // conntype = smprintf(" %s  %d%%", essid, strength); conntype = smprintf("📶 %d%%", strength); } else { return smprintf("offline"); } if(getbandwidth(&downbw, &upbw)) { warn("Failed to obtain bandwidth"); downstr = "---- KiB/s"; upstr = "---- KiB/s"; } else { downstr = bwstr(downbw); upstr = bwstr(upbw); } connection = smprintf("%s ▼%s ▲%s", conntype, downstr, upstr); free(upstr); free(downstr); free(conntype); return connection; } /* CPU info */ #define STAT_FILE "/proc/stat" #define TICS_EDGE 20 int num_cpus; typedef struct CT_t { unsigned long long u, n, s, i, w, x, y, z; unsigned long long tot; unsigned long long edge; } CT_t; void getnumcpus(void) { num_cpus = sysconf(_SC_NPROCESSORS_ONLN); if (num_cpus<1) /* SPARC glibc is buggy */ num_cpus=1; } char * getcpuload(void) { static CT_t tics_prv; static CT_t tics_cur; static CT_t tics_frme; float scale; double avgs[3]; float pct_tot; if (getloadavg(avgs, 3) < 0) { warn("cpuload call to getloadavg failed"); return smprintf(""); } memcpy(&tics_prv, &tics_cur, sizeof(CT_t)); if (readvaluesfromfile(STAT_FILE, "cpu %llu %llu %llu %llu %llu %llu %llu %llu", &tics_cur.u, &tics_cur.n, &tics_cur.s, &tics_cur.i, &tics_cur.w, &tics_cur.x, &tics_cur.y, &tics_cur.z)) return smprintf(""); tics_cur.tot = tics_cur.u + tics_cur.s + tics_cur.n + tics_cur.i + tics_cur.w + tics_cur.x + tics_cur.y + tics_cur.z; tics_cur.edge = ((tics_cur.tot - tics_prv.tot) / num_cpus) / (100 / TICS_EDGE); tics_frme.u = tics_cur.u - tics_prv.u; tics_frme.s = tics_cur.s - tics_prv.s; tics_frme.n = tics_cur.n - tics_prv.n; tics_frme.i = tics_cur.i - tics_prv.i; tics_frme.w = tics_cur.w - tics_prv.w; tics_frme.x = tics_cur.x - tics_prv.x; tics_frme.y = tics_cur.y - tics_prv.y; tics_frme.z = tics_cur.z - tics_prv.z; tics_frme.tot = tics_frme.u + tics_frme.s + tics_frme.n + tics_frme.i + tics_frme.w + tics_frme.x + tics_frme.y + tics_frme.z; if (tics_frme.tot < tics_cur.edge) { tics_frme.u = tics_frme.s = tics_frme.n = tics_frme.i = tics_frme.w = tics_frme.x = tics_frme.y = tics_frme.z = 0; } if (1 > tics_frme.tot) { tics_frme.i = tics_frme.tot = 1; } scale = 100.0 / (float)tics_frme.tot; pct_tot = (float)(tics_frme.u + tics_frme.n + tics_frme.s) * scale; return smprintf("🏽 %.0f%%(%.2f|%.2f|%.2f)", pct_tot,avgs[0], avgs[1], avgs[2]); } /* Memory info */ #define MEMINFO_FILE "/proc/meminfo" typedef struct mem_table_struct { const char *name; /* memory type name */ unsigned long *slot; /* slot in return struct */ } mem_table_struct; int compare_mem_table_structs(const void *a, const void *b) { return strcmp(((const mem_table_struct*)a)->name,((const mem_table_struct*)b)->name); } #define BAD_OPEN_MESSAGE \ "Error: /proc must be mounted\n" \ " To mount /proc at boot you need an /etc/fstab line like:\n" \ " proc /proc proc defaults\n" \ " In the meantime, run \"mount proc /proc -t proc\"\n" #define FILE_TO_BUF(filename, fd) do{ \ static int local_n; \ if (fd == -1 && (fd = open(filename, O_RDONLY)) == -1) { \ fputs(BAD_OPEN_MESSAGE, stderr); \ fflush(NULL); \ _exit(102); \ } \ lseek(fd, 0L, SEEK_SET); \ if ((local_n = read(fd, buf, sizeof buf - 1)) < 0) { \ perror(filename); \ fflush(NULL); \ _exit(103); \ } \ buf[local_n] = '\0'; \ }while(0) char * getmeminfo(void) { static int meminfo_fd = -1; static char buf[8192]; char namebuf[32]; /* big enough to hold any row name */ mem_table_struct findme = { namebuf, NULL }; mem_table_struct *found; char *head; char *tail; static unsigned long kb_main_buffers; static unsigned long kb_page_cache; static unsigned long kb_main_free; static unsigned long kb_main_total; static unsigned long kb_slab_reclaimable; static unsigned long kb_main_shared; static unsigned long kb_swap_cached; static unsigned long kb_swap_free; static unsigned long kb_swap_total; static const mem_table_struct mem_table[] = { {"Buffers", &kb_main_buffers}, {"Cached", &kb_page_cache}, {"MemFree", &kb_main_free}, {"MemTotal", &kb_main_total}, {"SReclaimable", &kb_slab_reclaimable}, {"Shmem", &kb_main_shared}, {"SwapCached", &kb_swap_cached}, {"SwapFree", &kb_swap_free}, {"SwapTotal", &kb_swap_total}, }; const int mem_table_count = sizeof(mem_table)/sizeof(mem_table_struct); unsigned long kb_main_cached, kb_swap_used, kb_main_used; float gb_main_used; /* , gb_main_total; */ float gb_swap_used; /* , gb_swap_total; */ FILE_TO_BUF(MEMINFO_FILE,meminfo_fd); head = buf; for(;;) { tail = strchr(head, ':'); if(!tail) break; *tail = '\0'; if(strlen(head) >= sizeof(namebuf)) { head = tail+1; goto nextline; } strcpy(namebuf,head); found = bsearch(&findme, mem_table, mem_table_count, sizeof(mem_table_struct), compare_mem_table_structs ); head = tail+1; if(!found) goto nextline; *(found->slot) = (unsigned long)strtoull(head,&tail,10); nextline: tail = strchr(head, '\n'); if(!tail) break; head = tail+1; } kb_main_cached = kb_page_cache + kb_slab_reclaimable; kb_swap_used = kb_swap_total - kb_swap_free - kb_swap_cached; kb_main_used = kb_main_total - kb_main_free - kb_main_cached - kb_main_buffers; gb_main_used = (float)kb_main_used / 1024 / 1024; /* gb_main_total = (float)kb_main_total / 1024 / 1024; */ gb_swap_used = (float)kb_swap_used / 1024 / 1024; /* gb_swap_total = (float)kb_swap_total / 1024 / 1024; */ return smprintf("🧠 %1.1f/%1.1fGb", gb_main_used, gb_swap_used); } /* Disk info */ /* char * diskfree(const char *mountpoint) { struct statvfs fs; float freespace; if (statvfs(mountpoint, &fs) < 0) { warn("Could not get %s filesystem info", mountpoint); return smprintf(""); } freespace = (float)fs.f_bsize * (float)fs.f_bfree / 1024 / 1024 / 1024; if (freespace < 100) return smprintf("%4.1f GiB", freespace); else return smprintf("%.0f GiB", freespace); } char * getdiskusage(void) { char *root = diskfree("/"); char *home = diskfree("/home"); char *s = smprintf(" %s  %s", root, home); free(root); free(home); return s; } */ /* Temperature info*/ #define TEMP_INPUT "/sys/class/hwmon/hwmon0/temp1_input" #define TEMP_CRIT "/sys/class/hwmon/hwmon0/temp1_crit" char * gettemperature(void) { long temp, tempc; if (readvaluesfromfile(TEMP_INPUT, "%ld\n", &temp)) return smprintf(""); if (readvaluesfromfile(TEMP_CRIT, "%ld\n", &tempc)) return smprintf(""); return smprintf("🌡 %ld°C", temp / 1000); } /* Battery info */ #define BATT_NOW "/sys/class/power_supply/BAT0/energy_now" #define BATT_FULL "/sys/class/power_supply/BAT0/energy_full" #define BATT_STATUS "/sys/class/power_supply/BAT0/status" #define POW_NOW "/sys/class/power_supply/BAT0/power_now" #define GLYPH_UNKWN "?" #define GLYPH_FULL "🔌 " #define GLYPH_CHRG "🗲 " #define GLYPH_DCHRG_0 "🔋 " #define GLYPH_DCHRG_1 "🔋 " #define GLYPH_DCHRG_2 "🔋 " #define GLYPH_DCHRG_3 "🔋 " #define GLYPH_DCHRG_4 "🔋 " char * getbattery() { long battnow, battfull = 0; long pow, pct, energy = -1; long mm, hh; char status[12]; char *s = GLYPH_UNKWN; if (readvaluesfromfile(BATT_NOW, "%ld\n", &battnow)) return smprintf(""); if (readvaluesfromfile(BATT_FULL, "%ld\n", &battfull)) return smprintf(""); if (readvaluesfromfile(BATT_STATUS, "%s\n", status)) return smprintf(""); if (readvaluesfromfile(POW_NOW, "%ld\n", &pow)) return smprintf(""); pct = 100*battnow/battfull; if (strcmp(status,"Charging") == 0) { s = GLYPH_CHRG; energy = battfull - battnow; } else if (strcmp(status,"Discharging") == 0) { if (pct < 20) s = GLYPH_DCHRG_0; else if (pct < 40) s = GLYPH_DCHRG_1; else if (pct < 60) s = GLYPH_DCHRG_2; else if (pct < 85) s = GLYPH_DCHRG_3; else s = GLYPH_DCHRG_4; energy = battnow; } else if (strcmp(status,"Full") == 0) s = GLYPH_FULL; if ( energy < 0 || pow <= 0) { return smprintf("%s%3ld%%", s,pct); } else { hh = energy / pow; mm = (energy % pow) * 60 / pow; return smprintf("%s%ld%%(%ld:%ld)", s,pct,hh,mm); } } /* Time info */ char * mktimes(char *fmt) { char buf[129]; time_t tim; struct tm *timtm; memset(buf, 0, sizeof(buf)); tim = time(NULL); timtm = localtime(&tim); if (timtm == NULL) { warn("Error when calling localtime"); return smprintf(""); } if (!strftime(buf, sizeof(buf)-1, fmt, timtm)) { warn("strftime == 0"); return smprintf(""); } return smprintf("%s", buf); } /* char * mktimestz(char *fmt, char *tzname) { setenv("TZ", tzname, 1); char *buf = mktimes(fmt); unsetenv("TZ"); return buf; } */ /* Main function */ void setstatus(char *str) { XStoreName(dpy, DefaultRootWindow(dpy), str); XSync(dpy, False); } int main(void) { char *status; char *conn; char *cpu; char *mem; // char *disk; char *temp; char *batt; char *tmloc; int counter = 0; int conn_interval = 1; int cpu_interval = 2; int mem_interval = 2; // int disk_interval = 30; int temp_interval = 30; int batt_interval = 30; int tmloc_interval = 1; int max_interval = 30; /* Run functions that have to be run only once */ getnumcpus(); if (!(dpy = XOpenDisplay(NULL))) { fprintf(stderr, "dwmstatus: cannot open display.\n"); return 1; } /* Regular updates */ for (;;sleep(1)) { if (counter % conn_interval == 0) conn = getconnection(); if (counter % cpu_interval == 0) cpu = getcpuload(); if (counter % mem_interval == 0) mem = getmeminfo(); // if (counter % disk_interval == 0) disk = getdiskusage(); if (counter % temp_interval == 0) temp = gettemperature(); if (counter % batt_interval == 0) batt = getbattery(); if (counter % tmloc_interval == 0) tmloc = mktimes("📆 %a,%d/%m/%Y ⌛ %H:%M"); // if (counter % tmloc_interval == 0) tmloc = mktimes("%Y-%m-%D %H:%M:%S %Z"); /* status = smprintf(" %s | %s | %s | %s | %s | %s | %s", conn, cpu, mem, disk, temp, batt, tmloc); setstatus(status); */ status = smprintf("%s %s %s %s %s %s ", conn, cpu, mem, temp, batt, tmloc); setstatus(status); counter = (counter + 1) % max_interval; if (counter % conn_interval == 0) free(conn); if (counter % cpu_interval == 0) free(cpu); if (counter % mem_interval == 0) free(mem); // if (counter % disk_interval == 0) free(disk); if (counter % temp_interval == 0) free(temp); if (counter % batt_interval == 0) free(batt); if (counter % tmloc_interval == 0) free(tmloc); free(status); } XCloseDisplay(dpy); return 0; }
the_stack_data/167330529.c
//Contributors //G. Poppe //Meredith Quail #include <stdlib.h> #include <ctype.h> #include <string.h> #include <time.h> #include <stdio.h> #include <stdbool.h> //void RollArray(int *arr);//LA char *randomString(char *p); void mQhelpPrompt(void); //mquail void mQhelpMenu(void); //mquail void mQcontinue(void); //mquail int mQuserInput(void); //mquail int mQparser(void); //mquail char uInput[100]; //mquail void printIntroduction(void); // Manuel Castaneda void printRules(int rollsPerTurn, int pointsToLoose); // Manuel Castaneda double averageM(int rolls[], int numberOfRolls); // Manuel Castaneda double sumM(double sums[], int maxSums); // Manuel Castaneda void printRollResults(int rolls[], int numberOfRolls, int isUser); // Manuel Castaneda void play(void);//josue // Talise void printMessage(int msg[]); void decodeMessage(char alphabet[], int codedMessage[], int *totalGuesses, int *wrong); void userFate(int x); //Monika void monikawelcome(char name[]); void monikacase1(char yellowdecision[]); void monikacase2(char reddecision[]); void monikacase3(char greenchoice[]); //Monika int main(int argc, char *argv[]) { int x,y,z,i,h,g,k,choice=0; char name[256]; int boxNum=0; int sum = 0; int number; float average; srand(time(NULL)); printf("Please enter your name: "); //Input any number of array inputs scanf("%s",name); printf("Hello %s welcome to the rpgGame!\n",name); while(choice != 99) { puts("You find yourself in a dark room and you are not sure how you got here."); puts("As you look around you see the room has 40 doors, each labeled with a number. You are not sure how such a small room can have 40 doors, sooo magic..."); puts("The room starts filling with water and you must choose a door to open or you will likely drown. you may quit anytime by selecting option 99"); puts("What door do you choose?"); scanf("%d",&choice); switch(choice) { case 1: { int counter = 0; while(choice != 99) { puts("You open the door and found a lot of people jumping around"); puts("You are almost certain that you have found a hidden civilization"); puts("At this point it seems like you have three options"); puts("Every option you choose has a hidden value related to it.."); puts("Choose wisely to earn enough points to win this game!!"); puts("1. Talk to the poeple and figure out why is everyone jumping!!"); puts("2. Walk further down and explore the place"); puts("3. Go back into the door you came from and drown"); scanf("%d",&choice); if (choice == 1) { puts("You talk to one of the elders and find out that a monster has threatened the city and everyone is panicking"); counter++; counter++; puts("The monster is a big red dragon that came upon the city to burn its lands"); printf("Once again.. You have 3 options.\n1. You can fight with them\n2. You can run away\n3. You can have a random option be chosen for you.\n"); scanf("%d",&choice); //switch statement switch(choice) { case 1: { puts("GREAT!! You chose to fight!"); counter++; counter++; counter++; break; } case 2: { puts("WOAH! You chose to be a coward! You do not deserve to play anymore.. GG"); counter--; break; } case 3: { //random choice = rand()%2 + 1; if (choice == 1) { puts("GREAT!! You chose to fight!"); counter++; counter++; counter++; break; } if (choice == 2) { puts("WOAH! You chose to be a coward! You do not deserve to play anymore.. GG"); counter--; break; } break; } } break; } else if (choice == 2) { puts("You walk further down the street and you get amazed by how beautiful the city is"); puts("To be continued..."); counter++; break; } else if (choice == 3) { puts("You opened the door and the water killed you"); counter++; break; } else { puts("Wrong choice!!!"); } } printf("Counter = %d. \n \n", counter); break; } case 2: { while(choice != 99) { puts("you open the door and find ........ \n"); puts("Watch out, look behind you, A Meeseeks is coming towarsds you.\n"); puts("Hi I'm Mr.Meeseeks look at me, waving hands around.\n"); puts("Ask him for a request and he will complete it and disapear.\n"); puts("What type of request would you want to make?\n"); puts("1st choice is Meeseeks can take you to Blips\n"); puts("2nd choice is you can join Morty and go on an Adventure\n"); puts("3rd choice is go back through the door you came from\n"); scanf("%d",&choice); if(choice == 1) { puts("Hi I'm Mr Meeseeks look at me.\n"); puts("Okay are you ready to go to Blips?\n"); puts("First you need Fleurbos.\n"); puts("Please enter how many games you want to play.\n"); scanf("%d", &x); puts("Enter the amount of Fleurbos that you will need for that game, one by one\n"); for(y = 0; y < x; ++y) { scanf("%d", &number); sum = sum + number; } average = sum / y; printf("You will need an average of %.2f Fleurbos, for your first time at Blips\n",average); return 0; } if(choice == 2) { int a,b,c,d; printf("Hey its Morty, hurry get in, Rick isn't watching, let go on a adventure\n"); printf("How old are you by the way?\n"); scanf("%d",&c); // int z = (rand()%10)+1; d = c; for(a = 1; a <= c; a++) { for(b = 1; b < d; b++) printf(" "); d--; for(b = 1; b <= 2 * a -1; b++) printf("*"); printf("\n"); } puts(" \n "); puts("Woooaaahhh get ready for Hyper Drive \n"); return 0; } if(choice == 3) { puts("You have exited that room"); } else { puts("Incorrect input, please selecte from the following choices, 1, 2, or 3.\n"); } return 0; } break; } case 3: { while(choice != 99) { int choice2; puts("you open the door and find a mysterious man saying: 'Wendy, darling, Light of my Life! I'm not gonna hurt ya \n"); puts("He looks at you menancingly and starts to run to you with a knife, there are multiple doors behind you and the door you came from. \n which door do you pick? \n you may quit anytime by selecting option:99"); scanf("%d",&choice); switch(choice) { // case 1: // { // char a; // int DieArr[6]; // for (i=0;i<6;i++) // { // DieArr[i] = 0; // } // puts("You stumble into a room, and a skeleton behind a counter and holds a die"); // puts("He asks you with a hollow voice, Hi would you like to roll the dice? [Y]es or [N]o"); // scanf("%c", &a); // if(a=='y') // { // RollArray(DieArr); // for (i=0;i<6;i++) // { // printf("%d = %d\n", i+1 , DieArr); // } // } // break; // } case 2: { while(choice != 99) { } break; } } } break; } case 4: { while(choice != 99) { puts("My room no 4. you open the door and find ........"); scanf("%d",&choice); } break; } case 5: { while(choice != 99) { puts("you open the door slowly, you hear a click in the distance:"); puts("Do you close the door or open it fast? Type 1 for open and 2 for close."); scanf("%d",&choice); switch(choice) { case 1: { puts("you get hit with an arrow in the knee!"); break; } case 2: { puts("you hear an arrow hit the door"); break; } } } break; } case 6: { while(choice != 99) { FILE *wptr; wptr = fopen(argv[2], "w"); int totalGuesses = 0; int wrongGuesses = 0; int *totalPtr = &totalGuesses; int *wrongPtr = &wrongGuesses; char alphabet[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'z', 'y', 'z', '\0'}; int codedMessage[10] = {8, 5, 12, 12, 15, 23, 15, 18, 12, 4}; char message[] = "Hello World"; puts("You open the door and walk inside the room."); puts("The door locks, and the only way out is to decode a message."); printMessage(codedMessage); decodeMessage(alphabet, codedMessage, totalPtr, wrongPtr); fprintf(wptr, "Total Guesses: %d \nWrong Guesses: %d \nDecoded Message: %s \n", totalGuesses, wrongGuesses, message); x = (rand() % (3 + 1 - 1) + 1); userFate(x); for(i = 0; name[i] != '\0'; i++) { name[i] = toupper(name[i]); } printf("That's all, %s \n", name); scanf("%d", &choice); } break; } case 7: { while(choice != 99) { int rollDie; rollDie = rand()%9; puts("\n You open the door and all the water drains"); puts("In front of you is another door, you look closely at writing on the wall and it says"); puts("In order to open this doo you need to roll a random number 1-10"); puts("If you roll the correct number the door will open"); puts("What number will you choose? (99 will exit the program)"); scanf("%d", &choice); if(choice == rollDie) { puts("Congrats the door is open"); } else { puts("You lose"); puts("Returning back to the main menu \n\n"); break; } } break; } case 8: { // Declare Variables char *userEntry[256]; char uYes[5] = "yes"; char uNo[4] = "no"; int gameLevel = 1; bool kitchen1Clear = false; bool lightsOn = false; while(choice != 99) { // Opening Narration puts("-------------------------------------------------------------------------------------------------------"); puts("\nTwisting the knob and bracing your shoulder, you push against the heavy door with a strained grunt.\n"); puts("It slams shut just as you weave your way through. The door is now sealed tightly behind you.\n"); puts("A familiar grumble roils from deep within your gut."); puts("Before you conquer that hefty door again, you'll have to vanquish the hunger beast.\n"); puts("Do you want to take a look around? (Type 'yes' or 'no') : \n"); scanf("%s", *userEntry); // Type yes (replace later with a better method) if (strstr(*userEntry, uYes) != NULL) { puts("\nPatting your stomach in agreement, you decide that going on incredible adventures through other mysterious doors can wait.\n"); puts("For now, you have to look around for some food. Eat first, think later.\n"); mQcontinue(); } // Type no else if (strstr(*userEntry, uNo) != NULL) { puts("\n...no?"); puts("\nNO?????"); printf("\noOOOooo OOO oo lookit me, I'm a silly little adventurer named %s! I dOnT nEeD To eAt!! i'M sO StROnG aN d ClEvEr AnD I'm nEvEr HuNgRYyyyYYH haAHAa heeHEEhoO\n\n", name); puts("You're about as dumb as a bowl of oats. Do you think you can open a heavily sealed door like this?\n"); puts("When you're so hungry, you couldn't open a door twice?!\n"); puts("Well, too bad - that door isn't budging, and you're looking around for some sustenance, whether you like it or not! Your stomach isn't giving you any other options here!\n"); mQcontinue(); } // Level 1 : Kitchen if (gameLevel == 1) { mQhelpPrompt(); mQhelpMenu(); mQcontinue(); if (kitchen1Clear == false) { // Lights Off if (lightsOn == false) { puts("----------------------------------------------------------------------------------------------------------------"); puts("\nYou were so preoccupied with the door and your appetite that you hadn't noticed the room is completely dark.\n"); puts("Fishing your phone out of your pocket, you swipe a few times to activate its flashlight. Suppose that will have to do, until you can get the lights working.\n"); puts("You tentatively stretch a hand to the wall next to the door to check for a light switch - no dice.\n"); puts("Sweeping the room with your cellphone light, you notice the stainless steel glint of a FRIDGE and FREEZER wedged into the right corner.\n"); puts("You make out the red glow of a STOVE clock, blinking 00:00 steadily against the darkness.\n"); //Parser Loop begins while (mQuserInput() && mQparser()); } // Lights On else if (lightsOn == true) { puts("The stainless steel glint of a REFRIDGERATOR and FREEZER glints from the right corner.\n"); puts("To the left of the freezer is an old combination STOVE and OVEN.\n"); puts("A dirty SINK full of dishes connects to the counter space left of it, with a MICROWAVE on the counter space nearby."); puts("Some CABINETS lay half-open on rusted hinges above the sink space.\n"); break; } //break? } } } break; } //case 8 ends case 9: { while(choice != 99) { puts("cl"); puts("you open the door and find ........"); scanf("%d",&choice); } break; } case 10: { while(choice != 99) { int i, j, n=10; for(i=n/2; i<=n; i+=2) { for(j=1; j<n-i; j+=2) { printf(" "); } for(j=1; j<=i; j++) { printf("*"); } for(j=1; j<=n-i; j++) { printf(" "); } for(j=1; j<=i; j++) { printf("*"); } printf("\n"); } for(i=n; i>=1; i--) { for(j=i; j<n; j++) { printf(" "); } for(j=1; j<=(i*2)-1; j++) { printf("*"); } printf("\n"); } puts("you open the door and find ........"); scanf("%d",&choice); } break; } case 11: { while(choice != 99) { puts("you open the door and find ........"); puts("3 closed doors"); printf("The first door is made of rock with cracks that seem to have orange lava flowing from them and fire comming out from the edges"); printf("The second door seems to be an ornage rock door with vines covering it and light bleeding from the edges with mist flowing from underneath"); printf("The final door seems to be an ordinary old wooden door of a broom closet"); printf("Which door will you choose?"); printf("1 for the fire door"); printf("2 for the mysterious glowing door"); printf("3 for the broom closet"); scanf("%d",&choice); } break; } case 12: { while(choice != 99) { } break; } case 13: { // Norville Amao while(choice != 99) { char name[20]; int race = 5; puts("\nCHARACTER CREATION"); puts("Enter your name:"); scanf("%s",name); while(race == 5){ puts("\nChoose your race"); puts("1 - human"); puts("2 - elf"); puts("3 - ilvyr"); puts("4 - ferren"); puts("5 - race information"); scanf("%d",&race); if(race == 5){ puts("\nTHE RACES OF HABREN"); puts("HUMANS"); puts("Known as Goddess's favorite. The most prosperous of all the races."); puts("ELVES"); puts("The racial offpsring of ilvyrs and humans. They often live underground, opposite of their ilvyr ancestors."); puts("ILVYRS"); puts("A race of fallen angels who have succumbed to the sin of pride. Identified by their pointed ears and white bird-like wings."); puts("FERRENS"); puts("Often mistaken as humans. They are identified by their towering heights, especially those of their women."); } } puts("\nType 99 to quit"); scanf("%d",&choice); } break; } case 14: { while(choice != 99) { } break; } case 15: {//Monika while(choice != 99) { char yellowdecision[2]; char reddecision[2]; char greenchoice[2]; srand(time(NULL)); monikawelcome(name); puts("You enter door 15 but you end up outside and see three colored paths\n"); puts("Choose a path:\n 1 (yellow)\n 2 (red)\n 3 (green)\n"); scanf("%d", &choice); switch(choice) { case 1: { monikacase1(yellowdecision); break; } case 2: { monikacase2(reddecision); break; } case 3: { monikacase3(greenchoice); break; } } } } case 16: { while(choice != 99) { puts("The room is dark and cold"); puts("You look at the empty room with empty Shelves.."); puts("You think to yourself, there's nothing of value in here.."); puts("What should you do?"); puts("1. Move and advance to the next room"); puts("2. Examine the room a little more carefully"); puts("3. Go back to the last room"); scanf("%d", &choice); if(choice == 1) { puts("You go towards the door, but the handle is locked.."); puts("*Maybe you should examine the room.."); break; } else if(choice == 2) { puts("You look at the very top of the shelf and find a old brass key"); break; } else if(choice = 3) { puts("You back out slowly towards the previous room... but it's locked!"); } else { puts("Try again"); } } break; } case 17: { while(choice != 99) { puts("you open the door and find ........"); scanf("%d",&choice); } break; } case 18: { while(choice != 99) { puts("you open the door and find ...."); printf("A expansive candlelit cavern; in the center is a wizen, old wizard shuffling cards at a card table."); scanf("%d",&choice); } break; } case 19: { while(choice != 99) { puts("you open the door and find ........"); puts("a computer science goblin student !"); scanf("%d",&choice); } break; } case 20: { while(choice != 99) { puts("There is a noise in the distance but you can't quite make out what it is"); puts("1.Do you open the door that us 50 feet in front of you or.."); puts("2. Do you simply stand there and see if the noise gets clearer on it's own?"); puts("3. You see an old, oriental gentleman in the corner which is lit up by a torch. Do you approach him?"); scanf("%d",&choice); switch(choice) { case 1: { puts("You open the door and actually find out the noise is just Naked in the Rain by the Red Hot Chili Peppers playing on a radio"); break; } case 2: { puts("The floor fails and you through it into the void"); break; } case 3: { int i, n; float num[10], sum = 0.0, avg; puts("The gentleman welcomes you into the corner with the light and he asks you to give him some numbers"); puts("However you find out that the old man cannot keep track of more than 10 values"); printf("Enter the amount of numbers you want to make an average out of \n"); scanf("%d",&n); while(n>10 || n<1) { printf("Error! Keep it between 1 and 10 values. \n"); printf("Enter the amoount of numbers you want to average: "); scanf("%d",&n); } for(i=0;i<n;++i) { printf("%d. Enter number: ",i+1); scanf("%f",&num[i]); sum += num[i]; } avg = sum /n; printf("Average = %.2f \n", avg); } } } break; } case 21: { while(choice != 99) { int x=0; int y; int z=0; srand(time(NULL)); puts("You have entered a chamber resembling the ruins of an Ancient Egyptian Temple "); puts("The door to your left shows signs of innocence"); puts("while the door to your right emits a dark and powerful energy"); puts("You see a dark figure in the distance"); puts("He tosses a coin"); for (i=0;i<1;i++) { y = rand()%2; if(y==1) { x++; puts("The coin lands on heads"); puts("Fate has decided for you to choose the door to your left"); } else { z++; puts("the coin lands on tails"); puts("???: Fate has decide for you to walk through the door to your right "); } printf("???: %s would you ignore fate \n",name); puts("???: Pick a door?!"); } scanf("%d",&choice); } break; } case 22: { while(choice != 99) { puts("you open the door and find ........"); scanf("%d",&choice); } break; } case 23: { while(choice != 99) { puts("you open the door and find ........"); puts("another door blocking the door"); scanf("%d",&choice); } break; } case 24: { while(choice != 99) { puts("Hello World"); puts("you open the door and find ........"); scanf("%d",&choice); } break; } case 25: { while(choice != 99) { puts("you open the door and find ........"); puts("You are in a small dark room"); puts("You start to hear noises but cannot see what it is"); puts("You panic and start running for your life"); scanf("%d",&choice); } break; } case 26: { while(choice != 99) { int choice26 = 0; printf("you open the door and find a small room with a door on the other side and a desk with three USB drives equally spread apart, one gree, one blue, one red.\n"); printf("You walk over to the desk and see a message above each USB...\n\n"); do{ printf("1) Inspect the Green USB.\n"); printf("2) Inspect the Blue USB.\n"); printf("3) Inspect the Red USB.\n"); printf("4) Walk up to the door on the other side of the room.\n"); printf("5) Leave the room and fall into the bottomless pit.\n"); printf("Enter choice 1-4: "); scanf("%d", &choice26); switch(choice26) { case 1: printf("\nYou are now viewing the green USB\n\n"); break; case 2: printf("\nYou are now viewing the blue USB\n\n"); break; case 3: printf("\nYou are now viewing the red USB\n\n"); break; case 4: printf("You walj over to the door and see a keypad lock on the door.\n\n"); break; } }while(choice26 != 5); printf("\nChoose another room 1-40 or type 99 to exit the program.\n"); scanf("%d",&choice); } break; } case 27: { while(choice != 99) { puts("you open the door and find ........"); puts("Fantasy world with flying dragons, mystery mythic, magic and rescuing princess... Your dream adventure world! Oh look! The little fairy flew and welcomes you."); puts("Would you like to talk to it (yes=1 no=0)?"); scanf("%d",&choice); if(choice == 1) { puts("You: Hey! How are you? This world seems pretty nic..."); puts("Fairy: Shut up and give me ALL you've got!!"); puts("You: Wait wha..?"); scanf("%c", &name[0]); puts("Fairy: I need a MONEY!(pulls out of a knife)."); puts("\nLooks like that wasn't clever choice."); puts("\t\t...YOU DIED...."); break; } puts("Are you really going to ignore this cute fairy? Come on~ at least saying hi wouldn't hurt anybody."); puts("Talk to the fairy(yes=1 no=0)."); scanf("%d",&choice); if(choice == 1) { puts("You: Hi,I was wonder what were you doing he..."); puts("Fairy: Were you trying to ignore me huh? (stabs with a knife)"); puts("Well... seems like that fairy would hurt anybody here haha. You Die..."); break; } puts("You have safely ranway from that cold blood fairy. Please select your derection to go"); puts("1.Mining Mountain 2.Shop 3.Gamble"); scanf("%d",&choice); switch(choice) { case 1: { puts("Entering Mining Mountain"); puts("Miner: Welcome to Pitcoin mining! You can mine your Pitcoin as many as you want. But the amount will be random. So GL!"); puts("Mine Pitcoin? (yes=1 no=0)"); scanf("%d",&choice); if(choice == 0) { puts("Exiting Mining Mountain"); break; } else if(choice == 1) { while(choice != -1) { puts("Let's mining!"); scanf("%d",&choice); } break; } else { puts("Please select again."); } } puts("reselect case"); scanf("%d",&choice); } } break; } case 28: { while(choice != 99) { puts("you open the door and find ........"); scanf("%d",&choice); } break; } case 29: { while(choice != 99) { puts("This is Sean."); puts("you open the door and find ........"); scanf("%d",&choice); } break; } case 30://Markease's room of "why did you do this?" { while(choice != 99) { puts("you open the door and find ........"); puts("Some guy screaming hello world. You panic and press 99!"); scanf("%d",&choice); } break; } case 31: { while (choice != 99) { // constants int MAX_SUMS = 30, ROLLS_PER_TURN = 3, POINTS_TO_LOOSE = 30, AI_STOPING_POINT = 10; FILE *writer = fopen("Casino.txt", "a"); // the "a" will append to the file printIntroduction(); int showRules = 2; printf("Would you like to read the rules? (1: yes | 2: no) "); scanf(" %d", &showRules); // format switch switch (showRules) { case 1: printRules(ROLLS_PER_TURN, POINTS_TO_LOOSE); break; } srand(time(NULL)); // arrays of all the averages that each player rolls double userSums[30] = {0}; double player2Sums[30] = {0}; double player3Sums[30] = {0}; // pointers for the sums arrays double *userSumPtr = userSums; double *player2SumPtr = player2Sums; double *player3SumPtr = player3Sums; // decides when the game should stop (if no one is able to play anymore) int userStillPlaying = 1, player2StillPlaying = 1, player3StillPlaying = 1; int iteration = 0; // increases in each loop, determines how large the dice will get double currentScore[3]; // keeps track of the score for each player int i; // for loops while (userStillPlaying == 1 || player2StillPlaying == 1 || player3StillPlaying == 1) { int userInput; int lowDiceSize, highDiceSize; // the lowest and highest value a dice can get you int rolls[3]; // holds the values of all the rolls int chooseToRoll; // stores the decision of the other players to roll or not iteration++; highDiceSize = iteration * 10; puts("\n- - - - - - -\n"); // just a divider since there is a lot going on in the console. printf("\nRound %d, Dice size is %d to %d", iteration, 1, highDiceSize); if (userStillPlaying) { puts("\n\nYour Turn:"); printf("Would you like to roll your three dice? (1: yes | 2: no) "); scanf(" %d", &userInput); if (userInput == 1) { for (i = 0; i < ROLLS_PER_TURN; i++) { // random number between the highest that the dice can get you and the lowest it can get you rolls[i] = (rand() % highDiceSize) + 1; } // stores the average of all three rolls in the sum array *userSumPtr = averageM(rolls, ROLLS_PER_TURN); printRollResults(rolls, ROLLS_PER_TURN, 1); // prints out the outcome of all your rolls printf("Average of your rolls: %.1lf\n", *userSumPtr); userSumPtr++; // increases pointer so next time it will add to the next index of the array currentScore[0] = sumM(userSums, MAX_SUMS); // takes the sum of all your averages so far printf("Your current score: %.1lf", currentScore[0]); if (currentScore[0] > POINTS_TO_LOOSE) { userStillPlaying = 0; printf("\nYou lost. %.1lf is larger than %d...", currentScore[0], POINTS_TO_LOOSE); } } else if (userInput == 2) { userStillPlaying = 0; } } if (player2StillPlaying) { puts("\n\nPlayer 2 Turn:"); chooseToRoll = 1; // decides to keep rolling if ((POINTS_TO_LOOSE - sumM(player2Sums, MAX_SUMS)) < AI_STOPING_POINT) // if the ai is (stoping point) away from the score limit, they will stop rolling { chooseToRoll = 0; player2StillPlaying = 0; puts("Player 2 chose not to roll anymore."); } if (chooseToRoll == 1) { for (i = 0; i < ROLLS_PER_TURN; i++) { // random number between the highest that the dice can get you and the lowest it can get you rolls[i] = (rand() % highDiceSize) + 1; } // stores the average of all three rolls in the sum array *player2SumPtr = averageM(rolls, ROLLS_PER_TURN); printRollResults(rolls, ROLLS_PER_TURN, 0); // prints out the outcome of all your rolls printf("Player 2 rolls average: %.1lf\n", *player2SumPtr); player2SumPtr++; // increases pointer so next time it will add to the next index of the array currentScore[1] = sumM(player2Sums, MAX_SUMS); // takes the sum of all your averages so far printf("Player 2 score: %.1lf", currentScore[1]); if (currentScore[1] > POINTS_TO_LOOSE) { player2StillPlaying = 0; printf("\nPlayer 2 is out. %.1lf is larger than %d...", currentScore[1], POINTS_TO_LOOSE); } } } if (player3StillPlaying) { puts("\n\nPlayer 3 Turn:"); chooseToRoll = 1; // decides to keep rolling if ((POINTS_TO_LOOSE - sumM(player3Sums, MAX_SUMS)) < AI_STOPING_POINT) // if the ai is (stoping point) away from the score limit, they will stop rolling { chooseToRoll = 0; player3StillPlaying = 0; puts("Player 3 is choosing not to roll anymore."); } if (chooseToRoll == 1) { for (i = 0; i < ROLLS_PER_TURN; i++) { // random number between the highest that the dice can get you and the lowest it can get you rolls[i] = (rand() % highDiceSize) + 1; } // stores the average of all three rolls in the sum array *player3SumPtr = averageM(rolls, ROLLS_PER_TURN); printRollResults(rolls, ROLLS_PER_TURN, 0); // prints out the outcome of all your rolls printf("Player 3 average rolls is %.1lf\n", *player3SumPtr); player3SumPtr++; // increases pointer so next time it will add to the next index of the array currentScore[2] = sumM(player3Sums, MAX_SUMS); // takes the sum of all your averages so far printf("Player 3 score: %.1lf", currentScore[2]); if (currentScore[2] > POINTS_TO_LOOSE) { player3StillPlaying = 0; printf("\nPlayer 3 is out. %.1lf is larger than %d...", currentScore[2], POINTS_TO_LOOSE); } } } } printf("\n\nUser score: %.1lf\n", currentScore[0]); printf("Player 2 score: %.1lf\n", currentScore[1]); printf("Player 3 score: %.1lf\n", currentScore[2]); if (currentScore[0] > POINTS_TO_LOOSE) { currentScore[0] = -1; } if (currentScore[1] > POINTS_TO_LOOSE) { currentScore[1] = -1; } if (currentScore[2] > POINTS_TO_LOOSE) { currentScore[2] = -1; } // change name to all capital letters for (i = 0; i < strlen(name); i++) // doing char function { if(i % 2 == 0) { name[i] = toupper(name[i]); } else { name[i] = tolower(name[i]); } } char nameToReplace[256] = "CTO OF HOT POCKETS"; char myNameWhichIsManny[256] = "MaNnY"; if(strcmp(myNameWhichIsManny, name) == 0) // compares strings // string function { strcpy(name, nameToReplace); // copies string } if ((currentScore[0] == -1) && (currentScore[1] == -1) && (currentScore[2] == -1)) { puts("\nEveryone lost..."); fprintf(writer, "%s lost with everyone\n", name); } else if ((currentScore[0] > currentScore[1]) && (currentScore[0] > currentScore[2])) { printf("\nYou won!"); fprintf(writer, "%s beat player 1 and 2\n", name); } else if ((currentScore[1] > currentScore[2]) && (currentScore[1] > currentScore[0])) { printf("\nPlayer 2 won!"); fprintf(writer, "%s lost to player 2\n", name); } else { printf("\nPlayer 3 won!"); fprintf(writer, "%s lost to player 3\n", name); } fclose(writer); // close the output file so i can start writing in it again. int showRecords = 2; printf("\nGood game. Would you like to see the records of previous games? (1: yes | 2: no) "); scanf(" %d", &showRecords); if (showRecords == 1) { FILE *reader = fopen("Casino.txt", "r"); char line[50]; char c; c = fgetc(reader); while (c != EOF) { printf("%c", c); c = fgetc(reader); } fclose(reader); } puts("\nRemember to enter 99 to exit!"); scanf("%d", &choice); } break; } case 32: { while(choice != 99) { puts("You are safe from the water, but strange random strings start to attack. What do you do?"); while(choice != 99) { char *ptr; char randStr[11] = ""; puts("1. Smack the string in the leftmost bit"); puts("2. Kick the string in the rightmost bit"); puts("99. Exit Room"); scanf("%d", &choice); switch(choice) { case 1: ptr = randomString(randStr); printf("String %s approaches you and you smack it!\n", ptr); printf("The string is confused and altered to %s \n", ptr); break; case 2: break; case 99: break; default: puts("You can't do that."); break; } } } break; } case 33: { while(choice != 99) { puts("you open the door and find ........"); scanf("%d",&choice); } break; } case 34: { while(choice != 99) { puts("you open the door and find ........"); scanf("%d",&choice); } break; } case 35: { while(choice != 99) { puts("you open the door and find ........"); scanf("%d",&choice); } break; } case 36: { while(choice != 99) { puts("you open the door and find ........"); scanf("%d",&choice); } break; } case 37: { while(choice != 99) { puts("you open the door and find ........"); scanf("%d",&choice); } break; } case 38: { while(choice != 99) { puts("you open the door 38 to and found a deadly cake........"); scanf("%d",&choice); } break; } case 39: { while(choice != 99) { puts("you open the door and find ........"); puts("A gambling machine, and it says, If you average is even, you win, but if your average is odd, you lose"); puts("You decide to play"); play(); scanf("%d",&choice); } break; } case 40: { while(choice != 99) { puts("You open the door and close it behind you."); puts("After you overcome the panic from almost drowning, you look around and You find yourself in a cave, the air is damp and you smell mold."); puts("You notice a skeleton at your feet with it's right hand clenched around something. The cave ahead leads to a tunnel and you see a door to your right."); puts("At this point you have 3 choices:"); puts("1. Examine the skeleton."); puts("2. Proceed further ahead in the cave."); puts("3. Enter the door to your right."); scanf("%d",&choice); if(choice == 1) { puts("You reach down and pry open the skeleton's hand, a finger breaks loose and you place it in your pocket. Once you pry the opject free you look at it closely in the light and see it is a live grenade and the pin springs free. You drop the grenade and dash through the cave. You can hear the grenade explode, collapsing the tunnel behind you."); puts("To be continued..."); break; } else if(choice == 2) { puts("You find yourself further ahead in the cave."); puts("To be continued...."); break; } else if(choice == 3) { puts("You enter the and close the door behind you."); printf("You hear an loud voice \" %s why do you disturb me? \" \n",name); puts("To be continued...."); break; } else { puts("wrong choice"); } } break; } } } return EXIT_SUCCESS; } // void RollArray(int *arr)//LA // { // int i; // int y; // int *ptr; // ptr = arr; // for (i=0;i<1;i++) // { // y= rand()%6; // *(arr+y) = *(arr+y)+1; // arr=ptr; // } // } void play(void) { int i; int total = 0; int numbers[4] = {0}; int avg; for(i = 0; i < 5; i++) { numbers[i] = rand() % 100; total = total + numbers[i]; } avg = total / 5; if(avg % 2 == 0) { printf("The number is even you win!!"); } else { printf("You lose"); } } //Monika void monikawelcome(char name[]) { int monikai = 0; char monikaname[256] = {0}; strcpy(monikaname, name); for(monikai = 0; monikai < 256; monikai++) { if(islower(monikaname[monikai])) { monikaname[monikai] = toupper(monikaname[monikai]); } if(isupper(monikaname[monikai])) { //printf("%c", monikaname[monikai]); } } printf("\n~Welcome %s to this minigame~\n\n", monikaname); puts("MAKE SURE THE TERMINAL IS IN FULL SCREEN WHEN RUNNING CASE 15\n"); } void monikacase1(char yellowdecision[]) { puts("You chose the yellow path, as you walk you see a hop scotch drawn on the floor\n"); puts(" ______ "); puts(" | 1 | "); puts(" _____|______|_____ "); puts("| 2 | 3 | 4 |"); puts("|_____|______|_____|"); puts(" | 5 | "); puts(" _____|______|_____ "); puts("| 6 | 7 | 8 |"); puts("|_____|______|_____|"); puts(" | 9 | "); puts(" |______| "); puts(" | 10 | "); puts(" |______| \n"); puts("do you want to play with it?\ny or n\n"); scanf(" %s", yellowdecision); //prints hopscotch if(strcmp(yellowdecision, "y") == 0) //if its equal to each other //0 = true, !0 == false { int jumps = 0; int i = 0; char anotherRoll[2]; int yellowTries = 0; while(jumps != 6) { yellowTries++; i = 0; for(i = 0; i < 2; i++) { puts("You stand infront of the first box, and you find a 6 sided die,\nnext to the die theres a note that says to roll the die in order to jump.\nDo you want to roll? (y or n)\n"); scanf(" %s", anotherRoll); //while the choices are wrong, do the below //but if its right it will exit and move forward if(strcmp(anotherRoll, "y") == 0) { jumps = (rand() % 6) + 1; //above prints one int if(jumps != 6) { printf("You got %d from the die, it wasnt enough to go to the other side, re-roll.\n", jumps); } else { printf("You got %d, you can pass\n", jumps); break; } } else { puts("ok, bye\n"); exit(1); } } if(jumps == 6) { break; } else { puts("\nYou ran out of attempts, good bye\n"); break; } } } else if (strcmp(yellowdecision, "n") == 0) { FILE *monikasponge; char filesponge[200] = "sponge.txt", spongePrint; // Open file monikasponge = fopen(filesponge, "r"); if (monikasponge == NULL) { printf("Wrong file name, retry \n"); exit(0); } // Read contents from file spongePrint = fgetc(monikasponge); while (spongePrint != EOF) { printf("%c", spongePrint); spongePrint = fgetc(monikasponge); } puts("I dOnT wAnT tO pResS yEs\n"); puts("\nbye\n"); fclose(monikasponge); exit(1); //return 0; //exits u from the program } } void monikacase2(char reddecision[]) { char key[20]; char monikausertry[20], pressF[2]; FILE *monikaoutput, *Deciphered; monikaoutput = fopen("monikaoutput.txt", "w"); Deciphered = fopen("Deciphered.txt", "r"); puts("Youve chosen the red road, and you see a blue tunnel. You enter and you\nsee a wall with a code pad on it, its asking if you\nwant to see the prompt to move forward. Do you say yes or no? (y or n)\n"); scanf(" %s", reddecision); //create a text thing where we show the user the file and we make them //deciper the code and if its right they will move forward int keepLooping = 1; while(strcmp(reddecision, "y") == 0 && keepLooping == 1) { printf("\nDecipher the following text: \nOnce you have an answer, input it below\n"); puts("\n71 97 114 114 101 116 116 66 108 117 80 111 112 112 101\n"); //text file to decipher puts("Need a hint? Ask the key\n"); scanf(" %s", monikausertry); //if yes then we will prompt the text and ask to deciper fscanf(Deciphered, " %s", key); if(strcmp(monikausertry, key) == 0) //check if the same then continue { puts("\nPIN UNLOCKED\n"); puts("You can see your previous attempts in the monikaoutput.txt file"); if(strcmp(monikausertry, key) == 0) { puts("\nYour sight is filled with darkness and the glistening of the water as it shines from the light behind you."); puts("You begin to move forward and get into the water but it feels weird. You think maybe its because its cold so you just dismiss it."); puts("You continue but you begin to feel a burning sensation on your body and you begin panicking,\n'what's in this water'"); puts("As you look for something to grab to get out of the water\nyour eyes lock on to a warning label on the side of the river, reading: 'WARNING: SULFURIC ACID REMAINS IN THE WATER\nIF IN CONTACT, PERISHABLE'\n"); puts("YOU DIED\n"); exit(1); } keepLooping = 0; } else { fprintf(monikaoutput, "Failed Attempt: %s\n", monikausertry); } fprintf(monikaoutput, "\n"); } rewind(monikaoutput); fclose(monikaoutput); if(strcmp(reddecision, "n") == 0) { puts("You said no\n"); puts("You tried going back to the entrance and fell through a dirt hole and died, press f to pay respects\n"); scanf(" %c", pressF); if(strcmp(pressF, "f") == 0) { exit(1); } else { puts("fine then, dont pay respects\n"); exit(1); } } } void monikacase3(char greenchoice[]) { puts("Do you want to continue green path? (y or n)\n"); scanf(" %s", greenchoice); if(strcmp(greenchoice, "y") == 0) { FILE *monikanothing; char filenothing[200] = "nothing.txt", nothingPrint; // Open file monikanothing = fopen(filenothing, "r"); if(monikanothing == NULL) { printf("Wrong file name, retry \n"); exit(0); } // Read contents from file nothingPrint = fgetc(monikanothing); while(nothingPrint != EOF) { printf("%c", nothingPrint); nothingPrint = fgetc(monikanothing); } puts("\nyoure welcome\n"); fclose(monikanothing); exit(1); } else if(strcmp(greenchoice, "n") == 0) { int monikai = 0, monikasize = 5, monikasum = 0, monikaArray[monikasize]; int *monikaPointer; monikaPointer = monikaArray; printf("Fine since you dont want to go the path you can play this boring calculator game\nInsert five numbers you want to add and find the sum of\n"); for(monikai = 0; monikai < monikasize; monikai++) { scanf(" %d", &monikaArray[monikai]); } printf("Things inputted are: \n"); monikasize = 5; for(monikai = 0; monikai < (monikasize - 1); monikai++) { printf(" %d\n", *monikaPointer); monikaPointer++; } monikasize = sizeof(*monikaPointer) / sizeof(int); printf(" + %d \n---------\n", monikaPointer[monikasize - 1]); monikasum = 0; monikasize = 5; for(monikai = 0; monikai < monikasize; monikai++) { monikasum += monikaArray[monikai]; } printf("sum : %d\n", monikasum); int monikaaverage = 0; monikaaverage = (double)monikasum / (double)monikasize; printf("Average: %.1lf\n", (double)monikaaverage); exit(1); } } //Monika char *randomString(char *p) { int randLine = rand() % 100; int i = 0; FILE *rfPtr; if((rfPtr = fopen("randomStrings.txt", "r")) == NULL) { puts("File could not be opened."); } else { while(fgets(p, 11, rfPtr) != NULL) { if(i == randLine) { fclose(rfPtr); return p; } else { i++; } } fclose(rfPtr); } return p; } void mQhelpPrompt(void) { puts("-----------------------------------------------------------------------------------------"); puts("Type 'help' at any time to see the Help menu, which has a list of commands you can use.\n"); puts("-----------------------------------------------------------------------------------------"); } void mQhelpMenu(void) { puts("--------------------------------------------------------------------------------------------------"); puts("Usable Commands: inv, go, look, use, and exit\n"); puts("Type 'inv' to see your inventory"); puts("Type 'go' followed by a location to move towards it"); puts("Type 'look' followed by an object OR location to inspect it."); puts("Type 'use' to use an object from your inventory, OR obtain it and put it in your inventory."); puts("\nType 'exit' to leave the parser."); puts("'Any noun in capital letters - like THIS - can be used with commands (example: use KEY, look TABLE"); puts("--------------------------------------------------------------------------------------------------"); } void mQcontinue(void) { printf("(Press 0 and Enter to continue)"); fflush(stdout); //do I need this? while(getchar() != '0'){}; } int mQuserInput(void) { //fflush(stdout); printf(" "); printf("\n------> "); return fgets (uInput, sizeof(uInput), stdin ) != NULL; } int mQparser(void) { char *word1 = strtok(uInput, " \n"); char *word2 = strtok(NULL, " \n"); if (word1 != NULL) { // command "exit" if (strcmp(word1, "exit") == 0) { puts("Insert clever start-over text here. Maybe a little 'are you sure you want to quit?' or whatever"); return 0; } // command "help" else if (strcmp(word1, "help") == 0) { mQhelpMenu(); } // command "inv" else if (strcmp(word1, "inv") == 0) { puts("The user only has 'updog' in their inventory.\n"); } // command "look" else if (strcmp(word1, "look") == 0) { // look stove if (strcmp(word2, "STOVE") == 0 || strcmp(word2, "stove") == 0) { puts("\nThe user looks at the stove. The user loves a good stove. This one has electric burners though, so it's not a good stove. The user frowns and wishes they picked another student's door."); } // look fridge else if (strcmp(word2, "FRIDGE") == 0 || strcmp(word2, "fridge") == 0) { puts("\nThe fridge's stainless steel surface is littered with post it notes. You pick one up and angle your cell phone to read it."); puts("\n\n'If one more person eats my leftovers without permission, I will COMMMIT A FELONY. I MEAN IT!!!!!'"); puts("\nFrowning, you turn it over to discover there's more written on the back."); puts("\n'Actually, you know what? YOU KNOW WHAT?! Eat them. Go on. I dare you. Eat all of it. I hope you choke on a piece and die in agony right here on my KITCHEN FLOOR. YOU SHOULD HAVE NEVER BEEN BORN. - J'"); puts("\nYou find yourself wondering who the hell this 'J' is, and what made them upset enough to cover their refridgerator with passive aggressive post-its."); } // look freezer else if (strcmp(word2, "FREEZER") == 0 || strcmp(word2, "freezer") == 0) { puts("\nThe freezer's stainless steel surface is littered with post it notes. You pick one up and angle your cell phone to read it."); puts("\n'Jim, I swear to God, if you move the eggs again to put more post-it notes inside, I will buy the dollar store brand of BBQ sauce from now on. Do not try me, young man. - H'"); puts("\nAnother post-it note is attached to the end of this one. It reads: "); puts("\n'I DO NOT FEAR DEATH OR DRY CHICKEN NUGGETS! I WILL NOT BE MANIPULATED BY THE SAUCE! \nI have an emergency stash of Sweet Baby Rays for just this occasion, anyway. -J'"); puts("\nYou are baffled by just how much writing can fit on a post-it note. Your eyes are starting to hurt from squinting at all the tiny writing.\n"); } } // command "go" - CONSIDER REMOVAL else if (strcmp(word1, "go") == 0) { // go stove if (strcmp(word2, "STOVE") == 0 || strcmp(word2, "stove") == 0) { puts("\nThe user goes to the stove. Good job. You're at the stove. You did it. Wonderful."); } // go fridge else if (strcmp(word2, "FRIDGE") == 0 || strcmp(word2, "fridge") == 0) { puts("\nThe user approaches the fridge. The distance...it's still too much. You must get closer..."); puts("\nThe user presses their cheek against the fridge, wrapping their arms around as far as they can reach."); puts("\nThe fridge does not hug you back, but you somehow feel a brief reprieve from your loneliness, nonetheless."); } // go freezer else if (strcmp(word2, "FREEZER") == 0 || strcmp(word2, "freezer") == 0) { puts("\nYou approach the freezer."); puts("\nYou think of a few cold-related puns, but you quickly banish them from your mind. Puns are the lowest form of comedy, of course, and you'd be a shameless wreck before you'd ever entertain one, even in your head."); puts("\nIf thought to yourself just now, 'Now, that's just cold...', you, in fact, did not. You didn't think anything at all. You don't think. Your head is empty. Go shove your stupid head full of puns in the freezer."); } } // command "use" else if (strcmp(word1, "use") == 0) { // use stove if (strcmp(word2, "STOVE") == 0 || strcmp(word2, "stove") == 0) { puts("\nThe user uses the stove. The stove says 'get the hell out of my kitchen.' The user does not, in fact, get the hell out of the kitchen."); } // use fridge else if (strcmp(word2, "FRIDGE") == 0 || strcmp(word2, "fridge") == 0) { puts("\nYou pull gently on the fridge handle, and are greeted with its soft inner glow and a faint whiff of eggs and...old onions? Ugh."); puts("\nYou see a small bowl of LEFTOVERS, a bottle of Sweet Baby Ray's bbq SAUCE, and a can of Natural Light BEER. There are post-it notes on each."); } // use freezer else if (strcmp(word2, "FREEZER") == 0 || strcmp(word2, "freezer") == 0) { puts("\nThe user pulls swiftly against the hermetic seal of the freezer, and is met with a small puff of chilled air."); puts("\n...followed closely by a much stronger, more decidedly *pungent* whiff of egg."); puts("\nBlinking rapidly to ensure they aren't seeing things, the user realizes the entire fridge is full of decorated frozen easter eggs. A small post-it note on eye-level with the user reads: 'Little Jimmy's Easter Eggs, 1987. DO ***NOT*** THROW AWAY!!!'"); puts("\nHorrified, the user sincerely wishes they had found a dead body instead."); puts("\nThere is an additional NOTE wedged in between the freezer wall and the awful, awful Egg Pile."); } // funny joke else if (strcmp(word2, "updog") == 0) { puts("\nNothin, what's up with you, man?\n"); puts(" ( ͡° ͜ʖ ͡°) "); puts("..."); puts("\nThis joke would have been better if I had figured out how to open a webpage to www.updog.com like I had originally planned."); } } // dumb parser else { printf("\nI have no idea how to %s, but knock yourself out.", word1); } } return 1; } // Talise void printMessage(int msg[]) { int i = 0; printf("Message: "); while(i < 10) { printf("%d ", msg[i]); i++; } printf("\n"); } void decodeMessage(char alphabet[], int codedMessage[], int *totalGuesses, int *wrong) { int i, x; char guess; char c; puts("Decode the message: "); for(i = 0; i < 10; i++) { printf("Enter lowercase guess for %d: ", codedMessage[i]); scanf(" %c", &guess); x = (codedMessage[i] - 1); c = alphabet[x]; if(guess == c) { (*totalGuesses)++; } while(guess != c) { printf("Try again. Enter lowercase guess for %d: ", codedMessage[i]); scanf(" %c", &guess); (*totalGuesses)++; (*wrong)++; } } } void userFate(int x) { int i, score; double avg = 0.0; double sum = 0.0; switch(x) { case 1: { puts("You are free."); break; } case 2: { puts("You decoded the message, but now you must enter 3 test scores: "); break; } } if(x == 2) { for(i = 0; i < 3; i++) { printf("Enter score: "); scanf("%d", &score); sum += score; } avg = sum / 3; printf("Your test score average is: %.2lf \n", avg); } } void printRollResults(int rolls[], int numberOfRolls, int isUser) // Manuel Castaneda { if (isUser) { printf("You rolled: "); } else { printf("they rolled: "); } int i; for (i = 0; i < numberOfRolls; i++) { printf("%d ", rolls[i]); } printf("\n"); } double averageM(int rolls[], int numberOfRolls) // Manuel Castaneda { int i, sum = 0; for (i = 0; i < numberOfRolls; i++) { sum = sum + rolls[i]; } return sum / (double)numberOfRolls; } double sumM(double sums[], int maxSums) // Manuel Castaneda { int i = 0; double sum = 0; for (i = 0; i < maxSums; i++) { if (sums[i] == 0) { break; } sum = sum + sums[i]; } return sum; } void printIntroduction(void) // Manuel Castaneda { puts("\n\nYou walked into a secret casino."); puts("The door closes behind you."); puts("The only way to leave is to play a game Dice Average."); } void printRules(int rollsPerTurn, int pointsToLoose) { puts("\nRules:"); printf("- Each turn, you and two other players will choose if you wish to roll %d dice.\n", rollsPerTurn); printf("- The average number of the %d dice are added to your score.\n", rollsPerTurn); printf("- Who ever can get their score closest to %d wins. If your score goes above %d then you loose.\n", pointsToLoose, pointsToLoose); puts("- Before each turn, the dice values increase."); puts("- After each turn, you will get an opportunity to roll again or stop rolling."); puts("- If you choose to stop rolling, you can no longer roll for the rest of the game."); } // Manuel Castaneda
the_stack_data/7949881.c
// PARAM: --set ana.activated[+] "'var_eq'" --set ana.activated[+] "'symb_locks'" --set ana.activated[+] "'region'" --set exp.region-offsets true #include<pthread.h> #include<stdlib.h> #include<stdio.h> struct s { int datum; struct s *next; }; struct s *new(int x) { struct s *p = malloc(sizeof(struct s)); p->datum = x; p->next = NULL; return p; } void list_add(struct s *node, struct s *list) { struct s *temp = list->next; list->next = node; node->next = temp; } pthread_mutex_t mutex[10]; struct s *slot[10]; void *t_fun(void *arg) { int i; pthread_mutex_lock(&mutex[i]); list_add(new(3), slot[i]); pthread_mutex_unlock(&mutex[i]); return NULL; } int main () { int j; struct s *p; pthread_t t1; slot[j] = new(1); list_add(new(2), slot[j]); pthread_create(&t1, NULL, t_fun, NULL); pthread_mutex_lock(&mutex[j]); p = slot[j]->next; // NORACE printf("%d\n", p->datum); pthread_mutex_unlock(&mutex[j]); return 0; }
the_stack_data/170452253.c
#include <stdio.h> #include <string.h> #include <math.h> #include <stdlib.h> int main() { int i, j, k, l; // int n = 5; int n; scanf("%d", &n); int m = (n + 1) / 2; int space, star; // int m = 2 * n - 1; for (i = 1; i <= n; i++) { if (i <= m) { space = m - i; star = 2 * i - 1; } else { space = i % m; star = 2 * m - 1 - 2 * (i % m); } for (j = 1; j <= space; j++) { printf("*"); } for (k = 1; k <= star; k++) { printf("D"); } for (l = 1; l <= space; l++) { printf("*"); } printf("\n"); } }
the_stack_data/133716.c
// RUN: %bmc "%s" | FileCheck "%s" // CHECK: Verification FAILED extern void abort(void); void __VERIFIER_error() { // empty } extern int __VERIFIER_nondet_int(); int main() { int x = __VERIFIER_nondet_int(); if (x) { __VERIFIER_error(); abort(); } return 0; }
the_stack_data/114050.c
#include <stdio.h> #include <string.h> /***** Problem 11 on Practice Test 2 * * A good way to approach these style of multiple questions is to scan the * various choices and observe their differences. For this problem the difference is * in the initialization of i in the for loop. This leads to an easy solution. * We don't what to print argv[0], the command, this eliminates (a) and (c). * argv[argc] does not exist because the array indexing starts at 0. * That eliminates (b). * * The answer is therefore (d) * *********************************/ /* // a. #include <stdio.h> int main(int argc, char *argv[]) { int i; for (i = argc; i >= 0; i--) // This will crash since argv[argc] does not exist. Also argv[0] is the command. printf("%s ", argv[i]); printf("\n"); return 0; } // b. #include <stdio.h> int main(int argc, char *argv[]) { int i; for (i = argc; i > 0; i--) // This will crash since argv[argc] does not exist. printf("%s ", argv[i]); printf("\n"); return 0; } // c. #include <stdio.h> int main(int argc, char *argv[]) { int i; for (i = argc - 1; i >= 0; i--) // This will print argv[0] which is the command. printf("%s ", argv[i]); printf("\n"); */ // d. #include <stdio.h> int main(int argc, char *argv[]) { int i; for (i = argc -1; i > 0; i--) // This will only print the arguments after the command. They will be printed in reverse order. printf("%s ", argv[i]); printf("\n"); return 0; } /********************* OUTPUT ************************** * * Input: ./a.out computer science * * Output: science computer * ********************************************************/
the_stack_data/150141405.c
#include <unistd.h> #include <sched.h> int main(int argc, char** argv){ struct sched_param p; sched_getparam(0, &p); if (argc < 1 || argv[1] ==NULL) p.sched_priority=sched_get_priority_max(SCHED_FIFO); else p.sched_priority=atoi(argv[1]); sched_setscheduler(0, SCHED_FIFO,&p); execlp("/bin/sh","/bin/sh",NULL); }
the_stack_data/200144449.c
/* * Author: Aurelio Colosimo, 2016 * Released under MIT-Expat License. */ /* Tool to compute Cooley–Tukey FFT twiddle factors and generate * a .h and a .c file which can be compiled and linked to your application * * Usage: psdr-twiddle N nbits output.h output.c * N: number of taps * nbits: number of bits of each real/imaginary value * output.h: filename for generated .h * output.c: filename for generated .c */ #include <stdio.h> #include <math.h> #include <stdint.h> #include <libgen.h> #define EXE "psdr-twiddle" #define COMMON_HEADER \ "/*\n * File %s\n * Automatically generated by " EXE " tool\n" \ " * Command line:" #define COMMON_IDX_COMMENT "/* First index: i; second index: k */\n" int main(int argc, char** argv) { unsigned N, nbits, i, k; const unsigned max_nbits = sizeof(long long) * 8 - 1; FILE *fh = NULL, *fc = NULL; float factor; long long intfactor; if (argc < 5) { printf("\n" EXE " - Tool to compute Cooley-Tukey FFT twiddles\n\n"); printf("Usage: " EXE " N nbits output.h output.c\n"); printf("\tN: number of taps\n"); printf("\tnbits: nbits: number of bits of each real/imaginary value\n"); printf("\toutput.h: filename for generated .h\n"); printf("\toutput.c: filename for generated .c\n"); printf("\n"); return 1; } N = strtoul(argv[1], NULL, 10); if (!N) { printf("Invalid N parameter: %s\n", argv[1]); return 1; } nbits = strtoul(argv[2], NULL, 10); if (!nbits || nbits > max_nbits) { printf("Invalid nbits parameter: %s, max %d\n", argv[2], max_nbits); return 2; } fh = fopen(argv[3], "w"); if (!fh) { printf("Unable to open %s in write mode.\n", argv[3]); return 3; } fc = fopen(argv[4], "w"); if (!fc) { printf("Unable to open %s in write mode.\n", argv[4]); fclose(fh); return 4; } fprintf(fh, COMMON_HEADER, argv[3]); fprintf(fc, COMMON_HEADER, argv[4]); for (i = 0; i < argc; i++) { fprintf(fh, " %s", argv[i]); fprintf(fc, " %s", argv[i]); } fprintf(fh, "\n */\n\n"); fprintf(fc, "\n */\n\n"); fprintf(fc, "#include \"%s\"\n\n", basename(argv[3])); fprintf(fc, COMMON_IDX_COMMENT "\n"); fprintf(fh, "#include <arith.h>\n\n"); fprintf(fh, COMMON_IDX_COMMENT); fprintf(fh, "extern const cpx_t twiddle%d_%db[%d][%d];\n", N, nbits, N, N / 2); fclose(fh); fprintf(fc, "const cpx_t twiddle%d_%db[%d][%d] = {\n", N, nbits, N, N / 2); factor = powf(2, nbits - 1); intfactor = llround(factor); for (i = 0; i < N; i++) { fprintf(fc, "\n\t{"); if (i % 4 == 0) fprintf(fc, " /* i = %u */", i); for (k = 0; k < N / 2; k++) { float phi = (-2 * M_PI / N) * i * k; float sf = sin(phi); float cf = cos(phi); long long c, s, f; if (k % 4 == 0) fprintf(fc, "\n\t\t"); c = llroundf(cf * factor); s = llroundf(sf * factor); if (c == intfactor) c--; if (s == intfactor) s--; fprintf(fc, "{%lld, %lld}, ", c, s); } fprintf(fc, "\n\t},\n"); } fprintf(fc, "\n};\n"); fclose(fc); return 0; }
the_stack_data/23576525.c
#include <stdio.h> #include <stdint.h> /* Compliant way to use \details in doxygen comment block below */ /** * \brief Get voltage level. * * \details Returns battery voltage * level as an integer value * in mV. For example 3.3 V * will be returned as 3300. * * \param Void. * * \return The voltage level. */ int getVoltage(void); int main(void) { printf("Doxygen rule 003 ."); } int getVoltage(void) { return 3300; /* 3.3 V */ }
the_stack_data/800304.c
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_strcat.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: lrudowic <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/04/30 11:45:06 by lrudowic #+# #+# */ /* Updated: 2019/05/20 16:41:03 by lrudowic ### ########.fr */ /* */ /* ************************************************************************** */ char *ft_strcat(char *s1, const char *s2) { char *res; res = s1; while (*s1) s1++; while ((*s1++ = *s2++) != '\0') ; return (res); }
the_stack_data/178264246.c
// RUN: %clang_cc1 -S -O3 -fno-builtin -o - %s | FileCheck %s // rdar://10551066 double ceil(double x); double copysign(double,double); double cos(double x); double fabs(double x); double floor(double x); double t1(double x) { return ceil(x); } // CHECK: t1 // CHECK: ceil double t2(double x, double y) { return copysign(x,y); } // CHECK: t2 // CHECK: copysign double t3(double x) { return cos(x); } // CHECK: t3 // CHECK: cos double t4(double x) { return fabs(x); } // CHECK: t4 // CHECK: fabs double t5(double x) { return floor(x); } // CHECK: t5 // CHECK: floor
the_stack_data/89199549.c
/* * Derived from: * http://www.kernel.org/pub/linux/libs/klibc/ */ /* * memccpy.c * * memccpy() */ #include <stddef.h> #include <string.h> void *memccpy(void *dst, const void *src, int c, size_t n) { char *q = (char *)dst; const char *p = (char *)src; char ch; while (n--) { *q++ = ch = *p++; if (ch == (char)c) return q; } return NULL; /* No instance of "c" found */ }
the_stack_data/45450635.c
//Insere um elemento em um vetor, printando o vetor resultante #include<stdio.h> int main() { int n = 0; scanf(" %d", &n); int a[n], i; for (i = 0; i < n; i++) { scanf(" %d", &a[i]); } int indice, valor; scanf(" %d %d", &indice, &valor); if(indice < 0) { printf("INVALIDO"); } else { int vet_res[n+1]; if(indice >= n) { for(i = 0; i < n; i++) { vet_res[i] = a[i]; } vet_res[n] = valor; } else { for(i = 0; i < indice; i++){ vet_res[i] = a[i]; } vet_res[indice] = valor; for(i = indice + 1; i <= n; i++){ vet_res[i] = a[i - 1]; } } for(i = 0; i <= n; i++) { printf("%d ", vet_res[i]); } } }
the_stack_data/67325874.c
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <unistd.h> #include <fcntl.h> #include <errno.h> #include <signal.h> #include <elf.h> #include <linux/limits.h> #include <sys/types.h> #include <sys/wait.h> #include <sys/user.h> #include <sys/stat.h> #include <sys/ptrace.h> #include <sys/mman.h> typedef struct handle { Elf64_Ehdr *ehdr; Elf64_Phdr *phdr; Elf64_Shdr *shdr; uint8_t *mem; char *symname; // function name 需要下断点的函数name Elf64_Addr symaddr; // function address 需要下断点的函数的地址 struct user_regs_struct pt_reg; char *exec; // executable file address 可执行文件路径 } handle_t; /** * 根据符号名查找符号地址 */ Elf64_Addr lookup_symbol(handle_t *, const char *); // 根据pid获取 进程路径 char * get_pid_path(int pid); // 信号处理 void sighandler(int); int global_pid; #define EXE_MODE 0 // 调试 mode #define PID_MODE 1 // attach mode int main(int argc, char **argv, char **envp) { int fd, c, mode = 0; handle_t h; struct stat st; long trap, orig; int status, pid; char * args[2]; struct user_regs_struct pt_reg2; if (argc < 3) { printf("Usage: %s [-ep <exe>/<pid>] [-f <fname>]\n", argv[0]); exit(0); } //初始化 handle_t h memset(&h, 0, sizeof(handle_t)); while ((c = getopt(argc, argv, "p:e:f:")) != -1) { switch(c) { case 'p': // -p pid pid = atoi(optarg); h.exec = get_pid_path(pid); if (h.exec == NULL) { printf("Unable to retrieve executable path for pid: %d\n", pid); exit(-1); } mode = PID_MODE; break; case 'e': // -e executalue file path if ((h.exec = strdup(optarg)) == NULL) { perror("strdup"); exit(-1); } mode = EXE_MODE; break; case 'f': // -f function name /* 获取指定符号名 */ if ((h.symname = strdup(optarg)) == NULL) { perror("strdup"); exit(-1); } break; default: printf("Unknown option\n"); break; } } if (h.symname == NULL) { printf("Specifying a function name with -f option is required\n"); exit(-1); } if (mode == EXE_MODE) { args[0] = h.exec; args[1] = NULL; } global_pid = pid; signal(SIGINT, sighandler); /* 打开指定文件 */ if ((fd = open(h.exec, O_RDONLY)) < 0) { perror("open"); exit(-1); } /* 获取指定文件的属性 */ if (fstat(fd, &st) < 0) { perror("fstat"); exit(-1); } /* 将目标文件映射到本进程的虚拟内存中 */ h.mem = mmap(NULL, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0); if (h.mem == MAP_FAILED) { perror("mmap"); exit(-1); } h.ehdr = (Elf64_Ehdr *)h.mem; h.phdr = (Elf64_Phdr *)(h.mem + h.ehdr->e_phoff); h.shdr = (Elf64_Shdr *)(h.mem + h.ehdr->e_shoff); /* 确保文件为ELF格式文件, '\0x7FELF' */ if (h.mem[0] != 0x7f && !strcmp((char *)&h.mem[1], "ELF")) { printf("%s is not an ELF file\n",h.exec); exit(-1); } /* 确保目标文件为可执行ELF文件, gcc编译时需要加-no-pie参数 */ if (h.ehdr->e_type != ET_EXEC) { printf("%s is not an ELF executable\n", h.exec); exit(-1); } /* 确保程序在编译过程中没有去掉节表 */ if (h.ehdr->e_shstrndx == 0 || h.ehdr->e_shoff == 0 || h.ehdr->e_shnum == 0) { printf("Section header table not found\n"); exit(-1); } /* 寻找目标符号地址 */ if ((h.symaddr = lookup_symbol(&h, h.symname)) == 0) { printf("Unable to find symbol: %s not found in executable\n", h.symname); exit(-1); } close(fd); if (mode == EXE_MODE) { // 若为调试模式 // fork child process if ((pid = fork()) < 0) { perror("fork"); exit(-1); } if (pid == 0) { // child process 允许被附加 if (ptrace(PTRACE_TRACEME, pid, NULL, NULL) < 0) { perror("PTRACE_TRACEME"); exit(-1); } // 用 h.exec image替换 当前进程镜像 execve(h.exec, args, envp); exit(0); } } else { // 若为 attach 模式,直接附加 if (ptrace(PTRACE_ATTACH, pid, NULL, NULL) < 0) { perror("PTRACE_ATTACH"); exit(-1); } } /* 等待子进程运行终止,获取子进程状态放入status中 */ wait(&status); printf("Beginning analysis of pid: %d at %lx\n", pid, h.symaddr); /* 读取被追踪进程中地址为h.symaddr处的数据 */ orig = ptrace(PTRACE_PEEKTEXT, pid, h.symaddr, NULL); /* int3指令码 0xcc */ trap = (orig & ~0xff) | 0xcc; /* 将int3指令替换掉print_string的第一条指令从而设置断点 */ if (ptrace(PTRACE_POKETEXT, pid, h.symaddr, trap) < 0) { perror("PTRACE_POKETEXT"); exit(-1); } trace: /* 重启已终止的被追踪进程 */ if (ptrace(PTRACE_CONT, pid, NULL, NULL) < 0) { perror("PTRACE_CONT"); exit(-1); } wait(&status); /* 由于breakpoint断点、trap终止运行 */ // 判断进程是否被暂停,及暂停号是否为 SIGTRAP (SIGTRAP 实现相关的硬件异常。一般是调试异常) if (WIFSTOPPED(status) && WSTOPSIG(status) == SIGTRAP) { /* 获取寄存器内容 */ if (ptrace(PTRACE_GETREGS, pid, NULL, &h.pt_reg) < 0) { perror("PTRACE_GETREGS"); exit(-1); } printf("\nExecutable %s (pid: %d) has hit breakpoint 0x%lx\n", h.exec, pid, h.symaddr); printf("%%rcx: %llx\n%%rdx: %llx\n%%rbx: %llx\n" "%%rax: %llx\n%%rdi: %llx\n%%rsi: %llx\n" "%%r8: %llx\n%%r9: %llx\n%%r10: %llx\n" "%%r11: %llx\n%%r12 %llx\n%%r13 %llx\n" "%%r14: %llx\n%%r15: %llx\n%%rsp: %llx", h.pt_reg.rcx, h.pt_reg.rdx, h.pt_reg.rbx, h.pt_reg.rax, h.pt_reg.rdi, h.pt_reg.rsi, h.pt_reg.r8, h.pt_reg.r9, h.pt_reg.r10, h.pt_reg.r11, h.pt_reg.r12, h.pt_reg.r13, h.pt_reg.r14, h.pt_reg.r15, h.pt_reg.rsp); printf("\nPlease hit any key to continue: "); getchar(); /* 还原print_string中的第一条指令内容 */ if (ptrace(PTRACE_POKETEXT, pid, h.symaddr, orig) < 0) { perror("PTRACE_POKETEXT"); exit(-1); } /* 将指令指针-1,即从print_string的第一条指令开始执行 */ h.pt_reg.rip = h.pt_reg.rip - 1; /* 设置寄存器内容 */ if (ptrace(PTRACE_SETREGS, pid, NULL, &h.pt_reg) < 0) { perror("PTRACE_SETREGS"); exit(-1); } /* 设置进程执行一条指令后切换到终止状态 */ if (ptrace(PTRACE_SINGLESTEP, pid, NULL, NULL) < 0) { perror("PTRACE_SINGLESTEP"); exit(-1); } wait(NULL); /* 继续设置断点 */ if (ptrace(PTRACE_POKETEXT, pid, h.symaddr, trap) < 0) { perror("PTRACE_POKETEXT"); exit(-1); } goto trace; } /* 判断进程是否正常退出 */ if (WIFEXITED(status)) printf("Completed tracing pid: %d\n", pid); exit(0); } Elf64_Addr lookup_symbol(handle_t *h, const char *symname) { unsigned long i, j, NumOfSym; char *strtab; Elf64_Sym *symtab; for (i = 0; i < h->ehdr->e_shnum; i++) { /* 找 .symtab 节,该节保存了符号信息,每一个符号项为Elf64_Sym */ if (h->shdr[i].sh_type == SHT_SYMTAB) { /* 类型为SHT_SYMTAB的节,其sh_link为字符串表所在节表中的下标 */ /* 因此h->shdr[i].sh_link为字符串表下标 */ strtab = (char *) (h->mem + h->shdr[h->shdr[i].sh_link].sh_offset); /* 此段代码为测试分析,输出字符串表中可视字符 */ //printf("0x%lx\n", h->shdr[29].sh_offset); //for (j = 0; j < h->shdr[29].sh_size; j++) { // if (strtab[j] >= 0x20 && strtab[j] <= 0x7e) { // printf("%c", strtab[j]); // } //} //puts(""); /* 获取符号表的首地址 */ symtab = (Elf64_Sym *) &h->mem[h->shdr[i].sh_offset]; NumOfSym = h->shdr[i].sh_size / sizeof(Elf64_Sym); for (j = 0; j < NumOfSym; j++) { //char *name = (char *) &strtab[symtab->st_name]; //printf("\nsymbol name : %s\n", name); /* st_name为符号名在字符串表中的下标 */ if (!strncmp(&strtab[symtab->st_name], symname, strlen(symname))) { /* st_value 为符号的地址 */ return symtab->st_value; } symtab++; } } } return 0; } char * get_pid_path(int pid) { //char dir[PATH_MAX] = {0}; char *dir = (char *) malloc(PATH_MAX * sizeof(char)); char path[20]={0}; sprintf(path, "/proc/%d/exe", pid); // dir 保存 进程pid 镜像所在的目录(绝对路径) int n = readlink(path, dir, PATH_MAX); printf("path : %s, dir : %s\n",path,dir); if(n < 0) { perror("readlink"); exit(-1); } return dir; } // 当 Ctrl + C 给当前进程发中断信号时,用这个函数处理中断信号。这个涵数的功能是通过 PTRACE_DETACH 结束跟踪目标进程,然后当前进程通过 exit结束 void sighandler(int sig) { printf("Caught SIGINT: Detaching from %d\n", global_pid); if (ptrace(PTRACE_DETACH, global_pid, NULL, NULL) < 0 && errno) { perror("PTRACE_DETACH"); exit(-1); } exit(0); }
the_stack_data/25063.c
// WARNING: This file contains code that is more than likely already // exposed from the Esp32 Arduino API. It will be removed once integration is complete. // // Copyright 2015-2016 Espressif Systems (Shanghai) PTE LTD // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #if defined(ARDUINO_ARCH_ESP32) #include "sdkconfig.h" // this sets useful config symbols, like CONFIG_IDF_TARGET_ESP32C3 // ESP32C3 I2S is not supported yet due to significant changes to interface #if !defined(CONFIG_IDF_TARGET_ESP32C3) #include <string.h> #include <stdio.h> #include "stdlib.h" #include "freertos/FreeRTOS.h" #include "freertos/task.h" #include "freertos/semphr.h" #include "freertos/queue.h" #if ESP_IDF_VERSION_MAJOR>=4 #include "esp_intr_alloc.h" #else #include "esp_intr.h" #endif #include "soc/gpio_reg.h" #include "soc/gpio_sig_map.h" #include "soc/io_mux_reg.h" #include "soc/rtc_cntl_reg.h" #include "soc/i2s_struct.h" #if defined(CONFIG_IDF_TARGET_ESP32) /* included here for ESP-IDF v4.x compatibility */ #include "soc/dport_reg.h" #endif #include "soc/sens_reg.h" #include "driver/gpio.h" #include "driver/i2s.h" #include "driver/dac.h" #include "Esp32_i2s.h" #include "esp32-hal.h" #if ESP_IDF_VERSION_MAJOR<=4 #define I2S_BASE_CLK (160000000L) #endif #define ESP32_REG(addr) (*((volatile uint32_t*)(0x3FF00000+(addr)))) #define I2S_DMA_BLOCK_COUNT_DEFAULT 16 // 24 bytes gives us enough time if we use single stage idle // with the two stage idle we can use the minimum of 4 bytes #define I2S_DMA_SILENCE_SIZE 4*1 #define I2S_DMA_SILENCE_BLOCK_COUNT 3 // two front, one back #define I2S_DMA_QUEUE_COUNT 2 typedef struct i2s_dma_item_s { uint32_t blocksize: 12; // datalen uint32_t datalen : 12; // len*(bits_per_sample/8)*2 => max 2047*8bit/1023*16bit samples uint32_t unused : 5; // 0 uint32_t sub_sof : 1; // 0 uint32_t eof : 1; // 1 => last? uint32_t owner : 1; // 1 void* data; // malloc(datalen) struct i2s_dma_item_s* next; // if this pointer is not null, it will be freed void* free_ptr; // if DMA buffers are preallocated uint8_t* buf; } i2s_dma_item_t; typedef struct { i2s_dev_t* bus; int8_t ws; int8_t bck; int8_t out; int8_t in; uint32_t rate; intr_handle_t isr_handle; xQueueHandle tx_queue; uint8_t* silence_buf; size_t silence_len; i2s_dma_item_t* dma_items; size_t dma_count; uint32_t dma_buf_len :12; uint32_t unused :20; volatile uint32_t is_sending_data; } i2s_bus_t; // is_sending_data values #define I2s_Is_Idle 0 #define I2s_Is_Pending 1 #define I2s_Is_Sending 2 static uint8_t i2s_silence_buf[I2S_DMA_SILENCE_SIZE] = { 0 }; #if !defined(CONFIG_IDF_TARGET_ESP32S2) && !defined(CONFIG_IDF_TARGET_ESP32C3) // (I2S_NUM_MAX == 2) static i2s_bus_t I2S[I2S_NUM_MAX] = { {&I2S0, -1, -1, -1, -1, 0, NULL, NULL, i2s_silence_buf, I2S_DMA_SILENCE_SIZE, NULL, I2S_DMA_BLOCK_COUNT_DEFAULT, 0, 0, I2s_Is_Idle}, {&I2S1, -1, -1, -1, -1, 0, NULL, NULL, i2s_silence_buf, I2S_DMA_SILENCE_SIZE, NULL, I2S_DMA_BLOCK_COUNT_DEFAULT, 0, 0, I2s_Is_Idle} }; #else static i2s_bus_t I2S[I2S_NUM_MAX] = { {&I2S0, -1, -1, -1, -1, 0, NULL, NULL, i2s_silence_buf, I2S_DMA_SILENCE_SIZE, NULL, I2S_DMA_BLOCK_COUNT_DEFAULT, 0, 0, I2s_Is_Idle} }; #endif void IRAM_ATTR i2sDmaISR(void* arg); bool i2sInitDmaItems(uint8_t bus_num) { if (bus_num >= I2S_NUM_MAX) { return false; } if (I2S[bus_num].tx_queue) {// already set return true; } size_t dmaCount = I2S[bus_num].dma_count; if (I2S[bus_num].dma_items == NULL) { I2S[bus_num].dma_items = (i2s_dma_item_t*)heap_caps_malloc(dmaCount * sizeof(i2s_dma_item_t), MALLOC_CAP_DMA); if (I2S[bus_num].dma_items == NULL) { log_e("MEM ERROR!"); return false; } } int i, i2; i2s_dma_item_t* item = NULL; i2s_dma_item_t* itemPrev = NULL; for(i=0; i< dmaCount; i++) { itemPrev = item; i2 = (i+1) % dmaCount; item = &I2S[bus_num].dma_items[i]; item->eof = 0; item->owner = 1; item->sub_sof = 0; item->unused = 0; item->data = I2S[bus_num].silence_buf; item->blocksize = I2S[bus_num].silence_len; item->datalen = I2S[bus_num].silence_len; item->next = &I2S[bus_num].dma_items[i2]; item->free_ptr = NULL; item->buf = NULL; } itemPrev->eof = 1; item->eof = 1; I2S[bus_num].tx_queue = xQueueCreate(I2S_DMA_QUEUE_COUNT, sizeof(i2s_dma_item_t*)); if (I2S[bus_num].tx_queue == NULL) {// memory error log_e("MEM ERROR!"); heap_caps_free(I2S[bus_num].dma_items); I2S[bus_num].dma_items = NULL; return false; } return true; } bool i2sDeinitDmaItems(uint8_t bus_num) { if (bus_num >= I2S_NUM_MAX) { return false; } if (!I2S[bus_num].tx_queue) { return false; // nothing to deinit } vQueueDelete(I2S[bus_num].tx_queue); I2S[bus_num].tx_queue = NULL; heap_caps_free(I2S[bus_num].dma_items); I2S[bus_num].dma_items = NULL; return true; } esp_err_t i2sSetClock(uint8_t bus_num, uint8_t div_num, uint8_t div_b, uint8_t div_a, uint8_t bck, uint8_t bits) { if (bus_num >= I2S_NUM_MAX || div_a > 63 || div_b > 63 || bck > 63) { return ESP_FAIL; } i2s_dev_t* i2s = I2S[bus_num].bus; typeof(i2s->clkm_conf) clkm_conf; clkm_conf.val = 0; #if !defined(CONFIG_IDF_TARGET_ESP32S2) && !defined(CONFIG_IDF_TARGET_ESP32C3) clkm_conf.clka_en = 0; #else clkm_conf.clk_sel = 2; #endif clkm_conf.clkm_div_a = div_a; clkm_conf.clkm_div_b = div_b; clkm_conf.clkm_div_num = div_num; i2s->clkm_conf.val = clkm_conf.val; typeof(i2s->sample_rate_conf) sample_rate_conf; sample_rate_conf.val = 0; sample_rate_conf.tx_bck_div_num = bck; sample_rate_conf.rx_bck_div_num = bck; sample_rate_conf.tx_bits_mod = bits; sample_rate_conf.rx_bits_mod = bits; i2s->sample_rate_conf.val = sample_rate_conf.val; return ESP_OK; } void i2sSetPins(uint8_t bus_num, int8_t out, bool invert) { if (bus_num >= I2S_NUM_MAX) { return; } int8_t outOld = I2S[bus_num].out; I2S[bus_num].out = out; // disable old pin if (outOld >= 0) { gpio_matrix_out(outOld, 0x100, false, false); pinMode(outOld, INPUT); } if (out >= 0) { pinMode(out, OUTPUT); int i2sSignal; #if !defined(CONFIG_IDF_TARGET_ESP32S2) && !defined(CONFIG_IDF_TARGET_ESP32C3) // (I2S_NUM_MAX == 2) if (bus_num == 1) { i2sSignal = I2S1O_DATA_OUT23_IDX; } else #endif { i2sSignal = I2S0O_DATA_OUT23_IDX; } gpio_matrix_out(out, i2sSignal, invert, false); } } bool i2sWriteDone(uint8_t bus_num) { if (bus_num >= I2S_NUM_MAX) { return false; } return (I2S[bus_num].is_sending_data == I2s_Is_Idle); } void i2sInit(uint8_t bus_num, uint32_t bits_per_sample, uint32_t sample_rate, i2s_tx_chan_mod_t chan_mod, i2s_tx_fifo_mod_t fifo_mod, size_t dma_count, size_t dma_len) { if (bus_num >= I2S_NUM_MAX) { return; } I2S[bus_num].dma_count = dma_count + I2S_DMA_SILENCE_BLOCK_COUNT; // an extra two for looping silence I2S[bus_num].dma_buf_len = dma_len & 0xFFF; if (!i2sInitDmaItems(bus_num)) { return; } #if !defined(CONFIG_IDF_TARGET_ESP32S2) && !defined(CONFIG_IDF_TARGET_ESP32C3) // (I2S_NUM_MAX == 2) if (bus_num) { periph_module_enable(PERIPH_I2S1_MODULE); } else #endif { periph_module_enable(PERIPH_I2S0_MODULE); } esp_intr_disable(I2S[bus_num].isr_handle); i2s_dev_t* i2s = I2S[bus_num].bus; i2s->out_link.stop = 1; i2s->conf.tx_start = 0; i2s->int_ena.val = 0; i2s->int_clr.val = 0xFFFFFFFF; i2s->fifo_conf.dscr_en = 0; // reset fifo i2s->conf.rx_fifo_reset = 1; i2s->conf.rx_fifo_reset = 0; i2s->conf.tx_fifo_reset = 1; i2s->conf.tx_fifo_reset = 0; // reset i2s i2s->conf.tx_reset = 1; i2s->conf.tx_reset = 0; i2s->conf.rx_reset = 1; i2s->conf.rx_reset = 0; // reset dma i2s->lc_conf.in_rst = 1; i2s->lc_conf.in_rst = 0; i2s->lc_conf.out_rst = 1; i2s->lc_conf.out_rst = 0; // Enable and configure DMA typeof(i2s->lc_conf) lc_conf; lc_conf.val = 0; lc_conf.out_eof_mode = 1; i2s->lc_conf.val = lc_conf.val; #if !defined(CONFIG_IDF_TARGET_ESP32S2) && !defined(CONFIG_IDF_TARGET_ESP32C3) i2s->pdm_conf.pcm2pdm_conv_en = 0; i2s->pdm_conf.pdm2pcm_conv_en = 0; #endif // SET_PERI_REG_BITS(RTC_CNTL_CLK_CONF_REG, RTC_CNTL_SOC_CLK_SEL, 0x1, RTC_CNTL_SOC_CLK_SEL_S); typeof(i2s->conf_chan) conf_chan; conf_chan.val = 0; conf_chan.tx_chan_mod = chan_mod; // 0-two channel;1-right;2-left;3-righ;4-left conf_chan.rx_chan_mod = chan_mod; // 0-two channel;1-right;2-left;3-righ;4-left i2s->conf_chan.val = conf_chan.val; typeof(i2s->fifo_conf) fifo_conf; fifo_conf.val = 0; fifo_conf.tx_fifo_mod = fifo_mod; // 0-right&left channel;1-one channel fifo_conf.rx_fifo_mod = fifo_mod; // 0-right&left channel;1-one channel i2s->fifo_conf.val = fifo_conf.val; typeof(i2s->conf) conf; conf.val = 0; conf.tx_msb_shift = (bits_per_sample != 8);// 0:DAC/PCM, 1:I2S conf.tx_right_first = (bits_per_sample == 8); i2s->conf.val = conf.val; typeof(i2s->conf2) conf2; conf2.val = 0; conf2.lcd_en = (bits_per_sample == 8); i2s->conf2.val = conf2.val; i2s->fifo_conf.tx_fifo_mod_force_en = 1; #if !defined(CONFIG_IDF_TARGET_ESP32S2) && !defined(CONFIG_IDF_TARGET_ESP32C3) i2s->pdm_conf.rx_pdm_en = 0; i2s->pdm_conf.tx_pdm_en = 0; #endif i2sSetSampleRate(bus_num, sample_rate, bits_per_sample); // enable intr in cpu // int i2sIntSource; #if !defined(CONFIG_IDF_TARGET_ESP32S2) && !defined(CONFIG_IDF_TARGET_ESP32C3) // (I2S_NUM_MAX == 2) if (bus_num == 1) { i2sIntSource = ETS_I2S1_INTR_SOURCE; } else #endif { i2sIntSource = ETS_I2S0_INTR_SOURCE; } esp_intr_alloc(i2sIntSource, ESP_INTR_FLAG_IRAM | ESP_INTR_FLAG_LEVEL1, &i2sDmaISR, &I2S[bus_num], &I2S[bus_num].isr_handle); // enable send intr i2s->int_ena.out_eof = 1; i2s->int_ena.out_dscr_err = 1; i2s->fifo_conf.dscr_en = 1;// enable dma i2s->out_link.start = 0; i2s->out_link.addr = (uint32_t)(&I2S[bus_num].dma_items[0]); // loads dma_struct to dma i2s->out_link.start = 1; // starts dma i2s->conf.tx_start = 1;// Start I2s module esp_intr_enable(I2S[bus_num].isr_handle); } void i2sDeinit(uint8_t bus_num) { i2sDeinitDmaItems(bus_num); } esp_err_t i2sSetSampleRate(uint8_t bus_num, uint32_t rate, uint8_t bits) { if (bus_num >= I2S_NUM_MAX) { return ESP_FAIL; } if (I2S[bus_num].rate == rate) { return ESP_OK; } int clkmInteger, clkmDecimals, bck = 0; double denom = (double)1 / 63; int channel = 2; // double mclk; double clkmdiv; int factor; if (bits == 8) { factor = 120; } else { factor = (256 % bits) ? 384 : 256; } clkmdiv = (double)I2S_BASE_CLK / (rate* factor); if (clkmdiv > 256) { log_e("rate is too low"); return ESP_FAIL; } I2S[bus_num].rate = rate; clkmInteger = clkmdiv; clkmDecimals = ((clkmdiv - clkmInteger) / denom); if (bits == 8) { // mclk = rate* factor; bck = 60; bits = 16; } else { // mclk = (double)clkmInteger + (denom* clkmDecimals); bck = factor/(bits* channel); } i2sSetClock(bus_num, clkmInteger, clkmDecimals, 63, bck, bits); return ESP_OK; } void IRAM_ATTR i2sDmaISR(void* arg) { i2s_bus_t* dev = (i2s_bus_t*)(arg); if (dev->bus->int_st.out_eof) { // i2s_dma_item_t* item = (i2s_dma_item_t*)(dev->bus->out_eof_des_addr); if (dev->is_sending_data == I2s_Is_Pending) { dev->is_sending_data = I2s_Is_Idle; } else if (dev->is_sending_data == I2s_Is_Sending) { // loop the silent items i2s_dma_item_t* itemSilence = &dev->dma_items[1]; itemSilence->next = &dev->dma_items[0]; dev->is_sending_data = I2s_Is_Pending; } } dev->bus->int_clr.val = dev->bus->int_st.val; } size_t i2sWrite(uint8_t bus_num, uint8_t* data, size_t len, bool copy, bool free_when_sent) { if (bus_num >= I2S_NUM_MAX || !I2S[bus_num].tx_queue) { return 0; } size_t blockSize = len; i2s_dma_item_t* item = &I2S[bus_num].dma_items[0]; size_t dataLeft = len; uint8_t* pos = data; // skip front two silent items item += 2; while (dataLeft) { blockSize = dataLeft; if (blockSize > I2S_DMA_MAX_DATA_LEN) { blockSize = I2S_DMA_MAX_DATA_LEN; } dataLeft -= blockSize; // data is constant. no need to copy item->data = pos; item->blocksize = blockSize; item->datalen = blockSize; item++; pos += blockSize; } // reset silence item to not loop item = &I2S[bus_num].dma_items[1]; item->next = &I2S[bus_num].dma_items[2]; I2S[bus_num].is_sending_data = I2s_Is_Sending; xQueueReset(I2S[bus_num].tx_queue); xQueueSend(I2S[bus_num].tx_queue, (void*)&I2S[bus_num].dma_items[0], 10); return len; } #endif // !defined(CONFIG_IDF_TARGET_ESP32C3) #endif // defined(ARDUINO_ARCH_ESP32)
the_stack_data/105282.c
#include <stdlib.h> #include <assert.h> #include <stdio.h> typedef short int16_t; #define ARRAY_CREATE(array, init_capacity, init_size) {\ array = malloc(sizeof(*array)); \ array->data = malloc((init_capacity) * sizeof(*array->data)); \ assert(array->data != NULL); \ array->capacity = init_capacity; \ array->size = init_size; \ } #define ARRAY_PUSH(array, item) {\ if (array->size == array->capacity) { \ array->capacity *= 2; \ array->data = realloc(array->data, array->capacity * sizeof(*array->data)); \ assert(array->data != NULL); \ } \ array->data[array->size++] = item; \ } struct array_string_t { int16_t size; int16_t capacity; const char ** data; }; struct array_number_t { int16_t size; int16_t capacity; int16_t* data; }; static struct array_number_t * arr1; static int16_t i; static int16_t j; static int16_t temp; static int16_t k; static struct array_string_t * arr2; static struct array_string_t * tmp_result; static int16_t l; static int16_t m; static const char * temp_2; static int16_t n; static struct array_string_t * arr3; static struct array_string_t * tmp_result_2; static int16_t i_2; static int16_t i_3; static const char * temp_3; static int16_t i_4; int main(void) { ARRAY_CREATE(arr1, 3, 3); arr1->data[0] = 1; arr1->data[1] = 3; arr1->data[2] = 2; i = 0; j = arr1->size - 1; while (i < j) { temp = arr1->data[i]; arr1->data[i] = arr1->data[j]; arr1->data[j] = temp; i++; j--; } ; printf("[ "); for (k = 0; k < arr1->size; k++) { if (k != 0) printf(", "); printf("%d", arr1->data[k]); } printf(" ]\n"); ARRAY_CREATE(arr2, 5, 5); arr2->data[0] = "def"; arr2->data[1] = "abc"; arr2->data[2] = "aba"; arr2->data[3] = "ced"; arr2->data[4] = "meh"; l = 0; m = arr2->size - 1; while (l < m) { temp_2 = arr2->data[l]; arr2->data[l] = arr2->data[m]; arr2->data[m] = temp_2; l++; m--; } tmp_result = ((void *)arr2); printf("[ "); for (n = 0; n < tmp_result->size; n++) { if (n != 0) printf(", "); printf("\"%s\"", tmp_result->data[n]); } printf(" ]\n"); ARRAY_CREATE(arr3, 2, 2); arr3->data[0] = "abc"; arr3->data[1] = "def"; i_2 = 0; i_3 = arr3->size - 1; while (i_2 < i_3) { temp_3 = arr3->data[i_2]; arr3->data[i_2] = arr3->data[i_3]; arr3->data[i_3] = temp_3; i_2++; i_3--; } tmp_result_2 = ((void *)arr3); printf("[ "); for (i_4 = 0; i_4 < tmp_result_2->size; i_4++) { if (i_4 != 0) printf(", "); printf("\"%s\"", tmp_result_2->data[i_4]); } printf(" ]\n"); free(arr1->data); free(arr1); free(arr2->data); free(arr2); free(arr3->data); free(arr3); return 0; }
the_stack_data/85837.c
#include <stdio.h> int main() { int num=3, k=4; for (int i = 1; i <= k; i++) { for (int j = 0; j < i; j++) { printf("%d", num); } printf("\n"); num++; } num--; for (int i = k; i > 0; i--) { for (int j = 0; j < i; j++) { printf("%d", num); } printf("\n"); num--; } return 0; }
the_stack_data/837518.c
//***************************************************************************** // // startup_gcc.c - Startup code for use with GNU tools. // // Copyright (c) 2008-2013 Texas Instruments Incorporated. All rights reserved. // Software License Agreement // // Texas Instruments (TI) is supplying this software for use solely and // exclusively on TI's microcontroller products. The software is owned by // TI and/or its suppliers, and is protected under applicable copyright // laws. You may not combine this software with "viral" open-source // software in order to form a larger program. // // THIS SOFTWARE IS PROVIDED "AS IS" AND WITH ALL FAULTS. // NO WARRANTIES, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING, BUT // NOT LIMITED TO, IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE APPLY TO THIS SOFTWARE. TI SHALL NOT, UNDER ANY // CIRCUMSTANCES, BE LIABLE FOR SPECIAL, INCIDENTAL, OR CONSEQUENTIAL // DAMAGES, FOR ANY REASON WHATSOEVER. // // This is part of revision 10636 of the RDK-IDM-L35 Firmware Package. // //***************************************************************************** //***************************************************************************** // // Forward declaration of the default fault handlers. // //***************************************************************************** void ResetISR(void); static void NmiSR(void); static void FaultISR(void); static void IntDefaultHandler(void); //***************************************************************************** // // External declarations for the interrupt handlers used by the application. // //***************************************************************************** extern void TouchScreenIntHandler(void); extern void SysTickIntHandler(void); extern void SoundIntHandler(void); extern void UARTStdioIntHandler(void); //***************************************************************************** // // The entry point for the application. // //***************************************************************************** extern int main(void); //***************************************************************************** // // Reserve space for the system stack. // //***************************************************************************** static unsigned long pulStack[384]; //***************************************************************************** // // The vector table. Note that the proper constructs must be placed on this to // ensure that it ends up at physical address 0x0000.0000. // //***************************************************************************** __attribute__ ((section(".isr_vector"))) void (* const g_pfnVectors[])(void) = { (void (*)(void))((unsigned long)pulStack + sizeof(pulStack)), // The initial stack pointer ResetISR, // The reset handler NmiSR, // The NMI handler FaultISR, // The hard fault handler IntDefaultHandler, // The MPU fault handler IntDefaultHandler, // The bus fault handler IntDefaultHandler, // The usage fault handler 0, // Reserved 0, // Reserved 0, // Reserved 0, // Reserved IntDefaultHandler, // SVCall handler IntDefaultHandler, // Debug monitor handler 0, // Reserved IntDefaultHandler, // The PendSV handler SysTickIntHandler, // The SysTick handler IntDefaultHandler, // GPIO Port A IntDefaultHandler, // GPIO Port B IntDefaultHandler, // GPIO Port C IntDefaultHandler, // GPIO Port D IntDefaultHandler, // GPIO Port E UARTStdioIntHandler, // UART0 Rx and Tx IntDefaultHandler, // UART1 Rx and Tx IntDefaultHandler, // SSI0 Rx and Tx IntDefaultHandler, // I2C0 Master and Slave IntDefaultHandler, // PWM Fault IntDefaultHandler, // PWM Generator 0 IntDefaultHandler, // PWM Generator 1 IntDefaultHandler, // PWM Generator 2 IntDefaultHandler, // Quadrature Encoder 0 IntDefaultHandler, // ADC Sequence 0 IntDefaultHandler, // ADC Sequence 1 IntDefaultHandler, // ADC Sequence 2 TouchScreenIntHandler, // ADC Sequence 3 IntDefaultHandler, // Watchdog timer IntDefaultHandler, // Timer 0 subtimer A IntDefaultHandler, // Timer 0 subtimer B IntDefaultHandler, // Timer 1 subtimer A IntDefaultHandler, // Timer 1 subtimer B IntDefaultHandler, // Timer 2 subtimer A SoundIntHandler, // Timer 2 subtimer B IntDefaultHandler, // Analog Comparator 0 IntDefaultHandler, // Analog Comparator 1 IntDefaultHandler, // Analog Comparator 2 IntDefaultHandler, // System Control (PLL, OSC, BO) IntDefaultHandler, // FLASH Control IntDefaultHandler, // GPIO Port F IntDefaultHandler, // GPIO Port G IntDefaultHandler, // GPIO Port H IntDefaultHandler, // UART2 Rx and Tx IntDefaultHandler, // SSI1 Rx and Tx IntDefaultHandler, // Timer 3 subtimer A IntDefaultHandler, // Timer 3 subtimer B IntDefaultHandler, // I2C1 Master and Slave IntDefaultHandler, // Quadrature Encoder 1 IntDefaultHandler, // CAN0 IntDefaultHandler, // CAN1 IntDefaultHandler, // CAN2 IntDefaultHandler, // Ethernet IntDefaultHandler // Hibernate }; //***************************************************************************** // // The following are constructs created by the linker, indicating where the // the "data" and "bss" segments reside in memory. The initializers for the // for the "data" segment resides immediately following the "text" segment. // //***************************************************************************** extern unsigned long _etext; extern unsigned long _data; extern unsigned long _edata; extern unsigned long _bss; extern unsigned long _ebss; //***************************************************************************** // // This is the code that gets called when the processor first starts execution // following a reset event. Only the absolutely necessary set is performed, // after which the application supplied entry() routine is called. Any fancy // actions (such as making decisions based on the reset cause register, and // resetting the bits in that register) are left solely in the hands of the // application. // //***************************************************************************** void ResetISR(void) { unsigned long *pulSrc, *pulDest; // // Copy the data segment initializers from flash to SRAM. // pulSrc = &_etext; for(pulDest = &_data; pulDest < &_edata; ) { *pulDest++ = *pulSrc++; } // // Zero fill the bss segment. // __asm(" ldr r0, =_bss\n" " ldr r1, =_ebss\n" " mov r2, #0\n" " .thumb_func\n" "zero_loop:\n" " cmp r0, r1\n" " it lt\n" " strlt r2, [r0], #4\n" " blt zero_loop"); // // Call the application's entry point. // main(); } //***************************************************************************** // // This is the code that gets called when the processor receives a NMI. This // simply enters an infinite loop, preserving the system state for examination // by a debugger. // //***************************************************************************** static void NmiSR(void) { // // Enter an infinite loop. // while(1) { } } //***************************************************************************** // // This is the code that gets called when the processor receives a fault // interrupt. This simply enters an infinite loop, preserving the system state // for examination by a debugger. // //***************************************************************************** static void FaultISR(void) { // // Enter an infinite loop. // while(1) { } } //***************************************************************************** // // This is the code that gets called when the processor receives an unexpected // interrupt. This simply enters an infinite loop, preserving the system state // for examination by a debugger. // //***************************************************************************** static void IntDefaultHandler(void) { // // Go into an infinite loop. // while(1) { } }
the_stack_data/231392092.c
#include <stdio.h> #include <stdlib.h> #include <string.h> #define MAX 201 typedef struct { char letter; int count; } pair_t; int findIndexOfLetterInCounter(const char letter, const pair_t *counter); int resetCounter(pair_t *counter, const int length); int sortCounter(const void *a, const void *b); int sortStr(const void *a, const void *b); int main() { int cases; scanf("%d", &cases); getchar(); char string[MAX]; pair_t counter[MAX]; while (cases--) { resetCounter(counter, MAX); int nextPushIndex = 0; scanf("%[^\n]s", string); getchar(); const int length = strlen(string); for (int i = 0; i < length; i++) { if (string[i] >= 'A' && string[i] <= 'Z') { string[i] = string[i] + 32; } } for (int i = 0; i < length; i++) { if (string[i] >= 'a' && string[i] <= 'z') { const int indexOf = findIndexOfLetterInCounter(string[i], counter); if (indexOf == -1) { counter[nextPushIndex].letter = string[i]; counter[nextPushIndex].count = 1; nextPushIndex++; } else { counter[indexOf].count++; } } } qsort(counter, MAX, sizeof(pair_t), sortCounter); int maxCount = counter[0].count; char maxLetters[nextPushIndex]; int nextMaxLetter = 0; for (int i = 0; i < nextPushIndex; i++) { if (counter[i].count > maxCount) { maxCount = counter[i].count; } } for (int i = 0; i < nextPushIndex; i++) { if (counter[i].count == maxCount) { maxLetters[nextMaxLetter++] = counter[i].letter; } } maxLetters[nextMaxLetter] = '\0'; char temp; for (int i = 0; i < nextMaxLetter; ++i) { for (int j = i + 1; j < nextMaxLetter; ++j) { if (maxLetters[i] > maxLetters[j]) { temp = maxLetters[i]; maxLetters[i] = maxLetters[j]; maxLetters[j] = temp; } } } puts(maxLetters); } return 0; } int findIndexOfLetterInCounter(const char letter, const pair_t *counter) { for (int i = 0; i < MAX; i++) { if (counter[i].letter == letter) { return i; } } return -1; } int resetCounter(pair_t *counter, const int length) { for (int i = 0; i < length; i++) { counter[i].letter = 0; counter[i].count = 0; } } int sortCounter(const void *a, const void *b) { return ((pair_t *)b)->count - ((pair_t *)a)->count; }
the_stack_data/57949997.c
#include<stdio.h> #include<time.h> #include<pthread.h> #define MAX_PRODUCTION2_NUM 512 #define MAX_PRODUCTION1_NUM 128 #define MAX_VN_NUM 128 #define MAX_VT_NUM 128 #define MAX_STRING_LENGTH 1024 #define THREAD_NUM 31 pthread_mutex_t public_mutex; pthread_cond_t public_cond; int end_thread = 0; typedef struct VnProduction { int parent, child1, child2; } VnProduction; typedef struct VtProduction { int parent; char child; } VtProduction; int vnProductions_cnt, vtProductions_cnt; unsigned dp[MAX_STRING_LENGTH * MAX_STRING_LENGTH * MAX_VN_NUM]; VtProduction vtProductions[MAX_PRODUCTION1_NUM]; VnProduction vnProductions[MAX_PRODUCTION2_NUM]; int slen; char solve[MAX_STRING_LENGTH]; int vnNum; void *task(void *args); void input() { freopen("input.txt", "r", stdin); scanf("%d\n", &vnNum); scanf("%d\n", &vnProductions_cnt); for (int i = 0; i < vnProductions_cnt; i++) scanf("<%d>::=<%d><%d>\n", &vnProductions[i].parent, &vnProductions[i].child1, &vnProductions[i].child2); scanf("%d\n", &vtProductions_cnt); for (int i = 0; i < vtProductions_cnt; i++) scanf("<%d>::=%c\n", &vtProductions[i].parent, &vtProductions[i].child); scanf("%d\n", &slen); scanf("%s\n", solve); } int main() { //clock_t start, end; //start = clock(); input(); for (int i = 0; i < slen; i++) { char c = solve[i]; int tmpIndex = i * slen * vnProductions_cnt + i * vnNum; for (int vt_index = 0; vt_index < vtProductions_cnt; vt_index++) { VtProduction tmp = vtProductions[vt_index]; if (c == tmp.child) dp[tmpIndex + tmp.parent]++; } } pthread_mutex_init(&public_mutex, NULL); pthread_cond_init(&public_cond, NULL); pthread_t handlers[THREAD_NUM]; for (int thread_index = 0; thread_index < THREAD_NUM; thread_index++) { pthread_create(&handlers[thread_index], NULL, task, (void *)thread_index); } for (int thread_index = 0; thread_index < THREAD_NUM; thread_index++) { pthread_join(handlers[thread_index], NULL); } printf("%u\n", dp[(slen - 1) * vnNum]); //end = clock(); //printf("%lfms\n", (double)(end - start)); return 0; } void *task(void *args) { int tid = (long long) args; for (int len = 2; len <= slen; len++) { for (int left = tid; left <= slen - len; left += THREAD_NUM) { for (int right = left + 1; right < left + len; right++) { int all = left * slen * vnNum + (left + len - 1) * vnNum; int leftPart = left * slen * vnNum + (right - 1) * vnNum; int rightPart = right * slen * vnNum + (left + len - 1) * vnNum; for (int vn_index = 0; vn_index < vnProductions_cnt; vn_index++) { VnProduction tmp = vnProductions[vn_index]; dp[all + tmp.parent] += dp[leftPart + tmp.child1] * dp[rightPart + tmp.child2]; } } } pthread_mutex_lock(&public_mutex); end_thread++; if (end_thread != THREAD_NUM) { pthread_cond_wait(&public_cond, &public_mutex); } else { end_thread = 0; pthread_cond_broadcast(&public_cond); } pthread_mutex_unlock(&public_mutex); } return NULL; }
the_stack_data/90764352.c
#include <stdio.h> #include <stdlib.h> #define CMP_LT(a, b) ((a) < (b)) #define CMP_GT(a, b) ((a) > (b)) typedef struct node { struct node *left, *right, *parent; int key; } Node; typedef struct { int size; Node *root; } Tree; typedef struct nqueue { struct nqueue *next; struct nqueue *prev; Node *cursor; } nQueue; typedef struct queue { nQueue *frnt; nQueue *rear; int size; } Queue; int qIsEmpty(Queue *q) { if (q->rear < q->frnt) return 1; else return 0; } void destroyQueue(Queue *q) { if (!qIsEmpty(q)) { if (q->frnt == NULL) exit(0); nQueue *tmp, *tq; tmp = q->frnt; while(tmp != NULL) { tq = tmp; tmp = tq->next; free(tq); } q->frnt = q->rear = NULL; } } int putToQueue(Queue *q, Node *n) { nQueue *temp = malloc(sizeof(nQueue)); temp->cursor = n; temp->next = NULL; if (q->frnt != NULL) q->rear->next = temp; else q->frnt = temp; q->rear = temp; q->size++; return 0; } Node* pop (Queue *q) { if (q->frnt != NULL) { nQueue *ntmp = q->frnt; Node *buf = q->frnt->cursor; q->frnt = q->frnt->next; if (q->frnt == NULL) q->rear = NULL; free(ntmp); q->size--; return buf; } else return NULL; } void init(Tree* t) { t->root = NULL; t->size = 0; } Node* getFreeNode(int key, Node *parent) { Node *tmp = (Node*)malloc(sizeof(Node)); tmp->left = tmp->right = NULL; tmp->key = key; tmp->parent = parent; return tmp; } int insert(Tree *t, int key) { Node *tmp = NULL; if (t->root == NULL) { t->root = getFreeNode(key, NULL); if (t->root == NULL) return 2; t->size++; } tmp = t->root; while (tmp) { if (CMP_GT(key, tmp->key)) { if (tmp->right) { tmp = tmp->right; continue; } else { tmp->right = getFreeNode(key, tmp); t->size++; return 0; } } else if (CMP_LT(key, tmp->key)) { if (tmp->left) { tmp = tmp->left; continue; } else { tmp->left = getFreeNode(key, tmp); t->size++; return 0; } } else { return 1; } } } void breadthFirst(Tree *t) { if (t == NULL) return; Queue *q = (Queue*)malloc(sizeof(Queue*)); q->frnt = q->rear = NULL; Node *n = t->root; putToQueue(q, n); while (q->size != 0) { n = pop(q); printf("%d ", n->key); if (n->left) putToQueue(q, n->left); if (n->right) putToQueue (q, n->right); } printf("\n"); destroyQueue(q); } int main(int argc, char const *argv[]) { Tree *tree; init(tree); int a; for (int i = 0; i < 7; i++) { scanf("%d", &a); insert(tree, a); } breadthFirst(tree); return 0; }
the_stack_data/48574051.c
// Author: Farmer Li ([email protected]) #include <stdbool.h> #include <stdio.h> #include <string.h> bool is_match_back_tracking(const char *s, const char *p) { int m = (int) strlen(s); int n = (int) strlen(p); if (n == 0) return m == 0; int k = 0; int last_k = -1; int i = 0; int last_i = 0; while (i < m) { if (*(p + k) == *(s + i) || *(p + k) == '?') { ++k; ++i; } else if (*(p + k) == '*' && k < n) { last_k = k; last_i = i; ++k; // Match nothing for first } else if (last_k != -1) { // If mismatch, and the last matching character is '*', then let it match one more character. k = last_k + 1; ++last_i; i = last_i; } else { return false; } } while (k < n && *(p + k) == '*') { ++k; } return k >= n; } bool is_match_recursively(const char *s, const char *p) { int m = (int) strlen(s); int n = (int) strlen(p); if (n == 0) return m == 0; bool match = m > 0 && (*s == *p || *p == '.' || *p == '*'); if (*p == '*') { return is_match_recursively(s, p + 1) || (match && is_match_recursively(s + 1, p)); } else { return match && is_match_recursively(s + 1, p + 1); } } bool is_match_dp(const char *s, const char *p) { int m = (int) strlen(s); int n = (int) strlen(p); int dp[m + 1][n + 1]; dp[m][n] = true; for (int i = 0; i < m; ++i) { dp[i][n] = false; } for (int i = m; i >= 0; --i) { for (int j = n - 1; j >= 0; --j) { char cp = *(p + j); // When i == m, match is always False, because (s + i) is an empty string. // So we don't need to worry about the (i + 1) will be out of bounds. bool match = i < m && (cp == *(s + i) || cp == '?' || cp == '*'); if (cp == '*') { dp[i][j] = dp[i][j + 1] || (match && dp[i + 1][j]); } else { dp[i][j] = (match && dp[i + 1][j + 1]); } } } for (int i = 0; i <= m; ++i) { for (int j = 0; j <= n; ++j) { printf("%d ", dp[i][j]); } printf("\n"); } return dp[0][0]; } int main(void) { printf("Testing wildcard matching:\n"); char *text = "ba"; char *pattern = "*ba"; bool match = is_match_back_tracking(text, pattern); printf("Pattern \"%s\" match the string: \"%s\" ? %s\n", pattern, text, match ? "True" : "False"); }
the_stack_data/333856.c
// Leia um valor de massa em quilogramas e apresente-o convertido em libras // Ivo Dias // Bibliotecas # include <stdio.h> # include <stdlib.h> int main() { // Define as variaveis float KG, Libras; // Recebe o numero printf("Informe o valor em KG: "); scanf("%f",&KG); // Faz a conta Libras = (KG/0.45); // Mostra o resultado printf("O valor em Libras eh de: %.2f \n", Libras); // Pausa para mostrar na tela system ("pause"); }
the_stack_data/906367.c
/* NOCW */ /* demos/bio/saccept.c */ /* A minimal program to server an SSL connection. * It uses blocking. * saccept host:port * host is the interface IP to use. If any interface, use *:port * The default it *:4433 * * cc -I../../include saccept.c -L../.. -lssl -lcrypto */ #include <stdio.h> #include <signal.h> #include <openssl/err.h> #include <openssl/ssl.h> #define CERT_FILE "server.pem" BIO *in=NULL; void close_up() { if (in != NULL) BIO_free(in); } int main(argc,argv) int argc; char *argv[]; { char *port=NULL; BIO *ssl_bio,*tmp; SSL_CTX *ctx; SSL *ssl; char buf[512]; int ret=1,i; if (argc <= 1) port="*:4433"; else port=argv[1]; signal(SIGINT,close_up); SSL_load_error_strings(); #ifdef WATT32 dbug_init(); sock_init(); #endif /* Add ciphers and message digests */ OpenSSL_add_ssl_algorithms(); ctx=SSL_CTX_new(SSLv23_server_method()); if (!SSL_CTX_use_certificate_file(ctx,CERT_FILE,SSL_FILETYPE_PEM)) goto err; if (!SSL_CTX_use_PrivateKey_file(ctx,CERT_FILE,SSL_FILETYPE_PEM)) goto err; if (!SSL_CTX_check_private_key(ctx)) goto err; /* Setup server side SSL bio */ ssl=SSL_new(ctx); ssl_bio=BIO_new_ssl(ctx,0); if ((in=BIO_new_accept(port)) == NULL) goto err; /* This means that when a new connection is acceptede on 'in', * The ssl_bio will be 'dupilcated' and have the new socket * BIO push into it. Basically it means the SSL BIO will be * automatically setup */ BIO_set_accept_bios(in,ssl_bio); again: /* The first call will setup the accept socket, and the second * will get a socket. In this loop, the first actual accept * will occur in the BIO_read() function. */ if (BIO_do_accept(in) <= 0) goto err; for (;;) { i=BIO_read(in,buf,512); if (i == 0) { /* If we have finished, remove the underlying * BIO stack so the next time we call any function * for this BIO, it will attempt to do an * accept */ printf("Done\n"); tmp=BIO_pop(in); BIO_free_all(tmp); goto again; } if (i < 0) goto err; fwrite(buf,1,i,stdout); fflush(stdout); } ret=0; err: if (ret) { ERR_print_errors_fp(stderr); } if (in != NULL) BIO_free(in); exit(ret); return(!ret); }
the_stack_data/35139.c
#include <sys/socket.h> #include <sys/time.h> #include <errno.h> #include "syscall.h" #define IS32BIT(x) !((x)+0x80000000ULL>>32) #define CLAMP(x) (int)(IS32BIT(x) ? (x) : 0x7fffffffU+((0ULL+(x))>>63)) int setsockopt(int fd, int level, int optname, const void *optval, socklen_t optlen) { const struct timeval *tv; time_t s; suseconds_t us; int r = __socketcall(setsockopt, fd, level, optname, optval, optlen, 0); if (r==-ENOPROTOOPT) switch (level) { case SOL_SOCKET: switch (optname) { case SO_RCVTIMEO: case SO_SNDTIMEO: if (SO_RCVTIMEO == SO_RCVTIMEO_OLD) break; if (optlen < sizeof *tv) return __syscall_ret(-EINVAL); tv = optval; s = tv->tv_sec; us = tv->tv_usec; if (!IS32BIT(s)) return __syscall_ret(-ENOTSUP); if (optname==SO_RCVTIMEO) optname=SO_RCVTIMEO_OLD; if (optname==SO_SNDTIMEO) optname=SO_SNDTIMEO_OLD; r = __socketcall(setsockopt, fd, level, optname, ((long[]){s, CLAMP(us)}), 2*sizeof(long), 0); } } return __syscall_ret(r); }
the_stack_data/921421.c
#include <stdio.h> void do_call(void (*puts)(const char *), const char *str); void do_print(const char *str) { if (!str) do_call(NULL, "delusion"); if ((int)str == -1) do_print(str + 10); puts("===="); puts(str); puts("===="); } void do_call(void (*puts)(const char *), const char *str) { if (!str) do_print("confusion"); if ((int)str == -1) do_call(NULL, str - 10); (*puts)(str); } int main(int argc, char **argv) { for (int i = 0; i < argc; i++) { do_call(i != 10 ? do_print : NULL, i != 15 ? "waka waka" : NULL); } return 0; }
the_stack_data/159514192.c
// gcc urlparse.c -o urlparse -Wl,-s,-z,relro,-z,now -fPIE -pie #include <ctype.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #define min(a, b) \ ({ __typeof__ (a) _a = (a); \ __typeof__ (b) _b = (b); \ _a < _b ? _a : _b; }) struct URLList { struct URLList *next; char url[]; }; struct URLList *g_head; unsigned int total_size = 0; char g_buf[0x100000]; void print_logo() { puts(""); puts(" # # #### ##### ######"); puts(" # # # # # #"); puts("### ### # # #####"); puts(" # # # # #"); puts(" # # # # # #"); puts(" #### # #"); puts(""); } static inline bool is_hex(char c) { return ((c >= '0') && (c <= '9')) || ((c >= 'a') && (c <= 'f')) || ((c >= 'A') && (c <= 'F')); } static inline char to_hex(unsigned char c) { if (c <= 9) { return c + '0'; } if (c < 16) { return c - 10 + 'A'; } exit(0); } char *url_encode(char *text) { char *cp, *xp; unsigned int size; for (cp = text, xp = g_buf; *cp; cp++) { *(xp++) = '%'; *(xp++) = to_hex(*cp / 16); *(xp++) = to_hex(*cp % 16); } strncpy(text, g_buf, strlen(text)); return text; } char *url_decode(char *text) { char *cp, *xp; for (cp = text, xp = text; *cp; cp++) { if (*cp == '%') { if (is_hex(*(cp + 1)) && is_hex(*(cp + 2))) { if (islower(*(cp + 1))) *(cp + 1) = toupper(*(cp + 1)); if (islower(*(cp + 2))) *(cp + 2) = toupper(*(cp + 2)); *(xp) = (*(cp + 1) >= 'A' ? *(cp + 1) - 'A' + 10 : *(cp + 1) - '0') * 16 + (*(cp + 2) >= 'A' ? *(cp + 2) - 'A' + 10 : *(cp + 2) - '0'); xp++; } cp += 2; } else { *(xp++) = *cp; } } xp = min(xp, text + strlen(text)); memset(xp, 0, cp - xp); return text; } void print_menu(void) { puts("===== Menu ====="); puts("1: create url"); puts("2: encode url"); puts("3: decode url"); puts("4: list urls"); puts("5: delete url"); puts("6: exit"); puts("================\n"); } int get_integer(void) { int ret = 0; char buf[16]; fgets(buf, sizeof(buf), stdin); sscanf(buf, "%d", &ret); return ret; } void create_url(void) { unsigned int size; struct URLList *node; printf("size: "); size = get_integer(); if (size + sizeof(struct URLList) < size) { puts("Error: invalid size"); exit(0); } if (size < 0x80) { puts("Error: too small"); exit(0); } if (size > 0x11111) { puts("Error: too large"); exit(0); } total_size += size; if (total_size > 222222) { puts("Error: too large (total)"); exit(0); } node = malloc(sizeof(struct URLList) + size); if (!node) { puts("Error: malloc failed"); exit(0); } printf("URL: "); memset(g_buf, 0, sizeof(g_buf)); fgets(g_buf, size, stdin); url_decode(g_buf); if (strlen(g_buf) > 0x400) { printf("As we need to pay for the data volume, we refuse long input!"); exit(-1); } size = min(size - 1, strlen(g_buf)); strncpy(node->url, g_buf, size); node->url[size] = '\0'; node->next = g_head; g_head = node; } void encode_url(void) { int idx; printf("index: "); idx = get_integer(); struct URLList *node = g_head; while (idx--) { if (node == NULL) break; node = node->next; } if (node == NULL) { puts("Error: no such url"); exit(0); } url_encode(node->url); } void decode_url(void) { int idx; printf("index: "); idx = get_integer(); struct URLList *node = g_head; while (idx--) { if (node == NULL) break; node = node->next; } if (node == NULL) { puts("Error: no such url"); exit(0); } url_decode(node->url); } void list_urls(void) { int idx = 0; struct URLList *node = g_head; puts("LIST START"); while (node) { printf("%d: %s\n", idx, node->url); node = node->next; idx++; } puts("LIST END"); } void delete_url(void) { int idx; printf("index: "); idx = get_integer(); struct URLList *prev = NULL; struct URLList *node = g_head; while (idx--) { if (node == NULL) break; prev = node; node = node->next; } if (node == NULL) { puts("Error: no such url"); exit(0); } if (prev == NULL) { g_head = node->next; } else { prev->next = node->next; } free(node); } int main() { setbuf(stdin, NULL); setbuf(stdout, NULL); print_logo(); while (1) { int cmd; print_menu(); printf("> "); cmd = get_integer(); if (cmd == 1) { create_url(); } else if (cmd == 2) { encode_url(); } else if (cmd == 3) { decode_url(); } else if (cmd == 4) { list_urls(); } else if (cmd == 5) { delete_url(); } else if (cmd == 6) { exit(0); } else { puts("Error: undefined command"); } } return 0; }
the_stack_data/275527.c
#include <stdio.h> int main(void) { long long int n; int n_test_cases; scanf("%i", &n_test_cases); for(int i = 0; i < n_test_cases; i++){ scanf("%lli", &n); printf("%lli\n", ((n*(3*n + 1)/2) % 1000007)); } return 0; }
the_stack_data/252261.c
// RUN: %cml %s -o %t && %t | FileCheck %s #include <stdio.h> enum ENUM { A, B, C, D }; int main() { enum ENUM E; E = C; if (E == A) printf ("A\n"); else if (E == B) printf ("B\n"); else if (E == C) // CHECK: C printf ("C\n"); else if (E == D) printf ("D\n"); else printf ("Unknown\n"); return 0; }
the_stack_data/243892094.c
#define _GNU_SOURCE #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <signal.h> #include <assert.h> #include <pthread.h> void handler(int signo) { switch (signo) { case SIGUSR1: break; case SIGABRT: break; default: break; } abort(); } void *thread(void *a) { usleep(1000*1000); return 0; } int main(int argc, char **argv) { pthread_t pt; setbuf(stdout, NULL); printf("expecting signal stack overflow to segfault...\n"); pid_t pid = getpid(); pthread_create(&pt, NULL, thread, 0); assert(signal(SIGUSR1, handler) != SIG_ERR); assert(signal(SIGABRT, handler) != SIG_ERR); kill(pid, SIGUSR1); pthread_join(pt, 0); return 0; }
the_stack_data/885145.c
/* $NetBSD: goodaout.c,v 1.8 2003/07/26 19:38:49 salo Exp $ */ /*- * Copyright (c) 1993 Christopher G. Demetriou * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * This product includes software developed for the * NetBSD Project. See http://www.NetBSD.org/ for * information about NetBSD. * 4. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * $FreeBSD: soc2013/dpl/head/tools/regression/execve/tests/goodaout.c 159140 2006-05-31 11:13:10Z maxim $ */ #include <stdio.h> #include <stdlib.h> int main(argc, argv) int argc; char *argv[]; { printf("succeeded\n"); exit(0); }
the_stack_data/419548.c
void fun2(void); int main(void) { fun2(); return 0; }