file
stringlengths 18
26
| data
stringlengths 3
1.04M
|
---|---|
the_stack_data/7951386.c | // RUN: %clang -target x86_64-linux-gnu -fsanitize=undefined -fsanitize-trap=undefined %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-UNDEFINED-TRAP
// RUN: %clang -target x86_64-linux-gnu -fsanitize=undefined -fsanitize-trap=undefined -fno-sanitize-trap=signed-integer-overflow %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-UNDEFINED-TRAP2
// RUN: %clang -target x86_64-linux-gnu -fsanitize=undefined -fsanitize-undefined-trap-on-error %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-UNDEFINED-TRAP
// RUN: %clang -target x86_64-linux-gnu -fsanitize=undefined-trap -fsanitize-undefined-trap-on-error %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-UNDEFINED-TRAP
// RUN: %clang -target x86_64-linux-gnu -fsanitize-undefined-trap-on-error -fsanitize=undefined-trap %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-UNDEFINED-TRAP
// CHECK-UNDEFINED-TRAP: "-fsanitize={{((signed-integer-overflow|integer-divide-by-zero|float-divide-by-zero|shift-base|shift-exponent|unreachable|return|vla-bound|alignment|null|object-size|float-cast-overflow|array-bounds|enum|bool|returns-nonnull-attribute|nonnull-attribute|function),?){18}"}}
// CHECK-UNDEFINED-TRAP: "-fsanitize-trap=alignment,array-bounds,bool,enum,float-cast-overflow,float-divide-by-zero,function,integer-divide-by-zero,nonnull-attribute,null,object-size,return,returns-nonnull-attribute,shift-base,shift-exponent,signed-integer-overflow,unreachable,vla-bound"
// CHECK-UNDEFINED-TRAP2: "-fsanitize-trap=alignment,array-bounds,bool,enum,float-cast-overflow,float-divide-by-zero,function,integer-divide-by-zero,nonnull-attribute,null,object-size,return,returns-nonnull-attribute,shift-base,shift-exponent,unreachable,vla-bound"
// RUN: %clang -target x86_64-linux-gnu -fsanitize=undefined %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-UNDEFINED
// CHECK-UNDEFINED: "-fsanitize={{((signed-integer-overflow|integer-divide-by-zero|float-divide-by-zero|function|shift-base|shift-exponent|unreachable|return|vla-bound|alignment|null|vptr|object-size|float-cast-overflow|array-bounds|enum|bool|returns-nonnull-attribute|nonnull-attribute),?){19}"}}
// RUN: %clang -target x86_64-apple-darwin10 -fsanitize=undefined %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-UNDEFINED-DARWIN
// CHECK-UNDEFINED-DARWIN: "-fsanitize={{((signed-integer-overflow|integer-divide-by-zero|float-divide-by-zero|shift-base|shift-exponent|unreachable|return|vla-bound|alignment|null|object-size|float-cast-overflow|array-bounds|enum|bool|returns-nonnull-attribute|nonnull-attribute),?){17}"}}
// RUN: %clang -target i386-unknown-openbsd -fsanitize=undefined %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-UNDEFINED-OPENBSD
// CHECK-UNDEFINED-OPENBSD: "-fsanitize={{((signed-integer-overflow|integer-divide-by-zero|float-divide-by-zero|shift-base|shift-exponent|unreachable|return|vla-bound|alignment|null|object-size|float-cast-overflow|array-bounds|enum|bool|returns-nonnull-attribute|nonnull-attribute),?){17}"}}
// RUN: %clang -target i386-pc-win32 -fsanitize=undefined %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-UNDEFINED-WIN --check-prefix=CHECK-UNDEFINED-WIN32
// RUN: %clang -target i386-pc-win32 -fsanitize=undefined -x c++ %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-UNDEFINED-WIN --check-prefix=CHECK-UNDEFINED-WIN32 --check-prefix=CHECK-UNDEFINED-WIN-CXX
// RUN: %clang -target x86_64-pc-win32 -fsanitize=undefined %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-UNDEFINED-WIN --check-prefix=CHECK-UNDEFINED-WIN64
// RUN: %clang -target x86_64-pc-win32 -fsanitize=undefined -x c++ %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-UNDEFINED-WIN --check-prefix=CHECK-UNDEFINED-WIN64 --check-prefix=CHECK-UNDEFINED-WIN-CXX
// CHECK-UNDEFINED-WIN: "-fsanitize={{((signed-integer-overflow|integer-divide-by-zero|float-divide-by-zero|shift-base|shift-exponent|unreachable|return|vla-bound|alignment|null|object-size|float-cast-overflow|array-bounds|enum|bool|returns-nonnull-attribute|nonnull-attribute),?){17}"}}
// CHECK-UNDEFINED-WIN32-SAME: "--dependent-lib={{[^"]*}}ubsan_standalone-i386.lib"
// CHECK-UNDEFINED-WIN64-SAME: "--dependent-lib={{[^"]*}}ubsan_standalone-x86_64.lib"
// CHECK-UNDEFINED-WIN-CXX-SAME: "--dependent-lib={{[^"]*}}ubsan_standalone_cxx{{[^"]*}}.lib"
// RUN: %clang -target x86_64-linux-gnu -fsanitize=integer %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-INTEGER
// CHECK-INTEGER: "-fsanitize={{((signed-integer-overflow|unsigned-integer-overflow|integer-divide-by-zero|shift-base|shift-exponent),?){5}"}}
// RUN: %clang -fsanitize=bounds -### -fsyntax-only %s 2>&1 | FileCheck %s --check-prefix=CHECK-BOUNDS
// CHECK-BOUNDS: "-fsanitize={{((array-bounds|local-bounds),?){2}"}}
// RUN: %clang -target x86_64-linux-gnu -fsanitize=all %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-FSANITIZE-ALL
// CHECK-FSANITIZE-ALL: error: unsupported argument 'all' to option 'fsanitize='
// RUN: %clang -target x86_64-linux-gnu -fsanitize=address,undefined -fno-sanitize=all -fsanitize=thread %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-FNO-SANITIZE-ALL
// CHECK-FNO-SANITIZE-ALL: "-fsanitize=thread"
// RUN: %clang -target x86_64-linux-gnu -fsanitize=thread,undefined -fno-sanitize=thread -fno-sanitize=float-cast-overflow,vptr,bool,enum %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-PARTIAL-UNDEFINED
// CHECK-PARTIAL-UNDEFINED: "-fsanitize={{((signed-integer-overflow|integer-divide-by-zero|float-divide-by-zero|function|shift-base|shift-exponent|unreachable|return|vla-bound|alignment|null|object-size|array-bounds|returns-nonnull-attribute|nonnull-attribute),?){15}"}}
// RUN: %clang -target x86_64-linux-gnu -fsanitize=shift -fno-sanitize=shift-base %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-FSANITIZE-SHIFT-PARTIAL
// CHECK-FSANITIZE-SHIFT-PARTIAL: "-fsanitize=shift-exponent"
// RUN: %clang -target x86_64-linux-gnu -fsanitize=vptr -fsanitize-trap=undefined %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-VPTR-TRAP-UNDEF
// RUN: %clang -target x86_64-linux-gnu -fsanitize=vptr -fsanitize-undefined-trap-on-error %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-VPTR-TRAP-UNDEF
// CHECK-VPTR-TRAP-UNDEF: error: invalid argument '-fsanitize=vptr' not allowed with '-fsanitize-trap=undefined'
// RUN: %clang -target x86_64-linux-gnu -fsanitize=vptr -fno-rtti %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-VPTR-NO-RTTI
// CHECK-VPTR-NO-RTTI: '-fsanitize=vptr' not allowed with '-fno-rtti'
// RUN: %clang -target x86_64-linux-gnu -fsanitize=undefined -fno-rtti %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-UNDEFINED-NO-RTTI
// CHECK-UNDEFINED-NO-RTTI-NOT: vptr
// RUN: %clang -target x86_64-linux-gnu -fsanitize=address,thread -fno-rtti %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-SANA-SANT
// CHECK-SANA-SANT: '-fsanitize=address' not allowed with '-fsanitize=thread'
// RUN: %clang -target x86_64-linux-gnu -fsanitize=address,memory -pie -fno-rtti %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-SANA-SANM
// CHECK-SANA-SANM: '-fsanitize=address' not allowed with '-fsanitize=memory'
// RUN: %clang -target x86_64-linux-gnu -fsanitize=thread,memory -pie -fno-rtti %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-SANT-SANM
// CHECK-SANT-SANM: '-fsanitize=thread' not allowed with '-fsanitize=memory'
// RUN: %clang -target x86_64-linux-gnu -fsanitize=memory,thread -pie -fno-rtti %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-SANM-SANT
// CHECK-SANM-SANT: '-fsanitize=thread' not allowed with '-fsanitize=memory'
// RUN: %clang -target x86_64-linux-gnu -fsanitize=leak,thread -pie -fno-rtti %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-SANL-SANT
// CHECK-SANL-SANT: '-fsanitize=leak' not allowed with '-fsanitize=thread'
// RUN: %clang -target x86_64-linux-gnu -fsanitize=leak,memory -pie -fno-rtti %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-SANL-SANM
// CHECK-SANL-SANM: '-fsanitize=leak' not allowed with '-fsanitize=memory'
// RUN: %clang -target x86_64-linux-gnu -fsanitize=kernel-address,thread -fno-rtti %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-SANKA-SANT
// CHECK-SANKA-SANT: '-fsanitize=kernel-address' not allowed with '-fsanitize=thread'
// RUN: %clang -target x86_64-linux-gnu -fsanitize=kernel-address,memory -pie -fno-rtti %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-SANKA-SANM
// CHECK-SANKA-SANM: '-fsanitize=kernel-address' not allowed with '-fsanitize=memory'
// RUN: %clang -target x86_64-linux-gnu -fsanitize=kernel-address,address -fno-rtti %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-SANKA-SANA
// CHECK-SANKA-SANA: '-fsanitize=kernel-address' not allowed with '-fsanitize=address'
// RUN: %clang -target x86_64-linux-gnu -fsanitize=kernel-address,leak -pie -fno-rtti %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-SANKA-SANL
// CHECK-SANKA-SANL: '-fsanitize=kernel-address' not allowed with '-fsanitize=leak'
// RUN: %clang -target x86_64-linux-gnu -fsanitize-memory-track-origins -pie %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-ONLY-TRACK-ORIGINS
// CHECK-ONLY-TRACK-ORIGINS: warning: argument unused during compilation: '-fsanitize-memory-track-origins'
// RUN: %clang -target x86_64-linux-gnu -fsanitize=memory -fno-sanitize=memory -fsanitize-memory-track-origins -pie %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-TRACK-ORIGINS-DISABLED-MSAN
// CHECK-TRACK-ORIGINS-DISABLED-MSAN-NOT: warning: argument unused
// RUN: %clang -target x86_64-linux-gnu -fsanitize=address %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-NO-EXTRA-TRACK-ORIGINS
// CHECK-NO-EXTRA-TRACK-ORIGINS-NOT: "-fsanitize-memory-track-origins"
// RUN: %clang -target x86_64-linux-gnu -fsanitize=address -fsanitize=alignment -fsanitize=vptr -fno-sanitize=vptr %s -### 2>&1
// OK
// RUN: %clang -target x86_64-linux-gnu -fsanitize=memory -pie %s -### 2>&1
// OK
// RUN: %clang -target x86_64-linux-gnu -fsanitize=memory -fsanitize-memory-track-origins -pie %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-TRACK-ORIGINS-2
// RUN: %clang -target x86_64-linux-gnu -fsanitize=memory -fsanitize-memory-track-origins=1 -pie %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-TRACK-ORIGINS-1
// RUN: %clang -target x86_64-linux-gnu -fsanitize=memory -fsanitize-memory-track-origins=1 -fsanitize-memory-track-origins -pie %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-TRACK-ORIGINS-2
// RUN: %clang -target x86_64-linux-gnu -fsanitize=memory -fsanitize-memory-track-origins=2 -fsanitize-memory-track-origins -pie %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-TRACK-ORIGINS-2
// RUN: %clang -target x86_64-linux-gnu -fsanitize=memory -fno-sanitize-memory-track-origins -fsanitize-memory-track-origins -pie %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-TRACK-ORIGINS-2
// RUN: %clang -target x86_64-linux-gnu -fsanitize=memory -fsanitize-memory-track-origins=0 -fsanitize-memory-track-origins=1 -pie %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-TRACK-ORIGINS-1
// RUN: %clang -target x86_64-linux-gnu -fsanitize=memory -fsanitize-memory-track-origins=0 -fsanitize-memory-track-origins -pie %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-TRACK-ORIGINS-2
// CHECK-TRACK-ORIGINS-1: -fsanitize-memory-track-origins=1
// RUN: %clang -target x86_64-linux-gnu -fsanitize=memory -fno-sanitize-memory-track-origins -pie %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-NO-TRACK-ORIGINS
// RUN: %clang -target x86_64-linux-gnu -fsanitize=memory -fsanitize-memory-track-origins=0 -pie %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-NO-TRACK-ORIGINS
// RUN: %clang -target x86_64-linux-gnu -fsanitize=memory -fsanitize-memory-track-origins -fno-sanitize-memory-track-origins -pie %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-NO-TRACK-ORIGINS
// RUN: %clang -target x86_64-linux-gnu -fsanitize=memory -fsanitize-memory-track-origins -fsanitize-memory-track-origins=0 -pie %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-NO-TRACK-ORIGINS
// RUN: %clang -target x86_64-linux-gnu -fsanitize=memory -fsanitize-memory-track-origins=2 -fno-sanitize-memory-track-origins -pie %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-NO-TRACK-ORIGINS
// RUN: %clang -target x86_64-linux-gnu -fsanitize=memory -fsanitize-memory-track-origins=2 -fsanitize-memory-track-origins=0 -pie %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-NO-TRACK-ORIGINS
// CHECK-NO-TRACK-ORIGINS-NOT: sanitize-memory-track-origins
// RUN: %clang -target x86_64-linux-gnu -fsanitize=memory -fsanitize-memory-track-origins=2 -pie %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-TRACK-ORIGINS-2
// CHECK-TRACK-ORIGINS-2: -fsanitize-memory-track-origins=2
// RUN: %clang -target x86_64-linux-gnu -fsanitize=memory -fsanitize-memory-track-origins=3 -pie %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-TRACK-ORIGINS-3
// CHECK-TRACK-ORIGINS-3: error: invalid value '3' in '-fsanitize-memory-track-origins=3'
// RUN: %clang -target x86_64-linux-gnu -fsanitize=memory -fsanitize-memory-use-after-dtor -pie %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-MSAN-USE-AFTER-DTOR
// CHECK-MSAN-USE-AFTER-DTOR: -cc1{{.*}}-fsanitize-memory-use-after-dtor
// RUN: %clang -target x86_64-linux-gnu -fsanitize=address -fsanitize-address-field-padding=0 %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-ASAN-FIELD-PADDING-0
// CHECK-ASAN-FIELD-PADDING-0-NOT: -fsanitize-address-field-padding
// RUN: %clang -target x86_64-linux-gnu -fsanitize=address -fsanitize-address-field-padding=1 %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-ASAN-FIELD-PADDING-1
// CHECK-ASAN-FIELD-PADDING-1: -fsanitize-address-field-padding=1
// RUN: %clang -target x86_64-linux-gnu -fsanitize=address -fsanitize-address-field-padding=2 %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-ASAN-FIELD-PADDING-2
// CHECK-ASAN-FIELD-PADDING-2: -fsanitize-address-field-padding=2
// RUN: %clang -target x86_64-linux-gnu -fsanitize=address -fsanitize-address-field-padding=3 %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-ASAN-FIELD-PADDING-3
// CHECK-ASAN-FIELD-PADDING-3: error: invalid value '3' in '-fsanitize-address-field-padding=3'
// RUN: %clang -target x86_64-linux-gnu -fsanitize-address-field-padding=2 %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-ASAN-FIELD-PADDING-NO-ASAN
// CHECK-ASAN-FIELD-PADDING-NO-ASAN: warning: argument unused during compilation: '-fsanitize-address-field-padding=2'
// RUN: %clang -target x86_64-linux-gnu -fsanitize-address-field-padding=2 -fsanitize=address -fno-sanitize=address %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-ASAN-FIELD-PADDING-DISABLED-ASAN
// CHECK-ASAN-FIELD-PADDING-DISABLED-ASAN-NOT: warning: argument unused
// RUN: %clang -target x86_64-linux-gnu -fsanitize=vptr -fno-sanitize=vptr -fsanitize=undefined,address %s -### 2>&1
// OK
// RUN: %clang -target x86_64-linux-gnu -fsanitize=thread %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-NO-PIE
// RUN: %clang -target x86_64-linux-gnu -fsanitize=memory %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-NO-PIE
// RUN: %clang -target x86_64-unknown-freebsd -fsanitize=memory %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-PIE
// RUN: %clang -target aarch64-linux-gnu -fsanitize=memory %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-PIE
// RUN: %clang -target arm-linux-androideabi -fsanitize=address %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-PIE
// RUN: %clang -target x86_64-linux-gnu -fsanitize=address %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-NO-PIE
// RUN: %clang -target i386-linux-gnu -fsanitize=address %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-NO-PIE
// CHECK-NO-PIE-NOT: "-pie"
// CHECK-NO-PIE: "-mrelocation-model" "static"
// CHECK-NO-PIE-NOT: "-pie"
// CHECK-PIE: "-mrelocation-model" "pic" "-pic-level" "2" "-pie-level" "2"
// CHECK-PIE: "-pie"
// RUN: %clang -target arm-linux-androideabi %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-ANDROID-NO-ASAN
// CHECK-ANDROID-NO-ASAN: "-mrelocation-model" "pic"
// RUN: %clang -target x86_64-linux-gnu %s -fsanitize=undefined -### 2>&1 | FileCheck %s --check-prefix=CHECK-RECOVER-UBSAN
// RUN: %clang -target x86_64-linux-gnu %s -fsanitize=undefined -fsanitize-recover -### 2>&1 | FileCheck %s --check-prefix=CHECK-RECOVER-UBSAN
// RUN: %clang -target x86_64-linux-gnu %s -fsanitize=undefined -fsanitize-recover=all -### 2>&1 | FileCheck %s --check-prefix=CHECK-RECOVER-UBSAN
// RUN: %clang -target x86_64-linux-gnu %s -fsanitize=undefined -fno-sanitize-recover -fsanitize-recover=undefined -### 2>&1 | FileCheck %s --check-prefix=CHECK-RECOVER-UBSAN
// RUN: %clang -target x86_64-linux-gnu %s -fsanitize=undefined -fno-sanitize-recover=undefined -### 2>&1 | FileCheck %s --check-prefix=CHECK-NO-RECOVER-UBSAN
// RUN: %clang -target x86_64-linux-gnu %s -fsanitize=undefined -fno-sanitize-recover=all -fsanitize-recover=thread -### 2>&1 | FileCheck %s --check-prefix=CHECK-NO-RECOVER-UBSAN
// RUN: %clang -target x86_64-linux-gnu %s -fsanitize=undefined -fsanitize-recover=all -fno-sanitize-recover=undefined -### 2>&1 | FileCheck %s --check-prefix=CHECK-NO-RECOVER-UBSAN
// CHECK-RECOVER-UBSAN: "-fsanitize-recover={{((signed-integer-overflow|integer-divide-by-zero|float-divide-by-zero|function|shift-base|shift-exponent|vla-bound|alignment|null|vptr|object-size|float-cast-overflow|array-bounds|enum|bool|returns-nonnull-attribute|nonnull-attribute),?){17}"}}
// CHECK-NO-RECOVER-UBSAN-NOT: sanitize-recover
// RUN: %clang -target x86_64-linux-gnu %s -fsanitize=undefined -fno-sanitize-recover=all -fsanitize-recover=object-size,shift-base -### 2>&1 | FileCheck %s --check-prefix=CHECK-PARTIAL-RECOVER
// CHECK-PARTIAL-RECOVER: "-fsanitize-recover={{((object-size|shift-base),?){2}"}}
// RUN: %clang -target x86_64-linux-gnu %s -fsanitize=address -fsanitize-recover=all -### 2>&1 | FileCheck %s --check-prefix=CHECK-RECOVER-ASAN
// CHECK-RECOVER-ASAN: "-fsanitize-recover=address"
// RUN: %clang -target x86_64-linux-gnu %s -fsanitize=undefined -fsanitize-recover=foobar,object-size,unreachable -### 2>&1 | FileCheck %s --check-prefix=CHECK-DIAG-RECOVER
// CHECK-DIAG-RECOVER: unsupported argument 'foobar' to option 'fsanitize-recover='
// CHECK-DIAG-RECOVER: unsupported argument 'unreachable' to option 'fsanitize-recover='
// RUN: %clang -target x86_64-linux-gnu %s -fsanitize=undefined -fsanitize-recover -fno-sanitize-recover -### 2>&1 | FileCheck %s --check-prefix=CHECK-DEPRECATED-RECOVER
// CHECK-DEPRECATED-RECOVER: argument '-fsanitize-recover' is deprecated, use '-fsanitize-recover=undefined,integer' instead
// CHECK-DEPRECATED-RECOVER: argument '-fno-sanitize-recover' is deprecated, use '-fno-sanitize-recover=undefined,integer' instead
// CHECK-DEPRECATED-RECOVER-NOT: is deprecated
// RUN: %clang -target x86_64-linux-gnu -fsanitize=leak %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-SANL
// CHECK-SANL: "-fsanitize=leak"
// RUN: %clang -target x86_64-linux-gnu -fsanitize=address,leak -fno-sanitize=address %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-SANA-SANL-NO-SANA
// CHECK-SANA-SANL-NO-SANA: "-fsanitize=leak"
// RUN: %clang -target x86_64-linux-gnu -fsanitize=memory %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-MSAN
// CHECK-MSAN: "-fno-assume-sane-operator-new"
// RUN: %clang -target x86_64-linux-gnu -fsanitize=address %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-ASAN
// CHECK-ASAN: "-fno-assume-sane-operator-new"
// RUN: %clang -target x86_64-linux-gnu -fsanitize=zzz %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-DIAG1
// CHECK-DIAG1: unsupported argument 'zzz' to option 'fsanitize='
// CHECK-DIAG1-NOT: unsupported argument 'zzz' to option 'fsanitize='
// RUN: %clang -target i686-linux-gnu -fsanitize=memory %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-MSAN-X86
// CHECK-MSAN-X86: error: unsupported option '-fsanitize=memory' for target 'i686--linux-gnu'
// RUN: %clang -target x86_64-apple-darwin10 -fsanitize=memory %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-MSAN-DARWIN
// CHECK-MSAN-DARWIN: unsupported option '-fsanitize=memory' for target 'x86_64-apple-darwin10'
// RUN: %clang -target x86_64-apple-darwin10 -fsanitize=memory -fno-sanitize=memory %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-MSAN-NOMSAN-DARWIN
// CHECK-MSAN-NOMSAN-DARWIN-NOT: unsupported option
// RUN: %clang -target x86_64-apple-darwin10 -fsanitize=memory -fsanitize=thread,memory %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-MSAN-TSAN-MSAN-DARWIN
// CHECK-MSAN-TSAN-MSAN-DARWIN: unsupported option '-fsanitize=memory' for target 'x86_64-apple-darwin10'
// CHECK-MSAN-TSAN-MSAN-DARWIN-NOT: unsupported option
// RUN: %clang -target x86_64-apple-darwin10 -fsanitize=thread,memory -fsanitize=memory %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-TSAN-MSAN-MSAN-DARWIN
// CHECK-TSAN-MSAN-MSAN-DARWIN: unsupported option '-fsanitize=memory' for target 'x86_64-apple-darwin10'
// CHECK-TSAN-MSAN-MSAN-DARWIN-NOT: unsupported option
// RUN: %clang -target x86_64-apple-darwin10 -fsanitize=function %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-FSAN-DARWIN
// CHECK-FSAN-DARWIN: unsupported option '-fsanitize=function' for target 'x86_64-apple-darwin10'
// RUN: %clang -target x86_64-apple-darwin10 -fsanitize=function -fsanitize=undefined %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-FSAN-UBSAN-DARWIN
// CHECK-FSAN-UBSAN-DARWIN: unsupported option '-fsanitize=function' for target 'x86_64-apple-darwin10'
// RUN: %clang -target x86_64-apple-darwin10 -mmacosx-version-min=10.8 -fsanitize=vptr %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-VPTR-DARWIN-OLD
// CHECK-VPTR-DARWIN-OLD: unsupported option '-fsanitize=vptr' for target 'x86_64-apple-darwin10'
// RUN: %clang -target x86_64-apple-darwin10 -mmacosx-version-min=10.9 -fsanitize=alignment,vptr %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-VPTR-DARWIN-NEW
// CHECK-VPTR-DARWIN-NEW: -fsanitize=alignment,vptr
// RUN: %clang -target armv7-apple-ios7 -miphoneos-version-min=7.0 -fsanitize=address %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-ASAN-IOS
// CHECK-ASAN-IOS: -fsanitize=address
// RUN: %clang -target i386-pc-openbsd -fsanitize=address %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-ASAN-OPENBSD
// CHECK-ASAN-OPENBSD: unsupported option '-fsanitize=address' for target 'i386-pc-openbsd'
// RUN: %clang -target x86_64-linux-gnu -fsanitize=cfi -flto -c %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-CFI
// RUN: %clang -target x86_64-apple-darwin10 -fsanitize=cfi -flto -c %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-CFI
// RUN: %clang -target x86_64-linux-gnu -fsanitize=cfi-derived-cast -flto -c %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-CFI-DCAST
// RUN: %clang -target x86_64-linux-gnu -fsanitize=cfi-unrelated-cast -flto -c %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-CFI-UCAST
// RUN: %clang -target x86_64-linux-gnu -flto -fsanitize=cfi-nvcall -c %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-CFI-NVCALL
// RUN: %clang -target x86_64-linux-gnu -flto -fsanitize=cfi-vcall -c %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-CFI-VCALL
// CHECK-CFI: -emit-llvm-bc{{.*}}-fsanitize=cfi-derived-cast,cfi-icall,cfi-unrelated-cast,cfi-nvcall,cfi-vcall
// CHECK-CFI-DCAST: -emit-llvm-bc{{.*}}-fsanitize=cfi-derived-cast
// CHECK-CFI-UCAST: -emit-llvm-bc{{.*}}-fsanitize=cfi-unrelated-cast
// CHECK-CFI-NVCALL: -emit-llvm-bc{{.*}}-fsanitize=cfi-nvcall
// CHECK-CFI-VCALL: -emit-llvm-bc{{.*}}-fsanitize=cfi-vcall
// RUN: %clang -target x86_64-linux-gnu -flto -fsanitize=cfi-derived-cast -fno-lto -c %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-CFI-NOLTO
// CHECK-CFI-NOLTO: '-fsanitize=cfi-derived-cast' only allowed with '-flto'
// RUN: %clang -target mips-unknown-linux -fsanitize=cfi-icall %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-CFI-ICALL-MIPS
// CHECK-CFI-ICALL-MIPS: unsupported option '-fsanitize=cfi-icall' for target 'mips-unknown-linux'
// RUN: %clang -target x86_64-linux-gnu -fsanitize-trap=address -c %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-ASAN-TRAP
// CHECK-ASAN-TRAP: error: unsupported argument 'address' to option '-fsanitize-trap'
// RUN: %clang -target x86_64-apple-darwin10 -mmacosx-version-min=10.7 -flto -fsanitize=cfi-vcall -fno-sanitize-trap=cfi -c %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-CFI-NOTRAP-OLD-MACOS
// CHECK-CFI-NOTRAP-OLD-MACOS: error: unsupported option '-fno-sanitize-trap=cfi-vcall' for target 'x86_64-apple-darwin10'
// RUN: %clang -target x86_64-pc-win32 -flto -fsanitize=cfi-vcall -fno-sanitize-trap=cfi -c %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-CFI-NOTRAP-WIN
// CHECK-CFI-NOTRAP-WIN: -emit-llvm-bc
// CHECK-CFI-NOTRAP-WIN-NOT: -fsanitize-trap=cfi
// RUN: %clang -target x86_64-linux-gnu -fsanitize=cfi -fsanitize-cfi-cross-dso -flto -c %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-CFI-CROSS-DSO
// RUN: %clang -target x86_64-linux-gnu -fsanitize=cfi -flto -c %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-CFI-NO-CROSS-DSO
// RUN: %clang -target x86_64-linux-gnu -fsanitize=cfi -fsanitize-cfi-cross-dso -fno-sanitize-cfi-cross-dso -flto -c %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-CFI-NO-CROSS-DSO
// RUN: %clang -target x86_64-linux-gnu -fsanitize=cfi -fno-sanitize-cfi-cross-dso -fsanitize-cfi-cross-dso -flto -c %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-CFI-CROSS-DSO
// CHECK-CFI-CROSS-DSO: -emit-llvm-bc
// CHECK-CFI-CROSS-DSO: -fsanitize-cfi-cross-dso
// CHECK-CFI-NO-CROSS-DSO: -emit-llvm-bc
// CHECK-CFI-NO-CROSS-DSO-NOT: -fsanitize-cfi-cross-dso
// RUN: %clang -target x86_64-linux-gnu -fsanitize=cfi -fsanitize-stats -flto -c %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-CFI-STATS
// CHECK-CFI-STATS: -fsanitize-stats
// RUN: %clang_cl -fsanitize=address -c -MDd -### -- %s 2>&1 | FileCheck %s -check-prefix=CHECK-ASAN-DEBUGRTL
// RUN: %clang_cl -fsanitize=address -c -MTd -### -- %s 2>&1 | FileCheck %s -check-prefix=CHECK-ASAN-DEBUGRTL
// RUN: %clang_cl -fsanitize=address -c -LDd -### -- %s 2>&1 | FileCheck %s -check-prefix=CHECK-ASAN-DEBUGRTL
// RUN: %clang_cl -fsanitize=address -c -MD -MDd -### -- %s 2>&1 | FileCheck %s -check-prefix=CHECK-ASAN-DEBUGRTL
// RUN: %clang_cl -fsanitize=address -c -MT -MTd -### -- %s 2>&1 | FileCheck %s -check-prefix=CHECK-ASAN-DEBUGRTL
// RUN: %clang_cl -fsanitize=address -c -LD -LDd -### -- %s 2>&1 | FileCheck %s -check-prefix=CHECK-ASAN-DEBUGRTL
// CHECK-ASAN-DEBUGRTL: error: invalid argument
// CHECK-ASAN-DEBUGRTL: not allowed with '-fsanitize=address'
// CHECK-ASAN-DEBUGRTL: note: AddressSanitizer doesn't support linking with debug runtime libraries yet
// RUN: %clang_cl -fsanitize=address -c -MT -### -- %s 2>&1 | FileCheck %s -check-prefix=CHECK-ASAN-RELEASERTL
// RUN: %clang_cl -fsanitize=address -c -MD -### -- %s 2>&1 | FileCheck %s -check-prefix=CHECK-ASAN-RELEASERTL
// RUN: %clang_cl -fsanitize=address -c -LD -### -- %s 2>&1 | FileCheck %s -check-prefix=CHECK-ASAN-RELEASERTL
// RUN: %clang_cl -fsanitize=address -c -MTd -MT -### -- %s 2>&1 | FileCheck %s -check-prefix=CHECK-ASAN-RELEASERTL
// RUN: %clang_cl -fsanitize=address -c -MDd -MD -### -- %s 2>&1 | FileCheck %s -check-prefix=CHECK-ASAN-RELEASERTL
// RUN: %clang_cl -fsanitize=address -c -LDd -LD -### -- %s 2>&1 | FileCheck %s -check-prefix=CHECK-ASAN-RELEASERTL
// CHECK-ASAN-RELEASERTL-NOT: error: invalid argument
// RUN: %clang -fno-sanitize=safe-stack -### %s 2>&1 | FileCheck %s -check-prefix=NOSP
// NOSP-NOT: "-fsanitize=safe-stack"
// RUN: %clang -target x86_64-linux-gnu -fsanitize=safe-stack -### %s 2>&1 | FileCheck %s -check-prefix=SP
// RUN: %clang -target x86_64-linux-gnu -fsanitize=address,safe-stack -### %s 2>&1 | FileCheck %s -check-prefix=SP-ASAN
// RUN: %clang -target x86_64-linux-gnu -fstack-protector -fsanitize=safe-stack -### %s 2>&1 | FileCheck %s -check-prefix=SP
// RUN: %clang -target x86_64-linux-gnu -fsanitize=safe-stack -fstack-protector-all -### %s 2>&1 | FileCheck %s -check-prefix=SP
// RUN: %clang -target arm-linux-androideabi -fsanitize=safe-stack -### %s 2>&1 | FileCheck %s -check-prefix=SP
// RUN: %clang -target aarch64-linux-android -fsanitize=safe-stack -### %s 2>&1 | FileCheck %s -check-prefix=SP
// SP-NOT: stack-protector
// SP: "-fsanitize=safe-stack"
// SP-ASAN-NOT: stack-protector
// SP-ASAN: "-fsanitize=address,safe-stack"
// RUN: %clang -target powerpc64-unknown-linux-gnu -fsanitize=memory %s -### 2>&1 | FileCheck %s -check-prefix=CHECK-SANM
// RUN: %clang -target powerpc64le-unknown-linux-gnu -fsanitize=memory %s -### 2>&1 | FileCheck %s -check-prefix=CHECK-SANM
// CHECK-SANM: "-fsanitize=memory"
// RUN: %clang -target aarch64-unknown-cloudabi -fsanitize=safe-stack %s -### 2>&1 | FileCheck %s -check-prefix=SAFESTACK-CLOUDABI
// RUN: %clang -target x86_64-unknown-cloudabi -fsanitize=safe-stack %s -### 2>&1 | FileCheck %s -check-prefix=SAFESTACK-CLOUDABI
// SAFESTACK-CLOUDABI: "-fsanitize=safe-stack"
// RUN: %clang -target x86_64-scei-ps4 -fsanitize=function -fsanitize=undefined %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-FSAN-UBSAN-PS4
// CHECK-FSAN-UBSAN-PS4: unsupported option '-fsanitize=function' for target 'x86_64-scei-ps4'
// RUN: %clang -target x86_64-scei-ps4 -fsanitize=function %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-FSAN-PS4
// CHECK-FSAN-PS4: unsupported option '-fsanitize=function' for target 'x86_64-scei-ps4'
// RUN: %clang -target x86_64-scei-ps4 -fsanitize=dataflow %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-DFSAN-PS4
// CHECK-DFSAN-PS4: unsupported option '-fsanitize=dataflow' for target 'x86_64-scei-ps4'
// RUN: %clang -target x86_64-scei-ps4 -fsanitize=leak %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-LSAN-PS4
// CHECK-LSAN-PS4: unsupported option '-fsanitize=leak' for target 'x86_64-scei-ps4'
// RUN: %clang -target x86_64-scei-ps4 -fsanitize=memory %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-MSAN-PS4
// CHECK-MSAN-PS4: unsupported option '-fsanitize=memory' for target 'x86_64-scei-ps4'
// RUN: %clang -target x86_64-scei-ps4 -fsanitize=thread %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-TSAN-PS4
// CHECK-TSAN-PS4: unsupported option '-fsanitize=thread' for target 'x86_64-scei-ps4'
// RUN: %clang -target x86_64-scei-ps4 -fsanitize=address %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-ASAN-PS4
// Make sure there are no *.{o,bc} or -l passed before the ASan library.
// CHECK-ASAN-PS4-NOT: {{(\.(o|bc)"? |-l).*-lSceDbgAddressSanitizer_stub_weak}}
// CHECK-ASAN-PS4: -lSceDbgAddressSanitizer_stub_weak
|
the_stack_data/234519295.c | /* This file was automatically generated by CasADi.
The CasADi copyright holders make no ownership claim of its contents. */
#ifdef __cplusplus
extern "C" {
#endif
/* How to prefix internal symbols */
#ifdef CODEGEN_PREFIX
#define NAMESPACE_CONCAT(NS, ID) _NAMESPACE_CONCAT(NS, ID)
#define _NAMESPACE_CONCAT(NS, ID) NS ## ID
#define CASADI_PREFIX(ID) NAMESPACE_CONCAT(CODEGEN_PREFIX, ID)
#else
#define CASADI_PREFIX(ID) impl_ode_fun_ ## ID
#endif
#include <math.h>
#ifndef casadi_real
#define casadi_real double
#endif
#ifndef casadi_int
#define casadi_int int
#endif
/* Add prefix to internal symbols */
#define casadi_f0 CASADI_PREFIX(f0)
#define casadi_s0 CASADI_PREFIX(s0)
#define casadi_s1 CASADI_PREFIX(s1)
#define casadi_sq CASADI_PREFIX(sq)
/* Symbol visibility in DLLs */
#ifndef CASADI_SYMBOL_EXPORT
#if defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__)
#if defined(STATIC_LINKED)
#define CASADI_SYMBOL_EXPORT
#else
#define CASADI_SYMBOL_EXPORT __declspec(dllexport)
#endif
#elif defined(__GNUC__) && defined(GCC_HASCLASSVISIBILITY)
#define CASADI_SYMBOL_EXPORT __attribute__ ((visibility ("default")))
#else
#define CASADI_SYMBOL_EXPORT
#endif
#endif
static const casadi_int casadi_s0[8] = {4, 1, 0, 4, 0, 1, 2, 3};
static const casadi_int casadi_s1[5] = {1, 1, 0, 1, 0};
casadi_real casadi_sq(casadi_real x) { return x*x;}
/* casadi_impl_ode_fun:(i0[4],i1[4],i2)->(o0[4]) */
static int casadi_f0(const casadi_real** arg, casadi_real** res, casadi_int* iw, casadi_real* w, void* mem) {
casadi_real a0, a1, a2, a3, a4, a5, a6, a7, a8, a9;
a0=arg[1] ? arg[1][0] : 0;
a1=arg[0] ? arg[0][2] : 0;
a0=(a0-a1);
if (res[0]!=0) res[0][0]=a0;
a0=arg[1] ? arg[1][1] : 0;
a1=arg[0] ? arg[0][3] : 0;
a0=(a0-a1);
if (res[0]!=0) res[0][1]=a0;
a0=arg[1] ? arg[1][2] : 0;
a2=-8.0000000000000016e-02;
a3=arg[0] ? arg[0][1] : 0;
a4=sin(a3);
a4=(a2*a4);
a5=casadi_sq(a1);
a4=(a4*a5);
a5=arg[2] ? arg[2][0] : 0;
a4=(a4+a5);
a6=9.8100000000000009e-01;
a7=cos(a3);
a7=(a6*a7);
a8=sin(a3);
a7=(a7*a8);
a4=(a4+a7);
a7=1.1000000000000001e+00;
a8=1.0000000000000001e-01;
a9=cos(a3);
a9=casadi_sq(a9);
a9=(a8*a9);
a9=(a7-a9);
a4=(a4/a9);
a0=(a0-a4);
if (res[0]!=0) res[0][2]=a0;
a0=arg[1] ? arg[1][3] : 0;
a4=cos(a3);
a2=(a2*a4);
a4=sin(a3);
a2=(a2*a4);
a1=casadi_sq(a1);
a2=(a2*a1);
a1=cos(a3);
a5=(a5*a1);
a2=(a2+a5);
a5=sin(a3);
a6=(a6*a5);
a2=(a2+a6);
a6=9.8100000000000005e+00;
a5=sin(a3);
a6=(a6*a5);
a2=(a2+a6);
a6=8.0000000000000004e-01;
a3=cos(a3);
a3=casadi_sq(a3);
a8=(a8*a3);
a7=(a7-a8);
a6=(a6*a7);
a2=(a2/a6);
a0=(a0-a2);
if (res[0]!=0) res[0][3]=a0;
return 0;
}
CASADI_SYMBOL_EXPORT int casadi_impl_ode_fun(const casadi_real** arg, casadi_real** res, casadi_int* iw, casadi_real* w, void* mem){
return casadi_f0(arg, res, iw, w, mem);
}
CASADI_SYMBOL_EXPORT void casadi_impl_ode_fun_incref(void) {
}
CASADI_SYMBOL_EXPORT void casadi_impl_ode_fun_decref(void) {
}
CASADI_SYMBOL_EXPORT casadi_int casadi_impl_ode_fun_n_in(void) { return 3;}
CASADI_SYMBOL_EXPORT casadi_int casadi_impl_ode_fun_n_out(void) { return 1;}
CASADI_SYMBOL_EXPORT const char* casadi_impl_ode_fun_name_in(casadi_int i){
switch (i) {
case 0: return "i0";
case 1: return "i1";
case 2: return "i2";
default: return 0;
}
}
CASADI_SYMBOL_EXPORT const char* casadi_impl_ode_fun_name_out(casadi_int i){
switch (i) {
case 0: return "o0";
default: return 0;
}
}
CASADI_SYMBOL_EXPORT const casadi_int* casadi_impl_ode_fun_sparsity_in(casadi_int i) {
switch (i) {
case 0: return casadi_s0;
case 1: return casadi_s0;
case 2: return casadi_s1;
default: return 0;
}
}
CASADI_SYMBOL_EXPORT const casadi_int* casadi_impl_ode_fun_sparsity_out(casadi_int i) {
switch (i) {
case 0: return casadi_s0;
default: return 0;
}
}
CASADI_SYMBOL_EXPORT int casadi_impl_ode_fun_work(casadi_int *sz_arg, casadi_int* sz_res, casadi_int *sz_iw, casadi_int *sz_w) {
if (sz_arg) *sz_arg = 3;
if (sz_res) *sz_res = 1;
if (sz_iw) *sz_iw = 0;
if (sz_w) *sz_w = 0;
return 0;
}
#ifdef __cplusplus
} /* extern "C" */
#endif
|
the_stack_data/190767696.c | /* Copyright (c) 2011 The WebM project authors. All Rights Reserved. */
/* */
/* Use of this source code is governed by a BSD-style license */
/* that can be found in the LICENSE file in the root of the source */
/* tree. An additional intellectual property rights grant can be found */
/* in the file PATENTS. All contributing project authors may */
/* be found in the AUTHORS file in the root of the source tree. */
static const char* const cfg = "--target=mips32-linux-gcc --disable-fast-unaligned --enable-external-build --enable-postproc --disable-install-srcs --enable-multi-res-encoding --enable-temporal-denoising --disable-unit-tests --disable-install-docs --disable-examples --disable-avx2";
const char *vpx_codec_build_config(void) {return cfg;}
|
the_stack_data/626649.c |
#include <stdlib.h>
/* function prototypes */
double *bspline(double *, double *, int, double *, int, int, int, int, int);
double bspline_quad(double *, int, int, int, int, int, int);
double *bspline_prod(double *, int, double *, int, int, int, int, int, int);
void bspline_gram(double *, double *, int, int, int, int);
void invband_compute(double *, double *, int, int);
double *bspline(double *output, double *x, int nx,
double *knots, int nknots,
int m, int d, int lower, int upper){
int nbasis;
int index, i, j, k;
double *result, *b, *b0, *b1;
double *f0, *f1;
double denom;
nbasis = upper - lower;
result = output;
f0 = (double *) malloc(sizeof(double) * nx);
f1 = (double *) malloc(sizeof(double) * nx);
if (m == 1) {
for(i=0; i<nbasis; i++) {
index = i + lower;
if(index < nknots - 1) {
if ((knots[index] != knots[index+1]) && (d <= 0)) {
for (k=0; k<nx; k++) {
*result = (double) (x[k] >= knots[index]) * (x[k] < knots[index+1]);
result++;
}
}
else {
for (k=0; k<nx; k++) {
*result = 0.;
result++;
}
}
}
else {
for (k=0; k<nx; k++) {
*result = 0.;
result++;
}
}
}
}
else {
b = (double *) malloc(sizeof(double) * (nbasis+1) * nx);
bspline(b, x, nx, knots, nknots, m-1, d-1, lower, upper+1);
for(i=0; i<nbasis; i++) {
b0 = b + nx*i;
b1 = b + nx*(i+1);
index = i+lower;
if ((knots[index] != knots[index+m-1]) && (index+m-1 < nknots)) {
denom = knots[index+m-1] - knots[index];
if (d <= 0) {
for (k=0; k<nx; k++) {
f0[k] = (x[k] - knots[index]) / denom;
}
}
else {
for (k=0; k<nx; k++) {
f0[k] = (m-1) / (knots[index+m-1] - knots[index]);
}
}
}
else {
for (k=0; k<nx; k++) {
f0[k] = 0.;
}
}
index = i+lower+1;
if ((knots[index] != knots[index+m-1]) && (index+m-1 < nknots)) {
denom = knots[index+m-1] - knots[index];
if (d <= 0) {
for (k=0; k<nx; k++) {
f1[k] = (knots[index+m-1] - x[k]) / denom;
}
}
else {
for (k=0; k<nx; k++) {
f1[k] = -(m-1) / (knots[index+m-1] - knots[index]);
}
}
}
else {
for (k=0; k<nx; k++) {
f1[k] = 0.;
}
}
for (k=0; k<nx; k++) {
*result = f0[k]*(*b0) + f1[k]*(*b1);
b0++; b1++; result++;
}
}
free(b);
}
free(f0); free(f1);
result = result - nx * nbasis;
return(result);
}
double bspline_quad(double *knots, int nknots,
int m, int l, int r, int dl, int dr)
/* This is based on scipy.integrate.fixed_quad */
{
double *y;
double qx[18]={-0.9915651684209309, -0.95582394957139838,
-0.89260246649755604, -0.80370495897252303, -0.69168704306035333,
-0.55977083107394743, -0.41175116146284346, -0.25188622569150576,
-0.084775013041735417, 0.084775013041735306, 0.25188622569150554,
0.41175116146284246, 0.55977083107394743, 0.69168704306035189,
0.80370495897252314, 0.89260246649755637, 0.95582394957139616,
0.9915651684209319};
double qw[18]={0.021616013526480963, 0.049714548894972385,
0.076425730254889301, 0.10094204410628659, 0.12255520671147889,
0.14064291467065104, 0.15468467512626605, 0.16427648374583206,
0.16914238296314324, 0.16914238296314299, 0.16427648374583295,
0.1546846751262658, 0.14064291467065093, 0.12255520671147752,
0.10094204410628753, 0.076425730254888483, 0.049714548894967854,
0.021616013526484387};
double x[18];
int nq=18;
int k, kk;
int lower, upper;
double result, a, b, partial;
result = 0;
/* TO DO: figure out knot span more efficiently */
lower = l - m - 1;
if (lower < 0) { lower = 0;}
upper = lower + 2 * m + 4;
if (upper > nknots - 1) { upper = nknots-1; }
for (k=lower; k<upper; k++) {
partial = 0.;
a = knots[k]; b=knots[k+1];
for (kk=0; kk<nq; kk++) {
x[kk] = (b - a) * (qx[kk] + 1) / 2. + a;
}
y = bspline_prod(x, nq, knots, nknots, m, l, r, dl, dr);
for (kk=0; kk<nq; kk++) {
partial += y[kk] * qw[kk];
}
free(y); /* bspline_prod malloc's memory, but does not free it */
result += (b - a) * partial / 2.;
}
return(result);
}
double *bspline_prod(double *x, int nx, double *knots, int nknots,
int m, int l, int r, int dl, int dr){
double *result, *bl, *br;
int k;
if (abs(r - l) <= m) {
result = (double *) malloc(sizeof(double) * nx);
bl = (double *) malloc(sizeof(double) * nx);
br = (double *) malloc(sizeof(double) * nx);
bl = bspline(bl, x, nx, knots, nknots, m, dl, l, l+1);
br = bspline(br, x, nx, knots, nknots, m, dr, r, r+1);
for (k=0; k<nx; k++) {
result[k] = bl[k] * br[k];
}
free(bl); free(br);
}
else {
for (k=0; k<nx; k++) {
result[k] = 0.;
}
}
return(result);
}
void bspline_gram(double *output, double *knots, int nknots,
int m, int dl, int dr){
/* Presumes that the first m and last m knots are to be ignored, i.e.
the interior knots are knots[(m+1):-(m+1)] and the boundary knots are
knots[m] and knots[-m]. In this setting the first basis element of interest
is the 1st not the 0th. Should maybe be fixed? */
double *result;
int l, r, i, j;
int nbasis;
nbasis = nknots - m;
result = output;
for (i=0; i<nbasis; i++) {
for (j=0; j<m; j++) {
l = i;
r = l+j;
*result = bspline_quad(knots, nknots, m, l, r, dl, dr);
result++;
}
}
}
void invband_compute(double *dataptr, double *L, int n, int m) {
/* Note: m is number of bands not including the diagonal so L is of size (m+1)xn */
int i,j,k;
int idx, idy;
double *data, *odata;
double diag;
data = dataptr;
for (i=0; i<n; i++) {
diag = L[i];
data[i] = 1.0 / (diag*diag) ;
for (j=0; j<=m; j++) {
L[j*n+i] /= diag;
if (j > 0) { data[j*n+i] = 0;}
}
}
for (i=n-1; i>=0; i--) {
for (j=1; j <= (m<n-1-i ? m:n-1-i); j++) {
for (k=1; k<=(n-1-i<m ? n-1-i:m); k++) {
idx = (j<k ? k-j:j-k); idy = (j<k ? i+j:i+k);
data[j*n+i] -= L[k*n+i] * data[idx*n+idy];
}
}
for (k=1; k<=(n-1-i<m ? n-1-i:m); k++) {
data[i] -= L[k*n+i] * data[k*n+i];
}
}
return;
}
|
the_stack_data/129142.c | #include<stdio.h>
int main()
{
int n,i,sum=0;
printf("Enter any number:");
scanf("%d",&n);
for(i=1;i<=n/2;i++)
{
if(n%i==0){
sum+=i;
}
}
if(sum==n){
printf("\n %d is a perfect number",n);
}
else{
printf("\n %d is not a perfect number",n);
}
return 0;
}
|
the_stack_data/148577595.c | #include<stdio.h>
int main(void){
int i,n,m,num[1005],t;
scanf("%d\n",&n);
t = 1;
while (0 != n) {
for (i = 0; i < n; i++) scanf(" %d",&num[i]);
int q,k,m,dif,s;
dif = (1<<26);
scanf("%d\n",&q);
printf("Case %d:\n",t++);
for (i = 1; i <= q; i++){
scanf("%d\n",&s);
for (k = 0; k < n; k++)
for ( m = k + 1; m < n; m++)
if ( abs(dif-s) > abs(s -(num[k]+num[m]))) dif = (num[k] + num[m]);
printf("Closest sum to %d is %d.\n",s,dif);
}
scanf("%d\n",&n);
}
}
|
the_stack_data/140888.c | /* $NetBSD: Lint_strchr.c,v 1.2 2000/06/14 06:49:09 cgd Exp $ */
/*
* This file placed in the public domain.
* Chris Demetriou, November 5, 1997.
*/
#include <string.h>
/*ARGSUSED*/
char *
strchr(src, c)
const char *src;
int c;
{
return (0);
}
|
the_stack_data/369310.c | // RUN: llvm-profdata merge %S/Inputs/path_equivalence.proftext -o %t.profdata
// RUN: llvm-cov show %S/Inputs/path_equivalence.covmapping -instr-profile=%t.profdata -path-equivalence=/tmp,%S | FileCheck %s
int main() {} // CHECK: [[@LINE]]| 1|int main() {}
|
the_stack_data/90766265.c | // Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// TODO: see issue #10410
// +build linux
// +build ppc64 ppc64le
#include <stdio.h>
#include <stdlib.h>
void
x_cgo_sys_thread_create(void* (*func)(void*), void* arg) {
fprintf(stderr, "x_cgo_sys_thread_create not implemented");
abort();
}
void
_cgo_wait_runtime_init_done() {
// TODO(spetrovic): implement this method.
}
void
x_cgo_notify_runtime_init_done(void* dummy) {
// TODO(spetrovic): implement this method.
} |
the_stack_data/31388030.c | #include <stdio.h>
#include <stdlib.h>
#define MAX 256
int main(int argc, char *argv[])
{
FILE *in = stdin;
char l[MAX];
char* i;
int dn;
if(argc > 2)
{
fprintf(stderr, "Usage: %s [<file>]\n", argv[0]);
exit(EXIT_FAILURE);
}
if(argc == 2)
{
in = fopen(argv[1], "r");
if(!in)
{
perror(argv[0]);
exit(EXIT_FAILURE);
}
}
while((i=fgets(l, MAX, in)))
{
int dn = 2* atoi(l);
printf("%d\n", dn);
}
if(in!=stdin)
{
fclose(in);
}
exit(EXIT_SUCCESS);
}
|
the_stack_data/184518347.c | /*
* 数组排序
*
*/
#include <stdio.h>
int main(void)
{
int a[8] = {5, 2, 4, 12, 100, 45, 30, 76};
int i, j;
int t;
for (i = 0; i < 8; ++i)
{
for (j = (i + 1); j < 8; ++j)
if (a[i] < a[j])
{
t = a[i];
a[i] = a[j];
a[j] = t;
}
}
printf("a[0]=%d\na[1]=%d\na[2]=%d\na[3]=%d\na[4]=%d\na[5]=%d\na[6]=%d\na[7]=%d\n", a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7]);
return 0;
}
/*
* i 0 j 1
* i 1 j 2
*
* */
|
the_stack_data/48576166.c | /*
* Benchmarks contributed by Divyesh Unadkat[1,2], Supratik Chakraborty[1], Ashutosh Gupta[1]
* [1] Indian Institute of Technology Bombay, Mumbai
* [2] TCS Innovation labs, Pune
*
*/
extern void __VERIFIER_error() __attribute__ ((__noreturn__));
extern void __VERIFIER_assume(int);
void __VERIFIER_assert(int cond) { if(!(cond)) { ERROR: __VERIFIER_error(); } }
extern int __VERIFIER_nondet_int(void);
int N;
int main()
{
N = __VERIFIER_nondet_int();
if(N <= 0) return 1;
int i;
int a[N];
int b[N];
for(i=0; i<N; i++)
{
if(i==0) {
a[0] = 2;
} else {
a[i] = a[i-1] + 2;
}
}
for(i=0; i<N; i++)
{
if(i==0) {
b[0] = 1;
} else {
b[i] = b[i-1] + a[i-1];
}
}
for(i=0; i<N; i++)
{
__VERIFIER_assert(b[i] == i*i + i + 1);
}
return 1;
}
|
the_stack_data/32949100.c | #ifdef OPENSSL_WITH_INTEL
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include "sm3_ipp.h"
#ifdef _WIN32
#pragma comment(lib, "ippcpmt.lib")
#pragma comment(lib, "ippcoremt.lib")
#endif
IppsSM3State* ipp_sm3_new()
{
int size = 0;
IppsSM3State *ctx = NULL;
IppStatus status = ippsSM3GetSize(&size);
if(status != ippStsNoErr)
{
fprintf(stderr, "%s %s:%u - %s\n", __FUNCTION__, __FILE__, __LINE__, ippGetStatusString(status));
return NULL;
}
ctx = (IppsSM3State*)malloc(size*sizeof(Ipp8u));
if(ctx == NULL)
{
fprintf(stderr, "%s %s:%u - %d:%s\n", __FUNCTION__, __FILE__, __LINE__, errno, strerror(errno));
return NULL;
}
return ctx;
}
int ipp_sm3_init(IppsSM3State *ctx)
{
IppStatus status = ippsSM3Init(ctx);
if(status != ippStsNoErr)
{
fprintf(stderr, "%s %s:%u - %s\n", __FUNCTION__, __FILE__, __LINE__, ippGetStatusString(status));
return 0;
}
return 1;
}
int ipp_sm3_update(IppsSM3State *ctx, unsigned char *msg, int len)
{
IppStatus status = ippsSM3Update(msg, len, ctx);
if(status != ippStsNoErr)
{
fprintf(stderr, "%s %s:%u - %s\n", __FUNCTION__, __FILE__, __LINE__, ippGetStatusString(status));
return 0;
}
return 1;
}
int ipp_sm3_final(IppsSM3State *ctx, unsigned char *md)
{
IppStatus status = ippsSM3Final(md, ctx);
if(status != ippStsNoErr)
{
fprintf(stderr, "%s %s:%u - %s\n", __FUNCTION__, __FILE__, __LINE__, ippGetStatusString(status));
return 0;
}
return 1;
}
void ipp_sm3_delete(IppsSM3State *ctx)
{
if(ctx) free(ctx);
}
unsigned char* ipp_sm3(unsigned char *msg, int len, unsigned char *md)
{
IppStatus status = ippsSM3MessageDigest(msg, len, md);
if(status != ippStsNoErr)
{
fprintf(stderr, "%s %s:%u - %s\n", __FUNCTION__, __FILE__, __LINE__, ippGetStatusString(status));
return NULL;
}
return md;
}
#endif
|
the_stack_data/812369.c | // RUN: %clang_cc1 -triple x86_64-unknown-nacl -emit-llvm -o - %s| FileCheck %s
#include <stdarg.h>
// Test for x86-64 structure representation (instead of pnacl representation),
// in particular for unions. Also crib a few tests from x86 Linux.
union PP_VarValue {
int as_int;
double as_double;
long long as_i64;
};
struct PP_Var {
int type;
int padding;
union PP_VarValue value;
};
// CHECK: define { i64, i64 } @f0()
struct PP_Var f0() {
struct PP_Var result = { 0, 0, 0 };
return result;
}
// CHECK-LABEL: define void @f1(i64 %p1.coerce0, i64 %p1.coerce1)
void f1(struct PP_Var p1) { while(1) {} }
// long doubles are 64 bits on NaCl
// CHECK-LABEL: define double @f5()
long double f5(void) {
return 0;
}
// CHECK-LABEL: define void @f6(i8 signext %a0, i16 signext %a1, i32 %a2, i64 %a3, i8* %a4)
void f6(char a0, short a1, int a2, long long a3, void *a4) {
}
// CHECK-LABEL: define i64 @f8_1()
// CHECK-LABEL: define void @f8_2(i64 %a0.coerce)
union u8 {
long double a;
int b;
};
union u8 f8_1() { while (1) {} }
void f8_2(union u8 a0) {}
// CHECK-LABEL: define i64 @f9()
struct s9 { int a; int b; int : 0; } f9(void) { while (1) {} }
// CHECK-LABEL: define void @f10(i64 %a0.coerce)
struct s10 { int a; int b; int : 0; };
void f10(struct s10 a0) {}
// CHECK-LABEL: define double @f11()
union { long double a; float b; } f11() { while (1) {} }
// CHECK-LABEL: define i32 @f12_0()
// CHECK-LABEL: define void @f12_1(i32 %a0.coerce)
struct s12 { int a __attribute__((aligned(16))); };
struct s12 f12_0(void) { while (1) {} }
void f12_1(struct s12 a0) {}
// Check that sret parameter is accounted for when checking available integer
// registers.
// CHECK: define void @f13(%struct.s13_0* noalias sret(%struct.s13_0) align 8 %agg.result, i32 %a, i32 %b, i32 %c, i32 %d, {{.*}}* byval({{.*}}) align 8 %e, i32 %f)
struct s13_0 { long long f0[3]; };
struct s13_1 { long long f0[2]; };
struct s13_0 f13(int a, int b, int c, int d,
struct s13_1 e, int f) { while (1) {} }
// CHECK-LABEL: define void @f20(%struct.s20* byval(%struct.s20) align 32 %x)
struct __attribute__((aligned(32))) s20 {
int x;
int y;
};
void f20(struct s20 x) {}
// CHECK: declare void @func(i64)
typedef struct _str {
union {
long double a;
long c;
};
} str;
void func(str s);
str ss;
void f9122143()
{
func(ss);
}
|
the_stack_data/28142.c | #include <stdio.h>
void fn() {
printf("old func\n");
} |
the_stack_data/87900.c | /*
* mendeleyBibFix - correct formatting of bib-files that are automatically
* generated by Mendeley Desktop
*
* NOTE: Mendeley Desktop is copyright 2008-2016 by Mendeley Ltd.
* This software is not provided by Mendeley and the author has no affiliation
* with their company.
*
* Documentation:
* This is a simple function intended to correct bib-files that are
* automatically generated by Mendeley Desktop. I have found it to work
* for bib-files generated with the IEEE citation style, but it should
* work for other styles as well. It makes the following corrections:
* - changes double braces around titles to single braces
* - removes escaping of { and } (will only matter if you checked
* "Escape LaTeX special characters" in the "Bibtex" Options tab)
* - removes URL for any entry that is not specified as an exception
* (read the comment block after start of main function to read
* how to change the exceptions)
* - removes braces around months
*
* It should work correctly for files generated by Mendeley Desktop v1.16.1.
* Still functioning as of v1.17.9.
*
* A number of fixes are hard-coded, i.e., it expects to know where the braces are.
* So this code runs very fast (bib files with hundreds of entries are fixed in a
* small fraction of a second) but may not be "future-proof"
*
* You will need to compile this code to run it. A compiled version for Windows is
* included on the release page of Github. If you are going to compile it yourself with gcc,
* then you will need the -std=c99 option
*
* Call syntax (Windows):
* mendeleyBibFix.exe [OUTPUT_FILENAME] [INPUT_FILENAME]
* Call syntax (Linux or macOS):
* ./mendeleyBibFix [OUTPUT_FILENAME] [INPUT_FILENAME]
*
* Both arguments are optional. If there is only one argument, then it is assumed to be
* the output filename. The default input filename is "library.bib", and the default
* output filename is "library_fixed.bib". If you're fine with the defaults, then
* you can also just double-click on the executable without needing a terminal open.
*
* Copyright 2016-2017 Adam Noel. All rights reserved.
* Distributed under the New BSD license. See LICENSE.txt for license details.
*
* Created June 15, 2016
* Current version v1.2.1 (2017-04-26)
*
* Revision history:
*
* Revision v1.2.1 (2017-04-26)
* - fixed removal of "file" field to properly deal with accented names in the file name
*
* Revision v1.2 (2017-03-17)
* - added removal of "file" field, which lists location of local soft copy
*
* Revision v1.1 (2016-10-26)
* - added removal of "annote" field, which includes personal annotations
*
* Revision v1.0.3 (2016-06-19)
* - corrected detection of bib entry after a URL that gets removed
* - added workaround to enable a custom date, "to appear", "in press", or any other custom
* data at end of entry. If an entry has an ISSN but no year, then the ISSN is renamed
* to the year.
*
* Revision v1.0.2 (2016-06-15)
* - removed unused variables
*
* Revision v1.0.1 (2016-06-15)
* - corrected end of bib entry detection to not catch annotations as false alarms
*
* Revision v1.0 (2016-06-15)
* - File created
*
*
*/
#include <stdio.h>
#include <stdlib.h> // for exit(), malloc
#include <string.h> // for strcpy()
#include <stdbool.h> // for C++ bool naming, requires C99
#include <time.h> // For time record keeping
#define BIB_TYPE_MAX 25
#define BIB_TAG_MAX 100
#define IGNORE_TECHREPORT 1
#define REMOVE_TITLE_EXTRA_BRACE 0
// Define the size of chars that should be escaped with "\" and ignore mendeley escape option
#define ESCAPE_SPECIAL_CHAR_LIST_SIZE 1
#define ESCAPE_CHAR_LIST "&"
// Function declarations
char * stringAllocate(long stringLength);
char * stringWrite(char * src);
unsigned long findEndOfLine(char * str, unsigned long startInd);
unsigned long findEndOfField(char * str, unsigned long startInd);
//
// MAIN
//
int main(int argc, char *argv[])
{
// MODIFY THIS BLOCK TO ADD/REMOVE BIB ENTRY TYPES THAT
// SHOULD HAVE A URL DISPLAYED. BY DEFAULT, ALL URLS
// ARE REMOVED FROM THE BIB-FILE.
// TO ADD AN EXCEPTION:
// 1) INCREMENT NUM_URL_EXCEPTIONS
// 2) APPEND THE NEW EXCEPTION TO THE LAST INDEX OF
// URL_EXCEPTION_TYPES (WRITE WITHOUT THE '@' PREFIX).
// TO REMOVE AN EXCEPTION:
// 1) DECREMENT NUM_URL_EXCEPTIONS
// 2) REMOVE EXCEPTION STRING WRITTEN TO URL_EXCEPTION_TYPES
// 3) CORRECT INDICES OF REMAINING EXCEPTIONS SO THAT THEY
// GO FROM 0 TO (NUM_URL_EXCEPTIONS-1)
// NOTE: MENDELEY EXPORTS A "WEB PAGE" ENTRY AS "misc"
const int NUM_URL_EXCEPTIONS = 2;
const char *URL_EXCEPTION_TYPES[NUM_URL_EXCEPTIONS];
URL_EXCEPTION_TYPES[0] = "misc";
URL_EXCEPTION_TYPES[1] = "unpublished";
// END OF USER-MODIFIED URL EXCEPTION BLOCK
int curException;
bool bUrlException;
char bibType[BIB_TYPE_MAX];
char bibTAG[BIB_TAG_MAX];
char INPUT_DEFAULT[] = "library.bib";
char OUTPUT_DEFAULT[] = "library_fixed.bib";
char * inputName;
char * outputName;
FILE * inputFile;
FILE * outputFile;
unsigned long fileLength;
unsigned long temp; // Garbage variable for discarded file content length
char * inputContent;
char * outputContent;
unsigned long curInputInd, curInputAnchorInd;
// Bib-entry variables
unsigned long numEntry = 0;
unsigned long numEntryIgnored = 0;
char * curBibEntry;
unsigned long curBibInd, curBibLength, indEOL;
// Year-tracking variables
bool bHasYear; // Current entry defined the year
bool bHasISSN; // Current entry defined the year
unsigned long issnInd; // Index of the issn in the current entry.
// This entry is renamed to the year if year is not defined
// Timer variables
clock_t startTime, endTime;
// Read in output filename if defined
if(argc > 2)
{
inputName = stringWrite(argv[2]);
} else
{
inputName = stringWrite(INPUT_DEFAULT);
}
// Read in input filename if defined
if(argc > 1)
{
outputName = stringWrite(argv[1]);
} else
{
outputName = stringWrite(OUTPUT_DEFAULT);
}
// Open input file
inputFile = fopen(inputName, "r");
if(inputFile == NULL)
{
fprintf(stderr,"ERROR: Input file \"%s\" not found.\n",inputName);
exit(EXIT_FAILURE);
}
printf("Successfully opened input file at \"%s\".\n", inputName);
// Read in contents of input file
fseek(inputFile, 0, SEEK_END);
fileLength = ftell(inputFile);
fseek(inputFile,0,SEEK_SET);
inputContent = malloc(fileLength + 1);
outputContent = malloc(2*fileLength + 1); // Output will be no longer than twice the input (Escapes)
if(inputContent == NULL
|| outputContent == NULL)
{
fprintf(stderr,"ERROR: Memory could not be allocated to store the input file contents.\n");
exit(EXIT_FAILURE);
}
temp = fread(inputContent,1,fileLength,inputFile);
fclose(inputFile);
printf("Successfully read and closed input file.\n");
#if IGNORE_TECHREPORT == 1
printf("Ignoring techreports with RFC.\n");
#endif
//
// Scan and fix bib entries
//
numEntry = 0;
startTime = clock();
curInputInd = 0;
curInputAnchorInd = 0;
outputContent[0] = '\0'; // Initialize output string as empty
while(true)
{
// Find start of next entry
while(inputContent[curInputInd] != '@')
{
if(inputContent[curInputInd] == '\0') {
break; // Reached EOF. No more entries to scan
} else {
curInputInd++;
}
}
if(inputContent[curInputInd] == '\0') {
printf("End of process\n");
break;
}
curInputAnchorInd = curInputInd++;
// Find end of entry
while(true)
{
if((inputContent[curInputInd] == '}'
&& inputContent[curInputInd-1] == '\n'
&& (inputContent[curInputInd+1] == '\n'
|| inputContent[curInputInd+1] == '\0'))
|| inputContent[curInputInd] == '\0')
break; // Reached end of current entry (or EOF)
else
curInputInd++;
}
if(inputContent[curInputInd] == '\0') {
printf("End of process\n");
break;
}
// Current entry goes from inputContent[curInputAnchorInd]
// to inputContent[curInputInd]+1
curBibLength = curInputInd-curInputAnchorInd+2;
// curBibLength was doubled for efficiency and applying escapes chars
curBibEntry = malloc((2*curBibLength + 1)*sizeof(char));
if(curBibEntry == NULL)
{
fprintf(stderr,"ERROR: Memory could not be allocated to copy bib entry %lu.\n", numEntry);
exit(EXIT_FAILURE);
}
int curBibIndWriter;
for(curBibInd = 0, curBibIndWriter = 0; curBibInd < curBibLength; curBibInd++, curBibIndWriter++)
{
curBibEntry[curBibIndWriter] = inputContent[curInputAnchorInd+curBibInd];
#if ESCAPE_SPECIAL_CHAR_LIST_SIZE > 0
int escape_counter;
for(escape_counter = 0; escape_counter < ESCAPE_SPECIAL_CHAR_LIST_SIZE; escape_counter++)
{
char *escape_list = ESCAPE_CHAR_LIST;
if(escape_list[escape_counter] == inputContent[curInputAnchorInd+curBibInd])
{
curBibEntry[curBibIndWriter++] = '\\';
curBibEntry[curBibIndWriter] = escape_list[escape_counter];
}
}
#endif
}
curBibEntry[curBibIndWriter] = '\0';
curBibLength = curBibIndWriter;
// curBibEntry is now a valid substring of the original input file
// Apply fixes as necessary
curBibInd = 1; // We know first character is '@'
// Check URL exception types
bUrlException = false;
while(curBibEntry[curBibInd] != '{'
&& curBibInd < BIB_TYPE_MAX)
{
bibType[curBibInd-1] = curBibEntry[curBibInd];
curBibInd++;
}
bibType[curBibInd-1] = '\0';
// Get the bib tag assigned skipping "{"
curBibInd++;
int tagCounter = 0;
while((curBibEntry[curBibInd] != ',' &&
curBibEntry[curBibInd] != '\n' &&
curBibEntry[curBibInd] != '\0')
&& curBibInd < BIB_TAG_MAX)
{
bibTAG[tagCounter++] = curBibEntry[curBibInd];
curBibInd++;
}
bibTAG[tagCounter] = '\0';
for(curException = 0; curException < NUM_URL_EXCEPTIONS; curException++)
{
if(!strcmp(bibType,URL_EXCEPTION_TYPES[curException]))
{
bUrlException = true; // Current type of entry needs to keep URL
numEntryIgnored++;
printf("Bib-entry in the ignored list: %s\n", bibTAG);
break;
}
}
#if IGNORE_TECHREPORT == 1
if(!strcmp(bibType,"techreport"))
{
// Should we free it here!?
if(strstr(bibTAG, "RFC") != NULL) {
numEntryIgnored++;
printf("Bib-entry RFC ignored: %s\n", bibTAG);
free(curBibEntry);
continue;
} else {
printf("Bib-entry is techreport, but not RFC: %s\n", bibTAG);
}
}
#endif
bHasYear = false;
bHasISSN = false;
// Scan Remainder of entry
while(curBibEntry[curBibInd] != '\0')
{
if(curBibEntry[curBibInd] == '\n')
{
// We're at the start of a line in the current bib entry
// Scan ahead to see if its an entry that we need to fix
/*
* The month is not a problem anymore
if(!strncmp(&curBibEntry[curBibInd+1], "month =",7))
{ // Next line lists month. Format should be mmm
// and not {mmm}
if(curBibEntry[curBibInd+9] == '{'
&& curBibEntry[curBibInd+13] == '}')
{
curBibEntry[curBibInd+9] = curBibEntry[curBibInd+10];
curBibEntry[curBibInd+10] = curBibEntry[curBibInd+11];
curBibEntry[curBibInd+11] = curBibEntry[curBibInd+12];
// Delete offsets 12 and 13
memmove(&curBibEntry[curBibInd+12], &curBibEntry[curBibInd+14],
curBibLength - curBibInd-13);
curBibLength -= 2;
}
} else */
if(!strncmp(&curBibEntry[curBibInd+1], "title =",7))
{
#if REMOVE_TITLE_EXTRA_BRACE == 1
// Title is supposed to be surrounded by 1 set of braces and not 2
// Remove extra set of curly braces
indEOL = findEndOfLine(curBibEntry, curBibInd+1);
// Shift title over extra opening curly brace
memmove(&curBibEntry[curBibInd+10], &curBibEntry[curBibInd+11],
indEOL - curBibInd-13);
// Shift remaining text over extra closing curly brace
memmove(&curBibEntry[indEOL-3], &curBibEntry[indEOL-1],
curBibLength - indEOL + 2);
curBibLength -= 2;
#endif /* REMOVE_TITLE_EXTRA_BRACER == 1 */
} else if(!strncmp(&curBibEntry[curBibInd+1], "annote =",8))
{ // Entry has an annotation. Erase the whole field
indEOL = findEndOfField(curBibEntry, curBibInd+1);
memmove(&curBibEntry[curBibInd+1], &curBibEntry[indEOL+1],
curBibLength - indEOL + 1);
curBibLength -= indEOL - curBibInd;
curBibInd--; // Correct index so that line after annote is read correctly
} else if(!strncmp(&curBibEntry[curBibInd+1], "file =",6))
{ // Entry has a filename. Erase the whole line
indEOL = findEndOfLine(curBibEntry, curBibInd+1);
memmove(&curBibEntry[curBibInd+1], &curBibEntry[indEOL+1],
curBibLength - indEOL + 1);
curBibLength -= indEOL - curBibInd;
curBibInd--; // Correct index so that line after filename is read correctly
} else if(!strncmp(&curBibEntry[curBibInd+1], "abstract =",10))
{ // Entry has a filename. Erase the whole line
indEOL = findEndOfLine(curBibEntry, curBibInd+1);
memmove(&curBibEntry[curBibInd+1], &curBibEntry[indEOL+1],
curBibLength - indEOL + 1);
curBibLength -= indEOL - curBibInd;
curBibInd--; // Correct index so that line after filename is read correctly
} else if(!strncmp(&curBibEntry[curBibInd+1], "eprint =",8))
{ // Entry has a filename. Erase the whole line
indEOL = findEndOfLine(curBibEntry, curBibInd+1);
memmove(&curBibEntry[curBibInd+1], &curBibEntry[indEOL+1],
curBibLength - indEOL + 1);
curBibLength -= indEOL - curBibInd;
curBibInd--; // Correct index so that line after filename is read correctly
} else if(!strncmp(&curBibEntry[curBibInd+1], "mendeley-tags =",15))
{ // Entry has a filename. Erase the whole line
indEOL = findEndOfLine(curBibEntry, curBibInd+1);
memmove(&curBibEntry[curBibInd+1], &curBibEntry[indEOL+1],
curBibLength - indEOL + 1);
curBibLength -= indEOL - curBibInd;
curBibInd--; // Correct index so that line after filename is read correctly
} else if(!strncmp(&curBibEntry[curBibInd+1], "archivePrefix =",15))
{ // Entry has a filename. Erase the whole line
indEOL = findEndOfLine(curBibEntry, curBibInd+1);
memmove(&curBibEntry[curBibInd+1], &curBibEntry[indEOL+1],
curBibLength - indEOL + 1);
curBibLength -= indEOL - curBibInd;
curBibInd--; // Correct index so that line after filename is read correctly
} else if(!strncmp(&curBibEntry[curBibInd+1], "arxivId =",9))
{ // Entry has a filename. Erase the whole line
indEOL = findEndOfLine(curBibEntry, curBibInd+1);
memmove(&curBibEntry[curBibInd+1], &curBibEntry[indEOL+1],
curBibLength - indEOL + 1);
curBibLength -= indEOL - curBibInd;
curBibInd--; // Correct index so that line after filename is read correctly
} else if(!strncmp(&curBibEntry[curBibInd+1], "keywords =",10))
{ // Entry has a filename. Erase the whole line
indEOL = findEndOfLine(curBibEntry, curBibInd+1);
memmove(&curBibEntry[curBibInd+1], &curBibEntry[indEOL+1],
curBibLength - indEOL + 1);
curBibLength -= indEOL - curBibInd;
curBibInd--; // Correct index so that line after filename is read correctly
}else if(!bUrlException
&& !strncmp(&curBibEntry[curBibInd+1], "url =",5))
{ // Entry has a URL but it should be removed. Erase the whole line
indEOL = findEndOfLine(curBibEntry, curBibInd+1);
memmove(&curBibEntry[curBibInd+1], &curBibEntry[indEOL+1],
curBibLength - indEOL + 1);
curBibLength -= indEOL - curBibInd;
curBibInd--; // Correct index so that line after URL is read correctly
} else if(!strncmp(&curBibEntry[curBibInd+1], "year =",6))
{ // This entry defines the year
bHasYear = true;
} else if(!strncmp(&curBibEntry[curBibInd+1], "issn =",6))
{ // Record line where issn starts in case we need to rename it to the year
bHasISSN = true;
issnInd = curBibInd + 1;
}
} else if(!strncmp(&curBibEntry[curBibInd], "{\\{}",4))
{ // We have an incorrectly formatted opening curly brace
// Remove 3 characters of memory
memmove(&curBibEntry[curBibInd+1], &curBibEntry[curBibInd+4],
curBibLength - curBibInd-2);
curBibLength -= 3;
} else if(!strncmp(&curBibEntry[curBibInd], "{\\}}",4))
{ // We have an incorrectly formatted closing curly brace
// Remove 3 characters of memory
curBibEntry[curBibInd] = '}';
memmove(&curBibEntry[curBibInd+1], &curBibEntry[curBibInd+4],
curBibLength - curBibInd-2);
curBibLength -= 3;
}
curBibInd++;
}
if(!bHasYear && bHasISSN)
{ // This entry does not define the year. Rename the issn to the year
curBibEntry[issnInd] = 'y';
curBibEntry[issnInd+1] = 'e';
curBibEntry[issnInd+2] = 'a';
curBibEntry[issnInd+3] = 'r';
}
// Write fixed entry to output string
strcat(outputContent, curBibEntry);
numEntry++;
}
endTime = clock();
printf("Entry fixing took %f seconds\n", (double) (endTime-startTime)/CLOCKS_PER_SEC);
// Write output string to output file
if((outputFile = fopen(outputName, "w")) == NULL)
{
fprintf(stderr,"ERROR: Cannot create output file \"%s\".\n",outputName);
exit(EXIT_FAILURE);
}
printf("Successfully created output file at \"%s\".\n", outputName);
fprintf(outputFile, "%s", outputContent);
fclose(outputFile);
printf("Successfully wrote and closed output file with %lu entries. %lu ignored.\n", numEntry, numEntryIgnored);
// Cleanup
free(inputContent);
free(inputName);
free(outputName);
free(curBibEntry);
return 0;
}
// Allocate memory for a string
char * stringAllocate(long stringLength)
{
char * string = malloc(stringLength+1);
if(string == NULL)
{
fprintf(stderr,"ERROR: Memory could not be allocated for string copy.\n");
exit(EXIT_FAILURE);
}
return string;
}
// Copy string (with memory allocation)
char * stringWrite(char * src)
{
char * string = stringAllocate(strlen(src));
strcpy(string, src);
return string;
}
// Find next end of line in current string
unsigned long findEndOfLine(char * str, unsigned long startInd)
{
unsigned long curInd = startInd;
while(str[curInd] != '\n')
curInd++;
return curInd;
}
// Find end of field in current string
unsigned long findEndOfField(char * str, unsigned long startInd)
{
unsigned long curInd = startInd;
while(strncmp(&str[curInd+1], "},",2))
curInd++;
return curInd+3;
} |
the_stack_data/41888.c | //
// Created by 吴超 on 2020/6/11.
//
#include <stdio.h>
struct ListNode {
int val;
struct ListNode *next;
};
//思路是prev指针指向head,current指针指向head->next,将prev的next指针指向current的下一个节点,然后prev向前走一步,current向前走一步
//直到current指针指向链表尾部。这样我们就将链表分成了奇数链表和偶数链表。在遍历之前将偶数链表的头部(即current)用evenHead指向。遍历完之后将奇数链表的尾节点的next指针指向evenHead
//current指针到达链表尾部时,这里要分两种情况,当总节点数是奇数时,current指针正好指向的是奇数链表尾部。而如果总结点数是偶数时,则prev指针指向的是奇数链表的尾部。
struct ListNode* oddEvenList(struct ListNode* head){
if(head==NULL||head->next==NULL||head->next->next==NULL){
return head;
}
int n = 0;
struct ListNode* prev = head;
struct ListNode* current = head->next;
struct ListNode* evenHead = current;
while(current->next!=NULL){
n++;
prev->next = current->next;
prev = current;
current = current->next;
}
if(n%2!=0){
//节点数为奇数时,这一步必须执行,不然会使链表成环
prev->next = NULL;
current->next = evenHead;
} else {
prev->next = evenHead;
}
return head;
} |
the_stack_data/173578719.c | #include <stdio.h>
#include <string.h>
#define MAX 10
void permutacao(char *string, int fim, char ant[], int nivel);
void shellSort(char *vet, int size);
int main() {
int e, i;
char str[MAX], aux[0];
scanf("%d", &e);
for(i = 0; i < e; i++) {
scanf("%s", str);
shellSort(str, strlen(str));
permutacao(str, strlen(str), aux, 0);
printf("\n");
}
return 0;
}
void shellSort(char *vet, int size) {
int i, j;
char value;
int gap = 1;
while(gap < size) {
gap = 3*gap+1;
}
while ( gap > 1) {
gap /= 3;
for(i = gap; i < size; i++) {
value = vet[i];
j = i - gap;
while (j >= 0 && value < vet[j]) {
vet [j + gap] = vet[j];
j -= gap;
}
vet[j + gap] = value;
}
}
}
void permutacao(char *string, int fim, char ant[], int nivel) {
int i,j,n,idx;
if (fim > 0) {
for (i = 0; i < fim; i++) {
if(i>0){
if(string[i]==string[i-1]){
continue;
}
}
char string2[fim - 1];
char ant2[nivel + 1];
int n = 0;
for (n = 0; n < nivel; n++) {
ant2[n] = ant[n];
}
ant2[n] = string[i];
idx = 0;
for (j = 0; j < fim; j++) {
if (j != i) {
string2[idx] = string[j];
idx++;
}
}
permutacao(string2, fim - 1, ant2, nivel + 1);
}
} else {
ant[nivel] = '\0';
printf("%s\n", ant);
}
}
|
the_stack_data/1006897.c | /**
******************************************************************************
* @file stm32h7xx_ll_spi.c
* @author MCD Application Team
* @brief SPI LL module driver.
******************************************************************************
* @attention
*
* <h2><center>© Copyright (c) 2017 STMicroelectronics.
* All rights reserved.</center></h2>
*
* This software component is licensed by ST under BSD 3-Clause license,
* the "License"; You may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
* opensource.org/licenses/BSD-3-Clause
*
******************************************************************************
*/
#if defined(USE_FULL_LL_DRIVER)
/* Includes ------------------------------------------------------------------*/
#include "stm32h7xx_ll_spi.h"
#include "stm32h7xx_ll_bus.h"
#include "stm32h7xx_ll_rcc.h"
#ifdef GENERATOR_I2S_PRESENT
#include "stm32h7xx_ll_rcc.h"
#endif /* GENERATOR_I2S_PRESENT*/
#ifdef USE_FULL_ASSERT
#include "stm32_assert.h"
#else
#define assert_param(expr) ((void)0U)
#endif
/** @addtogroup STM32H7xx_LL_Driver
* @{
*/
#if defined(SPI1) || defined(SPI2) || defined(SPI3) || defined(SPI4) || defined(SPI5) || defined(SPI6)
/** @addtogroup SPI_LL
* @{
*/
/* Private types -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private constants ---------------------------------------------------------*/
/* Private macros ------------------------------------------------------------*/
/** @addtogroup SPI_LL_Private_Macros
* @{
*/
#define IS_LL_SPI_MODE(__VALUE__) (((__VALUE__) == LL_SPI_MODE_MASTER) \
|| ((__VALUE__) == LL_SPI_MODE_SLAVE))
#define IS_LL_SPI_SS_IDLENESS(__VALUE__) (((__VALUE__) == LL_SPI_SS_IDLENESS_00CYCLE) \
|| ((__VALUE__) == LL_SPI_SS_IDLENESS_01CYCLE) \
|| ((__VALUE__) == LL_SPI_SS_IDLENESS_02CYCLE) \
|| ((__VALUE__) == LL_SPI_SS_IDLENESS_03CYCLE) \
|| ((__VALUE__) == LL_SPI_SS_IDLENESS_04CYCLE) \
|| ((__VALUE__) == LL_SPI_SS_IDLENESS_05CYCLE) \
|| ((__VALUE__) == LL_SPI_SS_IDLENESS_06CYCLE) \
|| ((__VALUE__) == LL_SPI_SS_IDLENESS_07CYCLE) \
|| ((__VALUE__) == LL_SPI_SS_IDLENESS_08CYCLE) \
|| ((__VALUE__) == LL_SPI_SS_IDLENESS_09CYCLE) \
|| ((__VALUE__) == LL_SPI_SS_IDLENESS_10CYCLE) \
|| ((__VALUE__) == LL_SPI_SS_IDLENESS_11CYCLE) \
|| ((__VALUE__) == LL_SPI_SS_IDLENESS_12CYCLE) \
|| ((__VALUE__) == LL_SPI_SS_IDLENESS_13CYCLE) \
|| ((__VALUE__) == LL_SPI_SS_IDLENESS_14CYCLE) \
|| ((__VALUE__) == LL_SPI_SS_IDLENESS_15CYCLE))
#define IS_LL_SPI_ID_IDLENESS(__VALUE__) (((__VALUE__) == LL_SPI_ID_IDLENESS_00CYCLE) \
|| ((__VALUE__) == LL_SPI_ID_IDLENESS_01CYCLE) \
|| ((__VALUE__) == LL_SPI_ID_IDLENESS_02CYCLE) \
|| ((__VALUE__) == LL_SPI_ID_IDLENESS_03CYCLE) \
|| ((__VALUE__) == LL_SPI_ID_IDLENESS_04CYCLE) \
|| ((__VALUE__) == LL_SPI_ID_IDLENESS_05CYCLE) \
|| ((__VALUE__) == LL_SPI_ID_IDLENESS_06CYCLE) \
|| ((__VALUE__) == LL_SPI_ID_IDLENESS_07CYCLE) \
|| ((__VALUE__) == LL_SPI_ID_IDLENESS_08CYCLE) \
|| ((__VALUE__) == LL_SPI_ID_IDLENESS_09CYCLE) \
|| ((__VALUE__) == LL_SPI_ID_IDLENESS_10CYCLE) \
|| ((__VALUE__) == LL_SPI_ID_IDLENESS_11CYCLE) \
|| ((__VALUE__) == LL_SPI_ID_IDLENESS_12CYCLE) \
|| ((__VALUE__) == LL_SPI_ID_IDLENESS_13CYCLE) \
|| ((__VALUE__) == LL_SPI_ID_IDLENESS_14CYCLE) \
|| ((__VALUE__) == LL_SPI_ID_IDLENESS_15CYCLE))
#define IS_LL_SPI_TXCRCINIT_PATTERN(__VALUE__) (((__VALUE__) == LL_SPI_TXCRCINIT_ALL_ZERO_PATTERN) \
|| ((__VALUE__) == LL_SPI_TXCRCINIT_ALL_ONES_PATTERN))
#define IS_LL_SPI_RXCRCINIT_PATTERN(__VALUE__) (((__VALUE__) == LL_SPI_RXCRCINIT_ALL_ZERO_PATTERN) \
|| ((__VALUE__) == LL_SPI_RXCRCINIT_ALL_ONES_PATTERN))
#define IS_LL_SPI_UDR_CONFIG_REGISTER(__VALUE__) (((__VALUE__) == LL_SPI_UDR_CONFIG_REGISTER_PATTERN) \
|| ((__VALUE__) == LL_SPI_UDR_CONFIG_LAST_RECEIVED) \
|| ((__VALUE__) == LL_SPI_UDR_CONFIG_LAST_TRANSMITTED))
#define IS_LL_SPI_UDR_DETECT_BEGIN_DATA(__VALUE__) (((__VALUE__) == LL_SPI_UDR_DETECT_BEGIN_DATA_FRAME) \
|| ((__VALUE__) == LL_SPI_UDR_DETECT_END_DATA_FRAME) \
|| ((__VALUE__) == LL_SPI_UDR_DETECT_BEGIN_ACTIVE_NSS))
#define IS_LL_SPI_PROTOCOL(__VALUE__) (((__VALUE__) == LL_SPI_PROTOCOL_MOTOROLA) \
|| ((__VALUE__) == LL_SPI_PROTOCOL_TI))
#define IS_LL_SPI_PHASE(__VALUE__) (((__VALUE__) == LL_SPI_PHASE_1EDGE) \
|| ((__VALUE__) == LL_SPI_PHASE_2EDGE))
#define IS_LL_SPI_POLARITY(__VALUE__) (((__VALUE__) == LL_SPI_POLARITY_LOW) \
|| ((__VALUE__) == LL_SPI_POLARITY_HIGH))
#define IS_LL_SPI_BAUDRATEPRESCALER(__VALUE__) (((__VALUE__) == LL_SPI_BAUDRATEPRESCALER_DIV2) \
|| ((__VALUE__) == LL_SPI_BAUDRATEPRESCALER_DIV4) \
|| ((__VALUE__) == LL_SPI_BAUDRATEPRESCALER_DIV8) \
|| ((__VALUE__) == LL_SPI_BAUDRATEPRESCALER_DIV16) \
|| ((__VALUE__) == LL_SPI_BAUDRATEPRESCALER_DIV32) \
|| ((__VALUE__) == LL_SPI_BAUDRATEPRESCALER_DIV64) \
|| ((__VALUE__) == LL_SPI_BAUDRATEPRESCALER_DIV128) \
|| ((__VALUE__) == LL_SPI_BAUDRATEPRESCALER_DIV256))
#define IS_LL_SPI_BITORDER(__VALUE__) (((__VALUE__) == LL_SPI_LSB_FIRST) \
|| ((__VALUE__) == LL_SPI_MSB_FIRST))
#define IS_LL_SPI_TRANSFER_DIRECTION(__VALUE__) (((__VALUE__) == LL_SPI_FULL_DUPLEX) \
|| ((__VALUE__) == LL_SPI_SIMPLEX_TX) \
|| ((__VALUE__) == LL_SPI_SIMPLEX_RX) \
|| ((__VALUE__) == LL_SPI_HALF_DUPLEX_RX) \
|| ((__VALUE__) == LL_SPI_HALF_DUPLEX_TX))
#define IS_LL_SPI_DATAWIDTH(__VALUE__) (((__VALUE__) == LL_SPI_DATAWIDTH_4BIT) \
|| ((__VALUE__) == LL_SPI_DATAWIDTH_5BIT) \
|| ((__VALUE__) == LL_SPI_DATAWIDTH_6BIT) \
|| ((__VALUE__) == LL_SPI_DATAWIDTH_7BIT) \
|| ((__VALUE__) == LL_SPI_DATAWIDTH_8BIT) \
|| ((__VALUE__) == LL_SPI_DATAWIDTH_9BIT) \
|| ((__VALUE__) == LL_SPI_DATAWIDTH_10BIT) \
|| ((__VALUE__) == LL_SPI_DATAWIDTH_11BIT) \
|| ((__VALUE__) == LL_SPI_DATAWIDTH_12BIT) \
|| ((__VALUE__) == LL_SPI_DATAWIDTH_13BIT) \
|| ((__VALUE__) == LL_SPI_DATAWIDTH_14BIT) \
|| ((__VALUE__) == LL_SPI_DATAWIDTH_15BIT) \
|| ((__VALUE__) == LL_SPI_DATAWIDTH_16BIT) \
|| ((__VALUE__) == LL_SPI_DATAWIDTH_17BIT) \
|| ((__VALUE__) == LL_SPI_DATAWIDTH_18BIT) \
|| ((__VALUE__) == LL_SPI_DATAWIDTH_19BIT) \
|| ((__VALUE__) == LL_SPI_DATAWIDTH_20BIT) \
|| ((__VALUE__) == LL_SPI_DATAWIDTH_21BIT) \
|| ((__VALUE__) == LL_SPI_DATAWIDTH_22BIT) \
|| ((__VALUE__) == LL_SPI_DATAWIDTH_23BIT) \
|| ((__VALUE__) == LL_SPI_DATAWIDTH_24BIT) \
|| ((__VALUE__) == LL_SPI_DATAWIDTH_25BIT) \
|| ((__VALUE__) == LL_SPI_DATAWIDTH_26BIT) \
|| ((__VALUE__) == LL_SPI_DATAWIDTH_27BIT) \
|| ((__VALUE__) == LL_SPI_DATAWIDTH_28BIT) \
|| ((__VALUE__) == LL_SPI_DATAWIDTH_29BIT) \
|| ((__VALUE__) == LL_SPI_DATAWIDTH_30BIT) \
|| ((__VALUE__) == LL_SPI_DATAWIDTH_31BIT) \
|| ((__VALUE__) == LL_SPI_DATAWIDTH_32BIT))
#define IS_LL_SPI_FIFO_TH(__VALUE__) (((__VALUE__) == LL_SPI_FIFO_TH_01DATA) \
|| ((__VALUE__) == LL_SPI_FIFO_TH_02DATA) \
|| ((__VALUE__) == LL_SPI_FIFO_TH_03DATA) \
|| ((__VALUE__) == LL_SPI_FIFO_TH_04DATA) \
|| ((__VALUE__) == LL_SPI_FIFO_TH_05DATA) \
|| ((__VALUE__) == LL_SPI_FIFO_TH_06DATA) \
|| ((__VALUE__) == LL_SPI_FIFO_TH_07DATA) \
|| ((__VALUE__) == LL_SPI_FIFO_TH_08DATA) \
|| ((__VALUE__) == LL_SPI_FIFO_TH_09DATA) \
|| ((__VALUE__) == LL_SPI_FIFO_TH_10DATA) \
|| ((__VALUE__) == LL_SPI_FIFO_TH_11DATA) \
|| ((__VALUE__) == LL_SPI_FIFO_TH_12DATA) \
|| ((__VALUE__) == LL_SPI_FIFO_TH_13DATA) \
|| ((__VALUE__) == LL_SPI_FIFO_TH_14DATA) \
|| ((__VALUE__) == LL_SPI_FIFO_TH_15DATA) \
|| ((__VALUE__) == LL_SPI_FIFO_TH_16DATA))
#define IS_LL_SPI_CRC(__VALUE__) (((__VALUE__) == LL_SPI_CRC_4BIT) \
|| ((__VALUE__) == LL_SPI_CRC_5BIT) \
|| ((__VALUE__) == LL_SPI_CRC_6BIT) \
|| ((__VALUE__) == LL_SPI_CRC_7BIT) \
|| ((__VALUE__) == LL_SPI_CRC_8BIT) \
|| ((__VALUE__) == LL_SPI_CRC_9BIT) \
|| ((__VALUE__) == LL_SPI_CRC_10BIT) \
|| ((__VALUE__) == LL_SPI_CRC_11BIT) \
|| ((__VALUE__) == LL_SPI_CRC_12BIT) \
|| ((__VALUE__) == LL_SPI_CRC_13BIT) \
|| ((__VALUE__) == LL_SPI_CRC_14BIT) \
|| ((__VALUE__) == LL_SPI_CRC_15BIT) \
|| ((__VALUE__) == LL_SPI_CRC_16BIT) \
|| ((__VALUE__) == LL_SPI_CRC_17BIT) \
|| ((__VALUE__) == LL_SPI_CRC_18BIT) \
|| ((__VALUE__) == LL_SPI_CRC_19BIT) \
|| ((__VALUE__) == LL_SPI_CRC_20BIT) \
|| ((__VALUE__) == LL_SPI_CRC_21BIT) \
|| ((__VALUE__) == LL_SPI_CRC_22BIT) \
|| ((__VALUE__) == LL_SPI_CRC_23BIT) \
|| ((__VALUE__) == LL_SPI_CRC_24BIT) \
|| ((__VALUE__) == LL_SPI_CRC_25BIT) \
|| ((__VALUE__) == LL_SPI_CRC_26BIT) \
|| ((__VALUE__) == LL_SPI_CRC_27BIT) \
|| ((__VALUE__) == LL_SPI_CRC_28BIT) \
|| ((__VALUE__) == LL_SPI_CRC_29BIT) \
|| ((__VALUE__) == LL_SPI_CRC_30BIT) \
|| ((__VALUE__) == LL_SPI_CRC_31BIT) \
|| ((__VALUE__) == LL_SPI_CRC_32BIT))
#define IS_LL_SPI_NSS(__VALUE__) (((__VALUE__) == LL_SPI_NSS_SOFT) \
|| ((__VALUE__) == LL_SPI_NSS_HARD_INPUT) \
|| ((__VALUE__) == LL_SPI_NSS_HARD_OUTPUT))
#define IS_LL_SPI_RX_FIFO(__VALUE__) (((__VALUE__) == LL_SPI_RX_FIFO_0PACKET) \
|| ((__VALUE__) == LL_SPI_RX_FIFO_1PACKET) \
|| ((__VALUE__) == LL_SPI_RX_FIFO_2PACKET) \
|| ((__VALUE__) == LL_SPI_RX_FIFO_3PACKET))
#define IS_LL_SPI_CRCCALCULATION(__VALUE__) (((__VALUE__) == LL_SPI_CRCCALCULATION_ENABLE) \
|| ((__VALUE__) == LL_SPI_CRCCALCULATION_DISABLE))
#define IS_LL_SPI_CRC_POLYNOMIAL(__VALUE__) ((__VALUE__) >= 0x1UL)
/**
* @}
*/
/* Private function prototypes -----------------------------------------------*/
/* Exported functions --------------------------------------------------------*/
/** @addtogroup SPI_LL_Exported_Functions
* @{
*/
/** @addtogroup SPI_LL_EF_Init
* @{
*/
/**
* @brief De-initialize the SPI registers to their default reset values.
* @param SPIx SPI Instance
* @retval An ErrorStatus enumeration value:
* - SUCCESS: SPI registers are de-initialized
* - ERROR: SPI registers are not de-initialized
*/
ErrorStatus LL_SPI_DeInit(SPI_TypeDef *SPIx)
{
ErrorStatus status = ERROR;
/* Check the parameters */
assert_param(IS_SPI_ALL_INSTANCE(SPIx));
#if defined(SPI1)
if (SPIx == SPI1)
{
/* Force reset of SPI clock */
LL_APB2_GRP1_ForceReset(LL_APB2_GRP1_PERIPH_SPI1);
/* Release reset of SPI clock */
LL_APB2_GRP1_ReleaseReset(LL_APB2_GRP1_PERIPH_SPI1);
status = SUCCESS;
}
#endif /* SPI1 */
#if defined(SPI2)
if (SPIx == SPI2)
{
/* Force reset of SPI clock */
LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_SPI2);
/* Release reset of SPI clock */
LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_SPI2);
status = SUCCESS;
}
#endif /* SPI2 */
#if defined(SPI3)
if (SPIx == SPI3)
{
/* Force reset of SPI clock */
LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_SPI3);
/* Release reset of SPI clock */
LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_SPI3);
status = SUCCESS;
}
#endif /* SPI3 */
#if defined(SPI4)
if (SPIx == SPI4)
{
/* Force reset of SPI clock */
LL_APB2_GRP1_ForceReset(LL_APB2_GRP1_PERIPH_SPI4);
/* Release reset of SPI clock */
LL_APB2_GRP1_ReleaseReset(LL_APB2_GRP1_PERIPH_SPI4);
status = SUCCESS;
}
#endif /* SPI4 */
#if defined(SPI5)
if (SPIx == SPI5)
{
/* Force reset of SPI clock */
LL_APB2_GRP1_ForceReset(LL_APB2_GRP1_PERIPH_SPI5);
/* Release reset of SPI clock */
LL_APB2_GRP1_ReleaseReset(LL_APB2_GRP1_PERIPH_SPI5);
status = SUCCESS;
}
#endif /* SPI5 */
#if defined(SPI6)
if (SPIx == SPI6)
{
/* Force reset of SPI clock */
LL_APB4_GRP1_ForceReset(LL_APB4_GRP1_PERIPH_SPI6);
/* Release reset of SPI clock */
LL_APB4_GRP1_ReleaseReset(LL_APB4_GRP1_PERIPH_SPI6);
status = SUCCESS;
}
#endif /* SPI6 */
return status;
}
/**
* @brief Initialize the SPI registers according to the specified parameters in SPI_InitStruct.
* @note As some bits in SPI configuration registers can only be written when the SPI is disabled (SPI_CR1_SPE bit =0),
* SPI IP should be in disabled state prior calling this function. Otherwise, ERROR result will be returned.
* @param SPIx SPI Instance
* @param SPI_InitStruct pointer to a @ref LL_SPI_InitTypeDef structure
* @retval An ErrorStatus enumeration value. (Return always SUCCESS)
*/
ErrorStatus LL_SPI_Init(SPI_TypeDef *SPIx, LL_SPI_InitTypeDef *SPI_InitStruct)
{
ErrorStatus status = ERROR;
uint32_t tmp_nss;
uint32_t tmp_mode;
/* Check the SPI Instance SPIx*/
assert_param(IS_SPI_ALL_INSTANCE(SPIx));
/* Check the SPI parameters from SPI_InitStruct*/
assert_param(IS_LL_SPI_TRANSFER_DIRECTION(SPI_InitStruct->TransferDirection));
assert_param(IS_LL_SPI_MODE(SPI_InitStruct->Mode));
assert_param(IS_LL_SPI_DATAWIDTH(SPI_InitStruct->DataWidth));
assert_param(IS_LL_SPI_POLARITY(SPI_InitStruct->ClockPolarity));
assert_param(IS_LL_SPI_PHASE(SPI_InitStruct->ClockPhase));
assert_param(IS_LL_SPI_NSS(SPI_InitStruct->NSS));
assert_param(IS_LL_SPI_BAUDRATEPRESCALER(SPI_InitStruct->BaudRate));
assert_param(IS_LL_SPI_BITORDER(SPI_InitStruct->BitOrder));
assert_param(IS_LL_SPI_CRCCALCULATION(SPI_InitStruct->CRCCalculation));
if (LL_SPI_IsEnabled(SPIx) == 0x00000000UL)
{
/*---------------------------- SPIx CFG1 Configuration ------------------------
* Configure SPIx CFG1 with parameters:
* - Master Baud Rate : SPI_CFG1_MBR[2:0] bits
* - CRC Computation Enable : SPI_CFG1_CRCEN bit
* - Length of data frame : SPI_CFG1_DSIZE[4:0] bits
*/
MODIFY_REG(SPIx->CFG1, SPI_CFG1_MBR | SPI_CFG1_CRCEN | SPI_CFG1_DSIZE,
SPI_InitStruct->BaudRate | SPI_InitStruct->CRCCalculation | SPI_InitStruct->DataWidth);
tmp_nss = SPI_InitStruct->NSS;
tmp_mode = SPI_InitStruct->Mode;
/* Checks to setup Internal SS signal level and avoid a MODF Error */
if ((LL_SPI_GetNSSPolarity(SPIx) == LL_SPI_NSS_POLARITY_LOW) && (tmp_nss == LL_SPI_NSS_SOFT) && (tmp_mode == LL_SPI_MODE_MASTER))
{
LL_SPI_SetInternalSSLevel(SPIx, LL_SPI_SS_LEVEL_HIGH);
}
/*---------------------------- SPIx CFG2 Configuration ------------------------
* Configure SPIx CFG2 with parameters:
* - NSS management : SPI_CFG2_SSM, SPI_CFG2_SSOE bits
* - ClockPolarity : SPI_CFG2_CPOL bit
* - ClockPhase : SPI_CFG2_CPHA bit
* - BitOrder : SPI_CFG2_LSBFRST bit
* - Master/Slave Mode : SPI_CFG2_MASTER bit
* - SPI Mode : SPI_CFG2_COMM[1:0] bits
*/
MODIFY_REG(SPIx->CFG2, SPI_CFG2_SSM | SPI_CFG2_SSOE |
SPI_CFG2_CPOL | SPI_CFG2_CPHA |
SPI_CFG2_LSBFRST | SPI_CFG2_MASTER | SPI_CFG2_COMM,
SPI_InitStruct->NSS | SPI_InitStruct->ClockPolarity |
SPI_InitStruct->ClockPhase | SPI_InitStruct->BitOrder |
SPI_InitStruct->Mode | (SPI_InitStruct->TransferDirection & SPI_CFG2_COMM));
/*---------------------------- SPIx CR1 Configuration ------------------------
* Configure SPIx CR1 with parameter:
* - Half Duplex Direction : SPI_CR1_HDDIR bit
*/
MODIFY_REG(SPIx->CR1, SPI_CR1_HDDIR, SPI_InitStruct->TransferDirection & SPI_CR1_HDDIR);
/*---------------------------- SPIx CRCPOLY Configuration ----------------------
* Configure SPIx CRCPOLY with parameter:
* - CRCPoly : CRCPOLY[31:0] bits
*/
if (SPI_InitStruct->CRCCalculation == LL_SPI_CRCCALCULATION_ENABLE)
{
assert_param(IS_LL_SPI_CRC_POLYNOMIAL(SPI_InitStruct->CRCPoly));
LL_SPI_SetCRCPolynomial(SPIx, SPI_InitStruct->CRCPoly);
}
/* Activate the SPI mode (Reset I2SMOD bit in I2SCFGR register) */
CLEAR_BIT(SPIx->I2SCFGR, SPI_I2SCFGR_I2SMOD);
status = SUCCESS;
}
return status;
}
/**
* @brief Set each @ref LL_SPI_InitTypeDef field to default value.
* @param SPI_InitStruct pointer to a @ref LL_SPI_InitTypeDef structure
* whose fields will be set to default values.
* @retval None
*/
void LL_SPI_StructInit(LL_SPI_InitTypeDef *SPI_InitStruct)
{
/* Set SPI_InitStruct fields to default values */
SPI_InitStruct->TransferDirection = LL_SPI_FULL_DUPLEX;
SPI_InitStruct->Mode = LL_SPI_MODE_SLAVE;
SPI_InitStruct->DataWidth = LL_SPI_DATAWIDTH_8BIT;
SPI_InitStruct->ClockPolarity = LL_SPI_POLARITY_LOW;
SPI_InitStruct->ClockPhase = LL_SPI_PHASE_1EDGE;
SPI_InitStruct->NSS = LL_SPI_NSS_HARD_INPUT;
SPI_InitStruct->BaudRate = LL_SPI_BAUDRATEPRESCALER_DIV2;
SPI_InitStruct->BitOrder = LL_SPI_MSB_FIRST;
SPI_InitStruct->CRCCalculation = LL_SPI_CRCCALCULATION_DISABLE;
SPI_InitStruct->CRCPoly = 7UL;
}
/** @addtogroup I2S_LL
* @{
*/
/* Private types -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private constants ---------------------------------------------------------*/
/** @defgroup I2S_LL_Private_Constants I2S Private Constants
* @{
*/
/* I2S registers Masks */
#define I2S_I2SCFGR_CLEAR_MASK (SPI_I2SCFGR_CHLEN | SPI_I2SCFGR_DATLEN | \
SPI_I2SCFGR_DATFMT | SPI_I2SCFGR_CKPOL | \
SPI_I2SCFGR_I2SSTD | SPI_I2SCFGR_MCKOE | \
SPI_I2SCFGR_I2SCFG | SPI_I2SCFGR_I2SMOD )
/**
* @}
*/
/* Private macros ------------------------------------------------------------*/
/** @defgroup I2S_LL_Private_Macros I2S Private Macros
* @{
*/
#define IS_LL_I2S_DATAFORMAT(__VALUE__) (((__VALUE__) == LL_I2S_DATAFORMAT_16B) \
|| ((__VALUE__) == LL_I2S_DATAFORMAT_16B_EXTENDED) \
|| ((__VALUE__) == LL_I2S_DATAFORMAT_24B) \
|| ((__VALUE__) == LL_I2S_DATAFORMAT_24B_LEFT_ALIGNED) \
|| ((__VALUE__) == LL_I2S_DATAFORMAT_32B))
#define IS_LL_I2S_CHANNEL_LENGTH_TYPE (__VALUE__) (((__VALUE__) == LL_I2S_SLAVE_VARIABLE_CH_LENGTH) \
|| ((__VALUE__) == LL_I2S_SLAVE_FIXED_CH_LENGTH))
#define IS_LL_I2S_CKPOL(__VALUE__) (((__VALUE__) == LL_I2S_POLARITY_LOW) \
|| ((__VALUE__) == LL_I2S_POLARITY_HIGH))
#define IS_LL_I2S_STANDARD(__VALUE__) (((__VALUE__) == LL_I2S_STANDARD_PHILIPS) \
|| ((__VALUE__) == LL_I2S_STANDARD_MSB) \
|| ((__VALUE__) == LL_I2S_STANDARD_LSB) \
|| ((__VALUE__) == LL_I2S_STANDARD_PCM_SHORT) \
|| ((__VALUE__) == LL_I2S_STANDARD_PCM_LONG))
#define IS_LL_I2S_MODE(__VALUE__) (((__VALUE__) == LL_I2S_MODE_SLAVE_TX) \
|| ((__VALUE__) == LL_I2S_MODE_SLAVE_RX) \
|| ((__VALUE__) == LL_I2S_MODE_SLAVE_FULL_DUPLEX) \
|| ((__VALUE__) == LL_I2S_MODE_MASTER_TX) \
|| ((__VALUE__) == LL_I2S_MODE_MASTER_RX) \
|| ((__VALUE__) == LL_I2S_MODE_MASTER_FULL_DUPLEX))
#define IS_LL_I2S_MCLK_OUTPUT(__VALUE__) (((__VALUE__) == LL_I2S_MCLK_OUTPUT_ENABLE) \
|| ((__VALUE__) == LL_I2S_MCLK_OUTPUT_DISABLE))
#define IS_LL_I2S_AUDIO_FREQ(__VALUE__) ((((__VALUE__) >= LL_I2S_AUDIOFREQ_8K) \
&& ((__VALUE__) <= LL_I2S_AUDIOFREQ_192K)) \
|| ((__VALUE__) == LL_I2S_AUDIOFREQ_DEFAULT))
#define IS_LL_I2S_PRESCALER_LINEAR(__VALUE__) ((__VALUE__) <= 0xFFUL)
#define IS_LL_I2S_PRESCALER_PARITY(__VALUE__) (((__VALUE__) == LL_I2S_PRESCALER_PARITY_EVEN) \
|| ((__VALUE__) == LL_I2S_PRESCALER_PARITY_ODD))
#define IS_LL_I2S_FIFO_TH (__VALUE__) (((__VALUE__) == LL_I2S_LL_I2S_FIFO_TH_01DATA) \
|| ((__VALUE__) == LL_I2S_LL_I2S_FIFO_TH_02DATA) \
|| ((__VALUE__) == LL_I2S_LL_I2S_FIFO_TH_03DATA) \
|| ((__VALUE__) == LL_I2S_LL_I2S_FIFO_TH_04DATA) \
|| ((__VALUE__) == LL_I2S_LL_I2S_FIFO_TH_05DATA) \
|| ((__VALUE__) == LL_I2S_LL_I2S_FIFO_TH_06DATA) \
|| ((__VALUE__) == LL_I2S_LL_I2S_FIFO_TH_07DATA) \
|| ((__VALUE__) == LL_I2S_LL_I2S_FIFO_TH_08DATA))
#define IS_LL_I2S_BIT_ORDER(__VALUE__) (((__VALUE__) == LL_I2S_LSB_FIRST) \
|| ((__VALUE__) == LL_I2S_MSB_FIRST))
/**
* @}
*/
/* Private function prototypes -----------------------------------------------*/
/* Exported functions --------------------------------------------------------*/
/** @addtogroup I2S_LL_Exported_Functions
* @{
*/
/** @addtogroup I2S_LL_EF_Init
* @{
*/
/**
* @brief De-initialize the SPI/I2S registers to their default reset values.
* @param SPIx SPI Instance
* @retval An ErrorStatus enumeration value:
* - SUCCESS: SPI registers are de-initialized
* - ERROR: SPI registers are not de-initialized
*/
ErrorStatus LL_I2S_DeInit(SPI_TypeDef *SPIx)
{
return LL_SPI_DeInit(SPIx);
}
/**
* @brief Initializes the SPI/I2S registers according to the specified parameters in I2S_InitStruct.
* @note As some bits in I2S configuration registers can only be written when the SPI is disabled (SPI_CR1_SPE bit =0),
* SPI IP should be in disabled state prior calling this function. Otherwise, ERROR result will be returned.
* @note I2S (SPI) source clock must be ready before calling this function. Otherwise will results in wrong programming.
* @param SPIx SPI Instance
* @param I2S_InitStruct pointer to a @ref LL_I2S_InitTypeDef structure
* @retval An ErrorStatus enumeration value:
* - SUCCESS: SPI registers are Initialized
* - ERROR: SPI registers are not Initialized
*/
ErrorStatus LL_I2S_Init(SPI_TypeDef *SPIx, LL_I2S_InitTypeDef *I2S_InitStruct)
{
uint32_t i2sdiv = 0UL, i2sodd = 0UL, packetlength = 1UL, ispcm = 0UL;
uint32_t tmp;
uint32_t sourceclock;
ErrorStatus status = ERROR;
/* Check the I2S parameters */
assert_param(IS_I2S_ALL_INSTANCE(SPIx));
assert_param(IS_LL_I2S_MODE(I2S_InitStruct->Mode));
assert_param(IS_LL_I2S_STANDARD(I2S_InitStruct->Standard));
assert_param(IS_LL_I2S_DATAFORMAT(I2S_InitStruct->DataFormat));
assert_param(IS_LL_I2S_MCLK_OUTPUT(I2S_InitStruct->MCLKOutput));
assert_param(IS_LL_I2S_AUDIO_FREQ(I2S_InitStruct->AudioFreq));
assert_param(IS_LL_I2S_CKPOL(I2S_InitStruct->ClockPolarity));
/* Check that SPE bit is set to 0 in order to be sure that SPI/I2S block is disabled.
* In this case, it is useless to check if the I2SMOD bit is set to 0 because
* this bit I2SMOD only serves to select the desired mode.
*/
if (LL_SPI_IsEnabled(SPIx) == 0x00000000UL)
{
/*---------------------------- SPIx I2SCFGR Configuration --------------------
* Configure SPIx I2SCFGR with parameters:
* - Mode : SPI_I2SCFGR_I2SCFG[2:0] bits
* - Standard : SPI_I2SCFGR_I2SSTD[1:0] and SPI_I2SCFGR_PCMSYNC bits
* - DataFormat : SPI_I2SCFGR_CHLEN, SPI_I2SCFGR_DATFMT and SPI_I2SCFGR_DATLEN[1:0] bits
* - ClockPolarity : SPI_I2SCFGR_CKPOL bit
* - MCLKOutput : SPI_I2SPR_MCKOE bit
* - I2S mode : SPI_I2SCFGR_I2SMOD bit
*/
/* Write to SPIx I2SCFGR */
MODIFY_REG(SPIx->I2SCFGR,
I2S_I2SCFGR_CLEAR_MASK,
I2S_InitStruct->Mode | I2S_InitStruct->Standard |
I2S_InitStruct->DataFormat | I2S_InitStruct->ClockPolarity |
I2S_InitStruct->MCLKOutput | SPI_I2SCFGR_I2SMOD);
/*---------------------------- SPIx I2SCFGR Configuration ----------------------
* Configure SPIx I2SCFGR with parameters:
* - AudioFreq : SPI_I2SCFGR_I2SDIV[7:0] and SPI_I2SCFGR_ODD bits
*/
/* If the requested audio frequency is not the default, compute the prescaler (i2sodd, i2sdiv)
* else, default values are used: i2sodd = 0U, i2sdiv = 0U.
*/
if (I2S_InitStruct->AudioFreq != LL_I2S_AUDIOFREQ_DEFAULT)
{
/* Check the frame length (For the Prescaler computing)
* Default value: LL_I2S_DATAFORMAT_16B (packetlength = 1U).
*/
if (I2S_InitStruct->DataFormat != LL_I2S_DATAFORMAT_16B)
{
/* Packet length is 32 bits */
packetlength = 2UL;
}
/* Check if PCM standard is used */
if ((I2S_InitStruct->Standard == LL_I2S_STANDARD_PCM_SHORT) ||
(I2S_InitStruct->Standard == LL_I2S_STANDARD_PCM_LONG))
{
ispcm = 1UL;
}
/* Get the I2S (SPI) source clock value */
sourceclock = LL_RCC_GetSPIClockFreq(LL_RCC_SPI123_CLKSOURCE);
/* Compute the Real divider depending on the MCLK output state with a fixed point */
if (I2S_InitStruct->MCLKOutput == LL_I2S_MCLK_OUTPUT_ENABLE)
{
/* MCLK output is enabled */
tmp = (((sourceclock / (256UL >> ispcm)) * 16UL) / I2S_InitStruct->AudioFreq) + 8UL;
}
else
{
/* MCLK output is disabled */
tmp = (((sourceclock / ((32UL >> ispcm) * packetlength)) * 16UL) / I2S_InitStruct->AudioFreq) + 8UL;
}
/* Remove the fixed point */
tmp = tmp / 16UL;
/* Check the parity of the divider */
i2sodd = tmp & 0x1UL;
/* Compute the i2sdiv prescaler */
i2sdiv = tmp / 2UL;
}
/* Test if the obtain values are forbiden or out of range */
if (((i2sodd == 1UL) && (i2sdiv == 1UL)) || (i2sdiv > 0xFFUL))
{
/* Set the default values */
i2sdiv = 0UL;
i2sodd = 0UL;
}
/* Write to SPIx I2SCFGR register the computed value */
MODIFY_REG(SPIx->I2SCFGR,
SPI_I2SCFGR_ODD | SPI_I2SCFGR_I2SDIV,
(i2sodd << SPI_I2SCFGR_ODD_Pos) | (i2sdiv << SPI_I2SCFGR_I2SDIV_Pos));
status = SUCCESS;
}
return status;
}
/**
* @brief Set each @ref LL_I2S_InitTypeDef field to default value.
* @param I2S_InitStruct pointer to a @ref LL_I2S_InitTypeDef structure
* whose fields will be set to default values.
* @retval None
*/
void LL_I2S_StructInit(LL_I2S_InitTypeDef *I2S_InitStruct)
{
/*--------------- Reset I2S init structure parameters values -----------------*/
I2S_InitStruct->Mode = LL_I2S_MODE_SLAVE_TX;
I2S_InitStruct->Standard = LL_I2S_STANDARD_PHILIPS;
I2S_InitStruct->DataFormat = LL_I2S_DATAFORMAT_16B;
I2S_InitStruct->MCLKOutput = LL_I2S_MCLK_OUTPUT_DISABLE;
I2S_InitStruct->AudioFreq = LL_I2S_AUDIOFREQ_DEFAULT;
I2S_InitStruct->ClockPolarity = LL_I2S_POLARITY_LOW;
}
/**
* @brief Set linear and parity prescaler.
* @note To calculate value of PrescalerLinear(I2SDIV[7:0] bits) and PrescalerParity(ODD bit)\n
* Check Audio frequency table and formulas inside Reference Manual (SPI/I2S).
* @param SPIx SPI Instance
* @param PrescalerLinear Value between Min_Data=0x00 and Max_Data=0xFF
* @note PrescalerLinear '1' is not authorized with parity LL_I2S_PRESCALER_PARITY_ODD
* @param PrescalerParity This parameter can be one of the following values:
* @arg @ref LL_I2S_PRESCALER_PARITY_EVEN
* @arg @ref LL_I2S_PRESCALER_PARITY_ODD
* @retval None
*/
void LL_I2S_ConfigPrescaler(SPI_TypeDef *SPIx, uint32_t PrescalerLinear, uint32_t PrescalerParity)
{
/* Check the I2S parameters */
assert_param(IS_I2S_ALL_INSTANCE(SPIx));
assert_param(IS_LL_I2S_PRESCALER_LINEAR(PrescalerLinear));
assert_param(IS_LL_I2S_PRESCALER_PARITY(PrescalerParity));
/* Write to SPIx I2SPR */
MODIFY_REG(SPIx->I2SCFGR, SPI_I2SCFGR_I2SDIV | SPI_I2SCFGR_ODD, (PrescalerLinear << SPI_I2SCFGR_I2SDIV_Pos) |
(PrescalerParity << SPI_I2SCFGR_ODD_Pos));
}
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
#endif /* defined(SPI1) || defined(SPI2) || defined(SPI3) || defined(SPI4) || defined(SPI5) || defined(SPI6) */
/**
* @}
*/
/**
* @}
*/
#endif /* USE_FULL_LL_DRIVER */
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
|
the_stack_data/140765184.c | #include <omp.h>
#include <stdio.h>
static long num_steps = 100000000;
double step;
#define NUM_THREADS 8
void main ()
{ int i;
double x, pi, sum = 0.0;
step = 1.0/(double) num_steps;
omp_set_num_threads(NUM_THREADS);
#pragma omp parallel for reduction(+:sum) private(x,i)
for (i=0;i<num_steps; i++){
x = (i+0.5)*step;
sum = sum + 4.0/(1.0+x*x);
}
pi = step * sum;
printf("Pi = %lf\n",pi);
}
|
the_stack_data/277410.c | /*
Problem statement: To change an Expression from Infix to Postfix
using stack in C
Algorithm:
1. At first we'll make simple push and pop function
2. If the leftmost character is an operand, set it as the current output to the Postfix string.
If the scanned character is the operator and the Stack is empty push the operator into the Stack.
3. If the scanned operator has higher priority than the existing priority operator in the Stack,
push it on the Stack.
4. If the scanned operator has lower or equal priority than the existing operator in the Stack,
pop all the Stack operators and after that push the scanned operator into the Stack.
5. If the scanned character is open parenthesis '(', always push it into the Stack.
6. If the scanned character is close parenthesis ')', pop the Stack and print all output string
character until '(' is encountered and discard both the bracket.
7. Repeat all steps from 2 to 8 until the infix expression is scanned.
8. Print the Stack output.
9. Pop and output all characters, including the operator, from the Stack until it is not empty.
*/
#include<stdio.h>
#include<ctype.h> //for alnum
#define max 100
//global variables
char stack [max];
//top is use to navigate in the stack
int top = -1;
void push (char x) //push function
{
if(top == max-1)
{
printf("\nStack Overflow.");
}
else
{
//increasing the top to next location and pushing character
stack[++top] = x ;
}
}
char pop() //pop function
{
char item;
if(top == -1)
{
printf("stack under flow: invalid infix expression");
/* underflow may occur because of invalid expression */
}
else
{
item = stack[top];
top = top-1;
return(item);
}
}
int priority(char x) //priority function
//it defines a level of precedence of a inputed character
{
if(x== '^')
return 3;
else if(x=='*' || x=='/')
return 2;
else if(x=='+' || x=='-')
return 1;
else
return 0;
}
void main()
{
char exp[20];
char*e , x;
printf("Enter an Infix expression: ");
scanf("%s",&exp);
e=exp;
printf("Its Post fix expression is: ");
while(*e!='\0')
//this loop will iterate untill value in *e become NULL
{
if(isalnum(*e))
{
//isalnum checks whether a given element is alphabet or number
printf("%c",*e);
}
else if(*e == '(')
{
//checks if the value on *e is '('
push(*e);
}
else if(*e == ')')
{
//checks if the value on *e is ')'
while((x = pop()) != '(')
printf("%c",x);
}
else
{
/*it means an operator is encountered so we
check its precedence by calling priority function.*/
while(priority(stack[top]) >= priority(*e))
printf("%c ",pop());
push(*e);
}
e++; //incrementing to check next character
} //end of while
while(top != -1)
{
//printing all the remaining elements in the stack
printf("%c ",pop());
}
} //end of main
/*
INPUT 1:
Enter an Infix expression: a*(b+c)
OUTPUT 1:
Its Post fix expression is: abc+*
INPUT 2:
Enter an Infix expression: ((A+B)*C-D)*E
OUTPUT 2:
Its Post fix expression is: AB+C* D-E*
Time Complexity : O(n^2)
as expression is iterated two
times simultaneously, firstly for scanning the infix expression
and secondly while poping out of stack.
Space Complexity : O(n)
For storing Infix expression of n literals the space complexity
is O(n) and for stack to hold atmost n literals the space complexity
is O(n), hence
Total space complexity is O(n+n) = O(2n) i.e : O(n)
*/
|
the_stack_data/72011997.c | #include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdlib.h>
int main() {
pid_t pid = fork();
if (pid == 0) {
char *args[] = {NULL};
execvp("./mycat", args);
exit(0);
}
else {
pid_t child = wait(NULL);
fprintf(stdout, "Parent : The child has terminated.\n");
exit(0);
}
}
|
the_stack_data/119171.c | /* Framework for the sorting programs.
* Program: 02
* Course: CS333 A0 - Spring 2010
* Author: Alejandro G. Carlstein
* Description: This program will read a set of integers from standard
* input and sort them by implement a heap sort using the pseudocode
* from the book Introduction to Algorithms" by Thomas H. Cormen.
* Then print them out in sorted order (smallest to largest).
*/
#include <stdio.h>
#define MAX_SIZE 1000000
#define LEFT(i) ((i << 1) + 1)
#define RIGHT(i) ((i << 1) + 2)
#define DIV_BY_2(i) (i >> 1)
void Max_heapify(int array[], int i, int heap_size);
void Build_max_heap(int array[], int heap_size);
void Exchange(int *a, int *b);
void Heapsort(int array[], int length);
int data[MAX_SIZE];
int n;
int main(int argc, char* argv[]){
int i;
int heap_size;
/* Read in the data */
n = 0;
while (scanf("%d", &data[n]) == 1)
++n;
/* Sort the numbers low to high */
Heapsort(data, n);
/* Print out the data */
for (i = 0; i < n; ++i)
printf("%d\n", data[i]);
return 0;
}
/*
* Max_heapify helps to rebuild the heap region
*/
void Max_heapify(int array[], int i, int heap_size){
int l, r, temp, largest;
l = LEFT(i);
r = RIGHT(i);
// Find Largest value
largest = (l < heap_size && array[l] > array[i]) ? l : i;
if (r < heap_size && array[r] > array[largest]) largest = r;
if (largest != i){
// Exchange
Exchange(&array[i], &array[largest]);
// Rebuild heap region
Max_heapify(array, largest, heap_size);
}// end if
}
/*
* Build_max_heap helps to build the initial heap
*/
void Build_max_heap(int array[], int heap_size){
int i = DIV_BY_2(heap_size);
for (; i > -1; i--){
Max_heapify(array, i, heap_size);
}//end for
}
/*
* Exchange swap the values holded by two variables
*/
void Exchange(int *a, int *b){
int temp;
temp = *a;
*a = *b;
*b = temp;
}
/*
* Heapsort sort an array from the smallest element to the largest
*/
void Heapsort(int array[], int length){
int i;
int heap_size = length ;
Build_max_heap(data, length);
for (i = (length - 1) ; i > 0; --i){
// Exchange the largest item in the heap region
// to the beginning of the sorted region
Exchange(&data[0], &data[i]);
// Reduce the heap region, increase the sorted region
heap_size--;
// Rebuild the heap region
Max_heapify(data, 0, heap_size);
}//end for
}
|
the_stack_data/36386.c | /*
count_max
*/
#include<stdio.h>
#include<limits.h>
int countMax(int* arData, int N){
int i,c=0,m=INT_MIN;
for(i=0;i<N;i++){
if(arData[i]>m){
m = arData[i];
c = 1;
}else if(arData[i] == m){
c++;
}
}
return c;
}
int main(){
int i,n,arr[10000];
scanf("%d",&n);
for(i=0;i<n;i++){
scanf("%d",&arr[i]);
}
printf("%d",countMax(arr,n));
return 0;
}
|
the_stack_data/97012343.c | /*--------------------------------------------------------------------
EECS 325, Spring 2019
Yue Shu, yxs626
Project 1
conference server
--------------------------------------------------------------------*/
#include <stdio.h>
#include <fcntl.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <time.h>
#include <errno.h>
#include <stdlib.h>
extern char * recvdata(int sd);
extern int senddata(int sd, char *msg);
extern int startserver();
/*--------------------------------------------------------------------*/
/*--------------------------------------------------------------------*/
main(int argc, char *argv[]) {
int serversock; /* server socket*/
fd_set liveskset, tempset; /* set of live client sockets */
int liveskmax; /* maximum socket */
/* check usage */
if (argc != 1) {
fprintf(stderr, "usage : %s\n", argv[0]);
exit(1);
}
/* get ready to receive requests */
serversock = startserver();
if (serversock == -1) {
exit(1);
}
/* init the live client set and its temp set to call select() on */
FD_ZERO(&liveskset);
FD_ZERO(&tempset);
/* add server socket to the live socket set */
FD_SET(serversock, &liveskset);
liveskmax = serversock;
/* receive and process requests */
while (1) {
tempset = liveskset; /* copy the master set */
int itsock; /* loop variable */
/* using select() to serve both live and new clients */
if (select(liveskmax + 1, &tempset, NULL, NULL, NULL) == -1) {
error("ERROR on select");
exit(4);
}
/* process messages from clients */
for (itsock = 3; itsock <= liveskmax; itsock++) {
/* skip the listen socket */
if (itsock == serversock) continue;
/* if receive message from client */
if (FD_ISSET(itsock, &tempset)) {
char * clienthost; /* host name of the client */
ushort clientport; /* port number of the client */
/* obtain client's host name and port using getpeername() and gethostbyaddr() */
struct sockaddr_in clientaddr;
bzero(&clientaddr, sizeof(clientaddr));
int client_len = sizeof(clientaddr);
/* get client's address */
if (getpeername(itsock, (struct sockaddr*)&clientaddr, (socklen_t*)&client_len) == -1) {
error("getpeername() failed");
return -1;
}
/* get client's port number */
clientport = ntohs(clientaddr.sin_port);
struct hostent *client;
client = gethostbyaddr((const char*)&clientaddr.sin_addr,
sizeof(clientaddr.sin_addr), AF_INET);
/* get client's host name */
clienthost = client->h_name;
/* read the message */
char * msg = recvdata(itsock);
/* if client has exited */
if (!msg) {
/* disconnect from client */
printf("admin: disconnect from '%s(%hu)'\n", clienthost, clientport);
/* remove this client from 'liveskset', close the socket */
FD_CLR(itsock, &liveskset);
close(itsock);
free(msg);
}
/* if received message from live client */
else {
/* send the message to other clients through a loop */
int j;
for (j = 3; j <= liveskmax; j++) {
if (FD_ISSET(j, &liveskset)) {
if (j != serversock && j != itsock)
senddata(j, msg);
}
}
/* print the message on the server site */
printf("%s(%hu): %s", clienthost, clientport, msg);
free(msg);
}
}
}
/* if new client has connected */
if (FD_ISSET(serversock, &tempset)) {
/* accept the new connection request */
struct sockaddr_in clientaddr;
bzero(&clientaddr, sizeof(clientaddr));
socklen_t clilen = sizeof(clientaddr);
int newsockfd = accept(serversock, (struct sockaddr *) &clientaddr, &clilen);
/* if connection successfully established */
if (newsockfd >= 0) {
char * clienthost; /* host name of the client */
ushort clientport; /* port number of the client */
/* get client's host name and port using gethostbyaddr() */
clientport = ntohs(clientaddr.sin_port);
struct hostent *client;
client = gethostbyaddr((const char*)&clientaddr.sin_addr,
sizeof(clientaddr.sin_addr), AF_INET);
/* get client's host name */
clienthost = client->h_name;
printf("admin: connect from '%s' at '%hu'\n", clienthost, clientport);
/* add the new client to the 'liveskset' */
FD_SET(newsockfd, &liveskset);
if (newsockfd > liveskmax)
liveskmax = newsockfd;
}
else {
perror("accept");
exit(0);
}
}
}
}
/*--------------------------------------------------------------------*/
|
the_stack_data/10748.c | #include <stdio.h>
#define MAX_SIZE 1024
int main(){
char *line[MAX_SIZE];
size_t size;
while(getline(line, &size, stdin) != -1)
printf("%s", *line);
return 0;
} |
the_stack_data/923516.c | //clang -Xclang -ast-dump -fsyntax-only *.c
#include <stdio.h>
long long a = 100;
long long b = 20;
long long c = 15;
int main() {
printf("%lld\n", a);
printf("%lld\n", b);
printf("%lld\n", c);
a *= c;
printf("%lld\n", a);
return 0;
}
|
the_stack_data/5618.c | #include <stdio.h>
#include <stdlib.h>
int main() {
float area, raio;
printf("Digite o valor do raio:");
scanf("%f", &raio);
area = 3.1415 * raio*raio;
printf("%f",area);
getch();
return 0; //
} |
the_stack_data/13993.c | /*
* Copyright (c) 2017, 2018, Oracle and/or its affiliates.
*
* 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. Neither the name of the copyright holder nor the names of its contributors may be used to
* endorse or promote products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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
* COPYRIGHT HOLDER OR CONTRIBUTORS 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.
*/
typedef enum asdf typedefenum;
enum asdf { E1, E2 };
int main() {
typedefenum test = E2;
return test;
}
|
the_stack_data/87638938.c | /*******************************************************************************
* Copyright (c) 2010-2018 Analog Devices, Inc.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* - 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.
* - Modified versions of the software must be conspicuously marked as such.
* - This software is licensed solely and exclusively for use with processors
* manufactured by or for Analog Devices, Inc.
* - This software may not be combined or merged with other code in any manner
* that would cause the software to become subject to terms and conditions
* which differ from those listed here.
* - Neither the name of Analog Devices, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
* - The use of this software may or may not infringe the patent rights of one
* or more patent holders. This license does not release you from the
* requirement that you obtain separate licenses from these patent holders
* to use this software.
*
* THIS SOFTWARE IS PROVIDED BY ANALOG DEVICES, INC. AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, NON-
* INFRINGEMENT, TITLE, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL ANALOG DEVICES, INC. OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, PUNITIVE OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, DAMAGES ARISING OUT OF
* CLAIMS OF INTELLECTUAL PROPERTY RIGHTS INFRINGEMENT; 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.
******************************************************************************/
#if DEVICE_FLASH
#include "flash_api.h"
#include "flash_data.h"
#include "mbed_critical.h"
// This file is automagically generated
// This is a flash algo binary blob. It is PIC (position independent code) that should be stored in RAM
static unsigned FLASH_ALGO[] = {
0x20004A4B,0x60111E41,0x6211494A,0x60912107,0x074B6811,0xF011D5FC,0xD0000F30,0x21002001,
0x47706211,0x2400B510,0xD1082A01,0xF872F000,0x6D09493F,0xD00207C8,0xFFE2F7FF,0x46204604,
0x493BBD10,0x62082000,0xB5104770,0xF862F000,0x4010E8BD,0x4601E7D4,0x20004A35,0x60131E43,
0x49346191,0x21066211,0x68116091,0xD5FC074B,0x0F30F011,0x2001D000,0x62112100,0xB57C4770,
0x4B2C4C2B,0x62232500,0xF04FE03E,0x602333FF,0xD3042908,0x61236813,0x61636853,0xF04FE025,
0xE9CD33FF,0x29083300,0xE8DFD21A,0x1619F001,0x0A0D1013,0x79910407,0x1006F88D,0xF88D7951,
0x79111005,0x1004F88D,0xF88D78D1,0x78911003,0x1002F88D,0xF88D7851,0x78111001,0x1000F88D,
0x1300E9DD,0x61636121,0x60E02108,0x60A32304,0xF0136823,0xD0010F30,0xE0072501,0x075B6823,
0x3008D5FC,0x32083908,0xD1BE2900,0x62202000,0xBD7C4628,0x21004806,0x4A066041,0x4A066202,
0x22046342,0x22016382,0x62016542,0x00004770,0x40018000,0x676C7565,0xB8950950,0
};
static const flash_algo_t flash_algo_config = {
.init = 0x00000025,
.uninit = 0x00000043,
.erase_sector = 0x00000057,
.program_page = 0x0000007F,
.static_base = 0x0000013C,
.algo_blob = (uint32_t *)FLASH_ALGO
};
static const sector_info_t sectors_info[] = {
{0x0, 0x800},
};
static const flash_target_config_t flash_target_config = {
.page_size = 0x8, // minimal programmable unit size
.flash_start = 0x0,
.flash_size = 0x0007F000,
.sectors = sectors_info,
.sector_info_count = sizeof(sectors_info) / sizeof(sector_info_t)
};
void flash_set_target_config(flash_t *obj)
{
obj->flash_algo = &flash_algo_config;
obj->target_config = &flash_target_config;
}
#endif
|
the_stack_data/43888036.c | int main(){
int i;
i = 3;
while(i){
printf("i = %d\n",i);
i--;
}
return 0;
}
|
the_stack_data/154126.c | /*
* correct the sign error in stanford fft.c program
* normalized for the inverse transform i.e. (sign < 0.)
* jeff g. s. pan feb '85
*/
/*
* AS WRITTEN THIS CALCULATES Y(f)= SUM X(t)exp(+i omega t) when asign=1
*/
#include "stdio.h"
#include "math.h"
char *alloc (size)
int size;
/*
* allocation with error detection
*/
{
char *ptr, *calloc();
if ((ptr = calloc (size,1)) <= 0)
err_("cant allocate %d bytes \n",size);
return (ptr);
}
refft_(x,ane,asign,amode)
register struct complex {float re, im;} *x;
int *ane, *asign, *amode;
/*
* radix 2 real <=> complex fast fourier transform
* x is the in place vector, n is the power of two transform length
* sign:
* 1 forward transform
* -1 backward transform (will preserve parceval's thrm)
* mode:
* 1 real to complex; real nyquist part in imaginary dc
* -1 complex to real; real nyquist part expected in imaginary dc
* 2 real to complex; unpacked
* -2 complex to real; unpacked
* scaling for postive modes
*/
{
register struct complex *xp, *yp;
int n, sign, mode, n2;
float cn, sn, cd, sd, arg, scale;
float aa, bb, ab, ba, real, imag;
double sin(), atan2();
n = *ane;
sign = *asign;
mode = *amode;
n2 = n / 2;
if (mode > 0) cefft_(x,&n2,&sign);
/* pack */
/* rfft butterfly */
if (mode == -2) x->im = x[n/2].re;
sn = 0.0;
cn = 1.0;
arg = 2. * atan2 (1.,0.) / n;
aa = sin (arg);
cd = 2.0 * aa * aa;
sd = sin (arg+arg);
if (sign < 0) sd = -sd; /* change sign for test */
aa = x->re;
bb = x->im;
if (sign > 0)
{
x->re = aa + bb;
x->im = aa - bb;
}
else
{
x->re = (aa + bb) * .5;
x->im = (bb - aa) * .5;
}
for (xp=x+1, yp=x+n/2-1; xp<=yp; xp++, yp--)
{
aa = cd * cn + sd * sn;
sn += sd * cn - cd * sn;
cn -= aa;
aa = (xp->re + yp->re) * .5;
ab = (xp->re - yp->re) * .5;
ba = (xp->im + yp->im) * .5;
bb = (xp->im - yp->im) * .5;
real = cn * ba + sn * ab;
imag = sn * ba - cn * ab;
yp->im = imag - bb;
xp->im = imag + bb;
yp->re = aa - real;
xp->re = aa + real;
}
if (0 > mode)
{
cefft_(x,&n2,&sign);
for (xp=x, yp=x+n/2; xp<yp; xp++) xp->im *= -1.;
}
/* unpack */
if (mode == 2)
{
x[n/2].re = x[0].im;
x[0].im = x[n/2].im = 0.;
}
}
cefft_(x,ane,asign)
register struct complex {float re, im;} *x;
int *ane, *asign;
/*
* radix 2 complex <=> complex fourier transform
* n is the number of complex points in x
* scaling on positive sign
*/
{
register struct complex *xp, *yp;
struct complex *end;
float cn, sn, cd, sd, real, imag, scale, *psintab;
float temp;
int i=0, j=0, step=0, n, sign;
/* sines from pi/2 to pi/2097152 */
static float sintab[] =
{
1.0000000000000000e-00,
7.0710678118654747e-01,
3.8268343236508974e-01,
1.9509032201612825e-01,
9.8017140329560596e-02,
4.9067674327418010e-02,
2.4541228522912286e-02,
1.2271538285719925e-02,
6.1358846491544749e-03,
3.0679567629659760e-03,
1.5339801862847655e-03,
7.6699031874270447e-04,
3.8349518757139556e-04,
1.9174759731070329e-04,
9.5873799095977337e-05,
4.7936899603066881e-05,
2.3968449808418217e-05,
1.1984224905069705e-05,
5.9921124526424274e-06,
2.9960562263346605e-06
};
n = *ane;
sign = *asign;
/* bit reverse address swapping */
for (xp=x, end=x+n, i=0; xp<end; xp++, i+=j)
{
if (xp < (yp=x+i))
{
temp = yp->re;
yp->re = xp->re;
xp->re = temp;
temp = yp->im;
yp->im = xp->im;
xp->im = temp;
}
for (j=n>>1; j>=1 && i>=j;)
{
i -= j;
j >>= 1;
}
}
/* first butterfly */
if (sign < 0) scale = 1. / n;
for (xp=x, yp=x+1; xp<end; xp+=2, yp+=2)
{
if (sign < 0)
{
xp->re *= scale;
xp->im *= scale;
yp->re *= scale;
yp->im *= scale;
}
temp = yp->re;
yp->re = xp->re - temp;
xp->re += temp;
temp = yp->im;
yp->im = xp->im - temp;
xp->im += temp;
}
/* remaining butterflies */
for (i=2, psintab=sintab; i<n; i=step)
{
step = i << 1;
sd = *psintab++;
temp = *psintab;
cd = 2.0 * temp * temp;
cn = 1.0;
sn = 0.0;
if (sign < 0) sd = -sd;
for (j=0; j<i; j++)
{
for (xp=x+j; xp<end; xp+=step)
{
yp = xp + i;
real = cn * yp->re - sn * yp->im;
imag = sn * yp->re + cn * yp->im;
yp->re = xp->re - real;
yp->im = xp->im - imag;
xp->re += real;
xp->im += imag;
}
temp = cd * cn + sd * sn;
sn += sd * cn - cd * sn;
cn -=temp;
}
}
}
err_(a,b,c,d,e,f,g,h)
char *a, *b, *c, *d, *e, *f, *g, *h;
/*
* error abortion subroutine
* a is a printf format string, while b-h are optional arguments
* I CANT FIND THIS ROUTINE SO COMMENT IT OUT -- JPARK 7/24/86
*/
{
printf("error \n");
/* fprintf (stderr,a,b,c,d,e,f,g,h);*/
exit (-1);
}
|
the_stack_data/4590.c | #include <stdint.h>
uint64_t fattRef(uint64_t n) {
if (n < 1)
return 1;
else
return (n * fattRef(n - 1));
}
|
the_stack_data/51699329.c | // Função : O sitema de avaliação de determinada disciplina, é composto por três
// provas. A primeira prova tem peso 2, a segunda tem peso 3 e a terceira prova
// tem peso 5. Faça um algoritmo para calcular a média final de um aluno desta
// disciplinae se a média for maior ou igual a 7, mostre APROVADO, se a nota for
// mostre maior que 4 e menor que 7, mostre RECUPERAÇÃO, e se a nota for a 4,
// mostre REPROVADO.
// Autor : Renato de Luna
// Data : 16/03/2018
// Revisão : 27/03/2018
#include <stdio.h>
main() {
float prova1, prova2, prova3, media_final;
printf("Digite a nota da prova 1 : ");
scanf("%f",&prova1);
printf("Digite a noda da prova 2 : ");
scanf("%f",&prova2);
printf("Digite a noda da prova 3 : ");
scanf("%f",&prova3);
prova1 = (prova1 * 2) / 10;
prova2 = (prova2 * 3) / 10;
prova3 = (prova3 * 5) / 10;
media_final = prova1 + prova2 + prova3;
if (media_final >= 7)
printf("A média final é : %f aluno APROVADO", media_final);
else if (media_final >= 4)
printf("A média final é : %f aluno em RECUPERAÇÃO", media_final);
else
printf("A média final é : %f aluno REPROVADO", media_final);
}
|
the_stack_data/42653.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): V. Mrazek, R. Hrbacek, Z. Vasicek and L. Sekanina, "EvoApprox8b: Library of approximate adders and multipliers for circuit design and benchmarking of approximation methods". Design, Automation & Test in Europe Conference & Exhibition (DATE), 2017, Lausanne, 2017, pp. 258-261. doi: 10.23919/DATE.2017.7926993
* This file contains a circuit from evoapprox8b dataset. Note that a new version of library was already published.
***/
#include <stdint.h>
#include <stdlib.h>
/// Approximate function mul8_241
/// Library = EvoApprox8b
/// Circuit = mul8_241
/// Area (180) = 4891
/// Delay (180) = 2.350
/// Power (180) = 1704.70
/// Area (45) = 366
/// Delay (45) = 0.880
/// Power (45) = 144.40
/// Nodes = 102
/// HD = 376052
/// MAE = 478.33157
/// MSE = 411598.84766
/// MRE = 8.54 %
/// WCE = 3142
/// WCRE = 300 %
/// EP = 99.1 %
uint16_t mul8_241(uint8_t a, uint8_t b)
{
uint16_t c = 0;
uint8_t n0 = (a >> 0) & 0x1;
uint8_t n2 = (a >> 1) & 0x1;
uint8_t n4 = (a >> 2) & 0x1;
uint8_t n6 = (a >> 3) & 0x1;
uint8_t n8 = (a >> 4) & 0x1;
uint8_t n10 = (a >> 5) & 0x1;
uint8_t n12 = (a >> 6) & 0x1;
uint8_t n14 = (a >> 7) & 0x1;
uint8_t n18 = (b >> 1) & 0x1;
uint8_t n20 = (b >> 2) & 0x1;
uint8_t n22 = (b >> 3) & 0x1;
uint8_t n24 = (b >> 4) & 0x1;
uint8_t n26 = (b >> 5) & 0x1;
uint8_t n28 = (b >> 6) & 0x1;
uint8_t n30 = (b >> 7) & 0x1;
uint8_t n35;
uint8_t n41;
uint8_t n42;
uint8_t n45;
uint8_t n49;
uint8_t n51;
uint8_t n53;
uint8_t n61;
uint8_t n65;
uint8_t n66;
uint8_t n67;
uint8_t n69;
uint8_t n70;
uint8_t n82;
uint8_t n87;
uint8_t n91;
uint8_t n105;
uint8_t n118;
uint8_t n120;
uint8_t n157;
uint8_t n190;
uint8_t n258;
uint8_t n261;
uint8_t n273;
uint8_t n297;
uint8_t n301;
uint8_t n306;
uint8_t n325;
uint8_t n386;
uint8_t n420;
uint8_t n460;
uint8_t n469;
uint8_t n476;
uint8_t n481;
uint8_t n482;
uint8_t n484;
uint8_t n491;
uint8_t n532;
uint8_t n564;
uint8_t n580;
uint8_t n595;
uint8_t n608;
uint8_t n682;
uint8_t n699;
uint8_t n712;
uint8_t n728;
uint8_t n729;
uint8_t n802;
uint8_t n816;
uint8_t n817;
uint8_t n832;
uint8_t n846;
uint8_t n854;
uint8_t n891;
uint8_t n906;
uint8_t n920;
uint8_t n921;
uint8_t n934;
uint8_t n950;
uint8_t n965;
uint8_t n1034;
uint8_t n1055;
uint8_t n1069;
uint8_t n1107;
uint8_t n1142;
uint8_t n1143;
uint8_t n1172;
uint8_t n1186;
uint8_t n1187;
uint8_t n1202;
uint8_t n1203;
uint8_t n1216;
uint8_t n1232;
uint8_t n1246;
uint8_t n1307;
uint8_t n1335;
uint8_t n1350;
uint8_t n1351;
uint8_t n1424;
uint8_t n1425;
uint8_t n1438;
uint8_t n1439;
uint8_t n1454;
uint8_t n1455;
uint8_t n1468;
uint8_t n1482;
uint8_t n1483;
uint8_t n1586;
uint8_t n1587;
uint8_t n1602;
uint8_t n1603;
uint8_t n1616;
uint8_t n1632;
uint8_t n1646;
uint8_t n1660;
uint8_t n1678;
uint8_t n1712;
uint8_t n1720;
uint8_t n1734;
uint8_t n1750;
uint8_t n1764;
uint8_t n1765;
uint8_t n1780;
uint8_t n1781;
uint8_t n1794;
uint8_t n1795;
uint8_t n1808;
uint8_t n1809;
uint8_t n1824;
uint8_t n1838;
uint8_t n1869;
uint8_t n1882;
uint8_t n1898;
uint8_t n1912;
uint8_t n1928;
uint8_t n1942;
uint8_t n1943;
uint8_t n1956;
uint8_t n1957;
uint8_t n1972;
uint8_t n1973;
uint8_t n1986;
uint8_t n1987;
uint8_t n2016;
n35 = (n14 & n20) | (n20 & n26) | (n14 & n26);
n41 = ~(n12 ^ n12);
n42 = ~(n6 & n28);
n45 = n41 | n20;
n49 = ~(n18 & n12);
n51 = (n41 & n0) | (n0 & n2) | (n41 & n2);
n53 = ~((n12 | n51) & n30);
n61 = ~(n12 & n28 & n14);
n65 = n41;
n66 = n65;
n67 = n65;
n69 = ~(n65 & n66);
n70 = ~(n26 | n24);
n82 = ~(n6 | n4 | n14);
n87 = n30 | n24;
n91 = ~(n87 | n28 | n35);
n105 = ~((n70 & n28) | n67);
n118 = n91 & n20;
n120 = n2 & n118;
n157 = ~((n53 & n82) | n91);
n190 = ~n69;
n258 = n2 & n28;
n261 = ~n61;
n273 = n105;
n297 = n273;
n301 = n69;
n306 = n22 | n20;
n325 = n301 | n42;
n386 = n6 | n8;
n420 = n26 & n386;
n460 = n10 & n306;
n469 = n297;
n476 = n12 & n22;
n481 = n41;
n482 = ~n53;
n484 = ~n49;
n491 = n14 & n22;
n532 = ~n325;
n564 = n8 & n24;
n580 = n10 & n24;
n595 = n12 & n24;
n608 = n14 & n24;
n682 = n8 | n306;
n699 = n10 & n26;
n712 = n12 & n26;
n728 = n14 & n26;
n729 = n14 & n26;
n802 = n8 & n28;
n816 = n10 & n28;
n817 = n10 & n28;
n832 = n12 & n28;
n846 = n14 & n28;
n854 = n595;
n891 = n4 & n30;
n906 = n6 & n30;
n920 = n8 & n30;
n921 = n8 & n30;
n934 = n10 & n30;
n950 = n12 & n30;
n965 = n14 & n30;
n1034 = n45;
n1055 = n120;
n1069 = n481 & n682;
n1107 = n491;
n1142 = n157;
n1143 = n157;
n1172 = n460 | n564;
n1186 = n476 ^ n580;
n1187 = n476 & n580;
n1202 = (n1107 ^ n854) ^ n699;
n1203 = (n1107 & n854) | (n854 & n699) | (n1107 & n699);
n1216 = n608 & n712;
n1232 = n608 ^ n712;
n1246 = ~(n1055 ^ n1034);
n1307 = n157;
n1335 = (n817 & n1069) | (n1069 & n1172) | (n817 & n1172);
n1350 = (n891 ^ n420) ^ n1186;
n1351 = (n891 & n420) | (n420 & n1186) | (n891 & n1186);
n1424 = (n1187 ^ n802) ^ n906;
n1425 = (n1187 & n802) | (n802 & n906) | (n1187 & n906);
n1438 = (n1203 ^ n816) ^ n920;
n1439 = (n1203 & n816) | (n816 & n920) | (n1203 & n920);
n1454 = (n1216 ^ n832) ^ n934;
n1455 = (n1216 & n832) | (n832 & n934) | (n1216 & n934);
n1468 = n261 & n482;
n1482 = n846 ^ n950;
n1483 = n846 & n950;
n1586 = n1350 ^ n1335;
n1587 = n1350 & n1335;
n1602 = (n1202 ^ n1216) ^ n1424;
n1603 = (n1202 & n1216) | (n1216 & n1424) | (n1202 & n1424);
n1616 = n1232 & n1438;
n1632 = n1232 ^ n1438;
n1646 = n728 & n1454;
n1660 = n728 ^ n1454;
n1678 = n1483;
n1712 = n921;
n1720 = (n1307 & n190) | (~n1307 & n1425);
n1734 = n1603 | n484;
n1750 = n1586 | n532;
n1764 = (n1602 ^ n1587) ^ n1351;
n1765 = (n1602 & n1587) | (n1587 & n1351) | (n1602 & n1351);
n1780 = (n1632 ^ n1603) ^ n1425;
n1781 = (n1632 & n1603) | (n1603 & n1425) | (n1632 & n1425);
n1794 = (n1660 ^ n1616) ^ n1439;
n1795 = (n1660 & n1616) | (n1616 & n1439) | (n1660 & n1439);
n1808 = (n1482 ^ n1646) ^ n1455;
n1809 = (n1482 & n1646) | (n1646 & n1455) | (n1482 & n1455);
n1824 = n41 & n1468;
n1838 = n965 ^ n1678;
n1869 = n469;
n1882 = n1720;
n1898 = n1734 | n258;
n1912 = n1750;
n1928 = n1764;
n1942 = n1780 ^ n1765;
n1943 = n1780 & n1765;
n1956 = (n1794 ^ n1781) ^ n1943;
n1957 = (n1794 & n1781) | (n1781 & n1943) | (n1794 & n1943);
n1972 = (n1808 ^ n1795) ^ n1957;
n1973 = (n1808 & n1795) | (n1795 & n1957) | (n1808 & n1957);
n1986 = (n1838 ^ n1809) ^ n1973;
n1987 = (n1838 & n1809) | (n1809 & n1973) | (n1838 & n1973);
n2016 = n1824 | n1987;
c |= (n729 & 0x1) << 0;
c |= (n1142 & 0x1) << 1;
c |= (n1246 & 0x1) << 2;
c |= (n1712 & 0x1) << 3;
c |= (n1869 & 0x1) << 4;
c |= (n1882 & 0x1) << 5;
c |= (n1143 & 0x1) << 6;
c |= (n1882 & 0x1) << 7;
c |= (n1898 & 0x1) << 8;
c |= (n1912 & 0x1) << 9;
c |= (n1928 & 0x1) << 10;
c |= (n1942 & 0x1) << 11;
c |= (n1956 & 0x1) << 12;
c |= (n1972 & 0x1) << 13;
c |= (n1986 & 0x1) << 14;
c |= (n2016 & 0x1) << 15;
return c;
}
|
the_stack_data/65115.c | /*
* gen_text.c
* Berlin Project
*
* Created by Nikki Chumakov on 28/01/2017.
*
* This is free and unencumbered software released into the public domain.
*
* Anyone is free to copy, modify, publish, use, compile, sell, or
* distribute this software, either in source code form or as a compiled
* binary, for any purpose, commercial or non-commercial, and by any
* means.
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
int main (int argc, char* argv[])
{
int rep = 10, len = 72;
char c = '0';
char NL = '\n';
ssize_t unusd, unused = 0;
int no_end_nl = 0;
srand ((unsigned) time (0));
for (int i=1; i<argc; ++i)
{
const char* token = strtok (argv[i], ":");
if (! token) continue;
if (strcmp (token, "new-line") == 0)
{
token = strtok (NULL, ":");
if (token) NL = *token;
}
else if (strcmp (token, "no-end-nl") == 0)
{
no_end_nl = 1;
}
else if (strcmp (token, "string") == 0)
{
token = strtok (NULL, ":");
if (token)
{
rep = atoi (token);
token = strtok (NULL, ":");
if (token)
{
c = *token;
token = strtok (NULL, ":");
if (token)
len = atoi (token);
}
}
char* buf = (char*) malloc (len+1);
memset (buf, c, len);
buf[len] = NL;
while (rep--)
{
if (no_end_nl && !rep) --len;
unused = write (1, buf, len+1);
}
free (buf);
}
else if (strcmp (token, "random1") == 0)
{
token = strtok (NULL, ":");
if (token)
{
rep = atoi (token);
token = strtok (NULL, ":");
if (token) len = atoi (token);
}
char* buf = (char*) malloc (len+1);
for (int k=0; k<len; ++k)
buf[k] = '!' + (rand() % 93);
buf[len] = NL;
while (rep--) {
if (no_end_nl && !rep) --len;
unused = write (1, buf, len+1);
}
free (buf);
}
else if (strcmp (token, "random") == 0)
{
token = strtok (NULL, ":");
if (token)
{
rep = atoi (token);
token = strtok (NULL, ":");
if (token) len = atoi (token);
}
char* buf = (char*) malloc (len+1);
buf[len] = NL;
while (rep--)
{
for (int k=0; k<len; ++k)
buf[k] = '!' + (rand() % 93);
if (no_end_nl && !rep) --len;
unused = write (1, buf, len+1);
}
free (buf);
}
}
/* making gcc and clang happy */
unusd = unused;
unused = unusd;
return 0;
}
/* vi: ts=8 et sts=2 sw=2 ai si cin :
*/
|
the_stack_data/165767038.c | /* { dg-run } */
/* { dg-require-effective-target int32plus } */
int
main ()
{
volatile int a = 0;
long long b = 2147483648LL;
int c = a % 2;
int x = ((int) -b + c) % -2147483647;
if (x != -1)
__builtin_abort ();
return 0;
}
|
the_stack_data/878478.c | /* compute proper and cumulated effects for intra01
compute proper and cumulated effects with points to for intra02
compute proper and cumulated pointer effects for intra03
*/
void bar(int ***ppp, int ***qqq) {
**ppp = **qqq;
return;
}
void inter05(){
int i = 0 , j = 1, *p = &i, *q = &j, **pp = &p, **qq = &q, ***ppp = &pp, ***qqq = &qq;
int k = 2, *r = &k;
bar(ppp,qqq);
return;
}
|
the_stack_data/85453.c | /* Copyright (C) 2000, 2002 Free Software Foundation, Inc.
This file is part of the GNU C Library.
Contributed by Ulrich Drepper <[email protected]>.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, write to the Free
Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
02111-1307 USA. */
#include <errno.h>
#include <error.h>
#include <limits.h>
#include <malloc.h>
#include <stdlib.h>
#include <stdio.h>
/* Number of samples per size. */
#define N 50000
static void
fixed_test (int size)
{
char *ptrs[N];
int i;
for (i = 0; i < N; ++i)
{
int j;
ptrs[i] = (char *) calloc (1, size);
if (ptrs[i] == NULL)
break;
for (j = 0; j < size; ++j)
{
if (ptrs[i][j] != '\0')
error (EXIT_FAILURE, 0,
"byte not cleared (size %d, element %d, byte %d)",
size, i, j);
ptrs[i][j] = '\xff';
}
}
while (i-- > 0)
free (ptrs[i]);
}
static void
random_test (void)
{
char *ptrs[N];
int i;
for (i = 0; i < N; ++i)
{
int j;
int n = 1 + random () % 10;
int elem = 1 + random () % 100;
int size = n * elem;
ptrs[i] = (char *) calloc (n, elem);
if (ptrs[i] == NULL)
break;
for (j = 0; j < size; ++j)
{
if (ptrs[i][j] != '\0')
error (EXIT_FAILURE, 0,
"byte not cleared (size %d, element %d, byte %d)",
size, i, j);
ptrs[i][j] = '\xff';
}
}
while (i-- > 0)
free (ptrs[i]);
}
static void
null_test (void)
{
/* If the size is 0 the result is implementation defined. Just make
sure the program doesn't crash. */
calloc (0, 0);
calloc (0, UINT_MAX);
calloc (UINT_MAX, 0);
calloc (0, ~((size_t) 0));
calloc (~((size_t) 0), 0);
}
int
main (void)
{
/* We are allocating blocks with `calloc' and check whether every
block is completely cleared. We first try this for some fixed
times and then with random size. */
fixed_test (15);
fixed_test (5);
fixed_test (17);
fixed_test (6);
fixed_test (31);
fixed_test (96);
random_test ();
null_test ();
return 0;
}
|
the_stack_data/150139379.c | //cmd3.c
#include<stdio.h>
int main()
{
printf("this is the cmd333333\n");
return 0;
}
|
the_stack_data/117326687.c | /*BEGIN_LEGAL
Intel Open Source License
Copyright (c) 2002-2013 Intel Corporation. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer. 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. Neither the name of
the Intel Corporation nor the names of its contributors may be used to
endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
``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 INTEL OR
ITS CONTRIBUTORS 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.
END_LEGAL */
#include <stdio.h>
int main()
{
printf(".");
return 0;
}
|
the_stack_data/67324798.c | #include <stdio.h>
#define BASE 10
int maxdec(int);
int main(int argc, char * argv[]) {
printf("%d\n", maxdec(1232012700));
return 0;
}
int maxdec(int n) {
int curr, max_rem;
if(n/BASE == 0)
return n;
else {
curr = n%BASE;
max_rem = maxdec(n/BASE);
if(curr > max_rem)
return curr;
else
return max_rem;
}
}
|
the_stack_data/117328519.c | /*=============================================================================
# FileName: test-getopt_long.c
# Desc: parse args both with -a and --all
# Author: mardyu
# Email: [email protected]
# Version: 0.0.1
# LastChange: 2015-12-03 20:17:41
# History:
=============================================================================*/
#include <stdio.h>
#include <unistd.h>
#include <getopt.h>
/*
* ./getopt_long -0 0 --aaa 11 --bbb 22 --ccc --ddd 444
* output:
* key 48, value: 0
* key 0, value: 11
* key 98, value: (null)
* key 99, value: (null)
* key 100, value: 444
*
* -----------------------
* option:
*
*
* */
int main(int argc, char **args)
{
struct option opts[] = {
{"aaa", required_argument, 0, 0},
{"bbb", no_argument, 0, 'b'},
{"ccc", optional_argument, 0, 'c'},
{"ddd", required_argument, 0, 'd'},
{0, 0, 0, 0}
};
int op = 0;
int index = -1;
while (0 <= (op = getopt_long(argc, args, "0:1", opts, &index))) {
fprintf(stdout, "key %d, value: %s, index: %d\n", op
, optarg, index);
/*
* if donot match opts elements, index value will not be changed
* , it will keep last value
* */
}
return 0;
}
|
the_stack_data/67325410.c | /*
* Copyright (c) 1983, 1993
* The Regents of the University of California. All rights reserved.
*
* %sccs.include.redist.c%
*/
#if defined(LIBC_SCCS) && !defined(lint)
static char sccsid[] = "@(#)getservbyport.c 8.1 (Berkeley) 06/04/93";
#endif /* LIBC_SCCS and not lint */
#include <netdb.h>
#include <string.h>
extern int _serv_stayopen;
struct servent *
getservbyport(port, proto)
int port;
const char *proto;
{
register struct servent *p;
setservent(_serv_stayopen);
while (p = getservent()) {
if (p->s_port != port)
continue;
if (proto == 0 || strcmp(p->s_proto, proto) == 0)
break;
}
if (!_serv_stayopen)
endservent();
return (p);
}
|
the_stack_data/95509.c | /* { dg-do run { target aarch64*-*-* } } */
/* { dg-options "-O" } */
typedef signed long long int S;
typedef unsigned long long int U;
typedef __int128 W;
__attribute__ ((noinline, noclone))
U upseu (U x, S y, int *ovf)
{
U res;
*ovf = __builtin_add_overflow (x, y, &res);
return res;
}
U
usueu (U x, U y, int *ovf)
{
U res;
*ovf = __builtin_sub_overflow (x, y, &res);
return res;
}
U
usseu (U x, S y, int *ovf)
{
U res;
*ovf = __builtin_sub_overflow (x, y, &res);
return res;
}
int
main ()
{
int i, j;
for (i = 0; i < ((unsigned char) ~0); i++)
for (j = 0; j < ((unsigned char) ~0); j++)
{
U u1 = ((W) i << ((8 - 1) * 8));
S s2 = ((W) j << ((8 - 1) * 8)) + (-0x7fffffffffffffffLL - 1);
U u2 = ((W) j << ((8 - 1) * 8));
W w;
int ovf;
w = ((W) u1) + ((W) s2);
if (upseu (u1, s2, &ovf) != (U) w || ovf != (w != (U) w))
__builtin_abort ();
w = ((W) u1) - ((W) u2);
if (usueu (u1, u2, &ovf) != (U) w || ovf != (w != (U) w))
__builtin_abort ();
w = ((W) u1) - ((W) s2);
if (usseu (u1, s2, &ovf) != (U) w || ovf != (w != (U) w))
__builtin_abort ();
}
}
|
the_stack_data/53481.c | #include<stdio.h>
int main()
{
int t,n[100000],j,i,min,swap,c,k;
scanf("%d",&t);
for(i=0; i<t; i++)
{
scanf("%d",&n[i]);
}
for(j=0; j<t; j++)
{
for (k=0; k<t-j; k++)
{
if (n[k] > n[k+1])
{
swap = n[k];
n[k] = n[k+1];
n[k+1] = swap;
}
}
}
for (c = 1; c <= t; c++)
printf("%d\n", n[c]);
return 0;
}
|
the_stack_data/220455328.c | #include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <time.h>
int TestTime()
{
FILE *stream;
char NOH[32],filename[256],o_Code[255],Limit[100];
int kb_Faux, kb_Vrai;
char MP[200];
char MP1[32];
char MP2[32];
char MP3[32];
char Tab[3][9];
char PW[4];
int l[3];
char *source[3];
char c;
char D[13];
long time1;
struct tm *time2;
int i, j, k;
kb_Faux = -1;
kb_Vrai = 0;
gethostname(NOH,31);
if ((char *) getenv("ALLEGORY") == (char *) NULL) {
fprintf(stderr,"Sorry, you should set the ALLEGORY environment variable first.\n");
exit(kb_Faux);}
sprintf(filename,"%s/CONFIG/%s.config",getenv("ALLEGORY"),NOH);
stream = fopen(filename,"r");
if (stream == (FILE *) NULL) {
fprintf(stderr,"Unable to open file %s\n",filename);
exit(kb_Faux);}
fscanf(stream,"*Magic.Clef : \"%s\n",o_Code);
if (fscanf(stream,"*Magic.Limite : \"") != EOF)
fscanf(stream,"%s\"\n",Limit);
else sprintf(Limit,"nolimit");
Tab[0][8] = 0;
Tab[1][8] = 0;
Tab[2][8] = 0;
PW[0] = '-';
PW[1] = 'p';
PW[2] = 'h';
PW[3] = 0;
l[0] = strlen(NOH);
l[1] = strlen(PW);
l[2] = strlen(Limit);
source[0] = NOH;
source[1] = PW;
source[2] = Limit;
for (i = 0; i < 3; i++)
{
for (j = 0; j < 8; j++)
{
if (j >= l[i]) {c = source[i][l[i]-1];} else {c = source[i][j];}
k = 3 * j + i;
Tab[k / 8][k % 8] = c;
}
}
sprintf(MP1, "%s", crypt(Tab[0], "PH"));
sprintf(MP2, "%s", crypt(Tab[1], "FR"));
sprintf(MP3, "%s", crypt(Tab[2], "XC"));
sprintf(MP, "%s%s%s", MP1+2, MP2+2, MP3+2);
if ( strncmp(o_Code,MP,33) == 0)
{
if ( strcmp(Limit,"nolimit") == 0)
{
return kb_Vrai;
}
time1 = time(NULL);
time2 = localtime(&time1);
i = strftime(D, 13, "%Y%m%d", time2);
free((char *)time2);
if (strncmp(D,Limit,8) > 0)
{
return kb_Faux;
}
return kb_Vrai;
}
return kb_Faux;
}
|
the_stack_data/179830282.c | main()
{
int j=1081;
struct
{
signed int m:11;
}l;
if((l.m=j)==j)abort();
exit(0);
}
|
the_stack_data/156392703.c | //Classification: p/BO/AE/aS/D(A(v))/lc/rp
//Written by: Sergey Pomelov
//Reviewed by:
//Comment:
#include <stdio.h>
int main(void)
{
float a[32];
int i;
for(i=0;i<32;i++) {
a[i] = i;
}
printf("%f",a[31]);
return 0;
}
|
the_stack_data/43887020.c | #include<stdio.h>
#include<stdlib.h>
#include<signal.h>
#include<string.h>
#include<unistd.h>
#include<errno.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<sys/times.h>
clock_t originTime;int main(void){
long clk_tck=sysconf(_SC_CLK_TCK);
clock_t origin=times(NULL);
while(1)
{
printf("PID:%d\ttime:%ld\n",getpid(),(times(NULL)-origin)/clk_tck);
sleep(1);
}
return 0;
}
|
the_stack_data/52709.c | #ifdef C8051
// 64-bit Arithmetic in C++
//
// This file contains C/C++ functions that allow the manipulation of
// 64-bit integers. It represents an alternative to the C++ class
// longlong. In this file, the type Longlong is treated as an ordinary
// C typedef, and the functions perform operations on the type without
// collection into a C++ class. For the sake of efficiency, the C++
// feature of operator overloading is not used. This implementation
// should be appreciated by those who are programming in C, since it is
// more easily translated into pure C.
//
// In this formulation, structs and unions are also used as sparingly
// as possible to maintain simplicity, while avoiding unnecessary
// data copying.
//
//
//#include <iostream.h>
#include "8051_64bit_support.h"
// macro definitions
// Function definitions
// assign signed long to longlong (y = x)
void assign(long x, Longlong* y){
y->lo = x;
y->hi = 0;
if(x < 0)
--y->hi;
}
// increment a longlong
void increment(Longlong* x){
++x->lo;
if(x->lo == 0)
++ x->hi;
}
// decrement a longlong
void decrement(Longlong* x){
--x->lo;
if((long)x->lo == -1)
-- x->hi;
}
// complement a longlong
void complement(Longlong* x){
x->hi = ~x->hi;
x->lo = ~x->lo;
}
// negate a longlong
void negate(Longlong* x){
complement(x);
increment(x);
}
// convert a longlong to its absolute value
void make_abs(Longlong* x){
if(isneg(x))
negate(x);
}
// shift a longlong left n bits
void shiftleft(Longlong* x, int n){
x->hi <<= n;
x->hi |= (x->lo >> (32-n));
x->lo <<= n;
}
// shift a longlong left n bits
void shiftright(Longlong* x, int n){
x->lo >>= n;
x->lo |= (x->hi << (32-n));
x->hi >>= n;
}
// test a longlong for zero
int iszero(const Longlong* x){
return ((x->hi | x->lo) == 0);
}
// test a longlong for sign
int isneg(const Longlong* x){
return ((long)x->hi < 0);
}
/* compare two longlongs
* return true if x == y
*/
int equal(const Longlong* x, const Longlong* y){
return ((x->hi == y->hi) & (x->lo == y->lo));
}
/* compare two longlongs
* return true if x != y
*/
int not_equal(const Longlong* x, const Longlong* y){
return ((x->hi != y->hi) || (x->lo != y->lo));
}
/* compare two longlongs
* return true if x < y
*/
int less(const Longlong* x, const Longlong* y){
if(x->hi == y->hi)
return (x->lo < y->lo);
else
return (x->hi < y->hi);
}
/* compare two longlongs
* return true if x > y
*/
int greater(const Longlong* x, const Longlong* y){
if(x->hi == y->hi)
return (x->lo > y->lo);
else
return (x->hi > y->hi);
}
/* compare two longlongs
* return true if x <= y
*/
int less_or_equal(const Longlong* x, const Longlong* y){
if(x->hi == y->hi)
return (x->lo <= y->lo);
else
return (x->hi < y->hi);
}
/* compare two longlongs
* return true if x >= y
*/
int greater_or_equal(const Longlong* x, const Longlong* y){
if(x->hi == y->hi)
return (x->lo >= y->lo);
else
return (x->hi > y->hi);
}
// logical and two longlongs
Longlong and(const Longlong* x, const Longlong* y){
Longlong retval;
retval = *x;
retval.hi = y->hi;
retval.lo = y->lo;
return retval;
}
// logical and two longlongs
Longlong or(const Longlong* x, const Longlong* y){
Longlong retval;
retval = *x;
retval.hi |= y->hi;
retval.lo |= y->lo;
return retval;
}
// logical exclusive or two longlongs
Longlong xor(const Longlong* x, const Longlong* y){
Longlong retval;
retval = *x;
retval.hi ^= y->hi;
retval.lo ^= y->lo;
return retval;
}
// subtract two longlongs
Longlong subtract(const Longlong* x, const Longlong* y){
Longlong retval;
retval = *x;
retval.lo -= y->lo;
retval.hi -= y->hi;
if(retval.lo > x->lo)
-- retval.hi;
return retval;
}
// add a (signed) long to a longlong
Longlong add(const Longlong* x, const long y){
Longlong retval;
retval = *x;
retval.lo += y;
if(y > 0){
if(retval.lo < x->lo)
++ retval.hi;
}
else{
if(retval.lo > x->lo)
-- retval.hi;
}
return retval;
}
// Multiply two (unsigned) longs to yield a longlong
Longlong umult(const unsigned long x, const unsigned long y){
Longlong retval;
Long X, Y;
Long mid; // middle two words
unsigned long ad, bc;
// pointer to address individual words
unsigned short *p = (unsigned short *)(&retval);
// copy is as quick as pointer assignment
X.lng = x;
Y.lng = y;
// generate partial products
retval.hi = (unsigned long)X.pr.hi * Y.pr.hi; // ac
ad = (unsigned long)X.pr.hi * Y.pr.lo;
bc = (unsigned long)X.pr.lo * Y.pr.hi;
retval.lo = (unsigned long)X.pr.lo * Y.pr.lo; // bd
mid.lng = ad + p[1]; // ad, high half of bd
if(mid.lng < ad) // if carry,
++p[3]; // bump high word
mid.lng += bc; // all of bc
if(mid.lng < bc) // if carry,
++p[3]; // bump high word
// results into place
retval.hi += mid.pr.hi; // mid.hi to hi.lo
p[1] = mid.pr.lo; // mid.lo to lo.hi
return retval;
}
/* Multiply two (signed) longs to yield a longlong
* Uses Booth's algorithm
*/
Longlong mult(const long x, const long y){
Longlong retval;
retval = umult((unsigned long)x, (unsigned long)y);
if(x < 0)
retval.hi -= y;
if(y < 0)
retval.hi -= x;
return retval;
}
// divide a longlong by an unsigned short
Longlong udiv (const Longlong* u, unsigned short a){
int i;
Longlong retval;
Long rem;
unsigned long temp;
unsigned short *up;
unsigned short *qp;
up = (u->hi);
qp = retval.hi;
// test for divide by zero
if(a == 0){
retval.lo = 0xffffffffL;
retval.hi = 0x7fffffffL;
if((long)u->hi < 0)
retval.hi |= 0x80000000L;
return retval;
}
// do first division (result may be long)
retval.hi = u->hi / a;
rem.lng = u->hi - retval.hi * a;
// loop for next two digits
for(i=0; i<2; i++){
--up;
--qp;
rem.pr.hi = rem.pr.lo;
rem.pr.lo = *up;
temp = rem.lng / a;
*qp = (unsigned short)temp;
rem.lng -= *qp * a;
}
return retval;
}
/* divide three digits by two
* (used by multiword division)
* inputs: dividend u (leftmost word = 0)
* divisor v,
* return value: quotient word
* u <- remainder
*/
unsigned short div3(unsigned short u[3], Long v){
unsigned long q;
unsigned short temp;
Long low;
unsigned long *p1 = (unsigned long *)(&u[1]);
unsigned long *p0 = (unsigned long *)(&u[0]);
/* get initial guess of q
* using high digit of v
*/
q = *p1 / v.pr.hi;
q = min(q, 0xffff);
// compute first remainder
*p1 -= q * v.pr.hi;
// then second remainder
low.lng = q * v.pr.lo;
temp = u[0];
u[0] -= low.pr.lo;
if(u[0] > temp)
--(*p1);
*p1 -= low.pr.hi;
// refine as needed
while((long)(*p1) < 0){
--q;
*p0 += v.lng;
if(*p0 < v.lng)
++u[2];
}
return (unsigned short)q;
}
#endif
|
the_stack_data/94681.c | #include <stdlib.h>
#include <stdio.h>
int main() {
printf("Hello World!\n");
return EXIT_SUCCESS;
}
|
the_stack_data/980399.c | #include <stdio.h>
#include <string.h>
typedef struct {
char nome[15];
char esporte[15];
int idade;
float altura;
} dados;
// Estrutura auxiliar para organização da estrutura dados
typedef struct {
char nome[15];
char esporte[15];
int idade;
float altura;
} auxiliar;
void main () {
dados atleta[5];
auxiliar aux;
int i, j = 4;
int swap = 0;
int tmp = 0;
for (i = 0; i < 5; i++) {
setbuf(stdin, NULL);
printf("\n-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\n");
printf("----------------- Atleta #%i -----------------\n", i+1);
printf("-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\n\n");
printf("Nome ?\b ");
setbuf(stdin, NULL);
fgets(atleta[i].nome, 15, stdin);
printf("Idade ?\b ");
setbuf(stdin, NULL);
scanf("%i", &atleta[i].idade);
printf("Esporte ?\b ");
setbuf(stdin, NULL);
fgets(atleta[i].esporte, 15, stdin);
printf("Altura ?\b ");
setbuf(stdin, NULL);
scanf("%f", &atleta[i].altura);
}
// Bubble sort com todos os dados
do {
swap = 0;
for (i = 0; i < 5; i++) {
if (atleta[i].idade > atleta[i + 1].idade) {
aux.idade = atleta[i].idade;
strcpy(aux.esporte, atleta[i].esporte);
strcpy(aux.nome, atleta[i].nome);
aux.altura = atleta[i].altura;
atleta[i].idade = atleta[i + 1].idade;
strcpy(atleta[i].esporte, atleta[i + 1].esporte);
strcpy(atleta[i].nome, atleta[i + 1].nome);
atleta[i].altura = atleta[i + 1].altura;
atleta[i + 1].idade = aux.idade;
strcpy(atleta[i + 1].esporte, aux.esporte);
strcpy(atleta[i + 1].nome, aux.nome);
atleta[i + 1].altura = aux.altura;
swap = 1;
}
}
} while (swap);
while (j >= 0) {
printf("----------------- Atleta #%i -----------------\n", j+1);
printf("--> Nome: %s\n", atleta[j].nome);
printf("--> Idade: %i\n", atleta[j].idade);
printf("--> Esporte: %s\n", atleta[j].esporte);
printf("--> Altura: %0.0f\n", atleta[j].altura);
j--;
}
} |
the_stack_data/150141861.c | /* lc136.c */
/* LeetCode 136. Single Number `E` */
/* acc | 94% | 36' */
/* A~0d25 */
int singleNumber(int *nums, int numsSize)
{
for (int i = 1; i < numsSize; i++)
nums[i] ^= nums[i - 1];
return nums[numsSize - 1];
}
|
the_stack_data/552918.c | #include <math.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>
/* public functions */
bool t_stat_values(double *distances, double * values, int length);
bool calculate_distance_matrix(double *series, double *distances, int length);
double calculate_t(double cross_term, double x_term, double y_term, int x_len, int y_len);
double square_sum(double * distances, int length, int row_start, int row_end, int column_start, int column_end);
/**
* Calculate the pairwise distances within the input series.
*
* @param distances The NxN double array to calculate the distances for.
* @param series The series of values to calculate a distance matrix for.
* @param length The length of the series of values.
*/
bool calculate_distance_matrix(double *series, double *distances, int length){
int i;
int j;
for(i=0;i<length;i++){
for(j=0;j<length;j++){
distances[i * length + j] = fabs(series[i] - series[j]);
}
}
return true;
}
/**
* Calculate a single t value from the terms.
*
* @param cross_term The sum of the distances across partitions.
* @param x_term The sum of the distances within the X partition.
* @param term3 The sum of the distances within the Y partition.
* @param x_len The length/size of the X partition.
* @param y_len The length/size of the Y partition.
*/
double calculate_t(double cross_term, double x_term, double y_term, int x_len, int y_len) {
double cross_term_reg;
double x_term_reg;
double y_term_reg;
if(x_len < 1 || y_len < 1) {
cross_term_reg = 0;
} else {
cross_term_reg = cross_term * (2.0 / (x_len * y_len));
}
if(x_len < 1) {
x_term_reg = 0;
} else {
x_term_reg = x_term / (x_len * x_len);
}
if(y_len < 1) {
y_term_reg = 0;
} else {
y_term_reg = y_term / (y_len * y_len);
}
double factor = ((double) x_len * y_len / (x_len + y_len));
return factor * (cross_term_reg - x_term_reg - y_term_reg);
}
/**
* Calculate the sum of terms in a NxN distance matrix within
* the square [row_start, row_end) x [column_start, column_end).
*
* @param distances The NxN distance matrix.
* @param length The length of one dimension of the distance matrix, i.e. the integer N.
* @param row_start Index of the row where the square begins (inclusive).
* @param row_end Index of the row where the square ends (exclusive).
* @param column_start Index of the column where the square begins (inclusive).
* @param column_end Index of the column where the square ends (exclusive).
*/
double square_sum(double * distances, int length, int row_start, int row_end, int column_start, int column_end) {
int row;
int column;
double sum = 0.0;
for(row=row_start;row<row_end;row++) {
for(column=column_start;column<column_end;column++) {
sum = sum + distances[row * length + column];
}
}
return sum;
}
/**
* Calculate all the t values for the input series and store the results in the values
* array.
*
* @param distances The NxN distance matrix for the series.
* @param t_stat_values The array to store the t values in.
* @param length Length of the series, i.e. N.
* @return true for success.
*/
bool t_stat_values(double * distances, double * t_stat_values, int length){
// We will partition our signal into:
// X = {Xi; 0 <= i < tau}
// Y = {Yj; tau <= j < len(signal) }
// and look for argmax(tau)Q(tau)
// sum |Xi - Yj| for i < tau <= j
double cross_term = 0;
// sum |Xi - Xj| for i < j < tau
double x_term = 0;
// sum |Yi - Yj| for tau <= i < j
double y_term = 0;
int row;
for(row=0;row<length;row++) {
y_term += square_sum(distances, length, row, row+1, row, length);
}
int tau;
for(tau=0;tau<length;tau++) {
t_stat_values[tau] = calculate_t(cross_term, 2*x_term, 2*y_term, tau, length - tau);
double column_delta = square_sum(distances, length, 0, tau, tau, tau+1);
double row_delta = square_sum(distances, length, tau, tau+1, tau, length);
cross_term = cross_term - column_delta + row_delta;
x_term = x_term + column_delta;
y_term = y_term - row_delta;
}
return true;
}
|
the_stack_data/212641866.c | /*
* Copyright (c) 2020 Wuklab, UCSD. All rights reserved.
*
* Testing: raw network layer latency and throughput.
* Using raw net layer means we skip any transport layer logic.
*/
#if 0
#include <uapi/vregion.h>
#include <uapi/compiler.h>
#include <uapi/sched.h>
#include <uapi/list.h>
#include <uapi/err.h>
#include <pthread.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <stdarg.h>
#include "../core.h"
#define NR_RUN_PER_THREAD 100000
static struct board_info *remote_board;
static pthread_barrier_t thread_barrier;
#define NR_MAX_THREADS (128)
/*
* Tuning
*
* Sometimes I see packet lost issue when go multithreading
* stats look like this:
* Sender:
* TX: (X+N)
* RX: (X)
*
* Receiver:
* RX: (X)
*
* It means some packets from sender never reach receiver.
*/
//static int test_size[] = { 4, 16, 64, 256, 1024 };
//static int test_nr_threads[] = { 1, 2, 4, 8, 16};
static int test_size[] = { 64};
static int test_nr_threads[] = { 16 };
static double latency_ns[128][128];
static inline void die(const char * str, ...)
{
va_list args;
va_start(args, str);
vfprintf(stderr, str, args);
fputc('\n', stderr);
exit(1);
}
struct thread_info {
int id;
int cpu;
};
/*
* BIG FAT NOTE: some steps for raw new testing
*
* 1. Have a host.o and monitor.o ready at two machines.
* 2. Use host.o to send packet
* 3. comment out the while (1) loop in dispatcher() [host.o]
* 4. try to use net_receive instead of net_receive_zeropy in dispather() [monitor.o]
* 5. Use scripts/test_raw_net.sh, modify ports, device etc
*/
static void *thread_func(void *_ti)
{
struct legomem_pingpong_req *req;
struct legomem_pingpong_req *resp;
struct lego_header *lego_header;
struct gbn_header *gbn_header;
int i, j, nr_tests;
struct timespec s, e;
struct session_net *ses;
struct thread_info *ti = (struct thread_info *)_ti;
int cpu, node;
double lat_ns;
int max_buf_size = 1024*1024;
ses = legomem_open_session_remote_mgmt(remote_board);
if (!ses) {
die("fail to open session. thread id %d\n", ti->id);
}
if (pin_cpu(ti->cpu))
die("can not pin to cpu %d\n", ti->cpu);
legomem_getcpu(&cpu, &node);
printf("%s(): thread id %d running on CPU %d, local session id %d remote session id %d\n",
__func__,
ti->id, cpu, get_local_session_id(ses), get_remote_session_id(ses));
resp = malloc(max_buf_size);
req = malloc(max_buf_size);
net_reg_send_buf(ses, req, max_buf_size);
lego_header = to_lego_header(req);
lego_header->opcode = OP_REQ_PINGPONG;
gbn_header = to_gbn_header(req);
gbn_header->type = GBN_PKT_DATA;
set_gbn_src_dst_session(gbn_header, get_local_session_id(ses), 0);
for (i = 0; i < ARRAY_SIZE(test_size); i++) {
int send_size = test_size[i];
req->reply_size = 0;
/* need to include header size */
send_size += sizeof(struct legomem_common_headers);
/* Sync for every round */
pthread_barrier_wait(&thread_barrier);
nr_tests = NR_RUN_PER_THREAD;
clock_gettime(CLOCK_MONOTONIC, &s);
for (j = 0; j < nr_tests; j++) {
raw_net_send(ses, req, send_size, NULL);
raw_net_receive(resp, max_buf_size);
}
clock_gettime(CLOCK_MONOTONIC, &e);
lat_ns = (e.tv_sec * NSEC_PER_SEC + e.tv_nsec) -
(s.tv_sec * NSEC_PER_SEC + s.tv_nsec);
latency_ns[ti->id][i] = lat_ns;
#if 1
dprintf_INFO("nr_tests: %d send_size: %u payload_size: %u avg: %lf ns\n",
nr_tests, send_size, test_size[i], lat_ns / nr_tests);
#endif
}
legomem_close_session(NULL, ses);
return NULL;
}
#endif
/*
* Special note:
*
* To use this, we have to use transport bypass, otherwise
* the packets will just be grabbed by GBN's background thread.
*
* However, this is not enough. Becuase host still has its mgmt background
* thread. Once GBN is disabled, the `net_receive` within that thread
* will be able receive anything. Thus, we need to diable that thread as well!
*/
int test_raw_net(char *board_ip_port_str)
{
#if 0
unsigned int ip, port;
unsigned int ip1, ip2, ip3, ip4;
int k, i, j, ret;
int nr_threads;
pthread_t *tid;
struct thread_info *ti;
if (transport_net_ops != &transport_bypass_ops) {
dprintf_ERROR("Raw network testing needs bypass transport layer.\n"
"Please restart the test and pass \"--net_trans_ops=bypass\" %d\n", 0);
return -1;
}
sscanf(board_ip_port_str, "%u.%u.%u.%u:%d", &ip1, &ip2, &ip3, &ip4, &port);
ip = ip1 << 24 | ip2 << 16 | ip3 << 8 | ip4;
remote_board = find_board(ip, port);
if (!remote_board) {
dprintf_ERROR("Couldn't find the board_info for %s\n",
board_ip_port_str);
dump_boards();
return -1;
}
printf("%s(): Using board %s\n", __func__, remote_board->name);
ti = malloc(sizeof(*ti) * NR_MAX_THREADS);
tid = malloc(sizeof(*tid) * NR_MAX_THREADS);
if (!tid || !ti)
die("OOM");
for (k = 0; k < ARRAY_SIZE(test_nr_threads); k++) {
nr_threads = test_nr_threads[k];
pthread_barrier_init(&thread_barrier, NULL, nr_threads);
for (i = 0; i < nr_threads; i++) {
/*
* cpu 0 is used for gbn polling now
* in case
*/
ti[i].cpu = i + 1;
ti[i].id = i;
ret = pthread_create(&tid[i], NULL, thread_func, &ti[i]);
if (ret)
die("fail to create test thread");
}
for (i = 0; i < nr_threads; i++) {
pthread_join(tid[i], NULL);
}
/*
* Aggregate all stats
*/
for (i = 0; i < ARRAY_SIZE(test_size); i++) {
int send_size = test_size[i];
double sum, avg;
for (j = 0, sum = 0; j < nr_threads; j++) {
sum += latency_ns[j][i];
}
avg = sum / nr_threads / NR_RUN_PER_THREAD;
dprintf_INFO("#tests_per_thread=%10d #nr_theads=%3d #payload_size=%8d avg_RTT=%10lf ns\n",
NR_RUN_PER_THREAD, nr_threads, send_size, avg);
}
}
return 0;
#endif
return 0;
}
|
the_stack_data/23574412.c | //clang -Xclang -ast-dump -fsyntax-only *.c
#include <stdio.h>
long long a = 100;
long long b = 20;
long long c = 15;
int main() {
printf("%lld\n", a);
printf("%lld\n", b);
printf("%lld\n", c);
a += c;
printf("%lld\n", a);
return 0;
}
|
the_stack_data/237902.c | #include<stdio.h>
int main()
{
int amt;
scanf("%i",&amt);
printf("%i\n",amt);
int notes[]={100,50,20,10,5,2,1};
for(int a=0;a<7;a++)
{
printf("%i nota(s) de R$ %i,00\n",amt/notes[a],notes[a]);
amt%=notes[a];
}
return 0;
}
|
the_stack_data/38018.c | /* Metnin Kelime Sayısını Bulan Program
//String (Karakter Tutan Diziler)
//While ile
Klavyeden girilen metnin kelime sayısını bulan C programı
*/
#include <stdio.h>
#include <locale.h>
int main()
{
setlocale(LC_ALL, "Turkish");
char ifade[256];
printf("ifadeyi giriniz: ");
gets(ifade);
int i = 0;
int sayac = 0;
while (ifade[i] == 32)
i++;
while (1)
{
if ((ifade[i] == 32) && (ifade[i - 1] != 32))
sayac++;
else if ((ifade[i] == '\0') && (ifade[i - 1] != 32))
{
sayac++;
break;
}
i++;
}
printf("%s ifadesinde %d tane kelime var.\n", ifade, sayac);
return 0;
}
|
the_stack_data/212643535.c | /*************************************************************************\
* Copyright (C) Michael Kerrisk, 2022. *
* *
* This program is free software. You may use, modify, and redistribute it *
* under the terms of the GNU General Public License as published by the *
* Free Software Foundation, either version 3 or (at your option) any *
* later version. This program is distributed without any warranty. See *
* the file COPYING.gpl-v3 for details. *
\*************************************************************************/
/* 41 */
/* foo1.c
*/
#include <stdlib.h>
#include <stdio.h>
void
xyz(void)
{
printf(" func1-xyz\n");
}
void
abc(void)
{
printf(" func1-abc\n");
}
void
func1(int x)
{
printf("Called func1\n");
xyz();
abc();
}
|
the_stack_data/150143532.c | #include <sys/mman.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <wait.h>
#include <time.h>
#include <sys/wait.h>
#include <string.h>
#include <sys/time.h>
#define NUMBER_OF_LETTERS 100
typedef struct {
char letters[NUMBER_OF_LETTERS];
} sample_struct;
int main(){
printf("WRITTER\n");
int open_check, size, close_check;
size = sizeof(sample_struct);
sample_struct *struct1;
shm_unlink("/ex04");
open_check = shm_open("/ex04", O_CREAT|O_EXCL|O_RDWR, S_IRUSR|S_IWUSR);
if (open_check == -1){
perror("shm_open failed");
exit(EXIT_FAILURE);
}
int ftruncate_value = ftruncate(open_check, size);
if (ftruncate_value == -1){
perror("ft failed");
exit(EXIT_FAILURE);
}
struct1 = (sample_struct *) mmap(NULL, size, PROT_READ|PROT_WRITE, MAP_SHARED, open_check, 0);
if (struct1 == MAP_FAILED) {
perror("mmap failed");
exit(EXIT_FAILURE);
}
int i;
char aux[NUMBER_OF_LETTERS];
for(i = 0; i < NUMBER_OF_LETTERS; i++) {
char random_letter = 'A' + (random() % 26);
aux[i] = random_letter;
printf("letter sent -> %c\n",aux[i]);
}
strcpy(struct1->letters,aux);
close_check = munmap((void *) struct1, size);
if (close_check < 0){
perror("munmap failed");
exit(EXIT_FAILURE);
}
close_check = close(open_check);
if (close_check < 0){
perror("close failed");
exit(EXIT_FAILURE);
}
printf("FIM\n");
return 0;
} |
the_stack_data/40763358.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 integer c__1 = 1;
/* > \brief \b DLAQP2 computes a QR factorization with column pivoting of the matrix block. */
/* =========== DOCUMENTATION =========== */
/* Online html documentation available at */
/* http://www.netlib.org/lapack/explore-html/ */
/* > \htmlonly */
/* > Download DLAQP2 + dependencies */
/* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.tgz?format=tgz&filename=/lapack/lapack_routine/dlaqp2.
f"> */
/* > [TGZ]</a> */
/* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.zip?format=zip&filename=/lapack/lapack_routine/dlaqp2.
f"> */
/* > [ZIP]</a> */
/* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.txt?format=txt&filename=/lapack/lapack_routine/dlaqp2.
f"> */
/* > [TXT]</a> */
/* > \endhtmlonly */
/* Definition: */
/* =========== */
/* SUBROUTINE DLAQP2( M, N, OFFSET, A, LDA, JPVT, TAU, VN1, VN2, */
/* WORK ) */
/* INTEGER LDA, M, N, OFFSET */
/* INTEGER JPVT( * ) */
/* DOUBLE PRECISION A( LDA, * ), TAU( * ), VN1( * ), VN2( * ), */
/* $ WORK( * ) */
/* > \par Purpose: */
/* ============= */
/* > */
/* > \verbatim */
/* > */
/* > DLAQP2 computes a QR factorization with column pivoting of */
/* > the block A(OFFSET+1:M,1:N). */
/* > The block A(1:OFFSET,1:N) is accordingly pivoted, but not factorized. */
/* > \endverbatim */
/* Arguments: */
/* ========== */
/* > \param[in] M */
/* > \verbatim */
/* > M is INTEGER */
/* > The number of rows of the matrix A. M >= 0. */
/* > \endverbatim */
/* > */
/* > \param[in] N */
/* > \verbatim */
/* > N is INTEGER */
/* > The number of columns of the matrix A. N >= 0. */
/* > \endverbatim */
/* > */
/* > \param[in] OFFSET */
/* > \verbatim */
/* > OFFSET is INTEGER */
/* > The number of rows of the matrix A that must be pivoted */
/* > but no factorized. OFFSET >= 0. */
/* > \endverbatim */
/* > */
/* > \param[in,out] A */
/* > \verbatim */
/* > A is DOUBLE PRECISION array, dimension (LDA,N) */
/* > On entry, the M-by-N matrix A. */
/* > On exit, the upper triangle of block A(OFFSET+1:M,1:N) is */
/* > the triangular factor obtained; the elements in block */
/* > A(OFFSET+1:M,1:N) below the diagonal, together with the */
/* > array TAU, represent the orthogonal matrix Q as a product of */
/* > elementary reflectors. Block A(1:OFFSET,1:N) has been */
/* > accordingly pivoted, but no factorized. */
/* > \endverbatim */
/* > */
/* > \param[in] LDA */
/* > \verbatim */
/* > LDA is INTEGER */
/* > The leading dimension of the array A. LDA >= f2cmax(1,M). */
/* > \endverbatim */
/* > */
/* > \param[in,out] JPVT */
/* > \verbatim */
/* > JPVT is INTEGER array, dimension (N) */
/* > On entry, if JPVT(i) .ne. 0, the i-th column of A is permuted */
/* > to the front of A*P (a leading column); if JPVT(i) = 0, */
/* > the i-th column of A is a free column. */
/* > On exit, if JPVT(i) = k, then the i-th column of A*P */
/* > was the k-th column of A. */
/* > \endverbatim */
/* > */
/* > \param[out] TAU */
/* > \verbatim */
/* > TAU is DOUBLE PRECISION array, dimension (f2cmin(M,N)) */
/* > The scalar factors of the elementary reflectors. */
/* > \endverbatim */
/* > */
/* > \param[in,out] VN1 */
/* > \verbatim */
/* > VN1 is DOUBLE PRECISION array, dimension (N) */
/* > The vector with the partial column norms. */
/* > \endverbatim */
/* > */
/* > \param[in,out] VN2 */
/* > \verbatim */
/* > VN2 is DOUBLE PRECISION array, dimension (N) */
/* > The vector with the exact column norms. */
/* > \endverbatim */
/* > */
/* > \param[out] WORK */
/* > \verbatim */
/* > WORK is DOUBLE PRECISION array, dimension (N) */
/* > \endverbatim */
/* Authors: */
/* ======== */
/* > \author Univ. of Tennessee */
/* > \author Univ. of California Berkeley */
/* > \author Univ. of Colorado Denver */
/* > \author NAG Ltd. */
/* > \date December 2016 */
/* > \ingroup doubleOTHERauxiliary */
/* > \par Contributors: */
/* ================== */
/* > */
/* > G. Quintana-Orti, Depto. de Informatica, Universidad Jaime I, Spain */
/* > X. Sun, Computer Science Dept., Duke University, USA */
/* > \n */
/* > Partial column norm updating strategy modified on April 2011 */
/* > Z. Drmac and Z. Bujanovic, Dept. of Mathematics, */
/* > University of Zagreb, Croatia. */
/* > \par References: */
/* ================ */
/* > */
/* > LAPACK Working Note 176 */
/* > \htmlonly */
/* > <a href="http://www.netlib.org/lapack/lawnspdf/lawn176.pdf">[PDF]</a> */
/* > \endhtmlonly */
/* ===================================================================== */
/* Subroutine */ int dlaqp2_(integer *m, integer *n, integer *offset,
doublereal *a, integer *lda, integer *jpvt, doublereal *tau,
doublereal *vn1, doublereal *vn2, doublereal *work)
{
/* System generated locals */
integer a_dim1, a_offset, i__1, i__2, i__3;
doublereal d__1, d__2;
/* Local variables */
doublereal temp;
extern doublereal dnrm2_(integer *, doublereal *, integer *);
doublereal temp2;
integer i__, j;
doublereal tol3z;
extern /* Subroutine */ int dlarf_(char *, integer *, integer *,
doublereal *, integer *, doublereal *, doublereal *, integer *,
doublereal *);
integer offpi, itemp;
extern /* Subroutine */ int dswap_(integer *, doublereal *, integer *,
doublereal *, integer *);
extern doublereal dlamch_(char *);
integer mn;
extern /* Subroutine */ int dlarfg_(integer *, doublereal *, doublereal *,
integer *, doublereal *);
extern integer idamax_(integer *, doublereal *, integer *);
doublereal aii;
integer pvt;
/* -- 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 */
a_dim1 = *lda;
a_offset = 1 + a_dim1 * 1;
a -= a_offset;
--jpvt;
--tau;
--vn1;
--vn2;
--work;
/* Function Body */
/* Computing MIN */
i__1 = *m - *offset;
mn = f2cmin(i__1,*n);
tol3z = sqrt(dlamch_("Epsilon"));
/* Compute factorization. */
i__1 = mn;
for (i__ = 1; i__ <= i__1; ++i__) {
offpi = *offset + i__;
/* Determine ith pivot column and swap if necessary. */
i__2 = *n - i__ + 1;
pvt = i__ - 1 + idamax_(&i__2, &vn1[i__], &c__1);
if (pvt != i__) {
dswap_(m, &a[pvt * a_dim1 + 1], &c__1, &a[i__ * a_dim1 + 1], &
c__1);
itemp = jpvt[pvt];
jpvt[pvt] = jpvt[i__];
jpvt[i__] = itemp;
vn1[pvt] = vn1[i__];
vn2[pvt] = vn2[i__];
}
/* Generate elementary reflector H(i). */
if (offpi < *m) {
i__2 = *m - offpi + 1;
dlarfg_(&i__2, &a[offpi + i__ * a_dim1], &a[offpi + 1 + i__ *
a_dim1], &c__1, &tau[i__]);
} else {
dlarfg_(&c__1, &a[*m + i__ * a_dim1], &a[*m + i__ * a_dim1], &
c__1, &tau[i__]);
}
if (i__ < *n) {
/* Apply H(i)**T to A(offset+i:m,i+1:n) from the left. */
aii = a[offpi + i__ * a_dim1];
a[offpi + i__ * a_dim1] = 1.;
i__2 = *m - offpi + 1;
i__3 = *n - i__;
dlarf_("Left", &i__2, &i__3, &a[offpi + i__ * a_dim1], &c__1, &
tau[i__], &a[offpi + (i__ + 1) * a_dim1], lda, &work[1]);
a[offpi + i__ * a_dim1] = aii;
}
/* Update partial column norms. */
i__2 = *n;
for (j = i__ + 1; j <= i__2; ++j) {
if (vn1[j] != 0.) {
/* NOTE: The following 4 lines follow from the analysis in */
/* Lapack Working Note 176. */
/* Computing 2nd power */
d__2 = (d__1 = a[offpi + j * a_dim1], abs(d__1)) / vn1[j];
temp = 1. - d__2 * d__2;
temp = f2cmax(temp,0.);
/* Computing 2nd power */
d__1 = vn1[j] / vn2[j];
temp2 = temp * (d__1 * d__1);
if (temp2 <= tol3z) {
if (offpi < *m) {
i__3 = *m - offpi;
vn1[j] = dnrm2_(&i__3, &a[offpi + 1 + j * a_dim1], &
c__1);
vn2[j] = vn1[j];
} else {
vn1[j] = 0.;
vn2[j] = 0.;
}
} else {
vn1[j] *= sqrt(temp);
}
}
/* L10: */
}
/* L20: */
}
return 0;
/* End of DLAQP2 */
} /* dlaqp2_ */
|
the_stack_data/131621.c |
#include "unistd.h"
int fooChildTwo() {
int a = 0;
int b = 4;
int c = 2;
return (a * b) / c;
}
int fooChildOne() {
int a = 0;
int b = 4;
int c = 2;
a++;
a = 0;
b = 4;
c = 2;
a++;
a++;
a++;
a++;
a++;
a++;
a++;
a++;
a++;
a++;
a++;
a++;
a++;
a++;
a++;
a++;
a++;
a++;
a++;
a++;
a++;
a++;
a++;
a++;
a++;
a++;
a++;
a++;
a++;
a++;
return (a * b) / c;
}
int foo() {
sleep(10);
fooChildTwo();
fooChildOne();
return 0;
}
int bar() {
sleep(1);
return 0;
}
int main(int argc, char **argv) {
int a = foo();
int b = bar();
return 0;
}
|
the_stack_data/39390.c | /*
* strdup: return a duplicate of a string
* Written by Eric R. Smith and placed in the public domain.
*/
#include <stdlib.h>
#include <string.h>
#undef strdup
char *
strdup(s)
const char *s;
{
char *dup;
dup = (char *) malloc(strlen(s)+1);
if (dup)
strcpy(dup, s);
return dup;
}
|
the_stack_data/116167.c | /*
!==========================================================================
elemental function gsw_pressure_coefficient_ice (t, p)
!==========================================================================
!
! Calculates pressure coefficient of ice.
!
! t = in-situ temperature (ITS-90) [ deg C ]
! p = sea pressure [ dbar ]
! ( i.e. absolute pressure - 10.1325 dbar )
!
! pressure_coefficient_ice = pressure coefficient of ice [Pa/K]
! Note. The output units are Pa/K NOT dbar/K.
!--------------------------------------------------------------------------
*/
double
gsw_pressure_coefficient_ice(double t, double p)
{
return (-gsw_gibbs_ice(1,1,t,p)/gsw_gibbs_ice(0,2,t,p));
}
|
the_stack_data/88916.c | /**************************************************************************/
/*!
@file board_lpcxpresso1769.c
@author hathach (tinyusb.org)
@section LICENSE
Software License Agreement (BSD License)
Copyright (c) 2013, hathach (tinyusb.org)
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. Neither the name of the copyright holders nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''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 COPYRIGHT HOLDER 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.
This file is part of the tinyusb stack.
*/
/**************************************************************************/
#ifdef BOARD_LPCXPRESSO1769
#include "../board.h"
#include "tusb.h"
#define LED_PORT 0
#define LED_PIN 22
#define BOARD_UART_PORT LPC_UART3
/* System oscillator rate and RTC oscillator rate */
const uint32_t OscRateIn = 12000000;
const uint32_t RTCOscRateIn = 32768;
/* Pin muxing configuration */
static const PINMUX_GRP_T pinmuxing[] =
{
{0, 0, IOCON_MODE_INACT | IOCON_FUNC2}, /* TXD3 */
{0, 1, IOCON_MODE_INACT | IOCON_FUNC2}, /* RXD3 */
{0, 22, IOCON_MODE_INACT | IOCON_FUNC0}, /* Led 0 */
/* Joystick buttons. */
{2, 3, IOCON_MODE_INACT | IOCON_FUNC0}, /* JOYSTICK_UP */
{0, 15, IOCON_MODE_INACT | IOCON_FUNC0}, /* JOYSTICK_DOWN */
{2, 4, IOCON_MODE_INACT | IOCON_FUNC0}, /* JOYSTICK_LEFT */
{0, 16, IOCON_MODE_INACT | IOCON_FUNC0}, /* JOYSTICK_RIGHT */
{0, 17, IOCON_MODE_INACT | IOCON_FUNC0}, /* JOYSTICK_PRESS */
};
static const PINMUX_GRP_T pin_usb_mux[] =
{
{0, 29, IOCON_MODE_INACT | IOCON_FUNC1}, // D+
{0, 30, IOCON_MODE_INACT | IOCON_FUNC1}, // D-
{2, 9, IOCON_MODE_INACT | IOCON_FUNC1}, // Connect
{1, 19, IOCON_MODE_INACT | IOCON_FUNC2}, // USB_PPWR
{1, 22, IOCON_MODE_INACT | IOCON_FUNC2}, // USB_PWRD
/* VBUS is not connected on this board, so leave the pin at default setting. */
/*Chip_IOCON_PinMux(LPC_IOCON, 1, 30, IOCON_MODE_INACT, IOCON_FUNC2);*/ /* USB VBUS */
};
enum {
BOARD_BUTTON_COUNT = 5
};
// Invoked by startup code
void SystemInit(void)
{
/* Enable IOCON clock */
Chip_IOCON_SetPinMuxing(LPC_IOCON, pinmuxing, sizeof(pinmuxing) / sizeof(PINMUX_GRP_T));
Chip_SetupXtalClocking();
}
void board_init(void)
{
SystemCoreClockUpdate();
#if CFG_TUSB_OS == OPT_OS_NONE
SysTick_Config(SystemCoreClock / BOARD_TICKS_HZ);
#elif CFG_TUSB_OS == OPT_OS_FREERTOS
// If freeRTOS is used, IRQ priority is limit by max syscall ( smaller is higher )
NVIC_SetPriority(USB_IRQn, configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY );
#endif
Chip_GPIO_Init(LPC_GPIO);
//------------- LED -------------//
Chip_GPIO_SetPinDIROutput(LPC_GPIO, LED_PORT, LED_PIN);
//------------- BUTTON -------------//
// for(uint8_t i=0; i<BOARD_BUTTON_COUNT; i++) GPIO_SetDir(buttons[i].port, TU_BIT(buttons[i].pin), 0);
#if 0
//------------- UART -------------//
PINSEL_CFG_Type PinCfg =
{
.Portnum = 0,
.Pinnum = 0, // TXD is P0.0
.Funcnum = 2,
.OpenDrain = 0,
.Pinmode = 0
};
PINSEL_ConfigPin(&PinCfg);
PinCfg.Portnum = 0;
PinCfg.Pinnum = 1; // RXD is P0.1
PINSEL_ConfigPin(&PinCfg);
UART_CFG_Type UARTConfigStruct;
UART_ConfigStructInit(&UARTConfigStruct);
UARTConfigStruct.Baud_rate = CFG_UART_BAUDRATE;
UART_Init(BOARD_UART_PORT, &UARTConfigStruct);
UART_TxCmd(BOARD_UART_PORT, ENABLE); // Enable UART Transmit
#endif
//------------- USB -------------//
Chip_USB_Init();
enum {
USBCLK_DEVCIE = 0x12, // AHB + Device
USBCLK_HOST = 0x19, // AHB + Host + OTG
// 0x1B // Host + Device + OTG + AHB
};
uint32_t const clk_en = TUSB_OPT_DEVICE_ENABLED ? USBCLK_DEVCIE : USBCLK_HOST;
LPC_USB->OTGClkCtrl = clk_en;
while ( (LPC_USB->OTGClkSt & clk_en) != clk_en );
#if TUSB_OPT_HOST_ENABLED
// set portfunc to host !!!
LPC_USB->StCtrl = 0x3; // should be 1
#endif
Chip_IOCON_SetPinMuxing(LPC_IOCON, pin_usb_mux, sizeof(pin_usb_mux) / sizeof(PINMUX_GRP_T));
}
/*------------------------------------------------------------------*/
/* TUSB HAL MILLISECOND
*------------------------------------------------------------------*/
#if CFG_TUSB_OS == OPT_OS_NONE
volatile uint32_t system_ticks = 0;
void SysTick_Handler (void)
{
system_ticks++;
}
uint32_t tusb_hal_millis(void)
{
return board_tick2ms(system_ticks);
}
#endif
//--------------------------------------------------------------------+
// LEDS
//--------------------------------------------------------------------+
void board_led_control(bool state)
{
Chip_GPIO_SetPinState(LPC_GPIO, LED_PORT, LED_PIN, state);
}
//--------------------------------------------------------------------+
// BUTTONS
//--------------------------------------------------------------------+
#if 0
static bool button_read(uint8_t id)
{
// return !TU_BIT_TEST( GPIO_ReadValue(buttons[id].port), buttons[id].pin ); // button is active low
return false;
}
#endif
uint32_t board_buttons(void)
{
uint32_t result = 0;
// for(uint8_t i=0; i<BOARD_BUTTON_COUNT; i++) result |= (button_read(i) ? TU_BIT(i) : 0);
return result;
}
//--------------------------------------------------------------------+
// UART
//--------------------------------------------------------------------+
void board_uart_putchar(uint8_t c)
{
(void) c;
// UART_Send(BOARD_UART_PORT, &c, 1, BLOCKING);
}
uint8_t board_uart_getchar(void)
{
// return UART_ReceiveByte(BOARD_UART_PORT);
return 0;
}
#endif
|
the_stack_data/27154.c | /* Generated by re2c */
#line 1 "input_custom_mjson.--input(custom).re"
#include <assert.h>
#include <memory.h>
#include <stdio.h>
#include <string.h>
#include <stddef.h>
/**
* mjson - modified json parser
* syntax changes:
* - no {} needed around the whole file
* - "=" is allowed instead of ":"
* - quotes around the key are optional
* - commas after values are optional
* - and c-style comments allowed
*
* intermediate storage is based on ideas from BJSON specification: http://bjson.org
*
* some code ideas are borrowed from another json parser: https://github.com/megous/sjson
*/
#ifndef __MJSON_H_INCLUDED__
#define __MJSON_H_INCLUDED__
#include <stdint.h>
#ifdef __cplusplus
extern "C"
{
#endif
struct _mjson_entry_t;
typedef const struct _mjson_entry_t* mjson_element_t;
enum mjson_element_id_t
{
MJSON_ID_NULL = 0,
MJSON_ID_FALSE = 1,
MJSON_ID_EMPTY_STRING = 2,
MJSON_ID_TRUE = 3,
MJSON_ID_UINT32 = 4,
MJSON_ID_UINT64 = 5,
MJSON_ID_SINT32 = 6,
MJSON_ID_SINT64 = 7,
MJSON_ID_FLOAT32 = 8,
MJSON_ID_FLOAT64 = 9,
MJSON_ID_UTF8_KEY32 = 10,
MJSON_ID_UTF8_KEY64 = 11,
MJSON_ID_UTF8_STRING32 = 12,
MJSON_ID_UTF8_STRING64 = 13,
MJSON_ID_BINARY32 = 14,
MJSON_ID_BINARY64 = 15,
MJSON_ID_ARRAY32 = 16,
MJSON_ID_ARRAY64 = 17,
MJSON_ID_DICT32 = 18,
MJSON_ID_DICT64 = 19
};
int mjson_parse(const char *json_data, size_t json_data_size, void* storage_buf, size_t storage_buf_size, mjson_element_t* top_element);
mjson_element_t mjson_get_top_element(void* storage_buf, size_t storage_buf_size);
mjson_element_t mjson_get_element_first(mjson_element_t array);
mjson_element_t mjson_get_element_next (mjson_element_t array, mjson_element_t current_value);
mjson_element_t mjson_get_element (mjson_element_t array, int index);
mjson_element_t mjson_get_member_first(mjson_element_t dictionary, mjson_element_t* value);
mjson_element_t mjson_get_member_next (mjson_element_t dictionary, mjson_element_t current_key, mjson_element_t* next_value);
mjson_element_t mjson_get_member (mjson_element_t dictionary, const char* name);
int mjson_get_type(mjson_element_t element);
const char* mjson_get_string(mjson_element_t element, const char* fallback);
int32_t mjson_get_int (mjson_element_t element, int32_t fallback);
float mjson_get_float (mjson_element_t element, float fallback);
int mjson_get_bool (mjson_element_t element, int fallback);
int mjson_is_null (mjson_element_t element);
#ifdef __cplusplus
}
#endif
#endif
enum mjson_token_t
{
TOK_NONE,
TOK_IDENTIFIER,
TOK_NOESC_STRING,
TOK_STRING,
TOK_OCT_NUMBER,
TOK_HEX_NUMBER,
TOK_DEC_NUMBER,
TOK_FLOAT_NUMBER,
TOK_COMMA,
TOK_COLON,
TOK_EQUAL,
TOK_LEFT_BRACKET,
TOK_RIGHT_BRACKET,
TOK_LEFT_CURLY_BRACKET,
TOK_RIGHT_CURLY_BRACKET,
TOK_FALSE,
TOK_TRUE,
TOK_NULL,
TOK_WHITESPACE,
TOK_INVALID,
TOK_COUNT
};
struct _mjson_parser_t
{
int token;
uint8_t* start;
uint8_t* next;
uint8_t* end;
uint8_t* bjson;
uint8_t* bjson_limit;
};
struct _mjson_entry_t
{
uint32_t id;
union
{
uint32_t val_u32;
int32_t val_s32;
float val_f32;
};
};
#define RETURN_VAL_IF_FAIL(cond, val) if (!(cond)) return (val)
#define RETURN_IF_FAIL(cond) if (!(cond)) return
#define MAX_UTF8_CHAR_LEN 6
#define TRUE 1
#define FALSE 0
typedef struct _mjson_parser_t mjson_parser_t;
typedef struct _mjson_entry_t mjson_entry_t;
static void* parsectx_allocate_output(mjson_parser_t* ctx, ptrdiff_t size);
static void parsectx_next_token (mjson_parser_t* context);
static int parse_value_list (mjson_parser_t *context);
static int parse_key_value_pair(mjson_parser_t *context, int stop_token);
static mjson_element_t next_element(mjson_element_t element);
int mjson_parse(const char *json_data, size_t json_data_size, void* storage_buf, size_t storage_buf_size, const mjson_entry_t** top_element)
{
uint32_t* fourcc;
mjson_parser_t c = {
TOK_NONE, 0,
(uint8_t*)json_data, (uint8_t*)json_data + json_data_size,
(uint8_t*)storage_buf, (uint8_t*)storage_buf + storage_buf_size
};
int stop_token = TOK_NONE;
*top_element = 0;
fourcc = (uint32_t*)parsectx_allocate_output(&c, (ptrdiff_t)sizeof(uint32_t));
if (!fourcc) return 0;
*fourcc = '23JB';
parsectx_next_token(&c);
if (c.token == TOK_LEFT_BRACKET)
{
parsectx_next_token(&c);
if (!parse_value_list(&c))
return 0;
}
else
{
if (c.token == TOK_LEFT_CURLY_BRACKET)
{
stop_token = TOK_RIGHT_CURLY_BRACKET;
parsectx_next_token(&c);
}
if (!parse_key_value_pair(&c, stop_token))
return 0;
}
if (c.token != TOK_NONE)
return 0;
*top_element = (mjson_entry_t*)(fourcc + 1);
return 1;
}
mjson_element_t mjson_get_top_element(void* storage_buf, size_t storage_buf_size)
{
mjson_element_t top = (mjson_element_t)storage_buf;
RETURN_VAL_IF_FAIL(top, NULL);
RETURN_VAL_IF_FAIL(top->id == MJSON_ID_DICT32 || top->id == MJSON_ID_ARRAY32, NULL);
RETURN_VAL_IF_FAIL(top->val_u32 <= storage_buf_size, NULL);
return top;
}
mjson_element_t mjson_get_element_first(mjson_element_t array)
{
RETURN_VAL_IF_FAIL(array, NULL);
RETURN_VAL_IF_FAIL(array->id == MJSON_ID_ARRAY32, NULL);
return array + 1;
}
mjson_element_t mjson_get_element_next(mjson_element_t array, mjson_element_t current_value)
{
mjson_element_t next = NULL;
RETURN_VAL_IF_FAIL(array, NULL);
RETURN_VAL_IF_FAIL(current_value, NULL);
RETURN_VAL_IF_FAIL(array->id == MJSON_ID_ARRAY32, NULL);
RETURN_VAL_IF_FAIL((uint8_t*)array + array->val_u32 > (uint8_t*)current_value, NULL);
next = next_element(current_value);
RETURN_VAL_IF_FAIL((uint8_t*)array + array->val_u32 > (uint8_t*)next, NULL);
return next;
}
mjson_element_t mjson_get_element(mjson_element_t array, int index)
{
mjson_element_t result;
result = mjson_get_element_first(array);
while (result && index--)
result = mjson_get_element_next(array, result);
return result;
}
mjson_element_t mjson_get_member_first(mjson_element_t dictionary, mjson_element_t* value)
{
RETURN_VAL_IF_FAIL(dictionary, NULL);
RETURN_VAL_IF_FAIL(dictionary->id == MJSON_ID_DICT32, NULL);
RETURN_VAL_IF_FAIL((dictionary+1)->id == MJSON_ID_UTF8_KEY32, NULL);
*value = next_element(dictionary+1);
return dictionary + 1;
}
mjson_element_t mjson_get_member_next(mjson_element_t dictionary, mjson_element_t current_key, mjson_element_t* next_value)
{
mjson_element_t next_key = NULL;
RETURN_VAL_IF_FAIL(dictionary, NULL);
RETURN_VAL_IF_FAIL(dictionary->id == MJSON_ID_DICT32, NULL);
RETURN_VAL_IF_FAIL(current_key, NULL);
RETURN_VAL_IF_FAIL((uint8_t*)dictionary + dictionary->val_u32 > (uint8_t*)current_key, NULL);
RETURN_VAL_IF_FAIL(current_key->id == MJSON_ID_UTF8_KEY32, NULL);
next_key = next_element(current_key);
next_key = next_element(next_key);
RETURN_VAL_IF_FAIL(next_key, NULL);
RETURN_VAL_IF_FAIL((uint8_t*)dictionary + dictionary->val_u32 > (uint8_t*)next_key, NULL);
RETURN_VAL_IF_FAIL(next_key->id == MJSON_ID_UTF8_KEY32, NULL);
*next_value = next_element(next_key);
return next_key;
}
mjson_element_t mjson_get_member(mjson_element_t dictionary, const char* name)
{
mjson_element_t key, result;
key = mjson_get_member_first(dictionary, &result);
while (key && strncmp(name, (char*)(key+1), key->val_u32) != 0)
result = mjson_get_member_next(dictionary, key, &result);
return result;
}
int mjson_get_type(mjson_element_t element)
{
RETURN_VAL_IF_FAIL(element, MJSON_ID_NULL);
return element->id;
}
const char* mjson_get_string(mjson_element_t element, const char* fallback)
{
RETURN_VAL_IF_FAIL(element, fallback);
RETURN_VAL_IF_FAIL(element->id == MJSON_ID_UTF8_STRING32 ||
element->id == MJSON_ID_UTF8_KEY32,
fallback);
return (const char*)(element+1);
}
int32_t mjson_get_int(mjson_element_t element, int32_t fallback)
{
RETURN_VAL_IF_FAIL(element, fallback);
RETURN_VAL_IF_FAIL(element->id == MJSON_ID_SINT32, fallback);
return element->val_s32;
}
float mjson_get_float(mjson_element_t element, float fallback)
{
RETURN_VAL_IF_FAIL(element, fallback);
RETURN_VAL_IF_FAIL(element->id == MJSON_ID_FLOAT32, fallback);
return element->val_f32;
}
int mjson_get_bool(mjson_element_t element, int fallback)
{
RETURN_VAL_IF_FAIL(element, fallback);
RETURN_VAL_IF_FAIL(element->id == MJSON_ID_TRUE || element->id == MJSON_ID_FALSE, fallback);
return element->id == MJSON_ID_TRUE;
}
int mjson_is_null(mjson_element_t element)
{
RETURN_VAL_IF_FAIL(element, TRUE);
return element->id == MJSON_ID_NULL;
}
/////////////////////////////////////////////////////////////////////////////
// API helpers
/////////////////////////////////////////////////////////////////////////////
static size_t element_size(mjson_element_t element)
{
RETURN_VAL_IF_FAIL(element, 0);
switch(element->id)
{
case MJSON_ID_NULL:
case MJSON_ID_FALSE:
case MJSON_ID_EMPTY_STRING:
case MJSON_ID_TRUE:
return sizeof(uint32_t);
case MJSON_ID_UINT32:
case MJSON_ID_SINT32:
case MJSON_ID_FLOAT32:
return sizeof(mjson_entry_t);
case MJSON_ID_UTF8_KEY32:
case MJSON_ID_UTF8_STRING32:
return sizeof(mjson_entry_t) + ((element->val_u32 + 1 + 3) & (~3));
case MJSON_ID_BINARY32:
case MJSON_ID_ARRAY32:
case MJSON_ID_DICT32:
return sizeof(mjson_entry_t) + ((element->val_u32 + 3) & (~3));
};
return 0;
}
static mjson_element_t next_element(mjson_element_t element)
{
size_t size;
RETURN_VAL_IF_FAIL(element, 0);
size = element_size(element);
assert(size>0);
return (mjson_element_t)((uint8_t*)element + size);
}
static void* parsectx_reserve_output(mjson_parser_t* ctx, ptrdiff_t size)
{
return (ctx->bjson_limit - ctx->bjson < size) ? 0 : ctx->bjson;
}
static void parsectx_advance_output(mjson_parser_t* ctx, ptrdiff_t size)
{
ctx->bjson += size;
}
static void* parsectx_allocate_output(mjson_parser_t* ctx, ptrdiff_t size)
{
void* ptr;
if (ctx->bjson_limit - ctx->bjson < size)
return 0;
ptr = ctx->bjson;
ctx->bjson += size;
return ptr;
}
//TODO: what about 64 bit code????
static void parsectx_align4_output(mjson_parser_t* ctx)
{
ctx->bjson = (uint8_t*)(((ptrdiff_t)ctx->bjson + 3) & (~3));
}
static void unicode_cp_to_utf8(uint32_t uni_cp, uint8_t* utf8char/*[6]*/, size_t* charlen)
{
uint32_t first, i;
if (uni_cp < 0x80)
{
first = 0;
*charlen = 1;
}
else if (uni_cp < 0x800)
{
first = 0xc0;
*charlen = 2;
}
else if (uni_cp < 0x10000)
{
first = 0xe0;
*charlen = 3;
}
else if (uni_cp < 0x200000)
{
first = 0xf0;
*charlen = 4;
}
else if (uni_cp < 0x4000000)
{
first = 0xf8;
*charlen = 5;
}
else
{
first = 0xfc;
*charlen = 6;
}
for (i = *charlen - 1; i > 0; --i)
{
utf8char[i] = (uni_cp & 0x3f) | 0x80;
uni_cp >>= 6;
}
utf8char[0] = uni_cp | first;
}
/////////////////////////////////////////////////////////////////////////////
// Lexer+Parser code
/////////////////////////////////////////////////////////////////////////////
#line 491 "input_custom_mjson.--input(custom).re"
static void parsectx_next_token(mjson_parser_t* context)
{
#define YYCTYPE uint8_t
#define YYPEEK() (c>=e?0:*c)
#define YYSKIP() ++c
#define YYBACKUP() m = c
#define YYRESTORE() c = m
uint8_t* c = context->next;
uint8_t* e = context->end;
uint8_t* m = NULL;
uint8_t* s;
int token = TOK_NONE;
assert(context);
RETURN_IF_FAIL(context->next != NULL);
while (TRUE)
{
s = c;
#line 491 "<stdout>"
{
YYCTYPE yych;
unsigned int yyaccept = 0;
yych = YYPEEK ();
switch (yych) {
case 0x00: goto yy31;
case '\t':
case '\n':
case '\r':
case ' ': goto yy2;
case '"': goto yy30;
case '+':
case '-': goto yy22;
case ',': goto yy18;
case '.': goto yy24;
case '/': goto yy4;
case '0': goto yy20;
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9': goto yy23;
case ':': goto yy14;
case '=': goto yy16;
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
case 'G':
case 'H':
case 'I':
case 'J':
case 'K':
case 'L':
case 'M':
case 'N':
case 'O':
case 'P':
case 'Q':
case 'R':
case 'S':
case 'T':
case 'U':
case 'V':
case 'W':
case 'X':
case 'Y':
case 'Z':
case '_':
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'g':
case 'h':
case 'i':
case 'j':
case 'k':
case 'l':
case 'm':
case 'o':
case 'p':
case 'q':
case 'r':
case 's':
case 'u':
case 'v':
case 'w':
case 'x':
case 'y':
case 'z': goto yy29;
case '[': goto yy10;
case ']': goto yy12;
case 'f': goto yy27;
case 'n': goto yy28;
case 't': goto yy25;
case '{': goto yy6;
case '}': goto yy8;
default: goto yy33;
}
yy2:
YYSKIP ();
yych = YYPEEK ();
goto yy126;
yy3:
#line 515 "input_custom_mjson.--input(custom).re"
{
continue;
}
#line 589 "<stdout>"
yy4:
yyaccept = 0;
YYSKIP ();
YYBACKUP ();
yych = YYPEEK ();
switch (yych) {
case '*': goto yy108;
case '/': goto yy110;
default: goto yy5;
}
yy5:
#line 622 "input_custom_mjson.--input(custom).re"
{
context->token = TOK_INVALID;
return;
}
#line 606 "<stdout>"
yy6:
YYSKIP ();
#line 527 "input_custom_mjson.--input(custom).re"
{
token = TOK_LEFT_CURLY_BRACKET;
goto done;
}
#line 614 "<stdout>"
yy8:
YYSKIP ();
#line 532 "input_custom_mjson.--input(custom).re"
{
token = TOK_RIGHT_CURLY_BRACKET;
goto done;
}
#line 622 "<stdout>"
yy10:
YYSKIP ();
#line 537 "input_custom_mjson.--input(custom).re"
{
token = TOK_LEFT_BRACKET;
goto done;
}
#line 630 "<stdout>"
yy12:
YYSKIP ();
#line 542 "input_custom_mjson.--input(custom).re"
{
token = TOK_RIGHT_BRACKET;
goto done;
}
#line 638 "<stdout>"
yy14:
YYSKIP ();
#line 547 "input_custom_mjson.--input(custom).re"
{
token = TOK_COLON;
goto done;
}
#line 646 "<stdout>"
yy16:
YYSKIP ();
#line 552 "input_custom_mjson.--input(custom).re"
{
token = TOK_EQUAL;
goto done;
}
#line 654 "<stdout>"
yy18:
YYSKIP ();
#line 557 "input_custom_mjson.--input(custom).re"
{
token = TOK_COMMA;
goto done;
}
#line 662 "<stdout>"
yy20:
YYSKIP ();
switch ((yych = YYPEEK ())) {
case '.':
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
case 'G':
case 'H':
case 'I':
case 'J':
case 'K':
case 'L':
case 'M':
case 'N':
case 'O':
case 'P':
case 'Q':
case 'R':
case 'S':
case 'T':
case 'U':
case 'V':
case 'W':
case 'Y':
case 'Z':
case '_':
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f':
case 'g':
case 'h':
case 'i':
case 'j':
case 'k':
case 'l':
case 'm':
case 'n':
case 'o':
case 'p':
case 'q':
case 'r':
case 's':
case 't':
case 'u':
case 'v':
case 'w':
case 'y':
case 'z': goto yy100;
case 'X':
case 'x': goto yy104;
default: goto yy21;
}
yy21:
#line 572 "input_custom_mjson.--input(custom).re"
{
token = TOK_DEC_NUMBER;
goto done;
}
#line 738 "<stdout>"
yy22:
yyaccept = 0;
YYSKIP ();
YYBACKUP ();
yych = YYPEEK ();
switch (yych) {
case '.': goto yy95;
case '0': goto yy92;
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9': goto yy93;
default: goto yy5;
}
yy23:
YYSKIP ();
yych = YYPEEK ();
goto yy71;
yy24:
YYSKIP ();
yych = YYPEEK ();
switch (yych) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9': goto yy63;
default: goto yy5;
}
yy25:
YYSKIP ();
switch ((yych = YYPEEK ())) {
case 'r': goto yy59;
default: goto yy49;
}
yy26:
#line 597 "input_custom_mjson.--input(custom).re"
{
token = TOK_IDENTIFIER;
goto done;
}
#line 790 "<stdout>"
yy27:
YYSKIP ();
yych = YYPEEK ();
switch (yych) {
case 'a': goto yy54;
default: goto yy49;
}
yy28:
YYSKIP ();
yych = YYPEEK ();
switch (yych) {
case 'u': goto yy50;
default: goto yy49;
}
yy29:
YYSKIP ();
yych = YYPEEK ();
goto yy49;
yy30:
yyaccept = 0;
YYSKIP ();
YYBACKUP ();
yych = YYPEEK ();
if (yych <= 0x00) goto yy5;
goto yy35;
yy31:
YYSKIP ();
#line 612 "input_custom_mjson.--input(custom).re"
{
context->token = TOK_NONE;
return;
}
#line 823 "<stdout>"
yy33:
YYSKIP ();
yych = YYPEEK ();
goto yy5;
yy34:
YYSKIP ();
yych = YYPEEK ();
yy35:
switch (yych) {
case 0x00: goto yy36;
case '"': goto yy38;
case '\\': goto yy37;
default: goto yy34;
}
yy36:
YYRESTORE ();
switch (yyaccept) {
case 0: goto yy5;
case 1: goto yy65;
case 2: goto yy74;
case 3: goto yy21;
default: goto yy120;
}
yy37:
YYSKIP ();
yych = YYPEEK ();
switch (yych) {
case '"':
case '/':
case '\\':
case 'b':
case 'f':
case 'n':
case 'r':
case 't': goto yy41;
case 'u': goto yy40;
default: goto yy36;
}
yy38:
YYSKIP ();
#line 602 "input_custom_mjson.--input(custom).re"
{
token = TOK_NOESC_STRING;
goto done;
}
#line 869 "<stdout>"
yy40:
YYSKIP ();
yych = YYPEEK ();
switch (yych) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f': goto yy45;
default: goto yy36;
}
yy41:
YYSKIP ();
yych = YYPEEK ();
switch (yych) {
case 0x00: goto yy36;
case '"': goto yy43;
case '\\': goto yy37;
default: goto yy41;
}
yy43:
YYSKIP ();
#line 607 "input_custom_mjson.--input(custom).re"
{
token = TOK_STRING;
goto done;
}
#line 914 "<stdout>"
yy45:
YYSKIP ();
yych = YYPEEK ();
switch (yych) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f': goto yy46;
default: goto yy36;
}
yy46:
YYSKIP ();
yych = YYPEEK ();
switch (yych) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f': goto yy47;
default: goto yy36;
}
yy47:
YYSKIP ();
yych = YYPEEK ();
switch (yych) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f': goto yy41;
default: goto yy36;
}
yy48:
YYSKIP ();
yych = YYPEEK ();
yy49:
switch (yych) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
case 'G':
case 'H':
case 'I':
case 'J':
case 'K':
case 'L':
case 'M':
case 'N':
case 'O':
case 'P':
case 'Q':
case 'R':
case 'S':
case 'T':
case 'U':
case 'V':
case 'W':
case 'X':
case 'Y':
case 'Z':
case '_':
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f':
case 'g':
case 'h':
case 'i':
case 'j':
case 'k':
case 'l':
case 'm':
case 'n':
case 'o':
case 'p':
case 'q':
case 'r':
case 's':
case 't':
case 'u':
case 'v':
case 'w':
case 'x':
case 'y':
case 'z': goto yy48;
default: goto yy26;
}
yy50:
YYSKIP ();
yych = YYPEEK ();
switch (yych) {
case 'l': goto yy51;
default: goto yy49;
}
yy51:
YYSKIP ();
yych = YYPEEK ();
switch (yych) {
case 'l': goto yy52;
default: goto yy49;
}
yy52:
YYSKIP ();
switch ((yych = YYPEEK ())) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
case 'G':
case 'H':
case 'I':
case 'J':
case 'K':
case 'L':
case 'M':
case 'N':
case 'O':
case 'P':
case 'Q':
case 'R':
case 'S':
case 'T':
case 'U':
case 'V':
case 'W':
case 'X':
case 'Y':
case 'Z':
case '_':
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f':
case 'g':
case 'h':
case 'i':
case 'j':
case 'k':
case 'l':
case 'm':
case 'n':
case 'o':
case 'p':
case 'q':
case 'r':
case 's':
case 't':
case 'u':
case 'v':
case 'w':
case 'x':
case 'y':
case 'z': goto yy48;
default: goto yy53;
}
yy53:
#line 592 "input_custom_mjson.--input(custom).re"
{
token = TOK_NULL;
goto done;
}
#line 1157 "<stdout>"
yy54:
YYSKIP ();
yych = YYPEEK ();
switch (yych) {
case 'l': goto yy55;
default: goto yy49;
}
yy55:
YYSKIP ();
yych = YYPEEK ();
switch (yych) {
case 's': goto yy56;
default: goto yy49;
}
yy56:
YYSKIP ();
yych = YYPEEK ();
switch (yych) {
case 'e': goto yy57;
default: goto yy49;
}
yy57:
YYSKIP ();
switch ((yych = YYPEEK ())) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
case 'G':
case 'H':
case 'I':
case 'J':
case 'K':
case 'L':
case 'M':
case 'N':
case 'O':
case 'P':
case 'Q':
case 'R':
case 'S':
case 'T':
case 'U':
case 'V':
case 'W':
case 'X':
case 'Y':
case 'Z':
case '_':
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f':
case 'g':
case 'h':
case 'i':
case 'j':
case 'k':
case 'l':
case 'm':
case 'n':
case 'o':
case 'p':
case 'q':
case 'r':
case 's':
case 't':
case 'u':
case 'v':
case 'w':
case 'x':
case 'y':
case 'z': goto yy48;
default: goto yy58;
}
yy58:
#line 587 "input_custom_mjson.--input(custom).re"
{
token = TOK_FALSE;
goto done;
}
#line 1253 "<stdout>"
yy59:
YYSKIP ();
yych = YYPEEK ();
switch (yych) {
case 'u': goto yy60;
default: goto yy49;
}
yy60:
YYSKIP ();
yych = YYPEEK ();
switch (yych) {
case 'e': goto yy61;
default: goto yy49;
}
yy61:
YYSKIP ();
switch ((yych = YYPEEK ())) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
case 'G':
case 'H':
case 'I':
case 'J':
case 'K':
case 'L':
case 'M':
case 'N':
case 'O':
case 'P':
case 'Q':
case 'R':
case 'S':
case 'T':
case 'U':
case 'V':
case 'W':
case 'X':
case 'Y':
case 'Z':
case '_':
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f':
case 'g':
case 'h':
case 'i':
case 'j':
case 'k':
case 'l':
case 'm':
case 'n':
case 'o':
case 'p':
case 'q':
case 'r':
case 's':
case 't':
case 'u':
case 'v':
case 'w':
case 'x':
case 'y':
case 'z': goto yy48;
default: goto yy62;
}
yy62:
#line 582 "input_custom_mjson.--input(custom).re"
{
token = TOK_TRUE;
goto done;
}
#line 1342 "<stdout>"
yy63:
yyaccept = 1;
YYSKIP ();
YYBACKUP ();
yych = YYPEEK ();
switch (yych) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9': goto yy63;
case 'E':
case 'e': goto yy66;
default: goto yy65;
}
yy65:
#line 577 "input_custom_mjson.--input(custom).re"
{
token = TOK_FLOAT_NUMBER;
goto done;
}
#line 1369 "<stdout>"
yy66:
YYSKIP ();
yych = YYPEEK ();
switch (yych) {
case '+':
case '-': goto yy67;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9': goto yy68;
default: goto yy36;
}
yy67:
YYSKIP ();
yych = YYPEEK ();
switch (yych) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9': goto yy68;
default: goto yy36;
}
yy68:
YYSKIP ();
yych = YYPEEK ();
switch (yych) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9': goto yy68;
default: goto yy65;
}
yy70:
YYSKIP ();
yych = YYPEEK ();
yy71:
switch (yych) {
case '.': goto yy76;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9': goto yy70;
case 'A':
case 'B':
case 'C':
case 'D':
case 'F':
case 'G':
case 'H':
case 'I':
case 'J':
case 'K':
case 'L':
case 'M':
case 'N':
case 'O':
case 'P':
case 'Q':
case 'R':
case 'S':
case 'T':
case 'U':
case 'V':
case 'W':
case 'X':
case 'Y':
case 'Z':
case '_':
case 'a':
case 'b':
case 'c':
case 'd':
case 'f':
case 'g':
case 'h':
case 'i':
case 'j':
case 'k':
case 'l':
case 'm':
case 'n':
case 'o':
case 'p':
case 'q':
case 'r':
case 's':
case 't':
case 'u':
case 'v':
case 'w':
case 'x':
case 'y':
case 'z': goto yy72;
case 'E':
case 'e': goto yy75;
default: goto yy21;
}
yy72:
YYSKIP ();
yych = YYPEEK ();
switch (yych) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
case 'G':
case 'H':
case 'I':
case 'J':
case 'K':
case 'L':
case 'M':
case 'N':
case 'O':
case 'P':
case 'Q':
case 'R':
case 'S':
case 'T':
case 'U':
case 'V':
case 'W':
case 'X':
case 'Y':
case 'Z':
case '_':
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f':
case 'g':
case 'h':
case 'i':
case 'j':
case 'k':
case 'l':
case 'm':
case 'n':
case 'o':
case 'p':
case 'q':
case 'r':
case 's':
case 't':
case 'u':
case 'v':
case 'w':
case 'x':
case 'y':
case 'z': goto yy72;
default: goto yy74;
}
yy74:
#line 617 "input_custom_mjson.--input(custom).re"
{
context->token = TOK_INVALID;
return;
}
#line 1566 "<stdout>"
yy75:
yyaccept = 2;
YYSKIP ();
YYBACKUP ();
yych = YYPEEK ();
switch (yych) {
case '+':
case '-': goto yy87;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9': goto yy88;
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
case 'G':
case 'H':
case 'I':
case 'J':
case 'K':
case 'L':
case 'M':
case 'N':
case 'O':
case 'P':
case 'Q':
case 'R':
case 'S':
case 'T':
case 'U':
case 'V':
case 'W':
case 'X':
case 'Y':
case 'Z':
case '_':
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f':
case 'g':
case 'h':
case 'i':
case 'j':
case 'k':
case 'l':
case 'm':
case 'n':
case 'o':
case 'p':
case 'q':
case 'r':
case 's':
case 't':
case 'u':
case 'v':
case 'w':
case 'x':
case 'y':
case 'z': goto yy72;
default: goto yy74;
}
yy76:
yyaccept = 1;
YYSKIP ();
YYBACKUP ();
yych = YYPEEK ();
switch (yych) {
case 'E':
case 'e': goto yy79;
default: goto yy78;
}
yy77:
yyaccept = 1;
YYSKIP ();
YYBACKUP ();
yych = YYPEEK ();
yy78:
switch (yych) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9': goto yy77;
case 'E':
case 'e': goto yy83;
default: goto yy65;
}
yy79:
YYSKIP ();
yych = YYPEEK ();
switch (yych) {
case '+':
case '-': goto yy80;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9': goto yy81;
default: goto yy36;
}
yy80:
YYSKIP ();
yych = YYPEEK ();
switch (yych) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9': goto yy81;
default: goto yy36;
}
yy81:
YYSKIP ();
yych = YYPEEK ();
switch (yych) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9': goto yy81;
default: goto yy65;
}
yy83:
YYSKIP ();
yych = YYPEEK ();
switch (yych) {
case '+':
case '-': goto yy84;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9': goto yy85;
default: goto yy36;
}
yy84:
YYSKIP ();
yych = YYPEEK ();
switch (yych) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9': goto yy85;
default: goto yy36;
}
yy85:
YYSKIP ();
yych = YYPEEK ();
switch (yych) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9': goto yy85;
default: goto yy65;
}
yy87:
YYSKIP ();
yych = YYPEEK ();
switch (yych) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9': goto yy90;
default: goto yy36;
}
yy88:
YYSKIP ();
yych = YYPEEK ();
switch (yych) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9': goto yy88;
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
case 'G':
case 'H':
case 'I':
case 'J':
case 'K':
case 'L':
case 'M':
case 'N':
case 'O':
case 'P':
case 'Q':
case 'R':
case 'S':
case 'T':
case 'U':
case 'V':
case 'W':
case 'X':
case 'Y':
case 'Z':
case '_':
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f':
case 'g':
case 'h':
case 'i':
case 'j':
case 'k':
case 'l':
case 'm':
case 'n':
case 'o':
case 'p':
case 'q':
case 'r':
case 's':
case 't':
case 'u':
case 'v':
case 'w':
case 'x':
case 'y':
case 'z': goto yy72;
default: goto yy65;
}
yy90:
YYSKIP ();
yych = YYPEEK ();
switch (yych) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9': goto yy90;
default: goto yy65;
}
yy92:
yyaccept = 3;
YYSKIP ();
YYBACKUP ();
yych = YYPEEK ();
switch (yych) {
case '.': goto yy76;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9': goto yy97;
case 'E':
case 'e': goto yy96;
default: goto yy21;
}
yy93:
yyaccept = 3;
YYSKIP ();
YYBACKUP ();
yych = YYPEEK ();
switch (yych) {
case '.': goto yy76;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9': goto yy93;
case 'E':
case 'e': goto yy96;
default: goto yy21;
}
yy95:
YYSKIP ();
yych = YYPEEK ();
switch (yych) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9': goto yy63;
default: goto yy36;
}
yy96:
YYSKIP ();
yych = YYPEEK ();
switch (yych) {
case '+':
case '-': goto yy87;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9': goto yy90;
default: goto yy36;
}
yy97:
YYSKIP ();
yych = YYPEEK ();
switch (yych) {
case '.': goto yy76;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9': goto yy97;
case 'E':
case 'e': goto yy96;
default: goto yy36;
}
yy99:
YYSKIP ();
yych = YYPEEK ();
yy100:
switch (yych) {
case '.': goto yy76;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7': goto yy99;
case '8':
case '9': goto yy102;
case 'A':
case 'B':
case 'C':
case 'D':
case 'F':
case 'G':
case 'H':
case 'I':
case 'J':
case 'K':
case 'L':
case 'M':
case 'N':
case 'O':
case 'P':
case 'Q':
case 'R':
case 'S':
case 'T':
case 'U':
case 'V':
case 'W':
case 'X':
case 'Y':
case 'Z':
case '_':
case 'a':
case 'b':
case 'c':
case 'd':
case 'f':
case 'g':
case 'h':
case 'i':
case 'j':
case 'k':
case 'l':
case 'm':
case 'n':
case 'o':
case 'p':
case 'q':
case 'r':
case 's':
case 't':
case 'u':
case 'v':
case 'w':
case 'x':
case 'y':
case 'z': goto yy72;
case 'E':
case 'e': goto yy75;
default: goto yy101;
}
yy101:
#line 562 "input_custom_mjson.--input(custom).re"
{
token = TOK_OCT_NUMBER;
goto done;
}
#line 2044 "<stdout>"
yy102:
YYSKIP ();
yych = YYPEEK ();
switch (yych) {
case '.': goto yy76;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9': goto yy102;
case 'A':
case 'B':
case 'C':
case 'D':
case 'F':
case 'G':
case 'H':
case 'I':
case 'J':
case 'K':
case 'L':
case 'M':
case 'N':
case 'O':
case 'P':
case 'Q':
case 'R':
case 'S':
case 'T':
case 'U':
case 'V':
case 'W':
case 'X':
case 'Y':
case 'Z':
case '_':
case 'a':
case 'b':
case 'c':
case 'd':
case 'f':
case 'g':
case 'h':
case 'i':
case 'j':
case 'k':
case 'l':
case 'm':
case 'n':
case 'o':
case 'p':
case 'q':
case 'r':
case 's':
case 't':
case 'u':
case 'v':
case 'w':
case 'x':
case 'y':
case 'z': goto yy72;
case 'E':
case 'e': goto yy75;
default: goto yy74;
}
yy104:
YYSKIP ();
yych = YYPEEK ();
switch (yych) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
case 'G':
case 'H':
case 'I':
case 'J':
case 'K':
case 'L':
case 'M':
case 'N':
case 'O':
case 'P':
case 'Q':
case 'R':
case 'S':
case 'T':
case 'U':
case 'V':
case 'W':
case 'X':
case 'Y':
case 'Z':
case '_':
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f':
case 'g':
case 'h':
case 'i':
case 'j':
case 'k':
case 'l':
case 'm':
case 'n':
case 'o':
case 'p':
case 'q':
case 'r':
case 's':
case 't':
case 'u':
case 'v':
case 'w':
case 'x':
case 'y':
case 'z': goto yy106;
default: goto yy74;
}
yy105:
YYSKIP ();
yych = YYPEEK ();
yy106:
switch (yych) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f': goto yy105;
case 'G':
case 'H':
case 'I':
case 'J':
case 'K':
case 'L':
case 'M':
case 'N':
case 'O':
case 'P':
case 'Q':
case 'R':
case 'S':
case 'T':
case 'U':
case 'V':
case 'W':
case 'X':
case 'Y':
case 'Z':
case '_':
case 'g':
case 'h':
case 'i':
case 'j':
case 'k':
case 'l':
case 'm':
case 'n':
case 'o':
case 'p':
case 'q':
case 'r':
case 's':
case 't':
case 'u':
case 'v':
case 'w':
case 'x':
case 'y':
case 'z': goto yy72;
default: goto yy107;
}
yy107:
#line 567 "input_custom_mjson.--input(custom).re"
{
token = TOK_HEX_NUMBER;
goto done;
}
#line 2260 "<stdout>"
yy108:
YYSKIP ();
yych = YYPEEK ();
switch (yych) {
case 0x00: goto yy36;
case '*': goto yy114;
default: goto yy108;
}
yy110:
YYSKIP ();
yych = YYPEEK ();
switch (yych) {
case 0x00: goto yy36;
case '\n': goto yy112;
default: goto yy110;
}
yy112:
YYSKIP ();
#line 519 "input_custom_mjson.--input(custom).re"
{
continue;
}
#line 2283 "<stdout>"
yy114:
YYSKIP ();
yych = YYPEEK ();
switch (yych) {
case '*': goto yy117;
case '/': goto yy119;
default: goto yy116;
}
yy115:
YYSKIP ();
yych = YYPEEK ();
yy116:
switch (yych) {
case 0x00: goto yy36;
case '*': goto yy122;
default: goto yy115;
}
yy117:
YYSKIP ();
yych = YYPEEK ();
switch (yych) {
case 0x00: goto yy36;
case '*': goto yy117;
case '/': goto yy121;
default: goto yy115;
}
yy119:
YYSKIP ();
yy120:
#line 523 "input_custom_mjson.--input(custom).re"
{
continue;
}
#line 2317 "<stdout>"
yy121:
yyaccept = 4;
YYSKIP ();
YYBACKUP ();
yych = YYPEEK ();
switch (yych) {
case 0x00: goto yy120;
case '*': goto yy122;
default: goto yy115;
}
yy122:
YYSKIP ();
yych = YYPEEK ();
switch (yych) {
case 0x00: goto yy36;
case '*': goto yy123;
case '/': goto yy119;
default: goto yy115;
}
yy123:
YYSKIP ();
yych = YYPEEK ();
switch (yych) {
case 0x00: goto yy36;
case '*': goto yy123;
case '/': goto yy121;
default: goto yy115;
}
yy125:
YYSKIP ();
yych = YYPEEK ();
yy126:
switch (yych) {
case '\t':
case '\n':
case '\r':
case ' ': goto yy125;
default: goto yy3;
}
}
#line 626 "input_custom_mjson.--input(custom).re"
}
done:
context->token = token;
context->start = s;
context->next = c;
#undef YYREADINPUT
#undef YYCTYPE
#undef YYCURSOR
#undef YYMARKER
}
static int parse_number(mjson_parser_t *context)
{
int num_parsed;
uint8_t bjson_id;
const char* format;
mjson_entry_t* bdata;
switch(context->token)
{
case TOK_OCT_NUMBER:
bjson_id = MJSON_ID_SINT32;
format = "%o";
break;
case TOK_HEX_NUMBER:
bjson_id = MJSON_ID_SINT32;
format = "%x";
break;
case TOK_DEC_NUMBER:
bjson_id = MJSON_ID_SINT32;
format = "%d";
break;
case TOK_FLOAT_NUMBER:
bjson_id = MJSON_ID_FLOAT32;
format = "%f";
break;
default:
assert(!"unknown token");
}
bdata = (mjson_entry_t*)parsectx_allocate_output(context, (ptrdiff_t)sizeof(mjson_entry_t));
if (!bdata) return 0;
bdata->id = bjson_id;
num_parsed = sscanf((char*)context->start, format, &bdata->val_u32);
assert(num_parsed == 1);
parsectx_next_token(context);
return 1;
}
static int parse_string(mjson_parser_t *context, uint32_t id)
{
#define YYREADINPUT(c) (c>=e?0:*c)
#define YYCTYPE uint8_t
#define YYCURSOR c
#define YYMARKER m
uint8_t* c = context->start+1;
uint8_t* e = context->next;
uint8_t* m = NULL;
uint8_t* s;
mjson_entry_t* bdata;
uint32_t ch = 0;
uint8_t* str_dst;
const uint8_t* str_src;
ptrdiff_t str_len;
size_t len;
int num_parsed;
assert(
context->token == TOK_STRING ||
context->token == TOK_NOESC_STRING ||
context->token == TOK_IDENTIFIER
);
bdata = (mjson_entry_t*)parsectx_allocate_output(context, (ptrdiff_t)sizeof(mjson_entry_t));
if (!bdata) return 0;
bdata->id = id;
if (context->token != TOK_STRING)
{
str_src = context->start;
str_len = context->next - context->start;
if (context->token==TOK_NOESC_STRING)
{
str_src += 1;
str_len -= 2;
}
bdata->val_u32 = str_len;
str_dst = (uint8_t*)parsectx_allocate_output(context, str_len + 1);
if (!str_dst) return 0;
memcpy(str_dst, str_src, str_len);
str_dst[str_len] = 0;
parsectx_align4_output(context);
parsectx_next_token(context);
return 1;
}
while (TRUE)
{
s = c;
#line 2478 "<stdout>"
{
YYCTYPE yych;
yych = YYPEEK ();
switch (yych) {
case 0x00: goto yy135;
case '"': goto yy133;
case '\\': goto yy131;
default: goto yy129;
}
yy129:
YYSKIP ();
yych = YYPEEK ();
goto yy146;
yy130:
#line 745 "input_custom_mjson.--input(custom).re"
{
str_dst = (uint8_t*)parsectx_allocate_output(context, c - s);
if (!str_dst) return 0;
memcpy(str_dst, s, c - s);
continue;
}
#line 2503 "<stdout>"
yy131:
YYSKIP ();
YYBACKUP ();
yych = YYPEEK ();
switch (yych) {
case '"':
case '/':
case '\\':
case 'b':
case 'f':
case 'n':
case 'r':
case 't': goto yy138;
case 'u': goto yy136;
default: goto yy132;
}
yy132:
#line 810 "input_custom_mjson.--input(custom).re"
{
assert(!"reachable");
}
#line 2525 "<stdout>"
yy133:
YYSKIP ();
#line 801 "input_custom_mjson.--input(custom).re"
{
bdata->val_u32 = context->bjson - (uint8_t*)(bdata + 1);
*context->bjson++ = 0;
parsectx_align4_output(context);
parsectx_next_token(context);
return 1;
}
#line 2537 "<stdout>"
yy135:
YYSKIP ();
yych = YYPEEK ();
goto yy132;
yy136:
YYSKIP ();
yych = YYPEEK ();
switch (yych) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f': goto yy140;
default: goto yy137;
}
yy137:
YYRESTORE ();
goto yy132;
yy138:
YYSKIP ();
#line 756 "input_custom_mjson.--input(custom).re"
{
char decoded = s[1];
switch (s[1])
{
case 'b':
decoded = '\b';
break;
case 'n':
decoded = '\n';
break;
case 'r':
decoded = '\r';
break;
case 't':
decoded = '\t';
break;
case 'f':
decoded = '\f';
break;
}
str_dst = (uint8_t*)parsectx_allocate_output(context, 1);
if (!str_dst) return 0;
*str_dst = decoded;
continue;
}
#line 2606 "<stdout>"
yy140:
YYSKIP ();
yych = YYPEEK ();
switch (yych) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f': goto yy141;
default: goto yy137;
}
yy141:
YYSKIP ();
yych = YYPEEK ();
switch (yych) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f': goto yy142;
default: goto yy137;
}
yy142:
YYSKIP ();
yych = YYPEEK ();
switch (yych) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f': goto yy143;
default: goto yy137;
}
yy143:
YYSKIP ();
#line 787 "input_custom_mjson.--input(custom).re"
{
str_dst = (uint8_t*)parsectx_reserve_output(context, 6);
if (!str_dst) return 0;
num_parsed = sscanf((char*)(s + 2), "%4x", &ch);
assert(num_parsed == 1);
unicode_cp_to_utf8(ch, str_dst, &len);
parsectx_advance_output(context, len);
continue;
}
#line 2707 "<stdout>"
yy145:
YYSKIP ();
yych = YYPEEK ();
yy146:
switch (yych) {
case 0x00:
case '"':
case '\\': goto yy130;
default: goto yy145;
}
}
#line 813 "input_custom_mjson.--input(custom).re"
}
#undef YYREADINPUT
#undef YYCTYPE
#undef YYCURSOR
#undef YYMARKER
assert(!"reachable");
return 0;
}
static int parse_simple(mjson_parser_t *context)
{
uint32_t* id;
assert(
context->token == TOK_NULL ||
context->token == TOK_FALSE ||
context->token == TOK_TRUE
);
id = (uint32_t*)parsectx_allocate_output(context, sizeof(uint32_t));
if (!id) return 0;
switch (context->token)
{
case TOK_NULL:
*id = MJSON_ID_NULL;
break;
case TOK_FALSE:
*id = MJSON_ID_FALSE;
break;
case TOK_TRUE:
*id = MJSON_ID_TRUE;
break;
}
parsectx_next_token(context);
return 1;
}
static int parse_value(mjson_parser_t *context)
{
assert(context);
switch (context->token)
{
case TOK_NULL:
case TOK_FALSE:
case TOK_TRUE:
return parse_simple(context);
case TOK_OCT_NUMBER:
case TOK_HEX_NUMBER:
case TOK_DEC_NUMBER:
case TOK_FLOAT_NUMBER:
return parse_number(context);
case TOK_NOESC_STRING:
case TOK_STRING:
return parse_string(context, MJSON_ID_UTF8_STRING32);
case TOK_LEFT_CURLY_BRACKET:
parsectx_next_token(context);
return parse_key_value_pair(context, TOK_RIGHT_CURLY_BRACKET);
case TOK_LEFT_BRACKET:
parsectx_next_token(context);
return parse_value_list(context);
}
return 0;
}
static int parse_value_list(mjson_parser_t *context)
{
mjson_entry_t* array;
uint8_t* data_start;
int expect_separator;
assert(context);
array = (mjson_entry_t*)parsectx_allocate_output(context, sizeof(mjson_entry_t));
if (!array) return 0;
array->id = MJSON_ID_ARRAY32;
data_start = context->bjson;
expect_separator = FALSE;
while (context->token != TOK_RIGHT_BRACKET)
{
if (expect_separator && context->token == TOK_COMMA)
parsectx_next_token(context);
else
expect_separator = TRUE;
if (!parse_value(context))
return 0;
}
array->val_u32 = context->bjson - data_start;
assert((array->val_u32 & 3) == 0);
parsectx_next_token(context);
return 1;
}
static int parse_key_value_pair(mjson_parser_t* context, int stop_token)
{
mjson_entry_t* dictionary;
uint8_t* data_start;
int expect_separator;
assert(context);
dictionary = (mjson_entry_t*)parsectx_allocate_output(context, sizeof(mjson_entry_t));
if (!dictionary) return 0;
dictionary->id = MJSON_ID_DICT32;
data_start = context->bjson;
expect_separator = FALSE;
while (context->token != stop_token)
{
if (expect_separator && context->token == TOK_COMMA)
parsectx_next_token(context);
else
expect_separator = TRUE;
switch (context->token)
{
case TOK_IDENTIFIER:
case TOK_NOESC_STRING:
if (!parse_string(context, MJSON_ID_UTF8_KEY32))
return 0;
break;
default:
return 0;
}
if (context->token != TOK_COLON && context->token != TOK_EQUAL)
return 0;
parsectx_next_token(context);
if (!parse_value(context))
return 0;
}
dictionary->val_u32 = context->bjson - data_start;
assert((dictionary->val_u32 & 3) == 0);
parsectx_next_token(context);
return 1;
}
|
the_stack_data/61075950.c | /*
ttyslot.c
Return the index in the utmp file for the current user's terminal. The
current user's terminal is the first file descriptor in the range 0..2
for which ttyname() returns a name. The index is the line number in the
/etc/ttytab file. 0 will be returned in case of an error.
Created: Oct 11, 1992 by Philip Homburg
*/
#define _MINIX_SOURCE
#include <sys/types.h>
#include <ttyent.h>
#include <string.h>
#include <unistd.h>
int ttyslot()
{
int slot;
slot= fttyslot(0);
if (slot == 0) slot= fttyslot(1);
if (slot == 0) slot= fttyslot(2);
return slot;
}
int fttyslot(fd)
int fd;
{
char *tname;
int lineno;
struct ttyent *ttyp;
tname= ttyname(fd);
if (tname == NULL) return 0;
/* Assume that tty devices are in /dev */
if (strncmp(tname, "/dev/", 5) != 0)
return 0; /* Malformed tty name. */
tname += 5;
/* Scan /etc/ttytab. */
lineno= 1;
while ((ttyp= getttyent()) != NULL)
{
if (strcmp(tname, ttyp->ty_name) == 0)
{
endttyent();
return lineno;
}
lineno++;
}
/* No match */
endttyent();
return 0;
}
/*
* $PchHeader: /mount/hd2/minix/lib/misc/RCS/ttyslot.c,v 1.3 1994/12/22 13:49:12 philip Exp $
*/
|
the_stack_data/111078859.c | #include <stdio.h>
int main ( void )
{
int N = 0, temp = 0;
int P = 1;
printf( "\nN = " );
scanf( "%d", &N );
if( N == 0 ) P = 0;
int i;
for( i = 0; i < N; i++ )
{
printf( "%d: ", i+1 );
scanf( "%d", &temp );
P *= temp - (i+1);
}
printf( "\nP = %d\n", P );
return 0;
}
|
the_stack_data/184517351.c | /*
* All hopefully^W possible ways to express do/while loops.
*/
int
main(void)
{
do
continue;
while (1);
do {
continue;
} while (1);
do {
} while (1);
}
|
the_stack_data/31387026.c | // https://www.codewars.com/kata/5b24bcecd74b5be066000054/train/c
// My solution
#include <stdbool.h>
#include <stdlib.h>
// A node in our linked list
typedef struct node
{
int data;
struct node *next;
} Node;
// Our stack, implemented as a wrapper around our linked list
typedef struct
{
Node *root;
} Stack;
// Modify the code below to implement the key operations for our stack
void stack_push(Stack *stack, int data)
{
Node *newNode = malloc(sizeof(Node));
newNode->next = stack->root;
newNode->data = data;
stack->root = newNode;
}
int stack_pop(Stack *stack)
{
Node *lastRoot = stack->root;
if (lastRoot != NULL)
{
int value = lastRoot->data;
stack->root = lastRoot->next;
free(lastRoot);
return value;
}
return 0;
}
int stack_peek(const Stack *stack)
{
if (stack->root != NULL)
{
return stack->root->data;
}
return 0;
}
bool stack_is_empty(const Stack *stack)
{
return stack->root == NULL;
}
|
the_stack_data/446572.c | /*BEGIN_LEGAL
Intel Open Source License
Copyright (c) 2002-2015 Intel Corporation. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer. 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. Neither the name of
the Intel Corporation nor the names of its contributors may be used to
endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
``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 INTEL OR
ITS CONTRIBUTORS 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.
END_LEGAL */
char data[0xa0000000];
int main()
{
return 0;
}
|
the_stack_data/178266371.c | /* Exercise 1-16.
Revise the main routine of the longest-line program so it will correctly
print the length of arbitrarily long input lines, and as much as possible of
the text.
*/
#include <stdio.h>
#define MAXLINE 40 /* maximum input line size */
int get_line(char line[], int maxline);
void copy(char to[], char from[]);
/* print longest input line */
int main()
{
int len; /* current line length */
int max; /* maximum length so far */
char line[MAXLINE]; /* current input line */
char longest[MAXLINE]; /* longest line saved here */
max = 0;
while ((len = get_line(line, MAXLINE)) > 0)
if (len > max) {
max = len;
copy(longest, line);
}
if (max > 0) /* there was a line */
printf("%d:%s\n", max, longest);
return 0;
}
/* getline: read as a line into s, return length */
int get_line(char s[], int lim)
{
int c, i;
for (i=0; (c=getchar())!=EOF && c!='\n'; ++i)
if (i<lim-1)
s[i] = c;
if (c == '\n') {
if (i<lim-1)
s[i] = c;
++i;
}
if (i < lim)
s[i] = '\0';
else
s[lim-1] = '\0';
return i;
}
/* copy: copy 'from' into 'to'; assume to is big enough */
void copy(char to[], char from[])
{
int i;
i = 0;
while ((to[i] = from[i]) != '\0')
++i;
}
/*
* cat lorem-ipsum.txt | a.out
79:Lorem ipsum dolor sit amet, consec
*/
|
the_stack_data/89199866.c | #include <stdio.h>
int main(void)
{
float x;
printf("f(x)=3x^5+2x^4+5x^3-x^2+7x-6\n");
printf("Insert a value for x: ");
scanf("%f", &x);
/*regola di Homer*/
printf("f(%.2f)=%.2f\n", x, ((((3 * x + 2) * x + 5) * x - 1) * x + 7) * x - 6);
return 0;
}
|
the_stack_data/165768165.c | #define _XOPEN_SOURCE 500
#include <sys/stat.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <dirent.h>
#include <errno.h>
#include <stdarg.h>
#include <stdlib.h>
#include <sys/types.h>
#include <signal.h>
#include <errno.h>
#include <sys/wait.h>
#include <sys/time.h>
#include <pwd.h>
#define BUFFER_LEN 1024
#ifdef SIGDET
#if SIGDET == 1
int isSignal = 1; /*Termination detected by signals*/
#endif
#endif
#ifndef SIGDET
int isSignal = 0;
#endif
pid_t foreground = -1;
struct command
{
char * const *argv;
};
/* Error handling function */
void err_syserr(char *fmt, ...)
{
int errnum = errno;
va_list args;
va_start(args, fmt);
vfprintf(stderr, fmt, args);
va_end(args);
if (errnum != 0)
fprintf(stderr, "(%d: %s)\n", errnum, strerror(errnum));
exit(EXIT_FAILURE);
}
/* Helper function that determines the beginning of a string */
int StartsWith(const char *a, const char *b)
{
if(strncmp(a, b, strlen(b)) == 0) return 1;
return 0;
}
/* Helper function that spawns processes */
static int spawn_proc(int in, int out, struct command *cmd)
{
pid_t pid;
if ((pid = fork()) == 0)
{
if (in != 0)
{
if (dup2(in, 0) < 0)
err_syserr("dup2() failed on stdin for %s: ", cmd->argv[0]);
close(in);
}
if (out != 1)
{
if (dup2(out, 1) < 0)
err_syserr("dup2() failed on stdout for %s: ", cmd->argv[0]);
close(out);
}
fprintf(stderr, "%d: executing %s\n", (int)getpid(), cmd->argv[0]);
execvp(cmd->argv[0], cmd->argv);
err_syserr("failed to execute %s: ", cmd->argv[0]);
}
else if (pid < 0) {
err_syserr("fork failed: ");
}
return pid;
}
/* Helper function that forks pipes */
static void fork_pipes(int n, struct command *cmd)
{
int i;
int in = 0;
int fd[2];
for (i = 0; i < n - 1; ++i)
{
if(pipe(fd)==-1) {
err_syserr("Failed creating pipe");
}
spawn_proc(in, fd[1], cmd + i);
close(fd[1]);
in = fd[0];
}
if (dup2(in, 0) < 0) {
err_syserr("dup2() failed on stdin for %s: ", cmd[i].argv[0]);
}
fprintf(stderr, "%d: executing %s\n", (int)getpid(), cmd[i].argv[0]);
execvp(cmd[i].argv[0], cmd[i].argv);
err_syserr("failed to execute %s: ", cmd[i].argv[0]);
}
/*Remove zoombie processes*/
/*Return if background process terminated*/
/*
http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/signal.h.html
*/
void Janitor(int status) {
if(status==SIGCHLD) { /*Child process terminated, stopped, or continued*/
int a = 1;
while(a) {
pid_t pid_my1 = waitpid(-1, &status, WNOHANG);
/*WNOHANG = return immediately if no child has exited*/
/*Wait*/
/*http://linux.die.net/man/2/waitpid*/
if(0<pid_my1) { /*Still things to clean up*/
if(pid_my1!=foreground) { /*Don't stop me since it's the foregound process*/
/*http://linux.die.net/man/3/wait*/
if(WIFSIGNALED(status) || WIFEXITED(status)) { /*Child process terminated*/
printf("\n\n\n\n%d terminated \n\n\n\n\n", pid_my1);
}
}
}
else { /*All work done, for now*/
a = 0;
}
}
}
}
/* helper function that removes spaces from a string */
void RemoveSpaces(char* source) {
char* i = source;
char* j = source;
while(*j != 0) {
*i = *j++;
if(*i != ' ')
i++;
}
*i = 0;
}
/* helper function that determines whether a file exists */
int file_exist (char *filename) {
struct stat buffer;
return (stat (filename, &buffer) == 0);
}
/* Signal handler */
void sighandler(int signo, siginfo_t *si, void *vp) {
int return_value;
return_value = write(2, "Received SIGINT\n", 16);
++return_value; /* use the value to please the compiler */
}
int main(int argc, char *argv[]) {
char line[BUFFER_LEN];
char line2[BUFFER_LEN];
char* argv2[100];
int argc2 = 0;
size_t length;
char *token;
char *token3;
int i=0;
char *tokenstr;
char *search = " ";
int isBackground = 0;
int built_in_command = 0;
int fd[2];
char *printenv[] = { "printenv", 0};
char *sort[] = { "sort", 0 };
char *pager_cmd[] = { "less", 0 };
char *grep[4];
long time;
int status = 0;
int max = 80;
int b;
int pos = 0;
char *tmp;
char *new_str;
int len = 1;
int k;
struct passwd *pw;
const char *homedir;
struct command cmd[3];
struct command cmd2[4];
struct timeval time_start;
struct timeval time_end;
sigset_t my_sig;
pid_t pid_temp;
char * pagerValue;
int ret;
char * pathValue;
char * pathValue2;
int breakloop=0;
struct sigaction sa, osa;
pid_temp = 0; /* To please the compiler */
sa.sa_sigaction = sighandler;
sa.sa_flags = SA_SIGINFO;
sigaction(SIGINT, &sa, &osa);
/* get the PATH environment to find if less is installed */
pathValue = getenv("PATH");
if (! pathValue) {
printf ("'%s' is not set.\n", "PATH");
}
else {
printf ("'%s' is set to %s.\n", "PATH", pathValue);
}
pathValue2 = strdup(pathValue);
token3 = strtok(pathValue2, ":");
ret = 1;
while( token3 != NULL ) {
if((new_str = malloc(strlen(token3)+strlen("/less")+1)) != NULL) {
new_str[0] = '\0';
strcat(new_str,token3);
strcat(new_str,"/less");
if (file_exist (new_str)) {
/* Found less */
ret=0;
breakloop = 1;
}
free(new_str);
if (breakloop) {
break;
}
} else {
printf("malloc failed!\n");
}
token3 = strtok(NULL, ":");
}
free(pathValue2);
while(1) {
i = 0;
Janitor(SIGCHLD);
printf("miniShell>> ");
memset(line, 0, sizeof line); /*Reset*/
if(!fgets(line, BUFFER_LEN, stdin)) {
break;
}
Janitor(SIGCHLD);
strncpy(line2, line, BUFFER_LEN);
RemoveSpaces(line2);
if (StartsWith(line2, "\n")) {
continue;
}
length = strlen(line);
if (line[length - 1] == '\n') {
line[length - 1] = '\0';
}
if(strcmp(line, "exit")==0) {
break;
}
if(StartsWith(line, "cd")) {
built_in_command=1;
if(strstr(line, " ") == NULL) {
pw = getpwuid(getuid());
homedir = pw->pw_dir;
if (chdir(homedir)==-1) { /*Change to home directory*/
perror("Failed changing to homedirectory\n");
}
} else {
tokenstr = strtok(line, search);
tokenstr = strtok(NULL, search);
if (chdir(tokenstr)==-1) {
perror("Failed changing directory\n");
}
}
}
token = strtok(line," ");
while(token!=NULL) {
argv2[i]=token;
token = strtok(NULL," ");
i++;
}
if(StartsWith(line, "checkEnv")) {
built_in_command=1;
pagerValue = getenv ("PAGER");
if (! pagerValue) {
if (ret == 0) {
pager_cmd[0]="less";
} else {
pager_cmd[0]="more";
}
}
else {
pager_cmd[0]=pagerValue;
}
if(i==1) {
cmd[0].argv= printenv;
cmd[1].argv= sort;
cmd[2].argv= pager_cmd;
fork_pipes(3, cmd);
}
else {
for (k = 1; k < i; k++)
{
len += strlen(argv2[k]) + 2;
}
tmp = (char *) malloc(len);
tmp[0] = '\0';
for (k = 1; k < i; k++)
{
pos += sprintf(tmp + pos, "%s%s", (k == 1 ? "" : "|"), argv2[k]);
}
grep[0]="grep";
grep[1]="-E";
grep[2]= tmp;
grep[3]= NULL;
cmd2[0].argv= printenv;
cmd2[1].argv= grep;
cmd2[2].argv= sort;
cmd2[3].argv= pager_cmd;
fork_pipes(4, cmd2);
free(tmp);
}
}
if(0==built_in_command) { /*Not a built in command, so let execute it*/
argv2[i]=NULL;
argc=i;
for(i=0; i<argc2; i++) {
printf("%s\n", argv2[i]);
}
isBackground = 0;
for (b = 0; b<max; b++) {
if ('&'==line[b]) {
isBackground = 1;
}
}
if (isBackground == 1) { /*If backgroundprocess*/
if (pipe(fd)==-1) { /*(two new file descriptors)*/
perror("Failed crating pipe\n");
}
pid_temp = fork();
}
else if (isBackground == 0) { /*If foreground process*/
gettimeofday(&time_start, NULL);
if (1 == isSignal) { /*If using signaldetection*/
sigemptyset(&my_sig); /*empty and initialising a signal set*/
sigaddset(&my_sig, SIGCHLD); /*Adds signal to a signal set (my_sig)*/
/*http://pubs.opengroup.org/onlinepubs/7908799/xsh/sigprocmask.html*/
sigprocmask(SIG_BLOCK, &my_sig, NULL);
}
pid_temp = fork();
foreground = pid_temp; /*Set pid for foreground process*/
}
if (0<pid_temp) {
/*Parent process*/
}
else if (0>pid_temp) {
/*Error*/
}
else {
/*Child process*/
if (1 == isBackground) { /*Backgroundprocess*/
dup2(fd[STDIN_FILENO], STDIN_FILENO);
close(fd[0]);
close(fd[1]);
}
/*http://www.lehman.cuny.edu/cgi-bin/man-cgi?execvp+2*/
if (execvp(argv2[0],argv2) < 0) {
printf("We are sorry to inform you that something went wrong %d \n", errno);
}
}
if (0 == isBackground) { /*Foregroundprocess*/
waitpid(foreground, &status, 0); /*Waiting*/
/*Foregroundprocess terminated*/
gettimeofday(&time_end, NULL);
time = (time_end.tv_sec-time_start.tv_sec)*1000000 + time_end.tv_usec-time_start.tv_usec;
printf("Execution time %ld ms\n", time); /*Print out the execution time*/
if (1 == isSignal) { /*If using signaldetection*/
int a = sigprocmask(SIG_UNBLOCK, &my_sig, NULL);
/*http://man7.org/linux/man-pages/man2/sigprocmask.2.html*/
if (0 == a) {
/*Sigprocmask was successfull*/
}
else {
/*Sigprocmask was not successfull, return=-1*/
}
Janitor(SIGCHLD);
}
}
else if (1==isBackground) {
close(fd[0]);
close(fd[1]);
}
}
built_in_command = 0; /*Reset*/
memset(line, 0, sizeof line); /*Reset*/
}
return (0);
}
|
the_stack_data/117328452.c | #include<stdio.h>
int main()
{
// Variable declaration
int a, b, sum;
// Take two numbers as input from the user
scanf("%d %d", &a, &b);
// Add the numbers and assign the value to some variable so that the
// calculated value can be used else where
sum = a + b;
// Use the calculated value
printf(sum);
return 0;
// End of program
}
|
the_stack_data/764287.c | /*
* $Id: othello.c $
*
* z88dk port of the 'historical' game by Leor Zolman
*
* This adaption shows how to translate a bi-dimensional
* array (not supported by sccz80) into a vector.
*
* Note that this program is recursive and requires
* a lot of stack space, thus it could need to be properly located.
*
* Examples on how to compile in text mode:
* zcc +zx -clib=ansi -lndos -O3 -create-app -zorg=50000 othello.c
* zcc +zx81 -O3 -create-app othello.c
*
* Examples on how to compile in graphics mode:
* zcc +zx -lndos -O3 -create-app -zorg=50000 -DGRAPHICS othello.c
* zcc +ts2068 -clib=ansi -O3 -lndos -create-app -zorg=45000 -DWIDEGRAPHICS -pragma-define:CLIB_DEFAULT_SCREEN_MODE=0x3e -DANSITEXT othello.c
* (16K, WRX HRG mode)
* zcc +zx81 -O3 -subtype=_wrx64 -clib=wrx64ansi -create-app -DSMALLGRAPHICS othello.c
* (32K + WRX HRG, add the '#pragma output hrgpage = 36096' line)
* zcc +zx81 -O3 -subtype=_wrx -clib=wrxansi -create-app -DSMALLGRAPHICS othello.c
*
* Examples on how to compile in redefinded font mode:
* zcc +zx81 -O3 -create-app -DREDEFINED_FONT -DZX81_FONT othello.c
* zcc +zx80 -O3 -create-app -DREDEFINED_FONT -DZX80_FONT othello.c
* zcc +ace -O3 -lndos -create-app -DREDEFINED_FONT othello.c
* zcc +srr -O3 -lndos -create-app -DREDEFINED_FONT othello.c
* zcc +zx -O3 -lndos -create-app -DREDEFINED_FONT othello.c
* zcc +trs80 -subtype=eg2000disk -O3 -lndos -create-app -DREDEFINED_FONT othello.c
*/
/*
OTHELLO -- The Game of Dramatic Reversals
written by Bert Halstead
modified for BDS C by Leor Zolman
This program is a good example of:
a) structured, heirarchical function organization
b) arrays as formal parameters
c) use of the "qsort" library function
Object of the game is for two players to alternate
placing their marker someplace on an 8 by 8 grid, so that
at least one of the opponent's pieces becomes surrounded
by the moving player's peices -- causing the flanked pieces
to flip 'color' and belong to the moving player. After 60
moves have been played (or if no player has a legal move left),
the player with the most of his own pieces on the board wins.
The playing pieces are '*' and '@'. You may choose to play
either '*' or '@' for the first game; thereafter, you and the
computer will alternate going first for each game. Whoever
goes first always plays `*'.
You enter a move as a two digit number, each digit being
from 1 to 8, first digit representing row and second representing
column. For example: if playing '*', your first move might be '46',
meaning 4th row down, 6th position across.
As an alternative to entering a move, one of the following
commands may be typed:
g causes computer to play both sides until game
is over
a causes computer to print out an analysis of
each of your possible moves. A letter from A
to Z will appear at each of your legal move
positions, where A is the machine's opinion
of an excellant move and Z is a real loser.
hn sets handicap. n is 1,2,3, or 4. If n is
positive, gives n free pieces to the computer.
If n is negative, gives YOU the free peices.
f forfeit the current move. This happens
automatically if you have no legal moves.
q quit the current game.
b prints out board again.
s prints out the score, and tells who is winning.
*/
/* z88dk specific opt */
#pragma printf = "%c %u"
#ifdef SCCZ80
void prtbrd(char b[64]) __z88dk_fastcall;
int prtscr(char b[64]) __z88dk_fastcall;
#endif
#define BLACK '*'
#define WHITE 'O'
#define EMPTY '-'
#ifdef __SPECTRUM__
#define G_BLACK 128
#define G_WHITE 129
#define G_EMPTY 130
#endif
#ifdef __TRS80__
#define G_BLACK 128
#define G_WHITE 129
#define G_EMPTY 130
#endif
#ifdef __ACE__
#define G_BLACK 0
#define G_WHITE 1
#define G_EMPTY 2
#endif
#ifdef __SORCERER__
#define G_BLACK 193
#define G_WHITE 194
#define G_EMPTY 195
#endif
#ifdef __SHARPMZ__
#define G_BLACK 0xf1
#define G_WHITE 0xf7
#define G_EMPTY 0xda
#endif
#ifdef ZX81_DKTRONICS
#define G_BLACK 6
#define G_WHITE 14
#define G_EMPTY 62
#endif
#ifndef G_BLACK
#define G_BLACK '*'
#define G_WHITE 'O'
#define G_EMPTY '.'
#endif
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
#include <time.h> /* Needed just for srand seed */
#ifdef WIDEGRAPHICS
#include <graphics.h>
#include <games.h>
#endif
#ifdef GRAPHICS
#include <graphics.h>
#include <games.h>
/* Declare GFX bitmap location for the expanded ZX81 */
//#pragma output hrgpage = 36096
#endif
#ifdef SMALLGRAPHICS
#include <graphics.h>
#include <games.h>
#endif
#ifndef fputc_cons
#define fputc_cons putchar
#endif
#ifndef getk
#define getk getchar
#endif
int handicap;
char selfplay; /* true if computer playing with itself */
/* int h[4][2]; */ /* handicap position table */
int h[8]; /* handicap position table */
char mine, his; /* who has black (*) and white (@) in current game */
char mefirst; /* true if computer goes first in current game */
struct mt {
int x;
int y;
int c;
int s;
};
#if defined (REDEFINED_FONT)
extern char whitepiece[];
extern char blackpiece[];
extern char frame[];
#asm
._whitepiece
defb @11111110
defb @11000011
defb @10001000
defb @10000101
defb @10000100
defb @10000001
defb @11000010
defb @01010101
._blackpiece
defb @11111110
defb @11000011
defb @10110100
defb @10111001
defb @10111100
defb @10111101
defb @11000010
defb @01010101
._frame
defb @11111110
defb @11111111
defb @11111110
defb @11111111
defb @11111110
defb @11111111
defb @11111110
defb @01010101
#endasm
#endif
#ifdef WIDEGRAPHICS
char numbers[] = {
3, 5, 0xE0 , 0xA0 , 0xA0 , 0xA0 , 0xE0,
3, 5, 0x40 , 0x40 , 0x40 , 0x40 , 0x40,
3, 5, 0xE0 , 0x20 , 0xE0 , 0x80 , 0xE0,
3, 5, 0xE0 , 0x20 , 0xE0 , 0x20 , 0xE0,
3, 5, 0xA0 , 0xA0 , 0xE0 , 0x20 , 0x20,
3, 5, 0xE0 , 0x80 , 0xE0 , 0x20 , 0xE0,
3, 5, 0xE0 , 0x80 , 0xE0 , 0xA0 , 0xE0,
3, 5, 0xE0 , 0x20 , 0x20 , 0x20 , 0x20,
3, 5, 0xE0 , 0xA0 , 0xE0 , 0xA0 , 0xE0,
3, 5, 0xE0 , 0xA0 , 0xE0 , 0x20 , 0xE0 };
// Generated by Daniel McKinnon's z88dk Sprite Editor
char frame[] = { 24, 16, 0xAA , 0xAA , 0xAA , 0x00 , 0x00 , 0x01 , 0x80 , 0x00 , 0x00 , 0x00 , 0x00
, 0x01 , 0x80 , 0x00 , 0x00 , 0x00 , 0x00 , 0x01 , 0x80 , 0x00 , 0x00 , 0x00
, 0x00 , 0x01 , 0x80 , 0x00 , 0x00
, 0x00 , 0x00 , 0x01 , 0x80 , 0x00 , 0x00 , 0x00 , 0x00 , 0x01 , 0x80 , 0x00
, 0x00 , 0x00 , 0x00 , 0x01 , 0x80 , 0x00 , 0x00 , 0x55 , 0x55 , 0x55 };
char whitepiece[] = { 24, 16, 0x00 , 0x00 , 0x00 , 0x00 , 0xFF , 0x00 , 0x03 , 0x00 , 0xC0 , 0x0C , 0x00
, 0x30 , 0x10 , 0x0E , 0x08 , 0x20 , 0x01 , 0x84 , 0x20 , 0x00 , 0x44 , 0x40
, 0x00 , 0x22 , 0x40 , 0x00 , 0x02
, 0x20 , 0x00 , 0x04 , 0x20 , 0x00 , 0x04 , 0x10 , 0x00 , 0x08 , 0x0C , 0x00
, 0x30 , 0x03 , 0x00 , 0xC0 , 0x00 , 0xFF , 0x00 , 0x00 , 0x00 , 0x00 };
char blackpiece[] = { 24, 16, 0x00 , 0x00 , 0x00 , 0x00 , 0xFF , 0x00 , 0x03 , 0xFF , 0xC0 , 0x0F , 0xFF
, 0xF0 , 0x1F , 0xF1 , 0xF8 , 0x3F , 0xFC , 0x7C , 0x3F , 0xFF , 0xBC , 0x7F
, 0xFF , 0xDE , 0x7F , 0xFF , 0xFE
, 0x3F , 0xFF , 0xFC , 0x3F , 0xFF , 0xFC , 0x1F , 0xFF , 0xF8 , 0x0F , 0xFF
, 0xF0 , 0x03 , 0xFF , 0xC0 , 0x00 , 0xFF , 0x00 , 0x00 , 0x00 , 0x00 };
#endif
#ifdef GRAPHICS
extern char whitepiece[];
extern char blackpiece[];
extern char frame[];
char numbers[] = {
3, 5, 0xE0 , 0xA0 , 0xA0 , 0xA0 , 0xE0,
3, 5, 0x40 , 0x40 , 0x40 , 0x40 , 0x40,
3, 5, 0xE0 , 0x20 , 0xE0 , 0x80 , 0xE0,
3, 5, 0xE0 , 0x20 , 0xE0 , 0x20 , 0xE0,
3, 5, 0xA0 , 0xA0 , 0xE0 , 0x20 , 0x20,
3, 5, 0xE0 , 0x80 , 0xE0 , 0x20 , 0xE0,
3, 5, 0xE0 , 0x80 , 0xE0 , 0xA0 , 0xE0,
3, 5, 0xE0 , 0x20 , 0x20 , 0x20 , 0x20,
3, 5, 0xE0 , 0xA0 , 0xE0 , 0xA0 , 0xE0,
3, 5, 0xE0 , 0xA0 , 0xE0 , 0x20 , 0xE0 };
#asm
._frame
defb 16,16
defb @10101010, @10101010
defb @00000000, @00000001
defb @10000000, @00000000
defb @00000000, @00000001
defb @10000000, @00000000
defb @00000000, @00000001
defb @10000000, @00000000
defb @00000000, @00000001
defb @10000000, @00000000
defb @00000000, @00000001
defb @10000000, @00000000
defb @00000000, @00000001
defb @10000000, @00000000
defb @00000000, @00000001
defb @10000000, @00000000
defb @01010101, @01010101
._whitepiece
defb 16,16
defb @00000000, @00000000
defb @00000000, @00000000
defb @00000011, @11000000
defb @00001100, @00110000
defb @00010000, @11001000
defb @00010000, @00101000
defb @00100000, @00010100
defb @00100000, @00010100
defb @00100000, @00000100
defb @00100000, @00000100
defb @00010000, @00001000
defb @00010000, @00001000
defb @00001100, @00110000
defb @00000011, @11000000
defb @00000000, @00000000
defb @00000000, @00000000
._blackpiece
defb 16,16
defb @00000000, @00000000
defb @00000000, @00000000
defb @00000011, @11000000
defb @00001111, @11110000
defb @00011111, @00111000
defb @00011111, @11011000
defb @00111111, @11101100
defb @00111111, @11101100
defb @00111111, @11111100
defb @00111111, @11111100
defb @00011111, @11111000
defb @00011111, @11111000
defb @00001111, @11110000
defb @00000011, @11000000
defb @00000000, @00000000
defb @00000000, @00000000
#endasm
#endif
#ifdef SMALLGRAPHICS
extern char whitepiece[];
extern char blackpiece[];
extern char frame[];
char numbers[] = {
3, 5, 0xE0 , 0xA0 , 0xA0 , 0xA0 , 0xE0,
3, 5, 0x40 , 0x40 , 0x40 , 0x40 , 0x40,
3, 5, 0xE0 , 0x20 , 0xE0 , 0x80 , 0xE0,
3, 5, 0xE0 , 0x20 , 0xE0 , 0x20 , 0xE0,
3, 5, 0xA0 , 0xA0 , 0xE0 , 0x20 , 0x20,
3, 5, 0xE0 , 0x80 , 0xE0 , 0x20 , 0xE0,
3, 5, 0xE0 , 0x80 , 0xE0 , 0xA0 , 0xE0,
3, 5, 0xE0 , 0x20 , 0x20 , 0x20 , 0x20,
3, 5, 0xE0 , 0xA0 , 0xE0 , 0xA0 , 0xE0,
3, 5, 0xE0 , 0xA0 , 0xE0 , 0x20 , 0xE0 };
#asm
._frame
defb 6,5
defb @00000100
defb @00000000
defb @00000100
defb @00000000
defb @01010100
._whitepiece
defb 4,4
defb @01100000
defb @10010000
defb @10010000
defb @01100000
._blackpiece
defb 4,4
defb @01100000
defb @11110000
defb @11110000
defb @01100000
#endasm
#endif
/*
void shift_right()
{
printf("%c[%uC",27,17);
}
*/
char skipbl()
{
char c;
while ((c = toupper(getchar())) == ' ' || c=='\t');
//fputc_cons(c);
return c;
}
int chkmv1( char b[64], char p, int x, int y, int m, int n )
{
int k;
k=0;
while ((x += m) >= 0 && x < 8 && (y += n) >= 0 && y<8)
{
if (b[x*8+y]==EMPTY) return 0;
if (b[x*8+y]== p ) return k;
if (x==0 || x==7 || y==0 || y==7)
k += 10;
else k++;
}
return 0;
}
int chkmov( char b[64], char p, int x, int y )
{
if (b[x*8+y] != EMPTY) return 0;
return chkmv1(b,p,x,y,0,1) + chkmv1(b,p,x,y,1,0) +
chkmv1(b,p,x,y,0,-1)+ chkmv1(b,p,x,y,-1,0)+
chkmv1(b,p,x,y,1,1) + chkmv1(b,p,x,y,1,-1)+
chkmv1(b,p,x,y,-1,1)+ chkmv1(b,p,x,y,-1,-1);
}
int chkmvs( char b[64], char p )
{
int i,j,k;
k=0;
for (i=0; i<8; i++) for (j=0; j<8; j++)
k += chkmov(b,p,i,j);
return k;
}
void cpybrd(char a[64], char b[64])
{
memcpy(a,b,64);
}
int cntbrd(char b[64], char p)
{
int i,k;
i=64;k=0;
while (i--)
if (b[i] == p) ++k;
return (k);
}
void clrbrd(char b[64])
{
int i,j;
for (i=0; i<8; i++)
for (j=0; j<8; j++)
b[i*8+j]= EMPTY;
b[27] = b[36] = BLACK;
b[28] = b[35] = WHITE;
}
void prtbrd(char b[64])
{
int i,j;
#define TEXT 1
#ifdef GRAPHICS
#undef TEXT
clg();
printf("%c",12);
for (i=0; i<8; i++) {
putsprite(spr_or,127+i*16,2,&numbers[(i+1)*7]);
putsprite(spr_or,112,16+i*16,&numbers[(i+1)*7]);
for (j=0; j<8; j++) {
putsprite(spr_or,120+i*16,10+j*16,frame);
switch(b[i*8+j]) {
case BLACK:
putsprite(spr_or,120+j*16,10+i*16,blackpiece);
break;
case WHITE:
putsprite(spr_or,120+j*16,10+i*16,whitepiece);
break;
}
}
}
#endif
#ifdef WIDEGRAPHICS
#undef TEXT
clg();
printf("%c",12);
for (i=0; i<8; i++) {
putsprite(spr_or,227+i*27,2,&numbers[(i+1)*7]);
putsprite(spr_or,212,15+i*17,&numbers[(i+1)*7]);
for (j=0; j<8; j++) {
putsprite(spr_or,220+i*27,10+j*17,frame);
switch(b[i*8+j]) {
case BLACK:
putsprite(spr_or,220+j*27,10+i*17,blackpiece);
break;
case WHITE:
putsprite(spr_or,220+j*27,10+i*17,whitepiece);
break;
}
}
}
#endif
#ifdef SMALLGRAPHICS
#undef TEXT
clg();
printf ("%c",12);
for (i=0; i<8; i++) {
putsprite(spr_or,157+i*7,0,&numbers[(i+1)*7]);
putsprite(spr_or,151,6+i*7,&numbers[(i+1)*7]);
for (j=0; j<8; j++) {
putsprite(spr_or,155+i*7,7+j*7,frame);
switch(b[i*8+j]) {
case BLACK:
putsprite(spr_or,155+j*7,6+i*7,blackpiece);
break;
case WHITE:
putsprite(spr_or,155+j*7,6+i*7,whitepiece);
break;
}
}
}
#endif
#ifdef TEXT
#if defined (REDEFINED_FONT) || defined (ZX81_FONT) || defined (ZX80_FONT)
printf(" 12345678\n");
for (i=0; i<8; i++) {
printf(" %u",i+1);
for (j=0; j<8; j++) {
#if defined (ZX80_FONT) || defined (ZX81_FONT) || defined (ZX81_DKTRONICS)
zx_asciimode(0);
switch(b[i*8+j]) {
#ifdef ZX81_DKTRONICS
case BLACK:
putchar (G_BLACK);
break;
case WHITE:
putchar (G_WHITE);
break;
default:
putchar (G_EMPTY);
break;
#else
#ifdef ZX80_FONT
case BLACK:
putchar (148);
break;
case WHITE:
putchar (180);
break;
default:
putchar (128+9*((i+j)&1));
break;
#else
case BLACK:
putchar (151);
break;
case WHITE:
putchar (180);
break;
default:
putchar (128+8*((i+j)&1));
break;
#endif
#endif
}
zx_asciimode(1);
#else
switch(b[i*8+j]) {
case BLACK:
putchar (G_BLACK);
break;
case WHITE:
putchar (G_WHITE);
break;
default:
putchar (G_EMPTY);
break;
}
#endif
}
putchar('\n');
}
#else
printf(" 1 2 3 4 5 6 7 8\n");
for (i=0; i<8; i++) {
printf(" %u",i+1);
for (j=0; j<8; j++) {
//#ifdef ANSITEXT
//#endif
putchar(' ');
putchar(b[i*8+j]);
}
putchar('\n');
}
#endif
#endif
putchar('\n');
}
int prtscr(char b[64])
{
int i,j;
printf("%u-%u",i = cntbrd(b,his), j=cntbrd(b,mine));
return i-j;
}
char getmov(int *i, int *j)
{
char a,c;
//int n;
//char *p;
/* char skipbl(); */
//shift_right();
if (selfplay == 'G') {
if (getk()==0) return 'G';
selfplay = ' ';
getchar();
}
printf("Move: ");
while(1) switch (c=skipbl()) {
case '\n': printf("Move? "); continue;
case 'G': if ((c = skipbl()) != '\n')
goto flush;
selfplay='G';
return 'G';
case 'B': case 'S': case 'Q':
case 'F': case 'A':
a=c;
if (( c = skipbl()) != '\n') goto flush;
return a;
case 'H': if ((a=c=skipbl()) == EMPTY)
c=getchar();
if (c<'1' || c>'4' || skipbl() !='\n')
goto flush;
*i = a==EMPTY? -(c-'0') : (c-'0');
return 'H';
case 4: return c;
default: if (c<'1' || c>'8') goto flush;
*i = c-'1';
c = skipbl();
if (c<'1' || c>'8') goto flush;
*j = c- '1';
if ((c=skipbl()) == '\n') return 'M';
flush: while (c != '\n' && c != 4)
c=getchar();
if (c==4) return c;
printf (" Huh?? ");
}
}
char ask()
{
char a,c;
printf ("Another game? ");
a=skipbl();
while (c != '\n' && c != 4) c= getchar();
return a;
}
void putmv1(char b[64], char p,int x, int y, int m, int n)
{
while ((x += m) >= 0 && x<8 && (y += n)>=0 && y<8) {
if (b[x*8+y] == EMPTY || b[x*8+y] == p) return;
b[x*8+y] = p;
}
}
void putmov(char b[64], char p, int x, int y)
{
int i,j;
b[x*8+y] = p;
for (i= -1; i<=1; i++) for (j= -1; j<=1; j++) {
if ((i != 0 || j!=0)&&chkmv1(b,p,x,y,i,j)>0)
putmv1(b,p,x,y,i,j);
}
}
char notak2(char b[64], char p,char o,char e, int x, int y,int m,int n)
{
x += m; y +=n;
if (x>=0 && x<=7 && y>=0 && y<=7)
while(b[x*8+y] == 0) {
x += m; y+=n;
if (x<0 || x>7 || y<0 || y>7 || b[x*8+y]==e)
return o;
}
while (x>=0 && x<=7 && y>=0 && y<=7 && b[x*8+y]==p)
{ x +=m; y+=n; }
if (x<0 || x>7 || y<0 || y>7) return p;
return b[x*8+y];
}
char notak1(char b[64], char p,char o,char e,int x,int y,int m,int n)
{
int c1,c2;
c1 = notak2(b,p,o,e,x,y,m,n);
c2 = notak2(b,p,o,e,x,y,-m,-n);
return !(c1==o && c2==e || c1==e && c2==o);
}
char notake(char b[64],char p,char o,char e,int x,int y)
{
return notak1(b,p,o,e,x,y,0,1)&&
notak1(b,p,o,e,x,y,1,1)&&
notak1(b,p,o,e,x,y,1,0)&&
notak1(b,p,o,e,x,y,1,-1);
}
char s_move(char b[64], char p, char o, char e, int i, int j)
{
char a[64];
int ok,s,k,l,side,oside;
int c,dkl;
cpybrd(a,b);
putmov(a,p,i,j);
side = 0;
if (i==0 || i==7) side++;
if (j==0 || j==7) side++;
s = 0;
ok = 0;
if (side==2 || notake(b,p,o,e,i,j)) ok++;
oside = 0;
for (k=0; k<8; k++) for(l=0; l<8; l++)
{
c=chkmov(a,o,k,l);
if (c==0) continue;
dkl = 1;
if (k==0 || k==7) { dkl+=2; oside|=4;}
if (l==0 || l==7) {dkl+=2; oside|=4; }
if (dkl==5) {dkl = 10; oside |= 16; }
else if (!notake(a,o,p,e,k,l))
continue;
oside |= 1;
s -= dkl;
if (c>=10) { s -= 4; oside |= 8; }
}
if (s< -oside) s= -oside;
if (side>0) return s+side-7+10*ok;
if (i==1 || i==6) {s--; side++;}
if (j==1 || j==6) {s--; side++;}
if (side>0) return s;
if (i==2 || i==5) s++;
if (j==2 || j==5) s++;
return s;
}
int fillmt(char b[64], char p, char o, char e, struct mt t[64])
{
int i,j,k;
k = 0;
for (i=0; i<8; i++) for(j=0; j<8; j++)
if (t[k].c = chkmov(b,p,i,j)) {
t[k].x =i;
t[k].y =j;
t[k].s = s_move(b,p,o,e,i,j);
++k;
}
return k;
}
void analyze(char b[64], char p, char o, char e)
{
struct mt t[64];
char a[64];
int i,k,c;
k = fillmt(b,p,o,e,t);
cpybrd(a,b);
for (i=0; i<k; i++)
a[t[i].x*8+t[i].y] = ((c = 'F' - t[i].s) <= 'Z')?c:'Z';
prtbrd(a);
}
int cmpmov(struct mt *a,struct mt *b)
{
if ((*a).s > (*b).s) return -1;
if ((*a).s < (*b).s) return 1;
if ((*a).c > (*b).c) return -1;
if ((*a).c < (*b).c) return 1;
return 0;
}
int my_mov(char b[64], char p,char o,char e,int *m,int *n)
{
struct mt t[64];
int i,k;
k = fillmt(b,p,o,e,t);
if (!k) return 0;
qsort (t, k, sizeof(struct mt), cmpmov);
for (i=1; i<k; i++)
if (t[i].s != t[0].s || t[i].c != t[0].c)
break;
k = rand() % i;
*m = t[k].x;
*n = t[k].y;
return 1;
}
int game(char b[64],int n)
{
char c;
int ff;
int i,j;
handicap = 0;
selfplay = ' ';
ff=0;
if (mefirst) {
mine = BLACK; his = WHITE;
printf("I go first:\n");
}
else {
mine = WHITE; his = BLACK;
printf("You go first:\n");
}
while(1) {
if (cntbrd(b,EMPTY)==0) return 'D';
if (cntbrd(b,EMPTY)==60 && mine == BLACK) goto Istart;
if (chkmvs(b,his)==0) {
printf(!mefirst ? "Forfeit" : " ...Forfeit\n");
ff |= 1;
}
else switch (c = getmov(&i,&j)) {
case 'B': prtbrd(b); continue;
case 'S': i= prtscr(b);
if (i>0) printf(" You're winning\n");
else if (i<0)printf(" You're losing!\n");
else putchar('\n');
continue;
case 'Q': case 4: return c;
case 'H': if (n>(unsigned int)(handicap)+4)
printf("Illegal!\n");
else for (j=0; i!=0; j++) {
b[h[j*2]*8+h[j*2+2]]= i>0?BLACK:WHITE;
handicap += i>0 ? 1 : -1;
++n;
i += i>0 ? -1 : 1;
}
prtbrd(b); continue;
case 'A': analyze(b,his,mine,EMPTY);
continue;
case 'G': my_mov(b,his,mine,EMPTY,&i,&j);
case 'M': if (chkmov(b,his,i,j)>0) {
printf(!mefirst ? "%u-%u" : " ...%u-%u\n",
i+1,j+1);
putmov(b,his,i,j);
}
else {
printf("Illegal!\n");
continue;
}
break;
case 'F': if (n>(unsigned int)(handicap)+4) {
printf ("Illegal!\n");
continue;
}
else printf(!mefirst ? "Forfeit" :
" ...Forfeit\n");
}
Istart: if (cntbrd(b,EMPTY) == 0) return 'D';
if (chkmvs(b,mine)==0) {
printf(!mefirst ? "...Forfeit\n": "Forfeit...\n");
ff |=2;
}
else {
my_mov(b,mine,his,EMPTY,&i,&j);
printf(!mefirst ? "...%u-%u\n" : "%u-%u...\n",
i+1,j+1);
putmov(b,mine,i,j);
++n;
}
if (ff==3 || n>64) return 'D';
if (!(ff & 1)) prtbrd(b);
ff = 0;
}
}
int main()
{
char b[64];
int i;
/*
h[0][0] = h[0][1] = h[2][0] = h[3][1] = 0;
h[1][0] = h[1][1] = h[2][1] = h[3][0] = 7;
*/
h[0] = h[1] = h[4] = h[7] = 0;
h[2] = h[3] = h[5] = h[6] = 7;
#ifdef REDEFINED_FONT
#ifdef __SPECTRUM__
/* set console driver for 32 columns mode */
printf("%c%c",1,32);
/* INK 7 */
printf("%c7",16);
/* PAPER 0 */
printf("%c0",17);
/* Copy graphics in UDG area */
memcpy(65368, whitepiece,24);
zx_border(0);
#endif
#ifdef __ACE__
memcpy(0x2c00, whitepiece,24);
#endif
#ifdef __SORCERER__
memcpy(0xfe08, whitepiece,24);
#endif
#ifdef __TRS80__
memcpy(0xf400, whitepiece,24);
#endif
#endif
#ifdef ANSITEXT
printf("%c\nWelcome to the %c[7m OTHELLO %c[27m program!\n",12,27,27);
printf("\nNote: %c[4m BLACK ALWAYS GOES FIRST\n %c[24m ...Good luck!!!\n\n\n",27,27);
#else
printf("%c\nWelcome to the OTHELLO program!\n",12);
printf("\nNote: BLACK ALWAYS GOES FIRST\n ...Good luck!!!\n\n\n");
#endif
printf("Do you want to go first? ");
if (toupper(getchar()) == 'Y')
mefirst = 0;
else
mefirst = 1;
#ifdef ZX81_DKTRONICS
#asm
ld a,$20
ld i,a
#endasm
#endif
//srand( (unsigned)clock() );
do {
clrbrd(b);
printf("\n");
prtbrd(b);
i = game(b,4);
mefirst = !mefirst;
if (i==4) break;
if (i=='Q') continue;
printf("\n");
i = prtscr(b);
if (i>0) printf(" You won by %u\n",i);
else if (i<0) printf(" You lost by %u\n",-i);
else printf(" A draw\n");
} while (ask()=='Y');
}
|
the_stack_data/225144589.c | #include <stdio.h>
#include <linux/input.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#define HELP_TEXT "keylistend v0.1.0\n" \
"Simple daemon to listen to event devices and react to keycodes with UT app launches.\n" \
"(C) 2021 nift4\n" \
"\nUsage:\n" \
"First argument: path to event device\n" \
"All following arguments should be pairs: keycode and UT app id to launch.\n\n" \
"Example: ./keylistend /dev/input/event3 87 dialer-app"
char err[200];
int fd = 0;
#ifdef NOUT
#define RUNTIME "sh"
#else
#define RUNTIME "ubuntu-app-launch"
#endif
int fail(int returncode, int ignored) {
printf("keylistend: %s\n", err);
if (fd > 0) close(fd);
return returncode;
}
int main(int argc, char* argv[]) {
if (argc == 2 && strcmp(argv[1], "--help") == 0) {
printf("%s\n", HELP_TEXT);
return 0;
}
if ((argc-1) % 2 == 0 || argc < 4)
return fail(1, sprintf(err, "got %i arguments, excepted multiple of 2 plus one", argc-1));
char cmd[(argc-2) / 2][4096];
int icode[(argc-2) / 2];
for (int i = 0; i < (argc-2) / 2; i++) {
icode[i] = atoi(argv[2 + (i * 2)]);
if (icode[i] < 1)
return fail(2, sprintf(err, "excepted non-null positive number, got %s", argv[2 + (i * 2)]));
strncat(cmd[i], argv[3 + (i * 2)], 4096);
}
if ((fd = open(argv[1], O_RDONLY)) < 0)
return fail(3, sprintf(err, "error opening device"));
struct input_event ev;
unsigned int size;
printf("keylistend: Listening on %s for codes:\n", argv[1]);
for (int i = 0; i < (argc-2) / 2; i++)
printf("%i\n", icode[i]);
while (1) {
size = read(fd, &ev, sizeof(struct input_event));
if (size < sizeof(struct input_event))
return fail(4, sprintf(err, "error reading from device"));
#ifdef SCANEVENTS
printf("Event: time %ld.%06ld, ", ev.time.tv_sec, ev.time.tv_usec);
printf("type: %i, code: %i, value: %i\n", ev.type, ev.code, ev.value);
#endif
if (ev.value != 1)
continue;
for (int i = 0; i < (argc-2) / 2; i++) {
if (ev.code == icode[i] && fork() == 0) {
execlp(RUNTIME, RUNTIME, cmd[i], (char*)NULL);
return fail(5, sprintf(err, "Warning: execlp() returned %i", errno));
}
}
}
}
|
the_stack_data/26701121.c | #include <asm-generic/socket.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <stdbool.h>
#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
#include <stdint.h>
#define CONNECTION_LIMIT 5
typedef struct connection_t {
int client_fd, proxy_fd;
} connection_t;
void *handle_client(void *connection_ptr)
{
connection_t const connection = *(connection_t*) connection_ptr;
uint8_t buf[1024];
while (true) {
ssize_t length = read(connection.client_fd, buf, sizeof buf);
if (length <= 0) break;
if (write(connection.proxy_fd, buf, length) <= 0) break;
}
close(connection.proxy_fd);
close(connection.client_fd);
return NULL;
}
void *handle_proxy(void *connection_ptr)
{
connection_t const connection = *(connection_t*) connection_ptr;
uint8_t buf[1024];
while (true) {
ssize_t length = read(connection.proxy_fd, buf, sizeof buf);
if (length <= 0) break;
if (write(connection.client_fd, buf, length) <= 0) break;
}
close(connection.proxy_fd);
close(connection.client_fd);
return NULL;
}
void *handle_connection(void *client_fd_ptr)
{
int const client_fd = *(int*) client_fd_ptr;
int const proxy_fd = socket(AF_INET, SOCK_STREAM, 0);
if (proxy_fd == -1) {
close(client_fd);
close(proxy_fd);
return NULL;
}
struct sockaddr_in server_address = {
.sin_family = AF_INET,
.sin_port = htons(25565)
};
// testing ip
if (inet_pton(AF_INET, "192.168.1.40", &server_address.sin_addr) <= 0) {
close(client_fd);
close(proxy_fd);
return NULL;
}
if (connect(proxy_fd, (struct sockaddr*) &server_address, sizeof server_address) != 0) {
close(client_fd);
close(proxy_fd);
return NULL;
}
connection_t connection = {
.client_fd = client_fd,
.proxy_fd = proxy_fd
};
pthread_t client_thread, proxy_thread;
pthread_create(&client_thread, NULL, handle_client, &connection);
pthread_create(&proxy_thread, NULL, handle_proxy, &connection);
pthread_join(client_thread, NULL);
pthread_join(proxy_thread, NULL);
close(client_fd);
close(proxy_fd);
return NULL;
}
int main(int argc, char *argv[])
{
int const server_fd = socket(AF_INET, SOCK_STREAM, 0);
if (server_fd == -1) {
perror("socket failed\n");
return EXIT_FAILURE;
}
int opt = 1;
if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof opt) == -1) {
perror("setsockopt failed\n");
return EXIT_FAILURE;
}
struct sockaddr_in server_addr = {
.sin_family = AF_INET,
.sin_addr = {
.s_addr = INADDR_ANY
},
.sin_port = htons(25565)
};
if (bind(server_fd, (struct sockaddr*) &server_addr, sizeof server_addr) == -1) {
perror("bind failed\n");
return EXIT_FAILURE;
}
if (listen(server_fd, CONNECTION_LIMIT) == -1) {
perror("listen failed\n");
return EXIT_FAILURE;
}
while (true) {
int client_fd = accept(server_fd, NULL, NULL);
if (client_fd == -1) {
close(client_fd);
continue;
}
pthread_t thread;
pthread_create(&thread, NULL, handle_connection, &client_fd);
}
return EXIT_SUCCESS;
}
|
the_stack_data/323423.c | #include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <time.h>
void stop(int sig){
printf("CHILD : Stopped by parent with signal %d\n",sig);
exit(5);
}
int main(void)
{
signal(SIGUSR1, stop);
int h,m,s;
printf("\n\n*******Format du compte a rebours : HH : MM : SS*******\n\n");
printf("Entrer le temps du compte a rebours : \n");
printf("Heures : ");
scanf("%d", &h);
printf("\nMinutes : ");
scanf("%d", &m);
printf("\nSecondes : ");
scanf("%d", &s);
while(h>=0)
{
while(m>=0)
{
while(s>=0)
{
system("clear");
printf("\n%02d : %02d : %02d\n",h,m,s);
sleep(1);
s--;
}
s=59;
m--;
}
m=59;
h--;
}
return(0);
}
|
the_stack_data/144137.c | #include <stdio.h>
void printA() {
for (int i = 0; i < 7; i++)
printf(" ");
printf("A\n");
}
void printB() {
for (int i = 0; i < 6; i++)
printf(" ");
printf("B B\n");
}
void printC() {
for (int i = 0; i < 5; i++)
printf(" ");
printf("C C\n");
}
void printD() {
for (int i = 0; i < 4; i++)
printf(" ");
printf("D D\n");
}
void printE() {
for (int i = 0; i < 3; i++)
printf(" ");
printf("E E\n");
}
int main(void) {
printA();
printB();
printC();
printD();
printE();
printD();
printC();
printB();
printA();
return 0;
} |
the_stack_data/52642.c | /*
*
* refclock_hopfser.c
* - clock driver for hopf serial boards (GPS or DCF77)
*
* Date: 30.03.2000 Revision: 01.10
*
* latest source and further information can be found at:
* http://www.ATLSoft.de/ntp
*
*/
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#if defined(SYS_WINNT)
#undef close
#define close closesocket
#endif
#if defined(REFCLOCK) && (defined(CLOCK_HOPF_SERIAL))
#include "ntpd.h"
#include "ntp_io.h"
#include "ntp_control.h"
#include "ntp_refclock.h"
#include "ntp_unixtime.h"
#include "ntp_stdlib.h"
#if defined HAVE_SYS_MODEM_H
# include <sys/modem.h>
# define TIOCMSET MCSETA
# define TIOCMGET MCGETA
# define TIOCM_RTS MRTS
#endif
#ifdef HAVE_TERMIOS_H
# ifdef TERMIOS_NEEDS__SVID3
# define _SVID3
# endif
# include <termios.h>
# ifdef TERMIOS_NEEDS__SVID3
# undef _SVID3
# endif
#endif
#ifdef HAVE_SYS_IOCTL_H
# include <sys/ioctl.h>
#endif
/*
* clock definitions
*/
#define DESCRIPTION "hopf Elektronik serial clock" /* Long name */
#define PRECISION (-10) /* precision assumed (about 1 ms) */
#define REFID "hopf\0" /* reference ID */
/*
* I/O definitions
*/
#define DEVICE "/dev/hopfclock%d" /* device name and unit */
#define SPEED232 B9600 /* uart speed (9600 baud) */
#define STX 0x02
#define ETX 0x03
#define CR 0x0c
#define LF 0x0a
/* parse states */
#define REC_QUEUE_EMPTY 0
#define REC_QUEUE_FULL 1
#define HOPF_OPMODE 0x0C /* operation mode mask */
#define HOPF_INVALID 0x00 /* no time code available */
#define HOPF_INTERNAL 0x04 /* internal clock */
#define HOPF_RADIO 0x08 /* radio clock */
#define HOPF_RADIOHP 0x0C /* high precision radio clock */
/*
* hopfclock unit control structure.
*/
struct hopfclock_unit {
l_fp laststamp; /* last receive timestamp */
short unit; /* NTP refclock unit number */
u_long polled; /* flag to detect noreplies */
char leap_status; /* leap second flag */
int rpt_next;
};
/*
* Function prototypes
*/
static int hopfserial_start P((int, struct peer *));
static void hopfserial_shutdown P((int, struct peer *));
static void hopfserial_receive P((struct recvbuf *));
static void hopfserial_poll P((int, struct peer *));
/* static void hopfserial_io P((struct recvbuf *)); */
/*
* Transfer vector
*/
struct refclock refclock_hopfser = {
hopfserial_start, /* start up driver */
hopfserial_shutdown, /* shut down driver */
hopfserial_poll, /* transmit poll message */
noentry, /* not used */
noentry, /* initialize driver (not used) */
noentry, /* not used */
NOFLAGS /* not used */
};
/*
* hopfserial_start - open the devices and initialize data for processing
*/
static int
hopfserial_start (
int unit,
struct peer *peer
)
{
register struct hopfclock_unit *up;
struct refclockproc *pp;
int fd;
char gpsdev[20];
#ifdef SYS_WINNT
(void) sprintf(gpsdev, "COM%d:", unit);
#else
(void) sprintf(gpsdev, DEVICE, unit);
#endif
/* LDISC_STD, LDISC_RAW
* Open serial port. Use CLK line discipline, if available.
*/
fd = refclock_open(gpsdev, SPEED232, LDISC_CLK);
if (fd <= 0) {
#ifdef DEBUG
printf("hopfSerialClock(%d) start: open %s failed\n", unit, gpsdev);
#endif
return 0;
}
msyslog(LOG_NOTICE, "hopfSerialClock(%d) fd: %d dev: %s", unit, fd,
gpsdev);
/*
* Allocate and initialize unit structure
*/
up = (struct hopfclock_unit *) emalloc(sizeof(struct hopfclock_unit));
if (!(up)) {
msyslog(LOG_ERR, "hopfSerialClock(%d) emalloc: %m",unit);
#ifdef DEBUG
printf("hopfSerialClock(%d) emalloc\n",unit);
#endif
(void) close(fd);
return (0);
}
memset((char *)up, 0, sizeof(struct hopfclock_unit));
pp = peer->procptr;
pp->unitptr = (caddr_t)up;
pp->io.clock_recv = hopfserial_receive;
pp->io.srcclock = (caddr_t)peer;
pp->io.datalen = 0;
pp->io.fd = fd;
if (!io_addclock(&pp->io)) {
#ifdef DEBUG
printf("hopfSerialClock(%d) io_addclock\n",unit);
#endif
(void) close(fd);
free(up);
return (0);
}
/*
* Initialize miscellaneous variables
*/
pp->clockdesc = DESCRIPTION;
peer->precision = PRECISION;
peer->burst = NSTAGE;
memcpy((char *)&pp->refid, REFID, 4);
up->leap_status = 0;
up->unit = (short) unit;
return (1);
}
/*
* hopfserial_shutdown - shut down the clock
*/
static void
hopfserial_shutdown (
int unit,
struct peer *peer
)
{
register struct hopfclock_unit *up;
struct refclockproc *pp;
pp = peer->procptr;
up = (struct hopfclock_unit *)pp->unitptr;
io_closeclock(&pp->io);
free(up);
}
/*
* hopfserial_receive - receive data from the serial interface
*/
static void
hopfserial_receive (
struct recvbuf *rbufp
)
{
struct hopfclock_unit *up;
struct refclockproc *pp;
struct peer *peer;
int synch; /* synchhronization indicator */
int DoW; /* Dow */
int day, month; /* ddd conversion */
/*
* Initialize pointers and read the timecode and timestamp.
*/
peer = (struct peer *)rbufp->recv_srcclock;
pp = peer->procptr;
up = (struct hopfclock_unit *)pp->unitptr;
if (up->rpt_next == 0 )
return;
up->rpt_next = 0; /* wait until next poll interval occur */
pp->lencode = (u_short)refclock_gtlin(rbufp, pp->a_lastcode, BMAX, &pp->lastrec);
if (pp->lencode == 0)
return;
sscanf(pp->a_lastcode,
#if 1
"%1x%1x%2d%2d%2d%2d%2d%2d", /* ...cr,lf */
#else
"%*c%1x%1x%2d%2d%2d%2d%2d%2d", /* stx...cr,lf,etx */
#endif
&synch,
&DoW,
&pp->hour,
&pp->minute,
&pp->second,
&day,
&month,
&pp->year);
/*
Validate received values at least enough to prevent internal
array-bounds problems, etc.
*/
if((pp->hour < 0) || (pp->hour > 23) ||
(pp->minute < 0) || (pp->minute > 59) ||
(pp->second < 0) || (pp->second > 60) /*Allow for leap seconds.*/ ||
(day < 1) || (day > 31) ||
(month < 1) || (month > 12) ||
(pp->year < 0) || (pp->year > 99)) {
/* Data out of range. */
refclock_report(peer, CEVNT_BADREPLY);
return;
}
/*
some preparations
*/
pp->day = ymd2yd(pp->year,month,day);
pp->leap=0;
/* Year-2000 check! */
/* wrap 2-digit date into 4-digit */
if(pp->year < YEAR_PIVOT) { pp->year += 100; } /* < 98 */
pp->year += 1900;
/* preparation for timecode ntpq rl command ! */
#if 0
wsprintf(pp->a_lastcode,
"STATUS: %1X%1X, DATE: %02d.%02d.%04d TIME: %02d:%02d:%02d",
synch,
DoW,
day,
month,
pp->year,
pp->hour,
pp->minute,
pp->second);
pp->lencode = strlen(pp->a_lastcode);
if ((synch && 0xc) == 0 ){ /* time ok? */
refclock_report(peer, CEVNT_BADTIME);
pp->leap = LEAP_NOTINSYNC;
return;
}
#endif
/*
* If clock has no valid status then report error and exit
*/
if ((synch & HOPF_OPMODE) == HOPF_INVALID ){ /* time ok? */
refclock_report(peer, CEVNT_BADTIME);
pp->leap = LEAP_NOTINSYNC;
return;
}
/*
* Test if time is running on internal quarz
* if CLK_FLAG1 is set, sychronize even if no radio operation
*/
if ((synch & HOPF_OPMODE) == HOPF_INTERNAL){
if ((pp->sloppyclockflag & CLK_FLAG1) == 0) {
refclock_report(peer, CEVNT_BADTIME);
pp->leap = LEAP_NOTINSYNC;
return;
}
}
if (!refclock_process(pp)) {
refclock_report(peer, CEVNT_BADTIME);
return;
}
pp->lastref = pp->lastrec;
refclock_receive(peer);
#if 0
msyslog(LOG_ERR, " D:%x D:%d D:%d",synch,pp->minute,pp->second);
#endif
record_clock_stats(&peer->srcadr, pp->a_lastcode);
return;
}
/*
* hopfserial_poll - called by the transmit procedure
*
*/
static void
hopfserial_poll (
int unit,
struct peer *peer
)
{
register struct hopfclock_unit *up;
struct refclockproc *pp;
pp = peer->procptr;
up = (struct hopfclock_unit *)pp->unitptr;
pp->polls++;
up->rpt_next = 1;
#if 0
record_clock_stats(&peer->srcadr, pp->a_lastcode);
#endif
return;
}
#else
int refclock_hopfser_bs;
#endif /* REFCLOCK */
|
the_stack_data/161081388.c | #include <stdio.h>
int main()
{
int a,b,sump,sumn;
printf("Enter the number of elements\n");
scanf("%d",&a);
int c[a];sump=sumn=0;
printf("Enter the elements\n");
for(b=0;b<a;b++){
scanf("%d",&c[b]);
}
for(b=0;b<a;b++){
if(c[b]>0){
sump+=c[b];}
else{
sumn+=c[b];
}
}
printf("Difference in magnitude of all the elements of the array are=%d\n",(sumn+sump));
return 0;
}
|
the_stack_data/179831041.c | //
// 2_5_any.c
// c_exercises
//
// Created by wongxp on 2019/1/22.
// Copyright © 2019年 wongxp. All rights reserved.
//
#include <stdio.h>
/// s1 = "abcde123f";
/// s2 = "xxx2yyy";
/// 6
int any(char s1[], char s2[]) {
int i, j;
for (i = 0; s1[i] != '\0'; ++i) {
for (j = 0; s2[j] != '\0'; ++j) {
if (s1[i] == s2[j]) {
return i;
}
}
}
return -1;
}
/// s1 = "abced123f";
/// s2 = "123";
/// 5
int any_v2(char s1[], char s2[]) {
int i, j, k;
for (i = 0; s1[i] != '\0'; ++i) {
for (k = 0,j = i; s2[k] != '\0' && s2[k++] == s1[j++]; ) {
;
}
if (k > 0 && s2[k] == '\0') {
return i;
}
}
return -1;
}
|
the_stack_data/218894310.c | // RUN: clang -o %t-opt %s -O2 -mno-sse
// RUN: llvm-mctoll -d -I /usr/include/stdio.h %t-opt
// RUN: clang -o %t-opt-dis %t-opt-dis.ll
// RUN: %t-opt-dis 2>&1 | FileCheck %s
// CHECK:a[0] = 4, a[1] = 5, a[2] = 6, a[3] = 7, a[4] = 8
// CHECK:arr[0] = 4
// CHECK:arr[1] = 5
// CHECK:arr[2] = 6
// CHECK:arr[3] = 7
// CHECK:arr[4] = 8
// CHECK:arr[0] = 4, arr[1] = 5, arr[2] = 6, arr[3] = 7, arr[4] = 8
#include <stdio.h>
int __attribute__((noinline))foo(int *a)
{
a[0] = 4;
a[1] = 5;
a[2] = 6;
a[3] = 7;
a[4] = 8;
printf("a[0] = %d, a[1] = %d, a[2] = %d, a[3] = %d, a[4] = %d\n", a[0], a[1], a[2], a[3], a[4]);
return 0;
}
int main()
{
int arr[5] = {0};
foo(arr);
if (arr[0] > 3)
printf("arr[0] = %d\n", arr[0]);
if (arr[1] > 4)
printf("arr[1] = %d\n", arr[1]);
if (arr[2] > 5)
printf("arr[2] = %d\n", arr[2]);
if (arr[3] > 6)
printf("arr[3] = %d\n", arr[3]);
if (arr[4] > 7)
printf("arr[4] = %d\n", arr[4]);
printf("arr[0] = %d, arr[1] = %d, arr[2] = %d, arr[3] = %d, arr[4] = %d\n", arr[0], arr[1], arr[2], arr[3], arr[4]);
return 0;
}
|
the_stack_data/75104.c | int main(){
int* i;
int* p;
int l = 20;
int d = 7;
i = &d;
p = i;
*p = 123;
{
int *p;
p = &l;
{
p = &d;
return *p;
}
}
return d+d+l + *p + *i;
}
|
the_stack_data/87637865.c | /*
Copyright (c) 2016, Alexey Frunze
2-clause BSD license.
*/
#ifdef __SMALLER_C_32__
#include <math.h>
#include <errno.h>
#ifdef __HUGE__
#define __HUGE_OR_UNREAL__
#endif
#ifdef __UNREAL__
#define __HUGE_OR_UNREAL__
#endif
#ifdef __HUGE_OR_UNREAL__
#define xbp "bp"
#else
#define xbp "ebp"
#endif
float asinf(float x)
{
union
{
unsigned u;
float f;
} u;
u.f = x;
if ((u.u &= 0x7FFFFFFF) > 0x3F800000) // if fabs(x) > 1 or x is NAN
{
if (u.u <= 0x7F800000) // if x isn't NAN
errno = EDOM;
return NAN;
}
asm
(
"fld dword ["xbp"+8]\n"
"fld st0\n"
"fld1\n"
"fsubr st1, st0\n"
"fadd st0, st2\n"
"fmulp\n"
"fsqrt\n"
"fpatan\n"
"fstp dword ["xbp"+8]\n"
"mov eax, ["xbp"+8]"
);
}
double asin(double x)
{
return asinf(x);
}
#endif
|
the_stack_data/156392648.c | // RUN: %clang -target mipsel-unknown-linux -O3 -S -o - -emit-llvm %s | FileCheck %s -check-prefix=O32
// RUN: %clang -target mips64el-unknown-linux -O3 -S -mabi=n64 -o - -emit-llvm %s | FileCheck %s -check-prefix=N64
typedef struct {
float f[3];
} S0;
extern void foo2(S0);
// O32-LABEL: define void @foo1(i32 %a0.coerce0, i32 %a0.coerce1, i32 %a0.coerce2)
// N64-LABEL: define void @foo1(i64 %a0.coerce0, i32 %a0.coerce1)
void foo1(S0 a0) {
foo2(a0);
}
|
the_stack_data/68888146.c | int foo(int i)
{
return i;
}
int bla(int i)
{
if (i>27)
i = foo(i - 13);
else if (i<-2)
i = foo(i + 3);
else
i = foo(i + 2);
return i;
}
int if03(int i)
{
if (i>10)
i = bla(i);
else if (i<3)
i = bla(i-1);
else if (i<5)
i = bla(i-2);
else if (i<7)
i = bla(i-3);
else
i = bla(i+1);
return i;
}
|
the_stack_data/95442.c | //
// Created by kkyse on 9/28/2017.
//
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <stdio.h>
/*
* strchr is like indexOf(char) in Java.
* It accepts a const char * (null-terminated string)
* and an int-promoted char to search for.
* It returns a char * to the first occurrence of the character in the string.
* The null character is included in the search.
* If the character was not found, the NULL pointer is returned.
*/
size_t strchr_index(const char *const string, const int search_char) {
return strchr(string, search_char) - string;
}
/*
* strstr is like indexOf(String) in Java
* It accepts two const char *,
* the first one being the main string
* and the second being the substring being searched for.
* It returns a char * to the first occurrence of str2 in str1.
* The null character is not included in the search.
* If str2 is not found in str1, the NULL pointer is returned.
*/
size_t strstr_index(const char *const string, const char *const substring) {
return strstr(string, substring) - string;
}
int main() {
assert(strchr_index("Hello, World", ',') == 5);
assert(strstr_index("Khyber Sen", "r S") == 5);
perror(EXIT_SUCCESS);
return EXIT_SUCCESS;
} |
the_stack_data/161080000.c | #include <dirent.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main (int argc, char** argv) {
if (argc != 2) {
printf("USAGE: which <thing to look for in the PATH>");
} else {
char* path = getenv("PATH");
char* name = argv[1];
char* token = strtok(path, ";");
struct dirent* dirPtr;
while (token) {
DIR* dir = opendir(token);
dirPtr = readdir(dir);
while (dirPtr) {
if (NULL == strcmp(dirPtr->d_name, name)) {
if (token[strlen(token) - 1] == '\\') {
printf("%s%s\n", token, name);
} else {
printf("%s\\%s\n", token, name);
}
return 0;
}
dirPtr = readdir(dir);
}
closedir(dir);
*(token-1) = ';';
token = strtok(NULL, ";");
}
printf("which: no '%s' in (%s)", name, path);
}
return 0;
}
|
the_stack_data/220455263.c | #include <stdarg.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <errno.h>
void
abend(const char *fmt, ...) {
va_list ap;
// print the global error, if any
if (errno != 0) {
fprintf(stderr, "\n%s\n", strerror(errno));
}
// print the termination message
if (fmt != 0 || fmt[0] != 0) {
char msg[4*1024]; // buffer for error
va_start(ap, fmt);
vsnprintf(msg, sizeof(msg)-1, fmt, ap);
va_end(ap);
fprintf(stderr, "\n%s\n", msg);
}
exit(2);
} |
the_stack_data/156391893.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 EK-LM3S6965 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 lwIPEthernetIntHandler(void);
extern void SysTickIntHandler(void);
//*****************************************************************************
//
// The entry point for the application.
//
//*****************************************************************************
extern int main(void);
//*****************************************************************************
//
// Reserve space for the system stack.
//
//*****************************************************************************
static unsigned long pulStack[256];
//*****************************************************************************
//
// 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
IntDefaultHandler, // 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
IntDefaultHandler, // 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
IntDefaultHandler, // 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
lwIPEthernetIntHandler, // 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/40763213.c | // INFO: rcu detected stall in ext4_file_write_iter
// https://syzkaller.appspot.com/bug?id=997b03a7f1ed8c68a818f0a2aa9174205bf61954
// status:open
// autogenerated by syzkaller (https://github.com/google/syzkaller)
#define _GNU_SOURCE
#include <dirent.h>
#include <endian.h>
#include <errno.h>
#include <fcntl.h>
#include <signal.h>
#include <stdarg.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/mount.h>
#include <sys/prctl.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <time.h>
#include <unistd.h>
unsigned long long procid;
static void sleep_ms(uint64_t ms)
{
usleep(ms * 1000);
}
static uint64_t current_time_ms(void)
{
struct timespec ts;
if (clock_gettime(CLOCK_MONOTONIC, &ts))
exit(1);
return (uint64_t)ts.tv_sec * 1000 + (uint64_t)ts.tv_nsec / 1000000;
}
static void use_temporary_dir(void)
{
char tmpdir_template[] = "./syzkaller.XXXXXX";
char* tmpdir = mkdtemp(tmpdir_template);
if (!tmpdir)
exit(1);
if (chmod(tmpdir, 0777))
exit(1);
if (chdir(tmpdir))
exit(1);
}
static bool write_file(const char* file, const char* what, ...)
{
char buf[1024];
va_list args;
va_start(args, what);
vsnprintf(buf, sizeof(buf), what, args);
va_end(args);
buf[sizeof(buf) - 1] = 0;
int len = strlen(buf);
int fd = open(file, O_WRONLY | O_CLOEXEC);
if (fd == -1)
return false;
if (write(fd, buf, len) != len) {
int err = errno;
close(fd);
errno = err;
return false;
}
close(fd);
return true;
}
#define FS_IOC_SETFLAGS _IOW('f', 2, long)
static void remove_dir(const char* dir)
{
DIR* dp;
struct dirent* ep;
int iter = 0;
retry:
while (umount2(dir, MNT_DETACH) == 0) {
}
dp = opendir(dir);
if (dp == NULL) {
if (errno == EMFILE) {
exit(1);
}
exit(1);
}
while ((ep = readdir(dp))) {
if (strcmp(ep->d_name, ".") == 0 || strcmp(ep->d_name, "..") == 0)
continue;
char filename[FILENAME_MAX];
snprintf(filename, sizeof(filename), "%s/%s", dir, ep->d_name);
while (umount2(filename, MNT_DETACH) == 0) {
}
struct stat st;
if (lstat(filename, &st))
exit(1);
if (S_ISDIR(st.st_mode)) {
remove_dir(filename);
continue;
}
int i;
for (i = 0;; i++) {
if (unlink(filename) == 0)
break;
if (errno == EPERM) {
int fd = open(filename, O_RDONLY);
if (fd != -1) {
long flags = 0;
if (ioctl(fd, FS_IOC_SETFLAGS, &flags) == 0)
close(fd);
continue;
}
}
if (errno == EROFS) {
break;
}
if (errno != EBUSY || i > 100)
exit(1);
if (umount2(filename, MNT_DETACH))
exit(1);
}
}
closedir(dp);
int i;
for (i = 0;; i++) {
if (rmdir(dir) == 0)
break;
if (i < 100) {
if (errno == EPERM) {
int fd = open(dir, O_RDONLY);
if (fd != -1) {
long flags = 0;
if (ioctl(fd, FS_IOC_SETFLAGS, &flags) == 0)
close(fd);
continue;
}
}
if (errno == EROFS) {
break;
}
if (errno == EBUSY) {
if (umount2(dir, MNT_DETACH))
exit(1);
continue;
}
if (errno == ENOTEMPTY) {
if (iter < 100) {
iter++;
goto retry;
}
}
}
exit(1);
}
}
static void kill_and_wait(int pid, int* status)
{
kill(-pid, SIGKILL);
kill(pid, SIGKILL);
int i;
for (i = 0; i < 100; i++) {
if (waitpid(-1, status, WNOHANG | __WALL) == pid)
return;
usleep(1000);
}
DIR* dir = opendir("/sys/fs/fuse/connections");
if (dir) {
for (;;) {
struct dirent* ent = readdir(dir);
if (!ent)
break;
if (strcmp(ent->d_name, ".") == 0 || strcmp(ent->d_name, "..") == 0)
continue;
char abort[300];
snprintf(abort, sizeof(abort), "/sys/fs/fuse/connections/%s/abort",
ent->d_name);
int fd = open(abort, O_WRONLY);
if (fd == -1) {
continue;
}
if (write(fd, abort, 1) < 0) {
}
close(fd);
}
closedir(dir);
} else {
}
while (waitpid(-1, status, __WALL) != pid) {
}
}
static void setup_test()
{
prctl(PR_SET_PDEATHSIG, SIGKILL, 0, 0, 0);
setpgrp();
write_file("/proc/self/oom_score_adj", "1000");
}
static void execute_one(void);
#define WAIT_FLAGS __WALL
static void loop(void)
{
int iter;
for (iter = 0;; iter++) {
char cwdbuf[32];
sprintf(cwdbuf, "./%d", iter);
if (mkdir(cwdbuf, 0777))
exit(1);
int pid = fork();
if (pid < 0)
exit(1);
if (pid == 0) {
if (chdir(cwdbuf))
exit(1);
setup_test();
execute_one();
exit(0);
}
int status = 0;
uint64_t start = current_time_ms();
for (;;) {
if (waitpid(-1, &status, WNOHANG | WAIT_FLAGS) == pid)
break;
sleep_ms(1);
if (current_time_ms() - start < 5 * 1000)
continue;
kill_and_wait(pid, &status);
break;
}
remove_dir(cwdbuf);
}
}
#ifndef __NR_sched_setattr
#define __NR_sched_setattr 314
#endif
uint64_t r[1] = {0xffffffffffffffff};
void execute_one(void)
{
intptr_t res = 0;
*(uint32_t*)0x20000080 = 0;
*(uint32_t*)0x20000084 = 6;
*(uint64_t*)0x20000088 = 0;
*(uint32_t*)0x20000090 = 0;
*(uint32_t*)0x20000094 = 0;
*(uint64_t*)0x20000098 = 0x8000000009917;
*(uint64_t*)0x200000a0 = 0x400000000000fffd;
*(uint64_t*)0x200000a8 = 0;
syscall(__NR_sched_setattr, 0, 0x20000080, 0);
memcpy((void*)0x20000080, "./bus\000", 6);
res = syscall(__NR_open, 0x20000080, 0x1fe, 0);
if (res != -1)
r[0] = res;
memcpy((void*)0x20000240, "\x9c\x54\xe7\x77\x25\x32\x3b\xe4\x8b\x2b\x58\x05"
"\xa7\x26\xde\x15\x4f\x38\x34\xdf\x22\x00\x08\xfb"
"\x9b\x15\x98\x52",
28);
syscall(__NR_write, r[0], 0x20000240, 0x1c);
*(uint64_t*)0x20000000 = 0;
syscall(__NR_sendfile, r[0], r[0], 0x20000000, 0x8080fffffffe);
}
int main(void)
{
syscall(__NR_mmap, 0x20000000, 0x1000000, 3, 0x32, -1, 0);
for (procid = 0; procid < 6; procid++) {
if (fork() == 0) {
use_temporary_dir();
loop();
}
}
sleep(1000000);
return 0;
}
|
the_stack_data/798856.c | // Custom sine and cosine accuracy test
// cc custom_sin.c -O2 -o test -lm -lpthread && ./test
/*
PI 3.14159265359 result
SMALL SINE -- Max: 0.003655% (-11.781015), Avg: 0.000252%
SMALL COSINE -- Max: 0.003652% (-10.210200), Avg: 0.000252%
SINE -- Max: 198.935837% (106667408.000000), Avg: 66.297116%
COSINE -- Max: 200.000000% (85563208.000000), Avg: 94.841570%
*/
/*
PI 3.14159265358979323846
SMALL COSINE -- Max: 0.003645% (-0.785422), Avg: 0.000249%
SMALL SINE -- Max: 0.003643% (11.780985), Avg: 0.000248%
SINE -- Max: 0.003656% (-2000234752.000000), Avg: 0.000249%
COSINE -- Max: 0.003659% (1487533056.000000), Avg: 0.000249%
*/
#include <stdio.h>
#include <math.h>
#include <pthread.h>
//#define PI 3.14159265359f
#define PI 3.14159265358979323846
// Normalize rotation between 0 and 2PI
float normalized_angle(float x)
{
return (x < 0) ? x + 2*PI*((int)(-x/(2*PI))+1) : x - 2*PI*(int)(x/(2*PI));
}
// Sine
float sine(float x)
{
// Normalize the rotation
x = normalized_angle(x);
// Check sign
float sign;
if (x < PI)
sign = 1;
else
sign = -1;
// Check symmetry
if (x < PI/2 || (x >= PI && x < 3*PI/2))
x -= (PI/2)*(int)(x/(PI/2));
else
x = PI/2 - x + (PI/2)*(int)(x/(PI/2));
// Check it to be below 45 degree
if (x < PI/4)
{
// Polinomial approximation
float x2 = x*x;
float x3 = x2*x;
float sine = x - x3/6 + x2*x3/120;
return sine*sign;
}
else
{
// Transform to cosine
x = PI/2 - x;
// Polinomial approximation
float x2 = x*x;
float x4 = x2*x2;
float x6 = x2*x4;
float cosine = 1 - x2/2 + x4/24 - x6/720;
return cosine*sign;
}
}
// Cosine
float cosine(float x)
{
// Normalize the rotation
x = normalized_angle(x);
// Check sign
float sign;
if (x < PI/2 || x >= 3*PI/2)
sign = 1;
else
sign = -1;
// Check symmetry
if (x < PI/2 || (x >= PI && x < 3*PI/2))
x -= (PI/2)*(int)(x/(PI/2));
else
x = PI/2 - x + (PI/2)*(int)(x/(PI/2));
// Check it to be below 45 degree
if (x < PI/4)
{
// Polinomial approximation
float x2 = x*x;
float x4 = x2*x2;
float x6 = x2*x4;
float cosine = 1 - x2/2 + x4/24 - x6/720;
return cosine*sign;
}
else
{
// Transform to sine
x = PI/2 - x;
// Polinomial approximation
float x2 = x*x;
float x3 = x2*x;
float sine = x - x3/6 + x2*x3/120;
return sine*sign;
}
}
void *reduced_test_sin()
{
// Start reduced test
printf("Running test on SMALL SINE sample...\n");
double avg_err = 0.;
double max_err = 0.;
unsigned long j = 0;
float max_err_value;
// Test only few value
for (float n = -4*PI; n < 4*PI; n+=0.000001)
{
double err = fabs(sin(n)-sine(n));
avg_err += err;
if (err > max_err)
{
max_err = err;
max_err_value = n;
}
j++;
}
// Print errors
printf("SMALL SINE -- Max: %lf%% (%f), Avg: %lf%\n", max_err*100., max_err_value, (avg_err*100/j));
return NULL;
}
void *reduced_test_cos()
{
// Start reduced test
printf("Running test on SMALL COSINE sample...\n");
double avg_err = 0.;
double max_err = 0.;
unsigned long j = 0;
float max_err_value;
// Test only few value
for (float n = -4*PI; n < 4*PI; n+=0.000001)
{
double err = fabs(cos(n)-cosine(n));
avg_err += err;
if (err > max_err)
{
max_err = err;
max_err_value = n;
}
j++;
}
// Print errors
printf("SMALL COSINE -- Max: %lf%% (%f), Avg: %lf%\n", max_err*100., max_err_value, (avg_err*100/j));
return NULL;
}
void *sin_test()
{
// Start sin test
printf("Running test on Sine...\n");
double avg_err = 0.;
double max_err = 0.;
unsigned long j = 0;
float max_err_value;
// Test all float32 value
for (int s = 0; s < (1 << 1); s++)
{
for (int e = 0; e < (1 << 8)-1; e++)
{
for (int m = 0; m < (1 << 23); m++)
{
float n = (s << 31) | (e << 23) | m;
double err = fabs(sin(n)-sine(n));
avg_err += err;
if (err > max_err)
{
max_err = err;
max_err_value = n;
}
j++;
}
}
}
// Print errors
printf("SINE -- Max: %lf%% (%f), Avg: %lf%\n", max_err*100., max_err_value, (avg_err*100/j));
return NULL;
}
void *cos_test()
{
// Start cos test
printf("Running test on Cosine...\n");
double avg_err = 0.;
double max_err = 0.;
unsigned long j = 0;
float max_err_value;
// Test all float32 value
for (int s = 0; s < (1 << 1); s++)
{
for (int e = 0; e < (1 << 8)-1; e++)
{
for (int m = 0; m < (1 << 23); m++)
{
float n = (s << 31) | (e << 23) | m;
double err = fabs(cos(n)-cosine(n));
avg_err += err;
if (err > max_err)
{
max_err = err;
max_err_value = n;
}
j++;
}
}
}
// Print errors
printf("COSINE -- Max: %lf%% (%f), Avg: %lf%\n", max_err*100., max_err_value, (avg_err*100/j));
return NULL;
}
// Main
int main()
{
// Run 3 additional thread
pthread_t sin_thread, cos_thread, reduced_sin_thread, reduced_cos_thread;
pthread_create(&sin_thread, NULL, sin_test, NULL);
pthread_create(&cos_thread, NULL, cos_test, NULL);
pthread_create(&reduced_sin_thread, NULL, reduced_test_sin, NULL);
pthread_create(&reduced_cos_thread, NULL, reduced_test_cos, NULL);
pthread_join(sin_thread, NULL);
pthread_join(cos_thread, NULL);
pthread_join(reduced_sin_thread, NULL);
pthread_join(reduced_cos_thread, NULL);
return 0;
}
|
the_stack_data/150143479.c | #ifdef _MSC_VER
#define _CRT_SECURE_NO_WARNINGS
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#define MAX_CHARACTERS 1005
#define MAX_PARAGRAPHS 5
struct word {
char* data;
};
struct sentence {
struct word* data;
int word_count;//denotes number of words in a sentence
};
struct paragraph {
struct sentence* data ;
int sentence_count;//denotes number of sentences in a paragraph
};
struct document {
struct paragraph* data;
int paragraph_count;//denotes number of paragraphs in a document
};
#include <stdbool.h>
#ifndef _WIN32
char *strtok_r(char *, const char *, char **);
#else
static inline char *strtok_r(char *const str, const char *const delim,
char **const context)
{
return strtok_s(str, delim, context);
}
#endif
static inline void require(const bool condition)
{
if (!condition) abort();
}
static void *xcalloc(const size_t count, const size_t size)
{
void *const p = calloc(count, size);
require(p);
return p;
}
static int tokenize(char *const str, const char *const delim,
char **const out, const int outlen)
{
int count = 0;
for (char *q = NULL, *p = strtok_r(str, delim, &q); p;
p = strtok_r(NULL, delim, &q)) {
assert(0 <= count);
require(count < outlen);
out[count++] = p;
}
return count;
}
static struct sentence get_sentence(char *const str)
{
char *words[MAX_CHARACTERS] = {0};
const int count = tokenize(str, " \t", words, MAX_CHARACTERS);
const struct sentence sen = {xcalloc(count, sizeof *sen.data)};
for (int i = 0; i < count; ++i) sen.data[i] = (struct word){words[i]};
return sen;
}
static struct paragraph get_paragraph(char *const str)
{
char *sentences[MAX_CHARACTERS] = {0};
const int count = tokenize(str, ".", sentences, MAX_CHARACTERS);
const struct paragraph para = {xcalloc(count, sizeof *para.data)};
for (int i = 0; i < count; ++i) para.data[i] = get_sentence(sentences[i]);
return para;
}
struct document get_document(char *const str)
{
char *paragraphs[MAX_PARAGRAPHS] = {0};
const int count = tokenize(str, "\r\n\f\v", paragraphs, MAX_PARAGRAPHS);
const struct document doc = {xcalloc(count, sizeof *doc.data)};
for (int i = 0; i < count; ++i) doc.data[i] = get_paragraph(paragraphs[i]);
return doc;
}
struct word kth_word_in_mth_sentence_of_nth_paragraph(
const struct document doc, const int k, const int m, const int n)
{
return doc.data[n - 1].data[m - 1].data[k - 1];
}
struct sentence kth_sentence_in_mth_paragraph(const struct document doc,
const int k, const int m)
{
return doc.data[m - 1].data[k - 1];
}
struct paragraph kth_paragraph(const struct document doc, const int k)
{
return doc.data[k - 1];
}
void print_word(struct word w) {
printf("%s", w.data);
}
void print_sentence(struct sentence sen) {
for(int i = 0; i < sen.word_count; i++) {
print_word(sen.data[i]);
if (i != sen.word_count - 1) {
printf(" ");
}
}
}
void print_paragraph(struct paragraph para) {
for(int i = 0; i < para.sentence_count; i++){
print_sentence(para.data[i]);
printf(".");
}
}
void print_document(struct document doc) {
for(int i = 0; i < doc.paragraph_count; i++) {
print_paragraph(doc.data[i]);
if (i != doc.paragraph_count - 1)
printf("\n");
}
}
char* get_input_text() {
int paragraph_count;
scanf("%d", ¶graph_count);
char p[MAX_PARAGRAPHS][MAX_CHARACTERS], doc[MAX_CHARACTERS];
memset(doc, 0, sizeof(doc));
getchar();
for (int i = 0; i < paragraph_count; i++) {
scanf("%[^\n]%*c", p[i]);
strcat(doc, p[i]);
if (i != paragraph_count - 1)
strcat(doc, "\n");
}
char* returnDoc = (char*)malloc((strlen (doc)+1) * (sizeof(char)));
strcpy(returnDoc, doc);
return returnDoc;
}
int main()
{
char* text = get_input_text();
struct document Doc = get_document(text);
int q;
scanf("%d", &q);
while (q--) {
int type;
scanf("%d", &type);
if (type == 3){
int k, m, n;
scanf("%d %d %d", &k, &m, &n);
struct word w = kth_word_in_mth_sentence_of_nth_paragraph(Doc, k, m, n);
print_word(w);
}
else if (type == 2) {
int k, m;
scanf("%d %d", &k, &m);
struct sentence sen= kth_sentence_in_mth_paragraph(Doc, k, m);
print_sentence(sen);
}
else{
int k;
scanf("%d", &k);
struct paragraph para = kth_paragraph(Doc, k);
print_paragraph(para);
}
printf("\n");
}
}
|
the_stack_data/299383.c | #include <stdio.h>
#include <string.h>
#define SIZE 3
typedef struct {
char name[16];
char surname[20];
float height;
float weight;
float bmi;
char answer[14];
} student;
void showData(student showstu[]);
int main() {
int n;
student std[SIZE];
for (n=0; n<SIZE; n++){
printf("Enter student data\n");
printf("\tName : ");
scanf("%s", std[n].name);
printf("\tSurname : ");
scanf("%s", std[n].surname);
printf("\tHeight (m) : ");
scanf("%f", &std[n].height);
printf("\tWeight (Kg) : ");
scanf("%f", &std[n].weight);
std[n].bmi = std[n].weight / (std[n].height * std[n].height);
if (std[n].bmi >= 20 && std[n].bmi <= 25){
strcpy(std[n].answer, "Normal BMI");
}else{
strcpy(std[n].answer, "Dangerous BMI");
}
}
printf("\n\nShow Data\n");
printf("------------------------------------------------------------------------\n");
printf("Name \t Surname \t Weight \t Height \t BMI \t Answer \n");
printf("------------------------------------------------------------------------\n");
showData (std);
system("pause");
return 0;
}
void showData(student showstu[]){
int i;
for(i=0; i<SIZE; i++){
printf("%s\t%+5s\t%14.2f kg.\t %.2f m.", showstu[i].name, showstu[i].surname, showstu[i].weight, showstu[i].height);
printf("\t%.2f\t%s\n", showstu[i].bmi, showstu[i].answer);
}
}
|
the_stack_data/51899.c | #include <stdio.h>
#include <stdlib.h> /*for exit*/
#include <unistd.h> /*for open/close..*/
#include <fcntl.h> /*for O_RDWR*/
#include <sys/ioctl.h> /*for ioctl*/
#include <linux/fb.h> /*for fb_var_screeninfo, FBIOGET_VSCREENINFO*/
#define FBDEVFILE "/dev/fb2"
int main()
{
int fbfd;
int ret;
struct fb_var_screeninfo fbvar;
struct fb_fix_screeninfo fbfix;
fbfd = open(FBDEVFILE, O_RDWR); //frame buffer의 node인 /dev/fb를 open
if (fbfd < 0)
{
perror("fbdevopen");
exit(1);
}
ret = ioctl(fbfd, FBIOGET_VSCREENINFO, &fbvar);
if (ret < 0)
{
perror("fbdevioctl(FSCREENINFO)");
exit(1);
}
ret = ioctl(fbfd, FBIOGET_FSCREENINFO, &fbfix);
if (ret < 0)
{
perror("fbdevioctl(FSCREENINFO)");
exit(1);
}
// x-resolution
printf("x-resolution: %d\n", fbvar.xres);
//y-resolution
printf("y-resolution: %d\n", fbvar.yres);
//virtual x-resolution
printf("x-resolution(virtual): %d\n", fbvar.xres_virtual);
//virtual y-resolution
printf("y-resolution(virtual): %d\n", fbvar.yres_virtual);
//bpp (bits per pixel)
printf("bpp: %d\n", fbvar.bits_per_pixel);
//the size of frame buffer memory
printf("lengthof frame buffer memory: %d\n", fbfix.smem_len);
close(fbfd);
return 0;
}
|
the_stack_data/38153.c | //Classification: #default/n/ZD/AE/aS+aS/A(D(v),c))/lc/ln
//Written by: Alexey Salmin
//Reviewed by: Igor Eremeev
int main(void)
{
int a = 1, b = 3, c, *p=&a;
c = b / (*p - 1);
return 0;
}
|
the_stack_data/416871.c | //
// dishizhang9.c
// dishizhang
//
// Created by mingyue on 15/10/28.
// Copyright © 2015年 G. All rights reserved.
//
#include <stdio.h>
#define SIZE 5
void show_array(const double ar[], int n);
void mult_array(double ar[], int n, double mult);
int main(int argc, const char* argv[]){
double dip[SIZE] = {20.0, 17.66, 8.2, 15.3, 22.22};
printf("The original dip array:\n");
show_array(dip, SIZE);
mult_array(dip, SIZE, 2.5);
printf("The dip array after calling mult_array():\n");
show_array(dip, SIZE);
return 0;
}
void show_array(const double ar[],int n){
int i;
for (i = 0; i < n; i++) {
printf("%8.3f ",ar[i]);
}
putchar('\n');
}
void mult_array(double ar[], int n, double mult){
int i;
for (i = 0; i < n; i++) {
ar[i] *= mult;
}
}
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.