file
stringlengths
18
26
data
stringlengths
3
1.04M
the_stack_data/173578455.c
/* { dg-options { -nostartfiles below100.o -Tbelow100.ld -O2 } } */ /* { dg-final { scan-assembler "b\[np\] B100A,#0," } } */ /* { dg-final { scan-assembler "b\[np\] B100B,#0," } } */ typedef struct { unsigned short b0:1; unsigned short b1:1; unsigned short b2:1; unsigned short b3:1; unsigned short b4:1; unsigned short b5:1; unsigned short b6:1; unsigned short b7:1; unsigned short b8:1; unsigned short b9:1; unsigned short b10:1; unsigned short b11:1; unsigned short b12:1; unsigned short b13:1; unsigned short b14:1; unsigned short b15:1; } BitField; char acDummy[0xf0] __attribute__ ((__BELOW100__)); BitField B100A __attribute__ ((__BELOW100__)); unsigned short *pA = (unsigned short *) &B100A; BitField B100B __attribute__ ((__BELOW100__)); unsigned short *pB = (unsigned short *) &B100B; char * Do (void) { if (!B100A.b0) { if (!B100B.b0) return "Fail"; else return "Success"; } else return "Fail"; } int main (void) { *pA = 0x1234; *pB = 0xedcb; return Do ()[0] == 'F'; }
the_stack_data/25138294.c
#include <unistd.h> void ft_putstr(char *str); int main(void) { char *str; str = ""; ft_putstr(str); write(1, "\n", 1); str = "This is a test string."; ft_putstr(str); write(1, "\n", 1); str = "This is a gianormous test string, testing to see whatever happens in here...."; ft_putstr(str); write(1, "\n", 1); return (0); }
the_stack_data/346123.c
/* +++Date last modified: 05-Jul-1997 */ /* Updated comments, 05-Aug-2013 */ /* SUNRISET.C - computes Sun rise/set times, start/end of twilight, and the length of the day at any date and latitude Written as DAYLEN.C, 1989-08-16 Modified to SUNRISET.C, 1992-12-01 (c) Paul Schlyter, 1989, 1992 Released to the public domain by Paul Schlyter, December 1992 */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <time.h> #include <getopt.h> #include <math.h> /* A macro to compute the number of days elapsed since 2000 Jan 0.0 */ /* (which is equal to 1999 Dec 31, 0h UT) */ #define days_since_2000_Jan_0(y,m,d) \ (367L*(y)-((7*((y)+(((m)+9)/12)))/4)+((275*(m))/9)+(d)-730530L) /* Some conversion factors between radians and degrees */ #ifndef PI #define PI 3.1415926535897932384 #endif #define RADEG ( 180.0 / PI ) #define DEGRAD ( PI / 180.0 ) /* The trigonometric functions in degrees */ #define sind(x) sin((x)*DEGRAD) #define cosd(x) cos((x)*DEGRAD) #define tand(x) tan((x)*DEGRAD) #define atand(x) (RADEG*atan(x)) #define asind(x) (RADEG*asin(x)) #define acosd(x) (RADEG*acos(x)) #define atan2d(y,x) (RADEG*atan2(y,x)) /* Following are some macros around the "workhorse" function __daylen__ */ /* They mainly fill in the desired values for the reference altitude */ /* below the horizon, and also selects whether this altitude should */ /* refer to the Sun's center or its upper limb. */ /* This macro computes the length of the day, from sunrise to sunset. */ /* Sunrise/set is considered to occur when the Sun's upper limb is */ /* 35 arc minutes below the horizon (this accounts for the refraction */ /* of the Earth's atmosphere). */ #define day_length(year,month,day,lon,lat) \ __daylen__( year, month, day, lon, lat, -35.0/60.0, 1 ) /* This macro computes the length of the day, including civil twilight. */ /* Civil twilight starts/ends when the Sun's center is 6 degrees below */ /* the horizon. */ #define day_civil_twilight_length(year,month,day,lon,lat) \ __daylen__( year, month, day, lon, lat, -6.0, 0 ) /* This macro computes the length of the day, incl. nautical twilight. */ /* Nautical twilight starts/ends when the Sun's center is 12 degrees */ /* below the horizon. */ #define day_nautical_twilight_length(year,month,day,lon,lat) \ __daylen__( year, month, day, lon, lat, -12.0, 0 ) /* This macro computes the length of the day, incl. astronomical twilight. */ /* Astronomical twilight starts/ends when the Sun's center is 18 degrees */ /* below the horizon. */ #define day_astronomical_twilight_length(year,month,day,lon,lat) \ __daylen__( year, month, day, lon, lat, -18.0, 0 ) /* This macro computes times for sunrise/sunset. */ /* Sunrise/set is considered to occur when the Sun's upper limb is */ /* 35 arc minutes below the horizon (this accounts for the refraction */ /* of the Earth's atmosphere). */ #define sun_rise_set(year,month,day,lon,lat,tz,rise,set) \ __sunriset__( year, month, day, lon, lat, tz, -35.0/60.0, 1, rise, set ) /* This macro computes the start and end times of civil twilight. */ /* Civil twilight starts/ends when the Sun's center is 6 degrees below */ /* the horizon. */ #define civil_twilight(year,month,day,lon,lat,tz,start,end) \ __sunriset__( year, month, day, lon, lat, tz, -6.0, 0, start, end ) /* This macro computes the start and end times of nautical twilight. */ /* Nautical twilight starts/ends when the Sun's center is 12 degrees */ /* below the horizon. */ #define nautical_twilight(year,month,day,lon,lat,tz,start,end) \ __sunriset__( year, month, day, lon, lat, tz, -12.0, 0, start, end ) /* This macro computes the start and end times of astronomical twilight. */ /* Astronomical twilight starts/ends when the Sun's center is 18 degrees */ /* below the horizon. */ #define astronomical_twilight(year,month,day,lon,lat,tz,start,end) \ __sunriset__( year, month, day, lon, lat, tz, -18.0, 0, start, end ) /* Function prototypes */ double __daylen__( int year, int month, int day, double lon, double lat, double altit, int upper_limb ); int __sunriset__( int year, int month, int day, double lon, double lat, double tz, double altit, int upper_limb, double *rise, double *set ); void sunpos( double d, double *lon, double *r ); void sun_RA_dec( double d, double *RA, double *dec, double *r ); double revolution( double x ); double rev180( double x ); double GMST0( double d ); int H( double r ) { return (int)r; } int M( double r ) { return (int)((r - (int)r)*60); } /* A small test program */ static void print_usage(const char *prog) { printf("Usage: %s [-ymdtoah]\n", prog); puts(" -y --year year (default today)\n" " -m --mon month (default today)\n" " -d --day day (default today)\n" " -t --tz time zone(default 9)\n" " -o --lon longitude (default 126.978420)\n" " -a --lat latitude (default 37.566692) \n" " -h --help this message\n"); exit(1); } static void parse_opts(int argc, char *argv[], int *y, int *m, int *d, double *lon, double *lat, double *tz) { time_t systime; time(&systime); struct tm * now = localtime(&systime); *y = now->tm_year + 1900; *m = now->tm_mon + 1; *d = now->tm_mday; *lon = 126.978420; *lat = 37.566692; *tz = 9; while(1) { static const struct option lopts[] = { { "year", required_argument, 0, 'y' }, { "mon", required_argument, 0, 'm' }, { "day", required_argument, 0, 'd' }, { "tz", required_argument, 0, 't' }, { "lon", required_argument, 0, 'o' }, { "lat", required_argument, 0, 'a' }, { "help", no_argument, 0, 'h' }, { NULL, 0, 0, 0 } }; int c; c = getopt_long(argc, argv, "y:m:d:t:o:a:", lopts, NULL); if(c == -1) break; switch(c) { case 'y': sscanf(optarg, "%d", y); break; case 'm': sscanf(optarg, "%d", m); break; case 'd': sscanf(optarg, "%d", d); break; case 'o': sscanf(optarg, "%lf", lon); break; case 'a': sscanf(optarg, "%lf", lat); break; case 't': sscanf(optarg, "%lf", tz); break; case 'h': default: print_usage(argv[0]); break; } } } int main(int argc, char * argv[]) { int year,month,day; double lon, lat; double tz; double daylen, civlen, nautlen, astrlen; double rise, set, civ_start, civ_end, naut_start, naut_end, astr_start, astr_end; int rs, civ, naut, astr; parse_opts(argc, argv, &year, &month, &day, &lon, &lat, &tz); printf("Longitude: %c%.6lf\n", (lon<0)?'W':'E', (lon<0)?-lon:lon); printf("Latitude: %c%.6lf\n", (lat<0)?'S':'N', (lat<0)?-lat:lat); printf("Date: %d %02d %02d\n", year, month, day); printf("Timezone: %d\n", (int)tz); daylen = day_length(year,month,day,lon,lat); civlen = day_civil_twilight_length(year,month,day,lon,lat); nautlen = day_nautical_twilight_length(year,month,day,lon,lat); astrlen = day_astronomical_twilight_length(year,month,day,lon,lat); printf( "With civil twilight %02d:%02d\n", H(civlen), M(civlen)); printf( "Day length: %02d:%02d\n", H(daylen), M(daylen)); printf( "With nautical twilight %02d:%02d\n", H(nautlen), M(nautlen)); printf( "With astronomical twilight %02d:%02d\n", H(astrlen), M(astrlen)); printf( "Length of twilight: civil %02d:%02d\n", H((civlen-daylen)/2.0), M((civlen-daylen)/2.0)); printf( " nautical %02d:%02d\n", H((nautlen-daylen)/2.0), M((nautlen-daylen)/2.0)); printf( " astronomical %02d:%02d\n", H((astrlen-daylen)/2.0), M((astrlen-daylen)/2.0)); rs = sun_rise_set ( year, month, day, lon, lat, tz, &rise, &set ); civ = civil_twilight ( year, month, day, lon, lat, tz, &civ_start, &civ_end ); naut = nautical_twilight ( year, month, day, lon, lat, tz, &naut_start, &naut_end ); astr = astronomical_twilight( year, month, day, lon, lat, tz, &astr_start, &astr_end ); printf( "Sun at south %02d:%02d\n", H((rise+set)/2.0), M((rise+set)/2.0)); switch( rs ) { case 0: printf( "Sun rises %02d:%02d, sets %02d:%02d\n", H(rise+tz), M(rise+tz), H(set+tz), M(set+tz)); break; case +1: printf( "Sun above horizon\n" ); break; case -1: printf( "Sun below horizon\n" ); break; } switch( civ ) { case 0: printf( "Civil twilight starts %02d:%02d, ends %02d:%02d\n", H(civ_start+tz), M(civ_start+tz), H(civ_end+tz), M(civ_end+tz)); break; case +1: printf( "Never darker than civil twilight\n" ); break; case -1: printf( "Never as bright as civil twilight\n" ); break; } switch( naut ) { case 0: printf( "Nautical twilight starts %02d:%02d, ends %02d:%02d\n", H(naut_start+tz), M(naut_start+tz), H(naut_end+tz), M(naut_end+tz)); break; case +1: printf( "Never darker than nautical twilight\n" ); break; case -1: printf( "Never as bright as nautical twilight\n" ); break; } switch( astr ) { case 0: printf( "Astronomical twilight starts %02d:%02d, ends %02d:%02d\n", H(astr_start+tz), H(astr_start+tz), H(astr_end+tz), M(astr_end+tz)); break; case +1: printf( "Never darker than astronomical twilight\n" ); break; case -1: printf( "Never as bright as astronomical twilight\n" ); break; } } /* The "workhorse" function for sun rise/set times */ int __sunriset__( int year, int month, int day, double lon, double lat, double tz, double altit, int upper_limb, double *trise, double *tset ) /***************************************************************************/ /* Note: year,month,date = calendar date, 1801-2099 only. */ /* Eastern longitude positive, Western longitude negative */ /* Northern latitude positive, Southern latitude negative */ /* The longitude value IS critical in this function! */ /* altit = the altitude which the Sun should cross */ /* Set to -35/60 degrees for rise/set, -6 degrees */ /* for civil, -12 degrees for nautical and -18 */ /* degrees for astronomical twilight. */ /* upper_limb: non-zero -> upper limb, zero -> center */ /* Set to non-zero (e.g. 1) when computing rise/set */ /* times, and to zero when computing start/end of */ /* twilight. */ /* *rise = where to store the rise time */ /* *set = where to store the set time */ /* Both times are relative to the specified altitude, */ /* and thus this function can be used to compute */ /* various twilight times, as well as rise/set times */ /* Return value: 0 = sun rises/sets this day, times stored at */ /* *trise and *tset. */ /* +1 = sun above the specified "horizon" 24 hours. */ /* *trise set to time when the sun is at south, */ /* minus 12 hours while *tset is set to the south */ /* time plus 12 hours. "Day" length = 24 hours */ /* -1 = sun is below the specified "horizon" 24 hours */ /* "Day" length = 0 hours, *trise and *tset are */ /* both set to the time when the sun is at south. */ /* */ /**********************************************************************/ { double d, /* Days since 2000 Jan 0.0 (negative before) */ sr, /* Solar distance, astronomical units */ sRA, /* Sun's Right Ascension */ sdec, /* Sun's declination */ sradius, /* Sun's apparent radius */ t, /* Diurnal arc */ tsouth, /* Time when Sun is at south */ sidtime; /* Local sidereal time */ int rc = 0; /* Return cde from function - usually 0 */ /* Compute d of 12h local mean solar time */ d = days_since_2000_Jan_0(year,month,day) + 0.5 - lon/360.0; /* Compute the local sidereal time of this moment */ sidtime = revolution( GMST0(d) + 180.0 + lon ); /* Compute Sun's RA, Decl and distance at this moment */ sun_RA_dec( d, &sRA, &sdec, &sr ); /* Compute time when Sun is at south - in hours UT */ tsouth = 12.0 - rev180(sidtime - sRA)/15.0; /* Compute the Sun's apparent radius in degrees */ sradius = 0.2666 / sr; /* Do correction to upper limb, if necessary */ if ( upper_limb ) altit -= sradius; /* Compute the diurnal arc that the Sun traverses to reach */ /* the specified altitude altit: */ { double cost; cost = ( sind(altit) - sind(lat) * sind(sdec) ) / ( cosd(lat) * cosd(sdec) ); if ( cost >= 1.0 ) rc = -1, t = 0.0; /* Sun always below altit */ else if ( cost <= -1.0 ) rc = +1, t = 12.0; /* Sun always above altit */ else t = acosd(cost)/15.0; /* The diurnal arc, hours */ } /* Store rise and set times - in hours UT */ *trise = tsouth - t; *tset = tsouth + t; return rc; } /* __sunriset__ */ /* The "workhorse" function */ double __daylen__( int year, int month, int day, double lon, double lat, double altit, int upper_limb ) /**********************************************************************/ /* Note: year,month,date = calendar date, 1801-2099 only. */ /* Eastern longitude positive, Western longitude negative */ /* Northern latitude positive, Southern latitude negative */ /* The longitude value is not critical. Set it to the correct */ /* longitude if you're picky, otherwise set to to, say, 0.0 */ /* The latitude however IS critical - be sure to get it correct */ /* altit = the altitude which the Sun should cross */ /* Set to -35/60 degrees for rise/set, -6 degrees */ /* for civil, -12 degrees for nautical and -18 */ /* degrees for astronomical twilight. */ /* upper_limb: non-zero -> upper limb, zero -> center */ /* Set to non-zero (e.g. 1) when computing day length */ /* and to zero when computing day+twilight length. */ /**********************************************************************/ { double d, /* Days since 2000 Jan 0.0 (negative before) */ obl_ecl, /* Obliquity (inclination) of Earth's axis */ sr, /* Solar distance, astronomical units */ slon, /* True solar longitude */ sin_sdecl, /* Sine of Sun's declination */ cos_sdecl, /* Cosine of Sun's declination */ sradius; /* Sun's apparent radius */ double t; /* Diurnal arc */ /* Compute d of 12h local mean solar time */ d = days_since_2000_Jan_0(year,month,day) + 0.5 - lon/360.0; /* Compute obliquity of ecliptic (inclination of Earth's axis) */ obl_ecl = 23.4393 - 3.563E-7 * d; /* Compute Sun's ecliptic longitude and distance */ sunpos( d, &slon, &sr ); /* Compute sine and cosine of Sun's declination */ sin_sdecl = sind(obl_ecl) * sind(slon); cos_sdecl = sqrt( 1.0 - sin_sdecl * sin_sdecl ); /* Compute the Sun's apparent radius, degrees */ sradius = 0.2666 / sr; /* Do correction to upper limb, if necessary */ if ( upper_limb ) altit -= sradius; /* Compute the diurnal arc that the Sun traverses to reach */ /* the specified altitude altit: */ { double cost; cost = ( sind(altit) - sind(lat) * sin_sdecl ) / ( cosd(lat) * cos_sdecl ); if ( cost >= 1.0 ) t = 0.0; /* Sun always below altit */ else if ( cost <= -1.0 ) t = 24.0; /* Sun always above altit */ else t = (2.0/15.0) * acosd(cost); /* The diurnal arc, hours */ } return t; } /* __daylen__ */ /* This function computes the Sun's position at any instant */ void sunpos( double d, double *lon, double *r ) /******************************************************/ /* Computes the Sun's ecliptic longitude and distance */ /* at an instant given in d, number of days since */ /* 2000 Jan 0.0. The Sun's ecliptic latitude is not */ /* computed, since it's always very near 0. */ /******************************************************/ { double M, /* Mean anomaly of the Sun */ w, /* Mean longitude of perihelion */ /* Note: Sun's mean longitude = M + w */ e, /* Eccentricity of Earth's orbit */ E, /* Eccentric anomaly */ x, y, /* x, y coordinates in orbit */ v; /* True anomaly */ /* Compute mean elements */ M = revolution( 356.0470 + 0.9856002585 * d ); w = 282.9404 + 4.70935E-5 * d; e = 0.016709 - 1.151E-9 * d; /* Compute true longitude and radius vector */ E = M + e * RADEG * sind(M) * ( 1.0 + e * cosd(M) ); x = cosd(E) - e; y = sqrt( 1.0 - e*e ) * sind(E); *r = sqrt( x*x + y*y ); /* Solar distance */ v = atan2d( y, x ); /* True anomaly */ *lon = v + w; /* True solar longitude */ if ( *lon >= 360.0 ) *lon -= 360.0; /* Make it 0..360 degrees */ } void sun_RA_dec( double d, double *RA, double *dec, double *r ) /******************************************************/ /* Computes the Sun's equatorial coordinates RA, Decl */ /* and also its distance, at an instant given in d, */ /* the number of days since 2000 Jan 0.0. */ /******************************************************/ { double lon, obl_ecl, x, y, z; /* Compute Sun's ecliptical coordinates */ sunpos( d, &lon, r ); /* Compute ecliptic rectangular coordinates (z=0) */ x = *r * cosd(lon); y = *r * sind(lon); /* Compute obliquity of ecliptic (inclination of Earth's axis) */ obl_ecl = 23.4393 - 3.563E-7 * d; /* Convert to equatorial rectangular coordinates - x is unchanged */ z = y * sind(obl_ecl); y = y * cosd(obl_ecl); /* Convert to spherical coordinates */ *RA = atan2d( y, x ); *dec = atan2d( z, sqrt(x*x + y*y) ); } /* sun_RA_dec */ /******************************************************************/ /* This function reduces any angle to within the first revolution */ /* by subtracting or adding even multiples of 360.0 until the */ /* result is >= 0.0 and < 360.0 */ /******************************************************************/ #define INV360 ( 1.0 / 360.0 ) double revolution( double x ) /*****************************************/ /* Reduce angle to within 0..360 degrees */ /*****************************************/ { return( x - 360.0 * floor( x * INV360 ) ); } /* revolution */ double rev180( double x ) /*********************************************/ /* Reduce angle to within +180..+180 degrees */ /*********************************************/ { return( x - 360.0 * floor( x * INV360 + 0.5 ) ); } /* revolution */ /*******************************************************************/ /* This function computes GMST0, the Greenwich Mean Sidereal Time */ /* at 0h UT (i.e. the sidereal time at the Greenwhich meridian at */ /* 0h UT). GMST is then the sidereal time at Greenwich at any */ /* time of the day. I've generalized GMST0 as well, and define it */ /* as: GMST0 = GMST - UT -- this allows GMST0 to be computed at */ /* other times than 0h UT as well. While this sounds somewhat */ /* contradictory, it is very practical: instead of computing */ /* GMST like: */ /* */ /* GMST = (GMST0) + UT * (366.2422/365.2422) */ /* */ /* where (GMST0) is the GMST last time UT was 0 hours, one simply */ /* computes: */ /* */ /* GMST = GMST0 + UT */ /* */ /* where GMST0 is the GMST "at 0h UT" but at the current moment! */ /* Defined in this way, GMST0 will increase with about 4 min a */ /* day. It also happens that GMST0 (in degrees, 1 hr = 15 degr) */ /* is equal to the Sun's mean longitude plus/minus 180 degrees! */ /* (if we neglect aberration, which amounts to 20 seconds of arc */ /* or 1.33 seconds of time) */ /* */ /*******************************************************************/ double GMST0( double d ) { double sidtim0; /* Sidtime at 0h UT = L (Sun's mean longitude) + 180.0 degr */ /* L = M + w, as defined in sunpos(). Since I'm too lazy to */ /* add these numbers, I'll let the C compiler do it for me. */ /* Any decent C compiler will add the constants at compile */ /* time, imposing no runtime or code overhead. */ sidtim0 = revolution( ( 180.0 + 356.0470 + 282.9404 ) + ( 0.9856002585 + 4.70935E-5 ) * d ); return sidtim0; } /* GMST0 */
the_stack_data/14199201.c
#include <stdlib.h> #define mask 0xffff0000L #define value 0xabcd0000L long foo (long x) { if ((x & mask) == value) return x & 0xffffL; return 1; } int main (void) { if (foo (value) != 0 || foo (0) != 1) abort (); exit (0); }
the_stack_data/121437.c
#include <stdio.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <stdlib.h> #include <string.h> #define SIZE 1024 char buf[SIZE]; #define PORT 13000 int main(int argc, char *argv[]) { int sockfd; int nread; struct sockaddr_in serv_addr; if (argc != 2) { fprintf(stderr, "usage: %s IPaddr\n", argv[0]); exit(1); } /* Read a line from stdin, open a connection, send the line and then close the connection */ while (fgets(buf, SIZE , stdin) != NULL) { /* create endpoint */ if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) { perror(NULL); exit(2); } /* connect to server */ serv_addr.sin_family = AF_INET; serv_addr.sin_addr.s_addr = inet_addr(argv[1]); serv_addr.sin_port = htons(PORT); while (connect(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) { /* allow for timesouts etc */ perror(NULL); sleep(1); } printf("%s", buf); nread = strlen(buf); /* transfer data and quit */ write(sockfd, buf, nread); close(sockfd); } }
the_stack_data/106371.c
#include <stdio.h> #include <stdlib.h> #include <string.h> int foo(char *arg) { char buf[400]; snprintf(buf, sizeof buf, arg); return 0; } int main(int argc, char *argv[]) { if (argc != 2) { fprintf(stderr, "target4: argc != 2\n"); exit(EXIT_FAILURE); } foo(argv[1]); return 0; }
the_stack_data/90766129.c
/////////////////////////////////////////////////////////// // // Function Name : Frequency() // Input : Integer // Output : Integer // Description : Accept Number From User & Find The Last Occurance Of The Element // Author : Prasad Dangare // Date : 17 Mar 2021 // /////////////////////////////////////////////////////////// #include <stdio.h> #include <stdlib.h> int Frequency(int Arr[], int iLength, int iValue) { int i = 0; for(i = iLength-1; i >= 0; i--) { if(Arr[i] == iValue) { break; } } return i; } int main() { int * arr = NULL; int i = 0, iSize = 0, iRet = 0, iNo = 0; printf("Enter Number Of Elements : "); scanf("%d", &iSize); arr = (int*)malloc(iSize * sizeof(int)); printf("Enter The Elements : \n"); for(i = 0; i < iSize; i++) { scanf("%d", &arr[i]); } printf("Enter the Elements you want to search : "); scanf("%d", &iNo); iRet = Frequency(arr, iSize, iNo); if(iRet == -1) { printf("Number Not Found"); } else { printf("last Occurance is at : %d\n", iRet); } free(arr); return 0; }
the_stack_data/29186.c
#include <stdio.h> int main (int argc, char** argv) { int a = 1000; if (fork()) { a /= 2; printf("\n1. Value of a = %d", a); } else { if (fork()) { a *= 2; printf("\n2. Value of a = %d", a); if (execl("ls", "ls", "-l", 0) == -1) { a = a + 2; printf("\n2.1. Value of a = %d", a); } } else { a +=2 ; printf("\n3.Value of a = %d", a); } } a++; printf("\nEnd: Value of a = %d", a); }
the_stack_data/43697.c
/* * This program sends messages to a server over TCP. * The program takes two arguments. * The first argument is the ip address of the server. * The second argument is the port of the server. * To exit the program write quit. */ #include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <netdb.h> #include <unistd.h> #include <string.h> #define MAX_INPUT 255 int main(int argc, char *argv[]) { if (argc != 3) { fprintf(stderr,"usage: %s <receiver ip> <reciver port>\n",argv[0]); exit(1); } int sockfd, err, sendBytes; struct addrinfo hints, *servInfo, *p; char sendBuf[MAX_INPUT]; memset(&hints,0,sizeof(hints)); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; if ((err = getaddrinfo(argv[1],argv[2],&hints,&servInfo)) < 0) { fprintf(stderr,"getaddrinfo: %s\n",gai_strerror(err)); exit(1); } for (p = servInfo; p != NULL; p = p->ai_next) { if ((sockfd = socket(p->ai_family,p->ai_socktype,p->ai_protocol)) < 0) { perror("socket"); continue; } if (connect(sockfd,p->ai_addr,p->ai_addrlen) < 0) { close(sockfd); perror("connect"); continue; } break; } freeaddrinfo(servInfo); if (p == NULL) { fprintf(stderr,"connect failed\n"); exit(1); } p = NULL; for (;;) { memset(sendBuf,0,MAX_INPUT); if (fgets(sendBuf,MAX_INPUT,stdin) == NULL) { fprintf(stderr,"Read interrupted.\n"); } if (strncmp(sendBuf,"quit",4) == 0) { break; } if ((sendBytes = send(sockfd,sendBuf,strlen(sendBuf) + 1,0)) < 0) { perror("send"); } else { printf("Sendt message %s, which is %d bytes on socket %d.\n",sendBuf,sendBytes,sockfd); } } printf("Ends the program.\n"); close(sockfd); exit(0); }
the_stack_data/991207.c
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_striteri.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: gmorer <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2015/12/02 11:57:35 by gmorer #+# #+# */ /* Updated: 2016/01/04 16:20:13 by gmorer ### ########.fr */ /* */ /* ************************************************************************** */ void ft_striteri(char *s, void (*f)(unsigned int, char *)) { int unsigned i; i = 0; if (s && *s && f && *f) { while (*s) { f(i++, s++); } } }
the_stack_data/123964.c
//--------------------------------------------------------------------- // sorted_snackbar.c // CS223 - Spring 2022 // Ask the user for a list of snacks and store them in alphabetical order // Name: // #include <stdio.h> #include <stdlib.h> #include <string.h> struct snack { char name[32]; int quantity; float cost; struct snack* next; }; // Insert a new node to a list (implemented as a linked list). // The new node should store the given properties // Param snacks: the first item in the list (NULL if empty) // Param name: the snack name (max length is 32 characters) // Param quantity: the snack quantity // Param cost: the snack cost // Returns the first item in the list struct snack* insert_sorted(struct snack* snacks, const char* name, int quantity, float cost) { // todo return NULL; } // Delete (e.g. free) all nodes in the given list of snacks // Param snacks: the first node in the list (NULL if empty) void clear(struct snack* snacks) { } int main() { return 0; }
the_stack_data/84497.c
#include <stdlib.h> #include <stdio.h> #include <dlfcn.h> typedef int (*main_t)(int, char **, char **); int main(int argc, char **argv, char **envp) { char *error = NULL; setbuf(stdout, NULL); setbuf(stderr, NULL); if (argc < 2) { fprintf(stderr, "USAGE: %s PROGRAM\nWhere PROGRAM is the user's program to supervise\n", argv[0]); return EXIT_FAILURE; } void *userhandle = dlopen(argv[1], RTLD_LAZY); if (userhandle == NULL) { fprintf(stderr, "%s: %s\n", argv[0], dlerror()); return EXIT_FAILURE; } dlerror(); main_t usermain = dlsym(userhandle, "main"); if ((error = dlerror()) != NULL) { fprintf(stderr, "%s: %s\n", argv[0], error); return EXIT_FAILURE; } /* Call Users main, but make master.c invisible by removing first argument */ return usermain(argc-1, argv+1, envp); }
the_stack_data/192329844.c
#include <sys/socket.h> #include <sys/types.h> #include <arpa/inet.h> #include <netinet/in.h> #include <stdio.h> #include <unistd.h> #include <string.h> #include <stdlib.h> #define MAX_MSG 1024 /* Experimento 01 Servidor aguarda por mensagem do cliente, imprime na tela e depois envia resposta. Quando o cliente enviar "fim" a conexão é finalizada. */ int main(void) { //Variáveis int socket_desc, conexao, c; struct sockaddr_in servidor, cliente; char *mensagem; char resposta[MAX_MSG]; int tamanho, count; //Para pegar o IP e porta do cliente char *cliente_ip; int cliente_port; //Criando um socket socket_desc = socket(AF_INET, SOCK_STREAM, 0); if (socket_desc == -1) { printf("Nao foi possivel criar o socket\n"); return -1; } int reuso = 1; if (setsockopt(socket_desc, SOL_SOCKET, SO_REUSEADDR, (const char *)&reuso, sizeof(reuso)) < 0) { perror("Não foi possível reusar endereço"); return -1; } #ifdef SO_REUSEPORT if (setsockopt(socket_desc, SOL_SOCKET, SO_REUSEPORT, (const char *)&reuso, sizeof(reuso)) < 0) { perror("Não foi possível reusar porta"); return -1; } #endif //Preparando a struct do socket servidor.sin_family = AF_INET; servidor.sin_addr.s_addr = INADDR_ANY; // Obtem IP do S.O. servidor.sin_port = htons(1234); //Associando o socket a porta e endereco if (bind(socket_desc, (struct sockaddr *)&servidor, sizeof(servidor)) < 0) { perror("Erro ao fazer bind\n"); return -1; } puts("Bind efetuado com sucesso\n"); //Ouvindo por conexoes listen(socket_desc, 3); //Aceitando e tratando conexoes puts("Aguardando por conexoes..."); c = sizeof(struct sockaddr_in); //Iniciando conexão conexao = accept(socket_desc, (struct sockaddr *)&cliente, (socklen_t *)&c); if (conexao < 0) { perror("Erro ao receber conexao\n"); return -1; } cliente_ip = inet_ntoa(cliente.sin_addr); cliente_port = ntohs(cliente.sin_port); printf("cliente conectou\nIP:PORTA -> %s:%d\n", cliente_ip, cliente_port); mensagem = "Seja bem-vindo cliente!"; write(conexao, mensagem, strlen(mensagem)); int k = 0; do{ if (conexao < 0) { perror("Erro ao receber conexao\n"); return -1; } // lendo dados enviados pelo cliente tamanho = read(conexao, resposta, MAX_MSG); if (tamanho < 0) { perror("Erro ao receber dados do cliente: "); return -1; } resposta[tamanho] = '\0'; int x = strcmp(resposta, "fim"); if(x == 0){ mensagem = "Encerrando conexão"; write(conexao, mensagem, strlen(mensagem)); printf("Cliente encerrou a conexão!\n"); k = 1; } else{ printf("O cliente falou: %s\n", resposta); mensagem = "Recebi sua mensagem!"; write(conexao, mensagem, strlen(mensagem)); } }while(k<1); //Finalizando conexão close(socket_desc); shutdown(socket_desc, 2); printf("Servidor finalizado...\n"); return 0; }
the_stack_data/65259.c
/**************************************************************************/ /*! @file board_lpcexpresso1347.c @author hathach (tinyusb.org) @section LICENSE Software License Agreement (BSD License) Copyright (c) 2013, hathach (tinyusb.org) All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holders nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT INCLUDING NEGLIGENCE OR OTHERWISE ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. This file is part of the tinyusb stack. */ /**************************************************************************/ #ifdef BOARD_LPCXPRESSO1347 #include "../board.h" #define LED_PORT 0 #define LED_PIN 7 static const struct { uint8_t port; uint8_t pin; } buttons[] = { {1, 22 }, // Joystick up {1, 20 }, // Joystick down {1, 23 }, // Joystick left {1, 21 }, // Joystick right {1, 19 }, // Joystick press {0, 1 }, // SW3 // {1, 4 }, // SW4 (require to remove J28) }; enum { BOARD_BUTTON_COUNT = sizeof(buttons) / sizeof(buttons[0]) }; /* System oscillator rate and RTC oscillator rate */ const uint32_t OscRateIn = 12000000; const uint32_t ExtRateIn = 0; /* Pin muxing table, only items that need changing from their default pin state are in this table. */ static const PINMUX_GRP_T pinmuxing[] = { {0, 1, (IOCON_FUNC1 | IOCON_RESERVED_BIT_7 | IOCON_MODE_INACT)}, /* PIO0_1 used for CLKOUT */ {0, 2, (IOCON_FUNC1 | IOCON_RESERVED_BIT_7 | IOCON_MODE_PULLUP)}, /* PIO0_2 used for SSEL */ {0, 3, (IOCON_FUNC1 | IOCON_RESERVED_BIT_7 | IOCON_MODE_INACT)}, /* PIO0_3 used for USB_VBUS */ {0, 6, (IOCON_FUNC1 | IOCON_RESERVED_BIT_7 | IOCON_MODE_INACT)}, /* PIO0_6 used for USB_CONNECT */ {0, 8, (IOCON_FUNC1 | IOCON_RESERVED_BIT_7 | IOCON_MODE_INACT)}, /* PIO0_8 used for MISO0 */ {0, 9, (IOCON_FUNC1 | IOCON_RESERVED_BIT_7 | IOCON_MODE_INACT)}, /* PIO0_9 used for MOSI0 */ {0, 11, (IOCON_FUNC2 | IOCON_ADMODE_EN | IOCON_FILT_DIS)}, /* PIO0_11 used for AD0 */ {0, 18, (IOCON_FUNC1 | IOCON_RESERVED_BIT_7 | IOCON_MODE_INACT)}, /* PIO0_18 used for RXD */ {0, 19, (IOCON_FUNC1 | IOCON_RESERVED_BIT_7 | IOCON_MODE_INACT)}, /* PIO0_19 used for TXD */ {1, 29, (IOCON_FUNC1 | IOCON_RESERVED_BIT_7 | IOCON_MODE_INACT)}, /* PIO1_29 used for SCK0 */ }; // Invoked by startup code void SystemInit(void) { /* Enable IOCON clock */ Chip_Clock_EnablePeriphClock(SYSCTL_CLOCK_IOCON); Chip_IOCON_SetPinMuxing(LPC_IOCON, pinmuxing, sizeof(pinmuxing) / sizeof(PINMUX_GRP_T)); Chip_SetupXtalClocking(); } void board_init(void) { SystemCoreClockUpdate(); #if CFG_TUSB_OS == OPT_OS_NONE SysTick_Config(SystemCoreClock / BOARD_TICKS_HZ); // 1 msec tick timer #endif Chip_GPIO_Init(LPC_GPIO_PORT); //------------- LED -------------// Chip_GPIO_SetPinDIROutput(LPC_GPIO_PORT, LED_PORT, LED_PIN); //------------- BUTTON -------------// // for(uint8_t i=0; i<BOARD_BUTTON_COUNT; i++) GPIOSetDir(buttons[i].port, TU_BIT(buttons[i].pin), 0); //------------- UART -------------// //UARTInit(CFG_UART_BAUDRATE); // USB Chip_USB_Init(); // Setup PLL clock, and power } /*------------------------------------------------------------------*/ /* TUSB HAL MILLISECOND *------------------------------------------------------------------*/ #if CFG_TUSB_OS == OPT_OS_NONE volatile uint32_t system_ticks = 0; void SysTick_Handler (void) { system_ticks++; } uint32_t tusb_hal_millis(void) { return board_tick2ms(system_ticks); } #endif //--------------------------------------------------------------------+ // LEDS //--------------------------------------------------------------------+ void board_led_control(bool state) { Chip_GPIO_SetPinState(LPC_GPIO_PORT, LED_PORT, LED_PIN, state); } //--------------------------------------------------------------------+ // BUTTONS //--------------------------------------------------------------------+ #if 0 static bool button_read(uint8_t id) { (void) id; // return !GPIOGetPinValue(buttons[id].port, buttons[id].pin); // button is active low return 0; } #endif uint32_t board_buttons(void) { uint32_t result = 0; // for(uint8_t i=0; i<BOARD_BUTTON_COUNT; i++) result |= (button_read(i) ? TU_BIT(i) : 0); return result; } //--------------------------------------------------------------------+ // UART //--------------------------------------------------------------------+ void board_uart_putchar(uint8_t c) { (void) c; // UARTSend(&c, 1); } uint8_t board_uart_getchar(void) { return 0; } #endif
the_stack_data/878734.c
/* ** Extract a range of bytes from a file. ** ** Usage: ** ** extract FILENAME OFFSET AMOUNT ** ** The bytes are written to standard output. */ #include <stdio.h> #include <stdlib.h> int main(int argc, char **argv){ FILE *f; char *zBuf; int ofst; int n; size_t got; if( argc!=4 ){ fprintf(stderr, "Usage: %s FILENAME OFFSET AMOUNT\n", *argv); return 1; } f = fopen(argv[1], "rb"); if( f==0 ){ fprintf(stderr, "cannot open \"%s\"\n", argv[1]); return 1; } ofst = atoi(argv[2]); n = atoi(argv[3]); zBuf = malloc( n ); if( zBuf==0 ){ fprintf(stderr, "out of memory\n"); return 1; } fseek(f, ofst, SEEK_SET); got = fread(zBuf, 1, n, f); fclose(f); if( got<n ){ fprintf(stderr, "got only %d of %d bytes\n", got, n); return 1; }else{ fwrite(zBuf, 1, n, stdout); } return 0; }
the_stack_data/165767374.c
#include <ctype.h> #include <stdio.h> /* * Exercise: 2 * Page: 155 * Write a program that will print arbitrary input in a sensible way. As a * minimum, it should print non-graphic characters in octal or hexadecimal * according to local custom, and break long text lines. * */ #define WIDTH 40 int main(void) { int c; int i = 0; while ((c = getchar()) != EOF) { if (isgraph(c) || isspace(c)) { (void)putchar(c); } else { printf("0X%x", (unsigned int)c); } if (c == (int)'\n') { i = 0; } else { i++; if (i % WIDTH == 0) { (void)putchar('\n'); } } } return 0; }
the_stack_data/117327643.c
// RUN: clang %loadLLOV %s -o /dev/null 2>&1 | FileCheck %s #include <omp.h> #define M 20 #define N 20 int main() { double A[M][N], C[M][N], alpha = 0.5, beta = 0.3; #pragma omp parallel for for (int i = 0; i < M; i++) { for (int j = 0; j <= i; j++) C[i][j] *= beta; for (int k = 0; k < N; k++) { for (int j = 0; j <= i; j++) C[i][j] += alpha * A[i][k] * A[j][k]; } } } // CHECK: Region is Data Race Free. // END
the_stack_data/203289.c
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_swap.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: soumanso <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/09/01 16:55:47 by soumanso #+# #+# */ /* Updated: 2021/09/01 16:56:24 by soumanso ### ########lyon.fr */ /* */ /* ************************************************************************** */ void ft_swap(int *a, int *b) { int temp; temp = *a; *a = *b; *b = temp; }
the_stack_data/72012400.c
#include <stdio.h> #include <math.h> #define PI 3.1415 int main(){ float raio, volume; printf("Qual o raio da esfera? "); scanf("%f", &raio); volume = ((float)4/3) * PI * pow(raio, 3); printf("O volume da esfera é: %.2f", volume); return 0; }
the_stack_data/12957.c
#include <limits.h> #include <stdbool.h> #include <stdio.h> int maxSubArraySum(int a[], int size) { int current_sum=0; int best_sum=0; for(int i=0;i<size;i++) { current_sum+=a[i]; //i will store maximum sum in the best_sum if(best_sum<current_sum) best_sum=current_sum; //if added no. make current_sum<0 then i make current_sum=0 again if(current_sum<0) current_sum=0; } return best_sum; } int main() { int n; printf("enter the number of elements in the array"); scanf("%d",&n); int a[n+1]; printf("enter the elements in the array"); for(int i=0;i<n;i++) { scanf("%d",&a[i]); } int max_sum = maxSubArraySum(a, n); printf("Maximum contiguous sum is %d",max_sum); return 0; }
the_stack_data/51699065.c
void printf(); struct num { short mantissa; short exponent; }; typedef int mynum; typedef struct numm { mynum mantissaa; short exponentt; } xxx; struct nummm { mynum mantissaaa; short exponenttt; } v; typedef struct nummm nummmmm; typedef union q1 { short qa; short qb; } q2; typedef union q3 { short qaa; short qbb; } q4; typedef union q6 q7; mynum main () { printf(""); }
the_stack_data/68887357.c
/* Copyright (c) 2020 SoulHarsh007 (Harsh Peshwani) * Contact: [email protected] or [email protected] * GitHub: https://github.com/SoulHarsh007/ */ #include <stdio.h> int main() { float c; printf("Input value in Centigrade: "); scanf("%f", &c); printf("Value in Fahrenheit is: %.2f\n", ((1.8 * c) + 32)); return 0; }
the_stack_data/5554.c
// KASAN: use-after-free Read in rtl_fw_do_work // https://syzkaller.appspot.com/bug?id=ff4b26b0bfbff2dc7960 // 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 <setjmp.h> #include <signal.h> #include <stdarg.h> #include <stdbool.h> #include <stddef.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/mount.h> #include <sys/prctl.h> #include <sys/stat.h> #include <sys/syscall.h> #include <sys/types.h> #include <sys/wait.h> #include <time.h> #include <unistd.h> #include <linux/usb/ch9.h> static unsigned long long procid; static __thread int skip_segv; static __thread jmp_buf segv_env; static void segv_handler(int sig, siginfo_t* info, void* ctx) { uintptr_t addr = (uintptr_t)info->si_addr; const uintptr_t prog_start = 1 << 20; const uintptr_t prog_end = 100 << 20; int skip = __atomic_load_n(&skip_segv, __ATOMIC_RELAXED) != 0; int valid = addr < prog_start || addr > prog_end; if (skip && valid) { _longjmp(segv_env, 1); } exit(sig); } static void install_segv_handler(void) { 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 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 bool write_file(const char* file, const char* what, ...) { char buf[1024]; va_list args; va_start(args, what); vsnprintf(buf, sizeof(buf), what, args); va_end(args); buf[sizeof(buf) - 1] = 0; int len = strlen(buf); int fd = open(file, O_WRONLY | O_CLOEXEC); if (fd == -1) return false; if (write(fd, buf, len) != len) { int err = errno; close(fd); errno = err; return false; } close(fd); return true; } #define MAX_FDS 30 #define USB_MAX_IFACE_NUM 4 #define USB_MAX_EP_NUM 32 #define USB_MAX_FDS 6 struct usb_endpoint_index { struct usb_endpoint_descriptor desc; int handle; }; struct usb_iface_index { struct usb_interface_descriptor* iface; uint8_t bInterfaceNumber; uint8_t bAlternateSetting; uint8_t bInterfaceClass; struct usb_endpoint_index eps[USB_MAX_EP_NUM]; int eps_num; }; struct usb_device_index { struct usb_device_descriptor* dev; struct usb_config_descriptor* config; uint8_t bDeviceClass; uint8_t bMaxPower; int config_length; struct usb_iface_index ifaces[USB_MAX_IFACE_NUM]; int ifaces_num; int iface_cur; }; struct usb_info { int fd; struct usb_device_index index; }; static struct usb_info usb_devices[USB_MAX_FDS]; static int usb_devices_num; static bool parse_usb_descriptor(const char* buffer, size_t length, struct usb_device_index* index) { if (length < sizeof(*index->dev) + sizeof(*index->config)) return false; memset(index, 0, sizeof(*index)); index->dev = (struct usb_device_descriptor*)buffer; index->config = (struct usb_config_descriptor*)(buffer + sizeof(*index->dev)); index->bDeviceClass = index->dev->bDeviceClass; index->bMaxPower = index->config->bMaxPower; index->config_length = length - sizeof(*index->dev); index->iface_cur = -1; size_t offset = 0; while (true) { if (offset + 1 >= length) break; uint8_t desc_length = buffer[offset]; uint8_t desc_type = buffer[offset + 1]; if (desc_length <= 2) break; if (offset + desc_length > length) break; if (desc_type == USB_DT_INTERFACE && index->ifaces_num < USB_MAX_IFACE_NUM) { struct usb_interface_descriptor* iface = (struct usb_interface_descriptor*)(buffer + offset); index->ifaces[index->ifaces_num].iface = iface; index->ifaces[index->ifaces_num].bInterfaceNumber = iface->bInterfaceNumber; index->ifaces[index->ifaces_num].bAlternateSetting = iface->bAlternateSetting; index->ifaces[index->ifaces_num].bInterfaceClass = iface->bInterfaceClass; index->ifaces_num++; } if (desc_type == USB_DT_ENDPOINT && index->ifaces_num > 0) { struct usb_iface_index* iface = &index->ifaces[index->ifaces_num - 1]; if (iface->eps_num < USB_MAX_EP_NUM) { memcpy(&iface->eps[iface->eps_num].desc, buffer + offset, sizeof(iface->eps[iface->eps_num].desc)); iface->eps_num++; } } offset += desc_length; } return true; } static struct usb_device_index* add_usb_index(int fd, const char* dev, size_t dev_len) { int i = __atomic_fetch_add(&usb_devices_num, 1, __ATOMIC_RELAXED); if (i >= USB_MAX_FDS) return NULL; if (!parse_usb_descriptor(dev, dev_len, &usb_devices[i].index)) return NULL; __atomic_store_n(&usb_devices[i].fd, fd, __ATOMIC_RELEASE); return &usb_devices[i].index; } static struct usb_device_index* lookup_usb_index(int fd) { for (int i = 0; i < USB_MAX_FDS; i++) { if (__atomic_load_n(&usb_devices[i].fd, __ATOMIC_ACQUIRE) == fd) { return &usb_devices[i].index; } } return NULL; } struct vusb_connect_string_descriptor { uint32_t len; char* str; } __attribute__((packed)); struct vusb_connect_descriptors { uint32_t qual_len; char* qual; uint32_t bos_len; char* bos; uint32_t strs_len; struct vusb_connect_string_descriptor strs[0]; } __attribute__((packed)); static const char default_string[] = {8, USB_DT_STRING, 's', 0, 'y', 0, 'z', 0}; static const char default_lang_id[] = {4, USB_DT_STRING, 0x09, 0x04}; static bool lookup_connect_response_in(int fd, const struct vusb_connect_descriptors* descs, const struct usb_ctrlrequest* ctrl, char** response_data, uint32_t* response_length) { struct usb_device_index* index = lookup_usb_index(fd); uint8_t str_idx; if (!index) return false; switch (ctrl->bRequestType & USB_TYPE_MASK) { case USB_TYPE_STANDARD: switch (ctrl->bRequest) { case USB_REQ_GET_DESCRIPTOR: switch (ctrl->wValue >> 8) { case USB_DT_DEVICE: *response_data = (char*)index->dev; *response_length = sizeof(*index->dev); return true; case USB_DT_CONFIG: *response_data = (char*)index->config; *response_length = index->config_length; return true; case USB_DT_STRING: str_idx = (uint8_t)ctrl->wValue; if (descs && str_idx < descs->strs_len) { *response_data = descs->strs[str_idx].str; *response_length = descs->strs[str_idx].len; return true; } if (str_idx == 0) { *response_data = (char*)&default_lang_id[0]; *response_length = default_lang_id[0]; return true; } *response_data = (char*)&default_string[0]; *response_length = default_string[0]; return true; case USB_DT_BOS: *response_data = descs->bos; *response_length = descs->bos_len; return true; case USB_DT_DEVICE_QUALIFIER: if (!descs->qual) { struct usb_qualifier_descriptor* qual = (struct usb_qualifier_descriptor*)response_data; qual->bLength = sizeof(*qual); qual->bDescriptorType = USB_DT_DEVICE_QUALIFIER; qual->bcdUSB = index->dev->bcdUSB; qual->bDeviceClass = index->dev->bDeviceClass; qual->bDeviceSubClass = index->dev->bDeviceSubClass; qual->bDeviceProtocol = index->dev->bDeviceProtocol; qual->bMaxPacketSize0 = index->dev->bMaxPacketSize0; qual->bNumConfigurations = index->dev->bNumConfigurations; qual->bRESERVED = 0; *response_length = sizeof(*qual); return true; } *response_data = descs->qual; *response_length = descs->qual_len; return true; default: break; } break; default: break; } break; default: break; } return false; } typedef bool (*lookup_connect_out_response_t)( int fd, const struct vusb_connect_descriptors* descs, const struct usb_ctrlrequest* ctrl, bool* done); static bool lookup_connect_response_out_generic( int fd, const struct vusb_connect_descriptors* descs, const struct usb_ctrlrequest* ctrl, bool* done) { switch (ctrl->bRequestType & USB_TYPE_MASK) { case USB_TYPE_STANDARD: switch (ctrl->bRequest) { case USB_REQ_SET_CONFIGURATION: *done = true; return true; default: break; } break; } return false; } struct vusb_descriptor { uint8_t req_type; uint8_t desc_type; uint32_t len; char data[0]; } __attribute__((packed)); struct vusb_descriptors { uint32_t len; struct vusb_descriptor* generic; struct vusb_descriptor* descs[0]; } __attribute__((packed)); struct vusb_response { uint8_t type; uint8_t req; uint32_t len; char data[0]; } __attribute__((packed)); struct vusb_responses { uint32_t len; struct vusb_response* generic; struct vusb_response* resps[0]; } __attribute__((packed)); static bool lookup_control_response(const struct vusb_descriptors* descs, const struct vusb_responses* resps, struct usb_ctrlrequest* ctrl, char** response_data, uint32_t* response_length) { int descs_num = 0; int resps_num = 0; if (descs) descs_num = (descs->len - offsetof(struct vusb_descriptors, descs)) / sizeof(descs->descs[0]); if (resps) resps_num = (resps->len - offsetof(struct vusb_responses, resps)) / sizeof(resps->resps[0]); uint8_t req = ctrl->bRequest; uint8_t req_type = ctrl->bRequestType & USB_TYPE_MASK; uint8_t desc_type = ctrl->wValue >> 8; if (req == USB_REQ_GET_DESCRIPTOR) { int i; for (i = 0; i < descs_num; i++) { struct vusb_descriptor* desc = descs->descs[i]; if (!desc) continue; if (desc->req_type == req_type && desc->desc_type == desc_type) { *response_length = desc->len; if (*response_length != 0) *response_data = &desc->data[0]; else *response_data = NULL; return true; } } if (descs && descs->generic) { *response_data = &descs->generic->data[0]; *response_length = descs->generic->len; return true; } } else { int i; for (i = 0; i < resps_num; i++) { struct vusb_response* resp = resps->resps[i]; if (!resp) continue; if (resp->type == req_type && resp->req == req) { *response_length = resp->len; if (*response_length != 0) *response_data = &resp->data[0]; else *response_data = NULL; return true; } } if (resps && resps->generic) { *response_data = &resps->generic->data[0]; *response_length = resps->generic->len; return true; } } return false; } #define UDC_NAME_LENGTH_MAX 128 struct usb_raw_init { __u8 driver_name[UDC_NAME_LENGTH_MAX]; __u8 device_name[UDC_NAME_LENGTH_MAX]; __u8 speed; }; enum usb_raw_event_type { USB_RAW_EVENT_INVALID = 0, USB_RAW_EVENT_CONNECT = 1, USB_RAW_EVENT_CONTROL = 2, }; struct usb_raw_event { __u32 type; __u32 length; __u8 data[0]; }; struct usb_raw_ep_io { __u16 ep; __u16 flags; __u32 length; __u8 data[0]; }; #define USB_RAW_EPS_NUM_MAX 30 #define USB_RAW_EP_NAME_MAX 16 #define USB_RAW_EP_ADDR_ANY 0xff struct usb_raw_ep_caps { __u32 type_control : 1; __u32 type_iso : 1; __u32 type_bulk : 1; __u32 type_int : 1; __u32 dir_in : 1; __u32 dir_out : 1; }; struct usb_raw_ep_limits { __u16 maxpacket_limit; __u16 max_streams; __u32 reserved; }; struct usb_raw_ep_info { __u8 name[USB_RAW_EP_NAME_MAX]; __u32 addr; struct usb_raw_ep_caps caps; struct usb_raw_ep_limits limits; }; struct usb_raw_eps_info { struct usb_raw_ep_info eps[USB_RAW_EPS_NUM_MAX]; }; #define USB_RAW_IOCTL_INIT _IOW('U', 0, struct usb_raw_init) #define USB_RAW_IOCTL_RUN _IO('U', 1) #define USB_RAW_IOCTL_EVENT_FETCH _IOR('U', 2, struct usb_raw_event) #define USB_RAW_IOCTL_EP0_WRITE _IOW('U', 3, struct usb_raw_ep_io) #define USB_RAW_IOCTL_EP0_READ _IOWR('U', 4, struct usb_raw_ep_io) #define USB_RAW_IOCTL_EP_ENABLE _IOW('U', 5, struct usb_endpoint_descriptor) #define USB_RAW_IOCTL_EP_DISABLE _IOW('U', 6, __u32) #define USB_RAW_IOCTL_EP_WRITE _IOW('U', 7, struct usb_raw_ep_io) #define USB_RAW_IOCTL_EP_READ _IOWR('U', 8, struct usb_raw_ep_io) #define USB_RAW_IOCTL_CONFIGURE _IO('U', 9) #define USB_RAW_IOCTL_VBUS_DRAW _IOW('U', 10, __u32) #define USB_RAW_IOCTL_EPS_INFO _IOR('U', 11, struct usb_raw_eps_info) #define USB_RAW_IOCTL_EP0_STALL _IO('U', 12) #define USB_RAW_IOCTL_EP_SET_HALT _IOW('U', 13, __u32) #define USB_RAW_IOCTL_EP_CLEAR_HALT _IOW('U', 14, __u32) #define USB_RAW_IOCTL_EP_SET_WEDGE _IOW('U', 15, __u32) static int usb_raw_open() { return open("/dev/raw-gadget", O_RDWR); } static int usb_raw_init(int fd, uint32_t speed, const char* driver, const char* device) { struct usb_raw_init arg; strncpy((char*)&arg.driver_name[0], driver, sizeof(arg.driver_name)); strncpy((char*)&arg.device_name[0], device, sizeof(arg.device_name)); arg.speed = speed; return ioctl(fd, USB_RAW_IOCTL_INIT, &arg); } static int usb_raw_run(int fd) { return ioctl(fd, USB_RAW_IOCTL_RUN, 0); } static int usb_raw_event_fetch(int fd, struct usb_raw_event* event) { return ioctl(fd, USB_RAW_IOCTL_EVENT_FETCH, event); } static int usb_raw_ep0_write(int fd, struct usb_raw_ep_io* io) { return ioctl(fd, USB_RAW_IOCTL_EP0_WRITE, io); } static int usb_raw_ep0_read(int fd, struct usb_raw_ep_io* io) { return ioctl(fd, USB_RAW_IOCTL_EP0_READ, io); } static int usb_raw_ep_write(int fd, struct usb_raw_ep_io* io) { return ioctl(fd, USB_RAW_IOCTL_EP_WRITE, io); } static int usb_raw_ep_enable(int fd, struct usb_endpoint_descriptor* desc) { return ioctl(fd, USB_RAW_IOCTL_EP_ENABLE, desc); } static int usb_raw_ep_disable(int fd, int ep) { return ioctl(fd, USB_RAW_IOCTL_EP_DISABLE, ep); } static int usb_raw_configure(int fd) { return ioctl(fd, USB_RAW_IOCTL_CONFIGURE, 0); } static int usb_raw_vbus_draw(int fd, uint32_t power) { return ioctl(fd, USB_RAW_IOCTL_VBUS_DRAW, power); } static int usb_raw_ep0_stall(int fd) { return ioctl(fd, USB_RAW_IOCTL_EP0_STALL, 0); } static int lookup_interface(int fd, uint8_t bInterfaceNumber, uint8_t bAlternateSetting) { struct usb_device_index* index = lookup_usb_index(fd); if (!index) return -1; for (int i = 0; i < index->ifaces_num; i++) { if (index->ifaces[i].bInterfaceNumber == bInterfaceNumber && index->ifaces[i].bAlternateSetting == bAlternateSetting) return i; } return -1; } static int lookup_endpoint(int fd, uint8_t bEndpointAddress) { struct usb_device_index* index = lookup_usb_index(fd); if (!index) return -1; if (index->iface_cur < 0) return -1; for (int ep = 0; index->ifaces[index->iface_cur].eps_num; ep++) if (index->ifaces[index->iface_cur].eps[ep].desc.bEndpointAddress == bEndpointAddress) return index->ifaces[index->iface_cur].eps[ep].handle; return -1; } static void set_interface(int fd, int n) { struct usb_device_index* index = lookup_usb_index(fd); if (!index) return; if (index->iface_cur >= 0 && index->iface_cur < index->ifaces_num) { for (int ep = 0; ep < index->ifaces[index->iface_cur].eps_num; ep++) { int rv = usb_raw_ep_disable( fd, index->ifaces[index->iface_cur].eps[ep].handle); if (rv < 0) { } else { } } } if (n >= 0 && n < index->ifaces_num) { for (int ep = 0; ep < index->ifaces[n].eps_num; ep++) { int rv = usb_raw_ep_enable(fd, &index->ifaces[n].eps[ep].desc); if (rv < 0) { } else { index->ifaces[n].eps[ep].handle = rv; } } index->iface_cur = n; } } static int configure_device(int fd) { struct usb_device_index* index = lookup_usb_index(fd); if (!index) return -1; int rv = usb_raw_vbus_draw(fd, index->bMaxPower); if (rv < 0) { return rv; } rv = usb_raw_configure(fd); if (rv < 0) { return rv; } set_interface(fd, 0); return 0; } #define USB_MAX_PACKET_SIZE 4096 struct usb_raw_control_event { struct usb_raw_event inner; struct usb_ctrlrequest ctrl; char data[USB_MAX_PACKET_SIZE]; }; struct usb_raw_ep_io_data { struct usb_raw_ep_io inner; char data[USB_MAX_PACKET_SIZE]; }; static volatile long syz_usb_connect_impl(uint64_t speed, uint64_t dev_len, const char* dev, const struct vusb_connect_descriptors* descs, lookup_connect_out_response_t lookup_connect_response_out) { if (!dev) { return -1; } int fd = usb_raw_open(); if (fd < 0) { return fd; } if (fd >= MAX_FDS) { close(fd); return -1; } struct usb_device_index* index = add_usb_index(fd, dev, dev_len); if (!index) { return -1; } char device[32]; sprintf(&device[0], "dummy_udc.%llu", procid); int rv = usb_raw_init(fd, speed, "dummy_udc", &device[0]); if (rv < 0) { return rv; } rv = usb_raw_run(fd); if (rv < 0) { return rv; } bool done = false; while (!done) { struct usb_raw_control_event event; event.inner.type = 0; event.inner.length = sizeof(event.ctrl); rv = usb_raw_event_fetch(fd, (struct usb_raw_event*)&event); if (rv < 0) { return rv; } if (event.inner.type != USB_RAW_EVENT_CONTROL) continue; char* response_data = NULL; uint32_t response_length = 0; if (event.ctrl.bRequestType & USB_DIR_IN) { if (!lookup_connect_response_in(fd, descs, &event.ctrl, &response_data, &response_length)) { usb_raw_ep0_stall(fd); continue; } } else { if (!lookup_connect_response_out(fd, descs, &event.ctrl, &done)) { usb_raw_ep0_stall(fd); continue; } response_data = NULL; response_length = event.ctrl.wLength; } if ((event.ctrl.bRequestType & USB_TYPE_MASK) == USB_TYPE_STANDARD && event.ctrl.bRequest == USB_REQ_SET_CONFIGURATION) { rv = configure_device(fd); if (rv < 0) { return rv; } } struct usb_raw_ep_io_data response; response.inner.ep = 0; response.inner.flags = 0; if (response_length > sizeof(response.data)) response_length = 0; if (event.ctrl.wLength < response_length) response_length = event.ctrl.wLength; response.inner.length = response_length; if (response_data) memcpy(&response.data[0], response_data, response_length); else memset(&response.data[0], 0, response_length); if (event.ctrl.bRequestType & USB_DIR_IN) { rv = usb_raw_ep0_write(fd, (struct usb_raw_ep_io*)&response); } else { rv = usb_raw_ep0_read(fd, (struct usb_raw_ep_io*)&response); } if (rv < 0) { return rv; } } sleep_ms(200); return fd; } static volatile long syz_usb_connect(volatile long a0, volatile long a1, volatile long a2, volatile long a3) { uint64_t speed = a0; uint64_t dev_len = a1; const char* dev = (const char*)a2; const struct vusb_connect_descriptors* descs = (const struct vusb_connect_descriptors*)a3; return syz_usb_connect_impl(speed, dev_len, dev, descs, &lookup_connect_response_out_generic); } static volatile long syz_usb_control_io(volatile long a0, volatile long a1, volatile long a2) { int fd = a0; const struct vusb_descriptors* descs = (const struct vusb_descriptors*)a1; const struct vusb_responses* resps = (const struct vusb_responses*)a2; struct usb_raw_control_event event; event.inner.type = 0; event.inner.length = USB_MAX_PACKET_SIZE; int rv = usb_raw_event_fetch(fd, (struct usb_raw_event*)&event); if (rv < 0) { return rv; } if (event.inner.type != USB_RAW_EVENT_CONTROL) { return -1; } char* response_data = NULL; uint32_t response_length = 0; if ((event.ctrl.bRequestType & USB_DIR_IN) && event.ctrl.wLength) { if (!lookup_control_response(descs, resps, &event.ctrl, &response_data, &response_length)) { usb_raw_ep0_stall(fd); return -1; } } else { if ((event.ctrl.bRequestType & USB_TYPE_MASK) == USB_TYPE_STANDARD || event.ctrl.bRequest == USB_REQ_SET_INTERFACE) { int iface_num = event.ctrl.wIndex; int alt_set = event.ctrl.wValue; int iface_index = lookup_interface(fd, iface_num, alt_set); if (iface_index < 0) { } else { set_interface(fd, iface_index); } } response_length = event.ctrl.wLength; } struct usb_raw_ep_io_data response; response.inner.ep = 0; response.inner.flags = 0; if (response_length > sizeof(response.data)) response_length = 0; if (event.ctrl.wLength < response_length) response_length = event.ctrl.wLength; if ((event.ctrl.bRequestType & USB_DIR_IN) && !event.ctrl.wLength) { response_length = USB_MAX_PACKET_SIZE; } response.inner.length = response_length; if (response_data) memcpy(&response.data[0], response_data, response_length); else memset(&response.data[0], 0, response_length); if ((event.ctrl.bRequestType & USB_DIR_IN) && event.ctrl.wLength) { rv = usb_raw_ep0_write(fd, (struct usb_raw_ep_io*)&response); } else { rv = usb_raw_ep0_read(fd, (struct usb_raw_ep_io*)&response); } if (rv < 0) { return rv; } sleep_ms(200); return 0; } static volatile long syz_usb_ep_write(volatile long a0, volatile long a1, volatile long a2, volatile long a3) { int fd = a0; uint8_t ep = a1; uint32_t len = a2; char* data = (char*)a3; int ep_handle = lookup_endpoint(fd, ep); if (ep_handle < 0) { return -1; } struct usb_raw_ep_io_data io_data; io_data.inner.ep = ep_handle; io_data.inner.flags = 0; if (len > sizeof(io_data.data)) len = sizeof(io_data.data); io_data.inner.length = len; memcpy(&io_data.data[0], data, len); int rv = usb_raw_ep_write(fd, (struct usb_raw_ep_io*)&io_data); if (rv < 0) { return rv; } sleep_ms(200); return 0; } static long syz_open_dev(volatile long a0, volatile long a1, volatile long a2) { if (a0 == 0xc || a0 == 0xb) { char buf[128]; sprintf(buf, "/dev/%s/%d:%d", a0 == 0xc ? "char" : "block", (uint8_t)a1, (uint8_t)a2); return open(buf, O_RDWR, 0); } else { char buf[1024]; char* hash; strncpy(buf, (char*)a0, sizeof(buf) - 1); buf[sizeof(buf) - 1] = 0; while ((hash = strchr(buf, '#'))) { *hash = '0' + (char)(a1 % 10); a1 /= 10; } return open(buf, a2, 0); } } 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"); } 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_one(void) { intptr_t res = 0; NONFAILING(memcpy((void*)0x20000000, "\x12\x01\x00\x00\xa6\x6f\x1b\x40\xda\x0b\x7f\x31\xcc\x9d" "\x00\x00\x00\x01\x09\x02\x24\x00\x01\x00\x00\x00\x00\x09" "\x04\x00\x00\x02\xff\xff\xff\x00\x09\x05\x81\x00\x00\x00" "\x00\x00\x00\x09\x05\x0e\x00\x00\x00\x00\x00\x00\x32\x8f" "\xaf\xe4\x03\xc1\x1b\xae\x4a\x39\xae", 65)); res = -1; NONFAILING(res = syz_usb_connect(0, 0x36, 0x20000000, 0)); if (res != -1) r[0] = res; NONFAILING(*(uint32_t*)0x20001bc0 = 0x84); NONFAILING(*(uint64_t*)0x20001bc4 = 0x20000080); NONFAILING(*(uint8_t*)0x20000080 = 0); NONFAILING(*(uint8_t*)0x20000081 = 0); NONFAILING(*(uint32_t*)0x20000082 = 3); NONFAILING(memcpy((void*)0x20000086, "\x13\x74\xee", 3)); NONFAILING(*(uint64_t*)0x20001bcc = 0); NONFAILING(*(uint64_t*)0x20001bd4 = 0); NONFAILING(*(uint64_t*)0x20001bdc = 0); NONFAILING(*(uint64_t*)0x20001be4 = 0); NONFAILING(*(uint64_t*)0x20001bec = 0); NONFAILING(*(uint64_t*)0x20001bf4 = 0); NONFAILING(*(uint64_t*)0x20001bfc = 0); NONFAILING(*(uint64_t*)0x20001c04 = 0); NONFAILING(*(uint64_t*)0x20001c0c = 0); NONFAILING(*(uint64_t*)0x20001c14 = 0); NONFAILING(*(uint64_t*)0x20001c1c = 0); NONFAILING(*(uint64_t*)0x20001c24 = 0); NONFAILING(*(uint64_t*)0x20001c2c = 0); NONFAILING(*(uint64_t*)0x20001c34 = 0); NONFAILING(*(uint64_t*)0x20001c3c = 0); NONFAILING(syz_usb_control_io(r[0], 0, 0x20001bc0)); NONFAILING(*(uint32_t*)0x20000840 = 0x84); NONFAILING(*(uint64_t*)0x20000844 = 0x20000340); NONFAILING(*(uint8_t*)0x20000340 = 0); NONFAILING(*(uint8_t*)0x20000341 = 0); NONFAILING(*(uint32_t*)0x20000342 = 1); NONFAILING(memcpy((void*)0x20000346, "\x98", 1)); NONFAILING(*(uint64_t*)0x2000084c = 0); NONFAILING(*(uint64_t*)0x20000854 = 0); NONFAILING(*(uint64_t*)0x2000085c = 0); NONFAILING(*(uint64_t*)0x20000864 = 0); NONFAILING(*(uint64_t*)0x2000086c = 0); NONFAILING(*(uint64_t*)0x20000874 = 0); NONFAILING(*(uint64_t*)0x2000087c = 0); NONFAILING(*(uint64_t*)0x20000884 = 0); NONFAILING(*(uint64_t*)0x2000088c = 0); NONFAILING(*(uint64_t*)0x20000894 = 0); NONFAILING(*(uint64_t*)0x2000089c = 0); NONFAILING(*(uint64_t*)0x200008a4 = 0); NONFAILING(*(uint64_t*)0x200008ac = 0); NONFAILING(*(uint64_t*)0x200008b4 = 0); NONFAILING(*(uint64_t*)0x200008bc = 0); NONFAILING(syz_usb_control_io(r[0], 0, 0x20000840)); NONFAILING(*(uint32_t*)0x20001280 = 0x84); NONFAILING(*(uint64_t*)0x20001284 = 0x20000dc0); NONFAILING(*(uint8_t*)0x20000dc0 = 0); NONFAILING(*(uint8_t*)0x20000dc1 = 0); NONFAILING(*(uint32_t*)0x20000dc2 = 1); NONFAILING(memcpy((void*)0x20000dc6, "\xbb", 1)); NONFAILING(*(uint64_t*)0x2000128c = 0); NONFAILING(*(uint64_t*)0x20001294 = 0); NONFAILING(*(uint64_t*)0x2000129c = 0); NONFAILING(*(uint64_t*)0x200012a4 = 0); NONFAILING(*(uint64_t*)0x200012ac = 0); NONFAILING(*(uint64_t*)0x200012b4 = 0); NONFAILING(*(uint64_t*)0x200012bc = 0); NONFAILING(*(uint64_t*)0x200012c4 = 0); NONFAILING(*(uint64_t*)0x200012cc = 0); NONFAILING(*(uint64_t*)0x200012d4 = 0); NONFAILING(*(uint64_t*)0x200012dc = 0); NONFAILING(*(uint64_t*)0x200012e4 = 0); NONFAILING(*(uint64_t*)0x200012ec = 0); NONFAILING(*(uint64_t*)0x200012f4 = 0); NONFAILING(*(uint64_t*)0x200012fc = 0); NONFAILING(syz_usb_control_io(r[0], 0, 0x20001280)); NONFAILING(memcpy((void*)0x200000c0, "\x12\x01\xa8\x00\x11\xf7\x9e\x08\x07" "\x0a\xda\x00\x45\x8f\x00\x00\x00\x01" "\x09\x02\x24\x00\x01\x00\x00\x00", 26)); NONFAILING(*(uint64_t*)0x200000da = r[0]); NONFAILING(*(uint64_t*)0x200000e2 = r[0]); NONFAILING(syz_usb_connect(0, 0x36, 0x200000c0, 0)); res = -1; NONFAILING(res = syz_open_dev(0xc, 0xb4, 0)); if (res != -1) r[1] = res; syscall(__NR_write, r[1], 0ul, 0ul); NONFAILING(syz_usb_ep_write(-1, 0x82, 0x10, 0x20000000)); NONFAILING(memcpy((void*)0x20000100, "/dev/hidraw#\000", 13)); NONFAILING(syz_open_dev(0x20000100, 0, 0x641)); syscall(__NR_read, r[1], 0ul, 0ul); } 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); install_segv_handler(); for (procid = 0; procid < 6; procid++) { if (fork() == 0) { loop(); } } sleep(1000000); return 0; }
the_stack_data/72013788.c
/** \file * \brief Timer Utility Functions * \author Atmel Crypto Products * \date June 20, 2013 * \copyright Copyright (c) 2013 Atmel Corporation. All rights reserved. * * \atmel_crypto_device_library_license_start * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name of Atmel may not be used to endorse or promote products derived * from this software without specific prior written permission. * * 4. This software may only be redistributed and used in connection with an * Atmel integrated circuit. * * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * \atmel_crypto_device_library_license_stop */ #include <stdint.h> // data type definitions /** \defgroup timer_utilities Module 09: Timers * * This module implements timers used during communication. * They are implemented using loop counters. But if you have hardware * timers available, you can implement the functions using them. @{ */ // The values below are valid for an AVR 8-bit processor running at 16 MHz. // Code is compiled with optimization set to -O1. #if F_CPU == 16000000UL //! Fill the inner loop of delay_10us() with these CPU instructions to achieve 10 us per iteration. # define TIME_UTILS_US_CALIBRATION //__asm__ volatile ("\n\tnop\n\tnop\n\tnop\n") /** Decrement the inner loop of delay_10us() this many times to achieve 10 us per * iteration of the outer loop. */ # define TIME_UTILS_LOOP_COUNT ((uint8_t) 14) //! The delay_ms function calls delay_10us with this parameter. # define TIME_UTILS_MS_CALIBRATION ((uint8_t) 104) #elif F_CPU == 8000000UL //! Fill the inner loop of delay_10us() with these CPU instructions to achieve 10 us per iteration. # define TIME_UTILS_US_CALIBRATION __asm__ volatile ("\n\tnop\n\tnop\n\tnop\n\tnop\n") /** \brief Decrement the inner loop of delay_10us() this many times to achieve 10 us per * iteration of the outer loop. */ # define TIME_UTILS_LOOP_COUNT ((uint8_t) 0) //! The delay_ms function calls delay_10us with this parameter. # define TIME_UTILS_MS_CALIBRATION ((uint8_t) 100) #elif F_CPU == 2000000UL //! Fill the inner loop of delay_10us() with these CPU instructions to achieve 10 us per iteration. # define TIME_UTILS_US_CALIBRATION __asm__ volatile ("\n\tnop\n") /** \brief Decrement the inner loop of delay_10us() this many times to achieve 10 us per * iteration of the outer loop. */ # define TIME_UTILS_LOOP_COUNT ((uint8_t) 1) //! The delay_ms function calls delay_10us with this parameter. # define TIME_UTILS_MS_CALIBRATION ((uint8_t) 91) #elif CONFIG_SYSCLK_SOURCE == SYSCLK_SRC_RC32MHZ // Xmega //! Fill the inner loop of delay_10us() with these CPU instructions to achieve 10 us per iteration. # define TIME_UTILS_US_CALIBRATION //__asm__ volatile ("\n\tnop\n\tnop\n\tnop\n") /** \brief Decrement the inner loop of delay_10us() this many times to achieve 10 us per * iteration of the outer loop. */ # define TIME_UTILS_LOOP_COUNT ((uint8_t) 28) //! The delay_ms function calls delay_10us with this parameter. # define TIME_UTILS_MS_CALIBRATION ((uint8_t) 104) #else # error Time macros are not defined. #endif /** \brief This function delays for a number of tens of microseconds. * * This function will not time correctly, if one loop iteration * plus the time it takes to enter this function takes more than 10 us. * \param[in] delay number of 0.01 milliseconds to delay */ void delay_10us(uint8_t delay) { volatile uint8_t delay_10us; for (; delay > 0; delay--) { for (delay_10us = TIME_UTILS_LOOP_COUNT; delay_10us > 0; delay_10us--) ; TIME_UTILS_US_CALIBRATION; } } /** \brief This function delays for a number of milliseconds. * * You can override this function if you like to do * something else in your system while delaying. * \param[in] delay number of milliseconds to delay */ void delay_ms(uint8_t delay) { uint8_t i; for (i = delay; i > 0; i--) delay_10us(TIME_UTILS_MS_CALIBRATION); } /** @} */
the_stack_data/6387804.c
#if 0 mini_start mini_vexec mini_writes mini_waitpid INCLUDESRC SHRINKELF LDSCRIPT onlytext return #endif void usage(){ writes("Usage: su [-h] [options for kinit and ksu]\n" "Get root and keep the kerberos ticket.\n"); exit(1); } int main(int argc,char**argv,char**envp){ if ( argc>1 && argv[1][0]=='-' && argv[1][1]=='h' ) usage(); int r = vexec("/usr/bin/klist",argv,envp); int i = 0; while ( r ){ if ( i++ > 2 ) exit(1); r = vexec("/usr/bin/kinit",argv,envp); } execve("/usr/bin/ksu", argv, envp ); writes("Couldn't execute ksu.\n"); exit(1); }
the_stack_data/534388.c
#include <panel.h> typedef struct _PANEL_DATA { int x, y, w, h; char label[80]; int label_color; PANEL *next; }PANEL_DATA; #define NLINES 10 #define NCOLS 40 void init_wins(WINDOW **wins, int n); void win_show(WINDOW *win, char *label, int label_color); void print_in_middle(WINDOW *win, int starty, int startx, int width, char *string, chtype color); void set_user_ptrs(PANEL **panels, int n); int main() { WINDOW *my_wins[3]; PANEL *my_panels[3]; PANEL_DATA *top; PANEL *stack_top; WINDOW *temp_win, *old_win; int ch; int newx, newy, neww, newh; int size = FALSE, move = FALSE; /* Initialize curses */ initscr(); start_color(); cbreak(); noecho(); keypad(stdscr, TRUE); /* Initialize all the colors */ init_pair(1, COLOR_RED, COLOR_BLACK); init_pair(2, COLOR_GREEN, COLOR_BLACK); init_pair(3, COLOR_BLUE, COLOR_BLACK); init_pair(4, COLOR_CYAN, COLOR_BLACK); init_wins(my_wins, 3); /* Attach a panel to each window */ /* Order is bottom up */ my_panels[0] = new_panel(my_wins[0]); /* Push 0, order: stdscr-0 */ my_panels[1] = new_panel(my_wins[1]); /* Push 1, order: stdscr-0-1 */ my_panels[2] = new_panel(my_wins[2]); /* Push 2, order: stdscr-0-1-2 */ set_user_ptrs(my_panels, 3); /* Update the stacking order. 2nd panel will be on top */ update_panels(); /* Show it on the screen */ attron(COLOR_PAIR(4)); mvprintw(LINES - 3, 0, "Use 'm' for moving, 'r' for resizing"); mvprintw(LINES - 2, 0, "Use tab to browse through the windows (F1 to Exit)"); attroff(COLOR_PAIR(4)); doupdate(); stack_top = my_panels[2]; top = (PANEL_DATA *)panel_userptr(stack_top); newx = top->x; newy = top->y; neww = top->w; newh = top->h; while((ch = getch()) != KEY_F(1)) { switch(ch) { case 9: /* Tab */ top = (PANEL_DATA *)panel_userptr(stack_top); top_panel(top->next); stack_top = top->next; top = (PANEL_DATA *)panel_userptr(stack_top); newx = top->x; newy = top->y; neww = top->w; newh = top->h; break; case 'r': /* Re-Size*/ size = TRUE; attron(COLOR_PAIR(4)); mvprintw(LINES - 4, 0, "Entered Resizing: Use Arrow Keys to resize and press <ENTER> to end resizing"); refresh(); attroff(COLOR_PAIR(4)); break; case 'm': /* Move */ attron(COLOR_PAIR(4)); mvprintw(LINES - 4, 0, "Entered Moving: Use Arrow Keys to Move and press <ENTER> to end moving"); refresh(); attroff(COLOR_PAIR(4)); move = TRUE; break; case KEY_LEFT: if(size == TRUE) { --newx; ++neww; } if(move == TRUE) --newx; break; case KEY_RIGHT: if(size == TRUE) { ++newx; --neww; } if(move == TRUE) ++newx; break; case KEY_UP: if(size == TRUE) { --newy; ++newh; } if(move == TRUE) --newy; break; case KEY_DOWN: if(size == TRUE) { ++newy; --newh; } if(move == TRUE) ++newy; break; case 10: /* Enter */ move(LINES - 4, 0); clrtoeol(); refresh(); if(size == TRUE) { old_win = panel_window(stack_top); temp_win = newwin(newh, neww, newy, newx); replace_panel(stack_top, temp_win); win_show(temp_win, top->label, top->label_color); delwin(old_win); size = FALSE; } if(move == TRUE) { move_panel(stack_top, newy, newx); move = FALSE; } break; } attron(COLOR_PAIR(4)); mvprintw(LINES - 3, 0, "Use 'm' for moving, 'r' for resizing"); mvprintw(LINES - 2, 0, "Use tab to browse through the windows (F1 to Exit)"); attroff(COLOR_PAIR(4)); refresh(); update_panels(); doupdate(); } endwin(); return 0; } /* Put all the windows */ void init_wins(WINDOW **wins, int n) { int x, y, i; char label[80]; y = 2; x = 10; for(i = 0; i < n; ++i) { wins[i] = newwin(NLINES, NCOLS, y, x); sprintf(label, "Window Number %d", i + 1); win_show(wins[i], label, i + 1); y += 3; x += 7; } } /* Set the PANEL_DATA structures for individual panels */ void set_user_ptrs(PANEL **panels, int n) { PANEL_DATA *ptrs; WINDOW *win; int x, y, w, h, i; char temp[80]; ptrs = (PANEL_DATA *)calloc(n, sizeof(PANEL_DATA)); for(i = 0;i < n; ++i) { win = panel_window(panels[i]); getbegyx(win, y, x); getmaxyx(win, h, w); ptrs[i].x = x; ptrs[i].y = y; ptrs[i].w = w; ptrs[i].h = h; sprintf(temp, "Window Number %d", i + 1); strcpy(ptrs[i].label, temp); ptrs[i].label_color = i + 1; if(i + 1 == n) ptrs[i].next = panels[0]; else ptrs[i].next = panels[i + 1]; set_panel_userptr(panels[i], &ptrs[i]); } } /* Show the window with a border and a label */ void win_show(WINDOW *win, char *label, int label_color) { int startx, starty, height, width; getbegyx(win, starty, startx); getmaxyx(win, height, width); box(win, 0, 0); mvwaddch(win, 2, 0, ACS_LTEE); mvwhline(win, 2, 1, ACS_HLINE, width - 2); mvwaddch(win, 2, width - 1, ACS_RTEE); print_in_middle(win, 1, 0, width, label, COLOR_PAIR(label_color)); } void print_in_middle(WINDOW *win, int starty, int startx, int width, char *string, chtype color) { int length, x, y; float temp; if(win == NULL) win = stdscr; getyx(win, y, x); if(startx != 0) x = startx; if(starty != 0) y = starty; if(width == 0) width = 80; length = strlen(string); temp = (width - length)/ 2; x = startx + (int)temp; wattron(win, color); mvwprintw(win, y, x, "%s", string); wattroff(win, color); refresh(); }
the_stack_data/795714.c
/************************************************************** singh.c -- Written by John Barron, 1992 -- Implementation of Ajit Singh, ICCV, 1990, pp168-177. -- See also "Optic Flow Computation: A Unified Perspective" IEEE Computer Society Press 1992. **************************************************************/ #include <stdio.h> #include <math.h> #include <string.h> #include <stdlib.h> #include <unistd.h> #include <fcntl.h> #include <time.h> #include <sys/types.h> #define HUGE HUGE_VAL #define PIC_X 325 #define PIC_Y 325 #define PMODE 0644 #define TRUE 1 #define FALSE 0 #define HEAD 32 #define TORAD (M_PI/180.) #define TODEG (180./M_PI) #define NO_VALUE 100.0 #define ARRSIZE 9 #define MAX_ARRSIZE 17 #define WEIGHTSIZE 21 #define NUMFILES 3 #define FULL 69 #define NORMAL 96 #define NOTHING 0 #define CELL_RASTER 0 #define WHITE 255 #define BLACK 0 #define PRINT 0 #define PRINT2 0 #define NO_ROWS 2 #define NO_COLS 2 #define DIM 2 #define DIFF_THRESH 1e-5 #define SVD_PRINT 0 #define TOTAL 64 #define PT_X1 75 #define PT_Y1 60 #define PT_X2 60 #define PT_Y2 75 #define SMALL 0.1 int EXTRA_OFFSET_X=0; int EXTRA_OFFSET_Y=0; int CUT_X=0,CUT_Y=0; int PRINT_ITERATIONS=0; int PRINT_LAPLACIAN=0; int PRINT1=0; int PRINT11=0; int OFFSET_X=10; int OFFSET_Y=10; typedef unsigned char cimages[NUMFILES][PIC_Y][PIC_X]; typedef float fimages[NUMFILES][PIC_Y][PIC_X]; void add21(float a[2], float b[2], float c[2]); void add22(float S1[2][2], float S2[2][2], float S3[2][2]); void mult21(float A[2][2], float b[2], float x[2]); void comp_eigen(float A[DIM][DIM], float value[DIM], float vector1[DIM], float vector2[DIM]); void rotate(float a[DIM][DIM], int i, int j, int k, int l, float*h, float*g, float s, float tau); void compute_SSD_surface(fimages fpic, int x, int y, int n, int N, float SSDdata[ARRSIZE][ARRSIZE],int*max_a, int*max_b); void calc_mean_and_covariance1(float calc[ARRSIZE][ARRSIZE], float mean[2], float covariance[2][2],float u_low, float u_high, float v_low, float v_high, float eigenvalues[2], float eigenvector1[2], float eigenvector2[2], int*vel_type, int N); void calc_statistics(float correct_vels[PIC_Y][PIC_X][2], float full_vels[PIC_Y][PIC_X][2], int pic_x, int pic_y, float*ave_error, float*st_dev, float*density, float*min_angle, float*max_angle, int SAMPLE); void calc_mean_and_covariance2(float weights[WEIGHTSIZE][WEIGHTSIZE], float velocities[WEIGHTSIZE][WEIGHTSIZE][2], int weighted_size, float mean[2], float covariance[2][2]); void read_image_files(char *s, cimages pic, int*pic_x, int*pic_y, int header_ints[8], int central_image, int STEP); void laplacian(cimages cpic, fimages fpic, float sigma, int pic_x, int pic_y); void write_image_files(char*s, cimages pic, int pic_x, int pic_y, int header_ints[8], int central_image, int STEP); void output_velocities(int fdf, float velocities[PIC_Y][PIC_X][2], int pic_x, int pic_y, char type[100], int SAMPLE); void input_covariances(int fdf, float covariances[PIC_Y][PIC_X][2][2], int pic_x, int pic_y); void output_covariances(int fdf, float covariances[PIC_Y][PIC_X][2][2], int pic_x, int pic_y); void input_velocities(int fdf,float velocities[PIC_Y][PIC_X][2], int pic_x, int pic_y); void threshold_velocities(float input_velocity[PIC_Y][PIC_X][2], float covariances[PIC_Y][PIC_X][2][2], float full_velocity[PIC_Y][PIC_X][2], int pic_x, int pic_y, float tau); void make_float(cimages cpic, fimages fpic, int pic_x, int pic_y); void compute_weights(float weights[WEIGHTSIZE][WEIGHTSIZE], int w); void compute_n_minimums(float data[ARRSIZE][ARRSIZE], int N, int n); void comp1(fimages fpic, int pic_x, int pic_y,float Ucc[PIC_Y][PIC_X][2], float Scc[PIC_Y][PIC_X][2][2], int n, int N, int STEP, int old_pic_x, int old_pic_y); void comp2(unsigned char path[100],unsigned char name[100], float Ucc[PIC_Y][PIC_X][2], float Scc[PIC_Y][PIC_X][2][2], float S[PIC_Y][PIC_X][2][2], int pic_x, int pic_y, float full_velocity[PIC_Y][PIC_X][2], unsigned char correct_filename[100], int w, int old_pic_x, int old_pic_y); void compute_big_n_minimums(float data[MAX_ARRSIZE][MAX_ARRSIZE], int N, int n); float cal_normal_angle_error(),cal_full_angle_error(); float dot(),PsiER(),PsiEN(),L2norm(),bigL2norm(); int check_eigen_calc(); float calc[ARRSIZE][ARRSIZE]; int fd_correct,SAMPLE,PREVIOUS1,PREVIOUS2,pic_x,pic_y,no_bytes,fd_vels; float offset_x,offset_y,size_x,size_y,actual_x,actual_y; int int_size_x,int_size_y,inverse22(),fdcov1,fdcov2; int COUNT_SINGULAR,STEP,PRINT_FLOWS1,PRINT_FLOWS2; int MAX_NUMBER_OF_ITERATIONS,SUBSET; long time1,time2,time3,time4,temporal_offset; float normal_velocities[PIC_Y][PIC_X][2]; float full_velocities[PIC_Y][PIC_X][2],threshold_velocity[PIC_Y][PIC_X][2]; float Ucc[PIC_Y][PIC_X][2],Scc[PIC_Y][PIC_X][2][2],S[PIC_Y][PIC_X][2][2]; float correct_velocities[PIC_Y][PIC_X][2],TAU,SsumI[PIC_Y][PIC_X][2][2]; float Un[2][PIC_Y][PIC_X][2],Sn[2][PIC_Y][PIC_X][2][2]; float SccI[PIC_Y][PIC_X][2][2],Ssum[PIC_Y][PIC_X][2][2]; float SccI_Ucc[PIC_Y][PIC_X][2],Ua[PIC_Y][PIC_X][2]; int fdf1,fdf2,BINARY,CORRECT_VELOCITIES,header_ints[8],STEP2,FILE_NUMBER; int LAPLACIAN; FILE *fp; cimages inpic; fimages fpic; char inname[100],filename[100],path1[100],path2[100],outname[100]; /******************************************************************/ int main(int argc, char **argv) { char command[100],correct_filename[100],name[100]; float tau1,tau2,sigma; int n,N,i,central_image,old_pic_x,old_pic_y,steps1,steps2; int threshold1,threshold2,w,offset; float ave_error,st_dev,density,min_angle,max_angle; float low_tau1,high_tau1,inc_tau1; float low_tau2,high_tau2,inc_tau2; FILE_NUMBER = -1; COUNT_SINGULAR = 0; SUBSET = FALSE; if(argc<7 || argc>36) { printf("Usage: %s <filename stem> <central_image> <input data path> <output data path> [-C <filename> -B <cols> <rows> -T1 <low> <high> <steps> -T2 <low> <high> <steps> -P1 -P2 -PR1 -PR2 -PRI -PRL -n <int> -N <int> -w <int> -i <int> -NL -s <int> -SUB <int> <int> <int> <int>]\n",argv[0]); printf("Use 2 images starting with stem.center_image\n"); printf("<input data path> - directory where images are\n"); printf("<output data path> - directory where the flow fields are stored\n"); printf("-C <file> - correct velocity data provided and error analysis\n"); printf(" will be performed on it\n"); printf("-B <cols> <rows> - Input binary images-specify dimensions \n"); printf(" not necessary for rasterfiles\n"); printf("-T1 <float> <float> <int> - threshold the step 1 velocities using the smallest\n"); printf(" eigenvalue of the step 1covariance matrix at each position\n"); printf("-T2 <float> <float> <int> - threshold the step 2 velocities using the smallest\n"); printf(" eigenvalue of the step 2 covariance matrix at each position\n"); printf("-P1 - do not perform step 1 of the compuatation, instead read the\n"); printf(" previously computed step 1 velocities and covariance matrices\n"); printf("-P2 - do not perform step 2 of the compuatation, instead read the\n"); printf(" previously computed step 2 velocities and covariance matrices\n"); printf(" If -P2 is used but -P1 is not the program terminates after step 1\n"); printf("-PR1 - print thresholded flow fields for step 1\n"); printf("-PR2 - print thresholded flow fields for step 2\n"); printf("-PRI - print flow fields after each iteration\n"); printf(" - These flow fields occupy a LOT of ddisk space\n"); printf("-PRL - print the laplacian images\n"); printf("-n - neighbourhood size (2n+1) in step1 computation (default 2)\n"); printf("-N - maximum displacement in pixels (-u,-v <= N <= u,v) (default and maximum value is/can be 4)\n"); printf("-w - window size (2w+1) for step 2 computation [currently must be 1 or 2] (default is 1)\n"); printf("-i - number of iterations for step 2 (default 10)\n"); printf("-s <int> - specify the distance of the adjacent left and right frames\n"); printf(" from the central frame - default is 1\n"); printf("-NL - use the original images as input\n"); printf("-SUB <x> <y> <size_x> <size_y> - compute velocity for a subset of the images\n"); printf(" compute flow for a subarea starting at (x,y) and of size (size_x,size_y)\n"); printf(" Note: you must take offsets into account!\n"); printf("-C, -B, -T1, -T2, -P1, -P2, -n, -N, -w, -i, -PR1, -PR2, PRI, -PRL, -NL and -SUB can be in any order and are optional\n"); exit(1); } else { printf("%d arguments\n",argc); printf("Command line:"); for(i=0;i<argc;i++) printf("%s ",argv[i]); printf("\n"); } sscanf(argv[2],"%d",&central_image); strcpy(path1,argv[3]); strcpy(path2,argv[4]); printf("<input path>: %s\n<output path>: %s\n",path1,path2); printf("SMALL: %f\n",SMALL); BINARY = FALSE; CORRECT_VELOCITIES = FALSE; SAMPLE = 1; STEP = 1; PREVIOUS1 = FALSE; PREVIOUS2 = FALSE; LAPLACIAN = TRUE; PRINT_FLOWS1 = FALSE; PRINT_FLOWS2 = FALSE; PRINT_ITERATIONS = FALSE; PRINT_LAPLACIAN = FALSE; strcpy(correct_filename,"unknown"); i = 6; threshold1 = threshold2 = FALSE; STEP2 = TRUE; w = 1; n = 2; N = 4; MAX_NUMBER_OF_ITERATIONS = 10; while(i <= argc) { if(strcmp(argv[i-1],"-S1")==0) { sscanf(argv[i],"%d",&SAMPLE); STEP2 = FALSE; i++; } else if(strcmp(argv[i-1],"-T1")==0) { sscanf(argv[i],"%f",&low_tau1); sscanf(argv[i+1],"%f",&high_tau1); sscanf(argv[i+2],"%d",&steps1); threshold1 = TRUE; if((low_tau1 >= high_tau1) || steps1 <= 0) { printf("Error: threshold ranges for step1 are wrong - no thresholding done\n"); threshold1 = FALSE; } else { inc_tau1 = (high_tau1-low_tau1)/steps1; } i+=3; } else if(strcmp(argv[i-1],"-T2")==0) { sscanf(argv[i],"%f",&low_tau2); sscanf(argv[i+1],"%f",&high_tau2); sscanf(argv[i+2],"%d",&steps2); threshold2 = TRUE; if((low_tau2 >= high_tau2) || steps2 <= 0) { printf("Error: threshold ranges for step2 are wrong - no thresholding done\n"); threshold2 = FALSE; } else { inc_tau2 = (high_tau2-low_tau2)/steps2; } i+=3; } else if(strcmp(argv[i-1],"-C")==0) { strcpy(correct_filename,argv[i]); CORRECT_VELOCITIES = TRUE; i++; } else if(strcmp(argv[i-1],"-B")==0) { sscanf(argv[i],"%d",&pic_y); sscanf(argv[i+1],"%d",&pic_x); BINARY = TRUE; i += 2; } else if(strcmp(argv[i-1],"-s")==0) { sscanf(argv[i],"%d",&STEP); i += 1; } else if(strcmp(argv[i-1],"-P1")==0) { PREVIOUS1 = TRUE; } else if(strcmp(argv[i-1],"-NL")==0) { LAPLACIAN = FALSE; } else if(strcmp(argv[i-1],"-PR1")==0) { PRINT_FLOWS1 = TRUE; } else if(strcmp(argv[i-1],"-PR2")==0) { PRINT_FLOWS2 = TRUE; } else if(strcmp(argv[i-1],"-PRI")==0) { PRINT_ITERATIONS = TRUE; } else if(strcmp(argv[i-1],"-PRL")==0) { PRINT_LAPLACIAN = TRUE; } else if(strcmp(argv[i-1],"-w")==0) { sscanf(argv[i],"%d",&w); if(w!=1 && w!=2) { printf("Fatal error: w must be 1 or 2\n"); exit(1); } i+= 1; } else if(strcmp(argv[i-1],"-n")==0) { sscanf(argv[i],"%d",&n); i+= 1; } else if(strcmp(argv[i-1],"-N")==0) { sscanf(argv[i],"%d",&N); i+= 1; } else if(strcmp(argv[i-1],"-i")==0) { sscanf(argv[i],"%d",&MAX_NUMBER_OF_ITERATIONS); i+= 1; } else if(strcmp(argv[i-1],"-P2")==0) { PREVIOUS2 = TRUE; } else if(strcmp(argv[i-1],"-SUB")==0) { sscanf(argv[i],"%d",&EXTRA_OFFSET_X); sscanf(argv[i+1],"%d",&EXTRA_OFFSET_Y); sscanf(argv[i+2],"%d",&CUT_X); sscanf(argv[i+3],"%d",&CUT_Y); SUBSET = TRUE; i+=4; } else { printf("Fatal error invalid %dth argument: %s\n",i,argv[i-1]); exit(1); } i++; } if(!PREVIOUS1 && PREVIOUS2) STEP2 = FALSE; if(threshold1) printf("Step 1 velocities are thresholded for tau=%f to %f in increments of %f\n", low_tau1,high_tau1,inc_tau1); if(threshold2) printf("Step 2 velocities are thresholded for tau=%f to %f in increments of %f\n", low_tau2,high_tau2,inc_tau2); printf("Velocity Range: -%d <= u,v <= %d\n",N,N); printf("n=%d neighbourhood size for SSD surface calculation\n",n); printf("w=%d window size for step 2\n",w); printf("Left image: %d\n",central_image-STEP); printf("Central image: %d\n",central_image); printf("Right image: %d\n",central_image+STEP); /* Create appropriate file names for step 1 results */ if(!PREVIOUS1) { if(STEP==1) sprintf(outname,"%s/singh.step1.%sF-n-%d-w-%d-N-%d",path2,argv[1],n,w,N); else sprintf(outname,"%s/singh.step1.%sF-n-%d-w-%d-N-%d-s-%d",path2,argv[1],n,w,N,STEP); if((fdf1 = creat(outname,0755))<0) { printf("Error creating file %s.\n",outname); exit(1); } printf("File %s opened for output\n",outname); if(STEP==1) sprintf(outname,"%s/singh.step1.%sC-n-%d-w-%d-N-%d",path2,argv[1],n,w,N); else sprintf(outname,"%s/singh.step1.%sC-n-%d-w-%d-N-%d-s-%d",path2,argv[1],n,w,N,STEP); if((fdcov1 = creat(outname,0755))<0) { printf("Error creating file %s.\n",outname); exit(1); } printf("File %s opened for output\n",outname); } else { if(STEP==1) sprintf(outname,"%s/singh.step1.%sF-n-%d-w-%d-N-%d",path2,argv[1],n,w,N); else sprintf(outname,"%s/singh.step1.%sF-n-%d-w-%d-N-%d-s-%d",path2,argv[1],n,w,N,STEP); if((fdf1 = open(outname,O_RDONLY))<0) { printf("Fatal error: file %s does not exit\n",outname); exit(1); } printf("File %s opened for input\n",outname); if(STEP==1) sprintf(outname,"%s/singh.step1.%sC-n-%d-w-%d-N-%d",path2,argv[1],n,w,N); else sprintf(outname,"%s/singh.step1.%sC-n-%d-w-%d-N-%d-s-%d",path2,argv[1],n,w,N,STEP); if((fdcov1 = open(outname,O_RDONLY))<0) { printf("Fatal error: file %s does not exist\n",outname); exit(1); } printf("File %s opened for input\n",outname); } /* Create appropriate file names for step 2 results */ if(!PREVIOUS2) { if(STEP==1) sprintf(outname,"%s/singh.step2.%sF-n-%d-w-%d-N-%d",path2,argv[1],n,w,N); else sprintf(outname,"%s/singh.step2.%sF-n-%d-w-%d-N-%d-s-%d",path2,argv[1],n,w,N,STEP); if((fdf2 = creat(outname,0755))<0) { printf("Error creating file %s.\n",outname); exit(1); } printf("File %s opened for output\n",outname); if(STEP==1) sprintf(outname,"%s/singh.step2.%sC-n-%d-w-%d-N-%d",path2,argv[1],n,w,N); else sprintf(outname,"%s/singh.step2.%sC-n-%d-w-%d-N-%d-s-%d",path2,argv[1],n,w,N,STEP); if((fdcov2 = creat(outname,0755))<0) { printf("Error creating file %s.\n",outname); exit(1); } printf("File %s opened for output\n",outname); fflush(stdout); } else { if(STEP==1) sprintf(outname,"%s/singh.step2.%sF-n-%d-w-%d-N-%d",path2,argv[1],n,w,N); else sprintf(outname,"%s/singh.step2.%sF-n-%d-w-%d-N-%d-s-%d",path2,argv[1],n,w,N,STEP); if((fdf2 = open(outname,O_RDONLY))<0) { printf("Fatal error: file %s does not exit\n",outname); exit(1); } printf("File %s opened for input\n",outname); if(STEP==1) sprintf(outname,"%s/singh.step2.%sC-n-%d-w-%d-N-%d",path2,argv[1],n,w,N); else sprintf(outname,"%s/singh.step2.%sC-n-%d-w-%d-N-%d-s-%d",path2,argv[1],n,w,N,STEP); if((fdcov2 = open(outname,O_RDONLY))<0) { printf("Fatal error: file %s does not exist\n",outname); exit(1); } printf("File %s opened for input\n",outname); } /* Process correct velocity data */ if(strcmp("unknown",correct_filename)!=0) { /* Read the correct velocity data */ fd_correct = open(correct_filename,O_RDONLY); no_bytes = 0; no_bytes += read(fd_correct,&actual_x,4); no_bytes += read(fd_correct,&actual_y,4); no_bytes += read(fd_correct,&size_x,4); no_bytes += read(fd_correct,&size_y,4); no_bytes += read(fd_correct,&offset_x,4); no_bytes += read(fd_correct,&offset_y,4); if(offset_x != 0.0 || offset_y != 0.0 || actual_x != size_x || actual_y != size_y) { printf("Fatal error: something wrong with correct velocity data\n"); printf("Actual y: %f Actual x: %f\n",actual_y,actual_x); printf("Size y: %f Size x: %f\n",size_y,size_x); printf("Offset y: %f Offset x: %f\n",offset_y,offset_x); exit(1); } int_size_x = size_x; int_size_y = size_y; for(i=0;i<int_size_y;i++) no_bytes += read(fd_correct,&correct_velocities[i][0][0],int_size_x*8); printf("\nFile %s opened and read\n",correct_filename); printf("Size of correct velocity data: %d %d --- ",int_size_x,int_size_y); printf("%d bytes read\n",no_bytes); fflush(stdout); } /* Perform timing measurements */ temporal_offset = 100; /* Each program requires at 100 seconds */ if(STEP!=1) sprintf(filename,"%s.%stime-n-%d-w-%d-s-%d",argv[0],argv[1],n,w,STEP); else sprintf(filename,"%s.%stime-n-%d-w-%d",argv[0],argv[1],n,w); fp = fopen(filename,"w"); fprintf(fp,"The time data is in file: %s\n",filename); time1 = time(NULL); fprintf(fp,"Start time: %ld\n",time1); fflush(fp); time2 = time1; /* Read data */ sprintf(name,"%s/%s",path1,argv[1]); read_image_files(name,inpic,&pic_x,&pic_y,header_ints,central_image,STEP); /*****************************************************************/ /* Set parameters for a subset of the image sequence */ /*****************************************************************/ old_pic_x = pic_x; old_pic_y = pic_y; if(SUBSET) { printf("\n"); pic_x = EXTRA_OFFSET_X+CUT_X+OFFSET_X; pic_y = EXTRA_OFFSET_Y+CUT_Y+OFFSET_Y; EXTRA_OFFSET_X -= OFFSET_X; EXTRA_OFFSET_Y -= OFFSET_Y; if(CUT_X <= 5 || CUT_Y <=5) { printf("Fatal error: subarea too small - must be at least 6*6\n"); printf("Subarea specified: %d*%d\n",CUT_X,CUT_Y); exit(1); } if((CUT_X+OFFSET_X+EXTRA_OFFSET_X > old_pic_x-OFFSET_X) || (CUT_Y+OFFSET_Y+EXTRA_OFFSET_Y > old_pic_y-OFFSET_Y)) { printf("Fatal error: subarea parameters incorrect\n"); printf("Starting Coordinates: %d,%d ",OFFSET_X+EXTRA_OFFSET_X,OFFSET_Y+EXTRA_OFFSET_Y); printf("Size: %d * %d\n",CUT_X,CUT_Y); printf("Too big by %d,%d\n",CUT_X+EXTRA_OFFSET_X+2*OFFSET_X-old_pic_x, CUT_Y+EXTRA_OFFSET_Y+2*OFFSET_Y-old_pic_y); exit(1); } printf("\n\nSubset of image sequence used\n"); printf("Starting Coordinates: %d,%d ",OFFSET_X+EXTRA_OFFSET_X,OFFSET_Y+EXTRA_OFFSET_Y); printf("Size: %d * %d\n",CUT_X,CUT_Y); } /* Compute laplacian images */ if(LAPLACIAN && !PREVIOUS1) { laplacian(inpic,fpic,1.0,pic_x,pic_y); if(PRINT_LAPLACIAN) write_image_files(argv[1],inpic,pic_x,pic_y,header_ints,central_image,STEP); } else make_float(inpic,fpic,pic_x,pic_y); /**********************************************/ /* Step 1: Conservation Information recovery */ /**********************************************/ if(!PREVIOUS1) { comp1(fpic,pic_x,pic_y,Ucc,Scc,n,N,STEP,old_pic_x,old_pic_y); /* Output velocities and rearrange them */ printf("\nOutputing flow data\n"); output_velocities(fdf1,Ucc,old_pic_x,old_pic_y,"Full",SAMPLE); output_covariances(fdcov1,Scc,old_pic_x,old_pic_y); } else { input_velocities(fdf1,Ucc,old_pic_x,old_pic_y); input_covariances(fdcov1,Scc,old_pic_x,old_pic_y); } if(strcmp("unknown",correct_filename)!=0) { printf("\nStep 1:\n"); calc_statistics(correct_velocities,Ucc,old_pic_x,old_pic_y, &ave_error,&st_dev,&density,&min_angle,&max_angle,SAMPLE); printf("\nError Analysis Performed\n"); printf("Average Error: %f Standard Deviation: %f Density: %f\n", ave_error,st_dev,density); printf("Minimum Angle Error: %f Maximum Angle Error: %f\n",min_angle,max_angle); fflush(stdout); /* Threshold step 1 velocities */ if(threshold1) { tau1 = low_tau1; printf("\n-----------------------------------------------------\n"); printf("Step 1 Thresholding"); printf("\n-----------------------------------------------------\n"); while(tau1 <= high_tau1) { threshold_velocities(Ucc,Scc,threshold_velocity,pic_x,pic_y,tau1); printf("\nThreshold: %f\n",tau1); calc_statistics(correct_velocities,threshold_velocity,old_pic_x,old_pic_y, &ave_error,&st_dev,&density,&min_angle,&max_angle,SAMPLE); printf("\nError Analysis Performed\n"); printf("Average Error: %f Standard Deviation: %f Density: %f\n", ave_error,st_dev,density); printf("Minimum Angle Error: %f Maximum Angle Error: %f\n",min_angle,max_angle); fflush(stdout); if(PRINT_FLOWS1) { sprintf(outname,"%s/singh.step1.%sF-tau-%4.2f",path2,argv[1],tau1); if((fd_vels = creat(outname,0755))<0) { printf("Error creating file %s.\n",outname); exit(1); } printf("File %s opened for output\n",outname); output_velocities(fd_vels,threshold_velocity,old_pic_x,old_pic_y,"Full",SAMPLE); } tau1 += inc_tau1; } printf("\n-----------------------------------------------------\n"); } } if(!STEP2) exit(1); /**********************************************/ /* Step 2: Neighbourhood Information recovery */ /**********************************************/ if(!PREVIOUS2) { comp2(path2,argv[1],Ucc,Scc,S,pic_x,pic_y,full_velocities,correct_filename,w,old_pic_x,old_pic_y); /* Output velocities for step 2 computation */ printf("\nOutputing flow data for step 2\n"); output_velocities(fdf2,full_velocities,old_pic_x,old_pic_y,"Full",1); output_covariances(fdcov2,S,old_pic_x,old_pic_y); } else { offset = (2*w+1)/2; OFFSET_X += offset; OFFSET_Y += offset; input_velocities(fdf2,full_velocities,old_pic_x,old_pic_y); input_covariances(fdcov2,S,old_pic_x,old_pic_y); } if(strcmp("unknown",correct_filename)!=0) { printf("\nStep 2:\n"); calc_statistics(correct_velocities,full_velocities,old_pic_x,old_pic_y, &ave_error,&st_dev,&density,&min_angle,&max_angle,1); printf("\nError Analysis Performed\n"); printf("Average Error: %f Standard Deviation: %f Density: %f\n", ave_error,st_dev,density); printf("Minimum Angle Error: %f Maximum Angle Error: %f\n",min_angle,max_angle); /* Threshold step 2 velocities */ if(threshold2) { tau2 = low_tau2; printf("\n-----------------------------------------------------\n"); printf("Step 2 Thresholding"); printf("\n-----------------------------------------------------\n"); while(tau2 <= high_tau2) { threshold_velocities(full_velocities,S,threshold_velocity,pic_x,pic_y,tau2); printf("\nThreshold: %f\n",tau2); calc_statistics(correct_velocities,threshold_velocity,old_pic_x,old_pic_y, &ave_error,&st_dev,&density,&min_angle,&max_angle,SAMPLE); printf("\nError Analysis Performed\n"); printf("Average Error: %f Standard Deviation: %f Density: %f\n", ave_error,st_dev,density); printf("Minimum Angle Error: %f Maximum Angle Error: %f\n",min_angle,max_angle); if(PRINT_FLOWS2) { sprintf(outname,"%s/singh.step2.%sF-tau-%4.2f",path2,argv[1],tau2); if((fd_vels = creat(outname,0755))<0) { printf("Error creating file %s.\n",outname); exit(1); } printf("File %s opened for output\n",outname); output_velocities(fd_vels,threshold_velocity,pic_x,pic_y,"Full",SAMPLE); } tau2 += inc_tau2; } printf("\n-----------------------------------------------------\n"); } } printf("\nProcessing Finished\n"); fflush(stdout); time2 = time(NULL); if(time2 > time1+temporal_offset) { fprintf(fp,"\nEnd time: %ld\n",time2); fprintf(fp,"End Time in seconds: %ld\n",(time2-time1)); fprintf(fp,"End Time in minutes: %f\n",(time2-time1)*1.0/60.0); fprintf(fp,"End Time in hours: %f\n",(time2-time1)*1.0/3600.0); fflush(fp); } } /************************************************************ Read raster files into internal 3-D array. Also sets pic_x and pic_y (the actual picture dimensions) which are global ************************************************************/ void read_image_files(char *s, cimages pic, int*pic_x, int*pic_y, int header_ints[8], int central_image, int STEP) { char fname[100]; int i,j,fd,ints[8],ONCE,bytes; unsigned char header[HEAD]; ONCE = TRUE; for(i=0;i<NUMFILES;i++) { sprintf(fname,"%s%d",s,central_image+(i-1)*STEP); if((fd = open(fname,O_RDONLY)) >0) { if(!BINARY) { if(ONCE) { read(fd,ints,HEAD); for(j=0;j<8;j++) header_ints[j] = ints[j]; (*pic_x) = ints[1]; (*pic_y) = ints[2]; ONCE = FALSE; if((*pic_y) > PIC_Y || (*pic_x) > PIC_X) { printf("Fatal error - not enough room\n"); printf("Required size: %d times %d\n",pic_y,pic_x); exit(1); } } else read(fd,header,HEAD); bytes = 32; } /* Read row by row */ for(j=0;j<(*pic_y);j++) bytes += read(fd,&pic[i][j][0],(*pic_x)); printf("File %s read -- %d bytes\n",fname,bytes); bytes = 0; fflush(stdout); } else { printf("File %s does not exist in read_image_files.\n",fname); exit(1); } } } /* End of read_image_files */ /************************************************************ write raster files from internal 3-D array. Also sets pic_x and pic_y (the actual picture dimensions) which are global ************************************************************/ void write_image_files(char*s, cimages pic, int pic_x, int pic_y, int header_ints[8], int central_image, int STEP) { char fname[100]; int i,j,fd,ints[8],ONCE,bytes; unsigned char header[HEAD]; ONCE = TRUE; for(i=0;i<NUMFILES;i++) { sprintf(fname,"laplacian.%s%d",s,central_image+(i-1)*STEP); if((fd = creat(fname,0755)) >= 0) { write(fd,header_ints,HEAD); bytes = 32; /* Read row by row */ for(j=0;j<(pic_y);j++) bytes += write(fd,&pic[i][j][0],(pic_x)); printf("File %s written -- %d bytes\n",fname,bytes); fflush(stdout); } else { printf("File %s does not exist in write_image_files.\n",fname); exit(1); } } } /* End of write_image_files */ /*****************************************************************/ /* Compute velocities */ /*****************************************************************/ void comp1(fimages fpic, int pic_x, int pic_y,float Ucc[PIC_Y][PIC_X][2], float Scc[PIC_Y][PIC_X][2][2], int n, int N, int STEP, int old_pic_x, int old_pic_y) { int i,j,vel_type,SKIP,ct,max_a,max_b; float vx,vy,step_size; float uve[2],uva[2],N2; float SSDdata[ARRSIZE][ARRSIZE],SI[2][2],condition_number; float covariance[2][2],mean[2],eigenvalues[2],eigenvector1[2],eigenvector2[2]; printf("\nComputing Velocity Information via step 1...\n"); for(i=0;i<PIC_Y;i++) for(j=0;j<PIC_X;j++) { Ucc[i][j][0] = Ucc[i][j][1] = NO_VALUE; Scc[i][j][0][0] = Scc[i][j][0][1] = NO_VALUE; Scc[i][j][1][0] = Scc[i][j][1][1] = NO_VALUE; } N2 = 2.0*N; step_size = 1.0*STEP; /* Compute velocity for every location */ printf("Processing rows for step 1:\n"); ct = 0; for(i=OFFSET_Y+EXTRA_OFFSET_Y;i<pic_y-OFFSET_Y;i++) { printf("%3d ",i); ct++; if((ct % 15) == 0) printf("\n"); fflush(stdout); for(j=OFFSET_X+EXTRA_OFFSET_X;j<pic_x-OFFSET_X;j++) { if(i%SAMPLE==0 && j%SAMPLE==0) { fflush(stdout); vel_type = NOTHING; compute_SSD_surface(fpic,i,j,n,N,SSDdata,&max_a,&max_b); calc_mean_and_covariance1(SSDdata,mean,covariance, -4.0+max_b,4.0+max_b,-4.0+max_a,4.0+max_a, eigenvalues,eigenvector1,eigenvector2,&vel_type,N); vx = mean[0]; vy = -mean[1]; Scc[i][j][0][0] = covariance[0][0]; Scc[i][j][0][1] = covariance[0][1]; Scc[i][j][1][0] = covariance[1][0]; Scc[i][j][1][1] = covariance[1][1]; Ucc[i][j][0] = vx/step_size; Ucc[i][j][1] = vy/step_size; } } } } /*************************************************************/ /* Smooth velocity field using velocities computed in step 1 */ /* Step 2 Neighbourhood Information */ /*************************************************************/ void comp2(unsigned char path[100],unsigned char name[100], float Ucc[PIC_Y][PIC_X][2], float Scc[PIC_Y][PIC_X][2][2], float S[PIC_Y][PIC_X][2][2], int pic_x, int pic_y, float full_velocity[PIC_Y][PIC_X][2], unsigned char correct_filename[100], int w, int old_pic_x, int old_pic_y) { int fd,i,j,k,l,FIRST,SECOND,weighted_size,RELAXATION,temp,ct; float neighbour_velocities[WEIGHTSIZE][WEIGHTSIZE][2]; float weights[WEIGHTSIZE][WEIGHTSIZE],diff[2],mean[2]; float SnI[2][2],vec1[2],vec2[2],bigdiff[PIC_Y][PIC_X][2]; float eigenvector1[2],eigenvector2[2],eigenvalues[2],max_diff; float ave_error,st_dev,min_angle,max_angle,density,size; int iteration_number,offset,SINGULAR,no_vels; FIRST = 0; SECOND = 1; max_diff = 0.0; for(i=0;i<PIC_Y;i++) for(j=0;j<PIC_X;j++) { bigdiff[i][j][0] = bigdiff[i][j][1] = NO_VALUE; Un[FIRST][i][j][0] = Un[FIRST][i][j][1] = NO_VALUE; Un[SECOND][i][j][0] = Un[SECOND][i][j][1] = NO_VALUE; full_velocity[i][j][0] = full_velocity[i][j][1] = NO_VALUE; } for(i=0;i<old_pic_y;i++) for(j=0;j<old_pic_x;j++) { Un[FIRST][i][j][0] = Un[SECOND][i][j][0] = Ucc[i][j][0]; Un[FIRST][i][j][1] = Un[SECOND][i][j][1] = Ucc[i][j][1]; } if(strcmp("unknown",correct_filename)!=0) { calc_statistics(correct_velocities,&Un[FIRST][0][0][0],old_pic_x,old_pic_y, &ave_error,&st_dev,&density,&min_angle,&max_angle,1); printf("Error Analysis Performed at start of step 2\n"); printf("Average Error: %f Standard Deviation: %f Density: %f\n", ave_error,st_dev,density); printf("Minimum Angle Error: %f Maximum Angle Error: %f\n\n",min_angle,max_angle); fflush(stdout); } compute_weights(weights,w); weighted_size = 2*w+1; offset = weighted_size/2; OFFSET_X += offset; OFFSET_Y += offset; /* Initialization: compute SccI and multiply by Ucc, compute the weighted_size*weighted_size velocity neighbourhood and its mean and covariance matrix */ printf("Computing velocity information via step 2\n"); printf("Performing Initialization...\n"); for(i=OFFSET_Y+EXTRA_OFFSET_Y;i<pic_y-OFFSET_Y;i++) { for(j=OFFSET_X+EXTRA_OFFSET_X;j<pic_x-OFFSET_X;j++) { /* Compute the inverse of Scc and multiply by Ucc */ SINGULAR=inverse22(&Scc[i][j][0][0],&SccI[i][j][0][0],SVD_PRINT); mult21(&SccI[i][j][0][0],&Ucc[i][j][0],&SccI_Ucc[i][j][0]); /* Compute neighbourhood velocities for initialization */ no_vels = 0; for(k=(-offset);k<=offset;k++) for(l=(-offset);l<=offset;l++) { if(Un[FIRST][i+k][j+l][0] != NO_VALUE && Un[FIRST][i+k][j+l][1] != NO_VALUE) { no_vels++; neighbour_velocities[k+offset][l+offset][0] = Un[FIRST][i+k][j+l][0]; neighbour_velocities[k+offset][l+offset][1] = Un[FIRST][i+k][j+l][1]; } else { printf("FIRST i=%d j=%d k=%d l=%d\n",i,j,k,l); for(k=(-offset);k<=offset;k++) for(l=(-offset);l<=offset;l++) printf("vel for k=%d l=%d: %f,%f\n",k,l,Un[FIRST][i+k][j+l][0],Un[FIRST][i+k][j+l][1]); printf("Fatal error: computed velocity undefined during initialization\n"); exit(1); } } calc_mean_and_covariance2(weights,neighbour_velocities, weighted_size,&Ua[i][j][0],&Sn[FIRST][i][j][0][0]); } } printf("\nInitialization complete for step 2\n"); /* Relaxation Computation using neighbourhood velocities */ RELAXATION = TRUE; iteration_number = 0; printf("\n"); while(RELAXATION && iteration_number < MAX_NUMBER_OF_ITERATIONS) { printf("Iteration %d\n",iteration_number); iteration_number++; RELAXATION = FALSE; size = 0.0; for(i=OFFSET_Y+EXTRA_OFFSET_Y;i<pic_y-OFFSET_Y;i++) { for(j=OFFSET_X+EXTRA_OFFSET_X;j<pic_x-OFFSET_X;j++) /* Perform an iteration */ { SINGULAR = inverse22(&Sn[FIRST][i][j][0][0],SnI,SVD_PRINT); add22(&SccI[i][j][0][0],SnI,&Ssum[i][j][0][0]); SINGULAR += inverse22(&Ssum[i][j][0][0],&SsumI[i][j][0][0],SVD_PRINT); mult21(SnI,&Ua[i][j][0],vec1); add21(&SccI_Ucc[i][j][0],vec1,vec2); mult21(&SsumI[i][j][0][0],vec2,&Un[SECOND][i][j][0]); /* if(i==32 && j==74) { printf("SsumI[32][74]:\n"); printf(" %f %f\n",SsumI[32][74][0][0],SsumI[32][74][0][1]); printf(" %f %f\n",SsumI[32][74][1][0],SsumI[32][74][1][1]); printf("SccI[32][74]:\n"); printf(" %f %f\n",SccI[32][74][0][0],SccI[32][74][0][1]); printf(" %f %f\n",SccI[32][74][1][0],SccI[32][74][1][1]); printf("SnI:\n"); printf(" %f %f\n",SnI[0][0],SnI[0][1]); printf(" %f %f\n",SnI[1][0],SnI[1][1]); printf("vec1: %f %f\n",vec1[0],vec1[1]); printf("vec2: %f %f\n",vec2[0],vec2[1]); printf("SccI_Ucc[32][74]: %f %f\n",SccI_Ucc[32][74][0],SccI_Ucc[32][74][1]); printf("Ua[32][74]: %f %f\n",Ua[32][74][0],Ua[32][74][1]); printf("U[FIRST][32][74]: %f %f\n",Un[FIRST][32][74][0],Un[FIRST][32][74][1]); printf("U[SECOND][32][74]: %f %f\n",Un[SECOND][32][74][0],Un[SECOND][32][74][1]); } */ diff[0] = Un[FIRST][i][j][0]-Un[SECOND][i][j][0]; diff[1] = Un[FIRST][i][j][1]-Un[SECOND][i][j][1]; bigdiff[i][j][0] = diff[0]; bigdiff[i][j][1] = diff[1]; size = L2norm(diff,2); if(size > max_diff) max_diff = size; if(size > DIFF_THRESH) RELAXATION = TRUE; } } if(!RELAXATION) printf("\nConvergence detected - iterative calculations are stopped\n"); /* Prepare for next iteration */ if(RELAXATION) { for(i=OFFSET_Y+EXTRA_OFFSET_Y;i<pic_y-OFFSET_Y;i++) { for(j=OFFSET_X+EXTRA_OFFSET_X;j<pic_x-OFFSET_X;j++) { /* Compute neighbourhood velocities for initialization */ for(k=(-offset);k<=offset;k++) for(l=(-offset);l<=offset;l++) { if(Un[SECOND][i+k][j+l][0] != NO_VALUE && Un[SECOND][i+k][j+l][1] != NO_VALUE) { neighbour_velocities[k+offset][l+offset][0] = Un[SECOND][i+k][j+l][0]; neighbour_velocities[k+offset][l+offset][1] = Un[SECOND][i+k][j+l][1]; } else { printf("SECOND i=%d j=%d k=%d l=%d\n",i,j,k,l); for(k=(-offset);k<=offset;k++) for(l=(-offset);l<=offset;l++) printf("vel for k=%d l=%d: %f,%f\n",k,l,Un[SECOND][i+k][j+l][0],Un[SECOND][i+k][j+l][1]); printf("\nFatal error: computed velocity undefined during iteration %d\n",iteration_number); exit(1); } calc_mean_and_covariance2(weights,neighbour_velocities,weighted_size, &Ua[i][j][0],&Sn[SECOND][i][j][0][0]); } } } if(PRINT_ITERATIONS) { sprintf(outname,"%s/singh.iteration.step2.%sF-%d",path,name,iteration_number-1); if((fd = creat(outname,0755))<0) { printf("Error creating file %s.\n",outname); exit(1); } printf("\nFile %s opened\n",outname); output_velocities(fd,&Un[SECOND][0][0][0],old_pic_x,old_pic_y,"Full",1); } /* Compute error statistics */ if(strcmp("unknown",correct_filename)!=0) { calc_statistics(correct_velocities,&Un[SECOND][0][0][0],old_pic_x,old_pic_y, &ave_error,&st_dev,&density,&min_angle,&max_angle,1); printf("Error Analysis Performed\n"); printf("Average Error: %f Standard Deviation: %f Density: %f\n", ave_error,st_dev,density); printf("Minimum Angle Error: %f Maximum Angle Error: %f\n",min_angle,max_angle); printf("L2norm of difference: %14.9f\n",bigL2norm(bigdiff,pic_x)); printf("Maximum individual velocity difference: %f\n\n",max_diff); fflush(stdout); } } /* Switch the values of FIRST and SECOND before next iteration */ temp = FIRST; FIRST = SECOND; SECOND = temp; } no_vels = 0; for(i=OFFSET_Y+EXTRA_OFFSET_Y;i<pic_y-OFFSET_Y;i++) for(j=OFFSET_X+EXTRA_OFFSET_X;j<pic_x-OFFSET_X;j++) { full_velocity[i][j][0] = Un[FIRST][i][j][0]; full_velocity[i][j][1] = Un[FIRST][i][j][1]; S[i][j][0][0] = SsumI[i][j][0][0]; S[i][j][1][0] = SsumI[i][j][1][0]; S[i][j][0][1] = SsumI[i][j][0][1]; S[i][j][1][1] = SsumI[i][j][1][1]; if(!(full_velocity[i][j][0]==NO_VALUE && full_velocity[i][j][1]==NO_VALUE)) no_vels++; else { printf("Velocity at %d,%d undefined\n",i,j); } } } /************************************************************************/ /* Threshold the velocities based of eigenvalues of covariance matrices */ /************************************************************************/ void threshold_velocities(float input_velocity[PIC_Y][PIC_X][2], float covariances[PIC_Y][PIC_X][2][2], float full_velocity[PIC_Y][PIC_X][2], int pic_x, int pic_y, float tau) { int i,j; float eigenvalues[2],eigenvector1[2],eigenvector2[2]; for(i=0;i<PIC_Y;i++) for(j=0;j<PIC_X;j++) full_velocity[i][j][0] = full_velocity[i][j][1] = NO_VALUE; /* Threshold the final result */ for(i=OFFSET_Y+EXTRA_OFFSET_Y;i<pic_y-OFFSET_Y;i++) for(j=OFFSET_X+EXTRA_OFFSET_X;j<pic_x-OFFSET_X;j++) { if(!(input_velocity[i][j][0] == NO_VALUE && input_velocity[i][j][1] == NO_VALUE)) { comp_eigen(&covariances[i][j][0][0],eigenvalues,eigenvector1,eigenvector2); if(fabs(eigenvalues[0]) < tau) { full_velocity[i][j][0] = input_velocity[i][j][0]; full_velocity[i][j][1] = input_velocity[i][j][1]; } else { full_velocity[i][j][0] = NO_VALUE; full_velocity[i][j][1] = NO_VALUE; } } else { full_velocity[i][j][0] = NO_VALUE; full_velocity[i][j][1] = NO_VALUE; } } } /************************************************************ Returns the norm of a vector v of length n. ************************************************************/ float L2norm(float v[], int n) { int i; float sum = 0.0; for (i=0;i<n; i++) sum += (float)(v[i]*v[i]); sum = sqrt(sum); return(sum); } /************************************************************ Output full velocities using Burkitt format ************************************************************/ void output_velocities(int fdf, float velocities[PIC_Y][PIC_X][2], int pic_x, int pic_y, char type[100], int SAMPLE) { float x,y; int i,j,bytes,no_novals,no_vals; if(fdf<0) { printf("\nFatal error: full velocity file not opened\n"); exit(1); } /* Original size */ x = pic_x; y = pic_y; write(fdf,&x,4); write(fdf,&y,4); /* Size of result data */ x = (pic_x-2*OFFSET_X); y = (pic_y-2*OFFSET_Y); write(fdf,&x,4); write(fdf,&y,4); /* Offset to start of data */ x = OFFSET_Y; y = OFFSET_X; write(fdf,&x,4); write(fdf,&y,4); bytes = 24; no_novals = no_vals = 0; /* Count velocity positions */ for(i=OFFSET_Y;i<pic_y-OFFSET_Y;i++) for(j=OFFSET_X;j<pic_x-OFFSET_X;j++) if(i%SAMPLE==0 && j%SAMPLE==0) { if(velocities[i][j][0] != NO_VALUE && velocities[i][j][1] != NO_VALUE) { no_vals++; } else { no_novals++; } } for(i=OFFSET_Y;i<pic_y-OFFSET_Y;i++) { bytes += write(fdf,&velocities[i][OFFSET_X][0],(pic_x-(2*OFFSET_X))*8); } close(fdf); printf("\n%s velocities output: %d bytes\n",type,bytes); printf("Number of positions with velocity: %d\n",no_vals); printf("Number of positions without velocity: %d\n",no_novals); printf("Percentage of %s velocities: %f\n",type, no_vals/(1.0*(no_vals+no_novals))*100.0); fflush(stdout); } /************************************************************ Output full velocities using Burkitt format ************************************************************/ void output_covariances(int fdf, float covariances[PIC_Y][PIC_X][2][2], int pic_x, int pic_y) { float x,y; int i,j,bytes,no_novals,no_vals; if(fdf<0) { printf("\nFatal error: covariance file not opened\n"); exit(1); } /* Original size */ x = pic_x; y = pic_y; write(fdf,&x,4); write(fdf,&y,4); /* Size of result data */ x = (pic_x-2*OFFSET_X); y = (pic_y-2*OFFSET_Y); write(fdf,&x,4); write(fdf,&y,4); /* Offset to start of data */ x = OFFSET_Y; y = OFFSET_X; write(fdf,&x,4); write(fdf,&y,4); bytes = 24; for(i=OFFSET_Y;i<pic_y-OFFSET_Y;i++) { bytes += write(fdf,&covariances[i][OFFSET_X][0][0],(pic_x-(2*OFFSET_X))*16); } close(fdf); printf("\nFull velocity covariance matrices output: %d bytes\n",bytes); fflush(stdout); } /************************************************************ Input full velocities using Burkitt format ************************************************************/ void input_velocities(int fdf,float velocities[PIC_Y][PIC_X][2], int pic_x, int pic_y) { float x,y; int i,j,bytes; for(i=0;i<PIC_Y;i++) for(j=0;j<PIC_X;j++) velocities[i][j][0] = velocities[i][j][1] = NO_VALUE; if(fdf<0) { printf("\nFatal error: full velocity file not opened\n"); exit(1); } /* Original size */ read(fdf,&x,4); read(fdf,&y,4); /* Size of result data */ read(fdf,&x,4); read(fdf,&y,4); /* Offset to start of data */ read(fdf,&x,4); read(fdf,&y,4); OFFSET_Y = x; OFFSET_X = y; bytes = 24; for(i=OFFSET_Y;i<pic_y-OFFSET_Y;i++) { bytes += read(fdf,&velocities[i][OFFSET_X][0],(pic_x-(2*OFFSET_X))*8); } close(fdf); printf("\nVelocities input: %d bytes\n",bytes); fflush(stdout); } /************************************************************ Output full velocities using Burkitt format ************************************************************/ void input_covariances(int fdf, float covariances[PIC_Y][PIC_X][2][2], int pic_x, int pic_y) { float x,y; int i,j,bytes; if(fdf<0) { printf("\nFatal error: covariance file not opened\n"); exit(1); } /* Original size */ read(fdf,&x,4); read(fdf,&y,4); /* Size of result data */ read(fdf,&x,4); read(fdf,&y,4); /* Offset to start of data */ read(fdf,&x,4); read(fdf,&y,4); bytes = 24; for(i=OFFSET_Y;i<pic_y-OFFSET_Y;i++) { bytes += read(fdf,&covariances[i][OFFSET_X][0][0],(pic_x-(2*OFFSET_X))*16); } close(fdf); printf("\nFull velocity covariance matrices input: %d bytes\n",bytes); fflush(stdout); } /***************************************************************************/ /* Compute average angle, standard deviation and density (as a percentage) */ /***************************************************************************/ void calc_statistics(float correct_vels[PIC_Y][PIC_X][2], float full_vels[PIC_Y][PIC_X][2], int pic_x, int pic_y, float*ave_error, float*st_dev, float*density, float*min_angle, float*max_angle, int SAMPLE) { int count,no_count,i,j; float sumX2,temp,uva[2],uve[2],sum2,temp1,sum1; float error[PIC_Y][PIC_X]; count = no_count = 0; sum2 = sumX2 = 0.0; (*min_angle) = HUGE; (*max_angle) = 0.0; (*ave_error) = (*st_dev) = 0.0; (*density) = 0.0; for(i=OFFSET_Y;i<pic_y-OFFSET_Y;i++) { for(j=OFFSET_X;j<pic_x-OFFSET_X;j++) if(i%SAMPLE==0 && j%SAMPLE==0) { if(full_vels[i][j][0] == NO_VALUE && full_vels[i][j][1] == NO_VALUE) { no_count++; error[i][j] = NO_VALUE; } else { count++; uve[0] = full_vels[i][j][0]; uve[1] = full_vels[i][j][1]; uva[0] = correct_vels[i][j][0]; uva[1] = correct_vels[i][j][1]; temp = PsiER(uve,uva,i,j); error[i][j] = temp; (*ave_error) += temp; sumX2 += temp*temp; if(temp < (*min_angle)) (*min_angle) = temp; if(temp > (*max_angle)) (*max_angle) = temp; } } } if(count != 0) (*ave_error) = (*ave_error)/(count*1.0); if(count > 1) { sum1 = 0.0; for(i=OFFSET_Y;i<pic_y-OFFSET_Y;i++) { for(j=OFFSET_X;j<pic_x-OFFSET_X;j++) if(i%SAMPLE==0 && j%SAMPLE==0) if(error[i][j] != NO_VALUE) { temp1 = error[i][j] - (*ave_error); temp1 = temp1*temp1; sum1 += temp1; } } (*st_dev) = sqrt(sum1/(count-1)); } else (*st_dev) = 0.0; (*density) = (count*100.0)/(count+no_count); if((*ave_error) == 0.0) { (*min_angle) = (*max_angle) = 0.0; } fflush(stdout); } /************************************************************ Full Image Velocity Angle Error ************************************************************/ float PsiER(ve,va,i,j) float ve[2],va[2]; int i,j; { float nva; float nve; float v,r; float VE[3],VA[3]; VE[0] = ve[0]; VE[1] = ve[1]; VE[2] = 1.0; VA[0] = va[0]; VA[1] = va[1]; VA[2] = 1.0; nva = L2norm(VA,3); nve = L2norm(VE,3); v = (VE[0]*VA[0]+VE[1]*VA[1]+1.0)/(nva*nve); /** sometimes roundoff error causes problems **/ if(v>1.0 && v < 1.0001) v = 1.0; r = acos(v)*TODEG; if(!(r>=0.0 && r< 180.0)) { printf("ERROR in PsiER()...\n r=%8.4f v=%8.4f nva=%8.4f nve= %8.4f\n", r,v,nva,nve); printf("va=(%f,%f) ve=(%f,%f)\n",va[0],va[1],ve[0],ve[1]); printf("i=%d j=%d\n",i,j); } return r; } /************************************************************ Normal Image Velocity Angle Error ************************************************************/ float PsiEN(ve,va) float ve[2],va[2]; { float nva,nve; float v1,v2; float n[2]; nva = L2norm(va,2), nve = L2norm(ve,2); if(nve > 0.00000001) { n[0] = ve[0]/nve; n[1] = ve[1]/nve; v1 = (va[0]*n[0] + va[1]*n[1]-nve) ; v2 = v1/(sqrt((1+nva*nva))*sqrt((1+nve*nve))); v1 = asin(v2)*TODEG; if(!(v1>=-90.0 && v1<=90.0)) { printf("ERROR in PsiEN() v1: %f ve: %f\n",v1,v2); printf("nve: %f nva: %f\n",nve,nva); printf("n: %f %f\n",n[0],n[1]); printf(" ve: %f %f va: %f %f\n",ve[0],ve[1],va[0],va[1]); fflush(stdout); } } else v1 = NO_VALUE; return fabs(v1); } /**************************************************************************/ /* Compute all eigenvalues and eigenvectors of a real symmetric matrix */ /* a[DIM][DIM]. On output elements of a above the disgonal are destroyed. */ /* d[DIM] returns the eigenvalues of a. v[DIM][DIM] is a matrix whose */ /* columns contain, on output, the normalized eigenvectors of a. nrot */ /* returns the number of Jacobi rotations that were required. */ /**************************************************************************/ void jacobi(aa,n,d,v,nrot) float aa[DIM][DIM],d[DIM],v[DIM][DIM]; int n,*nrot; { int j,iq,ip,i; float thresh,theta,tau,t,sm,s,h,g,c; float b[DIM],z[DIM],a[DIM][DIM]; if(n!=DIM) { fprintf(stderr,"\nFatal error: n not DIM %d in jacobi\n",DIM); exit(1); } for(ip=0;ip<n;ip++) /* Initialize to the identity matrix */ { for(iq=0;iq<n;iq++) v[ip][iq] = 0.0; for(iq=0;iq<n;iq++) a[ip][iq] = aa[ip][iq]; /* Don't destroy aa */ v[ip][ip] = 1.0; } /* Initialize b and d to the diagonals of a */ for(ip=0;ip<n;ip++) { b[ip] = d[ip] = a[ip][ip]; z[ip] = 0.0; } *nrot = 0; for(i=0;i<100;i++) { sm = 0.0; for(ip=0;ip<(n-1);ip++) { for(iq=ip+1;iq<n;iq++) sm += fabs(a[ip][iq]); } /* Normal return, which relies on quadratic convergence to machine underflow */ if(sm == 0.0) return; if(i<3) thresh=0.2*sm/(n*n); /* on the first three sweeps */ else thresh = 0.0; /* the rest of the sweeps */ for(ip=0;ip<(n-1);ip++) { for(iq=ip+1;iq<n;iq++) { g = 100.0*fabs(a[ip][iq]); /* After 4 sweeps skip the rotation if the off diagonal element is small */ if(i>3 && fabs(d[ip])+g == fabs(d[ip]) && fabs(d[iq])+g == fabs(d[iq])) a[ip][iq] = 0.0; else if(fabs(a[ip][iq]) > thresh) { h = d[iq]-d[ip]; if(fabs(h)+g==fabs(h)) t=(a[ip][iq])/h; else { theta = 0.5*h/(a[ip][iq]); t = 1.0/(fabs(theta)+sqrt(1.0+theta*theta)); if(theta < 0.0) t = -t; } c = 1.0/sqrt(1.0+t*t); s = t*c; tau = s/(1.0+c); h = t*a[ip][iq]; z[ip] -= h; z[iq] += h; d[ip] -= h; d[iq] += h; a[ip][iq] = 0.0; for(j=0;j<ip-1;j++) rotate(a,j,ip,j,iq,&h,&g,s,tau); for(j=ip+1;j<iq-1;j++) rotate(a,ip,j,j,iq,&h,&g,s,tau); for(j=iq+1;j<n;j++) rotate(a,ip,j,iq,j,&h,&g,s,tau); for(j=0;j<n;j++) rotate(v,j,ip,j,iq,&h,&g,s,tau); ++(*nrot); } } } for(ip=0;ip<n;ip++) { b[ip] += z[ip]; d[ip] = b[ip]; z[ip] = 0.0; } } /* fprintf(stderr,"\nFatal error: too many iterations in jacobi\n"); */ } /*********************************************************************/ /* Do rotations required by Jacobi Transformation */ /*********************************************************************/ void rotate(float a[DIM][DIM], int i, int j, int k, int l, float*h, float*g, float s, float tau) { (*g) = a[i][j]; (*h) = a[k][l]; a[i][j] = (*g)-s*((*h)+(*g)*tau); a[k][l] = (*h)+s*((*g)-(*h)*tau); } /*********************************************************************/ /* Compute the normalized mean and convariance matrix */ /* Step1: Recovery of Conservation Information. */ /*********************************************************************/ void calc_mean_and_covariance1(float calc[ARRSIZE][ARRSIZE], float mean[2], float covariance[2][2],float u_low, float u_high, float v_low, float v_high, float eigenvalues[2], float eigenvector1[2], float eigenvector2[2], int*vel_type, int N) { int i,j,k,Q,fdr,a,b,c,d,size; float inc[2],f_sum,uv[2],min,max,vx,vy,af,bf,est[2],temp[2][2],u,v,av,bv; unsigned char raster[ARRSIZE][ARRSIZE],name[100],path[100],command[100]; /* Compute normalized weighted mean */ (*vel_type) = FULL; max = -HUGE; min = HUGE; f_sum = 0.0; size = 2*N+1; for(i=0;i<size;i++) for(j=0;j<size;j++) { f_sum += calc[i][j]; if(calc[i][j] > max) { max = calc[i][j]; a=j; b=i; } if(calc[i][j] < min) { min = calc[i][j]; c=j; d=i; } } inc[0] = (u_high-u_low)/((size-1)*1.0); inc[1] = (v_high-v_low)/((size-1)*1.0); uv[0] = u_low; uv[1] = v_low; est[0] = uv[0]+(inc[0])*a; est[1] = uv[1]+(inc[1])*b; /* Compute weighted means */ af = bf = 0.0; for(i=0;i<size;i++) for(j=0;j<size;j++) { bv = uv[1]+inc[1]*i; av = uv[0]+inc[1]*j; bf += bv*calc[i][j]; af += av*calc[i][j]; } af = af/f_sum; bf = bf/f_sum; mean[0] = af; mean[1] = bf; /* Compute normalized weighted covariance matrix */ for(i=0;i<2;i++) for(j=0;j<2;j++) temp[i][j] = covariance[i][j] = 0.0; for(i=0;i<size;i++) for(j=0;j<size;j++) { bv = uv[1]+inc[1]*i; av = uv[0]+inc[0]*j; temp[0][0] = covariance[0][0] += (bv-bf)*(bv-bf)*calc[i][j]; temp[1][1] = covariance[1][1] += (av-af)*(av-af)*calc[i][j]; temp[0][1] = covariance[0][1] += (bv-bf)*(av-af)*calc[i][j]; } temp[1][0] = covariance[1][0] = covariance[0][1]; for(i=0;i<2;i++) for(j=0;j<2;j++) { temp[i][j] = (covariance[i][j] /= f_sum); } comp_eigen(temp,eigenvalues,eigenvector1,eigenvector2); (*vel_type) = FULL; } /************************************************************************/ /* Compute eigenvalues and eigenvectors of the covariance matrix */ /************************************************************************/ void comp_eigen(float A[DIM][DIM], float value[DIM], float vector1[DIM], float vector2[DIM]) { float v[2][2],temp,diff1[2],diff2[2],length1,length2,angle; float eigenvalues2[2],eigenvectors2[2][2]; int nrot,SWAP; SWAP = FALSE; jacobi(A,2,value,v,&nrot); /* if(value[0] < 0.0) { value[0] = -value[0]; v[0][0] = -v[0][0]; v[1][0] = -v[1][0]; } if(value[1] < 0.0) { value[1] = -value[1]; v[0][1] = -v[0][1]; v[1][1] = -v[1][1]; } */ /* The largest eigenvalue should be the first */ if(fabs(value[0]) > fabs(value[1])) { vector1[0] = v[0][0]; vector1[1] = v[1][0]; vector2[0] = v[0][1]; vector2[1] = v[1][1]; } else { temp = value[0]; value[0] = value[1]; value[1] = temp; vector2[0] = v[0][0]; vector2[1] = v[1][0]; vector1[0] = v[0][1]; vector1[1] = v[1][1]; temp = v[0][0]; v[0][0] = v[0][1]; v[0][1] = temp; temp = v[1][0]; v[1][0] = v[1][1]; v[1][1] = temp; SWAP = TRUE; } /* Check eigenvalue/eigenvector calculation */ if(check_eigen_calc(A,value,v,nrot,diff1,diff2,&length1,&length2,&angle)==FALSE) { printf("\n********************************************\n"); printf("Fatal error: eigenvalue/eigenvector error\n"); printf("eigenvalues: %f %f\n",value[0],value[1]); printf("eigenvector1: %f %f\n",v[0][0],v[1][0]); printf("eigenvector2: %f %f\n",v[0][1],v[1][1]); if(SWAP) printf("Eigenvalues/eigenvectors are swapped from original order\n"); printf("\n A:\n"); printf("%12.6f %12.6f\n",A[0][0],A[0][1]); printf("%12.6f %12.6f\n",A[1][0],A[1][1]); printf("Determinant of A: %f\n",A[0][0]*A[1][1]-A[0][1]*A[1][0]); printf("nrot: %d\n",nrot); printf("Angle between two eigenvectors: %f degrees\n",angle); printf("Difference length for eigenvector1\n"); printf("Difference: %f %f Length: %f\n",diff1[0],diff1[1],length1); printf("Difference length for eigenvector2\n"); printf("Difference: %f %f Length: %f\n",diff2[0],diff2[1],length2); /* Check eigenvalues/eigenvectors for 2*2 matrix using Anandan's method outlined in his thesis. */ eigenvalues2[0] = 0.5*((A[0][0]+A[1][1]) - sqrt((A[0][0]-A[1][1])*(A[0][0]-A[1][1])+4.0*A[0][1]*A[1][0])); eigenvalues2[1] = 0.5*((A[0][0]+A[1][1]) + sqrt((A[0][0]-A[1][1])*(A[0][0]-A[1][1])+4.0*A[0][1]*A[1][0])); angle = atan2(eigenvalues2[0]-A[0][0],A[0][1]); eigenvectors2[0][0] = -cos(angle); eigenvectors2[1][0] = -sin(angle); eigenvectors2[0][1] = -sin(angle); eigenvectors2[1][1] = cos(angle); printf("\nUsing Anandan's calculation:\n"); printf("Angle of rotation: %f degrees\n",angle*180/M_PI); printf("eigenvalues: %f %f\n",eigenvalues2[0],eigenvalues2[1]); printf("eigenvector1: %f %f\n",eigenvectors2[0][0],eigenvectors2[1][0]); printf("eigenvector2: %f %f\n",eigenvectors2[0][1],eigenvectors2[1][1]); check_eigen_calc(A,eigenvalues2,eigenvectors2,nrot,diff1,diff2, &length1,&length2,&angle); printf("Angle between two eigenvectors: %f degrees\n",angle); printf("Difference length for eigenvector1\n"); printf("Difference: %f %f Length: %f\n",diff1[0],diff1[1],length1); printf("Difference length for eigenvector2\n"); printf("Difference: %f %f Length: %f\n",diff2[0],diff2[1],length2); printf("Original eigenvalues set to infinity\n"); value[0] = value[1] = HUGE; printf("********************************************\n\n"); fflush(stdout); if(FALSE) exit(1); } } /*********************************************************************/ /* Check eigenvector and eigenvalue computation for 2*2 matrix */ /*********************************************************************/ int check_eigen_calc(mm,d,v,n,diff1,diff2,length1,length2,angle) float mm[2][2],d[2],v[2][2],diff1[2],diff2[2],*angle,*length1,*length2; int n; { int status; status = TRUE; /* Compute angle between two eigenvectors - should be orthogonal */ (*angle)=acos((v[0][0]*v[0][1]+v[1][0]*v[1][1])/ (sqrt(v[0][0]*v[0][0]+v[1][0]*v[1][0])* sqrt(v[0][1]*v[0][1]+v[1][1]*v[1][1])))*180.0/M_PI; if((*angle) < 89.5 && (*angle) > 90.5) { status = FALSE; } /* Eigenvector test */ diff1[0] = mm[0][0]*v[0][0]+mm[0][1]*v[1][0]; diff1[1] = mm[1][0]*v[0][0]+mm[1][1]*v[1][0]; diff1[0] = diff1[0] - d[0]*v[0][0]; diff1[1] = diff1[1] - d[0]*v[1][0]; if(((*length1)=sqrt(diff1[0]*diff1[0]+diff1[1]*diff1[1])) > 0.1) { status = FALSE; } diff2[0] = mm[0][0]*v[0][1]+mm[0][1]*v[1][1]; diff2[1] = mm[1][0]*v[0][1]+mm[1][1]*v[1][1]; diff2[0] = diff2[0] - d[1]*v[0][1]; diff2[1] = diff2[1] - d[1]*v[1][1]; if(((*length2)=sqrt(diff2[0]*diff2[0]+diff2[1]*diff2[1])) > 0.1) { status = FALSE; } if(n > 50) { status = FALSE; } return(status); } /*****************************************************************/ /* Compute the SSD surface for point (a,b) */ /*****************************************************************/ void compute_SSD_surface(fimages fpic, int x, int y, int n, int N, float SSDdata[ARRSIZE][ARRSIZE],int*max_a, int*max_b) { int u,v,u_index,v_index,i,j,a,b,fdr,pixel,size,c,d; float term1,term2,k,sum1,sum2,constant,sum_min,sum_max,max,min; float SSDvalues[MAX_ARRSIZE][MAX_ARRSIZE]; float SSDvalues1[MAX_ARRSIZE][MAX_ARRSIZE]; float SSDvalues2[MAX_ARRSIZE][MAX_ARRSIZE]; float SSDmin,SSDmax,SSDmag; unsigned char raster[MAX_ARRSIZE][MAX_ARRSIZE]; unsigned path[100],name[100],command[100]; constant = 0.95; size = 2*N; /****************************************************************/ /* Compute the SSD surfaces for left and right images about x,y */ /* in a 4N+1 bu 4N+1 area */ /****************************************************************/ for(u=(-size);u<=size;u++) for(v=(-size);v<=size;v++) { u_index = u+size; v_index = v+size; sum1 = 0.0; sum2 = 0.0; for(i=(-n);i<=n;i++) for(j=(-n);j<=n;j++) { term1 = (fpic[1][x+i][y+j]-fpic[2][x+i+u][y+j+v]); term2 = (fpic[1][x+i][y+j]-fpic[0][x+i+u][y+j+v]); sum1 += term1*term1; sum2 += term2*term2; } SSDvalues1[u_index][v_index] = sum1; SSDvalues2[2*size-u_index][2*size-v_index] = sum2; } /****************************************************************************/ /* Add the left and right SSD surfaces and compute minimum SSD coordinates */ /* in 2N+1 by 2N+1 area centered about the origin of 4N+1 by 4N+1 SSD data */ /****************************************************************************/ sum_min = HUGE; sum_max = -HUGE; SSDmin = HUGE; SSDmax = -HUGE; a = b = 0; SSDmag = 0.0; for(u=(-size);u<=size;u++) for(v=(-size);v<=size;v++) { u_index = u+size; v_index = v+size; SSDvalues[u_index][v_index] = SSDvalues1[u_index][v_index]+ SSDvalues2[u_index][v_index]; /* Only look for peak in 2N+1 by 2N+1 region centered at origin */ if(u >= -N && u <= N && v >= -N && v <= N) { if((fabs(SSDvalues[u_index][v_index]-sum_min) <= SMALL && (u*u+v*v) < SSDmag) || ((sum_min-SSDvalues[u_index][v_index]) > SMALL)) { sum_min=SSDvalues[u_index][v_index]; a=u; b=v; SSDmag = (u*u+v*v); } if(SSDvalues[u_index][v_index] > sum_max) { sum_max=SSDvalues[u_index][v_index]; } } if(SSDvalues[u_index][v_index] > SSDmax) SSDmax = SSDvalues[u_index][v_index]; if(SSDvalues[u_index][v_index] < SSDmin) SSDmin = SSDvalues[u_index][v_index]; } (*max_a) = a; (*max_b) = b; /* A test: compute the locations of n=10 minimum SSD responses */ if(FALSE) { if((x>=PT_X1-2 && x<= PT_X1+2&& y>=PT_Y1-2 && y<=PT_Y1+2) || (x>=PT_X2-2 && x<= PT_X2+2&& y>=PT_Y2-2 && y<=PT_Y2+2)) { printf("\nBig Minimum data at image point: %d,%d\n",x,y); printf("max_a: %d max_b: %d\n",*max_a,*max_b); compute_big_n_minimums(SSDvalues,size,20); } } /*******************************************/ /* Center SSD computation by extracting */ /* 2N+1 by 2N+1 SSD sub-surface about peak */ /*******************************************/ sum_min = HUGE; c = d = 0; for(u=(-N);u<=N;u++) for(v=(-N);v<=N;v++) { u_index = u+N; v_index = v+N; SSDdata[u_index][v_index] = SSDvalues[u_index+a+N][v_index+b+N]; /* Compute minimum non-zero SSD value */ if(SSDdata[u_index][v_index] < sum_min && SSDdata[u_index][v_index] != 0.0) { sum_min=SSDdata[u_index][v_index]; c=u_index; d=v_index;} } if(((x>=PT_X1-2 && x<= PT_X1+2&& y>=PT_Y1-2 && y<=PT_Y1+2) || (x>=PT_X2-2 && x<= PT_X2+2&& y>=PT_Y2-2 && y<=PT_Y2+2)) && FALSE) printf("c=%d d=%d u=%d v=%d\n",c,d,c-N,d-N); /* A test: compute the locations of n=10 minimum SSD responses */ if(FALSE) { if((x>=PT_X1-2 && x<= PT_X1+2&& y>=PT_Y1-2 && y<=PT_Y1+2) || (x>=PT_X2-2 && x<= PT_X2+2&& y>=PT_Y2-2 && y<=PT_Y2+2)) { printf("\nMinimum data at image point: %d,%d about: %d %d\n",x,y,a,b); compute_n_minimums(SSDdata,N,20); } } /**********************************************************************/ /* Compute a k value and recompute the SSD surface using it. */ /**********************************************************************/ if(sum_min < 1.0e-6) k = 0.0085; else k = -log(constant)/sum_min; min = HUGE; max = -HUGE; for(u=(-N);u<=N;u++) for(v=(-N);v<=N;v++) { u_index = u+N; v_index = v+N; SSDdata[u_index][v_index] = exp(-k*SSDdata[u_index][v_index]); if(SSDdata[u_index][v_index] > max) max = SSDdata[u_index][v_index]; if(SSDdata[u_index][v_index] < min) min = SSDdata[u_index][v_index]; } } /*********************************************************************/ /* Compute the normalized mean and convariance matrix */ /* Step2: Recovery of Neighbourhood Information. */ /*********************************************************************/ void calc_mean_and_covariance2(float weights[WEIGHTSIZE][WEIGHTSIZE], float velocities[WEIGHTSIZE][WEIGHTSIZE][2], int weighted_size, float mean[2], float covariance[2][2]) { int i,j,k,Q,fdr,a,b; float vx,vy,w_sum; /* Compute weighted means - sum of weights is 1.0 */ w_sum = vx = vy = 0.0; for(i=0;i<weighted_size;i++) for(j=0;j<weighted_size;j++) { if(velocities[i][j][0] != NO_VALUE && velocities[i][j][1] != NO_VALUE) { w_sum += weights[i][j]; vx += weights[i][j]*velocities[i][j][0]; vy += weights[i][j]*velocities[i][j][1]; } } mean[0] = vx; mean[1] = vy; /* Compute normalized weighted covariance matrix */ for(i=0;i<2;i++) for(j=0;j<2;j++) covariance[i][j] = 0.0; /* Sum of the weights is 1.0 so no need to normalize */ for(i=0;i<weighted_size;i++) for(j=0;j<weighted_size;j++) { if(velocities[i][j][0] != NO_VALUE && velocities[i][j][1] != NO_VALUE) { covariance[0][0] += (velocities[i][j][0]-vx)*(velocities[i][j][0]-vx)*weights[i][j]; covariance[1][1] += (velocities[i][j][1]-vy)*(velocities[i][j][1]-vy)*weights[i][j]; covariance[0][1] += (velocities[i][j][0]-vx)*(velocities[i][j][1]-vy)*weights[i][j]; } } covariance[0][0] /= w_sum; covariance[0][1] /= w_sum; covariance[1][1] /= w_sum; covariance[1][0] = covariance[0][1]; } /**********************************************************************/ /* Invert 2*2 matrix if possible */ /**********************************************************************/ int old_inverse22(M,MI) float M[2][2],MI[2][2]; { float denominator; /* Invert 2*2 matrix */ denominator = M[0][0]*M[1][1]-M[1][0]*M[0][1]; /* The determinant of M */ if(fabs(denominator) >= 0.000000001) { MI[0][0] = M[1][1]/denominator; MI[0][1] = -M[0][1]/denominator; MI[1][0] = -M[1][0]/denominator; MI[1][1] = M[0][0]/denominator; printf(" M MI\n"); printf("%12.8f %12.8f %12.8f %12.8f\n",M[0][0],M[0][1],MI[0][0],MI[0][1]); printf("%12.8f %12.8f %12.8f %12.8f\n",M[1][0],M[1][1],MI[1][0],MI[1][1]); printf("Determinant: %f\n",denominator); return(FALSE); /* Not singular */ } else { MI[0][0] = 1.0; MI[0][1] = 0.0; MI[1][0] = 0.0; MI[1][1] = HUGE; printf(" M MI\n"); printf("%12.8f %12.8f %12.8f %12.8f\n",M[0][0],M[0][1],MI[0][0],MI[0][1]); printf("%12.8f %12.8f %12.8f %12.8f\n",M[1][0],M[1][1],MI[1][0],MI[1][1]); printf("Determinant: %f\n",denominator); return(TRUE); /* Singular */ } } /***********************************************************************/ /* Add two vectors, a and b, and place result in c */ /***********************************************************************/ void add21(float a[2], float b[2], float c[2]) { c[0] = a[0] + b[0]; c[1] = a[1] + b[1]; } /***********************************************************************/ /* Add two 2*2 matrices S1 and S2 and save the result in 2*2 matrix s3 */ /***********************************************************************/ void add22(float S1[2][2], float S2[2][2], float S3[2][2]) { S3[0][0] = S1[0][0] + S2[0][0]; S3[1][0] = S1[1][0] + S2[1][0]; S3[0][1] = S1[0][1] + S2[0][1]; S3[1][1] = S1[1][1] + S2[1][1]; } /***********************************************************************/ /* Multiple a 2*2 matrix and a 2*1 vector */ /***********************************************************************/ void mult21(float A[2][2], float b[2], float x[2]) { x[0] = A[0][0]*b[0]+A[0][1]*b[1]; x[1] = A[1][0]*b[0]+A[1][1]*b[1]; } /**********************************************************************/ /* Compute 2D Gaussian weights */ /**********************************************************************/ void compute_weights(float weights[WEIGHTSIZE][WEIGHTSIZE], int w) { int i,j,offset,weighted_size; float kernel[WEIGHTSIZE],term1,term2,sum; weighted_size = 2*w+1; if(w==1) { kernel[0] = 0.25; kernel[1] = 0.5; kernel[2] = 0.25; sum = 0.0; for(i=0;i<(weighted_size);i++) for(j=0;j<(weighted_size);j++) { weights[i][j] = kernel[i]*kernel[j]; sum += weights[i][j]; } if(sum!=1.0) { printf("Fatal error: sum of Gaussian coefficients is zero\n"); exit(1); } } else if(w==2) { kernel[0] = 0.0625; kernel[1] = 0.25; kernel[2] = 0.375; kernel[3] = 0.25; kernel[4] = 0.0625; sum = 0.0; for(i=0;i<(weighted_size);i++) for(j=0;j<(weighted_size);j++) { weights[i][j] = kernel[i]*kernel[j]; sum += weights[i][j]; } if(sum!=1.0) { printf("Fatal error: sum of Gaussian coefficients is zero\n"); exit(1); } } else { printf("\nFatal error: window size not 1 or 2: w=%d\n",w); exit(1); } printf("\nWeights:\n"); for(i=0;i<(weighted_size);i++) { for(j=0;j<(weighted_size);j++) printf("%8.5f ",weights[i][j]); printf("\n"); } } /*************************************************************************/ /* Compute the pseudo-inverse of J using its SVD */ /*************************************************************************/ int inverse22(J,JI, print) float J[NO_ROWS][NO_COLS], JI[NO_COLS][NO_ROWS]; int print; { extern void dsvdc(double [], int* , int*, int*, double [], double [], double [], int*, double [], int* , double [], int*, int*); int size; float VT[NO_COLS][NO_COLS]; float U[NO_COLS][NO_ROWS],DI[NO_COLS][NO_COLS]; float UT[NO_ROWS][NO_COLS],V[NO_COLS][NO_COLS]; float D[NO_COLS][NO_COLS],I[NO_COLS][NO_COLS]; double JT[NO_COLS][NO_ROWS], W[NO_ROWS+1], zero[NO_COLS]; double UU[NO_COLS][NO_ROWS],temp[NO_ROWS],VV[NO_COLS][NO_COLS]; float min,max,cond,best,worst; int i,j,k,m,n,mdim,error,Ierr,job; size = NO_ROWS; n = NO_COLS; m = NO_ROWS; mdim = NO_ROWS; for(i=0;i<NO_COLS;i++) for(j=0;j<size;j++) JT[i][j] = J[j][i]; job = 21; dsvdc(JT,&mdim,&m,&n,W,zero,UU,&mdim,VV,&n,temp,&job,&Ierr); for(i=0;i<size;i++) for(j=0;j<NO_COLS;j++) { U[j][i] = UU[j][i]; UT[i][j] = UU[j][i]; } for(i=0;i<NO_COLS;i++) for(j=0;j<NO_COLS;j++) { V[i][j] = VV[i][j]; D[i][j] = DI[i][j] = 0.0; } for(i=0;i<NO_COLS;i++) for(j=0;j<NO_COLS;j++) VT[i][j] = V[j][i]; for(i=0;i<NO_COLS;i++) D[i][i] = W[i]; min = W[0]; max = W[0]; for(i=1;i<NO_COLS;i++) { if(W[i] > max) max=W[i]; if(W[i] < min) min=W[i]; } if(min != 0.0) { cond = max/min; worst = 1.0/min; } else { cond = HUGE; worst = HUGE; } best = 1.0/max; for(i=0;i<NO_COLS;i++) if(D[i][i] !=0.0) DI[i][i] = 1.0/D[i][i]; else DI[i][i] = HUGE; if(print) printf("\nIerr=%d DI[0][0]: %f DI[1][1]: %f\n",Ierr,DI[0][0],DI[1][1]); /* Check correctness of SVD, compute I = JI*J */ if(DI[0][0] <= 10.0 && DI[1][1] <= 10.0) { for(i=0;i<NO_COLS;i++) for(j=0;j<NO_COLS;j++) { V[i][j] = 0.0; for(k=0;k<NO_COLS;k++) V[i][j] = V[i][j] + VT[i][k]*DI[k][j]; } for(i=0;i<NO_COLS;i++) for(j=0;j<size;j++) { JI[i][j] = 0.0; for(k=0;k<NO_COLS;k++) JI[i][j] = JI[i][j] + V[i][k]*U[k][j]; } for(i=0;i<NO_COLS;i++) for(j=0;j<NO_COLS;j++) { I[i][j] = 0.0; for(k=0;k<size;k++) I[i][j] = I[i][j] + JI[i][k]*J[k][j]; } /* Check I */ error = FALSE; for(i=0;i<NO_COLS;i++) for(j=0;j<NO_COLS;j++) { if(i==j) { if(fabs(I[i][i])<0.9999 || fabs(I[i][i])>1.0001) error=TRUE; } else if(fabs(I[i][j]) > 0.0001) error=TRUE; } if(error==TRUE) { printf("\nFatal error: Pseudo-inverse of J wrong\n"); printf("The identity matrix:\n"); for(i=0;i<NO_COLS;i++) { for(j=0;j<NO_COLS;j++) printf("%6.3f ",I[i][j]); printf("\n"); } fflush(stdout); exit(1); } } else /* Set inverse elements over 10 to 10 and compute inverse */ { if(DI[0][0] > 10.0) DI[0][0] = 10.0; if(DI[1][1] > 10.0) DI[1][1] = 10.0; COUNT_SINGULAR++; /* JI[0][0] = 10.0; JI[0][1] = 0.0; JI[1][0] = 0.0; JI[1][1] = 10.0; */ if(TRUE) { for(i=0;i<NO_COLS;i++) for(j=0;j<NO_COLS;j++) { VV[i][j] = 0.0; for(k=0;k<NO_COLS;k++) VV[i][j] = VV[i][j] + VT[i][k]*DI[k][j]; } for(i=0;i<NO_COLS;i++) for(j=0;j<size;j++) { JI[i][j] = 0.0; for(k=0;k<NO_COLS;k++) JI[i][j] = JI[i][j] + VV[i][k]*U[k][j]; } } } if(print) { printf("Diagonal(s) greater than 10\n"); printf(" J JI\n"); printf("%12.8f %12.8f %12.8f %12.8f\n",J[0][0],J[0][1],JI[0][0],JI[0][1]); printf("%12.8f %12.8f %12.8f %12.8f\n",J[1][0],J[1][1],JI[1][0],JI[1][1]); } return(FALSE); /* The inverse matrix is guaranteed to be non-singular */ } /************************************************************ Convolve images with center surround filter, i.e. a DOG (Difference of Gaussians) ************************************************************/ void laplacian(cimages cpic, fimages fpic, float sigma, int pic_x, int pic_y) { int i,j,k,l,m,OFFSET,count,no_count; float sigma2,begin,end; float val2,pic2[PIC_Y][PIC_X]; float h2[TOTAL],const2,x1,x2; float pic22[PIC_Y][PIC_X],min,max; /* Use the original image as first image and subtract a second Gaussian blurred image (with sigma2 from it */ sigma2 = sigma; const2 = 1.0/(sqrt(2.0*M_PI)*sigma2); OFFSET = (int) (6*sigma2+1)/2.0; for(i=0,x1=(-OFFSET),x2=(-OFFSET);i<=2*OFFSET;i++,x1++,x2++) { h2[i] = const2 * exp((-x2*x2)/(2.0*sigma2*sigma2)); } /* Do convolutions using separable 2D filters */ printf("\nComputing Laplacian as a center-surround filter...\n"); printf("sigma1=%f sigma2=%f\n",0.0,sigma2); for(i=0;i<NUMFILES; i++) { printf("\n\n"); for(j=0;j<pic_y;j++) { for(k=OFFSET;k<pic_x-OFFSET;k++) { val2 = 0.0; for(l=(-OFFSET);l<=OFFSET;l++) { val2 += cpic[i][j][k+l]*h2[l+OFFSET]; } pic2[j][k] = val2; } } printf("Image #%d - column convolution completed\n",i); fflush(stdout); for(j=OFFSET;j<pic_y-OFFSET;j++) { for(k=OFFSET;k<pic_x-OFFSET;k++) { val2 = 0.0; for(m=(-OFFSET);m<=OFFSET;m++) { val2 += pic2[j+m][k]*h2[m+OFFSET]; } pic22[j][k] = val2; } } printf("Image #%d - row convolution completed\n",i); fflush(stdout); /* Subtract blurred images to obtain Laplacian of Gaussian */ min = HUGE; max = -HUGE; for(j=OFFSET;j<pic_y-OFFSET;j++) for(k=OFFSET;k<pic_x-OFFSET;k++) { fpic[i][j][k] = (((float) cpic[i][j][k]) - pic22[j][k]); if(fpic[i][j][k] < min) min=fpic[i][j][k]; if(fpic[i][j][k] > max) max=fpic[i][j][k]; } printf("Gaussian images subtracted\n"); printf("Minimum value: %f Maximun value: %f\n",min,max); fflush(stdout); for(j=OFFSET;j<pic_y-OFFSET;j++) for(k=OFFSET;k<pic_x-OFFSET;k++) cpic[i][j][k] = ((int) (fpic[i][j][k]-min)/(max-min)*255); } } /*************************************************************************/ /* Make the image grayvalues stored in cpic as unsigned characters into */ /* float numbers stored in fpic. */ /*************************************************************************/ void make_float(cimages cpic, fimages fpic, int pic_x, int pic_y) { int i,j,k; for(k=0;k<3;k++) for(i=0;i<pic_y;i++) for(j=0;j<pic_x;j++) fpic[k][i][j] = (float) cpic[k][i][j]; } /*************************************************************************/ /* Compute the n maximum data values and their locations in the array. */ /*************************************************************************/ void compute_n_minimums(float data[ARRSIZE][ARRSIZE], int N, int n) { int i,j,u,v,u_index,v_index,u_min,v_min; float min_value; float SSD[ARRSIZE][ARRSIZE],SSDmag; /* Copy SSD data so we can modify it without affecting the SSD data */ for(i=0;i<2*N+1;i++) { for(j=0;j<2*N+1;j++) { SSD[i][j] = data[i][j]; } } for(i=0;i<n;i++) { min_value = HUGE; SSDmag = HUGE; u_min = v_min = 0; for(u=(-N);u<=N;u++) for(v=(-N);v<=N;v++) { u_index = u+N; v_index = v+N; if((fabs(SSD[u_index][v_index]-min_value) <= SMALL && (u*u+v*v < SSDmag)) || SSD[u_index][v_index] < min_value) { min_value = SSD[u_index][v_index]; SSDmag = u*u+v*v; u_min = u; v_min = v; } } SSD[u_min+N][v_min+N] = HUGE; printf("%dth minimum: %f at %d,%d\n",i,min_value,u_min,v_min); } } /*************************************************************************/ /* Compute the n maximum data values and their locations in the array. */ /*************************************************************************/ void compute_big_n_minimums(float data[MAX_ARRSIZE][MAX_ARRSIZE], int N, int n) { int i,j,u,v,u_index,v_index,u_min,v_min; float min_value; float SSD[MAX_ARRSIZE][MAX_ARRSIZE],SSDmag; /* Copy SSD data so we can modify it without affecting the SSD data */ for(i=0;i<2*N+1;i++) { for(j=0;j<2*N+1;j++) { SSD[i][j] = data[i][j]; } } for(i=0;i<n;i++) { min_value = HUGE; SSDmag = 0.0; u_min = v_min = 0; for(u=(-N);u<=N;u++) for(v=(-N);v<=N;v++) { u_index = u+N; v_index = v+N; if((fabs(SSD[u_index][v_index]-min_value) <= SMALL && (u*u+v*v < SSDmag)) || (min_value-SSD[u_index][v_index] > SMALL)) { min_value = SSD[u_index][v_index]; SSDmag = u*u+v*v; u_min = u; v_min = v; } } SSD[u_min+N][v_min+N] = HUGE; printf("%dth minimum: %f at %d,%d SSDmag: %d\n",i,min_value,u_min,v_min,u_min*u_min+v_min*v_min); } } float bigL2norm(float bigdiff[PIC_X][PIC_Y][2], int n) { int i,j,ct; float sum; sum = 0.0; ct = 0; for(i=0;i<n;i++) for(j=0;j<n;j++) { if(bigdiff[i][j][0] != NO_VALUE && bigdiff[i][j][1] != NO_VALUE) { sum += bigdiff[i][j][1]*bigdiff[i][j][1]+bigdiff[i][j][0]*bigdiff[i][j][0]; ct++; } } return(sqrt(sum)); }
the_stack_data/471169.c
#include <stdio.h> #include <stdlib.h> #include <math.h> int nbDeChiffres(int x); int estPair(int x); int extraitNombre(int x, int n, int lg); int sommeDesChiffres(int x); int main() { int x = 45863047; printf("Entrer un nombre x: "); scanf("%d", &x); if (!estPair(x)) exit(EXIT_FAILURE); int nC = nbDeChiffres(x); int eN_1 = extraitNombre(x, 0, floor(nC / 2)); int eN_2 = extraitNombre(x, floor(nC / 2), nC); int estCouicable = sommeDesChiffres(eN_1) == sommeDesChiffres(eN_2); printf("%d est couicable ? : %s\n", x, estCouicable ? "Oui" : "Non"); } int nbDeChiffres(int x) { int nbr = 0; while (x > 0) { x /= 10; nbr++; } return nbr; } int estPair(int x) { return nbDeChiffres(x) % 2 == 0; } int extraitNombre(int x, int n, int lg) { return (int)(x / pow(10, n)) % (int)pow(10, lg); } int sommeDesChiffres(int x) { int somme = 0, m; while (x >= 10) { m = floor(x / 10); somme += x - 10 * m; x = m; } return x + somme; }
the_stack_data/36181.c
// RUN: %clang_cc1 -triple powerpc64-unknown-linux-gnu -emit-llvm %s \ // RUN: -target-cpu pwr7 -o - | FileCheck %s // RUN: %clang_cc1 -triple powerpc64le-unknown-linux-gnu -emit-llvm %s \ // RUN: -target-cpu pwr8 -o - | FileCheck %s // RUN: %clang_cc1 -triple powerpc64-unknown-aix -emit-llvm %s \ // RUN: -target-cpu pwr7 -o - | FileCheck %s // RUN: %clang_cc1 -triple powerpc-unknown-aix -emit-llvm %s \ // RUN: -target-cpu pwr7 -o - | FileCheck %s // CHECK-LABEL: @mtfsb0( // CHECK: call void @llvm.ppc.mtfsb0(i32 10) // CHECK-NEXT: ret void // void mtfsb0 (void) { __mtfsb0 (10); } // CHECK-LABEL: @mtfsb1( // CHECK: call void @llvm.ppc.mtfsb1(i32 0) // CHECK-NEXT: ret void // void mtfsb1 (void) { __mtfsb1 (0); } // CHECK-LABEL: @mtfsf( // CHECK: [[TMP0:%.*]] = uitofp i32 %{{.*}} to double // CHECK-NEXT: call void @llvm.ppc.mtfsf(i32 8, double [[TMP0]]) // CHECK-NEXT: ret void // void mtfsf (unsigned int ui) { __mtfsf (8, ui); } // CHECK-LABEL: @mtfsfi( // CHECK: call void @llvm.ppc.mtfsfi(i32 7, i32 15) // CHECK-NEXT: ret void // void mtfsfi (void) { __mtfsfi (7, 15); } // CHECK-LABEL: @fmsub( // CHECK: [[D_ADDR:%.*]] = alloca double, align 8 // CHECK-NEXT: store double [[D:%.*]], double* [[D_ADDR]], align 8 // CHECK-NEXT: [[TMP0:%.*]] = load double, double* [[D_ADDR]], align 8 // CHECK-NEXT: [[TMP1:%.*]] = load double, double* [[D_ADDR]], align 8 // CHECK-NEXT: [[TMP2:%.*]] = load double, double* [[D_ADDR]], align 8 // CHECK-NEXT: [[TMP3:%.*]] = call double @llvm.ppc.fmsub(double [[TMP0]], double [[TMP1]], double [[TMP2]]) // CHECK-NEXT: ret double [[TMP3]] // double fmsub (double d) { return __fmsub (d, d, d); } // CHECK-LABEL: @fmsubs( // CHECK: [[F_ADDR:%.*]] = alloca float, align 4 // CHECK-NEXT: store float [[F:%.*]], float* [[F_ADDR]], align 4 // CHECK-NEXT: [[TMP0:%.*]] = load float, float* [[F_ADDR]], align 4 // CHECK-NEXT: [[TMP1:%.*]] = load float, float* [[F_ADDR]], align 4 // CHECK-NEXT: [[TMP2:%.*]] = load float, float* [[F_ADDR]], align 4 // CHECK-NEXT: [[TMP3:%.*]] = call float @llvm.ppc.fmsubs(float [[TMP0]], float [[TMP1]], float [[TMP2]]) // CHECK-NEXT: ret float [[TMP3]] // float fmsubs (float f) { return __fmsubs (f, f, f); } // CHECK-LABEL: @fnmadd( // CHECK: [[D_ADDR:%.*]] = alloca double, align 8 // CHECK-NEXT: store double [[D:%.*]], double* [[D_ADDR]], align 8 // CHECK-NEXT: [[TMP0:%.*]] = load double, double* [[D_ADDR]], align 8 // CHECK-NEXT: [[TMP1:%.*]] = load double, double* [[D_ADDR]], align 8 // CHECK-NEXT: [[TMP2:%.*]] = load double, double* [[D_ADDR]], align 8 // CHECK-NEXT: [[TMP3:%.*]] = call double @llvm.ppc.fnmadd(double [[TMP0]], double [[TMP1]], double [[TMP2]]) // CHECK-NEXT: ret double [[TMP3]] // double fnmadd (double d) { return __fnmadd (d, d, d); } // CHECK-LABEL: @fnmadds( // CHECK: [[F_ADDR:%.*]] = alloca float, align 4 // CHECK-NEXT: store float [[F:%.*]], float* [[F_ADDR]], align 4 // CHECK-NEXT: [[TMP0:%.*]] = load float, float* [[F_ADDR]], align 4 // CHECK-NEXT: [[TMP1:%.*]] = load float, float* [[F_ADDR]], align 4 // CHECK-NEXT: [[TMP2:%.*]] = load float, float* [[F_ADDR]], align 4 // CHECK-NEXT: [[TMP3:%.*]] = call float @llvm.ppc.fnmadds(float [[TMP0]], float [[TMP1]], float [[TMP2]]) // CHECK-NEXT: ret float [[TMP3]] // float fnmadds (float f) { return __fnmadds (f, f, f); } // CHECK-LABEL: @fnmsub( // CHECK: [[D_ADDR:%.*]] = alloca double, align 8 // CHECK-NEXT: store double [[D:%.*]], double* [[D_ADDR]], align 8 // CHECK-COUNT-3: load double, double* [[D_ADDR]], align 8 // CHECK-NEXT: [[TMP0:%.*]] = load double, double* [[D_ADDR]], align 8 // CHECK-NEXT: [[TMP1:%.*]] = load double, double* [[D_ADDR]], align 8 // CHECK-NEXT: [[TMP2:%.*]] = load double, double* [[D_ADDR]], align 8 // CHECK-NEXT: [[TMP3:%.*]] = call double @llvm.ppc.fnmsub.f64(double [[TMP0]], double [[TMP1]], double [[TMP2]]) // CHECK-NEXT: ret double [[TMP3]] // double fnmsub (double d) { return __fnmsub (d, d, d); } // CHECK-LABEL: @fnmsubs( // CHECK: [[F_ADDR:%.*]] = alloca float, align 4 // CHECK-NEXT: store float [[F:%.*]], float* [[F_ADDR]], align 4 // CHECK-COUNT-3: load float, float* [[F_ADDR]], align 4 // CHECK-NEXT: [[TMP0:%.*]] = load float, float* [[F_ADDR]], align 4 // CHECK-NEXT: [[TMP1:%.*]] = load float, float* [[F_ADDR]], align 4 // CHECK-NEXT: [[TMP2:%.*]] = load float, float* [[F_ADDR]], align 4 // CHECK-NEXT: [[TMP3:%.*]] = call float @llvm.ppc.fnmsub.f32(float [[TMP0]], float [[TMP1]], float [[TMP2]]) // CHECK-NEXT: ret float [[TMP3]] // float fnmsubs (float f) { return __fnmsubs (f, f, f); } // CHECK-LABEL: @fre( // CHECK: [[D_ADDR:%.*]] = alloca double, align 8 // CHECK-NEXT: store double [[D:%.*]], double* [[D_ADDR]], align 8 // CHECK-NEXT: [[TMP0:%.*]] = load double, double* [[D_ADDR]], align 8 // CHECK-NEXT: [[TMP1:%.*]] = call double @llvm.ppc.fre(double [[TMP0]]) // CHECK-NEXT: ret double [[TMP1]] // double fre (double d) { return __fre (d); } // CHECK-LABEL: @fres( // CHECK: [[F_ADDR:%.*]] = alloca float, align 4 // CHECK-NEXT: store float [[F:%.*]], float* [[F_ADDR]], align 4 // CHECK-NEXT: [[TMP0:%.*]] = load float, float* [[F_ADDR]], align 4 // CHECK-NEXT: [[TMP1:%.*]] = call float @llvm.ppc.fres(float [[TMP0]]) // CHECK-NEXT: ret float [[TMP1]] // float fres (float f) { return __fres (f); }
the_stack_data/119376.c
#include <stdio.h> #include <string.h> int main(void) { char b_word[81]; char a_word[81]; gets(b_word); int a = 0; int i = strlen(b_word) - 1; while (i >= 0){ int j = i; while(j > 0 && b_word[j - 1] != ' ') { j--; if(j == 0) break; } int len = -(j - i - 1); for (;j <= i; j++) { a_word[a] = b_word[j]; if(a <= strlen(b_word) - 1) a++; } if(a < strlen(b_word) - 1) { a_word[a] = ' '; a++; } i = i - len - 1; } a_word[a] = 0; puts(a_word); }
the_stack_data/140765383.c
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <ctype.h> //from https://www.geeksforgeeks.org/xor-cipher/ void encryptDecrypt(char inpString[100]) { // Define XOR key // Any character value will work char xorKey = '!'; // calculate length of input string int len = strlen(inpString); // perform XOR operation of key // with every caracter in string for (int i = 0; i < len; i++) { inpString[i] = inpString[i] ^ xorKey; } } int validateInput(char filename[100]) { int len = strlen(filename); char safeFilename[len + 4]; char ch; int count = 0; for (int i = 0; i < len; i++) { ch = filename[i]; //validate input for filename if (isalnum(ch)) { safeFilename[count] = ch; count++; } } safeFilename[count] = '.'; safeFilename[count + 1] = 't'; safeFilename[count + 2] = 'x'; safeFilename[count + 3] = 't'; if (strcmp(safeFilename, ".txt") == 0){ strlcpy(safeFilename, "passfile.txt", 12); } strlcpy(filename, safeFilename, len + 5); return 0; } int CreateSaferPassword(char filename[100], char password[100]) { //buffer much larger than we need FILE *passFile; //printf("about to validate input \n"); //validate input //printf("about to open file in safefile's name\n"); char safeFilename[100]; strlcpy(safeFilename, filename, 100); validateInput(safeFilename); //printf(safeFilename); //flawfinder: ignore //printf("\n"); passFile = fopen(safeFilename, "wb+"); //encrypt password so people can't just find it or change it //printf("about to encrypt\n"); char encryptedPassword[100]; strlcpy(encryptedPassword, password, 100); encryptDecrypt(encryptedPassword); //printf(encryptedPassword); //flawfinder: ignore //printf("\n"); // printf("about to print password to file \n"); fprintf(passFile, "%s", encryptedPassword); fclose(passFile); return 0; } int GuessSaferPassword(char filename[100], char userInput[100]) { FILE *passFile; char safeFilename[100]; strlcpy(safeFilename, filename, 100); validateInput(safeFilename); passFile = fopen(safeFilename, "r"); char realPassword[100]; fgets(realPassword, 100, passFile); encryptDecrypt(realPassword); if (strcmp(userInput, realPassword) == 0) { printf("You guessed the password!\n"); } else { printf("You did not guess the password.\n"); } fclose(passFile); return 0; } /* function: GetSaferPassword * input: string filename * output: 0 * unencrypts password, makes sure no buffer overflows will happen, uses safer function than fscanf */ int GetSaferPassword(char filename[100], char pass[100]) { FILE *passFile; char safeFilename[100]; strlcpy(safeFilename, filename, 100); validateInput(safeFilename); passFile = fopen(safeFilename, "r"); fgets(pass, 100, passFile); encryptDecrypt(pass); fclose(passFile); return 0; } int main () { char filename[20] = "normalfile.txt"; //argv[0]; char evilfilename[20] = "../evilfile.txt"; char password0[20] = "%p.%p.%p"; char password1[20] = "password1"; //argv[1]; char password2[20] = "password2"; //argv[2]; char password3[100] = "password3isMuchTooLongForTheVulnerableFunctionButNotTheSafeOne"; //argv[3]; char password4[20]; strcpy(filename, "safefile"); printf("\nCalling CreateSaferPassword to try to print stack vars into a place we're not supposed to be...\n"); CreateSaferPassword(evilfilename, password0); printf("Calling CreateSaferPassword like we're supposed to...\n"); CreateSaferPassword(filename, password1); printf("Guessing correct password..."); GuessSaferPassword(filename, password1); printf("Taking advantage of the race condition to change the password file...\n"); char safeFilename[100]; strcpy(safeFilename, filename); validateInput(safeFilename); FILE *passFile = fopen(safeFilename, "wb+"); fprintf(passFile, "%s", password2); fclose(passFile); printf("Calling GuessSaferPassword with original password...\n"); GuessSaferPassword(filename, password1); printf("Calling GuessSaferPassword with new password...\n"); GuessSaferPassword(filename, password2); printf("Trying to make password that will crash the system...\n"); CreateSaferPassword(filename, password3); printf("Getting unencrypted password..."); GetSaferPassword(filename, password4); printf("%s", password4); return 0; }
the_stack_data/277617.c
#include <stdio.h> #include <stdlib.h> #include <string.h> // ------------------------- // プロトタイプ宣言 // ------------------------- int count(char *s); int equals(char *arg1, char *arg2); int main(int argc, char *argv[]) { if (argc != 3) { printf("入力文字列は一つのみです。プログラムを終了します。\n"); exit(1); } if (equals(argv[1], argv[2]) == 0) { printf("入力文字列は同一です。"); } else { printf("入力文字列は同一ではありません。"); } printf("\n"); return 0; } /** * 2つの文字列hが等しいことを確認します。 * @param arg1 * @param arg2 * @return 0/1 */ int equals(char *arg1, char *arg2) { if (count(arg1) != count(arg2)) return -1; int i = 0; while (*arg1++ != '\0') { if (arg1[i] != arg2[i]) { break; } i++; } return 0; } /** * 文字列の大きさをカウントします。 * @param s 文字ポインタ * @return 文字数 */ int count(char *s) { int counter = 0; while (*s++ != '\0') { counter++; } return counter; }
the_stack_data/97012144.c
/** ****************************************************************************** * @file stm32f1xx_ll_spi.c * @author MCD Application Team * @brief SPI LL module driver. ****************************************************************************** * @attention * * <h2><center>&copy; COPYRIGHT(c) 2016 STMicroelectronics</center></h2> * * 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 STMicroelectronics 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. * ****************************************************************************** */ #if defined(USE_FULL_LL_DRIVER) /* Includes ------------------------------------------------------------------*/ #include "stm32f1xx_ll_spi.h" #include "stm32f1xx_ll_bus.h" #include "stm32f1xx_ll_rcc.h" #ifdef USE_FULL_ASSERT #include "stm32_assert.h" #else #define assert_param(expr) ((void)0U) #endif /** @addtogroup STM32F1xx_LL_Driver * @{ */ #if defined (SPI1) || defined (SPI2) || defined (SPI3) /** @addtogroup SPI_LL * @{ */ /* Private types -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private constants ---------------------------------------------------------*/ /** @defgroup SPI_LL_Private_Constants SPI Private Constants * @{ */ /* SPI registers Masks */ #define SPI_CR1_CLEAR_MASK (SPI_CR1_CPHA | SPI_CR1_CPOL | SPI_CR1_MSTR | \ SPI_CR1_BR | SPI_CR1_LSBFIRST | SPI_CR1_SSI | \ SPI_CR1_SSM | SPI_CR1_RXONLY | SPI_CR1_DFF | \ SPI_CR1_CRCNEXT | SPI_CR1_CRCEN | SPI_CR1_BIDIOE | \ SPI_CR1_BIDIMODE) /** * @} */ /* Private macros ------------------------------------------------------------*/ /** @defgroup SPI_LL_Private_Macros SPI Private Macros * @{ */ #define IS_LL_SPI_TRANSFER_DIRECTION(__VALUE__) (((__VALUE__) == LL_SPI_FULL_DUPLEX) \ || ((__VALUE__) == LL_SPI_SIMPLEX_RX) \ || ((__VALUE__) == LL_SPI_HALF_DUPLEX_RX) \ || ((__VALUE__) == LL_SPI_HALF_DUPLEX_TX)) #define IS_LL_SPI_MODE(__VALUE__) (((__VALUE__) == LL_SPI_MODE_MASTER) \ || ((__VALUE__) == LL_SPI_MODE_SLAVE)) #define IS_LL_SPI_DATAWIDTH(__VALUE__) (((__VALUE__) == LL_SPI_DATAWIDTH_8BIT) \ || ((__VALUE__) == LL_SPI_DATAWIDTH_16BIT)) #define IS_LL_SPI_POLARITY(__VALUE__) (((__VALUE__) == LL_SPI_POLARITY_LOW) \ || ((__VALUE__) == LL_SPI_POLARITY_HIGH)) #define IS_LL_SPI_PHASE(__VALUE__) (((__VALUE__) == LL_SPI_PHASE_1EDGE) \ || ((__VALUE__) == LL_SPI_PHASE_2EDGE)) #define IS_LL_SPI_NSS(__VALUE__) (((__VALUE__) == LL_SPI_NSS_SOFT) \ || ((__VALUE__) == LL_SPI_NSS_HARD_INPUT) \ || ((__VALUE__) == LL_SPI_NSS_HARD_OUTPUT)) #define IS_LL_SPI_BAUDRATE(__VALUE__) (((__VALUE__) == LL_SPI_BAUDRATEPRESCALER_DIV2) \ || ((__VALUE__) == LL_SPI_BAUDRATEPRESCALER_DIV4) \ || ((__VALUE__) == LL_SPI_BAUDRATEPRESCALER_DIV8) \ || ((__VALUE__) == LL_SPI_BAUDRATEPRESCALER_DIV16) \ || ((__VALUE__) == LL_SPI_BAUDRATEPRESCALER_DIV32) \ || ((__VALUE__) == LL_SPI_BAUDRATEPRESCALER_DIV64) \ || ((__VALUE__) == LL_SPI_BAUDRATEPRESCALER_DIV128) \ || ((__VALUE__) == LL_SPI_BAUDRATEPRESCALER_DIV256)) #define IS_LL_SPI_BITORDER(__VALUE__) (((__VALUE__) == LL_SPI_LSB_FIRST) \ || ((__VALUE__) == LL_SPI_MSB_FIRST)) #define IS_LL_SPI_CRCCALCULATION(__VALUE__) (((__VALUE__) == LL_SPI_CRCCALCULATION_ENABLE) \ || ((__VALUE__) == LL_SPI_CRCCALCULATION_DISABLE)) #define IS_LL_SPI_CRC_POLYNOMIAL(__VALUE__) ((__VALUE__) >= 0x1U) /** * @} */ /* Private function prototypes -----------------------------------------------*/ /* Exported functions --------------------------------------------------------*/ /** @addtogroup SPI_LL_Exported_Functions * @{ */ /** @addtogroup SPI_LL_EF_Init * @{ */ /** * @brief De-initialize the SPI registers to their default reset values. * @param SPIx SPI Instance * @retval An ErrorStatus enumeration value: * - SUCCESS: SPI registers are de-initialized * - ERROR: SPI registers are not de-initialized */ ErrorStatus LL_SPI_DeInit(SPI_TypeDef *SPIx) { ErrorStatus status = ERROR; /* Check the parameters */ assert_param(IS_SPI_ALL_INSTANCE(SPIx)); #if defined(SPI1) if (SPIx == SPI1) { /* Force reset of SPI clock */ LL_APB2_GRP1_ForceReset(LL_APB2_GRP1_PERIPH_SPI1); /* Release reset of SPI clock */ LL_APB2_GRP1_ReleaseReset(LL_APB2_GRP1_PERIPH_SPI1); status = SUCCESS; } #endif /* SPI1 */ #if defined(SPI2) if (SPIx == SPI2) { /* Force reset of SPI clock */ LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_SPI2); /* Release reset of SPI clock */ LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_SPI2); status = SUCCESS; } #endif /* SPI2 */ #if defined(SPI3) if (SPIx == SPI3) { /* Force reset of SPI clock */ LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_SPI3); /* Release reset of SPI clock */ LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_SPI3); status = SUCCESS; } #endif /* SPI3 */ return status; } /** * @brief Initialize the SPI registers according to the specified parameters in SPI_InitStruct. * @note As some bits in SPI configuration registers can only be written when the SPI is disabled (SPI_CR1_SPE bit =0), * SPI IP should be in disabled state prior calling this function. Otherwise, ERROR result will be returned. * @param SPIx SPI Instance * @param SPI_InitStruct pointer to a @ref LL_SPI_InitTypeDef structure * @retval An ErrorStatus enumeration value. (Return always SUCCESS) */ ErrorStatus LL_SPI_Init(SPI_TypeDef *SPIx, LL_SPI_InitTypeDef *SPI_InitStruct) { ErrorStatus status = ERROR; /* Check the SPI Instance SPIx*/ assert_param(IS_SPI_ALL_INSTANCE(SPIx)); /* Check the SPI parameters from SPI_InitStruct*/ assert_param(IS_LL_SPI_TRANSFER_DIRECTION(SPI_InitStruct->TransferDirection)); assert_param(IS_LL_SPI_MODE(SPI_InitStruct->Mode)); assert_param(IS_LL_SPI_DATAWIDTH(SPI_InitStruct->DataWidth)); assert_param(IS_LL_SPI_POLARITY(SPI_InitStruct->ClockPolarity)); assert_param(IS_LL_SPI_PHASE(SPI_InitStruct->ClockPhase)); assert_param(IS_LL_SPI_NSS(SPI_InitStruct->NSS)); assert_param(IS_LL_SPI_BAUDRATE(SPI_InitStruct->BaudRate)); assert_param(IS_LL_SPI_BITORDER(SPI_InitStruct->BitOrder)); assert_param(IS_LL_SPI_CRCCALCULATION(SPI_InitStruct->CRCCalculation)); if (LL_SPI_IsEnabled(SPIx) == 0x00000000U) { /*---------------------------- SPIx CR1 Configuration ------------------------ * Configure SPIx CR1 with parameters: * - TransferDirection: SPI_CR1_BIDIMODE, SPI_CR1_BIDIOE and SPI_CR1_RXONLY bits * - Master/Slave Mode: SPI_CR1_MSTR bit * - DataWidth: SPI_CR1_DFF bit * - ClockPolarity: SPI_CR1_CPOL bit * - ClockPhase: SPI_CR1_CPHA bit * - NSS management: SPI_CR1_SSM bit * - BaudRate prescaler: SPI_CR1_BR[2:0] bits * - BitOrder: SPI_CR1_LSBFIRST bit * - CRCCalculation: SPI_CR1_CRCEN bit */ MODIFY_REG(SPIx->CR1, SPI_CR1_CLEAR_MASK, SPI_InitStruct->TransferDirection | SPI_InitStruct->Mode | SPI_InitStruct->DataWidth | SPI_InitStruct->ClockPolarity | SPI_InitStruct->ClockPhase | SPI_InitStruct->NSS | SPI_InitStruct->BaudRate | SPI_InitStruct->BitOrder | SPI_InitStruct->CRCCalculation); /*---------------------------- SPIx CR2 Configuration ------------------------ * Configure SPIx CR2 with parameters: * - NSS management: SSOE bit */ MODIFY_REG(SPIx->CR2, SPI_CR2_SSOE, (SPI_InitStruct->NSS >> 16U)); /*---------------------------- SPIx CRCPR Configuration ---------------------- * Configure SPIx CRCPR with parameters: * - CRCPoly: CRCPOLY[15:0] bits */ if (SPI_InitStruct->CRCCalculation == LL_SPI_CRCCALCULATION_ENABLE) { assert_param(IS_LL_SPI_CRC_POLYNOMIAL(SPI_InitStruct->CRCPoly)); LL_SPI_SetCRCPolynomial(SPIx, SPI_InitStruct->CRCPoly); } status = SUCCESS; } #if defined (SPI_I2S_SUPPORT) /* Activate the SPI mode (Reset I2SMOD bit in I2SCFGR register) */ CLEAR_BIT(SPIx->I2SCFGR, SPI_I2SCFGR_I2SMOD); #endif /* SPI_I2S_SUPPORT */ return status; } /** * @brief Set each @ref LL_SPI_InitTypeDef field to default value. * @param SPI_InitStruct pointer to a @ref LL_SPI_InitTypeDef structure * whose fields will be set to default values. * @retval None */ void LL_SPI_StructInit(LL_SPI_InitTypeDef *SPI_InitStruct) { /* Set SPI_InitStruct fields to default values */ SPI_InitStruct->TransferDirection = LL_SPI_FULL_DUPLEX; SPI_InitStruct->Mode = LL_SPI_MODE_SLAVE; SPI_InitStruct->DataWidth = LL_SPI_DATAWIDTH_8BIT; SPI_InitStruct->ClockPolarity = LL_SPI_POLARITY_LOW; SPI_InitStruct->ClockPhase = LL_SPI_PHASE_1EDGE; SPI_InitStruct->NSS = LL_SPI_NSS_HARD_INPUT; SPI_InitStruct->BaudRate = LL_SPI_BAUDRATEPRESCALER_DIV2; SPI_InitStruct->BitOrder = LL_SPI_MSB_FIRST; SPI_InitStruct->CRCCalculation = LL_SPI_CRCCALCULATION_DISABLE; SPI_InitStruct->CRCPoly = 7U; } /** * @} */ /** * @} */ /** * @} */ #if defined(SPI_I2S_SUPPORT) /** @addtogroup I2S_LL * @{ */ /* Private types -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private constants ---------------------------------------------------------*/ /** @defgroup I2S_LL_Private_Constants I2S Private Constants * @{ */ /* I2S registers Masks */ #define I2S_I2SCFGR_CLEAR_MASK (SPI_I2SCFGR_CHLEN | SPI_I2SCFGR_DATLEN | \ SPI_I2SCFGR_CKPOL | SPI_I2SCFGR_I2SSTD | \ SPI_I2SCFGR_I2SCFG | SPI_I2SCFGR_I2SMOD ) #define I2S_I2SPR_CLEAR_MASK 0x0002U /** * @} */ /* Private macros ------------------------------------------------------------*/ /** @defgroup I2S_LL_Private_Macros I2S Private Macros * @{ */ #define IS_LL_I2S_DATAFORMAT(__VALUE__) (((__VALUE__) == LL_I2S_DATAFORMAT_16B) \ || ((__VALUE__) == LL_I2S_DATAFORMAT_16B_EXTENDED) \ || ((__VALUE__) == LL_I2S_DATAFORMAT_24B) \ || ((__VALUE__) == LL_I2S_DATAFORMAT_32B)) #define IS_LL_I2S_CPOL(__VALUE__) (((__VALUE__) == LL_I2S_POLARITY_LOW) \ || ((__VALUE__) == LL_I2S_POLARITY_HIGH)) #define IS_LL_I2S_STANDARD(__VALUE__) (((__VALUE__) == LL_I2S_STANDARD_PHILIPS) \ || ((__VALUE__) == LL_I2S_STANDARD_MSB) \ || ((__VALUE__) == LL_I2S_STANDARD_LSB) \ || ((__VALUE__) == LL_I2S_STANDARD_PCM_SHORT) \ || ((__VALUE__) == LL_I2S_STANDARD_PCM_LONG)) #define IS_LL_I2S_MODE(__VALUE__) (((__VALUE__) == LL_I2S_MODE_SLAVE_TX) \ || ((__VALUE__) == LL_I2S_MODE_SLAVE_RX) \ || ((__VALUE__) == LL_I2S_MODE_MASTER_TX) \ || ((__VALUE__) == LL_I2S_MODE_MASTER_RX)) #define IS_LL_I2S_MCLK_OUTPUT(__VALUE__) (((__VALUE__) == LL_I2S_MCLK_OUTPUT_ENABLE) \ || ((__VALUE__) == LL_I2S_MCLK_OUTPUT_DISABLE)) #define IS_LL_I2S_AUDIO_FREQ(__VALUE__) ((((__VALUE__) >= LL_I2S_AUDIOFREQ_8K) \ && ((__VALUE__) <= LL_I2S_AUDIOFREQ_192K)) \ || ((__VALUE__) == LL_I2S_AUDIOFREQ_DEFAULT)) #define IS_LL_I2S_PRESCALER_LINEAR(__VALUE__) ((__VALUE__) >= 0x2U) #define IS_LL_I2S_PRESCALER_PARITY(__VALUE__) (((__VALUE__) == LL_I2S_PRESCALER_PARITY_EVEN) \ || ((__VALUE__) == LL_I2S_PRESCALER_PARITY_ODD)) /** * @} */ /* Private function prototypes -----------------------------------------------*/ /* Exported functions --------------------------------------------------------*/ /** @addtogroup I2S_LL_Exported_Functions * @{ */ /** @addtogroup I2S_LL_EF_Init * @{ */ /** * @brief De-initialize the SPI/I2S registers to their default reset values. * @param SPIx SPI Instance * @retval An ErrorStatus enumeration value: * - SUCCESS: SPI registers are de-initialized * - ERROR: SPI registers are not de-initialized */ ErrorStatus LL_I2S_DeInit(SPI_TypeDef *SPIx) { return LL_SPI_DeInit(SPIx); } /** * @brief Initializes the SPI/I2S registers according to the specified parameters in I2S_InitStruct. * @note As some bits in SPI configuration registers can only be written when the SPI is disabled (SPI_CR1_SPE bit =0), * SPI IP should be in disabled state prior calling this function. Otherwise, ERROR result will be returned. * @param SPIx SPI Instance * @param I2S_InitStruct pointer to a @ref LL_I2S_InitTypeDef structure * @retval An ErrorStatus enumeration value: * - SUCCESS: SPI registers are Initialized * - ERROR: SPI registers are not Initialized */ ErrorStatus LL_I2S_Init(SPI_TypeDef *SPIx, LL_I2S_InitTypeDef *I2S_InitStruct) { uint16_t i2sdiv = 2U, i2sodd = 0U, packetlength = 1U; uint32_t tmp = 0U; uint32_t sourceclock = 0U; #if defined(I2S2_I2S3_CLOCK_FEATURE) #else LL_RCC_ClocksTypeDef rcc_clocks; #endif /* I2S2_I2S3_CLOCK_FEATURE */ ErrorStatus status = ERROR; /* Check the I2S parameters */ assert_param(IS_I2S_ALL_INSTANCE(SPIx)); assert_param(IS_LL_I2S_MODE(I2S_InitStruct->Mode)); assert_param(IS_LL_I2S_STANDARD(I2S_InitStruct->Standard)); assert_param(IS_LL_I2S_DATAFORMAT(I2S_InitStruct->DataFormat)); assert_param(IS_LL_I2S_MCLK_OUTPUT(I2S_InitStruct->MCLKOutput)); assert_param(IS_LL_I2S_AUDIO_FREQ(I2S_InitStruct->AudioFreq)); assert_param(IS_LL_I2S_CPOL(I2S_InitStruct->ClockPolarity)); if (LL_I2S_IsEnabled(SPIx) == 0x00000000U) { /*---------------------------- SPIx I2SCFGR Configuration -------------------- * Configure SPIx I2SCFGR with parameters: * - Mode: SPI_I2SCFGR_I2SCFG[1:0] bit * - Standard: SPI_I2SCFGR_I2SSTD[1:0] and SPI_I2SCFGR_PCMSYNC bits * - DataFormat: SPI_I2SCFGR_CHLEN and SPI_I2SCFGR_DATLEN bits * - ClockPolarity: SPI_I2SCFGR_CKPOL bit */ /* Write to SPIx I2SCFGR */ MODIFY_REG(SPIx->I2SCFGR, I2S_I2SCFGR_CLEAR_MASK, I2S_InitStruct->Mode | I2S_InitStruct->Standard | I2S_InitStruct->DataFormat | I2S_InitStruct->ClockPolarity | SPI_I2SCFGR_I2SMOD); /*---------------------------- SPIx I2SPR Configuration ---------------------- * Configure SPIx I2SPR with parameters: * - MCLKOutput: SPI_I2SPR_MCKOE bit * - AudioFreq: SPI_I2SPR_I2SDIV[7:0] and SPI_I2SPR_ODD bits */ /* If the requested audio frequency is not the default, compute the prescaler (i2sodd, i2sdiv) * else, default values are used: i2sodd = 0U, i2sdiv = 2U. */ if (I2S_InitStruct->AudioFreq != LL_I2S_AUDIOFREQ_DEFAULT) { /* Check the frame length (For the Prescaler computing) * Default value: LL_I2S_DATAFORMAT_16B (packetlength = 1U). */ if (I2S_InitStruct->DataFormat != LL_I2S_DATAFORMAT_16B) { /* Packet length is 32 bits */ packetlength = 2U; } #if defined(I2S2_I2S3_CLOCK_FEATURE) /* If an external I2S clock has to be used, the specific define should be set in the project configuration or in the stm32f1xx_ll_rcc.h file */ if(SPIx == SPI2) { /* Get the I2S source clock value */ sourceclock = LL_RCC_GetI2SClockFreq(LL_RCC_I2S2_CLKSOURCE); } else /* SPI3 */ { /* Get the I2S source clock value */ sourceclock = LL_RCC_GetI2SClockFreq(LL_RCC_I2S3_CLKSOURCE); } #else /* I2S Clock source is System clock: Get System Clock frequency */ LL_RCC_GetSystemClocksFreq(&rcc_clocks); /* Get the source clock value: based on System Clock value */ sourceclock = rcc_clocks.SYSCLK_Frequency; #endif /* I2S2_I2S3_CLOCK_FEATURE */ /* Compute the Real divider depending on the MCLK output state with a floating point */ if (I2S_InitStruct->MCLKOutput == LL_I2S_MCLK_OUTPUT_ENABLE) { /* MCLK output is enabled */ tmp = (uint16_t)(((((sourceclock / 256U) * 10U) / I2S_InitStruct->AudioFreq)) + 5U); } else { /* MCLK output is disabled */ tmp = (uint16_t)(((((sourceclock / (32U * packetlength)) * 10U) / I2S_InitStruct->AudioFreq)) + 5U); } /* Remove the floating point */ tmp = tmp / 10U; /* Check the parity of the divider */ i2sodd = (uint16_t)(tmp & (uint16_t)0x0001U); /* Compute the i2sdiv prescaler */ i2sdiv = (uint16_t)((tmp - i2sodd) / 2U); /* Get the Mask for the Odd bit (SPI_I2SPR[8]) register */ i2sodd = (uint16_t)(i2sodd << 8U); } /* Test if the divider is 1 or 0 or greater than 0xFF */ if ((i2sdiv < 2U) || (i2sdiv > 0xFFU)) { /* Set the default values */ i2sdiv = 2U; i2sodd = 0U; } /* Write to SPIx I2SPR register the computed value */ WRITE_REG(SPIx->I2SPR, i2sdiv | i2sodd | I2S_InitStruct->MCLKOutput); status = SUCCESS; } return status; } /** * @brief Set each @ref LL_I2S_InitTypeDef field to default value. * @param I2S_InitStruct pointer to a @ref LL_I2S_InitTypeDef structure * whose fields will be set to default values. * @retval None */ void LL_I2S_StructInit(LL_I2S_InitTypeDef *I2S_InitStruct) { /*--------------- Reset I2S init structure parameters values -----------------*/ I2S_InitStruct->Mode = LL_I2S_MODE_SLAVE_TX; I2S_InitStruct->Standard = LL_I2S_STANDARD_PHILIPS; I2S_InitStruct->DataFormat = LL_I2S_DATAFORMAT_16B; I2S_InitStruct->MCLKOutput = LL_I2S_MCLK_OUTPUT_DISABLE; I2S_InitStruct->AudioFreq = LL_I2S_AUDIOFREQ_DEFAULT; I2S_InitStruct->ClockPolarity = LL_I2S_POLARITY_LOW; } /** * @brief Set linear and parity prescaler. * @note To calculate value of PrescalerLinear(I2SDIV[7:0] bits) and PrescalerParity(ODD bit)\n * Check Audio frequency table and formulas inside Reference Manual (SPI/I2S). * @param SPIx SPI Instance * @param PrescalerLinear value: Min_Data=0x02 and Max_Data=0xFF. * @param PrescalerParity This parameter can be one of the following values: * @arg @ref LL_I2S_PRESCALER_PARITY_EVEN * @arg @ref LL_I2S_PRESCALER_PARITY_ODD * @retval None */ void LL_I2S_ConfigPrescaler(SPI_TypeDef *SPIx, uint32_t PrescalerLinear, uint32_t PrescalerParity) { /* Check the I2S parameters */ assert_param(IS_I2S_ALL_INSTANCE(SPIx)); assert_param(IS_LL_I2S_PRESCALER_LINEAR(PrescalerLinear)); assert_param(IS_LL_I2S_PRESCALER_PARITY(PrescalerParity)); /* Write to SPIx I2SPR */ MODIFY_REG(SPIx->I2SPR, SPI_I2SPR_I2SDIV | SPI_I2SPR_ODD, PrescalerLinear | (PrescalerParity << 8U)); } /** * @} */ /** * @} */ /** * @} */ #endif /* SPI_I2S_SUPPORT */ #endif /* defined (SPI1) || defined (SPI2) || defined (SPI3) */ /** * @} */ #endif /* USE_FULL_LL_DRIVER */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
the_stack_data/37209.c
// 2021-06-07 22:19:53 #include <stdio.h> int main() { int i, j, rows; printf("Enter the number of rows: "); scanf("%d", &rows); for (i = rows; i >= 1; --i) { for (j = 1; j <= i; ++j) { printf("%d ", j); } printf("\n"); } return 0; }
the_stack_data/659979.c
/* Test Thread-Specific Data. Copyright (C) 2000-2020 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see <https://www.gnu.org/licenses/>. */ #define _GNU_SOURCE #include <pthread.h> #include <assert.h> #include <stdio.h> #include <error.h> #include <errno.h> #define THREADS 10 #define KEYS 400 pthread_key_t key[KEYS]; void * thr (void *arg) { error_t err; int i; for (i = 0; i < KEYS; i++) { printf ("pthread_getspecific(%d).\n", key[i]); assert (pthread_getspecific (key[i]) == NULL); printf ("pthread_setspecific(%d, %d).\n", key[i], pthread_self ()); err = pthread_setspecific (key[i], (void *) pthread_self ()); printf ("pthread_setspecific(%d, %d) => %d.\n", key[i], pthread_self (), err); assert_perror (err); } return 0; } int main (int argc, char **argv) { error_t err; int i; pthread_t tid[THREADS]; void des (void *val) { assert ((pthread_t) val == pthread_self ()); } assert (pthread_getspecific ((pthread_key_t) 0) == NULL); assert (pthread_setspecific ((pthread_key_t) 0, (void *) 0x1) == EINVAL); for (i = 0; i < KEYS; i++) err = pthread_key_create (&key[i], des); for (i = 0; i < THREADS; i++) { err = pthread_create (&tid[i], 0, thr, 0); if (err) error (1, err, "pthread_create (%d)", i); } for (i = 0; i < THREADS; i++) { void *ret; err = pthread_join (tid[i], &ret); if (err) error (1, err, "pthread_join"); assert (ret == 0); } return 0; }
the_stack_data/242330628.c
/* * Copyright (c) 2019, Philippe Mertes <[email protected]> * 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 <sys/types.h> #include <sys/socket.h> #include <sys/un.h> #include <arpa/inet.h> #include <unistd.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <errno.h> #define SOCKET_FILE "/tmp/pvd-stats.uds" int main(int argc, char ** argv) { int create_socket; struct sockaddr_un addr; char msg[2048]; ssize_t size; printf("Message to send: "); fgets(msg, 256, stdin); printf("msg: %s\n", msg); if ((create_socket = socket(PF_LOCAL, SOCK_STREAM, 0)) > 0) printf("Socket successfully created\n"); addr.sun_family = AF_LOCAL; strcpy(addr.sun_path, SOCKET_FILE); if (connect(create_socket, (struct sockaddr *) &addr, sizeof(addr)) == 0) { printf("Connected successfully to pvd-stats\n"); send(create_socket, msg, strlen(msg), 0); } else { fprintf(stderr, "Connection error: %s\n", strerror(errno)); } size = recv(create_socket, msg, 2048, 0); printf("Answer: %s\n", msg); return EXIT_SUCCESS; }
the_stack_data/25139057.c
#include <stdio.h> #define BL 0.9765625 int main(){ int x; char c; while(scanf("%d %c",&x,&c) != EOF){ double xf = x * BL*BL*BL; if(c == 'G'){ printf("%.1f %c\n",xf,c); } else{ xf = xf * BL; printf("%.1f %c\n",xf,c); } } return 0; }
the_stack_data/40907.c
/* { dg-do compile { target { ! x32 } } } */ /* { dg-options "-fcheck-pointer-bounds -mmpx -fdump-tree-chkp" } */ /* { dg-final { scan-tree-dump-not "bnd_null_ptr_bounds" "chkp" } } */ void * chkp_test (void *p) { return __builtin___bnd_null_ptr_bounds (p); }
the_stack_data/90766062.c
/* main.c * Main source file to solve Project Euler's problem 3 * Author: HgN * Day: April 29th, 2017 */ #include <inttypes.h> #include <stdbool.h> #include <stdint.h> #include <stdio.h> const uint64_t givenNumber = 600851475143; uint64_t factorNumber = 2; int main(void) { bool flag = false; uint8_t count = 0; uint64_t tempNumber = givenNumber; while (tempNumber != 1) { while ((tempNumber % factorNumber) == 0) { tempNumber = tempNumber / factorNumber; flag = true; count++; } if (flag == true) { printf("%" PRIu64 "^%i\n", factorNumber, count); flag = false; count = 0; } factorNumber++; } printf("Largest prime factor: %" PRIu64 "\n", factorNumber - 1); return 0; }
the_stack_data/31388237.c
/*- * Copyright (c) 1993 * The Regents of the University of California. 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 University 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 REGENTS 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 REGENTS 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 <err.h> #include <stdarg.h> void warn(const char *fmt, ...) { va_list ap; va_start(ap, fmt); vwarn(fmt, ap); va_end(ap); }
the_stack_data/48576361.c
/* * heatbeat.c -- flash NumLock in an hearthbeat fashion * * Copyright (C) 2001 Alessandro Rubini and Jonathan Corbet * Copyright (C) 2001 O'Reilly & Associates * * The source code in this file can be freely used, adapted, * and redistributed in source or binary form, so long as an * acknowledgment appears in derived source files. The citation * should list that the code comes from the book "Linux Device * Drivers" by Alessandro Rubini and Jonathan Corbet, published * by O'Reilly & Associates. No warranty is attached; * we cannot take responsibility for errors or fitness for use. */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <ctype.h> #include <errno.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <sys/ioctl.h> #include <linux/kd.h> int main(int argc, char **argv) { char led; int chosenled = 1; char hearth[]={1,0,1,1,0,0,0,0,0,0,0,0,0}; int udelay = 100000; int load = 0; char *prgname = argv[0]; FILE *f; if (argc > 1 && isdigit(argv[1][0])) { /* the time delay */ udelay = 1000 * atoi(argv[1]); if (udelay < 1000) fprintf(stderr, "%s: delay too short\n", prgname); else { argv++; argc--; } } nice(-20); /* in case is succeeds... */ udelay *= 100; /* prepare for a later division */ if (argc > 1 && strlen(argv[1]) == 1) { argv++, argc--; if (tolower(argv[0][0]) == 's') chosenled = 1; /* scroll lock */ else if (tolower(argv[0][0]) == 'n') chosenled = 2; /* num lock */ else if (tolower(argv[0][0]) == 'c') chosenled = 4; /* caps lock */ else { fprintf(stderr, "%s: unknown led '%s'\n", prgname, argv[1]); argc++; } } if (argc>1) { fprintf(stderr, "%s: usage \"%s [delay ms] [ n | c | s ]\"\n", prgname, prgname); exit(1); } /* ok, now do your loop */ for (;;) { int consolefd=open("/dev/tty0",O_RDONLY); int i; f=fopen("/proc/loadavg", "r"); if (f) { fscanf(f, "%d.%d", &load, &i); fclose(f); } else { load = i = 0; } load = 100 + load * 100 + i; for (i=0; i < sizeof(hearth)/sizeof(hearth[0]); i++) { if (ioctl(consolefd, KDGETLED, &led) || ioctl(consolefd, KDSETLED, (led & ~chosenled) | chosenled * hearth[i])) { fprintf(stderr, "%s: ioctl(): %s\n", prgname, strerror(errno)); exit(2); } usleep(udelay/load); } close(consolefd); } exit(0); /* never happen */ }
the_stack_data/184518140.c
/**/ #include <stdio.h> #include <math.h> int main(){ int num1, num2, num3, num4, small; printf("Please enter 4 numbers separated by spaces > "); scanf("%d%d%d%d", &num1, &num2, &num3, &num4); if (num1 < num2 && num1 < num3 && num1 < num4) small = num1; else if (num2 < num1 && num2 < num3 && num2 < num4) small = num2; else if (num3 < num1 && num3 < num2 && num3 < num4) small = num3; else small = num4; printf("%d is the smallest\n", small); return(0); }
the_stack_data/1057550.c
void matriz_33(){ }
the_stack_data/1199725.c
/* Problem: replace all spaces in a string with '%20'. May assume string has sufficient space. You are given true length of the string Solution: maintain copy of original and iterate over it moving values into string based on an offset which is increased as spaces are found - linear time, linear space total time: 40 mistakes: - didn't add null character to end of string after replacement */ #include <stdio.h> #include <string.h> void replace_spaces(char* str, int length) { char original_string[length]; strcpy(original_string, str); int i = 0, offset = 0; for (i = 0; original_string[i] != '\0'; i++) { if (original_string[i] == ' ') { str[i+offset] = '%'; str[i+offset+1] = '2'; str[i+offset+2] = '0'; offset += 2; } else { str[i+offset] = original_string[i]; } } str[i+offset] = '\0'; } int main() { char string[11] = "a b"; replace_spaces(string, 11); printf("%s\n", string); strcpy(string, "a bc"); replace_spaces(string, 11); printf("%s\n", string); strcpy(string, "a bc"); replace_spaces(string, 11); printf("%s\n", string); strcpy(string, " a"); replace_spaces(string, 11); printf("%s\n", string); return 0; }
the_stack_data/28345.c
#include <stdio.h> int main(void) { // The resultant temperatures can be in decimals as well, so we use double double c, f, result = 0; // We use an integer type data to run the switch statement int choice; printf("Select your choice: \n"); printf("1. Celcius to Fahrenheit\n"); printf("2. Fahrenheit to Celcius\n"); printf("Enter your choice: "); scanf("%d", &choice); // We compute the temperatures for both the cases here respectively switch(choice) { case 1: printf("Enter the temperature in Celcius: "); scanf("%lf", &c); result = (9.0 / 5.0) * c + 32.0; break; case 2: printf("Enter the temperature in Fahrenheit: "); scanf("%lf", &f); result = (5.0 / 9.0) * (f - 32.0); break; // This case gets activated when the user inputs anything othrer than 1 or 2 default: printf("Invalid case!\n"); } // Printing out the result according to the computation printf("The resultant temperature is: %lf\n", result); return 0; }
the_stack_data/646835.c
glScale(x, y, z);
the_stack_data/32949307.c
// carddeck_2a.c // Chapter 16 // Learn C Programming, 2nd Edition // // carddeck_2a.c builds upon carddeck_1a.c. // In this version, we add the hand structure using // individual Card variables. // // compile with // cc carddeck_2a.c -o carddeck_2a -Wall -Werror =std=c17 #include <stdio.h> #include <stdbool.h> #include <string.h> // for strcpy() and strcat() // Useful constants (avoid "magic numbers" whose meaning is // sometimes vague and whose values may change). Use these instead // of literals; when you need to change these, they are applied // everywhere. // enum { kCardsInDeck = 52, // For now, 52 cards in a deck. This will change // depending upon the card game and the # of wild // cards, etc. kCardsInSuit = 13, // For now, kCardsInDeck / 4. This will change // depending upon the card game. kCardsInHand = 5, // For now, 5 cards dealt for each hange. This will // change depending upon the card game. kNumHands = 4 // For now, for hands per "table". This will change // depending on the game we want to implement. }; const bool kWildCard = true; const bool kNotWildCard = false; // ============================================ // Definitions related to a Card // ============================================ // Card Suits typedef enum { eClub = 1, eDiamond, eHeart, eSpade } Suit; // Card Faces typedef enum { eOne = 1, eTwo , eThree , eFour , eFive , eSix , eSeven , eEight , eNine , eTen , eJack , eQueen , eKing , eAce } Face; // A Card typedef struct { Suit suit; int suitValue; Face face; int faceValue; bool isWild; } Card; // Operations on a Card void InitializeCard( Card* pCard , Suit s , Face f , bool w ); void PrintCard( Card* pCard ); void CardToString( Card* pCard , char pCardStr[20] ); int GetCardFaceValue( Card* pCard ); int GetCardSuitValue( Card* pCard ); // ============================================ // Defintions related to a hand // ============================================ // A Hand typedef struct { int cardsDealt; Card card1; Card card2; Card card3; Card card4; Card card5; } Hand; // Operations on a Hand void InitializeHand( Hand* pHand ); void AddCardToHand( Hand* pHand , Card* pCard ); void PrintHand( Hand* pHand , char* pHandStr , char* pLeadStr ); Card* GetCardInHand( Hand* pHand , int cardIndex ); // ============================================ // Definitions related to a Deck // ============================================ // A Deck // For now, the deck will be declared as an array of Cards in main(). // So, nothing to declare here. // Operations on a Deck (array of cards) void InitializeDeck( Card* pDeck ); Card* DealCardFromDeck( Card pDeck[] , int index ); void PrintDeck( Card* pDeck ); int main( void ) { Card deck[ kCardsInDeck ]; Card* pDeck = deck; InitializeDeck( &deck[0] ); Hand h1 , h2 , h3 , h4; InitializeHand( &h1 ); InitializeHand( &h2 ); InitializeHand( &h3 ); InitializeHand( &h4 ); for( int i = 0 ; i < kCardsInHand ; i++ ) { AddCardToHand( &h1 , DealCardFromDeck( pDeck , i ) ); AddCardToHand( &h2 , DealCardFromDeck( pDeck , i+13 ) ); AddCardToHand( &h3 , DealCardFromDeck( pDeck , i+26 ) ); AddCardToHand( &h4 , DealCardFromDeck( pDeck , i+39 ) ); } } // ============================================ // Operations on a Card // ============================================ void InitializeCard( Card* pCard, Suit s , Face f , bool w ) { pCard->suit = s; pCard->suitValue = GetCardSuitValue( pCard ); pCard->face = f; pCard->faceValue = GetCardFaceValue( pCard ); pCard->isWild = w; } void PrintCard( Card* pCard ) { char cardStr[20] = {0}; CardToString( pCard , cardStr ); printf( "%18s" , cardStr ); } void CardToString( Card* pCard , char pCardStr[20] ) { switch( pCard->face ) { case eTwo: strcpy( pCardStr , " 2 " ); break; case eThree: strcpy( pCardStr , " 3 " ); break; case eFour: strcpy( pCardStr , " 4 " ); break; case eFive: strcpy( pCardStr , " 5 " ); break; case eSix: strcpy( pCardStr , " 6 " ); break; case eSeven: strcpy( pCardStr , " 7 " ); break; case eEight: strcpy( pCardStr , " 8 " ); break; case eNine: strcpy( pCardStr , " 9 " ); break; case eTen: strcpy( pCardStr , " 10 " ); break; case eJack: strcpy( pCardStr , " Jack " ); break; case eQueen: strcpy( pCardStr , "Queen " ); break; case eKing: strcpy( pCardStr , " King " ); break; case eAce: strcpy( pCardStr , " Ace " ); break; default: strcpy( pCardStr , " ??? " ); break; } switch( pCard->suit ) { case eSpade: strcat( pCardStr , "of Spades "); break; case eHeart: strcat( pCardStr , "of Hearts "); break; case eDiamond: strcat( pCardStr , "of Diamonds"); break; case eClub: strcat( pCardStr , "of Clubs "); break; default: strcat( pCardStr , "of ???s "); break; } } // For now, rely upon proper definition of enum Faces. // If, at some future time, face values need to chage, // this function can be changed as needed and program will continue // to work as expected. inline int GetCardFaceValue( Card* pCard ) { return (int)pCard->face; } // For now, realy upon proper definition of enum Suits. // If, at some future time, the suit values need to chage, // this function can be changed as needed and program will continue // to work as expected. inline int GetCardSuitValue( Card* pCard ) { return (int)pCard->suit; } // ============================================ // Operations on a Hand // ============================================ void InitializeHand( Hand* pHand ) { pHand->cardsDealt = 0; } void AddCardToHand( Hand* pHand , Card* pCard ) { int numInHand = pHand->cardsDealt; if( numInHand == kCardsInHand ) { printf( "ERROR: hand is full\n" ); return; } Card* pC = GetCardInHand( pHand , numInHand ); InitializeCard( pC , pCard->suit , pCard->face , pCard->isWild ); pHand->cardsDealt++; } void PrintHand( Hand* pHand , char* pHandStr , char* pLeadStr ) { printf( "%s%s\n" , pLeadStr , pHandStr ); for( int i = 0; i < kCardsInHand ; i++ ) { // 0..4 Card* pCard = GetCardInHand( pHand , i ); printf("%s" , pLeadStr ); PrintCard( pCard ); printf("\n"); } } Card* GetCardInHand( Hand* pHand , int cardIndex ) { Card* pC = NULL; switch( cardIndex ) { case 0: pC = &(pHand->card1); break; case 1: pC = &(pHand->card2); break; case 2: pC = &(pHand->card3); break; case 3: pC = &(pHand->card4); break; case 4: pC = &(pHand->card5); break; } return pC; } // ============================================ // Operations on a Deck of Cards // ============================================ void InitializeDeck( Card* pDeck ) { Face f[] = { eTwo , eThree , eFour , eFive , eSix , eSeven , eEight , eNine , eTen , eJack , eQueen , eKing , eAce }; Card* pC; for( int i = 0 ; i < kCardsInSuit ; i++ ) { pC = &(pDeck[ i + (0*kCardsInSuit) ]); InitializeCard( pC , eSpade , f[i], kNotWildCard ); pC = &(pDeck[ i + (1*kCardsInSuit) ]); InitializeCard( pC , eHeart , f[i], kNotWildCard ); pC = &(pDeck[ i + (2*kCardsInSuit) ]); InitializeCard( pC , eDiamond , f[i], kNotWildCard ); pC = &(pDeck[ i + (3*kCardsInSuit) ]); InitializeCard( pC , eClub , f[i], kNotWildCard ); } } Card* DealCardFromDeck( Card pDeck[] , int index ) { Card* pCard = &pDeck[ index ]; return pCard; } void PrintDeck( Card* pDeck ) { printf( "%d cards in the deck\n\n" , kCardsInDeck ); printf( "The ordered deck: \n" ); for( int i = 0 ; i < kCardsInSuit ; i++ ) { int index = i + (0*kCardsInSuit); printf( "(%2d)" , index+1 ); PrintCard( &(pDeck[ index ] ) ); index = i + (1*kCardsInSuit); printf( " (%2d)" , index+1 ); PrintCard( &(pDeck[ index ] ) ); index = i + (2*kCardsInSuit); printf( " (%2d)" , index+1 ); PrintCard( &(pDeck[ i + (2*kCardsInSuit) ] ) ); index = i + (3*kCardsInSuit); printf( " (%2d)" , index+1 ); PrintCard( &(pDeck[ index ] ) ); printf( "\n" ); } printf( "\n\n" ); } /* eof */
the_stack_data/1018854.c
/* Generated by CIL v. 1.7.0 */ /* print_CIL_Input is false */ struct _IO_FILE; struct timeval; extern void signal(int sig , void *func ) ; extern float strtof(char const *str , char const *endptr ) ; typedef struct _IO_FILE FILE; extern int atoi(char const *s ) ; extern double strtod(char const *str , char const *endptr ) ; extern int fclose(void *stream ) ; extern void *fopen(char const *filename , char const *mode ) ; extern void abort() ; extern void exit(int status ) ; extern int raise(int sig ) ; extern int fprintf(struct _IO_FILE *stream , char const *format , ...) ; extern int strcmp(char const *a , char const *b ) ; extern int rand() ; extern unsigned long strtoul(char const *str , char const *endptr , int base ) ; void RandomFunc(unsigned int input[1] , unsigned int output[1] ) ; extern int strncmp(char const *s1 , char const *s2 , unsigned long maxlen ) ; extern int gettimeofday(struct timeval *tv , void *tz , ...) ; extern int printf(char const *format , ...) ; int main(int argc , char *argv[] ) ; void megaInit(void) ; extern unsigned long strlen(char const *s ) ; extern long strtol(char const *str , char const *endptr , int base ) ; extern unsigned long strnlen(char const *s , unsigned long maxlen ) ; extern void *memcpy(void *s1 , void const *s2 , unsigned long size ) ; struct timeval { long tv_sec ; long tv_usec ; }; extern void *malloc(unsigned long size ) ; extern int scanf(char const *format , ...) ; void megaInit(void) { { } } int main(int argc , char *argv[] ) { unsigned int input[1] ; unsigned int output[1] ; int randomFuns_i5 ; unsigned int randomFuns_value6 ; int randomFuns_main_i7 ; { megaInit(); if (argc != 2) { printf("Call this program with %i arguments\n", 1); exit(-1); } else { } randomFuns_i5 = 0; while (randomFuns_i5 < 1) { randomFuns_value6 = (unsigned int )strtoul(argv[randomFuns_i5 + 1], 0, 10); input[randomFuns_i5] = randomFuns_value6; randomFuns_i5 ++; } RandomFunc(input, output); if (output[0] == 699649582U) { printf("You win!\n"); } else { } randomFuns_main_i7 = 0; while (randomFuns_main_i7 < 1) { printf("%u\n", output[randomFuns_main_i7]); randomFuns_main_i7 ++; } } } void RandomFunc(unsigned int input[1] , unsigned int output[1] ) { unsigned int state[1] ; unsigned int local1 ; char copy12 ; unsigned short copy13 ; { state[0UL] = input[0UL] ^ 700325083U; local1 = 0UL; while (local1 < 1UL) { if (! (state[0UL] != local1)) { copy12 = *((char *)(& state[0UL]) + 0); *((char *)(& state[0UL]) + 0) = *((char *)(& state[0UL]) + 1); *((char *)(& state[0UL]) + 1) = copy12; } if (state[0UL] <= local1) { copy13 = *((unsigned short *)(& state[0UL]) + 0); *((unsigned short *)(& state[0UL]) + 0) = *((unsigned short *)(& state[0UL]) + 1); *((unsigned short *)(& state[0UL]) + 1) = copy13; copy13 = *((unsigned short *)(& state[0UL]) + 1); *((unsigned short *)(& state[0UL]) + 1) = *((unsigned short *)(& state[0UL]) + 0); *((unsigned short *)(& state[0UL]) + 0) = copy13; } local1 += 2UL; } output[0UL] = state[0UL] ^ 910028U; } }
the_stack_data/117327708.c
#define ARR_SIZE_UNIT 5000 typedef struct __data { int price; int span; } DATA; typedef struct { DATA *arr; int cur; } StockSpanner; StockSpanner *stockSpannerCreate() { StockSpanner *obj = malloc(sizeof(StockSpanner)); obj->arr = malloc(sizeof(DATA)); obj->cur = 0; return obj; } int stockSpannerNext(StockSpanner *obj, int price) { int cur = obj->cur; if (cur % ARR_SIZE_UNIT == 0) obj->arr = realloc(obj->arr, sizeof(DATA) * (cur + ARR_SIZE_UNIT)); int ret = 1, cmp_idx = cur; while (cmp_idx > 0 && obj->arr[cmp_idx - 1].price <= price) { ret += obj->arr[cmp_idx - 1].span; cmp_idx = cmp_idx - obj->arr[cmp_idx - 1].span; } obj->arr[cur].price = price; obj->arr[cur].span = ret; obj->cur = cur + 1; return ret; } void stockSpannerFree(StockSpanner *obj) { free(obj->arr); free(obj); } /** * Your StockSpanner struct will be instantiated and called as such: * StockSpanner* obj = stockSpannerCreate(); * int param_1 = stockSpannerNext(obj, price); * stockSpannerFree(obj); */
the_stack_data/42454.c
/* toysql.c */ /* A lexer for a very small subset of SQL. */ /* This lexer operates on a string. I hope to do a */ /* version that operates on a file very soon. */ /* This code is released to the public domain. */ /* "Share and enjoy......" :) */ #include <stdio.h> #include <ctype.h> #include <string.h> #include <stdlib.h> #define NUMBER_OF_KEYWORDS 9 /* Array of our keywords in string form. */ char *kw_strings[] = { "select", "from", "where", "and", "or", "not", "in", "is", "null" } ; /* Search function to search the array of keywords. */ int search(char *arr[], int dim, char *str) { int i; int found_match; for (i=0; i<dim; i++) { if ( !strcmp(arr[i] , str ) ) { found_match = 1; break; } else found_match = 0; } /* For */ return found_match; } /* search */ /* Forward declarations. */ void lex(char *str) ; void parse(char token[], char *toktype); void lex_kwident(char *str) { char token[20]; char *toktype; int i=0; while (isalnum(*str) && *str != '\0' && i<20) { token[i] = *str; i++; str++; } token[i] = '\0' ; if (search(kw_strings, NUMBER_OF_KEYWORDS, token) == 1 ) toktype = "Keyword"; else toktype = "Identifier" ; parse(token, toktype); memset(&token[0], 0, sizeof(token)); lex(str); } void lex_string(char *str) { char token[20]; char *toktype; token[0] = '"' ; // Put the quote in the array. int i=1; // 1 Because token[0] has been filled. str++; // Move on from the quote. while ( (*str != '\"') && *str != '\0' && i<20) { token[i] = *str; i++; str++; } /* Add the end double-quote. */ token[i] = '"' ; token[i+1] = '\0' ; str++; // Move on from quote. toktype = "String" ; parse(token, toktype); memset(&token[0], 0, sizeof(token)); lex(str); } void lex_number(char *str) { char token[20]; char *toktype; int i=0; while (isdigit(*str) && *str != '\0' && i<20) { token[i] = *str; i++; str++; } token[i] = '\0' ; toktype = "Number" ; parse(token, toktype); memset(&token[0], 0, sizeof(token)); lex(str); } void lex_punct(char *str) { char token[20]; char *toktype; int i=0; while (ispunct(*str) && *str != '\0' && i<20) { token[i] = *str; i++; str++; } token[i] = '\0' ; toktype = "Punct" ; parse(token, toktype); memset(&token[0], 0, sizeof(token)); lex(str); } void lex(char *str) { if (isalpha(*str) || *str == '_') lex_kwident(str) ; else if ( (*str == '\"') ) lex_string(str); else if (isdigit(*str)) lex_number(str); else if (ispunct(*str) && *str != '_') lex_punct(str); else if (isspace(*str)) {str++; lex(str);} } /* Not a parser (yet) - just prints the tokens. */ void parse(char token[], char *toktype) { printf("Token: %s Tokentype: %s\n", token, toktype); } int main() { char *mystr1 = "select mycol1, mycol2 from mytable where mycol1 <= 10;" ; lex(mystr1); char *mystr2 = "select mycol1, mycol2 from mytable where city = \"Sydney\";" ; lex(mystr2); return 0; }
the_stack_data/65312.c
int countingSort(int *A, int *B, int k, int n){ int *C = malloc(sizeof(int)*10); for(int x = 0; x <= 10; x++){ C[x] = 0; } for(int x = 0; x < 10; x++) { C[A[x]] = C[A[x]] + 1; } for(int i = 1; i <= 10; i++){ C[i] = C[i] + C[i+1]; } for (int j = 9; j >= 0; j--){ B[C[A[j]] - 1] = A[j]; C[A[j]] = C[A[j]] - 1; } return 0; }
the_stack_data/644566.c
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_sort_params.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: anajmi <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/07/08 11:20:25 by anajmi #+# #+# */ /* Updated: 2021/07/08 12:06:12 by anajmi ### ########.fr */ /* */ /* ************************************************************************** */ #include <unistd.h> int print(int argc, char **argv) { int i; int j; i = 1; j = 0; while (i < argc) { while (argv[i][j] != '\0') { write(1, &argv[i][j], 1); j++; } write(1, "\n", 1); j = 0; i++; } return (0); } int strcomp(char *s1, char *s2) { int i; i = 0; while (s1[i] != '\0' || s2[i] != '\0') { if (s1[i] != s2[i]) return (s1[i] - s2[i]); i++; } return (0); } int main(int argc, char **argv) { char *a; int i; if (argc == 1) print(argc, &argv[0]); i = 1; while (i < argc - 1) { if (strcomp(argv[i], argv[i + 1]) > 0) { a = argv[i]; argv[i] = argv[i + 1]; argv[i + 1] = a; i = 0; } i++; } print(argc, argv); return (0); }
the_stack_data/423072.c
#include <stdio.h> int main(){ printf("Hola Mundo!"); }
the_stack_data/85654.c
// RUN: false // XFAIL: *
the_stack_data/43888231.c
#include <ncurses.h> int main(void) { int ch; initscr(); scrollok(stdscr,TRUE); keypad(stdscr,TRUE); noecho(); addstr("Press Enter to quit; Up/Down to scroll"); mvaddstr(LINES/2,0,"Scroll me!"); refresh(); do { ch = getch(); if(ch == KEY_UP) scrl(1); if(ch == KEY_DOWN) scrl(-1); } while( ch != '\n'); endwin(); return 0; }
the_stack_data/154321.c
/* * Copyright (c) 2005-2014 Rich Felker, et al. * Copyright (c) 2015-2016 HarveyOS et al. * * Use of this source code is governed by a MIT-style * license that can be found in the LICENSE.mit file. */ #define _GNU_SOURCE #include <stdio.h> #include <stdarg.h> #include <stdlib.h> int vasprintf(char **s, const char *fmt, va_list ap) { va_list ap2; va_copy(ap2, ap); int l = vsnprintf(0, 0, fmt, ap2); va_end(ap2); if (l<0 || !(*s=malloc(l+1U))) return -1; return vsnprintf(*s, l+1U, fmt, ap); }
the_stack_data/4797.c
/* PR c/19449 */ extern void abort (void); int y; int z = __builtin_choose_expr (!__builtin_constant_p (y), 3, 4); int foo (int x) { return __builtin_choose_expr (!__builtin_constant_p (x), 3, y++); } int main () { if (y || z != 3 || foo (4) != 3) abort (); return 0; }
the_stack_data/156392504.c
#include <math.h> #include <errno.h> #define _RESEARCH_SOURCE #include <float.h> #define MASK 0x7ffL #define SHIFT 20 #define BIAS 1022L typedef union { double d; struct { #ifdef IEEE_8087 long ls; long ms; #else long ms; long ls; #endif }; } Cheat; double frexp(double d, int *ep) { Cheat x; if(d == 0) { *ep = 0; return 0; } x.d = d; *ep = ((x.ms >> SHIFT) & MASK) - BIAS; x.ms &= ~(MASK << SHIFT); x.ms |= BIAS << SHIFT; return x.d; } double ldexp(double d, int e) { Cheat x; if(d == 0) return 0; x.d = d; e += (x.ms >> SHIFT) & MASK; if(e <= 0) return 0; if(e >= MASK){ errno = ERANGE; if(d < 0) return -HUGE_VAL; return HUGE_VAL; } x.ms &= ~(MASK << SHIFT); x.ms |= (long)e << SHIFT; return x.d; } double modf(double d, double *ip) { double f; Cheat x; int e; if(d < 1) { if(d < 0) { f = modf(-d, ip); *ip = -*ip; return -f; } *ip = 0; return d; } x.d = d; e = ((x.ms >> SHIFT) & MASK) - BIAS; if(e <= SHIFT+1) { x.ms &= ~(0x1fffffL >> e); x.ls = 0; } else if(e <= SHIFT+33) x.ls &= ~(0x7fffffffL >> (e-SHIFT-2)); *ip = x.d; return d - x.d; }
the_stack_data/1204883.c
void nextPermutation(int *nums, int numsSize) { if (!numsSize || numsSize == 1) return; int i, chan_ind, part_ind, j; chan_ind = part_ind = -1; for (i = numsSize - 2; i >= 0; i--) { if (nums[i] < nums[i + 1]) { part_ind = i; break; } } for (i = numsSize - 1; i >= 0; i--) { if (nums[i] > nums[part_ind]) { chan_ind = i; break; } } if (part_ind >= 0) { i = nums[part_ind]; nums[part_ind] = nums[chan_ind]; nums[chan_ind] = i; } i = part_ind + 1; j = numsSize - 1; chan_ind = (i + j) / 2; for ( ; i <= chan_ind; i++, j--) { part_ind = nums[i]; nums[i] = nums[j]; nums[j] = part_ind; } return; } int main(void) { int x[] = { 1, 1, 5 }; nextPermutation(x, 3); return(0); }
the_stack_data/53686.c
#include <stdio.h> int main() { int a[200000]={0},i,n,b,k; scanf("%d",&n); for(i=0;i<n;i++) { scanf("%d",&b); a[b]++; } scanf("%d",&k); for(i=199999;i>=0;i--) { if(a[i]!=0) { k--; if(k==0) { printf("%d %d",i,a[i]); break; } } } return 0; }
the_stack_data/179830085.c
// RUN: %llvmgcc %s -g -S -o - | llvm-as | opt -std-compile-opts | \ // RUN: llvm-dis | grep {test/CFrontend} // PR676 #include <stdio.h> void test() { printf("Hello World\n"); }
the_stack_data/68889182.c
#include<stdio.h> int main(){ int i,j; for ( i = 1; i < 5; i++) { for (j = 1; j <=i; j++) { printf("%d\t",j+1); } } return 0; }
the_stack_data/75248.c
/* This testcase is part of GDB, the GNU debugger. Copyright 2013-2017 Free Software Foundation, Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* This program is intended to be started outside of gdb, and then attached to by gdb. It loops for a while, but not forever. */ #include <unistd.h> static void foo1 (void) { sleep (100); } static void foo2 (void) { foo1 (); } static void foo3 (void) { foo2 (); } int main (void) { foo3 (); return 0; }
the_stack_data/946016.c
/* DSO indirectly opened by tst-audit11, with symbol versioning. Copyright (C) 2015-2016 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see <http://www.gnu.org/licenses/>. */ int f2 (void) { return 42; }
the_stack_data/43887227.c
// RUN: %clang_cc1 -fsyntax-only %s 2>&1 \ // RUN: | FileCheck %s -check-prefix=BASE // RUN: %clang_cc1 -fsyntax-only -fdiagnostics-show-option %s 2>&1 \ // RUN: | FileCheck %s -check-prefix=OPTION // RUN: not %clang_cc1 -fsyntax-only -fdiagnostics-show-option -Werror %s 2>&1 \ // RUN: | FileCheck %s -check-prefix=OPTION_ERROR // RUN: %clang_cc1 -fsyntax-only -std=c89 -pedantic -fdiagnostics-show-option %s 2>&1 \ // RUN: | FileCheck %s -check-prefix=OPTION_PEDANTIC // RUN: %clang_cc1 -fsyntax-only -fdiagnostics-show-category id %s 2>&1 \ // RUN: | FileCheck %s -check-prefix=CATEGORY_ID // RUN: %clang_cc1 -fsyntax-only -fdiagnostics-show-category name %s 2>&1 \ // RUN: | FileCheck %s -check-prefix=CATEGORY_NAME // RUN: not %clang_cc1 -fsyntax-only -fdiagnostics-show-option -fdiagnostics-show-category name -Werror %s 2>&1 \ // RUN: | FileCheck %s -check-prefix=OPTION_ERROR_CATEGORY void test(int x, int y) { if (x = y) ++x; // BASE: {{.*}}: warning: {{[a-z ]+$}} // OPTION: {{.*}}: warning: {{[a-z ]+}} [-Wparentheses] // OPTION_ERROR: {{.*}}: error: {{[a-z ]+}} [-Werror,-Wparentheses] // CATEGORY_ID: {{.*}}: warning: {{[a-z ]+}} [2] // CATEGORY_NAME: {{.*}}: warning: {{[a-z ]+}} [Semantic Issue] // OPTION_ERROR_CATEGORY: {{.*}}: error: {{[a-z ]+}} [-Werror,-Wparentheses,Semantic Issue] // Leverage the fact that all these '//'s get warned about in C89 pedantic. // OPTION_PEDANTIC: {{.*}}: warning: {{[/a-z ]+}} [-Wcomment] }
the_stack_data/6388959.c
/* paiza POH! vol.2 * result: * http://paiza.jp/poh/paizen/result/1e7a5bdf25a4c2a25172afaaa2cba7ea * author: Leonardone @ NEETSDKASU */ #include <stdio.h> #define OUTPUTSIZE (600000) char output[OUTPUTSIZE]; char *optr = output; inline void putInt(int v) { if (v < 10) { *optr = '0' + (char)v; ++optr; } else { putInt(v / 10); *optr = '0' + (char)(v % 10); ++optr; } } inline void putNewline(void) { *optr = '\n'; ++optr; } #define BUFSIZE (900000) char buf[BUFSIZE]; char *ptr = buf; inline int getInt(void) { int v = 0; while (*ptr < '0' || *ptr > '9') ++ptr; while (*ptr >= '0' && *ptr <= '9') { v = 10 * v + (int)(*ptr - '0'); ++ptr; } return v; } inline char getChar(void) { while (*ptr < '0' || *ptr > '9') ++ptr; return *ptr++; } int space2top[301]; int table[301][301]; typedef int * PINT; int main(void) { int H, W, N, s, t, i, x, y; char str[310]; PINT p, q; fread(buf, sizeof(char), BUFSIZE, stdin); H = getInt(); W = getInt(); for (y = 0; y < H; ++y) { q = space2top + 1; for (x = 0; x < W; ++x, ++q) { if (getChar() == '0') { p = q; s = ++(*p); t = 1; while (*p) { if (*p < s) { s = *p; } ++table[t][s]; ++t; --p; } } else { *q = 0; } } } for (x = 1; x <= W; ++x) { p = table[x] + H; for (y = 1; y < H; ++y) { --p; *p += *(p + 1); } } N = getInt(); for (i = 0; i < N; ++i) { s = getInt(); t = getInt(); putInt(table[t][s]); putNewline(); } fwrite(output, sizeof(char), (int)optr - (int)output, stdout); return 0; }
the_stack_data/133975.c
#include <stdio.h> int main(int argc, const char *argv[]) { for (int i = 0; i < 10; ++i) { printf("Hello, World!\n"); } int x = 20; /* A comment */ printf("%d bytes per int.\n", sizeof(x)); return 0; }
the_stack_data/94486.c
#include <string.h> int memcmp(const void *s1, const void *s2, size_t n) { for (size_t i = 0; i < n; i++) { if (((unsigned char *)s1)[i] != ((unsigned char *)s2)[i]) return ((unsigned char *)s1)[i] - ((unsigned char *)s2)[i]; } return 0; }
the_stack_data/45450856.c
/*C program to find students grades in a class through structure */ #include<stdio.h> struct stud { char nam[20], grad[5]; int obtain_mark, per; }; struct stud s[5]; int i; int main() { for(i=1; i<=5; i++) { printf("Enter %d student name : ",i); scanf("%s",&s[i].nam); printf("Enter %d student obtained marks = ",i); scanf("%d",&s[i].obtain_mark); fflush(stdin); } for(i=1; i<=5; i++) s[i].per=s[i].obtain_mark/5; for(i=1; i<=5; i++) { if(s[i].per>=80) strcpy(s[i].grad,"A"); else if(s[i].per>=60) strcpy(s[i].grad,"B"); else if(s[i].per>=50) strcpy(s[i].grad,"C"); else if(s[i].per>=40) strcpy(s[i].grad,"D"); else strcpy(s[i].grad,"F"); } for(i=1; i<=5; i++) printf("\n%d student %s has obtained grade %s ",i,s[i].nam,s[i].grad); getch(); return 0; }
the_stack_data/165768229.c
#include<stdio.h> #include<omp.h> int main(int argc, char *argv[]){ int nThreads = 4; omp_set_num_threads(nThreads); int n = 0; scanf("%d", &n); double sum1 = 0, sum2 = 0, sum3 = 0, sum4 = 0; double sum1P[nThreads]; double sum2P[nThreads]; for(int i = 0; i < nThreads+1; i++) sum1P[i] = sum2P[i] = 0; /* * PARALLEL * if(expression) * num_threads(int|expression) * private(list) * firstprivate(list) * shared(list) * default(shared|none) * copyin(list) * reduction(operator: list) //basic operators only */ #pragma omp parallel { int at = omp_get_thread_num(); int end = (at+1)*(n/nThreads); for(int i = at*(n/nThreads); i < end; i++) sum1P[at] += i; } if(n%4 == 0) sum1 += n*((n%4)+1)-(n%4); else if(n%4 == 1) sum1 += n*((n%4)+1)-(n%4); else if(n%4 == 2) sum1 += n*((n%4)+1)-(n%4-1)-2; else sum1 += n*((n%4)+1)-2*(n%4); for(int i = 0; i < nThreads; i++){ sum1 += sum1P[i]; } #pragma omp parallel for for(int i = 0; i <= n; i++){ sum2P[omp_get_thread_num()] += i; } for(int i = 0; i < nThreads; i++){ sum2 += sum2P[i]; } #pragma omp parallel for reduction(+: sum3) for(int i = 0; i <= n; i++){ //printf("Hello from thread #%d iteration #%d\n", omp_get_thread_num(), i); sum3 += i; } #pragma omp parallel sections { #pragma omp section { double sumP = 0; #pragma omp parallel for for(int i = 0; i <= n; i += 2){ sumP += i; } #pragma omp atomic sum4 += sumP; } #pragma omp section { double sumP = 0; #pragma omp parallel for for(int i = 1; i <= n; i += 2){ sumP += i; } #pragma omp atomic sum4 += sumP; } } printf("Sum1 from 0 to %d = %.0lf\n", n, sum1); printf("Sum2 from 0 to %d = %.0lf\n", n, sum2); printf("Sum3 from 0 to %d = %.0lf\n", n, sum3); printf("Sum4 from 0 to %d = %.0lf\n", n, sum4); return 0; }
the_stack_data/67325617.c
#include <stdio.h> #include <unistd.h> #include <fcntl.h> void SetNoBlock(int fd) { int fl = fcntl(fd, F_GETFL); if (fl < 0) { perror("fcntl"); return; } fcntl(fd, F_SETFL, fl | O_NONBLOCK); } int main() { SetNoBlock(0); while (1) { char buf[1024] = {0}; ssize_t read_size = read(0, buf, sizeof(buf) - 1); if (read_size < 0) { perror("read"); sleep(1); continue; } printf("input:%s\n", buf); } return 0; }
the_stack_data/1153860.c
#include <stdio.h> #include <stdlib.h> int wcount(char *s){ //> int wcnt = 0, space = 0; char *s1 = s; while ( *s1 ) { if ( *s1++ != ' '){ s1 = NULL; break; } } if ( s1 ) return 0; while ( *s ){ if (( *s++ ) == ' '){ if (!space) wcnt++; space = 1; } else space = 0; } if ( space ) return wcnt - 1; else return wcnt + 1; } int main() { char *s = malloc(255 * sizeof(char)); gets(s); printf("%d\n", wcount(s)); free(s); return 0; }
the_stack_data/604874.c
typedef int v2si __attribute__((__vector_size__(8))); v2si f (int x) { return (v2si) { (__INTPTR_TYPE__) "", x }; }
the_stack_data/173577508.c
/* * Copyright 2013 The Emscripten Authors. All rights reserved. * Emscripten is available under two separate licenses, the MIT license and the * University of Illinois/NCSA Open Source License. Both these licenses can be * found in the LICENSE file. */ #include <errno.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/ioctl.h> #include <assert.h> #ifdef __EMSCRIPTEN__ #include <emscripten.h> #endif #define EXPECTED_BYTES 5 #define BUFLEN 16 int result = 0; int sock; char buf[BUFLEN]; char expected[] = "emscripten"; struct sockaddr_in si_host, si_peer; struct iovec iov[1]; struct msghdr hdr; int done = 0; void iter() { int n; n = recvmsg(sock, &hdr, 0); if(0 < n) { done = 1; fprintf(stderr, "received %d bytes: %s", n, (char*)hdr.msg_iov[0].iov_base); shutdown(sock, SHUT_RDWR); close(sock); #ifdef __EMSCRIPTEN__ if(strlen((char*)hdr.msg_iov[0].iov_base) == strlen(expected) && 0 == strncmp((char*)hdr.msg_iov[0].iov_base, expected, strlen(expected))) { result = 1; } REPORT_RESULT(result); exit(EXIT_SUCCESS); emscripten_cancel_main_loop(); #endif } else if(EWOULDBLOCK != errno) { perror("recvmsg failed"); exit(EXIT_FAILURE); emscripten_cancel_main_loop(); } } int main(void) { memset(&si_host, 0, sizeof(struct sockaddr_in)); memset(&si_peer, 0, sizeof(struct sockaddr_in)); si_host.sin_family = AF_INET; si_host.sin_port = htons(8991); si_host.sin_addr.s_addr = htonl(INADDR_ANY); if(-1 == (sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP))) { perror("cannot create host socket"); exit(EXIT_FAILURE); } if(-1 == bind(sock, (struct sockaddr*)&si_host, sizeof(struct sockaddr))) { perror("cannot bind host socket"); exit(EXIT_FAILURE); } iov[0].iov_base = buf; iov[0].iov_len = sizeof(buf); memset (&hdr, 0, sizeof (struct msghdr)); hdr.msg_name = &si_peer; hdr.msg_namelen = sizeof(struct sockaddr_in); hdr.msg_iov = iov; hdr.msg_iovlen = 1; #ifdef __EMSCRIPTEN__ emscripten_set_main_loop(iter, 0, 0); #else while (!done) iter(); #endif return EXIT_SUCCESS; }
the_stack_data/27353.c
// WARNING in kmem_cache_create_usercopy // https://syzkaller.appspot.com/bug?id=cca700e277be3358b5738a93c38f1d5b594c9882 // status:fixed // autogenerated by syzkaller (https://github.com/google/syzkaller) #define _GNU_SOURCE #include <endian.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/syscall.h> #include <sys/types.h> #include <unistd.h> uint64_t r[2] = {0xffffffffffffffff, 0xffffffffffffffff}; int main(void) { syscall(__NR_mmap, 0x20000000, 0x1000000, 3, 0x32, -1, 0); long res = 0; res = syscall(__NR_pipe2, 0x20000100, 0); if (res != -1) { r[0] = *(uint32_t*)0x20000100; r[1] = *(uint32_t*)0x20000104; } memcpy((void*)0x20000140, "./file0", 8); syscall(__NR_mkdir, 0x20000140, 0); *(uint32_t*)0x20000040 = 0x15; *(uint8_t*)0x20000044 = 0x65; *(uint16_t*)0x20000045 = -1; *(uint32_t*)0x20000047 = 8; *(uint16_t*)0x2000004b = 8; memcpy((void*)0x2000004d, "9P2000.u", 8); syscall(__NR_write, r[1], 0x20000040, 0x15); memcpy((void*)0x20000000, "./file0", 8); memcpy((void*)0x200008c0, "9p", 3); memcpy((void*)0x20000a80, "trans=fd,", 9); memcpy((void*)0x20000a89, "rfdno", 5); *(uint8_t*)0x20000a8e = 0x3d; sprintf((char*)0x20000a8f, "0x%016llx", (long long)r[0]); *(uint8_t*)0x20000aa1 = 0x2c; memcpy((void*)0x20000aa2, "wfdno", 5); *(uint8_t*)0x20000aa7 = 0x3d; sprintf((char*)0x20000aa8, "0x%016llx", (long long)r[1]); *(uint8_t*)0x20000aba = 0x2c; memcpy((void*)0x20000abb, "\x63\x61\x63\x68\x65\x3d\xc0\x6d\x61\x70", 10); *(uint8_t*)0x20000ac5 = 0x2c; *(uint8_t*)0x20000ac6 = 0; syscall(__NR_mount, 0, 0x20000000, 0x200008c0, 0, 0x20000a80); return 0; }
the_stack_data/237642855.c
#include <stdlib.h> #include <stdio.h> int main(){ short int v[5] = {2,5,1,4,0}; int v1[5] = {2,5,1,4,0}; char c[5] = {'a','b','m','4','-'}; float f[5] = {2.66, 0.125, 1.0, 4.99, 2.009}; double d[5] = {2.66, 0.125, 1.0, 4.99, 2.009}; printf("Quantidade de byte de um elemendo do vetor do tipo short int gasta eh:%d\n",((int) (&v[1]))-((int) (&v[0]))); printf("Quantidade de byte de um elemendo do vetor do tipo int gasta eh:%d\n",((int) (&v1[1]))-((int) (&v1[0]))); printf("Quantidade de byte de um elemendo do vetor do tipo char gasta eh:%d\n",((int) (&c[1]))-((int) (&c[0]))); printf("Quantidade de byte de um elemendo do vetor do tipo float gasta eh:%d\n",((int) (&f[1]))-((int) (&f[0]))); printf("Quantidade de byte de um elemendo do vetor do tipo double gasta eh:%d\n",((int) (&d[1]))-((int) (&d[0]))); }
the_stack_data/588500.c
#include <stdio.h> #include <stdlib.h> #include <string.h> char key[50] = "\x79\x17\x46\x55\x10\x53\x5f\x5d\x55\x10\x58\x55\x42\x55\x10\x44\x5f\x3a"; void win(void) { system("/bin/sh"); } void main(void) { char input[50]; fgets(input, sizeof(input) - 1, stdin); if (strlen(input) == strlen(key)) { for (int i = 0; i < strlen(key); i++) { if ((input[i] ^ 0x30) != key[i]) { exit(0); } } system("/bin/sh"); } }
the_stack_data/175142852.c
/* Hexadecimal number is a number which has base value as 16. To convert a decimal number to hexadecimal number, we have to keep on dividing the decimal number by 16 & store the remainder in each division. According to remainder the hexadecimal digits are stored. The mapping of remainder to hex digit is same for remainder 0-9(i.e 0 in decimal is 0 in hexadecimal as well). For remainder 10-15, the corresponding hexadecimal digits are A-F. (i.e 10(in decimal) = A(in hex) & so on). Once all the remainders are calculated write those remainders in reverse order, this gives the equivalent hexadecimal number. In this problem, decimal number is given as input & we have to output its equivalent hexadecimal number. I/O : 201 O/P : C9 Explanation : 201 in decimal format is equivalent to the C9 in hexadecimal. */ #include<stdio.h> //Function that converts decimal number to hexadecimal number. int decToHex(int fdec , char fhex[]) { int j = 0, remainder = 0; //This loop calculates the remainder & map it to hex number until the number is greater than 0. while(fdec > 0) { remainder = fdec % 16 ; /* If remainder is less than 10(i.e 0-9) then add remainder to 48. 48 is the ASCII value of 0. ASCII value of 1 is 49. So we add the remainder to ASCII value of 0 to get ASCII value of remainder & store it in character array. Here, j is used to keep track of array index. If remainder is greater than 9(i.e 10-15) which means remainder is A-F in hexadecimal. So add remainder to 55. 55 is ASCII value of A. ASCII value of B is 56. So we add remainder & ASCII value of A to get ASCII value of remainder in terms of hex form & store it in array. */ if(remainder < 10) { fhex[j] = 48 + remainder ; } else { fhex[j] = 55 + remainder ; } j = j + 1 ; fdec = fdec / 16 ; } //j contains the number of digits in hexadecimal number. return j ; } int main(void) { int dec = 0, i = 0, len = 0 ; //Character array to store hexadecimal number. char hex[100] = {'\0'} ; //Take decimal number as input. printf("Enter the number in Decimal form : "); scanf("%d" , &dec) ; //Call to the function decToHex(). len = decToHex(dec , hex); printf("The equivalent Hexadecimal number is : ") ; /* Here array is printed reversely as according to method to convert decimal number to hex number, the 1st obtained & stored remainder in array is actually last digit in hexadeciaml number. So to get correct hexadecimal number, print it reversely. */ for(i=len-1 ; i>=0 ; --i) { printf("%c" , hex[i]); } return 0 ; } /* Sample Input/Output : Input : Enter the number in Decimal form : 45 Output : The equivalent Hexadecimal number is : 2D Time Complexity : O(n) Space complexity : O(1) */
the_stack_data/184517156.c
extern void __VERIFIER_error() __attribute__ ((__noreturn__)); extern void __VERIFIER_assume(int); void __VERIFIER_assert(int cond) { if(!(cond)) { ERROR: __VERIFIER_error(); } } extern int __VERIFIER_nondet_int(void); int N; int main() { N = __VERIFIER_nondet_int(); if(N <= 0) return 1; int i; long long sum; long long a[N]; int b[N]; sum = 0; for(i=0; i<N; i++) { a[i] = 1; } for(i=0; i<N; i++) { b[i] = 1; } for(i=0; i<N; i++) { sum = sum + a[i]; } for(i=0; i<N; i++) { a[i] = b[i] + sum; } for(i=0; i<N; i++) { __VERIFIER_assert(a[i] == N + 1); } return 1; }
the_stack_data/89899.c
// Copyright (c) Athena Dev Teams - Licensed under GNU GPL // For more information, see LICENCE in the main folder #ifdef PCRE_SUPPORT #include "../common/timer.h" #include "../common/malloc.h" #include "../common/nullpo.h" #include "../common/showmsg.h" #include "../common/strlib.h" #include "mob.h" // struct mob_data #include "npc.h" // struct npc_data #include "pc.h" // struct map_session_data #include "script.h" // set_var() #include <pcre.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdarg.h> /** * Written by MouseJstr in a vision... (2/21/2005) * * This allows you to make npc listen for spoken text (global * messages) and pattern match against that spoken text using perl * regular expressions. * * Please feel free to copy this code into your own personal ragnarok * servers or distributions but please leave my name. Also, please * wait until I've put it into the main eA branch which means I * believe it is ready for distribution. * * So, how do people use this? * * The first and most important function is defpattern * * defpattern 1, "[^:]+: (.*) loves (.*)", "label"; * * this defines a new pattern in set 1 using perl syntax * (http://www.troubleshooters.com/codecorn/littperl/perlreg.htm) * and tells it to jump to the supplied label when the pattern * is matched. * * each of the matched Groups will result in a variable being * set ($@p1$ through $@p9$ with $@p0$ being the entire string) * before the script gets executed. * * activatepset 1; * * This activates a set of patterns.. You can have many pattern * sets defined and many active all at once. This feature allows * you to set up "conversations" and ever changing expectations of * the pattern matcher * * deactivatepset 1; * * turns off a pattern set; * * deactivatepset -1; * * turns off ALL pattern sets; * * deletepset 1; * * deletes a pset */ /* Structure containing all info associated with a single pattern block */ struct pcrematch_entry { struct pcrematch_entry* next; char* pattern; pcre* pcre_; pcre_extra* pcre_extra_; char* label; }; /* A set of patterns that can be activated and deactived with a single command */ struct pcrematch_set { struct pcrematch_set* prev; struct pcrematch_set* next; struct pcrematch_entry* head; int setid; }; /* * Entire data structure hung off a NPC * * The reason I have done it this way (a void * in npc_data and then * this) was to reduce the number of patches that needed to be applied * to a ragnarok distribution to bring this code online. I * also wanted people to be able to grab this one file to get updates * without having to do a large number of changes. */ struct npc_parse { struct pcrematch_set* active; struct pcrematch_set* inactive; }; /** * delete everythign associated with a entry * * This does NOT do the list management */ void finalize_pcrematch_entry(struct pcrematch_entry* e) { pcre_free(e->pcre_); pcre_free(e->pcre_extra_); aFree(e->pattern); aFree(e->label); } /** * Lookup (and possibly create) a new set of patterns by the set id */ static struct pcrematch_set* lookup_pcreset(struct npc_data* nd, int setid) { struct pcrematch_set *pcreset; struct npc_parse *npcParse = (struct npc_parse *) nd->chatdb; if (npcParse == NULL) nd->chatdb = npcParse = (struct npc_parse *) aCalloc(sizeof(struct npc_parse), 1); pcreset = npcParse->active; while (pcreset != NULL) { if (pcreset->setid == setid) break; pcreset = pcreset->next; } if (pcreset == NULL) pcreset = npcParse->inactive; while (pcreset != NULL) { if (pcreset->setid == setid) break; pcreset = pcreset->next; } if (pcreset == NULL) { pcreset = (struct pcrematch_set *) aCalloc(sizeof(struct pcrematch_set), 1); pcreset->next = npcParse->inactive; if (pcreset->next != NULL) pcreset->next->prev = pcreset; pcreset->prev = 0; npcParse->inactive = pcreset; pcreset->setid = setid; } return pcreset; } /** * activate a set of patterns. * * if the setid does not exist, this will silently return */ static void activate_pcreset(struct npc_data* nd, int setid) { struct pcrematch_set *pcreset; struct npc_parse *npcParse = (struct npc_parse *) nd->chatdb; if (npcParse == NULL) return; // Nothing to activate... pcreset = npcParse->inactive; while (pcreset != NULL) { if (pcreset->setid == setid) break; pcreset = pcreset->next; } if (pcreset == NULL) return; // not in inactive list if (pcreset->next != NULL) pcreset->next->prev = pcreset->prev; if (pcreset->prev != NULL) pcreset->prev->next = pcreset->next; else npcParse->inactive = pcreset->next; pcreset->prev = NULL; pcreset->next = npcParse->active; if (pcreset->next != NULL) pcreset->next->prev = pcreset; npcParse->active = pcreset; } /** * deactivate a set of patterns. * * if the setid does not exist, this will silently return */ static void deactivate_pcreset(struct npc_data* nd, int setid) { struct pcrematch_set *pcreset; struct npc_parse *npcParse = (struct npc_parse *) nd->chatdb; if (npcParse == NULL) return; // Nothing to deactivate... if (setid == -1) { while(npcParse->active != NULL) deactivate_pcreset(nd, npcParse->active->setid); return; } pcreset = npcParse->active; while (pcreset != NULL) { if (pcreset->setid == setid) break; pcreset = pcreset->next; } if (pcreset == NULL) return; // not in active list if (pcreset->next != NULL) pcreset->next->prev = pcreset->prev; if (pcreset->prev != NULL) pcreset->prev->next = pcreset->next; else npcParse->active = pcreset->next; pcreset->prev = NULL; pcreset->next = npcParse->inactive; if (pcreset->next != NULL) pcreset->next->prev = pcreset; npcParse->inactive = pcreset; } /** * delete a set of patterns. */ static void delete_pcreset(struct npc_data* nd, int setid) { int active = 1; struct pcrematch_set *pcreset; struct npc_parse *npcParse = (struct npc_parse *) nd->chatdb; if (npcParse == NULL) return; // Nothing to deactivate... pcreset = npcParse->active; while (pcreset != NULL) { if (pcreset->setid == setid) break; pcreset = pcreset->next; } if (pcreset == NULL) { active = 0; pcreset = npcParse->inactive; while (pcreset != NULL) { if (pcreset->setid == setid) break; pcreset = pcreset->next; } } if (pcreset == NULL) return; if (pcreset->next != NULL) pcreset->next->prev = pcreset->prev; if (pcreset->prev != NULL) pcreset->prev->next = pcreset->next; if(active) npcParse->active = pcreset->next; else npcParse->inactive = pcreset->next; pcreset->prev = NULL; pcreset->next = NULL; while (pcreset->head) { struct pcrematch_entry* n = pcreset->head->next; finalize_pcrematch_entry(pcreset->head); aFree(pcreset->head); // Cleanin' the last ones.. [Lance] pcreset->head = n; } aFree(pcreset); } /** * create a new pattern entry */ static struct pcrematch_entry* create_pcrematch_entry(struct pcrematch_set* set) { struct pcrematch_entry * e = (struct pcrematch_entry *) aCalloc(sizeof(struct pcrematch_entry), 1); struct pcrematch_entry * last = set->head; // Normally we would have just stuck it at the end of the list but // this doesn't sink up with peoples usage pattern. They wanted // the items defined first to have a higher priority then the // items defined later. as a result, we have to do some work up front. /* if we are the first pattern, stick us at the end */ if (last == NULL) { set->head = e; return e; } /* Look for the last entry */ while (last->next != NULL) last = last->next; last->next = e; e->next = NULL; return e; } /** * define/compile a new pattern */ void npc_chat_def_pattern(struct npc_data* nd, int setid, const char* pattern, const char* label) { const char *err; int erroff; struct pcrematch_set * s = lookup_pcreset(nd, setid); struct pcrematch_entry *e = create_pcrematch_entry(s); e->pattern = aStrdup(pattern); e->label = aStrdup(label); e->pcre_ = pcre_compile(pattern, PCRE_CASELESS, &err, &erroff, NULL); e->pcre_extra_ = pcre_study(e->pcre_, 0, &err); } /** * Delete everything associated with a NPC concerning the pattern * matching code * * this could be more efficent but.. how often do you do this? */ void npc_chat_finalize(struct npc_data* nd) { struct npc_parse *npcParse = (struct npc_parse *) nd->chatdb; if (npcParse == NULL) return; while(npcParse->active) delete_pcreset(nd, npcParse->active->setid); while(npcParse->inactive) delete_pcreset(nd, npcParse->inactive->setid); // Additional cleaning up [Lance] aFree(npcParse); } /** * Handler called whenever a global message is spoken in a NPC's area */ int npc_chat_sub(struct block_list* bl, va_list ap) { struct npc_data* nd = (struct npc_data *) bl; struct npc_parse* npcParse = (struct npc_parse *) nd->chatdb; char* msg; int len, i; struct map_session_data* sd; struct npc_label_list* lst; struct pcrematch_set* pcreset; struct pcrematch_entry* e; // Not interested in anything you might have to say... if (npcParse == NULL || npcParse->active == NULL) return 0; msg = va_arg(ap,char*); len = va_arg(ap,int); sd = va_arg(ap,struct map_session_data *); // iterate across all active sets for (pcreset = npcParse->active; pcreset != NULL; pcreset = pcreset->next) { // interate across all patterns in that set for (e = pcreset->head; e != NULL; e = e->next) { int offsets[2*10 + 10]; // 1/3 reserved for temp space requred by pcre_exec // perform pattern match int r = pcre_exec(e->pcre_, e->pcre_extra_, msg, len, 0, 0, offsets, ARRAYLENGTH(offsets)); if (r > 0) { // save out the matched strings for (i = 0; i < r; i++) { char var[6], val[255]; snprintf(var, sizeof(var), "$@p%i$", i); pcre_copy_substring(msg, offsets, r, i, val, sizeof(val)); set_var(sd, var, val); } // find the target label.. this sucks.. lst = nd->u.scr.label_list; ARR_FIND(0, nd->u.scr.label_list_num, i, strncmp(lst[i].name, e->label, sizeof(lst[i].name)) == 0); if (i == nd->u.scr.label_list_num) { ShowWarning("Unable to find label: %s\n", e->label); return 0; } // run the npc script run_script(nd->u.scr.script,lst[i].pos,sd->bl.id,nd->bl.id); return 0; } } } return 0; } // Various script builtins used to support these functions int buildin_defpattern(struct script_state* st) { int setid = conv_num(st,& (st->stack->stack_data[st->start+2])); const char* pattern = conv_str(st,& (st->stack->stack_data[st->start+3])); const char* label = conv_str(st,& (st->stack->stack_data[st->start+4])); struct npc_data* nd = (struct npc_data *)map_id2bl(st->oid); npc_chat_def_pattern(nd, setid, pattern, label); return 0; } int buildin_activatepset(struct script_state* st) { int setid = conv_num(st,& (st->stack->stack_data[st->start+2])); struct npc_data* nd = (struct npc_data *)map_id2bl(st->oid); activate_pcreset(nd, setid); return 0; } int buildin_deactivatepset(struct script_state* st) { int setid = conv_num(st,& (st->stack->stack_data[st->start+2])); struct npc_data* nd = (struct npc_data *)map_id2bl(st->oid); deactivate_pcreset(nd, setid); return 0; } int buildin_deletepset(struct script_state* st) { int setid = conv_num(st,& (st->stack->stack_data[st->start+2])); struct npc_data* nd = (struct npc_data *)map_id2bl(st->oid); delete_pcreset(nd, setid); return 0; } #endif //PCRE_SUPPORT
the_stack_data/31387221.c
#include <stdio.h> #define MAX 100 int length(char *s) { int i, len = 0; for (i = 0; s[i] != '\0'; i++) len++; return len; } int length_r(char *s) { if (*s == '\0') return 0; return 1 + length_r(s + 1); } int main() { char s[MAX]; gets(s); printf("Length: %d and %d\n", length(s), length_r(s)); return 0; }
the_stack_data/178266176.c
#include <stdio.h> #include <sys/types.h> #include <signal.h> #include <sys/ipc.h> #include <sys/shm.h> #include <stdlib.h> #include <unistd.h> void SIGINT_handler(int); void SIGQUIT_handler(int); int ShmID; pid_t *ShmPTR; void main(void) { int i; pid_t pid = getpid(); key_t MyKey; if (signal(SIGINT, SIGINT_handler) == SIG_ERR) { printf("SIGINT install error\n"); exit(1); } if (signal(SIGQUIT, SIGQUIT_handler) == SIG_ERR) { printf("SIGQUIT install error\n"); exit(2); } MyKey = ftok(".", 's'); ShmID = shmget(MyKey, sizeof(pid_t), IPC_CREAT | 0666); ShmPTR = (pid_t *) shmat(ShmID, NULL, 0); *ShmPTR = pid; for (i = 0; ; i++) { printf("From process %d: %d\n", pid, i); sleep(1); } } void SIGINT_handler(int sig) { signal(sig, SIG_IGN); printf("From SIGINT: just got a %d (SIGINT ^C) signal\n", sig); signal(sig, SIGINT_handler); } void SIGQUIT_handler(int sig) { signal(sig, SIG_IGN); printf("From SIGQUIT: just got a %d (SIGQUIT ^\\) signal" " and is about to quit\n", sig); shmdt(ShmPTR); shmctl(ShmID, IPC_RMID, NULL); exit(3); }
the_stack_data/23574615.c
/* Middle Square Weyl Sequence (PRNG) * Generator state may be seeded to any value. * Ref: https://arxiv.org/abs/1704.00358 * This is free and unencumbered software released into the public domain. */ #include <stdint.h> static uint32_t msws32(uint64_t s[2]) { s[0] *= s[0]; s[1] += 0xdc6b2b45361498ad; s[0] += s[1]; s[0] = s[0]<<32 | s[0]>>32; return s[0]; } static uint64_t msws64(uint64_t s[4]) { unsigned __int128 x = (unsigned __int128)s[1]<<64 | s[0]; unsigned __int128 w = (unsigned __int128)s[3]<<64 | s[2]; x *= x; w += (unsigned __int128)0x918fba1eff8e67e1<<64 | 0x8367589d496e8afd; x += w; s[0] = x >> 64; s[1] = x >> 0; s[2] = w >> 0; s[3] = w >> 64; return s[0]; }
the_stack_data/131426.c
/* TAGS: min c */ /* LIFT_OPTS: explicit +--explicit_args +--explicit_args_count 8 */ /* LIFT_OPTS: default */ #include <assert.h> #include <stdio.h> // Compiler should generate bitcast in llvm.global_ctors and llvm.global_dtors. int x = 0, y = 0; __attribute__((constructor(1), destructor(1))) void assert_zeroes() { assert( x == 0 ); assert( y == 0 ); putchar( 'c' ); } __attribute__((constructor(2))) int increase_and_return() { ++x; return x; } __attribute__((destructor(2))) int decrease_and_return() { --x; return x; } int main() { assert( x == 1 ); int inc_x = increase_and_return(); assert( x == inc_x ); int dec_x = decrease_and_return(); assert( x == dec_x ); }
the_stack_data/116360.c
/* f2c.h -- Standard Fortran to C header file */ /** barf [ba:rf] 2. "He suggested using FORTRAN, and everybody barfed." - From The Shogakukan DICTIONARY OF NEW ENGLISH (Second edition) */ #ifndef F2C_INCLUDE #define F2C_INCLUDE #include <math.h> #include <stdlib.h> #include <string.h> #include <stdio.h> #include <complex.h> #ifdef complex #undef complex #endif #ifdef I #undef I #endif #if defined(_WIN64) typedef long long BLASLONG; typedef unsigned long long BLASULONG; #else typedef long BLASLONG; typedef unsigned long BLASULONG; #endif #ifdef LAPACK_ILP64 typedef BLASLONG blasint; #if defined(_WIN64) #define blasabs(x) llabs(x) #else #define blasabs(x) labs(x) #endif #else typedef int blasint; #define blasabs(x) abs(x) #endif typedef blasint integer; typedef unsigned int uinteger; typedef char *address; typedef short int shortint; typedef float real; typedef double doublereal; typedef struct { real r, i; } complex; typedef struct { doublereal r, i; } doublecomplex; static inline _Complex float Cf(complex *z) {return z->r + z->i*_Complex_I;} static inline _Complex double Cd(doublecomplex *z) {return z->r + z->i*_Complex_I;} static inline _Complex float * _pCf(complex *z) {return (_Complex float*)z;} static inline _Complex double * _pCd(doublecomplex *z) {return (_Complex double*)z;} #define pCf(z) (*_pCf(z)) #define pCd(z) (*_pCd(z)) typedef int logical; typedef short int shortlogical; typedef char logical1; typedef char integer1; #define TRUE_ (1) #define FALSE_ (0) /* Extern is for use with -E */ #ifndef Extern #define Extern extern #endif /* I/O stuff */ typedef int flag; typedef int ftnlen; typedef int ftnint; /*external read, write*/ typedef struct { flag cierr; ftnint ciunit; flag ciend; char *cifmt; ftnint cirec; } cilist; /*internal read, write*/ typedef struct { flag icierr; char *iciunit; flag iciend; char *icifmt; ftnint icirlen; ftnint icirnum; } icilist; /*open*/ typedef struct { flag oerr; ftnint ounit; char *ofnm; ftnlen ofnmlen; char *osta; char *oacc; char *ofm; ftnint orl; char *oblnk; } olist; /*close*/ typedef struct { flag cerr; ftnint cunit; char *csta; } cllist; /*rewind, backspace, endfile*/ typedef struct { flag aerr; ftnint aunit; } alist; /* inquire */ typedef struct { flag inerr; ftnint inunit; char *infile; ftnlen infilen; ftnint *inex; /*parameters in standard's order*/ ftnint *inopen; ftnint *innum; ftnint *innamed; char *inname; ftnlen innamlen; char *inacc; ftnlen inacclen; char *inseq; ftnlen inseqlen; char *indir; ftnlen indirlen; char *infmt; ftnlen infmtlen; char *inform; ftnint informlen; char *inunf; ftnlen inunflen; ftnint *inrecl; ftnint *innrec; char *inblank; ftnlen inblanklen; } inlist; #define VOID void union Multitype { /* for multiple entry points */ integer1 g; shortint h; integer i; /* longint j; */ real r; doublereal d; complex c; doublecomplex z; }; typedef union Multitype Multitype; struct Vardesc { /* for Namelist */ char *name; char *addr; ftnlen *dims; int type; }; typedef struct Vardesc Vardesc; struct Namelist { char *name; Vardesc **vars; int nvars; }; typedef struct Namelist Namelist; #define abs(x) ((x) >= 0 ? (x) : -(x)) #define dabs(x) (fabs(x)) #define f2cmin(a,b) ((a) <= (b) ? (a) : (b)) #define f2cmax(a,b) ((a) >= (b) ? (a) : (b)) #define dmin(a,b) (f2cmin(a,b)) #define dmax(a,b) (f2cmax(a,b)) #define bit_test(a,b) ((a) >> (b) & 1) #define bit_clear(a,b) ((a) & ~((uinteger)1 << (b))) #define bit_set(a,b) ((a) | ((uinteger)1 << (b))) #define abort_() { sig_die("Fortran abort routine called", 1); } #define c_abs(z) (cabsf(Cf(z))) #define c_cos(R,Z) { pCf(R)=ccos(Cf(Z)); } #define c_div(c, a, b) {pCf(c) = Cf(a)/Cf(b);} #define z_div(c, a, b) {pCd(c) = Cd(a)/Cd(b);} #define c_exp(R, Z) {pCf(R) = cexpf(Cf(Z));} #define c_log(R, Z) {pCf(R) = clogf(Cf(Z));} #define c_sin(R, Z) {pCf(R) = csinf(Cf(Z));} //#define c_sqrt(R, Z) {*(R) = csqrtf(Cf(Z));} #define c_sqrt(R, Z) {pCf(R) = csqrtf(Cf(Z));} #define d_abs(x) (fabs(*(x))) #define d_acos(x) (acos(*(x))) #define d_asin(x) (asin(*(x))) #define d_atan(x) (atan(*(x))) #define d_atn2(x, y) (atan2(*(x),*(y))) #define d_cnjg(R, Z) { pCd(R) = conj(Cd(Z)); } #define r_cnjg(R, Z) { pCf(R) = conj(Cf(Z)); } #define d_cos(x) (cos(*(x))) #define d_cosh(x) (cosh(*(x))) #define d_dim(__a, __b) ( *(__a) > *(__b) ? *(__a) - *(__b) : 0.0 ) #define d_exp(x) (exp(*(x))) #define d_imag(z) (cimag(Cd(z))) #define r_imag(z) (cimag(Cf(z))) #define d_int(__x) (*(__x)>0 ? floor(*(__x)) : -floor(- *(__x))) #define r_int(__x) (*(__x)>0 ? floor(*(__x)) : -floor(- *(__x))) #define d_lg10(x) ( 0.43429448190325182765 * log(*(x)) ) #define r_lg10(x) ( 0.43429448190325182765 * log(*(x)) ) #define d_log(x) (log(*(x))) #define d_mod(x, y) (fmod(*(x), *(y))) #define u_nint(__x) ((__x)>=0 ? floor((__x) + .5) : -floor(.5 - (__x))) #define d_nint(x) u_nint(*(x)) #define u_sign(__a,__b) ((__b) >= 0 ? ((__a) >= 0 ? (__a) : -(__a)) : -((__a) >= 0 ? (__a) : -(__a))) #define d_sign(a,b) u_sign(*(a),*(b)) #define r_sign(a,b) u_sign(*(a),*(b)) #define d_sin(x) (sin(*(x))) #define d_sinh(x) (sinh(*(x))) #define d_sqrt(x) (sqrt(*(x))) #define d_tan(x) (tan(*(x))) #define d_tanh(x) (tanh(*(x))) #define i_abs(x) abs(*(x)) #define i_dnnt(x) ((integer)u_nint(*(x))) #define i_len(s, n) (n) #define i_nint(x) ((integer)u_nint(*(x))) #define i_sign(a,b) ((integer)u_sign((integer)*(a),(integer)*(b))) #define pow_dd(ap, bp) ( pow(*(ap), *(bp))) #define pow_si(B,E) spow_ui(*(B),*(E)) #define pow_ri(B,E) spow_ui(*(B),*(E)) #define pow_di(B,E) dpow_ui(*(B),*(E)) #define pow_zi(p, a, b) {pCd(p) = zpow_ui(Cd(a), *(b));} #define pow_ci(p, a, b) {pCf(p) = cpow_ui(Cf(a), *(b));} #define pow_zz(R,A,B) {pCd(R) = cpow(Cd(A),*(B));} #define s_cat(lpp, rpp, rnp, np, llp) { ftnlen i, nc, ll; char *f__rp, *lp; ll = (llp); lp = (lpp); for(i=0; i < (int)*(np); ++i) { nc = ll; if((rnp)[i] < nc) nc = (rnp)[i]; ll -= nc; f__rp = (rpp)[i]; while(--nc >= 0) *lp++ = *(f__rp)++; } while(--ll >= 0) *lp++ = ' '; } #define s_cmp(a,b,c,d) ((integer)strncmp((a),(b),f2cmin((c),(d)))) #define s_copy(A,B,C,D) { int __i,__m; for (__i=0, __m=f2cmin((C),(D)); __i<__m && (B)[__i] != 0; ++__i) (A)[__i] = (B)[__i]; } #define sig_die(s, kill) { exit(1); } #define s_stop(s, n) {exit(0);} static char junk[] = "\n@(#)LIBF77 VERSION 19990503\n"; #define z_abs(z) (cabs(Cd(z))) #define z_exp(R, Z) {pCd(R) = cexp(Cd(Z));} #define z_sqrt(R, Z) {pCd(R) = csqrt(Cd(Z));} #define myexit_() break; #define mycycle() continue; #define myceiling(w) {ceil(w)} #define myhuge(w) {HUGE_VAL} //#define mymaxloc_(w,s,e,n) {if (sizeof(*(w)) == sizeof(double)) dmaxloc_((w),*(s),*(e),n); else dmaxloc_((w),*(s),*(e),n);} #define mymaxloc(w,s,e,n) {dmaxloc_(w,*(s),*(e),n)} /* procedure parameter types for -A and -C++ */ #define F2C_proc_par_types 1 #ifdef __cplusplus typedef logical (*L_fp)(...); #else typedef logical (*L_fp)(); #endif static float spow_ui(float x, integer n) { float pow=1.0; unsigned long int u; if(n != 0) { if(n < 0) n = -n, x = 1/x; for(u = n; ; ) { if(u & 01) pow *= x; if(u >>= 1) x *= x; else break; } } return pow; } static double dpow_ui(double x, integer n) { double pow=1.0; unsigned long int u; if(n != 0) { if(n < 0) n = -n, x = 1/x; for(u = n; ; ) { if(u & 01) pow *= x; if(u >>= 1) x *= x; else break; } } return pow; } static _Complex float cpow_ui(_Complex float x, integer n) { _Complex float pow=1.0; unsigned long int u; if(n != 0) { if(n < 0) n = -n, x = 1/x; for(u = n; ; ) { if(u & 01) pow *= x; if(u >>= 1) x *= x; else break; } } return pow; } static _Complex double zpow_ui(_Complex double x, integer n) { _Complex double pow=1.0; unsigned long int u; if(n != 0) { if(n < 0) n = -n, x = 1/x; for(u = n; ; ) { if(u & 01) pow *= x; if(u >>= 1) x *= x; else break; } } return pow; } static integer pow_ii(integer x, integer n) { integer pow; unsigned long int u; if (n <= 0) { if (n == 0 || x == 1) pow = 1; else if (x != -1) pow = x == 0 ? 1/x : 0; else n = -n; } if ((n > 0) || !(n == 0 || x == 1 || x != -1)) { u = n; for(pow = 1; ; ) { if(u & 01) pow *= x; if(u >>= 1) x *= x; else break; } } return pow; } static integer dmaxloc_(double *w, integer s, integer e, integer *n) { double m; integer i, mi; for(m=w[s-1], mi=s, i=s+1; i<=e; i++) if (w[i-1]>m) mi=i ,m=w[i-1]; return mi-s+1; } static integer smaxloc_(float *w, integer s, integer e, integer *n) { float m; integer i, mi; for(m=w[s-1], mi=s, i=s+1; i<=e; i++) if (w[i-1]>m) mi=i ,m=w[i-1]; return mi-s+1; } static inline void cdotc_(complex *z, integer *n_, complex *x, integer *incx_, complex *y, integer *incy_) { integer n = *n_, incx = *incx_, incy = *incy_, i; _Complex float zdotc = 0.0; if (incx == 1 && incy == 1) { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += conjf(Cf(&x[i])) * Cf(&y[i]); } } else { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += conjf(Cf(&x[i*incx])) * Cf(&y[i*incy]); } } pCf(z) = zdotc; } static inline void zdotc_(doublecomplex *z, integer *n_, doublecomplex *x, integer *incx_, doublecomplex *y, integer *incy_) { integer n = *n_, incx = *incx_, incy = *incy_, i; _Complex double zdotc = 0.0; if (incx == 1 && incy == 1) { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += conj(Cd(&x[i])) * Cd(&y[i]); } } else { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += conj(Cd(&x[i*incx])) * Cd(&y[i*incy]); } } pCd(z) = zdotc; } static inline void cdotu_(complex *z, integer *n_, complex *x, integer *incx_, complex *y, integer *incy_) { integer n = *n_, incx = *incx_, incy = *incy_, i; _Complex float zdotc = 0.0; if (incx == 1 && incy == 1) { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += Cf(&x[i]) * Cf(&y[i]); } } else { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += Cf(&x[i*incx]) * Cf(&y[i*incy]); } } pCf(z) = zdotc; } static inline void zdotu_(doublecomplex *z, integer *n_, doublecomplex *x, integer *incx_, doublecomplex *y, integer *incy_) { integer n = *n_, incx = *incx_, incy = *incy_, i; _Complex double zdotc = 0.0; if (incx == 1 && incy == 1) { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += Cd(&x[i]) * Cd(&y[i]); } } else { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += Cd(&x[i*incx]) * Cd(&y[i*incy]); } } pCd(z) = zdotc; } #endif /* -- translated by f2c (version 20000121). You must link the resulting object file with the libraries: -lf2c -lm (in that order) */ /* > \brief \b ILACLR scans a matrix for its last non-zero row. */ /* =========== DOCUMENTATION =========== */ /* Online html documentation available at */ /* http://www.netlib.org/lapack/explore-html/ */ /* > \htmlonly */ /* > Download ILACLR + dependencies */ /* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.tgz?format=tgz&filename=/lapack/lapack_routine/ilaclr. f"> */ /* > [TGZ]</a> */ /* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.zip?format=zip&filename=/lapack/lapack_routine/ilaclr. f"> */ /* > [ZIP]</a> */ /* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.txt?format=txt&filename=/lapack/lapack_routine/ilaclr. f"> */ /* > [TXT]</a> */ /* > \endhtmlonly */ /* Definition: */ /* =========== */ /* INTEGER FUNCTION ILACLR( M, N, A, LDA ) */ /* INTEGER M, N, LDA */ /* COMPLEX A( LDA, * ) */ /* > \par Purpose: */ /* ============= */ /* > */ /* > \verbatim */ /* > */ /* > ILACLR scans A for its last non-zero row. */ /* > \endverbatim */ /* Arguments: */ /* ========== */ /* > \param[in] M */ /* > \verbatim */ /* > M is INTEGER */ /* > The number of rows of the matrix A. */ /* > \endverbatim */ /* > */ /* > \param[in] N */ /* > \verbatim */ /* > N is INTEGER */ /* > The number of columns of the matrix A. */ /* > \endverbatim */ /* > */ /* > \param[in] A */ /* > \verbatim */ /* > A is COMPLEX array, dimension (LDA,N) */ /* > The m by n matrix A. */ /* > \endverbatim */ /* > */ /* > \param[in] LDA */ /* > \verbatim */ /* > LDA is INTEGER */ /* > The leading dimension of the array A. LDA >= f2cmax(1,M). */ /* > \endverbatim */ /* Authors: */ /* ======== */ /* > \author Univ. of Tennessee */ /* > \author Univ. of California Berkeley */ /* > \author Univ. of Colorado Denver */ /* > \author NAG Ltd. */ /* > \date June 2017 */ /* > \ingroup complexOTHERauxiliary */ /* ===================================================================== */ integer ilaclr_(integer *m, integer *n, complex *a, integer *lda) { /* System generated locals */ integer a_dim1, a_offset, ret_val, i__1, i__2; /* Local variables */ integer i__, j; /* -- LAPACK auxiliary routine (version 3.7.1) -- */ /* -- LAPACK is a software package provided by Univ. of Tennessee, -- */ /* -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..-- */ /* June 2017 */ /* ===================================================================== */ /* Quick test for the common case where one corner is non-zero. */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1 * 1; a -= a_offset; /* Function Body */ if (*m == 0) { ret_val = *m; } else /* if(complicated condition) */ { i__1 = *m + a_dim1; i__2 = *m + *n * a_dim1; if (a[i__1].r != 0.f || a[i__1].i != 0.f || (a[i__2].r != 0.f || a[ i__2].i != 0.f)) { ret_val = *m; } else { /* Scan up each column tracking the last zero row seen. */ ret_val = 0; i__1 = *n; for (j = 1; j <= i__1; ++j) { i__ = *m; for(;;) { /* while(complicated condition) */ i__2 = f2cmax(i__,1) + j * a_dim1; if (!(a[i__2].r == 0.f && a[i__2].i == 0.f && i__ >= 1)) break; --i__; } ret_val = f2cmax(ret_val,i__); } } } return ret_val; } /* ilaclr_ */
the_stack_data/39197.c
#include <unistd.h> int mx_strlen(const char *s); void mx_printstr(const char *s) { write(1, "$@", mx_strlen(s)); } // int main(){ // mx_printstr("sifdgfjbe"); // }
the_stack_data/356132.c
char clang_mwaitxintrin_buf [] = { 47,42,61,61,61,45,45,45,45,32,109,119,97,105,116,120, 105,110,116,114,105,110,46,104,32,45,32,77,79,78,73,84, 79,82,88,47,77,87,65,73,84,88,32,105,110,116,114,105, 110,115,105,99,115,32,45,45,45,45,45,45,45,45,45,45, 45,45,45,45,45,45,45,45,45,45,45,45,61,61,61,10, 32,42,10,32,42,32,80,101,114,109,105,115,115,105,111,110, 32,105,115,32,104,101,114,101,98,121,32,103,114,97,110,116, 101,100,44,32,102,114,101,101,32,111,102,32,99,104,97,114, 103,101,44,32,116,111,32,97,110,121,32,112,101,114,115,111, 110,32,111,98,116,97,105,110,105,110,103,32,97,32,99,111, 112,121,10,32,42,32,111,102,32,116,104,105,115,32,115,111, 102,116,119,97,114,101,32,97,110,100,32,97,115,115,111,99, 105,97,116,101,100,32,100,111,99,117,109,101,110,116,97,116, 105,111,110,32,102,105,108,101,115,32,40,116,104,101,32,34, 83,111,102,116,119,97,114,101,34,41,44,32,116,111,32,100, 101,97,108,10,32,42,32,105,110,32,116,104,101,32,83,111, 102,116,119,97,114,101,32,119,105,116,104,111,117,116,32,114, 101,115,116,114,105,99,116,105,111,110,44,32,105,110,99,108, 117,100,105,110,103,32,119,105,116,104,111,117,116,32,108,105, 109,105,116,97,116,105,111,110,32,116,104,101,32,114,105,103, 104,116,115,10,32,42,32,116,111,32,117,115,101,44,32,99, 111,112,121,44,32,109,111,100,105,102,121,44,32,109,101,114, 103,101,44,32,112,117,98,108,105,115,104,44,32,100,105,115, 116,114,105,98,117,116,101,44,32,115,117,98,108,105,99,101, 110,115,101,44,32,97,110,100,47,111,114,32,115,101,108,108, 10,32,42,32,99,111,112,105,101,115,32,111,102,32,116,104, 101,32,83,111,102,116,119,97,114,101,44,32,97,110,100,32, 116,111,32,112,101,114,109,105,116,32,112,101,114,115,111,110, 115,32,116,111,32,119,104,111,109,32,116,104,101,32,83,111, 102,116,119,97,114,101,32,105,115,10,32,42,32,102,117,114, 110,105,115,104,101,100,32,116,111,32,100,111,32,115,111,44, 32,115,117,98,106,101,99,116,32,116,111,32,116,104,101,32, 102,111,108,108,111,119,105,110,103,32,99,111,110,100,105,116, 105,111,110,115,58,10,32,42,10,32,42,32,84,104,101,32, 97,98,111,118,101,32,99,111,112,121,114,105,103,104,116,32, 110,111,116,105,99,101,32,97,110,100,32,116,104,105,115,32, 112,101,114,109,105,115,115,105,111,110,32,110,111,116,105,99, 101,32,115,104,97,108,108,32,98,101,32,105,110,99,108,117, 100,101,100,32,105,110,10,32,42,32,97,108,108,32,99,111, 112,105,101,115,32,111,114,32,115,117,98,115,116,97,110,116, 105,97,108,32,112,111,114,116,105,111,110,115,32,111,102,32, 116,104,101,32,83,111,102,116,119,97,114,101,46,10,32,42, 10,32,42,32,84,72,69,32,83,79,70,84,87,65,82,69, 32,73,83,32,80,82,79,86,73,68,69,68,32,34,65,83, 32,73,83,34,44,32,87,73,84,72,79,85,84,32,87,65, 82,82,65,78,84,89,32,79,70,32,65,78,89,32,75,73, 78,68,44,32,69,88,80,82,69,83,83,32,79,82,10,32, 42,32,73,77,80,76,73,69,68,44,32,73,78,67,76,85, 68,73,78,71,32,66,85,84,32,78,79,84,32,76,73,77, 73,84,69,68,32,84,79,32,84,72,69,32,87,65,82,82, 65,78,84,73,69,83,32,79,70,32,77,69,82,67,72,65, 78,84,65,66,73,76,73,84,89,44,10,32,42,32,70,73, 84,78,69,83,83,32,70,79,82,32,65,32,80,65,82,84, 73,67,85,76,65,82,32,80,85,82,80,79,83,69,32,65, 78,68,32,78,79,78,73,78,70,82,73,78,71,69,77,69, 78,84,46,32,73,78,32,78,79,32,69,86,69,78,84,32, 83,72,65,76,76,32,84,72,69,10,32,42,32,65,85,84, 72,79,82,83,32,79,82,32,67,79,80,89,82,73,71,72, 84,32,72,79,76,68,69,82,83,32,66,69,32,76,73,65, 66,76,69,32,70,79,82,32,65,78,89,32,67,76,65,73, 77,44,32,68,65,77,65,71,69,83,32,79,82,32,79,84, 72,69,82,10,32,42,32,76,73,65,66,73,76,73,84,89, 44,32,87,72,69,84,72,69,82,32,73,78,32,65,78,32, 65,67,84,73,79,78,32,79,70,32,67,79,78,84,82,65, 67,84,44,32,84,79,82,84,32,79,82,32,79,84,72,69, 82,87,73,83,69,44,32,65,82,73,83,73,78,71,32,70, 82,79,77,44,10,32,42,32,79,85,84,32,79,70,32,79, 82,32,73,78,32,67,79,78,78,69,67,84,73,79,78,32, 87,73,84,72,32,84,72,69,32,83,79,70,84,87,65,82, 69,32,79,82,32,84,72,69,32,85,83,69,32,79,82,32, 79,84,72,69,82,32,68,69,65,76,73,78,71,83,32,73, 78,10,32,42,32,84,72,69,32,83,79,70,84,87,65,82, 69,46,10,32,42,10,32,42,61,61,61,45,45,45,45,45, 45,45,45,45,45,45,45,45,45,45,45,45,45,45,45,45, 45,45,45,45,45,45,45,45,45,45,45,45,45,45,45,45, 45,45,45,45,45,45,45,45,45,45,45,45,45,45,45,45, 45,45,45,45,45,45,45,45,45,45,45,45,45,45,45,45, 45,45,61,61,61,10,32,42,47,10,10,35,105,102,110,100, 101,102,32,95,95,88,56,54,73,78,84,82,73,78,95,72, 10,35,101,114,114,111,114,32,34,78,101,118,101,114,32,117, 115,101,32,60,109,119,97,105,116,120,105,110,116,114,105,110, 46,104,62,32,100,105,114,101,99,116,108,121,59,32,105,110, 99,108,117,100,101,32,60,120,56,54,105,110,116,114,105,110, 46,104,62,32,105,110,115,116,101,97,100,46,34,10,35,101, 110,100,105,102,10,10,35,105,102,110,100,101,102,32,95,77, 87,65,73,84,88,73,78,84,82,73,78,95,72,10,35,100, 101,102,105,110,101,32,95,77,87,65,73,84,88,73,78,84, 82,73,78,95,72,10,10,47,42,32,68,101,102,105,110,101, 32,116,104,101,32,100,101,102,97,117,108,116,32,97,116,116, 114,105,98,117,116,101,115,32,102,111,114,32,116,104,101,32, 102,117,110,99,116,105,111,110,115,32,105,110,32,116,104,105, 115,32,102,105,108,101,46,32,42,47,10,35,100,101,102,105, 110,101,32,95,95,68,69,70,65,85,76,84,95,70,78,95, 65,84,84,82,83,32,95,95,97,116,116,114,105,98,117,116, 101,95,95,40,40,95,95,97,108,119,97,121,115,95,105,110, 108,105,110,101,95,95,44,32,95,95,110,111,100,101,98,117, 103,95,95,44,32,32,95,95,116,97,114,103,101,116,95,95, 40,34,109,119,97,105,116,120,34,41,41,41,10,115,116,97, 116,105,99,32,95,95,105,110,108,105,110,101,95,95,32,118, 111,105,100,32,95,95,68,69,70,65,85,76,84,95,70,78, 95,65,84,84,82,83,10,95,109,109,95,109,111,110,105,116, 111,114,120,40,118,111,105,100,32,99,111,110,115,116,32,42, 32,95,95,112,44,32,117,110,115,105,103,110,101,100,32,95, 95,101,120,116,101,110,115,105,111,110,115,44,32,117,110,115, 105,103,110,101,100,32,95,95,104,105,110,116,115,41,10,123, 10,32,32,95,95,98,117,105,108,116,105,110,95,105,97,51, 50,95,109,111,110,105,116,111,114,120,40,40,118,111,105,100, 32,42,41,95,95,112,44,32,95,95,101,120,116,101,110,115, 105,111,110,115,44,32,95,95,104,105,110,116,115,41,59,10, 125,10,10,115,116,97,116,105,99,32,95,95,105,110,108,105, 110,101,95,95,32,118,111,105,100,32,95,95,68,69,70,65, 85,76,84,95,70,78,95,65,84,84,82,83,10,95,109,109, 95,109,119,97,105,116,120,40,117,110,115,105,103,110,101,100, 32,95,95,101,120,116,101,110,115,105,111,110,115,44,32,117, 110,115,105,103,110,101,100,32,95,95,104,105,110,116,115,44, 32,117,110,115,105,103,110,101,100,32,95,95,99,108,111,99, 107,41,10,123,10,32,32,95,95,98,117,105,108,116,105,110, 95,105,97,51,50,95,109,119,97,105,116,120,40,95,95,101, 120,116,101,110,115,105,111,110,115,44,32,95,95,104,105,110, 116,115,44,32,95,95,99,108,111,99,107,41,59,10,125,10, 10,35,117,110,100,101,102,32,95,95,68,69,70,65,85,76, 84,95,70,78,95,65,84,84,82,83,10,10,35,101,110,100, 105,102,32,47,42,32,95,77,87,65,73,84,88,73,78,84, 82,73,78,95,72,32,42,47,10, }; unsigned int clang_mwaitxintrin_buf_size = sizeof(clang_mwaitxintrin_buf);
the_stack_data/212643732.c
#include <stdio.h> int main() { int a[30000], b[3001] = { 0 }, c, d, k, e, f, g, h, i = 0; scanf("%d %d %d %d", &c, &d, &k, &e); g = k; for (; i < c; i++) { scanf("%d", a + i); if (i < k) if (b[a[i]]++) g--; } f = g + (b[e] ? 0 : 1); for (i = 0; i < c; i++) { if (!--b[a[i%c]]) g--; if (!b[a[(i + k)%c]]++) g++; h = b[e] ? 0 : 1; if (f < g + h) f = g + h; } printf("%d", f); }
the_stack_data/150143735.c
/* * Oracle Linux DTrace. * Copyright (c) 2006, 2020, Oracle and/or its affiliates. All rights reserved. * Licensed under the Universal Permissive License v 1.0 as shown at * http://oss.oracle.com/licenses/upl. */ #include <stdlib.h> #include <unistd.h> #include <pthread.h> volatile long long count = 0; int baz(int a) { getpid(); while (count != -1) { count++; a++; } return a + 1; } int bar(int a) { return baz(a + 1) - 1; } struct arg { int a; long b; }; void * foo(void *a) { struct arg *arg = a; int *ret = malloc(sizeof(int)); *ret = bar(arg->a) - arg->b; return ret; } int main(int argc, char **argv) { pthread_attr_t a; struct arg arg = { argc, (long)argv }; pthread_t threads[2]; int *one, *two; /* bleah. */ pthread_attr_init(&a); pthread_attr_setdetachstate(&a, PTHREAD_CREATE_DETACHED); pthread_create(&threads[0], &a, foo, &arg); pthread_create(&threads[1], &a, foo, &arg); pthread_attr_destroy(&a); pause(); pthread_join(threads[0], (void **)&one); pthread_join(threads[1], (void **)&two); return *one - *two; }
the_stack_data/62920.c
#include<stdio.h> void mergesort(int a[],int i,int j); void merge(int a[],int i1,int j1,int j2,int j); int main() { int a[30],n,i; printf("\n Enter the no of elements: "); scanf("%d",&n); printf("Enter array elements:"); for(i=0;i<n;i++) scanf("%d",&a[i]); mergesort(a,0,n-1); printf("\n Sorted Array is: "); for(i=0;i<n;i++) printf("%d",a[i]); return 0; } void mergesort(int a[],int i,int j) { int mid; if(i<j) { mid=(i+j)/2; mergesort(a,i,mid); mergesort(a,mid+1,j); merge(a,i,mid,mid+1,j); } } void merge(int a[],int i1,int j1,int i2,int j2) { int temp[50]; int i,j,k; i=i1; j=i2; k=0; while(i<=j1 && j<=j2) { if(a[i]<a[j]) temp[k++]=a[i++]; else temp[k++]=a[j++]; } while(i<=j1) temp[k++]=a[i++]; while(j<=j2) temp[k++]=a[j++]; for(i=i1,j=0;i<=j2;i++,j++) a[i]=temp[j]; }
the_stack_data/90763703.c
/* Password Protected Hello 4 */ #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> //Forward Declarations //=========================================================================== void Fini(void); bool LoadUsers(void); void FreeUsers(void); //Structures //=========================================================================== typedef struct { char name[32]; char pswd[32]; } User; //Constants //=========================================================================== User *users = NULL; int userCnt; //Functions //=========================================================================== bool Init(void) { //Load user data printf("%s", "Loading user data..."); if(!LoadUsers()) { printf("%s\n", "failed"); fprintf(stderr, "%s\n", "Fatal Error: Failed to load user data."); return false; } printf("%s\n", "ok"); //Register with atexit atexit(Fini); return true; } void Fini(void) { //Free user data FreeUsers(); } bool LoadUsers(void) { //Open users config file FILE *usrCfg = fopen("./data/users.cfg", "r"); if(usrCfg == NULL) { return false; } //Find users section char line[64] = ""; while(strncmp(line, "[Users]", 7) != 0) { //Get next line fgets(line, sizeof(line), usrCfg); //Fail if no users section if(feof(usrCfg)) { return false; } } //Parse user count if(fscanf(usrCfg, "count = %i ", &userCnt) < 1) { fprintf(stderr, "%s\n", "Fatal Error: User config file is corrupt."); return false; } //Allocate users array users = (User*)malloc(sizeof(User) * userCnt); if(users == NULL) { fprintf(stderr, "%s\n", "Fatal Error: Out of memory."); return false; } //Load user data int i = 0; while(i < userCnt) { //Get next line fgets(line, sizeof(line), usrCfg); //User entry? if(strncmp(line, "[User]", 6) == 0) { //Load user data if(fscanf(usrCfg, "name = %31s pswd = %31s ", users[i].name, users[i].pswd) < 2) { free(users); fclose(usrCfg); fprintf(stderr, "%s\n", "Fatal Error: Failed to parse user data."); return false; } i++; } //Corrupt garbage else { free(users); fclose(usrCfg); fprintf(stderr, "%s\n", "Fatal Error: User config file is corrupt."); return false; } } //Close users config file fclose(usrCfg); return true; } void FreeUsers(void) { free(users); } void Prompt(char *msg, char *buf, int bufSize) { //Display prompt printf("%s ", msg); //Get input fgets(buf, bufSize, stdin); buf[strlen(buf) - 1] = 0; } bool IsValid(char *name, char *pswd) { //Verify password for(int i = 0; i < userCnt; i++) { //Found username? if(strcmp(name, users[i].name) == 0) { return (strcmp(pswd, users[i].pswd) == 0); } } return false; } //Entry Point //=========================================================================== int main(int argc, char **argv) { //Initialize if(!Init()) { return 1; } //Get credentials char name[32]; char pswd[32]; Prompt("Name:", name, sizeof(name)); Prompt("Pswd:", pswd, sizeof(pswd)); //Verify credentials if(IsValid(name, pswd)) { printf("Hello %s!\n", name); } else { printf("You're not allowed here %s!\n", name); } return 0; }
the_stack_data/1235725.c
/* QUESTAO 1 LISTA 2 Utilize uma estrutura de controle em um algoritmo que imprime a tabuada de 1 a 3. */ #include <stdio.h> int main(void) { int i, j, x; for(i=1; i<=3; ++i){ printf("TABUADA DO %d\n", i); for(j=0; j<=9; ++j){ x=i*j; printf("%d x %d = %d\n", i, j, x); } printf("\n\n"); } return 0; }
the_stack_data/162643195.c
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> #define MAX_CHARACTERS 1005 #define MAX_PARAGRAPHS 5 struct word { char* data; }; struct sentence { struct word* data; int word_count;//denotes number of words in a sentence }; struct paragraph { struct sentence* data ; int sentence_count;//denotes number of sentences in a paragraph }; struct document { struct paragraph* data; int paragraph_count;//denotes number of paragraphs in a document }; struct word get_word(char* text, int beg, int end) { struct word answer; answer.data = calloc(end - beg + 2, sizeof(char)); int index = 0; int i; for (i = beg; i <= end; i++) answer.data[index++] = text[i]; answer.data[index] = 0; return answer; } struct sentence get_sentence(char* text, int beg, int end) { struct sentence answer; answer.word_count = 1; int i; for (i = beg; i <= end; i++) if (text[i] == ' ') ++answer.word_count; answer.data = calloc(answer.word_count, sizeof(struct word)); int start = beg; int index = 0; for (i = beg; i <= end; i++) if (text[i] == ' ') { answer.data[index++] = get_word(text, start, i - 1); start = i + 1; } answer.data[index] = get_word(text, start, i - 1); return answer; } struct paragraph get_paragraph(char* text, int beg, int end) { struct paragraph answer; answer.sentence_count = 0; int i; for (i = beg; i <= end; i++) if (text[i] == '.') ++answer.sentence_count; answer.data = calloc(answer.sentence_count, sizeof(struct sentence)); int start = beg; int index = 0; for (i = beg; i <= end; i++) if (text[i] == '.') { answer.data[index++] = get_sentence(text, start, i - 1); start = i + 1; } return answer; } struct document get_document(char* text) { struct document answer; answer.paragraph_count = 1; int i; for (i = 0; text[i]; i++) if (text[i] == '\n') ++answer.paragraph_count; answer.data = calloc(answer.paragraph_count, sizeof(struct paragraph)); int start = 0; int index = 0; for (i = 0; text[i]; i++) if (text[i] == '\n') { answer.data[index++] = get_paragraph(text, start, i - 1); start = i + 1; } answer.data[index] = get_paragraph(text, start, i - 1); return answer; } struct word kth_word_in_mth_sentence_of_nth_paragraph(struct document Doc, int k, int m, int n) { return Doc.data[n - 1].data[m - 1].data[k - 1]; } struct sentence kth_sentence_in_mth_paragraph(struct document Doc, int k, int m) { return Doc.data[m - 1].data[k - 1]; } struct paragraph kth_paragraph(struct document Doc, int k) { return Doc.data[k - 1]; } void print_word(struct word w) { printf("%s", w.data); } void print_sentence(struct sentence sen) { for(int i = 0; i < sen.word_count; i++) { print_word(sen.data[i]); if (i != sen.word_count - 1) { printf(" "); } } } void print_paragraph(struct paragraph para) { for(int i = 0; i < para.sentence_count; i++){ print_sentence(para.data[i]); printf("."); } } void print_document(struct document doc) { for(int i = 0; i < doc.paragraph_count; i++) { print_paragraph(doc.data[i]); if (i != doc.paragraph_count - 1) printf("\n"); } } char* get_input_text() { int paragraph_count; scanf("%d", &paragraph_count); char p[MAX_PARAGRAPHS][MAX_CHARACTERS], doc[MAX_CHARACTERS]; memset(doc, 0, sizeof(doc)); getchar(); for (int i = 0; i < paragraph_count; i++) { scanf("%[^\n]%*c", p[i]); strcat(doc, p[i]); if (i != paragraph_count - 1) strcat(doc, "\n"); } char* returnDoc = (char*)malloc((strlen (doc)+1) * (sizeof(char))); strcpy(returnDoc, doc); return returnDoc; } int main() { char* text = get_input_text(); struct document Doc = get_document(text); int q; scanf("%d", &q); while (q--) { int type; scanf("%d", &type); if (type == 3){ int k, m, n; scanf("%d %d %d", &k, &m, &n); struct word w = kth_word_in_mth_sentence_of_nth_paragraph(Doc, k, m, n); print_word(w); } else if (type == 2) { int k, m; scanf("%d %d", &k, &m); struct sentence sen= kth_sentence_in_mth_paragraph(Doc, k, m); print_sentence(sen); } else{ int k; scanf("%d", &k); struct paragraph para = kth_paragraph(Doc, k); print_paragraph(para); } printf("\n"); } }
the_stack_data/51700521.c
#include<stdio.h> #include<stdlib.h> struct treenode { struct treenode *left; struct treenode *right; int data; }; struct treenode * getnode(int i) { struct treenode *node = (struct treenode *) malloc(sizeof(struct treenode)); node->left = NULL; node->right = NULL; node->data = i; return node; } void print_k_distance_down(struct treenode *root, int k) { if (root == NULL || k <0) { return; } if (k==0) { printf("%d ", root->data); } print_k_distance_down(root->left, k-1); print_k_distance_down(root->right, k-1); } int get_k_distance(struct treenode *root, struct treenode *node, int k) { // base case if(root == NULL) { // we didnt not found the node so far return -1; } if(root == node) { // we found the target node; node print all nodes below it k distcance away print_k_distance_down(root, k); return 0; } int dl = get_k_distance(root->left, node, k); if(dl != -1) { // this means we have found target node in left subtree if(dl+1 == k) { // check if left child is k-1 distance away, it means this node is k distance away printf("%d ", root->data); } else { // if not then search right subtree print_k_distance_down(root->right, k-dl-2); } // return distance of this node return dl+1; } int dr = get_k_distance(root->right, node, k); if(dr != 0) { if(dr+1 == k) { printf("%d ", root->data); } else { print_k_distance_down(root->left, k-dr-2); } return dr+1; } return -1; } void inorder(struct treenode *root) { if(root) { inorder(root->left); printf("%d ", root->data); inorder(root->right); } } void main() { struct treenode *root = getnode(10); root->left = getnode(5); root->right = getnode(15); root->left->left = getnode(3); root->left->right = getnode(7); root->right->left = getnode(13); root->right->right = getnode(17); //inorder(root); //get_k_distance(root, root->right->right, 2); get_k_distance(root, root->right, 2); }
the_stack_data/125195.c
#include <stdio.h> #include <stdlib.h> #include <math.h> void pausar(){ printf("\nPressione alguma tecla para continuar..."); getch(); } int main(){ float a, b, hipotenusa, area, perimetro, seno, cosseno; printf("Triangulo Retangulo \n"); printf("Letra A: \n"); printf("Digite o valor da Altura: \n"); scanf("%f", &a); printf("Digite o valor da Base: \n"); scanf("%f", &b); hipotenusa = sqrt(pow(a, 2) + pow(b, 2)); printf("Resultado da Hipotenusa eh: %f \n", hipotenusa); printf("----------------------------------------------------------------- \n"); printf("Letra B: \n"); area = a * b / 2; printf("Resultado da area eh: %f \n", area); printf("----------------------------------------------------------------- \n"); printf("Letra C: \n"); perimetro = a + b + hipotenusa; printf("Resultado do perimetro eh: %f \n", perimetro); printf("----------------------------------------------------------------- \n"); printf("Letra D: \n"); seno = sin(a / hipotenusa); cosseno = cos(b / hipotenusa); printf("Resultado do Seno eh: %f \n", seno); printf("Resultado do Cosseno eh: %f \n", cosseno); pausar(); return (0); }
the_stack_data/64199460.c
//Luiz Fernando -- Matricula: 159325 //Tarefa 003 - Exercício 3 /*Programa que lê um numero inteiro e retorna se é um número natural triangular*/ #include <stdio.h> int main() { int numero, i; scanf("%d", &numero); i = 1; while ((i * (i + 1) * (i + 2)) <= numero) { i = i + 1; } if (((i - 1) * i * (i + 1)) == numero) { printf("sim"); } else { printf("nao"); } return 0; }
the_stack_data/50137986.c
// RUN: %clang_cc1 -fdebug-compilation-dir /nonsense -emit-llvm -g %s -o - | FileCheck -check-prefix=CHECK-NONSENSE %s // CHECK-NONSENSE: nonsense // RUN: %clang_cc1 -emit-llvm -g %s -o - | FileCheck -check-prefix=CHECK-DIR %s // CHECK-DIR: CodeGen
the_stack_data/115765846.c
/*Exercício 08 - Preencher um vetor com os números pares do número 2 a 20. Preencher um vetor com os números de 10 a 19. Somar os vetores acima.*/ #include<stdio.h> int main(void){ int i, auxiliar = 0, vet_pares[10], vet_alearorios[10]; // preechimento do vet_paresor vet_pares for(i = 0; i <= 9; i++){ vet_pares[i] = auxiliar + 2; auxiliar = auxiliar + 2; } //exibindo o vet_paresor vet_pares for(i = 0; i <= 9; i++){ //exibindo os valores pares 2,4,6,8,10,12,14,16,18,20. printf("\t %d ",vet_pares[i]); } printf("\n"); // preechimento do vet_paresor, vet_alearorios for(i = 0; i <= 9; i++){ vet_alearorios[i] = i+10; } //exibindo o vet_paresor, vet_alearorios for(i = 0; i <= 9; i++){ //exibindo os valores pares 10,11,12,13,14,15,16,17,18,19,20. printf("\t %d ", vet_alearorios[i]); } printf("\n"); //preechimento da soma dos vet_paresores vet_pares[i] +, vet_alearorios[i] for(i = 0; i <= 9; i++){ /*exibindo a soma dos valores 2+10=12, 4+11=15, 6+12=18, 8+13=21 10+14=24, 12+15=27, 14+16=30, 16+17=33, 18+18=36, 20+19=39*/ printf("\t %d ",vet_pares[i] + vet_alearorios[i]); } printf("\n\n"); system("pause"); }
the_stack_data/830149.c
#include <stdio.h> #include <stdlib.h> main () { int return_value; return_value = system ("ls -l /"); printf("valor devuelto=%d\n", return_value); }
the_stack_data/1182280.c
#include<stdio.h> #include<malloc.h> #include<stdlib.h> #include<string.h> typedef struct tree_node_s { float frequency; char c; char code[128]; struct tree_node_s *left; struct tree_node_s *right; } tree_node_t; tree_node_t *arr[26], *letters[26]; void findMinAndSecondMin(tree_node_t **, float *, int *, float *, int *); void printTree(tree_node_t *); void interpret(char *, int *, tree_node_t *); void printTree(tree_node_t *); void encode(tree_node_t *, tree_node_t **, char, short, char*); int main() { char str[128]; int i, j,k, index, n,r; float min, secondMin; int minIndex, secondMinIndex; int numberOfCharacters = 0; tree_node_t *tree; FILE *fp = fopen("sdlab.txt", "r"); if ( fp == NULL ) { printf("\nFile not found"); return 0; } else { for (i = 'A'; i <= 'Z'; i++) { index = i - 'A'; arr[index] = NULL; }//For having none values in each index;arr[26==NULL]; numberOfCharacters = 0; r = fgets(str, 128, fp) != NULL; while(!feof(fp) || r) { n = strlen(str); printf("\n%s", str); for (i = 0; i < n ; i ++ ) { str[i] = toupper(str[i]);//Uppercase Conversion for any char if (str[i] >= 'A' && str[i] <= 'Z') { numberOfCharacters =numberOfCharacters+1; index = str[i] - 'A'; if (arr[index] == NULL) { arr[index] = malloc(sizeof(tree_node_t)); (*arr[index]).c = str[i]; (*arr[index]).frequency = 1; (*arr[index]).left = (*arr[index]).right = NULL; } else { (*arr[index]).frequency ++ ; } } } if (r==1) { r = fgets(str, 128, fp) != NULL; } } } fclose(fp); for ( i = 0, n = 0 ; i < 26 ; i ++ ) { letters[i] = arr[i]; if (arr[i] != NULL) { //(*arr[i]).frequency = (*arr[i]).frequency/numberOfCharacters; // Computing the frequency. n ++; // n is the number of involved letters which is going to be consumed in the do while loop's condition } } j = 1; do { findMinAndSecondMin(arr, &min, &minIndex, &secondMin, &secondMinIndex); if (minIndex != -1 && secondMinIndex != -1 && minIndex != secondMinIndex) { tree_node_t *temp; tree = malloc(sizeof(tree_node_t)); (*tree).frequency = (*arr[minIndex]).frequency + (*arr[secondMinIndex]).frequency; (*tree).c = j; (*tree).left = arr[minIndex]; temp =malloc(sizeof(tree_node_t)); (*temp).c = (*arr[secondMinIndex]).c; (*temp).frequency = (*arr[secondMinIndex]).frequency; (*temp).left = (*arr[secondMinIndex]).left; (*temp).right = (*arr[secondMinIndex]).right; (*tree).right = temp; arr[minIndex] = tree; arr[secondMinIndex] = NULL; } j ++; } while( j < n ); for ( i = 0 ; i < 26 ; i ++ ) { if (arr[i] != NULL) { char code[128]; strcpy(code, ""); encode(tree = arr[i], letters, 0, 0, code); puts("\nSuccessful encoding"); printTree(arr[i]); break; } } fp = fopen("sdlab.txt", "r"); r = fgets(str, 128, fp) != NULL; while(!feof(fp) || r) { n = strlen(str); for (i = 0; i < n ; i ++ ) { str[i] = toupper(str[i]); if (str[i] >= 'A' && str[i] <= 'Z') { index = str[i] - 'A'; } } if (r) { r = fgets(str, 128, fp) != NULL; } } fclose(fp); printf("\nFile size (only letters) of the input file:%d bits", numberOfCharacters * 8); numberOfCharacters = 0; return 0; } //LEFT RIGHT void encode(tree_node_t *node, tree_node_t **letters, char direction, short level, char* code) { int n; if ( node != NULL ) { if ((n = strlen(code)) < level) { if (direction == 'R') { strcat(code, "1"); } else { if (direction == 'L') { strcat(code, "0"); } } } else { if (n >= level) { code[n - (n - level) - 1] = 0; if (direction == 'R') { strcat(code, "1"); } else { if (direction == 'L') { strcat(code, "0"); } } } } if ((*node).c >= 'A' && (*node).c <= 'Z') { strcpy((*node).code, code); strcpy((*letters[(*node).c - 'A']).code, code); } encode((*node).left, letters, 'L', level + 1, code); encode((*node).right, letters, 'R', level + 1, code); } } void printTree(tree_node_t *node) { int n; if ( node != NULL ) { if ((*node).c >= 'A' && (*node).c <= 'Z') { printf("\t%c - frequency: %.0f\tencoding: %s\n", (*node).c, (*node).frequency, (*node).code); } printTree((*node).left); printTree((*node).right); } } void findMinAndSecondMin(tree_node_t *arr[], float *min, int *minIndex, float *secondMin, int *secondMinIndex) { int i, k; k = 0; *minIndex = -1; while (k < 26 && arr[k] == NULL) k++; *minIndex = k; *min = (*arr[k]).frequency; for ( i = k ; i < 26; i ++ ) { if ( arr[i] != NULL && (*arr[i]).frequency < *min ) { *min = (*arr[i]).frequency; *minIndex = i; } } k = 0; *secondMinIndex = -1; while ((k < 26 && arr[k] == NULL) || (k == *minIndex && arr[k] != NULL)) k++; *secondMin = (*arr[k]).frequency; *secondMinIndex = k; if (k == *minIndex) k ++; for ( i = k ; i < 26; i ++ ) { if ( arr[i] != NULL && (*arr[i]).frequency < *secondMin && i != *minIndex ) { *secondMin = (*arr[i]).frequency; *secondMinIndex = i; } } } void interpret(char *str, int *index, tree_node_t *tree) { int n = strlen(str); if ((*tree).c >= 'A' && (*tree).c <= 'Z') { printf("%c ", (*tree).c); return ; } else { if ( *index < n ) { if (str[*index] == '0') { (*index) ++; interpret(str, index, (*tree).left); } else { if (str[*index] == '1') { (*index) ++; interpret(str, index, (*tree).right); } } } } }