language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
#include<stdio.h> #include<stdlib.h> #define MAX_SIZE 1024 #define PUSH(lcs_stack, cur_pos, size,ele) \ do { \ if (cur_pos > size-1) { \ printf("\n Some error occurred \n"); \ exit(0); \ } \ lcs_stack[cur_pos++] = ele; \ }while(0) int main(int argc, char *argv[]) { int arr[MAX_SIZE]; int lcs_arr[MAX_SIZE]; int lcs_arr_end[MAX_SIZE]; int count; int i = 0; int max_lcs_end_here = 0; scanf("%d", &count); for (i = 0; i < count; i++) { scanf("%d", &arr[i]); } printf("\n max_end_here = %d \n", (max_lcs_end_here = find_lcs(arr, lcs_arr, lcs_arr_end, count))); print_arr(lcs_arr_end, count); print_lcs(arr, lcs_arr_end, max_lcs_end_here,count); return 0; } int find_lcs(int arr[], int lcs_arr[], int lcs_arr_end[], int n) { int i = 0; int j = 0; int max_lcs = 0; int max_lcs_end = 0; for(i = 0; i < n; i++) { lcs_arr[i] = 0; lcs_arr_end[i] = 0; } for (i = 0; i < n ; i++) { for (j = 0; j < i ; j++) { if (arr[i] > arr[j]) { if (lcs_arr[i] < (lcs_arr[j] + 1)) { printf("\n i = %d, lcs = %d , new_lcs = %d, new_j = %d", i, lcs_arr[i], lcs_arr[j]+1, j); lcs_arr[i] = lcs_arr[j] + 1; lcs_arr_end[i] = j; } } } if (max_lcs < lcs_arr[i]) { max_lcs = lcs_arr[i]; max_lcs_end = i; //printf("\n max_lcs_end = %d , max_lcs_prev = %d", i, lcs_arr[i]); } } return max_lcs_end; } int print_lcs(int arr[], int lcs_arr[], int max_lcs_end_here, int size) { int lcs_stack[MAX_SIZE]; int ele = 0; int cur_pos_arr = max_lcs_end_here; int cur_pos = 0; int cur_pos_tmp = 0; int loop_end = 0; while(!loop_end) { ele = arr[cur_pos_arr]; PUSH(lcs_stack, cur_pos, size,ele); cur_pos_arr = lcs_arr[cur_pos_arr]; if (cur_pos_arr == 0) { loop_end = 1; } } cur_pos_tmp = cur_pos-1; while(cur_pos_tmp >= 0 ) { printf("\n %d", lcs_stack[cur_pos_tmp--]); } return cur_pos; } int print_arr(int lcs_arr[], int count) { int i =0; for(i = 0; i < count; i++) { printf("\n %d", lcs_arr[i]); } return 0; }
C
/* 1800 - Onde Estão Minhas Chaves > Cassiano Rodrigues > 27/11/2020 */ #include <stdio.h> #include <stdlib.h> #include <string.h> main() { int vetor[1100], i, j, q, e, csi; while (scanf("%d %d", &q, &e) != EOF) { for (i = 0; i < e; i++) { scanf("%d", &csi); vetor[csi] = csi; // Alocar Informações } for (i = 0; i < q; i++) { scanf("%d", &csi); if (csi == vetor[csi]) // Verifica Alocações { printf("0\n"); } else { printf("1\n"); vetor[csi] = csi; } } } system("pause"); }
C
#include<sys/socket.h> void gameHandle(int *clntSock){ int flag[2] = {0,1}; int turn=0; int coord; int isGameset; while(1){ // broadcast turn send(clntSock[turn], &flag[0],4,0); send(clntSock[!turn], &flag[1],4,0); //coordinate 0-> 1 recv(clntSock[turn],&coord,4,0); send(clntSock[!turn],&coord,4,0); // is Game set? recv(clntSock[turn], &isGameset,4,0); if(isGameset) break; // alternative turn turn = !turn; } }
C
#include <stdio.h> #include <string.h> #include <pcre.h> extern int check_ipv4_valid(char *s); //return 0: invalid 1:valid int check_ipv4_valid(char *s) { if (s == NULL || strlen(s) == 0) return -1; pcre *code; int rc; int ovector[2*3]; const char *errptr; const char *ip; int erroffet; char *p; char buf[20]; code = pcre_compile("(\\d{1,3}\\.){3}\\d{1,3}", 0, &errptr, &erroffet, NULL); if((rc = pcre_exec(code,NULL, s, strlen(s), 0, 0, ovector,2*3)) > 0) { pcre_get_substring(s, ovector, rc, 0, &ip); snprintf(buf,20,"%s",ip); pcre_free_substring(ip); for(p = strtok(buf,".");p != NULL;p = strtok(NULL,".")) { if(atoi(p) > 255) goto end; } printf("Correct ip!\n"); return 1; } end:printf("Error ip!\n"); pcre_free(code); return 0; } /*******************************************/ //test /*int main(int argc,char **argv) { //char *s="192.168.1.1"; char sTmp[80] = {0}; char *s = fgets(sTmp, 80, stdin); if (check_ipv4_valid(s)) printf("main Correct ip!.\n"); else printf("main Error ip!.\n"); return 0; }*/ /*******************************************/
C
#include <pebble.h> #include "weekday.h" #include "string.h" const char* WEEKDAY_ES[] = { "Dom", "Lun", "Mar", "Mie", "Jue", "Vie", "Sab", }; const char* WEEKDAY_EN[] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", }; const char* WEEKDAY_DE[] = { "Son", "Mon", "Die", "Mit", "Don", "Fre", "Sam", }; const char* WEEKDAY_FR[] = { "Dim", "Lun", "Mar", "Mer", "Jeu", "Ven", "Sam", }; const char* WEEKDAY_PT[] = { "Dom", "Seg", "Ter", "Qua", "Qui", "Sex", "Sab", }; const char* WEEKDAY_IT[] = { "Dom", "Lun", "Mar", "Mer", "Gio", "Ven", "Sab", };//End_Weekday void fetchwday(int WD, const char* lang, char *iterweekday ){ if (strcmp(lang,"es_ES")==0) {strcpy(iterweekday, WEEKDAY_ES[WD]);} else if (strcmp(lang,"fr_FR")==0) {strcpy(iterweekday, WEEKDAY_FR[WD]);} else if (strcmp(lang,"de_DE")==0) {strcpy(iterweekday, WEEKDAY_DE[WD]);} else if (strcmp(lang,"it_IT")==0) {strcpy(iterweekday, WEEKDAY_IT[WD]);} else if (strcmp(lang,"pt_PT")==0) {strcpy(iterweekday, WEEKDAY_PT[WD]);} else {strcpy(iterweekday, WEEKDAY_EN[WD]);}; }
C
#include<stdio.h> #include<math.h> int main(){ float a, b, c, delta, x1, x2; printf("Valor de a: "); scanf("%f", &a); printf("Valor de b: "); scanf("%f", &b); printf("Valor de c: "); scanf("%f", &c); delta = pow(b,2) - 4*a*c; x1 = (sqrt(delta)-b)/(2*a); x2 = (-sqrt(delta)-b)/(2*a); if(delta < 0) { printf("\nNão existem raizes reais"); } else { printf("\nEquação é: %.2fx² %.2fx %.2f", a, b, c); printf("\nRaiz 1 = %.2f", x1); printf("\nRaiz 2 = %.2f", x2); } return 0; }
C
#include<stdio.h> void main() { int eng, mar, chem, bio, maths; int total_marks; printf("Please Enter Your Marks :\n"); printf("Marks in English outof 100:\n"); scanf("%d",&eng); printf("Marks in Marathi outof 100:\n"); scanf("%d",&mar); printf("Marks in Chemistry outof 100:\n"); scanf("%d",&chem); printf("Marks in Biology outof 100:\n"); scanf("%d",&bio); printf("Marks in Maths outof 100:\n"); scanf("%d",&maths); if(eng >= 35 && mar >= 35 && chem >= 35 && bio >= 35 && maths >= 35) { //passing condition total_marks = eng + mar + chem + bio + maths; switch(1) { case 1: switch(total_marks > 400 && total_marks <= 500) { case 0: break; case 1: printf("Congratulations You got First Class\n"); break; } switch(total_marks >300 && total_marks <= 400) { case 0: break; case 1: printf("Congratulations You got Second Class\n"); break; } break; default: printf("You Passed In Examination..."); break; } }else { printf("You Failed in Exam...\n"); } } /* vivek@vivek-HIRAY:~/Desktop/SwitchAssignment$ cc switchAssign7.c vivek@vivek-HIRAY:~/Desktop/SwitchAssignment$ ./a.out Please Enter Your Marks : Marks in English outof 100: 80 Marks in Marathi outof 100: 80 Marks in Chemistry outof 100: 80 Marks in Biology outof 100: 80 Marks in Maths outof 100: 80 Congratulations You got Second Class vivek@vivek-HIRAY:~/Desktop/SwitchAssignment$ ./a.out Please Enter Your Marks : Marks in English outof 100: 65 Marks in Marathi outof 100: 70 Marks in Chemistry outof 100: 45 Marks in Biology outof 100: 33 Marks in Maths outof 100: 50 You Failed in Exam... vivek@vivek-HIRAY:~/Desktop/SwitchAssignment$ ./a.out Please Enter Your Marks : Marks in English outof 100: 90 Marks in Marathi outof 100: 85 Marks in Chemistry outof 100: 90 Marks in Biology outof 100: 85 Marks in Maths outof 100: 90 Congratulations You got First Class */
C
#include <stdio.h> #include <stdlib.h> #include <time.h> #include "fun.h" void ShellSort(char *aArray, long length) { int g, H = 1; while(H <= length / 3) { H = H * 3 + 1; } while(H > 0) { for(int i = H; i < length; i++) { int tmp = aArray[i]; g = i; while(g > H - 1 && aArray[g - H] >= tmp) { aArray[g] = aArray[g - H]; g = g - H; } aArray[g] = tmp; } H = (H - 1) / 3; } } int binarysearch(char *aArray, long length, char val) { int middle, lower = 0, upper = length - 1; while(lower <= upper) { middle = (lower + upper) / 2; if(aArray[middle] == val) { return 0; } else if(aArray[middle] < val) { lower = middle + 1; } else { upper = middle - 1; } } return -1; } void searchArray(char *aArray, long length) { char val, result; do{ printf("\nEnter value to search: "); scanf("%x", &val); }while(val < 0); printf("Binary search started\n"); clock_t start = clock(); result = binarysearch(aArray, length, val); clock_t end = clock(); float time1 = end - start; printf("Time sorting: %0.10f\n", time1/CLOCKS_PER_SEC); printf("Binary search finished\n"); if(result == 0) { printf("Founded!\n"); } else { printf("Not founded\n"); } } void inPut( long length, char *aArray){ int i = 0; FILE *file = fopen("Tekst_sort.txt","wt"); while(i<length) { putc((int)aArray[i],file); i++; } fclose(file); free(aArray); } void Open(){ FILE *txt_file = fopen("Text.txt", "rt"); if(txt_file == NULL){ printf("No such file found"); exit(0); } else printf("File opened\n"); }
C
#include "mh.h" #include <signal.h> #include <stdio.h> int g_sigint; /* sensed an interrupt */ int g_sig(); char **getans(prompt, ansp) struct swit *ansp; { static char ansbuf[128]; register char *cp, **cpp; register int i; struct swit *ap; signal(SIGINT, g_sig); for(;;) { printf("%s", prompt); fflush(stdout); cp = ansbuf; while((i = getchar()) != '\n') { if(i == EOF || g_sigint) { g_sigint = 0; return(0); } if(cp < &ansbuf[127]) *cp++ = i; } *cp = 0; if(ansbuf[0] == '?' || cp == ansbuf) { printf("Options are:\n"); printsw(ALL, ansp, ""); continue; } cpp = brkstring(ansbuf, " ", 0); switch(smatch(*cpp, ansp)) { case -2:ambigsw(*cpp, ansp); /* ambiguous */ continue; case -1: /* unknown */ printf(" -%s unknown. Hit <CR> for help.\n", *cpp); continue; default: return(cpp); /* list, edit, quit, send */ } } } g_sig() { signal(SIGINT, g_sig); g_sigint = 1; return; }
C
#include <iostream> using namespace std; int main(void) { int arr[6] = { 34, 45, 56, 67, 78, 89 }; for (int i = 0; i < 6; i++) { printf("%d ", arr[i]); } printf("\n"); int A[2][2] = { { 1, 1 }, { 0, 1 } }; int B[2][2] = { { 2, 0 }, { 3, 0 } }; int C[2][2] = { {},{} }; for (int i = 0; i < 2; i++) { for (int j = 0; j < 2; j++) { C[i][j] = 0; for (int k = 0; k < 2; k++) { C[i][j] += A[i][k] * B[k][j]; } } } for (int i = 0; i < 2; i++) { for (int j = 0; j < 2; j++) { printf("%d ", C[i][j]); } printf("\n"); } }
C
#include "mpi.h" #include <stdio.h> #include <stdlib.h> #include <time.h> #include <sys/times.h> #define min(x, y) ((x)<(y)?(x):(y)) double* gen_matrix(int n, int m); int mmult(double *c, double *a, int aRows, int aCols, double *b, int bRows, int bCols); void compare_matrix(double *a, double *b, int nRows, int nCols); /** Program to multiply a matrix times a matrix using both mpi to distribute the computation among nodes and omp to distribute the computation among threads. */ int main(int argc, char* argv[]) { int ans; int i, j, numsent, sender; int anstype, row; int nrows = 5; int ncols = 5; //double *aa = (double*)malloc(sizeof(double) * nrows * ncols); /* the A matrix */ //double *bb; /* the B matrix */ double *buffer1; double *buffer2; double *cc1; /* A x B computed using the omp-mpi code you write */ double *cc2; /* A x B computed using the conventional algorithm */ int myid, master, numprocs; double starttime, endtime; MPI_Status status; /* insert other global variables here */ MPI_Init(&argc, &argv); MPI_Comm_size(MPI_COMM_WORLD, &numprocs); MPI_Comm_rank(MPI_COMM_WORLD, &myid); double aa[25] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25}; double bb[25] = {1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1}; buffer1 = (double*)malloc(sizeof(double) * ncols); buffer2 = (double*)malloc(sizeof(double) * ncols); if (myid == master) { // Master Code goes here starttime = MPI_Wtime(); numsent = 0; MPI_Bcast(bb, ncols, MPI_DOUBLE, master, MPI_COMM_WORLD); for (i = 0; i < min(numprocs-1, nrows); i++) { for (j = 0; j < ncols; j++) { buffer1[j] = aa[i * ncols + j]; } MPI_Send(buffer1, ncols, MPI_DOUBLE, i+1, i+1, MPI_COMM_WORLD); numsent++; } /* Insert your master code here to store the product into cc1 */ for (i = 0; i < nrows; i++) { MPI_Recv(&ans, 1, MPI_DOUBLE, MPI_ANY_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, &status); sender = status.MPI_TAG; anstype = status.MPI_TAG; if (anstype < 25) cc1[anstype-1] = ans; if(numsent < nrows) { for (j = 0; j < ncols; j++) { //buffer1[j] = aa[numsent*ncols + j]; } MPI_Send(buffer1, ncols, MPI_DOUBLE, sender, numsent+1, MPI_COMM_WORLD); numsent++; } else { MPI_Send(MPI_BOTTOM, 0, MPI_DOUBLE, sender, 0, MPI_COMM_WORLD); } } endtime = MPI_Wtime(); printf("%f\n",(endtime - starttime)); //cc2 = malloc(sizeof(double) * nrows * ncols); //mmult(cc2, aa, nrows, ncols, bb, ncols, nrows); //compare_matrices(cc2, cc1, nrows, nrows); } else { // Slave Code goes here MPI_Bcast(bb, ncols, MPI_DOUBLE, master, MPI_COMM_WORLD); if(myid <= nrows) { while(1){ MPI_Recv(buffer1, ncols, MPI_DOUBLE, master, MPI_ANY_TAG, MPI_COMM_WORLD, &status); if (status.MPI_TAG == 0) break; ans = 0; #pragma omp shared(ans) for reduction(+:ans) for (j = 0; j < ncols; j++) { ans += buffer1[j] * bb[5 * j]; } MPI_Send(&ans, 1, MPI_DOUBLE, master, row, MPI_COMM_WORLD); } } else { fprintf(stderr, "Usage matrix_times_vector <size>\n"); } MPI_Finalize(); return 0; } }
C
#include<stdio.h> int main(){ char c='4'; int result = (c =='f') ? 4 : 0; printf("Result is %d\n",result); return 0; }
C
#include <stdio.h> #include <string.h> #include <stdlib.h> #include "spreadsheetintro.h" #include "spreadsheetfunctions.h" void invokeFunctions(int mainchoice, int subchoice) { int val; char arr[100]; switch (mainchoice) { case 1: switch (subchoice) { case 1: printf("Enter the decimal value : "); scanf("%d", &val); dectobin(val); break; case 2: printf("Enter the decimal value : "); scanf("%d", &val); dectooct(val); break; case 3: printf("Enter the decimal value : "); scanf("%d", &val); dectohex(val); break; } break; case 2: switch (subchoice) { case 1: printf("\nPlease Enter the BINARY VALUES :"); gets(arr); printf("\n%d", bintodec(arr,strlen(arr))); break; case 2: printf("\nPlease Enter the BINARY VALUES :"); gets(arr); printf("\n%o", bintodec(arr, strlen(arr))); break; case 3: printf("\nPlease Enter the BINARY VALUES :"); gets(arr); printf("\n%x", bintodec(arr, strlen(arr))); break; } break; case 3: switch (subchoice) { case 1: printf("Enter the Octal value : "); scanf("%o", &val); dectobin(val); break; case 2: printf("Enter the Octal value : "); scanf("%o", &val); printf("\n%d", val); break; case 3: printf("Enter the Octal value : "); scanf("%o", &val); dectohex(val); break; } break; case 4: switch (subchoice) { case 1: printf("Enter the HexaDecimal value : "); scanf("%x", &val); dectobin(val); break; case 2: printf("Enter the HexaDecimal value : "); scanf("%x", &val); printf("\n%o", val); break; case 3: printf("Enter the HexaDecimal value : "); scanf("%x", &val); printf("%d", val); break; } break; } } int main() { int choice=1; while (choice==1) { int mainchoice = MainChoice(); int subchoice = SubChoice(mainchoice); invokeFunctions(mainchoice, subchoice); printf("\nWould you like to continue \n1) Yes\n2) No\n"); scanf("%d", &choice); } return 0; }
C
#include "ad_mik2455_def.h" #define MIK2455_FAST_SWITCH (0) #define MIK2455_CHN_PER_CHIP (4) static unsigned char MIK2455_WRITE(int chip, unsigned char addr, unsigned char data) { gpio_i2c_write(MIK2455_DEV[chip],addr,data); udelay(75); return 0; } static unsigned char MIK2455_READ(int chip, unsigned char addr) { //master slave mode I2C need double read gpio_i2c_read(MIK2455_DEV[chip],addr); udelay(75); return gpio_i2c_read(MIK2455_DEV[chip],addr); } static inline void MIK2455_WRITE_TABLE(unsigned char chip, const unsigned char *tbl_ptr, unsigned char tbl_cnt) { unsigned char i = 0; for(i = 0; i < tbl_cnt; i += 2){ MIK2455_WRITE(chip, *(tbl_ptr + i), *(tbl_ptr + i + 1)); } } static void mik2455_set_hue(int chip, int chn, unsigned char gain) { const unsigned char MAP[] = VIDEO_COLOR_ADJTBL1; if(!(chn < MIK2455_CHN_PER_CHIP)){ return; } if(gain >= sizeof(MAP)/sizeof(MAP[0])){ gain = sizeof(MAP)/sizeof(MAP[0])-1; } MIK2455_WRITE(chip, 0x40, (1 << chn)); MIK2455_WRITE(chip, 0x2c, MAP[gain]); } static void mik2455_set_contrast(int chip, int chn, unsigned char gain) { const unsigned char MAP[] = VIDEO_COLOR_ADJTBL1; if(!(chn < MIK2455_CHN_PER_CHIP)){ return; } if(gain >= sizeof(MAP)/sizeof(MAP[0])) { gain = sizeof(MAP)/sizeof(MAP[0])-1; } MIK2455_WRITE(chip, 0x40, (1 << chn)); MIK2455_WRITE(chip, 0x2e, MAP[gain]); } static void mik2455_set_brightness(int chip, int chn, unsigned char gain) { const unsigned char MAP[] = VIDEO_COLOR_ADJTBL0; if(!(chn < MIK2455_CHN_PER_CHIP)){ return; } if(gain >= sizeof(MAP)/sizeof(MAP[0])) { gain = sizeof(MAP)/sizeof(MAP[0])-1; } MIK2455_WRITE(chip, 0x40, (1 << chn)); MIK2455_WRITE(chip, 0x2f, MAP[gain]); } static void mik2455_set_saturation(int chip, int chn, unsigned char gain) { const unsigned char MAP[] = VIDEO_COLOR_ADJTBL1; if(!(chn < MIK2455_CHN_PER_CHIP)){ return; } if(gain >= sizeof(MAP)/sizeof(MAP[0])) { gain = sizeof(MAP)/sizeof(MAP[0])-1; } MIK2455_WRITE(chip, 0x40, (1 << chn)); MIK2455_WRITE(chip, 0x2d, MAP[gain]); } static int mik2455_set_standard(int chip, const char* std) { if(!strncasecmp(std, "PAL", strlen("PAL"))){ MIK2455_WRITE(chip, 0x40 ,0x0f);//select 4 Channel one time MIK2455_WRITE(chip, 0x10 ,0x40);//force 4 channel to PAL } else if(!strncasecmp(std, "NTSC", strlen("NTSC"))){ MIK2455_WRITE(chip, 0x40 ,0x0f);//select 4 Channel one time MIK2455_WRITE(chip, 0x10 ,0x04);//force 4 channel to PAL } else { printk("MIK2455 not support this video norm : %d\n", chip); return -1; } return 0; } static unsigned int mik2455_get_loss(int chip) { //return 0; int i = 0; unsigned int ret_bit = 0; for(i = 0; i < MIK2455_CHN_PER_CHIP; ++i){ if(MIK2455_READ(chip, 0x51 + i * 0x05)){ ret_bit &= ~(1<<i); }else{ ret_bit |= (1<<i); } } return ret_bit; } static int mik2455_set_mode_4d1(unsigned chip) { // Video Channel Output Control // Four Channel ITU0R BT.656 Time-multiplexed format output MIK2455_WRITE(chip, 0x40, 0x0f); // Output Enable Control and Clock Output Control // 108MHz clock output MIK2455_WRITE(chip, 0x45, 0x02); MIK2455_WRITE(chip, 0x44, 0x03); if (MIK2455_FAST_SWITCH){ MIK2455_WRITE(chip, 0x47, 0x00); }else{ MIK2455_WRITE(chip, 0x47, 0x04); } //printk("mik2455 0x%x set to 4d1 mode ok\n", chip_addr); return 0; } static int mik2455_set_mode_2d1(unsigned chip_addr) { // Video Channel Output Control MIK2455_WRITE(chip_addr, 0x40, 0x0f); // Output Enable Control and Clock Output Control // 54MHz clock output MIK2455_WRITE(chip_addr, 0x45, 0x01); MIK2455_WRITE(chip_addr, 0x44, 0x03); if (MIK2455_FAST_SWITCH){ MIK2455_WRITE(chip_addr, 0x47, 0x00); }else{ MIK2455_WRITE(chip_addr, 0x47, 0x04); } return 0; } static int mik2455_set_audio_samplerate(int chip, audio_samplerate_t samplerate) { int temp, val; // for mik2455 switch (samplerate) { case SAMPLE_RATE_8000: val = 0xc; break; case SAMPLE_RATE_16000: val = 0x8; break; /* case SAMPLE_RATE_24000: val = 0x4; break;*/ case SAMPLE_RATE_48000: val = 0x0; break; default: printk("not support this samplerate:%d \n", samplerate); return -1; } temp = MIK2455_READ(chip, 0xd4); temp &= 0xf3; temp |= val; MIK2455_WRITE(chip, 0xd4, temp); temp = MIK2455_READ(chip, 0xd8); temp &= 0xf3; temp |= val; MIK2455_WRITE(chip, 0xd8, temp); printk("mik2455 audio samplerate set to %d ok\n", val); return 0; } static int mik2455_set_audio_format(int chip, audio_format_t audio_format) { unsigned char temp; /* Define the digital serial audio data format for record and mixing audio on the ACLKR, ASYNR, ADATR and ADATM pin.*/ temp = MIK2455_READ(chip, 0xd4); temp &= 0xfd;/* [1]*/ temp |= (0==audio_format.format) ? 0 : 0x2;/* 0:I2S format 1:DSP format */ MIK2455_WRITE(chip, 0xd4, temp); /* Define the digital serial audio data format for playback audio on the ACLKP, ASYNP and ADATP pin.*/ temp = MIK2455_READ(chip, 0xd8); temp &= 0xfd;/* [1]*/ temp |= (0==audio_format.format) ? 0x0 : 0x2; /* 0:I2S format 1:DSP format */ MIK2455_WRITE(chip, 0xd8, temp); return 0; } static int mik2455_audio_init(int chip) { return 0; } static int mik2455_video_init(int chip, char* std) { return 0; } static unsigned char mik2455_check(int chip) { if(0x45 == MIK2455_READ(chip, 0xb6)) { // add for MIK2455 MIK2455_WRITE(chip, 0x41, 0x03); // for i2c slave device MIK2455_WRITE(chip, 0xa9, 0xC0); //Device address ID is 0xc0 MIK2455_WRITE(chip, 0xab, 0x40); //Not fast I2C speed MIK2455_WRITE(chip, 0x40, 0x0f); if(0x0f != MIK2455_READ(chip, 0x40)) { return 0; } MIK2455_WRITE_TABLE(chip,tbl_mik2455_common,sizeof(tbl_mik2455_common)/sizeof(unsigned char)); mik2455_set_mode_4d1(chip); return 1; } return 0; }
C
float converte_float(const char *str){ float num_float, frac, div_frac; char cop_str[30], separ[2] = ".", *parte; memcpy(cop_str, str, strlen(str)); parte = strtok(cop_str, separ); num_float = atoi(parte); parte = strtok(NULL, separ); if(parte == NULL) parte = "0"; frac = atoi(parte); div_frac = strlen(parte); div_frac = powf(10, div_frac); num_float += (frac / div_frac); return num_float; };
C
#include <stdio.h> int mjir4d_sentence1() { printf("Alas he was now as old as the ancient Linus Torvald.\n"); return 1; } int mjir4d_sentence2() { printf("Thus Agent Buckwald set forth on the great engineering feat that was making a time machine out of a Delorean.\n"); return 1; }
C
// dorm.c #include <GL/glut.h> #include <stdlib.h> #include <stdio.h> #include <jpeglib.h> #include <jerror.h> #define BED 1 // height of 10, 2.5 above, 7.5 below #define CHAIR 2 // height of 9, 4.5 above, 4.5 below #define DESK 3 // height of 11, 1 above origin, 10 below #define LAMP 4 // height of 5, 5 above origin int debug = FALSE; GLuint portrait, portrait2, wall, window, wood, checkerboard; GLfloat position[] = {0.0, 17.0, 0.0, 1.0}; GLuint loadTexJPG(const char * filename) { GLuint texture; GLuint type = GL_RGB; FILE* file = fopen(filename, "rb"); //open the file struct jpeg_decompress_struct info; //the jpeg decompress info struct jpeg_error_mgr err; // error handler info.err = jpeg_std_error(&err); jpeg_create_decompress(&info); //sets info to all the default stuff jpeg_stdio_src(&info, file); //tell the jpeg lib the file we'er reading jpeg_read_header(&info, TRUE); //tell it to start reading it if(debug){printf("Channels: %d\n", info.num_components);} jpeg_start_decompress(&info); //decompress the file unsigned long size = info.output_width * info.output_height * 3; unsigned char * dataBuff = malloc(size); unsigned char ** dataPointer = malloc(sizeof(unsigned char *)); *dataPointer = dataBuff; // while scan lines remain to be read while(info.output_scanline < info.output_height) { jpeg_read_scanlines(&info, dataPointer, 1); *dataPointer = dataBuff + (info.output_scanline * 3 * info.output_width); } jpeg_finish_decompress(&info); //finish decompressing this file fclose(file); //close the file // allocate a texture name glGenTextures(1, &texture); // select current texture glBindTexture(GL_TEXTURE_2D, texture); // mix texture with color for shading glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexImage2D(GL_TEXTURE_2D, 0, type, info.output_width, info.output_height, 0, type, GL_UNSIGNED_BYTE, dataBuff); if(debug) { unsigned char * address = dataBuff; int counter; while(address < dataBuff + size) { counter++; printf("R: %d, G: %d, B: %d\n", *address, *(address+1), *(address+2)); address += 3; } printf("Pixels: %d\n", counter); } return texture; } void myInit() { glClearColor(0.5, 0.5, 0.5, 1.0); glDepthFunc(GL_LEQUAL); glEnable(GL_DEPTH_TEST); GLfloat global_ambient[] = {0.3, 0.3, 0.3, 1.0}; GLfloat specular[] = {0.8, 0.8, 0.8, 1.0}; GLfloat diffuse[] = {0.7, 0.7, 0.7, 1.0}; glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); glLightModelfv(GL_LIGHT_MODEL_AMBIENT, global_ambient); glShadeModel(GL_SMOOTH); glLightfv(GL_LIGHT0, GL_DIFFUSE, diffuse); glLightfv(GL_LIGHT0, GL_SPECULAR, specular); glLightfv(GL_LIGHT0, GL_POSITION, position); glColorMaterial(GL_FRONT, GL_AMBIENT_AND_DIFFUSE); glEnable(GL_COLOR_MATERIAL); portrait = loadTexJPG("portrait.jpg"); portrait2 = loadTexJPG("portrait2.jpg"); wall = loadTexJPG("wall.jpg"); wood = loadTexJPG("wood.jpg"); window = loadTexJPG("window.jpg"); checkerboard = loadTexJPG("checkerboard.jpg"); glEnable(GL_TEXTURE_2D); } void displayRoom() { // floor glColor3f(0.6, 0.12, 0.12); glPushMatrix(); glTranslatef(0.0, -1.0, 0.0); glScalef(1.0, 0.05, 1.0); glutSolidCube(40); glPopMatrix(); // floor glBegin(GL_QUADS); glBindTexture(GL_TEXTURE_2D, wood); glTexCoord2d(1, 0);glVertex3d(20, 0, 20); glTexCoord2d(0, 0);glVertex3d(20, 0, -20); glTexCoord2d(0, 1);glVertex3d(-20, 0, -20); glTexCoord2d(1, 1);glVertex3d(-20, 0, 20); glEnd(); glBindTexture(GL_TEXTURE_2D, 0); // left wall glColor3f(0.5, 0.5, 0.5); glPushMatrix(); glTranslatef(-21.0, 10.0, 0.0); glScalef(0.05, 0.5, 1.0); glutSolidCube(40); glPopMatrix(); // right wall glPushMatrix(); glTranslatef(21.0, 10.0, 0.0); glScalef(0.05, 0.5, 1.0); glutSolidCube(40); glPopMatrix(); // back wall glPushMatrix(); glTranslatef(0.0, 10.0, -21.0); glScalef(1.0, 0.5, 0.05); glutSolidCube(40); glPopMatrix(); // checkerboard back wall glBindTexture(GL_TEXTURE_2D, checkerboard); glBegin(GL_QUADS); glTexCoord2d(1, 0);glVertex3d(20, 20, -20); glTexCoord2d(0, 0);glVertex3d(-20, 20, -20); glTexCoord2d(0, 1);glVertex3d(-20, 0, -20); glTexCoord2d(1, 1);glVertex3d(20, 0, -20); glEnd(); // left wall glBindTexture(GL_TEXTURE_2D, wall); glBegin(GL_QUADS); glTexCoord2d(1, 0);glVertex3d(-20, 20, -20); glTexCoord2d(0, 0);glVertex3d(-20, 20, 20); glTexCoord2d(0, 1);glVertex3d(-20, 0, 20); glTexCoord2d(1, 1);glVertex3d(-20, 0, -20); glEnd(); // right wall glBegin(GL_QUADS); glTexCoord2d(1, 0);glVertex3d(20, 20, 20); glTexCoord2d(0, 0);glVertex3d(20, 20, -20); glTexCoord2d(0, 1);glVertex3d(20, 0, -20); glTexCoord2d(1, 1);glVertex3d(20, 0, 20); glEnd(); // ceiling glColor3f(0.4, 0.4, 0.4); glPushMatrix(); glTranslatef(0.0, 21.0, 0.0); glScalef(1.0, 0.05, 1.0); glutSolidCube(40); glPopMatrix(); // right wall glBegin(GL_QUADS); glTexCoord2d(1, 0);glVertex3d(20, 20, 20); glTexCoord2d(0, 0);glVertex3d(20, 20, -20); glTexCoord2d(0, 1);glVertex3d(-20, 20, -20); glTexCoord2d(1, 1);glVertex3d(-20, 20, 20); glEnd(); glBindTexture(GL_TEXTURE_2D, 0); } void display() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glLoadIdentity(); displayRoom(); glPushMatrix(); glTranslatef(-10.0, 10, -17.5); glCallList(DESK); glPopMatrix(); glPushMatrix(); glTranslatef(10.0, 10, -17.5); glCallList(DESK); glPopMatrix(); glPushMatrix(); glColor3f(0, 0.4, 0); glTranslatef(-15, 7.5, 7.5); glRotatef(90, 0, 1, 0); glCallList(BED); glPopMatrix(); glPushMatrix(); glColor3f(0, 0, 0.4); glTranslatef(15, 7.5, 7.5); glRotatef(90, 0, 1, 0); glCallList(BED); glPopMatrix(); glPushMatrix(); glTranslatef(5, 4.5, 0); glRotatef(-45, 0, 1, 0); glCallList(CHAIR); glPopMatrix(); glPushMatrix(); glTranslatef(-5, 4.5, 10); glRotatef(0, 0, 1, 0); glCallList(CHAIR); glPopMatrix(); glPushMatrix(); glTranslatef(-5, 11, -17); glCallList(LAMP); glPopMatrix(); glPushMatrix(); glTranslatef(15, 11, -17); glCallList(LAMP); glPopMatrix(); // draw a box for ceiling light glPushMatrix(); glColor3f(1, 1, 0); glTranslatef(position[0], position[1] + 3.5, position[2]); glScalef(3.0, 1.0, 6.0); glutSolidCube(1); glPopMatrix(); // portrait on left wall (Joel) glColor3f(0.8, 0.8, 0.8); glBindTexture(GL_TEXTURE_2D, portrait); glBegin(GL_QUADS); glTexCoord2d(1, 0);glVertex3d(-19.9, 17.5, -5); glTexCoord2d(0, 0);glVertex3d(-19.9, 17.5, 0); glTexCoord2d(0, 1);glVertex3d(-19.9, 12.5, 0); glTexCoord2d(1, 1);glVertex3d(-19.9, 12.5, -5); glEnd(); // portrait on right wall (Caleb) glBindTexture(GL_TEXTURE_2D, portrait2); glBegin(GL_QUADS); glTexCoord2d(1, 0);glVertex3d(20, 17.5, -5); glTexCoord2d(0, 0);glVertex3d(20, 17.5, 0); glTexCoord2d(0, 1);glVertex3d(20, 12.5, 0); glTexCoord2d(1, 1);glVertex3d(20, 12.5, -5); glEnd(); glBindTexture(GL_TEXTURE_2D, 0); glFlush(); glutSwapBuffers(); } void myReshape(int w, int h) { glViewport(0, 0, w, h); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(90.0, (GLfloat) w / (GLfloat) h, 1.0, 100.0); gluLookAt(0.0, 15.0, 25.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); } void defineDisplayLists() { GLuint myIndex = glGenLists(3); ///////////////////////// DEFINE A STANDARD BED ///////////////////////// glNewList(myIndex, GL_COMPILE); // Matress glPushMatrix(); glScalef(1.0, 0.15, 0.5); glutSolidCube(20); glPopMatrix(); // One End glColor3f(0.42, 0.28, 0.22); glPushMatrix(); glTranslatef(10.5, -2.5, 0.0); glScalef(0.1, 1.0, 1.0); glutSolidCube(10); glPopMatrix(); // Other End glPushMatrix(); glTranslatef(-10.5, -2.5, 0.0); glScalef(0.1, 1.0, 1.0); glutSolidCube(10); glPopMatrix(); glEndList(); /////////////////////// DEFINE A STANDARD CHAIR ///////////////////// glNewList(myIndex+1, GL_COMPILE); // Chair seat glColor3f(0.3, 1.0, 0.3); glPushMatrix(); glScalef(1.0, 0.25, 1.0); glutSolidCube(4); glPopMatrix(); // Chair back glColor3f(0.42, 0.28, 0.22); glPushMatrix(); glTranslatef(-1.825, 2.5, 0.0); glScalef(0.125, 1.0, 1.0); glutSolidCube(4); glPopMatrix(); // leg 1 glPushMatrix(); glTranslatef(1.875, -2.5, 1.875); glScalef(.125, 1.0, .125); glutSolidCube(4); glPopMatrix(); // leg 2 glPushMatrix(); glTranslatef(-1.875, -2.5, 1.875); glScalef(.125, 1.0, .125); glutSolidCube(4); glPopMatrix(); // leg 3 glPushMatrix(); glTranslatef(1.875, -2.5, -1.875); glScalef(.125, 1.0, .125); glutSolidCube(4); glPopMatrix(); // leg 4 glPushMatrix(); glTranslatef(-1.875, -2.5, -1.875); glScalef(.125, 1.0, .125); glutSolidCube(4); glPopMatrix(); glEndList(); ///////////////////////// DEFINE A STANDARD DESK /////////////////////////// glNewList(myIndex+2, GL_COMPILE); //Desk top glColor3f(0.42, 0.28, 0.22); glPushMatrix(); glScalef(1.0, 0.1, 0.5); glutSolidCube(20); glPopMatrix(); // Desk large side glPushMatrix(); glTranslatef(5.5, -5.5, 0.0); glScalef(0.45, 0.45, 0.5); glutSolidCube(20); glPopMatrix(); // Desk top drawer glPushMatrix(); glTranslatef(5.5, -3.5, 5.125); glScalef(7.0, 3.0, 0.25); glutSolidCube(1); glPopMatrix(); // Desk bottom drawer glPushMatrix(); glTranslatef(5.5, -7.5, 5.125); glScalef(7.0, 3.0, 0.25); glutSolidCube(1); glPopMatrix(); // Desk small side glPushMatrix(); glTranslatef(-9.5, -5.5, 0.0); glScalef(0.05, 0.45, 0.5); glutSolidCube(20); glPopMatrix(); glEndList(); //////////////////////// DEFINE A STANDARD LAMP ///////////////////////////// glNewList(myIndex+3, GL_COMPILE); // base of lamp glColor3f(0.38, 0.68, 0.1); glPushMatrix(); glTranslatef(0.0, 1.5, 0.0); glScalef(1.0, 3.0, 1.0); glutSolidCube(1); glPopMatrix(); // lamp top glColor3f(0.95, 0.95, 0.31); glPushMatrix(); glTranslatef(0.0, 2.5, 0.0); glutSolidSphere(1, 100, 100); glPopMatrix(); glEndList(); glListBase(myIndex); } void main(int argc, char **argv) { glutInit(&argc, argv); glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH); glutInitWindowSize(500, 500); glutInitWindowPosition(0, 0); glutCreateWindow("Dorm"); myInit(); glutReshapeFunc(myReshape); glutDisplayFunc(display); defineDisplayLists(); glutMainLoop(); }
C
#include <stdio.h> #define PI 3.14 // ޸𸮰 int main() { //const /* double pi = 3.14; pi = 4.14; int aaa = 1; int bbb = 2; //const int* p = NULL; //*p //int* const p = NULL; //p const int* const p = NULL; //Ѵ p = &aaa; printf("1.pǰ : %d\n", *p); //1 aaa = 100; printf("2.pǰ : %d\n", *p); //100 *p = 1000; // printf("3.pǰ : %d\n", *p); //1000 p = &bbb; printf("4.pǰ : %d\n", *p); //100 return 0; */ int a[3]; // --> a[2]== *a(a+2) int arr[2][3] = { 10,20,30,40,50,60 }; //->arr[1][2],*(*(arr+1)+2),*(arr[1])+2) printf("arr :%d\n", sizeof(arr)); //24B int* ptr0; printf("ptr0 :%d\n", sizeof(ptr0)); //4B ptr0 = arr; printf("1.:%d ,ּ:%d\n", *ptr0, ptr0); //10 ptr0++; printf("2.:%d ,ּ:%d\n", *ptr0, ptr0);//20 ,4B ptr0++; printf("3.:%d ,ּ:%d\n", *ptr0, ptr0); //30,4B ptr0++; printf("4.:%d ,ּ:%d\n", *ptr0, ptr0);//40, 4B int* ptr1[3]; // 迭 printf("ptr1 :%d\n", sizeof(ptr1)); //12B ptr1[1] = arr; printf("11.:%d ,ּ:%d\n", **(ptr1 + 1), *(ptr1 + 1)); // 10 printf("12.:%d ,ּ:%d\n", *(ptr1[1] + 1), ptr1[1]); // 10 int(*ptr2)[3]; printf("ptr2 :%d\n", sizeof(ptr2)); //4B ptr2 = arr; printf("11.:%d ,ּ:%d\n", **ptr2, *ptr2); // 10 ptr2 = ptr2 + 1; printf("12.:%d ,ּ:%d\n", **ptr2, *ptr2); // 40, 12B ptr2 = arr; printf("%d\n", ptr2[0]); //ּ printf("%d\n", ptr2[1]); //ּ printf("%d\n", ptr2[0][0]); //(10) printf("%d\n", ptr2[1][0]); //(40) return 0; }
C
#include <stdio.h> #include <stdlib.h> #define dimN 16 #define dimM 8 #define ELEM(Mat,i,j) Mat[i*dimN+j] #define PRINTMAT(MAT) \ do { \ printf("Stampo la matrice %s:\n", #MAT); \ for(size_t i=0;i<dimN;++i) { \ for(size_t j=0;j<dimM;++j) \ printf("%4ld ", ELEM(MAT,i,j)); \ printf("\n"); \ } \ }while(0) int main(int argc, char *argv[]) { long *M = malloc(dimN*dimM*sizeof(long)); for(size_t i=0;i<dimN;++i) for(size_t j=0;j<dimM;++j) ELEM(M,i,j) = i+j; PRINTMAT(M); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> struct NO{ int info; int altura; struct NO *esq; struct NO *dir; }; typedef struct NO* ArvAVL; int nivelBuscaAVL=0; int altura_NO(struct NO* no){ if(no == NULL) return -1; else return no->altura; } int fatorBalanceamento_NO(struct NO* no){ return labs(altura_NO(no->esq) - altura_NO(no->dir)); } int maior(int x, int y){ if(x > y) return x; else return y; } void rotacaoLL(ArvAVL *raiz){ struct NO *no; no = (*raiz)->esq; (*raiz)->esq = no->dir; no->dir = (*raiz); (*raiz)->altura = maior(altura_NO((*raiz)->esq), altura_NO((*raiz)->dir)) + 1; no->altura = maior(altura_NO(no->esq),(*raiz)->altura) +1; *raiz = no; } void rotacaoRR(ArvAVL *raiz){ struct NO *no; no = (*raiz)->dir; (*raiz)->dir = no->esq; no->esq = (*raiz); (*raiz)->altura = maior(altura_NO((*raiz)->esq), altura_NO((*raiz)->dir)) +1; no->altura = maior(altura_NO(no->dir), (*raiz)->altura) +1; (*raiz) = no; } void rotacaoRL(ArvAVL *raiz){ rotacaoRR(&(*raiz)->esq); rotacaoLL(raiz); } void rotacaoLR(ArvAVL *raiz){ rotacaoLL(&(*raiz)->dir); rotacaoRR(raiz); } ArvAVL insere_ArvAVL(ArvAVL *raiz, int valor){ if(*raiz == NULL){ struct NO *raiz; raiz = (struct NO*)malloc(sizeof(struct NO)); raiz->info = valor; raiz->altura = 0; raiz->esq = NULL; raiz->dir = NULL; return raiz; } struct NO *atual = *raiz; if(valor < atual->info){ atual->esq = insere_ArvAVL(&atual->esq,valor); if(fatorBalanceamento_NO(atual) >= 2){ if(valor < (*raiz)->esq->info){ rotacaoLL(raiz); }else{ rotacaoLR(raiz); } } } else{ if(valor > atual->info){ atual->dir = insere_ArvAVL(&atual->dir,valor); if(fatorBalanceamento_NO(atual) >=2){ if((*raiz)->dir->info < valor){ rotacaoRR(raiz); } else{ rotacaoRL(raiz); } } } } atual->altura = maior(altura_NO(atual->esq), altura_NO(atual->dir) + 1); return *raiz; } ArvAVL procurarAVL (ArvAVL raiz, int info){ puts("Entrada AVL"); if (!raiz){ puts("Entrada AVL"); FILE *arq; char infotexto[100]; char name[10]; sprintf(name, "%d", info); arq = fopen(strcat(name,".txt"), "r"); while( (fgets(infotexto, sizeof(infotexto), arq)!=NULL)){ printf("%s",infotexto); } fclose(arq); printf("%d",nivelBuscaAVL); nivelBuscaAVL=0; return NULL; } if (info > raiz->info){ puts("Primeira entrada"); nivelBuscaAVL++; return procurarAVL(raiz->dir, info); } else{ nivelBuscaAVL++; return procurarAVL (raiz->esq, info); } return NULL; } /* main(){ ArvAVL* raiz; int acao, num, x; char continua, s, n; while(continua == s){ puts("Escolha a acao:"); puts("1 - Inserir na arvore"); puts("2 - realizar busca"); puts("3 - sair"); scanf("%d", &acao); switch(acao){ case 1: puts("Valor a ser inserido:"); scanf("%d", &num); x = insere_ArvAVL(raiz, num); if(x == 1){ puts("Inserção realizada com sucesso"); } break; case 2: case 3: continua = n; break; } } } */
C
/* * This is a driver to test pass1 and the Label Table functions. * * Author: Alyce Brady * Date: 2/18/99 * Modified by: Caitlin Braun and Giancarlo Anemone to test pass2 of the assembler. */ #include <stdio.h> #include <string.h> #include "LabelTable.h" LabelTable pass1 (char * filename); LabelTable pass2 (char * filename, LabelTable table); int main () { LabelTable table; int i; table = pass1 ("testfile.txt"); (void)pass2("testfile.txt", table); //printLabels (&table); return 0; }
C
#include <stdio.h> #define MAX 20 int search(char t[][20], int i, int j, int l, int w, int c) { if(i >= 0 && i < l && j >=0 && j < w && t[i][j] == '.') { t[i][j] = '#'; c++; } else return c; c = search(t, i-1, j, l, w, c); c = search(t, i, j-1, l, w, c); c = search(t, i+1, j, l, w, c); c = search(t, i, j+1, l, w, c); return c; } int main() { char tile[MAX][MAX]; int i, j, x, y, len, wid, count; while(1) { count = 0; scanf("\n%d%d", &wid, &len); if(len == 0) break; for(i = 0; i < len; i++) { getchar(); for(j = 0; j < wid; j++) { scanf("%c", &tile[i][j]); if(tile[i][j] == '@') { x = i; y = j; tile[i][j] = '.'; } } } count = search(tile, x, y, len, wid, count); printf("%d\n", count); } return 0; }
C
#include<stdio.h> #include<stdlib.h> int main() { int r1,r2,c1,c2; int i,j,k,p; int md; char go; //========frist Matrices input========= printf("First Matrices Rows: "); scanf("%d",&r1); printf("First Matrices Colloms: "); scanf("%d",&c1); float arr1[r1][c1]; printf("Enter first Matrices\n"); for(i=0;i<r1;i++){ for(j=0;j<c1;j++){ scanf("%f",&arr1[i][j]); } } //========second Matrices input========= printf("\nSecod Matrices Row: "); scanf("%d",&r2); printf("Second Matrices Collom: "); scanf("%d",&c2); float arr2[r2][c2]; printf("Enter Second Matrices\n"); for(i=0;i<r2;i++){ for(j=0;j<c2;j++){ scanf("%f",&arr2[i][j]); } } printf("\n\n"); //first Matrices printing printf("First Matrices\n"); for(i=0;i<r1;i++){ for(j=0;j<c1;j++){ printf("%.0f ",arr1[i][j]); } printf("\n"); } printf("\n"); //second Matrices printing printf("Second Matrices\n"); for(i=0;i<r2;i++){ for(j=0;j<c2;j++){ printf("%.0f ",arr2[i][j]); } printf("\n"); } while (1) { //calculator menu printf("\n---------------------------"); printf("\n 1. Matrices multification\n"); printf(" 2. Matrices Divide\n"); printf(" 3. Matrices sum\n"); printf(" 4. Matrices subtract\n"); printf(" 5. All\n"); printf(" 6. EXIT\n"); printf("\nWhat do you want?: "); scanf("%d",&md); switch (md) { case 5: { case 1: { //Matrices multification logic float mularr[r1][c2],mul; for(i=0;i<r1;i++){ for(j=0;j<c2;j++){ mul=0; for(k=0;k<c1;k++){ mul=mul+(arr1[i][k]*arr2[k][j]); } mularr[i][j]=mul; } } printf("\nMatrices Multification\n"); //printing output for(i=0;i<r1;i++){ for(j=0;j<c2;j++){ printf("%.0f ",mularr[i][j]); } printf("\n"); } } if(md!=5){ break; } case 2: { //Matrices Divide logic float div,divarr[r1][c2]; for(i=0;i<r1;i++){ for(j=0;j<c2;j++){ div=0; for(p=0;p<c1;p++){ div=div+(float)(arr1[i][p]/arr2[p][j]); } divarr[i][j]=div; } } printf("\nMatrices Divide\n"); for(i=0;i<r1;i++){ for(j=0;j<c2;j++){ printf("%.1f ",divarr[i][j]); } printf("\n"); } }if(md!=5){ break; } //Matrices sum logic case 3: { printf("\nMatrices Sum\n"); int sum[r1][c1]; for(i=0;i<r1;i++){ for(j=0;j<c1;j++){ sum[i][j]=(arr1[i][j]+arr2[i][j]); printf("%d ",sum[i][j]); } printf("\n"); } }if(md!=5){ break; } case 4: { // Matrices sumbtract logic printf("\nMatrices subtract\n"); int sub[r1][c1]; for(i=0;i<r1;i++){ for(j=0;j<c1;j++){ sub[i][j]=(arr1[i][j]-arr2[i][j]); printf("%d ",sub[i][j]); } printf("\n"); } }if(md!=5){ break; } case 6: { if(md==6){ system("cls"); printf("\n\tHave a nice Day!\n\n"); exit(0); } }break; default : if(md!=6) printf("Invalide Option"); }break; } //loop continue or exit printf("\nAnother calculation is required?(Y/N): "); scanf("%s",&go); if(go=='y') { printf("---------------------------------\n"); break; } } }
C
#include<stdio.h> int main() { int i,j,n,temp; int arr[1000]; printf("Enter array size : "); scanf("%d",&n); printf("Enter array elements : \n"); for(i=0;i<n;i++) { scanf("%d",&arr[i]); } printf("Before sorting : \n"); for(i=0;i<n;i++) { printf("%d\t",arr[i]); } printf("\n"); for(i=1;i<n;i++) { temp=arr[i]; for(j=i;j>0 && temp<arr[j-1];j--) { arr[j]=arr[j-1]; } arr[j]=temp; } printf("After sorting : \n"); for(i=0;i<n;i++) { printf("%d\t",arr[i]); } printf("\n"); return 0; }
C
#include<stdio.h> #include<string.h> #include<ctype.h> void push(char ele,char s[100],int *t); char pop(char s[100],int *t); int is_operator(char e); int precedence(char e); int main() { char stack[100],infix[100],postfix[100],x; int i=0,j=0,top=-1; printf("enter infix exp\n"); scanf("%s",infix); while(infix[i]!='\0') { if(infix[i]=='(') { push(infix[i],stack,&top); } else if(infix[i]==')') { x=pop(stack,&top); while(x!='(') { postfix[j]=x; j++; x=pop(stack,&top); } } else if(isdigit(infix[i])||isalpha(infix[i])) { postfix[j]=infix[i]; j++; } else if(is_operator(infix[i])==1) { x=infix[i]; while(top!=-1&&precedence(x)<precedence(stack[top])) { postfix[j]=pop(stack,&top); j++; } push(infix[i],stack,&top); } else { printf("Invalid input\n"); } i++; } while(top!=-1) { x=pop(stack,&top); postfix[j]=x; j++; } postfix[j]='\0'; printf("enter postfix exp\n"); puts(postfix); return 0; } void push(char ele,char s[100],int *t) { if(*t<99) { *t=*t+1; s[*t]=ele; } } char pop(char s[100],int *t) { char item; if(*t>-1) { item=s[*t]; *t=*t-1; return item; } } int is_operator(char e) { if(e=='*'||e=='/'||e=='+'||e=='-'||e=='^') { return 1; } else { return 0; } } int precedence(char e) { if(e=='^') return 3; else if(e=='*'||e=='/') return 2; else if(e=='+'||e=='-') return 1; else return 0; }
C
/* * File: termometro.c * Author: USER * * Created on 11 de octubre de 2020, 01:35 PM */ #include <xc.h> #include<stdio.h> #include "config.h" #define _XTAL_FREQ 4000000 #include "LCD.h" #pragma config PLLDIV=1 float volt,temp,tempK,tempF; int adc; char str[20]; void configurar_puertos(void) { //Configuracin puerto A como entrada TRISA=1; //Configuracin puertos E, D, C como salidas TRISE=0; TRISC=0; // Inicializar puertos en 0 PORTE=0; PORTC=0; } void configurar_ADCON (void) { //configuracion 5v como voltaje de referencia ADCON1bits.VCFG0=0; ADCON1bits.VCFG1=0; //Configuracion de entradas analogicas ADCON1bits.PCFG=0b0011; //seleccion de canal AN0 ADCON0bits.CHS0=0; //configuracin de tiempo de adquisicin ADCON2bits.ACQT=2; ADCON2bits.ADCS=4; ADCON2bits.ADFM=1; //iniciar el conversor ADCON0bits.ADON=1; } void configurar_interrupcion (void) { INTCONbits.GIE=0;//desctivar interrupciones globales T0CONbits.T0SE=1; //configurar conteo de reloj T0CKI T0CONbits.T0CS=1;//timer como contador T0CONbits.PSA=1;//deshabilitar prescaler T0CONbits.T08BIT=0;//16 bits para contar T0CONbits.TMR0ON=1;//encendet tmr INTCONbits.TMR0IE=1;//permitir interrupcion por desbordamiento INTCONbits.TMR0IF=0;//bandera en 0 INTCONbits.PEIE=1;//permitir interrupcion de perisferico INTCONbits.GIE=1;//activar interrupciones globales } void main(void) { configurar_puertos(); configurar_ADCON(); configurar_interrupcion (); while(1) { LATD=0x01; ADCON0bits.GO_DONE=1; while(ADCON0bits.GO_DONE==1); adc=ADRESH<<8; adc=adc+ADRESL; volt=adc; volt=(adc*5.0)/1023.0;//conversin BCD temp=volt*100; // ya que la sencibilidad del lm35 es de 10mv/c if(TMR0==0) { sprintf(str,"%2.2f c",temp); lcd_init();//inicializar led lcd_print("la temperatura"); lcd_print_with_position(1,2,"es:"); lcd_print_with_position(6,2,str); } if(TMR0==1) { tempK=(temp+273.15); sprintf(str,"%2.2f k",tempK); lcd_print_with_position(1,2,"es:"); lcd_print_with_position(6,2,str); __delay_ms(100); } if(TMR0==2) { tempF=((temp*9/5)+32); sprintf(str,"%2.2f F",tempF); lcd_print_with_position(1,2,"es:"); lcd_print_with_position(6,2,str); __delay_ms(100); } } return; }
C
#define _CRT_SECURE_NO_WARNINGS #include<stdio.h> #include<string.h> #include<stdlib.h> #include<ctype.h> void* my_memcpy(void* dest, const void* src, int num) { char* p1 = (char*)dest; const char* p2 = (char*)src; while (num--) { *p1++ = *p2++; } return dest; } void test1() { int arr1[] = { 1, 2, 3,4, 5,6,7,8,9,10 }; int arr2[10]; my_memcpy(arr2, arr1, 20); } int main() { //char c = '2'; //printf("%d\n",isdigit(c)); //char arr[10]; //for (int i = 0; i < 10; i++) //{ // scanf("%c", &arr[i]); // if (islower(arr[i])) // arr[i] = toupper(arr[i]); // printf("%c ", arr[i]); //} test1(); return 0; }
C
#include <stdio.h> int main(){ int a, b; int *p; a=10; p=&a; b=20; printf("Zmienna p (wskazuje adres a): %d \n", p); *p=b; printf("Zmienna p (wskazuje adres a): %d \n", p); printf("Wartosc zmiennej p po '*p=b': %d \n", p); printf("Wartosc zmiennej p po '*p=b': %d \n", *p); printf("\nWartosc zmiennej a po '*p=b': %d \n", a); }
C
#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <stdlib.h> #include <string.h> typedef enum { False, True } Boolean; typedef struct dish { char* name; int price; int quantity; int startQuantity; char premium; struct dish* next; } dish; typedef struct dishes { dish* head; dish* tail; }dishes; typedef struct TableOrders { int sum; int numberOfPremium; Boolean isTaken; struct dishesOrdered* theDishesThatOrdered; }TableOrders; typedef struct dishesOrdered { char* dishName; int amount; // how many ordered from this dish struct dishesOrdered* next; struct dishesOrdered* prev; }dishesOrdered; Boolean readDishes(dishes* dishesManager, FILE* dishesF); Boolean printDishes(dishes* dishesManager); dish* findDish(dishes* dishesManager, char* nameOfDish); Boolean addItemsToTheKitchen(dishes* dishesManager, char* productName, int quantity); dish* parameterIntegrityCheck(dishes* dishesManager, int TableNumber, char* ProductName, int Quantity, int numberOfTables); Boolean makeOrder(dishes* dishesManager, TableOrders* tableOrders, int TableNumber, char* ProductName, int Quantity, int numberOfTables); Boolean cancelOrder(dishes* dishesManager, TableOrders* tableOrders, int TableNumber, char* ProductName, int Quantity, int numberOfTables); Boolean removeTable(TableOrders* tableOrders, int TableNumber); Boolean printTableDishes(TableOrders* tableOrders, int TableNumber, int closeTable); Boolean showReport(dishes* dishesManager, TableOrders* tableOrders, char para, char* ProductName, int tableNumber); void Error_Msg(char* msg);
C
/* comment 1 with a '/' inside it */ #include <stdio.h> // for using printf and scanf */ /* a comment occupying separate lines */ int main(){ // hello how are you? (a single line comment) int a, b; /* declaring two variables for storing user input */ printf("Enter two numbers for addition: "); /* prompt user for input */ // /* a /* complex */ comment */ scanf("%d %d", &a, &b); /* read the user input */ printf("The result of addition is: %d\n", a + b); /* compute and print the result */ return 0; /* another test comment * hi * hi */ }
C
//----------------------------------------------------------------------------- // DictionaryTest.c // Pattawut Manapongpun // pmanapon // CMPS-12M // Date: 2-20-2018 // Tests Dictionary ADT. //----------------------------------------------------------------------------- #include<stdio.h> #include<stdlib.h> #include<string.h> #include"Dictionary.h" int main(int argc, char* argv[]){ Dictionary A = newDictionary(); printf("%s\n", (isEmpty(A)?"true":"false")); insert(A,"1","one"); insert(A,"2","two"); insert(A,"3","three"); printf("%s\n", (isEmpty(A)?"true":"false")); printDictionary(stdout, A); delete(A,"1"); delete(A,"3"); printDictionary(stdout, A); // delete(A,"5"); // error insert(A,"5","five"); delete(A,"2"); printf("%s\n", (isEmpty(A)?"true":"false")); printDictionary(stdout, A); insert(A,"10","ten"); printDictionary(stdout, A); freeDictionary(&A); //printDictionary(stdout, A); //error //insert(A,"1","one"); //error Dictionary B = newDictionary(); printf("%s\n", (isEmpty(B)?"true":"false")); insert(B,"1","one"); insert(B,"2","two"); insert(B,"3","three"); printf("%s\n", (isEmpty(B)?"true":"false")); printDictionary(stdout, B); makeEmpty(B); printf("%s\n", (isEmpty(B)?"true":"false")); //prints true; freeDictionary(&B); return(EXIT_SUCCESS); }
C
#include <stdio.h> // INtegral DUplo #include <math.h> double function(double x, double y) { return sin(x+y); } double int_duplo(double a, double b, double A, double B, int n_int) { double S0=0, S1=0, S2=0, sum=0; double hx = (A-a)/n_int; double hy = (B-b)/n_int; double x1=a, y1=b, i=0; //pontos dos vertices do retangulo de lados A-a E b-B //S0 = soma dos valores nos vertices da malha, S0=function(a, b) + 4*function(a, B)+ function(A, b)+ function(A, B); for(x1 = a; x1 < A; x1 = x1 + i*hx ){ for(y1=b; y1<B; y1=x1+i*hx){ S1+=function(x1,b)+4*function(a,y1)+function(A, y1)+function(x1,B);//S1 = (..) nos pontos medios dos lados da malha S2+=function(x1,y1); //calcula valores de f no centro da malha i++; } } sum = (hx*hy/9) * (S0+4*S1+16*S2) ; printf("sum = %f\n", sum); return sum; } int main() { double x0 = 0, xn = M_PI; double y0=0, yn=M_PI; double S=0, S1=0, S2=0; int n=10; int_duplo(x0, y0, xn, yn, n); }
C
#include <stdio.h> int main5(){ char a; int b; float f; double d; a=7; b=-13; f=0.1; d=42.5; printf("nombre: %c,\t direccion:%p, \tvalor:%d\n",'a',&a,a); return 0; }
C
#include "../../ft_putchar.c" #include <stdio.h> int sum(int lower, int upper) { int total; total = 0; while (lower < upper) { total += lower; lower += 1; } return (total); } int total_lines (int total_levels) { return sum(3, total_levels + 3); } int lines_in_level (int level) { return level + 3; } int lines_above_level (int level) { return sum(3, 3 + level); } int lines_below_level (int level, int total_levels) { return total_lines(total_levels) - lines_in_level(level) - lines_above_level(level); } int shifting_level (int level) { return level / 2 + level % 2 + 1; } int shifting_level_sum(int level) { int i; int sum; i = 0; sum = 0; while (i < level) { sum += shifting_level(i); i++; } printf("shifting_level_sum(%d): %d\n", level, sum); return sum; } int spaces_in_line (int total_levels, int level, int line) { int a = lines_below_level(level, total_levels); // slope below level int b = lines_in_level(level) - 1 - line; // slope within level int c = 3 * (total_levels - level - 1); // level shifting return a + b + c; } int stars_in_line (int level, int line) { int a = lines_above_level(level); // slope above level int b = line; // slope within level int c = 3 * level; // level shifting return 2 * (a + b + c) + 1; } void put_spaces(int total_levels, int level, int line) { int i; i = 0; while (i < spaces_in_line(total_levels, level, line)) { ft_putchar(' '); i++; } ft_putchar('/'); } void put_stars(int level, int line) { int i; i = 0; while (i < stars_in_line(level, line)) { ft_putchar('*'); i++; } ft_putchar('\\'); } /* ** Have testing above this line */ // builds the damn thingy void build_thingy (int total_levels) { int level; int line; level = 0; line = 0; while (level < total_levels) { while (line < lines_in_level(level)) { put_spaces(total_levels, level, line); put_stars(level, line); ft_putchar('\n'); line++; } line = 0; level++; } } /* ** main */ int main() { build_thingy(5); return(0); } /* ** testing */
C
#include <stdio.h> int main() { /* Declare variables */ int i1, i2; int retVal; /* Prompt for and get user input */ printf("Enter two integers:\n"); retVal = scanf("%d%d", &i1, &i2); /* Check for valid user input. If the user entered the correct types, * retVal will be 2, since two values were successfully read and converted * to the desired types. If the user entered an incorrect type (try * entering a character rather than a number!), then retVal will not be 2. */ if (retVal != 2) { printf("Invalid input! Try running the program again!\n"); return 1; } else { /* Use the modulo operator, %, to compute the remainder */ printf("The remainder is %d\n", i1%i2); } return 0; }
C
#include <stdio.h> int main_3(void) { float pi = 3.141592f; float volume, r; printf("Enter the radius: "); scanf("%f",&r); volume = (4.0f / 3.0f) * pi * r * r * r; printf("Volume : %.1f\n", volume); return 0; }
C
#include <stdio.h> #include "holberton.h" #include <stdlib.h> /** * main - multiply 2 numbers, prints result * @argc: number of arguments * @argv: list of arguments * Return: 1 if number of arguments is not 3, 0 otherwise */ int main(int argc, char *argv[]) { if (argc != 3) { puts("Error"); return (1); } printf("%i\n", atoi(argv[1]) * atoi(argv[2])); return (0); }
C
#include "holberton.h" /** * mul - funtion to multiply two numbers * Description: A function to multiply * two integer numbers. * @a: The first factor * @b: The second factor * Return: the multiply result. */ int mul(int a, int b) { return (a * b); }
C
internal c_struct ParseStruct(memory_arena *Arena, tokenizer *Tokenizer, string Name) { c_struct Result = { .Type = PushString_(Arena, Name.Size, Name.Data), .Name = PushString_(Arena, Name.Size, Name.Data), .Members = 0 }; c_member *CurrentMember = 0; ToUpperCamelCase(&Result.Name); RequireToken(Tokenizer, Token_OpenCurlyBracket); while(Parsing(Tokenizer)) { token Token = GetToken(Tokenizer); if(Token.Type == Token_CloseCurlyBracket) { break; } else if(Token.Type == Token_SemiColon) { } else if(Token.Type == Token_ForwardSlash) { if(Tokenizer->At[0] == '/') { while((Tokenizer->At[0]) && (!IsEndOfLine(Tokenizer->At[0]))) { TokenizerAdvance(Tokenizer, 1); } } } else if(Token.Type == Token_Identifier) { if(CurrentMember == 0) { Result.Members = CurrentMember = PushStruct(Arena, c_member); } else { CurrentMember->Next = PushStruct(Arena, c_member); CurrentMember = CurrentMember->Next; } CurrentMember->TypeName = Token.Text; if(StringsAreEqual(String("b32"), Token.Text)) { CurrentMember->Type = C_B32; } else if(StringsAreEqual(String("f32"), Token.Text)) { CurrentMember->Type = C_F32; } else if(StringsAreEqual(String("u32"), Token.Text)) { CurrentMember->Type = C_U32; } else if(StringsAreEqual(String("string"), Token.Text)) { CurrentMember->Type = C_String; } else { if(StringsAreEqual(String("struct"), Token.Text)) { Token = RequireToken(Tokenizer, Token_Identifier); } CurrentMember->Type = C_Custom; } Token = GetToken(Tokenizer); if(Token.Type == Token_Asterisk) { CurrentMember->IsPointer = true; Token = GetToken(Tokenizer); } if(Token.Type == Token_Identifier) { CurrentMember->Name = Token.Text; } else { TokenError(Tokenizer, Token, "Expected member name"); } } else { TokenError(Tokenizer, Token, "Expecting struct members but got %S \"%S\"", GetTokenTypeName(Token.Type), Token.Text); } } return Result; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* utils_vector2.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: jwoo <jwoo@student.42seoul.kr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/04/23 18:55:30 by jwoo #+# #+# */ /* Updated: 2021/04/23 18:55:34 by jwoo ### ########.fr */ /* */ /* ************************************************************************** */ #include "minirt.h" t_vector3 vec3_scalar(t_vector3 vec, double scalar) { t_vector3 ret; ret.x = vec.x * scalar; ret.y = vec.y * scalar; ret.z = vec.z * scalar; return (ret); } double vec3_dot(t_vector3 u, t_vector3 v) { double dot_product; dot_product = u.x * v.x + u.y * v.y + u.z * v.z; return (dot_product); } t_vector3 vec3_cross(t_vector3 u, t_vector3 v) { t_vector3 ret; ret.x = u.y * v.z - u.z * v.y; ret.y = u.z * v.x - u.x * v.z; ret.z = u.x * v.y - u.y * v.x; return (ret); } double vec3_len(t_vector3 vec) { double len; len = sqrt(vec.x * vec.x + vec.y * vec.y + vec.z * vec.z); return (len); } t_vector3 vec3_unit(t_vector3 vec) { t_vector3 ret; ret = vec3_scalar(vec, (1 / vec3_len(vec))); return (ret); }
C
/* pphs - a pretty printer for Haskell code */ #include <stdio.h> #include <stdlib.h> #include <string.h> #define MAXLINELENGTH 256 enum face {KW, ID, IS, SU, ST, CO, NU, MA, SP, LC, RC, CR, BF, FQ, EQ, DQ, QD, EE, DC, DP, CP, LE, GE, LA, RA, RR, TI, BE}; /* Possible values of typeface */ int widecolons = 0; /* User may want space between double colons */ int subscripts = 0; /* User may want subscripts after '_' in identifiers */ int tablength = 8; /* User's input file tablength */ typedef struct ElementType_Tag { /* Basic storage unit */ char chars[MAXLINELENGTH]; /* Characters */ enum face typeface[MAXLINELENGTH]; /* Typefaces */ int indentation, length, col; /* Indentation level, non-empty length, column level */ } ElementType; typedef struct StackNodeType_Tag *Link; /* Stack-related types */ typedef struct StackNodeType_Tag { ElementType Element; /* Stack item */ Link Next; /* Link to next node */ } StackNodeType; typedef StackNodeType *StackNodePtr; typedef StackNodePtr StackType; typedef int QueueSizeType; /* Queue-related types */ typedef struct QueueNodeType_Tag *Connection; typedef struct QueueNodeType_Tag { ElementType Element; /* Queue item */ Connection Next; /* Link to next node */ } QueueNodeType; typedef QueueNodeType *QueueNodePtr; typedef struct QueueType_Tag { QueueNodePtr Front, Rear; QueueSizeType Length; } QueueType; FILE *ifptr; /* input file pointer */ /* * * STACK FUNCTIONS * * */ StackType CreateStack() /* Returns an empty stack */ { return(NULL); } int IsEmptyStack(s) /* Returns 1 if s is empty, 0 otherwise */ StackType s; { return(s == NULL); } StackType Push(s, x) /* Returns stack with x pushed onto s */ StackType s; ElementType x; { StackType p; p = (StackNodeType *) malloc(sizeof(StackNodeType)); if (p == NULL) { fprintf(stderr, "pphs: Stack is too big\n"); exit(3); } else { (*p).Element = x; (*p).Next = s; return(p); } } ElementType Top(s) /* Returns value of top element in s */ StackType s; { return((*s).Element); } StackType Pop(s) /* Returns stack with top element of s popped off */ StackType s; { StackType t; t = (*s).Next; free(s); return(t); } StackType PopSym(s) /* Returns stack with top element of s popped off without freeing */ StackType s; { StackType t; t = (*s).Next; /* free(s); As PopSym is called within a function, free would free space needed later */ return(t); } /* * * QUEUE FUNCTIONS * * */ QueueType CreateQueue() /* Returns an empty queue */ { QueueType q; q.Front = NULL; q.Rear = NULL; q.Length = 0; return(q); } int IsEmptyQueue(q) /* Returns 1 if q is empty, 0 otherwise */ QueueType q; { return(q.Front == NULL); } int LengthOfQueue(q) /* Returns length of q */ QueueType q; { return(q.Length); } QueueNodePtr FrontOfQueue(q) /* Returns pointer to front of q */ QueueType q; { return(q.Front); } QueueNodePtr RearOfQueue(q) /* Returns pointer to rear of q */ QueueType q; { return(q.Rear); } QueueType AddToQueue(q, x) /* Adds item x to rear of queue q */ QueueType q; ElementType x; { QueueNodePtr p; p = (QueueNodeType *) malloc(sizeof(QueueNodeType)); if (p == NULL) { fprintf(stderr, "pphs: Queue is too big\n"); exit(4); } else { (*p).Element = x; (*p).Next = NULL; if (q.Front == NULL) q.Front = p; else (*(q.Rear)).Next = p; q.Rear = p; q.Length++; return(q); } } QueueType TakeFromQueue(q) /* Removes front item from queue */ QueueType q; { QueueNodePtr p; if (q.Front == NULL) { fprintf(stderr, "pphs: Stack underflow\n"); exit(5); } else { p = q.Front; q.Front = (*(q.Front)).Next; if (q.Front == NULL) q.Rear = NULL; q.Length--; free(p); return(q); } } /* * * TYPEFACE FUNCTIONS * * */ int IsMathsChar(c) /* Returns 1 if c is a character to be in maths */ char c; { return((c == '[') || (c == ']') || (c == '/') || (c == ',') || (c == '!') || (c == ':') || (c == ';') || (c == '(') || (c == ')') || (c == '&') || (c == '#') || (c == '+') || (c == '-') || (c == '<') || (c == '>') || (c == '{') || (c == '}') || (c == '=') || (c == '|') || (c == '\'') || (c == '^')); } ElementType ChangeTypeface(store, length, finish, tf) /* Changes the typeface to tf in store for length until finish */ ElementType store; int length, finish; enum face tf; { int counter; for (counter = (finish - length); counter < finish; counter++) store.typeface[counter] = tf; return(store); } ElementType CheckForDoubleChar(store, position) /* Checks for double character in store.chars[position - 2..position - 1], if found alters typeface */ ElementType store; int position; { if ((position >= 2) && (store.typeface[position - 2] != DC)) { if ((store.chars[position - 2] == '-') && (store.chars[position - 1] == '-')) { store.typeface[position - 2] = LC; /* Haskell "--" line comment */ store.typeface[position - 1] = LC; } else if ((store.chars[position - 2] == '{') && (store.chars[position - 1] == '-')) { store.typeface[position - 2] = RC; /* Haskell "{-" regional comment begin */ store.typeface[position - 1] = DC; } else if ((store.chars[position - 2] == '-') && (store.chars[position - 1] == '}')) { store.typeface[position - 2] = CR; /* Haskell "-}" regional comment end */ store.typeface[position - 1] = DC; } else if ((store.chars[position - 2] == '+') && (store.chars[position - 1] == '+')) { store.typeface[position - 2] = DP; /* Double plus */ store.typeface[position - 1] = DC; } else if ((store.chars[position - 2] == ':') && (store.chars[position - 1] == '+')) { store.typeface[position - 2] = CP; /* Colon plus */ store.typeface[position - 1] = DC; } else if ((store.chars[position - 2] == '<') && (store.chars[position - 1] == '=')) { store.typeface[position - 2] = LE; /* Less than or equal to */ store.typeface[position - 1] = DC; } else if ((store.chars[position - 2] == '>') && (store.chars[position - 1] == '=')) { store.typeface[position - 2] = GE; /* Greater than or equal to */ store.typeface[position - 1] = DC; } else if ((store.chars[position - 2] == '<') && (store.chars[position - 1] == '-')) { store.typeface[position - 2] = LA; /* Leftarrow */ store.typeface[position - 1] = DC; } else if ((store.chars[position - 2] == '-') && (store.chars[position - 1] == '>')) { store.typeface[position - 2] = RA; /* Rightarrow */ store.typeface[position - 1] = DC; } else if ((store.chars[position - 2] == '=') && (store.chars[position - 1] == '>')) { store.typeface[position - 2] = RR; /* Double rightarrow */ store.typeface[position - 1] = DC; } else if (((store.chars[position - 2] == '*') && (store.chars[position - 1] == '*')) || ((store.chars[position - 2] == '^') && (store.chars[position - 1] == '^'))) { store.typeface[position - 2] = MA; /* Exponent, ie not Times */ store.typeface[position - 1] = MA; } } return(store); } int IsHaskellPunc(c) /* Returns 1 if c is a punctuation mark not part of identifier */ char c; { return((c == ' ') || (c == ',') || (c == '@') || (c == '#') || (c == '$') || (c == '%') || (c == '&') || (c == '*') || (c == '(') || (c == ')') || (c == '-') || (c == '+') || (c == '=') || (c == '\\') || (c == '|') || (c == '[') || (c == ']') || (c == '{') || (c == '}') || (c == ':') || (c == ';') || (c == '"') || (c == '~') || (c == '?') || (c == '/') || (c == '<') || (c == '>') || (c == '^')); } int IsKeyWord(str) /* Returns 1 if str is a keyword to be in keyword font */ char str[MAXLINELENGTH]; { return((!(strcmp(str, "case"))) || (!(strcmp(str, "class"))) || (!(strcmp(str, "data"))) || (!(strcmp(str, "default"))) || (!(strcmp(str, "deriving"))) || (!(strcmp(str, "else"))) || (!(strcmp(str, "hiding"))) || (!(strcmp(str, "if"))) || (!(strcmp(str, "import"))) || (!(strcmp(str, "in"))) || (!(strcmp(str, "infix"))) || (!(strcmp(str, "infixl"))) || (!(strcmp(str, "infixr"))) || (!(strcmp(str, "instance"))) || (!(strcmp(str, "interface"))) || (!(strcmp(str, "let"))) || (!(strcmp(str, "module"))) || (!(strcmp(str, "of"))) || (!(strcmp(str, "renaming"))) || (!(strcmp(str, "then"))) || (!(strcmp(str, "to"))) || (!(strcmp(str, "type"))) || (!(strcmp(str, "where")))); } int KeyWord(c, store, position) /* Returns length of keyword if a keyword ends at store.chars[position - 1] */ char c; ElementType store; int position; { int counter, start, end = position - 1, keywordlen = 0; char str[MAXLINELENGTH]; if ((!isalpha(c)) && (c != '_') && (c != '\'') && (position)) { for (counter = end; (counter >= 0) && ((isalpha(store.chars[counter])) || (c == '_') || (c == '\'')) && (counter >= store.indentation); counter--) { ; /* Just count letters */ } start = ++counter; for (counter = 0; counter + start <= end; counter++) { str[counter] = store.chars[counter + start]; /* Copy letters into str */ } str[counter] = '\0'; /* Add null character to end */ if (IsKeyWord(str)) /* Checks word in str is keyword */ keywordlen = strlen(str); /* and measures it */ } return(keywordlen); } ElementType CheckForKeyword(c, store, position) /* Returns store with any possible keyword ending at store.chars[position - 1] identified as such in store.typeface */ char c; ElementType store; int position; { if (KeyWord(c, store, position)) store = ChangeTypeface(store, KeyWord(c, store, position), position, KW); return(store); } int IsNumber(c, store, position, statesok) /* Returns 1 if c forms part of a number */ char c; ElementType store; int position, statesok; { int counter, foundident = 0, foundpunc = 0; if (((isdigit(c)) || (c == 'e') || (c == 'E') || (c == '|') || (c == '.')) && (statesok)) { counter = position - 1; while ((isdigit(store.chars[counter])) && (counter >= 0)) counter--; if (((store.chars[counter] == '+') || (store.chars[counter] == '-')) && ((store.chars[counter - 1] == 'e') || (store.chars[counter - 1] == 'E')) && (counter > 2)) counter -= 2; else if (((store.chars[counter] == 'e') || (store.chars[counter] == 'E')) && (counter > 1)) counter--; while ((isdigit(store.chars[counter])) && (counter >= 0)) counter--; if ((store.chars[counter] == '.') && (counter > 1)) counter--; while ((isdigit(store.chars[counter])) && (counter >= 0)) counter--; if ((isalpha(store.chars[counter])) && (counter >= 0)) foundident = 1; /* ie not number */ else if ((IsHaskellPunc(store.chars[counter])) || (counter < 0)) foundpunc = 1; /* ie is number */ } return(foundpunc); } /* * * LINE SELECTION FUNCTIONS * * */ ElementType SelectSkipLine(s, store, linecounter) /* Returns store containing line for skipover */ StackType s; ElementType store; int linecounter; { ElementType temp; int counter; if (!(IsEmptyStack(s))) { while (((Top(s)).length <= linecounter) || ((Top(s)).indentation >= linecounter)) { temp = Top(s); s = PopSym(s); if (IsEmptyStack(s)) { counter = temp.length; while (counter < linecounter) { temp.chars[counter] = ' '; temp.typeface[counter++] = SP; } temp.chars[counter] = '\0'; /* Add null character to end */ s = Push(s, temp); break; } } store = Top(s); } else { /* Stack is empty */ counter = store.length; while (counter < linecounter) { store.chars[counter] = ' '; store.typeface[counter++] = SP; } store.chars[counter] = '\0'; /* Add null character to end */ } return(store); } /* * * STORING FUNCTIONS * * */ ElementType CreateStore() /* Returns an empty store */ { ElementType store; strcpy(store.chars, ""); store.length = 0; store.indentation = 0; store.col = 0; return(store); } ElementType StoreSpace(store, position) /* Stores a space in the store at current position */ ElementType store; int position; { store.chars[position] = ' '; store.typeface[position] = SP; return(store); } /* * * WRITING FUNCTIONS * * */ void WriteStartFace(tf) /* Writes LaTeX typeface commands for start of section */ enum face tf; { if (tf == KW) /* Keywords */ printf("{\\keyword "); else if ((tf == ID) || (tf == IS)) /* Identifiers */ printf("{\\iden "); else if (tf == ST) /* Strings */ printf("{\\stri "); else if (tf == CO) /* Comments */ printf("{\\com "); else if (tf == NU) /* Numbers */ printf("{\\numb "); else if ((tf == MA) || (tf == TI)) /* Various maths */ printf("$"); } void WriteFinishFace(tf) /* Writes LaTeX typeface commands for end of section */ enum face tf; { if ((tf == KW) || (tf == ID) || (tf == ST) || (tf == CO) || (tf == NU)) /* Keywords, identifiers, strings, comments or numbers */ printf("\\/}"); else if ((tf == MA) || (tf == TI)) /* Various maths */ printf("$"); else if (tf == IS) /* Subscripts in identifiers */ printf("\\/}$"); } int WriteSpaces(store, counter, finish) /* Writes consecutive spaces, returning new counter value */ ElementType store; int counter, finish; { int spaces = 0; /* The number of spaces found */ for (; (store.typeface[counter] == SP) && (counter < finish); counter++) spaces++; printf("\\xspa{%d}", spaces); return(--counter); } int WriteChar(store, counter, finish) /* Writes charater, returning new counter value */ ElementType store; int counter, finish; { if (store.typeface[counter] == SP) /* Space */ printf("\\xspa1"); /* Redundant */ else if (store.typeface[counter] == BE) /* Bar under equals sign */ printf("\\bareq"); else if (store.typeface[counter] == DP) { /* Double plus */ if ((counter < finish - 1) && (store.typeface[counter + 1] == DC)) { printf("\\plusplus"); counter++; } } else if (store.typeface[counter] == CP) { /* Colon plus */ if ((counter < finish - 1) && (store.typeface[counter + 1] == DC)) { printf("{:}{+}"); counter++; } } else if (store.typeface[counter] == LE) { /* Less than or equal to */ if ((counter < finish - 1) && (store.typeface[counter + 1] == DC)) { printf("$\\leq$"); counter++; } } else if (store.typeface[counter] == GE) { /* Greater than or equal to */ if ((counter < finish - 1) && (store.typeface[counter + 1] == DC)) { printf("$\\geq$"); counter++; } } else if (store.typeface[counter] == LA) { /* Leftarrow */ if ((counter < finish - 1) && (store.typeface[counter + 1] == DC)) { printf("$\\leftarrow$"); counter++; } } else if (store.typeface[counter] == RA) { /* Rightarrow */ if ((counter < finish - 1) && (store.typeface[counter + 1] == DC)) { printf("$\\rightarrow$"); counter++; } } else if (store.typeface[counter] == RR) { /* Double rightarrow */ if ((counter < finish - 1) && (store.typeface[counter + 1] == DC)) { printf("$\\Rightarrow$"); counter++; } } else if (store.typeface[counter] == RC) { /* Regional comment begin */ if ((counter < finish - 1) && (store.typeface[counter + 1] == DC)) { printf("{\\com \\{-\\/}"); counter++; } else printf("{\\com \\{\\/}"); } else if (store.typeface[counter] == CR) { /* Regional comment end */ if ((counter < finish - 1) && (store.typeface[counter + 1] == DC)) { printf("{\\com -\\}\\/}"); counter++; } else printf("{\\com -\\/}"); } else if ((store.typeface[counter] == LC) && (store.chars[counter] == '-')) printf("{\\rm -}"); /* Comment - problem: "--" becomes "-" in LaTeX so fix done */ else if (store.chars[counter] == '\\') printf("\\hbox{$\\setminus$}"); /* Backslash */ else if (store.chars[counter] == '*') { if (store.typeface[counter] == TI) printf("\\times "); /* Multiplication */ else printf("*"); /* Other star symbols, eg Exponent */ } else if ((store.chars[counter] == '_') && (store.typeface[counter] == SU)) { if ((counter < finish - 1) && (store.typeface[counter + 1] == IS)) printf("$_"); /* Subscript character */ } else if (store.chars[counter] == '^') printf("\\char'136 "); /* Up-arrow */ else if (store.chars[counter] == '~') printf("\\char'176 "); /* Tilda */ else if ((store.chars[counter] == ':') && (store.chars[counter - 1] == ':') && (widecolons)) printf("\\,:"); /* Double colon */ else if (store.chars[counter] == '"') { if ((counter) && ((store.chars[counter - 1] == '"') || (store.chars[counter - 1] == '\''))) printf("\\,"); /* If previous character was a quote, leave a little space */ if (store.typeface[counter] == DQ) printf("{\\rm ``}"); /* Open doublequote */ else if (store.typeface[counter] == QD) printf("{\\rm \"}"); /* Close doublequote */ else printf("{\\rm \\char'175}"); /* Escape doublequote in string */ } else if (store.chars[counter] == '\'') { if ((counter) && ((store.chars[counter - 1] == '"') || ((store.chars[counter - 1] == '\'') && ((store.typeface[counter - 1] != MA) || (store.typeface[counter] != MA))))) printf("\\,"); /* If previous character was a quote, leave a little space except when it's a double prime */ if (store.typeface[counter] == FQ) printf("\\forquo "); /* Forward single quote */ else if (store.typeface[counter] == EQ) printf("\\escquo "); /* Escape single quote */ else if (store.typeface[counter] == BF) { if ((counter + 1 < store.length) && (store.typeface[counter + 1] == BF) && (counter + 1 != store.indentation)) { printf("{\\com \'\'\\/}"); /* Closing LaTeX style quote */ counter++; } else printf("{\\com \'\\/}"); /* Single quote following backquote in comment */ } else printf("\'"); /* Prime */ } else if (store.chars[counter] == '{') printf("\\hbox{$\\cal \\char'146$}"); /* Open curly bracket */ else if (store.chars[counter] == '}') printf("\\hbox{$\\cal \\char'147$}"); /* Close curly bracket */ else if ((counter) && (store.chars[counter - 1] == '[') && (store.chars[counter] == ']')) printf("\\,]"); /* Leave small gap between adjacent square brackets */ else if ((store.chars[counter] == '$') || (store.chars[counter] == '%') || (store.chars[counter] == '_') || (store.chars[counter] == '#') || (store.chars[counter] == '&')) /* Various characters needing '\' for LaTeX */ printf("\\%c", store.chars[counter]); else /* Other characters */ printf("%c", store.chars[counter]); return(counter); } void WriteSkipover(store) /* Writes the skipover portion of line in store */ ElementType store; { int counter = 0; printf("\\skipover{"); /* Write opening LaTeX skipover command */ WriteStartFace(store.typeface[counter]); /* Write opening LaTeX typeface command */ if (store.typeface[counter] == SP) counter = WriteSpaces(store, counter, store.indentation); /* Write spaces */ else counter = WriteChar(store, counter, store.indentation); /* Write character */ for (counter++; counter < store.indentation; counter++){ /* until end of skipover */ if (store.typeface[counter - 1] != store.typeface[counter]) { /* If typeface change */ WriteFinishFace(store.typeface[counter - 1]); /* write closing typeface command */ WriteStartFace(store.typeface[counter]); /* write opening LaTeX typeface command */ } if (store.typeface[counter] == SP) counter = WriteSpaces(store, counter, store.indentation); /* Write spaces */ else counter = WriteChar(store, counter, store.indentation); /* Write character */ } if (store.typeface[counter - 1] == SU) ; /* If indentation is under subscript don't open math section */ else WriteFinishFace(store.typeface[counter - 1]); /* Write closing LaTeX typeface command */ printf("}"); /* Write closing LaTeX skipover command */ } void WriteWords(store) /* Writes rest of line, starting at indentation level */ ElementType store; { int counter = store.indentation; int intabular = 0; /* Boolean: is in tabular section for internal alignment */ WriteStartFace(store.typeface[counter]); /* Write opening LaTeX typeface command */ if (store.typeface[counter] == SP) counter = WriteSpaces(store, counter, store.length); /* Write spaces */ else counter = WriteChar(store, counter, store.length); /* Write character */ for (counter++; counter < store.length; counter++){ /* until end of word */ if ((store.col) && (store.col == counter)) { printf(" & "); if (store.chars[counter - 1] == ':') printf("$:"); intabular = 1; } if (store.typeface[counter - 1] != store.typeface[counter]) /* If typeface change */ WriteFinishFace(store.typeface[counter - 1]); /* Write closing typeface command */ if ((store.typeface[counter] == SP) && (intabular)) { printf(" & "); intabular = 0; } if ((store.typeface[counter - 1] != store.typeface[counter]) /* If typeface change */ && ((store.chars[counter] != ':') || (store.col != counter + 1))) WriteStartFace(store.typeface[counter]); /* Write opening LaTeX typeface command */ if (store.typeface[counter] == SP) counter = WriteSpaces(store, counter, store.length); /* Write spaces */ else if ((store.chars[counter] != ':') || (!store.col) || (store.col != counter + 1)) counter = WriteChar(store, counter, store.length); /* Write character */ } WriteFinishFace(store.typeface[counter - 1]); /* Write closing LaTeX typeface command */ } void WriteLine(store, needed) /* Writes the line in store, only writing LaTeX newline if needed */ ElementType store; int needed; { if (store.indentation) WriteSkipover(store); if (store.indentation < store.length) WriteWords(store); if (needed) printf("\\\\"); /* LaTeX newline character */ printf("\n"); } QueueType WriteQueue(q) /* Writes lines, removing them from queue, leaves last line in queue if not in tabular section */ QueueType q; { int intabular = 0; if ((!(IsEmptyQueue(q))) && ((*(FrontOfQueue(q))).Element.col)) { printf("\\begin{tabular}{@{}l@{\\xspa1}c@{}l}\n"); intabular = 1; } while (LengthOfQueue(q) > !intabular) { WriteLine((*(FrontOfQueue(q))).Element, 1); /* LaTeX newline character is needed */ q = TakeFromQueue(q); } if (intabular) printf("\\end{tabular}\\\\\n"); return(q); } QueueType WriteRestOfQueue(q) /* Writes all lines, removing them from queue, doesn't have LaTeX newline after last line */ QueueType q; { int intabular = 0; if ((!(IsEmptyQueue(q))) && ((*(FrontOfQueue(q))).Element.col)) { printf("\\begin{tabular}{@{}l@{\\xspa1}c@{}l}\n"); intabular = 1; } while (!(IsEmptyQueue(q))) { WriteLine((*(FrontOfQueue(q))).Element, (LengthOfQueue(q) > 1)); /* Last line doesn't need LaTeX newline character */ q = TakeFromQueue(q); } if (intabular) { printf("\\end{tabular}"); if (!IsEmptyQueue(q)) /* Last line doesn't need LaTeX newline character */ printf("\\\\"); printf("\n"); } return(q); } int main (argc, argv) /* * * MAIN PROGRAM * * */ int argc; char *argv[]; { int tripped = 1, instring = 0, instringincomment = 0, inlinecomment = 0; int incharquote = 0, incharquoteincomment = 0, inbackquoteincomment = 0; int insub = 0; /* Booleans - just taken new line, in string, in string inside comment, in line comment, in character quote, in character quote inside comment, in backquote inside comment, in subscript */ int linecounter = 0, indentcounter = 0, inregcomment = 0, pos; /* Counters: current position on line, indentation of current line, nesting level of regional comments, position marker */ char c; /* Character */ StackType s; /* Stack of previous longest lines */ QueueType q; /* Queue of lines waiting to be printed */ ElementType store; /* Store of letters, typefaces and non-empty length */ if ((argc == 3) && (argv[1][0] == '-')) { /* If options specified with call */ if (strstr(argv[1], "s")) /* if -s option, subscripts in identifiers wanted */ subscripts = 1; if (strstr(argv[1], "t")) { /* if -tX option, tab characters are X spaces */ for (pos = 1; (argv[1][pos] != 't'); pos++) /* find 't' */ ; for (pos++, tablength = 0; isdigit(argv[1][pos]); pos++) /* read number */ tablength = (tablength * 10) + (argv[1][pos] - '0'); } if (strstr(argv[1], "w")) /* if -w option called, wide double colons wanted */ widecolons = 1; } else if (argc == 2) /* If no options */ ; else { /* If not called with pphs and a filename */ fprintf(stderr, "pphs: Call with one file name\n"); exit(1); } if ((strcspn(argv[argc - 1], ".") == strlen(argv[argc - 1])) /* If filename has no extention */ && ((ifptr = fopen(argv[argc - 1], "r")) == NULL)) /* and no plain file of that name */ strcat(argv[argc - 1], ".hs"); /* add a ".hs" extention */ if ((ifptr = fopen(argv[argc - 1], "r")) == NULL) { /* Open input file */ fprintf(stderr, "pphs: File could not be opened\n"); /* eg isn't there */ exit(2); } else { printf("\\begin{tabbing}\n"); /* Start of Haskell program */ store = CreateStore(); /* an empty one */ s = CreateStack(); /* an empty one */ q = CreateQueue(); /* an empty one */ fscanf(ifptr, "%c", &c); /* Read character */ while (!feof(ifptr)) { /* While not at end of input file */ while ((isspace(c)) && (!(feof(ifptr)))) { /* Read blank characters */ if (c == ' ') { if (tripped) linecounter++; /* Count leading spaces */ else { /* or */ store = StoreSpace(store, linecounter++); /* Store intermediate or trailing space */ if (store.length < linecounter) store.chars[linecounter] = '\0'; /* Add null character to end */ } fscanf(ifptr, "%c", &c); /* Read next character */ } else if (c == '\t') { if (tripped) linecounter += (tablength - (linecounter % tablength)); else { store = StoreSpace(store, linecounter++); for (; linecounter % tablength; linecounter++) store = StoreSpace(store, linecounter); if (store.length < linecounter) store.chars[linecounter] = '\0'; /* Add null character to end */ } fscanf(ifptr, "%c", &c); /* Read next character */ } else if (c == '\n') { tripped = 1; /* Just taken a new line */ inlinecomment = 0; if (!(IsEmptyStack(s))) while (((Top(s)).length <= store.length) && ((Top(s)).indentation >= store.length)) { s = Pop(s); if (IsEmptyStack(s)) break; } if (store.length > 0) { /* Push non-empty line onto indentation stack */ store.indentation = indentcounter; s = Push(s, store); } if (!(IsEmptyQueue(q))) { if ((store.col != (*(FrontOfQueue(q))).Element.col) || (!(*(FrontOfQueue(q))).Element.col)) q = WriteQueue(q); /* If internal alignment changes or there is none write out lines */ } q = AddToQueue(q, store); /* Add to writing queue */ linecounter = 0; /* Get ready to count leading spaces */ store.length = linecounter; fscanf(ifptr, "%c", &c); /* Read next character */ } else break; } if (tripped) { indentcounter = linecounter; store.indentation = linecounter; store.col = 0; } if ((tripped) && (linecounter)) { /* Skipover necessary for indentation */ store = SelectSkipLine(s, store, linecounter); store.indentation = linecounter; store.col = 0; } if (!feof(ifptr)) tripped = 0; /* No longer just taken new line */ while ((!(isspace(c))) && (!(feof(ifptr)))) { /* Read word */ if ((linecounter > 1) && (!IsEmptyQueue(q)) && ((*(RearOfQueue(q))).Element.length >= linecounter) && (linecounter > store.indentation) && (linecounter > (*(RearOfQueue(q))).Element.indentation) && (store.chars[linecounter - 1] == ' ') && ((((*(RearOfQueue(q))).Element.chars[linecounter - 1] == ' ') && ((c == (*(RearOfQueue(q))).Element.chars[linecounter]) || ((c == '=') && ((*(RearOfQueue(q))).Element.chars[linecounter] == ':') && ((*(RearOfQueue(q))).Element.chars[linecounter + 1] == ':')))) || (((*(RearOfQueue(q))).Element.chars[linecounter - 1] == ':') && ((*(RearOfQueue(q))).Element.chars[linecounter] == ':') && (c == '='))) && ((store.chars[linecounter - 2] == ' ') || ((*(RearOfQueue(q))).Element.chars[linecounter - 2] == ' ')) && (((*(RearOfQueue(q))).Element.col == 0) || ((*(RearOfQueue(q))).Element.col == linecounter))) { store.col = linecounter; /* Identify any internal alignment */ (*(RearOfQueue(q))).Element.col = linecounter; } if ((c == '"') && (!incharquote) /* String outside comments */ && (!inregcomment) && (!inlinecomment)) { if (((linecounter) && (store.chars[linecounter - 1] != '\\')) || (!linecounter)) instring = !instring; } else if ((c == '"') && (!incharquoteincomment) /* String inside comment */ && (!inbackquoteincomment) && ((inregcomment) || (inlinecomment))) { if (((linecounter) && (store.chars[linecounter - 1] != '\\')) || (!linecounter)) instringincomment = !instringincomment; } else if ((c == '`') && ((inlinecomment) || (inregcomment))) { if ((linecounter) && (store.chars[linecounter - 1] == '`')) inbackquoteincomment = 2; /* Opening LaTeX style quote in comment */ else inbackquoteincomment = !inbackquoteincomment; /* Backquote in comment */ } else if ((linecounter) && (!inlinecomment) && (!instring)) { if ((store.chars[linecounter - 1] == '{') && (c == '-')) inregcomment++; /* Haskell "{-" regional comment begin */ else if ((store.chars[linecounter - 1] == '-') && (c == '}')) { inregcomment--; /* Haskell "-}" regional comment end */ instringincomment = 0; incharquoteincomment = 0; inbackquoteincomment = 0; } } if (c == '|') { if ((!IsEmptyQueue(q)) && ((((*(RearOfQueue(q))).Element.chars[linecounter] == '=') && (linecounter == store.indentation)) || ((*(RearOfQueue(q))).Element.typeface[linecounter] == BE))) store.typeface[linecounter] = BE; else store.typeface[linecounter] = MA; } else if ((c == '\'') && (linecounter) && (store.chars[linecounter - 1] == '\\')) store.typeface[linecounter] = EQ; /* Escape character quote */ else if ((c == '\'') && (!instring) && (!inregcomment) && (!inlinecomment)) { if (((linecounter) && (store.chars[linecounter - 1] != '\\') && ((IsHaskellPunc(store.chars[linecounter - 1])) || (incharquote))) || (!linecounter)) { incharquote = !incharquote; store.typeface[linecounter] = FQ; /* Character quote */ } else store.typeface[linecounter] = MA; /* Prime */ } else if ((c == '\'') && (!instringincomment) && ((inregcomment) || (inlinecomment))) { if (((linecounter) && (store.chars[linecounter - 1] != '\\') && ((IsHaskellPunc(store.chars[linecounter - 1])) || (incharquoteincomment))) || (!linecounter)) { incharquoteincomment = !incharquoteincomment; store.typeface[linecounter] = FQ; /* Character quote in comment */ } else if (inbackquoteincomment) { inbackquoteincomment--; store.typeface[linecounter] = BF; /* `x' character quote in comment */ } else store.typeface[linecounter] = MA; /* Prime */ } else if (c == '"') { if ((!incharquote) && (!incharquoteincomment) && (!inbackquoteincomment) && ((instring) || (instringincomment))) { if (((linecounter) && (store.chars[linecounter - 1] != '\\')) || (!linecounter)) store.typeface[linecounter] = DQ; /* Open doublequote */ else if (store.chars[linecounter - 1] == '\\') store.typeface[linecounter] = EE; /* Escape doublequote */ } else if ((!incharquote) && (!incharquoteincomment) && (!inbackquoteincomment)) { if (((linecounter) && (store.chars[linecounter - 1] != '\\')) || (!linecounter)) store.typeface[linecounter] = QD; /* Close doublequote */ else if (store.chars[linecounter - 1] == '\\') store.typeface[linecounter] = EE; /* Escape doublequote */ } else store.typeface[linecounter] = EE; /* Character quote of doublequote */ } else if (c == '`') { if ((inlinecomment) || (inregcomment)) store.typeface[linecounter] = CO; else store.typeface[linecounter] = MA; } else if ((linecounter) && (subscripts) && (c == '_') && (store.typeface[linecounter - 1] == ID)) store.typeface[linecounter] = SU; /* Subscript in identifier */ else if (c == '*') store.typeface[linecounter] = TI; /* Times - may be changed by double char */ else if (IsMathsChar(c)) store.typeface[linecounter] = MA; /* Maths characters */ else if (IsNumber(c, store, linecounter, ((!inregcomment) && (!instring) && (!inlinecomment)))) store.typeface[linecounter] = NU; /* Numbers */ else if ((instring) || (incharquote)) store.typeface[linecounter] = ST; /* Characters in strings */ else if ((inlinecomment) || (inregcomment)) store.typeface[linecounter] = CO; /* Characters in comments */ else { if (insub) store.typeface[linecounter] = IS; /* Subscript identifiers */ else store.typeface[linecounter] = ID; /* Others */ } if (linecounter) if ((store.typeface[linecounter - 1] == IS) && (store.typeface[linecounter] != IS)) insub = 0; /* End of subscript identifier */ store.chars[linecounter++] = c; /* Place character in store */ if (linecounter > store.indentation + 1) store = CheckForDoubleChar(store, linecounter); if ((store.typeface[linecounter - 1] == LC) && (!inregcomment) && (!instring) && (!incharquote)) { instringincomment = 0; incharquoteincomment = 0; inbackquoteincomment = 0; inlinecomment = 1; } else if ((store.typeface[linecounter - 1] == SU) && (linecounter != store.indentation)) insub = 1; fscanf(ifptr, "%c", &c); /* Read next character */ if (feof(ifptr)) c = ' '; if ((!inregcomment) && (!inlinecomment) && (!instring)) store = CheckForKeyword(c, store, linecounter); /* Keywords not in comments or strings to be in keyword typeface */ } insub = 0; store.chars[linecounter] = '\0'; /* String terminating null character */ store.length = linecounter; } if ((!tripped) && (!store.col)) /* If last line not in internal alignment */ q = WriteQueue(q); /* write previous lines which might */ if (!tripped) /* Put final line in queue if non-empty */ q = AddToQueue(q, store); if (feof(ifptr)) /* Write remaining lines */ q = WriteRestOfQueue(q); printf("\\end{tabbing}\n"); /* End of Haskell program */ exit(0); } }
C
/* * File: timetable_entry.h * Author: Jannis Diekmann * * Created on 31. Januar 2021, 12:22 */ #ifndef TIMETABLE_ENTRY_H #define TIMETABLE_ENTRY_H #ifdef __cplusplus extern "C" { #endif #include <time.h> #include <stdint.h> // Id to select a specific timetable typedef uint8_t timetable_id; /************************************************************************* Struct: timetable_entry Purpose: store the time, duration and the interval for a timed event **************************************************************************/ struct timetable_entry{ // time of first activation from event time_t next_event; // time till deactivation time_t duration_of_activation; // time till next activation time_t interval; // last function executed was activation function uint8_t is_active :1; // event_id; uint8_t event_id :7; //repeat times? maybe _interval == NULL => do only once? }; #ifdef __cplusplus } #endif #endif /* TIMETABLE_ENTRY_H */
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* instructions.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: marvin <marvin@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/09/29 16:13:21 by marvin #+# #+# */ /* Updated: 2021/09/29 16:13:23 by marvin ### ########.fr */ /* */ /* ************************************************************************** */ #include "instructions.h" void swap_stack(t_list **stack) { t_list *first_node; t_list *second_node; first_node = *stack; if (!first_node || !first_node->next) return ; second_node = first_node->next; *stack = second_node; first_node->next = second_node->next; second_node->next = first_node; } void push_stack(t_list **dest, t_list **src) { t_list *tmp; tmp = *src; if (!tmp) return ; *src = tmp->next; tmp->next = 0; ft_lstadd_front(dest, tmp); } void rotate_stack(t_list **stack) { t_list *first_node; first_node = *stack; if (!first_node || !first_node->next) return ; *stack = first_node->next; first_node->next = 0; ft_lstadd_back(stack, first_node); } void rev_rotate_stack(t_list **stack) { t_list *tmp; t_list *last_node; tmp = *stack; if (!tmp || !tmp->next) return ; while (tmp->next->next) tmp = tmp->next; last_node = tmp->next; tmp->next = 0; ft_lstadd_front(stack, last_node); }
C
/********************************************/ /* */ /* OL 61 */ /* Fixed Size Allocator */ /* */ /********************************************/ #ifndef OL61_FSA #define OL61_FSA #include <stddef.h> /* size_t */ typedef struct fsa_t fsa_t; /* * O(n) * return value - pointer to administrative struct. * arguments - pointer to user's malloc, malloc'ed size, size of element. * this function hands over malloc'ed space for management. */ fsa_t *FsaInit(void *memory, size_t size, size_t element_size); /* * O(1) * return value - calculated size for malloc (includes administratives). * arguments - element size, number of elements. * this function calculates the total size that needs to be malloc'ed in order * for the user to be able to receieve the requested capacity. */ size_t FsaSuggestSize(size_t element_size, size_t element_num); /* * O(1) * return value - pointer to allocated value. * arguments - administrative struct. * this function allocates managed memory. */ void *FsaAlloc(fsa_t *fsa); /* * O(1) * return value - none. * arguments - pointer to memory space to be freed. * this function frees managed memory space. */ void FsaFree(void *element); /* * O(n) * return value - number of free elements. * arguments - administrative struct. * this function returns number of free elements. */ size_t FsaCountFree(fsa_t *fsa); #endif /*OL61_FSA*/
C
#include <stdlib.h> #include <stdio.h> #include <assert.h> #include "header_sort.h" /** * Given two pointers, this function switches the content: * e1: pointer to the first value * e2: pointer to the second value */ void swap(void** e1, void** e2) { void* tmp = *e1; *e1 = *e2; *e2 = tmp; } /*-----MERGE SORT-----*/ //COMPLEXITY: // # Best case: O(n log n) // # Middle case: O(n log n) // # Worse case: O(n log n) /** * merge function creates the support array where memorizes the values while the * array is ordering. When the merge is complete values are stored ordered into * the original array and the support array is freed. */ void merge(void** array, int first, int middle, int last, CompFunction compare) { int dim = last - first + 1; int i, j, k; int** new_array; new_array = malloc(dim*sizeof(void*)); i = first; j = middle + 1; k = 0; while (i <= middle && j <= last) { if (compare(array[i], array[j]) < 0) new_array[k++] = array[i++]; else new_array[k++] = array[j++]; } while (i <= middle) new_array[k++] = array[i++]; while (j <= last) new_array[k++] = array[j++]; for (int h=0; h<dim; h++) { swap (&array[first+h], (void**)&new_array[h]); } free(new_array); } /** * Function that calls itself for the first and the secon middle of the array. * Once the the two halve are ordered, it calls the merge function that actually * merge them in an ordred array. */ void msort(void** array, int first, int last, CompFunction compare) { if (first < last) { int middle = (first + last) / 2; msort(array, first, middle, compare); msort(array, middle+1, last, compare); merge(array, first, middle, last, compare); } } void merge_sort(void** array, int size, CompFunction compare) { msort(array, 0, size-1, compare); }
C
// /wizards/kalinash/bin/_langs.c // Shows what languages a player knows // Also shows numeric proficiency values // By Kalinash@Nightmare on 16 Dec 93 #include <std.h> inherit DAEMON; int cmd_langs(string str) { string *lang, tmp; int amt, x; object ob; if(!str || str=="me") { str=(string)this_player()->query_name(); } if(!ob=find_player(str)) { notify_fail(capitalize(str)+" is not in our reality.\n"); return 0; } if(ob->query_invis() && !archp(this_player())) { notify_fail(capitalize(str)+" is not in our reality.\n"); return 0; } lang = ob->query_all_languages(); amt = sizeof(lang); if(!amt) { notify_fail("They know no languages!\n"); return 0; } message("my_action", ob->query_cap_name()+" knows the following " "languages :\n", this_player()); for(x=0;x<amt;x++) { tmp = lang[x]; tmp = arrange_string(tmp, 15); tmp += ob->query_lang_prof(lang[x]); x++; if(x<amt) { tmp = arrange_string(tmp, 20); tmp += lang[x]; tmp = arrange_string(tmp, 35); tmp += ob->query_lang_prof(lang[x]); } message("my_action", tmp, this_player()); } return 1; } void help() { message("help", "Usage : langs <who>\n\nThis is a wizard " "command to show the langues and proficiencies " "of players.", this_player()); return; }
C
#include <string.h> #include "builtins.h" #include "macros.h" lval* builtin_lambda(lenv* e, lval* a) { /* \ {x y} {+ x y}*/ /* Need 2 args, both Q-Expr */ LASSERT_NUM("\\", a, 2); LASSERT_TYPE("\\", a, 0, LVAL_QEXPR); LASSERT_TYPE("\\", a, 1, LVAL_QEXPR); /* First Q-EXPR is set of params / formals, check it contains only symbols */ for (int i = 0; i < a->cell[0]->count; ++i) { LASSERT(a, (a->cell[0]->cell[i]->type == LVAL_SYM), "Cannot define non-symbol. Got %s, Expected %s.", ltype_name(a->cell[0]->cell[i]->type),ltype_name(LVAL_SYM)); } /* Set formals and body*/ lval* formals = lval_pop(a, 0); lval* body = lval_pop(a, 0); lval_del(a); return lval_lambda(formals, body); } lval* builtin_list(lenv* e, lval* a) { a->type = LVAL_QEXPR; return a; } lval* builtin_head(lenv* e, lval* a) { /*Check error conditions */ LASSERT_NUM("head", a, 1); LASSERT_TYPE("head", a, 0, LVAL_QEXPR); LASSERT_NOT_EMPTY("head", a, 0); /* Otherwise take first argument */ lval* v = lval_take(a, 0); /* Delete rest of elements in list */ while (v->count > 1) { lval_del(lval_pop(v, 1)); } return v; } lval* builtin_tail(lenv* e, lval* a) { /*Check error conditions */ LASSERT_NUM("tail", a, 1); LASSERT_TYPE("tail", a, 0, LVAL_QEXPR); LASSERT_NOT_EMPTY("tail", a, 0); lval* v = lval_take(a, 0); /*Delete first element and return*/ lval_del(lval_pop(v, 0)); return v; } lval* builtin_eval(lenv* e, lval* a) { /*Check error conditions */ LASSERT_NUM("eval", a, 1); LASSERT_TYPE("eval", a, 0, LVAL_QEXPR); lval* x = lval_take(a, 0); x->type = LVAL_SEXPR; return lval_eval(e, x); } lval* builtin_join(lenv* e, lval* a) { for (int i = 0; i < a->count; ++i) { LASSERT_TYPE("join", a, i, LVAL_QEXPR); } lval* x = lval_pop(a, 0); while (a->count) { lval* y = lval_pop(a, 0); x = lval_join(x, y); } lval_del(a); return x; } lval* builtin_op(lenv*e, lval* a, char* op) { for (int i = 0; i < a->count; ++i) { LASSERT_TYPE(op, a, i, LVAL_NUM); } lval* x = lval_pop(a, 0); /* If no args & unary operator */ if ((!strcmp(op, "-")) && a->count == 0) { x->num = - x->num; } while (a->count) { lval* y = lval_pop(a, 0); if (!strcmp(op, "+")) { x->num += y->num; } if (!strcmp(op, "-")) { x->num -= y->num; } if (!strcmp(op, "*")) { x->num *= y->num; } if (!strcmp(op, "/")) { if (y->num == 0) { lval_del(x); lval_del(y); x = lval_err("Division by zero!!"); break; } x->num /= y->num; } lval_del(y); } lval_del(a); return x; } lval* builtin_add(lenv* e, lval* a) { return builtin_op(e, a, "+"); } lval* builtin_sub(lenv* e, lval* a) { return builtin_op(e, a, "-"); } lval* builtin_mul(lenv* e, lval* a) { return builtin_op(e, a, "*"); } lval* builtin_div(lenv* e, lval* a) { return builtin_op(e, a, "/"); } lval* builtin_ord(lenv* e, lval* a, char* func) { LASSERT_NUM(func, a, 2); LASSERT_TYPE(func, a, 0, LVAL_NUM); LASSERT_TYPE(func, a, 1, LVAL_NUM); int result = 0; if (!strcmp(func, ">")) { result = (a->cell[0]->num > a->cell[1]->num); } else if (!strcmp(func, "<")) { result = (a->cell[0]->num < a->cell[1]->num); } else if (!strcmp(func, ">=")) { result = (a->cell[0]->num >= a->cell[1]->num); } else if (!strcmp(func, "<=")) { result = (a->cell[0]->num <= a->cell[1]->num); } lval_del(a); return lval_num(result); } lval* builtin_gt(lenv* e, lval* a) { return builtin_ord(e, a, ">"); } lval* builtin_lt(lenv* e, lval* a) { return builtin_ord(e, a, "<"); } lval* builtin_ge(lenv* e, lval* a) { return builtin_ord(e, a, ">="); } lval* builtin_le(lenv* e, lval* a) { return builtin_ord(e, a, "<="); } lval* builtin_cmp(lenv* e, lval* a, char* op) { LASSERT_NUM(op, a, 2); int r; if (strcmp(op, "==") == 0) { r = lval_eq(a->cell[0], a->cell[1]); } if (strcmp(op, "!=") == 0) { r = !lval_eq(a->cell[0], a->cell[1]); } lval_del(a); return lval_num(r); } lval* builtin_eq(lenv* e, lval* a) { return builtin_cmp(e, a, "=="); } lval* builtin_ne(lenv* e, lval* a) { return builtin_cmp(e, a, "!="); } lval* builtin_if(lenv* e, lval* a) { LASSERT_NUM("if", a, 3); LASSERT_TYPE("if", a, 0, LVAL_NUM); LASSERT_TYPE("if", a, 1, LVAL_QEXPR); LASSERT_TYPE("if", a, 2, LVAL_QEXPR); /* Mark Both Expressions as evaluable */ lval* x; a->cell[1]->type = LVAL_SEXPR; a->cell[2]->type = LVAL_SEXPR; if (a->cell[0]->num) { /* If condition is true evaluate first expression */ x = lval_eval(e, lval_pop(a, 1)); } else { /* Otherwise evaluate second expression */ x = lval_eval(e, lval_pop(a, 2)); } /* Delete argument list and return */ lval_del(a); return x; } lval* builtin_var(lenv* e, lval* a, char* func) { LASSERT_TYPE(func, a, 0, LVAL_QEXPR); /* First arg is symbol list */ lval* syms = a->cell[0]; /*Ensure all elements of first list are symbols*/ for (int i = 0; i < syms->count; ++i) { LASSERT(a, (syms->cell[i]->type == LVAL_SYM), "Function '%s' cannot define non-symbol. " "Got %s, Expected %s.", func, ltype_name(syms->cell[i]->type), ltype_name(LVAL_SYM)); } /*Check correct number of symbols and values*/ LASSERT(a, (syms->count == a->count-1), "Function '%s' passed too many arguments for symbols. Got %i, Expected %i.", func, syms->count, a->count-1); /*Assign copies of values to symbols*/ for (int i = 0; i < syms->count; ++i) { if (!strcmp(func, "def")) { lenv_def(e, syms->cell[i], a->cell[1 + i]); } else if (!strcmp(func, "=")) { lenv_put(e, syms->cell[i], a->cell[1 + i]); } } lval_del(a); return lval_sexpr(); } lval* builtin_def(lenv* e, lval* a) { return builtin_var(e, a, "def"); } lval* builtin_put(lenv* e, lval* a) { return builtin_var(e, a, "="); } /* Evaluation */ lval* lval_call(lenv* e, lval* f, lval* a) { /* If Builtin then simply apply that */ if (f->builtin) { return f->builtin(e, a); } /* Record Argument Counts */ int given = a->count; int total = f->formals->count; /* While arguments still remain to be processed */ while (a->count) { /* If we've ran out of formal arguments to bind */ if (f->formals->count == 0) { lval_del(a); return lval_err( "Function passed too many arguments. " "Got %i, Expected %i.", given, total); } /* Pop the first symbol from the formals */ lval* sym = lval_pop(f->formals, 0); /* Special Case to deal with '&' */ if (strcmp(sym->sym, "&") == 0) { /* Ensure '&' is followed by another symbol */ if (f->formals->count != 1) { lval_del(a); return lval_err("Function format invalid. " "Symbol '&' not followed by single symbol."); } /* Next formal should be bound to remaining arguments */ lval* nsym = lval_pop(f->formals, 0); lenv_put(f->env, nsym, builtin_list(e, a)); lval_del(sym); lval_del(nsym); break; } /* Pop the next argument from the list */ lval* val = lval_pop(a, 0); /* Bind a copy into the function's environment */ lenv_put(f->env, sym, val); /* Delete symbol and value */ lval_del(sym); lval_del(val); } /* Argument list is now bound so can be cleaned up */ lval_del(a); /* If '&' remains in formal list bind to empty list */ if (f->formals->count > 0 && strcmp(f->formals->cell[0]->sym, "&") == 0) { /* Check to ensure that & is not passed invalidly. */ if (f->formals->count != 2) { return lval_err("Function format invalid. " "Symbol '&' not followed by single symbol."); } /* Pop and delete '&' symbol */ lval_del(lval_pop(f->formals, 0)); /* Pop next symbol and create empty list */ lval* sym = lval_pop(f->formals, 0); lval* val = lval_qexpr(); /* Bind to environment and delete */ lenv_put(f->env, sym, val); lval_del(sym); lval_del(val); } /* If all formals have been bound evaluate */ if (f->formals->count == 0) { /* Set environment parent to evaluation environment */ f->env->par = e; /* Evaluate and return */ return builtin_eval( f->env, lval_add(lval_sexpr(), lval_copy(f->body))); } else { /* Otherwise return partially evaluated function */ return lval_copy(f); } } lval* lval_eval_sexpr(lenv* e, lval* v) { for (int i = 0; i < v->count; ++i) { v->cell[i] = lval_eval(e, v->cell[i]); } for (int i = 0; i < v->count; ++i) { if (v->cell[i]->type == LVAL_ERR) return lval_take(v, i); } if (v->count == 0) return v; if (v->count == 1) return lval_take(v, 0); lval* f = lval_pop(v, 0); if (f->type != LVAL_FUN) { lval* err = lval_err( "S-Expression starts with incorrect type. " "Got %s, Expected %s.", ltype_name(f->type), ltype_name(LVAL_FUN)); lval_del(f); lval_del(v); return err; } lval* result = lval_call(e, f, v); lval_del(f); return result; } lval* lval_eval(lenv* e, lval* v) { if (v->type == LVAL_SYM) { lval* x = lenv_get(e, v); lval_del(v); return x; } if (v->type == LVAL_SEXPR) return lval_eval_sexpr(e, v); return v; } /*Reading*/ lval* lval_read_num(mpc_ast_t* t) { errno = 0; long x = strtol(t->contents, NULL, 10); return errno != ERANGE ? lval_num(x) : lval_err("Invalid number"); } lval* lval_read_str(mpc_ast_t* t) { /* Cut off the final quote character */ t->contents[strlen(t->contents)-1] = '\0'; /* Copy the string missing out the first quote character */ char* unescaped = malloc(strlen(t->contents+1)+1); strcpy(unescaped, t->contents+1); /* Pass through the unescape function */ unescaped = mpcf_unescape(unescaped); /* Construct a new lval using the string */ lval* str = lval_str(unescaped); /* Free the string and return */ free(unescaped); return str; } lval* lval_read(mpc_ast_t* t) { if (strstr(t->tag, "number")) return lval_read_num(t); if (strstr(t->tag, "symbol")) return lval_sym(t->contents); if (strstr(t->tag, "string")) { return lval_read_str(t); } /* If root(>) or sexpression then create list */ lval* x = NULL; if ((strstr(t->tag, "sexpr")) || (!strcmp(t->tag, ">"))) x = lval_sexpr(); if (strstr(t->tag, "qexpr")) { x = lval_qexpr(); } for (int i = 0; i < t->children_num; i++) { if (!strcmp(t->children[i]->contents, "(")) continue; if (!strcmp(t->children[i]->contents, ")")) continue; if (!strcmp(t->children[i]->contents, "{")) continue; if (!strcmp(t->children[i]->contents, "}")) continue; if (strstr(t->children[i]->tag, "comment")) continue; if (!strcmp(t->children[i]->tag, "regex")) continue; x = lval_add(x, lval_read(t->children[i])); } return x; }
C
#include <stdio.h> #include <stdlib.h> #include <math.h> int main() { //%e %f e %lf %g double //%i %o %u %x para int //%c para char double valor_investido,juros,meses,ganho_juros; printf("Digite o valor do investimento: "); scanf("%lf",&valor_investido); printf("Digite a taxa de juros: "); scanf("%lf",&juros); printf("Digite em meses o tempo da aplicacao : "); scanf("%lf",&meses); ganho_juros = ((valor_investido/100)*juros)* meses ; printf("O valor investido foi %0.2f \nO valor ganho foi de %0.2f \nTendo o ganho total de : %0.2f",valor_investido, ganho_juros, valor_investido+ganho_juros); return 0; }
C
#ifndef _SCRATCHPAD_H #define _SCRATCHPAD_H /* Tim Hollebeek * * The data must also consist of zero terminated chunks, with lengths in the * range 0 < len < 256. Longer things can be handled, but they're just * malloc'ed. * * Designed to be used by the compile stack (if pointers get popped off due * to errors, we don't have to worry about them b/c we'll reclaim the space * when we throw away the scratchpad; this is another advantage), it could * be used by other things as well. */ #define SCRATCHPAD_SIZE 4096 #define SDEBUG(x) #define SDEBUG2(x) #define SCRATCH_MAGIC ((unsigned char)0xbb) typedef struct sp_block_s { struct sp_block_s *next, *prev; char block[2]; /* block[0] must be nonzero, usually SCRATCH_MAGIC */ } sp_block_t; #define scratch_free_last() \ scr_tail = --scr_last; \ scr_last -= *scr_tail; \ while (!(*scr_last) && scr_tail != scr_last) { \ /* check if the one before was already freed */ \ scr_tail = --scr_last; \ scr_last -= *scr_tail; \ } extern unsigned char *scr_last; extern unsigned char *scr_tail; extern unsigned char *scratch_end; /* * scratchpad.c */ void scratch_destroy(void); char *scratch_copy(char*); char *scratch_alloc(int); void scratch_free(char*); char *scratch_join(char *, char*); char *scratch_join2(char *, char*); char *scratch_realloc(char *, int); char *scratch_copy_string(char*); char *scratch_large_alloc(int); #endif
C
// Write a program that calls `fork()` and then calls some form of `exec()` // to run the program `/bin/ls`. Try a few variants of `exec()`, such as // `execl()`, `execle()`, `execv()`, and others. Why do you think there // are so many variants of the same basic call? #include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <sys/wait.h> int main(void) { // Your code here int temp = fork(); if(temp == 0){ char *args[2]; args[0] = "bin/ls"; args[1] = NULL; execvp(args[0], args); printf("Child process\n"); }else if(temp < 0){ printf("fork failed\n"); } else { int wc = waitpid(temp, NULL, 0); printf("Completed child process\n"); } return 0; }
C
#include<stdio.h> void main() { int a,b,c,sum,perc; printf("1st side of triangle a\n"); scanf("%d",&a); printf("2nd side of tringle b\n"); scanf("%d",&b); printf("3rd side of trianglec\n"); scanf("%d",&c); if((a+b>c)||(b+c>a)||(c+a>b)) printf("triangle is valid\n"); else printf("triangle is not valid\n"); }
C
#define _CRT_SECURE_NO_WARNINGS #include<stdio.h> #include<stdlib.h> #include<string.h> //һṹ嶨 ṹеijԱ ڴ沼־ //ͨ ageַ ȥĽṹڴַ typedef struct AdvTeacher { char name[64]; int age; char*pname; }AdvTeacher; int main561() { AdvTeacher t1; AdvTeacher*p = NULL; p - 1;//ͨ ͨ 仰 CPUм p - 2; int offsize = (int)&(p->age); printf("%d\n", offsize); system("pause"); return 0; } void main562() { AdvTeacher t1; AdvTeacher*p = NULL; p = &t1; int offsize = (int)&(((AdvTeacher*)0)->age);//AdvTeacherķʽʹ㿪ʼڴ սṹж˳ int offsize1 = (int)&(p->age) - (int)p; printf("%d\n", offsize); printf("%d\n", offsize1); printf("p:%d", (int)p); system("pause"); return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_display_list.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: mmthethw <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/09/15 10:18:42 by mmthethw #+# #+# */ /* Updated: 2017/09/18 09:35:01 by mmthethw ### ########.fr */ /* */ /* ************************************************************************** */ #include "ft_ls.h" static int ft_basic_list(t_data *lst, int flags) { while (lst) { ft_display_name(lst, flags); ft_putchar('\n'); lst = lst->next; } return (1); } int ft_display_list(t_data **lst, int flags) { ft_sort_list(lst, flags); if (!(flags & LS_L)) ft_basic_list(*lst, flags); else ft_display_detailed_list(*lst, flags); return (1); } void ft_display_name(t_data *l, int flags) { if (flags & LS_G) { if (S_ISDIR(l->mode)) ft_printf("%{cyan}%s%{eoc}", l->name); else ft_printf((S_IXUSR & l->mode) ? "%{red}%s%{eoc}" : "%s", l->name); } else ft_putstr(l->name); }
C
/* exercicios ordenados */ int main(){ int numeros[10]; int i, fim; int aux; for(i=0;i<10;i++){ printf("numeros[%i]: ",i); scanf("%i",&numeros[i]); } for(fim=9;fim>0;fim--){ for(i=0;i<=fim;i++){ if(numeros[i]>numeros[i+1]){ aux=numeros[i]; numeros[i]=numeros[i+1]; numeros[i+1]=aux; } } } for(i=0;i<10;i++){ printf("\nnumeros[%i]=%i",i,numeros[i]); } getch(); return 0; }
C
/* *Compute factorial of a number using iterative method * * */ #include <stdio.h> int main() { int n, i; long long int sum = 1; printf("Input a number to compute the factorial\n"); scanf("%d", &n); if (n <= 1) { printf("Input No = %d\tFactorial(%d) = 1\n", n, n); } else { for(i = n; i > 1; i--) { sum = sum * i; } printf("Input No = %d\tFactorial(%d!) = %lld\n", n, n, sum); } return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_lstmap.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: bmenant <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/11/26 11:20:24 by bmenant #+# #+# */ /* Updated: 2018/11/26 13:51:34 by bmenant ### ########.fr */ /* */ /* ************************************************************************** */ #include "libft.h" t_list *ft_lstmap(t_list *lst, t_list *(*f)(t_list *elem)) { t_list *lst_bis; t_list *beg_lst_bis; t_list *temp; if (lst) { temp = f(lst); if (!(lst_bis = ft_lstnew(temp->content, temp->content_size))) return (NULL); lst = lst->next; beg_lst_bis = lst_bis; while (lst != NULL) { temp = f(lst); if (!(lst_bis->next = ft_lstnew(temp->content, temp->content_size))) return (NULL); lst = lst->next; lst_bis = lst_bis->next; } return (beg_lst_bis); } return (NULL); }
C
#include <stdlib.h> #include <string.h> #include <errno.h> #include "SMO.h" #include "uart_term.h" static void SMO_Event_init(SMO_Event *Event); static void SMO_Event_setTime(SMO_Event *Event, uint8_t AlarmHour, uint8_t AlarmMin); static int SMO_Event_addMed(SMO_Event *Event, uint8_t nCmptmt, uint8_t nPills); static void SMO_Vector_init(SMO_Vector *Vec); static void SMO_Vector_free(SMO_Vector *Vec); static int SMO_Vector_addMed(SMO_Vector *Vec, SMO_PacketMed *Med); static SMO_Event *SMO_Vector_findNextEvent(SMO_Vector *Vec, uint8_t Hour, uint8_t Min); static int SMO_Control_addMedStr(SMO_Control *Ctrl, uint8_t nCmptmt, char *MedString, uint8_t Len); static void SMO_Event_init(SMO_Event *Event) { Event->AlarmHour = 0; Event->AlarmMin = 0; Event->Compartments = 0; memset(Event->nPills, 0, sizeof(Event->nPills)); } static void SMO_Event_setTime(SMO_Event *Event, uint8_t AlarmHour, uint8_t AlarmMin) { Event->AlarmHour = AlarmHour; Event->AlarmMin = AlarmMin; } static int SMO_Event_addMed(SMO_Event *Event, uint8_t nCmptmt, uint8_t nPills) { int Res = 0; if (nCmptmt >= SMO_MAX_COMPARTMENTS || ((Event->Compartments & (1 << nCmptmt)) != 0)) { UART_PRINT("Error adding medication\r\n"); Res = -EINVAL; goto Error; } Event->Compartments |= (1 << nCmptmt); Event->nPills[nCmptmt] = nPills; Error: return Res; } static void SMO_Vector_init(SMO_Vector *Vec) { Vec->Events = malloc(sizeof(void*)*SMO_VECTOR_MAX_SIZE); int i; for (i = 0; i < SMO_VECTOR_MAX_SIZE; ++i) { Vec->Events[i] = NULL; } Vec->Size = 0; } static void SMO_Vector_free(SMO_Vector *Vec) { int i; if (Vec->Events != NULL) { for (i = 0; i < SMO_VECTOR_MAX_SIZE; ++i) { free(Vec->Events[i]); Vec->Events[i] = NULL; } } free(Vec->Events); Vec->Events = NULL; Vec->Size = 0; } static int SMO_Vector_addMed(SMO_Vector *Vec, SMO_PacketMed *Med) { int Res = 0; SMO_Event *TmpEvent = NULL, *NewEvent = NULL; int i, AddIndex; if (Vec->Size >= SMO_VECTOR_MAX_SIZE) { Res = -EINVAL; UART_PRINT("Vector capacity full\r\n"); goto Error; } //events are sorted chronologically, with respect to time of day //find where medication should go and insert it AddIndex = Vec->Size; for (i = 0; i < Vec->Size; ++i) { TmpEvent = Vec->Events[i]; if (TmpEvent->AlarmHour == Med->AlarmHour && TmpEvent->AlarmMin == Med->AlarmMin) { UART_PRINT("Adding med to event at %02d:%02d in Cmptmt %d\r\n", TmpEvent->AlarmHour, TmpEvent->AlarmMin, Med->nCmptmt); SMO_Event_addMed(TmpEvent, Med->nCmptmt, Med->nPills); goto Success; } else if (TmpEvent->AlarmHour > Med->AlarmHour || (TmpEvent->AlarmHour == Med->AlarmHour && TmpEvent->AlarmMin > Med->AlarmMin)) { AddIndex = i; break; } } UART_PRINT("Creating new event for med at %02d:%02d in Cmptmt %d\r\n", Med->AlarmHour, Med->AlarmMin, Med->nCmptmt); //allocate memory for the new event NewEvent = malloc(sizeof(SMO_Event)); SMO_Event_init(NewEvent); SMO_Event_setTime(NewEvent, Med->AlarmHour, Med->AlarmMin); SMO_Event_addMed(NewEvent, Med->nCmptmt, Med->nPills); //shift other events if necessary Vec->Size++; for (i = AddIndex; i < Vec->Size; ++i) { TmpEvent = Vec->Events[i]; Vec->Events[i] = NewEvent; NewEvent = TmpEvent; } Error: Success: return Res; } static SMO_Event *SMO_Vector_findNextEvent(SMO_Vector *Vec, uint8_t Hour, uint8_t Min) { SMO_Event *Event = NULL; if (Vec->Size == 0) { goto Error; } //first element is default, e.g. if the given time is after all events //in vector, the next event will be the first event on the next day Event = Vec->Events[0]; int i; for (i = 0; i < Vec->Size; ++i) { if (Vec->Events[i]->AlarmHour > Hour || ((Vec->Events[i]->AlarmHour == Hour) && Vec->Events[i]->AlarmMin > Min)) { Event = Vec->Events[i]; break; } } Error: return Event; } void SMO_Timer_init(SMO_Timer *Timer) { Timer->Timing = false; Timer->Count = 0; } void SMO_Timer_start(SMO_Timer *Timer) { //start counting up to SMO event timeout, every minute Timer->Count = 0; Timer->Timing = true; Timer->Delaying = false; Timer->Delay = 0; } void SMO_Timer_stop(SMO_Timer *Timer) { //reset timer state Timer->Timing = false; Timer->Count = SMO_TIMER_DELAY; } void SMO_Control_init(SMO_Control *Ctrl) { SMO_Vector_init(&Ctrl->EventsVec); Ctrl->CurrentEvent = NULL; SMO_Timer_init(&Ctrl->Timer); int i; for (i = 0; i < SMO_MAX_COMPARTMENTS; ++i) { Ctrl->CompartmentStrings[i] = NULL; } } void SMO_Control_free(SMO_Control *Ctrl) { if (Ctrl->Timer.Timing) { SMO_Timer_stop(&Ctrl->Timer); } Ctrl->CurrentEvent = NULL; SMO_Vector_free(&Ctrl->EventsVec); int i; for (i = 0; i < SMO_MAX_COMPARTMENTS; ++i) { free(Ctrl->CompartmentStrings[i]); Ctrl->CompartmentStrings[i] = NULL; } } static int SMO_Control_addMedStr(SMO_Control *Ctrl, uint8_t nCmptmt, char *MedStr, uint8_t Len) { int Res = 0; char Str[SMO_PACKET_MED_PAYLOAD_SIZE]; if (nCmptmt >= SMO_MAX_COMPARTMENTS) { Res = -EINVAL; goto Error; } memset(Str, 0, sizeof(Str)); strncpy(Str, MedStr, Len); if (Ctrl->CompartmentStrings[nCmptmt] != NULL) { free(Ctrl->CompartmentStrings[nCmptmt]); } UART_PRINT("Adding med info in %d, %s\r\n", nCmptmt, Str); Ctrl->CompartmentStrings[nCmptmt] = strdup(Str); Error: return Res; } int SMO_Control_configure(SMO_Control *Ctrl, SMO_Packet *Pkt) { int Res = 0; //reset control before reconfiguring SMO_Control_free(Ctrl); SMO_Control_init(Ctrl); SMO_PacketMed *Med = NULL; int i; for (i = 0; i < Pkt->nMeds; ++i) { Med = &Pkt->Meds[i]; Res |= SMO_Vector_addMed(&Ctrl->EventsVec, Med); Res |= SMO_Control_addMedStr(Ctrl, Med->nCmptmt, Med->Payload, Med->Length); } return Res; } SMO_Event *SMO_Control_nextEvent(SMO_Control *Ctrl, uint8_t Hour, uint8_t Min) { return SMO_Vector_findNextEvent(&Ctrl->EventsVec, Hour, Min); } char *SMO_Control_getMedStr(SMO_Control *Ctrl, uint8_t nCmptmt) { char *Str = NULL; if (nCmptmt >= SMO_MAX_COMPARTMENTS) { goto Error; } Str = Ctrl->CompartmentStrings[nCmptmt]; Error: return Str; }
C
#ifndef _myQuadEEPROM_ #define _myQuadEEPROM_ #include <Arduino.h> #define CALSENS_DATA_VALID 0x15fc #define CALSENS_DATA_VALID_LOW 0xfc // pattern to detect valid config - low byte #define CALSENS_DATA_VALID_HIGH 0x15 // pattern to detect valid config - high byte #define CALMOTOR_DATA_VALID 0xEA03 #define CALMOTOR_DATA_VALID_LOW 0x03 // pattern to detect valid config - low byte #define CALMOTOR_DATA_VALID_HIGH 0xEA // pattern to detect valid config - high byte typedef struct { short valid; // should contain the valid pattern if a good config boolean magValid; // true if mag data valid short magMinX; // mag min x value short magMaxX; // mag max x value short magMinY; // mag min y value short magMaxY; // mag max y value short magMinZ; // mag min z value short magMaxZ; // mag max z value boolean accelValid; // true if accel data valid short accelMinX; // mag min x value short accelMaxX; // mag max x value short accelMinY; // mag min y value short accelMaxY; // mag max y value short accelMinZ; // mag min z value short accelMaxZ; // mag max z value } CALSENS_DATA; typedef struct { short valid; boolean motorValid; short motor1Cal; short motor2Cal; short motor3Cal; short motor4Cal; } CALMOTOR_DATA; // EEPROMErase() erases any current data in the EEPROM void EEPROMErase(); // calSensWrite() writes new data to the EEPROM void calSensWrite(CALSENS_DATA * calData); // calSensRead() reads existing data and returns true if valid else false in not. boolean calSensRead(CALSENS_DATA * calData); // motorCalWrite() writes new data to the EEPROM void motorCalWrite(CALMOTOR_DATA * calData); // motorCalRead() reads existing data and returns true if valid else false in not. boolean motorCalRead(CALMOTOR_DATA * calData); #endif
C
#include <mqueue.h> #include "messages.h" #include <pthread.h> #include "database.h" #include <assert.h> #include <stdlib.h> #include <stdio.h> #include <string.h> typedef struct Data Data; Data new_data(char * value1, float value2); /* Create a fresh empty database */ Response process_init(Request request); /* Add a new key to the database */ Response process_set(Request request); /* Retrieve a key from the database */ Response process_get(Request request); /* Modify an existing value in the database */ Response process_modify(Request request); /* Delete a given key from the database */ Response process_delete(Request request); /* Return a message with the number of entries in the database */ Response process_count(Request request); /* The entry point for a worker thread. Copies the buffer using a mutex, and sends a response */ void * process_request(void * buffer);
C
/* KR 5-17: Add a field-handling capability, so sorting may be done on fields * within lines, each field sorted according to an independent set of options. * * Solution Notes: * The inline flag is passed with -i. If a field has inline flag set, then * individual elements are sorted with a , delimiter. * * A field can be specified by including a number as the last argument in * a given flag, i.e. * * -df3 * * will do a fold-case directory sort on the 3rd field * * One global field is allowed, an arbitrary number of inline fields are * allowed. */ #include <stdio.h> #include <stdlib.h> #include <strings.h> #include <ctype.h> #include <math.h> #define MAXLINES 5000 #define MAXELEMENTS 1000 #define MAXOPTS 100 #define OPT_NUMERIC 0x1 #define OPT_REVERSE 0x2 #define OPT_FOLDCASE 0x4 #define OPT_DIR 0x8 #define OPT_INLINE 0x10 #define OPT_SENTINEL 0x20 #define MIN(a,b) ((a) < (b)) ? (a) : (b) char *lineptr[MAXLINES]; int readlines(char *lineptr[], int nlines); int split_fields(char *delimited, char **split); void getdir(char *s, char *t, size_t n); char *getfield(char *s, int field, size_t *n); int comp(char *s1, char *s2, int opts[2]); void writelines(char *lineptr[], int nlines); void sort_inplace(int opts[2], int nlines); void qsort_lomuto(void *lineptr[], int left, int right, int (*fieldopts)[2]); void swap(void *v[], int x, int y); int numcmp(const char *, const char *, size_t); int main(int argc, char **argv) { int nlines; int fieldopts[MAXOPTS][2]; int i; for(i = 0; *++argv != NULL; i++) { if((*argv)[0] == '-') { int field_num = 0; int opts = 0; while(*++*argv) { switch(**argv) { case 'd': opts |= OPT_DIR; break; case 'f': opts |= OPT_FOLDCASE; break; case 'i': opts |= OPT_INLINE; break; case 'n': opts |= OPT_NUMERIC; break; case 'r': opts |= OPT_REVERSE; break; default: if(isdigit(**argv)) { field_num = atoi(*argv); } } } fieldopts[i][0] = field_num; fieldopts[i][1] = opts; } } fieldopts[i][0] = -1; fieldopts[i][1] = OPT_SENTINEL; if((nlines = readlines(lineptr, MAXLINES)) >= 0) { i = 0; do { if(fieldopts[i][1] & OPT_INLINE) { sort_inplace(*(fieldopts+i), nlines); } else { qsort_lomuto((void **) lineptr, 0, nlines-1, fieldopts); } i++; } while(fieldopts[0][1] != OPT_SENTINEL && fieldopts[i][1] != OPT_SENTINEL); writelines(lineptr, nlines); return 0; } else { printf("Input too large to sort.\n"); return 1; } } void sort_inplace(int opts[2], int nlines) { int j; size_t n = 0; for(j = 0; j < nlines; j++) { int nfields; char *split[MAXELEMENTS]; char *t = getfield(*(lineptr+j), opts[0], &n); nfields = split_fields(t, split); int inline_opts[2] = { 0, opts[1] }; qsort_lomuto((void **) split, 0, nfields-1, &inline_opts); int k; for(k = 0; k < nfields; k++) { int l = 0; while(*(*(split+k)+l)) { *t++ = *(*(split+k)+l++); } if(k < nfields - 1) { *t++ = ','; } } } } int comp(char *s1, char *s2, int opts[2]) { int comp_raw; int (*comp_func)(const char *, const char *, size_t); size_t n, n1 = 0, n2 = 0; /* Get comparison method based on flags */ if(opts[1] & OPT_NUMERIC) { comp_func = numcmp; } else if(opts[1] & OPT_FOLDCASE) { comp_func = strncasecmp; } else { comp_func = strncmp; } /* Set comparison length if sorting on a field */ if(opts[0] > 0) { s1 = getfield(s1, opts[0], &n1); s2 = getfield(s2, opts[0], &n2); n = MIN(n1, n2); } else { n = MIN(strlen(s1), strlen(s2)); } /* Filter strings if doing dirsort */ if(opts[1] & OPT_DIR) { char t1[n+1]; char t2[n+1]; getdir(s1, t1, n); getdir(s2, t2, n); comp_raw = comp_func(t1, t2, n); } else { comp_raw = comp_func(s1, s2, n); } /* If two fields in a field sort returned equal, shorter one is first */ if(comp_raw == 0) { if(n1 < n2) { comp_raw = -1; } else if(n1 > n2) { comp_raw = 1; } } /* Invert result if reverse is set */ if(opts[1] & OPT_REVERSE) { comp_raw *= -1; } return comp_raw; } void getdir(char *s, char *t, size_t n) { char *tp = t; size_t i; for(i = 0; *s && i < n; i++) { if(isalnum(*s) || *s == ' ') { *tp++ = *s; } s++; } *tp = '\0'; } int split_fields(char *delimited, char **split) { int i; size_t j; i = 0; while(*delimited && !isspace(*delimited) && i < MAXELEMENTS) { for(j = 0; *(delimited+j) && !isspace(*(delimited+j)) && *(delimited+j) != ','; j++) ; if(j > 0) { *(split+i) = calloc(j, sizeof(char)); strncpy(*(split+i), delimited, j); i++; } if(!*(delimited+j) || isspace(*(delimited+j))) { break; } else { delimited += j + 1; } } return i; } char *getfield(char *s, int field, size_t *n) { /* Return a pointer to the given field in string s. If the passed field is * greater than the amount of fields, return a pointer to '\0'. * size_t n is passed by reference to provide the size of the field * that is returned. */ int i; char *t = NULL; while(isspace(*s)) { /* Skip initial spaces */ s++; } /* Advance s to correct field; fields are 1-indexed */ for(i = 1; *s != '\0' && i < field; i++) { while(!isspace(*s) && *s) { s++; } while(isspace(*s) && *s) { s++; } } t = s; for(*n = 0; !isspace(*s) && *s; (*n)++, s++) ; return t; } void qsort_lomuto(void *v[], int left, int right, int (*fieldopts)[2]) { /* qsort using Lomuto's pivot selection */ int pivot; /* Recursion exit condition: array has 1 element */ if(left >= right) { return; } /* Select pivot and move it to i[left]*/ swap(v, left, (right-left)/2 + left); /* Partition the list */ pivot = left; for(int x = left+1; x <= right; x++) { if(comp(v[x], v[left], *fieldopts) < 0) { swap(v, ++pivot, x); } } swap(v, pivot, left); // Move pivot from i[left] to the end of its partition /* qsort_lomuto each side of pivot */ qsort_lomuto(v, left, pivot-1, fieldopts); qsort_lomuto(v, pivot+1, right, fieldopts); } void swap(void *v[], int x, int y) { void *tmp; tmp = v[x]; v[x] = v[y]; v[y] = tmp; } int numcmp(const char *s1, const char *s2, size_t n) { double v1, v2; v1 = atof(s1); v2 = atof(s2); if(v1 < v2) { return -1; } else if (v1 > v2) { return 1; } else { return 0; } } int readlines(char *lineptr[], int nlines) { char *line = NULL; size_t n; int i; for(i = 0; getline(&line, &n, stdin) != -1; i++) { if(i == nlines) { /* Input larger than maximum line count */ return -1; } lineptr[i] = line; line = NULL; } return i; } void writelines(char *lineptr[], int nlines) { int i; for(i = 0; i < nlines; i++) { printf("%s", lineptr[i]); } }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdbool.h> #define prodN 100 // O trabalho foi divido em fun��es pois seria mais simples de organizar as rotinas // As vari�veis foram declaradas fora do main() para que elas sejam globais e possam ser acessadas por diferentes fun��es //Defini��o das vari�veis que ser�o utilizadas no trabalho //Quantidade maxima de produtos que podem ser cadastrados const int nProd = prodN; //Vari�veis que cont�m as informa��es dos produtos int codigo[prodN]; char* genero[prodN][100]; char* tamanho[prodN][4]; char* marca[prodN][100]; char* cor[prodN][100]; float valor[prodN]; char* linha[prodN][100]; int ano[prodN]; char* tipo[prodN][100]; char* estilo[prodN][100]; int estoque[prodN]; int qtdCadastrada = 0; //Fun��o que imprime a listagem dos produtos void relatorio(){ int i; int total = 0; system("cls"); printf("======================== \n"); printf("RELATORIO DE PRODUTOS \n"); printf("======================== \n"); // La�o que percorre a quantidade de produtos cadastrados. A vari�vel qtdCadastrada guarda esse n�mero for (i=0; i < qtdCadastrada; i++){ imprimeProduto(i); //Acumulador que soma os estques dos produtos total += estoque[i]; } printf("\nEstoque total: %d", total); //Fun��o que espera um caracter. Usado para para a execu��o. Qualquer tecla que seja clicada continua a execu��o getche(); } //Fun��o que imprime os dados de um produto espec�fico void imprimeProduto(int aux){ printf("\n-------------------------\n"); printf("CODIGO %d\n", codigo[aux]); printf("GENERO %s\n", genero[aux]); printf("TAMANHO %s\n",tamanho[aux]); printf("MARCA %s\n", marca[aux]); printf("VALOR %.2f\n", valor[aux]); printf("LINHA %s\n", linha[aux]); printf("ANO %d\n", ano[aux]); printf("ESTILO %s\n", estilo[aux]); printf("TIPO %s\n", tipo[aux]); printf("-------------------------\n"); } //Fun��o que representa uma compra de produto; void compra(){ char continua = 's'; int aux; //La�o se repete enquanto continua � igual a "s", ou seja, enquanto queremos cadastrar compras while (continua == 's'){ char op = 'n'; system("cls"); printf("======================== \n"); printf("COMPRA\n"); printf("======================== \n"); //Testa se a vari�vel qtdCadastrada � igual a zero, se sim, indica que nenhum produto foi cadastrado if (qtdCadastrada == 0){ printf("Nenhum produto cadastrado!"); getche(); //Finaliza a exeu��o da fun��o return; } while (op != 's' && op != 'S'){ system("cls"); printf("======================== \n"); printf("COMPRA\n"); printf("======================== \n"); //L� o c�digo do produto que o estoque ser� atualizado printf("Informe o codigo do produto ou '-1' para sair: "); scanf("%d", &aux); if (aux == -1){ return; } aux = busca_cod(aux); //Testa se o c�digo informado � v�lido if (aux < 0){ printf("\nCodigo Invalido!"); getche(); } else { imprimeProduto(aux); printf("Continua (s/n)? "); op = getche(); } } system("cls"); printf("======================== \n"); printf("COMPRA\n"); printf("======================== \n"); imprimeProduto(aux); int qtd; //l� a quantidade de produtos comprados printf("Quantidade comprada: "); scanf("%d", &qtd); //Atualiza o estoque do produto. O operador += soma o valor que est� guardado em estoque[aux] com o valor qtd e //guarda o resultado em estoque[aux] estoque[aux] += qtd; printf("\n\nCadastrar outra compra (s/n)?: "); continua = getche(); //Atribue -1 a aux para que outro c�digo seja informado, aux = -1; } } int busca_cod(int cod){ int i; for (i = 0; i < qtdCadastrada; i++){ if(codigo[i] == cod){ return i; } } return -1; } void cadstro(){ int i; int aux; char opcao = 's'; int cadastros; system("cls"); printf("======================== \n"); printf("CADASTRO DE PRODUTOS \n"); printf("======================== \n"); printf("\nQuantas pecas voce deseja cadastrar?"); scanf("%d", &cadastros); //Executa o trecho entquanto o usua�rio quiser cadastrar produtos ou at� o limite ser atingido for (i = 0; i < cadastros && qtdCadastrada < prodN; i ++){ system("cls"); printf("======================== \n"); printf("CADASTRO DE PRODUTOS \n"); printf("======================== \n"); //1 printf("\nInsira o codigo do produto %d: ", i + 1); scanf("%d", &codigo[qtdCadastrada]); //2 printf("\nInsira o genero da peca %d (masculino ou feminino): ", i + 1); scanf("%s", &genero[qtdCadastrada]); //3 printf("\nInsira o tamanho da peca %d (PP, P, M, G, GG ou XGG): ", i + 1); scanf("%s", &tamanho[qtdCadastrada]); //4 printf("\nInsira o marca da peca %d: ", i + 1); scanf("%s", &marca[qtdCadastrada]); //5 printf("\nInsira a cor da peca %d: ", i + 1); scanf("%s", &cor[qtdCadastrada]); //6 printf("\nInsira a valor da peca %d: ", i + 1); scanf("%f", &valor[qtdCadastrada]); //7 printf("\nInsira o linha da peca %d: ", i + 1); scanf("%s", &linha[qtdCadastrada]); //8 printf("\nInsira o ano da peca %d: ", i + 1); scanf("%d", &ano[qtdCadastrada]); //9 printf("\nInsira o estilo da peca %d: ", i + 1); scanf("%s", &estilo[qtdCadastrada]); //10 printf("\nInsira o tipo da peca %d: ", i + 1); scanf("%s", &tipo[qtdCadastrada]); //Atualiza a quantidade de produtos cadastrados. O operador ++ soma +1 no valor contido em qtdCadastrada qtdCadastrada++; printf("\nCadastro realizado com sucesso !"); getche(); } } void consultar(){ int aux2; int i = 0; int t_int; char* t_str[100]; float t_float; bool flag; flag = false; system("cls"); printf("======================== \n"); printf("CONSULTAR PRODUTOS\n"); printf("======================== \n"); if (qtdCadastrada == 0){ printf("Nenhum produto cadastrado!"); getche(); //Finaliza a exeu��o da fun��o return; } printf("Digite o numero referente ao filtro que voce deseja usar em sua cosultar"); printf("\n1\tCodigo\n2\tGenero\n3\tTamanho\n4\tMarca\n5\tCor\n6\tValor\n7\tLinha\n8\tAno de Lancamento\n9\tEstilo\n10\tTipo\n"); scanf("%d", &aux2); switch(aux2){ case 1 : printf("\nInsira o codigo que voce esta procurando: "); scanf("%d", &t_int); for(i = 0; i < qtdCadastrada; i++){ if (codigo[i] == t_int){ flag = true; imprimeProduto(i); } } if (!flag){ printf("\nNenhum produto encontrado"); } break; case 2 : printf("\nInsira o genero que voce esta procurando: "); scanf("%s", &t_str); for(i = 0; i < qtdCadastrada; i++){ if (strcmp(t_str, genero[i]) == 0){ imprimeProduto(i); flag = true; } } if (!flag){ printf("\nNenhum produto encontrado"); } break; case 3: printf("\nInsira o tamanho que voce esta procurando: "); scanf("%s", &t_str); for(i = 0; i < qtdCadastrada; i++){ if (strcmp(t_str, tamanho[i]) == 0){ imprimeProduto(i); flag = true; } } if (!flag){ printf("\nNenhum produto encontrado"); } break; case 4 : printf("\nInsira o marca que voce esta procurando: "); scanf("%s", &t_str); for(i = 0; i < qtdCadastrada; i++){ if (strcmp(t_str, marca[i]) == 0){ imprimeProduto(i); flag = true; } } if (!flag){ printf("\nNenhum produto encontrado"); } break; case 5 : printf("\nInsira o cor que voce esta procurando: "); scanf("%s", &t_str); for(i = 0; i < qtdCadastrada; i++){ if (strcmp(t_str, cor[i]) == 0){ imprimeProduto(i); flag = true; } } if (!flag){ printf("\nNenhum produto encontrado"); } break; case 6 : printf("\nInsira o valor que voce esta procurando: "); scanf("%f", &t_float); for(i = 0; i < qtdCadastrada; i++){ if (t_float == valor[i]){ imprimeProduto(i); flag = true; } } if (!flag){ printf("\nNenhum produto encontrado"); } break; case 7 : printf("\nInsira o linha que voce esta procurando: "); scanf("%s", &t_str); for(i = 0; i < qtdCadastrada; i++){ if (strcmp(t_str, linha[i]) == 0){ imprimeProduto(i); flag = true; } } if (!flag){ printf("\nNenhum produto encontrado"); } break; case 8 : printf("\nInsira o ano que voce esta procurando: "); scanf("%d", &t_int); for(i = 0; i < qtdCadastrada; i++){ if (t_int == ano[i]){ imprimeProduto(i); flag = true; } } if (!flag){ printf("\nNenhum produto encontrado"); } break; case 9 : printf("\nInsira o estilo que voce esta procurando: "); scanf("%s", &t_str); for(i = 0; i < qtdCadastrada; i++){ if (strcmp(t_str, estilo[i]) == 0){ imprimeProduto(i); flag = true; } } if (!flag){ printf("\nNenhum produto encontrado"); } break; case 10 : printf("\nInsira o tipo que voce esta procurando: "); scanf("%s", &t_str); for(i = 0; i < qtdCadastrada; i++){ if (strcmp(t_str, tipo[i]) == 0){ imprimeProduto(i); flag = true; } } if (!flag){ printf("\nNenhum produto encontrado"); } break; } getche(); } void editar(){ int t_int, cod; system("cls"); printf("======================== \n"); printf("EDITAR PRODUTO\n"); printf("======================== \n"); printf("\nInsira o codigo que voce esta procurando: "); scanf("%d", &t_int); cod = busca_cod(t_int); if (cod == -1){ printf("\nCodigo Invalido!"); getche(); return; } else { imprimeProduto(cod); printf("\Insira as novas informa��es:\n"); //1 printf("\nInsira o codigo do produto: "); scanf("%d", &codigo[cod]); //2 printf("\nInsira o genero da peca (masculino ou feminino): "); scanf("%s", &genero[cod]); //3 printf("\nInsira o tamanho da peca (PP, P, M, G, GG ou XGG): "); scanf("%s", &tamanho[cod]); //4 printf("\nInsira o marca da peca: "); scanf("%s", &marca[cod]); //5 printf("\nInsira a cor da peca: "); scanf("%s", &cor[cod]); //6 printf("\nInsira a valor da peca: "); scanf("%f", &valor[cod]); //7 printf("\nInsira o linha da peca: "); scanf("%s", &linha[cod]); //8 printf("\nInsira o ano da peca: "); scanf("%d", &ano[cod]); //9 printf("\nInsira o estilo da peca: "); scanf("%s", &estilo[cod]); //10 printf("\nInsira o tipo da peca: "); scanf("%s", &tipo[cod]); printf("\nEdicao concluida!"); getche(); } } //Fun��o principal do C, engloba o Menu do trabalho void main(void){ int i; //Inicializa o vetor estoque com 0's para que a linha 115 possa ser executada (ou seja, utilzar o operador +=) for (i = 0; i < nProd; i++){ estoque[i] = 0; } char opcao = 'n'; while (opcao != 's' && opcao != 'S'){ system("cls"); printf("======================== \n"); printf("MENU\n"); printf("======================== \n"); printf("1 - Cadastro\n"); printf("2 - Compra\n"); printf("3 - Relatorio\n"); printf("4 - Consultar\n"); printf("5 - Editar\n"); printf("S - Sair\n"); printf("-------------------------\n"); printf("Digite uma opcao: "); opcao = getche(); // Direciona a execu��o para alguma das op��es if (opcao == '1'){ cadstro(); } else if (opcao == '2'){ compra(); } else if (opcao == '3'){ relatorio(); } else if (opcao == '4'){ consultar(); } else if (opcao == '5'){ editar(); } } }
C
// Dimensions.h #ifndef DIMENSIONS_H #define DIMENSIONS_H #include <kernel/OS.h> #include <game/WindowScreen.h> // the possible resolutions extern uint32 color_spaces[]; // the names of the resolutions extern char *color_space_names[]; // the number of color spaces extern size_t color_spaces_count; enum { CURRENT_WORKSPACE_DIMENSIONS = 0 }; inline void get_dimensions_for(uint32 space, int32 *w, int32 *h) { switch (space) { case B_8_BIT_640x480: *w = 640; *h = 480; break; case B_8_BIT_800x600: *w = 800; *h = 600; break; case B_8_BIT_1024x768: *w = 1024; *h = 768; break; case B_8_BIT_1152x900: *w = 1152; *h = 900; break; case B_8_BIT_1280x1024: *w = 1280; *h = 1024; break; case B_8_BIT_1600x1200: *w = 1600; *h = 1200; break; } } inline uint32 color_space_for(int32 w, int32) { if (w <= 640) return B_8_BIT_640x480; if (w <= 800) return B_8_BIT_800x600; if (w <= 1024) return B_8_BIT_1024x768; if (w <= 1152) return B_8_BIT_1152x900; if (w <= 1280) return B_8_BIT_1280x1024; // if (w <= 1600) // return B_8_BIT_1600x1200; return B_8_BIT_1600x1200; } #endif // DIMENSIONS_H
C
#include<stdio.h> #include <stdlib.h> int i = 3; typedef struct node { int value1; struct node *nxt; } node ; typedef struct stack { node *top; } str; void push(str *,int); int pop(str *); void display(str *); str initStack() { str st ; st.top = NULL ; return st ; } int main() { int j,k,a,b; int value=0; str top1 = initStack() ; str top2 = initStack() ; str top3 = initStack() ; for(j=1;j<i+1;j++) { push(&top1,j); } printf("A kulesi: "); display(&top1); printf("B kulesi: "); display(&top2); printf("C kulesi: "); display(&top3); printf("--------------------\n"); for(k=1;k < 1<<i ;k++) { a=(k&k-1)%3; b=((k|k-1)+1)%3; switch(a) { case 0: value=pop(&top1); break; case 1: value=pop(&top2); break; case 2: value=pop(&top3); break; } switch(b) { case 0: push(&top1,value); break; case 1: push(&top2,value); break; case 2: push(&top3,value); break; } printf("A kulesi: "); display(&top1); printf("B kulesi: "); display(&top2); printf("C kulesi: "); display(&top3); printf("--------------------\n"); } } void push(str *s,int t) { node *n1 = (node*)malloc(sizeof(node)) ; n1->value1 = t; n1->nxt = s->top ; s->top = n1 ; } int pop(str *s) { node *n2 = s->top ; s->top = n2->nxt ; char ch = n2->value1 ; free(n2) ; return ch; } void display(str *st) { node *s = st->top ; while(s!=NULL) { printf("%d ",s->value1); s = s->nxt ; } printf("\n"); }
C
/****************************************************************************/ /* _FSSetDate.c ** ** Created by FileSystem VectorPort tool. (FSVPTool 53.23) ** ** :ts=4 ** */ /****************************************************************************/ #include "all_includes.h" /****************************************************************************/ /* ** ================================================================== ** This string input function can have a NULL reference lock to ** indicate a root directory relative object name string, ** The string name may also be a nul-string to indicate the relative ** lock object should be used, and both conditions may also occur to ** indicate a root directory reference, all these situations must be ** handled here appropriately. ** See the FSLock() autodoc for example code to handle this. ** ================================================================== */ /* ** ================================================================== ** The FSetXXXX() functions must also cause a change update, however, ** this must begin at the objects parent dir and not on the object, ** as this will interfere with multiple successive attribute changes ** for operations such as clone file copying. ** ================================================================== */ static int32 do_setdate(APTR dummy UNUSED,...) { return 0; /* Write me ! */ } /****************************************************************************/ int32 FSSetDate(struct FSVP *vp, int32 *res2, struct Lock *dirlock, CONST_STRPTR objname, const struct DateStamp *ds) { struct GlobalData *gd = vp->FSV.FSPrivate; struct ObjLock * lock = (struct ObjLock *)dirlock; int32 result; IEXEC->ObtainSemaphore(gd->Sem); result = do_setdate(gd,res2,lock,objname,ds); IEXEC->ReleaseSemaphore(gd->Sem); return(result); } /****************************************************************************/ /** NAME ACTION_SET_DATE - FSSetDate() SYNOPSIS int32 RESULT1 = FSSetDate(struct FileSystemVectorPort *fsvp, int32 *result2, struct Lock *rel, CONST_STRPTR name, const struct DateStamp *date); FUNCTION This action allows an application to set an object's creation date. Sets the date for a file or directory. To handle the 'rel' and 'name' parameters correctly, use the example code shown in ACTION_LOCATE_OBJECT / FSLock() autodoc. INPUTS (FileSystemVectorPort method) fsvp - (struct FileSystemVectorPort *) Pointer to the vector port. result2 - (int32 *) Pointer to the storage area for RESULT2. rel - (struct Lock *) Pointer to the 'name' reference dir lock. name - (CONST_STRPTR) Pointer to the object name.(no path component) date - (const struct DateStamp *) Pointer to a struct DateStamp. RESULT1 - (int32) Success/failure (DOSTRUE/FALSE) (FALSE on error). RESULT2 - (int32) Failure code if RESULT1 == FALSE INPUTS (DosPacket method) dp_Type - (int32) ACTION_SET_DATE dp_Arg1 - <unused> 0 dp_Arg2 - (BPTR) Lock to which dp_Arg3 is relative. dp_Arg3 - (BSTR) Name of object relative to dp_Arg2 dp_Arg4 - (struct DateStamp *) Datestamp to set object to. (Not a BPTR). dp_Arg5 - (BSTR) Nametype - name format indicator value. if(dp_Arg3==dp_Arg5) then all BSTR's are guaranteed to be nul-terminated. (53.23) RESULT1 - (int32) Success/failure (DOSTRUE/FALSE) (FALSE on error). RESULT2 - (int32) Failure code if RESULT1 == FALSE SEE ALSO IDOS->SetDate() **/ /****************************************************************************/ /* EOF */
C
#include <iostream.h> #include <conio.h> int a[50]; void merge(int,int,int); void merge_sort(int low,int high) { int mid; if(low<high) { mid=(low+high)/2; merge_sort(low,mid); merge_sort(mid+1,high); merge(low,mid,high); } } void merge(int low,int mid,int high) { int h,i,j,b[50],k; h=low; i=low; j=mid+1; while((h<=mid)&&(j<=high)) { if(a[h]<=a[j]) { b[i]=a[h]; h++; } else { b[i]=a[j]; j++; } i++; } if(h>mid) { for(k=j;k<=high;k++) { b[i]=a[k]; i++; } } else { for(k=h;k<=mid;k++) { b[i]=a[k]; i++; } } for(k=low;k<=high;k++) a[k]=b[k]; } void main() { int num,i; cout<<"******************************************************************* *************"<<endl; cout<<" MERGE SORT PROGRAM "<<endl; cout<<"******************************************************************* *************"<<endl; cout<<endl<<endl; cout<<"Masukkan Banyak Bilangan: ";cin>>num; cout<<endl; cout<<"Sekarang masukkan "<< num <<" Bilangan yang ingin Diurutkan :"<<endl; for(i=1;i<=num;i++) { cout<<"Bilangan ke-"<<i<<" ";cin>>a[i] ; } merge_sort(1,num); cout<<endl; cout<<"Hasil akhir pengurutan :"<<endl; cout<<endl; for(i=1;i<=num;i++) cout<<a[i]<<" "; cout<<endl<<endl<<endl<<endl; getch(); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* write_dir_label_fd.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: cwitting <cwitting@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/03/17 03:06:21 by cwitting #+# #+# */ /* Updated: 2020/03/17 03:14:19 by cwitting ### ########.fr */ /* */ /* ************************************************************************** */ #include "asm.h" static void case_1_local(int label_bc, int fd, int dir_size) { unsigned test; unsigned res; test = (unsigned)label_bc; if (dir_size == 2) { test = test & 0xffff; res = ((test << 8) | (test >> 8)) & 0xffff; } else if (dir_size == 4) res = ((test << 24) | (test >> 24)) & 0xffffffff; write(fd, &res, dir_size); } static void case_2_local(int label_bc, int fd, int dir_size) { unsigned test; unsigned res; test = (unsigned)label_bc; if (dir_size == 2) { test = test & 0xffff; res = (((test >> 8) & 0xff) | ((test << 8) & 0xff00)); } else if (dir_size == 4) { test = test & 0xffffffff; res = (((test << 24) & 0xff000000) | ((test << 8) & 0xff0000) | ((test >> 8) & 0xff00) | ((test >> 24) & 0xff)); } write(fd, &res, dir_size); } void write_dir_label_fd(int label_bc, int fd, int dir_size) { if (label_bc >= 0) case_1_local(label_bc, fd, dir_size); else case_2_local(label_bc, fd, dir_size); }
C
#ifndef POSPOPCNT_H #define POSPOPCNT_H #include <stdint.h> #if defined(__clang__) #pragma clang loop vectorize(disable) #elif defined(__GNUC__) __attribute__((optimize("no-tree-vectorize"))) #endif // given a stream of len 16-bit words (in data), generates // an histogram of 16 counts stored in flags, corresponding // to the number of bit sets at the corresponding indexes (0,1,...,15). static void pospopcnt_u16_scalar(const uint16_t *data, uint32_t len, flags_type *flags) { for (int i = 0; i < len; ++i) { uint64_t w = data[i]; flags[0] += ((w >> 0) & 1); flags[1] += ((w >> 1) & 1); flags[2] += ((w >> 2) & 1); flags[3] += ((w >> 3) & 1); flags[4] += ((w >> 4) & 1); flags[5] += ((w >> 5) & 1); flags[6] += ((w >> 6) & 1); flags[7] += ((w >> 7) & 1); flags[8] += ((w >> 8) & 1); flags[9] += ((w >> 9) & 1); flags[10] += ((w >> 10) & 1); flags[11] += ((w >> 11) & 1); flags[12] += ((w >> 12) & 1); flags[13] += ((w >> 13) & 1); flags[14] += ((w >> 14) & 1); flags[15] += ((w >> 15) & 1); } } #endif // POSPOPCNT_H
C
#include<stdio.h> // ϱ⿡ ռ, Լ ϳĴ // ǹ ִµ ص // Լ ˰ ־ ذ ȴٰ ؼ // Լ մϴ. // ! ! ! // mainȿ ִ оּ! int a; // ʱȭ X int b = 10; // ʱȭ O char c = 'P'; // Լ ˾ƺ! void fuc(); int main() { // ? // // Ư ڵ ȿ ϸ // main , ٸ Լ ̰ // for(int i = 0 ; i < 10; i++) i for ȿ // ̹Ƿ ̴. // ̷ Ư¡ // 1. Ư ڵ ȿ ϴٴ ( ڵ尡 ޸𸮿 ) // 2. ޸ ٴ // 3. ڵ带 ʱȭ Ǵ // ִ. // // α׷ ü ϸ // Լ ۿ Ѵ. // ҽ ڵ ȿ ̰ ٸ ҽ ڵ忡 ִ. ( <- ٸ ҽ 𸥴...) // ̷ Ư¡ // 1. α׷ ü ϴٴ // 2. ޸𸮴 ٴ // 3. ʱȭ ʾƵ 0 ̶ ڵ ٴ // ִ. // ū // ٸ Լ (α׷ ü) ϳ Ұϳİ Ŭ ̴. // غϱ // ߽ϴ. // 2- ʿ ֽϴ. // Լ ȣ printf("a = %d b = %d c = %c\n",a,b,c); fuc(); printf("a = %d b = %d c = %c\n", a, b, c); // a ϸ鼭 ʱȭ ʾұ // ó 0 ߰ // Լ ȣ Ŀ // a , // b Կڸ 30 ü, // c W ü // ̷ α׷ ü ϴ ( ϴ) } void fuc() { a++; b = 30; c = 'W'; }
C
// // Created by Xiaowei Min on 2019-02-13. // #include <stdbool.h> #include <stdlib.h> #include <stdio.h> #include <memory.h> #include <unistd.h> #include "ncurses.h" #include "window.h" bool window_init(window_t *rval, int num_rows, int num_cols) { rval->num_rows = num_rows; rval->num_cols = num_cols; rval->pval = (char*)malloc(sizeof(char) * num_rows * num_cols); if(rval->pval != NULL) memset(rval->pval, '*', num_rows * num_cols); return rval->pval != NULL; } void window_print(window_t *pwindow) { char *tmp = pwindow->pval; for(int i = 0; i < pwindow->num_rows; ++i) { for(int j = 0; j < pwindow->num_cols; ++j) addch(*(tmp++)); addch('\n'); } refresh(); } void window_log(window_t *pwindow, FILE *fout) { char *tmp = pwindow->pval; for(int i = 0; i < pwindow->num_rows; ++i) { for(int j = 0; j < pwindow->num_cols; ++j) fputc(*(tmp++), fout); fputc('\n', fout); } fflush(fout); } char* window_get(window_t *pwindow, int x, int y) { if(x < 0 || x >= pwindow->num_rows || y < 0 || y >= pwindow->num_cols) return NULL; return pwindow->pval + (x * pwindow->num_cols) + y; } int max(int a, int b) { return a > b ? a : b; } int do_window_count(window_t *pwindow, int x, int y, int dx, int dy) { int ans = 0; char ch_std = *window_get(pwindow, x, y); x += dx; y += dy; while(x > -1 && x < pwindow->num_rows && y > -1 && y < pwindow->num_cols && (*(window_get(pwindow, x, y)) == ch_std)) { ++ans; x += dx; y += dy; } return ans; } int window_count(window_t *pwindow, int x, int y) { const int dx[] = {1, 1, 0, -1}; const int dy[] = {0, 1, 1, 1}; int ans = 0; for(int i = 0; i < 4; ++i) ans = max(ans, 1 + do_window_count(pwindow, x, y, dx[i], dy[i]) + do_window_count(pwindow, x, y, -dx[i], -dy[i])); return ans; } void window_destroy(window_t *pwindow) { free(pwindow->pval); }
C
#include<stdio.h> int main(void){ printf("%d\n", 5/3); printf("%f\n", 5/3); printf("%f\n", (float)5/3); }
C
#include "sim.h" #include "util/cfgParser.h" #include "util/algebra.h" int main(int argc, char *argv[]) { char *cfg; char *m; int mode = 0; // simulator mode: 0 = simulate, 1 = render if (argc < 3) { printf("No config file!\n"); printf("Usage: ./Vortexy <-s / -r> <sim.cfg>\n"); cfg = "sim.cfg"; // default } else { m = argv[1]; cfg = argv[2]; if (strcmp(m, "-s") == 0) { // simulation mode mode = 0; } if (strcmp(m, "-r") == 0) { // rendering mode mode = 1; } } char *date = currentDateTime(); printf("Vortexy Roninkoi (roninkoi@iki.fi) %s\n", date); free(date); struct Sim sim; sim.mode = mode; // initialize simulation s_init(&sim); // load simulation configuration simParser(&sim, cfg); // start s_run(&sim); printf("Closing\n"); return 0; }
C
# include <stdio.h> # include <cs50.h> int main (void) { int i; i = GetInt(); int numBits = sizeof(int) * 8; bool start = false; for( int j = numBits - 1;j >= 0;j--) { if ((i & (1 << j))) start = true; if (start) printf("%s", i & (1 << j)? "1":"0"); } printf("\n"); return 0; }
C
/* * CSE 109 * Calvin Tong * cyt219 * implements the getopts prototype defined in prog2.c, parses the args the user enters * Program #2 */ #include <string.h> #include <stdlib.h> #include <stdio.h> /* * parses the users command line argument and returns them in a string array * @param command that the user types in stdin * @return char** the string array holding the tokenized cmdline args with a 0 as the last element */ char **getopts(char cmd[]) { //the string array that will hold the parsed command line args char **strarray; //copy the array into a new string array so we can use strtok to count the args without editing //the original string int len = strlen(cmd); char copy[len + 1]; strcpy(copy, cmd); //the number of tokens that have been read int tokcount = 0; //count the number of tokens in the inputed array //gets the first token in the string char *token = strtok(copy, " "); while(token != NULL) { //increment the token counter tokcount++; //grab the next token token = strtok(NULL, " "); } //use the number of tokens found to dynamically allocate the string array //adding 1 because we need to put a 0 onto the end of the array strarray = malloc((tokcount + 1) * sizeof(char*)); //reset the tok count to 0 for the second iteration //on this iteration it is used as an index rather than just a count tokcount = 0; //since the copied array has been modified during the token count use the cmd array //for the second iteration //grab the first token token = strtok(cmd, " "); while(token != NULL) { //use the length of the token to dynamically allocate elements of strarray //adding one to acomidate the null termination strarray[tokcount] = malloc((strlen(token) + 1) * sizeof(char)); //copy the token into the correct index of the string array strcpy(strarray[tokcount], token); //increment the token count tokcount++; //grab the next token token = strtok(NULL, " "); } //put a 0 onto the end of the array and then return the parsed opts strarray[tokcount] = 0; return strarray; }
C
#include <stdio.h> int main() { int n; // number of lines and columns int i, j; // aux variables scanf("%d", &n); int matrix[n][n]; for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { scanf("%d", &matrix[i][j]); } } int pdiag_sum = 0, sdiag_sum = 0, sum_line, sum_column; // variables that represents the sum value int evensum_lines = 0, oddsum_columns = 0; // variables to count number of lines and columns with even or odd sums for (i = 0; i < n; i++) { sum_column = 0; sum_line = 0; for (j = 0; j < n; j++) { // calculates the sum of principal diagonal arguments if (i == j) { pdiag_sum = pdiag_sum + matrix[i][j]; } // calculates the sum of secondary diagonal arguments if ((i + j) == (n - 1)) { sdiag_sum += matrix[i][j]; } sum_line = sum_line + matrix[j][i]; // calculates the sum of the arguments in a given line sum_column = sum_column + matrix[i][j]; //calculates the sum of the arguments in a given column } // condition to check if the sum of the arguments in a given line is even if ((sum_line % 2) == 0) { evensum_lines = evensum_lines + 1; } // condition to check if the sum of the arguments in a given column is odd if ((sum_column % 2) != 0) { oddsum_columns = oddsum_columns + 1; } } printf("%d %d %d %d", pdiag_sum, sdiag_sum, evensum_lines, oddsum_columns); return 0; } // valgrind --leak-check=full ./lab01 < arq01.in
C
#include "thermometer.h" #include "one_wire.h" #include "crc.h" #include <stdio.h> #include <string.h> //----------------------------------------------------------------// // Класс термометра // //----------------------------------------------------------------// typedef struct ClassThermometer { /*public:*/ Thermometer m_thermometer; /*private:*/ uint8_t m_lowAlarmTrigger; uint8_t m_highAlarmTrigger; uint16_t m_temperature; uint64_t m_serialNumber; Resolution m_resolution; ThermometerName m_name; } ClassThermometer; //----------------------------------------------------------------// // Параметры термометра по умолчанию // //----------------------------------------------------------------// static const uint8_t default_low_alarm_trigger = (uint8_t)-55; static const uint8_t default_high_alarm_trigger = (uint8_t)125; static const uint16_t default_temperature = 0x0550; static const uint64_t no_serial_number = 0; static const Resolution default_resolution = RES_12BITS; static const ThermometerName default_name = "thermometer"; static const uint32_t conversion_time[] = { 94, 188, 375, 750 }; //----------------------------------------------------------------// // Методы класса термометра // //----------------------------------------------------------------// uint16_t getThermometerTemperature(void); uint64_t getThermometerSerialNumber(void); uint32_t getThermometerConversionTime(void); bool isThermometerTriggered(void); void setThermometerName(const ThermometerName name); void getThermometerName(ThermometerName name); void setThermometerLowAlarmTrigger(const int8_t lowAlarmTrigger); int8_t getThermometerLowAlarmTrigger(void); void setThermometerHighAlarmTrigger(const int8_t highAlarmTrigger); int8_t getThermometerHighAlarmTrigger(void); void setThermometerResolution(const Resolution resolution); Resolution getThermometerResolution(void); void updateThermometerParameters(void); //----------------------------------------------------------------// // Счётчик экземпляров класса термометра // //----------------------------------------------------------------// static uint32_t thermometerCounter = 0; static Thermometer *thermometerPtr = 0; static ClassThermometer thermometer = { .m_thermometer = { .getTemperature = getThermometerTemperature, .getSerialNumber = getThermometerSerialNumber, .getConversionTime = getThermometerConversionTime, .isTriggered = isThermometerTriggered, .setName = setThermometerName, .getName = getThermometerName, .setLowAlarmTrigger = setThermometerLowAlarmTrigger, .getLowAlarmTrigger = getThermometerLowAlarmTrigger, .setHighAlarmTrigger = setThermometerHighAlarmTrigger, .getHighAlarmTrigger = getThermometerHighAlarmTrigger, .setResolution = setThermometerResolution, .getResolution = getThermometerResolution, }, .m_lowAlarmTrigger = default_low_alarm_trigger, .m_highAlarmTrigger = default_high_alarm_trigger, .m_temperature = default_temperature, .m_serialNumber = no_serial_number, .m_resolution = default_resolution }; static void initThermometer(ClassThermometer *thermometer) { thermometerCounter++; sprintf(thermometer->m_name, "%s_%i", default_name, thermometerCounter); getThermometerSerialNumber(); updateThermometerParameters(); } const Thermometer *getThermometer(void) { if (thermometerPtr == 0) { initThermometer(&thermometer); thermometerPtr = &thermometer.m_thermometer; } return thermometerPtr; } //----------------------------------------------------------------// // Геттер температуры термометра // //----------------------------------------------------------------// uint16_t getThermometerTemperature(void) { getOneWire()->open(); if (getOneWire()->isBusy() == true) { getOneWire()->close(); return thermometer.m_temperature; } uint8_t data[NUMBER_OF_REGISTERS] = { 0 }; #if (NUMBER_OF_THERMOMETERS == 1) getOneWire()->makeTransaction(SKIP_ROM, no_serial_number, READ_SCRATCHPAD, (char *)&data); #if defined(USE_CRC8) if (crc8((char *)&data, 9) == 0) #endif { uint16_t temperature = (data[TEMPERATURE_MSB] << 8) | data[TEMPERATURE_LSB]; thermometer.m_temperature = temperature; } getOneWire()->makeTransaction(SKIP_ROM, no_serial_number, CONVERT_T, 0); getOneWire()->close(); #else #endif //NUMBER_OF_THERMOMETERS return thermometer.m_temperature; } //----------------------------------------------------------------// // Геттер серийного номера термометра // //----------------------------------------------------------------// uint64_t getThermometerSerialNumber(void) { if (thermometer.m_serialNumber != no_serial_number) { return thermometer.m_serialNumber; } getOneWire()->open(); if (getOneWire()->isBusy() == true) { getOneWire()->close(); return thermometer.m_serialNumber; } uint64_t serialNumber = 0; #if (NUMBER_OF_THERMOMETERS == 1) getOneWire()->open(); getOneWire()->makeTransaction(READ_ROM, no_serial_number, NONE, (char *)&serialNumber); getOneWire()->close(); #if defined(USE_CRC8) if (crc8((char *)&serialNumber, 8) == 0) #endif { thermometer.m_serialNumber = serialNumber; } #else #endif //NUMBER_OF_THERMOMETERS return thermometer.m_serialNumber; } //----------------------------------------------------------------// // Геттер времени измерения температуры // //----------------------------------------------------------------// uint32_t getThermometerConversionTime(void) { return conversion_time[thermometer.m_resolution >> 5]; } bool isThermometerTriggered(void) { static bool isTriggered = false; getOneWire()->open(); if (getOneWire()->isBusy() == true) { getOneWire()->close(); return isTriggered; } // uint64_t serialNumber = no_serial_number; // getOneWire()->makeTransaction(ALARM_SEARCH, no_serial_number, NONE, (char *)&serialNumber); // getOneWire()->close(); // // if (serialNumber != thermometer.m_serialNumber) if ((int8_t)(thermometer.m_temperature >> 4) > (int8_t)thermometer.m_lowAlarmTrigger && (int8_t)(thermometer.m_temperature >> 4) < (int8_t)thermometer.m_highAlarmTrigger) { isTriggered = false; } else { isTriggered = true; } return isTriggered; } //----------------------------------------------------------------// // Сеттер и геттер наименования термометра // //----------------------------------------------------------------// void setThermometerName(const ThermometerName name) { uint32_t nameSize = strlen(name); nameSize = nameSize > MAX_NAME_SIZE ? nameSize : MAX_NAME_SIZE; strncpy(thermometer.m_name, name, nameSize); } void getThermometerName(ThermometerName name) { strcpy(name, thermometer.m_name); } //----------------------------------------------------------------// // Сеттер и геттер нижнего порога температуры термометра // //----------------------------------------------------------------// void setThermometerLowAlarmTrigger(const int8_t lowAlarmTrigger) { if ((uint8_t)lowAlarmTrigger != thermometer.m_lowAlarmTrigger) { thermometer.m_lowAlarmTrigger = (uint8_t)lowAlarmTrigger; updateThermometerParameters(); } } int8_t getThermometerLowAlarmTrigger(void) { return thermometer.m_lowAlarmTrigger; } //----------------------------------------------------------------// // Сеттер и геттер верхнего порога температуры термометра // //----------------------------------------------------------------// void setThermometerHighAlarmTrigger(const int8_t highAlarmTrigger) { if ((uint8_t)highAlarmTrigger != thermometer.m_highAlarmTrigger) { thermometer.m_highAlarmTrigger = (uint8_t)highAlarmTrigger; updateThermometerParameters(); } } int8_t getThermometerHighAlarmTrigger(void) { return thermometer.m_highAlarmTrigger; } //----------------------------------------------------------------// // Сеттер и геттер разрешения термометра // //----------------------------------------------------------------// void setThermometerResolution(const Resolution resolution) { switch (resolution) { case RES_9BITS: case RES_10BITS: case RES_11BITS: case RES_12BITS: { if (resolution != thermometer.m_resolution) { thermometer.m_resolution = resolution; updateThermometerParameters(); } } } } Resolution getThermometerResolution(void) { return thermometer.m_resolution; } void updateThermometerParameters(void) { uint8_t parameters[] = { thermometer.m_highAlarmTrigger, thermometer.m_lowAlarmTrigger, thermometer.m_resolution }; #if (NUMBER_OF_THERMOMETERS == 1) getOneWire()->open(); getOneWire()->makeTransaction(SKIP_ROM, no_serial_number, WRITE_SCRATCHPAD, (char *)&parameters); getOneWire()->makeTransaction(SKIP_ROM, no_serial_number, COPY_SCRATCHPAD, 0); getOneWire()->close(); #endif //NUMBER_OF_THERMOMETERS }
C
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <assert.h> #include "evaluator.h" #include "kev/kev_eval.h" int main(void) { int a, b, c, d, e, f, g; int count = 0; for(a=0; a<46; a++) { for(b=a+1; b<47; b++) { for(c=b+1; c<48; c++) { for(d=c+1; d<49; d++) { for(e=d+1; e<50; e++) { for(f=e+1; f<51; f++) { for(g=f+1; g<52; g++) { int ph_eval = evaluate_7cards(a, b, c, d, e, f, g); int kev_eval = kev_eval_7cards(a, b, c, d, e, f, g); assert(ph_eval == kev_eval); count++; } } } } } } } printf("Test completed. Tested %d hands in total\n", count); return 0; }
C
/* Exercise 5.5: Finding perfect numbers Alistair Moffat, March 2013. */ #include <stdio.h> #include <stdlib.h> #include <limits.h> /* function prototypes */ int isperfect(int n); int nextperfect(int n); int sumfactors(int n); int main(int argc, char *argv[]) { int n; /* scaffolding to fetch an input value */ printf("Enter a number n: "); if (scanf("%d", &n) != 1) { printf("Invalid input\n"); exit(EXIT_FAILURE); } /* and try it out in the two functions */ if (isperfect(n)) { printf("%d is a perfect number\n", n); } else { printf("%d is not a perfect number\n", n); } printf("The next perfect is : %d\n", nextperfect(n)); return 0; } /* sum the factors of the argument */ int sumfactors(int n) { int i, sum=1; /* the sum already includes the first factor */ for (i=2; i*i<n; i++) { /* the loop is much more efficient if stopped at sqrt(n) */ if (n%i==0) { /* found a factor */ sum += i; /* and get two for the price of one */ sum += (n/i); } } /* one more thing to check, that last value of i */ if (i*i==n) { /* yes, n is a square, and has one more factor */ sum += i; } return sum; } /* determine whether n is perfect */ int isperfect(int n) { /* yes, it is perfectly (boom boom) ok for a function to just have one line */ return (sumfactors(n) == n); } /* determine the next perfect number after n */ int nextperfect(int n) { n = n+1; /* and just search until one is found */ while (!isperfect(n)) { n = n+1; /* time to be a bit careful... */ if (n==INT_MAX) { /* ...and time to bail out */ printf("No more perfect numbers\n"); exit(EXIT_FAILURE); } } /* got one */ return n; }
C
#include <stdio.h> #include <stdlib.h> #include <errno.h> #include <fcntl.h> #include <string.h> #include <unistd.h> #define BUFFER_LEN 256 static char recv[BUFFER_LEN] = {0}; int main(int argc, char** argv) { (void) argc; (void) argv; char sentStr[BUFFER_LEN] = {0}; printf("Starting test of a char device!\n"); int ret = -1, dev = -1; dev = open("/dev/izchar", O_RDWR); if (dev < 0) { perror("Failed to open the device!\n"); return errno; } printf("Type a short message to send to the kern module!\n"); scanf("%[^\n]%*c", sentStr); ret = write(dev, sentStr, strlen(sentStr)); if (ret < 0) { perror("Failed to write to kernel module!\n"); return errno; } printf("Press ENTER to read back from modyule!\n"); getchar(); printf("Reading back from device!\n"); ret = read(dev, recv, BUFFER_LEN); if (ret < 0) { perror("Failed to read message from module!\n"); return errno; } printf("The message recieved is: [%s]\n", recv); printf("PROGRAM END!\n\n"); return 0; }
C
#include<strings.h> #include<sys/types.h> #include<sys/socket.h> #include<arpa/inet.h> #include<netinet/in.h> #include "basic.h" #include "socketComm.h" #define BACKLOG 200 /*创建一个socket,侦听pscAddr及port对应的ip和端口 */ int createSocketListen(int port, char *pscAddr) { int ret; int sockfd; struct sockaddr_in my_addr; bzero(&my_addr, sizeof(my_addr)); my_addr.sin_family = AF_INET; my_addr.sin_port = htons(port); ret = inet_pton(AF_INET, pscAddr, &(my_addr.sin_addr.s_addr)); /*将ip字符串转成stuct in_addr类型 */ exit_if(ret < 0); sockfd = socket(AF_INET, SOCK_STREAM, 0); exit_if(sockfd < 0); ret = bind(sockfd, (struct sockaddr *)&my_addr, sizeof(my_addr)); exit_if(ret < 0); ret = listen(sockfd,BACKLOG); exit_if(ret < 0); return sockfd; } /*从fd读出uiBufLen个字节到pscBuf中,如果收不到uiBufLen个字节,由于fd被设置为非阻塞将会报错 */ void socketRecv(int fd, char *pscBuf, int uiBufLen) { int recvedLen = 0; int leftLen; int recvTempLen; int bufLen = (int)uiBufLen; do { leftLen = bufLen - recvedLen; do { recvTempLen = recv(fd, pscBuf+recvedLen, lenLeft, 0); } while ((recvTempLen == -1) && (errno == EINTR)); exit_if(recvTempLen == -1); if(recvTempLen == 0) { printf("The fd has been closed"); return; } recvedLen += recvTempLen; } while (recvedLen != bufLen); } void socketSend(int siFd, char *pscMsgBuf, uint32 uiBufLen) { int siLenFill;/*一共要发送的消息字节数*/ int siLenSent;/*已发送的消息字节数*/ int siLenLeft;/*剩余应该要发送的消息字节数*/ int siLen; siLenFill = (int)uiBufLen; do { do { siLen = send(siFd, pscMsgBuf + siLenSent, siLenLeft, 0); } while((siLen == -1) && (errno == EINTR)); exit_if(siLen == -1); siLenSent += siLen; } while(siLenSent != siLenFill); }
C
#include <CUnit/CUnit.h> #include <CUnit/Basic.h> #include "../src/board.h" void init_board_test() { board_t board; int i, j; init_board(&board); for (i = 0; i < BOARD_SIZE; i++) { for (j = 0; j < BOARD_SIZE; j++) { if (board.grid[i][j].value) { CU_FAIL("All of board.grid's values weren't initialized to 0"); } } } CU_PASS("All of board.grid's values were initialized to 0"); } void print_row_test() { board_t board; char buffer[ROW_LENGTH + 1]; uint8_t i; init_board(&board); for (i = 0; i < BOARD_SIZE; i++) { board.grid[0][i].value = i + 1; } const char *result = print_row(&board, buffer, 0); CU_ASSERT_STRING_EQUAL(result, "|123|456|789|\n"); } void print_blank_row_test() { CU_ASSERT_STRING_EQUAL(print_blank_row(), "-------------\n"); } void print_board_test0() { board_t board; init_board(&board); char buffer[ROW_LENGTH * COL_LENGTH + 1]; char *expected_board_printout = "-------------\n" "|000|000|000|\n" "|000|000|000|\n" "|000|000|000|\n" "-------------\n" "|000|000|000|\n" "|000|000|000|\n" "|000|000|000|\n" "-------------\n" "|000|000|000|\n" "|000|000|000|\n" "|000|000|000|\n" "-------------\n"; char *actual_board_printout = print_board(&board, buffer); CU_ASSERT_STRING_EQUAL(actual_board_printout, expected_board_printout); } void print_board_test1() { board_t board; init_board(&board); char buffer[ROW_LENGTH * COL_LENGTH + 1]; uint8_t i; for (i = 0; i < BOARD_SIZE; i++) { board.grid[i][i].value = i + 1; } const char *expected_printout = "-------------\n" "|100|000|000|\n" "|020|000|000|\n" "|003|000|000|\n" "-------------\n" "|000|400|000|\n" "|000|050|000|\n" "|000|006|000|\n" "-------------\n" "|000|000|700|\n" "|000|000|080|\n" "|000|000|009|\n" "-------------\n"; const char *actual_printout = print_board(&board, buffer); CU_ASSERT_STRING_EQUAL(actual_printout, expected_printout); } void set_board_string_test() { board_t board; init_board(&board); char buffer[ROW_LENGTH * COL_LENGTH + 1]; const char *board_string = "111111111" "222222222" "333333333" "444444444" "555555555" "666666666" "777777777" "888888888" "999999999"; set_board_string(&board, board_string); const char *expected_printout = "-------------\n" "|111|111|111|\n" "|222|222|222|\n" "|333|333|333|\n" "-------------\n" "|444|444|444|\n" "|555|555|555|\n" "|666|666|666|\n" "-------------\n" "|777|777|777|\n" "|888|888|888|\n" "|999|999|999|\n" "-------------\n"; const char *actual_printout = print_board(&board, buffer); CU_ASSERT_STRING_EQUAL(actual_printout, expected_printout); } void should_return_error_when_string_is_not_correct_length() { board_t board; init_board(&board); char *bad_string = "This is a bad string\n"; uint8_t actual_error_code = set_board_string(&board, bad_string); CU_ASSERT_EQUAL(actual_error_code, 1); } void set_poss_test() { cell_t cell; cell.poss = 0b111111111; elim_poss(&cell, 1); elim_poss(&cell, 2); elim_poss(&cell, 3); uint16_t actual_poss = cell.poss; CU_ASSERT_EQUAL(actual_poss, 0b111111000); }
C
#include "lists.h" /** * delete_nodeint_at_index - delete * @head: pointer * @index: int * Return: Always 0. */ int delete_nodeint_at_index(listint_t **head, unsigned int index) { unsigned int i = 1; listint_t *remove, *tmp; if (head == NULL) return (-1); tmp = *head; if (index == 0) { if (tmp == NULL) return (-1); *head = tmp->next; free(tmp); return (1); } while (tmp) { if (i == index) { remove = tmp->next; tmp->next = remove->next; free(remove); return (1); } i++; tmp = tmp->next; } return (-1); }
C
/******************************** Author: Sravanthi Kota Venkata ********************************/ #include <stdio.h> #include <stdlib.h> #include <time.h> #include "segment.h" #ifndef M_PI #define M_PI 3.141592653589793 #endif // dissimilarity measure between pixels float diff(F2D *r, int x1, int y1, int x2, int y2) { return sqrt(abs(( subsref(r,y1,x1) * subsref(r,y1,x1)) - ( subsref(r,y2,x2) * subsref(r,y2,x2)))); } I2D *segment_image(I2D* im, float sigma, float c, int min_size, int *num_ccs) { int width = im->width; int height = im->height; int num = 0, x, y, i; F2D* smooth_im; I2D *output; edge* edges; int components = 0; /* int *colors = (int *) malloc(width*height*sizeof(int)); */ int *segments = (int *) malloc(height*width*sizeof(int)); // smooth each color channel smooth_im = imageBlur(im); //build graph edges = (edge*)malloc(sizeof(edge)*width*height*4); for (y = 0; y < height; y++) { for (x = 0; x < width; x++) { segments[y*width+x] = -1; if (x < width-1) { edges[num].a = y * width + x; edges[num].b = y * width + (x+1); edges[num].w = diff(smooth_im, x, y, x+1, y); num++; } if (y < height-1) { edges[num].a = y * width + x; edges[num].b = (y+1) * width + x; edges[num].w = diff(smooth_im, x, y, x, y+1); num++; } if ((x < width-1) && (y < height-1)) { edges[num].a = y * width + x; edges[num].b = (y+1) * width + (x+1); edges[num].w = diff(smooth_im, x, y, x+1, y+1); num++; } if ((x < width-1) && (y > 0)) { edges[num].a = y * width + x; edges[num].b = (y-1) * width + (x+1); edges[num].w = diff(smooth_im, x, y, x+1, y-1); num++; } } } free(smooth_im); // segment universe *u = segment_graph(width*height, num, edges, c); // post process small components for (i = 0; i < num; i++) { int a, b; a = find(u,edges[i].a); b = find(u,edges[i].b); if ((a != b) && ((u->elts[a].size < min_size) || (u->elts[b].size < min_size))) join(u, a, b); } free(edges); arrayref(num_ccs,0) = u->num; // pick random colors for each component output = iMallocHandle(height, width); /* srand(time(0)); for (i = 0; i < width*height; i++) { float temp; temp = rand()/((float)RAND_MAX); colors[i] = (int)(temp*255); } */ for (y = 0; y < height; y++) { for (x = 0; x < width; x++) { int comp; comp = find(u, y * width + x); if(segments[comp] == -1) segments[comp] = components++; subsref(output, y, x) = segments[comp]; } } /* for (y = 0; y < height; y++) { for (x = 0; x < width; x++) { int comp; comp = find(u, y * width + x); subsref(output, y, x) = colors[comp]; } } */ free(u->elts); free(u); free(segments); return output; }
C
#include<stdio.h> #include<math.h> #define N_MAX 100000 #define False 0 #define True 1 int Max(const int a, const int b); void IsPrime(const int l, const int r, const int n); int main(void) { IsPrime(100, 200, test); return 0; } /** * l 到 r 为区间 * n 为 l 到 r 区间的数 */ void IsPrime(const int l, const int r, const int n) { const int N = sqrt(r); int isPrime[N], count = 0; int isPrimeLR[r-l]; int i, j, begin; for(i = 0; i < Max(N, r-l); i++) { if(i < N) isPrime[i] = True; if(i < r-l) isPrimeLR[i] = True; } isPrime[0] = isPrime[1] = False; for(i = 0; i < N; i++) { if(isPrime[i]) { // 筛 0 到 sqrt(l) 的素数 for(j = 2 * i; j < N; j += i) isPrime[j] = False; // 筛 r 到 l // begin 寻找大于 r 最小的素数倍数 begin = Max(2, (l + i - 1) / i) * i; for(j = begin; j < r; j += i) isPrimeLR[j-l] = False; } } printf("%d = %d\n",n, isPrimeLR[n-l]); } int Max(const int a, const int b) { if(a > b) return a; else return b; }
C
#include <SDL2/SDL.h> #include <stdio.h> #include <stdlib.h> #include "check_score.h" #include "collision.h" #include "init.h" #include "main.h" #include "move_paddle.h" // Program globals ball_t ball; paddle_t paddle[2]; int width, height; // used if fullscreen SDL_Window *window = NULL; // The window we'll be rendering to SDL_Renderer *renderer; // The renderer SDL will use to draw to the screen // surfaces SDL_Surface *screen; SDL_Surface *title; SDL_Surface *numbermap; SDL_Surface *end; // textures SDL_Texture *screen_texture; // Initialize starting position and sizes of game elemements static void init_game() { ball.x = screen->w / 2; ball.y = screen->h / 2; ball.w = 10; ball.h = 10; ball.dy = 1; ball.dx = 1; paddle[0].x = 20; paddle[0].y = screen->h / 2 - 50; paddle[0].w = 10; paddle[0].h = 50; paddle[1].x = screen->w - 20 - 10; paddle[1].y = screen->h / 2 - 50; paddle[1].w = 10; paddle[1].h = 50; } /* This routine moves each ball by its motion vector. */ static void move_ball() { /* Move the ball by its motion vector. */ ball.x += ball.dx; ball.y += ball.dy; /* Turn the ball around if it hits the edge of the screen. */ if (ball.x < 0) { increment_score(1); init_game(); } if (ball.x > screen->w - 10) { increment_score(0); init_game(); } if (ball.y < 0 || ball.y > screen->h - 10) { ball.dy = -ball.dy; } // check for collision with the paddle for (int i = 0; i < 2; i++) { // collision detected if (hasCollision(ball, paddle[i])) { // ball moving left if (ball.dx < 0) { ball.dx -= 1; // ball moving right } else { ball.dx += 1; } // change ball direction ball.dx = -ball.dx; // change ball angle based on where on the paddle it hit int hit_pos = (paddle[i].y + paddle[i].h) - ball.y; if (hit_pos >= 0 && hit_pos < 7) { ball.dy = 4; } if (hit_pos >= 7 && hit_pos < 14) { ball.dy = 3; } if (hit_pos >= 14 && hit_pos < 21) { ball.dy = 2; } if (hit_pos >= 21 && hit_pos < 28) { ball.dy = 1; } if (hit_pos >= 28 && hit_pos < 32) { ball.dy = 0; } if (hit_pos >= 32 && hit_pos < 39) { ball.dy = -1; } if (hit_pos >= 39 && hit_pos < 46) { ball.dy = -2; } if (hit_pos >= 46 && hit_pos < 53) { ball.dy = -3; } if (hit_pos >= 53 && hit_pos <= 60) { ball.dy = -4; } // ball moving right if (ball.dx > 0) { // teleport ball to avoid mutli collision glitch if (ball.x < 30) { ball.x = 30; } // ball moving left } else { // teleport ball to avoid mutli collision glitch if (ball.x > 600) { ball.x = 600; } } } } } static void draw_game_over(int p) { SDL_Rect p1; SDL_Rect p2; SDL_Rect cpu; SDL_Rect dest; p1.x = 0; p1.y = 0; p1.w = end->w; p1.h = 75; p2.x = 0; p2.y = 75; p2.w = end->w; p2.h = 75; cpu.x = 0; cpu.y = 150; cpu.w = end->w; cpu.h = 75; dest.x = (screen->w / 2) - (end->w / 2); dest.y = (screen->h / 2) - (75 / 2); dest.w = end->w; dest.h = 75; switch (p) { case 1: SDL_BlitSurface(end, &p1, screen, &dest); break; case 2: SDL_BlitSurface(end, &p2, screen, &dest); break; default: SDL_BlitSurface(end, &cpu, screen, &dest); } } static void draw_menu() { SDL_Rect src; SDL_Rect dest; src.x = 0; src.y = 0; src.w = title->w; src.h = title->h; dest.x = (screen->w / 2) - (src.w / 2); dest.y = (screen->h / 2) - (src.h / 2); dest.w = title->w; dest.h = title->h; SDL_BlitSurface(title, &src, screen, &dest); } static void draw_net() { SDL_Rect net; net.x = screen->w / 2; net.y = 20; net.w = 5; net.h = 15; // draw the net int i, r; for (i = 0; i < 15; i++) { r = SDL_FillRect(screen, &net, 0xffffffff); if (r != 0) { printf("fill rectangle failled in func draw_net()"); } net.y = net.y + 30; } } static void draw_ball() { SDL_Rect src; src.x = ball.x; src.y = ball.y; src.w = ball.w; src.h = ball.h; if (SDL_FillRect(screen, &src, 0xffffffff) != 0) { printf("fill rectangle failled in func drawball()"); } } static void draw_paddle() { SDL_Rect src; int i; for (i = 0; i < 2; i++) { src.x = paddle[i].x; src.y = paddle[i].y; src.w = paddle[i].w; src.h = paddle[i].h; if (SDL_FillRect(screen, &src, 0xffffffff) != 0) { printf("fill rectangle failled in func draw_paddle()"); } } } static void draw_player_0_score() { SDL_Rect src; SDL_Rect dest; src.x = 0; src.y = 0; src.w = 64; src.h = 64; dest.x = (screen->w / 2) - src.w - 12; // 12 is just padding spacing dest.y = 0; dest.w = 64; dest.h = 64; if (getScore(0) > 0 && getScore(0) < 10) { src.x += src.w * getScore(0); } SDL_BlitSurface(numbermap, &src, screen, &dest); } static void draw_player_1_score() { SDL_Rect src; SDL_Rect dest; src.x = 0; src.y = 0; src.w = 64; src.h = 64; dest.x = (screen->w / 2) + 12; dest.y = 0; dest.w = 64; dest.h = 64; if (getScore(1) > 0 && getScore(1) < 10) { src.x += src.w * getScore(1); } SDL_BlitSurface(numbermap, &src, screen, &dest); } int main(int argc, char *args[]) { // SDL Window setup if (init(SCREEN_WIDTH, SCREEN_HEIGHT, argc, args) == 1) { return 0; } SDL_GetWindowSize(window, &width, &height); int sleep = 0; int quit = 0; int state = 0; int r = 0; Uint32 next_game_tick = SDL_GetTicks(); // Initialize the ball position data. init_game(); // render loop while (quit == 0) { // check for new events every frame SDL_PumpEvents(); const Uint8 *keystate = SDL_GetKeyboardState(NULL); if (keystate[SDL_SCANCODE_ESCAPE]) { quit = 1; } if (keystate[SDL_SCANCODE_DOWN]) { move_paddle(0); } if (keystate[SDL_SCANCODE_UP]) { move_paddle(1); } // draw background SDL_RenderClear(renderer); SDL_FillRect(screen, NULL, 0x000000ff); // display main menu if (state == 0) { if (keystate[SDL_SCANCODE_SPACE]) { state = 1; } // draw menu draw_menu(); // display gameover } else if (state == 2) { if (keystate[SDL_SCANCODE_SPACE]) { state = 0; // delay for a little bit so the space bar press dosnt get triggered // twice while the main menu is showing SDL_Delay(500); } if (r == 1) { // if player 1 is AI if player 1 was human display the return value of r // not 3 draw_game_over(3); } else { // display gameover draw_game_over(r); } // display the game } else if (state == 1) { // check score r = check_score(); // if either player wins, change to game over state if (r == 1) { state = 2; } else if (r == 2) { state = 2; } // paddle ai movement move_paddle_ai(); //* Move the balls for the next frame. move_ball(); // draw net draw_net(); // draw paddles draw_paddle(); //* Put the ball on the screen. draw_ball(); // draw the score draw_player_0_score(); // draw the score draw_player_1_score(); } SDL_UpdateTexture(screen_texture, NULL, screen->pixels, screen->w * sizeof(Uint32)); SDL_RenderCopy(renderer, screen_texture, NULL, NULL); // draw to the display SDL_RenderPresent(renderer); // time it takes to render frame in milliseconds next_game_tick += 1000 / 60; sleep = next_game_tick - SDL_GetTicks(); if (sleep >= 0) { SDL_Delay(sleep); } } SDL_Surface *ptr[] = {screen, title, numbermap, end, NULL}; cleanUp(renderer, window, ptr); return 0; }
C
#include <stdio.h> int main (int argc,char **argv) { int i=0; if(argc-1 != 2) { printf("Il faut 2 arguments.\n"); return 1; } if(atoi(argv[2]) <= 0) { printf("Il faut que le deuxième arguments soit un entier strictement positif\n"); return 1; } for (i=0;i<atoi(argv[2]);i++) { printf("%s\n",argv[1]); } return 0; }
C
/** * @file * @brief D(ata) S(tructure) Int(erfaces) * pronounced "decent," "descent," or "dissent" */ #ifndef _DSINT_H_ #define _DSINT_H_ #ifdef __cplusplus extern "C" { #endif #include <glitter.h> /* #ifndef DOXYGEN #define ATTRIBUTE(attr) __attribute__ (attr) #else #define ATTRIBUTE(attr) #endif */ /** @return whether the datastructure is at full capacity */ typedef __attribute__ ((nonnull (1), warn_unused_result)) \ bool (*isfull_t) (void const *restrict arg) ; /** @return whether the datastructure is at empty capacity */ typedef __attribute__ ((nonnull (1), warn_unused_result)) \ bool (*isempty_t) (void const *restrict arg) ; /** @return the amount of remaining space in the datastructure */ typedef __attribute__ ((nonnull (1), warn_unused_result)) \ size_t (*remaining_space_t) (void const *restrict arg) ; /** @return the amount of used space in the datastructure */ typedef __attribute__ ((nonnull (1), warn_unused_result)) \ size_t (*used_space_t) (void const *restrict arg) ; /** add an element to the datastructure */ typedef __attribute__ ((nonnull (1, 2))) \ void (*add_t) (void *restrict ds, void const *restrict e) ; /** remove an element from the datastructure */ typedef __attribute__ ((nonnull (1, 2))) \ void (*remove_t) (void *restrict ds, void *restrict e) ; /** bulk add operation: use this to add multiple elements--it could reduce your order of complexity */ typedef __attribute__ ((nonnull (1, 2))) \ void (*adds_t) (void *restrict ds, void const *restrict e, size_t n) ; /** bulk remove operation--use this to remove multiple elements--it could reduce your order of complexity */ typedef __attribute__ ((nonnull (1, 2))) \ void (*removes_t) (void *restrict ds, void *restrict e, size_t n) ; /** dynamically allocate the datastructure */ typedef __attribute__ ((warn_unused_result)) \ void *(*alloc_t) (void const *restrict) ; /* free a dynamically allocated datastructure */ typedef __attribute__ ((nonnull (1))) \ void (*free_t) (void *restrict) ; /** free a dynamically allocated datastructure and its elements */ typedef __attribute__ ((nonnull (1))) \ void (*frees_t) (void *restrict, size_t n) ; #ifdef __cplusplus } #endif #endif /* _DSINT_H_ */
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* split_tetris.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ade-verd <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/11/30 10:45:44 by ade-verd #+# #+# */ /* Updated: 2017/12/04 15:26:18 by ade-verd ### ########.fr */ /* */ /* ************************************************************************** */ /* ** Description ** Split each tetriminos in an array of char*. ** The initial string doesn't need to be valid. Tests are made after that. ** ** Return ** char** : Array of each Tetriminos */ #include "fillit.h" int ft_count_tm(char const *str) { int i; int count; i = 0; count = 0; while (str[i] != '\0') { if (str[i] == '\n' && (str[i + 1] == '\n' || str[i + 1] == '\0')) count++; i++; } return (count); } static char *ft_extract_tm(char const *s, int start) { int i; int end; char *tm; i = 0; end = start; while (s[end]) { if (s[end] == '\n' && (s[end + 1] == '\n' || s[end + 1] == '\0')) break ; end++; } if ((tm = (char*)malloc(sizeof(char) * (end - start + 1))) == NULL) return (NULL); while (s[i] != '\0' && start <= end) { tm[i] = s[start]; start++; i++; } tm[i] = '\0'; return (tm); } char **ft_splittetris(char *str) { char **tab; int i; int j; int len; char *tm; if (str == NULL) return (NULL); i = 0; j = 0; if ((tab = (char**)malloc(sizeof(char*) * ft_count_tm(str) + 1)) == NULL) return (NULL); while (i < ft_count_tm(str)) { tm = ft_extract_tm(str, j); len = ft_strlen(tm); if ((tab[i] = (char*)malloc(sizeof(char) * len + 1)) == NULL) return (NULL); tab[i] = tm; j = j + len + 1; i++; } tab[i] = 0; return (tab); }
C
#include "learnuv.h" #include "../deps/libuv/include/uv.h" #define BUF_SIZE 37 static const char *filename = __MAGIC_FILE__; /* Making our lifes a bit easier by using this global, a better solution in the next exercise ;) */ static uv_fs_t open_req; static uv_buf_t iov; void read_cb(uv_fs_t *read_req) { int r = 0; if (read_req->result < 0) CHECK(read_req->result, "uv_fs_read callback"); /* 4. Report the contents of the buffer */ log_report("%s", iov.base); log_info("%s", iov.base); /* 5. Close the file descriptor */ uv_fs_t close_req; r = uv_fs_close(read_req->loop, &close_req, open_req.result, NULL); if (r < 0) CHECK(r, "uv_fs_close"); uv_fs_req_cleanup(&open_req); uv_fs_req_cleanup(read_req); uv_fs_req_cleanup(&close_req); } int main() { int r = 0; uv_loop_t *loop = uv_default_loop(); /* 1. Open file (synchronously) */ r = uv_fs_open(loop, &open_req, filename, O_RDONLY, S_IRUSR, NULL); if (r < 0) CHECK(r, "uv_fs_open"); fprintf(stderr, "\npath %s", open_req.path); fprintf(stderr, "\npath %zi\n", open_req.result); /* 2. Create buffer and initialize it to turn it into a a uv_buf_t */ char buf[BUF_SIZE]; iov = uv_buf_init(buf, sizeof(buf)); /* 3. Use the file descriptor (the .result of the open_req) to read **aynchronously** from the file into the buffer */ uv_fs_t read_req; fprintf(stderr, "\niov.len %zu", iov.len); fprintf(stderr, "\nsizeof(buf) %zu\n", sizeof(buf)); fprintf(stderr, "\nsizeof(iov) %zu\n", sizeof(iov)); r = uv_fs_read(loop, &read_req, open_req.result, &iov, 5, -1, read_cb); if (r < 0) CHECK(r, "uv_fs_read"); printf("\nsizeof(uv_buf_t):%zu", sizeof(uv_buf_t)); printf("\nsizeof(size_t):%zu", sizeof(size_t)); printf("\nsizeof(uv_buf_t*):%zu", sizeof(uv_buf_t*)); // log_report("%s", buf); // log_info("%s", iov.base); // // char *s = "This is the magic we are looking for!"; // const uv_buf_t buf2[37]; uv_buf_t* d[10]; memcpy(d, &iov, 80); //// d[strlen(s)] = '\0';//因为从d[0]开始复制,总长度为strlen(s),d[strlen(s)]置为结束符 // printf("%s", d); // // // // char buf3[37]; // char* d1[8]; // memcpy(d1, buf3, 65); uv_run(loop, UV_RUN_DEFAULT); return 0; }
C
#pragma once #include <stddef.h> #include <stdbool.h> //#define VDBG struct Vector { #ifdef VDBG int elements[100]; #else void *elements; #endif size_t size; size_t capacity; size_t element_size; void (*freefn)(void *); }; typedef struct Vector *VECTOR; typedef bool (*VECTOR_ITERATOR_FUNC)(VECTOR, void *); VECTOR vector_new(size_t hint, size_t element_size, void (*freefn)(void *)); void vector_free(struct Vector *v); size_t vector_size(struct Vector *v); bool vector_empty(struct Vector *v); bool vector_clear(struct Vector *v); void* vector_at(struct Vector *v, size_t index); bool vector_get(struct Vector *v, size_t index, void *elem); bool vector_append(struct Vector *v, void *elem); bool vector_insert(struct Vector *v, size_t index, void *elem); bool vector_remove(struct Vector *v, size_t index, void *elem); void vector_foreach(struct Vector *v, VECTOR_ITERATOR_FUNC each);
C
#include "../../shared/header/shared.h" #include <stdio.h> #include <stdlib.h> #include <string.h> void editScore(float*** scoresPtr, char** assignmentNames, char** studentNames) { float** scores = *scoresPtr; short assignmentIdx = getAssignmentIdx(assignmentNames); short studentIdx = getStudentIdx(studentNames); char* scoreString = malloc(8); float score; printf("Score: "); fgets(scoreString, 8, stdin); scoreString[strlen(scoreString)-1] = '\0'; score = strtof(scoreString, NULL); while (score >= 10000) { printf("Sorry, maximum score is 9999.\n"); printf("Score: "); fgets(scoreString, 8, stdin); scoreString[strlen(scoreString)-1] = '\0'; score = strtof(scoreString, NULL); } scores[studentIdx][assignmentIdx] = score; *scoresPtr = scores; }
C
int execBuiltInCommand(char** args); int handleUserDefinedCommands(char *data,char **commandArgs); int executeCollonCommands(char *input1,char *input2,char** command1Args,char** command2Args){ pid_t pid1=fork(); if(pid1==0){ if(handleUserDefinedCommands(input1,command1Args)){ exit(0); } else{ if(execBuiltInCommand(command1Args)){ exit(0); } else{ printf("illegal command or argument\n"); exit(0);} } } else{ pid_t pid2=fork(); if(pid2==0){ if(handleUserDefinedCommands(input2,command2Args)){ exit(0); } else{ if(execBuiltInCommand(command2Args)){ exit(0); } else{ printf("illegal command or argument\n"); exit(0);} } } waitpid (pid1,NULL,0); waitpid(pid2,NULL,0); return 0; } } int handleCollonCommands(char *input,char** command1Args,char** command2Args) { char input1[100]; int size=strlen(input); char delim[] = ";"; char *ptr = strtok(input, delim); int count =0; char *seprateCommand[2]; while(ptr != NULL) { if(count==2){ break; } seprateCommand[count++] = ptr; ptr = strtok(NULL, delim); } removeSpace(seprateCommand[0],command1Args); removeSpace(seprateCommand[1],command2Args); int a=executeCollonCommands(seprateCommand[0],seprateCommand[1],command1Args,command2Args); return 1; }
C
#include <Python.h> #include <numpy/arrayobject.h> #include "heron.h" #include "segment.h" #include "areas.h" static char module_docstring[] = "This module is used to calcuate the areas of geometric shapes"; static char heron_docstring[] = "Calculate triange area with only the lengths known."; static char segment_docstring[] = "Calculate the area of a circle segment."; static char quad_docstring[] = "Calculate the area of a circle segment."; static PyObject *heron_heron(PyObject *self, PyObject *args); static PyObject *heron_segment(PyObject *self, PyObject *args); static PyObject *heron_find_segment_area(PyObject *self, PyObject *args); static PyObject *heron_find_quad_area(PyObject *self, PyObject *args); static PyObject *heron_one_in_one_out(PyObject *self, PyObject *args); static PyMethodDef module_methods[] = { {"heron", heron_heron, METH_VARARGS, heron_docstring}, {"segment", heron_segment, METH_VARARGS, segment_docstring}, {"find_segment_area", heron_find_segment_area, METH_VARARGS, segment_docstring}, {"find_quad_area", heron_find_quad_area, METH_VARARGS, quad_docstring}, {"one_in_one_out", heron_one_in_one_out, METH_VARARGS, quad_docstring}, {NULL, NULL, 0, NULL} }; PyMODINIT_FUNC #if PY_MAJOR_VERSION >= 3 PyInit__heron(void) #else init_heron(void) #endif { #if PY_MAJOR_VERSION >= 3 PyObject *module; static struct PyModuleDef moduledef = { PyModuleDef_HEAD_INIT, "_heron", /* m_name */ module_docstring, /* m_doc */ -1, /* m_size */ module_methods, /* m_methods */ NULL, /* m_reload */ NULL, /* m_traverse */ NULL, /* m_clear */ NULL, /* m_free */ }; #endif #if PY_MAJOR_VERSION >= 3 module = PyModule_Create(&moduledef); if (!module) return NULL; /* Load `numpy` functionality. */ import_array(); return module; #else PyObject *m = Py_InitModule3("_heron", module_methods, module_docstring); if (m == NULL) return; /* Load `numpy` functionality. */ import_array(); #endif } static PyObject *heron_heron(PyObject *self, PyObject *args) { double a, b,c; /* Parse the input tuple */ if (!PyArg_ParseTuple(args, "ddd", &a, &b, &c)) return NULL; /* Call the external C function to compute the area. */ double area = heron(a,b,c); /* Build the output tuple */ PyObject *ret = Py_BuildValue("d",area); return ret; } static PyObject *heron_segment(PyObject *self, PyObject *args) { double r, theta; /* Parse the input tuple */ if (!PyArg_ParseTuple(args, "dd", &r, &theta)) return NULL; /* Call the external C function to compute the area. */ double area = segment(r,theta); /* Build the output tuple */ PyObject *ret = Py_BuildValue("d",area); return ret; } static PyObject *heron_find_segment_area(PyObject *self, PyObject *args) { double c1x,c2x,x2,r2; /* Parse the input tuple */ if (!PyArg_ParseTuple(args, "dddd", &c1x, &c2x,&x2,&r2)) return NULL; /* Call the external C function to compute the area. */ double area = find_segment_area(c1x,c2x,x2,r2); /* Build the output tuple */ PyObject *ret = Py_BuildValue("d",area); return ret; } static PyObject *heron_find_quad_area(PyObject *self, PyObject *args) { PyObject *a_obj,*b_obj,*c_obj,*d_obj; /* Parse the input tuple */ if (!PyArg_ParseTuple(args, "OOOO", &a_obj, &b_obj,&c_obj,&d_obj)) return NULL; /* Interpret the input objects as numpy arrays. */ PyObject *a_array = PyArray_FROM_OTF(a_obj, NPY_DOUBLE, NPY_IN_ARRAY); PyObject *b_array = PyArray_FROM_OTF(b_obj, NPY_DOUBLE, NPY_IN_ARRAY); PyObject *c_array = PyArray_FROM_OTF(c_obj, NPY_DOUBLE, NPY_IN_ARRAY); PyObject *d_array = PyArray_FROM_OTF(d_obj, NPY_DOUBLE, NPY_IN_ARRAY); /* If that didn't work, throw an exception. */ if (a_array == NULL || b_array == NULL || c_array == NULL || d_array == NULL) { Py_XDECREF(a_array); Py_XDECREF(b_array); Py_XDECREF(c_array); Py_XDECREF(d_array); return NULL; } /* Get pointers to the data as C-types. */ double *a = (double*)PyArray_DATA(a_array); double *b = (double*)PyArray_DATA(b_array); double *c = (double*)PyArray_DATA(c_array); double *d = (double*)PyArray_DATA(d_array); /* Call the external C function to compute the area. */ double area = find_quad_area(a,b,c,d); /* Build the output tuple */ PyObject *ret = Py_BuildValue("d",area); return ret; } static PyObject *heron_one_in_one_out(PyObject *self, PyObject *args) { double r_inner,r_outer,r2,x2,y2; PyObject *c1_obj,*c2_obj,*e1_obj,*e2_obj; /* Parse the input tuple */ if (!PyArg_ParseTuple(args, "OOOOddddd", &c1_obj, &c2_obj,&e1_obj,&e2_obj,&r_inner,&r_outer,&r2,&x2,&y2)) return NULL; /* Interpret the input objects as numpy arrays. */ PyObject *c1_array = PyArray_FROM_OTF(c1_obj, NPY_DOUBLE, NPY_IN_ARRAY); PyObject *c2_array = PyArray_FROM_OTF(c2_obj, NPY_DOUBLE, NPY_IN_ARRAY); PyObject *e1_array = PyArray_FROM_OTF(e1_obj, NPY_DOUBLE, NPY_IN_ARRAY); PyObject *e2_array = PyArray_FROM_OTF(e2_obj, NPY_DOUBLE, NPY_IN_ARRAY); /* If that didn't work, throw an exception. */ if (c1_array == NULL || c2_array == NULL || e1_array == NULL || e2_array == NULL) { Py_XDECREF(c1_array); Py_XDECREF(c2_array); Py_XDECREF(e1_array); Py_XDECREF(e2_array); return NULL; } /* Get pointers to the data as C-types. */ double *c1 = (double*)PyArray_DATA(c1_array); double *c2 = (double*)PyArray_DATA(c2_array); double *e1 = (double*)PyArray_DATA(e1_array); double *e2 = (double*)PyArray_DATA(e2_array); /* Call the external C function to compute the area. */ double area = one_in_one_out(c1,c2,e1,e2,r_inner,r_outer,r2,x2,y2); /* Build the output tuple */ PyObject *ret = Py_BuildValue("d",area); return ret; }
C
//--------------------------------------------------------------- // // 4190.308 Computer Architecture (Fall 2020) // // Project #2: FP12 (12-bit floating point) Representation // // September 28, 2020 // // Injae Kang (abcinje@snu.ac.kr) // Sunmin Jeong (sunnyday0208@snu.ac.kr) // Systems Software & Architecture Laboratory // Dept. of Computer Science and Engineering // Seoul National University // //--------------------------------------------------------------- #include <stdint.h> #include <stdio.h> #define RED "\033[0;31m" #define GREEN "\033[0;32m" #define CYAN "\033[0;36m" #define RESET "\033[0m" #include "pa2.h" #define BINARY_PATTERN "%c%c%c%c%c%c%c%c" #define BINARY(BYTE) \ (BYTE & 0x80 ? '1' : '0'), \ (BYTE & 0x40 ? '1' : '0'), \ (BYTE & 0x20 ? '1' : '0'), \ (BYTE & 0x10 ? '1' : '0'), \ (BYTE & 0x08 ? '1' : '0'), \ (BYTE & 0x04 ? '1' : '0'), \ (BYTE & 0x02 ? '1' : '0'), \ (BYTE & 0x01 ? '1' : '0') #define PRINT_BYTE(BYTE) printf(BINARY_PATTERN, BINARY(BYTE)) #define PRINT(DATATYPE, TYPENAME, NUM) \ do { \ size_t typesize = sizeof(DATATYPE); \ DATATYPE data = NUM; \ uint8_t *ptr = (uint8_t *)&data; \ \ printf("%s(", TYPENAME); \ PRINT_BYTE(*(ptr + typesize - 1)); \ for (ssize_t i = typesize - 2; i >= 0; i--) { \ printf(" "); \ PRINT_BYTE(*(ptr + i)); \ } \ printf(")"); \ } while (0) #define CHECK(RES, ANS) printf("%s"RESET, (RES) == (ANS) ? GREEN"CORRECT" : RED"WRONG") #define COMP(RES, ANS, TYPENAME) comp_##TYPENAME(RES, ANS) static void comp_int(uint32_t result, uint32_t answer) { CHECK(result, answer); } static void comp_fp12(uint16_t result, uint16_t answer) { uint16_t exp = 0x7e0 & result; uint16_t frac = 0x1f & result; if (exp == 0x7e0 && frac != 0) { result &= 0xffe0; result++; } CHECK(result, answer); } static void comp_float(uint32_t result, uint32_t answer) { uint32_t exp = 0x7f800000 & result; uint32_t frac = 0x7fffff & result; if (exp == 0x7f800000 && frac != 0) { result &= 0xff800000; result++; } CHECK(result, answer); } #define N 6 /* int -> fp12 */ uint32_t test1[N] = {0x00000000, 0x00000001, 0x000007e4, 0xffffff9b, 0x7fffffff, 0x80000000}; uint16_t ans1[N] = {0x0000, 0x03e0, 0x053f, 0xfcb2, 0x07c0, 0xffc0}; /* fp12 -> int */ uint16_t test2[N] = {0xf800, 0x04d6, 0x044c, 0xf81f, 0x07e0, 0xffff}; uint32_t ans2[N] = {0x00000000, 0x000000d8, 0x0000000b, 0x00000000, 0x80000000, 0x80000000}; /* float -> fp12 */ uint32_t test3[N] = {0x00000001, 0x3fe00000, 0xe0000000, 0x80b5840c, 0x7f800000, 0xff800001}; uint16_t ans3[N] = {0x0000, 0x03f8, 0xffe0, 0xf800, 0x07e0, 0xffe1}; /* fp12 -> float */ uint16_t test4[N] = {0x0000, 0xf801, 0x0555, 0x07e0, 0xffe0, 0x07e1}; uint32_t ans4[N] = {0x00000000, 0xae000000, 0x45540000, 0x7f800000, 0xff800000, 0x7f800001}; int main(void) { printf("\n%sTest 1: Casting from int to fp12%s\n", CYAN, RESET); for (int i = 0; i < N; i++) { uint16_t result = (uint16_t)int_fp12(test1[i]); PRINT(uint32_t, "int", test1[i]); printf(" => "); PRINT(uint16_t, "fp12", result); printf(", "); PRINT(uint16_t, "ans", ans1[i]); printf(", "); COMP(result, ans1[i], fp12); printf("\n"); } printf("\n%sTest 2: Casting from fp12 to int%s\n", CYAN, RESET); for (int i = 0; i < N; i++) { uint32_t result = (uint32_t)fp12_int(test2[i]); PRINT(uint16_t, "fp12", test2[i]); printf(" => "); PRINT(uint32_t, "int", result); printf(", "); PRINT(uint32_t, "ans", ans2[i]); printf(", "); COMP(result, ans2[i], int); printf("\n"); } printf("\n%sTest 3: Casting from float to fp12%s\n", CYAN, RESET); for (int i = 0; i < N; i++) { float *p = (float *)&test3[i]; float f = *p; uint16_t result = (uint16_t)float_fp12(f); PRINT(uint32_t, "float", test3[i]); printf(" => "); PRINT(uint16_t, "fp12", result); printf(", "); PRINT(uint16_t, "ans", ans3[i]); printf(", "); COMP(result, ans3[i], fp12); printf("\n"); } printf("\n%sTest 4: Casting from fp12 to float%s\n", CYAN, RESET); for (int i = 0; i < N; i++) { float f = fp12_float(test4[i]); uint32_t *p = (uint32_t *)&f; uint32_t result = *p; PRINT(uint16_t, "fp12", test4[i]); printf(" => "); PRINT(uint32_t, "float", result); printf(", "); PRINT(uint32_t, "ans", ans4[i]); printf(", "); COMP(result, ans4[i], float); printf("\n"); } printf("\n"); return 0; }
C
#include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <fcntl.h> #include <pthread.h> int receive_file(int cl,char fname[32]) { int sum=0, csum=0, bytes=0, fdwr; char buffer[4]; bzero(buffer,sizeof(buffer)); creat(fname,0777); if ((fdwr=open(fname, O_CREAT|O_WRONLY, 0777))<0) { printf("eroare la open"); return 0;} do { if ((bytes=read(cl,buffer,sizeof(buffer)))<0) { printf("eroare la read"); break;} if (write(fdwr,buffer,bytes)<0) {printf("eroare la write"); break;} sum=sum+bytes; } while (bytes==4); close(fdwr); return sum; } int send_file(int cl,char fname[32]) { int bytes=0, sum=0, fdrd; if ((fdrd=open(fname,O_RDONLY))<0) {printf("eroare la open"); return 0;} char buffer[4]; bzero(buffer,sizeof(buffer)); do { if ((bytes=read(fdrd,buffer,sizeof(buffer)))<0) {printf("eroare la read"); break;} if (write(cl,buffer,bytes)<0) {printf("eroare la write"); break;} sum=sum+bytes; } while (bytes==4); close(fdrd); return sum; }
C
#ifndef VALIDATE_H #define VALIDATE_H #include <stdbool.h> #include "definitions.h" static inline bool squareOnBoard(const int square) { return filesBoard[square] != OFFBOARD; } static inline bool boardSideValid(const int boardSide) { return (boardSide == WHITE || boardSide == BLACK); } static inline bool fileRankValid(const int fileRank) { return (fileRank >= 0 && fileRank <= 7); } static inline bool pieceValidateEmpty(const int piece) { return (piece >= EMPTY_SQR && piece <= blackKing); } static inline bool pieceValidate(const int piece) { // #ifdef DEBUG // fprintf(stderr, "piece: %d\n", piece); // #endif return (piece >= whitePwn && piece <= blackKing); } #endif /* VALIDATE_H */
C
#include <stdio.h> #include <stdlib.h> int main() { int i; int *p; int a[5] = { 3, 6, 7, 1, 4 }; for (p = a; p<a + 5; p++) { *p = 100; } for (i = 0; i<5; i++) printf("a[%d]=%d\n", i, a[i]); system("pause"); }
C
/********************** * Hello Webcam * OpenCV Demo * Cooper Bills (csb8@cornell.edu) *********************/ #include <stdio.h> #include <unistd.h> #include <math.h> #include <time.h> #include <opencv/highgui.h> // highgui.h contains openCV gui elements #include <main.h> // Main function int main() { CvCapture* captureDevice; // our webcam handler IplImage* currentFrame; // where we'll store the current frame captureDevice = cvCaptureFromCAM(1); // get webcam handler. if(!captureDevice) { printf("Error opening webcam. Exiting. \n"); return -1; } // Create a window to display our webcam in cvNamedWindow("original", CV_WINDOW_AUTOSIZE); cvNamedWindow("modified", CV_WINDOW_AUTOSIZE); cvNamedWindow("extMask", CV_WINDOW_AUTOSIZE); cvNamedWindow("object1", CV_WINDOW_AUTOSIZE); cvNamedWindow("object1_gray", CV_WINDOW_AUTOSIZE); cvNamedWindow("trackbars", CV_WINDOW_AUTOSIZE); cvCreateTrackbar("H_min", "trackbars", &H_min, 360, NULL); cvCreateTrackbar("H_max", "trackbars", &H_max, 360, NULL); cvCreateTrackbar("S_min", "trackbars", &S_min, 255, NULL); cvCreateTrackbar("S_max", "trackbars", &S_max, 255, NULL); cvCreateTrackbar("V_min", "trackbars", &V_min, 255, NULL); cvCreateTrackbar("V_max", "trackbars", &V_max, 255, NULL); cvCreateTrackbar("HOUGH_PARAM_1", "trackbars", &HOUGH_PARAM_1, 256, NULL); cvCreateTrackbar("HOUGH_PARAM_2", "trackbars", &HOUGH_PARAM_2, 256, NULL); cvCreateTrackbar("SNG_ERODE_SIZE", "trackbars", &SNG_ERODE_SIZE, 20, NULL); cvCreateTrackbar("SNG_MEDIAN_BLUR", "trackbars", &SNG_MEDIAN_BLUR, 21, NULL); cvCreateTrackbar("SNG_GAUSSIAN_BLUR", "trackbars", &SNG_GAUSSIAN_BLUR, 21, NULL); cvCreateTrackbar("SNG_TRESHOLD", "trackbars", &SNG_TRESHOLD, 256, NULL); cvCreateTrackbar("CANNY_PARAM_1", "trackbars", &CANNY_PARAM_1, 256, NULL); cvCreateTrackbar("CANNY_PARAM_2", "trackbars", &CANNY_PARAM_2, 256, NULL); cvCreateTrackbar("SNG_DILATE_SIZE", "trackbars", &SNG_DILATE_SIZE, 20, NULL); cvCreateTrackbar("SNG_PERC_CUTOFF", "trackbars", &SNG_PERC_CUTOFF, 100, NULL); cvCreateTrackbar("SNG_DISTORTION_RATIO", "trackbars", &SNG_DISTORTION_RATIO, 10, NULL); // Calibrate Camera calibrateCamera(captureDevice); int key = -1; // while there is no key press by the user, CvVideoWriter* vidOriWriter; CvVideoWriter* vidModWriter; char timeStr[60]; char fname_ori[68]; char fname_mod[68]; trackResults trackRes[MAX_NEIGHBOURS + 1]; while(key == -1) { if(WRITE_VIDEO == 1) { // Write video to file cvWriteFrame(vidModWriter,currentFrame); currentFrame = cvQueryFrame(captureDevice); // get current frame cvFlip(currentFrame,currentFrame,1); cvWriteFrame(vidOriWriter,currentFrame); }else{ currentFrame = cvQueryFrame(captureDevice); // get current frame cvFlip(currentFrame,currentFrame,1); } // check for errors: if(!currentFrame) { printf("Current frame not found.\n"); continue; } // Display the current frame in the window we created earlier trackObjects(currentFrame,&trackRes); int i=0; CvFont font; cvInitFont(&font, CV_FONT_VECTOR0, 0.25, 0.5, 0, 1.5, 8); //rate of width and height is 1:2 double dist; while(trackRes[i].x_p != -1) { dist = area2distance(trackRes[i].area_p); printf("Object %i at distance %f found at (%i,%i)\n", i, dist, trackRes[i].x_p, trackRes[i].y_p); cvCircle(currentFrame,cvPoint(trackRes[i].x_p,trackRes[i].y_p),sqrt(trackRes[i].area_p/M_PI),cvScalar(0,255,0,0),1,8,0); char str[10]; sprintf(str,"(%i, %i, %0.2f m)",trackRes[i].x_p,trackRes[i].y_p,dist); cvPutText(currentFrame,str,cvPoint(trackRes[i].x_p,trackRes[i].y_p),&font,cvScalar(0,255,0,0)); i++; } cvShowImage("original", currentFrame); // Wait for user input for 30ms, cvWaitKey return the user's // keypress, or -1 if time limit is reached. (0 = wait forever) key = cvWaitKey(100); switch(key) { case -1 : break; case 114 : if(WRITE_VIDEO==1) { printf("Stopped recording of files %s_ori.avi and _mod.avi\n",timeStr); cvWriteFrame(vidModWriter,currentFrame); cvReleaseVideoWriter(&vidOriWriter); cvReleaseVideoWriter(&vidModWriter); WRITE_VIDEO = 0; }else{ time_t rawtime; time(&rawtime); struct tm *info; info = localtime(&rawtime); strftime(timeStr,60,"/home/fred/workspace/recordings/%Y-%m-%d-%H-%M-%S",info); strcpy(fname_ori,timeStr); strcpy(fname_mod,timeStr); strcat(fname_ori,"_ori.avi"); strcat(fname_mod,"_mod.avi"); printf("Starting recording to files %s_ori.avi and _mod.avi\n",timeStr); vidOriWriter = cvCreateVideoWriter(fname_ori,CV_FOURCC('F','F','V','1'),10,cvSize(currentFrame->width,currentFrame->height),1); vidModWriter = cvCreateVideoWriter(fname_mod,CV_FOURCC('F','F','V','1'),10,cvSize(currentFrame->width,currentFrame->height),1); WRITE_VIDEO = 1; } key = -1; break; case 27 : break; default: printf("Pressed key %i",key); key = -1; break; } } // Appropreate Cleanup cvReleaseCapture(&captureDevice); cvReleaseImage(&currentFrame); cvDestroyAllWindows(); return 0; } IplImage* processImage(IplImage* currentFrame) { IplImage* hsvFrame; IplImage* tresholdFrame; hsvFrame = cvCreateImage(cvGetSize(currentFrame), 8, 3); tresholdFrame = cvCreateImage(cvGetSize(currentFrame), 8, 1); //convert frame from BGR to HSV colorspace cvCvtColor(currentFrame, hsvFrame, CV_BGR2HSV); if(H_max > 180) { // Adjust for circular Hue value IplImage* tresholdFrame2; tresholdFrame2 = cvCreateImage(cvGetSize(currentFrame), 8, 1); cvInRangeS(hsvFrame,cvScalar(H_min,S_min,V_min, 0),cvScalar(180,S_max,V_max, 0),tresholdFrame); cvInRangeS(hsvFrame,cvScalar(0,S_min,V_min, 0),cvScalar(H_max-180,S_max,V_max, 0),tresholdFrame2); cvOr(tresholdFrame,tresholdFrame2,tresholdFrame,NULL); }else{ cvInRangeS(hsvFrame,cvScalar(H_min,S_min,V_min, 0),cvScalar(H_max,S_max,V_max, 0),tresholdFrame); } //Create erode and dialate elements IplConvKernel* erodeElm = cvCreateStructuringElementEx(6,6,3,3,CV_SHAPE_RECT,NULL); IplConvKernel* dialateElm = cvCreateStructuringElementEx(20,20,10,10,CV_SHAPE_RECT,NULL); //Erode and dialate treshold cvErode(tresholdFrame,tresholdFrame,erodeElm,1); cvDilate(tresholdFrame,tresholdFrame,dialateElm,1); cvSmooth(tresholdFrame,tresholdFrame,CV_GAUSSIAN,5,0,0,0); return tresholdFrame; } void trackObjects(IplImage* currentFrame,trackResults* dest) { IplImage* tresholdFrame; IplImage* tresholdClone; tresholdFrame = cvCreateImage(cvGetSize(currentFrame), 8, 1); tresholdClone = cvCreateImage(cvGetSize(currentFrame), 8, 1); cvSet(tresholdFrame, cvScalar(0,0,0,0),NULL); cvSet(tresholdClone, cvScalar(0,0,0,0),NULL); tresholdFrame = processImage(currentFrame); cvShowImage("modified",tresholdFrame); //Create clone for contours cvCopy(tresholdFrame,tresholdClone,NULL); // Enable/disable lecagy blob fallback int legacy_blob_fallback = 0; //Track CvMemStorage *mem; mem = cvCreateMemStorage(0); CvSeq *contours = 0; int blobs_found = 0; int j = 0; int circles_found = 0; int t = cvFindContours(tresholdClone, mem, &contours, sizeof(CvContour), CV_RETR_CCOMP, CV_CHAIN_APPROX_SIMPLE, cvPoint(0,0)); if (t>MAX_NEIGHBOURS) { printf("Please adjust filter, more than %i blobs found.\n",MAX_NEIGHBOURS); }else{ trackResults tmp_results[t]; IplImage* maskFrame; maskFrame = cvCreateImage(cvGetSize(tresholdFrame), 8, 1); cvSet(maskFrame, cvScalar(0,0,0,0),NULL); for(; contours != 0; contours = contours->h_next) { CvMoments moment; cvMoments(contours, &moment, 1); double m00 = moment.m00; if(m00>ELM_MIN_AREA && m00<ELM_MAX_AREA) { double m10 = moment.m10; double m01 = moment.m01; int x = m10/m00; int y = m01/m00; tmp_results[blobs_found].x_p = x; tmp_results[blobs_found].y_p = y; tmp_results[blobs_found].area_p = m00; // Draw rectangle to show cutout for detailed object detection cvRectangle(maskFrame,cvPoint(x-sqrt(m00/M_PI),y-sqrt(m00/M_PI)),cvPoint(x+sqrt(m00/M_PI),y+sqrt(m00/M_PI)),cvScalar(255,255,255,0),1,8,0); blobs_found++; } } cvShowImage("extMask", maskFrame); if(blobs_found>0) { for(j=0; j<blobs_found; j++) { // Calculate range & safety factor of found blob to determine size of rectangle int obj_r = sqrt(tmp_results[j].area_p/M_PI); double safety_f = 1.5; // Crop object from currentframe cvSetImageROI(currentFrame,cvRect(tmp_results[j].x_p - safety_f*obj_r, tmp_results[j].y_p - safety_f*obj_r, 2*safety_f*obj_r, 2*safety_f*obj_r)); IplImage* object1_crop = cvCreateImage(cvGetSize(currentFrame),currentFrame->depth,currentFrame->nChannels); cvSet(object1_crop, cvScalar(0,0,0,0),NULL); cvCopy(currentFrame,object1_crop,NULL); cvResetImageROI(currentFrame); IplImage* object1 = cvCreateImage(cvSize(200,200),8,3); cvResize(object1_crop,object1,CV_INTER_LINEAR); double resizeScale = ((double) object1_crop->width) / object1->width; // Allocate other used frames //IplImage* object1_hsv = cvCreateImage(cvGetSize(object1),object1->depth,object1->nChannels); IplImage* object1_gray = cvCreateImage(cvGetSize(object1),object1->depth,1); IplImage* object1_gray_contour = cvCreateImage(cvGetSize(object1),object1->depth,1); /* Using simple colour conversion (did not work really well) cvCvtColor(object1, object1_gray, CV_BGR2GRAY ); cvCvtColor(object1, object1, CV_BGR2YCrCb ); cvCvtColor(object1, object1_hsv, CV_BGR2YCrCb ); IplImage* object1_Y = cvCreateImage(cvGetSize(object1),object1->depth,1); IplImage* object1_cr = cvCreateImage(cvGetSize(object1),object1->depth,1); IplImage* object1_cb = cvCreateImage(cvGetSize(object1),object1->depth,1); cvSplit(object1,object1_Y,object1_cr,object1_cb,NULL); */ int col, row; uchar B, G, R; for( row = 0; row < object1->height; row++ ) { for ( col = 0; col < object1->width; col++ ) { B = object1->imageData[object1->widthStep * row + col * 3]; G = object1->imageData[object1->widthStep * row + col * 3 + 1]; R = object1->imageData[object1->widthStep * row + col * 3 + 2]; double gr = R*R/(256) *(R * R - B * B - G * G) / (R * R); if(gr > 0) { object1_gray->imageData[object1_gray->widthStep * row + col] = round(gr); }else{ object1_gray->imageData[object1_gray->widthStep * row + col] = 0; } } } IplConvKernel* erodeElm = cvCreateStructuringElementEx(SNG_ERODE_SIZE,SNG_ERODE_SIZE,SNG_ERODE_SIZE/2,SNG_ERODE_SIZE/2,CV_SHAPE_RECT,NULL); cvErode(object1_gray,object1_gray,erodeElm,1); cvSmooth(object1,object1,CV_MEDIAN,floor(SNG_MEDIAN_BLUR/2)*2+1,0,0,0); cvSmooth(object1_gray,object1_gray,CV_GAUSSIAN,floor(SNG_GAUSSIAN_BLUR/2)*2+1,0,0,0); cvThreshold(object1_gray,object1_gray,SNG_TRESHOLD,255,CV_THRESH_BINARY); cvCanny(object1_gray,object1_gray,CANNY_PARAM_1,CANNY_PARAM_2,3); IplConvKernel* dilateElm = cvCreateStructuringElementEx(SNG_DILATE_SIZE,SNG_DILATE_SIZE,SNG_DILATE_SIZE/2,SNG_DILATE_SIZE/2,CV_SHAPE_RECT,NULL); cvDilate(object1_gray,object1_gray,dilateElm,1); /* HSV filtering (did not work really well) IplImage* object1_gray_nomask = cvCreateImage(cvGetSize(object1),object1->depth,1); cvCvtColor(object1, object1_hsv, CV_BGR2HSV); cvCvtColor(object1, object1_gray_nomask, CV_BGR2GRAY ); IplImage* object_mask1 = cvCreateImage(cvGetSize(object1),object1->depth,1); IplImage* object_mask2 = cvCreateImage(cvGetSize(object1),object1->depth,1); cvInRangeS(object1_hsv,cvScalar(160,50,120, 0),cvScalar(180,256,256, 0),object_mask1); cvInRangeS(object1_hsv,cvScalar(0,50,120, 0),cvScalar(10,256,256, 0),object_mask2); cvOr(object_mask1,object_mask2,object_mask1,NULL); //Create erode and dialate elements IplConvKernel* erodeElm = cvCreateStructuringElementEx(8,8,4,4,CV_SHAPE_RECT,NULL); IplConvKernel* dialateElm = cvCreateStructuringElementEx(20,20,10,10,CV_SHAPE_RECT,NULL); //Erode and dialate treshold //cvErode(object_mask1,object_mask1,erodeElm,1); //cvDilate(object_mask1,object_mask1,dialateElm,1); //cvSmooth(object_mask1,object_mask1,CV_GAUSSIAN,11,0,0,0); cvSet(object1_gray, cvScalar(0,0,0,0),NULL); cvCopy(object1_gray_nomask,object1_gray,object_mask1);*/ // Find cirlce if (HOUGH_TRANS == 1) { CvMemStorage *mem; mem = cvCreateMemStorage(0); CvSeq* circles = cvHoughCircles(object1_gray,mem,CV_HOUGH_GRADIENT,1.5, object1_gray->width/(2*2*safety_f),HOUGH_PARAM_1,HOUGH_PARAM_2,object1_gray->width/(6*2*safety_f),2*object1_gray->width); if(circles->total > 10 || circles->total == 0) { printf("Please adjust circle filter, %i circles found. Falling back to blob tracking.\n",circles->total); if(legacy_blob_fallback==1) { dest[circles_found] = tmp_results[j]; //update circles_found counter circles_found++; } }else{ int c; for(c=0;c<circles->total;c++) { float* p = (float*) cvGetSeqElem( circles, c); // Calc area and see if >MIN <MAX double obj_area = M_PI * p[2] * p[2] * resizeScale * resizeScale; if(obj_area>ELM_MIN_AREA && obj_area<ELM_MAX_AREA) { // Calc position of frame & object within frame int frame_x = tmp_results[j].x_p - safety_f*obj_r; int frame_y = tmp_results[j].y_p - safety_f*obj_r; int obj_x = (frame_x>0)*frame_x + p[0]*resizeScale; int obj_y = (frame_y>0)*frame_y + p[1]*resizeScale; // Save to dest dest[circles_found].x_p = obj_x; dest[circles_found].y_p = obj_y; dest[circles_found].area_p = obj_area; //update circles_found counter if(circles_found==0) { cvShowImage("object1_gray",object1_gray); cvShowImage("object1",object1); } circles_found++; } } } }else{ cvSet(object1_gray_contour, cvScalar(0,0,0,0),NULL); cvCopy(object1_gray,object1_gray_contour,NULL); CvMemStorage *mem; mem = cvCreateMemStorage(0); CvSeq *contours_obj = 0; int t = cvFindContours(object1_gray_contour, mem, &contours_obj, sizeof(CvContour), CV_RETR_CCOMP, CV_CHAIN_APPROX_SIMPLE, cvPoint(0,0)); if(t>SNG_MAX_NEIGHBOURS || t==0) { switch(t) { case 0 : printf("No contours found. Fallback.\n"); break; default : printf("Too many neighbouring contours found. Fallback.\n"); break; } }else{ for(; contours_obj != 0; contours_obj = contours_obj->h_next) { CvMoments obj_moment; cvMoments(contours_obj, &obj_moment, 1); if(obj_moment.m00 > (SNG_PERC_CUTOFF/(float)100) * object1->width * object1->height) { double obj_area = obj_moment.m00 * resizeScale * resizeScale; if(obj_area>ELM_MIN_AREA && obj_area<ELM_MAX_AREA) { float obj_radius; CvPoint2D32f obj_centre; cvMinEnclosingCircle(contours_obj,&obj_centre,&obj_radius); int frame_x = tmp_results[j].x_p - safety_f*obj_r; int frame_y = tmp_results[j].y_p - safety_f*obj_r; int obj_x = (frame_x>0)*frame_x + obj_centre.x * resizeScale; int obj_y = (frame_y>0)*frame_y + obj_centre.y * resizeScale; float circ_area = M_PI * obj_radius * resizeScale * obj_radius * resizeScale; if(circ_area < SNG_DISTORTION_RATIO*obj_area) { dest[circles_found].x_p = obj_x; dest[circles_found].y_p = obj_y; dest[circles_found].area_p = circ_area; //update circles_found counter if(circles_found==0) { cvCircle(object1,cvPoint(obj_centre.x,obj_centre.y),obj_radius,cvScalar(0,0,255,0),1,8,0); cvShowImage("object1_gray",object1_gray); cvShowImage("object1",object1); } circles_found++; }else{ //printf("Object with dispr circle rejected: %f > 2*%f\n",circ_area,obj_area); } }else{ //printf("Object with area %f rejected (sizef: %f pixArea: %f)\n",obj_area,resizeScale,obj_moment.m00); } }else{ //printf("Object rejected taking up only %f percent of frame.\n",100*obj_moment.m00/(object1->width*object1->height)); } } } } } } } for(j=MAX_NEIGHBOURS + 1; j>=circles_found; j--) { dest[j].x_p = -1; dest[j].y_p = -1; dest[j].area_p = -1; } } /* void translate_pb(trackResults* self) { // translate self.x_p / y_p / area_p (pixel coordinate system) to self.x_b / y_b / z_b (body coordinate system) } */ void calibrateCamera(CvCapture* captureDevice) { IplImage* cal_Frame; if (access("./cal_1m.jpg",F_OK) != -1) { printf("Calibration image found.\n"); cal_Frame = cvLoadImage("./cal_1m.jpg",CV_LOAD_IMAGE_COLOR); }else{ int c_key = -1; printf("Please hold marker at 1m distance and press any key.\n"); trackResults cal_trackRes[MAX_NEIGHBOURS + 1]; while(c_key == -1) { cal_Frame = cvQueryFrame(captureDevice); trackObjects(cal_Frame,&cal_trackRes); if(cal_trackRes[0].x_p != -1) { cvCircle(cal_Frame,cvPoint(cal_trackRes[0].x_p,cal_trackRes[0].y_p),sqrt(cal_trackRes[0].area_p/M_PI),cvScalar(0,255,0,0),1,8,0); } cvShowImage("original", cal_Frame); c_key = cvWaitKey(10); } cal_Frame = cvQueryFrame(captureDevice); cvSaveImage("./cal_1m.jpg",cal_Frame,0); } trackResults cal_trackRes[MAX_NEIGHBOURS + 1]; trackObjects(cal_Frame,&cal_trackRes); if(cal_trackRes[0].x_p != -1) { CAM_FOCAL = (1*sqrt(cal_trackRes[0].area_p/M_PI))/MARKER_RADIUS; printf("Calibration ball has area of %f\n",cal_trackRes[0].area_p); printf("Determined camera focal length of %f m\n",CAM_FOCAL); }else{ printf("Error: calibration 1m failed.\n"); } } double area2distance(double elmArea) { return MARKER_RADIUS*CAM_FOCAL/sqrt(elmArea/M_PI); }
C
/* 4 使用嵌套循环,按下面的格式打印字母: A BC DEF GHIJ KLMNO PQRSTU 如果你的系统不使用以数字顺序编码的代码,请参照练习3的方案解 决。 */ #include <stdio.h> #define SIZE 27 int main(int argc, char const *argv[]) { int x = 65; for(int i = 0; i < 6; i++) { for(int j = 0; j <= i; j++) { printf("%c", x++); } printf("\n"); } return 0; }
C
#include <stdio.h> #include <stdlib.h> typedef int Item; #define key(A) (A) #define less(A, B) (key(A) < key(B)) #define exch(A, B) { Item t = A; A = B; B = t; } #define compexch(A, B) if (less(B, A)) exch(A, B) void insertion(Item a[], int l, int r) { int i; for (i = r; i > l; i--) compexch(a[i-1], a[i]); for (i = l+2; i <= r; i++) { int j = i; Item v = a[i]; while (less(v, a[j-1])) { a[j] = a[j-1]; j--; } a[j] = v; } } int main(int argc, char *argv[]) { int i, N = atoi(argv[1]), sw = atoi(argv[2]); int *a = malloc(N*sizeof(int)); srand(1); if (sw) for (i = 0; i < N; i++) a[i] = 1000*(1.0*rand()/RAND_MAX); else for (N = 0; scanf("%d", &a[N]) == 1; N++); insertion(a, 0, N-1); for (i = 0; i < N; i++) printf("%3d ", a[i]); printf("\n"); return 0; }
C
/* =========================================================================== File: system_main.c Author: Clinton Freeman Created on: Sep 29, 2010 =========================================================================== */ #include "headers/SDL/SDL.h" #include "headers/SDL/SDL_main.h" #include "headers/SDL/SDL_opengl.h" #include "headers/common.h" #include "headers/mathlib.h" #include "headers/input_public.h" #include "headers/renderer_public.h" #include "headers/world_public.h" typedef struct { int current; int updated; int delta; int accumulated; } Timer; static Timer timer; static void timer_init(); static void timer_update(); /* * SDL_main */ int SDL_main(int argc, char* argv[]) { SDL_Event event; SDL_Surface *screen, *icon; putenv(strdup("SDL_VIDEO_CENTERED=1")); if(SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER) != 0) { printf("Unable to initialize SDL: %s\n", SDL_GetError()); return EXIT_FAILURE; } icon = SDL_LoadBMP("gui/icon.bmp"); SDL_WM_SetIcon(icon, NULL); SDL_WM_SetCaption("Convex Hull Testing", "Convex Hull Testing"); SDL_ShowCursor(SDL_DISABLE); SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, etrue); //Initialize window // | SDL_FULLSCREEN screen = SDL_SetVideoMode(WINDOW_WIDTH, WINDOW_HEIGHT, 32, SDL_OPENGL | SDL_NOFRAME); if(!screen) { printf("Unable to set video mode: %s\n", SDL_GetError()); return EXIT_FAILURE; } SDL_WarpMouse(512.0, 384.0); //gameState = STATE_MAINMENU; timer_init(); renderer_init(); world_init(); //model_init(); //Main loop while(!user_exit) { //Handle input while(SDL_PollEvent(&event)) { switch(event.type) { case SDL_KEYDOWN: input_keyDown(event.key.keysym.sym); break; case SDL_KEYUP: input_keyUp(event.key.keysym.sym); break; case SDL_MOUSEMOTION: input_mouseMove(event.motion.x, event.motion.y); break; case SDL_QUIT: user_exit = etrue; } } timer_update(); while(timer.accumulated >= TIMESTEP) { input_update(); world_update(); timer.accumulated -= TIMESTEP; } world_lerpPositions(timer.accumulated); renderer_drawFrame(); } SDL_Quit(); return EXIT_SUCCESS; } /* * timer_init * Initializes timer struct to zero, gets current time. */ static void timer_init() { timer.updated = timer.delta = timer.accumulated = 0; timer.current = SDL_GetTicks(); } /* * timer_update * Gets time since last update, accumulates the difference. */ static void timer_update() { timer.updated = SDL_GetTicks(); timer.delta = timer.updated - timer.current; timer.current = timer.updated; timer.accumulated += timer.delta; }