file
stringlengths 18
26
| data
stringlengths 3
1.04M
|
---|---|
the_stack_data/211081345.c | #include <pthread.h>
int pthread_mutex_destroy(pthread_mutex_t* mutex) {
return 0;
}
|
the_stack_data/122014411.c | #include <stdio.h>
int main(){
char c = 'x';
char *ap;
ap = &c;
printf("&c = %x\n", &c);
printf("ap -> %x\n", ap);
printf("&ap = %x\n", &ap);
return 0;
}
|
the_stack_data/154831181.c | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_intsort.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: abiri <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/10/10 02:12:13 by abiri #+# #+# */
/* Updated: 2018/10/11 13:32:08 by abiri ### ########.fr */
/* */
/* ************************************************************************** */
void ft_intsort(int *tab, int size)
{
int i;
int j;
int temp;
int good;
i = 0;
j = 0;
good = 1;
while (i++ < size)
{
while (j < size - 1)
{
if (tab[j] > tab[j + 1])
{
temp = tab[j];
tab[j] = tab[j + 1];
tab[j + 1] = temp;
}
else
good += 1;
j++;
}
}
if (good < size)
ft_intsort(tab, size);
}
|
the_stack_data/1038006.c | #import <stdio.h>
typedef struct {
int zee;
int yee;
} foo;
int main(int argc, char** argv){
foo x;
x.zee=2;
x.yee=3;
int fooy=10;
int z = 0;
while (z<fooy){
puts("In the while loop!");
z++;
}
for (int i=0; i<10; i++){
puts("In the for loop!");
}
}
|
the_stack_data/1097844.c | // RUN: %clang_cc1 -ftrapping-math -frounding-math -ffp-exception-behavior=strict -emit-llvm -o - %s | FileCheck %s -check-prefix=FPMODELSTRICT
// RUN: %clang_cc1 -ffp-contract=fast -emit-llvm -o - %s | FileCheck %s -check-prefix=PRECISE
// RUN: %clang_cc1 -ffast-math -ffp-contract=fast -emit-llvm -o - %s | FileCheck %s -check-prefix=FAST
// RUN: %clang_cc1 -ffast-math -emit-llvm -o - %s | FileCheck %s -check-prefix=FASTNOCONTRACT
// RUN: %clang_cc1 -ffast-math -ffp-contract=fast -ffp-exception-behavior=ignore -emit-llvm -o - %s | FileCheck %s -check-prefix=FAST
// RUN: %clang_cc1 -ffast-math -ffp-contract=fast -ffp-exception-behavior=strict -emit-llvm -o - %s | FileCheck %s -check-prefix=EXCEPT
// RUN: %clang_cc1 -ffast-math -ffp-contract=fast -ffp-exception-behavior=maytrap -emit-llvm -o - %s | FileCheck %s -check-prefix=MAYTRAP
float f0, f1, f2;
void foo() {
// CHECK-LABEL: define {{.*}}void @foo()
// MAYTRAP: llvm.experimental.constrained.fadd.f32(float %{{.*}}, float %{{.*}}, metadata !"round.tonearest", metadata !"fpexcept.maytrap")
// EXCEPT: llvm.experimental.constrained.fadd.f32(float %{{.*}}, float %{{.*}}, metadata !"round.tonearest", metadata !"fpexcept.strict")
// FPMODELSTRICT: llvm.experimental.constrained.fadd.f32(float %{{.*}}, float %{{.*}}, metadata !"round.dynamic", metadata !"fpexcept.strict")
// STRICTEXCEPT: llvm.experimental.constrained.fadd.f32(float %{{.*}}, float %{{.*}}, metadata !"round.dynamic", metadata !"fpexcept.strict")
// STRICTNOEXCEPT: llvm.experimental.constrained.fadd.f32(float %{{.*}}, float %{{.*}}, metadata !"round.dynamic", metadata !"fpexcept.ignore")
// PRECISE: fadd contract float %{{.*}}, %{{.*}}
// FAST: fadd fast
// FASTNOCONTRACT: fadd reassoc nnan ninf nsz arcp afn float
f0 = f1 + f2;
// CHECK: ret
}
|
the_stack_data/215769220.c | #include <stdio.h>
/*
* This program shows that a context-insensitive analysis loses precision.
* In this case, we can improve the results with inlining.
*/
int foo(int k, int N) {
while (k < N) {
int i = 0;
int j = k;
while (i < j) {
i = i + 1;
j = j - 1;
}
k = k + 1;
}
return k;
}
int main(int argc, char** argv) {
printf("%d\n", foo(0, 10));
printf("%d\n", foo(30, 100));
}
|
the_stack_data/18887010.c | /*********************************************************************
* SEGGER Microcontroller GmbH *
* The Embedded Experts *
**********************************************************************
* *
* (c) 1995 - 2021 SEGGER Microcontroller GmbH *
* *
* www.segger.com Support: [email protected] *
* *
**********************************************************************
* *
* SEGGER RTT * Real Time Transfer for embedded targets *
* *
**********************************************************************
* *
* All rights reserved. *
* *
* SEGGER strongly recommends to not make any changes *
* to or modify the source code of this software in order to stay *
* compatible with the RTT protocol and J-Link. *
* *
* Redistribution and use in source and binary forms, with or *
* without modification, are permitted provided that the following *
* condition is met: *
* *
* o Redistributions of source code must retain the above copyright *
* notice, this condition and the following disclaimer. *
* *
* 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 SEGGER Microcontroller 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. *
* *
**********************************************************************
* *
* RTT version: 7.22b *
* *
**********************************************************************
---------------------------END-OF-HEADER------------------------------
File : RTT_Syscalls_KEIL.c
Purpose : Retargeting module for KEIL MDK-CM3.
Low-level functions for using printf() via RTT
Revision: $Rev: 20754 $
Notes : (1) https://wiki.segger.com/Keil_MDK-ARM#RTT_in_uVision
----------------------------------------------------------------------
*/
#if (defined __CC_ARM) || (defined __ARMCC_VERSION)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <rt_sys.h>
#include <rt_misc.h>
#include "SEGGER_RTT.h"
/*********************************************************************
*
* #pragmas
*
**********************************************************************
*/
#if __ARMCC_VERSION < 6000000
#pragma import(__use_no_semihosting)
#endif
#ifdef _MICROLIB
#pragma import(__use_full_stdio)
#endif
/*********************************************************************
*
* Defines non-configurable
*
**********************************************************************
*/
/* Standard IO device handles - arbitrary, but any real file system handles must be
less than 0x8000. */
#define STDIN 0x8001 // Standard Input Stream
#define STDOUT 0x8002 // Standard Output Stream
#define STDERR 0x8003 // Standard Error Stream
/*********************************************************************
*
* Public const
*
**********************************************************************
*/
#if __ARMCC_VERSION < 5000000
//const char __stdin_name[] = "STDIN";
const char __stdout_name[] = "STDOUT";
const char __stderr_name[] = "STDERR";
#endif
/*********************************************************************
*
* Public code
*
**********************************************************************
*/
/*********************************************************************
*
* _ttywrch
*
* Function description:
* Outputs a character to the console
*
* Parameters:
* c - character to output
*
*/
void _ttywrch(int c) {
fputc(c, stdout); // stdout
fflush(stdout);
}
/*********************************************************************
*
* _sys_open
*
* Function description:
* Opens the device/file in order to do read/write operations
*
* Parameters:
* sName - sName of the device/file to open
* OpenMode - This parameter is currently ignored
*
* Return value:
* != 0 - Handle to the object to open, otherwise
* == 0 -"device" is not handled by this module
*
*/
FILEHANDLE _sys_open(const char * sName, int OpenMode) {
(void)OpenMode;
// Register standard Input Output devices.
if (strcmp(sName, __stdout_name) == 0) {
return (STDOUT);
} else if (strcmp(sName, __stderr_name) == 0) {
return (STDERR);
} else
return (0); // Not implemented
}
/*********************************************************************
*
* _sys_close
*
* Function description:
* Closes the handle to the open device/file
*
* Parameters:
* hFile - Handle to a file opened via _sys_open
*
* Return value:
* 0 - device/file closed
*
*/
int _sys_close(FILEHANDLE hFile) {
(void)hFile;
return 0; // Not implemented
}
/*********************************************************************
*
* _sys_write
*
* Function description:
* Writes the data to an open handle.
* Currently this function only outputs data to the console
*
* Parameters:
* hFile - Handle to a file opened via _sys_open
* pBuffer - Pointer to the data that shall be written
* NumBytes - Number of bytes to write
* Mode - The Mode that shall be used
*
* Return value:
* Number of bytes *not* written to the file/device
*
*/
int _sys_write(FILEHANDLE hFile, const unsigned char * pBuffer, unsigned NumBytes, int Mode) {
int r = 0;
(void)Mode;
if (hFile == STDOUT) {
SEGGER_RTT_Write(0, (const char*)pBuffer, NumBytes);
return 0;
}
return r;
}
/*********************************************************************
*
* _sys_read
*
* Function description:
* Reads data from an open handle.
* Currently this modules does nothing.
*
* Parameters:
* hFile - Handle to a file opened via _sys_open
* pBuffer - Pointer to buffer to store the read data
* NumBytes - Number of bytes to read
* Mode - The Mode that shall be used
*
* Return value:
* Number of bytes read from the file/device
*
*/
int _sys_read(FILEHANDLE hFile, unsigned char * pBuffer, unsigned NumBytes, int Mode) {
(void)hFile;
(void)pBuffer;
(void)NumBytes;
(void)Mode;
return (0); // Not implemented
}
/*********************************************************************
*
* _sys_istty
*
* Function description:
* This function shall return whether the opened file
* is a console device or not.
*
* Parameters:
* hFile - Handle to a file opened via _sys_open
*
* Return value:
* 1 - Device is a console
* 0 - Device is not a console
*
*/
int _sys_istty(FILEHANDLE hFile) {
if (hFile > 0x8000) {
return (1);
}
return (0); // Not implemented
}
/*********************************************************************
*
* _sys_seek
*
* Function description:
* Seeks via the file to a specific position
*
* Parameters:
* hFile - Handle to a file opened via _sys_open
* Pos -
*
* Return value:
* int -
*
*/
int _sys_seek(FILEHANDLE hFile, long Pos) {
(void)hFile;
(void)Pos;
return (0); // Not implemented
}
/*********************************************************************
*
* _sys_ensure
*
* Function description:
*
*
* Parameters:
* hFile - Handle to a file opened via _sys_open
*
* Return value:
* int -
*
*/
int _sys_ensure(FILEHANDLE hFile) {
(void)hFile;
return (-1); // Not implemented
}
/*********************************************************************
*
* _sys_flen
*
* Function description:
* Returns the length of the opened file handle
*
* Parameters:
* hFile - Handle to a file opened via _sys_open
*
* Return value:
* Length of the file
*
*/
long _sys_flen(FILEHANDLE hFile) {
(void)hFile;
return (0); // Not implemented
}
/*********************************************************************
*
* _sys_tmpnam
*
* Function description:
* This function converts the file number fileno for a temporary
* file to a unique filename, for example, tmp0001.
*
* Parameters:
* pBuffer - Pointer to a buffer to store the name
* FileNum - file number to convert
* MaxLen - Size of the buffer
*
* Return value:
* 1 - Error
* 0 - Success
*
*/
int _sys_tmpnam(char * pBuffer, int FileNum, unsigned MaxLen) {
(void)pBuffer;
(void)FileNum;
(void)MaxLen;
return (1); // Not implemented
}
/*********************************************************************
*
* _sys_command_string
*
* Function description:
* This function shall execute a system command.
*
* Parameters:
* cmd - Pointer to the command string
* len - Length of the string
*
* Return value:
* == NULL - Command was not successfully executed
* == sCmd - Command was passed successfully
*
*/
char * _sys_command_string(char * cmd, int len) {
(void)len;
return cmd; // Not implemented
}
/*********************************************************************
*
* _sys_exit
*
* Function description:
* This function is called when the application returns from main
*
* Parameters:
* ReturnCode - Return code from the main function
*
*
*/
void _sys_exit(int ReturnCode) {
(void)ReturnCode;
while (1); // Not implemented
}
#if __ARMCC_VERSION >= 5000000
/*********************************************************************
*
* stdout_putchar
*
* Function description:
* Put a character to the stdout
*
* Parameters:
* ch - Character to output
*
*
*/
int stdout_putchar(int ch) {
(void)ch;
return ch; // Not implemented
}
#endif
#endif
/*************************** End of file ****************************/
|
the_stack_data/151166.c | /*
* comparators.c
*
* Functions that can be used as comparators in various collections.
*
* This file is part of libcoll, a generic collections library for C.
* Copyright (c) 2010-2020 Mika Wahlroos ([email protected])
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include <string.h>
int libcoll_intptrcmp(const void *value1, const void *value2)
{
int *a = (int*) value1;
int *b = (int*) value2;
return *a - *b;
}
int libcoll_strcmp_wrapper(const void *value1, const void *value2)
{
char *s1 = (char*) value1;
char *s2 = (char*) value2;
return strcmp(s1, s2);
}
int libcoll_memaddrcmp(const void *value1, const void *value2)
{
int cmpval;
if (value1 == value2) {
cmpval = 0;
} else if (value1 < value2) {
cmpval = -1;
} else {
cmpval = 1;
}
return cmpval;
}
|
the_stack_data/125140687.c | #include<stdio.h>
int main()
{
int n,k,i,j;
int l,r,H;
scanf("%d%d",&n,&k);
int a[n];
for(i = 0;i<n;i++)
scanf("%d",&a[i]);
for(i = 0;i<k;i++)
{
int sum = 0,pai = 1;
scanf("%d%d",&l,&r);
for(j = l;j<=r;j++)
{
sum += a[j];
if(pai >= n ) pai%=n;
pai *= a[j];
}
sum %= n;
pai %= n;
int max,min;
sum>pai?(max = sum,min =pai):(max = pai,min = sum);
H = a[min];
for(j = min;j<=max-1;j++)
{
H ^= a[j+1];
}
printf("%d\n",H);
}
} |
the_stack_data/439379.c | #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;
#ifdef _MSC_VER
static inline _Fcomplex Cf(complex *z) {_Fcomplex zz={z->r , z->i}; return zz;}
static inline _Dcomplex Cd(doublecomplex *z) {_Dcomplex zz={z->r , z->i};return zz;}
static inline _Fcomplex * _pCf(complex *z) {return (_Fcomplex*)z;}
static inline _Dcomplex * _pCd(doublecomplex *z) {return (_Dcomplex*)z;}
#else
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;}
#endif
#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)); }
#ifdef _MSC_VER
#define c_div(c, a, b) {Cf(c)._Val[0] = (Cf(a)._Val[0]/Cf(b)._Val[0]); Cf(c)._Val[1]=(Cf(a)._Val[1]/Cf(b)._Val[1]);}
#define z_div(c, a, b) {Cd(c)._Val[0] = (Cd(a)._Val[0]/Cd(b)._Val[0]); Cd(c)._Val[1]=(Cd(a)._Val[1]/df(b)._Val[1]);}
#else
#define c_div(c, a, b) {pCf(c) = Cf(a)/Cf(b);}
#define z_div(c, a, b) {pCd(c) = Cd(a)/Cd(b);}
#endif
#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) = conjf(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) (cimagf(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;
}
#ifdef _MSC_VER
static _Fcomplex cpow_ui(complex x, integer n) {
complex pow={1.0,0.0}; unsigned long int u;
if(n != 0) {
if(n < 0) n = -n, x.r = 1/x.r, x.i=1/x.i;
for(u = n; ; ) {
if(u & 01) pow.r *= x.r, pow.i *= x.i;
if(u >>= 1) x.r *= x.r, x.i *= x.i;
else break;
}
}
_Fcomplex p={pow.r, pow.i};
return p;
}
#else
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;
}
#endif
#ifdef _MSC_VER
static _Dcomplex zpow_ui(_Dcomplex x, integer n) {
_Dcomplex pow={1.0,0.0}; unsigned long int u;
if(n != 0) {
if(n < 0) n = -n, x._Val[0] = 1/x._Val[0], x._Val[1] =1/x._Val[1];
for(u = n; ; ) {
if(u & 01) pow._Val[0] *= x._Val[0], pow._Val[1] *= x._Val[1];
if(u >>= 1) x._Val[0] *= x._Val[0], x._Val[1] *= x._Val[1];
else break;
}
}
_Dcomplex p = {pow._Val[0], pow._Val[1]};
return p;
}
#else
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;
}
#endif
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;
#ifdef _MSC_VER
_Fcomplex zdotc = {0.0, 0.0};
if (incx == 1 && incy == 1) {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc._Val[0] += conjf(Cf(&x[i]))._Val[0] * Cf(&y[i])._Val[0];
zdotc._Val[1] += conjf(Cf(&x[i]))._Val[1] * Cf(&y[i])._Val[1];
}
} else {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc._Val[0] += conjf(Cf(&x[i*incx]))._Val[0] * Cf(&y[i*incy])._Val[0];
zdotc._Val[1] += conjf(Cf(&x[i*incx]))._Val[1] * Cf(&y[i*incy])._Val[1];
}
}
pCf(z) = zdotc;
}
#else
_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;
}
#endif
static inline void zdotc_(doublecomplex *z, integer *n_, doublecomplex *x, integer *incx_, doublecomplex *y, integer *incy_) {
integer n = *n_, incx = *incx_, incy = *incy_, i;
#ifdef _MSC_VER
_Dcomplex zdotc = {0.0, 0.0};
if (incx == 1 && incy == 1) {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc._Val[0] += conj(Cd(&x[i]))._Val[0] * Cd(&y[i])._Val[0];
zdotc._Val[1] += conj(Cd(&x[i]))._Val[1] * Cd(&y[i])._Val[1];
}
} else {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc._Val[0] += conj(Cd(&x[i*incx]))._Val[0] * Cd(&y[i*incy])._Val[0];
zdotc._Val[1] += conj(Cd(&x[i*incx]))._Val[1] * Cd(&y[i*incy])._Val[1];
}
}
pCd(z) = zdotc;
}
#else
_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;
}
#endif
static inline void cdotu_(complex *z, integer *n_, complex *x, integer *incx_, complex *y, integer *incy_) {
integer n = *n_, incx = *incx_, incy = *incy_, i;
#ifdef _MSC_VER
_Fcomplex zdotc = {0.0, 0.0};
if (incx == 1 && incy == 1) {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc._Val[0] += Cf(&x[i])._Val[0] * Cf(&y[i])._Val[0];
zdotc._Val[1] += Cf(&x[i])._Val[1] * Cf(&y[i])._Val[1];
}
} else {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc._Val[0] += Cf(&x[i*incx])._Val[0] * Cf(&y[i*incy])._Val[0];
zdotc._Val[1] += Cf(&x[i*incx])._Val[1] * Cf(&y[i*incy])._Val[1];
}
}
pCf(z) = zdotc;
}
#else
_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;
}
#endif
static inline void zdotu_(doublecomplex *z, integer *n_, doublecomplex *x, integer *incx_, doublecomplex *y, integer *incy_) {
integer n = *n_, incx = *incx_, incy = *incy_, i;
#ifdef _MSC_VER
_Dcomplex zdotc = {0.0, 0.0};
if (incx == 1 && incy == 1) {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc._Val[0] += Cd(&x[i])._Val[0] * Cd(&y[i])._Val[0];
zdotc._Val[1] += Cd(&x[i])._Val[1] * Cd(&y[i])._Val[1];
}
} else {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc._Val[0] += Cd(&x[i*incx])._Val[0] * Cd(&y[i*incy])._Val[0];
zdotc._Val[1] += Cd(&x[i*incx])._Val[1] * Cd(&y[i*incy])._Val[1];
}
}
pCd(z) = zdotc;
}
#else
_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 CGECON */
/* =========== DOCUMENTATION =========== */
/* Online html documentation available at */
/* http://www.netlib.org/lapack/explore-html/ */
/* > \htmlonly */
/* > Download CGECON + dependencies */
/* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.tgz?format=tgz&filename=/lapack/lapack_routine/cgecon.
f"> */
/* > [TGZ]</a> */
/* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.zip?format=zip&filename=/lapack/lapack_routine/cgecon.
f"> */
/* > [ZIP]</a> */
/* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.txt?format=txt&filename=/lapack/lapack_routine/cgecon.
f"> */
/* > [TXT]</a> */
/* > \endhtmlonly */
/* Definition: */
/* =========== */
/* SUBROUTINE CGECON( NORM, N, A, LDA, ANORM, RCOND, WORK, RWORK, */
/* INFO ) */
/* CHARACTER NORM */
/* INTEGER INFO, LDA, N */
/* REAL ANORM, RCOND */
/* REAL RWORK( * ) */
/* COMPLEX A( LDA, * ), WORK( * ) */
/* > \par Purpose: */
/* ============= */
/* > */
/* > \verbatim */
/* > */
/* > CGECON estimates the reciprocal of the condition number of a general */
/* > complex matrix A, in either the 1-norm or the infinity-norm, using */
/* > the LU factorization computed by CGETRF. */
/* > */
/* > An estimate is obtained for norm(inv(A)), and the reciprocal of the */
/* > condition number is computed as */
/* > RCOND = 1 / ( norm(A) * norm(inv(A)) ). */
/* > \endverbatim */
/* Arguments: */
/* ========== */
/* > \param[in] NORM */
/* > \verbatim */
/* > NORM is CHARACTER*1 */
/* > Specifies whether the 1-norm condition number or the */
/* > infinity-norm condition number is required: */
/* > = '1' or 'O': 1-norm; */
/* > = 'I': Infinity-norm. */
/* > \endverbatim */
/* > */
/* > \param[in] N */
/* > \verbatim */
/* > N is INTEGER */
/* > The order of the matrix A. N >= 0. */
/* > \endverbatim */
/* > */
/* > \param[in] A */
/* > \verbatim */
/* > A is COMPLEX array, dimension (LDA,N) */
/* > The factors L and U from the factorization A = P*L*U */
/* > as computed by CGETRF. */
/* > \endverbatim */
/* > */
/* > \param[in] LDA */
/* > \verbatim */
/* > LDA is INTEGER */
/* > The leading dimension of the array A. LDA >= f2cmax(1,N). */
/* > \endverbatim */
/* > */
/* > \param[in] ANORM */
/* > \verbatim */
/* > ANORM is REAL */
/* > If NORM = '1' or 'O', the 1-norm of the original matrix A. */
/* > If NORM = 'I', the infinity-norm of the original matrix A. */
/* > \endverbatim */
/* > */
/* > \param[out] RCOND */
/* > \verbatim */
/* > RCOND is REAL */
/* > The reciprocal of the condition number of the matrix A, */
/* > computed as RCOND = 1/(norm(A) * norm(inv(A))). */
/* > \endverbatim */
/* > */
/* > \param[out] WORK */
/* > \verbatim */
/* > WORK is COMPLEX array, dimension (2*N) */
/* > \endverbatim */
/* > */
/* > \param[out] RWORK */
/* > \verbatim */
/* > RWORK is REAL array, dimension (2*N) */
/* > \endverbatim */
/* > */
/* > \param[out] INFO */
/* > \verbatim */
/* > INFO is INTEGER */
/* > = 0: successful exit */
/* > < 0: if INFO = -i, the i-th argument had an illegal value */
/* > \endverbatim */
/* Authors: */
/* ======== */
/* > \author Univ. of Tennessee */
/* > \author Univ. of California Berkeley */
/* > \author Univ. of Colorado Denver */
/* > \author NAG Ltd. */
/* > \date December 2016 */
/* > \ingroup complexGEcomputational */
/* ===================================================================== */
/* Subroutine */ int cgecon_(char *norm, integer *n, complex *a, integer *lda,
real *anorm, real *rcond, complex *work, real *rwork, integer *info)
{
/* System generated locals */
integer a_dim1, a_offset, i__1;
real r__1, r__2;
/* Local variables */
integer kase, kase1;
real scale;
extern logical lsame_(char *, char *);
integer isave[3];
extern /* Subroutine */ int clacn2_(integer *, complex *, complex *, real
*, integer *, integer *);
real sl;
integer ix;
extern integer icamax_(integer *, complex *, integer *);
extern real slamch_(char *);
real su;
extern /* Subroutine */ int xerbla_(char *, integer *, ftnlen);
real ainvnm;
extern /* Subroutine */ int clatrs_(char *, char *, char *, char *,
integer *, complex *, integer *, complex *, real *, real *,
integer *), csrscl_(integer *,
real *, complex *, integer *);
logical onenrm;
char normin[1];
real smlnum;
/* -- LAPACK computational 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 */
/* ===================================================================== */
/* Test the input parameters. */
/* Parameter adjustments */
a_dim1 = *lda;
a_offset = 1 + a_dim1 * 1;
a -= a_offset;
--work;
--rwork;
/* Function Body */
*info = 0;
onenrm = *(unsigned char *)norm == '1' || lsame_(norm, "O");
if (! onenrm && ! lsame_(norm, "I")) {
*info = -1;
} else if (*n < 0) {
*info = -2;
} else if (*lda < f2cmax(1,*n)) {
*info = -4;
} else if (*anorm < 0.f) {
*info = -5;
}
if (*info != 0) {
i__1 = -(*info);
xerbla_("CGECON", &i__1, (ftnlen)6);
return 0;
}
/* Quick return if possible */
*rcond = 0.f;
if (*n == 0) {
*rcond = 1.f;
return 0;
} else if (*anorm == 0.f) {
return 0;
}
smlnum = slamch_("Safe minimum");
/* Estimate the norm of inv(A). */
ainvnm = 0.f;
*(unsigned char *)normin = 'N';
if (onenrm) {
kase1 = 1;
} else {
kase1 = 2;
}
kase = 0;
L10:
clacn2_(n, &work[*n + 1], &work[1], &ainvnm, &kase, isave);
if (kase != 0) {
if (kase == kase1) {
/* Multiply by inv(L). */
clatrs_("Lower", "No transpose", "Unit", normin, n, &a[a_offset],
lda, &work[1], &sl, &rwork[1], info);
/* Multiply by inv(U). */
clatrs_("Upper", "No transpose", "Non-unit", normin, n, &a[
a_offset], lda, &work[1], &su, &rwork[*n + 1], info);
} else {
/* Multiply by inv(U**H). */
clatrs_("Upper", "Conjugate transpose", "Non-unit", normin, n, &a[
a_offset], lda, &work[1], &su, &rwork[*n + 1], info);
/* Multiply by inv(L**H). */
clatrs_("Lower", "Conjugate transpose", "Unit", normin, n, &a[
a_offset], lda, &work[1], &sl, &rwork[1], info);
}
/* Divide X by 1/(SL*SU) if doing so will not cause overflow. */
scale = sl * su;
*(unsigned char *)normin = 'Y';
if (scale != 1.f) {
ix = icamax_(n, &work[1], &c__1);
i__1 = ix;
if (scale < ((r__1 = work[i__1].r, abs(r__1)) + (r__2 = r_imag(&
work[ix]), abs(r__2))) * smlnum || scale == 0.f) {
goto L20;
}
csrscl_(n, &scale, &work[1], &c__1);
}
goto L10;
}
/* Compute the estimate of the reciprocal condition number. */
if (ainvnm != 0.f) {
*rcond = 1.f / ainvnm / *anorm;
}
L20:
return 0;
/* End of CGECON */
} /* cgecon_ */
|
the_stack_data/336472.c | // WARNING: kernel stack regs has bad 'bp' value (3)
// https://syzkaller.appspot.com/bug?id=bea1c185923957c5339d5b43bca13e71047453da
// status:fixed
// autogenerated by syzkaller (http://github.com/google/syzkaller)
#define _GNU_SOURCE
#include <endian.h>
#include <errno.h>
#include <linux/net.h>
#include <netinet/in.h>
#include <signal.h>
#include <stdarg.h>
#include <stdio.h>
#include <sys/prctl.h>
#include <sys/socket.h>
#include <sys/syscall.h>
#include <sys/time.h>
#include <sys/wait.h>
#include <time.h>
#include <unistd.h>
__attribute__((noreturn)) static void doexit(int status)
{
volatile unsigned i;
syscall(__NR_exit_group, status);
for (i = 0;; i++) {
}
}
#include <setjmp.h>
#include <signal.h>
#include <stdint.h>
#include <string.h>
#include <string.h>
const int kFailStatus = 67;
const int kRetryStatus = 69;
static void fail(const char* msg, ...)
{
int e = errno;
va_list args;
va_start(args, msg);
vfprintf(stderr, msg, args);
va_end(args);
fprintf(stderr, " (errno %d)\n", e);
doexit((e == ENOMEM || e == EAGAIN) ? kRetryStatus : kFailStatus);
}
static __thread int skip_segv;
static __thread jmp_buf segv_env;
static void segv_handler(int sig, siginfo_t* info, void* uctx)
{
uintptr_t addr = (uintptr_t)info->si_addr;
const uintptr_t prog_start = 1 << 20;
const uintptr_t prog_end = 100 << 20;
if (__atomic_load_n(&skip_segv, __ATOMIC_RELAXED) &&
(addr < prog_start || addr > prog_end)) {
_longjmp(segv_env, 1);
}
doexit(sig);
}
static void install_segv_handler()
{
struct sigaction sa;
memset(&sa, 0, sizeof(sa));
sa.sa_handler = SIG_IGN;
syscall(SYS_rt_sigaction, 0x20, &sa, NULL, 8);
syscall(SYS_rt_sigaction, 0x21, &sa, NULL, 8);
memset(&sa, 0, sizeof(sa));
sa.sa_sigaction = segv_handler;
sa.sa_flags = SA_NODEFER | SA_SIGINFO;
sigaction(SIGSEGV, &sa, NULL);
sigaction(SIGBUS, &sa, NULL);
}
#define NONFAILING(...) \
{ \
__atomic_fetch_add(&skip_segv, 1, __ATOMIC_SEQ_CST); \
if (_setjmp(segv_env) == 0) { \
__VA_ARGS__; \
} \
__atomic_fetch_sub(&skip_segv, 1, __ATOMIC_SEQ_CST); \
}
static uint64_t current_time_ms()
{
struct timespec ts;
if (clock_gettime(CLOCK_MONOTONIC, &ts))
fail("clock_gettime failed");
return (uint64_t)ts.tv_sec * 1000 + (uint64_t)ts.tv_nsec / 1000000;
}
struct ipt_getinfo {
char name[32];
unsigned int valid_hooks;
unsigned int hook_entry[5];
unsigned int underflow[5];
unsigned int num_entries;
unsigned int size;
};
struct ipt_get_entries {
char name[32];
unsigned int size;
void* entrytable[1024 / sizeof(void*)];
};
struct xt_counters {
uint64_t pcnt, bcnt;
};
struct ipt_replace {
char name[32];
unsigned int valid_hooks;
unsigned int num_entries;
unsigned int size;
unsigned int hook_entry[5];
unsigned int underflow[5];
unsigned int num_counters;
struct xt_counters* counters;
char entrytable[1024];
};
struct ipt_table_desc {
const char* name;
struct ipt_getinfo info;
struct ipt_get_entries entries;
struct ipt_replace replace;
struct xt_counters counters[10];
};
static struct ipt_table_desc ipv4_tables[] = {
{.name = "filter"}, {.name = "nat"}, {.name = "mangle"},
{.name = "raw"}, {.name = "security"},
};
#define IPT_BASE_CTL 64
#define IPT_SO_SET_REPLACE (IPT_BASE_CTL)
#define IPT_SO_GET_INFO (IPT_BASE_CTL)
#define IPT_SO_GET_ENTRIES (IPT_BASE_CTL + 1)
static void checkpoint_net_namespace(void)
{
socklen_t optlen;
unsigned i;
int fd;
fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (fd == -1)
fail("socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)");
for (i = 0; i < sizeof(ipv4_tables) / sizeof(ipv4_tables[0]); i++) {
struct ipt_table_desc* table = &ipv4_tables[i];
strcpy(table->info.name, table->name);
strcpy(table->entries.name, table->name);
strcpy(table->replace.name, table->name);
optlen = sizeof(table->info);
if (getsockopt(fd, SOL_IP, IPT_SO_GET_INFO, &table->info, &optlen)) {
switch (errno) {
case EPERM:
case ENOENT:
case ENOPROTOOPT:
continue;
}
fail("getsockopt(IPT_SO_GET_INFO)");
}
if (table->info.size > sizeof(table->entries.entrytable))
fail("table size is too large: %u", table->info.size);
if (table->info.num_entries >
sizeof(table->counters) / sizeof(table->counters[0]))
fail("too many counters: %u", table->info.num_entries);
table->entries.size = table->info.size;
optlen = sizeof(table->entries) - sizeof(table->entries.entrytable) +
table->info.size;
if (getsockopt(fd, SOL_IP, IPT_SO_GET_ENTRIES, &table->entries, &optlen))
fail("getsockopt(IPT_SO_GET_ENTRIES)");
table->replace.valid_hooks = table->info.valid_hooks;
table->replace.num_entries = table->info.num_entries;
table->replace.counters = table->counters;
table->replace.size = table->info.size;
memcpy(table->replace.hook_entry, table->info.hook_entry,
sizeof(table->replace.hook_entry));
memcpy(table->replace.underflow, table->info.underflow,
sizeof(table->replace.underflow));
memcpy(table->replace.entrytable, table->entries.entrytable,
table->info.size);
}
close(fd);
}
static void reset_net_namespace(void)
{
struct ipt_get_entries entries;
struct ipt_getinfo info;
socklen_t optlen;
unsigned i;
int fd;
memset(&info, 0, sizeof(info));
memset(&entries, 0, sizeof(entries));
fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (fd == -1)
fail("socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)");
for (i = 0; i < sizeof(ipv4_tables) / sizeof(ipv4_tables[0]); i++) {
struct ipt_table_desc* table = &ipv4_tables[i];
if (table->info.valid_hooks == 0)
continue;
strcpy(info.name, table->name);
optlen = sizeof(info);
if (getsockopt(fd, SOL_IP, IPT_SO_GET_INFO, &info, &optlen))
fail("getsockopt(IPT_SO_GET_INFO)");
if (memcmp(&table->info, &info, sizeof(table->info)) == 0) {
strcpy(entries.name, table->name);
entries.size = table->info.size;
optlen = sizeof(entries) - sizeof(entries.entrytable) + entries.size;
if (getsockopt(fd, SOL_IP, IPT_SO_GET_ENTRIES, &entries, &optlen))
fail("getsockopt(IPT_SO_GET_ENTRIES)");
if (memcmp(&table->entries, &entries, optlen) == 0)
continue;
}
table->replace.num_counters = info.num_entries;
optlen = sizeof(table->replace) - sizeof(table->replace.entrytable) +
table->replace.size;
if (setsockopt(fd, SOL_IP, IPT_SO_SET_REPLACE, &table->replace, optlen))
fail("setsockopt(IPT_SO_SET_REPLACE)");
}
close(fd);
}
static void test();
void loop()
{
int iter;
checkpoint_net_namespace();
for (iter = 0;; iter++) {
int pid = fork();
if (pid < 0)
fail("loop fork failed");
if (pid == 0) {
prctl(PR_SET_PDEATHSIG, SIGKILL, 0, 0, 0);
setpgrp();
test();
doexit(0);
}
int status = 0;
uint64_t start = current_time_ms();
for (;;) {
int res = waitpid(-1, &status, __WALL | WNOHANG);
if (res == pid)
break;
usleep(1000);
if (current_time_ms() - start > 5 * 1000) {
kill(-pid, SIGKILL);
kill(pid, SIGKILL);
while (waitpid(-1, &status, __WALL) != pid) {
}
break;
}
}
reset_net_namespace();
}
}
long r[3];
uint64_t procid;
void test()
{
memset(r, -1, sizeof(r));
syscall(__NR_mmap, 0x20000000, 0xfff000, 3, 0x32, -1, 0);
r[0] = syscall(__NR_socket, 0x26, 5, 0);
syscall(__NR_close, r[0]);
r[1] = syscall(__NR_socket, 0x26, 5, 0);
NONFAILING(*(uint16_t*)0x20219fa8 = 0x26);
NONFAILING(memcpy((void*)0x20219faa,
"\x73\x6b\x63\x69\x70\x68\x65\x72\x00\x00\x00\x00\x00\x00",
14));
NONFAILING(*(uint32_t*)0x20219fb8 = 0);
NONFAILING(*(uint32_t*)0x20219fbc = 0);
NONFAILING(memcpy((void*)0x20219fc0,
"\x73\x61\x6c\x73\x61\x32\x30\x00\x00\x00\x00\x00\x00\x00"
"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
"\x00\x00\x00\x00\x00\x00\x00\x00",
64));
syscall(__NR_bind, r[0], 0x20219fa8, 0x58);
NONFAILING(memcpy(
(void*)0x20001f3a,
"\xad\x56\xb6\xc5\x82\x0f\xae\xb9\x95\x29\x89\x92\xea\x54\xc7\xbe", 16));
syscall(__NR_setsockopt, r[1], 0x117, 1, 0x20001f3a, 0x10);
r[2] = syscall(__NR_accept, r[1], 0, 0);
NONFAILING(*(uint64_t*)0x20791000 = 0);
NONFAILING(*(uint32_t*)0x20791008 = 0);
NONFAILING(*(uint64_t*)0x20791010 = 0x20cf6000);
NONFAILING(*(uint64_t*)0x20791018 = 1);
NONFAILING(*(uint64_t*)0x20791020 = 0x20000000);
NONFAILING(*(uint64_t*)0x20791028 = 0);
NONFAILING(*(uint32_t*)0x20791030 = 0);
NONFAILING(*(uint64_t*)0x20cf6000 = 0x20087000);
NONFAILING(*(uint64_t*)0x20cf6008 = 0x80);
NONFAILING(
memcpy((void*)0x20087000,
"\x51\xc8\xfb\x29\x29\x98\x9d\x20\xaf\xe7\x3d\xca\xc1\x12\x91\xb7"
"\x20\xbd\x7b\x71\xdd\xeb\x91\x61\x96\x6d\x49\x86\xbc\x69\x33\x5f"
"\xf6\x3b\x71\x1f\x36\x65\x3d\x33\xc3\xaf\x96\xb4\x27\x39\x38\x69"
"\x50\x91\x95\xdb\xe3\xbb\xd7\x2d\x89\x61\x05\xf0\x20\x41\x6b\xbc"
"\xa5\xf9\xc9\x6a\x03\x1e\xde\x84\xd7\x22\xa8\xca\x57\x49\x65\xa5"
"\x35\x85\x02\x15\x33\x5d\x66\xef\xc5\xe1\x24\xd0\x25\xa7\x62\xf7"
"\x7b\x51\xe2\xad\x1a\xe8\x86\x5d\xa4\xed\x5d\xde\x15\xbe\x35\xbe"
"\x78\xfc\xdb\x66\x7a\x12\xe2\x45\x2c\x8b\x20\x14\x61\xf9\x62\xad",
128));
syscall(__NR_sendmmsg, r[2], 0x20791000, 1, 0);
NONFAILING(*(uint64_t*)0x20b2f000 = 0x208e8000);
NONFAILING(*(uint32_t*)0x20b2f008 = 0x10);
NONFAILING(*(uint64_t*)0x20b2f010 = 0x204f3f73);
NONFAILING(*(uint64_t*)0x20b2f018 = 2);
NONFAILING(*(uint64_t*)0x20b2f020 = 0x20590000);
NONFAILING(*(uint64_t*)0x20b2f028 = 0);
NONFAILING(*(uint32_t*)0x20b2f030 = 0);
NONFAILING(*(uint64_t*)0x204f3f73 = 0x20284f81);
NONFAILING(*(uint64_t*)0x204f3f7b = 0x7f);
NONFAILING(*(uint64_t*)0x204f3f83 = 0x203bc000);
NONFAILING(*(uint64_t*)0x204f3f8b = 0xc6);
syscall(__NR_recvmsg, r[2], 0x20b2f000, 0);
}
int main()
{
for (procid = 0; procid < 8; procid++) {
if (fork() == 0) {
install_segv_handler();
for (;;) {
loop();
}
}
}
sleep(1000000);
return 0;
}
|
the_stack_data/924805.c | /*
** 2015-08-18
**
** The author disclaims copyright to this source code. In place of
** a legal notice, here is a blessing:
**
** May you do good and not evil.
** May you find forgiveness for yourself and forgive others.
** May you share freely, never taking more than you give.
**
*************************************************************************
**
** This file demonstrates how to create a table-valued-function using
** a virtual table. This demo implements the generate_series() function
** which gives similar results to the eponymous function in PostgreSQL.
** Examples:
**
** SELECT * FROM generate_series(0,100,5);
**
** The query above returns integers from 0 through 100 counting by steps
** of 5.
**
** SELECT * FROM generate_series(0,100);
**
** Integers from 0 through 100 with a step size of 1.
**
** SELECT * FROM generate_series(20) LIMIT 10;
**
** Integers 20 through 29.
**
** HOW IT WORKS
**
** The generate_series "function" is really a virtual table with the
** following schema:
**
** CREATE TABLE generate_series(
** value,
** start HIDDEN,
** stop HIDDEN,
** step HIDDEN
** );
**
** Function arguments in queries against this virtual table are translated
** into equality constraints against successive hidden columns. In other
** words, the following pairs of queries are equivalent to each other:
**
** SELECT * FROM generate_series(0,100,5);
** SELECT * FROM generate_series WHERE start=0 AND stop=100 AND step=5;
**
** SELECT * FROM generate_series(0,100);
** SELECT * FROM generate_series WHERE start=0 AND stop=100;
**
** SELECT * FROM generate_series(20) LIMIT 10;
** SELECT * FROM generate_series WHERE start=20 LIMIT 10;
**
** The generate_series virtual table implementation leaves the xCreate method
** set to NULL. This means that it is not possible to do a CREATE VIRTUAL
** TABLE command with "generate_series" as the USING argument. Instead, there
** is a single generate_series virtual table that is always available without
** having to be created first.
**
** The xBestIndex method looks for equality constraints against the hidden
** start, stop, and step columns, and if present, it uses those constraints
** to bound the sequence of generated values. If the equality constraints
** are missing, it uses 0 for start, 4294967295 for stop, and 1 for step.
** xBestIndex returns a small cost when both start and stop are available,
** and a very large cost if either start or stop are unavailable. This
** encourages the query planner to order joins such that the bounds of the
** series are well-defined.
*/
#include "sqlite3ext.h"
SQLITE_EXTENSION_INIT1
#include <assert.h>
#include <string.h>
#ifndef SQLITE_OMIT_VIRTUALTABLE
/* series_cursor is a subclass of sqlite3_vtab_cursor which will
** serve as the underlying representation of a cursor that scans
** over rows of the result
*/
typedef struct series_cursor series_cursor;
struct series_cursor {
sqlite3_vtab_cursor base; /* Base class - must be first */
int isDesc; /* True to count down rather than up */
sqlite3_int64 iRowid; /* The rowid */
sqlite3_int64 iValue; /* Current value ("value") */
sqlite3_int64 mnValue; /* Mimimum value ("start") */
sqlite3_int64 mxValue; /* Maximum value ("stop") */
sqlite3_int64 iStep; /* Increment ("step") */
};
/*
** The seriesConnect() method is invoked to create a new
** series_vtab that describes the generate_series virtual table.
**
** Think of this routine as the constructor for series_vtab objects.
**
** All this routine needs to do is:
**
** (1) Allocate the series_vtab object and initialize all fields.
**
** (2) Tell SQLite (via the sqlite3_declare_vtab() interface) what the
** result set of queries against generate_series will look like.
*/
static int seriesConnect(
sqlite3 *db,
void *pAux,
int argc, const char *const*argv,
sqlite3_vtab **ppVtab,
char **pzErr
){
sqlite3_vtab *pNew;
int rc;
/* Column numbers */
#define SERIES_COLUMN_VALUE 0
#define SERIES_COLUMN_START 1
#define SERIES_COLUMN_STOP 2
#define SERIES_COLUMN_STEP 3
rc = sqlite3_declare_vtab(db,
"CREATE TABLE x(value,start hidden,stop hidden,step hidden)");
if( rc==SQLITE_OK ){
pNew = *ppVtab = sqlite3_malloc( sizeof(*pNew) );
if( pNew==0 ) return SQLITE_NOMEM;
memset(pNew, 0, sizeof(*pNew));
}
return rc;
}
/*
** This method is the destructor for series_cursor objects.
*/
static int seriesDisconnect(sqlite3_vtab *pVtab){
sqlite3_free(pVtab);
return SQLITE_OK;
}
/*
** Constructor for a new series_cursor object.
*/
static int seriesOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
series_cursor *pCur;
pCur = sqlite3_malloc( sizeof(*pCur) );
if( pCur==0 ) return SQLITE_NOMEM;
memset(pCur, 0, sizeof(*pCur));
*ppCursor = &pCur->base;
return SQLITE_OK;
}
/*
** Destructor for a series_cursor.
*/
static int seriesClose(sqlite3_vtab_cursor *cur){
sqlite3_free(cur);
return SQLITE_OK;
}
/*
** Advance a series_cursor to its next row of output.
*/
static int seriesNext(sqlite3_vtab_cursor *cur){
series_cursor *pCur = (series_cursor*)cur;
if( pCur->isDesc ){
pCur->iValue -= pCur->iStep;
}else{
pCur->iValue += pCur->iStep;
}
pCur->iRowid++;
return SQLITE_OK;
}
/*
** Return values of columns for the row at which the series_cursor
** is currently pointing.
*/
static int seriesColumn(
sqlite3_vtab_cursor *cur, /* The cursor */
sqlite3_context *ctx, /* First argument to sqlite3_result_...() */
int i /* Which column to return */
){
series_cursor *pCur = (series_cursor*)cur;
sqlite3_int64 x = 0;
switch( i ){
case SERIES_COLUMN_START: x = pCur->mnValue; break;
case SERIES_COLUMN_STOP: x = pCur->mxValue; break;
case SERIES_COLUMN_STEP: x = pCur->iStep; break;
default: x = pCur->iValue; break;
}
sqlite3_result_int64(ctx, x);
return SQLITE_OK;
}
/*
** Return the rowid for the current row. In this implementation, the
** rowid is the same as the output value.
*/
static int seriesRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
series_cursor *pCur = (series_cursor*)cur;
*pRowid = pCur->iRowid;
return SQLITE_OK;
}
/*
** Return TRUE if the cursor has been moved off of the last
** row of output.
*/
static int seriesEof(sqlite3_vtab_cursor *cur){
series_cursor *pCur = (series_cursor*)cur;
if( pCur->isDesc ){
return pCur->iValue < pCur->mnValue;
}else{
return pCur->iValue > pCur->mxValue;
}
}
/* True to cause run-time checking of the start=, stop=, and/or step=
** parameters. The only reason to do this is for testing the
** constraint checking logic for virtual tables in the SQLite core.
*/
#ifndef SQLITE_SERIES_CONSTRAINT_VERIFY
# define SQLITE_SERIES_CONSTRAINT_VERIFY 0
#endif
/*
** This method is called to "rewind" the series_cursor object back
** to the first row of output. This method is always called at least
** once prior to any call to seriesColumn() or seriesRowid() or
** seriesEof().
**
** The query plan selected by seriesBestIndex is passed in the idxNum
** parameter. (idxStr is not used in this implementation.) idxNum
** is a bitmask showing which constraints are available:
**
** 1: start=VALUE
** 2: stop=VALUE
** 4: step=VALUE
**
** Also, if bit 8 is set, that means that the series should be output
** in descending order rather than in ascending order.
**
** This routine should initialize the cursor and position it so that it
** is pointing at the first row, or pointing off the end of the table
** (so that seriesEof() will return true) if the table is empty.
*/
static int seriesFilter(
sqlite3_vtab_cursor *pVtabCursor,
int idxNum, const char *idxStr,
int argc, sqlite3_value **argv
){
series_cursor *pCur = (series_cursor *)pVtabCursor;
int i = 0;
if( idxNum & 1 ){
pCur->mnValue = sqlite3_value_int64(argv[i++]);
}else{
pCur->mnValue = 0;
}
if( idxNum & 2 ){
pCur->mxValue = sqlite3_value_int64(argv[i++]);
}else{
pCur->mxValue = 0xffffffff;
}
if( idxNum & 4 ){
pCur->iStep = sqlite3_value_int64(argv[i++]);
if( pCur->iStep<1 ) pCur->iStep = 1;
}else{
pCur->iStep = 1;
}
if( idxNum & 8 ){
pCur->isDesc = 1;
pCur->iValue = pCur->mxValue;
if( pCur->iStep>0 ){
pCur->iValue -= (pCur->mxValue - pCur->mnValue)%pCur->iStep;
}
}else{
pCur->isDesc = 0;
pCur->iValue = pCur->mnValue;
}
pCur->iRowid = 1;
return SQLITE_OK;
}
/*
** SQLite will invoke this method one or more times while planning a query
** that uses the generate_series virtual table. This routine needs to create
** a query plan for each invocation and compute an estimated cost for that
** plan.
**
** In this implementation idxNum is used to represent the
** query plan. idxStr is unused.
**
** The query plan is represented by bits in idxNum:
**
** (1) start = $value -- constraint exists
** (2) stop = $value -- constraint exists
** (4) step = $value -- constraint exists
** (8) output in descending order
*/
static int seriesBestIndex(
sqlite3_vtab *tab,
sqlite3_index_info *pIdxInfo
){
int i; /* Loop over constraints */
int idxNum = 0; /* The query plan bitmask */
int startIdx = -1; /* Index of the start= constraint, or -1 if none */
int stopIdx = -1; /* Index of the stop= constraint, or -1 if none */
int stepIdx = -1; /* Index of the step= constraint, or -1 if none */
int nArg = 0; /* Number of arguments that seriesFilter() expects */
const struct sqlite3_index_constraint *pConstraint;
pConstraint = pIdxInfo->aConstraint;
for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
if( pConstraint->usable==0 ) continue;
if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
switch( pConstraint->iColumn ){
case SERIES_COLUMN_START:
startIdx = i;
idxNum |= 1;
break;
case SERIES_COLUMN_STOP:
stopIdx = i;
idxNum |= 2;
break;
case SERIES_COLUMN_STEP:
stepIdx = i;
idxNum |= 4;
break;
}
}
if( startIdx>=0 ){
pIdxInfo->aConstraintUsage[startIdx].argvIndex = ++nArg;
pIdxInfo->aConstraintUsage[startIdx].omit= !SQLITE_SERIES_CONSTRAINT_VERIFY;
}
if( stopIdx>=0 ){
pIdxInfo->aConstraintUsage[stopIdx].argvIndex = ++nArg;
pIdxInfo->aConstraintUsage[stopIdx].omit = !SQLITE_SERIES_CONSTRAINT_VERIFY;
}
if( stepIdx>=0 ){
pIdxInfo->aConstraintUsage[stepIdx].argvIndex = ++nArg;
pIdxInfo->aConstraintUsage[stepIdx].omit = !SQLITE_SERIES_CONSTRAINT_VERIFY;
}
if( (idxNum & 3)==3 ){
/* Both start= and stop= boundaries are available. This is the
** the preferred case */
pIdxInfo->estimatedCost = (double)(2 - ((idxNum&4)!=0));
pIdxInfo->estimatedRows = 1000;
if( pIdxInfo->nOrderBy==1 ){
if( pIdxInfo->aOrderBy[0].desc ) idxNum |= 8;
pIdxInfo->orderByConsumed = 1;
}
}else{
/* If either boundary is missing, we have to generate a huge span
** of numbers. Make this case very expensive so that the query
** planner will work hard to avoid it. */
pIdxInfo->estimatedCost = (double)2147483647;
pIdxInfo->estimatedRows = 2147483647;
}
pIdxInfo->idxNum = idxNum;
return SQLITE_OK;
}
/*
** This following structure defines all the methods for the
** generate_series virtual table.
*/
static sqlite3_module seriesModule = {
0, /* iVersion */
0, /* xCreate */
seriesConnect, /* xConnect */
seriesBestIndex, /* xBestIndex */
seriesDisconnect, /* xDisconnect */
0, /* xDestroy */
seriesOpen, /* xOpen - open a cursor */
seriesClose, /* xClose - close a cursor */
seriesFilter, /* xFilter - configure scan constraints */
seriesNext, /* xNext - advance a cursor */
seriesEof, /* xEof - check for end of scan */
seriesColumn, /* xColumn - read data */
seriesRowid, /* xRowid - read data */
0, /* xUpdate */
0, /* xBegin */
0, /* xSync */
0, /* xCommit */
0, /* xRollback */
0, /* xFindMethod */
0, /* xRename */
};
#endif /* SQLITE_OMIT_VIRTUALTABLE */
#ifdef _WIN32
__declspec(dllexport)
#endif
int sqlite3_series_init(
sqlite3 *db,
char **pzErrMsg,
const sqlite3_api_routines *pApi
){
int rc = SQLITE_OK;
SQLITE_EXTENSION_INIT2(pApi);
#ifndef SQLITE_OMIT_VIRTUALTABLE
if( sqlite3_libversion_number()<3008012 ){
*pzErrMsg = sqlite3_mprintf(
"generate_series() requires SQLite 3.8.12 or later");
return SQLITE_ERROR;
}
rc = sqlite3_create_module(db, "generate_series", &seriesModule, 0);
#endif
return rc;
}
|
the_stack_data/34511966.c | #include <stdlib.h>
#include <stdio.h>
#include <sys/utsname.h>
#include <string.h>
#include <errno.h>
int main(void) {
struct utsname name;
if (uname(&name) == -1) {
fprintf(stderr, "uname error: %s\n", strerror(errno));
exit(EXIT_FAILURE);
}
printf("sysname: %s, nodename: %s, release: %s, version: %s, machine: %s\n", name.sysname, name.nodename, name.release, name.version, name.machine);
exit(0);
} |
the_stack_data/29826085.c | #include <assert.h>
#include <limits.h>
#include <math.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* readline();
int main()
{
char* n_endptr;
char* n_str = readline();
int n = strtol(n_str, &n_endptr, 10);
if (n_endptr == n_str || *n_endptr != '\0') { exit(EXIT_FAILURE); }
// Write Your Code Here
if (n == 1){
printf("one");
}
else if (n == 2){
printf("two");
}
else if (n == 3){
printf("three");
}
else if (n == 4){
printf("four");
}
else if (n == 5){
printf("five");
}
else if (n == 6){
printf("six");
}
else if (n == 7){
printf("seven");
}
else if (n == 8){
printf("eight");
}
else if (n == 9){
printf("nine");
}
else{
printf("Greater than 9");
}
return 0;
}
char* readline() {
size_t alloc_length = 1024;
size_t data_length = 0;
char* data = malloc(alloc_length);
while (true) {
char* cursor = data + data_length;
char* line = fgets(cursor, alloc_length - data_length, stdin);
if (!line) { break; }
data_length += strlen(cursor);
if (data_length < alloc_length - 1 || data[data_length - 1] == '\n') { break; }
size_t new_length = alloc_length << 1;
data = realloc(data, new_length);
if (!data) { break; }
alloc_length = new_length;
}
if (data[data_length - 1] == '\n') {
data[data_length - 1] = '\0';
}
data = realloc(data, data_length);
return data;
}
|
the_stack_data/76700263.c | #include <stdio.h>
#include <string.h>
int main(void){
char a[100];
char b[100];
char str[1000];
scanf("%s", a);
scanf("%s", b);
if(strcmp(a,b)==0){
printf("OK");
}else{
printf("NG");
}
return 0;
} |
the_stack_data/1267318.c | #include <stdio.h>
int main()
{
int i,n ;
scanf("%d",&n);
i=n;
while(i>0)
{
printf("%d\n",i);
i--;
}
return 0;
}
|
the_stack_data/89200408.c | /**
* @file init_chip_internal.c
* @brief Initializes chip internal drivers
* @author Kacper Kowalski - [email protected]
*/
void init_chip_internal_drivers()
{
}
|
the_stack_data/32105.c | #include <stdlib.h>
/*
* Creditos: unix-
*
*
*
*/
static int (*qscmp)(const void*, const void*);
static int qses;
static void qsexc(char *i, char *j)
{
register char *ri, *rj, c;
int n;
n = qses;
ri = i;
rj = j;
do {
c = *ri;
*ri++ = *rj;
*rj++ = c;
} while(--n);
}
static void qstexc(char *i, char *j, char *k)
{
char *ri, *rj, *rk;
int c, n;
n = qses;
ri = i;
rj = j;
rk = k;
do {
c = *ri;
*ri++ = *rk;
*rk++ = *rj;
*rj++ = c;
} while(--n);
}
static void qs1( char *a, char *l )
{
char *i, *j;
int es;
// char **k;
char *lp, *hp;
int c;
unsigned n;
es = qses;
start:
if((n=l-a) <= es)
return;
n = es * (n / (2*es));
hp = lp = a+n;
i = a;
j = l-es;
for(;;) {
if(i < lp) {
if((c = (*qscmp)(i, lp)) == 0) {
qsexc(i, lp -= es);
continue;
}
if(c < 0) {
i += es;
continue;
}
}
loop:
if(j > hp) {
if((c = (*qscmp)(hp, j)) == 0) {
qsexc(hp += es, j);
goto loop;
}
if(c > 0) {
if(i == lp) {
qstexc(i, hp += es, j);
i = lp += es;
goto loop;
}
qsexc(i, j);
j -= es;
i += es;
continue;
}
j -= es;
goto loop;
}
if(i == lp) {
if(lp-a >= l-hp) {
qs1(hp+es, l);
l = lp;
} else {
qs1(a, lp);
a = hp+es;
}
goto start;
}
qstexc(j, lp -= es, i);
j = hp -= es;
}
}
void qsort(void *base, size_t nmemb, size_t size, int (*compar)(const void *, const void *))
{
qscmp = compar;
qses = size;
qs1(base, base+nmemb*size);
}
|
the_stack_data/192330594.c | /*
* fixstrtod.c --
*
* Source code for the "fixstrtod" procedure. This procedure is
* used in place of strtod under Solaris 2.4, in order to fix
* a bug where the "end" pointer gets set incorrectly.
*
* Copyright (c) 1995 Sun Microsystems, Inc.
*
* See the file "license.terms" for information on usage and redistribution
* of this file, and for a DISCLAIMER OF ALL WARRANTIES.
*
* RCS: @(#) $Id$
*/
#include <stdio.h>
#undef strtod
/*
* Declare strtod explicitly rather than including stdlib.h, since in
* somes systems (e.g. SunOS 4.1.4) stdlib.h doesn't declare strtod.
*/
extern double strtod(char *, char **);
double
fixstrtod(
char *string,
char **endPtr)
{
double d;
d = strtod(string, endPtr);
if ((endPtr != NULL) && (*endPtr != string) && ((*endPtr)[-1] == 0)) {
*endPtr -= 1;
}
return d;
}
|
the_stack_data/15643.c | #include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <string.h>
int main(){
char code[5], store;
srand(time(0));
for(int i=0;i<=4;i++){
do{
store = (rand() % 122) + 1;
if(store>=48 && store<=57){
break;
}
}while(store<97 || store>122);
code[i] = store;
}
system("cls");
printf("Code: ");
for(int i=0;i<=4;i++){
printf("%c", code[i]);
}
return 0;
} |
the_stack_data/75137104.c | // This contrived example is not useful in any way; it just shows that you can do mutual lemma recursion using lemma function pointer chunks.
/*@
typedef lemma void oddfunc(oddfunc *odd, evenfunc *even, int x);
requires multi_is_oddfunc(odd, x) &*& multi_is_evenfunc(even, x);
ensures multi_is_oddfunc(odd, x) &*& multi_is_evenfunc(even, x);
typedef lemma void evenfunc(oddfunc *odd, evenfunc *even, int x);
requires multi_is_oddfunc(odd, x) &*& multi_is_evenfunc(even, x);
ensures multi_is_oddfunc(odd, x) &*& multi_is_evenfunc(even, x);
predicate multi_is_oddfunc(oddfunc *odd, int n) = n <= 0 ? emp : is_oddfunc(odd) &*& multi_is_oddfunc(odd, n - 1);
predicate multi_is_evenfunc(evenfunc *even, int n) = n <= 0 ? emp : is_evenfunc(even) &*& multi_is_evenfunc(even, n - 1);
lemma void odd_lemma(oddfunc *odd, evenfunc *even, int x) : oddfunc
requires multi_is_oddfunc(odd, x) &*& multi_is_evenfunc(even, x);
ensures multi_is_oddfunc(odd, x) &*& multi_is_evenfunc(even, x);
{
open multi_is_oddfunc(odd, x);
open multi_is_evenfunc(even, x);
if (x <= 0) {
} else {
even(odd, even, x - 1);
}
close multi_is_oddfunc(odd, x);
close multi_is_evenfunc(even, x);
}
lemma void even_lemma(oddfunc *odd, evenfunc *even, int x) : evenfunc
requires multi_is_oddfunc(odd, x) &*& multi_is_evenfunc(even, x);
ensures multi_is_oddfunc(odd, x) &*& multi_is_evenfunc(even, x);
{
open multi_is_oddfunc(odd, x);
open multi_is_evenfunc(even, x);
if (x <= 0) {
} else {
odd(odd, even, x - 1);
}
close multi_is_oddfunc(odd, x);
close multi_is_evenfunc(even, x);
}
inductive nat = zero | succ(nat);
fixpoint int int_of_nat(nat n) {
switch (n) {
case zero: return 0;
case succ(m): return 1 + int_of_nat(m);
}
}
lemma void int_of_nat_nonneg(nat n)
requires true;
ensures 0 <= int_of_nat(n);
{
switch (n) {
case zero:
case succ(m):
int_of_nat_nonneg(m);
}
}
lemma void produce_chunks(int m, nat n)
requires multi_is_oddfunc(odd_lemma, m - int_of_nat(n)) &*& multi_is_evenfunc(even_lemma, m - int_of_nat(n));
ensures multi_is_oddfunc(odd_lemma, m - int_of_nat(n)) &*& multi_is_evenfunc(even_lemma, m - int_of_nat(n));
{
switch (n) {
case zero:
odd_lemma(odd_lemma, even_lemma, m);
case succ(n0):
int_of_nat_nonneg(n0);
produce_lemma_function_pointer_chunk(odd_lemma) {
produce_lemma_function_pointer_chunk(even_lemma) {
close multi_is_oddfunc(odd_lemma, m - int_of_nat(n0));
close multi_is_evenfunc(even_lemma, m - int_of_nat(n0));
produce_chunks(m, n0);
open multi_is_oddfunc(odd_lemma, m - int_of_nat(n0));
open multi_is_evenfunc(even_lemma, m - int_of_nat(n0));
}
}
}
}
lemma void main_lemma(nat n)
requires true;
ensures true;
{
close multi_is_evenfunc(even_lemma, 0);
close multi_is_oddfunc(odd_lemma, 0);
produce_chunks(int_of_nat(n), n);
open multi_is_evenfunc(even_lemma, 0);
open multi_is_oddfunc(odd_lemma, 0);
}
@*/ |
the_stack_data/232955216.c | #include <stdio.h>
int main(){
FILE *rp, *wp;
char str;
char input_text[81];
char output_text[81];
int count;
printf("Input text_name -->");
scanf("%s", input_text);
printf("Output text_name -->");
scanf("%s", output_text);
rp = fopen(input_text, "r");
wp = fopen(output_text, "w");
if(rp == NULL){
printf("file open error\n");
return -1;
}
if(wp == NULL){
printf("file open error\n");
return -1;
}
while((str = fgetc(rp)) != EOF){
if(str >= 0x61 && str <= 0x7a || str >= 0x41 && str <= 0x5a){
putchar(str);
}else if(str == 0x20){
putchar(str);
}else if(str == 0x0A){
putchar(str);
count++;
}else{
str = 0x20;
putchar(str);
}
fputc(str, wp);
}
fclose(rp);
fclose(wp);
printf("\ncomplete!\n");
return 0;
}
|
the_stack_data/37638098.c | /* PR c/85094 */
/* { dg-do compile } */
/* { dg-options "-O1 -Wduplicated-branches -g" } */
extern int g;
void
foo (int r)
{
if (r < 64)
g -= 48;
else if (r < 80) /* { dg-warning "this condition has identical branches" } */
g -= 64 - 45;
else
g -= 80 - 61;
}
|
the_stack_data/92326612.c | #include <stdio.h>
int main(void) {
int num;
printf("Informe um numero natural positivo: ");
scanf("%d", &num);
while (num <= 0)
{
printf("Informe um numero natural positivo: ");
scanf("%d", &num);
}
for (int i = num; i >= 0; i--)
{
printf("%d-> ", i);
}
return 0;
} |
the_stack_data/44983.c | /*
* Copyright (c) 2013 Jan-Piet Mens <[email protected]> wendal <wendal1985()gmai.com>
* 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 mosquitto 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 OWNER 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.
*/
#ifdef BE_HTTP
#include "backends.h"
#include "be-http.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "hash.h"
#include "log.h"
#include "envs.h"
#include <curl/curl.h>
#ifndef WIN32
#include <pthread.h>
#else
#define PTHREAD_MUTEX_INITIALIZER {0}
#define pthread_mutex_t CRITICAL_SECTION
#define pthread_mutex_lock(mutex) EnterCriticalSection(mutex)
#define pthread_mutex_unlock(mutex) LeaveCriticalSection(mutex)
#define pthread_mutex_init(mutex, attr) InitializeCriticalSection(mutex)
#define pthread_mutex_destroy(mutex) DeleteCriticalSection(mutex)
#endif
#define NO_OF_THREAD 128L
CURLSH *share = NULL;
pthread_mutex_t share_locker = PTHREAD_MUTEX_INITIALIZER;
CURL *curl_pool[NO_OF_THREAD];
volatile size_t curl_pool_current = 0L;
pthread_mutex_t curl_pool_locker = PTHREAD_MUTEX_INITIALIZER;
static int get_string_envs(CURL *curl, const char *required_env, char *querystring)
{
char *data = NULL;
char *escaped_key = NULL;
char *escaped_val = NULL;
char *env_string = NULL;
char *params_key[MAXPARAMSNUM];
char *env_names[MAXPARAMSNUM];
char *env_value[MAXPARAMSNUM];
int i, num = 0;
//_log(LOG_DEBUG, "sys_envs=%s", sys_envs);
env_string = (char *)malloc( strlen(required_env) + 20);
if (env_string == NULL) {
_fatal("ENOMEM");
return (-1);
}
sprintf(env_string, "%s", required_env);
//_log(LOG_DEBUG, "env_string=%s", env_string);
num = get_sys_envs(env_string, ",", "=", params_key, env_names, env_value);
//sprintf(querystring, "");
for( i = 0; i < num; i++ ){
escaped_key = curl_easy_escape(curl, params_key[i], 0);
escaped_val = curl_easy_escape(curl, env_value[i], 0);
//_log(LOG_DEBUG, "key=%s", params_key[i]);
//_log(LOG_DEBUG, "escaped_key=%s", escaped_key);
//_log(LOG_DEBUG, "escaped_val=%s", escaped_envvalue);
data = (char *)malloc(strlen(escaped_key) + strlen(escaped_val) + 4);
if ( data == NULL ) {
_fatal("ENOMEM");
return (-1);
}
sprintf(data, "%s=%s&", escaped_key, escaped_val);
if ( i == 0 ) {
sprintf(querystring, "%s", data);
} else {
strcat(querystring, data);
}
free(data);
curl_free(escaped_key);
curl_free(escaped_val);
}
if (escaped_key) free(escaped_key);
if (escaped_val) free(escaped_val);
free(env_string);
return (num);
}
static void lock(CURL *handle, curl_lock_data data, curl_lock_access
access,void *useptr ){
(void)handle; /* unused */
(void)useptr; /* unused */
(void)access; /* unused */
(void)data; /* unused */
pthread_mutex_lock(&share_locker);
}
/* unlock callback */
static void unlock(CURL *handle, curl_lock_data data, void *useptr ){
(void)handle; /* unused */
(void)useptr; /* unused */
(void)data; /* unused */
pthread_mutex_unlock(&share_locker);
}
static CURL* my_curl_easy_init() {
CURL* curl = NULL;
pthread_mutex_lock(&curl_pool_locker);
if (curl_pool_current > 0) {
curl = curl_pool[--curl_pool_current];
}
pthread_mutex_unlock(&curl_pool_locker);
if (curl == NULL) {
if ((curl = curl_easy_init()) != NULL) {
curl_easy_setopt(curl, CURLOPT_SHARE, share);
curl_easy_setopt(curl, CURLOPT_MAXCONNECTS, NO_OF_THREAD);
}
}
return curl;
}
static void my_curl_easy_cleanup(CURL* curl) {
pthread_mutex_lock(&curl_pool_locker);
if (curl_pool_current < sizeof(curl_pool)/sizeof(curl_pool[curl_pool_current])) {
curl_pool[curl_pool_current++] = curl;
curl = NULL;
}
pthread_mutex_unlock(&curl_pool_locker);
if (curl != NULL) {
curl_easy_cleanup(curl);
}
}
static int http_post(void *handle, char *uri, const char *clientid, const char *username, const char *password, const char *topic, int acc, int method)
{
struct http_backend *conf = (struct http_backend *)handle;
CURL *curl;
struct curl_slist *headerlist=NULL;
int re, urllen = 0;
int respCode = 0;
int ok = BACKEND_DEFER;
char *url;
char *data;
if (username == NULL) {
return BACKEND_DEFER;
}
clientid = (clientid && *clientid) ? clientid : "";
password = (password && *password) ? password : "";
topic = (topic && *topic) ? topic : "";
if ((curl = my_curl_easy_init()) == NULL) {
_fatal("create curl_easy_handle fails");
return BACKEND_ERROR;
}
if (conf->hostheader != NULL)
headerlist = curl_slist_append(headerlist, conf->hostheader);
headerlist = curl_slist_append(headerlist, "Expect:");
if(conf->basic_auth !=NULL){
headerlist = curl_slist_append(headerlist, conf->basic_auth);
}
//_log(LOG_NOTICE, "u=%s p=%s t=%s acc=%d", username, password, topic, acc);
urllen = strlen(conf->hostname) + strlen(uri) + 20;
url = (char *)malloc(urllen);
if (url == NULL) {
_fatal("ENOMEM");
return BACKEND_ERROR;
}
// uri begins with a slash
snprintf(url, urllen, "%s://%s:%d%s",
strcmp(conf->with_tls, "true") == 0 ? "https" : "http",
conf->hostname ? conf->hostname : "127.0.0.1",
conf->port,
uri);
char* escaped_username = curl_easy_escape(curl, username, 0);
char* escaped_password = curl_easy_escape(curl, password, 0);
char* escaped_topic = curl_easy_escape(curl, topic, 0);
char* escaped_clientid = curl_easy_escape(curl, clientid, 0);
char string_acc[20];
snprintf(string_acc, 20, "%d", acc);
char *string_envs = (char *)malloc(MAXPARAMSLEN);
if (string_envs == NULL) {
_fatal("ENOMEM");
return BACKEND_ERROR;
}
memset(string_envs, 0, MAXPARAMSLEN);
//get the sys_env from here
int env_num = 0;
if ( method == METHOD_GETUSER && conf->getuser_envs != NULL ){
env_num = get_string_envs(curl, conf->getuser_envs, string_envs);
}else if ( method == METHOD_SUPERUSER && conf->superuser_envs != NULL ){
env_num = get_string_envs(curl, conf->superuser_envs, string_envs);
} else if ( method == METHOD_ACLCHECK && conf->aclcheck_envs != NULL ){
env_num = get_string_envs(curl, conf->aclcheck_envs, string_envs);
}
if( env_num == -1 ){
return BACKEND_ERROR;
}
//---- over ----
data = (char *)malloc(strlen(string_envs) + strlen(escaped_username) + strlen(escaped_password) + strlen(escaped_topic) + strlen(string_acc) + strlen(escaped_clientid) + 50);
if (data == NULL) {
_fatal("ENOMEM");
return BACKEND_ERROR;
}
sprintf(data, "%susername=%s&password=%s&topic=%s&acc=%s&clientid=%s",
string_envs,
escaped_username,
escaped_password,
escaped_topic,
string_acc,
clientid);
_log(LOG_DEBUG, "url=%s", url);
_log(LOG_DEBUG, "data=%s", data);
//curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
curl_easy_setopt(curl, CURLOPT_URL, url);
curl_easy_setopt(curl, CURLOPT_POST, 1L);
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, data);
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headerlist);
curl_easy_setopt(curl, CURLOPT_TIMEOUT, 10);
re = curl_easy_perform(curl);
if (re == CURLE_OK) {
re = curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &respCode);
if (re == CURLE_OK && respCode >= 200 && respCode < 300) {
ok = BACKEND_ALLOW;
} else if (re == CURLE_OK && respCode >= 500) {
ok = BACKEND_ERROR;
} else {
//_log(LOG_NOTICE, "http auth fail re=%d respCode=%d", re, respCode);
}
} else {
_log(LOG_DEBUG, "http req fail url=%s re=%s", url, curl_easy_strerror(re));
ok = BACKEND_ERROR;
}
my_curl_easy_cleanup(curl);
curl_slist_free_all (headerlist);
free(url);
free(data);
free(string_envs);
free(escaped_username);
free(escaped_password);
free(escaped_topic);
free(escaped_clientid);
return (ok);
}
void *be_http_init()
{
struct http_backend *conf;
char *hostname;
char *getuser_uri;
char *superuser_uri;
char *aclcheck_uri;
if (curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK) {
_fatal("init curl fail");
return (NULL);
}
if ((hostname = p_stab("http_ip")) == NULL && (hostname = p_stab("http_hostname")) == NULL) {
_fatal("Mandatory parameter: one of either `http_ip' or `http_hostname' required");
return (NULL);
}
if ((getuser_uri = p_stab("http_getuser_uri")) == NULL) {
_fatal("Mandatory parameter `http_getuser_uri' missing");
return (NULL);
}
if ((superuser_uri = p_stab("http_superuser_uri")) == NULL) {
_fatal("Mandatory parameter `http_superuser_uri' missing");
return (NULL);
}
if ((aclcheck_uri = p_stab("http_aclcheck_uri")) == NULL) {
_fatal("Mandatory parameter `http_aclcheck_uri' missing");
return (NULL);
}
conf = (struct http_backend *)malloc(sizeof(struct http_backend));
conf->hostname = hostname;
conf->port = p_stab("http_port") == NULL ? 80 : atoi(p_stab("http_port"));
if (p_stab("http_hostname") != NULL) {
conf->hostheader = (char *)malloc(128);
sprintf(conf->hostheader, "Host: %s", p_stab("http_hostname"));
} else {
conf->hostheader = NULL;
}
conf->getuser_uri = getuser_uri;
conf->superuser_uri = superuser_uri;
conf->aclcheck_uri = aclcheck_uri;
conf->getuser_envs = p_stab("http_getuser_params");
conf->superuser_envs = p_stab("http_superuser_params");
conf->aclcheck_envs = p_stab("http_aclcheck_params");
if(p_stab("http_basic_auth_key")!= NULL){
conf->basic_auth = (char *)malloc( strlen("Authorization: Basic %s") + strlen(p_stab("http_basic_auth_key")));
sprintf(conf->basic_auth, "Authorization: Basic %s",p_stab("http_basic_auth_key"));
} else {
conf->basic_auth = NULL;
}
if (p_stab("http_with_tls") != NULL) {
conf->with_tls = p_stab("http_with_tls");
} else {
conf->with_tls = "false";
}
conf->retry_count = p_stab("http_retry_count") == NULL ? 3 : atoi(p_stab("http_retry_count"));
_log(LOG_DEBUG, "with_tls=%s", conf->with_tls);
_log(LOG_DEBUG, "getuser_uri=%s", getuser_uri);
_log(LOG_DEBUG, "superuser_uri=%s", superuser_uri);
_log(LOG_DEBUG, "aclcheck_uri=%s", aclcheck_uri);
_log(LOG_DEBUG, "getuser_params=%s", conf->getuser_envs);
_log(LOG_DEBUG, "superuser_params=%s", conf->superuser_envs);
_log(LOG_DEBUG, "aclcheck_params=%s", conf->aclcheck_envs);
_log(LOG_DEBUG, "retry_count=%d", conf->retry_count);
pthread_mutex_init(&curl_pool_locker, NULL);
pthread_mutex_init(&share_locker, NULL);
share = curl_share_init();
curl_share_setopt(share, CURLSHOPT_LOCKFUNC, lock);
curl_share_setopt(share, CURLSHOPT_UNLOCKFUNC, unlock);
curl_share_setopt(share, CURLSHOPT_SHARE, CURL_LOCK_DATA_DNS);
curl_share_setopt(share, CURLSHOPT_SHARE, CURL_LOCK_DATA_SSL_SESSION);
curl_share_setopt(share, CURLSHOPT_SHARE, CURL_LOCK_DATA_CONNECT);
#ifdef CURL_LOCK_DATA_PSL
curl_share_setopt(share, CURLSHOPT_SHARE, CURL_LOCK_DATA_PSL);
#endif
return (conf);
};
void be_http_destroy(void *handle)
{
struct http_backend *conf = (struct http_backend *)handle;
while (curl_pool_current > 0L) {
curl_easy_cleanup(curl_pool[--curl_pool_current]);
}
if (conf) {
curl_global_cleanup();
free(conf);
}
pthread_mutex_destroy(&curl_pool_locker);
pthread_mutex_destroy(&share_locker);
};
int be_http_getuser(void *handle, const char *username, const char *password, char **phash, const char *clientid) {
struct http_backend *conf = (struct http_backend *)handle;
int re, try;
if (username == NULL) {
return BACKEND_DEFER;
}
re = BACKEND_ERROR;
try = 0;
while (re == BACKEND_ERROR && try <= conf->retry_count) {
try++;
re = http_post(handle, conf->getuser_uri, NULL, username, password, NULL, -1, METHOD_GETUSER);
}
return re;
};
int be_http_superuser(void *handle, const char *username)
{
struct http_backend *conf = (struct http_backend *)handle;
int re, try;
re = BACKEND_ERROR;
try = 0;
while (re == BACKEND_ERROR && try <= conf->retry_count) {
try++;
re = http_post(handle, conf->superuser_uri, NULL, username, NULL, NULL, -1, METHOD_SUPERUSER);
}
return re;
};
int be_http_aclcheck(void *handle, const char *clientid, const char *username, const char *topic, int acc)
{
struct http_backend *conf = (struct http_backend *)handle;
int re, try;
re = BACKEND_ERROR;
try = 0;
while (re == BACKEND_ERROR && try <= conf->retry_count) {
try++;
re = http_post(conf, conf->aclcheck_uri, clientid, username, NULL, topic, acc, METHOD_ACLCHECK);
}
return re;
};
#endif /* BE_HTTP */
|
the_stack_data/122016809.c | #include <stdio.h>
#include <math.h>
int main()
{
double i1, i2;
double tri = 1;
int counter = 0;
double root;
i1 = 2;
while(counter < 500){
counter = 0;
tri += i1;
root = sqrt(tri);
for(i2 = 1; i2 < root; i2++){
if(!((long int)tri % (long int)i2))
counter++;
}
counter *= 2;
i1++;
}
printf("tri: %lf\n", tri);
return 0;
}
|
the_stack_data/73575750.c | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_atoi.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: tmoska <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2016/11/17 16:19:54 by tmoska #+# #+# */
/* Updated: 2016/11/17 16:19:57 by tmoska ### ########.fr */
/* */
/* ************************************************************************** */
int ft_atoi(const char *str)
{
int neg;
int res;
res = 0;
neg = 1;
while (*str == ' ' || *str == '\t' || *str == '\n' ||
*str == '\v' || *str == '\f' || *str == '\r')
str++;
if (*str == '-' || *str == '+')
{
if (*str == '-')
neg = -1;
str++;
}
while (*str >= '0' && *str <= '9')
{
res *= 10;
res += *str - 48;
str++;
}
return (res * neg);
}
|
the_stack_data/124670.c | // RUN: %clang_analyze_cc1 -analyzer-checker=core,unix -verify %s
// expected-no-diagnostics
// Testing core functionality of the SValBuilder.
int SValBuilderLogicNoCrash(int *x) {
return 3 - (int)(x +3);
}
// http://llvm.org/bugs/show_bug.cgi?id=15863
// Don't crash when mixing 'bool' and 'int' in implicit comparisons to 0.
void pr15863() {
extern int getBool();
_Bool a = getBool();
(void)!a; // no-warning
}
|
the_stack_data/162642670.c | /**ARGS: source -DFOO */
/**SYSCODE: = 2 */
#define OTHER_CLIENT_HAS_LOCK() \
(\
( isr_blk == &_buffer ) \
? (_buffer_1._status == _GRANTED) || (_buffer_1._status == _RETAINED_FOR_ACCESS) \
: (_buffer._status == _GRANTED) || (_buffer._status == _RETAINED_FOR_ACCESS) \
)
#define CHECK_NEITHER_CLIENT_HAS_LOCK() \
( (_buffer._status != _GRANTED) && \
(_buffer._status != _RETAINED_FOR_ACCESS) && \
(_buffer_1._status != _GRANTED) && \
(_buffer_1._status != _RETAINED_FOR_ACCESS) )
#define CHECK_NEITHER_CLIENT_IS_ABORTING_LOCK() \
( (_buffer._status != _ABORTING) && (_buffer_1._status != _ABORTING) )
|
the_stack_data/103136.c | /*此程序对以下形式的表达式进行求值
数字 运算符 数字*/
#include <stdio.h>
int main(void)
{
float value1, value2;
char operator;
printf("Type in your expression.\n");
scanf("%f %c %f", &value1, &operator, & value2);
switch(operator)
{
case '+':
printf("%.2f\n", value1 + value2);
break;
case '-':
printf("%.2f\n", value1 - value2);
break;
case '*':
printf("%.2f\n", value1 * value2);
break;
case '/':
if(value2 == 0)
printf("Division by zero.\n");
else
printf("%.2f\n", value1 / value2);
break;
default:
printf("Unknown operator.\n");
break;
}
return 0;
} |
the_stack_data/107953872.c | #include <stdio.h>
int main()
{
int i , num , fat;
fat = 1;
printf("Digite um numero N entre 1 e 7 para calcular seu fatorial: ");
scanf("%d" , &num);
for(int i = num ; i > 1 ; i--)
fat = fat * i;
printf("%d" , fat);
return 0;
} |
the_stack_data/231394326.c | // databased.c
// Create by 發現號(Find@TX).
// Update by Lonely
// databased.c 提供的外部函數:
//
// 通用語句:
// mixed *db_fetch_row() - 為查找一行
// mixed db_query() - 為執行語句
// mixed *db_all_query() - 查找所有行
// mixed db_crypt() - 加密字符串
// string query_db_status() - 數據庫狀態
// 用户管理:
// int db_find_user() - 查詢 ID 是否存在
// int db_create_user() - 創建新的用户
// int db_remove_user() - 刪除用户檔案
// int db_set_user() - 設定用户屬性
// int db_add_user() - 增加用户屬性
// int db_query_user() - 查詢用户屬性
// int db_count_user() - 計算用户數量
#ifdef DB_SAVE
#include <mudlib.h>
#include "/adm/etc/database.h"
#define REG_BONUS 2100
class target
{
string host;
string user;
mapping quest;
}
#ifdef STATIC_LINK
nosave int db_handle = 0;
public int query_db_handle()
{
return db_handle;
}
#endif
nosave int crc_status = 0;
protected mixed *all_target = ({});
string *do_sql(string);
int do_sqlexec(string sql);
// db_save_all() 時這裏的好幾個字段應該從 DBASE 裏分離出來單獨存儲
nosave string *cols = ({
"id", "name", "surname", "purename", "password", "ad_password",
"birthday", "online", "on_time", "fee_time", "save_time", "f_mail",
"last_from", "last_on", "last_off", "last_station", "endrgt",
"login_dbase", "char_idname", "f_autoload", "f_dbase", "f_damage",
"f_condition", "f_attack", "f_skill", "f_alias", "f_user", "f_business",
});
// 確定用户返回數據時是否校驗數據和 臨時舉措
int crc_status() { return crc_status; }
int clean_up() { return 1; }
protected void chat(string msg)
{
#ifdef DEBUG
CHANNEL_D->do_channel(this_object(), "sys", msg);
log_file("database", "chat() call : " + msg + "\n");
#endif
}
protected void init_target()
{
if (! sizeof(all_others_db))
return;
foreach (string h, string u in all_others_db)
{
class target one;
one = new(class target);
one->host = h;
one->user = u;
one->quest = ([]);
all_target += ({ one });
}
}
protected void log_error(string func, mixed err)
{
log_file("database", sprintf("%s ERROR ** %s\n%O\n", func, ctime(time()), err));
}
int query_db_status()
{
mixed ret;
#ifdef STATIC_LINK
ret = DATABASE_D->db_fetch_row("SHOW DATABASES");
if (db_handle && arrayp(ret) && sizeof(ret) > 0)
return 1;
#endif
return 0;
}
#ifdef STATIC_LINK
void connect_to_database()
#else
int connect_to_database()
#endif
{
mixed n;
n = db_connect(DB_HOST, DATABASE, DB_USER);
if (intp(n) && (n > 0)) // 連接成功
#ifdef STATIC_LINK
{
db_handle = n;
chat("已經與MySQL數據庫建立連接!連接號是:" + n);
return;
}
#else
return n;
#endif
else
{
log_error("db_connect", n);
#ifdef STATIC_LINK
// call_out("connect_to_database", 30);
return;
#endif
return 0;
}
}
protected void close_database(int db)
{
mixed ret;
db_handle = 0;
if (! intp(db) || (db < 1))
return 0;
ret = db_close(db);
if (intp(ret) && (ret == 1))
return;
else
log_error("db_close", ret);
}
protected void create()
{
seteuid(ROOT_UID);
#ifdef STATIC_LINK
connect_to_database();
set_heart_beat(1);
#endif
init_target();
crc_status = 1;
}
protected void heart_beat()
{
#ifdef STATIC_LINK
if (! query_db_status())
connect_to_database();
#endif
}
protected int valid_caller()
{
#ifdef DEBUG
return 1;
#else
if (! previous_object() ||
(previous_object() != find_object(SIMUL_EFUN_OB)))
return 0;
else
return 1;
#endif
}
// 不能增加記錄,只能修改已經有的記錄裏存在字段的合適值
int db_remove_player(string id)
{
int db;
string sql;
mixed ret;
if (! stringp(id) || id == "")
return 0;
#ifdef STATIC_LINK
if (! db_handle)
{
chat("數據庫失去連接。");
return 0;
}
db = db_handle;
#else
if (! (db = connect_to_database()))
return 0;
#endif
sql = "delete from users where id='" + id + "'";
chat("執行刪除語句!" + sql);
ret = db_exec(db, sql);
if (! intp(ret))
{
log_error("db_delete.db_exec", ret + "\n" + sql);
return 0;
}
if (ret < 1) return 0;
#ifndef STATIC_LINK
close_database(db);
#endif
return ret;
}
// 不能增加記錄,只能修改已經有的記錄裏存在字段的合適值
int db_set_player(string id, string prop, mixed value)
{
int db;
string sql;
mixed ret;
if (! stringp(id) || id == "" ||
! stringp(prop) || prop == "")
return 0;
if (member_array(prop, cols) == -1)
return 0;
#ifdef STATIC_LINK
if (! db_handle)
{
chat("數據庫失去連接。");
return 0;
}
db = db_handle;
#else
if (! (db = connect_to_database()))
return 0;
#endif
if (prop == "login_dbase" && (value == 0 ||
! stringp(value) || sizeof(value) < 2 ))
return 0;
// 對於不同類型的屬性應該有不同的設置手段,分整型,MAPP,數組
if (intp(value))
sql = "update users set " + prop + "=" + value + " where id = '" + id + "'";
else if (mapp(value) || arrayp(value))
sql = "update users set " + prop + "=" + DB_STR(save_variable(value)) + " where id = '" + id + "'";
else if (stringp(value))
sql = "update users set " + prop + "=" + DB_STR(value) + " where id = '" + id + "'";
else
{
chat("數據庫函數db_set的參數value類型不可識別!");
return 0;
}
ret = db_exec(db, sql);
if (! intp(ret))
{
log_error("db_set.db_exec", ret + "\n" + sql);
return 0;
}
if (ret < 1) return 0;
#ifndef STATIC_LINK
close_database(db);
#endif
return ret;
}
mixed db_query_player(string id, string prop)
{
int db;
string sql,*res;
mixed ret;
if (! stringp(id) || id == "" ||
! stringp(prop) || prop == "")
return 0;
if (member_array(prop, cols) == -1 &&
prop != "count(*)")
return 0;
#ifdef STATIC_LINK
if (! db_handle)
{
chat("數據庫失去連接。");
return 0;
}
db = db_handle;
#else
if (! (db = connect_to_database()))
return 0;
#endif
sql = "select " + prop + " from users where id='" + id + "'";
ret = db_exec(db, sql);
if (! intp(ret))
{
log_error("db_query.db_exec", ret);
return 0;
}
if (ret < 1) return 0;
res = db_fetch(db, 1);
#ifndef STATIC_LINK
close_database(db);
#endif
chat("查詢" + id + "的" + prop + "屬性字段值。返回:" + save_variable(res[0]));
return res[0];
}
int db_new_player(object ob, object user)
{
int db,n;
string sql;
mixed ret;
mapping my, myob;
if (! objectp(ob) || ! objectp(user))
return 0;
myob = ob->query_entire_dbase();
my = user->query_entire_dbase();
if (! stringp(my["id"]) || (my["id"] == "") ||
! stringp(my["name"]) || (my["name"] == ""))
{
chat("存儲字段ID或NAME為空,拒絕存儲。");
return -1;
}
#ifdef STATIC_LINK
if (! db_handle)
{
chat("數據庫失去連接。");
return -1;
}
db = db_handle;
#else
if (! (db = connect_to_database()))
return -1;
#endif
// 不判斷數據庫裏是否已經有該項記錄
// fee_time不在這裏做修改,故不存儲了
sql = "insert into users set id = '" + my["id"] + "',";
sql += "name = " + DB_STR(my["name"]) + ", surname = " +
DB_STR(myob["surname"]) + ", purename = " +
DB_STR(myob["purename"]) + ", password = " +
DB_STR(myob["password"]) + ", ad_password = " +
DB_STR(myob["ad_password"]);
sql += ", birthday = now(), online = 1, on_time = 0, fee_time = " + REG_BONUS;
sql += ", login_dbase = " + DB_STR(save_variable(myob));
sql += ", f_dbase = " + DB_STR(save_variable(my));
chat("請求數據庫創建帳號!\n");
ret = db_exec(db, sql);
if(!intp(ret))
{
chat("數據庫存儲失敗!!!");
log_error(sprintf("db_new_player(%s).db_exec", my["id"]), ret);
return -1;
}
n = db_affected(db);
#ifndef STATIC_LINK
close_database(db);
#endif
return n;
}
int db_restore_all(object user)
{
int db, n;
string sql, *res;
mixed ret;
mapping my;
object myob;
myob=query_temp("link_ob", user);
my = user->query_entire_dbase();
if (! mapp(my) || ! stringp(my["id"]) || (my["id"] == "") ||
! stringp(my["name"]) || (my["name"] == ""))
{
chat("存儲字段ID或NAME為空,拒絕存儲。");
return -1;
}
#ifdef STATIC_LINK
if (! db_handle)
{
chat("數據庫失去連接。");
return -1;
}
db = db_handle;
#else
if (! (db = connect_to_database()))
return -1;
#endif
sql = "select login_dbase, f_autoload, f_dbase, f_damage, f_condition, f_business, f_mail, " +
"f_attack, f_skill, f_alias, f_user, char_idname from users where id = '" + my["id"] + "'";
ret = db_exec(db, sql);
if (! intp(ret))
{
chat("數據庫存儲失敗!!!");
log_error(sprintf("db_restore_all(%s).db_exec",my["id"]),ret);
return -1;
}
if (ret < 1) return 0;
res = db_fetch(db, 1);
if(sizeof(res) < 1)
n = 0;
else
{
string login_dbase, char_idname, f_autoload, f_dbase, f_damage, f_mail;
string f_condition, f_attack, f_skill, f_alias, f_user, f_business;
n = 0;
login_dbase = res[n];
f_autoload = res[n + 1];
f_dbase = res[n + 2];
//f_dbase = replace_string(f_dbase, "\\n", "\\"+"\\n"); // Added by Lonely 2011/6/10
f_damage = res[n + 3];
f_condition = res[n + 4];
f_business = res[n + 5];
f_mail = res[n + 6];
f_attack = res[n + 7];
f_skill = res[n + 8];
f_alias = res[n + 9];
f_user = res[n + 10];
char_idname = res[n + 11];
user->set_dbase(restore_variable(f_dbase));
user->set_autoload_info(restore_variable(f_autoload));
user->set_CONDITION(restore_variable(f_condition));
user->set_business(restore_variable(f_business));
user->set_mail(restore_variable(f_mail));
user->set_ALIAS(restore_variable(f_alias));
user->set_ATTACK(restore_variable(f_attack));
user->set_ghost(restore_variable(f_damage));
user->set_SKILL(restore_variable(f_skill));
user->set_USER(restore_variable(f_user));
user->set_IDNAME(restore_variable(char_idname));
if (objectp(myob)) myob->set_dbase(restore_variable(login_dbase));
n = 1;
}
#ifndef STATIC_LINK
close_database(db);
#endif
return n;
}
int db_save_all(object user)
{
int db, n;
string sql;
mixed ret;
mapping my, myob;
object link_ob=query_temp("link_ob", user);
if (objectp(link_ob))
myob = link_ob->query_entire_dbase();
my = user->query_entire_dbase();
if (! stringp(my["id"]) || (my["id"] == "") ||
! stringp(my["name"]) || (my["name"] == ""))
{
chat("存儲字段ID或NAME為空,拒絕存儲。");
return -1;
}
#ifdef STATIC_LINK
if (! db_handle)
{
chat("數據庫失去連接。");
return -1;
}
db = db_handle;
#else
if (! (db = connect_to_database()))
return -1;
#endif
// 不判斷數據庫裏是否已經有該項記錄
// fee_time不在這裏做修改,故不存儲了
sql = "update users set ";
sql += "name = " + DB_STR(my["name"]);
if (objectp(link_ob) && mapp(myob))
{
if (sizeof(myob["password"]))
sql += ", password=" + DB_STR(myob["password"]);
if (sizeof(myob["ad_password"]))
sql += ", ad_password = " + DB_STR(myob["ad_password"]);
sql += ", login_dbase = " + DB_STR(save_variable(myob));
}
if (my["on_time"] > 0) // 認為已經挪移到on_time計費了
sql += ", online = 1, on_time = " + my["on_time"] + ", save_time = now()";
else
{
sql += ", online = 1, on_time = " + my["mud_age"] + ", save_time = now()";
// my["on_time"] = my["mud_age"]; 因為要重新計算sec_id,所以這裏不能這樣做
}
sql += ", char_idname = " + DB_STR(save_variable(user->query_IDNAME()));
sql += ", f_autoload = " + DB_STR(save_variable(user->query_autoload_info()));
sql += ", f_dbase = " + DB_STR(save_variable(my));
sql += ", f_damage = " + DB_STR(save_variable(user->is_ghost()));
sql += ", f_condition = " + DB_STR(save_variable(user->query_CONDITION()));
sql += ", f_business = " + DB_STR(save_variable(user->query_business()));
sql += ", f_mail = " + DB_STR(save_variable(user->query_mail()));
sql += ", f_attack = " + DB_STR(save_variable(user->query_ATTACK()));
sql += ", f_skill = " + DB_STR(save_variable(user->query_SKILL()));
sql += ", f_alias = " + DB_STR(save_variable(user->query_all_alias()));
sql += ", f_user = " + DB_STR(save_variable(user->query_USER()));
sql += " where id = '" + my["id"] + "'";
ret = db_exec(db, sql);
if (! intp(ret))
{
chat("數據庫存儲失敗!!!" + sql);
log_error(sprintf("db_save_all(%s).db_exec", my["id"]), ret);
return -1;
}
n = db_affected(db);
#ifndef STATIC_LINK
close_database(db);
#endif
return n;
}
string *do_sql(string sql)
{
int db;
string *res;
mixed ret;
#ifdef STATIC_LINK
if (! db_handle)
{
chat("數據庫失去連接。");
return 0;
}
db = db_handle;
#else
if (! (db = connect_to_database()))
return 0;
#endif
ret = db_exec(db,sql);
if (! intp(ret))
{
log_error("do_sql.db_exec", ret);
return 0;
}
if (ret == 0) return 0;
//只返回首行
res = db_fetch(db, 1);
#ifndef STATIC_LINK
close_database(db);
#endif
return res;
}
int do_sqlexec(string sql)
{
int db;
int ret;
#ifdef STATIC_LINK
if (! db_handle)
{
chat("數據庫失去連接。");
return -2;
}
db = db_handle;
#else
if (! (db = connect_to_database()))
return -2;
#endif
if(!intp(db_exec(db,sql)))
ret = -1;
else
ret = db_affected(db);
#ifndef STATIC_LINK
close_database(db);
#endif
return ret;
}
mixed *do_sqls(string sql)
{
int db;
mixed res = ({}), tmp;
mixed ret;
#ifdef STATIC_LINK
if (! db_handle)
{
chat("數據庫失去連接。");
return 0;
}
db = db_handle;
#else
if (! (db = connect_to_database()))
return 0;
#endif
ret = db_exec(db, sql);
if (! intp(ret))
{
log_error("do_sql.db_exec", ret);
return 0;
}
if (ret == 0) return 0;
//要返回所有行
//res = allocate(ret);
for (int i = 0; i < ret; i++)
{
tmp = db_fetch(db, i + 1);
res += ({ tmp });
}
#ifndef STATIC_LINK
close_database(db);
#endif
return res;
}
// 查詢 ID 是否存在
int db_find_user(string key, mixed data)
{
int db;
mixed ret;
string sql;
if (! stringp(key) || key == "" || ! data)
return 0;
#ifdef STATIC_LINK
if (! db_handle)
return 0;
db = db_handle;
#else
if (! (db = connect_to_database()))
return 0;
#endif
if (intp(data))
sql = sprintf("SELECT id FROM %s WHERE %s = %s",
USER_TABLE, key, data);
else if (stringp(data))
sql = sprintf("SELECT id FROM %s WHERE %s = \"%s\"",
USER_TABLE, key, data);
else sql = sprintf("SELECT id FROM %s WHERE %s = %O",
USER_TABLE, key, data);
ret = db_exec(db, sql);
#ifndef STATIC_LINK
close_database(db);
#endif
if (! intp(ret))
{
log_error("db_find_user.db_exec", ret);
return 0;
}
return ret;
}
// 創建新的用户
int db_create_user(string id)
{
int db;
mixed ret;
string sql;
if (! stringp(id) || id == "")
return 0;
#ifdef STATIC_LINK
if (! db_handle)
return 0;
db = db_handle;
#else
if (! (db = connect_to_database()))
return 0;
#endif
sql = sprintf("INSERT INTO %s SET id = \"%s\"",
USER_TABLE, id);
ret = db_exec(db, sql);
#ifndef STATIC_LINK
close_database(db);
#endif
if (! intp(ret))
{
log_error("db_create_user.db_exec", ret);
return 0;
}
return ret;
}
// 刪除用户
int db_remove_user(string id)
{
int db, n;
mixed ret;
string sql;
if (! stringp(id) || id == "")
return 0;
#ifdef STATIC_LINK
if (! db_handle)
return 0;
db = db_handle;
#else
if (! (db = connect_to_database()))
return 0;
#endif
sql = sprintf("DELETE FROM %s WHERE id = \"%s\"",
USER_TABLE, id);
ret = db_exec(db, sql);
if (! intp(ret))
{
log_error(sprintf("db_romove_user(%s).db_exec", id), ret);
return 0;
}
n = db_affected(db);
if (n < 1)
log_error(sprintf("db_romove_user(%s).db_exec", id), "Fail to del.\n");
#ifndef STATIC_LINK
close_database(db);
#endif
return n;
}
// 設定用户屬性
int db_set_user(string id, string key, mixed data)
{
int db, n;
mixed ret;
string sql;
if (! stringp(id) || id == "" ||
! stringp(key) || key == "")
return 0;
#ifdef STATIC_LINK
if (! db_handle)
return 0;
db = db_handle;
#else
if (! (db = connect_to_database()))
return 0;
#endif
if (intp(data))
sql = sprintf("UPDATE %s SET %s = %d WHERE id = \"%s\"",
USER_TABLE, key, data, id);
else if (stringp(data))
sql = sprintf("UPDATE %s SET %s = \"%s\" WHERE id = \"%s\"",
USER_TABLE, key, data, id);
else sql = sprintf("UPDATE %s SET %s = %O WHERE id = \"%s\"",
USER_TABLE, key, data, id);
ret = db_exec(db, sql);
if (! intp(ret))
{
log_error(sprintf("db_set_user(%s).db_exec", id), ret);
return 0;
}
n = db_affected(db);
#ifndef STATIC_LINK
close_database(db);
#endif
return n;
}
// 增加用户屬性點
int db_add_user(string id, string key, int num)
{
int db, n;
mixed ret;
string sql;
if (! stringp(id) || id == "" ||
! stringp(key) || key == "" ||
! intp(num) || ! num)
return 0;
#ifdef STATIC_LINK
if (! db_handle)
return 0;
db = db_handle;
#else
if (! (db = connect_to_database()))
return 0;
#endif
sql = sprintf("UPDATE %s SET %s = %s + %d WHERE id = \"%s\"",
USER_TABLE, key, key, num, id);
ret = db_exec(db, sql);
if (! intp(ret))
log_error("db_add_user.db_exec", ret);
n = db_affected(db);
if (n < 1)
{
log_error(sprintf("db_set_user(%s).db_exec", id), "Fail to del.\n");
return 0;
}
#ifndef STATIC_LINK
close_database(db);
#endif
return n;
}
// 查詢用户屬性
mixed db_query_user(string id, string key)
{
int db;
mixed ret, *res;
string sql;
if (! stringp(id) || id == "" ||
! stringp(key) || key == "")
return 0;
#ifdef STATIC_LINK
if (! db_handle)
return 0;
db = db_handle;
#else
if (! (db = connect_to_database()))
return 0;
#endif
sql = sprintf("SELECT %s FROM %s WHERE id = \"%s\"",
key, USER_TABLE, id);
ret = db_exec(db, sql);
#ifndef STATIC_LINK
close_database(db);
#endif
if (! intp(ret))
{
log_error("db_query_user.db_exec", ret);
return 0;
}
if (ret > 0)
{
res = db_fetch(db, 1);
return res[0];
}
else
return 0;
}
// 加密函數
mixed db_crypt(string passwd)
{
int db;
mixed res, ret;
string sql;
if (! stringp(passwd) || passwd == "")
return 0;
#ifdef STATIC_LINK
if (! db_handle)
return 0;
db = db_handle;
#else
if (! (db = connect_to_database()))
return 0;
#endif
sql = sprintf("SELECT %s(\"%s\")",
DB_CRYPT, passwd);
ret = db_exec(db, sql);
if (ret)
{
if (sizeof(res = db_fetch(db, 1)) && stringp(res[0]))
ret = res[0];
else
return 0;
}
#ifndef STATIC_LINK
close_database(db);
#endif
return ret;
}
// 查找一行
varargs mixed *db_fetch_row(string sql, int row)
{
int db;
mixed ret;
if (! stringp(sql) || sql == "")
return 0;
#ifdef STATIC_LINK
if (! db_handle)
return 0;
db = db_handle;
#else
if (! (db = connect_to_database()))
return 0;
#endif
if (stringp(sql) && sql != "")
{
db_exec(db, sql);
}
if (! row) row = 1;
ret = db_fetch(db, row);
#ifndef STATIC_LINK
close_database(db);
#endif
return ret;
}
// 執行 SQL 指令
varargs mixed do_exec(string sql)
{
int db;
mixed ret;
if (! stringp(sql) || sql == "")
return 0;
#ifdef STATIC_LINK
if (! db_handle)
return 0;
db = db_handle;
#else
if (! (db = connect_to_database()))
return 0;
#endif
ret = db_exec(db, sql);
#ifndef STATIC_LINK
close_database(db);
#endif
return ret;
}
// 執行語句
mixed db_query(string sql)
{
int db;
mixed ret;
if (! stringp(sql) || sql == "")
return 0;
#ifdef STATIC_LINK
if (! db_handle)
return 0;
db = db_handle;
#else
if (! (db = connect_to_database()))
return 0;
#endif
ret = db_exec(db, sql);
if (! intp(ret))
ret = 0;
else
ret = db_affected(db);
#ifndef STATIC_LINK
close_database(db);
#endif
return ret;
}
// 查找所有行
mixed *db_all_query(string sql)
{
int db, i;
mixed max, ret;
if (! stringp(sql) || sql == "")
return 0;
#ifdef STATIC_LINK
if (! db_handle)
return 0;
db = db_handle;
#else
if (! (db = connect_to_database()))
return 0;
#endif
max = db_exec(db, sql);
if (intp(max) && max != 0)
{
ret = ({ });
for (i = 1; i <= max; i++)
ret += ({ db_fetch(db, i) });
}
#ifndef STATIC_LINK
close_database(db);
#endif
return ret;
}
// 計算玩家數量
int db_count_user()
{
int db;
mixed ret, res;
#ifdef STATIC_LINK
if (! db_handle)
return 0;
db = db_handle;
#else
if (! (db = connect_to_database()))
return 0;
#endif
ret = db_exec(db, sprintf("SELECT COUNT(*) FROM %s", USER_TABLE));
//ret = db_exec(db, sprintf("SELECT MAX(id) FROM %s", USER_TABLE));
if (! intp(ret) || (ret < 1))
{
log_error("count_reg_user", ret);
return 0;
}
res = db_fetch(db, 1);
#ifndef STATIC_LINK
close_database(db);
#endif
return res[0];
}
#ifdef STATIC_LINK
void remove(string id)
{
close_database(db_handle);
}
#endif
// by Lonely
int db_remove_item(string id)
{
int db;
string sql;
mixed ret;
if (! stringp(id) || id == "")
return 0;
sscanf(id, "%s.c", id);
#ifdef STATIC_LINK
if (! db_handle)
{
chat("數據庫失去連接。");
return 0;
}
db = db_handle;
#else
if (! (db = connect_to_database()))
return 0;
#endif
sql = "delete from items where id='" + id + "'";
chat("執行刪除語句!" + sql);
ret = db_exec(db, sql);
if (! intp(ret))
{
log_error("db_remove_item.db_exec", ret + "\n" + sql);
return 0;
}
if (ret < 1) return 0;
#ifndef STATIC_LINK
close_database(db);
#endif
return ret;
}
mixed db_restore_item(mixed ob)
{
int db;
string sql, *res;
string index;
mixed ret;
mapping data;
#ifdef STATIC_LINK
if (! db_handle)
{
chat("數據庫失去連接。");
return 0;
}
db = db_handle;
#else
if (! (db = connect_to_database()))
return 0;
#endif
if( !ob ) return 0;
if( stringp(ob) )
{
index = ob;
sscanf(index, "%s.c", index);
}
else if( objectp(ob) )
index = base_name(ob);
else
return 0;
sql = "select dbase from items where id = '" + index + "'";
ret = db_exec(db, sql);
if (! intp(ret))
{
chat("數據庫存儲失敗!!!");
log_error(sprintf("db_restore_item(%s).db_exec", index), ret);
return 0;
}
if (ret < 1) return 0;
res = db_fetch(db, 1);
if (mapp(restore_variable(res[0])))
data = restore_variable(res[0]);
else
data = ([]);
#ifndef STATIC_LINK
close_database(db);
#endif
return data;
}
int db_create_item(mixed ob, mixed data)
{
int db, n;
string sql;
string index;
mixed ret;
#ifdef STATIC_LINK
if (! db_handle)
{
chat("數據庫失去連接。");
return -1;
}
db = db_handle;
#else
if (! (db = connect_to_database()))
return -1;
#endif
if( !ob ) return 0;
if( stringp(ob) )
{
index = ob;
sscanf(index, "%s.c", index);
}
else if( objectp(ob) )
index = base_name(ob);
else
return 0;
sql = "insert into items set id = '" + index +
"', dbase = " + DB_STR(save_variable(data));
ret = db_exec(db, sql);
if (! intp(ret))
{
chat("數據庫存儲失敗!!!" + sql);
log_error(sprintf("db_create_item(%s).db_exec", index), ret);
return -1;
}
n = db_affected(db);
#ifndef STATIC_LINK
close_database(db);
#endif
return n;
}
int db_save_item(mixed ob, mixed data)
{
int db, n;
string sql;
string index;
mixed ret;
#ifdef STATIC_LINK
if (! db_handle)
{
chat("數據庫失去連接。");
return -1;
}
db = db_handle;
#else
if (! (db = connect_to_database()))
return -1;
#endif
if( !ob ) return 0;
if( stringp(ob) )
{
index = ob;
sscanf(index, "%s.c", index);
}
else if( objectp(ob) )
index = base_name(ob);
else
return 0;
/*
sql = "select dbase from items where id = '" + index + "'";
ret = db_exec(db, sql);
if (! intp(ret))
sql = "insert into items set id = '" + index +
"', dbase = " + DB_STR(save_variable(data));
else
*/
sql = "update items set dbase = " + DB_STR(save_variable(data)) +
" where id = '" + index + "'";
ret = db_exec(db, sql);
if (! intp(ret))
{
chat("數據庫存儲失敗!!!" + sql);
log_error(sprintf("db_save_item(%s).db_exec", index), ret);
return -1;
}
n = db_affected(db);
#ifndef STATIC_LINK
close_database(db);
#endif
return n;
}
string query_name()
{
return "MySQL數據庫(DATABASE_D)";
}
#endif
|
the_stack_data/168894296.c | /*Programmer Chase Singhofen
Date 10/8/16
Specifications: Ask the user to enter test scores.
When they have entered all the tests scores,
they will enter the value of -1. The Program
will sum up all the scores entered, and output sum.
70, 80, 90, -1. Expected 240*/
#include<stdio.h>
#include<stdlib.h>
main() {
double score, sum = 0, grade = 0, gradeNum = 0, avg = 0, pass = 0, totalGrades = 0;
printf("Enter a test score(-1 to quit):");
scanf_s("%.2lf", &grade);
while (grade != -1)
{
if (grade <= 100 && grade >= 70) {
pass++;
printf("Pass: %.2lf\n", pass);
}
if (grade > 100 || grade <0) {
printf("Error, grade is not in grade range\n");
}
if (grade >= 0 && grade <= 100) {
totalGrades++;
}
printf("Enter a test score(-1 to quit):");
scanf_s("%.2lf", &grade);
}
avg = 100 * pass / totalGrades;
printf("\nThe avg of the scores is : %.2lf\n", avg);
system("pause");
} |
the_stack_data/126703035.c | #include<stdio.h>
int main(int argc, char **argv , char **env) // main function syntax
{
int i=0;
printf("\n cmdline args count=%d",argc); //argc count the number of argument given in shell including executable file to
/* first argument in executable name only*/
printf("\n name =%s",*argv); //*argv is shows first argument argv[0];
for(i=1;i<argc;i++)
printf("\n arg %d = %s",i,argv[i]);
i=0;
while(*env!=NULL) //*env is a pointer variable which point to shell environment variable
{
i++;
printf("\n env var %d => %s",i,*(env++));
}
printf("\n");
return 0;
}
|
the_stack_data/61396.c | #define _GNU_SOURCE
#include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
int hexdump(char* dest, int dest_off, char* src, int src_off, int size) {
char* d = dest + dest_off;
int di = 0;
for (int si = src_off; si < src_off + size; si++) {
if (si != src_off) {
d[0] = ' ';
d += 1;
di += 1;
}
sprintf(d, "%02X", src[si]);
d += 2;
di += 2;
}
d[0] = '\0';
return di;
}
int main(int argc, char* argv[]) {
if (argc != 3) {
fprintf(stderr, "usage: %s ip port\n", argv[0]);
exit(-1);
}
const char* ip = argv[1];
int port = atoi(argv[2]);
int sockfd;
if ((sockfd = socket(PF_INET, SOCK_STREAM, 0)) < 0) {
fprintf(stderr, "create socket fd failed, msg: %s\n", strerror(errno));
exit(-1);
}
int reuse = 1;
setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse));
struct sockaddr_in addr;
bzero(&addr, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
inet_pton(AF_INET, ip, &addr.sin_addr);
if (bind(sockfd, (struct sockaddr*)&addr, sizeof(addr)) == -1) {
fprintf(stderr, "bind failed, msg: %s\n", strerror(errno));
close(sockfd);
exit(-1);
}
if ((listen(sockfd, 5)) == -1) {
fprintf(stderr, "listen failed, msg: %s\n", strerror(errno));
close(sockfd);
exit(-1);
}
for (;;) {
printf("waiting for connection\n");
struct sockaddr_in client;
socklen_t client_addr_length = sizeof(client);
int connfd;
if ((connfd = accept(sockfd, (struct sockaddr*)&client,
&client_addr_length)) < 0) {
fprintf(stderr, "accept failed, msg: %s\n", strerror(errno));
close(sockfd);
exit(-1);
}
printf("accepted connection\n");
char buf[4096];
char pb[4096 * 3];
for (;;) {
int read = recv(connfd, buf, 4096, 0);
int hlen = hexdump(pb, 0, buf, 0, read);
printf("recv %d bytes:%.*s\n", read, hlen, pb);
if (!read) {
break;
}
if (send(connfd, buf, read, 0) != read) {
fprintf(stderr, "send failed, msg: %s\n", strerror(errno));
close(connfd);
close(sockfd);
exit(-1);
}
}
close(connfd);
printf("connection closed\n");
}
close(sockfd);
printf("program exited");
exit(0);
}
|
the_stack_data/80558.c | #include<stdio.h>
#include<stdlib.h>
struct Node {
int data;
struct Node *next;
}*first = NULL;
void create(int array[], int n) {
int i;
struct Node *t, *last;
first = (struct Node *)malloc(sizeof(struct Node));
first->data = array[0];
first->next = NULL;
last = first;
for (i=1; i<n; i++) {
t = (struct Node *)malloc(sizeof(struct Node));
t->data = array[i];
t->next = NULL;
last->next = t;
last = t;
}
}
void display(struct Node *p) {
while (p != NULL) {
printf("%d ", p->data);
p = p->next;
}
}
void insertSorted(struct Node *p, int x) {
struct Node *t, *q;
t = (struct Node *)malloc(sizeof(struct Node));
t->data = x;
t->next = NULL;
if (first == NULL)
t = first;
else {
while (p && p->data < x) {
q = p;
p = p->next;
}
if (p == first) {
t->next = first;
first = t;
}
else {
t->next = q->next;
q->next = t;
}
}
}
int main() {
int array[5] = {1,3,5,7,9};
create(array, 5);
printf("Displaying linked list:\n");
display(first);
insertSorted(first, 12);
printf("\n");
display(first);
return 0;
}
|
the_stack_data/93887016.c | main()
{
int a[100],prod=1,n,i,j;
scanf("%d",&n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
for(j=0;j<n;j++)
{
if(a[j]>=0)
{
printf("%d ",a[j]);
prod*=a[j];
}
}
printf("\nProduct=%d",prod);
}
|
the_stack_data/145453986.c | #include <stdio.h>
int main(){
int n;
printf("\n=======================PROGRAMA PARA SABER O TRIMESTRE==========================\n");
printf("\nEm qual mês você está? Informe de (1 a 12);\n");
printf("1.Janeiro\n");
printf("2.Fevereiro\n");
printf("3.Março\n");
printf("4.Abril\n");
printf("5.Maio\n");
printf("6.Junho\n");
printf("7.Julho\n");
printf("8.Agosto\n");
printf("9.Setembro\n");
printf("10.Outubro\n");
printf("11.Novembro\n");
printf("12.Dezembro\n\n");
scanf("%d", &n);
switch(n)
{
case 1:
case 2:
case 3:
printf("\nVocê está no 1º Trimestre!");
break;
case 4:
case 5:
case 6:
printf("\nVocê está no 2º Trimestre!");
break;
case 7:
case 8:
case 9:
printf("\nVocê está no 3º Trimestre!");
break;
case 10:
case 11:
case 12:
printf("\nVocê está no 4º Trimestre!");
break;
default:
printf("\nEsta opção não existe!");
}
return 0;
}
|
the_stack_data/211080186.c | /*
* Copyright (c) 1983, 1993
* The Regents of the University of California. All rights reserved.
*
* %sccs.include.redist.c%
*/
#ifndef lint
static char sccsid[] = "@(#)hertz.c 8.1 (Berkeley) 06/06/93";
#endif /* not lint */
#include <sys/time.h>
/*
* discover the tick frequency of the machine
* if something goes wrong, we return 0, an impossible hertz.
*/
#define HZ_WRONG 0
hertz()
{
struct itimerval tim;
tim.it_interval.tv_sec = 0;
tim.it_interval.tv_usec = 1;
tim.it_value.tv_sec = 0;
tim.it_value.tv_usec = 0;
setitimer(ITIMER_REAL, &tim, 0);
setitimer(ITIMER_REAL, 0, &tim);
if (tim.it_interval.tv_usec < 2)
return(HZ_WRONG);
return (1000000 / tim.it_interval.tv_usec);
}
|
the_stack_data/154830342.c | /*
* Copy me if you can.
* by 20h
*/
#define _BSD_SOURCE
#include <ifaddrs.h>
#include <netdb.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include <strings.h>
#include <sys/time.h>
#include <time.h>
#include <sys/statvfs.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <X11/Xlib.h>
#define DELAY 5
#define GB 1073741824
#define IF_NAME "wlp0s20f3"
static Display *dpy;
char *
smprintf(char *fmt, ...)
{
va_list fmtargs;
char *ret;
int len;
va_start(fmtargs, fmt);
len = vsnprintf(NULL, 0, fmt, fmtargs);
va_end(fmtargs);
ret = malloc(++len);
if (ret == NULL) {
perror("malloc");
exit(1);
}
va_start(fmtargs, fmt);
vsnprintf(ret, len, fmt, fmtargs);
va_end(fmtargs);
return ret;
}
char *
mktimes(char *fmt)
{
char buf[129];
time_t tim;
struct tm *timtm;
tim = time(NULL);
timtm = localtime(&tim);
if (timtm == NULL)
return smprintf("");
if (!strftime(buf, sizeof(buf)-1, fmt, timtm)) {
fprintf(stderr, "strftime == 0\n");
return smprintf("");
}
return smprintf("%s", buf);
}
void
setstatus(char *str)
{
XStoreName(dpy, DefaultRootWindow(dpy), str);
XSync(dpy, False);
}
char *
loadavg(void)
{
double avgs[1];
if (getloadavg(avgs, 1) < 0)
return smprintf("");
return smprintf("%.2f", avgs[0]);
}
char *
readfile(char *base, char *file)
{
char *path, line[513];
FILE *fd;
memset(line, 0, sizeof(line));
path = smprintf("%s/%s", base, file);
fd = fopen(path, "r");
free(path);
if (fd == NULL)
return NULL;
if (fgets(line, sizeof(line)-1, fd) == NULL)
return NULL;
fclose(fd);
return smprintf("%s", line);
}
char *
getbattery(char *base)
{
char *co;
int capacity;
char status;
int wattage;
if ((co = readfile(base, "capacity")) == NULL) {
return smprintf("");
}
sscanf(co, "%d", &capacity);
free(co);
if ((co = readfile(base, "status")) == NULL) {
return smprintf("");
}
sscanf(co, "%c", &status);
free(co);
if ((co = readfile(base, "power_now")) == NULL) {
return smprintf("");
}
sscanf(co, "%d", &wattage);
free(co);
return smprintf("%c %d%% (%.1fW)", status, capacity, (double)wattage/1000000.0);
}
char *
freespace(void)
{
struct statvfs vfs;
if (statvfs("/", &vfs) < 0) {
perror("statvfs");
exit(1);
}
return smprintf("%.2f GB", (double)(vfs.f_bfree * vfs.f_bsize) / GB);
}
char *
gettemperature(char *base, char *sensor)
{
char *co;
int temp;
co = readfile(base, sensor);
if (co == NULL)
return smprintf("");
sscanf(co, "%d", &temp);
free(co);
return smprintf("%02.0f°C", (double)temp / 1000);
}
char *
ipaddr(void)
{
struct ifaddrs *ifaddr, *ifa;
char host[NI_MAXHOST] = "NULL";
if (getifaddrs(&ifaddr) == -1) {
perror("getifaddrs");
exit(1);
}
for (ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next) {
if (strcmp(ifa->ifa_name, IF_NAME) != 0 ||
ifa->ifa_addr->sa_family != AF_INET)
continue;
if (getnameinfo(ifa->ifa_addr, sizeof(struct sockaddr_in),
host, NI_MAXHOST, NULL, 0,
NI_NUMERICHOST) != 0) {
perror("getnameinfo");
exit(1);
}
}
freeifaddrs(ifaddr);
return smprintf("%s: %s", IF_NAME, host);
}
int
main(void)
{
char *status;
char *avgs;
char *bat;
char *space;
char *time;
char *temp0;
char *wifi;
if (!(dpy = XOpenDisplay(NULL))) {
fprintf(stderr, "dwmstatus: cannot open display.\n");
return 1;
}
for (;;sleep(DELAY)) {
avgs = loadavg();
bat = getbattery("/sys/class/power_supply/BAT0");
time = mktimes("%m-%d %I:%M %p");
temp0 = gettemperature("/sys/class/hwmon/hwmon0", "temp1_input");
space = freespace();
wifi = ipaddr();
status = smprintf("%s | %s | %s | %s | %s | %s",
wifi, temp0, avgs, space, bat, time);
setstatus(status);
free(temp0);
free(avgs);
free(bat);
free(space);
free(time);
free(status);
free(wifi);
}
XCloseDisplay(dpy);
return 0;
}
|
the_stack_data/47758.c | /* PR c/54559 */
typedef double _Complex T;
T
foo (double x, double y)
{
return x + y * (T) (__extension__ 1.0iF);
}
|
the_stack_data/76700328.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.
*/
#include <stdio.h>
int main() {
fputc('a', stdout);
fputc('\n', stdout);
}
|
the_stack_data/770015.c | #include <stdio.h>
#include <stdlib.h>
#include <setjmp.h>
static void f1(int, int, int, int);
static void f2(void);
static jmp_buf jmpbuffer;
static int globval;
int main(void) {
int autoval;
register int regival;
volatile int volaval;
static int statval;
globval = 1; autoval = 2; regival = 3; volaval = 4; statval = 5;
if (setjmp(jmpbuffer) != 0) {
puts("after longjmp:");
printf("global = %d, autoval = %d, regival = %d,"
" volaval = %d, statval = %d\n", globval, autoval,
regival, volaval, statval);
exit(0);
}
globval = 95; autoval = 96; regival = 97; volaval = 98;
statval = 99;
f1(autoval, regival, volaval, statval);
exit(0);
}
static void f1(int i, int j, int k, int l) {
puts("in f1()");
printf("global = %d, autoval = %d, regival = %d,"
" volaval = %d, statval = %d\n", globval, i, j, k, l);
f2();
}
static void f2(void) {
longjmp(jmpbuffer, 1);
}
|
the_stack_data/790553.c | // Written by Aravind Reddy V
// Communicate between two machines using sockets.
// ಠ_ಠ
#include <sys/types.h>
#include <sys/socket.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#define PORT 8085
void pex(const char* message) {
// print error and exit.
perror(message);
exit(EXIT_FAILURE);
}
int create_socket(char* server_addr) {
int sockfd;
if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
perror("Error creating socket.");
exit(EXIT_FAILURE);
}
struct sockaddr_in server_address;
memset(&server_address, '0', sizeof(server_address));
server_address.sin_family = AF_INET;
server_address.sin_port = htons(PORT);
if(inet_pton(AF_INET, server_addr, &server_address.sin_addr)<=0) {
perror("\nInvalid address/ Address not supported \n");
exit(EXIT_FAILURE);
}
if (connect(sockfd, (struct sockaddr *)&server_address, sizeof(server_address)) < 0) {
perror("\nConnection Failed \n");
exit(EXIT_FAILURE);
}
return sockfd;
}
int main(int argc, char* argv[]) {
int sockfd;
sockfd = create_socket(argv[1]);
char message_buffer[1028]; // extra 4 bytes
memset(message_buffer, 0, sizeof(message_buffer));
scanf("%s", message_buffer);
if(send(sockfd, message_buffer, strlen(message_buffer) * sizeof(char), 0) == -1) pex("Error transmitting to server.");
memset(message_buffer, 0, sizeof(message_buffer));
if(recv(sockfd, message_buffer, 1024 * sizeof(char), 0) == -1) pex("Error recieving from server.");
printf("From server: %s\n", message_buffer);
}
|
the_stack_data/243894320.c | #include <stdio.h>
void main()
{
int index, sum, t;
char num[1000];
printf("Input an integer: \n");
scanf("%s", num);
sum = index = 0;
while (num[index] != '\0')
{
t = num[index] - '0';
sum = sum + t;
index++;
}
printf("Sum of digits of %s = %d\n", num, sum);
}
|
the_stack_data/125141444.c | #include<stdio.h>
int main()
{
int a,b,x;
scanf("%d%d%d",&x,&a,&b);
if(a+b<=x)
{
printf("Farei hoje!\n");
}
else
{
printf("Deixa para amanha!\n");
}
return 0;
}
|
the_stack_data/699526.c | #include <stdio.h>
#include <stdlib.h>
int main()
{
double income;
int select, dependents = 0, children = 0, deduction = 0;
double tax = 0;
printf("Enter your annual income: ");
scanf("%lf", &income);
if (income < 9350)
{
printf("0\n");
exit(0);
}
printf("What is your filing status? \n1) single\n2) married filing jointly\n3) married filing separately\nPlease enter a number: ");
scanf("%d", &select);
switch (select)
{
case 1:
case 3:
dependents = 1;
deduction = 5700;
break;
case 2:
deduction = 11400;
dependents = 2;
break;
default:
printf("The option you entered is incorrect\n");
exit(1);
}
if (dependents > 1)
{
printf("How many children do you have? ");
scanf("%d", &children);
}
deduction += (children + dependents) * 3650;
income -= deduction;
if (income >= 137300)
{
printf("%.2lf\n", (income - 137300) * 0.28 + 26687.5);
}
else if (income >= 68000)
{
printf("%.2lf\n", (income - 68000) * 0.25 + 9362.5);
}
else if (income >= 16750)
{
printf("%.2lf\n", (income - 16750) * 0.15 + 1675);
}
else if (income >= 0)
{
printf("%.2lf\n", income * 0.1);
}
return 0;
} |
the_stack_data/16898.c | #include <stdio.h>
/* Function prototypes */
int KEY_pressed(void);
void doit(void);
/* This program demonstrates the use of inline assembly code in C code */
int main(void)
{
while (1) // endless loop
{
if (KEY_pressed()) doit();
asm("and r10, r11, r12");
if (KEY_pressed()) doit();
asm("xor r13, r14, r15");
if (KEY_pressed()) doit();
asm("or r16, r17, r18");
if (KEY_pressed()) doit();
asm("and r18, r17, r16");
if (KEY_pressed()) doit();
asm("xor r15, r14, r13");
if (KEY_pressed()) doit();
asm("or r12, r11, r10");
if (KEY_pressed()) doit();
}
}
int KEY_pressed()
{
// code not shown
}
void doit()
{
unsigned int machine_code;
// get the machine code of the next instruction on return from this
// subroutine
asm("ldw r10, 0(ra)" : : : "r10"); // read machine code into R0
asm("mov %0, r10" : "=r"(machine_code) : :); // copy R0 into variable
// machine code
// code not shown
}
|
the_stack_data/58614.c | #include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <inttypes.h>
#include <string.h>
int debug=0;
// generate random number:
uint16_t get_number16(uint16_t min,uint16_t max)
{
float rf=(float)rand() / (float)RAND_MAX * (float)(max+1);
uint16_t r = (uint16_t)rf;
if(r<min) r=min;
//printf("r=%d\n",r);
return (uint16_t)r;
}
uint32_t get_number32(uint32_t min,uint32_t max)
{
float rf=(float)rand() / (float)RAND_MAX * (float)(max+1);
uint32_t r = (uint32_t)rf;
if(r<min) r=min;
//printf("r=%d\n",r);
return (uint32_t)r;
}
/*
* id: 9 digit with a range from 000000000 up to 999999999
* number of days, use 3 digits with a range from 000 up to 999
* sequence, I do not have any specific requirements, 2 or 3 digits seem fine
*
* Some notes about the number of bits required:
* - id max is: 999999999 this needs 30 bits
* (2^30 = 1073741824)
* - days max is: 999 this needs 10 bits (2^10 = 1024)
* - seq max is: 99 this needs 7 bits (2^7 = 128)
*
* total nr of bits= 30+10+7=47 (2^47 = 140737488355328)
*/
void print_binary(uint64_t val, int nof_bits);
const uint8_t seqlut[] = {
35, 86, 69, 93, 99, 63, 74, 15, 84, 88,
82, 26, 50, 43, 58, 55, 97, 71, 52, 96,
13, 67, 56, 20, 27, 46, 9, 19, 73, 38,
1, 2, 77, 64, 5, 57, 3, 25, 21, 31,
61, 16, 8, 75, 24, 92, 78, 30, 33, 6,
10, 44, 72, 83, 53, 95, 49, 11, 18, 42,
40, 28, 76, 17, 0, 14, 12, 80, 47, 87,
68, 98, 32, 51, 39, 81, 62, 34, 45, 54,
85, 36, 4, 37, 41, 66, 91, 70, 89, 60,
79, 94, 29, 90, 22, 7, 65, 48, 59, 23
};
const uint8_t digitlut[] = {1, 7, 2, 6, 4, 0, 9, 8, 5, 3};
void crypt_digits(char *code_str)
{
int i;
//printf("crypt_digits(%s)\n",code_str);
for(i=0;i<14;i++) {
code_str[i]='0'+digitlut[code_str[i]-'0'];
}
//printf("=(%s)\n",code_str);
}
void decrypt_digits(char *code_str)
{
int i,c;
//printf("decrypt_digits(%s)\n",code_str);
for(i=0;i<14;i++) {
for(c=0;c<10;c++) {
if(code_str[i] == (digitlut[c]+'0')) break;
}
code_str[i]=c+'0';
}
//printf("=(%s)\n",code_str);
}
uint64_t generate_rcode(uint64_t code, unsigned int seq)
{
int i;
char str[16];
char str1[16];
char str2[16];
sprintf(str,"%012lu",code);
for(i=0;i<seq;i++) {
strncpy(str1,str,11);
str1[11]='\0';
strncpy(str2,&str[11],1);
str2[1]='\0';
//printf("str1=%s str2=%s\n",str1,str2);
strcpy(str,str2);
strcat(str,str1);
}
//printf("code=%012lu seq=%02d ",code,seq);
code = strtoul(str,NULL,10);
//printf("sizeof=%ld\n",sizeof(code));
//printf("==> code=%012lu\n",code);
return code;
}
int decode_rcode(char *code_str, uint8_t *seq, uint32_t *id, uint16_t *days)
{
uint64_t code;
uint8_t seqc,seqcode;
int i;
char str[16];
char str1[16];
char str2[16];
decrypt_digits(code_str);
seqcode = strtoul(&code_str[12],NULL,10);
if(seqcode < 0 || seqcode > 99) {
printf("Error: illegal seq)\n");
return -1;
}
strcpy(str,code_str);
str[12]='\0';
// rol <<
for(i=0;i<seqcode;i++) {
strncpy(str1,str,1); // take most left digit
str1[1]='\0';
strncpy(str2,&str[1],11); // take other right digits
str2[11]='\0';
//printf("str1=%s str2=%s\n",str1,str2);
strcpy(str,str2);
strcat(str,str1);
}
//printf("==> code=%s\n",str);
for(seqc=0;seqc<100;seqc++) {
if(seqcode==seqlut[seqc]) break;
}
*seq=seqc;
//printf("seqcode=%u --> seqlut --> seq=%u\n",seqcode,seqc);
strcpy(str1,str);
strcpy(str2,str);
// 123456789012
// 0 9
str1[9]='\0';
str2[8]=' ';
// printf("str1=%s str2=%s\n",str1,&str2[9]);
*id = strtoul(str1,NULL,10);
*days = strtoul(&str2[9],NULL,10);
return 1;
}
int main(int argc, char* argv[])
{
uint64_t code;
unsigned int shsid,days,seq=0,runs=100,i,r;
unsigned int rruns=10000;
uint32_t chk_shsid;
uint16_t chk_days;
uint8_t chk_seq;
char code_str[32];
for(r=0;r<rruns;r++) {
shsid=get_number32(1,999999999);
days=get_number16(1,999);
seq=0;
for(i=0;i<runs;i++) {
code = (uint64_t)shsid * 1000UL;
code += (uint64_t)days;
code = generate_rcode(code,seqlut[seq]);
printf("codegen id=%09u days=%03d seq=%02d ==> code = %09u%03u%02u -> ",
shsid,days,seq,shsid,days,seqlut[seq]);
sprintf(code_str,"%012lu%02u",code,seqlut[seq]);
printf("%s -> ",code_str);
crypt_digits(code_str);
printf("%s\n",code_str);
// decode, test and check:
if(decode_rcode(code_str,&chk_seq,&chk_shsid,&chk_days) <0) exit(EXIT_FAILURE);
printf("codechk id=%09u days=%03d seq=%02d <== code = %s\n",
chk_shsid,chk_days,chk_seq,code_str);
if(chk_seq != seq) { fprintf(stderr,"chk_seq != seq\n"); exit(EXIT_FAILURE);}
if(chk_shsid != shsid) { fprintf(stderr,"chk_shsid != shsid\n"); exit(EXIT_FAILURE);}
if(chk_days != days) { fprintf(stderr,"chk_days != days\n"); exit(EXIT_FAILURE);}
seq++;
}
}
printf("PASS\n");
}
void print_binary(uint64_t val, int nof_bits)
{
uint64_t n=val;
char str[100];
int i,nof_bits_cnt=0;
memset(str,0,sizeof(str));
while (n) {
if (n & 1)
strcat(str,"1");
else
strcat(str,"0");
nof_bits_cnt++;
n >>= 1;
}
while(nof_bits_cnt < nof_bits) {
strcat(str,"0");
nof_bits_cnt++;
if(strlen(str) >= sizeof(str)-1) break;
}
// print reverse:
for(i=strlen(str);i>=0;i--) {
printf("%c",str[i]);
}
printf("\n");
}
|
the_stack_data/200141926.c | /**
* Copyright (c) 2016 - 2017, Nordic Semiconductor ASA
*
* 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, except as embedded into a Nordic
* Semiconductor ASA integrated circuit in a product or a software update for
* such product, 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 Nordic Semiconductor ASA nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* 4. This software, with or without modification, must only be used with a
* Nordic Semiconductor ASA integrated circuit.
*
* 5. Any software provided in binary form under this license must not be reverse
* engineered, decompiled, modified and/or disassembled.
*
* THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA "AS IS" AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL NORDIC SEMICONDUCTOR ASA 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.
*
*/
#include <stdint.h>
/* Record Payload Type for Bluetooth Carrier Configuration LE record */
const uint8_t le_oob_rec_type_field[] =
{
'a', 'p', 'p', 'l', 'i', 'c', 'a', 't', 'i', 'o', 'n', '/', 'v', 'n', 'd', '.',
'b', 'l', 'u', 'e', 't', 'o', 'o', 't', 'h', '.', 'l', 'e', '.', 'o', 'o', 'b'
};
|
the_stack_data/57602.c | /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Copyright by The HDF Group. *
* All rights reserved. *
* *
* This file is part of HDF5. The full HDF5 copyright notice, including *
* terms governing use, modification, and redistribution, is contained in *
* the COPYING file, which can be found at the root of the source code *
* distribution tree, or in https://support.hdfgroup.org/ftp/HDF5/releases. *
* If you do not have access to either file, you may request a copy from *
* [email protected]. *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
#define SIMPLE_TEST(x) int main(){ x; return 0; }
#ifdef HAVE_C99_DESIGNATED_INITIALIZER
#ifdef FC_DUMMY_MAIN
#ifndef FC_DUMMY_MAIN_EQ_F77
# ifdef __cplusplus
extern "C"
# endif
int FC_DUMMY_MAIN()
{ return 1;}
#endif
#endif
int
main ()
{
typedef struct
{
int x;
union
{
int i;
double d;
}u;
}di_struct_t;
di_struct_t x =
{ 0,
{ .d = 0.0}};
;
return 0;
}
#endif
#ifdef HAVE_C99_FUNC
#ifdef FC_DUMMY_MAIN
#ifndef FC_DUMMY_MAIN_EQ_F77
# ifdef __cplusplus
extern "C"
# endif
int FC_DUMMY_MAIN() { return 1; }
#endif
#endif
int
main ()
{
const char *fname = __func__;
;
return 0;
}
#endif
#ifdef STDC_HEADERS
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include <float.h>
int main() { return 0; }
#endif /* STDC_HEADERS */
#ifdef HAVE_ATTRIBUTE
#if 0
static void test int __attribute((unused)) var)
{
int __attribute__((unused)) x = var;
}
int main(void)
{
test(19);
}
#else
int
main ()
{
int __attribute__((unused)) x
;
return 0;
}
#endif
#endif /* HAVE_ATTRIBUTE */
#ifdef HAVE_FUNCTION
#ifdef FC_DUMMY_MAIN
#ifndef FC_DUMMY_MAIN_EQ_F77
# ifdef __cplusplus
extern "C"
# endif
int FC_DUMMY_MAIN() { return 1; }
#endif
#endif
int
main ()
{
(void)__FUNCTION__
;
return 0;
}
#endif /* HAVE_FUNCTION */
#ifdef HAVE_TIMEZONE
#ifdef HAVE_SYS_TIME_H
#include <sys/time.h>
#endif
#include <time.h>
SIMPLE_TEST(timezone=0);
#endif /* HAVE_TIMEZONE */
#ifdef PRINTF_LL_WIDTH
#ifdef HAVE_LONG_LONG
# define LL_TYPE long long
#else /* HAVE_LONG_LONG */
# define LL_TYPE __int64
#endif /* HAVE_LONG_LONG */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#if defined(_MSC_VER) && defined(_DEBUG)
# include <crtdbg.h>
int DebugReport(int reportType, char* message, int* returnValue)
{
(void)reportType;
(void)message;
(void)returnValue;
return 1; /* no further handling required */
}
#endif
int main(void)
{
char *llwidthArgs[] = { "I64", "l64", "l", "L", "q", "ll", NULL };
char *s = malloc(128);
char **currentArg = NULL;
LL_TYPE x = (LL_TYPE)1048576 * (LL_TYPE)1048576;
#if defined(_MSC_VER) && defined(_DEBUG)
_CrtSetReportHook(DebugReport);
#endif
for (currentArg = llwidthArgs; *currentArg != NULL; currentArg++)
{
char formatString[64];
sprintf(formatString, "%%%sd", *currentArg);
sprintf(s, formatString, x);
if (strcmp(s, "1099511627776") == 0)
{
printf("PRINTF_LL_WIDTH=[%s]\n", *currentArg);
return 0;
}
}
return 1;
}
#endif /* PRINTF_LL_WIDTH */
#ifdef SYSTEM_SCOPE_THREADS
#include <stdlib.h>
#include <pthread.h>
int main(void)
{
pthread_attr_t attribute;
int ret;
pthread_attr_init(&attribute);
ret=pthread_attr_setscope(&attribute, PTHREAD_SCOPE_SYSTEM);
if (ret==0)
return 0;
return 1;
}
#endif /* SYSTEM_SCOPE_THREADS */
#ifdef HAVE_SOCKLEN_T
#include <stdio.h>
#include <stdlib.h>
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#ifdef HAVE_SYS_TYPES_H
#include <sys/types.h>
#endif
SIMPLE_TEST(socklen_t foo);
#endif /* HAVE_SOCKLEN_T */
#ifdef DEV_T_IS_SCALAR
#ifdef HAVE_SYS_TYPES_H
#include <sys/types.h>
#endif
int main ()
{
dev_t d1, d2;
if(d1==d2)
return 0;
return 1;
}
#endif /* DEV_T_IS_SCALAR */
#ifdef HAVE_OFF64_T
#include <sys/types.h>
int main()
{
off64_t n = 0;
return (int)n;
}
#endif
#ifdef TEST_DIRECT_VFD_WORKS
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int main(void)
{
int fid;
if((fid=open("tst_file", O_CREAT | O_TRUNC | O_DIRECT, 0755))<0)
return 1;
close(fid);
remove("tst_file");
return 0;
}
#endif
#ifdef HAVE_DIRECT
SIMPLE_TEST(posix_memalign());
#endif
#ifdef HAVE_DEFAULT_SOURCE
/* check default source */
#include <features.h>
int
main(void)
{
#ifdef __GLIBC_PREREQ
return __GLIBC_PREREQ(2,19);
#else
return 0;
#endif /* defined(__GLIBC_PREREQ) */
}
#endif
#ifdef TEST_LFS_WORKS
/* Return 0 when LFS is available and 1 otherwise. */
#define _LARGEFILE_SOURCE
#define _LARGEFILE64_SOURCE
#define _LARGE_FILES
#define _FILE_OFFSET_BITS 64
#include <sys/types.h>
#include <sys/stat.h>
#include <assert.h>
#include <stdio.h>
int main(int argc, char **argv)
{
/* check that off_t can hold 2^63 - 1 and perform basic operations... */
#define OFF_T_64 (((off_t) 1 << 62) - 1 + ((off_t) 1 << 62))
if (OFF_T_64 % 2147483647 != 1)
return 1;
/* stat breaks on SCO OpenServer */
struct stat buf;
stat( argv[0], &buf );
if (!S_ISREG(buf.st_mode))
return 2;
FILE *file = fopen( argv[0], "r" );
off_t offset = ftello( file );
fseek( file, offset, SEEK_CUR );
fclose( file );
return 0;
}
#endif
#ifdef GETTIMEOFDAY_GIVES_TZ
#include <time.h>
#ifdef HAVE_SYS_TIME_H
#include <sys/time.h>
#endif
int main(void)
{
struct timeval tv;
struct timezone tz;
tz.tz_minuteswest = 7777; /* Initialize to an unreasonable number */
tz.tz_dsttime = 7;
gettimeofday(&tv, &tz);
/* Check whether the function returned any value at all */
if(tz.tz_minuteswest == 7777 && tz.tz_dsttime == 7)
return 1;
else return 0;
}
#endif
#ifdef HAVE_IOEO
#include <windows.h>
typedef void (WINAPI *PGNSI)(LPSYSTEM_INFO);
int main ()
{
PGNSI pGNSI;
pGNSI = (PGNSI) GetProcAddress(
GetModuleHandle(TEXT("kernel32.dll")),
"InitOnceExecuteOnce");
if(NULL == pGNSI)
return 1;
else
return 0;
}
#endif /* HAVE_IOEO */
#if defined( HAVE_INLINE ) || defined( HAVE___INLINE__ ) || defined( HAVE___INLINE )
#ifndef __cplusplus
#if defined( HAVE_INLINE )
# define INLINE_KW inline
#elif defined ( HAVE___INLINE__ )
# define INLINE_KW __inline__
#elif defined ( HAVE___INLINE )
# define INLINE_KW __inline
#endif /* HAVE_INLINE */
typedef int foo_t;
static INLINE_KW foo_t static_foo () { return 0; }
INLINE_KW foo_t foo () {return 0; }
int main(void) { return 0; }
#endif /* __cplusplus */
#endif /* defined( HAVE_INLINE ) || defined( HAVE___INLINE__ ) || defined( HAVE___INLINE ) */
|
the_stack_data/70144.c | /* Tests for the "Initializer entry defined twice" warning. */
/* Initializing a struct field twice should trigger the warning. */
struct normal {
int field1;
int field2;
};
static struct normal struct_error = {
.field1 = 0,
.field1 = 0
};
/* Initializing two different fields of a union should trigger the warning. */
struct has_union {
int x;
union {
int a;
int b;
} y;
int z;
};
static struct has_union union_error = {
.y = {
.a = 0,
.b = 0
}
};
/* Empty structures can make two fields have the same offset in a struct.
* Initializing both should not trigger the warning. */
struct empty { };
struct same_offset {
struct empty field1;
int field2;
};
static struct same_offset not_an_error = {
.field1 = { },
.field2 = 0
};
/*
* _Bools generally take a whole byte, so ensure that we can initialize
* them without spewing a warning.
*/
static _Bool boolarray[3] = {
[0] = 1,
[1] = 1,
};
/*
* check-name: Initializer entry defined twice
*
* check-error-start
initializer-entry-defined-twice.c:10:10: warning: Initializer entry defined twice
initializer-entry-defined-twice.c:11:10: also defined here
initializer-entry-defined-twice.c:26:18: warning: Initializer entry defined twice
initializer-entry-defined-twice.c:27:18: also defined here
* check-error-end
*/
|
the_stack_data/206392644.c | /* Copyright (c) 2007-2009, UNINETT AS
* Copyright (c) 2010-2011,2015-2016, NORDUnet A/S */
/* See LICENSE for licensing information. */
#if defined(RADPROT_TLS) || defined(RADPROT_DTLS)
#define _GNU_SOURCE
#include <stdio.h>
#include <signal.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <string.h>
#include <unistd.h>
#include <limits.h>
#include <fcntl.h>
#include <poll.h>
#include <sys/time.h>
#include <sys/types.h>
#include <ctype.h>
#include <sys/wait.h>
#include <arpa/inet.h>
#include <regex.h>
#include <libgen.h>
#include <pthread.h>
#include <openssl/ssl.h>
#include <openssl/rand.h>
#include <openssl/err.h>
#include <openssl/md5.h>
#include <openssl/x509v3.h>
#include "debug.h"
#include "hash.h"
#include "util.h"
#include "hostport.h"
#include "radsecproxy.h"
static struct hash *tlsconfs = NULL;
#define COOKIE_SECRET_LENGTH 16
static unsigned char cookie_secret[COOKIE_SECRET_LENGTH];
static uint8_t cookie_secret_initialized = 0;
int radsecproxy_ssl_servername_index;
/* callbacks for making OpenSSL < 1.1 thread safe */
#if OPENSSL_VERSION_NUMBER < 0x10100000
static pthread_mutex_t *ssl_locks = NULL;
#if OPENSSL_VERSION_NUMBER < 0x10000000
unsigned long ssl_thread_id() {
return (unsigned long)pthread_self();
}
#else
void ssl_thread_id(CRYPTO_THREADID *id) {
CRYPTO_THREADID_set_numeric(id, (unsigned long)pthread_self());
}
#endif
void ssl_locking_callback(int mode, int type, const char *file, int line) {
if (mode & CRYPTO_LOCK)
pthread_mutex_lock(&ssl_locks[type]);
else
pthread_mutex_unlock(&ssl_locks[type]);
}
#endif
void sslinit() {
#if OPENSSL_VERSION_NUMBER < 0x10100000
int i;
SSL_library_init();
ssl_locks = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t));
if (!ssl_locks)
debugx(1, DBG_ERR, "malloc failed");
for (i = 0; i < CRYPTO_num_locks(); i++) {
pthread_mutex_init(&ssl_locks[i], NULL);
}
#if OPENSSL_VERSION_NUMBER < 0x10000000
CRYPTO_set_id_callback(ssl_thread_id);
#else
CRYPTO_THREADID_set_callback(ssl_thread_id);
#endif
CRYPTO_set_locking_callback(ssl_locking_callback);
SSL_load_error_strings();
#else
OPENSSL_init_ssl(0, NULL);
#endif
radsecproxy_ssl_servername_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, NULL);
if (radsecproxy_ssl_servername_index == -1) {
debug(DBG_ERR, "SSL_get_ex_new_index for radsecproxy_ssl_servername_index failed");
}
}
static int pem_passwd_cb(char *buf, int size, int rwflag, void *userdata) {
int pwdlen = strlen(userdata);
if (rwflag != 0 || pwdlen > size) /* not for decryption or too large */
return 0;
memcpy(buf, userdata, pwdlen);
return pwdlen;
}
static int verify_cb(int ok, X509_STORE_CTX *ctx) {
char *buf = NULL;
X509 *err_cert;
int err, depth;
err_cert = X509_STORE_CTX_get_current_cert(ctx);
err = X509_STORE_CTX_get_error(ctx);
depth = X509_STORE_CTX_get_error_depth(ctx);
if (depth > MAX_CERT_DEPTH) {
ok = 0;
err = X509_V_ERR_CERT_CHAIN_TOO_LONG;
X509_STORE_CTX_set_error(ctx, err);
}
if (!ok) {
if (err_cert)
buf = X509_NAME_oneline(X509_get_subject_name(err_cert), NULL, 0);
debug(DBG_WARN, "verify error: num=%d:%s:depth=%d:%s", err, X509_verify_cert_error_string(err), depth, buf ? buf : "");
free(buf);
buf = NULL;
switch (err) {
case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
if (err_cert) {
buf = X509_NAME_oneline(X509_get_issuer_name(err_cert), NULL, 0);
if (buf) {
debug(DBG_WARN, "\tIssuer=%s", buf);
free(buf);
buf = NULL;
}
}
break;
case X509_V_ERR_CERT_NOT_YET_VALID:
case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
debug(DBG_WARN, "\tCertificate not yet valid");
break;
case X509_V_ERR_CERT_HAS_EXPIRED:
debug(DBG_WARN, "Certificate has expired");
break;
case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
debug(DBG_WARN, "Certificate no longer valid (after notAfter)");
break;
case X509_V_ERR_NO_EXPLICIT_POLICY:
debug(DBG_WARN, "No Explicit Certificate Policy");
break;
}
}
#ifdef DEBUG
printf("certificate verify returns %d\n", ok);
#endif
return ok;
}
static int cookie_calculate_hash(struct sockaddr *peer, time_t time, uint8_t *result, unsigned int *resultlength) {
uint8_t *buf;
int length;
length = SOCKADDRP_SIZE(peer) + sizeof(time_t);
buf = OPENSSL_malloc(length);
if (!buf) {
debug(DBG_ERR, "cookie_calculate_hash: malloc failed");
return 0;
}
memcpy(buf, &time, sizeof(time_t));
memcpy(buf+sizeof(time_t), peer, SOCKADDRP_SIZE(peer));
HMAC(EVP_sha256(), (const void*) cookie_secret, COOKIE_SECRET_LENGTH,
buf, length, result, resultlength);
OPENSSL_free(buf);
return 1;
}
static int cookie_generate_cb(SSL *ssl, unsigned char *cookie, unsigned int *cookie_len) {
struct sockaddr_storage peer;
struct timeval now;
uint8_t result[EVP_MAX_MD_SIZE];
unsigned int resultlength;
if (!cookie_secret_initialized) {
if (!RAND_bytes(cookie_secret, COOKIE_SECRET_LENGTH))
debugx(1,DBG_ERR, "cookie_generate_cg: error generating random secret");
cookie_secret_initialized = 1;
}
if (BIO_dgram_get_peer(SSL_get_rbio(ssl), &peer) <= 0)
return 0;
gettimeofday(&now, NULL);
if (!cookie_calculate_hash((struct sockaddr *)&peer, now.tv_sec, result, &resultlength))
return 0;
memcpy(cookie, &now.tv_sec, sizeof(time_t));
memcpy(cookie + sizeof(time_t), result, resultlength);
*cookie_len = resultlength + sizeof(time_t);
return 1;
}
#if OPENSSL_VERSION_NUMBER < 0x10100000
static int cookie_verify_cb(SSL *ssl, unsigned char *cookie, unsigned int cookie_len) {
#else
static int cookie_verify_cb(SSL *ssl, const unsigned char *cookie, unsigned int cookie_len) {
#endif
struct sockaddr_storage peer;
struct timeval now;
time_t cookie_time;
uint8_t result[EVP_MAX_MD_SIZE];
unsigned int resultlength;
if (!cookie_secret_initialized)
return 0;
if (cookie_len < sizeof(time_t)) {
debug(DBG_DBG, "cookie_verify_cb: cookie too short. ignoring.");
return 0;
}
gettimeofday(&now, NULL);
cookie_time = *(time_t *)cookie;
if (now.tv_sec - cookie_time > 5) {
debug(DBG_DBG, "cookie_verify_cb: cookie invalid or older than 5s. ignoring.");
return 0;
}
if (BIO_dgram_get_peer(SSL_get_rbio(ssl), &peer) <= 0)
return 0;
if (!cookie_calculate_hash((struct sockaddr *)&peer, cookie_time, result, &resultlength))
return 0;
if (resultlength + sizeof(time_t) != cookie_len) {
debug(DBG_DBG, "cookie_verify_cb: invalid cookie length. ignoring.");
return 0;
}
if (memcmp(cookie + sizeof(time_t), result, resultlength)) {
debug(DBG_DBG, "cookie_verify_cb: cookie not valid. ignoring.");
return 0;
}
return 1;
}
#ifdef DEBUG
static void ssl_info_callback(const SSL *ssl, int where, int ret) {
const char *s;
int w;
w = where & ~SSL_ST_MASK;
if (w & SSL_ST_CONNECT)
s = "SSL_connect";
else if (w & SSL_ST_ACCEPT)
s = "SSL_accept";
else
s = "undefined";
if (where & SSL_CB_LOOP)
debug(DBG_DBG, "%s:%s\n", s, SSL_state_string_long(ssl));
else if (where & SSL_CB_ALERT) {
s = (where & SSL_CB_READ) ? "read" : "write";
debug(DBG_DBG, "SSL3 alert %s:%s:%s\n", s, SSL_alert_type_string_long(ret), SSL_alert_desc_string_long(ret));
}
else if (where & SSL_CB_EXIT) {
if (ret == 0)
debug(DBG_DBG, "%s:failed in %s\n", s, SSL_state_string_long(ssl));
else if (ret < 0)
debug(DBG_DBG, "%s:error in %s\n", s, SSL_state_string_long(ssl));
}
}
#endif
static X509_VERIFY_PARAM *createverifyparams(char **poids) {
X509_VERIFY_PARAM *pm;
ASN1_OBJECT *pobject;
int i;
pm = X509_VERIFY_PARAM_new();
if (!pm)
return NULL;
for (i = 0; poids[i]; i++) {
pobject = OBJ_txt2obj(poids[i], 0);
if (!pobject) {
X509_VERIFY_PARAM_free(pm);
return NULL;
}
X509_VERIFY_PARAM_add0_policy(pm, pobject);
}
X509_VERIFY_PARAM_set_flags(pm, X509_V_FLAG_POLICY_CHECK | X509_V_FLAG_EXPLICIT_POLICY);
return pm;
}
static int tlsaddcacrl(SSL_CTX *ctx, struct tls *conf) {
STACK_OF(X509_NAME) *calist;
X509_STORE *x509_s;
unsigned long error;
SSL_CTX_set_cert_store(ctx, X509_STORE_new());
if (!SSL_CTX_load_verify_locations(ctx, conf->cacertfile, conf->cacertpath)) {
while ((error = ERR_get_error()))
debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
debug(DBG_ERR, "tlsaddcacrl: Error updating TLS context %s", conf->name);
return 0;
}
calist = conf->cacertfile ? SSL_load_client_CA_file(conf->cacertfile) : NULL;
if (!conf->cacertfile || calist) {
if (conf->cacertpath) {
if (!calist)
calist = sk_X509_NAME_new_null();
if (!SSL_add_dir_cert_subjects_to_stack(calist, conf->cacertpath)) {
sk_X509_NAME_free(calist);
calist = NULL;
}
}
}
if (!calist) {
while ((error = ERR_get_error()))
debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
debug(DBG_ERR, "tlsaddcacrl: Error adding CA subjects in TLS context %s", conf->name);
return 0;
}
ERR_clear_error(); /* add_dir_cert_subj returns errors on success */
SSL_CTX_set_client_CA_list(ctx, calist);
SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, verify_cb);
SSL_CTX_set_verify_depth(ctx, MAX_CERT_DEPTH + 1);
SSL_CTX_set_cookie_generate_cb(ctx, cookie_generate_cb);
SSL_CTX_set_cookie_verify_cb(ctx, cookie_verify_cb);
if (conf->crlcheck || conf->vpm) {
x509_s = SSL_CTX_get_cert_store(ctx);
if (conf->crlcheck)
X509_STORE_set_flags(x509_s, X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL);
if (conf->vpm)
X509_STORE_set1_param(x509_s, conf->vpm);
}
debug(DBG_DBG, "tlsaddcacrl: updated TLS context %s", conf->name);
return 1;
}
static int ssl_servername_cb(SSL *s, int *ad, void *arg)
{
const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
struct tls *tls = NULL;
SSL_CTX *ctx = NULL;
if (servername == NULL)
return SSL_TLSEXT_ERR_OK;
tls = tlsgettls((char *)servername, NULL);
if (tls) {
ctx = tlsgetctx(RAD_TLS, tls);
if (ctx) {
debug(DBG_DBG, "ssl_servername_cb: servername: %s, calling SSL_set_SSL_CTX()", servername);
SSL_set_SSL_CTX(s, ctx);
if (SSL_set_ex_data(s, radsecproxy_ssl_servername_index, (char *)servername) == 0) {
debug(DBG_ERR, "ssl_servername_cb: SSL_set_ex_data(radsecproxy_ssl_servername_index: %d) failed", radsecproxy_ssl_servername_index);
}
} else {
debug(DBG_ERR, "ssl_servername_cb: tlsgetctx() for %s failed", servername);
}
}
return SSL_TLSEXT_ERR_OK;
}
static SSL_CTX *tlscreatectx(uint8_t type, struct tls *conf) {
SSL_CTX *ctx = NULL;
unsigned long error;
switch (type) {
#ifdef RADPROT_TLS
case RAD_TLS:
#if OPENSSL_VERSION_NUMBER >= 0x10100000
/* TLS_method() was introduced in OpenSSL 1.1.0. */
ctx = SSL_CTX_new(TLS_method());
#else
/* No TLS_method(), use SSLv23_method() and disable SSLv2 and SSLv3. */
ctx = SSL_CTX_new(SSLv23_method());
SSL_CTX_set_options(ctx, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3);
#endif
#ifdef DEBUG
SSL_CTX_set_info_callback(ctx, ssl_info_callback);
#endif
break;
#endif
#ifdef RADPROT_DTLS
case RAD_DTLS:
#if OPENSSL_VERSION_NUMBER >= 0x10002000
/* DTLS_method() seems to have been introduced in OpenSSL 1.0.2. */
ctx = SSL_CTX_new(DTLS_method());
#else
ctx = SSL_CTX_new(DTLSv1_method());
#endif
#ifdef DEBUG
SSL_CTX_set_info_callback(ctx, ssl_info_callback);
#endif
SSL_CTX_set_read_ahead(ctx, 1);
break;
#endif
}
if (!ctx) {
debug(DBG_ERR, "tlscreatectx: Error initialising SSL/TLS in TLS context %s", conf->name);
return NULL;
}
#if OPENSSL_VERSION_NUMBER < 0x10100000L
{
long sslversion = SSLeay();
if (sslversion < 0x00908100L ||
(sslversion >= 0x10000000L && sslversion < 0x10000020L)) {
debug(DBG_WARN, "%s: %s seems to be of a version with a "
"certain security critical bug (fixed in OpenSSL 0.9.8p and "
"1.0.0b). Disabling OpenSSL session caching for context %p.",
__func__, SSLeay_version(SSLEAY_VERSION), ctx);
SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF);
}
}
#endif
if (conf->snicallback) {
SSL_CTX_set_tlsext_servername_callback(ctx, ssl_servername_cb);
}
if (conf->certkeypwd) {
SSL_CTX_set_default_passwd_cb_userdata(ctx, conf->certkeypwd);
SSL_CTX_set_default_passwd_cb(ctx, pem_passwd_cb);
}
if (!SSL_CTX_use_certificate_chain_file(ctx, conf->certfile) ||
!SSL_CTX_use_PrivateKey_file(ctx, conf->certkeyfile, SSL_FILETYPE_PEM) ||
!SSL_CTX_check_private_key(ctx)) {
while ((error = ERR_get_error()))
debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
debug(DBG_ERR, "tlscreatectx: Error initialising SSL/TLS in TLS context %s", conf->name);
SSL_CTX_free(ctx);
return NULL;
}
if (conf->policyoids) {
if (!conf->vpm) {
conf->vpm = createverifyparams(conf->policyoids);
if (!conf->vpm) {
debug(DBG_ERR, "tlscreatectx: Failed to add policyOIDs in TLS context %s", conf->name);
SSL_CTX_free(ctx);
return NULL;
}
}
}
if (!tlsaddcacrl(ctx, conf)) {
if (conf->vpm) {
X509_VERIFY_PARAM_free(conf->vpm);
conf->vpm = NULL;
}
SSL_CTX_free(ctx);
return NULL;
}
debug(DBG_DBG, "tlscreatectx: created TLS context %s", conf->name);
return ctx;
}
struct tls *tlsgettls(char *alt1, char *alt2) {
struct tls *t;
t = hash_read(tlsconfs, alt1, strlen(alt1));
if (!t)
t = hash_read(tlsconfs, alt2, strlen(alt2));
return t;
}
SSL_CTX *tlsgetctx(uint8_t type, struct tls *t) {
struct timeval now;
if (!t)
return NULL;
gettimeofday(&now, NULL);
switch (type) {
#ifdef RADPROT_TLS
case RAD_TLS:
if (t->tlsexpiry && t->tlsctx) {
if (t->tlsexpiry < now.tv_sec) {
t->tlsexpiry = now.tv_sec + t->cacheexpiry;
tlsaddcacrl(t->tlsctx, t);
}
}
if (!t->tlsctx) {
t->tlsctx = tlscreatectx(RAD_TLS, t);
if (t->cacheexpiry)
t->tlsexpiry = now.tv_sec + t->cacheexpiry;
}
return t->tlsctx;
#endif
#ifdef RADPROT_DTLS
case RAD_DTLS:
if (t->dtlsexpiry && t->dtlsctx) {
if (t->dtlsexpiry < now.tv_sec) {
t->dtlsexpiry = now.tv_sec + t->cacheexpiry;
tlsaddcacrl(t->dtlsctx, t);
}
}
if (!t->dtlsctx) {
t->dtlsctx = tlscreatectx(RAD_DTLS, t);
if (t->cacheexpiry)
t->dtlsexpiry = now.tv_sec + t->cacheexpiry;
}
return t->dtlsctx;
#endif
}
return NULL;
}
void tlsreloadcrls() {
struct tls *conf;
struct hash_entry *entry;
struct timeval now;
debug (DBG_NOTICE, "reloading CRLs");
gettimeofday(&now, NULL);
for (entry = hash_first(tlsconfs); entry; entry = hash_next(entry)) {
conf = (struct tls *)entry->data;
#ifdef RADPROT_TLS
if (conf->tlsctx) {
if (conf->tlsexpiry)
conf->tlsexpiry = now.tv_sec + conf->cacheexpiry;
tlsaddcacrl(conf->tlsctx, conf);
}
#endif
#ifdef RADPROT_DTLS
if (conf->dtlsctx) {
if (conf->dtlsexpiry)
conf->dtlsexpiry = now.tv_sec + conf->cacheexpiry;
tlsaddcacrl(conf->dtlsctx, conf);
}
#endif
}
}
X509 *verifytlscert(SSL *ssl) {
X509 *cert;
unsigned long error;
if (SSL_get_verify_result(ssl) != X509_V_OK) {
debug(DBG_ERR, "verifytlscert: basic validation failed");
while ((error = ERR_get_error()))
debug(DBG_ERR, "verifytlscert: TLS: %s", ERR_error_string(error, NULL));
return NULL;
}
cert = SSL_get_peer_certificate(ssl);
if (!cert)
debug(DBG_ERR, "verifytlscert: failed to obtain certificate");
return cert;
}
static int subjectaltnameaddr(X509 *cert, int family, struct in6_addr *addr) {
int loc, i, l, n, r = 0;
char *v;
X509_EXTENSION *ex;
STACK_OF(GENERAL_NAME) *alt;
GENERAL_NAME *gn;
debug(DBG_DBG, "subjectaltnameaddr");
loc = X509_get_ext_by_NID(cert, NID_subject_alt_name, -1);
if (loc < 0)
return r;
ex = X509_get_ext(cert, loc);
alt = X509V3_EXT_d2i(ex);
if (!alt)
return r;
n = sk_GENERAL_NAME_num(alt);
for (i = 0; i < n; i++) {
gn = sk_GENERAL_NAME_value(alt, i);
if (gn->type != GEN_IPADD)
continue;
r = -1;
v = (char *)ASN1_STRING_get0_data(gn->d.ia5);
l = ASN1_STRING_length(gn->d.ia5);
if (((family == AF_INET && l == sizeof(struct in_addr)) || (family == AF_INET6 && l == sizeof(struct in6_addr)))
&& !memcmp(v, addr, l)) {
r = 1;
break;
}
}
GENERAL_NAMES_free(alt);
return r;
}
static int subjectaltnameregexp(X509 *cert, int type, char *exact, regex_t *regex) {
int loc, i, l, n, r = 0;
char *s, *v, *fail = NULL, *tmp;
X509_EXTENSION *ex;
STACK_OF(GENERAL_NAME) *alt;
GENERAL_NAME *gn;
debug(DBG_DBG, "subjectaltnameregexp");
loc = X509_get_ext_by_NID(cert, NID_subject_alt_name, -1);
if (loc < 0)
return r;
ex = X509_get_ext(cert, loc);
alt = X509V3_EXT_d2i(ex);
if (!alt)
return r;
n = sk_GENERAL_NAME_num(alt);
for (i = 0; i < n; i++) {
gn = sk_GENERAL_NAME_value(alt, i);
if (gn->type != type)
continue;
r = -1;
v = (char *)ASN1_STRING_get0_data(gn->d.ia5);
l = ASN1_STRING_length(gn->d.ia5);
if (l <= 0)
continue;
#ifdef DEBUG
printfchars(NULL, gn->type == GEN_DNS ? "dns" : "uri", NULL, (uint8_t *) v, l);
#endif
if (exact) {
if (memcmp(v, exact, l))
continue;
} else {
s = stringcopy((char *)v, l);
if (!s) {
debug(DBG_ERR, "malloc failed");
continue;
}
debug(DBG_DBG, "subjectaltnameregex: matching %s", s);
if (regexec(regex, s, 0, NULL, 0)) {
tmp = fail;
if (asprintf(&fail, "%s%s%s", tmp ? tmp : "", tmp ? ", " : "", s) >= 0)
free(tmp);
else
fail = tmp;
free(s);
continue;
}
free(s);
}
r = 1;
break;
}
if (r!=1)
debug(DBG_WARN, "subjectaltnameregex: no matching Subject Alt Name %s found! (%s)",
type == GEN_DNS ? "DNS" : "URI", fail);
GENERAL_NAMES_free(alt);
free(fail);
return r;
}
static int cnregexp(X509 *cert, char *exact, regex_t *regex) {
int loc, l;
char *v, *s;
X509_NAME *nm;
X509_NAME_ENTRY *e;
ASN1_STRING *t;
nm = X509_get_subject_name(cert);
loc = -1;
for (;;) {
loc = X509_NAME_get_index_by_NID(nm, NID_commonName, loc);
if (loc == -1)
break;
e = X509_NAME_get_entry(nm, loc);
t = X509_NAME_ENTRY_get_data(e);
v = (char *) ASN1_STRING_get0_data(t);
l = ASN1_STRING_length(t);
if (l < 0)
continue;
if (exact) {
if (l == strlen(exact) && !strncasecmp(exact, v, l))
return 1;
} else {
s = stringcopy((char *)v, l);
if (!s) {
debug(DBG_ERR, "malloc failed");
continue;
}
if (regexec(regex, s, 0, NULL, 0)) {
free(s);
continue;
}
free(s);
return 1;
}
}
return 0;
}
/* this is a bit sloppy, should not always accept match to any */
int certnamecheck(X509 *cert, struct list *hostports) {
struct list_node *entry;
struct hostportres *hp;
int r = 0;
uint8_t type = 0; /* 0 for DNS, AF_INET for IPv4, AF_INET6 for IPv6 */
struct in6_addr addr;
for (entry = list_first(hostports); entry; entry = list_next(entry)) {
hp = (struct hostportres *)entry->data;
if (hp->prefixlen != 255) {
/* we disable the check for prefixes */
return 1;
}
if (inet_pton(AF_INET, hp->host, &addr))
type = AF_INET;
else if (inet_pton(AF_INET6, hp->host, &addr))
type = AF_INET6;
else
type = 0;
if (type)
r = subjectaltnameaddr(cert, type, &addr);
if (!r)
r = subjectaltnameregexp(cert, GEN_DNS, hp->host, NULL);
if (r) {
if (r > 0) {
debug(DBG_DBG, "certnamecheck: Found subjectaltname matching %s %s", type ? "address" : "host", hp->host);
return 1;
}
debug(DBG_WARN, "certnamecheck: No subjectaltname matching %s %s", type ? "address" : "host", hp->host);
} else {
if (cnregexp(cert, hp->host, NULL)) {
debug(DBG_DBG, "certnamecheck: Found cn matching host %s", hp->host);
return 1;
}
debug(DBG_WARN, "certnamecheck: cn not matching host %s", hp->host);
}
}
return 0;
}
int verifyconfcert(X509 *cert, struct clsrvconf *conf) {
char *subject;
char addrbuf[INET6_ADDRSTRLEN];
int ok = 1;
subject = X509_NAME_oneline(X509_get_subject_name(cert), NULL, 0);
debug(DBG_DBG, "verifyconfcert: verify certificate for host %s, subject %s", conf->name, subject);
if (conf->certnamecheck) {
debug(DBG_DBG, "verifyconfcert: verify hostname");
if (!certnamecheck(cert, conf->hostports)) {
debug(DBG_DBG, "verifyconfcert: certificate name check failed for host %s", conf->name);
ok = 0;
}
}
if (conf->certcnregex) {
debug(DBG_DBG, "verifyconfcert: matching CN regex %s", conf->matchcertattr);
if (cnregexp(cert, NULL, conf->certcnregex) < 1) {
debug(DBG_WARN, "verifyconfcert: CN not matching regex for host %s (%s)", conf->name, subject);
ok = 0;
}
}
if (conf->certuriregex) {
debug(DBG_DBG, "verifyconfcert: matching subjectaltname URI regex %s", conf->matchcertattr);
if (subjectaltnameregexp(cert, GEN_URI, NULL, conf->certuriregex) < 1) {
debug(DBG_WARN, "verifyconfcert: subjectaltname URI not matching regex for host %s (%s)", conf->name, subject);
ok = 0;
}
}
if (conf->certdnsregex) {
debug(DBG_DBG, "verifyconfcert: matching subjectaltname DNS regex %s", conf->matchcertattr);
if (subjectaltnameregexp(cert, GEN_DNS, NULL, conf->certdnsregex) < 1) {
debug(DBG_WARN, "verifyconfcert: subjectaltname DNS not matching regex for host %s (%s)", conf->name, subject);
ok = 0;
}
}
if (conf->certipmatchaf) {
debug(DBG_DBG, "verifyconfcert: matching subjectaltname IP %s", inet_ntop(conf->certipmatchaf, &conf->certipmatch, addrbuf, INET6_ADDRSTRLEN));
if (subjectaltnameaddr(cert, conf->certipmatchaf, &conf->certipmatch) < 1) {
debug(DBG_WARN, "verifyconfcert: subjectaltname IP not matching regex for host %s (%s)", conf->name, subject);
ok = 0;
}
}
free(subject);
return ok;
}
int tlssn_in_conf(char *tlssn, struct clsrvconf *conf) {
char *sn = NULL;
int ret = 0;
int i;
if ((!tlssn) || (!conf) || (!conf->tlssn)) {
return 0;
}
for (i=0, sn=conf->tlssn[i]; sn; sn=conf->tlssn[++i]) {
if (!strcasecmp(tlssn, sn)) {
ret = 1;
break;
}
}
return ret;
}
int conftls_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
struct tls *conf;
long int expiry = LONG_MIN;
debug(DBG_DBG, "conftls_cb called for %s", block);
conf = malloc(sizeof(struct tls));
if (!conf) {
debug(DBG_ERR, "conftls_cb: malloc failed");
return 0;
}
memset(conf, 0, sizeof(struct tls));
if (!getgenericconfig(cf, block,
"CACertificateFile", CONF_STR, &conf->cacertfile,
"CACertificatePath", CONF_STR, &conf->cacertpath,
"CertificateFile", CONF_STR, &conf->certfile,
"CertificateKeyFile", CONF_STR, &conf->certkeyfile,
"CertificateKeyPassword", CONF_STR, &conf->certkeypwd,
"CacheExpiry", CONF_LINT, &expiry,
"CRLCheck", CONF_BLN, &conf->crlcheck,
"PolicyOID", CONF_MSTR, &conf->policyoids,
"SNICallback", CONF_BLN, &conf->snicallback,
NULL
)) {
debug(DBG_ERR, "conftls_cb: configuration error in block %s", val);
goto errexit;
}
if (!conf->certfile || !conf->certkeyfile) {
debug(DBG_ERR, "conftls_cb: TLSCertificateFile and TLSCertificateKeyFile must be specified in block %s", val);
goto errexit;
}
if (!conf->cacertfile && !conf->cacertpath) {
debug(DBG_ERR, "conftls_cb: CA Certificate file or path need to be specified in block %s", val);
goto errexit;
}
if (expiry != LONG_MIN) {
if (expiry < 0) {
debug(DBG_ERR, "error in block %s, value of option CacheExpiry is %ld, may not be negative", val, expiry);
goto errexit;
}
conf->cacheexpiry = expiry;
}
conf->name = stringcopy(val, 0);
if (!conf->name) {
debug(DBG_ERR, "conftls_cb: malloc failed");
goto errexit;
}
pthread_mutex_init(&conf->lock, NULL);
if (!tlsconfs)
tlsconfs = hash_create();
if (!hash_insert(tlsconfs, val, strlen(val), conf)) {
debug(DBG_ERR, "conftls_cb: malloc failed");
goto errexit;
}
if (!tlsgetctx(RAD_TLS, conf))
debug(DBG_ERR, "conftls_cb: error creating ctx for TLS block %s", val);
debug(DBG_DBG, "conftls_cb: added TLS block %s", val);
return 1;
errexit:
free(conf->cacertfile);
free(conf->cacertpath);
free(conf->certfile);
free(conf->certkeyfile);
free(conf->certkeypwd);
freegconfmstr(conf->policyoids);
free(conf);
return 0;
}
int addmatchcertattr(struct clsrvconf *conf) {
char *v;
regex_t **r;
if (!strncasecmp(conf->matchcertattr, "SubjectAltName:IP:", 18)) {
if (inet_pton(AF_INET, conf->matchcertattr+18, &conf->certipmatch))
conf->certipmatchaf = AF_INET;
else if (inet_pton(AF_INET6, conf->matchcertattr+18, &conf->certipmatch))
conf->certipmatchaf = AF_INET6;
else
return 0;
return 1;
}
/* the other cases below use a common regex match */
if (!strncasecmp(conf->matchcertattr, "CN:/", 4)) {
r = &conf->certcnregex;
v = conf->matchcertattr + 4;
} else if (!strncasecmp(conf->matchcertattr, "SubjectAltName:URI:/", 20)) {
r = &conf->certuriregex;
v = conf->matchcertattr + 20;
} else if (!strncasecmp(conf->matchcertattr, "SubjectAltName:DNS:/", 20)) {
r = &conf->certdnsregex;
v = conf->matchcertattr + 20;
}
else
return 0;
if (!*v)
return 0;
/* regexp, remove optional trailing / if present */
if (v[strlen(v) - 1] == '/')
v[strlen(v) - 1] = '\0';
if (!*v)
return 0;
*r = malloc(sizeof(regex_t));
if (!*r) {
debug(DBG_ERR, "malloc failed");
return 0;
}
if (regcomp(*r, v, REG_EXTENDED | REG_ICASE | REG_NOSUB)) {
free(*r);
*r = NULL;
debug(DBG_ERR, "failed to compile regular expression %s", v);
return 0;
}
return 1;
}
int sslaccepttimeout (SSL *ssl, int timeout) {
int socket, origflags, ndesc, r = -1, sockerr = 0;
socklen_t errlen = sizeof(sockerr);
struct pollfd fds[1];
uint8_t want_write = 1;
socket = SSL_get_fd(ssl);
origflags = fcntl(socket, F_GETFL, 0);
if (origflags == -1) {
debugerrno(errno, DBG_WARN, "Failed to get flags");
return -1;
}
if (fcntl(socket, F_SETFL, origflags | O_NONBLOCK) == -1) {
debugerrno(errno, DBG_WARN, "Failed to set O_NONBLOCK");
return -1;
}
while (r < 1) {
fds[0].fd = socket;
fds[0].events = POLLIN;
if (want_write) {
fds[0].events |= POLLOUT;
want_write = 0;
}
if ((ndesc = poll(fds, 1, timeout * 1000)) < 1) {
if (ndesc == 0)
debug(DBG_DBG, "sslaccepttimeout: timeout during SSL_accept");
else
debugerrno(errno, DBG_DBG, "sslaccepttimeout: poll error");
break;
}
if (fds[0].revents & POLLERR) {
if(!getsockopt(socket, SOL_SOCKET, SO_ERROR, (void *)&sockerr, &errlen))
debug(DBG_WARN, "SSL Accept failed: %s", strerror(sockerr));
else
debug(DBG_WARN, "SSL Accept failed: unknown error");
} else if (fds[0].revents & POLLHUP) {
debug(DBG_WARN, "SSL Accept error: hang up");
} else if (fds[0].revents & POLLNVAL) {
debug(DBG_WARN, "SSL Accept error: fd not open");
} else {
r = SSL_accept(ssl);
if (r <= 0) {
switch (SSL_get_error(ssl, r)) {
case SSL_ERROR_WANT_WRITE:
want_write = 1;
case SSL_ERROR_WANT_READ:
continue;
}
}
}
break;
}
if (fcntl(socket, F_SETFL, origflags) == -1)
debugerrno(errno, DBG_WARN, "Failed to set original flags back");
return r;
}
int sslconnecttimeout(SSL *ssl, int timeout) {
int socket, origflags, ndesc, r = -1, sockerr = 0;
socklen_t errlen = sizeof(sockerr);
struct pollfd fds[1];
uint8_t want_write = 1;
socket = SSL_get_fd(ssl);
origflags = fcntl(socket, F_GETFL, 0);
if (origflags == -1) {
debugerrno(errno, DBG_WARN, "Failed to get flags");
return -1;
}
if (fcntl(socket, F_SETFL, origflags | O_NONBLOCK) == -1) {
debugerrno(errno, DBG_WARN, "Failed to set O_NONBLOCK");
return -1;
}
while (r < 1) {
fds[0].fd = socket;
fds[0].events = POLLIN;
if (want_write) {
fds[0].events |= POLLOUT;
want_write = 0;
}
if ((ndesc = poll(fds, 1, timeout * 1000)) < 1) {
if (ndesc == 0)
debug(DBG_DBG, "sslconnecttimeout: timeout during SSL_connect");
else
debugerrno(errno, DBG_DBG, "sslconnecttimeout: poll error");
break;
}
if (fds[0].revents & POLLERR) {
if(!getsockopt(socket, SOL_SOCKET, SO_ERROR, (void *)&sockerr, &errlen))
debug(DBG_WARN, "SSL Connection failed: %s", strerror(sockerr));
else
debug(DBG_WARN, "SSL Connection failed: unknown error");
} else if (fds[0].revents & POLLHUP) {
debug(DBG_WARN, "SSL Connect error: hang up");
} else if (fds[0].revents & POLLNVAL) {
debug(DBG_WARN, "SSL Connect error: fd not open");
} else {
r = SSL_connect(ssl);
if (r <= 0) {
switch (SSL_get_error(ssl, r)) {
case SSL_ERROR_WANT_WRITE:
want_write = 1;
case SSL_ERROR_WANT_READ:
continue;
}
}
}
break;
}
if (fcntl(socket, F_SETFL, origflags) == -1)
debugerrno(errno, DBG_WARN, "Failed to set original flags back");
return r;
}
#else
/* Just to makes file non-empty, should rather avoid compiling this file when not needed */
static void tlsdummy() {
}
#endif
/* Local Variables: */
/* c-file-style: "stroustrup" */
/* End: */
|
the_stack_data/1106724.c | /* This file is part of The Firekylin Operating System.
*
* Copyright 2016 Liuxiaofeng
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <string.h>
int strncmp(const char *s1, const char *s2, size_t n)
{
char *ts1=(char *)s1;
char *ts2=(char *)s2;
while (n--) {
if (*ts1 && (*ts1 == *ts2)) {
ts1++;
ts2++;
} else {
return (*ts1 - *ts2);
}
}
return 0;
}
|
the_stack_data/90402.c | /* HAL raised several warnings, ignore them */
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-parameter"
#ifdef STM32F2xx
#include "stm32f2xx_hal_cryp.c"
#elif STM32F4xx
#include "stm32f4xx_hal_cryp.c"
#elif STM32F7xx
#include "stm32f7xx_hal_cryp.c"
#elif STM32G0xx
#include "stm32g0xx_hal_cryp.c"
#elif STM32G4xx
#include "stm32g4xx_hal_cryp.c"
#elif STM32H7xx
#include "stm32h7xx_hal_cryp.c"
#elif STM32L0xx
#include "stm32l0xx_hal_cryp.c"
#elif STM32L1xx
#include "stm32l1xx_hal_cryp.c"
#elif STM32L4xx
#include "stm32l4xx_hal_cryp.c"
#elif STM32L5xx
#include "stm32l5xx_hal_cryp.c"
#elif STM32MP1xx
#include "stm32mp1xx_hal_cryp.c"
#elif STM32WBxx
#include "stm32wbxx_hal_cryp.c"
#elif STM32WLxx
#include "stm32wlxx_hal_cryp.c"
#endif
#pragma GCC diagnostic pop
|
the_stack_data/651730.c | int main(int argc, char** argv) {
int i = 40;
return i+2;
}
|
the_stack_data/942092.c | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
void vulnFunction(char *input) {
char buffer[16] = {'\0'};
printf("Address of %s: %p\n", "shellcode", getenv("shellcode"));
strcpy(buffer, input); //copy input to buffer
printf("Hello %s!\n",buffer);
}
int main(int argc, char *argv[]) {
if (!(setreuid(0, 0)==0)) //Get studentroot(owner) priviledges
printf("\nSetuid failed.\n");
vulnFunction(argv[1]);
}
|
the_stack_data/93888000.c | #include<stdio.h>
int main()
{
const int ROWS=10;
int row,col;
for(row=1;row<=ROWS;++row)
{
for(col=1;col<=row;++col)
printf(" ");
for(col=1;col<=ROWS-row;++col)
printf("*");
printf("\n");
}
return 0;
}
|
the_stack_data/22012786.c | #include <stdint.h>
/* Implements the xoshiro128+ PRNG. */
static uint32_t rotl(const uint32_t x, const int k)
{
return (x << k) | (x >> (32 - k));
}
static uint32_t s[4];
static uint32_t splitmix32(uint32_t* x)
{
uint32_t z = (*x += 0x9e3779b9UL);
z = (z ^ (z >> 15)) * 0xbf58476dUL;
z = (z ^ (z >> 13)) * 0x94d049bbUL;
return z ^ (z >> 16);
}
static void seed(
const uint32_t s0,
const uint32_t s1,
const uint32_t s2,
const uint32_t s3
) {
s[0] = s0;
s[1] = s1;
s[2] = s2;
s[3] = s3;
}
uint32_t xoshiro_next(void)
{
const uint32_t result = s[0] + s[3];
const uint32_t t = s[1] << 9;
s[2] ^= s[0];
s[3] ^= s[1];
s[1] ^= s[2];
s[0] ^= s[3];
s[2] ^= t;
s[3] = rotl(s[3], 11);
return result;
}
void xoshiro_seed(uint32_t s)
{
const uint32_t s0 = splitmix32(&s);
const uint32_t s1 = splitmix32(&s);
const uint32_t s2 = splitmix32(&s);
const uint32_t s3 = splitmix32(&s);
seed(s0, s1, s2, s3);
}
float xoshiro_rand(void)
{
return ((float) xoshiro_next()) / ((float) UINT32_MAX);
}
|
the_stack_data/141177.c | static unsigned char memory[65536];
unsigned char memmapRead(unsigned int addr) {
if (addr < 65536) {
return memory[addr];
} else {
return 255;
}
}
void memmapWrite(unsigned int addr, unsigned char byte) {
if (addr < 65536) {
memory[addr] = byte;
}
}
|
the_stack_data/151707018.c | //fib.2c
//
//sum of last 3 terms is next term.
//
#include<stdio.h>
int main()
{
int t1 = 1, t2 = 2, t3 = 3, t, n = 3 ,i;
printf("\n\nEnter no of terms ( n > 3 ):\t");
scanf("%d", &n);
assert(n > 3);
printf("%d\t%d\t%d", t1, t2, t3);
for(i = 3 ; i < n ; i++)
{
t = t1 + t2 + t3;
printf("\t%d" ,t);
t1 = t2;
t2 = t3;
t3 = t;
}
}
|
the_stack_data/11075810.c |
#define SIZE 10
int v[SIZE] = {5,2,9,6,3,10,7,4,1,8};
int summ=0;
void main (void) {
int i;
summ;
for (i = 0; i < SIZE; i++) {
summ+=v[i];
}
}
|
the_stack_data/182952663.c | /*Exercise 3 - Repetition
Write a C program to calculate the sum of the numbers from 1 to n.
Where n is a keyboard input.
e.g.
n -> 100
sum = 1+2+3+....+ 99+100 = 5050
n -> 1-
sum = 1+2+3+...+10 = 55 */
#include <stdio.h>
int main() {
int i, n, sum=0;
//input a number from user
printf("Enter an upper limit : ");
scanf("%d", &n);
//find the sum of all numbers
for(i=1; i<=n; i++)
{
sum = sum + i;
}
printf("Sum of first %d natural number : %d", n, sum);
return 0;
}
|
the_stack_data/198581418.c | /* ************************************************************************
crc-32_test.c
**************************************************************************/
/*
https://my.st.com/public/STe2ecommunities/mcu/Lists/cortex_mx_stm32/Flat.aspx?RootFolder=https%3a%2f%2fmy.st.com%2fpublic%2fSTe2ecommunities%2fmcu%2fLists%2fcortex_mx_stm32%2fCC%2b%2b%20Example%20for%20CRC%20Calculation&FolderCTID=0x01200200770978C69A1141439FE559EB459D7580009C4E14902C3CDE46A77F0FFD06506F5B¤tviews=2282
gcc crc-32_test.c -o crc-32_test -lz && ./crc-32_test
*/
unsigned int Crc32(unsigned int* pData, unsigned int intcount)
{
int i;
int k;
unsigned int Crc = 0xFFFFFFFF;
for (k = 0; k < intcount; k += 1)
{
Crc = Crc ^ *pData++;
for(i=0; i<32; i++)
if (Crc & 0x80000000)
Crc = (Crc << 1) ^ 0x04C11DB7; // Polynomial used in STM32
else
Crc = (Crc << 1);
}
return(Crc);
}
unsigned int Crc32Fast(unsigned int* pData, unsigned int intcount)
{
static const unsigned int CrcTable[16] = { // Nibble lookup table for 0x04C11DB7 polynomial
0x00000000,0x04C11DB7,0x09823B6E,0x0D4326D9,0x130476DC,0x17C56B6B,0x1A864DB2,0x1E475005,
0x2608EDB8,0x22C9F00F,0x2F8AD6D6,0x2B4BCB61,0x350C9B64,0x31CD86D3,0x3C8EA00A,0x384FBDBD };
int k;
unsigned int Crc = 0xFFFFFFFF;
for (k = 0; k < intcount; k += 1)
{
Crc = Crc ^ *pData++; // Apply all 32-bits
// Process 32-bits, 4 at a time, or 8 rounds
Crc = (Crc << 4) ^ CrcTable[Crc >> 28]; // Assumes 32-bit reg, masking index to 4-bits
Crc = (Crc << 4) ^ CrcTable[Crc >> 28]; // 0x04C11DB7 Polynomial used in STM32
Crc = (Crc << 4) ^ CrcTable[Crc >> 28];
Crc = (Crc << 4) ^ CrcTable[Crc >> 28];
Crc = (Crc << 4) ^ CrcTable[Crc >> 28];
Crc = (Crc << 4) ^ CrcTable[Crc >> 28];
Crc = (Crc << 4) ^ CrcTable[Crc >> 28];
Crc = (Crc << 4) ^ CrcTable[Crc >> 28];
}
return(Crc);
}
void main (void)
{
unsigned int z[4] = { 0x12345678, 0x87654321, 0xabcdef12, 0x1};
printf("%08X\n\n",Crc32(z,4)); //
printf("%08X\n\n",Crc32Fast(z,4)); //
}
|
the_stack_data/181393753.c | extern void __VERIFIER_error() __attribute__ ((__noreturn__));
void __VERIFIER_assert(int expression) { if (!expression) { ERROR: __VERIFIER_error(); }; return; }
int __global_lock;
void __VERIFIER_atomic_begin() { __VERIFIER_assume(__global_lock==0); __global_lock=1; return; }
void __VERIFIER_atomic_end() { __VERIFIER_assume(__global_lock==1); __global_lock=0; return; }
#include <assert.h>
#include <pthread.h>
#ifndef TRUE
#define TRUE (_Bool)1
#endif
#ifndef FALSE
#define FALSE (_Bool)0
#endif
#ifndef NULL
#define NULL ((void*)0)
#endif
#ifndef FENCE
#define FENCE(x) ((void)0)
#endif
#ifndef IEEE_FLOAT_EQUAL
#define IEEE_FLOAT_EQUAL(x,y) (x==y)
#endif
#ifndef IEEE_FLOAT_NOTEQUAL
#define IEEE_FLOAT_NOTEQUAL(x,y) (x!=y)
#endif
void * P0(void *arg);
void * P1(void *arg);
void * P2(void *arg);
void * P3(void *arg);
void fence();
void isync();
void lwfence();
int __unbuffered_cnt;
int __unbuffered_cnt = 0;
int __unbuffered_p3_EAX;
int __unbuffered_p3_EAX = 0;
int __unbuffered_p3_EBX;
int __unbuffered_p3_EBX = 0;
int a;
int a = 0;
int b;
int b = 0;
_Bool b$flush_delayed;
int b$mem_tmp;
_Bool b$r_buff0_thd0;
_Bool b$r_buff0_thd1;
_Bool b$r_buff0_thd2;
_Bool b$r_buff0_thd3;
_Bool b$r_buff0_thd4;
_Bool b$r_buff1_thd0;
_Bool b$r_buff1_thd1;
_Bool b$r_buff1_thd2;
_Bool b$r_buff1_thd3;
_Bool b$r_buff1_thd4;
_Bool b$read_delayed;
int *b$read_delayed_var;
int b$w_buff0;
_Bool b$w_buff0_used;
int b$w_buff1;
_Bool b$w_buff1_used;
_Bool main$tmp_guard0;
_Bool main$tmp_guard1;
int x;
int x = 0;
int y;
int y = 0;
int z;
int z = 0;
_Bool weak$$choice0;
_Bool weak$$choice2;
void * P0(void *arg)
{
__VERIFIER_atomic_begin();
b$w_buff1 = b$w_buff0;
b$w_buff0 = 1;
b$w_buff1_used = b$w_buff0_used;
b$w_buff0_used = TRUE;
__VERIFIER_assert(!(b$w_buff1_used && b$w_buff0_used));
b$r_buff1_thd0 = b$r_buff0_thd0;
b$r_buff1_thd1 = b$r_buff0_thd1;
b$r_buff1_thd2 = b$r_buff0_thd2;
b$r_buff1_thd3 = b$r_buff0_thd3;
b$r_buff1_thd4 = b$r_buff0_thd4;
b$r_buff0_thd1 = TRUE;
__VERIFIER_atomic_end();
__VERIFIER_atomic_begin();
x = 1;
__VERIFIER_atomic_end();
__VERIFIER_atomic_begin();
b = b$w_buff0_used && b$r_buff0_thd1 ? b$w_buff0 : (b$w_buff1_used && b$r_buff1_thd1 ? b$w_buff1 : b);
b$w_buff0_used = b$w_buff0_used && b$r_buff0_thd1 ? FALSE : b$w_buff0_used;
b$w_buff1_used = b$w_buff0_used && b$r_buff0_thd1 || b$w_buff1_used && b$r_buff1_thd1 ? FALSE : b$w_buff1_used;
b$r_buff0_thd1 = b$w_buff0_used && b$r_buff0_thd1 ? FALSE : b$r_buff0_thd1;
b$r_buff1_thd1 = b$w_buff0_used && b$r_buff0_thd1 || b$w_buff1_used && b$r_buff1_thd1 ? FALSE : b$r_buff1_thd1;
__VERIFIER_atomic_end();
__VERIFIER_atomic_begin();
__unbuffered_cnt = __unbuffered_cnt + 1;
__VERIFIER_atomic_end();
return nondet_0();
}
void * P1(void *arg)
{
__VERIFIER_atomic_begin();
x = 2;
__VERIFIER_atomic_end();
__VERIFIER_atomic_begin();
y = 1;
__VERIFIER_atomic_end();
__VERIFIER_atomic_begin();
b = b$w_buff0_used && b$r_buff0_thd2 ? b$w_buff0 : (b$w_buff1_used && b$r_buff1_thd2 ? b$w_buff1 : b);
b$w_buff0_used = b$w_buff0_used && b$r_buff0_thd2 ? FALSE : b$w_buff0_used;
b$w_buff1_used = b$w_buff0_used && b$r_buff0_thd2 || b$w_buff1_used && b$r_buff1_thd2 ? FALSE : b$w_buff1_used;
b$r_buff0_thd2 = b$w_buff0_used && b$r_buff0_thd2 ? FALSE : b$r_buff0_thd2;
b$r_buff1_thd2 = b$w_buff0_used && b$r_buff0_thd2 || b$w_buff1_used && b$r_buff1_thd2 ? FALSE : b$r_buff1_thd2;
__VERIFIER_atomic_end();
__VERIFIER_atomic_begin();
__unbuffered_cnt = __unbuffered_cnt + 1;
__VERIFIER_atomic_end();
return nondet_0();
}
void * P2(void *arg)
{
__VERIFIER_atomic_begin();
y = 2;
__VERIFIER_atomic_end();
__VERIFIER_atomic_begin();
z = 1;
__VERIFIER_atomic_end();
__VERIFIER_atomic_begin();
b = b$w_buff0_used && b$r_buff0_thd3 ? b$w_buff0 : (b$w_buff1_used && b$r_buff1_thd3 ? b$w_buff1 : b);
b$w_buff0_used = b$w_buff0_used && b$r_buff0_thd3 ? FALSE : b$w_buff0_used;
b$w_buff1_used = b$w_buff0_used && b$r_buff0_thd3 || b$w_buff1_used && b$r_buff1_thd3 ? FALSE : b$w_buff1_used;
b$r_buff0_thd3 = b$w_buff0_used && b$r_buff0_thd3 ? FALSE : b$r_buff0_thd3;
b$r_buff1_thd3 = b$w_buff0_used && b$r_buff0_thd3 || b$w_buff1_used && b$r_buff1_thd3 ? FALSE : b$r_buff1_thd3;
__VERIFIER_atomic_end();
__VERIFIER_atomic_begin();
__unbuffered_cnt = __unbuffered_cnt + 1;
__VERIFIER_atomic_end();
return nondet_0();
}
void * P3(void *arg)
{
__VERIFIER_atomic_begin();
z = 2;
__VERIFIER_atomic_end();
__VERIFIER_atomic_begin();
a = 1;
__VERIFIER_atomic_end();
__VERIFIER_atomic_begin();
__unbuffered_p3_EAX = a;
__VERIFIER_atomic_end();
__VERIFIER_atomic_begin();
weak$$choice0 = nondet_1();
weak$$choice2 = nondet_1();
b$flush_delayed = weak$$choice2;
b$mem_tmp = b;
b = !b$w_buff0_used || !b$r_buff0_thd4 && !b$w_buff1_used || !b$r_buff0_thd4 && !b$r_buff1_thd4 ? b : (b$w_buff0_used && b$r_buff0_thd4 ? b$w_buff0 : b$w_buff1);
b$w_buff0 = weak$$choice2 ? b$w_buff0 : (!b$w_buff0_used || !b$r_buff0_thd4 && !b$w_buff1_used || !b$r_buff0_thd4 && !b$r_buff1_thd4 ? b$w_buff0 : (b$w_buff0_used && b$r_buff0_thd4 ? b$w_buff0 : b$w_buff0));
b$w_buff1 = weak$$choice2 ? b$w_buff1 : (!b$w_buff0_used || !b$r_buff0_thd4 && !b$w_buff1_used || !b$r_buff0_thd4 && !b$r_buff1_thd4 ? b$w_buff1 : (b$w_buff0_used && b$r_buff0_thd4 ? b$w_buff1 : b$w_buff1));
b$w_buff0_used = weak$$choice2 ? b$w_buff0_used : (!b$w_buff0_used || !b$r_buff0_thd4 && !b$w_buff1_used || !b$r_buff0_thd4 && !b$r_buff1_thd4 ? b$w_buff0_used : (b$w_buff0_used && b$r_buff0_thd4 ? FALSE : b$w_buff0_used));
b$w_buff1_used = weak$$choice2 ? b$w_buff1_used : (!b$w_buff0_used || !b$r_buff0_thd4 && !b$w_buff1_used || !b$r_buff0_thd4 && !b$r_buff1_thd4 ? b$w_buff1_used : (b$w_buff0_used && b$r_buff0_thd4 ? FALSE : FALSE));
b$r_buff0_thd4 = weak$$choice2 ? b$r_buff0_thd4 : (!b$w_buff0_used || !b$r_buff0_thd4 && !b$w_buff1_used || !b$r_buff0_thd4 && !b$r_buff1_thd4 ? b$r_buff0_thd4 : (b$w_buff0_used && b$r_buff0_thd4 ? FALSE : b$r_buff0_thd4));
b$r_buff1_thd4 = weak$$choice2 ? b$r_buff1_thd4 : (!b$w_buff0_used || !b$r_buff0_thd4 && !b$w_buff1_used || !b$r_buff0_thd4 && !b$r_buff1_thd4 ? b$r_buff1_thd4 : (b$w_buff0_used && b$r_buff0_thd4 ? FALSE : FALSE));
__unbuffered_p3_EBX = b;
b = b$flush_delayed ? b$mem_tmp : b;
b$flush_delayed = FALSE;
__VERIFIER_atomic_end();
__VERIFIER_atomic_begin();
b = b$w_buff0_used && b$r_buff0_thd4 ? b$w_buff0 : (b$w_buff1_used && b$r_buff1_thd4 ? b$w_buff1 : b);
b$w_buff0_used = b$w_buff0_used && b$r_buff0_thd4 ? FALSE : b$w_buff0_used;
b$w_buff1_used = b$w_buff0_used && b$r_buff0_thd4 || b$w_buff1_used && b$r_buff1_thd4 ? FALSE : b$w_buff1_used;
b$r_buff0_thd4 = b$w_buff0_used && b$r_buff0_thd4 ? FALSE : b$r_buff0_thd4;
b$r_buff1_thd4 = b$w_buff0_used && b$r_buff0_thd4 || b$w_buff1_used && b$r_buff1_thd4 ? FALSE : b$r_buff1_thd4;
__VERIFIER_atomic_end();
__VERIFIER_atomic_begin();
__unbuffered_cnt = __unbuffered_cnt + 1;
__VERIFIER_atomic_end();
return nondet_0();
}
void fence()
{
}
void isync()
{
}
void lwfence()
{
}
int main()
{
pthread_create(NULL, NULL, P0, NULL);
pthread_create(NULL, NULL, P1, NULL);
pthread_create(NULL, NULL, P2, NULL);
pthread_create(NULL, NULL, P3, NULL);
__VERIFIER_atomic_begin();
main$tmp_guard0 = __unbuffered_cnt == 4;
__VERIFIER_atomic_end();
__VERIFIER_assume(main$tmp_guard0);
__VERIFIER_atomic_begin();
b = b$w_buff0_used && b$r_buff0_thd0 ? b$w_buff0 : (b$w_buff1_used && b$r_buff1_thd0 ? b$w_buff1 : b);
b$w_buff0_used = b$w_buff0_used && b$r_buff0_thd0 ? FALSE : b$w_buff0_used;
b$w_buff1_used = b$w_buff0_used && b$r_buff0_thd0 || b$w_buff1_used && b$r_buff1_thd0 ? FALSE : b$w_buff1_used;
b$r_buff0_thd0 = b$w_buff0_used && b$r_buff0_thd0 ? FALSE : b$r_buff0_thd0;
b$r_buff1_thd0 = b$w_buff0_used && b$r_buff0_thd0 || b$w_buff1_used && b$r_buff1_thd0 ? FALSE : b$r_buff1_thd0;
__VERIFIER_atomic_end();
__VERIFIER_atomic_begin();
/* Program proven to be relaxed for X86, model checker says YES. */
main$tmp_guard1 = !(x == 2 && y == 2 && z == 2 && __unbuffered_p3_EAX == 1 && __unbuffered_p3_EBX == 0);
__VERIFIER_atomic_end();
/* Program proven to be relaxed for X86, model checker says YES. */
__VERIFIER_assert(main$tmp_guard1);
return 0;
}
|
the_stack_data/151706390.c | #include <stdio.h>
int main(int a,char *b[])
{
if(a<2)
{
puts("参数不够");
return 120;
};
FILE *fp=fopen(b[1],"r");
char as,sdf[500];
a=0;
sprintf(sdf,"%saghjkybvg",b[1]);
FILE *fp1=fopen(sdf,"w");
while((as=fgetc(fp))!=EOF)
{
a++;
if(a>28)
fputc(as,fp1);
if(as=='\n')
a=0;
};
fclose(fp);
fclose(fp1);
remove(b[1]);
rename(sdf,b[1]);
return 0;
}
|
the_stack_data/198580790.c | #include <stdbool.h>
#include <stdlib.h>
/*
* For documenting intentional null
* statements that do nothing.
*/
#define DO_NOTHING
#define TEMP_MIN 18U
#define TEMP_MAX 25U
static bool systemInitialized = false;
int main(void)
{
initializeSystem();
volatile int engineTemperature = 0;
startWarmup();
for (;;)
{
if (timeOut())
{
abort();
}
else
{
DO_NOTHING;
}
}
return EXIT_SUCCESS;
}
void initializeSystem(void)
{
systemInitialized = true;
}
void temperatureControlTask(void)
{
int temperature = 0;
temperature = getTemperature();
if (temperature < TEMP_MIN)
{
turnOnHeater();
}
else if (temperature > TEMP_MAX)
{
turnOffHeater();
}
else
{
}
}
|
the_stack_data/572206.c | /**
******************************************************************************
* @file stm32f0xx_ll_comp.c
* @author MCD Application Team
* @brief COMP LL module driver
******************************************************************************
* @attention
*
* <h2><center>© Copyright (c) 2016 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 "stm32f0xx_ll_comp.h"
#ifdef USE_FULL_ASSERT
#include "stm32_assert.h"
#else
#define assert_param(expr) ((void)0U)
#endif
/** @addtogroup STM32F0xx_LL_Driver
* @{
*/
#if defined (COMP1) || defined (COMP2)
/** @addtogroup COMP_LL COMP
* @{
*/
/* Private types -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private constants ---------------------------------------------------------*/
/* Private macros ------------------------------------------------------------*/
/** @addtogroup COMP_LL_Private_Macros
* @{
*/
/* Check of parameters for configuration of COMP hierarchical scope: */
/* COMP instance. */
#define IS_LL_COMP_POWER_MODE(__POWER_MODE__) \
( ((__POWER_MODE__) == LL_COMP_POWERMODE_HIGHSPEED) \
|| ((__POWER_MODE__) == LL_COMP_POWERMODE_MEDIUMSPEED) \
|| ((__POWER_MODE__) == LL_COMP_POWERMODE_LOWPOWER) \
|| ((__POWER_MODE__) == LL_COMP_POWERMODE_ULTRALOWPOWER) \
)
/* Note: On this STM32 serie, comparator input plus parameters are */
/* the different depending on COMP instances. */
#define IS_LL_COMP_INPUT_PLUS(__COMP_INSTANCE__, __INPUT_PLUS__) \
(((__COMP_INSTANCE__) == COMP1) \
? ( \
((__INPUT_PLUS__) == LL_COMP_INPUT_PLUS_IO1) \
|| ((__INPUT_PLUS__) == LL_COMP_INPUT_PLUS_DAC1_CH1) \
) \
: \
( \
((__INPUT_PLUS__) == LL_COMP_INPUT_PLUS_IO1) \
) \
)
/* Note: On this STM32 serie, comparator input minus parameters are */
/* the same on all COMP instances. */
/* However, comparator instance kept as macro parameter for */
/* compatibility with other STM32 families. */
#define IS_LL_COMP_INPUT_MINUS(__COMP_INSTANCE__, __INPUT_MINUS__) \
( ((__INPUT_MINUS__) == LL_COMP_INPUT_MINUS_1_4VREFINT) \
|| ((__INPUT_MINUS__) == LL_COMP_INPUT_MINUS_1_2VREFINT) \
|| ((__INPUT_MINUS__) == LL_COMP_INPUT_MINUS_3_4VREFINT) \
|| ((__INPUT_MINUS__) == LL_COMP_INPUT_MINUS_VREFINT) \
|| ((__INPUT_MINUS__) == LL_COMP_INPUT_MINUS_DAC1_CH1) \
|| ((__INPUT_MINUS__) == LL_COMP_INPUT_MINUS_DAC1_CH2) \
|| ((__INPUT_MINUS__) == LL_COMP_INPUT_MINUS_IO1) \
)
#define IS_LL_COMP_INPUT_HYSTERESIS(__INPUT_HYSTERESIS__) \
( ((__INPUT_HYSTERESIS__) == LL_COMP_HYSTERESIS_NONE) \
|| ((__INPUT_HYSTERESIS__) == LL_COMP_HYSTERESIS_LOW) \
|| ((__INPUT_HYSTERESIS__) == LL_COMP_HYSTERESIS_MEDIUM) \
|| ((__INPUT_HYSTERESIS__) == LL_COMP_HYSTERESIS_HIGH) \
)
#define IS_LL_COMP_OUTPUT_SELECTION(__OUTPUT_SELECTION__) \
( ((__OUTPUT_SELECTION__) == LL_COMP_OUTPUT_NONE) \
|| ((__OUTPUT_SELECTION__) == LL_COMP_OUTPUT_TIM1_BKIN) \
|| ((__OUTPUT_SELECTION__) == LL_COMP_OUTPUT_TIM1_IC1) \
|| ((__OUTPUT_SELECTION__) == LL_COMP_OUTPUT_TIM1_OCCLR) \
|| ((__OUTPUT_SELECTION__) == LL_COMP_OUTPUT_TIM2_IC4) \
|| ((__OUTPUT_SELECTION__) == LL_COMP_OUTPUT_TIM2_OCCLR) \
|| ((__OUTPUT_SELECTION__) == LL_COMP_OUTPUT_TIM3_IC1) \
|| ((__OUTPUT_SELECTION__) == LL_COMP_OUTPUT_TIM3_OCCLR) \
)
#define IS_LL_COMP_OUTPUT_POLARITY(__POLARITY__) \
( ((__POLARITY__) == LL_COMP_OUTPUTPOL_NONINVERTED) \
|| ((__POLARITY__) == LL_COMP_OUTPUTPOL_INVERTED) \
)
/**
* @}
*/
/* Private function prototypes -----------------------------------------------*/
/* Exported functions --------------------------------------------------------*/
/** @addtogroup COMP_LL_Exported_Functions
* @{
*/
/** @addtogroup COMP_LL_EF_Init
* @{
*/
/**
* @brief De-initialize registers of the selected COMP instance
* to their default reset values.
* @note If comparator is locked, de-initialization by software is
* not possible.
* The only way to unlock the comparator is a device hardware reset.
* @param COMPx COMP instance
* @retval An ErrorStatus enumeration value:
* - SUCCESS: COMP registers are de-initialized
* - ERROR: COMP registers are not de-initialized
*/
ErrorStatus LL_COMP_DeInit(COMP_TypeDef *COMPx)
{
ErrorStatus status = SUCCESS;
/* Check the parameters */
assert_param(IS_COMP_ALL_INSTANCE(COMPx));
/* Note: Hardware constraint (refer to description of this function): */
/* COMP instance must not be locked. */
if(LL_COMP_IsLocked(COMPx) == 0U)
{
/* Note: Connection switch is applicable only to COMP instance COMP1, */
/* therefore is COMP2 is selected the equivalent bit is */
/* kept unmodified. */
if(COMPx == COMP1)
{
CLEAR_BIT(COMP->CSR,
( COMP_CSR_COMP1MODE
| COMP_CSR_COMP1INSEL
| COMP_CSR_COMP1SW1
| COMP_CSR_COMP1OUTSEL
| COMP_CSR_COMP1HYST
| COMP_CSR_COMP1POL
| COMP_CSR_COMP1EN
) << __COMP_BITOFFSET_INSTANCE(COMPx)
);
}
else
{
CLEAR_BIT(COMP->CSR,
( COMP_CSR_COMP1MODE
| COMP_CSR_COMP1INSEL
| COMP_CSR_COMP1OUTSEL
| COMP_CSR_COMP1HYST
| COMP_CSR_COMP1POL
| COMP_CSR_COMP1EN
) << __COMP_BITOFFSET_INSTANCE(COMPx)
);
}
}
else
{
/* Comparator instance is locked: de-initialization by software is */
/* not possible. */
/* The only way to unlock the comparator is a device hardware reset. */
status = ERROR;
}
return status;
}
/**
* @brief Initialize some features of COMP instance.
* @note This function configures features of the selected COMP instance.
* Some features are also available at scope COMP common instance
* (common to several COMP instances).
* Refer to functions having argument "COMPxy_COMMON" as parameter.
* @param COMPx COMP instance
* @param COMP_InitStruct Pointer to a @ref LL_COMP_InitTypeDef structure
* @retval An ErrorStatus enumeration value:
* - SUCCESS: COMP registers are initialized
* - ERROR: COMP registers are not initialized
*/
ErrorStatus LL_COMP_Init(COMP_TypeDef *COMPx, LL_COMP_InitTypeDef *COMP_InitStruct)
{
ErrorStatus status = SUCCESS;
/* Check the parameters */
assert_param(IS_COMP_ALL_INSTANCE(COMPx));
assert_param(IS_LL_COMP_POWER_MODE(COMP_InitStruct->PowerMode));
assert_param(IS_LL_COMP_INPUT_PLUS(COMPx, COMP_InitStruct->InputPlus));
assert_param(IS_LL_COMP_INPUT_MINUS(COMPx, COMP_InitStruct->InputMinus));
assert_param(IS_LL_COMP_INPUT_HYSTERESIS(COMP_InitStruct->InputHysteresis));
assert_param(IS_LL_COMP_OUTPUT_SELECTION(COMP_InitStruct->OutputSelection));
assert_param(IS_LL_COMP_OUTPUT_POLARITY(COMP_InitStruct->OutputPolarity));
/* Note: Hardware constraint (refer to description of this function) */
/* COMP instance must not be locked. */
if(LL_COMP_IsLocked(COMPx) == 0U)
{
/* Configuration of comparator instance : */
/* - PowerMode */
/* - InputPlus */
/* - InputMinus */
/* - InputHysteresis */
/* - OutputSelection */
/* - OutputPolarity */
/* Note: Connection switch is applicable only to COMP instance COMP1, */
/* therefore is COMP2 is selected the equivalent bit is */
/* kept unmodified. */
if(COMPx == COMP1)
{
MODIFY_REG(COMP->CSR,
( COMP_CSR_COMP1MODE
| COMP_CSR_COMP1INSEL
| COMP_CSR_COMP1SW1
| COMP_CSR_COMP1OUTSEL
| COMP_CSR_COMP1HYST
| COMP_CSR_COMP1POL
) << __COMP_BITOFFSET_INSTANCE(COMPx)
,
( COMP_InitStruct->PowerMode
| COMP_InitStruct->InputPlus
| COMP_InitStruct->InputMinus
| COMP_InitStruct->InputHysteresis
| COMP_InitStruct->OutputSelection
| COMP_InitStruct->OutputPolarity
) << __COMP_BITOFFSET_INSTANCE(COMPx)
);
}
else
{
MODIFY_REG(COMP->CSR,
( COMP_CSR_COMP1MODE
| COMP_CSR_COMP1INSEL
| COMP_CSR_COMP1OUTSEL
| COMP_CSR_COMP1HYST
| COMP_CSR_COMP1POL
) << __COMP_BITOFFSET_INSTANCE(COMPx)
,
( COMP_InitStruct->PowerMode
| COMP_InitStruct->InputPlus
| COMP_InitStruct->InputMinus
| COMP_InitStruct->InputHysteresis
| COMP_InitStruct->OutputSelection
| COMP_InitStruct->OutputPolarity
) << __COMP_BITOFFSET_INSTANCE(COMPx)
);
}
}
else
{
/* Initialization error: COMP instance is locked. */
status = ERROR;
}
return status;
}
/**
* @brief Set each @ref LL_COMP_InitTypeDef field to default value.
* @param COMP_InitStruct pointer to a @ref LL_COMP_InitTypeDef structure
* whose fields will be set to default values.
* @retval None
*/
void LL_COMP_StructInit(LL_COMP_InitTypeDef *COMP_InitStruct)
{
/* Set COMP_InitStruct fields to default values */
COMP_InitStruct->PowerMode = LL_COMP_POWERMODE_ULTRALOWPOWER;
COMP_InitStruct->InputPlus = LL_COMP_INPUT_PLUS_IO1;
COMP_InitStruct->InputMinus = LL_COMP_INPUT_MINUS_VREFINT;
COMP_InitStruct->InputHysteresis = LL_COMP_HYSTERESIS_NONE;
COMP_InitStruct->OutputSelection = LL_COMP_OUTPUT_NONE;
COMP_InitStruct->OutputPolarity = LL_COMP_OUTPUTPOL_NONINVERTED;
}
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
#endif /* COMP1 || COMP2 */
/**
* @}
*/
#endif /* USE_FULL_LL_DRIVER */
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
|
the_stack_data/132954013.c | /*
* Copyright (C) 2008-2021 Intel Corporation.
* SPDX-License-Identifier: MIT
*/
/*
* This is a test case sent by a pinhead. It used to demonstrate a problem on newer linux
* kernels (e.g. 2.6.25) when a signal interrupts a futex system call.
*/
#include <stdio.h>
#include <pthread.h>
#include <signal.h>
#include <unistd.h>
volatile int flag = 0;
static void Handler(int);
static void* Start(void*);
int main()
{
pthread_t thrd1;
pthread_t thrd2;
pthread_create(&thrd1, 0, Start, 0);
pthread_create(&thrd2, 0, Start, (void*)1);
pthread_join(thrd1, 0);
pthread_join(thrd2, 0);
return 0;
}
static void Handler(int sig)
{
flag = 1;
printf("received signal\n");
}
static void* Start(void* v)
{
if (v != 0)
{
printf("setting alarm\n");
signal(SIGALRM, &Handler);
alarm(2);
}
printf("waiting for signal at %p\n", &flag);
while (!flag)
;
return 0;
}
|
the_stack_data/200143475.c | /*
* Copyright (C) 2015-2019 Rahmat M. Samik-Ibrahim
* http://rahmatm.samik-ibrahim.vlsm.org/
* This program is free script/software. This program is distributed in the
* hope that it will be useful, but WITHOUT ANY WARRANTY; without even the
* implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*
* TAKE NOTE (MA)
* Program ini akan mengcopy isi dari suatu file
* ke file lain yang sudah ada atau belum ada
*
* Argumen argc dan argv dari main digunakan
* sebagai cara untuk mengirim argumen ke program
* argc adalah jumlah argumen,
* argv adalah list argumennya,
* yang untuk list ke 0 merupakan nama filenya.
*
* Jadi, program ini butuh 2 argumen tambahan saat dijalankan,
* yang pertama adalah file yang isinya mau dicopy
* yang kedua adalah file hasil copy-annya
* yang jika file kedua namanya sudah ada maka akan direplace isinya
*
* Contohnya: ./56-copy test.txt test2.txt
* (test.txt harus ada dibuat terlebih dahulu dahulu atau akan error)
*
* REV04 Tue Nov 26 11:39:10 WIB 2019
* REV03 Wed Aug 29 20:55:23 WIB 2018
* REV01 Mon Oct 2 16:23:50 WIB 2017
* START Tue Apr 25 XX:XX:XX WIB 2015
* USE "cmp file1 file2"
*/
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#define BUF_SIZE 16
void main(int argc, char* argv[])
{
int fdread, fdwrite;
unsigned int total_bytes = 0;
ssize_t nbytes_read, nbytes_write;
char buf[BUF_SIZE];
if (argc != 3) {
printf("Usage: %s source destination\n",
argv[0]);
exit(1);
}
fdread = open(argv[1], O_RDONLY);
if (fdread < 0) {
perror("Failed to open source file");
exit(1);
}
fdwrite = creat(argv[2], S_IRWXU);
if (fdwrite < 0) {
perror("Failed to open destination file");
exit(1);
}
do {
nbytes_read = read(fdread, buf, BUF_SIZE);
if (nbytes_read < 0) {
perror("Failed to read from file");
exit(1);
}
nbytes_write = write(fdwrite, buf, nbytes_read);
if (nbytes_write < 0) {
perror("Failed to write to file");
exit(1);
}
} while (nbytes_read > 0);
close(fdread);
close(fdwrite);
exit(0);
}
|
the_stack_data/98576150.c | // SmallFont.c
// Font type : Full (95 characters)
// Font size : 8x12 pixels
// Memory usage : 1144 bytes
#if defined(__AVR__)
#include <avr/pgmspace.h>
#define fontdatatype const uint8_t
#elif defined(__PIC32MX__)
#define PROGMEM
#define fontdatatype const unsigned char
#elif defined(__arm__)
#define PROGMEM
#define fontdatatype const unsigned char
#endif
const unsigned char tft_SmallFont[1144] =
{
0x08,0x0C,0x20,0x5F,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, // <space>
0x00,0x00,0x20,0x20,0x20,0x20,0x20,0x20,0x00,0x20,0x00,0x00, // !
0x00,0x28,0x50,0x50,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, // "
0x00,0x00,0x28,0x28,0xFC,0x28,0x50,0xFC,0x50,0x50,0x00,0x00, // #
0x00,0x20,0x78,0xA8,0xA0,0x60,0x30,0x28,0xA8,0xF0,0x20,0x00, // $
0x00,0x00,0x48,0xA8,0xB0,0x50,0x28,0x34,0x54,0x48,0x00,0x00, // %
0x00,0x00,0x20,0x50,0x50,0x78,0xA8,0xA8,0x90,0x6C,0x00,0x00, // &
0x00,0x40,0x40,0x80,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, // '
0x00,0x04,0x08,0x10,0x10,0x10,0x10,0x10,0x10,0x08,0x04,0x00, // (
0x00,0x40,0x20,0x10,0x10,0x10,0x10,0x10,0x10,0x20,0x40,0x00, // )
0x00,0x00,0x00,0x20,0xA8,0x70,0x70,0xA8,0x20,0x00,0x00,0x00, // *
0x00,0x00,0x20,0x20,0x20,0xF8,0x20,0x20,0x20,0x00,0x00,0x00, // +
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x40,0x40,0x80, // ,
0x00,0x00,0x00,0x00,0x00,0xF8,0x00,0x00,0x00,0x00,0x00,0x00, // -
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x40,0x00,0x00, // .
0x00,0x08,0x10,0x10,0x10,0x20,0x20,0x40,0x40,0x40,0x80,0x00, // /
0x00,0x00,0x70,0x88,0x88,0x88,0x88,0x88,0x88,0x70,0x00,0x00, // 0
0x00,0x00,0x20,0x60,0x20,0x20,0x20,0x20,0x20,0x70,0x00,0x00, // 1
0x00,0x00,0x70,0x88,0x88,0x10,0x20,0x40,0x80,0xF8,0x00,0x00, // 2
0x00,0x00,0x70,0x88,0x08,0x30,0x08,0x08,0x88,0x70,0x00,0x00, // 3
0x00,0x00,0x10,0x30,0x50,0x50,0x90,0x78,0x10,0x18,0x00,0x00, // 4
0x00,0x00,0xF8,0x80,0x80,0xF0,0x08,0x08,0x88,0x70,0x00,0x00, // 5
0x00,0x00,0x70,0x90,0x80,0xF0,0x88,0x88,0x88,0x70,0x00,0x00, // 6
0x00,0x00,0xF8,0x90,0x10,0x20,0x20,0x20,0x20,0x20,0x00,0x00, // 7
0x00,0x00,0x70,0x88,0x88,0x70,0x88,0x88,0x88,0x70,0x00,0x00, // 8
0x00,0x00,0x70,0x88,0x88,0x88,0x78,0x08,0x48,0x70,0x00,0x00, // 9
0x00,0x00,0x00,0x00,0x20,0x00,0x00,0x00,0x00,0x20,0x00,0x00, // :
0x00,0x00,0x00,0x00,0x00,0x20,0x00,0x00,0x00,0x20,0x20,0x00, // ;
0x00,0x04,0x08,0x10,0x20,0x40,0x20,0x10,0x08,0x04,0x00,0x00, // <
0x00,0x00,0x00,0x00,0xF8,0x00,0x00,0xF8,0x00,0x00,0x00,0x00, // =
0x00,0x40,0x20,0x10,0x08,0x04,0x08,0x10,0x20,0x40,0x00,0x00, // >
0x00,0x00,0x70,0x88,0x88,0x10,0x20,0x20,0x00,0x20,0x00,0x00, // ?
0x00,0x00,0x70,0x88,0x98,0xA8,0xA8,0xB8,0x80,0x78,0x00,0x00, // @
0x00,0x00,0x20,0x20,0x30,0x50,0x50,0x78,0x48,0xCC,0x00,0x00, // A
0x00,0x00,0xF0,0x48,0x48,0x70,0x48,0x48,0x48,0xF0,0x00,0x00, // B
0x00,0x00,0x78,0x88,0x80,0x80,0x80,0x80,0x88,0x70,0x00,0x00, // C
0x00,0x00,0xF0,0x48,0x48,0x48,0x48,0x48,0x48,0xF0,0x00,0x00, // D
0x00,0x00,0xF8,0x48,0x50,0x70,0x50,0x40,0x48,0xF8,0x00,0x00, // E
0x00,0x00,0xF8,0x48,0x50,0x70,0x50,0x40,0x40,0xE0,0x00,0x00, // F
0x00,0x00,0x38,0x48,0x80,0x80,0x9C,0x88,0x48,0x30,0x00,0x00, // G
0x00,0x00,0xCC,0x48,0x48,0x78,0x48,0x48,0x48,0xCC,0x00,0x00, // H
0x00,0x00,0xF8,0x20,0x20,0x20,0x20,0x20,0x20,0xF8,0x00,0x00, // I
0x00,0x00,0x7C,0x10,0x10,0x10,0x10,0x10,0x10,0x90,0xE0,0x00, // J
0x00,0x00,0xEC,0x48,0x50,0x60,0x50,0x50,0x48,0xEC,0x00,0x00, // K
0x00,0x00,0xE0,0x40,0x40,0x40,0x40,0x40,0x44,0xFC,0x00,0x00, // L
0x00,0x00,0xD8,0xD8,0xD8,0xD8,0xA8,0xA8,0xA8,0xA8,0x00,0x00, // M
0x00,0x00,0xDC,0x48,0x68,0x68,0x58,0x58,0x48,0xE8,0x00,0x00, // N
0x00,0x00,0x70,0x88,0x88,0x88,0x88,0x88,0x88,0x70,0x00,0x00, // O
0x00,0x00,0xF0,0x48,0x48,0x70,0x40,0x40,0x40,0xE0,0x00,0x00, // P
0x00,0x00,0x70,0x88,0x88,0x88,0x88,0xE8,0x98,0x70,0x18,0x00, // Q
0x00,0x00,0xF0,0x48,0x48,0x70,0x50,0x48,0x48,0xEC,0x00,0x00, // R
0x00,0x00,0x78,0x88,0x80,0x60,0x10,0x08,0x88,0xF0,0x00,0x00, // S
0x00,0x00,0xF8,0xA8,0x20,0x20,0x20,0x20,0x20,0x70,0x00,0x00, // T
0x00,0x00,0xCC,0x48,0x48,0x48,0x48,0x48,0x48,0x30,0x00,0x00, // U
0x00,0x00,0xCC,0x48,0x48,0x50,0x50,0x30,0x20,0x20,0x00,0x00, // V
0x00,0x00,0xA8,0xA8,0xA8,0x70,0x50,0x50,0x50,0x50,0x00,0x00, // W
0x00,0x00,0xD8,0x50,0x50,0x20,0x20,0x50,0x50,0xD8,0x00,0x00, // X
0x00,0x00,0xD8,0x50,0x50,0x20,0x20,0x20,0x20,0x70,0x00,0x00, // Y
0x00,0x00,0xF8,0x90,0x10,0x20,0x20,0x40,0x48,0xF8,0x00,0x00, // Z
0x00,0x38,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x38,0x00, // [
0x00,0x40,0x40,0x40,0x20,0x20,0x10,0x10,0x10,0x08,0x00,0x00, // <backslash>
0x00,0x70,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x70,0x00, // ]
0x00,0x20,0x50,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, // ^
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xFC, // _
0x00,0x20,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, // `
0x00,0x00,0x00,0x00,0x00,0x30,0x48,0x38,0x48,0x3C,0x00,0x00, // a
0x00,0x00,0xC0,0x40,0x40,0x70,0x48,0x48,0x48,0x70,0x00,0x00, // b
0x00,0x00,0x00,0x00,0x00,0x38,0x48,0x40,0x40,0x38,0x00,0x00, // c
0x00,0x00,0x18,0x08,0x08,0x38,0x48,0x48,0x48,0x3C,0x00,0x00, // d
0x00,0x00,0x00,0x00,0x00,0x30,0x48,0x78,0x40,0x38,0x00,0x00, // e
0x00,0x00,0x1C,0x20,0x20,0x78,0x20,0x20,0x20,0x78,0x00,0x00, // f
0x00,0x00,0x00,0x00,0x00,0x3C,0x48,0x30,0x40,0x78,0x44,0x38, // g
0x00,0x00,0xC0,0x40,0x40,0x70,0x48,0x48,0x48,0xEC,0x00,0x00, // h
0x00,0x00,0x20,0x00,0x00,0x60,0x20,0x20,0x20,0x70,0x00,0x00, // i
0x00,0x00,0x10,0x00,0x00,0x30,0x10,0x10,0x10,0x10,0x10,0xE0, // j
0x00,0x00,0xC0,0x40,0x40,0x5C,0x50,0x70,0x48,0xEC,0x00,0x00, // k
0x00,0x00,0xE0,0x20,0x20,0x20,0x20,0x20,0x20,0xF8,0x00,0x00, // l
0x00,0x00,0x00,0x00,0x00,0xF0,0xA8,0xA8,0xA8,0xA8,0x00,0x00, // m
0x00,0x00,0x00,0x00,0x00,0xF0,0x48,0x48,0x48,0xEC,0x00,0x00, // n
0x00,0x00,0x00,0x00,0x00,0x30,0x48,0x48,0x48,0x30,0x00,0x00, // o
0x00,0x00,0x00,0x00,0x00,0xF0,0x48,0x48,0x48,0x70,0x40,0xE0, // p
0x00,0x00,0x00,0x00,0x00,0x38,0x48,0x48,0x48,0x38,0x08,0x1C, // q
0x00,0x00,0x00,0x00,0x00,0xD8,0x60,0x40,0x40,0xE0,0x00,0x00, // r
0x00,0x00,0x00,0x00,0x00,0x78,0x40,0x30,0x08,0x78,0x00,0x00, // s
0x00,0x00,0x00,0x20,0x20,0x70,0x20,0x20,0x20,0x18,0x00,0x00, // t
0x00,0x00,0x00,0x00,0x00,0xD8,0x48,0x48,0x48,0x3C,0x00,0x00, // u
0x00,0x00,0x00,0x00,0x00,0xEC,0x48,0x50,0x30,0x20,0x00,0x00, // v
0x00,0x00,0x00,0x00,0x00,0xA8,0xA8,0x70,0x50,0x50,0x00,0x00, // w
0x00,0x00,0x00,0x00,0x00,0xD8,0x50,0x20,0x50,0xD8,0x00,0x00, // x
0x00,0x00,0x00,0x00,0x00,0xEC,0x48,0x50,0x30,0x20,0x20,0xC0, // y
0x00,0x00,0x00,0x00,0x00,0x78,0x10,0x20,0x20,0x78,0x00,0x00, // z
0x00,0x18,0x10,0x10,0x10,0x20,0x10,0x10,0x10,0x10,0x18,0x00, // {
0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10, // |
0x00,0x60,0x20,0x20,0x20,0x10,0x20,0x20,0x20,0x20,0x60,0x00, // }
0x40,0xA4,0x18,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, // ~
};
|
the_stack_data/103266380.c | /**********************************************************************************/
/* Copyright (c) 2018, Christopher Deotte */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining a copy */
/* of this software and associated documentation files (the "Software"), to deal */
/* in the Software without restriction, including without limitation the rights */
/* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell */
/* copies of the Software, and to permit persons to whom the Software is */
/* furnished to do so, subject to the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be included in all */
/* copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR */
/* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, */
/* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE */
/* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER */
/* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, */
/* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE */
/* SOFTWARE. */
/**********************************************************************************/
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<sys/stat.h>
#include<unistd.h>
#include<dirent.h>
#include<math.h>
#include<time.h>
#include<pthread.h>
/* WEBGUI External Routines needed from webgui.c */
/* (These could be placed into a webgui.h) */
int webstart(int x);
void webreadline(char* str);
void webwriteline(char* str);
void webinit(char* str,int x);
void webupdate(int* ip, double* rp, char* sp);
void websettitle(char* str);
void websetmode(int x);
void webstop();
void websetcolors(int nc, double* r,double* g,double* b,int pane);
void webimagedisplay(int nx, int ny, int* image, int ipane);
void webframe(int frame);
void weblineflt(float* x, float* y, float* z, int n, int color);
void webfillflt(float* x, float* y, float* z, int n, int color);
void weblinedbl(double* x, double* y, double* z, int n, int color);
void webfilldbl(double* x, double* y, double* z, int n, int icolor);
void webgldisplay(int pane);
int webquery();
void webbutton(int highlight,char* cmd);
void webpause();
unsigned long fsize(char* file);
/* WEBGUI Internal Routines and Variables */
/* general routines for any program using webgui.c */
void initParameterMap(char* str, int n);
char* extractVal(char* str, char key);
char processCommand(char* str);
void updateParameter(char* str, int index1, int index2);
char arrayGet(char* key);
int ipGet(char* key);
void ipSet(char* key, int value);
double rpGet(char* key);
void rpSet(char* key, double value);
char* spGet(char* key);
void spSet(char* key, char* value);
/* general variables for any program using webgui.c */
int ct=0;
char** map_keys;
int* map_indices;
char* map_array;
double *rp_default, *rp;
int *ip_default, *ip;
char *sp_default, *sp;
char buffer[80];
/* Program Specific Routines */
/* Organized by category. (These functions */
/* could be placed in 10 different C files.) */
// LOAD DATA
int loadTrain(int ct, double testProp, int sh, float imgScale, float imgBias);
int loadTest(int ct, int sh, int rc, float imgScale, float imgBias);
// DISPLAY DATA
void displayDigit(int x, int ct, int p, int lay, int chan, int train, int cfy, int big);
void displayDigits(int *dgs, int ct, int pane, int train, int cfy, int wd, int big);
void doAugment(int img, int big, int t);
void viewAugment(int img, int ct, float rat, int r, float sc, int dx, int dy, int p, int big, int t, int cfy);
void printDigit(int a,int b,int *canvas,int m,int n,float *digit,int row,int col,int d3,int d1,int d2);
void printInt(int a,int b,int *canvas,int m,int n,int num,int col,int d1);
void printStr(int a,int b,int *canvas,int m,int n,char *str,int col,int d1);
// ADVANCED DISPLAY
void displayFilter(int ct, int p, int lay, int chan);
void displayFilter2(int ct, int p, int lay, int chan);
void maxActivations(int ct, int p, int lay, int chan, int t, int x);
void maxActivations2(int ct, int p, int lay, int chan, int t, int x);
void maxActivations3(int ct, int p, int lay, int chan, int train, int x);
void drawBorders(int lay, int chan, int *idxA, int *idxB, int ct);
void fakeHeap3(float *dist,int *idx, int *idxA, int *idxB, int k);
void sortHeap3(float *dist, int *idx, int *idxA, int *idxB, int k);
void setColors();
void setColors2();
void setColors3();
// DISPLAY PROGRESS
void displayConfusion(int (*confusion)[10]);
void displayCDigits(int x,int y);
void displayEntropy(float *ents, int entSize, float *ents2, int display);
void displayAccuracy(float *accs, int accSize,float *accs2, int display);
void line(int* img, int m, int n,float x1, float y1, float x2, float y2,int d,int c);
// DISPLAY DOTS
void clearImage(int p);
void updateImage();
void displayClassify(int dd);
void displayClassify3D();
void setColors4();
void placeDots();
void removeDot(float x, float y);
// INIT-NET
void initNet(int t);
void initArch(char *str, int x);
// NEURAL-NET
int isDigits(int init);
void randomizeTrainSet();
void dataAugment(int img, int r, float sc, float dx, float dy, int p, int hiRes, int loRes, int t);
void *runBackProp(void *arg);
int backProp(int x,float *ent, int ep);
int forwardProp(int x, int dp, int train, int lay);
float ReLU(float x);
float TanH(float x);
// KNN
void *runKNN(void *arg);
int singleKNN(int x, int k, int d, int p, int train, int big, int disp);
void fakeHeap(float *dist,int *idx,int k);
void sortHeap(float *dist,int *idx,int k);
float distance(float *digitA, float *digitB, int n, int x);
// PREDICT
void *predictKNN(void *arg);
void writePredictFile(int NN, int k, int d, int y, int big);
void writeFile();
// SPECIAL AND/OR DEBUG
void dreamProp(int y, int it, float bs, float ft, int ds, int lay, int chan, int p);
void dream(int x, int y, int it, float bs, float ft, int ds, int lay, int chan, int p);
int heatmap(int x, int t, int p, int wd);
void boundingBoxes();
void initData(int z);
void displayWeights();
void writeFile2();
float square(float x);
/* Program Specific Variables */
// MENU CREATION ARRAY
// (explained in webgui.c user manual)
//
const int lines = 218;
char init[218][80]={
"c c=Load, k=l",
"c c=Display, k=p",
"c c=Init-Net, k=i",
"c c=Activation, k=a",
"c c=DropOut, k=o",
"c c=DataAugment, k=d",
"c c=Train-Net, k=b",
"c c=Find-kNN, k=g",
"c c=Validate-kNN, k=k",
"c c=STOP, k=t",
"c c=Predict, k=w",
"c c=QUIT, k=q",
"c c=DotColor, k=s",
"c c=ClearPane3, k=c",
"c c=DotRemoveMode, k=r",
"c c=DotLowResMode, k=u",
"c c=Dot3dMode, k=h",
// Special features and/or debugging
// "c c=Dream, k=e",
// "c c=Heatmap, k=f",
// "c c=BoundingBoxes, k=j",
// "c c=InitImage, k=n",
// "c c=SaveImage, k=v",
// "c c=DisplayWeights, k=y",
// "c c=WriteWeights, k=z",
"n n=x, t=i, i=1, d=0",
"n n=epochs, t=i, i=2, d=100000",
"n n=learn, t=r, i=1, d=0.01",
"n n=color, t=i, i=3, d=0",
"n n=displayFreq, t=i, i=4, d=1",
"n n=net, t=i, i=5, d=3",
"n n=type, t=i, i=6, d=1",
"n n=rows, t=i, i=7, d=0",
"n n=k, t=i, i=8, d=5",
"n n=pane, t=i, i=9, d=3",
"n n=ratioD, t=r, i=2, d=0.0",
"n n=it, t=i, i=11, d=10",
"n n=blur, t=r, i=3, d=2.0",
"n n=y, t=i, i=12, d=0",
"n n=true, t=i, i=13, d=5",
"n n=predict, t=i, i=14, d=3",
"n n=norm, t=i, i=15, d=2",
"n n=count, t=i, i=16, d=54",
"n n=L0, t=s, i=1, d=0",
"n n=L1, t=s, i=2, d=0",
"n n=L2, t=s, i=3, d=0",
"n n=L3, t=s, i=4, d=0",
"n n=L4, t=s, i=5, d=0",
"n n=L5, t=s, i=6, d=0",
"n n=L6, t=s, i=7, d=2",
"n n=L7, t=s, i=8, d=20",
"n n=L8, t=s, i=9, d=20",
"n n=L9, t=s, i=10, d=6",
"n n=x2, t=i, i=17, d=43000",
"n n=mode, t=i, i=18, d=4",
"n n=validRatio, t=r, i=4, d=0.25",
"n n=trainSet, t=i, i=19, d=1",
"n n=NN, t=i, i=20, d=1",
"n n=big, t=i, i=21, d=1",
"n n=maxY, t=r, i=5, d=1.0",
"n n=minY, t=r, i=6, d=0.9",
"n n=displayFreq2, t=i, i=22, d=100",
"n n=angle, t=i, i=23, d=13",
"n n=layer, t=i, i=26, d=0",
"n n=channel, t=i, i=27, d=0",
"n n=z, t=i, i=28, d=1",
"n n=removeHeader, t=i, i=29, d=1",
"n n=dataFile, t=f, i=11, d=train.csv",
"n n=decay, t=r, i=7, d=0.95",
"n n=divideBy, t=r, i=8, d=255.0",
"n n=subtractBy, t=r, i=9, d=0.0",
"n n=classify, t=i, i=30, d=0",
"n n=scaleWeights, t=r, i=10, d=1.414",
"n n=scale, t=r, i=11, d=0.13",
"n n=conv, t=i, i=31, d=0",
"n n=pool, t=i, i=32, d=1",
"n n=dense, t=i, i=33, d=1",
"n n=ratioA, t=r, i=12, d=1.0",
"n n=col1Name, t=s, i=12, d=ImageId",
"n n=col2Name, t=s, i=13, d=Label",
"n n=row1Num, t=i, i=34, d=1",
"n n=fileName, t=s, i=14, d=submit.csv",
"n n=augment, t=i, i=35, d=0",
"n n=removeCol1, t=i, i=36, d=0",
"n n=xshift, t=r, i=13, d=2.8",
"n n=yshift, t=r, i=14, d=2.8",
"n n=flatten, t=r, i=15, d=1.0",
"n n=filterWidth, t=i, i=37, d=5",
"n n=colorize, t=i, i=38, d=0",
"n n=displayFreq3, t=i, i=39, d=2",
"r c=Heatmap, n=trainSet",
"r c=Heatmap, n=x",
"r c=Heatmap, n=filterWidth",
"r c=Heatmap, n=pane",
"r c=InitData, n=z",
"r c=NNpredict, n=trainSet",
"r c=NNpredict, n=x",
"r c=Dream, n=x",
"r c=Dream, n=y",
"r c=Dream, n=it",
"r c=Dream, n=learn",
"r c=Dream, n=blur",
"r c=Dream, n=flatten",
"r c=Dream, n=layer",
"r c=Dream, n=channel",
"r c=Dream, n=pane",
"r c=Dream, n=displayFreq3",
"r c=Train-Net, n=epochs",
"r c=Train-Net, n=learn",
"r c=Train-Net, n=decay",
"r c=Train-Net, n=displayFreq",
"r c=Train-Net, n=maxY",
"r c=Train-Net, n=minY",
"r c=Train-Net, n=mode",
"r c=DotColor, n=color",
"r c=Init-Net, n=net",
"r c=Init-Net, n=scaleWeights",
"r c=Activation, n=type",
"r c=Validate-kNN, n=big",
"r c=Validate-kNN, n=k",
"r c=Validate-kNN, n=norm",
"r c=Validate-kNN, n=displayFreq",
"r c=DropOut, n=ratioD",
"r c=DropOut, n=conv",
"r c=DropOut, n=pool",
"r c=DropOut, n=dense",
"r c=Display, n=trainSet",
"r c=Display, n=x",
"r c=Display, n=count",
"r c=Display, n=pane",
"r c=Display, n=big",
"r c=Display, n=layer",
"r c=Display, n=channel",
"r c=Display, n=classify",
"r c=Display, n=NN",
"r c=Display, n=augment",
"r c=Display, n=colorize",
"r c=Init-Net, n=L0",
"r c=Init-Net, n=L1",
"r c=Init-Net, n=L2",
"r c=Init-Net, n=L3",
"r c=Init-Net, n=L4",
"r c=Init-Net, n=L5",
"r c=Init-Net, n=L6",
"r c=Init-Net, n=L7",
"r c=Init-Net, n=L8",
"r c=Init-Net, n=L9",
"r c=SaveImage, n=x",
"r c=SaveImage, n=x2",
"r c=Find-kNN, n=trainSet",
"r c=Find-kNN, n=big",
"r c=Find-kNN, n=x",
"r c=Find-kNN, n=k",
"r c=Find-kNN, n=norm",
"r c=Find-kNN, n=pane",
"r c=Load, n=trainSet",
"r c=Load, n=rows",
"r c=Load, n=validRatio",
"r c=Load, n=removeHeader",
"r c=Load, n=removeCol1",
"r c=Load, n=dataFile",
"r c=Load, n=divideBy",
"r c=Load, n=subtractBy",
"r c=Predict, n=NN",
"r c=Predict, n=big",
"r c=Predict, n=k",
"r c=Predict, n=norm",
"r c=Predict, n=displayFreq2",
"r c=Predict, n=col1Name",
"r c=Predict, n=col2Name",
"r c=Predict, n=row1Num",
"r c=Predict, n=fileName",
"r c=DisplayAugment, n=x",
"r c=DisplayAugment, n=count",
"r c=DisplayAugment, n=ratioA",
"r c=DisplayAugment, n=angle",
"r c=DisplayAugment, n=scale",
"r c=DisplayAugment, n=xshift",
"r c=DisplayAugment, n=yshift",
"r c=DisplayAugment, n=pane",
"r c=DisplayAugment, n=big",
"r c=DataAugment, n=ratioA",
"r c=DataAugment, n=angle",
"r c=DataAugment, n=scale",
"r c=DataAugment, n=xshift",
"r c=DataAugment, n=yshift",
"s n=color, v=0, l=red",
"s n=color, v=1, l=orange",
"s n=color, v=2, l=yellow",
"s n=color, v=3, l=green",
"s n=color, v=4, l=blue",
"s n=color, v=5, l=purple",
"s n=net, v=0, l=custom",
// NAMES OF PRE-DEFINED NETS
"s n=net, v=1, l=2-20-20-6",
"s n=net, v=2, l=LeNet-5",
"s n=net, v=3, l=784-C3:10-C3:10-P2-C3:20-C3:20-P2-128-10",
"s n=net, v=4, l=784-1000-1000-10",
// debug nets
//"s n=net, v=5, l=784-C5:6-P2-50-10",
//"s n=net, v=6, l=196-100-10",
//"s n=net, v=7, l=16-C3:2-P2-2-2",
// NAMES ABOVE
"s n=type, v=0, l=Identity",
"s n=type, v=1, l=ReLU",
"s n=type, v=2, l=TanH",
"s n=mode, v=2, l=2fps",
"s n=mode, v=4, l=10fps",
"s n=mode, v=5, l=20fps",
"s n=mode, v=6, l=30fps",
"s n=trainSet, v=1, l=train_set",
"s n=trainSet, v=0, l=test_set",
"s n=NN, v=0, l=usekNN",
"s n=NN, v=1, l=useNN",
"s n=big, v=0, l=use196",
"s n=big, v=1, l=use784",
"s n=big, v=2, l=other",
"s n=removeHeader, v=0, l=no",
"s n=removeHeader, v=1, l=yes",
"s n=removeCol1, v=0, l=no",
"s n=removeCol1, v=1, l=yes",
"s n=classify, v=0, l=no",
"s n=classify, v=1, l=yes",
"s n=augment, v=0, l=no",
"s n=augment, v=1, l=yes",
"s n=colorize, v=0, l=no",
"s n=colorize, v=1, l=yes-1",
"s n=colorize, v=2, l=yes-2",
"s n=colorize, v=3, l=yes-3",
"s n=divideBy, v=255.0, l=pixel_data",
"s n=divideBy, v=1.0, l=no_scaling",
"s n=subtractBy, v=0.0, l=no_bias"
};
// NUMBER BITMAPS
const int digits[10][15] =
{{1,1,1, 1,0,1, 1,0,1, 1,0,1, 1,1,1}, //0
{0,1,0, 0,1,0, 0,1,0, 0,1,0, 0,1,0}, //1
{1,1,1, 0,0,1, 1,1,1, 1,0,0, 1,1,1}, //2
{1,1,1, 0,0,1, 1,1,1, 0,0,1, 1,1,1}, //3
{1,0,1, 1,0,1, 1,1,1, 0,0,1, 0,0,1}, //4
{1,1,1, 1,0,0, 1,1,1, 0,0,1, 1,1,1}, //5
{1,1,1, 1,0,0, 1,1,1, 1,0,1, 1,1,1}, //6
{1,1,1, 0,0,1, 0,0,1, 0,0,1, 0,0,1}, //7
{1,1,1, 1,0,1, 1,1,1, 1,0,1, 1,1,1}, //8
{1,1,1, 1,0,1, 1,1,1, 0,0,1, 0,0,1}}; //9
// LETTER BITMAPS
const int letters[26][15] =
{{0,1,0, 1,0,1, 1,1,1, 1,0,1, 1,0,1}, //A
{1,1,0, 1,0,1, 1,1,0, 1,0,1, 1,1,0}, //B
{1,1,1, 1,0,0, 1,0,0, 1,0,0, 1,1,1}, //C
{1,1,0, 1,0,1, 1,0,1, 1,0,1, 1,1,0}, //D
{1,1,1, 1,0,0, 1,1,1, 1,0,0, 1,1,1}, //E
{1,1,1, 1,0,0, 1,1,0, 1,0,0, 1,0,0}, //F
{1,1,1, 1,0,0, 1,0,1, 1,0,1, 1,1,1}, //G
{1,0,0, 1,0,1, 1,1,1, 1,0,1, 1,0,1}, //H
{1,1,1, 0,1,0, 0,1,0, 0,1,0, 1,1,1}, //I
{1,1,1, 0,1,0, 0,0,1, 1,0,1, 1,1,1}, //J
{1,0,1, 1,0,1, 1,1,0, 1,0,1, 1,0,1}, //K
{1,0,0, 1,0,0, 1,0,0, 1,0,0, 1,1,1}, //L
{1,0,1, 1,1,1, 1,0,1, 1,0,1, 1,0,1}, //M
{1,0,1, 1,1,1, 1,1,1, 1,1,1, 1,0,1}, //N
{0,1,0, 1,0,1, 1,0,1, 1,0,1, 0,1,0}, //O
{1,1,0, 1,0,1, 1,1,0, 1,0,0, 1,0,0}, //P
{1,1,1, 1,0,1, 1,0,1, 1,1,1, 0,0,1}, //Q
{1,1,1, 1,0,1, 1,1,1, 1,1,0, 1,0,1}, //R
{1,1,1, 1,0,0, 1,1,1, 0,0,1, 1,1,1}, //S
{1,1,1, 0,1,0, 0,1,0, 0,1,0, 0,1,0}, //T
{1,0,1, 1,0,1, 1,0,1, 1,0,1, 1,1,1}, //U
{1,0,1, 1,0,1, 1,0,1, 1,0,1, 0,1,0}, //V
{1,0,1, 1,0,1, 1,0,1, 1,1,1, 1,0,1}, //W
{1,0,1, 1,1,1, 1,1,1, 1,1,1, 1,0,1}, //X
{1,0,1, 1,0,1, 0,1,0, 0,1,0, 0,1,0}, //Y
{1,1,1, 0,0,1, 0,1,0, 1,0,0, 1,1,1}}; //Z
// TRAINING AND VALIDATION DATA
float (*trainImages)[784] = 0;
float (*trainImages2)[196] = 0;
int *trainDigits = 0;
int trainSizeI = 0, extraTrainSizeI = 1000;
int trainColumns = 0, trainSizeE = 0;
int *trainSet = 0; int trainSetSize = 0;
int *validSet = 0; int validSetSize = 0;
float *ents = 0, *ents2 = 0;
float *accs = 0, *accs2 = 0;
// TEST DATA
float (*testImages)[784] = 0;
float (*testImages2)[196] = 0;
int *testDigits;
int testSizeI = 0;
int testColumns = 0;
// NETWORK VARIABLES
int inited = -1;
int activation = 1; //0=Identity, 1=ReLU, 2=TanH
const int randomizeDescent = 1;
float an = 0.01;
int DOconv=1, DOdense=1, DOpool=1;
float dropOutRatio = 0.0, decay = 1.0;
float augmentRatio = 0.0, weightScale = 1.0;
float augmentScale = 0, imgBias=0.0;
int augmentAngle = 0;
float augmentDx = 0.0, augmentDy = 0.0;
// NETWORK ACTIVATIONS AND ERRORS
float prob = 0.0, prob0 = 0.0;
float prob1 = 0.0, prob2 = 0.0;
float* layers[10] = {0};
int* dropOut[10] = {0};
float* weights[10] = {0};
float* errors[10] = {0};
// NETWORK ARCHITECTURE
int numLayers = 0;
char layerNames[10][20] = {0};
int layerType[10] = {0}; //0FC, 1C, 2P
int layerSizes[10] = {0};
int layerConv[10] = {0};
int layerPad[10] = {0};
int layerWidth[10] = {0};
int layerChan[10] = {0};
int layerStride[10] = {0};
int layerConvStep[10] = {0};
int layerConvStep2[10] = {0};
// PREDEFINED NET ARCHITECTURES
char nets[8][10][20] =
{{"","","","","","","","","",""},
{"","","","","","","2","20","20","6"},
{"","","","784","C5:6","P2","C5:16","P2","128","10"},
{"","784","C3:10","C3:10","P2","C3:20","C3:20","P2","128","10"},
{"","","","","","","784","1000","1000","10"},
// debug nets below
{"","","","","","784","C5:6","P2","50","10"},
{"","","","","","","","196","100","10"},
{"","","","","","16","C3:2","P2","2","2"}};
// THREAD VARIABLES
pthread_t workerThread;
pthread_attr_t stackSizeAttribute;
int pass[5] = {0};
int working = 0;
int requiredStackSize = 8*1024*1024;
// IMAGE DISPLAY
int colorize = 1;
double red[8] = {1.0, 1.0, 1.0, 0.0, 0.0, 0.5, 1.0, 0.0};
double green[8] = {0.0, 0.5, 1.0, 1.0, 0.0, 0.0, 1.0, 0.0};
double blue[8] = {0.0, 0.0, 0.0, 0.0, 1.0, 0.5, 1.0, 0.0};
double red2[256],green2[256],blue2[256];
double red3[256],green3[256],blue3[256];
int image[400][600] = {{0}};
int image2[80][120] = {{0}};
// CONFUSION MATRIX DATA
int maxCD = 54;
int cDigits[10][10][54];
int showAcc = 1;
int showEnt = 1;
int showCon = 0;
int showDig[3][55] = {{0}};
float scaleMin = 0.9, scaleMax = 1.0;
// DOT DATA
const int maxDots=250;
float trainDots[250][2];
int trainColors[250];
int trainSizeD = 0;
// DOT PARAMETERS
int useSmall = -1;
int removeMode = -1;
int dotsMode = 4; //6=fluid display 2=slower
// DOT 3D DISPLAY
int use3D = -1;
float heights3D[121][81] = {{0}};
float pa3D[121][81] = {{0}};
float pb3D[121][81] = {{0}};
float pc3D[121][81] = {{0}};
double *red4=0, *green4=0, *blue4=0;
int requestInit = 0;
// MISC
const char *weightsFile1 = "weights1.txt";
const char *weightsFile2 = "weights2.txt";
/**********************************************************************/
/* MAIN ROUTINE */
/**********************************************************************/
int main(int argc, char *argv[]){
if (argc>1) printf("Ignoring unknown argument(s)\n");
srand(time(0));
int i, offset=0;
char cmd, str[80], buffer[80];
// INITIALIZE WEBGUI
initParameterMap((char*)init,lines);
webinit((char*)init,lines);
websetmode(2);
websettitle("MNIST");
while (webstart(15000+offset)<0) offset++;
websetcolors(8,red,green,blue,3);
for (i=0;i<240000;i++) ((int*)image)[i]=6;
webimagedisplay(600,400,(int*)image,3);
for (i=0;i<256;i++){
red2[i] = (double)i/255.0;
green2[i] = (double)i/255.0;
blue2[i] = (double)i/255.0;
}
pthread_attr_init (&stackSizeAttribute);
pthread_attr_setstacksize (&stackSizeAttribute, requiredStackSize);
// MAIN LOOP TO PROCESS COMMANDS
while (1){
webreadline(str);
cmd = processCommand(str);
if (cmd=='l'){ // LOAD
int ct = ipGet("rows");
double v = rpGet("validRatio");
int t = ipGet("trainSet");
int sh = ipGet("removeHeader");
int rc = ipGet("removeCol1");
float imgScale = rpGet("divideBy");
imgBias = rpGet("subtractBy");
if (t==1){
webwriteline("Loading training images, please wait...");
int x = loadTrain(ct,v,sh,imgScale,imgBias);
sprintf(buffer,"Loaded %d rows training, %d features, vSetSize=%d",x,trainColumns,validSetSize);
webwriteline(buffer);
}
else{
webwriteline("Loading test images, please wait...");
int x = loadTest(ct,sh,rc,imgScale,imgBias);
sprintf(buffer,"Loaded %d rows test, %d features",x,testColumns);
webwriteline(buffer);
}
}
else if (cmd=='p'){ // DISPLAY
int x = ipGet("x");
int p = ipGet("pane");
int ct = ipGet("count");
int t = ipGet("trainSet");
int lay = ipGet("layer");
int chan = ipGet("channel");
int cfy = ipGet("classify");
int big = ipGet("big");
int aug = ipGet("augment");
colorize = ipGet("colorize");
//int nn = ipGet("NN");
char nm[10] = "training";
char ext[20] = " with label";
if (t==0) {
strcpy(nm,"test");
strcpy(ext,"");
}
if (cfy==1) strcpy(ext," with prediction");
// ADVANCED DISPLAY
if (lay!=0){
if ( (lay<0 || chan<0 || ct<0) && x>=0){
lay = abs(lay); chan = abs(chan); ct = abs(ct);
if (ct > layerChan[lay] - chan) ct = layerChan[lay] - chan;
sprintf(buffer,"Displaying layer %d max activation for x=%d",lay,x);
if (layerType[lay]!=0) maxActivations2(ct,p,lay,chan,t,x);
else sprintf(buffer,"Layer %d doesnt have filters",lay);
webwriteline(buffer);
}
else if (x<-1){
if (lay<0 || chan<0) ct = -abs(ct);
lay = abs(lay); chan = abs(chan);
if (ct < -layerChan[lay] + chan) ct = -layerChan[lay] + chan;
sprintf(buffer,"Displaying layer %d filter %d max activations",lay,chan);
if (layerType[lay]!=0) maxActivations(ct,p,lay,chan,t,x);
else sprintf(buffer,"Layer %d doesnt have filters",lay);
webwriteline(buffer);
}
else if (x==-1){
if (lay<0 || chan<0) ct = -abs(ct);
lay = abs(lay); chan = abs(chan);
if (ct > layerChan[lay] - chan) ct = layerChan[lay] - chan;
if (ct<=1) sprintf(buffer,"Displaying layer %d filter %d",lay,chan);
else sprintf(buffer,"Displaying layer %d filters %d thru %d",lay,chan,chan+ct-1);
if (lay==11-numLayers && layerType[lay]!=0) displayFilter(ct,p,lay,chan);
else if (lay>11-numLayers && layerType[lay]!=0) displayFilter2(ct,p,lay,chan);
else sprintf(buffer,"Layer %d doesnt have filters",lay);
webwriteline(buffer);
}
else{
if (aug==1) lay = -lay;
ct = abs(ct); if (ct==0) ct = 1;
if (ct > layerChan[lay] - chan) ct = layerChan[lay] - chan;
if (ct==1) sprintf(buffer,"Displaying layer %d filter %d activations for x=%d",abs(lay),chan,x);
else sprintf(buffer,"Displaying layer %d filter %d thru %d activations for x=%d",abs(lay),chan,chan+ct-1,x);
if (layerType[abs(lay)]!=0) displayDigit(x,ct,p,lay,chan,t,cfy,big);
else sprintf(buffer,"Layer %d doesnt have filters",abs(lay));
webwriteline(buffer);
}
}
// BASIC DISPLAY
else if (aug==1){
float rat = 1.0;
int p = ipGet("pane");
int r = ipGet("angle");
float sc = rpGet("scale");
float dx = rpGet("xshift");
float dy = rpGet("yshift");
viewAugment(x,ct,rat,r,sc,dx,dy,p,big,t,cfy);
}
else {
displayDigit(x,ct,p,0,0,t,cfy,big);
if (ct>1) sprintf(buffer,"Displaying %s images %d to %d%s",nm,x,x+ct-1,ext);
else sprintf(buffer,"Displaying %s image %d%s",nm,x,ext);
webwriteline(buffer);
}
}
else if (cmd=='i'){ // INIT-NET
int t = ipGet("net");
weightScale = rpGet("scaleWeights");
if (working==1) requestInit = 1;
else initNet(t);
sprintf(buffer,"Initialized NN=%d with Xavier init scaled=%.3f",t,weightScale);
webwriteline(buffer);
int len = sprintf(buffer,"Architecture (%s",layerNames[0]);
for (i=1;i<10;i++) len += sprintf(buffer+len,"-%s",layerNames[i]);
sprintf(buffer+len,")");
webwriteline(buffer);
}
else if (cmd=='a'){ // ACTIVATION
int a = ipGet("type");
if (a<0 || a>2) webwriteline("Invalid activation");
else {
activation = a;
sprintf(buffer,"Activation=%d where 0=Identity, 1=ReLU, 2=TanH",a);
webwriteline(buffer);
if (a==2 || a==0) webbutton(1,"Activation");
else webbutton(-1,"Activation");
}
}
else if (cmd=='o'){ // DROPOUT
dropOutRatio = rpGet("ratioD");
DOconv = ipGet("conv");
DOpool = ipGet("pool");
DOdense = ipGet("dense");
sprintf(buffer,"DropOutRatio = %f, conv=%d, pool=%d, dense=%d",dropOutRatio,DOconv,DOpool,DOdense);
webwriteline(buffer);
if (dropOutRatio>0.0) webbutton(1,"DropOut");
else webbutton(-1,"DropOut");
}
else if (cmd=='d'){ // DATA AUGMENTATION
augmentRatio = rpGet("ratioA");
augmentAngle = abs(ipGet("angle"));
augmentScale = fabs(rpGet("scale"));
augmentDx = rpGet("xshift");
augmentDy = rpGet("yshift");
sprintf(buffer,"AugmentRatio = %f, Angle = %d, Scale = %.2f, Dx = %.1f, Dy = %.1f",
augmentRatio,augmentAngle,augmentScale,augmentDx,augmentDy);
webwriteline(buffer);
if (augmentRatio>0.0) webbutton(1,"DataAugment");
else webbutton(-1,"DataAugment");
}
else if (cmd=='b'){ // TRAIN-NET
an = rpGet("learn");
scaleMin = rpGet("minY");
scaleMax = rpGet("maxY");
decay = rpGet("decay");
if (working==1){
sprintf(buffer,"wait until learning ends, learn=%f",an);
webwriteline(buffer);
}
else{
int x = ipGet("epochs");
int y = ipGet("displayFreq");
dotsMode = ipGet("mode");
sprintf(buffer,"Beginning %d epochs with lr=%f and decay=%f",x,an,decay);
webwriteline(buffer);
pass[0]=x; pass[1]=y; pass[2]=1; working=1;
pthread_create(&workerThread,&stackSizeAttribute,runBackProp,NULL);
}
}
else if (cmd=='g'){ // FIND-KNN
int t = ipGet("trainSet");
int big = ipGet("big");
int x = ipGet("x");
int k = ipGet("k");
int d = ipGet("norm");
int p = ipGet("pane");
int c = singleKNN(x,k,d,p,t,big,1);
sprintf(buffer,"kNN predicts %d for image %d with k=%d and L%d norm",c,x,k,d);
webwriteline(buffer);
}
else if (cmd=='k'){ // VALIDATE-KNN
if (working==1){
webwriteline("wait until learning ends");
}
else{
int x = ipGet("k");
int y = ipGet("displayFreq");
int big = ipGet("big");
int d = ipGet("norm");
pass[0]=big; pass[1]=y; pass[2]=x; pass[3]=d;
pass[4]=1; working=1;
pthread_create(&workerThread,&stackSizeAttribute,runKNN,NULL);
}
}
else if (cmd=='t'){ // STOP
working=0;
}
else if (cmd=='w'){ // PREDICT
int NN = ipGet("NN");
int k = ipGet("k");
int d = ipGet("norm");
int y = ipGet("displayFreq2");
int big = ipGet("big");
writePredictFile(NN,k,d,y,big);
}
else if (cmd=='q'){ // QUIT
if (working==1) pthread_cancel(workerThread);
webwriteline("QUITTING. Good-bye");
usleep(500000);
webstop();
return 0;
}
else if (cmd=='c'){ // CLEAR PANE 3
trainSizeD = 0;
updateImage();
webwriteline("Pane 3 cleared. Dots cleared");
if (red4 != NULL){
free(red4); free(green4); free(blue4);
red4 = NULL;
}
}
else if (cmd=='r'){ // DOT REMOVE MODE
if (removeMode==-1) removeMode = 1;
else removeMode = -1;
webbutton(removeMode,"DotRemoveMode");
sprintf(buffer,"Remove mode = %d",removeMode);
webwriteline(buffer);
}
else if (cmd=='u'){ // DOT LOW RES MODE
if (useSmall==-1) useSmall = 1;
else useSmall = -1;
webbutton(useSmall,"DotLowResMode");
sprintf(buffer,"UseSmall = %d",useSmall);
webwriteline(buffer);
if (isDigits(inited)!=1 && layerSizes[10-numLayers]==2 && working==0 && trainSizeD!=0){
if (use3D==1) displayClassify3D();
else displayClassify(0);
}
}
else if (cmd=='h'){ // DOT 3D MODE
if (use3D==-1) use3D = 1;
else use3D = -1;
webbutton(use3D,"Dot3dMode");
sprintf(buffer,"Use3D = %d",use3D);
webwriteline(buffer);
if (isDigits(inited)!=1 && layerSizes[10-numLayers]==2 && working==0 && trainSizeD!=0){
if (use3D==1) displayClassify3D();
else displayClassify(0);
}
}
// SPECIAL FEATURES, UNCOMMENT IN MENU TO TURN ON
else if (cmd=='e'){ // DREAM
int x = ipGet("x");
int y = ipGet("y");
int it = ipGet("it");
an = rpGet("learn");
int ds = ipGet("displayFreq3");
int lay = ipGet("layer");
int chan = ipGet("channel");
float bs = rpGet("blur");
float ft = rpGet("flatten");
int p = ipGet("pane");
sprintf(buffer,"Dreaming x=%d to y=%d, it=%d, an=%f",x,y,it,an);
webwriteline(buffer);
dream(x,y,it,bs,ft,ds,lay,chan,p);
}
else if (cmd=='f'){ // HEATMAP
int x = ipGet("x");
int p = ipGet("pane");
int t = ipGet("trainSet");
int wd = ipGet("filterWidth");
int y = heatmap(x,t,p,wd);
sprintf(buffer,"Displaying heatmap for x=%d, predict=%d, prob=%.3f",x,y,prob);
webwriteline(buffer);
}
else if (cmd=='j') // BOUNDING BOXES
boundingBoxes();
else if (cmd=='n'){ // INIT IMAGE
int z = ipGet("z");
sprintf(buffer,"Initing data with z=%d",z);
webwriteline(buffer);
initData(z);
}
else if (cmd=='v'){ // SAVE IMAGE
int x = ipGet("x");
int x2 = ipGet("x2");
for (i=0;i<196;i++) trainImages2[x2][i] = trainImages2[x][i];
for (i=0;i<784;i++) trainImages[x2][i] = trainImages[x][i];
trainDigits[x2] = trainDigits[x];
sprintf(buffer,"Saved image %d to %d",x,x2);
webwriteline(buffer);
}
else if (cmd=='y'){ // DISPLAY WEIGHTS
webwriteline("Weights displayed in shell");
displayWeights();
}
else if (cmd=='z'){ // WRITE WEIGHTS
writeFile2();
}
// PROCESS MOUSE CLICKS
else if (cmd=='m'){ // MOUSE CLICKS
float x = atof(extractVal(str,'x'));
float y = atof(extractVal(str,'y'));
int b = atoi(extractVal(str,'n'));
int p = atoi(extractVal(str,'e'));
int r, row, col, d, num, dd;
float c;
if (showDig[p-3][0]!=0){
d = showDig[p-3][0];
if (d<=6) {r=2; c=3;}
else if (d<=12) {r=3; c=4.5;}
else if (d<=24) {r=4; c=6;}
else if (d<=35) {r=5; c=7;}
else if (d<=54) {r=6; c=9;}
col = (int)(x*c/1.5);
row = (int)((1-y)*r);
if (col<0) col=0; if (col>=(int)c) col=c-1;
if (row<0) row=0; if (row>=r) row=r-1;
dd = 1+row*c+col;
num = showDig[p-3][dd];
if (x>1.48 && (1-y)<0.025){
if (p==3) showCon = 1;
else if (p==4) showEnt = 1;
else if (p==5) showAcc = 1;
clearImage(p);
}
else if (num!=-1 && dd<=showDig[p-3][0]){
sprintf(buffer,"Clicked image %d, digit %d",num,trainDigits[num]);
webwriteline(buffer);
ipSet("x",num);
webupdate(ip,rp,sp);
}
}
else if (showCon==0){
int c = ipGet("color");
if (p==3 && trainSizeD<100){
if (removeMode==1){
removeDot(x,y);
}
else{
trainDots[trainSizeD][0] = x;
trainDots[trainSizeD][1] = y;
trainColors[trainSizeD] = c + b;
trainSizeD++;
}
if (working==0) updateImage();
}
}
else if (p==3){
int col = (int)(x/0.1364)-1;
int row = (int)((1-y)/0.0909)-1;
if (col<0) col=0; if (col>9) col=9;
if (row<0) row=0; if (row>9) row=9;
displayCDigits(row,col);
}
}
}
return 0;
}
/**********************************************************************/
/* LOAD DATA */
/**********************************************************************/
int loadTrain(int ct, double testProp, int sh, float imgScale, float imgBias){
char *data;
// LOAD TRAINING DATA FROM FILE
if (ct<=0) ct=1e6;
int i, len = 0, lines=1, lines2=1;
float rnd;
// READ IN TRAIN.CSV
char buffer[1000000];
char name[80] = "train.csv";
strcpy(name,spGet("dataFile"));
if (access(name,F_OK)!=0) sprintf(name,"../%s",spGet("dataFile"));
if (access(name,F_OK)==0){
data = (char*)malloc((int)fsize(name)+1);
FILE *fp;
fp = fopen(name,"r");
while (fgets(buffer, 1000000, fp)) {
len += sprintf(data+len,"%s",buffer);
//lines++;
}
fclose(fp);
}
else {
sprintf(buffer,"ERROR: File %s not found.",name);
webwriteline(buffer);
return 0;
}
// COUNT LINES
for (i=0;i<len;i++){
if (data[i]=='\n') lines++;
if (data[i]=='\r') lines2++;
}
if (lines2>lines) lines=lines2;
// ALLOCATE MEMORY
if (trainImages!=NULL){
free(trainImages);
free(trainImages2);
free(trainDigits);
free(trainSet);
free(validSet);
trainImages = NULL;
}
trainImages = malloc(784 * (lines+extraTrainSizeI) * sizeof(float));
trainImages2 = malloc(196 * (lines+extraTrainSizeI) * sizeof(float));
trainDigits = malloc(lines * sizeof(int));
trainSet = malloc(lines * sizeof(int));
validSet = malloc(lines * sizeof(int));
// DECODE COMMA SEPARATED ROWS
int j = 0, k = 0, c = 0, mark = -1;
int d = 0, j1,j2;
while (data[j]!='\n' && data[j]!='\r'){
if (data[j]==',') c++;
j++;
}
if (data[j]!='\n' || data[j]!='\r') j++;
trainColumns = c;
c = 0; i = 0;
if (sh==1) i = j+1;
while(i<len && k<ct){
j = i; while (data[j]!=',' && data[j]!='\r' && data[j]!='\n') j++;
if (data[j]=='\n' || data[j]=='\r') mark = 1;
data[j] = 0;
d = atof(data+i);
if (mark == -1){
trainDigits[k] = (int)d;
mark = 0;
}
else if (mark==0) {
trainImages[k][c] = d/imgScale - imgBias;
c++;
}
if (mark>=1){
trainImages[k][c] = d/imgScale - imgBias;
if (c>=trainColumns-1) k++;
c = 0;
if (j+1<len && (data[j+1]=='\n' || data[j+1]=='\r')) mark++;
i = j + mark;
mark = -1;
}
else i = j + 1;
}
validSetSize = 0;
trainSetSize = 0;
// CREATE A SUBSAMPLED VERSION OF IMAGES
if (trainColumns==784){
for (i=0;i<k;i++){
for (j1=0;j1<14;j1++)
for (j2=0;j2<14;j2++){
trainImages2[i][14*j1+j2] = (trainImages[i][28*j1*2+j2*2]
+ trainImages[i][28*j1*2+j2*2+1]
+ trainImages[i][28*(j1*2+1)+j2*2]
+ trainImages[i][28*(j1*2+1)+j2*2+1])/4.0;
}
}
}
// CREATE TRAIN AND VALIDATION SETS
for (i=0;i<k;i++){
rnd = (float)rand()/(float)RAND_MAX;
if (rnd<=testProp) validSet[validSetSize++] = i;
else trainSet[trainSetSize++] = i;
}
trainSizeI = k;
trainSizeE = k;
free(data);
return k;
}
/**********************************************************************/
/* LOAD DATA */
/**********************************************************************/
int loadTest(int ct, int sh, int rc, float imgScale, float imgBias){
char *data;
// LOAD TEST DATA FROM FILE
if (ct<=0) ct=1e6;
int i,len = 0, lines=0, lines2=0;;
float rnd;
// READ IN TEST.CSV
char buffer[1000000];
char name[80] = "test.csv";
strcpy(name,spGet("dataFile"));
if (access(name,F_OK)!=0) sprintf(name,"../%s",spGet("dataFile"));
if (access(name,F_OK)==0){
data = (char*)malloc((int)fsize(name)+1);
FILE *fp;
fp = fopen(name,"r");
while (fgets(buffer, 1000000, fp)){
len += sprintf(data+len,"%s",buffer);
//lines++;
}
fclose(fp);
}
else {
sprintf(buffer,"ERROR: File %s not found.",name);
webwriteline(buffer);
return 0;
}
// COUNT LINES
for (i=0;i<len;i++){
if (data[i]=='\n') lines++;
if (data[i]=='\r') lines2++;
}
if (lines2>lines) lines=lines2;
// ALLOCATE MEMORY
if (testImages!=NULL){
free(testImages);
free(testImages2);
free(testDigits);
testImages = NULL;
}
testImages = malloc(784 * lines * sizeof(float));
testImages2 = malloc(196 * lines * sizeof(float));
testDigits = malloc(lines * sizeof(int));
// DECODE COMMA SEPARATED ROWS
int j = 0, k = 0, c = 0, mark = 0;
int d = 0, j1,j2;
while (data[j]!='\n' && data[j]!='\r'){
if (data[j]==',') c++;
j++;
}
if (data[j]!='\n' || data[j]!='\r') j++;
testColumns = c+1;
if (rc==1) {
testColumns--;
mark = -1;
}
//printf("len=%d lines=%d columns=%d\n",len,lines,testColumns);
c = 0; i = 0;
if (sh==1) i = j+1;
while(i<len && k<ct){
j = i; while (data[j]!=',' && data[j]!='\r' && data[j]!='\n') j++;
if (data[j]=='\n' || data[j]=='\r') mark = 1;
data[j] = 0;
d = atof(data+i);
if (mark==-1){
mark = 0;
}
else if (mark==0) {
testImages[k][c] = d/imgScale - imgBias;
c++;
}
if (mark>=1){
testImages[k][c] = d/imgScale - imgBias;
if (c>=testColumns-1) k++;
c = 0;
if (j+1<len && (data[j+1]=='\n' || data[j+1]=='\r')) mark++;
i = j + mark;
mark = 0;
if (rc==1) mark = -1;
}
else i = j + 1;
}
// CREATE A SUBSAMPLED VERSION OF IMAGES
if (testColumns==784){
for (i=0;i<k;i++){
for (j1=0;j1<14;j1++)
for (j2=0;j2<14;j2++){
testImages2[i][14*j1+j2] = (testImages[i][28*j1*2+j2*2]
+ testImages[i][28*j1*2+j2*2+1]
+ testImages[i][28*(j1*2+1)+j2*2]
+ testImages[i][28*(j1*2+1)+j2*2+1])/4.0;
}
}
}
testSizeI = k;
free(data);
return k;
}
/**********************************************************************/
/* DISPLAY DATA */
/**********************************************************************/
void displayDigit(int x, int ct, int p, int lay, int chan, int train, int cfy, int big){
// DISPLAYS 1 OR MORE IMAGES. OR DISPLAYS NET'S LAYER ACTIVATIONS
if (p!=-1 && (p<3 || p>5)) {
webwriteline("Invalid pane");
return;
}
float mm;
float (*trainImagesB)[784] = trainImages;
float (*trainImages2B)[196] = trainImages2;
if (train==0){
trainImagesB = testImages;
trainImages2B = testImages2;
}
int i, j, k, imax, imin;
// DISPLAY NET'S LAYER ACTIVATIONS
if (lay!=0){
if (lay<0){ // do data augment
lay = -lay;
doAugment(x,big,train);
x = trainSizeE;
train = 1;
}
forwardProp(x,0,train,lay);
float max2 = -1e6;
for (k=0;k<ct;k++){
float min=1e6, max=-1e6;
for (i=0;i<layerSizes[lay];i++) {
trainImages[trainSizeE+k][i] = layers[lay][(chan+k)*layerSizes[lay] + i];
if (trainImages[trainSizeE+k][i]>max2)
max2 = trainImages[trainSizeE+k][i];
if (trainImages[trainSizeE+k][i]>max) {
max = trainImages[trainSizeE+k][i];
imax = i;
}
if (trainImages[trainSizeE+k][i]<min) {
min = trainImages[trainSizeE+k][i];
imin = i;
}
}
// rescale individual
if (lay==11-numLayers)
for (i=0;i<layerSizes[lay];i++) {
// display in grayscale
if (colorize!=1)
trainImages[trainSizeE+k][i] = (trainImages[trainSizeE+k][i] - min) / (max - min);
// display in color
if (colorize==1){
if (trainImages[trainSizeE+k][i]>0){
mm = trainImages[trainSizeE+k][i] / max / 8.0;
if (mm > 0.12) mm = 0.12;
trainImages[trainSizeE+k][i] = (k%6+1) * 0.1255 + mm;
}
else if (trainImages[trainSizeE+k][i]==0) trainImages[trainSizeE+k][i] = 0.502;
else{
mm = (trainImages[trainSizeE+k][i] - min) / fabs(min) / 8.0;
if (mm > 0.12) mm = 0.12;
trainImages[trainSizeE+k][i] = mm;
}
}
else if (colorize>=2)
trainImages[trainSizeE+k][i] = 0.1255 * (k%6+1) + trainImages[trainSizeE+k][i]/8.33 + 0.005;
}
// clip individual
//for (i=0;i<layerSizes[lay];i++) if (trainImages[trainSizeE+k][i]>1.0) trainImages[trainSizeE+k][i] = 1.0;
}
// rescale all together
if (lay!=11-numLayers)
for (k=0;k<ct;k++)
for (i=0;i<layerSizes[lay];i++) trainImages[trainSizeE+k][i] = trainImages[trainSizeE+k][i] / max2;
// DISPLAY MAP'S ACTIVATIONS
int dgs[ct];
for (int i=0;i<ct;i++) dgs[i] = trainSizeE+i;
if (lay!=11-numLayers || colorize==0)
// not first conv layer, display in grayscale
displayDigits(dgs,ct,p,1,0,layerWidth[lay],2);
else{
// first conv layer, display in color
displayDigits(dgs,ct,-1,1,0,layerWidth[lay],2);
if (colorize==1) setColors();
else if (colorize==3) setColors2();
else setColors3();
websetcolors(256,red3,green3,blue3,p);
webimagedisplay(600,400,(int*)image,p);
showDig[p-3][0] = ct;
}
}
// DISPLAY IMAGES
else{
// DISPLAY 1 IMAGE
if (ct==1){
if (p!=-1) websetcolors(256,red2,green2,blue2,p);
for (i=0;i<240000;i++) ((int*)image)[i] = 128;
int wid;
if (train==1) wid = (int)sqrt(trainColumns);
else wid = (int)sqrt(testColumns);
printDigit(0,15*12,(int*)image,400,600,trainImagesB[x],wid,wid,1,10,2);
printDigit(0,0,(int*)image,400,600,trainImages2B[x],14,14,1,10,2);
int dt = -1;
if (train==1) dt = trainDigits[x];
int nn = ipGet("NN");
if (nn==1 && cfy==1 && layers[0]!=NULL) dt = forwardProp(x,0,train,0);
else if (nn==0 && cfy==1)
dt = singleKNN(x,ipGet("k"),ipGet("norm"),3,train,big,0);
if (train!=0 || (cfy!=0 && nn==0) || (cfy!=0 && layers[0]!=NULL))
printInt(14*12,14*12-7,(int*)image,400,600,dt,255,2);
printInt(14*12,7,(int*)image,400,600,x,0,2);
for (i=0;i<10;i++)
for (j=0;j<10;j++){
if (i==j || i+j==9) image[390+i][590+j] = 0;
else image[390+i][590+j] = 255;
}
if (p!=-1){
webimagedisplay(600,400,(int*)image,p);
showDig[p-3][0]=1;
if (p==4) showEnt = 0;
else if (p==5) showAcc = 0;
else if (p==3) showCon = 0;
}
}
// DISPLAY MULTIPLE IMAGES
else{
int dgs[ct];
for (int i=0;i<ct;i++) dgs[i] = x+i;
displayDigits(dgs,ct,p,train,cfy,0,big);
}
}
}
/**********************************************************************/
/* DISPLAY DATA */
/**********************************************************************/
void displayDigits(int *dgs, int ct, int pane, int train, int cfy, int wd, int big){
// DISPLAY MULTIPLE IMAGES
if (ct==0) return;
int i, j, w, m, col, row, in = 10-numLayers;
int size = layerSizes[in],st=1,sk=1,sp=7;
if (size!=196 && size!=784) size=196;
if (big==1) size=784;
else if (big==0) size=196;
if (wd!=0) size=784;
float (*tImage)[size];
if (size==784) {tImage = trainImages; w=28; m=1;}
else {tImage = trainImages2; w=14; m=2;}
if (train==0 && size==784) tImage = testImages;
else if (train==0) tImage = testImages2;
if (wd!=0) {
w = wd;
if (w<=5) m=5;
else if (w<=7) m=4;
else if (w<=9) m=3;
else if (w<=14) m=2;
}
if (pane>=3 && pane<=5)
websetcolors(256,red2,green2,blue2,pane);
for (int i=0;i<240000;i++) ((int*)image)[i] = 128;
int cc, pp, ss, dt;
if (ct<=6) {cc = 3; pp = 5; ss = 200;}
else if (ct<=12) {cc = 4; pp = 3; ss = 133;}
else if (ct<=24) {cc = 6; pp = 5; ss = 100; if (m==2) m = 1;}
else if (ct<=35) {cc = 7; pp = 4; ss = 80; if (m==2) m = 1;}
else {cc = 9; pp = 3; ss = 67; if (m==2) m = 1;}
if (size==784 && ct>12 && ct<=24) {sk=0; pp=3;}
else if (size==784 && ct>=24) {sk=0; pp=2;}
//if (m==0) m = 1;
if (ct>35) sp=2;
if (pane>=3 && pane<=5)
showDig[pane-3][0] = ct;
for (i=0;i<ct;i++){
col = i%cc;
row = i/cc;
if (dgs[i]!=-1){
printDigit(row*ss,col*ss,(int*)image,400,600,tImage[dgs[i]],w,w,st,pp*m,sk*m);
dt = -1;
if (train==1) dt = trainDigits[dgs[i]];
int nn = ipGet("NN");
//nn = 1;
if (nn==1 && cfy==1 && layers[0]!=NULL) dt = forwardProp(dgs[i],0,train,0);
else if (nn==0 && cfy==1) dt = singleKNN(dgs[i],ipGet("k"),ipGet("norm"),3,train,big,0);
if ((train!=0 || (cfy!=0 && nn==0) || (cfy!=0 && layers[0]!=NULL)) && dt!=-1)
printInt(row*ss+w*(pp+1+(sk-1))*m/st,col*ss+w*(pp+1+(sk-1))*m/st-7,(int*)image,400,600,dt,255,2);
printInt(row*ss+w*(pp+1+(sk-1))*m/st,col*ss+sp,(int*)image,400,600,dgs[i],0,2);
}
if (pane>=3 && pane<=5)
showDig[pane-3][i+1] = dgs[i];
}
for (i=0;i<10;i++)
for (j=0;j<10;j++){
if (i==j || i+j==9) image[390+i][590+j] = 0;
else image[390+i][590+j] = 255;
}
if (pane>=3 && pane<=5)
webimagedisplay(600,400,(int*)image,pane);
if (pane==4) showEnt = 0;
else if (pane==5) showAcc = 0;
else if (pane==3) showCon = 0;
}
/**********************************************************************/
/* DISPLAY DATA */
/**********************************************************************/
void doAugment(int img, int big, int t){
// PERFORM DATA AUGMENTATION ON 1 IMAGE FOR LAYERS DISPLAY
int i, j, rot=0, hres=0, lres=1;
if (big==1) {hres=1; lres=0;}
float xs, ys, sc2;
int r = ipGet("angle");
float sc = rpGet("scale");
float dx = rpGet("xshift");
float dy = rpGet("yshift");
rot = (int)(2.0 * r * (float)rand()/(float)RAND_MAX - r);
sc2 = 1.0 + 2.0 * sc * (float)rand()/(float)RAND_MAX - sc;
xs = (2.0 * dx * (float)rand()/(float)RAND_MAX - dx);
ys = (2.0 * dy * (float)rand()/(float)RAND_MAX - dy);
dataAugment(img,rot,sc2,xs,ys,-1,hres,lres,t);
}
/**********************************************************************/
/* DISPLAY DATA */
/**********************************************************************/
void viewAugment(int img, int ct, float ratio, int r, float sc, int dx, int dy, int p, int big, int t, int cfy){
// DISPLAY IMAGES WITH DATA AUGMENTATION
int i, j, rot=0, hres=0, lres=1;
float xs, ys, sc2;
if (big==2 &&layerSizes[10-numLayers]==784){hres=1;lres=0;}
else if (big==1) {hres=1;lres=0;}
for (i=ct-1;i>=0;i--){
if ( (float)rand()/(float)RAND_MAX <= ratio ){
rot = (int)(2.0 * r * (float)rand()/(float)RAND_MAX - r);
sc2 = 1.0 + 2.0 * sc * (float)rand()/(float)RAND_MAX - sc;
xs = (2.0 * dx * (float)rand()/(float)RAND_MAX - dx);
ys = (2.0 * dy * (float)rand()/(float)RAND_MAX - dy);
}
else{ rot=0; sc2=1.0; xs=0.0; ys=0.0; }
dataAugment(img+i,rot,sc2,xs,ys,-1,hres,lres,t);
if (lres==1) for (j=0;j<196;j++) trainImages2[trainSizeE+i][j] = trainImages2[trainSizeE][j];
if (hres==1) for (j=0;j<784;j++) trainImages[trainSizeE+i][j] = trainImages[trainSizeE][j];
trainDigits[trainSizeE+i] = trainDigits[trainSizeE];
}
displayDigit(trainSizeE,ct,p,0,0,1,cfy,big);
}
/**********************************************************************/
/* DISPLAY DATA */
/**********************************************************************/
void printDigit(int a,int b,int *canvas,int m,int n,float *digit,int row,int col,int d3,int d1,int d2){
//DRAWS DIGIT INTO CANVAS STARTING AT (X,Y)=(B,A) FROM TOP LEFT CORNER
//D3 IS STRIDE, D1 IS PIXEL WIDTH, D2 IS SPACING
int dx = d1 + d2;
int dy = d1 + d2;
int i,j,ki,kj;
for (i=0;i<row/d3;i++)
for (j=0;j<col/d3;j++)
for (ki=0;ki<d1;ki++)
for (kj=0;kj<d1;kj++)
if (m-1-(dx*i+ki+a)>=0 && m-1-(dx*i+ki+a)<m && dy*j+kj+b<n)
canvas[n*(m-1-(dx*i+ki+a)) + dy*j+kj+b] = 255*digit[row*i*d3 + j*d3];
}
/**********************************************************************/
/* DISPLAY DATA */
/**********************************************************************/
void printInt(int a,int b,int *canvas,int m,int n,int num,int col,int d1){
// DRAWS INT ON CANVAS
char str[80];
sprintf(str,"%d",num);
int i,j,k1,k2,w;
for (w=0;w<strlen(str);w++)
for (i=0;i<5;i++)
for (j=0;j<3;j++)
for (k1=0;k1<d1;k1++)
for (k2=0;k2<d1;k2++)
if (digits[str[w]-'0'][i*3+j] != 0)
if (m-1-(a+(i*d1+k1))>=0 && m-1-(a+(i*d1+k1))<m && b+(j*d1+k2)+4*d1*w<n)
canvas[n*(m-1-(a+(i*d1+k1))) + b+(j*d1+k2)+4*d1*w] = col;
}
/**********************************************************************/
/* DISPLAY DATA */
/**********************************************************************/
void printStr(int a,int b,int *canvas,int m,int n,char *str,int col,int d1){
// DRAWS STRING ON CANVAS
// MAKE STR ALL LOWERCASE
int i,j,k1,k2,w;
for (w=0;w<strlen(str);w++)
for (i=0;i<5;i++)
for (j=0;j<3;j++)
for (k1=0;k1<d1;k1++)
for (k2=0;k2<d1;k2++)
if (letters[str[w]-'a'][i*3+j] != 0)
if (m-1-(a+(i*d1+k1))>=0 && m-1-(a+(i*d1+k1))<m && b+(j*d1+k2)+4*d1*w<n)
canvas[n*(m-1-(a+(i*d1+k1))) + b+(j*d1+k2)+4*d1*w] = col;
}
/**********************************************************************/
/* ADVANCED DISPLAY */
/**********************************************************************/
void displayFilter(int ct, int p, int lay, int chan){
int i, j, k;
float mn, mx, mm;
int wd = layerConv[lay];
for (k=0; k<ct; k++){
mn = 0.0; mx = 0.0;
for (i=0;i<wd;i++)
for (j=0;j<wd;j++){
trainImages[trainSizeE+k][wd*i+j] = weights[lay][(layerConvStep[lay]+1)*(chan+k) + wd*i + j];
if (trainImages[trainSizeE+k][wd*i+j] < mn) mn = trainImages[trainSizeE+k][wd*i+j];
if (trainImages[trainSizeE+k][wd*i+j] > mx) mx = trainImages[trainSizeE+k][wd*i+j];
}
for (i=0;i<wd*wd;i++){
// display in grayscale
if (colorize!=1)
trainImages[trainSizeE+k][i] = (trainImages[trainSizeE+k][i] - mn) / (mx - mn);
// display in color
if (colorize==1){
if (trainImages[trainSizeE+k][i]>0){
mm = trainImages[trainSizeE+k][i] / mx / 8.0;
if (mm > 0.12) mm = 0.12;
trainImages[trainSizeE+k][i] = (k%6+1) * 0.1255 + mm;
}
else if (trainImages[trainSizeE+k][i]==0) trainImages[trainSizeE+k][i] = 0.502;
else{
mm = (trainImages[trainSizeE+k][i] - mn) / fabs(mn) / 8.0;
if (mm > 0.12) mm = 0.12;
trainImages[trainSizeE+k][i] = mm;
}
}
else if (colorize>=2)
trainImages[trainSizeE+k][i] = 0.1255 * (k%6+1) + trainImages[trainSizeE+k][i]/8.33 + 0.005;
}
}
int dgs[ct];
for (k=0;k<ct;k++) {
dgs[k] = trainSizeE+k;
trainDigits[trainSizeE+k] = -1;
}
if (colorize==0)
displayDigits(dgs,ct,p,1,0,wd,2);
else{
displayDigits(dgs,ct,-1,1,0,wd,2);
if (colorize==1) setColors();
else if (colorize==2) setColors3();
else setColors2();
websetcolors(256,red3,green3,blue3,p);
webimagedisplay(600,400,(int*)image,p);
showDig[p-3][0] = ct;
}
}
/**********************************************************************/
/* ADVANCED DISPLAY */
/**********************************************************************/
void displayFilter2(int ct, int p, int lay, int chan){
int i, j, k, i2, f2;
float mm, mx, mx2, w;
int wd = layerConv[lay];
int single = 0;
if (ct<0){ ct = 1; single = 1;}
// DISPLAYS THE FILTERS PER CHANNEL MIXED TOGETHER (ignores negatives)
for (k=0; k<ct; k++){
// CALCULATE LARGEST WEIGHT IN FILTER K
mx = 0.0;
for (i=0;i<layerConvStep[lay];i++){
if (weights[lay][(layerConvStep[lay]+1)*(chan+k) + i]>mx)
mx = weights[lay][(layerConvStep[lay]+1)*(chan+k) + i];
}
// CALCULATE LARGEST CONTRIBUTOR over 0.0
if (single==0)
for (i=0;i<wd;i++)
for (j=0;j<wd;j++){
mx2 = 0.0;
f2 = 0;
for (i2=0;i2<layerChan[lay-1];i2++){
w = weights[lay][(layerConvStep[lay]+1)*(chan+k) + layerConvStep2[lay]*i2 + wd*i + j];
if (w>mx2){
mx2 = w;
f2 = i2;
}
}
mm = mx2 / mx / 8.0;
if (mm > 0.12) mm = 0.12;
//mm = 0.0;
trainImages[trainSizeE+k][wd*i+j] = (f2%6+1) * 0.1255 + mm;
}
}
// DISPLAYS EACH FILTER PER CHANNEL SEPARATELY (ignores negatives)
if (single == 1){
ct = layerChan[lay-1];
for (k=0; k<ct; k++){
for (i=0;i<layerConvStep2[lay];i++){
mm = weights[lay][(layerConvStep[lay]+1)*chan + layerConvStep2[lay]*k + i] / mx / 8.0;
if (mm > 0.12) mm = 0.12;
if (mm < 0) mm = 0.0;
trainImages[trainSizeE+k][i] = (k%6+1) * 0.1255 + mm;
}
}
}
int dgs[ct];
for (k=0;k<ct;k++) {
dgs[k] = trainSizeE+k;
trainDigits[trainSizeE+k] = -1;
}
displayDigits(dgs,ct,-1,1,0,wd,2);
setColors();
websetcolors(256,red3,green3,blue3,p);
webimagedisplay(600,400,(int*)image,p);
showDig[p-3][0] = ct;
}
/**********************************************************************/
/* ADVANCED DISPLAY */
/**********************************************************************/
void setColors(){
int i;
for (i=0;i<32;i++){ // BLACK
red3[i] = i/62.0;
green3[i] = i/62.0;
blue3[i] = i/62.0;
}
for (i=0;i<32;i++){ // WHITE
red3[i+224] = 0.5 + i/62.0;
green3[i+224] = 0.5 + i/62.0;
blue3[i+224] = 0.5 + i/62.0;
}
for (i=0;i<32;i++){ // RED
red3[i+32] = 0.5 + i/64.0;
green3[i+32] = 0.5 - i/64.0;
blue3[i+32] = 0.5 - i/64.0;
}
for (i=0;i<32;i++){ // ORANGE
red3[i+64] = 0.5 + i/64.0;
green3[i+64] = 0.5;
blue3[i+64] = 0.5 - i/64.0;
}
for (i=0;i<32;i++){ // YELLOW
red3[i+96] = 0.5 + i/64.0;
green3[i+96] = 0.5 + i/64.0;
blue3[i+96] = 0.5 - i/64.0;
}
for (i=0;i<32;i++){ // GREEN
red3[i+128] = 0.5 - i/64.0;
green3[i+128] = 0.5 + i/64.0;
blue3[i+128] = 0.5 - i/64.0;
}
for (i=0;i<32;i++){ // BLUE
red3[i+160] = 0.5 - i/64.0;
green3[i+160] = 0.5 - i/64.0;
blue3[i+160] = 0.5 + i/64.0;
}
for (i=0;i<32;i++){ // PURPLE
red3[i+192] = 0.5;
green3[i+192] = 0.5 - i/64.0;
blue3[i+192] = 0.5;
}
}
/**********************************************************************/
/* ADVANCED DISPLAY */
/**********************************************************************/
void setColors2(){
int i;
for (i=0;i<32;i++){ // BLACK
red3[i] = i/62.0;
green3[i] = i/62.0;
blue3[i] = i/62.0;
}
for (i=0;i<32;i++){ // WHITE
red3[i+224] = 0.5 + i/62.0;
green3[i+224] = 0.5 + i/62.0;
blue3[i+224] = 0.5 + i/62.0;
}
for (i=0;i<32;i++){ // RED
red3[i+32] = i/31.0;
green3[i+32] = 0.0;
blue3[i+32] = 0.0;
}
for (i=0;i<32;i++){ // ORANGE
red3[i+64] = i/31.0;
green3[i+64] = i/62.0;
blue3[i+64] = 0.0;
}
for (i=0;i<32;i++){ // YELLOW
red3[i+96] = i/31.0;
green3[i+96] = i/31.0;
blue3[i+96] = 0.0;
}
for (i=0;i<32;i++){ // GREEN
red3[i+128] = 0.0;
green3[i+128] = i/31.0;
blue3[i+128] = 0.0;
}
for (i=0;i<32;i++){ // BLUE
red3[i+160] = 0.0;
green3[i+160] = 0.0;
blue3[i+160] = i/31.0;
}
for (i=0;i<32;i++){ // PURPLE
red3[i+192] = i/62.0;
green3[i+192] = 0.0;
blue3[i+192] = i/62.0;
}
red3[128]=0.5;
green3[128]=0.5;
blue3[128]=0.5;
}
/**********************************************************************/
/* ADVANCED DISPLAY */
/**********************************************************************/
void setColors3(){
int i;
for (i=0;i<32;i++){ // BLACK
red3[i] = i/62.0;
green3[i] = i/62.0;
blue3[i] = i/62.0;
}
for (i=0;i<32;i++){ // WHITE
red3[i+224] = 0.5 + i/62.0;
green3[i+224] = 0.5 + i/62.0;
blue3[i+224] = 0.5 + i/62.0;
}
for (i=0;i<32;i++){ // RED
if (i<16){
red3[i+32] = i/31.0;
green3[i+32] = i/31.0;
blue3[i+32] = i/31.0;
}
else{
red3[i+32] = 0.5 + (i-16)/30.0;
green3[i+32] = 0.5 - (i-16)/30.0;
blue3[i+32] = 0.5 - (i-16)/30.0;
}
}
for (i=0;i<32;i++){ // ORANGE
if (i<16){
red3[i+64] = i/31.0;
green3[i+64] = i/31.0;
blue3[i+64] = i/31.0;
}
else{
red3[i+64] = 0.5 + (i-16)/30.0;
green3[i+64] = 0.5;
blue3[i+64] = 0.5 - (i-16)/30.0;
}
}
for (i=0;i<32;i++){ // YELLOW
if (i<16){
red3[i+96] = i/31.0;
green3[i+96] = i/31.0;
blue3[i+96] = i/31.0;
}
else{
red3[i+96] = 0.5 + (i-16)/30.0;
green3[i+96] = 0.5 + (i-16)/30.0;
blue3[i+96] = 0.5 - (i-16)/30.0;
}
}
for (i=0;i<32;i++){ // GREEN
if (i<16){
red3[i+128] = i/31.0;
green3[i+128] = i/31.0;
blue3[i+128] = i/31.0;
}
else{
red3[i+128] = 0.5 - (i-16)/30.0;
green3[i+128] = 0.5 + (i-16)/30.0;
blue3[i+128] = 0.5 - (i-16)/30.0;
}
}
for (i=0;i<32;i++){ // BLUE
if (i<16){
red3[i+160] = i/31.0;
green3[i+160] = i/31.0;
blue3[i+160] = i/31.0;
}
else{
red3[i+160] = 0.5 - (i-16)/30.0;
green3[i+160] = 0.5 - (i-16)/30.0;
blue3[i+160] = 0.5 + (i-16)/30.0;
}
}
for (i=0;i<32;i++){ // PURPLE
if (i<16){
red3[i+192] = i/31.0;
green3[i+192] = i/31.0;
blue3[i+192] = i/31.0;
}
else{
red3[i+192] = 0.5;
green3[i+192] = 0.5 - (i-16)/30.0;
blue3[i+192] = 0.5;
}
}
red3[128]=0.5;
green3[128]=0.5;
blue3[128]=0.5;
}
/**********************************************************************/
/* ADVANCED DISPLAY */
/**********************************************************************/
void setColors4(){
if (red4 == NULL){
red4 = (double*)malloc(262164 * sizeof(double));
green4 = (double*)malloc(262164 * sizeof(double));
blue4 = (double*)malloc(262164 * sizeof(double));
}
int i, j, k;
for (i=0;i<64;i++)
for (j=0;j<64;j++)
for (k=0;k<64;k++){
red4[i*4096+j*64+k] = i/63.0;
green4[i*4096+j*64+k] = j/63.0;
blue4[i*4096+j*64+k] = k/63.0;
}
}
/**********************************************************************/
/* ADVANCED DISPLAY */
/**********************************************************************/
void maxActivations(int ct, int p, int lay, int chan, int train, int x){
// DISPLAYS CT TOP REGION PER 1 FILTER
if (ct<0) return maxActivations3(-ct,p,lay,chan,train,x);
int i, j, k, imax, jmax, temp;
int numImages = trainSizeI;
numImages = abs(x);
float maxA[ct], max;
int idx[ct], idxA[ct], idxB[ct];
// FIND MAX ACTIVATIONS. THIS TAKES A WHILE :-(
for (k=0;k<numImages;k++){
if (k%100==0) printf("Finding max act, k=%d\n",k);
forwardProp(k,0,train,lay);
max = 0.0; imax = 0; jmax = 0;
for (i=0;i<layerWidth[lay];i++){
temp = layerSizes[lay]*chan + i*layerWidth[lay];
for (j=0;j<layerWidth[lay];j++)
if (layers[lay][temp + j]>max){
max = layers[lay][temp + j];
imax = i;
jmax = j;
}
}
if (k==ct) fakeHeap3(maxA,idx,idxA,idxB,ct);
if (k<ct){
maxA[k] = max;
idx[k] = k;
idxA[k] = imax;
idxB[k] = jmax;
}
else{
if (max>maxA[0]){
maxA[0] = max;
idx[0] = k;
idxA[0] = imax;
idxB[0] = jmax;
fakeHeap3(maxA,idx,idxA,idxB,ct);
}
}
}
sortHeap3(maxA,idx,idxA,idxB,ct);
// DRAW DIGITS THAT CONTAIN MAX ACTIVATIONS REGIONS
int dgs[ct];
float (*tImages)[784] = trainImages;
if (train==0) tImages = testImages;
for (k=0;k<ct;k++){
for (i=0;i<784;i++)
trainImages[trainSizeE+k][i] = tImages[idx[k]][i];
trainDigits[trainSizeE+k] = trainDigits[idx[k]];
dgs[k] = trainSizeE+k;
printf("Img%d has act = %f\n",k,maxA[k]);
}
displayDigits(dgs,ct,-1,1,0,0,2);
drawBorders(lay,chan,idxA,idxB,ct);
websetcolors(256,red3,green3,blue3,p);
webimagedisplay(600,400,(int*)image,p);
showDig[p-3][0] = ct;
}
/**********************************************************************/
/* ADVANCED DISPLAY */
/**********************************************************************/
void maxActivations3(int ct, int p, int lay, int chan, int train, int x){
// DISPLAYS 1 TOP REGION PER CT FILTERS
int i, j, k, kk, imax, jmax, temp;
int numImages = trainSizeI;
numImages = abs(x);
float maxA[ct], max;
int idx[ct], idxA[ct], idxB[ct];
// FIND MAX ACTIVATIONS. THIS TAKES A WHILE :-(
for (k=0;k<numImages;k++){
if (k%100==0) printf("Finding max act, k=%d\n",k);
forwardProp(k,0,train,lay);
for (kk=0;kk<ct;kk++){
max = 0.0; imax = 0; jmax = 0;
for (i=0;i<layerWidth[lay];i++){
temp = layerSizes[lay]*(chan+kk) + i*layerWidth[lay];
for (j=0;j<layerWidth[lay];j++)
if (layers[lay][temp + j]>max){
max = layers[lay][temp + j];
imax = i;
jmax = j;
}
}
if (k==0){
maxA[kk] = max;
idx[kk] = k;
idxA[kk] = imax;
idxB[kk] = jmax;
}
else{
if (max>maxA[kk]){
maxA[kk] = max;
idx[kk] = k;
idxA[kk] = imax;
idxB[kk] = jmax;
}
}
}
}
int mt = 1, wt = 1;
for (i=11-numLayers;i<=lay;i++){
wt = wt + (layerConv[i]-1)*mt;
mt = mt * layerStride[i];
}
// DRAW DIGITS THAT CONTAIN MAX ACTIVATIONS REGIONS
int dgs[ct];
float (*tImages)[784] = trainImages;
if (train==0) tImages = testImages;
for (k=0;k<ct;k++){
//for (i=0;i<784;i++)
// trainImages[trainSizeE+k][i] = tImages[idx[k]][i];
for (i=0;i<wt;i++)
for (j=0;j<wt;j++){
trainImages[trainSizeE+k][i*wt+j] = tImages[idx[k]][ (mt*idxA[k]+i)*28 + (mt*idxB[k]+j) ];
}
trainDigits[trainSizeE+k] = trainDigits[idx[k]];
dgs[k] = trainSizeE+k;
printf("Img%d has act = %f\n",k,maxA[k]);
}
if (11-numLayers!=lay || colorize==0)
// DISPLAY GRAYSCALE
displayDigits(dgs,ct,p,1,0,wt,2);
else{
// DISPLAY IN COLOR
for (k=0;k<ct;k++)
for (i=0;i<wt*wt;i++)
trainImages[trainSizeE+k][i] = 0.1255 * (k%6+1) + trainImages[trainSizeE+k][i]/8.33 + 0.005;
displayDigits(dgs,ct,-1,1,0,wt,2);
//drawBorders(lay,-1,idxA,idxB,ct);
if (colorize==3) setColors2();
else setColors3();
websetcolors(256,red3,green3,blue3,p);
webimagedisplay(600,400,(int*)image,p);
showDig[p-3][0] = ct;
}
}
/**********************************************************************/
/* ADVANCED DISPLAY */
/**********************************************************************/
void drawBorders(int lay, int chan, int *idxA, int *idxB, int ct){
int i, j, k;
// ADJUST GRAYSCALE PALALETTE TO CONTAIN A COLOR
for (i=0;i<256;i++){
red3[i] = (double)i/255.0;
green3[i] = (double)i/255.0;
blue3[i] = (double)i/255.0;
}
for (i=0;i<240000;i++) if (((int*)image)[i] == 1 ) ((int*)image)[i] = 0;
if (lay>11-numLayers || chan<0) { red3[1] = 1.0; green3[1] = 0.0; blue3[1] = 1.0; } // MAGENTA
else if (chan%6==0) { red3[1] = 1.0; green3[1] = 0.0; blue3[1] = 0.0; } // RED
else if (chan%6==1) { red3[1] = 1.0; green3[1] = 0.5; blue3[1] = 0.0; } // ORANGE
else if (chan%6==2) { red3[1] = 1.0; green3[1] = 1.0; blue3[1] = 0.0; } // YELLOW
else if (chan%6==3) { red3[1] = 0.0; green3[1] = 1.0; blue3[1] = 0.0; } // GREEN
else if (chan%6==4) { red3[1] = 0.0; green3[1] = 0.0; blue3[1] = 1.0; } // BLUE
else { red3[1] = 0.5; green3[1] = 0.0; blue3[1] = 0.5; } // PURPLE
// DRAW BORDERS REGIONS FOR SPECIFIC NEURON
int row, col, ii, jj;
int dx = 200, dx2 = 6, cc = 3;
int mt = 1, wt = 1;
for (i=11-numLayers;i<=lay;i++){
wt = wt + (layerConv[i]-1)*mt;
mt = mt * layerStride[i];
}
if (ct<=6){}
else if (ct<=12){dx=133; dx2=4; cc=4;}
else if (ct<=24){dx=100; dx2=3; cc=6;}
else if (ct<=35){dx=80; dx2=2; cc=7;}
else if (ct<=54){dx=67; dx2=2; cc=9;}
for (k=0;k<ct;k++){
if (idxA[k]<0) continue;
row = k/cc;
col = k%cc;
for (jj=0;jj<wt+2;jj++)
for (i=0;i<dx2;i++)
for (j=0;j<dx2;j++){
image[399 - (row*dx + (mt*idxA[k]-1)*dx2 +i)][col*dx + (mt*idxB[k]+jj-1)*dx2 + j] = 1;
image[399 - (row*dx + (mt*idxA[k]+wt)*dx2 +i)][col*dx + (mt*idxB[k]+jj-1)*dx2 + j] = 1;
}
for (ii=0;ii<wt+2;ii++)
for (i=0;i<dx2;i++)
for (j=0;j<dx2;j++){
image[399 - (row*dx + (mt*idxA[k]+ii-1)*dx2 +i)][col*dx + (mt*idxB[k]-1)*dx2 + j] = 1;
image[399 - (row*dx + (mt*idxA[k]+ii-1)*dx2 +i)][col*dx + (mt*idxB[k]+wt)*dx2 + j] = 1;
}
}
}
/**********************************************************************/
/* ADVANCED DISPLAY */
/**********************************************************************/
void maxActivations2(int ct, int p, int lay, int chan, int train, int x){
// DISPLAYS 1 TOP REGION PER CT FILTERS ON 1 X
int i, j, k, imax, jmax, temp;
float maxA[ct], max, max2 = 0.0;
int idx[ct], idxA[ct], idxB[ct];
forwardProp(x,0,train,lay);
// FIND MAX ACTIVATIONS FOR X
for (k=0;k<ct;k++){
max = 0.0; imax = 0; jmax = 0;
for (i=0;i<layerWidth[lay];i++){
temp = layerSizes[lay]*(chan+k) + i*layerWidth[lay];
for (j=0;j<layerWidth[lay];j++)
if (layers[lay][temp + j]>max){
max = layers[lay][temp + j];
imax = i;
jmax = j;
}
if (max>max2) max2 = max;
}
maxA[k] = max;
idx[k] = x;
idxA[k] = imax;
idxB[k] = jmax;
}
// DRAW DIGITS
int dgs[ct];
float (*tImages)[784] = trainImages;
if (train==0) tImages = testImages;
for (k=0;k<ct;k++){
for (i=0;i<784;i++)
trainImages[trainSizeE+k][i] = tImages[idx[k]][i];
trainDigits[trainSizeE+k] = trainDigits[idx[k]];
dgs[k] = trainSizeE+k;
printf("Filter%d has act = %f\n",k,maxA[k]);
}
displayDigits(dgs,ct,-1,1,0,0,2);
if (colorize==0) for (i=0;i<ct;i++)
if (maxA[i]<max2 * 0.75) idxA[i] = -1;
drawBorders(lay,-1,idxA,idxB,ct);
// DISPLAY
websetcolors(256,red3,green3,blue3,p);
webimagedisplay(600,400,(int*)image,p);
showDig[p-3][0] = ct;
}
/**********************************************************************/
/* DISPLAY PROGRESS */
/**********************************************************************/
void displayEntropy(float *ents, int entSize, float *ents2, int display){
// DISPLAY ENTROPY PLOT
int i,j;
int *img = (int*)image2;
int w=120, h=80;
if (useSmall==-1){
img = (int*) image;
w = 600;
h = 400;
}
float x1,y1,x2,y2,y1B,y2B;
for (i=0;i<w*h;i++) img[i]=6;
line(img,h,w,0.1,0.9,0.1,0.1,0,7);
line(img,h,w,0.1,0.1,1.4,0.1,0,7);
int pwr = (int)log10f(entSize);
int inc = (int)pow(10,pwr);
for (i=1;i<entSize/inc+1;i++){
if (useSmall==-1){
line(img,h,w,0.1+1.3*(inc*i)/entSize,0.08,0.1+1.3*(inc*i)/entSize,0.12,0,7);
printInt(370,(int)(40+520*(inc*i)/(float)entSize)-(pwr+1)*5,img,h,w,inc*i*display,0,3);
}
else{
line(img,h,w,0.1+1.3*(inc*i)/entSize,0.1,0.1+1.3*(inc*i)/entSize,0.13,0,7);
printInt(73,(int)(8+104*(inc*i)/(float)entSize)-(pwr+1)*1,img,h,w,inc*i*display,0,1);
}
}
float dx = 1.3/(entSize-1);
float ymax = 0;
for (i=0;i<entSize;i++)
if (ents[i]>ymax) ymax=ents[i];
for (i=1;i<entSize;i++){
x2 = 0.1 + dx*i;
x1 = 0.1 + dx*(i-1);
y2 = 0.1 + 0.8*(ents[i]/ymax);
y1 = 0.1 + 0.8*(ents[i-1]/ymax);
line(img,h,w,x1,y1,x2,y2,0,0);
if (useSmall==-1)line(img,h,w,x1,y1,x1,y1,2,0);
if (isDigits(inited)==1){
y2B = 0.1 + 0.8*(ents2[i]/ymax);
y1B = 0.1 + 0.8*(ents2[i-1]/ymax);
line(img,h,w,x1,y1B,x2,y2B,0,4);
if (useSmall==-1)line(img,h,w,x1,y1B,x1,y1B,2,4);
}
}
if (useSmall==-1) line(img,h,w,x2,y2,x2,y2,2,0);
if (isDigits(inited)==1 && useSmall==-1) line(img,h,w,x2,y2B,x2,y2B,2,4);
int d=3, ww=100, hh=10; if (useSmall==1) {d=1; ww=10; hh=1;}
printStr(hh,ww,img,h,w,"entropy",0,d);
websetcolors(8,red,green,blue,4);
webimagedisplay(w,h,img,4);
showDig[1][0]=0;
}
/**********************************************************************/
/* DISPLAY PROGRESS */
/**********************************************************************/
void displayAccuracy(float *accs, int accSize,float *accs2, int display){
// DISPLAY ACCURACY PLOT
int i,j;
float min = 0.8, max = 1.0;
min = scaleMin;
max = scaleMax;
int *img = (int*)image2;
int w=120, h=80;
if (useSmall==-1){
img = (int*) image;
w = 600;
h = 400;
}
float x1,y1,x2,y2,y1B,y2B;
for (i=0;i<w*h;i++) img[i]=6;
line(img,h,w,0.1,0.9,0.1,0.1,0,7);
line(img,h,w,0.1,0.9,1.4,0.9,0,7);
line(img,h,w,0.1,0.1,1.4,0.1,0,7);
for (i=0;i<11;i++){
if (useSmall==-1) line(img,h,w,0.08,0.1+0.08*i,0.12,0.1+0.08*i,0,7);
else line(img,h,w,0.1,0.1+0.08*i,0.12,0.1+0.08*i,0,7);
}
int pwr = (int)log10f(accSize);
int inc = (int)pow(10,pwr);
for (i=1;i<accSize/inc+1;i++){
if (useSmall==-1){
line(img,h,w,0.1+1.3*(inc*i)/accSize,0.08,0.1+1.3*(inc*i)/accSize,0.12,0,7);
printInt(370,(int)(40+520*(inc*i)/(float)accSize)-(pwr+1)*5,img,h,w,inc*i*display,0,3);
}
else{
line(img,h,w,0.1+1.3*(inc*i)/accSize,0.1,0.1+1.3*(inc*i)/accSize,0.13,0,7);
printInt(73,(int)(8+104*(inc*i)/(float)accSize)-(pwr+1)*1,img,h,w,inc*i*display,0,1);
}
}
//line(img,h,w,0.1,0.66,1.4,0.66,0,3);
float dx = 1.3/(accSize-1);
float ymax = max-min;
for (i=1;i<accSize;i++){
x2 = 0.1 + dx*i;
x1 = 0.1 + dx*(i-1);
y2 = 0.1 + 0.8*((accs[i]-min)/ymax);
y1 = 0.1 + 0.8*((accs[i-1]-min)/ymax);
line(img,h,w,x1,y1,x2,y2,0,0);
if (useSmall==-1) line(img,h,w,x1,y1,x1,y1,2,0);
if (isDigits(inited)==1){
y2B = 0.1 + 0.8*((accs2[i]-min)/ymax);
y1B = 0.1 + 0.8*((accs2[i-1]-min)/ymax);
line(img,h,w,x1,y1B,x2,y2B,0,4);
if (useSmall==-1) line(img,h,w,x1,y1B,x1,y1B,2,4);
}
}
if (useSmall==-1) line(img,h,w,x2,y2,x2,y2,2,0);
if (isDigits(inited)==1 && useSmall==-1) line(img,h,w,x2,y2B,x2,y2B,2,4);
int d=3, ww=100, hh=10, ss=32, dy=7; if (useSmall==1) {d=1; ww=10; hh=1; ss=6; dy=0;}
float scale = (max-min)/0.1;
for (i=10;i>=0;i--){
if (i==0 && max==1.0) dy=0;
printInt((i+1)*ss,dy,img,h,w,(int)(100*max-scale*i),0,d);
}
printStr(hh,ww,img,h,w,"accuracy",0,d);
websetcolors(8,red,green,blue,5);
webimagedisplay(w,h,img,5);
showDig[2][0]=0;
}
/**********************************************************************/
/* DISPLAY PROGRESS */
/**********************************************************************/
void displayConfusion(int (*confusion)[10]){
// DISPLAY CONFUSION MATRIX FOR EITHER NN TRAIN OR KNN VALIDATION
int i,j;
int *img = (int*)image2;
int w=120, h=80, t=1;
img = (int*) image;
w = 600;
h = 400;
t = 3;
for (i=0;i<w*h;i++) img[i]=6;
for (i=1;i<12;i++){
line(img,h,w,i*0.135,0,i*0.135,0.9091,1,7);
line(img,h,w,0.1364,(i-1)*0.09,1.5,(i-1)*0.09,1,7);
}
for (i=0;i<10;i++)
for (j=0;j<10;j++)
printInt((i+1)*36+12,(j+1)*54+4,img,h,w,confusion[i][j],4,3);
for (i=0;i<10;i++){
printInt((i+1)*36+12,20,img,h,w,i,0,3);
printInt(12,(i+1)*54+20,img,h,w,i,0,3);
}
websetcolors(8,red,green,blue,3);
webimagedisplay(w,h,img,3);
showCon = 1;
showDig[0][0]=0;
}
/**********************************************************************/
/* DISPLAY PROGRESS */
/**********************************************************************/
void displayCDigits(int x, int y){
// DISPLAY IMAGES FOR SPECIFIC CONFUSION MATRIX CELL
char buffer[1024];
int i,j,ct = 0;
for (i=0;i<maxCD;i++) if (cDigits[x][y][i]==-1) ct++;
ct = maxCD - ct;
sprintf(buffer,"Displaying true=%d, predict=%d",x,y);
if (ct==0) sprintf(buffer,"None to display: true=%d, predict=%d",x,y);
webwriteline(buffer);
displayDigits(cDigits[x][y],ct,4,1,0,0,2);
}
/**********************************************************************/
/* DISPLAY PROGRESS */
/**********************************************************************/
void line(int *img, int m, int n, float x1, float y1, float x2, float y2, int d, int c){
// DRAW A LINE INTO CANVAS
int xA, yA, xB, yB, xD, yD, d1, d2, s;
float xDf = 1.0, yDf = 1.0;
int i, j, k;
int points[(int)(1.5*m*m)][2];
int pointsSize = 0;
xA = (int)(x1*m);
yA = (int)(y1*m);
xB = (int)(x2*m);
yB = (int)(y2*m);
s = abs(xB - xA);
if (abs(yB - yA)>s) s = abs(yB - yA);
if (s!=0){
yDf = (float)(yB-yA)/(float)s;
xDf = (float)(xB-xA)/(float)s;
}
for (i=0;i<s+1;i++){
points[i][0] = (int)(xA+xDf*i);
points[i][1] = (int)(yA+yDf*i);
}
pointsSize = s+1;
for (i=0;i<pointsSize;i++)
for (j=-d;j<1+d;j++)
for (k=-d;k<1+d;k++){
if (points[i][1]+j>=0 && points[i][1]+j<m && points[i][0]+k>=0 && points[i][0]+k<1.5*m)
img[n*(points[i][1]+j) + points[i][0]+k] = c;
}
}
/**********************************************************************/
/* DISPLAY DOTS */
/**********************************************************************/
void displayClassify(int dd){
// DISPLAY CLASSIFICATION REGIONS FOR DOTS
int dx = 10, dy = 10, i,j,x,y,c;
websetcolors(8,red,green,blue,3);
for (i=0;i<240000;i++) ((int*)image)[i]=6;
int xl = 600/dx;
int yl = 400/dy;
for (x=0; x<xl; x++)
for (y=0; y<yl; y++){
trainDots[maxDots-1][0] = (float)dx*((float)x+0.5)/400.0;
trainDots[maxDots-1][1] = (float)dy*((float)y+0.5)/400.0;
c = forwardProp(maxDots-1,0,1,0);
for (i=x*dx;i<(x+1)*dx;i++)
for (j=y*dy;j<(y+1)*dy;j++)
image[j][i] = c;
}
placeDots();
if (useSmall==-1 || dd==1) webimagedisplay(600,400,(int*)image,3);
else{
for (i=0;i<80;i++)
for (j=0;j<120;j++)
image2[i][j] = image[i*5][j*5];
webimagedisplay(120,80,(int*)image2,3);
}
showDig[0][0]=0;
}
/**********************************************************************/
/* DISPLAY DOTS */
/**********************************************************************/
void displayClassify3D(){
// DISPLAY CLASSIFICATION REGIONS FOR DOTS IN 3D!
int dx = 5, dy = 5, i,j,x,y,c;
if (useSmall==1){ dx=10; dy=10;}
float xv[3], yv[3], zv[3];
float p0avg, p1avg, p2avg;
if (red4==NULL) setColors4();
websetcolors(262144,red4,green4,blue4,0);
webframe(5);
int xl = 600/dx;
int yl = 400/dy;
for (x=0; x<xl+1; x++)
for (y=0; y<yl+1; y++){
trainDots[maxDots-1][0] = (float)dx*((float)x+0.5)/400.0;
trainDots[maxDots-1][1] = (float)dy*((float)y+0.5)/400.0;
c = forwardProp(maxDots-1,0,1,0);
heights3D[x][y] = prob0 + 0.5*prob1;
pa3D[x][y] = prob0;
pb3D[x][y] = prob1;
pc3D[x][y] = prob2;
}
for (x=0; x<xl; x++)
for (y=0; y<yl; y++){
xv[0] = (float)x/xl;
yv[0] = (float)y/yl;
zv[0] = heights3D[x][y]/5.0 + 0.4;
xv[1] = (float)x/xl;
yv[1] = (float)(y+1)/yl;
zv[1] = heights3D[x][y+1]/5.0 + 0.4;
xv[2] = (float)(x+1)/xl;
yv[2] = (float)y/yl;
zv[2] = heights3D[x+1][y]/5.0 + 0.4;
p0avg = (pa3D[x][y]+pa3D[x][y+1]+pa3D[x+1][y])/3.0;
p1avg = (pb3D[x][y]+pb3D[x][y+1]+pb3D[x+1][y])/3.0;
p2avg = (pc3D[x][y]+pc3D[x][y+1]+pc3D[x+1][y])/3.0;
webfillflt(xv,yv,zv,3,(int)(p0avg*63)*4096 + (int)(p1avg*63)*64 + (int)(p2avg*63) + 1);
xv[0] = (float)x/xl;
yv[0] = (float)(y+1)/yl;
zv[0] = heights3D[x][y+1]/5.0 + 0.4;
xv[1] = (float)(x+1)/xl;
yv[1] = (float)(y+1)/yl;
zv[1] = heights3D[x+1][y+1]/5.0 + 0.4;
xv[2] = (float)(x+1)/xl;
yv[2] = (float)y/yl;
zv[2] = heights3D[x+1][y]/5.0 + 0.4;
p0avg = (pa3D[x+1][y+1]+pa3D[x][y+1]+pa3D[x+1][y])/3.0;
p1avg = (pb3D[x+1][y+1]+pb3D[x][y+1]+pb3D[x+1][y])/3.0;
p2avg = (pc3D[x+1][y+1]+pc3D[x][y+1]+pc3D[x+1][y])/3.0;
webfillflt(xv,yv,zv,3,(int)(p0avg*63)*4096 + (int)(p1avg*63)*64 + (int)(p2avg*63) + 1);
}
webgldisplay(0);
showDig[0][0]=0;
}
/**********************************************************************/
/* DISPLAY DOTS */
/**********************************************************************/
void removeDot(float x, float y){
// REMOVES DOT THAT USER UNCLICKED
float d, min = 10;
int i,imin = -1;
for (i=0;i<trainSizeD;i++){
d = pow(x-trainDots[i][0],2) + pow(y-trainDots[i][1],2);
if (d<min){
min = d;
imin = i;
}
}
if (imin!=-1){
trainDots[imin][0] = trainDots[trainSizeD-1][0];
trainDots[imin][1] = trainDots[trainSizeD-1][1];
trainColors[imin] = trainColors[trainSizeD-1];
trainSizeD--;
}
}
/**********************************************************************/
/* DISPLAY DOTS */
/**********************************************************************/
void placeDots(){
// DRAWS DOTS TO PANE 3
int i,j,k,x,y;
for (i=0;i<trainSizeD;i++){
x = trainDots[i][0]*400 - 7;
y = trainDots[i][1]*400 - 7;
for (j=0;j<15;j++)
for (k=0;k<15;k++){
if (y+j>=0 && y+j<400 && x+k>=0 && x+k<600){
image[y+j][x+k] = trainColors[i];
if (j<2 | j>12 | k<2 | k>12)
image[y+j][x+k] = 7;
}
}
}
}
/**********************************************************************/
/* DISPLAY DOTS */
/**********************************************************************/
void updateImage(){
// UPDATES PANE 3 IMAGE WITH DOTS
int i,j;
websetcolors(8,red,green,blue,3);
for (i=0;i<240000;i++) ((int*)image)[i]=6;
placeDots();
if (useSmall==-1) webimagedisplay(600,400,(int*)image,3);
else{
for (i=0;i<80;i++)
for (j=0;j<120;j++)
image2[i][j] = image[i*5][j*5];
webimagedisplay(120,80,(int*)image2,3);
}
showDig[0][0]=0;
showCon=0;
}
/**********************************************************************/
/* DISPLAY DOTS */
/**********************************************************************/
void clearImage(int p){
// CLEARS IMAGE IN PANE P
websetcolors(8,red,green,blue,p);
for (int i=0;i<80;i++) for (int j=0;j<120;j++)
image2[i][j] = 6;
webimagedisplay(120,80,(int*)image2,p);
}
/**********************************************************************/
/* INIT NET */
/**********************************************************************/
void initArch(char *str, int x){
// PARSES USER INPUT TO CREATE DESIRED NETWORK ARCHITECTURE
//TODO: remove all spaces, check for invalid characters
int i;
char *idx = str, *idx2;
while (idx[0]==' ' && idx[0]!=0) idx++;
for (i=0;i<strlen(idx);i++) str[i]=idx[i];
if (str[0]==0) {str[0]='0'; str[1]=0;}
if (str[0]>='0' && str[0]<='9'){
layerSizes[x] = atoi(str);
layerConv[x] = 0;
layerChan[x] = 1;
layerPad[x] = 0;
layerWidth[x] = (int)sqrt(layerSizes[x]);
if (layerWidth[x]*layerWidth[x]!=layerSizes[x]) layerWidth[x]=1;
layerStride[x] = 1;
layerConvStep[x] = 0;
layerConvStep2[x] = 0;
layerType[x] = 0;
}
else if (str[0]=='c' || str[0]=='C'){
int more = 1;
str[0]='C';
idx = str+1;
while(*idx!=':' && *idx!='-' && *idx!=0) idx++;
if (*idx==0) more = 0; *idx = 0;
layerConv[x] = atoi(str+1);
layerChan[x] = 1;
layerPad[x] = 0;
//layerWidth[x] = layerWidth[x-1];
layerWidth[x] = layerWidth[x-1]-layerConv[x]+1;
if (more==1){
*idx = ':';
idx++; idx2 = idx;
while(*idx!=':' && *idx!='-' && *idx!=0) idx++;
if (*idx==0) more = 0; *idx = 0;
layerChan[x] = atoi(idx2);
if (more==1){
*idx = ':';
idx++; idx2 = idx;
while(*idx!=':' && *idx!='-' && *idx!=0) idx++;
if (*idx==0) more = 0; *idx = 0;
layerPad[x] = atoi(idx2);
if (layerPad[x]==1)
layerWidth[x] = layerWidth[x-1];
//layerWidth[x] = layerWidth[x-1]-layerConv[x]+1;
}
}
layerSizes[x] = layerWidth[x] * layerWidth[x];
layerConvStep2[x] = layerConv[x] * layerConv[x];
layerConvStep[x] = layerConvStep2[x] * layerChan[x-1];
layerStride[x] = 1;
layerType[x] = 1;
}
else if (str[0]=='p' || str[0]=='P'){
int more = 1;
if (activation!=0) str[0]='P'; // allow avg pool if identity act
idx = str+1;
while(*idx!=':' && *idx!='-' && *idx!=0) idx++;
if (*idx==0) more = 0; *idx = 0;
layerConv[x] = atoi(str+1);
layerStride[x] = layerConv[x];
if (more==1){
*idx = ':';
idx++; idx2 = idx;
while(*idx!=':' && *idx!='-' && *idx!=0) idx++;
if (*idx==0) more = 0; *idx = 0;
layerStride[x] = atoi(idx2);
}
int newWidth = layerWidth[x-1]/layerStride[x];
if (layerStride[x]!=layerConv[x])
newWidth = (layerWidth[x-1]-layerConv[x]+layerStride[x])/layerStride[x];
layerSizes[x] = newWidth * newWidth;
layerChan[x] = layerChan[x-1];
layerPad[x] = 0;
layerWidth[x] = newWidth;
layerConvStep2[x] = layerConv[x] * layerConv[x];
layerConvStep[x] = layerConvStep2[x];
layerType[x] = 2; // MAX POOLING
if (str[0]=='p') layerType[x] = 3; // AVG POOLING
}
strcpy(layerNames[x],str);
}
/**********************************************************************/
/* INIT NET */
/**********************************************************************/
void initNet(int t){
// ALLOCATION MEMORY AND INITIALIZE NETWORK WEIGHTS
int i,j, same=1, LL, dd=9;
char buf[10], buf2[20];
if (t==0){
for (i=0;i<10;i++) {
strcpy(nets[0][i],"0");
layerType[i] = 0;
}
for (i=9;i>=0;i--){
sprintf(buf,"L%d",i);
strcpy (buf2,spGet(buf));
buf2[19]=0;
if (buf2[0]!=0 && buf2[0]!='0'){
if (strcmp(buf2,nets[0][dd])!=0) same=0;
strcpy(nets[0][dd--],buf2);
}
}
if (numLayers!=9-dd) same=0;
}
// FREE OLD NET
if ( (t!=inited && layers[0]!=NULL) || (t==0 && same==0) ){
free(layers[0]);
free(errors[0]);
for (i=1;i<10;i++){
free(layers[i]);
free(dropOut[i]);
free(errors[i]);
free(weights[i]);
}
layers[0] = NULL;
}
// SET NEW NET ARCHITECTURE
numLayers = 0;
for (i=0;i<10;i++) {
initArch(nets[t][i],i);
sprintf(buf,"L%d",i);
spSet(buf,nets[t][i]);
if (numLayers==0 && layerSizes[i]!=0) numLayers = 10-i;
}
webupdate(ip,rp,sp);
//printf("\n");
// ALOCATE MEMORY
if (layers[0]==NULL){
layers[0] = (float*)malloc((layerSizes[0]+1) * sizeof(float));
errors[0] = (float*)malloc(layerSizes[0] * sizeof(float));
for (i=1;i<10;i++){
layers[i] = (float*)malloc((layerSizes[i] * layerChan[i] + 1) * sizeof(float));
dropOut[i] = (int*)malloc((layerSizes[i] * layerChan[i] + 1) * sizeof(int));
//printf("setting dropOut i=%d to %d\n",i,(layerSizes[i] * layerChan[i] + 1));
errors[i] = (float*)malloc((layerSizes[i] * layerChan[i] + 1) * sizeof(float));
if (layerType[i]==0) // FULLY CONNECTED
weights[i] = (float*)malloc(layerSizes[i] * (layerSizes[i-1]*layerChan[i-1]+1) * sizeof(float));
else if (layerType[i]==1) // CONVOLUTION
weights[i] = (float*)malloc((layerConvStep[i]+1) * layerChan[i] * sizeof(float));
else if (layerType[i]>=2) // POOLING (2=max, 3=avg)
weights[i] = (float*)malloc( sizeof(float));
}
}
// RANDOMIZE WEIGHTS AND BIAS
float scale;
for (i=0;i<10;i++) layers[i][layerSizes[i] * layerChan[i]]=1.0;
for (j=1;j<10;j++){
scale = 1.0;
if (layerSizes[j-1]!=0){
// XAVIER INITIALIZATION (= SQRT( 6/(N_in + N_out) ) ) What is N_out to MaxPool ??
if (layerType[j]==0){ // FC LAYER
if (layerType[j+1]==0)
scale = 2.0 * sqrt(6.0/ ( layerSizes[j-1]*layerChan[j-1] + layerSizes[j] ));
else if (layerType[j+1]==1) // impossible
scale = 2.0 * sqrt(6.0/ ( layerSizes[j-1]*layerChan[j-1] + layerConvStep[j+1] ));
else if (layerType[j+1]>=2) // impossible
scale = 2.0 * sqrt(6.0/ ( layerSizes[j-1]*layerChan[j-1] + layerSizes[j-1]*layerChan[j-1] ));
}
else if (layerType[j]==1){ // CONV LAYER
if (layerType[j+1]==0)
scale = 2.0 * sqrt(6.0/ ( layerConvStep[j] + layerSizes[j]*layerChan[j] ));
else if (layerType[j+1]==1)
scale = 2.0 * sqrt(6.0/ ( layerConvStep[j] + layerConvStep[j+1] ));
else if (layerType[j+1]>=2)
scale = 2.0 * sqrt(6.0/ ( layerConvStep[j] + layerConvStep[j] ));
}
//if (activation==1 && j!=9) scale *= sqrt(2.0); // DO I WANT THIS? INPUT ISN'T MEAN=0
//printf("Init layer %d: LS=%d LC=%d LCS=%d Scale=%f\n",j,layerSizes[j],layerChan[j],layerConvStep[j],scale);
if (j!=9) scale *= weightScale;
}
if (layerType[j]==0){ // FULLY CONNECTED
for (i=0;i<layerSizes[j] * (layerSizes[j-1]*layerChan[j-1]+1);i++)
weights[j][i] = scale * ( (float)rand()/(float)RAND_MAX - 0.5 );
//weights[j][i] = 0.1;
for (i=0;i<layerSizes[j];i++) // set biases to zero
weights[j][(layerSizes[j-1]*layerChan[j-1]+1)*(i+1)-1] = 0.0;
}
else if (layerType[j]==1){ // CONVOLUTION
for (i=0;i<(layerConvStep[j]+1) * layerChan[j];i++)
weights[j][i] = scale * ( (float)rand()/(float)RAND_MAX - 0.5 );
for (i=0;i<layerChan[j];i++) // set conv biases to zero
weights[j][(layerConvStep[j]+1)*(i+1)-1] = 0.0;
}
}
inited = t;
if (isDigits(inited)!=1) {
showCon = 0;
showDig[0][0] = 0;
updateImage();
}
}
/**********************************************************************/
/* NEURAL NETWORK */
/**********************************************************************/
int isDigits(int init){
// DETERMINES WHETHER TO TRAIN DOTS OR LOADED DATA
int in = 10-numLayers;
if (layerSizes[in]==196 || layerSizes[in]==784 || layerSizes[in]==trainColumns) return 1;
else return 0;
}
/**********************************************************************/
/* NEURAL NETWORK */
/**********************************************************************/
void randomizeTrainSet(){
// RANDOMIZES INDICES IN TRAINING SET
int i, temp, x;
for (i=0;i<trainSetSize;i++){
x = (int)(trainSetSize * ((float)rand()/(float)RAND_MAX) - 1);
temp = trainSet[i];
trainSet[i] = trainSet[x];
trainSet[x] = temp;
}
}
/**********************************************************************/
/* NEURAL NETWORK */
/**********************************************************************/
void dataAugment(int img, int r, float sc, float dx, float dy, int p, int hiRes, int loRes, int t){
// AUGMENT AN IMAGE AND STORE RESULT IN TRAIN IMAGES ARRAY
int i,j,x2,y2;
float x,y;
float pi = 3.1415926;
float c = cos(pi * r/180.0);
float s = sin(pi * r/180.0);
float (*trainImagesB)[784] = trainImages;
float (*trainImages2B)[196] = trainImages2;
if (t==0){
trainImagesB = testImages;
trainImages2B = testImages2;
}
if (loRes==1){
for (i=0;i<14;i++)
for (j=0;j<14;j++){
x = (j - 6.5)/sc - dx/2.0;
y = (i - 6.5)/sc + dy/2.0;
x2 = (int)round((c*x-s*y)+6.5);
y2 = (int)round((s*x+c*y)+6.5);
if (y2>=0 && y2<14 && x2>=0 && x2<14)
trainImages2[trainSizeE][i*14+j] = trainImages2B[img][y2*14+x2];
else trainImages2[trainSizeE][i*14+j] = -imgBias;
}}
if (hiRes==1){
for (i=0;i<28;i++)
for (j=0;j<28;j++){
x = (j - 13.5)/sc - dx;
y = (i - 13.5)/sc + dy;
x2 = (int)round((c*x-s*y)+13.5);
y2 = (int)round((s*x+c*y)+13.5);
if (y2>=0 && y2<28 && x2>=0 && x2<28)
trainImages[trainSizeE][i*28+j] = trainImagesB[img][y2*28+x2];
else trainImages[trainSizeE][i*28+j] = -imgBias;
}}
if (p>=3 && p<=5) displayDigit(trainSizeE,1,p,0,0,1,0,2);
trainDigits[trainSizeE] = trainDigits[img];
if (t==0) trainDigits[trainSizeE] = -1;
}
/**********************************************************************/
/* NEURAL NETWORK */
/**********************************************************************/
void *runBackProp(void *arg){
// TRAINS NEURAL NETWORK WITH TRAINING DATA
time_t start,stop;
showEnt = 1; showAcc = 1;
char buffer[80];
int i, x = pass[0], y = pass[1], z = pass[2];
int p, confusion[10][10]={{0}};
if (layers[0]==NULL){
initNet(1);
if (z==1) {
sprintf(buffer,"Assuming NN=1 with Xavier init scaled=%.3f",weightScale);
webwriteline(buffer);
ipSet("net",1);
webupdate(ip,rp,sp);
}
int len = sprintf(buffer,"Architecture (%d",layerSizes[0]);
for (i=1;i<10;i++) len += sprintf(buffer+len,"-%d",layerSizes[i]);
sprintf(buffer+len,")");
if (z==1) webwriteline(buffer);
}
// LEARN DIGITS
int trainSize = trainSetSize;
int testSize = validSetSize;
if (isDigits(inited)==1) {
websetmode(2);
showCon=1;
}
else { // LEARN DOTS
trainSize = trainSizeD;
testSize = 0;
websetmode(dotsMode);
}
if (trainSize==0){
if (isDigits(inited)==1) webwriteline("Load images first. Click load.");
else webwriteline("Create training dots first. Click dots inside pane to the right.");
working=0; websetmode(2);
return NULL;
}
// ALLOCATE MEMORY FOR ENTORPY AND ACCURACY HISTORY
if (ents!=NULL){
free(ents); free(ents2); free(accs); free(accs2);
ents = NULL;
}
ents = (float*)malloc( (int)(x/y+1) * sizeof(float) );
ents2 = (float*)malloc( (int)(x/y+1) * sizeof(float) );
accs = (float*)malloc( (int)(x/y+1) * sizeof(float) );
accs2 = (float*)malloc( (int)(x/y+1) * sizeof(float) );
int entSize = 0, accSize = 0, ent2Size = 0, acc2Size = 0;
int j,j2,k,s,s2,b;
float entropy,entropy2,ent;
time(&start);
// PERFORM X TRAINING EPOCHS
for (j=0;j<x;j++){
s = 0; entropy = 0.0;
if (isDigits(inited)!=1) trainSize = trainSizeD;
for (i=0;i<trainSize;i++){
//if (i%100==0) printf("x=%d, i=%d\n",j,i);
if (isDigits(inited)==1) b = backProp(trainSet[i],&ent,j); // LEARN DIGITS
else b = backProp(i,&ent,0); // LEARN DOTS
if (b==-1) {
if (z==1) webwriteline("Exploded. Lower learning rate.");
else printf("Exploded. Lower learning rate.\n");
working=0; websetmode(2);
return NULL;
}
s += b;
entropy += ent;
if (working==0){
webwriteline("learning stopped early");
pthread_exit(NULL);
}
}
entropy = entropy / trainSize;
s2 = 0; entropy2 = 0.0;
for (i=0;i<10;i++) for (k=0;k<10;k++) confusion[i][k]=0;
for (i=0;i<10;i++) for (j2=0;j2<10;j2++) for (k=0;k<maxCD;k++) cDigits[i][j2][k]= -1;
for (i=0;i<testSize;i++){
p = forwardProp(validSet[i],0,1,0);
if (p==-1) {
if (z==1) webwriteline("Test exploded.");
else printf("Test exploded.\n");
working=0; websetmode(2);
return NULL;
}
if (p==trainDigits[validSet[i]]) s2++;
cDigits[trainDigits[validSet[i]]][p][ confusion[trainDigits[validSet[i]]][p]%maxCD ] = validSet[i];
confusion[trainDigits[validSet[i]]][p]++;
if (layers[9][p]==0){
if (z==1) webwriteline("Test vanished.");
else printf("Test vanished.\n");
working=0; websetmode(2);
return NULL;
}
entropy2 -= log(layers[9][p]);
if (working==0){
webwriteline("learning stopped early");
pthread_exit(NULL);
}
}
entropy2 = entropy2 / testSize;
if (j==0 || (j+1)%y==0){
ents[entSize++] = entropy;
accs[accSize++] = (float)s/trainSize;
if (isDigits(inited)==1) {
accs2[acc2Size++] = (float)s2/testSize;
ents2[ent2Size++] = entropy2;
}
time(&stop);
sprintf(buffer,"i=%d acc=%d/%d, ent=%.4f, lr=%.1e",j+1,s,trainSize,entropy,an*pow(decay,j));
if (isDigits(inited)==1 && testSize>0) sprintf(buffer,"i=%d train=%.2f ent=%.4f,valid=%.2f ent=%.4f (%.0fsec) lr=%.1e",
j+1,100.0*s/trainSize,entropy,100.0*s2/testSize,entropy2,difftime(stop,start),an*pow(decay,j));
else if (isDigits(inited)==1 && testSize==0) sprintf(buffer,"i=%d train=%.2f ent=%.4f (%.0fsec) lr=%.1e",
j+1,100.0*s/trainSize,entropy,difftime(stop,start),an*pow(decay,j));
time(&start);
if (z==1) webwriteline(buffer);
else printf("%s\n",buffer);
if (z==1 && isDigits(inited)!=1) {
if (use3D==1) displayClassify3D();
else displayClassify(0);
}
if (z==1 && showEnt==1) displayEntropy(ents,entSize,ents2,y);
if (z==1 && showAcc==1) displayAccuracy(accs,accSize,accs2,y);
if (z==1 && isDigits(inited)==1 && showCon==1) displayConfusion(confusion);
}
if (requestInit==1){
initNet(ipGet("net"));
requestInit = 0;
}
if (working==0){
webwriteline("learning stopped early");
pthread_exit(NULL);
}
if (isDigits(inited)==1 && randomizeDescent==1) randomizeTrainSet();
}
webwriteline("Done");
working=0; websetmode(2);
return NULL;
}
/**********************************************************************/
/* NEURAL NETWORK */
/**********************************************************************/
int backProp(int x, float *ent, int ep){
// BACK PROPAGATION WITH 1 TRAINING IMAGE
int i = 0, j, k, r = 0, d=0, rot=0, hres=0, lres=1;
float der=1.0, xs=0.0, ys=0.0, extra=0.0, sc=1.0, sum;
int dc, a, a2, i2, j2, i3, j3, pmax, imax, jmax;
int temp, temp2;
// DATA AUGMENTATION
if (augmentRatio>0.0 && isDigits(inited)==1)
if ( (float)rand()/(float)RAND_MAX <= augmentRatio ){
if (augmentAngle>0.0)
rot = (int)(2.0 * augmentAngle * (float)rand()/(float)RAND_MAX - augmentAngle);
if (augmentDx>0.0)
xs = (2.0 * augmentDx * (float)rand()/(float)RAND_MAX - augmentDx);
if (augmentDy>0.0)
ys = (2.0 * augmentDy * (float)rand()/(float)RAND_MAX - augmentDy);
if (augmentScale>0.0)
sc = 1.0 + 2.0 * augmentScale * (float)rand()/(float)RAND_MAX - augmentScale;
if (layerSizes[10-numLayers]==784){hres=1;lres=0;}
dataAugment(x,rot,sc,xs,ys,-1,hres,lres,1);
x = trainSizeE;
}
// FORWARD PROP FIRST
int p = forwardProp(x,1,1,0);
if (p==-1) return -1; // GRADIENT EXPLODED
// CORRECT PREDICTION?
int y;
if (isDigits(inited)==1) y = trainDigits[x];
else y = trainColors[x];
if (p==y) r=1;
// OUTPUT LAYER - CALCULATE ERRORS
for (i=0;i<layerSizes[9];i++){
errors[9][i] = an * (0 - layers[9][i]) * pow(decay,ep);
if (i==y) {
errors[9][i] = an * (1 - layers[9][i]) * pow(decay,ep);
if (layers[9][i]==0) return -1; // GRADIENT VANISHED
*ent = -log(layers[9][i]);
}
}
// HIDDEN LAYERS - CALCULATE ERRORS
for (k=8;k>10-numLayers;k--){
if (layerType[k+1]==0) // FEEDS INTO FULLY CONNECTED
for (i=0;i<layerSizes[k]*layerChan[k];i++){
errors[k][i] = 0.0;
if (dropOutRatio==0.0 || DOdense==0 || dropOut[k][i]==1){ // dropout
if (activation==2) der = (layers[k][i]+1)*(1-layers[k][i]); //TanH derivative
if (activation==0 || activation==2 || layers[k][i]>0){ //this is ReLU derivative
temp = layerSizes[k]*layerChan[k]+1;
for (j=0;j<layerSizes[k+1];j++)
errors[k][i] += errors[k+1][j]*weights[k+1][j*temp+i]*der;
}
}
}
else if (layerType[k+1]==1){ // FEEDS INTO CONVOLUTION
for (i=0;i<layerSizes[k]*layerChan[k];i++) errors[k][i] = 0.0;
dc = 0; if (layerPad[k+1]==1) dc = layerConv[k+1]/2;
for (a=0;a<layerChan[k+1];a++)
for (i=0;i<layerWidth[k+1];i++)
for (j=0;j<layerWidth[k+1];j++){
temp = a*(layerConvStep[k+1]+1);
temp2 = a*layerSizes[k+1] + i*layerWidth[k+1] + j;
for (a2=0;a2<layerChan[k];a2++)
for (i2=0;i2<layerConv[k+1];i2++)
for (j2=0;j2<layerConv[k+1];j2++){
i3 = i + i2 - dc;
j3 = j + j2 - dc;
if (activation==2) der = (layers[k][a2*layerSizes[k] + i3*layerWidth[k] + j3]+1)*(1-layers[k][a2*layerSizes[k] + i3*layerWidth[k] + j3]); //TanH
if (activation==0 || activation==2 || layers[k][a2*layerSizes[k] + i3*layerWidth[k] + j3]>0) // this is ReLU derivative
if (i3>=0 && i3<layerWidth[k] && j3>=0 && j3<layerWidth[k]) // padding
errors[k][a2*layerSizes[k] + i3*layerWidth[k] + j3] +=
weights[k+1][temp + a2*layerConvStep2[k+1] + i2*layerConv[k+1] +j2]
* errors[k+1][temp2] * der;
}
}
if (dropOutRatio>0.0 && DOconv==1) // dropout
for (i=0;i<layerSizes[k]*layerChan[k];i++) errors[k][i] = errors[k][i] * dropOut[k][i];
}
else if (layerType[k+1]>=2){ // FEEDS INTO POOLING (2=max, 3=avg)
for (i=0;i<layerSizes[k]*layerChan[k];i++) errors[k][i] = 0.0;
for (a=0;a<layerChan[k];a++)
for (i=0;i<layerWidth[k+1];i++)
for (j=0;j<layerWidth[k+1];j++){
pmax = -1e6;
if (layerType[k+1]==3)
temp = errors[k+1][a*layerSizes[k+1] + i*layerWidth[k+1] + j] / layerConvStep2[k+1];
for (i2=0;i2<layerConv[k+1];i2++)
for (j2=0;j2<layerConv[k+1];j2++){
if (layerType[k+1]==3) errors[k][a*layerSizes[k] + (i*layerStride[k+1]+i2)*layerWidth[k] + j*layerStride[k+1]+j2] = temp;
else if (layers[k][a*layerSizes[k] + (i*layerStride[k+1]+i2)*layerWidth[k] + j*layerStride[k+1]+j2]>pmax){
pmax = layers[k][a*layerSizes[k] + (i*layerStride[k+1]+i2)*layerWidth[k] + j*layerStride[k+1]+j2];
imax = i2;
jmax = j2;
}
}
if (layerType[k+1]==2)
errors[k][a*layerSizes[k] + (i*layerStride[k+1]+imax)*layerWidth[k] + j*layerStride[k+1]+jmax] =
errors[k+1][a*layerSizes[k+1] + i*layerWidth[k+1] + j];
}
if (dropOutRatio>0.0 && DOpool==1) //dropout
for (i=0;i<layerSizes[k]*layerChan[k];i++) errors[k][i] = errors[k][i] * dropOut[k][i];
}
}
// UPDATE WEIGHTS - GRADIENT DESCENT
int count = 0;
for (k=11-numLayers;k<10;k++){
if (layerType[k]==0){ // FULLY CONNECTED LAYER
for (i=0;i<layerSizes[k];i++){
temp = i*(layerSizes[k-1]*layerChan[k-1]+1);
for (j=0;j<layerSizes[k-1]*layerChan[k-1]+1;j++)
weights[k][temp+j] += errors[k][i]*layers[k-1][j];
}
}
else if (layerType[k]==1){ // CONVOLUTION LAYER
dc = 0; if (layerPad[k]==1) dc = layerConv[k]/2;
for (a=0;a<layerChan[k];a++)
for (i=0;i<layerWidth[k];i++)
for (j=0;j<layerWidth[k];j++){
temp = a*(layerConvStep[k]+1);
temp2 = a*layerSizes[k] + i*layerWidth[k] + j;
for (a2=0;a2<layerChan[k-1];a2++)
for (i2=0;i2<layerConv[k];i2++)
for (j2=0;j2<layerConv[k];j2++){
i3 = i + i2 - dc;
j3 = j + j2 - dc;
if (i3>=0 && i3<layerWidth[k-1] && j3>=0 && j3<layerWidth[k-1])
weights[k][temp + a2*layerConvStep2[k] + i2*layerConv[k] + j2] +=
errors[k][temp2] * layers[k-1][a2*layerSizes[k-1] + i3*layerWidth[k-1] + j3];
}
weights[k][(a+1)*(layerConvStep[k]+1)-1] += errors[k][a*layerSizes[k] + i*layerWidth[k] + j];
}
}
}
return r;
}
/**********************************************************************/
/* NEURAL NETWORK */
/**********************************************************************/
int forwardProp(int x, int dp, int train, int lay){
// FORWARD PROPAGATION WITH 1 IMAGE
int i,j,k,imax,dc;
int a, a2, i2, j2, i3, j3;
float sum, esum, max, rnd, pmax;
int temp, temp2;
// INPUT LAYER
if (isDigits(inited)==1 && layerSizes[10-numLayers]==196){
if (train==1) for (i=0;i<196;i++) layers[10-numLayers][i] = trainImages2[x][i];
else for (i=0;i<196;i++) layers[10-numLayers][i] = testImages2[x][i];
}
else if (isDigits(inited)==1 && layerSizes[10-numLayers]==784){
if (train==1) for (i=0;i<784;i++) layers[10-numLayers][i] = trainImages[x][i];
else for (i=0;i<784;i++) layers[10-numLayers][i] = testImages[x][i];
}
else if (isDigits(inited)==1 && layerSizes[10-numLayers]==trainColumns){
if (train==1) for (i=0;i<trainColumns;i++) layers[10-numLayers][i] = trainImages[x][i];
else for (i=0;i<trainColumns;i++) layers[10-numLayers][i] = testImages[x][i];
}
else if (layerSizes[10-numLayers]==2)
for (i=0;i<2;i++) layers[10-numLayers][i] = trainDots[x][i];
// HIDDEN LAYERS
for (k=11-numLayers;k<9;k++){
if (lay!=0 && k>lay) return -1;
// CALCULATE DROPOUT
//if (dropOutRatio>0.0) // ALWAYS SET TO 1 TO BE SAFE
for (i=0;i<layerSizes[k]*layerChan[k];i++) {
dropOut[k][i] = 1;
if (dropOutRatio>0.0 && dp==1) {
rnd = (float)rand()/(float)RAND_MAX;
if (rnd<dropOutRatio) dropOut[k][i] = 0;
}
}
if (layerType[k]==0) // FULLY CONNECTED LAYER
for (i=0;i<layerSizes[k];i++){
if (dropOutRatio==0.0 || dp==0 || DOdense==0 || dropOut[k][i]==1){
temp = i*(layerSizes[k-1]*layerChan[k-1]+1);
sum = 0.0;
for (j=0;j<layerSizes[k-1]*layerChan[k-1]+1;j++)
sum += layers[k-1][j]*weights[k][temp+j];
if (activation==0) layers[k][i] = sum;
else if (activation==1) layers[k][i] = ReLU(sum);
else layers[k][i] = TanH(sum);
//if (dropOutRatio>0.0 && dp==1) layers[k][i] = layers[k][i] / (1-dropOutRatio);
if (dropOutRatio>0.0 && dp==0 && DOdense==1) layers[k][i] = layers[k][i] * (1-dropOutRatio);
}
else layers[k][i] = 0.0;
}
else if (layerType[k]==1){ // CONVOLUTION LAYER
dc = 0; if (layerPad[k]==1) dc = layerConv[k]/2;
for (a=0;a<layerChan[k];a++)
for (i=0;i<layerWidth[k];i++)
for (j=0;j<layerWidth[k];j++){
temp = a*(layerConvStep[k]+1);
sum = 0.0;
for (a2=0;a2<layerChan[k-1];a2++)
for (i2=0;i2<layerConv[k];i2++)
for (j2=0;j2<layerConv[k];j2++){
i3 = i + i2 - dc;
j3 = j + j2 - dc;
if (i3>=0 && i3<layerWidth[k-1] && j3>=0 && j3<layerWidth[k-1])
sum += layers[k-1][a2*layerSizes[k-1] + i3*layerWidth[k-1] + j3] * weights[k][temp + a2*layerConvStep2[k] + i2*layerConv[k] + j2];
else sum -= imgBias * weights[k][temp + a2*layerConvStep2[k] + i2*layerConv[k] + j2];
}
sum += weights[k][(a+1)*(layerConvStep[k]+1)-1];
if (activation==0) layers[k][a*layerSizes[k] + i*layerWidth[k] + j] = sum;
else if (activation==1) layers[k][a*layerSizes[k] + i*layerWidth[k] + j] = ReLU(sum);
else layers[k][a*layerSizes[k] + i*layerWidth[k] + j] = TanH(sum);
}
// APPLY DROPOUT
if (dropOutRatio>0.0 && DOconv==1)
for (i=0;i<layerSizes[k]*layerChan[k];i++){
if (dp==0) layers[k][i] = layers[k][i] * (1-dropOutRatio);
else if (dp==1) layers[k][i] = layers[k][i] * dropOut[k][i];
}
}
else if (layerType[k]>=2) // POOLING LAYER (2=max, 3=avg)
for (a=0;a<layerChan[k];a++)
for (i=0;i<layerWidth[k];i++)
for (j=0;j<layerWidth[k];j++){
sum = 0.0;
pmax = -1e6;
for (i2=0;i2<layerConv[k];i2++)
for (j2=0;j2<layerConv[k];j2++){
if (layerType[k]==3) sum += layers[k-1][a*layerSizes[k-1] + (i*layerStride[k]+i2)*layerWidth[k-1] + j*layerStride[k]+j2];
else if (layers[k-1][a*layerSizes[k-1] + (i*layerStride[k]+i2)*layerWidth[k-1] + j*layerStride[k]+j2]>pmax)
pmax = layers[k-1][a*layerSizes[k-1] + (i*layerStride[k]+i2)*layerWidth[k-1] + j*layerStride[k]+j2];
}
if (layerType[k]==3) layers[k][a*layerSizes[k] + i*layerWidth[k] + j] = sum / layerConvStep2[k];
else layers[k][a*layerSizes[k] + i*layerWidth[k] + j] = pmax;
}
// APPLY DROPOUT
if (dropOutRatio>0.0 && DOpool==1)
for (i=0;i<layerSizes[k]*layerChan[k];i++){
if (dp==0) layers[k][i] = layers[k][i] * (1-dropOutRatio);
else if (dp==1) layers[k][i] = layers[k][i] * dropOut[k][i];
}
}
// OUTPUT LAYER - SOFTMAX ACTIVATION
esum = 0.0;
for (i=0;i<layerSizes[9];i++){
sum = 0.0;
for (j=0;j<layerSizes[8]+1;j++)
sum += layers[8][j]*weights[9][i*(layerSizes[8]+1)+j];
layers[9][i] = exp(sum);
if (layers[9][i]>1e30) return -1; //GRADIENTS EXPLODED
esum += layers[9][i];
}
// SOFTMAX FUNCTION
max = layers[9][0]; imax=0;
for (i=0;i<layerSizes[9];i++){
if (layers[9][i]>max){
max = layers[9][i];
imax = i;
}
layers[9][i] = layers[9][i] / esum;
}
prob = layers[9][imax]; // ugly use of global variable :-(
prob0 = layers[9][0];
prob1 = layers[9][2];
prob2 = layers[9][4];
return imax;
}
/**********************************************************************/
/* NEURAL NETWORK */
/**********************************************************************/
float ReLU(float x){
if (x>0) return x;
else return 0;
}
/**********************************************************************/
/* NEURAL NETWORK */
/**********************************************************************/
float TanH(float x){
return 2.0/(1.0+exp(-2*x))-1.0;
}
/**********************************************************************/
/* KNN */
/**********************************************************************/
int singleKNN(int x, int k, int d, int p, int train, int big, int disp){
// PERFORM KNN ON A SINGLE IMAGE
char buffer[80];
int i,j,j2,c,max=0,imax=0,s=0,sz=196;
float dist[k], dd;
int idx[k];
if (big==1) sz = 784;
float (*testImages3)[sz];
float (*trainImages3)[sz];
if (big==0){
if (train==1) {
testImages3 = trainImages2;
trainImages3 = trainImages2;
}
else {
testImages3 = testImages2;
trainImages3 = trainImages2;
}
}
else if (big==1){
if (train==1) {
testImages3 = trainImages;
trainImages3 = trainImages;
}
else {
testImages3 = testImages;
trainImages3 = trainImages;
}
}
int votes[10];
for (j=0;j<k;j++){
idx[j] = j;
dist[j] = distance( testImages3[x], trainImages3[j],sz,d);
if (train==1 && x==j) dist[j] = 1e9;
}
fakeHeap(dist,idx,k);
for (j=k;j<trainSizeI;j++){
dd = distance( testImages3[x], trainImages3[j],sz,d);
if (train==1 && x==j) dd = 1e9;
if (dd<dist[0]){
dist[0] = dd;
idx[0] = j;
fakeHeap(dist,idx,k);
}
}
max = 0;
for (j=0;j<10;j++) votes[j]=0;
for (j=0;j<k;j++){
c = trainDigits[idx[j]];
votes[c]++;
if (votes[c]>max){
max = votes[c];
imax = c;
}
}
if (disp==1){
sortHeap(dist,idx,k);
int dgs[k+1];
dgs[0] = x;
if (train==0){
for (i=0;i<196;i++) trainImages2[trainSizeE][i] = testImages2[x][i];
for (i=0;i<784;i++) trainImages[trainSizeE][i] = testImages[x][i];
trainDigits[trainSizeE] = 0;
dgs[0] = trainSizeE;
}
for (i=0;i<k;i++) dgs[i+1] = idx[i];
displayDigits(dgs,k+1,p,1,0,0,big);
}
return imax;
}
/**********************************************************************/
/* KNN */
/**********************************************************************/
void *runKNN(void *arg){
// PERFORM KNN ON ENTIRE VALIDATION SET
// I SHOULD UTILIZE SINGLE KNN FUNCTION
int y2=pass[1], y=pass[1], k=pass[2], d=pass[3], z=pass[4], big=pass[0];
if (validSetSize==0){
webwriteline("Load images first. Click load.");
working=0;
return NULL;
}
showCon = 1;
char buffer[80];
sprintf(buffer,"Begin kNN with k=%d, L%d norm, big=%d",k,d,big);
webwriteline(buffer);
int dp = 0;
int i,j,j2,c,max=0,imax=0,s=0;
int trainSize = trainSetSize;
int testSize = validSetSize;
float dist[k], dd;
int idx[k], dgs[24];
int votes[10];
int confusion[10][10]={{0}};
for (i=0;i<10;i++) for (j=0;j<10;j++) for (j2=0;j2<maxCD;j2++) cDigits[i][j][j2]= -1;
int size = 196; if (big==1 || big==2) size = 784;
float (*trainImages3)[size];
if (big==1 || big==2) trainImages3 = trainImages;
else trainImages3 = trainImages2;
if (big==2) size = trainColumns;
for (i=0;i<validSetSize;i++){
for (j=0;j<k;j++){
idx[j] = j;
dist[j] = distance( trainImages3[validSet[i]], trainImages3[trainSet[j]],size,d);
}
fakeHeap(dist,idx,k);
for (j=k;j<trainSetSize;j++){
dd = distance( trainImages3[validSet[i]], trainImages3[trainSet[j]],size,d);
if (dd<dist[0]){
dist[0] = dd;
idx[0] = j;
fakeHeap(dist,idx,k);
}
}
max = 0;
for (j=0;j<10;j++) votes[j]=0;
for (j=0;j<k;j++){
c = trainDigits[trainSet[idx[j]]];
votes[c]++;
if (votes[c]>max){
max = votes[c];
imax = c;
}
}
c = trainDigits[validSet[i]];
if (c==imax) s++;
cDigits[c][imax][ confusion[c][imax]%maxCD ] = validSet[i];
confusion[c][imax]++;
if (i%y2==0) {
dp=0;
if (showCon==1) displayConfusion(confusion);
}
if (c==imax && dp<4){
int kk = 5; if (k<kk) kk=k;
dgs[dp*6] = validSet[i];
for (j=0;j<kk;j++) dgs[dp*6+j+1] = trainSet[idx[j]];
for (j=kk;j<5;j++) dgs[dp*6+j+1] = -1;
if (dp==3) displayDigits(dgs,24,5,1,0,0,2);
dp++;
}
if (i==0 || (i+1)%y==0){
sprintf(buffer,"i=%d, accuracy = %.2f",i+1,100.0*s/(i+1));
if (z==1) webwriteline(buffer);
else printf("%s\n",buffer);
}
if (working==0){
webwriteline("learning stopped early");
pthread_exit(NULL);
}
}
sprintf(buffer,"i=%d, k=%d, Accuracy = %.2f",validSetSize,k,100.0*s/validSetSize);
if (z==1) webwriteline(buffer);
else printf("%s\n",buffer);
webwriteline("Done");
working=0;
return NULL;
}
/**********************************************************************/
/* KNN */
/**********************************************************************/
void fakeHeap(float *dist,int *idx,int k){
// EMULATES A MAX HEAP BY PUTTING MAX ITEM FIRST
float max = 0.0;
int imax = 0;
for (int i=0;i<k;i++)
if (dist[i]>max){
max = dist[i];
imax = i;
}
float tempDist;
int tempIdx;
tempDist = dist[0];
tempIdx = idx[0];
dist[0] = dist[imax];
idx[0] = idx[imax];
dist[imax] = tempDist;
idx[imax] = tempIdx;
}
/**********************************************************************/
/* ADVANCED DISPLAY */
/**********************************************************************/
void fakeHeap3(float *dist,int *idx, int *idxA, int *idxB, int k){
// EMULATES A MIN HEAP BY PUTTING MIN ITEM FIRST
// THIS FUNCITON COULD BE COMBINED WITH fakeHeap above
float min = dist[0];
int imin = 0;
for (int i=1;i<k;i++)
if (dist[i]<min){
min = dist[i];
imin = i;
}
float tempDist;
int tempIdx;
tempDist = dist[0];
tempIdx = idx[0];
dist[0] = dist[imin];
idx[0] = idx[imin];
dist[imin] = tempDist;
idx[imin] = tempIdx;
//
tempIdx = idxA[0];
idxA[0] = idxA[imin];
idxA[imin] = tempIdx;
tempIdx = idxB[0];
idxB[0] = idxB[imin];
idxB[imin] = tempIdx;
}
/**********************************************************************/
/* ADVANCED DISPLAY */
/**********************************************************************/
void sortHeap3(float *dist, int *idx, int *idxA, int *idxB, int k){
// SORTS HEAP
float dist2[k];
int idx2[k];
int idxA2[k];
int idxB2[k];
int i,j;
float min;
int imin = 0;
for (j=0;j<k;j++){
min = -1e6;
for (i=0;i<k;i++){
if (dist[i]>min){
imin = i;
min = dist[i];
}
}
dist2[j] = dist[imin];
dist[imin]= -1e6;
idx2[j] = idx[imin];
idxA2[j] = idxA[imin];
idxB2[j] = idxB[imin];
}
for (i=0;i<k;i++){
dist[i] = dist2[i];
idx[i] = idx2[i];
idxA[i] = idxA2[i];
idxB[i] = idxB2[i];
}
}
/**********************************************************************/
/* KNN */
/**********************************************************************/
void sortHeap(float *dist, int *idx, int k){
// SORTS HEAP
float dist2[k];
int idx2[k];
int i,j;
float min;
int imin = 0;
for (j=0;j<k;j++){
min = 1e6;
for (i=0;i<k;i++){
if (dist[i]<min){
imin = i;
min = dist[i];
}
}
dist2[j] = dist[imin];
dist[imin]=1e6;
idx2[j] = idx[imin];
}
for (i=0;i<k;i++){
dist[i] = dist2[i];
idx[i] = idx2[i];
}
}
/**********************************************************************/
/* KNN */
/**********************************************************************/
float distance(float *digitA, float *digitB, int n, int x){
// RETURNS DISTANCE BETWEEN DIGITS USING L-X NORM
int i=0;
float dist = 0.0;
for (i=0;i<n;i++){
if (x==1) dist += fabs(digitA[i] - digitB[i]);
else if (x==2) dist += pow(digitA[i] - digitB[i],2);
}
return dist;
}
/**********************************************************************/
/* PREDICT */
/**********************************************************************/
void *predictKNN(void *arg){
// FUNCTION TO MAKE PREDICTIONS TO WRITE TO FILE
int k=pass[0], d=pass[1], y=pass[2], big=pass[3];
char buffer[80];
float dist[k], dd;
int c, i, max, imax, j, idx[k], votes[10];
int size = 196; if (big==1 || big==2) size = 784;
float (*imageTrain)[size];
if (big==1 || big==2) imageTrain = trainImages;
else imageTrain = trainImages2;
float (*imageTest)[size];
if (big==1 || big==2) imageTest = testImages;
else imageTest = testImages2;
if (big==2) size = trainColumns;
for (i=0;i<testSizeI;i++){
for (j=0;j<k;j++){
idx[j] = j;
dist[j] = distance( imageTest[i], imageTrain[j],size,d);
}
fakeHeap(dist,idx,k);
for (j=k;j<trainSizeI;j++){
dd = distance( imageTest[i], imageTrain[j],size,d);
if (dd<dist[0]){
dist[0] = dd;
idx[0] = j;
fakeHeap(dist,idx,k);
}
}
max = 0;
for (j=0;j<10;j++) votes[j]=0;
for (j=0;j<k;j++){
c = trainDigits[idx[j]];
votes[c]++;
if (votes[c]>max){
max = votes[c];
imax = c;
}
}
testDigits[i] = imax;
if (i==0 || (i+1)%y==0){
sprintf(buffer,"i=%d",i+1);
webwriteline(buffer);
}
if (working==0){
webwriteline("predict kNN stopped early");
pthread_exit(NULL);
}
}
writeFile();
working=0;
return NULL;
}
/**********************************************************************/
/* PREDICT */
/**********************************************************************/
void writePredictFile(int NN, int k, int d, int y, int big){
// PREDICTS TEST IMAGES AND WRITES RESULTS TO FILE
char buffer[80];
if (NN==1){
for (int i=0;i<testSizeI;i++) {
testDigits[i] = forwardProp(i,0,0,0);
if (i==0 || (i+1)%y==0){
sprintf(buffer,"i=%d",i+1);
webwriteline(buffer);
}
}
writeFile();
}
else if (working==1){
webwriteline("wait until learning ends");
return;
}
else{
sprintf(buffer,"predict kNN with k=%d, L%d norm, big=%d",k,d,big);
webwriteline(buffer);
pass[0]=k; pass[1]=d; pass[2]=y; pass[3]=big; working=1;
pthread_create(&workerThread,&stackSizeAttribute,predictKNN,NULL);
}
}
/**********************************************************************/
/* PREDICT */
/**********************************************************************/
void writeFile(){
// FUNCTION TO WRITE PREDICTIONS TO FILE
int in = layerSizes[10-numLayers], offset=1;
char buffer[80];
FILE *fp;
fp = fopen(spGet("fileName"),"w");
char colA[40], colB[40];
strcpy(colA,spGet("col1Name"));
strcpy(colB,spGet("col2Name"));
sprintf(buffer,"%s,%s\r\n",colA,colB);
offset = ipGet("row1Num");
fputs(buffer,fp);
for (int i=0;i<testSizeI;i++){
sprintf(buffer,"%d,%d\r\n",i+offset,testDigits[i]);
fputs(buffer,fp);
}
fclose(fp);
sprintf(buffer,"Wrote predictions to %s\n",spGet("fileName"));
webwriteline(buffer);
}
/**********************************************************************/
/* SPECIAL AND/OR DEBUGGING */
/**********************************************************************/
void dream(int x, int y, int it, float bs, float ft, int ds, int lay, int chan, int p){
// MAKE A NEURAL NETWORK DREAM
showCon = 0;
int i, in = 10-numLayers;
float (*tImage)[layerSizes[in]];
if (layerSizes[in]==784) tImage = trainImages;
else tImage = trainImages2;
for (i=0;i<layerSizes[in];i++) {
if (x>=0 && x<=trainSizeI+extraTrainSizeI) tImage[trainSizeE][i] = tImage[x][i];
//else if (x==-1) tImage[trainSizeE][i] = 0.1;
else tImage[trainSizeE][i] = 0.2 * (float)rand()/(float)RAND_MAX + 0.4;
}
dreamProp(y,it,bs,ft,ds,lay,chan,p);
webwriteline("Done");
}
/**********************************************************************/
/* SPECIAL AND/OR DEBUGGING */
/**********************************************************************/
void dreamProp(int y, int it, float bs, float ft,int ds, int lay, int chan, int p){
// MAKE A NEURAL NETWORK DREAM
// NEEDS TO BE UPDATED FOR CONV AND POOL LAYERS
char buffer[80];
int i = 0, j, k, n, r = 0, d=0, c;
int dc, a, a2, i2, j2, i3, j3, pmax, imax, jmax;
int in = 10-numLayers, row, col, ct=0;
int start = 8, idx = 0, idxC;
if (lay!=0) {
start = lay-1;
int mt = 1, wt = 1;
for (i=11-numLayers;i<=lay;i++){
wt = wt + (layerConv[i]-1)*mt;
mt = mt * layerStride[i];
}
idxC = (28 - wt)/2/mt;
idx = layerWidth[lay]*idxC + idxC;
}
float der = 1.0, min, max;
float (*tImage)[layerSizes[in]];
if (layerSizes[in]==784) tImage = trainImages;
else tImage = trainImages2;
for (n=0;n<it;n++){
c = forwardProp(trainSizeE+n,0,1,lay);
trainDigits[trainSizeE+n] = c;
// OUTPUT LAYER - CALCULATE ERRORS
if (lay==0)
for (i=0;i<layerSizes[9];i++){
errors[9][i] = an * (0 - layers[9][i]);
if (i==y) errors[9][i] = an * (1 - layers[9][i]);
}
else{
for (i=0;i<layerSizes[lay]*layerChan[lay];i++) errors[lay][i] = 0.0;
//if (y==1) for (i=0;i<layerSizes[lay];i++)
// errors[lay][layerSizes[lay]*chan + i] = 1.0;
//else if (y>=2) for (i=0;i<layerSizes[lay];i++)
// errors[lay][layerSizes[lay]*chan + i] = layers[lay][layerSizes[lay]*chan + i] - y/2.0;
//else
errors[lay][layerSizes[lay]*chan + idx] = 1.0;
}
int temp, temp2;
// HIDDEN LAYERS - CALCULATE ERRORS
for (k=start;k>9-numLayers;k--){
if (layerType[k+1]==0) // FEEDS INTO FULLY CONNECTED
for (i=0;i<layerSizes[k]*layerChan[k];i++){
errors[k][i] = 0.0;
if (activation==2) der = (layers[k][i]+1)*(1-layers[k][i]); //TanH derivative
if (activation==0 || activation==2 || layers[k][i]>0){ //this is ReLU derivative
temp = layerSizes[k]*layerChan[k]+1;
for (j=0;j<layerSizes[k+1];j++)
errors[k][i] += errors[k+1][j]*weights[k+1][j*temp+i]*der;
}
}
else if (layerType[k+1]==1){ // FEEDS INTO CONVOLUTION
for (i=0;i<layerSizes[k]*layerChan[k];i++) errors[k][i] = 0.0;
dc = 0; if (layerPad[k+1]==1) dc = layerConv[k+1]/2;
for (a=0;a<layerChan[k+1];a++)
for (i=0;i<layerWidth[k+1];i++)
for (j=0;j<layerWidth[k+1];j++){
temp = a*layerSizes[k+1] + i*layerWidth[k+1] + j;
temp2 = a*(layerConvStep[k+1]+1);
for (a2=0;a2<layerChan[k];a2++)
for (i2=0;i2<layerConv[k+1];i2++)
for (j2=0;j2<layerConv[k+1];j2++){
i3 = i + i2 - dc;
j3 = j + j2 - dc;
if (activation==2) der = (layers[k][a2*layerSizes[k] + i3*layerWidth[k] + j3]+1)*(1-layers[k][a2*layerSizes[k] + i3*layerWidth[k] + j3]); //TanH
if (activation==0 || activation==2 || layers[k][a2*layerSizes[k] + i3*layerWidth[k] + j3]>0) // this is ReLU derivative
if (i3>=0 && i3<layerWidth[k] && j3>=0 && j3<layerWidth[k]) // padding
errors[k][a2*layerSizes[k] + i3*layerWidth[k] + j3] +=
weights[k+1][temp2 + a2*layerConvStep2[k+1] + i2*layerConv[k+1] +j2]
* errors[k+1][temp];
}
}
}
else if (layerType[k+1]>=2){ // FEEDS INTO POOLING (2=max, 3=avg)
for (i=0;i<layerSizes[k]*layerChan[k];i++) errors[k][i] = 0.0;
for (a=0;a<layerChan[k];a++)
for (i=0;i<layerWidth[k+1];i++)
for (j=0;j<layerWidth[k+1];j++){
pmax = -1e6;
if (layerType[k+1]==3)
temp = errors[k+1][a*layerSizes[k+1] + i*layerWidth[k+1] + j] / layerConvStep2[k+1];
for (i2=0;i2<layerConv[k+1];i2++)
for (j2=0;j2<layerConv[k+1];j2++){
if (layerType[k+1]==3)
errors[k][a*layerSizes[k] + (i*layerStride[k+1]+i2)*layerWidth[k] + j*layerStride[k+1]+j2] = temp;
else if (layers[k][a*layerSizes[k] + (i*layerStride[k+1]+i2)*layerWidth[k] + j*layerStride[k+1]+j2]>pmax){
pmax = layers[k][a*layerSizes[k] + (i*layerStride[k+1]+i2)*layerWidth[k] + j*layerStride[k+1]+j2];
imax = i2;
jmax = j2;
}
}
if (layerType[k+1]==2)
errors[k][a*layerSizes[k] + (i*layerStride[k+1]+imax)*layerWidth[k] + j*layerStride[k+1]+jmax] =
errors[k+1][a*layerSizes[k+1] + i*layerWidth[k+1] + j];
}
}
}
//for (i=0;i<layerSizes[in];i++) printf("%f ",errors[in][i]);
//printf("\n");
float nei;
int ct;
for (i=0;i<layerSizes[in];i++)
tImage[trainSizeE+n+1][i] = tImage[trainSizeE+n][i];
for (i=0;i<layerSizes[in];i++){
nei = 0.0; ct = 0;
if (i-1>=0) {nei += tImage[trainSizeE+n+1][i-1]; ct++;}
if (i+1<28) {nei += tImage[trainSizeE+n+1][i+1]; ct++;}
if (i-28>=0) {nei += tImage[trainSizeE+n+1][i-28]; ct++;}
if (i+28<784) {nei += tImage[trainSizeE+n+1][i+28]; ct++;}
if (bs<=0) nei = 0.0;
else nei = (nei/ct - tImage[trainSizeE+n+1][i])/bs;
tImage[trainSizeE+n+1][i] += errors[in][i] + nei;
//tImage[trainSizeE+n+1][i] = ft * (tImage[trainSizeE+n+1][i] - 0.5) + 0.5;
if (ft!=1.0) tImage[trainSizeE+n+1][i] = ft * tImage[trainSizeE+n+1][i];
if (tImage[trainSizeE+n+1][i]<0.0) tImage[trainSizeE+n+1][i]=0.0;
if (tImage[trainSizeE+n+1][i]>1.0) tImage[trainSizeE+n+1][i]=1.0;
}
}
c = forwardProp(trainSizeE+it,0,1,lay);
trainDigits[trainSizeE+it] = c;
if (lay!=0){
if (y==0) printf("Dream has act = %f\n",layers[lay][layerSizes[lay]*chan + idx]);
else{
float sum = 0.0;
for (i=0;i<layerSizes[lay];i++)
sum += layers[lay][layerSizes[lay]*chan + i];
printf("Dream has act avg = %f\n",sum/layerSizes[lay]);
}
}
int adj = 0;
if (it%ds==0) adj=-1;
int dgs[it/ds+2];
for (i=0;i<it/ds+2;i++) dgs[i] = trainSizeE+i*ds;
dgs[it/ds+1] = trainSizeE+it;
if (lay==0) displayDigits(dgs, it/ds+2+adj, p,1,0,0,2);
else{
int ctt = it/ds+2+adj;
displayDigits(dgs, ctt, -1,1,0,0,2);
int idxA[ctt], idxB[ctt];
for (i=0;i<ctt;i++){
idxA[i] = idxC;
idxB[i] = idxC;
}
drawBorders(lay,chan,idxA,idxB,ctt);
websetcolors(256,red3,green3,blue3,p);
webimagedisplay(600,400,(int*)image,p);
showDig[p-3][0] = ctt;
}
}
/**********************************************************************/
/* SPECIAL AND/OR DEBUGGING */
/**********************************************************************/
int heatmap(int x, int t, int p, int wd){
// DISPLAY PIXEL IMPORTANCE FOR CLASSIFICATION
int i, j, k, ii, jj;
for (i=0;i<784;i++) {
if (t==1) trainImages[trainSizeE][i] = trainImages[x][i];
else trainImages[trainSizeE][i] = testImages[x][i];
trainImages[trainSizeE+1][i] = 0.0;
trainImages[trainSizeE+2][i] = 0.0;
}
for (i=0;i<196;i++){
if (t==1) trainImages2[trainSizeE+2][i] = trainImages2[x][i]/4.0;
else trainImages2[trainSizeE+2][i] = testImages2[x][i]/4.0;
}
int r2, r = forwardProp(trainSizeE,0,1,0);
float prb2, prb = prob;
for (i=0;i<28-wd+1;i++)
for (j=0;j<28-wd+1;j++){
//if (i==0) printf("i=0, j=%d\n",j);
for (k=0;k<784;k++)
trainImages[trainSizeE+1][k] = trainImages[trainSizeE][k];
for (ii=0;ii<wd;ii++)
for (jj=0;jj<wd;jj++)
trainImages[trainSizeE+1][28*(i+ii) + (j+jj)] = 0.0;
r2 = forwardProp(trainSizeE+1,0,1,0);
prb2 = prb - prob;
if (prb2<0.0) prb2=0.0;
for (ii=0;ii<wd;ii++)
for (jj=0;jj<wd;jj++)
trainImages[trainSizeE+2][28*(i+ii) + (j+jj)] += prb2;
}
float max = 0.0;
for (i=0;i<784;i++) if (trainImages[trainSizeE+2][i]>max)
max = trainImages[trainSizeE+2][i];
for (i=0;i<784;i++){
trainImages[trainSizeE+2][i] = trainImages[trainSizeE+2][i]/max;
if (trainImages[trainSizeE+2][i]<0.25) trainImages[trainSizeE+2][i] = 0.0;
else if (trainImages[trainSizeE+2][i]<0.5) trainImages[trainSizeE+2][i] = 0.251;
else if (trainImages[trainSizeE+2][i]<0.75) trainImages[trainSizeE+2][i] = 0.506;
else trainImages[trainSizeE+2][i] = 0.753;
trainImages[trainSizeE+2][i] += trainImages[trainSizeE][i]/4.05;
}
displayDigit(trainSizeE+2, 1, -1, 0, 0, 1, 0, 1);
for (i=0;i<256;i++){red3[i]=0.0; green3[i]=0.0; blue3[i]=0.0;}
for (i=0;i<64;i++){ // GRAY SCALE
red3[i] = i/63.0;
green3[i] = i/63.0;
blue3[i] = i/63.0;
}
red3[128]=0.5; green3[128]=0.5; blue3[128]=0.5;
for (i=0;i<64;i++) blue3[i+64] = i/63.0;
for (i=1;i<64;i++) green3[i+128] = i/63.0;
for (i=0;i<64;i++) red3[i+192] = i/63.0;
websetcolors(256,red3,green3,blue3,p);
webimagedisplay(600,400,(int*)image,p);
showDig[p-3][0] = 1;
prob = prb;
return r;
}
/**********************************************************************/
/* SPECIAL AND/OR DEBUGGING */
/**********************************************************************/
void boundingBoxes(){
// CALCULATES VARIANCE OF BOUNDING BOXES
webwriteline("Calculating bounding boxes");
int i,j,k,found;
int left[trainSizeI], right[trainSizeI];
int top[trainSizeI], bottom[trainSizeI];
for (k=0;k<trainSizeI;k++){
top[k] = 0; bottom[k] = 28; left[k] = 0; right[k] = 28;
for (i=0;i<28;i++){
found = 0;
for (j=0;j<28;j++)
if (trainImages[k][28*i+j] != 0) found=1;
if (found==1){
top[k] = i;
break;
}
}
for (i=27;i>=0;i--){
found = 0;
for (j=0;j<28;j++)
if (trainImages[k][28*i+j] != 0) found=1;
if (found==1){
bottom[k] = i;
break;
}
}
for (j=0;j<28;j++){
found = 0;
for (i=0;i<28;i++)
if (trainImages[k][28*i+j] != 0) found=1;
if (found==1){
left[k] = j;
break;
}
}
for (j=27;j>=0;j--){
found = 0;
for (i=0;i<28;i++)
if (trainImages[k][28*i+j] != 0) found=1;
if (found==1){
right[k] = j;
break;
}
}
}
int sum1 = 0, sum2 = 0;
int wd1[10]={0}, wd2[10]={0}, ct[10]={0};
float wd1avg[10], wd2avg[10], xavg, yavg;
for (k=0;k<trainSizeI;k++){
wd1[trainDigits[k]] += right[k] - left[k] + 1;
wd2[trainDigits[k]] += bottom[k] - top[k] + 1;
ct[trainDigits[k]] ++;
sum1 += right[k] + left[k];
sum2 += bottom[k] + top[k];
}
char buffer[80];
float wXavg = 0.0, wYavg = 0.0;
for (k=0;k<10;k++){
wd1avg[k] = (float)wd1[k]/ct[k];
wd2avg[k] = (float)wd2[k]/ct[k];
wXavg += (float)wd1[k];
wYavg += (float)wd2[k];
}
wXavg = wXavg/trainSizeI;
wYavg = wYavg/trainSizeI;
xavg = sum1/2.0/trainSizeI;
yavg = sum2/2.0/trainSizeI;
float varScaleX = 0.0, varScaleY = 0.0;
float varShiftX = 0.0, varShiftY = 0.0;
for (k=0;k<trainSizeI;k++){
varScaleX += square( (right[k] - left[k] + 1)/wd1avg[trainDigits[k]] - 1.0);
varScaleY += square( (bottom[k] - top[k] + 1)/wd2avg[trainDigits[k]] - 1.0);
varShiftX += square( (right[k]+left[k])/2.0 - xavg );
varShiftY += square( (bottom[k]+top[k])/2.0 - yavg );
}
varScaleX = sqrt (varScaleX / trainSizeI);
varScaleY = sqrt (varScaleY / trainSizeI);
varShiftX = sqrt (varShiftX / trainSizeI);
varShiftY = sqrt (varShiftY / trainSizeI);
sprintf(buffer,"Avg center=%.1f,%.1f has sdX=%.3f sdY=%.3f",xavg,yavg,varShiftX,varShiftY);
webwriteline(buffer);
sprintf(buffer,"Avg widthX=%.1f avg widthY=%.1f has sdScaleX=%.3f, sdScaleY=%.3f",wXavg,wYavg,varScaleX,varScaleY);
webwriteline(buffer);
}
float square(float x){
return x*x;
}
/**********************************************************************/
/* SPECIAL AND/OR DEBUGGING */
/**********************************************************************/
void writeFile2(){
// FUNCTION TO WRITE DEBUG WEIGHTS
char buffer[80];
FILE *fp;
fp = fopen(weightsFile1,"w");
sprintf(buffer,"var weightsHidden = [%.6f",weights[8][0]);
fputs(buffer,fp);
for (int i=1;i<layerSizes[8]*(layerSizes[7]+1);i++){
sprintf(buffer,", %.6f",weights[8][i]);
fputs(buffer,fp);
}
fputs("];",fp);
fclose(fp);
sprintf(buffer,"Wrote hidden weights for %d-%d to %s\n",layerSizes[7],layerSizes[8],weightsFile1);
webwriteline(buffer);
fp = fopen(weightsFile2,"w");
sprintf(buffer,"var weightsOutput = [%.6f",weights[9][0]);
fputs(buffer,fp);
for (int i=1;i<layerSizes[9]*(layerSizes[8]+1);i++){
sprintf(buffer,", %.6f",weights[9][i]);
fputs(buffer,fp);
}
fputs("];",fp);
fclose(fp);
sprintf(buffer,"Wrote output weights for %d-%d to %s\n",layerSizes[8],layerSizes[9],weightsFile2);
webwriteline(buffer);
}
/**********************************************************************/
/* SPECIAL AND/OR DEBUGGING */
/**********************************************************************/
void initData(int z){
// DEBUG FEATURE MAKES 4X4 IMAGE
trainSizeI = 1;
trainSetSize = 1;
trainSet[0] = 0;
for (int i=0;i<16;i++) trainImages[0][i]=1.0;
trainImages[0][5] = 0.0;
trainImages[0][6] = 0.0;
trainImages[0][9] = 0.0;
trainImages[0][10] = 0.0;
trainColumns = 16;
trainDigits[0] = z;
}
/**********************************************************************/
/* SPECIAL AND/OR DEBUGGING */
/**********************************************************************/
void displayWeights(){
// DEBUG FEATURE DISPLAYS WEIGHTS, ACTIVATIONS, ERRORS, DROPOUT
int i,j,ws;
char name[10];
printf("Weights:\n");
for (i=11-numLayers;i<10;i++){
if (layerType[i]==0){ // FULLY CONNECTED
ws = layerSizes[i] * (layerSizes[i-1]*layerChan[i-1]+1);
strcpy(name,"FC");
}
else if (layerType[i]==1){ // CONVOLUTION
ws = (layerConvStep[i]+1) * layerChan[i];
strcpy(name,"conv");
}
else if (layerType[i]>=2){ // POOLING (2=max, 3=avg)
ws = 1;
strcpy(name,"pool");
}
printf("Layer %d (%s):\n",i,name);
for (j=0;j<ws;j++){
printf(", %.3f",weights[i][j]);
}
printf("\n");
}
printf("Activations:\n");
for (i=10-numLayers;i<10;i++){
printf("LAYER %d: ",i);
for (j=0;j<layerSizes[i]*layerChan[i]+1;j++){
printf(", %.3f",layers[i][j]);
}
printf("\n");
}
printf("\n");
printf("Dropout:\n");
for (i=11-numLayers;i<9;i++){
printf("LAYER %d: ",i);
for (j=0;j<layerSizes[i]*layerChan[i];j++){
printf(", %d",dropOut[i][j]);
}
printf("\n");
}
printf("\n");
printf("Errors:\n");
for (i=11-numLayers;i<10;i++){
printf("LAYER %d: ",i);
for (j=0;j<layerSizes[i]*layerChan[i];j++){
printf(", %.3e",errors[i][j]);
}
printf("\n");
}
printf("\n");
}
// THE FOLLOWING ROUTINES ARE FROM WEBGUI'S FILE EXAMPLE.C
/***************************************************************************/
/* WEBGUI A web browser based graphical user interface */
/* Version: 1.0 - June 25 2017 */
/***************************************************************************/
/* Author: Christopher Deotte */
/* Advisor: Randolph E. Bank */
/* Funding: NSF DMS-1345013 */
/* Documentation: http://ccom.ucsd.edu/~cdeotte/webgui */
/***************************************************************************/
/**********************************************************************/
/* WEBGUI A web browser based graphical user interface */
/* */
/* Author: Christopher Deotte */
/* */
/* Version: 1.0 - June 25, 2017 */
/**********************************************************************/
void initParameterMap(char* str, int n){
/* reads array of strings and initializes ip, rp, sp */
/* and creates a map for accessing ip, rp, and sp */
int i, index=0;
for (i=0; i<n; i++) if (str[80*i]=='n') ct++;
map_keys = (char**)malloc(ct * sizeof(char*));
map_indices = (int*)malloc(ct * sizeof(int));
map_array = (char*)malloc(ct * sizeof(char));
rp_default = (double*)malloc(ct * sizeof(double));
ip_default = (int*)malloc(ct * sizeof(int));
sp_default = (char*)malloc(ct * sizeof(char*) * 80);
rp = (double*)malloc(ct * sizeof(double));
ip = (int*)malloc(ct * sizeof(int));
sp = (char*)malloc(ct * sizeof(char*) * 80);
for (i=0; i<ct; i++) map_keys[i] = (char*)malloc(20 * sizeof(char));
for (i=0; i<n; i++)
if (str[80*i]=='n'){
strcpy(map_keys[index],extractVal(str+80*i,'n'));
map_indices[index] = atoi(extractVal(str+80*i,'i'))-1;
map_array[index] = *extractVal(str+80*i,'t');
if (map_array[index]=='r'){
rp_default[map_indices[index]] = atof(extractVal(str+80*i,'d'));
rp[map_indices[index]] = rp_default[map_indices[index]];
}
else if (map_array[index]=='i'){
ip_default[map_indices[index]] = atoi(extractVal(str+80*i,'d'));
ip[map_indices[index]] = ip_default[map_indices[index]];
}
else if (map_array[index]=='s' || map_array[index]=='f' || map_array[index]=='l'){
strcpy(sp_default+80*map_indices[index],extractVal(str+80*i,'d'));
strcpy(sp+80*map_indices[index],sp_default+80*map_indices[index]);
}
index++;
}
}
/**********************************************************************/
/* WEBGUI A web browser based graphical user interface */
/* */
/* Author: Christopher Deotte */
/* */
/* Version: 1.0 - June 25, 2017 */
/**********************************************************************/
char* extractVal(char* str, char key){
/* returns the value associated with key in str */
buffer[0]=0;
str[79]=0;
int index1 = 0, index2;
while (index1<strlen(str)){
if (str[index1]=='='){
if (str[index1-1]==key){
index2 = index1;
while (index2<strlen(str) && str[index2]!=',') index2++;
strncpy(buffer,str+index1+1,index2-index1-1);
buffer[index2-index1-1]=0;
break;
}
}
index1++;
}
return buffer;
}
/**********************************************************************/
/* WEBGUI A web browser based graphical user interface */
/* */
/* Author: Christopher Deotte */
/* */
/* Version: 1.0 - June 25, 2017 */
/**********************************************************************/
char processCommand(char* str){
/* returns command char and updates parameters */
int index1 = 1, index2 = 2;
while (str[index2]!=' '){
if (str[index2]==','){
updateParameter(str,index1,index2);
index1 = index2;
}
index2++;
}
if (index2>2) {
updateParameter(str,index1,index2);
}
return str[0];
}
/**********************************************************************/
/* WEBGUI A web browser based graphical user interface */
/* */
/* Author: Christopher Deotte */
/* */
/* Version: 1.0 - June 25, 2017 */
/**********************************************************************/
void updateParameter(char* str, int index1, int index2){
/* parses str between index1 and index2 and updates parameter */
int index3 = index1+1;
while (str[index3]!='=') index3++;
str[index2]=0; str[index3]=0;
char ch = arrayGet(str+index1+1);
if (ch=='r') rpSet(str+index1+1,atof(str+index3+1));
else if (ch=='i') ipSet(str+index1+1,atoi(str+index3+1));
else if (ch=='s' || ch=='f' || ch=='l') spSet(str+index1+1,str+index3+1);
str[index2]=','; str[index3]='=';
}
/**********************************************************************/
/* WEBGUI A web browser based graphical user interface */
/* */
/* Author: Christopher Deotte */
/* */
/* Version: 1.0 - June 25, 2017 */
/**********************************************************************/
char arrayGet(char* key){
/* returns which array (ip, rp, sp) key belongs to */
int i;
char value = ' ';
for (i=0; i<ct; i++) if (strcmp(map_keys[i],key)==0)
value = map_array[i];
return value;
}
/**********************************************************************/
/* WEBGUI A web browser based graphical user interface */
/* */
/* Author: Christopher Deotte */
/* */
/* Version: 1.0 - June 25, 2017 */
/**********************************************************************/
int ipGet(char* key){
int i, value = 0;
for (i=0; i<ct; i++) if (strcmp(map_keys[i],key)==0)
value = ip[map_indices[i]];
return value;
}
/**********************************************************************/
/* WEBGUI A web browser based graphical user interface */
/* */
/* Author: Christopher Deotte */
/* */
/* Version: 1.0 - June 25, 2017 */
/**********************************************************************/
void ipSet(char* key, int value){
int i;
for (i=0; i<ct; i++) if (strcmp(map_keys[i],key)==0)
ip[map_indices[i]] = value;
return;
}
/**********************************************************************/
/* WEBGUI A web browser based graphical user interface */
/* */
/* Author: Christopher Deotte */
/* */
/* Version: 1.0 - June 25, 2017 */
/**********************************************************************/
double rpGet(char* key){
int i;
double value = 0;
for (i=0; i<ct; i++) if (strcmp(map_keys[i],key)==0)
value = rp[map_indices[i]];
return value;
}
/**********************************************************************/
/* WEBGUI A web browser based graphical user interface */
/* */
/* Author: Christopher Deotte */
/* */
/* Version: 1.0 - June 25, 2017 */
/**********************************************************************/
void rpSet(char* key, double value){
int i;
for (i=0; i<ct; i++) if (strcmp(map_keys[i],key)==0)
rp[map_indices[i]] = value;
return;
}
/**********************************************************************/
/* WEBGUI A web browser based graphical user interface */
/* */
/* Author: Christopher Deotte */
/* */
/* Version: 1.0 - June 25, 2017 */
/**********************************************************************/
char* spGet(char* key){
int i;
buffer[0] = 0;
for (i=0; i<ct; i++) if (strcmp(map_keys[i],key)==0)
strcpy(buffer,sp + 80 * map_indices[i]);
return buffer;
}
/**********************************************************************/
/* WEBGUI A web browser based graphical user interface */
/* */
/* Author: Christopher Deotte */
/* */
/* Version: 1.0 - June 25, 2017 */
/**********************************************************************/
void spSet(char* key, char* value){
int i;
for (i=0; i<ct; i++) if (strcmp(map_keys[i],key)==0)
strcpy(sp + 80 * map_indices[i],value);
return;
}
|
the_stack_data/92951.c | #include <stdio.h>
#include <stdlib.h>
int array[10] = {1, 3, 5, 6, 7, 9, 11, 20, 30};
int search_binary(int key, int low, int high)
{
int middle;
if(low <= high){
middle = (low + high) / 2;
if(key == array[middle])
return middle;
else if(key < array[middle])
return search_binary(key, low, middle-1);
else
return search_binary(key, middle+1, high);
}
return -1;
}
int main()
{
int n;
for(int i = 0; i < 2; i++){
scanf("%d", &n);
if(search_binary(n, 0, 8) != -1)
printf("Success!\n");
else
printf("Failed\n");
}
} |
the_stack_data/232809.c | #include <stdio.h>
int main() {
printf("Hello World.");
return 0;
} |
the_stack_data/75138112.c | // main.c
// CLI-Diary - A command line based personal diary.
// Created by Tom Reid 22/7/2021
#include <stdio.h>
#include <ncurses.h>
int main(void)
{
} |
the_stack_data/26699187.c | /*-*/
/********************************************************
* Program: ADD5 -- Adds up 5 numbers. *
* *
* Usage: *
* Run it, type in 5 numbers and get a total. *
* *
* Note: This is the same as program 8.1 except it *
* uses a for loop instead of a while. *
********************************************************/
/*+*/
#include <stdio.h>
int total; /* total of all the numbers */
int current; /* current value from the user */
int counter; /* for loop counter */
char line[80]; /* Input from keyboard */
int main() {
total = 0;
for (counter = 0; counter < 5; ++counter) {
printf("Number? ");
fgets(line, sizeof(line), stdin);
sscanf(line, "%d", ¤t);
total += current;
}
printf("The grand total is %d\n", total);
return (0);
}
|
the_stack_data/159514781.c | /* Check that memory leaks created by an assignment are detected */
#include <malloc.h>
int main()
{
int *p = (int *) malloc(10*sizeof(int)), i;
p = &i;
return 0;
}
|
the_stack_data/140766528.c | #include <stdio.h>
int main() {
printf("\nHello World!\n");
int i = 10;
printf("I is: %d", i);
printf("\n");
return 0;
}
|
the_stack_data/633618.c | /*
* Generated by util/mkerr.pl DO NOT EDIT
* Copyright 1995-2018 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <openssl/err.h>
#include <openssl/cmserr.h>
#ifndef OPENSSL_NO_ERR
static const ERR_STRING_DATA CMS_str_functs[] = {
{ERR_PACK(ERR_LIB_CMS, CMS_F_CHECK_CONTENT, 0), "check_content"},
{ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_ADD0_CERT, 0), "CMS_add0_cert"},
{ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_ADD0_RECIPIENT_KEY, 0),
"CMS_add0_recipient_key"},
{ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_ADD0_RECIPIENT_PASSWORD, 0),
"CMS_add0_recipient_password"},
{ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_ADD1_RECEIPTREQUEST, 0),
"CMS_add1_ReceiptRequest"},
{ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_ADD1_RECIPIENT_CERT, 0),
"CMS_add1_recipient_cert"},
{ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_ADD1_SIGNER, 0), "CMS_add1_signer"},
{ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_ADD1_SIGNINGTIME, 0),
"cms_add1_signingTime"},
{ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_COMPRESS, 0), "CMS_compress"},
{ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_COMPRESSEDDATA_CREATE, 0),
"cms_CompressedData_create"},
{ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_COMPRESSEDDATA_INIT_BIO, 0),
"cms_CompressedData_init_bio"},
{ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_COPY_CONTENT, 0), "cms_copy_content"},
{ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_COPY_MESSAGEDIGEST, 0),
"cms_copy_messageDigest"},
{ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_DATA, 0), "CMS_data"},
{ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_DATAFINAL, 0), "CMS_dataFinal"},
{ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_DATAINIT, 0), "CMS_dataInit"},
{ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_DECRYPT, 0), "CMS_decrypt"},
{ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_DECRYPT_SET1_KEY, 0),
"CMS_decrypt_set1_key"},
{ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_DECRYPT_SET1_PASSWORD, 0),
"CMS_decrypt_set1_password"},
{ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_DECRYPT_SET1_PKEY, 0),
"CMS_decrypt_set1_pkey"},
{ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_DIGESTALGORITHM_FIND_CTX, 0),
"cms_DigestAlgorithm_find_ctx"},
{ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_DIGESTALGORITHM_INIT_BIO, 0),
"cms_DigestAlgorithm_init_bio"},
{ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_DIGESTEDDATA_DO_FINAL, 0),
"cms_DigestedData_do_final"},
{ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_DIGEST_VERIFY, 0), "CMS_digest_verify"},
{ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_ENCODE_RECEIPT, 0), "cms_encode_Receipt"},
{ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_ENCRYPT, 0), "CMS_encrypt"},
{ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_ENCRYPTEDCONTENT_INIT, 0),
"cms_EncryptedContent_init"},
{ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_ENCRYPTEDCONTENT_INIT_BIO, 0),
"cms_EncryptedContent_init_bio"},
{ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_ENCRYPTEDDATA_DECRYPT, 0),
"CMS_EncryptedData_decrypt"},
{ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_ENCRYPTEDDATA_ENCRYPT, 0),
"CMS_EncryptedData_encrypt"},
{ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_ENCRYPTEDDATA_SET1_KEY, 0),
"CMS_EncryptedData_set1_key"},
{ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_ENVELOPEDDATA_CREATE, 0),
"CMS_EnvelopedData_create"},
{ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_ENVELOPEDDATA_INIT_BIO, 0),
"cms_EnvelopedData_init_bio"},
{ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_ENVELOPED_DATA_INIT, 0),
"cms_enveloped_data_init"},
{ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_ENV_ASN1_CTRL, 0), "cms_env_asn1_ctrl"},
{ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_FINAL, 0), "CMS_final"},
{ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_GET0_CERTIFICATE_CHOICES, 0),
"cms_get0_certificate_choices"},
{ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_GET0_CONTENT, 0), "CMS_get0_content"},
{ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_GET0_ECONTENT_TYPE, 0),
"cms_get0_econtent_type"},
{ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_GET0_ENVELOPED, 0), "cms_get0_enveloped"},
{ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_GET0_REVOCATION_CHOICES, 0),
"cms_get0_revocation_choices"},
{ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_GET0_SIGNED, 0), "cms_get0_signed"},
{ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_MSGSIGDIGEST_ADD1, 0),
"cms_msgSigDigest_add1"},
{ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_RECEIPTREQUEST_CREATE0, 0),
"CMS_ReceiptRequest_create0"},
{ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_RECEIPT_VERIFY, 0), "cms_Receipt_verify"},
{ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_RECIPIENTINFO_DECRYPT, 0),
"CMS_RecipientInfo_decrypt"},
{ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_RECIPIENTINFO_ENCRYPT, 0),
"CMS_RecipientInfo_encrypt"},
{ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_RECIPIENTINFO_KARI_ENCRYPT, 0),
"cms_RecipientInfo_kari_encrypt"},
{ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_RECIPIENTINFO_KARI_GET0_ALG, 0),
"CMS_RecipientInfo_kari_get0_alg"},
{ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_RECIPIENTINFO_KARI_GET0_ORIG_ID, 0),
"CMS_RecipientInfo_kari_get0_orig_id"},
{ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_RECIPIENTINFO_KARI_GET0_REKS, 0),
"CMS_RecipientInfo_kari_get0_reks"},
{ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_RECIPIENTINFO_KARI_ORIG_ID_CMP, 0),
"CMS_RecipientInfo_kari_orig_id_cmp"},
{ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_RECIPIENTINFO_KEKRI_DECRYPT, 0),
"cms_RecipientInfo_kekri_decrypt"},
{ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_RECIPIENTINFO_KEKRI_ENCRYPT, 0),
"cms_RecipientInfo_kekri_encrypt"},
{ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_RECIPIENTINFO_KEKRI_GET0_ID, 0),
"CMS_RecipientInfo_kekri_get0_id"},
{ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_RECIPIENTINFO_KEKRI_ID_CMP, 0),
"CMS_RecipientInfo_kekri_id_cmp"},
{ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_RECIPIENTINFO_KTRI_CERT_CMP, 0),
"CMS_RecipientInfo_ktri_cert_cmp"},
{ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_RECIPIENTINFO_KTRI_DECRYPT, 0),
"cms_RecipientInfo_ktri_decrypt"},
{ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_RECIPIENTINFO_KTRI_ENCRYPT, 0),
"cms_RecipientInfo_ktri_encrypt"},
{ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_RECIPIENTINFO_KTRI_GET0_ALGS, 0),
"CMS_RecipientInfo_ktri_get0_algs"},
{ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_RECIPIENTINFO_KTRI_GET0_SIGNER_ID, 0),
"CMS_RecipientInfo_ktri_get0_signer_id"},
{ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_RECIPIENTINFO_PWRI_CRYPT, 0),
"cms_RecipientInfo_pwri_crypt"},
{ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_RECIPIENTINFO_SET0_KEY, 0),
"CMS_RecipientInfo_set0_key"},
{ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_RECIPIENTINFO_SET0_PASSWORD, 0),
"CMS_RecipientInfo_set0_password"},
{ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_RECIPIENTINFO_SET0_PKEY, 0),
"CMS_RecipientInfo_set0_pkey"},
{ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_SD_ASN1_CTRL, 0), "cms_sd_asn1_ctrl"},
{ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_SET1_IAS, 0), "cms_set1_ias"},
{ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_SET1_KEYID, 0), "cms_set1_keyid"},
{ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_SET1_SIGNERIDENTIFIER, 0),
"cms_set1_SignerIdentifier"},
{ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_SET_DETACHED, 0), "CMS_set_detached"},
{ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_SIGN, 0), "CMS_sign"},
{ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_SIGNED_DATA_INIT, 0),
"cms_signed_data_init"},
{ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_SIGNERINFO_CONTENT_SIGN, 0),
"cms_SignerInfo_content_sign"},
{ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_SIGNERINFO_SIGN, 0),
"CMS_SignerInfo_sign"},
{ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_SIGNERINFO_VERIFY, 0),
"CMS_SignerInfo_verify"},
{ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_SIGNERINFO_VERIFY_CERT, 0),
"cms_signerinfo_verify_cert"},
{ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_SIGNERINFO_VERIFY_CONTENT, 0),
"CMS_SignerInfo_verify_content"},
{ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_SIGN_RECEIPT, 0), "CMS_sign_receipt"},
{ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_STREAM, 0), "CMS_stream"},
{ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_UNCOMPRESS, 0), "CMS_uncompress"},
{ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_VERIFY, 0), "CMS_verify"},
{ERR_PACK(ERR_LIB_CMS, CMS_F_KEK_UNWRAP_KEY, 0), "kek_unwrap_key"},
{0, NULL}
};
static const ERR_STRING_DATA CMS_str_reasons[] = {
{ERR_PACK(ERR_LIB_CMS, 0, CMS_R_ADD_SIGNER_ERROR), "add signer error"},
{ERR_PACK(ERR_LIB_CMS, 0, CMS_R_CERTIFICATE_ALREADY_PRESENT),
"certificate already present"},
{ERR_PACK(ERR_LIB_CMS, 0, CMS_R_CERTIFICATE_HAS_NO_KEYID),
"certificate has no keyid"},
{ERR_PACK(ERR_LIB_CMS, 0, CMS_R_CERTIFICATE_VERIFY_ERROR),
"certificate verify error"},
{ERR_PACK(ERR_LIB_CMS, 0, CMS_R_CIPHER_INITIALISATION_ERROR),
"cipher initialisation error"},
{ERR_PACK(ERR_LIB_CMS, 0, CMS_R_CIPHER_PARAMETER_INITIALISATION_ERROR),
"cipher parameter initialisation error"},
{ERR_PACK(ERR_LIB_CMS, 0, CMS_R_CMS_DATAFINAL_ERROR),
"cms datafinal error"},
{ERR_PACK(ERR_LIB_CMS, 0, CMS_R_CMS_LIB), "cms lib"},
{ERR_PACK(ERR_LIB_CMS, 0, CMS_R_CONTENTIDENTIFIER_MISMATCH),
"contentidentifier mismatch"},
{ERR_PACK(ERR_LIB_CMS, 0, CMS_R_CONTENT_NOT_FOUND), "content not found"},
{ERR_PACK(ERR_LIB_CMS, 0, CMS_R_CONTENT_TYPE_MISMATCH),
"content type mismatch"},
{ERR_PACK(ERR_LIB_CMS, 0, CMS_R_CONTENT_TYPE_NOT_COMPRESSED_DATA),
"content type not compressed data"},
{ERR_PACK(ERR_LIB_CMS, 0, CMS_R_CONTENT_TYPE_NOT_ENVELOPED_DATA),
"content type not enveloped data"},
{ERR_PACK(ERR_LIB_CMS, 0, CMS_R_CONTENT_TYPE_NOT_SIGNED_DATA),
"content type not signed data"},
{ERR_PACK(ERR_LIB_CMS, 0, CMS_R_CONTENT_VERIFY_ERROR),
"content verify error"},
{ERR_PACK(ERR_LIB_CMS, 0, CMS_R_CTRL_ERROR), "ctrl error"},
{ERR_PACK(ERR_LIB_CMS, 0, CMS_R_CTRL_FAILURE), "ctrl failure"},
{ERR_PACK(ERR_LIB_CMS, 0, CMS_R_DECRYPT_ERROR), "decrypt error"},
{ERR_PACK(ERR_LIB_CMS, 0, CMS_R_ERROR_GETTING_PUBLIC_KEY),
"error getting public key"},
{ERR_PACK(ERR_LIB_CMS, 0, CMS_R_ERROR_READING_MESSAGEDIGEST_ATTRIBUTE),
"error reading messagedigest attribute"},
{ERR_PACK(ERR_LIB_CMS, 0, CMS_R_ERROR_SETTING_KEY), "error setting key"},
{ERR_PACK(ERR_LIB_CMS, 0, CMS_R_ERROR_SETTING_RECIPIENTINFO),
"error setting recipientinfo"},
{ERR_PACK(ERR_LIB_CMS, 0, CMS_R_INVALID_ENCRYPTED_KEY_LENGTH),
"invalid encrypted key length"},
{ERR_PACK(ERR_LIB_CMS, 0, CMS_R_INVALID_KEY_ENCRYPTION_PARAMETER),
"invalid key encryption parameter"},
{ERR_PACK(ERR_LIB_CMS, 0, CMS_R_INVALID_KEY_LENGTH), "invalid key length"},
{ERR_PACK(ERR_LIB_CMS, 0, CMS_R_MD_BIO_INIT_ERROR), "md bio init error"},
{ERR_PACK(ERR_LIB_CMS, 0, CMS_R_MESSAGEDIGEST_ATTRIBUTE_WRONG_LENGTH),
"messagedigest attribute wrong length"},
{ERR_PACK(ERR_LIB_CMS, 0, CMS_R_MESSAGEDIGEST_WRONG_LENGTH),
"messagedigest wrong length"},
{ERR_PACK(ERR_LIB_CMS, 0, CMS_R_MSGSIGDIGEST_ERROR), "msgsigdigest error"},
{ERR_PACK(ERR_LIB_CMS, 0, CMS_R_MSGSIGDIGEST_VERIFICATION_FAILURE),
"msgsigdigest verification failure"},
{ERR_PACK(ERR_LIB_CMS, 0, CMS_R_MSGSIGDIGEST_WRONG_LENGTH),
"msgsigdigest wrong length"},
{ERR_PACK(ERR_LIB_CMS, 0, CMS_R_NEED_ONE_SIGNER), "need one signer"},
{ERR_PACK(ERR_LIB_CMS, 0, CMS_R_NOT_A_SIGNED_RECEIPT),
"not a signed receipt"},
{ERR_PACK(ERR_LIB_CMS, 0, CMS_R_NOT_ENCRYPTED_DATA), "not encrypted data"},
{ERR_PACK(ERR_LIB_CMS, 0, CMS_R_NOT_KEK), "not kek"},
{ERR_PACK(ERR_LIB_CMS, 0, CMS_R_NOT_KEY_AGREEMENT), "not key agreement"},
{ERR_PACK(ERR_LIB_CMS, 0, CMS_R_NOT_KEY_TRANSPORT), "not key transport"},
{ERR_PACK(ERR_LIB_CMS, 0, CMS_R_NOT_PWRI), "not pwri"},
{ERR_PACK(ERR_LIB_CMS, 0, CMS_R_NOT_SUPPORTED_FOR_THIS_KEY_TYPE),
"not supported for this key type"},
{ERR_PACK(ERR_LIB_CMS, 0, CMS_R_NO_CIPHER), "no cipher"},
{ERR_PACK(ERR_LIB_CMS, 0, CMS_R_NO_CONTENT), "no content"},
{ERR_PACK(ERR_LIB_CMS, 0, CMS_R_NO_CONTENT_TYPE), "no content type"},
{ERR_PACK(ERR_LIB_CMS, 0, CMS_R_NO_DEFAULT_DIGEST), "no default digest"},
{ERR_PACK(ERR_LIB_CMS, 0, CMS_R_NO_DIGEST_SET), "no digest set"},
{ERR_PACK(ERR_LIB_CMS, 0, CMS_R_NO_KEY), "no key"},
{ERR_PACK(ERR_LIB_CMS, 0, CMS_R_NO_KEY_OR_CERT), "no key or cert"},
{ERR_PACK(ERR_LIB_CMS, 0, CMS_R_NO_MATCHING_DIGEST), "no matching digest"},
{ERR_PACK(ERR_LIB_CMS, 0, CMS_R_NO_MATCHING_RECIPIENT),
"no matching recipient"},
{ERR_PACK(ERR_LIB_CMS, 0, CMS_R_NO_MATCHING_SIGNATURE),
"no matching signature"},
{ERR_PACK(ERR_LIB_CMS, 0, CMS_R_NO_MSGSIGDIGEST), "no msgsigdigest"},
{ERR_PACK(ERR_LIB_CMS, 0, CMS_R_NO_PASSWORD), "no password"},
{ERR_PACK(ERR_LIB_CMS, 0, CMS_R_NO_PRIVATE_KEY), "no private key"},
{ERR_PACK(ERR_LIB_CMS, 0, CMS_R_NO_PUBLIC_KEY), "no public key"},
{ERR_PACK(ERR_LIB_CMS, 0, CMS_R_NO_RECEIPT_REQUEST), "no receipt request"},
{ERR_PACK(ERR_LIB_CMS, 0, CMS_R_NO_SIGNERS), "no signers"},
{ERR_PACK(ERR_LIB_CMS, 0, CMS_R_PRIVATE_KEY_DOES_NOT_MATCH_CERTIFICATE),
"private key does not match certificate"},
{ERR_PACK(ERR_LIB_CMS, 0, CMS_R_RECEIPT_DECODE_ERROR),
"receipt decode error"},
{ERR_PACK(ERR_LIB_CMS, 0, CMS_R_RECIPIENT_ERROR), "recipient error"},
{ERR_PACK(ERR_LIB_CMS, 0, CMS_R_SIGNER_CERTIFICATE_NOT_FOUND),
"signer certificate not found"},
{ERR_PACK(ERR_LIB_CMS, 0, CMS_R_SIGNFINAL_ERROR), "signfinal error"},
{ERR_PACK(ERR_LIB_CMS, 0, CMS_R_SMIME_TEXT_ERROR), "smime text error"},
{ERR_PACK(ERR_LIB_CMS, 0, CMS_R_STORE_INIT_ERROR), "store init error"},
{ERR_PACK(ERR_LIB_CMS, 0, CMS_R_TYPE_NOT_COMPRESSED_DATA),
"type not compressed data"},
{ERR_PACK(ERR_LIB_CMS, 0, CMS_R_TYPE_NOT_DATA), "type not data"},
{ERR_PACK(ERR_LIB_CMS, 0, CMS_R_TYPE_NOT_DIGESTED_DATA),
"type not digested data"},
{ERR_PACK(ERR_LIB_CMS, 0, CMS_R_TYPE_NOT_ENCRYPTED_DATA),
"type not encrypted data"},
{ERR_PACK(ERR_LIB_CMS, 0, CMS_R_TYPE_NOT_ENVELOPED_DATA),
"type not enveloped data"},
{ERR_PACK(ERR_LIB_CMS, 0, CMS_R_UNABLE_TO_FINALIZE_CONTEXT),
"unable to finalize context"},
{ERR_PACK(ERR_LIB_CMS, 0, CMS_R_UNKNOWN_CIPHER), "unknown cipher"},
{ERR_PACK(ERR_LIB_CMS, 0, CMS_R_UNKNOWN_DIGEST_ALGORITHM),
"unknown digest algorithm"},
{ERR_PACK(ERR_LIB_CMS, 0, CMS_R_UNKNOWN_ID), "unknown id"},
{ERR_PACK(ERR_LIB_CMS, 0, CMS_R_UNSUPPORTED_COMPRESSION_ALGORITHM),
"unsupported compression algorithm"},
{ERR_PACK(ERR_LIB_CMS, 0, CMS_R_UNSUPPORTED_CONTENT_TYPE),
"unsupported content type"},
{ERR_PACK(ERR_LIB_CMS, 0, CMS_R_UNSUPPORTED_KEK_ALGORITHM),
"unsupported kek algorithm"},
{ERR_PACK(ERR_LIB_CMS, 0, CMS_R_UNSUPPORTED_KEY_ENCRYPTION_ALGORITHM),
"unsupported key encryption algorithm"},
{ERR_PACK(ERR_LIB_CMS, 0, CMS_R_UNSUPPORTED_RECIPIENTINFO_TYPE),
"unsupported recipientinfo type"},
{ERR_PACK(ERR_LIB_CMS, 0, CMS_R_UNSUPPORTED_RECIPIENT_TYPE),
"unsupported recipient type"},
{ERR_PACK(ERR_LIB_CMS, 0, CMS_R_UNSUPPORTED_TYPE), "unsupported type"},
{ERR_PACK(ERR_LIB_CMS, 0, CMS_R_UNWRAP_ERROR), "unwrap error"},
{ERR_PACK(ERR_LIB_CMS, 0, CMS_R_UNWRAP_FAILURE), "unwrap failure"},
{ERR_PACK(ERR_LIB_CMS, 0, CMS_R_VERIFICATION_FAILURE),
"verification failure"},
{ERR_PACK(ERR_LIB_CMS, 0, CMS_R_WRAP_ERROR), "wrap error"},
{0, NULL}
};
#endif
int ERR_load_CMS_strings(void)
{
#ifndef OPENSSL_NO_ERR
if (ERR_func_error_string(CMS_str_functs[0].error) == NULL) {
ERR_load_strings_const(CMS_str_functs);
ERR_load_strings_const(CMS_str_reasons);
}
#endif
return 1;
}
|
the_stack_data/159515409.c | #include <assert.h>
#include <stdio.h>
#include <stdlib.h>
struct ExtendedGcd {
int a, b, g;
};
void swap(int *x, int *y) {
int temp;
temp = *x;
*x = *y;
*y = temp;
}
int iabs(const int x) {
return (x < 0) ? -x : x;
}
int eu_mod(int x, int y) {
int r;
assert(y != 0);
r = x % y;
if (r < 0) {
r += iabs(y);
}
return r;
}
int eu_div(const int x, const int y) {
assert(y != 0);
return (x - eu_mod(x, y)) / y;
}
/* https://en.wikipedia.org/wiki/Extended_Euclidean_algorithm */
int extended_gcd(struct ExtendedGcd *egcd, const int x, const int y) {
int old_r, r, old_s, s, old_t, t, q;
old_r = x;
old_s = 1;
old_t = 0;
r = y;
s = 0;
t = 1;
assert(y != 0);
while (r != 0) {
q = eu_div(old_r, r);
swap(&old_r, &r);
swap(&old_s, &s);
swap(&old_t, &t);
r = r - q * old_r;
s = s - q * old_s;
t = t - q * old_t;
}
egcd->g = old_r;
egcd->a = old_s;
egcd->b = old_t;
return 0;
}
int main() {
int x, y, res;
struct ExtendedGcd egcd;
res = scanf("%d%d", &x, &y);
if (res != 2 || y == 0) {
printf("%s\n", "Wrong input");
abort();
}
extended_gcd(&egcd, x, y);
printf("%d %d %d\n", egcd.a, egcd.b, egcd.g);
return 0;
}
|
the_stack_data/105491.c | /* sampleCodeModule.c */
char * v = (char*)0xB8000 + 79 * 2;
static int var1 = 0;
static int var2 = 0;
int main() {
//All the following code may be removed
*v = 'X';
*(v+1) = 0x74;
//Test if BSS is properly set up
if (var1 == 0 && var2 == 0)
return 0xDEADC0DE;
return 0xDEADBEEF;
} |
the_stack_data/231392681.c | // general protection fault in __tcf_idr_release
// https://syzkaller.appspot.com/bug?id=9848e7488c582717ef7a
// status:0
// autogenerated by syzkaller (https://github.com/google/syzkaller)
#define _GNU_SOURCE
#include <dirent.h>
#include <endian.h>
#include <errno.h>
#include <fcntl.h>
#include <pthread.h>
#include <signal.h>
#include <stdarg.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.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>
#include <linux/futex.h>
static 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 thread_start(void* (*fn)(void*), void* arg)
{
pthread_t th;
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setstacksize(&attr, 128 << 10);
int i = 0;
for (; i < 100; i++) {
if (pthread_create(&th, &attr, fn, arg) == 0) {
pthread_attr_destroy(&attr);
return;
}
if (errno == EAGAIN) {
usleep(50);
continue;
}
break;
}
exit(1);
}
#define BITMASK(bf_off, bf_len) (((1ull << (bf_len)) - 1) << (bf_off))
#define STORE_BY_BITMASK(type, htobe, addr, val, bf_off, bf_len) \
*(type*)(addr) = \
htobe((htobe(*(type*)(addr)) & ~BITMASK((bf_off), (bf_len))) | \
(((type)(val) << (bf_off)) & BITMASK((bf_off), (bf_len))))
typedef struct {
int state;
} event_t;
static void event_init(event_t* ev)
{
ev->state = 0;
}
static void event_reset(event_t* ev)
{
ev->state = 0;
}
static void event_set(event_t* ev)
{
if (ev->state)
exit(1);
__atomic_store_n(&ev->state, 1, __ATOMIC_RELEASE);
syscall(SYS_futex, &ev->state, FUTEX_WAKE | FUTEX_PRIVATE_FLAG, 1000000);
}
static void event_wait(event_t* ev)
{
while (!__atomic_load_n(&ev->state, __ATOMIC_ACQUIRE))
syscall(SYS_futex, &ev->state, FUTEX_WAIT | FUTEX_PRIVATE_FLAG, 0, 0);
}
static int event_isset(event_t* ev)
{
return __atomic_load_n(&ev->state, __ATOMIC_ACQUIRE);
}
static int event_timedwait(event_t* ev, uint64_t timeout)
{
uint64_t start = current_time_ms();
uint64_t now = start;
for (;;) {
uint64_t remain = timeout - (now - start);
struct timespec ts;
ts.tv_sec = remain / 1000;
ts.tv_nsec = (remain % 1000) * 1000 * 1000;
syscall(SYS_futex, &ev->state, FUTEX_WAIT | FUTEX_PRIVATE_FLAG, 0, &ts);
if (__atomic_load_n(&ev->state, __ATOMIC_ACQUIRE))
return 1;
now = current_time_ms();
if (now - start > timeout)
return 0;
}
}
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;
}
static void kill_and_wait(int pid, int* status)
{
kill(-pid, SIGKILL);
kill(pid, SIGKILL);
for (int 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");
}
struct thread_t {
int created, call;
event_t ready, done;
};
static struct thread_t threads[16];
static void execute_call(int call);
static int running;
static void* thr(void* arg)
{
struct thread_t* th = (struct thread_t*)arg;
for (;;) {
event_wait(&th->ready);
event_reset(&th->ready);
execute_call(th->call);
__atomic_fetch_sub(&running, 1, __ATOMIC_RELAXED);
event_set(&th->done);
}
return 0;
}
static void execute_one(void)
{
int i, call, thread;
for (call = 0; call < 4; call++) {
for (thread = 0; thread < (int)(sizeof(threads) / sizeof(threads[0]));
thread++) {
struct thread_t* th = &threads[thread];
if (!th->created) {
th->created = 1;
event_init(&th->ready);
event_init(&th->done);
event_set(&th->done);
thread_start(thr, th);
}
if (!event_isset(&th->done))
continue;
event_reset(&th->done);
th->call = call;
__atomic_fetch_add(&running, 1, __ATOMIC_RELAXED);
event_set(&th->ready);
event_timedwait(&th->done, 45);
break;
}
}
for (i = 0; i < 100 && __atomic_load_n(&running, __ATOMIC_RELAXED); i++)
sleep_ms(1);
}
static void execute_one(void);
#define WAIT_FLAGS __WALL
static void loop(void)
{
int iter = 0;
for (;; iter++) {
int pid = fork();
if (pid < 0)
exit(1);
if (pid == 0) {
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;
}
}
}
uint64_t r[2] = {0xffffffffffffffff, 0xffffffffffffffff};
void execute_call(int call)
{
intptr_t res = 0;
switch (call) {
case 0:
res = syscall(__NR_socket, 0x10ul, 0x80002ul, 0);
if (res != -1)
r[0] = res;
break;
case 1:
*(uint64_t*)0x20002980 = 0;
*(uint32_t*)0x20002988 = 0;
*(uint64_t*)0x20002990 = 0x20002940;
*(uint64_t*)0x20002940 = 0x20000800;
memcpy((void*)0x20000800,
"\x98\x00\x00\x00\x30\x00\x3b\x05\x00\x00\x00\x00\x00\x00\x00\x00"
"\x00\x00\x00\x00\x84\x00\x01\x00\x50\x00\x01\x00\x0d\x00\x01\x00"
"\x63\x6f\x6e\x6e\x6d\x61\x72\x6b\x00\x00\x00\x00\x20\x00\x02\x80"
"\x1c\x00\x01\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00\x06\x00"
"\x0c\x00\x07\x00\x00\x00\x00\x00\x00\x00\x00\x00\x0c\x00\x08\x00"
"\x00\x00\x00\x00\x00\x00\x00\x00\x30\x00\x02\x00\x09\x00\x01",
111);
*(uint64_t*)0x20002948 = 0x98;
*(uint64_t*)0x20002998 = 1;
*(uint64_t*)0x200029a0 = 0;
*(uint64_t*)0x200029a8 = 0;
*(uint32_t*)0x200029b0 = 0;
syscall(__NR_sendmsg, r[0], 0x20002980ul, 0ul);
break;
case 2:
res = syscall(__NR_socket, 0x10ul, 0x80002ul, 0);
if (res != -1)
r[1] = res;
break;
case 3:
*(uint64_t*)0x20002980 = 0;
*(uint32_t*)0x20002988 = 0;
*(uint64_t*)0x20002990 = 0x20002940;
*(uint64_t*)0x20002940 = 0x20000800;
*(uint32_t*)0x20000800 = 0x68;
*(uint16_t*)0x20000804 = 0x30;
*(uint16_t*)0x20000806 = 0x53b;
*(uint32_t*)0x20000808 = 0;
*(uint32_t*)0x2000080c = 0;
*(uint8_t*)0x20000810 = 0;
*(uint8_t*)0x20000811 = 0;
*(uint16_t*)0x20000812 = 0;
*(uint16_t*)0x20000814 = 0x54;
*(uint16_t*)0x20000816 = 1;
*(uint16_t*)0x20000818 = 0x50;
STORE_BY_BITMASK(uint16_t, , 0x2000081a, 1, 0, 14);
STORE_BY_BITMASK(uint16_t, , 0x2000081b, 0, 6, 1);
STORE_BY_BITMASK(uint16_t, , 0x2000081b, 0, 7, 1);
*(uint16_t*)0x2000081c = 0xd;
*(uint16_t*)0x2000081e = 1;
memcpy((void*)0x20000820, "connmark\000", 9);
*(uint16_t*)0x2000082c = 0x20;
STORE_BY_BITMASK(uint16_t, , 0x2000082e, 2, 0, 14);
STORE_BY_BITMASK(uint16_t, , 0x2000082f, 0, 6, 1);
STORE_BY_BITMASK(uint16_t, , 0x2000082f, 1, 7, 1);
*(uint16_t*)0x20000830 = 0x1c;
*(uint16_t*)0x20000832 = 1;
*(uint32_t*)0x20000834 = 1;
*(uint32_t*)0x20000838 = 0;
*(uint32_t*)0x2000083c = 0;
*(uint32_t*)0x20000840 = 0;
*(uint32_t*)0x20000844 = 0;
*(uint16_t*)0x20000848 = 0;
*(uint16_t*)0x2000084c = 4;
*(uint16_t*)0x2000084e = 6;
*(uint16_t*)0x20000850 = 0xc;
*(uint16_t*)0x20000852 = 7;
*(uint32_t*)0x20000854 = 0;
*(uint32_t*)0x20000858 = 0;
*(uint16_t*)0x2000085c = 0xc;
*(uint16_t*)0x2000085e = 8;
*(uint32_t*)0x20000860 = 0;
*(uint32_t*)0x20000864 = 0;
*(uint64_t*)0x20002948 = 0x68;
*(uint64_t*)0x20002998 = 1;
*(uint64_t*)0x200029a0 = 0;
*(uint64_t*)0x200029a8 = 0;
*(uint32_t*)0x200029b0 = 0;
syscall(__NR_sendmsg, r[1], 0x20002980ul, 0ul);
break;
}
}
int main(void)
{
syscall(__NR_mmap, 0x1ffff000ul, 0x1000ul, 0ul, 0x32ul, -1, 0ul);
syscall(__NR_mmap, 0x20000000ul, 0x1000000ul, 7ul, 0x32ul, -1, 0ul);
syscall(__NR_mmap, 0x21000000ul, 0x1000ul, 0ul, 0x32ul, -1, 0ul);
for (procid = 0; procid < 6; procid++) {
if (fork() == 0) {
loop();
}
}
sleep(1000000);
return 0;
}
|
the_stack_data/48574642.c | /*
* Title: Gültigskeitsbereich von Variablen
* Name: Simon Schaufelberger
* Date: 10.11.20
*/
// Includes
#include <stdio.h>
#include <stdlib.h>
#define STR(var) #var
typedef double f64;
int main()
{
f64 Umfang = 11.45;
printf("%s = %lf\n", STR(Umfang), Umfang);
return 0;
}
/* Aufgaben:
1. Können beide Programme ohne Fehler kompiliert werden?
- Ja es können beide Programme kompiliert werden, da sich an der Variable ausser ihrem wirkungs bereich eigentlich nichts ändert.
2. Geben beide Programme beide das gleiche aus?
- Ja sie geben das gleiche aus.
3. Welche Vor- und Nachteile haben die beiden Lösungen?
- Zum Beispiel ermöglicht der Approach mit einer Globalen Variable eine wieder verwendung/zuweisung im Programm.
*/
|
the_stack_data/104719.c | /*
* Copyright (C) 2011 Gabor Juhos <[email protected]>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published
* by the Free Software Foundation.
*
*/
#include <errno.h>
#include <fcntl.h>
#include <libgen.h>
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
static char *progname;
static unsigned int xtra_offset;
static unsigned char eof_mark[4] = {0xde, 0xad, 0xc0, 0xde};
static unsigned char jffs2_pad_be[] = "\x19\x85\x20\x04\x04\x00\x00\x00\xc4\x94\xdb\xf4";
static unsigned char jffs2_pad_le[] = "\x85\x19\x04\x20\x00\x00\x00\x04\xa8\xfb\xa0\xb4";
static unsigned char *pad = eof_mark;
static int pad_len = sizeof(eof_mark);
#define ERR(fmt, ...) do { \
fflush(0); \
fprintf(stderr, "[%s] *** error: " fmt "\n", \
progname, ## __VA_ARGS__ ); \
} while (0)
#define ERRS(fmt, ...) do { \
int save = errno; \
fflush(0); \
fprintf(stderr, "[%s] *** error: " fmt ", %s\n", \
progname, ## __VA_ARGS__, strerror(save)); \
} while (0)
#define BUF_SIZE (64 * 1024)
#define ALIGN(_x,_y) (((_x) + ((_y) - 1)) & ~((_y) - 1))
static int pad_image(char *name, uint32_t pad_mask)
{
char *buf;
int fd;
ssize_t in_len;
ssize_t out_len;
int ret = -1;
buf = malloc(BUF_SIZE);
if (!buf) {
ERR("No memory for buffer");
goto out;
}
fd = open(name, O_RDWR);
if (fd < 0) {
ERRS("Unable to open %s", name);
goto free_buf;
}
in_len = lseek(fd, 0, SEEK_END);
if (in_len < 0)
goto close;
memset(buf, '\xff', BUF_SIZE);
in_len += xtra_offset;
out_len = in_len;
while (pad_mask) {
uint32_t mask;
ssize_t t;
int i;
for (i = 10; i < 32; i++) {
mask = 1UL << i;
if (pad_mask & mask)
break;
}
in_len = ALIGN(in_len, mask);
for (i = 10; i < 32; i++) {
mask = 1UL << i;
if ((in_len & (mask - 1)) == 0)
pad_mask &= ~mask;
}
printf("padding image to %08x\n", (unsigned int) in_len - xtra_offset);
while (out_len < in_len) {
ssize_t len;
len = in_len - out_len;
if (len > BUF_SIZE)
len = BUF_SIZE;
t = write(fd, buf, len);
if (t != len) {
ERRS("Unable to write to %s", name);
goto close;
}
out_len += len;
}
/* write out the JFFS end-of-filesystem marker */
t = write(fd, pad, pad_len);
if (t != pad_len) {
ERRS("Unable to write to %s", name);
goto close;
}
out_len += pad_len;
}
ret = 0;
close:
close(fd);
free_buf:
free(buf);
out:
return ret;
}
static int usage(void)
{
fprintf(stderr,
"Usage: %s file [<options>] [pad0] [pad1] [padN]\n"
"Options:\n"
" -x <offset>: Add an extra offset for padding data\n"
" -J: Use a fake big-endian jffs2 padding element instead of EOF\n"
" This is used to work around broken boot loaders that\n"
" try to parse the entire firmware area as one big jffs2\n"
" -j: (like -J, but little-endian instead of big-endian)\n"
"\n",
progname);
return EXIT_FAILURE;
}
int main(int argc, char* argv[])
{
char *image;
uint32_t pad_mask;
int ret = EXIT_FAILURE;
int err;
int ch, i;
progname = basename(argv[0]);
if (argc < 2)
return usage();
image = argv[1];
argv++;
argc--;
pad_mask = 0;
while ((ch = getopt(argc, argv, "x:Jj")) != -1) {
switch (ch) {
case 'x':
xtra_offset = strtoul(optarg, NULL, 0);
fprintf(stderr, "assuming %u bytes offset\n",
xtra_offset);
break;
case 'J':
pad = jffs2_pad_be;
pad_len = sizeof(jffs2_pad_be) - 1;
break;
case 'j':
pad = jffs2_pad_le;
pad_len = sizeof(jffs2_pad_le) - 1;
break;
default:
return usage();
}
}
for (i = optind; i < argc; i++)
pad_mask |= strtoul(argv[i], NULL, 0) * 1024;
if (pad_mask == 0)
pad_mask = (4 * 1024) | (8 * 1024) | (64 * 1024) |
(128 * 1024);
err = pad_image(image, pad_mask);
if (err)
goto out;
ret = EXIT_SUCCESS;
out:
return ret;
}
|
the_stack_data/90764541.c | /* # This test file is C:006 error compliant */
/*========== Includes =======================================================*/
/*========== Macros and Definitions =========================================*/
/*========== Static Constant and Variable Definitions =======================*/
/*========== Extern Constant and Variable Definitions =======================*/
/*========== Static Function Prototypes =====================================*/
/*========== Static Function Implementations ================================*/
/*========== Extern Function Implementations ================================*/
/*========== Externalized Static Function Implementations (Unit Test) =======*/
|
the_stack_data/1215221.c | #ifdef CS333_P3
/*
Test written and supplied
by Josh W.
*/
#include "types.h"
#include "user.h"
#include "uproc.h"
int
main(int argc,char *argv[]){
int ret = 1;
for(int i = 0; i < 5; i++)
{
if(ret > 0){
printf(1, "Looping process created\n");
ret = fork();
}else{
break;
}
}
if(ret > 0){
printf(1, "PRESS CTRL-R and CTRL-P TO SHOW LISTS\n");
printf(1, "-------------------------------------\n");
sleep(7*TPS);
while(wait() != -1);
}
for(;;){
ret = 1 + 1;
}
exit();
}
#endif
|
the_stack_data/231393509.c | /**
150. Evaluate Reverse Polish Notation [M]
Ref: https://leetcode.com/problems/evaluate-reverse-polish-notation/
Evaluate the value of an arithmetic expression in Reverse Polish Notation.
Valid operators are +, -, *, /. Each operand may be an integer or another expression.
Note:
Division between two integers should truncate toward zero.
The given RPN expression is always valid. That means the expression would always evaluate to a result and there won't be any divide by zero operation.
Example 1:
Input: ["2", "1", "+", "3", "*"]
Output: 9
Explanation: ((2 + 1) * 3) = 9
Example 2:
Input: ["4", "13", "5", "/", "+"]
Output: 6
Explanation: (4 + (13 / 5)) = 6
Example 3:
Input: ["10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"]
Output: 22
Explanation:
((10 * (6 / ((9 + 3) * -11))) + 17) + 5
= ((10 * (6 / (12 * -11))) + 17) + 5
= ((10 * (6 / -132)) + 17) + 5
= ((10 * 0) + 17) + 5
= (0 + 17) + 5
= 17 + 5
= 22
*/
typedef struct stackInfo
{
int size;
int top;
int *s;
} STACK;
STACK* createStack(int size)
{
STACK *obj = malloc(sizeof(STACK));
obj->size = size;
obj->top = -1;
obj->s = malloc(sizeof(int *)*size);
return obj;
}
void destroyStack(STACK *obj)
{
free(obj->s);
free(obj);
}
void push(STACK *obj, int num)
{
obj->top = (obj->top + 1) % obj->size;
obj->s[obj->top] = num;
}
int pop(STACK *obj)
{
int ret = obj->s[obj->top];
obj->top = (obj->top - 1) % obj->size;
return ret;
}
int str2int(char* s)
{
int n = strlen(s);
int res = 0;
int i = 0;
int sign = s[0] == '-' ? -1 : 1;
for (i = 0; i < n; i++)
{
if (s[i] == '-')
{
continue;
}
res *= 10;
res += s[i] - '0';
}
return res * sign;
}
int evalRPN(char ** tokens, int tokensSize)
{
STACK *s = createStack(tokensSize);
for (int i = 0; i < tokensSize; i++)
{
if ((strlen(tokens[i]) == 1) &&
(tokens[i][0] == '+' || tokens[i][0] == '-' ||
tokens[i][0] == '*' || tokens[i][0] == '/'))
{
int num2 = pop(s);
int num1 = pop(s);
switch (tokens[i][0])
{
case '+':
push(s, num1+num2);
break;
case '-':
push(s, num1-num2);
break;
case '*':
push(s, num1*num2);
break;
case '/':
push(s, num1/num2);
break;
}
} else
{
push(s, str2int(tokens[i]));
}
}
int ret = pop(s);
destroyStack(s);
return ret;
}
|
the_stack_data/768776.c | /* $OpenBSD: ldexp.c,v 1.10 2015/10/27 05:54:49 guenther Exp $ */
/* @(#)s_scalbn.c 5.1 93/09/24 */
/* @(#)fdlibm.h 5.1 93/09/24 */
/*
* ====================================================
* Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
*
* Developed at SunPro, a Sun Microsystems, Inc. business.
* Permission to use, copy, modify, and distribute this
* software is freely granted, provided that this notice
* is preserved.
* ====================================================
*/
#include <sys/types.h>
#include <endian.h>
#include <float.h>
#include <math.h>
/* Bit fiddling routines copied from msun/src/math_private.h,v 1.15 */
#if (BYTE_ORDER == BIG_ENDIAN) || (defined(__arm__) && !defined(__VFP_FP__))
typedef union
{
double value;
struct
{
u_int32_t msw;
u_int32_t lsw;
} parts;
} ieee_double_shape_type;
#endif
#if (BYTE_ORDER == LITTLE_ENDIAN) && !(defined(__arm__) && !defined(__VFP_FP__))
typedef union
{
double value;
struct
{
u_int32_t lsw;
u_int32_t msw;
} parts;
} ieee_double_shape_type;
#endif
/* Get two 32 bit ints from a double. */
#define EXTRACT_WORDS(ix0,ix1,d) \
do { \
ieee_double_shape_type ew_u; \
ew_u.value = (d); \
(ix0) = ew_u.parts.msw; \
(ix1) = ew_u.parts.lsw; \
} while (0)
/* Get the more significant 32 bit int from a double. */
#define GET_HIGH_WORD(i,d) \
do { \
ieee_double_shape_type gh_u; \
gh_u.value = (d); \
(i) = gh_u.parts.msw; \
} while (0)
/* Set the more significant 32 bits of a double from an int. */
#define SET_HIGH_WORD(d,v) \
do { \
ieee_double_shape_type sh_u; \
sh_u.value = (d); \
sh_u.parts.msw = (v); \
(d) = sh_u.value; \
} while (0)
static const double
two54 = 1.80143985094819840000e+16, /* 0x43500000, 0x00000000 */
twom54 = 5.55111512312578270212e-17, /* 0x3C900000, 0x00000000 */
huge = 1.0e+300,
tiny = 1.0e-300;
static double
_copysign(double x, double y)
{
u_int32_t hx,hy;
GET_HIGH_WORD(hx,x);
GET_HIGH_WORD(hy,y);
SET_HIGH_WORD(x,(hx&0x7fffffff)|(hy&0x80000000));
return x;
}
double
ldexp(double x, int n)
{
int32_t k,hx,lx;
EXTRACT_WORDS(hx,lx,x);
k = (hx&0x7ff00000)>>20; /* extract exponent */
if (k==0) { /* 0 or subnormal x */
if ((lx|(hx&0x7fffffff))==0) return x; /* +-0 */
x *= two54;
GET_HIGH_WORD(hx,x);
k = ((hx&0x7ff00000)>>20) - 54;
if (n< -50000) return tiny*x; /*underflow*/
}
if (k==0x7ff) return x+x; /* NaN or Inf */
k = k+n;
if (k > 0x7fe) return huge*_copysign(huge,x); /* overflow */
if (k > 0) /* normal result */
{SET_HIGH_WORD(x,(hx&0x800fffff)|(k<<20)); return x;}
if (k <= -54) {
if (n > 50000) /* in case integer overflow in n+k */
return huge*_copysign(huge,x); /*overflow*/
else return tiny*_copysign(tiny,x); /*underflow*/
}
k += 54; /* subnormal result */
SET_HIGH_WORD(x,(hx&0x800fffff)|(k<<20));
return x*twom54;
}
DEF_STRONG(ldexp);
#if LDBL_MANT_DIG == DBL_MANT_DIG
__strong_alias(ldexpl, ldexp);
#endif /* LDBL_MANT_DIG == DBL_MANT_DIG */
|
the_stack_data/165764494.c | #include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define MAX_VALUE 30
int isPrime(int number) {
int i;
for (i = 2; i < number; i++) {
if (number % i == 0 && i != number)
return 0;
}
return 1;
}
int main() {
srand(time(NULL));
int credits = 10;
while (credits > 0) {
int wager = 0, guess = -1;
while (wager < 1 || wager > credits) {
printf("\n\nYou have %d credits.\n", credits);
printf("How much would you like to bet? ");
scanf("%d", &wager);
}
while (guess < 0 || guess > MAX_VALUE) {
printf("\n\nWhich number do you want to place your wager on? ");
scanf("%i", &guess);
}
int randomNumber = rand() % MAX_VALUE;
// printf("%d\n", randomNumber);
if (guess == randomNumber) {
// They've guessed correctly
int winMultiplier = 0;
if (isPrime(randomNumber))
winMultiplier += 5;
if (randomNumber % 10 == 0)
winMultiplier += 3;
if (randomNumber < 5)
winMultiplier += 2;
if (winMultiplier == 0)
winMultiplier = 1;
printf("Congratulations! You guessed correctly!\n");
printf(
"You won %d credits with a %dx multiplier (%d credits "
"total)!\n",
wager, winMultiplier, wager * winMultiplier);
credits += wager * winMultiplier;
} else {
// They're wrong
credits -= wager;
printf("Oh no, you guessed incorrectly. The number was %d.", randomNumber);
}
}
printf("Hello, World!\n");
return 0;
}
|
the_stack_data/111077238.c | /* $OpenBSD: bio_ndef.c,v 1.9 2014/07/25 06:05:32 doug Exp $ */
/* Written by Dr Stephen N Henson ([email protected]) for the OpenSSL
* project.
*/
/* ====================================================================
* Copyright (c) 2008 The OpenSSL Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
*
* 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please contact
* [email protected].
*
* 5. Products derived from this software may not be called "OpenSSL"
* nor may "OpenSSL" appear in their names without prior written
* permission of the OpenSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED 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 OpenSSL PROJECT 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.
* ====================================================================
*
*/
#include <openssl/asn1.h>
#include <openssl/asn1t.h>
#include <openssl/bio.h>
#include <openssl/err.h>
#include <stdio.h>
/* Experimental NDEF ASN1 BIO support routines */
/* The usage is quite simple, initialize an ASN1 structure,
* get a BIO from it then any data written through the BIO
* will end up translated to approptiate format on the fly.
* The data is streamed out and does *not* need to be
* all held in memory at once.
*
* When the BIO is flushed the output is finalized and any
* signatures etc written out.
*
* The BIO is a 'proper' BIO and can handle non blocking I/O
* correctly.
*
* The usage is simple. The implementation is *not*...
*/
/* BIO support data stored in the ASN1 BIO ex_arg */
typedef struct ndef_aux_st {
/* ASN1 structure this BIO refers to */
ASN1_VALUE *val;
const ASN1_ITEM *it;
/* Top of the BIO chain */
BIO *ndef_bio;
/* Output BIO */
BIO *out;
/* Boundary where content is inserted */
unsigned char **boundary;
/* DER buffer start */
unsigned char *derbuf;
} NDEF_SUPPORT;
static int ndef_prefix(BIO *b, unsigned char **pbuf, int *plen, void *parg);
static int ndef_prefix_free(BIO *b, unsigned char **pbuf, int *plen, void *parg);
static int ndef_suffix(BIO *b, unsigned char **pbuf, int *plen, void *parg);
static int ndef_suffix_free(BIO *b, unsigned char **pbuf, int *plen, void *parg);
BIO *
BIO_new_NDEF(BIO *out, ASN1_VALUE *val, const ASN1_ITEM *it)
{
NDEF_SUPPORT *ndef_aux = NULL;
BIO *asn_bio = NULL;
const ASN1_AUX *aux = it->funcs;
ASN1_STREAM_ARG sarg;
if (!aux || !aux->asn1_cb) {
ASN1error(ASN1_R_STREAMING_NOT_SUPPORTED);
return NULL;
}
ndef_aux = malloc(sizeof(NDEF_SUPPORT));
asn_bio = BIO_new(BIO_f_asn1());
/* ASN1 bio needs to be next to output BIO */
out = BIO_push(asn_bio, out);
if (!ndef_aux || !asn_bio || !out)
goto err;
BIO_asn1_set_prefix(asn_bio, ndef_prefix, ndef_prefix_free);
BIO_asn1_set_suffix(asn_bio, ndef_suffix, ndef_suffix_free);
/* Now let callback prepend any digest, cipher etc BIOs
* ASN1 structure needs.
*/
sarg.out = out;
sarg.ndef_bio = NULL;
sarg.boundary = NULL;
if (aux->asn1_cb(ASN1_OP_STREAM_PRE, &val, it, &sarg) <= 0)
goto err;
ndef_aux->val = val;
ndef_aux->it = it;
ndef_aux->ndef_bio = sarg.ndef_bio;
ndef_aux->boundary = sarg.boundary;
ndef_aux->out = out;
BIO_ctrl(asn_bio, BIO_C_SET_EX_ARG, 0, ndef_aux);
return sarg.ndef_bio;
err:
BIO_free(asn_bio);
free(ndef_aux);
return NULL;
}
static int
ndef_prefix(BIO *b, unsigned char **pbuf, int *plen, void *parg)
{
NDEF_SUPPORT *ndef_aux;
unsigned char *p;
int derlen;
if (!parg)
return 0;
ndef_aux = *(NDEF_SUPPORT **)parg;
derlen = ASN1_item_ndef_i2d(ndef_aux->val, NULL, ndef_aux->it);
p = malloc(derlen);
ndef_aux->derbuf = p;
*pbuf = p;
derlen = ASN1_item_ndef_i2d(ndef_aux->val, &p, ndef_aux->it);
if (!*ndef_aux->boundary)
return 0;
*plen = *ndef_aux->boundary - *pbuf;
return 1;
}
static int
ndef_prefix_free(BIO *b, unsigned char **pbuf, int *plen, void *parg)
{
NDEF_SUPPORT *ndef_aux;
if (!parg)
return 0;
ndef_aux = *(NDEF_SUPPORT **)parg;
free(ndef_aux->derbuf);
ndef_aux->derbuf = NULL;
*pbuf = NULL;
*plen = 0;
return 1;
}
static int
ndef_suffix_free(BIO *b, unsigned char **pbuf, int *plen, void *parg)
{
NDEF_SUPPORT **pndef_aux = (NDEF_SUPPORT **)parg;
if (!ndef_prefix_free(b, pbuf, plen, parg))
return 0;
free(*pndef_aux);
*pndef_aux = NULL;
return 1;
}
static int
ndef_suffix(BIO *b, unsigned char **pbuf, int *plen, void *parg)
{
NDEF_SUPPORT *ndef_aux;
unsigned char *p;
int derlen;
const ASN1_AUX *aux;
ASN1_STREAM_ARG sarg;
if (!parg)
return 0;
ndef_aux = *(NDEF_SUPPORT **)parg;
aux = ndef_aux->it->funcs;
/* Finalize structures */
sarg.ndef_bio = ndef_aux->ndef_bio;
sarg.out = ndef_aux->out;
sarg.boundary = ndef_aux->boundary;
if (aux->asn1_cb(ASN1_OP_STREAM_POST,
&ndef_aux->val, ndef_aux->it, &sarg) <= 0)
return 0;
derlen = ASN1_item_ndef_i2d(ndef_aux->val, NULL, ndef_aux->it);
p = malloc(derlen);
ndef_aux->derbuf = p;
*pbuf = p;
derlen = ASN1_item_ndef_i2d(ndef_aux->val, &p, ndef_aux->it);
if (!*ndef_aux->boundary)
return 0;
*pbuf = *ndef_aux->boundary;
*plen = derlen - (*ndef_aux->boundary - ndef_aux->derbuf);
return 1;
}
|
the_stack_data/87377.c | #include <stdio.h>
int foo(int i, int j) {
printf("%d\n", j);
return j;
}
int main(void) {
int level = 5;
int i;
int fval[4];
//for (i = 3; i < 10; i--)
for (i = 3; i >= 0; i--)
fval[i] = foo(level - 1, level*4 + i + 1);
for (i = 0; i < 4; ++i)
foo(0, fval[i]);
return 0;
}
|
the_stack_data/1136717.c | #include<stdio.h>
int main ( void ) {
int n = 0;
for(int i = 0; i < 5; i++) {
printf("Digite um numero de 1 a 30:");
scanf("%d", &n);
if ( !(n >= 1 && n <= 30) ) break;
for(int j = 0; j < n; j++) {
printf("*");
}
printf("\n");
}
}
|
the_stack_data/1230834.c | #include <math.h>
double sqrt(double x)
{
__asm__ ("sqrtsd %1, %0" : "=x"(x) : "x"(x));
return x;
}
|
the_stack_data/168892731.c | /*
** EPITECH PROJECT, 2019
** my_swap
** File description:
** swaps the content of two integers whose addresses are given as parameter
*/
void my_swap(int *a, int *b)
{
int c;
c = *a;
*a = *b;
*b = c;
}
|
the_stack_data/184518930.c | /* Taxonomy Classification: 0020000000000000000300 */
/*
* WRITE/READ 0 write
* WHICH BOUND 0 upper
* DATA TYPE 2 float
* MEMORY LOCATION 0 stack
* SCOPE 0 same
* CONTAINER 0 no
* POINTER 0 no
* INDEX COMPLEXITY 0 constant
* ADDRESS COMPLEXITY 0 constant
* LENGTH COMPLEXITY 0 N/A
* ADDRESS ALIAS 0 none
* INDEX ALIAS 0 none
* LOCAL CONTROL FLOW 0 none
* SECONDARY CONTROL FLOW 0 none
* LOOP STRUCTURE 0 no
* LOOP COMPLEXITY 0 N/A
* ASYNCHRONY 0 no
* TAINT 0 no
* RUNTIME ENV. DEPENDENCE 0 no
* MAGNITUDE 3 4096 bytes
* CONTINUOUS/DISCRETE 0 discrete
* SIGNEDNESS 0 no
*/
/*
Copyright 2004 M.I.T.
Permission is hereby granted, without written agreement or royalty fee, to use,
copy, modify, and distribute this software and its documentation for any
purpose, provided that the above copyright notice and the following three
paragraphs appear in all copies of this software.
IN NO EVENT SHALL M.I.T. BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL,
INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE
AND ITS DOCUMENTATION, EVEN IF M.I.T. HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMANGE.
M.I.T. SPECIFICALLY DISCLAIMS ANY WARRANTIES INCLUDING, BUT NOT LIMITED TO
THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE,
AND NON-INFRINGEMENT.
THE SOFTWARE IS PROVIDED ON AN "AS-IS" BASIS AND M.I.T. HAS NO OBLIGATION TO
PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
*/
int main(int argc, char *argv[])
{
float buf[10];
/* BAD */
buf[4105] = 55.55;
return 0;
}
|
the_stack_data/90766812.c | // Ensure analyzer option 'ctu-import-threshold' is a recognized option.
//
// RUN: %clang_cc1 -analyze -analyzer-config ctu-import-threshold=30 -verify %s
//
// expected-no-diagnostics
|
the_stack_data/67631.c | #include <stdio.h>
int main()
{
float x;
float y;
scanf("%f", &x);
scanf("%f", &y);
if(x == 0 && y == 0){
printf("Origem\n");
}else if(x == 0){
printf("Eixo Y\n");
}else if(y == 0){
printf("Eixo X\n");
}else if(x > 0 && y > 0){
printf("Q1\n");
}else if(x > 0 && y < 0){
printf("Q4\n");
}else if(x < 0 && y > 0){
printf("Q2\n");
}else{
printf("Q3\n");
}
return 0;
}
|
the_stack_data/40177.c | #include <sys/time.h>
#include <sys/resource.h>
#include <stdio.h>
void
add_timeval( struct timeval *x, const struct timeval *y )
{
x->tv_sec += y->tv_sec;
x->tv_usec += y->tv_usec;
if( x->tv_usec > 1000000 ) {
++x->tv_sec;
x->tv_usec -= 1000000;
}
}
void
sub_timeval( struct timeval *x, const struct timeval *y )
{
x->tv_sec -= y->tv_sec;
if( x->tv_usec < y->tv_usec ) {
--x->tv_sec;
x->tv_usec = x->tv_usec + (1000000 - y->tv_usec);
} else
x->tv_usec -= y->tv_usec;
}
void
print_timeval( const struct timeval *t )
{
printf( "%ld", (long int) t->tv_sec * 1000 + (long int) t->tv_usec / 1000 );
}
|
the_stack_data/243892687.c | /* ヘッダファイルのインクルード */
#include <stdio.h> /* 標準入出力 */
#include <unistd.h> /* UNIX標準 */
#include <sys/types.h> /* 派生型 */
#include <sys/stat.h> /* ファイル状態 */
#include <fcntl.h> /* ファイル制御 */
/* main関数の定義 */
int main(void){
/* 変数の宣言 */
int result; /* mknodの戻り値result. */
/* mknodで空のファイルを作成. */
result = mknod("test.txt", S_IFREG | S_IRWXU | S_IRWXG | S_IRWXO, 0); /* mknodで"test.txt"を作成. */
if (result == 0){ /* 成功 */
printf("create test.txt success!\n"); /* "create test.txt success!"と出力. */
}
else{ /* 失敗 */
printf("create test.txt failed!\n"); /* "create test.txt failed!"と出力. */
}
/* mknodで名前付きパイプを作成. */
result = mknod("TEST1", S_IFIFO | S_IRWXU | S_IRWXG | S_IRWXO, 0); /* mknodで"TEST1"を作成. */
if (result == 0){ /* 成功 */
printf("create TEST1 success!\n"); /* "create TEST1 success!"と出力. */
}
else{ /* 失敗 */
printf("create TEST1 failed!\n"); /* "create TEST1 failed!"と出力. */
}
/* プログラムの終了 */
return 0; /* 0を返して正常終了. */
}
|
the_stack_data/864198.c | #include <stdio.h>
#include <stdlib.h>
#define N 3
typedef const char* String;
int main(void) {
String const bird[N] = {"raven","magpie","jay"};
String const pronoun[N] = {"we", "you", "they"};
String const ordinal[N] = {"first", "second", "third"};
for (unsigned i = 0; i < N; i++) {
printf("Corvid #%u is the %s.\n", i+1, bird[i]);
}
for (unsigned i = 0; i < N; i++) {
printf("The %s plural pronoun is %s.\n", ordinal[i], pronoun[i]);
}
return EXIT_SUCCESS;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.