language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
#include "lists.h" #include <string.h> /** * add_node_end - function will add new node to end of list * @head: represents pointer to pointer of first node * @str: represents string to be duplicated * Return: function will return address to new element */ list_t *add_node_end(list_t **head, const char *str) { list_t *new; list_t *buffer; new = malloc(sizeof(*new)); if (new == NULL) { free(new); return (NULL); } new->str = strdup(str); new->len = strlen(str); new->next = NULL; if (*head == NULL) { *head = new; return (new); } buffer = *head; while (buffer->next != NULL) buffer = buffer->next; buffer->next = new; return (new); }
C
#include<stdio.h> void swap(double *pa, double *pb); void line_up(double *maxp, double *midp, double *minp); int main (void) { double max, mid, min; printf("silsu three : "); scanf("%1f%1f%1f", &max, &mid, &min); line_up(&max, &mid, &min); printf("real : %.1lf, %.1lf, %.1lf \n", max, mid, min); return 0; } void swap(double *pa, double *pb) { double temp; temp = *pa; *pa = *pb; *pb = temp; } void line_up(double *maxp, double *midp, double *minp) { if(*maxp < *midp) { swap(&*maxp,&*midp); } if(*maxp < *minp) { swap(&*maxp,&*minp); } if(*midp < *minp) { swap(&*midp,&*minp); } }
C
#include<stdio.h> #include<string.h> #include<errno.h> #include<stdlib.h> #include<assert.h> #include "bst.h" // #include "bst.c" #include "pds.h" struct PDS_RepoInfo repo_handle; int deleted_record_offset[105]; int findfileSize(char f_n[]) { FILE* fp = (FILE *)fopen(f_n, "r"); // opening a file in read mode fseek(fp, 0L, SEEK_END); int res = ftell(fp); //counting the size of the file fclose(fp); //closing the file return res; } int isEmpty(FILE *file){ long savedOffset = ftell(file); fseek(file, 0, SEEK_END); if (ftell(file) == 0){ return 1; } fseek(file, savedOffset, SEEK_SET); return 0; } int pds_open(char *repo_name,int rec_size) { // assert(rec_size==sizeof(struct PDS_RepoInfo)); char repo_file[30]; char ndx_file[30]; if(repo_handle.repo_status==PDS_REPO_OPEN) return PDS_REPO_ALREADY_OPEN; strcpy(repo_handle.pds_name,repo_name); strcpy(repo_file,repo_name); strcat(repo_file,".dat"); strcpy(ndx_file,repo_name); strcat(ndx_file,".ndx"); repo_handle.pds_data_fp=(FILE *)fopen(repo_file,"rb+"); if(repo_handle.pds_data_fp==NULL) perror(repo_file); repo_handle.pds_ndx_fp=(FILE *)fopen(ndx_file,"rb"); if(repo_handle.pds_ndx_fp==NULL) perror(ndx_file); repo_handle.repo_status=PDS_REPO_OPEN; repo_handle.rec_size=rec_size; repo_handle.pds_bst=NULL; /*added from here*/ struct PDS_NdxInfo *read_data; if(isEmpty(repo_handle.pds_ndx_fp)) memset(deleted_record_offset,-1,sizeof(deleted_record_offset)); else fread(deleted_record_offset,sizeof(int),100,repo_handle.pds_ndx_fp); while(feof(repo_handle.pds_ndx_fp)==0) { read_data=(struct PDS_NdxInfo *)malloc(sizeof(struct PDS_NdxInfo)); fread(read_data,sizeof(struct PDS_NdxInfo),1,repo_handle.pds_ndx_fp); bst_add_node(&repo_handle.pds_bst,read_data->key,read_data); } /*till here*/ return PDS_SUCCESS; } int put_rec_by_key(int key,void *rec) { int offset,status,writesize; struct PDS_NdxInfo *ndx_entry; fseek(repo_handle.pds_data_fp,0,SEEK_END); offset=ftell(repo_handle.pds_data_fp); int ind=-1; for(int i=0;i<100;i++) { if(deleted_record_offset[i]>=0) { ind=i; offset=deleted_record_offset[i]; break; } } ndx_entry=(struct PDS_NdxInfo *)malloc(sizeof(struct PDS_NdxInfo)); ndx_entry->key=key; ndx_entry->offset=offset; int bst_status=bst_add_node(&repo_handle.pds_bst,key,ndx_entry); if(bst_status!=BST_SUCCESS){ free(ndx_entry); return PDS_ADD_FAILED; } if(ind>=0) deleted_record_offset[ind]=-1; fseek(repo_handle.pds_data_fp,offset,SEEK_SET); fwrite(&key,sizeof(int),1,repo_handle.pds_data_fp); fwrite(rec, repo_handle.rec_size, 1, repo_handle.pds_data_fp); return PDS_SUCCESS; } int get_rec_by_ndx_key(int key, void *rec) { int offset; struct BST_Node *temp_node = bst_search(repo_handle.pds_bst, key); if (temp_node == NULL) return PDS_REC_NOT_FOUND; else{ struct PDS_NdxInfo *ndx_entry = (struct PDS_NdxInfo *)(temp_node->data); offset = ndx_entry->offset; fseek(repo_handle.pds_data_fp, offset, SEEK_SET); int tmpkey; fread(&tmpkey,sizeof(int),1,repo_handle.pds_data_fp); fread(rec, repo_handle.rec_size, 1, repo_handle.pds_data_fp); return PDS_SUCCESS; } } void bst_preorder(struct BST_Node *roott) { if(roott==NULL) { return; } fwrite((struct PDS_NdxInfo*)(roott->data),sizeof(struct PDS_NdxInfo),1,repo_handle.pds_ndx_fp); bst_preorder(roott->left_child); bst_preorder(roott->right_child); } int pds_close() { /*added from here*/ char ndx_file[30]; strcpy(ndx_file,repo_handle.pds_name); strcat(ndx_file,".ndx"); fclose(repo_handle.pds_ndx_fp); repo_handle.pds_ndx_fp=(FILE*)fopen(ndx_file,"wb"); fwrite(deleted_record_offset,sizeof(int),100,repo_handle.pds_ndx_fp); bst_preorder(repo_handle.pds_bst); fclose(repo_handle.pds_ndx_fp); strcpy(repo_handle.pds_name, ""); fclose(repo_handle.pds_data_fp); /*till here*/ bst_destroy(repo_handle.pds_bst); repo_handle.repo_status = PDS_REPO_CLOSED; return PDS_SUCCESS; } int get_rec_by_non_ndx_key( void *key, /* The search key */ void *rec, /* The output record */ int (*matcher)(void *rec, void *key), /*Function pointer for matching*/ int *io_count /* Count of the number of records read */ ) { fseek(repo_handle.pds_data_fp,0L,SEEK_SET); *io_count=0; while(feof(repo_handle.pds_data_fp)==0) { // struct PDS_RepoInfo *cur; int curoffset=ftell(repo_handle.pds_data_fp); int flag=1; for(int j=0;j<100;j++) { if(deleted_record_offset[j]==curoffset) { flag=0;break; } } int tmpkey; fread(&tmpkey,sizeof(int),1,repo_handle.pds_data_fp); fread(rec,repo_handle.rec_size,1,repo_handle.pds_data_fp); if(!flag)continue; (*io_count)++; int er=matcher(rec,key); if(er>1)return er; else if(er==0)return 0; } rec=NULL; return 0; } int update_by_key( int key, void *newrec ) { int offset; struct BST_Node *temp_node = bst_search(repo_handle.pds_bst, key); if (temp_node == NULL) return PDS_REC_NOT_FOUND; else{ struct PDS_NdxInfo *ndx_entry = (struct PDS_NdxInfo *)(temp_node->data); offset = ndx_entry->offset; fseek(repo_handle.pds_data_fp, offset, SEEK_SET); fwrite(&key,sizeof(int),1,repo_handle.pds_data_fp); fwrite(newrec, repo_handle.rec_size, 1, repo_handle.pds_data_fp); return PDS_SUCCESS; } } int delete_by_key( int key ) { int offset; struct BST_Node *temp_node = bst_search(repo_handle.pds_bst, key); if (temp_node == NULL) return PDS_REC_NOT_FOUND; else { struct PDS_NdxInfo *ndx_entry = (struct PDS_NdxInfo *)(temp_node->data); offset = ndx_entry->offset; int flag=0; for(int i=0;i<100;i++) { if(deleted_record_offset[i]==-1) { deleted_record_offset[i]=offset;flag=1; break; } } if(!flag)return PDS_FILE_ERROR; bst_del_node(&repo_handle.pds_bst,key); return PDS_SUCCESS; } }
C
/** ****************************************************************************** * @file : 24c02.h * @brief : header for 24c02.c file. * AT24Cxx 读写模块. ****************************************************************************** * * ****************************************************************************** */ #ifndef __24C02_H #define __24C02_H #include "stm32f1xx_hal.h" #define ADDR_AT24C02_Write 0xA0 #define ADDR_AT24C02_Read 0xA1 /************************************************************** --24C02存放数据定义 **************************************************************/ #define ADDR_WIFI_NAME 0x0 #define ADDR_WIFI_PASS 0x20 /************************************************************** --24C02驱动函数 **************************************************************/ /** * @brief 从24c02读取 1Byte 数据 * @param ReadAddr 读取地址 0-0xff * @retval 数据 */ uint8_t AT24C02_ReadOneByte(uint16_t ReadAddr); /** * @brief 从24c02读取数据 * @param ReadAddr 读取地址 0-0xff * @param readSize 读取大小 * @param readBuffer 读取缓冲区 * @retval None */ void AT24C02_Read(uint16_t ReadAddr, uint8_t readSize, uint8_t* readBuffer); /** * @brief 写入1Byte数据至24c02 * @param WriteAddr 地址 0-0xff * @retval None */ void AT24C02_WriteOneByte(uint16_t WriteAddr, uint8_t DataToWrite); /** * @brief 写入一页数据至24c02 * @param PageAddr 页 0-32 * @param WriteAddr 地址 0-8 * @param DataToWrite 数据,8B大小 * @retval None */ void AT24C02_WriteOnePage(uint16_t PageAddr, uint16_t WriteAddr, uint8_t *DataToWrite); /** * @brief 擦除24c02所有数据(为0) * @retval None */ void AT24C02_FlushAll(void); #endif
C
#include <stdio.h> #include <string.h> #include <stdlib.h> int simple() { char a[] = "a"; char b[] = "bb"; char c[] = "cc"; char *data = NULL; int total = 0; total = bee_tlv_appender(1, strlen(a), a, &data, total); total = bee_tlv_appender(2, strlen(b), b, &data, total); total = bee_tlv_appender(3, strlen(c), c, &data, total); noly_hexdump(data, total); return 0; } int cloud_agent_command() { char *tlv = NULL; //1. switch command type int total = 0; unsigned char sw[2]; sw[0] = 0x00; sw[1] = 0x02; total = bee_tlv_appender(0, 2, sw, &tlv, total ); //2. tlv class unsigned char cla[2]; cla[0] = 0x00; cla[1] = 0x08; total = bee_tlv_appender(1, 2, cla, &tlv, total ); //3. tlv cmd char cmd[]= "set_power"; total = bee_tlv_appender(2, strlen(cmd), cmd, &tlv, total ); //4. tlv value char val[]= "{\"power\":\"on\"}"; total = bee_tlv_appender(3, strlen(val), val, &tlv, total ); //5. tlv pid char pid[]= "112233445566"; total = bee_tlv_appender(3, strlen(pid), pid, &tlv, total ); //6. tlv nonce char nonce[]= "fb0e4ebc6e61e21b82ac0faf3ade9dbd"; total = bee_tlv_appender(7, strlen(nonce), nonce, &tlv, total ); //7. wrap a total length TLV void *output = NULL; total = bee_tlv_creator(0xffff, total, tlv, &output); printf("Cloud Aget TLV Length: %d\n Value:\n", total); noly_hexdump(output, total); } int main() { simple(); cloud_agent_command(); return 0; }
C
//Q4 - LUCAS MIRANDA - Numero USP: 12542838 #include <stdio.h> void main(){ int matr[][4] = {1,2,3,4,5,6,7,8,9,10,11,12}; //(A) **matr é 1? //VERDADEIRO //**matr é o mesmo que matr[0][0] printf("A) %d\n", **matr ); //(B) *(*(matr+1)+2) é 7? //VERDADEIRO //matr+1 faz o programa avançar uma linha (equivale a [1]), +2 faz o programa avançar 2 elementos (equivale a [1][2]), localização do numero 7. printf("B) %d\n", *(*(matr+1)+2) ); //(C) *(matr[2]+3) é 12? //VERDADEIRO //matr[2] é a terceira linha (cada uma formada por 4), iniciada por 9. O +3 faz o programa andar 3 endereços, chegando até o 12. printf("C) %d\n", *(matr[2]+3) ); //(D) (*(matr+2))[2] é 11? //VERDADEIRO //matr+2 é o mesmo que matr[2], ou seja, a terceira linha, iniciada em 9. O [2] faz o programa pegar o terceiro endereço dessa linha, ou seja, 11. printf("D) %d\n", (*(matr+2))[2] ); //(E) *((*matr)+1) é 5? //FALSO //*matr é equivalente a matr[0], ou seja, a primeira linha. Ja (*matr)+1 é equivalente a matr[0][1], ou seja, o segundo elemento (2) e não o 5. printf("E) %d\n", *((*matr)+1) ); }
C
#include <stdlib.h> #include <stdio.h> #include "stack.h" int main(){ struct Stack* stack = new_stack(); push(stack,3); push(stack,2); push(stack,1); while(stack->size > 0) printf("%d\n", pop(stack)); return 0; }
C
/* * @Author : G.F * @Date : 2021-03-26 00:13:06 * @LastEditTime : 2021-03-26 00:30:05 * @LastEditors : G.F * @FilePath : /CL/format.c * @Description : */ // %d 十进制有符号整数 // %ld 十进制 long 有符号整数 // %u 十进制无符号整数 // %o 八进制表示的整数 // %x 十六进制表示的整数 // %f float 型浮点数 // %lf double 型浮点数 // %e 指数形式的浮点数 // %c 单个字符 // %s sfring // %p 指针的值 #include <stdio.h> int main(){ // 输出整数 int a = 100; printf("a = %d \n", a); //十进制 printf("a = %o \n", a); // 八进制 printf("a = %#o \n", a); // 前导符 printf("a = %x \n", a); //十六进制 printf("a = %#x \n", a); float b = 3.1415926; double c = 2345.3343; printf("b = %f\n", b); printf("c = %lf\n", c); //输出字符,使用%c输出字符,使用%d可以输出字符的ascii码值 char d = 'y'; printf("d = %c %d\n", d, d); printf("%c %d\n", d, d); // y 121 //输出字符串,使用%s //没有专门的变量保存字符串,一般使用数组来保存 char e[] = "hello world"; printf("%s\n", e); //输出地址,使用%p int f=999; //&:取一个变量的地址,一般地址用十六进制数标识 printf("&f = %p\n", &f); return 0; }
C
#include <stdlib.h> #include <stdio.h> #include <limits.h> #include <assert.h> #include "util.h" #include "amino_acids.h" #include "closest_seqs.h" // Define a collection of structures. typedef struct { int seq_idx; int hamming_dist; } index_and_dist; void hamming_distance_considering_unknown(char **ref_seqs, char *query_seqs, int num_refs, int num_bases, int tmp_hamming[num_refs]) { int i, r, len_count_ref, len_count_query; for(r = 0; r < num_refs; r++) { tmp_hamming[r] = 0; len_count_ref = 0; len_count_query = 0; for(i = 0; i < num_bases; i++) { // Ignore the positions in the query sequence that are unknown. if((int)base_to_code(query_seqs[i]) != 4) { len_count_query += 1; // Ignore the position in ref sequence that are unknown. if((int)base_to_code(ref_seqs[r][i] != 4)) { len_count_ref += 1; tmp_hamming[r] += (base_to_code(query_seqs[i]) != base_to_code(ref_seqs[r][i])); } else { printf("unknown nucleotide in the reference sequence\n"); } } } // Gap penalty here is 1/2. // Set the gap penalty using the ratios of addition to len_count and // multiplication by the factor below. tmp_hamming[r]*=2; tmp_hamming[r]+=len_count_query-len_count_ref; } } static int compare_hamming_dsts(const void *p1, const void *p2) { const index_and_dist *w1 = (const index_and_dist *)p1; const index_and_dist *w2 = (const index_and_dist *)p2; return (w1->hamming_dist - w2->hamming_dist); } void knuth_perm_idx_and_dist(index_and_dist *arr, int length) { int i, j; for(i = 0; i < length; i++) { j = rand_lim(i+1); SWAP3(arr[i], arr[j]); } } void closest_sequences(int num_refs, int tmp_hamming[num_refs], int closest_n, int closest_refs[closest_n]) { assert(num_refs > 0); assert(closest_n > 0); int i; index_and_dist dists[num_refs]; for(i = 0; i < num_refs; i++) { dists[i].seq_idx = i; dists[i].hamming_dist = tmp_hamming[i]; } // Initial sort (of the first closest_n elements). qsort(dists, num_refs, sizeof(index_and_dist), compare_hamming_dsts); // Get start end end int start = closest_n-1, end = closest_n-1; int largest_hamming = dists[closest_n].hamming_dist; while(start > 0 && dists[start-1].hamming_dist == largest_hamming) start--; while(end+1 < num_refs && dists[end+1].hamming_dist == largest_hamming) end++; int num_last = end - start + 1; // Knuth perm // Next, randomly permute these indices and choose those to include in // closest_refs. knuth_perm_idx_and_dist(dists+start, num_last); for(i = 0; i < closest_n; i++) closest_refs[i] = dists[i].seq_idx; }
C
#include <stdio.h> int main() { int num[9], max = -100; int i; int important_i; for (i = 0; i < 9; i++) { scanf("%d", &num[i]); if (num[i] > max) { max = num[i]; important_i = i; //remember this 'i' using a variable!! } } printf("%d %d", max, important_i + 1); }
C
#include<stdio.h> int main() { double ans; double n; while(scanf("%lf",&n) != EOF) { ans = (n*(n+1) / 2); printf("%.0lf\n",ans); } return 0; }
C
#include "lab05_Task1.h" // each of the files has 6834 lines #define MAX_SAMPLES_2 6834 void lab05_Task1(int type, int arg_N, float arg_fc, int arg_M) { /* Define all variables*/ /* INSERT CODE HERE */ float data[MAX_SAMPLES_2], time[MAX_SAMPLES_2]; float ss[MAX_SAMPLES_2],bs[MAX_SAMPLES_2]; int j =0,i=0; FILE *sig,*fp; float b_coefs[arg_M+1]; //~ char out[10]; /* Read Files into data vector for raw data and filter with smoothing and blackman*/ /* Check "type" variable (= 1,2,3 or 4) to analyse corresponding ramp or sinus /* file with / without noise. */ /* INSERT CODE HERE */ switch(type) { case 1: sig = fopen("ramp_noise.txt","r"); //~ out[] = "FRN.txt"; fp = fopen ("FRN.txt", "w"); //~ printf(fp, "time\t raw data\t moving average\t windowed sinc"); break; case 2: sig = fopen("sinus_noise.txt","r"); //~ out[] = "FSN.txt"; fp = fopen ("FSN.txt", "w"); //~ printf(fp, "time\t raw data\t moving average\t windowed sinc"); break; case 3: sig = fopen("ramp.txt","r"); //~ out[] = "FR.txt"; fp = fopen ("FR.txt", "w"); //~ printf(fp, "time\t raw data\t moving average\t windowed sinc"); break; case 4: sig = fopen("sinus.txt","r"); //~ out[] = "FS.txt"; fp = fopen ("FS.txt", "w"); //~ printf(fp, "time\t raw data\t moving average\t windowed sinc"); break; default: break; } //printf(fp, "time\t raw data\t moving average\t windowed sinc"); //~ fclose(fp); for(j=0;j<MAX_SAMPLES_2;j++) { fscanf(sig,"%f%*c%f\n",&time[j],&data[j]); } fclose(sig); // Version 2: int counters = 0,counterb = 0; float buf[arg_N],bufb[arg_M+1],arg_coefs[arg_M+1]; blackman_coefs(arg_M,arg_fc,b_coefs); for(i=0;i<MAX_SAMPLES_2;i++){ // smoothing if(counters<arg_N){ buffer_fill(buf,data[i],counters); counters++; // ss[i] = data[i]; } else{ ss[i-(arg_N/2)] = smoothing_filter(buf,arg_N); buffer_update(buf,data[i],arg_N); } // blackman if(counterb<arg_M+1){ buffer_fill(bufb,data[i],counterb); counterb++; // bs[i]=data[i]; } else{ bs[i-arg_M/2] = blackman_filter(bufb,b_coefs,arg_M); buffer_update(bufb,data[i],arg_M+1); } } //~ fp = fopen (out, "w"); fprintf(fp, "time\t raw data\t moving average\t windowed sinc"); for (j=0;j<MAX_SAMPLES_2;j++) { fprintf(fp, "\n%.3f\t%f\t%f\t%f",time[j],data[j],ss[j],bs[j]); } fclose(fp); }
C
int find_pattern(char text[],char pattern[]) { int d = 26; long q = 1e9+7; long p = 0,t = 0; int h = 1; int m = strlen(pattern),l = strlen(text); if(m > l) { return -1; } for(int i = 0;i < m-1;++i) { h = (h*1ll*d)%q; } for(int i = 0;i < m;++i) { p = (p*1ll*d + pattern[i])%q; t = (t*1ll*d + text[i])%q; } /* If all the characters of the pattern ar different then we can slide first j matches as first char of pattern wont match any other j matches for(int i = 0;i <= (l-m);) { if(p == t) { int j; for(j = 0;j < m;++j) { if(pattern[j] != text[i+j]) break; } if(j == m) { return i+1; } if(j == 0) i += 1; else i += j; } //without if future extension is difficult if(i < l-m) t = (d*1ll*(t - (h*1ll*text[i])%q)%q + text[i+m])%q; if(t < 0) t += q; } */ for(int i = 0;i <= (l-m);++i) { if(p == t) { int j; for(j = 0;j < m;++j) { if(pattern[j] != text[i+j]) break; } if(j == m) { return i+1; } } //without if future extension is difficult if(i < l-m) t = (d*1ll*(t - (h*1ll*text[i])%q)%q + text[i+m])%q; if(t < 0) t += q; } return -1; }
C
#include <stdio.h> #define MAXLENGTH 80 void itoa(int number, char str[], int field_width); /* test the itoa function */ main() { int n, fw; char s[MAXLENGTH]; printf("convert integer to string: "); scanf("%d", &n); printf("filling a field width of : "); scanf("%d", &fw); itoa(n, s, fw); printf("%s\n", s); return 0; } /* itoa: convert decimal n to character string s, padded to fill fw columns */ void itoa(int n, char s[], int fw) { int i, d, sign; void reverse(char s[]); i = 0; sign = n; /* store sign */ do /* generate digits in reverse order */ { /* get next digit: absolute value of n % 10 */ d = ((d = n%10) < 0) ? -d : d; s[i++] = '0' + d; } while ((n /= 10) != 0); /* quotient becomes the new dividend */ if (sign < 0) s[i++] = '-'; while (i < fw) /* pad with blanks to make it fill fw */ s[i++] = ' '; s[i] = '\0'; reverse(s); } /* reverse: reverse the character string s */ void reverse(char s[]) { int i, len; char temp; /* find the length of the string */ for (len = 0; s[len] != '\0'; ++len) ; if (s[len-1] == '\n') /* if the last character is newline, */ --len; /* leave it in place */ /* reverse s */ for (i = 0; i < len/2; ++i) { temp = s[i]; s[i] = s[len-1-i]; s[len-1-i] = temp; } }
C
#include "utils/node_list.h" #include <stdlib.h> #include <utlist.h> // keeps the pointers dangling void free_sequence(mks_node_t *seq) { mks_free_type(seq->type); free(seq->sequence); free(seq); } void mk_seq_to_list(mks_node_t *seq, node_list_t **dest, bool free_seq) { node_list_t *list = malloc(sizeof(node_list_t)); if (seq->tag == NODE_SEQUENCE) { mks_node_t *left = seq->sequence->left; mks_node_t *right = seq->sequence->right; if (free_seq) free_sequence(seq); list->node = right; DL_PREPEND(*dest, list); return mk_seq_to_list(left, dest, free_seq); } list->node = seq; DL_PREPEND(*dest, list); } void node_list_iterate(node_list_t *list_top, node_list_iterate_cb cb) { node_list_t *elt, *tmp; DL_FOREACH_SAFE(list_top, elt, tmp) { cb(elt); } } void free_node_list(node_list_t *list_top) { node_list_t *elt, *tmp; DL_FOREACH_SAFE(list_top, elt, tmp) { free(elt); } }
C
/*--------------- main.c ---------------*/ /* BY: Sudha Shunmugam Computer Engineering Dept. UMASS Lowell */ /* PURPOSE Assignment 4 - Operating Systems Course (16.573) CHANGES 11-25-2006 - Created. 11-25-2006 - */ /************* Include files **************/ #include <stdio.h> #include <pthread.h> // For Thread fuctions #include <stdlib.h> // For Malloc Function #include <sys/ipc.h> #include <sys/types.h> #include <sys/msg.h> #include <signal.h> #include "common.h" #include "mem_mgr.h" /*********** Constant Declaration **********/ int num_threads; pthread_t *user_thread_id, sig_wait_id, allocator_id; int *pdata, semid; long allocator_channel; int g_allocated = 0; int g_freed = 0; int alloc_algorithm = 0; /*********** Function Prototypes **********/ void kill_child(); void *sig_waiter(void *arg); void print_report(); extern void *user_thread(void *arg); extern void *allocator_thread(void *arg); extern void create_allocator_queue(); extern void delete_allocator_queue(); extern int get_total_memory_size(); /*********** Main program **********/ int main() { int i,nsigs; char temp[20]; int total_mem_size = 0; sigset_t all_signals; int sigs[] = { SIGBUS, SIGSEGV, SIGFPE }; pthread_attr_t thread_attr; struct sched_param sched_struct; struct sigaction new_sig_action; while(1) { system("clear"); printf("Memory Manager. Press Control+C to exit anytime\n"); /* Get the Number of threads from User */ printf("\nEnter the Number of Threads[1 - 1000], 0 - Exit\n"); fgets(temp, 19, stdin); /* fgets is the best way to read an input */ num_threads = atoi(temp); /* Validate the User Input */ if(!(isdigit(temp[0])) || num_threads < 0 || num_threads > 1000){ printf("Invalid Value for Number of Threads.\ \nPlease press <Enter> to Continue\n"); getchar(); continue; } if(num_threads == 0) { printf("Thank You. Bye\n"); exit(0); } else { printf("\nMemory Manager Configuration\n"); while(1) { printf("Enter the Total Memory Size: Minimum 256 Bytes Maximum 16K\n"); fgets(temp, 19, stdin); total_mem_size = atoi(temp); if(!(isdigit(temp[0])) || total_mem_size < 0){ printf("Invalid Input for memory size \ \n Please press Enter to continue\n"); getchar(); continue; } break; } for(i = 256; i < 16384 ; i = i << 1) { if(i >= total_mem_size){ printf("Rounded the value to the nearest power of 2. "); break; } } total_mem_size = i; printf("Size accepted in system = %d\n", total_mem_size); while(1) { printf("\n Enter the type of algorithm\n"); printf("1. First Fit\n"); printf("2. Best Fit\n"); printf("3. Worst Fit\n"); fgets(temp, 19, stdin); alloc_algorithm = atoi(temp); if(!(isdigit(temp[0])) ||alloc_algorithm > 3 || alloc_algorithm <= 0){ printf("Invalid Input for Algorithm Type \ \nPlease press Enter to continue\n"); getchar(); continue; } break; } break; } } allocator_channel = num_threads+1; create_allocator_queue(); mem_mgr_init((alloc_algo_e_t)alloc_algorithm, total_mem_size); /* Create the two semaphores - 1st one should be the number of consumers*/ if((semid = semget((key_t)SEM_KEY, 1, IPC_CREAT|0666)) == -1) { printf("!!!Error: Can not create semaphore1\n"); exit(1); } /* Turning all bits on ie, setting to 1 */ sigfillset (&all_signals ); nsigs = sizeof ( sigs ) / sizeof ( int ); /* Now setting all those bits off for each signal * that we are interested in */ for ( i = 0; i < nsigs; i++ ) sigdelset ( &all_signals, sigs [i] ); sigprocmask ( SIG_BLOCK, &all_signals, NULL ); /* Create a thread to wait for the control+c to quit the program */ if ( pthread_create(&sig_wait_id, NULL, sig_waiter, NULL) != 0 ){ printf("pthread_create failed for sig wait thread "); exit(3); } if ( pthread_create(&allocator_id, NULL, allocator_thread, NULL) != 0 ){ printf("pthread_create failed for allocator thread"); exit(3); } pthread_attr_init ( &thread_attr ); pthread_attr_setinheritsched ( &thread_attr, PTHREAD_INHERIT_SCHED ); /* Allocate thread related data structures */ user_thread_id = (pthread_t *)malloc((num_threads + 1) * sizeof(pthread_t)); pdata = (int *)malloc((num_threads + 1) * sizeof(int)); /* Create user threads */ for(i = 0; i < num_threads; i++) { pdata[i] = i; if(pthread_create(&user_thread_id[i], &thread_attr, user_thread, &pdata[i]) != 0) printf("Pthread create failed for user thread %d\n", i); } for(i = 0; i < num_threads; i++){ pthread_join(user_thread_id[i], NULL); } /* Kill the sig_waiter thread */ pthread_kill(sig_wait_id, SIGKILL); pthread_kill(allocator_id, SIGKILL); print_report(); if(user_thread_id) free(user_thread_id); if(pdata) free(pdata); delete_allocator_queue(); if(semctl(semid, IPC_RMID, 0) < 0) printf("Error deleting Semaphore\n"); mem_mgr_shutdown(); return(0); } void print_report() { printf("\n\n################# Memory Manager report #################\n"); printf("Number of threads\t= %d\nMemory Block Size\t= %d\nAllocation Algorithm\t= ", num_threads, get_total_memory_size()); switch(alloc_algorithm){ case 1: printf("FirstFit");break; case 2: printf("BestFit");break; case 3: printf("WorstFit");break; } printf("\n"); printf("Total allocations\t= %d\n", 10*num_threads); printf("Succeeded allocations\t= %d\n", g_allocated); printf("\nFragmented Memory\t= %d\n\n", get_fragmented_mem_size()); print_alloc_list(); print_free_list(); if(get_fragmented_mem_size() > 0) { printf("\nDefragmenting now...\n"); defragment_memory(); print_alloc_list(); print_free_list(); } printf("##################### End of report #######################\n\n"); } void *sig_waiter (void *arg) { sigset_t sigterm_signal; int i, signo; sigemptyset(&sigterm_signal); sigaddset(&sigterm_signal, SIGTERM); sigaddset(&sigterm_signal, SIGINT); if (sigwait(&sigterm_signal, &signo) != 0) { printf ("\n sigwait ( ) failed, exiting \n"); exit(2); } printf ("Process got SIGNAL (number %d)\n\n", signo); pthread_kill(allocator_id, SIGKILL); for(i = 0; i < num_threads; i++) { pthread_kill(user_thread_id[i], SIGKILL); } print_report(); if(user_thread_id) free(user_thread_id); if(pdata) free(pdata); delete_allocator_queue(); if(semctl(semid, IPC_RMID, 0) < 0) printf("Error deleting Semaphore\n"); mem_mgr_shutdown(); exit ( 1 ); return NULL; }
C
#include<stdio.h> int main() { float r,luas; scanf("%f",&r); luas=3.14159*r*r; printf("A=%.4f\n",luas); return 0; }
C
#include "ncurses.h" int main() { const int width = 50; const int height = 20; if (!initscr()) { fprintf(stderr, "Error initialising ncurses.\n"); exit(1); } initscr(); curs_set(0); refresh(); int offsetx = (COLS - width) / 2; int offsety = (LINES - height) / 2; // инициализация окна // WINDOW *newwin(nlines, ncols, y0, x0) // nlines — это число строк; // ncols — число столбцов окна; // y0 и x0 — координаты верхнего левого угла окна. WINDOW *win = newwin(5, 5, 20, 20); WINDOW *win2 = newwin(5, 5, 0, 0); // char hello[] = "qwerty!"; // mvaddstr(LINES/2, (COLS - strlen(hello))/2, hello); box(win, 0, 0); box(win2, 0, 0); wrefresh(win); // getch(); wrefresh(win2); getch(); delwin(win); endwin(); delwin(win2); endwin(); return (0); } // gcc -lncurses main.c
C
#include <stdio.h> int Sort(char); int main() { char teste[14], d; int n,y; scanf("%s", teste); for(n=1; n<13; n++) { for(y=0; y<13-n; y++) { if(Sort(teste[y]) > Sort(teste[y+1])) { d=teste[y]; teste[y]=teste[y+1]; teste[y+1]=d; } } } printf("%s", teste); return 0; } int Sort(char c) { switch(c) { case '2': return 2; case '3': return 3; case '4': return 4; case '5': return 5; case '6': return 6; case '7': return 7; case '8': return 8; case '9': return 9; case 'T': return 10; case 'J': return 11; case 'Q': return 12; case 'K': return 13; case 'A': return 14; default: return 1; } }
C
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <errno.h> #include <signal.h> #ifndef EXEC_H #define EXEC_H #include "exec.h" #endif #ifndef PARSER_H #define PARSER_H #include "parser.h" #endif static int LAST_EXIT; //Ignore Ctrl - C void ignore(int sigNum) { return; } //Read the command void readCommand(FILE* stdin) { signal(SIGINT, ignore); //LAST_EXIT = 0; while(1) { printf("? "); char *buffer = NULL; int read; unsigned int len; read = getline(&buffer, &len, stdin); if (-1 == read) { // Crl-D printf("\n"); exit(0); } if (strcmp(buffer, "exit\n") == 0 ) { printf("Exit with: %d\n", LAST_EXIT); exit(LAST_EXIT); } int nCmds; struct command *cmds = parse(buffer, read, &nCmds); //printCommands(cmds, nCmds); LAST_EXIT = runCommands(cmds, nCmds); free(cmds); free(buffer); } } int main(int argc, char **argv) { if (argc > 1) { runScript(argv[1]); } else readCommand(stdin); return 0; }
C
// // Created by Thinkpad on 2019/6/30. // #include <stdio.h> #include <time.h> #include <math.h> #include <stdlib.h> #include <string.h> #include "uno.h" #define JACK 11 #define QUEEN 12 #define KING 13 #define ACE 14 void card_print(card a, FILE* fp){ if(a.num == JACK){ printf("-%s Jack ",a.kind); fprintf(fp,"-%s Jack ",a.kind); } else if(a.num == QUEEN){ printf("-%s Queen ",a.kind); fprintf(fp,"-%s Queen ",a.kind); } else if(a.num == KING){ printf("-%s King ",a.kind); fprintf(fp,"-%s King ",a.kind); } else if(a.num == ACE){ printf("-%s Ace ",a.kind); fprintf(fp,"-%s Ace ",a.kind); } else{ printf("-%s %d ",a.kind,a.num); fprintf(fp,"-%s %d ",a.kind,a.num); } }
C
// // Created by messi-lp on 18-9-14. // #include <stdio.h> //#include "ChapterTwo.c" #include "ArraySort.c" int main(){ SqList list; list.length=20; for (int i = 0; i <= 20; ++i) { list.elem[i]=i; } list.elem[4]=20; list.elem[5]=43; list.elem[11]=9; list.elem[3]=0; list.elem[14]=99; quickSort(list.elem,1,20); //bubbleSort(&list); // selectSort(&list); //insertSort(&list); for (int j = 1; j <list.length ; ++j) { printf("%d\n",list.elem[j]); } return 0; }
C
#include "stdio.h" #include <math.h> int main() { int x,b,i=0,y=0,sum=0; scanf("%d",&x); if(x<0) { printf("fu "); x=-x; } b=x; while(b/10>0) { b/=10; i++; } i++; int a[i]; while(x/10>0) { a[y]=x%10; y++; x/=10; } a[i-1]=x; int temp,u=0; for(;u<i/2;u++) { temp=a[u]; a[u]=a[i-u-1]; a[i-u-1]=temp; } for(y=0;y<i;y++) { switch(a[y]) { case 0:printf("ling ");break; case 1:printf("yi ");break; case 2:printf("er ");break; case 3:printf("san ");break; case 4:printf("si ");break; case 5:printf("wu ");break; case 6:printf("liu ");break; case 7:printf("qi ");break; case 8:printf("ba ");break; case 9:printf("jiu ");break; } } printf("\b"); return 0; }
C
#include<stdio.h> #define max 7 void ins(int [],int *,int *); void del(int [],int *); void dis(int [],int *,int *); void main() { int ch,q[max]; int f=-1,r=-1; do{ printf("\n\n1 2 3 4\n"); scanf("%d",&ch); switch(ch) { case 1: ins(q,&r,&f); if(*f==-1) //... {*f=0; } break; case 2: del(q,&f); //if(f=r+1) then f=-1 and r=-1. if(*f==(*r+1)) {*f=-1; *r=-1; } break; case 3: dis(q,&r,&f); break; } }while(ch!=4); } void ins(int q[],int *r,int *f) { int x; if(*r==max-1) {printf("fulllllllll"); } else { *r=*(r+1); printf("Enter x----------"); scanf("%d",&x); q[*r]=x; } } void del(int q[],int *f) { int X; if(*f==-1) printf("Emptyyyyyyyyyyy"); else {X=q[*f]; *f=*(f+1); printf("deleted ====%d",X); } } void dis(int q[],int *r,int *f) { int i; if(*f==(-1)&& *r==(-1)) {printf("Noting to showwwwwwwww"); } else {printf("Elements are..........."); for(i=*f;i<(*r);i++) printf(" %d",q[i]); } }
C
#include <stdlib.h> #include <time.h> #include <stdio.h> /** *main - Entry point *Description: prints alfhabets in revers *Return: 0 Always */ int main(void) { char asd; for (asd = 'z' ; asd >= 'a'; asd--) putchar(asd); putchar('\n'); return (0); }
C
#include <math.h> #include <stdio.h> #include <string.h> #include <stdlib.h> int main(){ int n,m,x,sum=0; scanf("%d%d",&n,&m); sum=n; x=n/m; while(x>0) { sum=sum+x; x=x/m; } if(sum%m==0) printf("%d\n",sum+1); else printf("%d\n",sum); return 0; }
C
/* * File: main.c * Author: student * * Created on May 2, 2016, 8:29 AM */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <time.h> #include <sys/time.h> #define ERR_SUCCESS (0) #define ERR_NOTCREATE (1) #define ERR_EMPTY (2) #define EXIT_ERROR (1) #define IPCOUNT (1000000) #define NETCOUNT (20000) /* * */ struct RTEntry { struct RTEntry * Next; unsigned int Address; unsigned int Mask; }; struct RTEntry * CreateRTable(void) { struct RTEntry * Head; Head = (struct RTEntry *) malloc(sizeof (struct RTEntry)); if (Head == NULL) return Head; Head->Next = NULL; Head->Address = Head->Mask = 0xFFFFFFFF; return Head; } struct RTEntry * FindExisting(struct RTEntry * Table, unsigned int Address, unsigned int Mask) { struct RTEntry * I; if (Table == NULL) return NULL; if (Table->Next == NULL) return NULL; I = Table->Next; while (I != NULL) { if ((I->Address == Address) && (I->Mask == Mask)) return I; if (I->Mask < Mask) return NULL; I = I-> Next; } return NULL; } struct RTEntry * AddEntry(struct RTEntry * Table, unsigned int Address, unsigned int Mask) { struct RTEntry * I = Table; struct RTEntry * Entry; if (Table == NULL) return NULL; if ((Entry = FindExisting(Table, Address, Mask)) != NULL) return Entry; Entry = (struct RTEntry *) malloc(sizeof (struct RTEntry)); if (Entry == NULL) return NULL; Entry->Address = Address; Entry->Mask = Mask; if (Table->Next == NULL) { Table->Next = Entry; Entry->Next = NULL; return Entry; } I = Table; while (I->Next != NULL) { if ((I->Mask >= Mask) && (I->Next->Mask < Mask)) break; I = I->Next; } Entry->Next = I->Next; I->Next = Entry; return Entry; } int PrintRTable(struct RTEntry * Table) { struct RTEntry * I; if (Table == NULL) return -ERR_NOTCREATE; if (Table->Next == NULL) return -ERR_EMPTY; I = Table->Next; while (I != NULL) { printf("%hhu.%hhu.%hhu.%hhu/%hhu.%hhu.%hhu.%hhu\n", (I->Address >> 24) &0xFF, (I->Address >> 16) & 0xFF, (I->Address >> 8) & 0xFF, (I->Address) & 0xFF, (I->Mask >> 24) &0xFF, (I->Mask >> 16) & 0xFF, (I->Mask >> 8) & 0xFF, (I->Mask) & 0xFF); I = I->Next; } return -ERR_SUCCESS; } struct RTEntry * RoutingLookup(struct RTEntry * Table, unsigned int DstAddr) { struct RTEntry * I; if (Table == NULL) return NULL; if (Table->Next == NULL) return NULL; I = Table->Next; while (I != NULL) { if ((DstAddr & (I->Mask)) == I->Address) return I; I = I->Next; } return NULL; } void FlushRTable(struct RTEntry * Table) { struct RTEntry *I, *J; if (Table == NULL) return; if (Table->Next == NULL) return; I = Table->Next; J = I->Next; while (J != NULL) { free(I); I = J; J = I->Next; } free(I); } int GenerateNetworks(struct RTEntry * Table, int Count) { if (Table == NULL) return -ERR_NOTCREATE; srandom(time(NULL)); int i; for (i = 0; i < Count; i++) { int MaskLen = ((float) random()) / RAND_MAX * 32; int Mask = 0xFFFFFFFF << MaskLen; int Address = random() & Mask; AddEntry(Table, Address, Mask); } return -ERR_SUCCESS; } int CountRTable(struct RTEntry * Table) { int Count = 0; struct RTEntry *I; if (Table == NULL) return -1; I = Table -> Next; while (I != NULL) { Count++; I = I->Next; } return Count; } int main(void) { struct RTEntry * Table; unsigned int * IPs; struct timeval Before, After, Duration; int MatchCount = 0; Table = CreateRTable(); if (Table == NULL) { perror("Create Table"); exit(EXIT_ERROR); } GenerateNetworks(Table, NETCOUNT); //PrintRTable(Table); IPs = (unsigned int *) malloc(IPCOUNT * sizeof (int)); if (IPs == NULL) { perror("Malloc"); FlushRTable(Table); free(Table); exit(EXIT_ERROR); } for (int i = 0; i < IPCOUNT; i++) { IPs[i] = random(); } printf("Starting lookups...\n"); fflush(stdout); gettimeofday(&Before, NULL); for (int i = 0; i < IPCOUNT; i++) { struct RTEntry * I = RoutingLookup(Table, IPs[i]); /*printf("%hhu.%hhu.%hhu.%hhu -> ", (IPs[i] >> 24) &0xFF, (IPs[i] >> 16) & 0xFF, (IPs[i] >> 8) & 0xFF, (IPs[i]) & 0xFF);*/ if (I != NULL) { MatchCount++; /*printf("%hhu.%hhu.%hhu.%hhu/%hhu.%hhu.%hhu.%hhu\n", (I->Address >> 24) &0xFF, (I->Address >> 16) & 0xFF, (I->Address >> 8) & 0xFF, (I->Address) & 0xFF, (I->Mask >> 24) &0xFF, (I->Mask >> 16) & 0xFF, (I->Mask >> 8) & 0xFF, (I->Mask) & 0xFF);*/ } //else /*printf("not found");*/ } gettimeofday(&After, NULL); timersub(&After, &Before, &Duration); printf("done. Time %ld sec %ld usec, hits: %d, hit ratio: %f, avg lookup time : %f usec, table size: %d\n", Duration.tv_sec, Duration.tv_usec, MatchCount, ((float) MatchCount) / IPCOUNT * 100, (float) (Duration.tv_sec * 1000000 + Duration.tv_usec) / IPCOUNT, CountRTable(Table)); FlushRTable(Table); free(Table); return (EXIT_SUCCESS); }
C
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * * @param socket * @param port */ void bind_to_port(int socket, int port) { struct sockaddr_in name; name.sin_family = PF_INET; name.sin_port = (in_port_t)htons(port); name.sin_addr.s_addr = htonl(INADDR_ANY); int reuse = 1; if (setsockopt(socket, SOL_SOCKET, SO_REUSEADDR, (char *)&reuse, sizeof(int)) == -1) error("Nie można ustawić opcji ponownego użycia gniazda. "); int c = bind(socket, (struct sockaddr *) &name, sizeof(name)); if (c == -1) error("Nie można utworzyć powiązania z gniazdami. "); } /** * * @param sig * @param handler * @return */ int catch_signal(int sig, void (*handler)(int)) { struct sigaction action; action.sa_handler = handler; sigemptyset(&action.sa_mask); action.sa_flags = 0; return sigaction(sig, &action, NULL); } /** * * @param sig */ void handle_shutdown(int sig) { if (listener_d) close(listener_d); fprintf(stderr, "\nZakończono dziłanie aplikacji na żądanie\n"); exit(0); } /** * * @return */ int open_listener_socket() { int s = socket(PF_INET, SOCK_STREAM, 0); if (s == -1) error("Nie można otworzyć gniazda. "); return s; } /** * * @param socket * @param buf * @param len * @return */ int read_in(int socket, char *buf, int len) { char *s = buf; int slen = len; int c = recv(socket, s, slen, 0); while ((c > 0) && (s[c-1] != '\n')) { s += c; slen -= c; c = recv(socket, s, slen, 0); } if (c < 0) return c; else if (c == 0) buf[0] = '\0'; else s[c-1] = '\0'; return len - slen; } /** * * @param socket * @param s * @return */ int say(int socket, char *s) { int result = send(socket, s, strlen(s), 0); if (result == -1) fprintf(stderr, "%s: %s \n", "Błąd komunikacji z serwerem", strerror(errno)); return result; }
C
#include "parser.h" #include <ctype.h> #include <string.h> #include "exceptions.h" #include "parser_private_defns.h" /* String processing macros */ #define to_index(literal) ((int)strtol(literal + 1, NULL, 0)) #define is_equal(literal) (literal[0] == '=') #define is_hash(literal) (literal[0] == '#') #define remove_bracket(literal) (strtok(literal + 1, "]")) #define remove_space(string) for (; isspace(*string); string++) #define open_brak(literal) (literal[0] == '[') #define close_brak(literal) (literal[strlen(literal) - 1] == ']') /* result-computing data processing instructions */ #define is_compute(opcode) (opcode_field <= 4 || opcode_field == 12) #define is_move(opcode) (opcode_field == 13) #define is_flag_set(opcode) (opcode_field >= 8 && opcode_field <= 10) /* data processing -> multiply -> branch -> data transfer */ static const int parser_func_maxfield[] = {3, 4, 1, 3}; static const parse_func parser_helper[] = {&parse_dp, &parse_ml, &parse_br, &parse_dt}; void free_machine_code(machine_code *mcode) { free(mcode->bin); free(mcode); } machine_code *parse(assembly_program *program, symbol_table_t *label_table) { machine_code *mcode = eMalloc(sizeof(machine_code)); mcode->length = program->total_lines; mcode->bin = eCalloc(mcode->length, sizeof(word_t)); parser_t * parser_state = eMalloc(sizeof(parser_t)); parser_state->mcode = mcode; parser_state->label_table = label_table; for (int i = 0; i < program->total_lines; i++) { assembly_line *line = program->lines[i]; char **operands = operand_processor(line->operands, 3); mnemonic_p content = get_mnemonic_data(line->opcode); parser_state->line = line; parser_state->content = &content; /* Special case for ldr interpreted as mov */ parse_ldr_mov(operands, parser_state); free_operands(operands); /* Special case for lsl */ if (strcmp(line->opcode, "lsl") == 0) { parse_lsl_mov(operands, mcode->bin + i, parser_state); continue; } word_t bin = content->bin; switch (content->type) { case HALT: return mcode; case EMPTY: exceptions(UNKNOWN_INSTRUCTION_TYPE, line->location_counter); default: operands = operand_processor(line->operands, parser_func_maxfield[content->type]); parser_helper[content->type](operands, &bin, parser_state); } mcode->bin[i] = bin; free_operands(operands); } free(parser_state); return mcode; } /* Special instruction helper functions */ static void parse_ldr_mov(char **operands, parser_t * parser_state) { assembly_line *cur_line = parser_state->line; if (strcmp(cur_line->opcode, "ldr") == 0 && operands[1] != NULL && is_equal(operands[1]) && (to_index(operands[1]) <= 0xFF)) { /* Convert ldr to mov instruction */ *parser_state->content = get_mnemonic_data("mov"); *strchr(cur_line->operands, '=') = '#'; strcpy(cur_line->opcode, "mov"); } } static void parse_lsl_mov(char **operands, word_t *mcode_bin, parser_t * parser_state) { *parser_state->content = get_mnemonic_data("mov"); char *rn = strtok(parser_state->line->operands, ","); char expr[strlen(rn) * 2 + 6]; strcpy(expr, rn); strcat(expr, ",lsl "); strcat(expr, strtok(NULL, "")); operands = eCalloc(3, sizeof(char *)); operands[0] = rn; operands[1] = expr; word_t bin = (*parser_state->content)->bin; parse_dp(operands, &bin, parser_state); *mcode_bin = bin; free(operands); } static void parse_dp(char **operands, word_t *bin, parser_t * parser_state) { byte_t opcode_field = (*bin >> OPCODE_LOCATION) & FOUR_BIT_FIELD; if (is_compute(opcode_field)) { *bin |= to_index(operands[0]) << DP_DT_RD_LOCATION; *bin |= to_index(operands[1]) << DP_DT_RN_LOCATION; *bin |= parse_operand2(operands[2]); } else if (is_move(opcode_field)) { *bin |= to_index(operands[0]) << DP_DT_RD_LOCATION; *bin |= parse_operand2(operands[1]); } else if (is_flag_set(opcode_field)) { *bin |= to_index(operands[0]) << DP_DT_RN_LOCATION; *bin |= parse_operand2(operands[1]); } } static word_t parse_operand2(char *operand2) { return is_hash(operand2) ? parse_hash_operand2(operand2) : parse_reg_operand2(operand2); } static word_t parse_hash_operand2(char *operand2) { long imm = to_index(operand2); /* Sets I-bit */ word_t bin = 1 << IMM_LOCATION; /* Immediate constant fits in 8 bits */ if (imm >= 0 && imm < 256) return bin |= imm; /* Check if the hash constant can be represented using right-rotation */ int rotation = 0; word_t rotated_value = imm & 0xffffffff; for (; rotated_value >= 255 && rotation <= 15; rotation++) { int mask = (rotated_value >> 30) & 3; rotated_value <<= 2; rotated_value |= mask; } /* Throw an exception if cannot represent using right-rotation */ if (rotation > 15 || rotated_value > 255) exceptions(IMMEDIATE_VALUE_OUT_OF_BOUND, 0x00000000); bin |= rotation << OPERAND2_ROTATE_LOCATION; bin |= rotated_value; return bin; } static word_t parse_reg_operand2(char *operand2) { word_t bin = 0; char *base_reg = strtok(operand2, ","); bin |= to_index(base_reg); char *shift_name_list[] = {"lsl", "lsr", "asr", "ror"}; char *shift_name = strtok(NULL, " "); if (shift_name == NULL) return bin; for (int shift_type = 0; shift_type < 4; shift_type++) { if (strcmp(shift_name_list[shift_type], shift_name) == 0) bin |= shift_type << OPERAND2_SHIFT_TYPE_LOCATION; } char *shamt_str = strtok(NULL, " "); long shamt = to_index(shamt_str); if is_hash(shamt_str) { if (shamt >= 32) exceptions(SHIFT_AMOUNT_OUT_OF_BOUND, 0x0); bin |= shamt << OPERAND2_INTEGER_SHIFT_LOCATION; } else { bin |= 1 << OPERAND2_SHIFT_SPEC_LOCATION; bin |= shamt << OPERAND2_REGISTER_SHIFT_LOCATION; } return bin; } static void parse_ml(char **operands, word_t *bin, parser_t * parser_state) { /* Sets Rd, Rm and Rs registers */ *bin |= (to_index(operands[0]) & FOUR_BIT_FIELD) << MUL_RD_LOCATION; *bin |= (to_index(operands[1]) & FOUR_BIT_FIELD) << MUL_RM_LOCATION; *bin |= (to_index(operands[2]) & FOUR_BIT_FIELD) << MUL_RS_LOCATION; /* Sets Rn register */ if (strcmp(parser_state->line->opcode, "mla") == 0) { *bin |= (to_index(operands[3]) & FOUR_BIT_FIELD) << MUL_RN_LOCATION; } } static void parse_dt(char **operands, word_t *bin, parser_t * parser_state) { word_t data = 0; machine_code *mcode = parser_state->mcode; address_t offset = mcode->length * 4 - parser_state->line->location_counter - PIPELINE_OFFSET; /* Sets Rd Register */ *bin |= (to_index(operands[0]) & FOUR_BIT_FIELD) << DP_DT_RD_LOCATION; /* Pre-indexing if no comma can be found in the second operand OR there are * only two operands */ bool pre_index = operands[2] == NULL || (open_brak(operands[1]) && close_brak(operands[2])); bool up = true, imm = false; if (is_equal(operands[1])) { /* Load value (equal expression) */ data = to_index(operands[1]); /* Sets Rn to PC */ *bin |= PC << DP_DT_RN_LOCATION; *bin |= offset & TWELVE_BIT_FIELD; } else if (pre_index) { /* Pre-indexing */ *bin |= (to_index(operands[1] + 1) & FOUR_BIT_FIELD) << DP_DT_RN_LOCATION; if (operands[2] != NULL) strtok(operands[2], "]"); } else { /* Post-indexing */ *bin |= (to_index(remove_bracket(operands[1])) & FOUR_BIT_FIELD) << DP_DT_RN_LOCATION; } if (operands[2] != NULL) { up = !(operands[2][0] == '-') && !(operands[2][1] == '-'); imm = !is_hash(operands[2]); *bin |= is_hash(operands[2]) ? to_index(operands[2] + !up) & TWELVE_BIT_FIELD /* Hash Expr */ : parse_operand2(operands[2] + !up); /* Operand2 */ } *bin |= imm << IMM_LOCATION; *bin |= up << UP_BIT_LOCATION; *bin |= pre_index << P_INDEX_LOCATION; if (data != 0) { /* Append data to the end of the machine code */ mcode->length++; mcode->bin = eRealloc(mcode->bin, mcode->length * sizeof(word_t)); mcode->bin[mcode->length - 1] = data; } } static void parse_br(char **operands, word_t *bin, parser_t * parser_state) { char *errptr = NULL; address_t cur_addr = parser_state->line->location_counter; word_t addr = (word_t)strtol(operands[0] + 1, &errptr, 0); /* Expression is a label, not a number. See documentation for strtol */ if (errptr != NULL) { addr = get_label_address(parser_state->label_table, operands[0]); } *bin |= ((addr - cur_addr - PIPELINE_OFFSET) >> 2) & TWENTY_FOUR_BIT_FIELD; } static char **operand_processor(const char *operand, int field_count) { char **tokens = eCalloc(field_count, sizeof(char *)); char str[strlen(operand) + 1]; strcpy(str, operand); char *literal = strtok(str, ","); int i = 0; while (literal != NULL && i < field_count) { tokens[i] = eCalloc(strlen(literal) + 1, sizeof(char)); remove_space(literal); strcpy(tokens[i], literal); if (++i + 1 == field_count) literal = strtok(NULL, "\0"); else literal = strtok(NULL, ","); } tokens = eRealloc(tokens, (i + 1) * sizeof(char *)); tokens[i] = NULL; return tokens; } /* * @brief: free an array of string tokens * @param: * - tokens: the array of string tokens that need to be freed */ static void free_operands(char **tokens) { for (int i = 0; tokens[i]; i++) free(tokens[i]); free(tokens); }
C
#include "holberton.h" /** * _print_ptr - prints a long argument converted into hexadecimal * @p: Pointer to count buffer * @n: Decimal number to be converted * @buffer: buffer array * @count: Count chars * Return: Counter for number of chars printed */ int _print_ptr(int *p, unsigned long n, char *buffer, int count) { unsigned int remainder; int i, j = 0; char hex_rev[2000], *ptr_0x = "0x", *ptr_null = "(nil)"; if (!n) count = _string_to_buff(p, ptr_null, buffer, count); else { if (n == 0) hex_rev[j++] = 48; while (n != 0) { remainder = n % 16; if (remainder < 10) hex_rev[j++] = 48 + remainder; else hex_rev[j++] = 87 + remainder; n = n / 16; } count = _string_to_buff(p, ptr_0x, buffer, count); for (i = j - 1; i >= 0; i--) count = _write_char(p, hex_rev[i], buffer, count); } return (count); }
C
#include<stdio.h> /* copies input to output and replaces each tab by \t and each backspace by \b and each backslash by \\ */ main() { int c; char t; char b; c = 0; b = 'b'; t = 't'; while( (c = getchar()) != EOF ) { if ('\t' == c) printf("\\%c\0",t); else if ('\b' == c) printf("\\%c\0",b); else if('\\' == c) printf("\\\\\0"); else putchar(c); } /* the backspace is not explicitly outputted because getchar cannot read backspaces from the keyboard in the same manner that it can't read EOF */ }
C
#include <common.h> #include <os.h> #include <thread.h> #include <spinlock.h> #include <semaphore.h> #include <debug.h> extern struct spinlock os_trap_lock; extern struct task **cpu_tasks; extern struct task root_task; void semaphore_init(struct semaphore *sem, const char *name, int value) { spinlock_init(&sem->lock, name); sem->name = name; sem->value = value; } void semaphore_wait(struct semaphore *sem) { Assert(!spinlock_holding(&os_trap_lock), "no semaphore wait in trap"); spinlock_acquire(&sem->lock); while (sem->value <= 0) { Assert(!spinlock_holding(&os_trap_lock), "sleep in trap"); // release the lock first to prevent deadlock spinlock_release(&sem->lock); spinlock_acquire(&os_trap_lock); struct task *cur = get_current_task(); Assert(cur, "in semaphore, no task"); cur->alarm = sem; spinlock_release(&os_trap_lock); _yield(); spinlock_acquire(&sem->lock); } __sync_synchronize(); --sem->value; spinlock_release(&sem->lock); } void semaphore_signal(struct semaphore *sem) { spinlock_acquire(&sem->lock); ++sem->value; spinlock_release(&sem->lock); bool holding = spinlock_holding(&os_trap_lock); if (!holding) spinlock_acquire(&os_trap_lock); for (struct task *tp = root_task.next; tp != NULL; tp = tp->next) { if (tp->alarm == sem) { if (tp->state == ST_S) tp->state = ST_W; tp->alarm = NULL; // stop going to sleep } } if (!holding) spinlock_release(&os_trap_lock); }
C
#ifndef __header_Monitor_h__ #define __header_Monitor_h__ #ifdef __cplusplus extern "C" { #endif /** \brief Define mode for monitoring @note an example should be a=MonitorMode_STD | MonitorMode_LOG */ enum __eMonitorMode { MonitorMode_OFF = 0,/*!< default logical value*/ MonitorMode_STD = 1,/*!< mode to display messages on standard output*/ MonitorMode_LOG = 2,/*!< mode to display messages on log output*/ MonitorMode_EXITIFERROR = 4 /*!< mode to exit if an error message is received */ }; /** \brief Type MonitorMode enumeration */ typedef enum __eMonitorMode MonitorMode; /** \brief Shutdown the monitor @note it will close all log files. */ void Monitor_shutdown(void); /** \brief Define a monitor @param ithread_ thread number @param progname_ name of the program @param mode_ mode of the monitor */ void Monitor_def (const int ithread_, const char * progname_, const unsigned char mode_); /** \brief Send a message to the monitor @param ithread_ thread number @param msg_ message to send @note additional arguments are similar to printf */ void Monitor_msg (const int ithread_, const char * msg_, ...); /** \brief Send a warning to the monitor @param ithread_ thread number @param msg_ message to send @note additional arguments are similar to printf */ void Monitor_warn (const int ithread_, const char * msg_, ...); /** \brief Send an error message to the monitor @param ithread_ thread number @param msg_ message to send @note additional arguments are similar to printf */ void Monitor_errmsg (const int ithread_, const char * msg_, ...); void Monitor_createDirectory (const char * name_, ...); #ifdef __cplusplus } #endif #endif
C
#include <stdio.h> #include <stdarg.h> #include <stdbool.h> #include <malloc.h> //-----------function prototyping------------- /*int getAddition(int a,int b){ return a+b; } int main(){ int(*addition)(int,int); addition = &getAddition; printf("functionspointer mit malloc: %d",addition(2,3)); return 0; }*/ //-----------Manual Management in C-------------------------------- /*int main(void){ int *p1= malloc(sizeof(int)); *p1 = 5; //int *p2=p1; free(p1); printf("Invoking free does NOT assign null to any pointers.\n You have to take care of that manually.\n"); printf("p1: %i\n",*p1); //printf("p2: %i\n",*p2); return 0; }*/ //------------------------------------------------------ //static austesten.! #include "Test.h" #include <stdarg.h> static int t=4; externVariable = 4; int test(int a){ int *t = malloc(sizeof(int)); *t = a; return *t; } char *varL(int nummer, char array[]){ char *res = malloc(2*sizeof(char)); for(int i = 0 ;i<nummer;i++){ res[i] = array[i]; } return res; } int main(){ char ar[] = "HI"; char* test = varL(3,ar); printf("%s",test); return 0; }
C
#include "holberton.h" /** *print_sign- use only user defined variables to create output *@n : variable input *Return: 0 if the character is lower 1 fi not **/ int print_sign(int n) { if (n > 0) { _putchar(43); return (1); } else if (n == 0) { _putchar(48); return (0); } else _putchar(45); return (-1); }
C
/* Regula-Falsi method. */ #include <stdio.h> #include <conio.h> float fx(float x) { float result; result = ((x*x*x)-x-1); return result; } void main() { int cnt=0; float x0,x1,x2; clrscr(); printf("Enter the value of x0 and x1 : "); scanf("%f %f",&x0,&x1); printf("x0 x1 F(x0) F(x1) x2 Count\n"); x2 = x1-(fx(x1)/(fx(x1)-fx(x0)))*(x1-x0); cnt=1; printf("%f %f %f %f %f %d\n",x0,x1,fx(x0),fx(x1),x2,cnt); while(((x1-x0)/x0)>=0.0001) { if((fx(x2)*fx(x0))<0) { x1 = x2; x2 = x1 - (fx(x1)/(fx(x1)-fx(x0)))*(x1-x0); if(x2==x1) { break; } } else { x0 = x2; x2 = x1 - (fx(x1)/(fx(x1)-fx(x0)))*(x1-x0); if(x2==x0) { break; } } cnt++; printf("%f %f %f %f %f %d\n",x0,x1,fx(x0),fx(x1),x2,cnt); } getch(); }
C
/** * Note: The returned array must be malloced, assume caller calls free(). */ enum work_state{ down, left, up, right, }; int* spiralOrder(int** matrix, int matrixSize, int* matrixColSize, int* returnSize){ int i=0,j=0,row_step=0,col_step=0,count=0,state=down,step=0; int * ans; count=matrixSize*(*matrixColSize); *returnSize=0; ans=(int*)malloc(sizeof(int)*count); printf("m=%d n=%d\n",matrixSize,matrixColSize[0]); for(j=0;j<matrixColSize[0];j++){ ans[(*returnSize)++]=matrix[i][j]; count--; } j--; row_step=matrixColSize[0]-1; col_step=matrixSize-1; while(count!=0){ switch(state){ case down: for(step=0;step<col_step;step++){ //printf("down %d %d\n",i,j); ans[(*returnSize)++]=matrix[++i][j]; count--; } col_step--; state=left; break; case left: for(step=0;step<row_step;step++){ //printf("left %d %d\n",i,j); ans[(*returnSize)++]=matrix[i][--j]; count--; } row_step--; state=up; break; case up: for(step=0;step<col_step;step++){ ans[(*returnSize)++]=matrix[--i][j]; count--; } col_step--; state=right; break; case right: for(step=0;step<row_step;step++){ ans[(*returnSize)++]=matrix[i][++j]; count--; } row_step--; state=down; break; } } return ans; }
C
#include<stdio.h> #include<stdlib.h> #define ZERO 1e-4 #define N 110 void swap(int row1,int row2,int n); int correct(int); void det(int n,double *determine); void findans(int n); void printMat(int,double,FILE*); void solve(int n, double determine); double mat[N][N],sol[N]; /* Matrix = 00 01 02 03.. 10 11 12 13.. 20 21 22 23..*/ int main(int argc,char *argv[]){ int n,i,j,c=0; FILE *fin,*fout; if(!argv[1] || !argv[2]){ // judge if there are two file names printf("Please input two files\n"); return -1; } fin = fopen(argv[1],"r"); fout = fopen(argv[2],"w"); if(fin==NULL){ printf("can't read the file\n"); return -1; } if(fout==NULL){ printf("can't write the file\n"); return -1; } while(fscanf(fin,"%d",&n)){ fprintf(fout,"============>Case %d <===========\n",c++); if(!n) break; int swapping = 0; for(i=0;i<n;i++) for(j=0;j<n;j++) fscanf(fin,"%lf",&mat[i][j]); for(i=0;i<n;i++) fscanf(fin,"%lf",&mat[i][n]); for(i=0;i<n;i++){ if(abs(mat[i][i])<=ZERO){ for(j=0;j<n;j++){ if(i == j) continue; if(abs(mat[j][i])>=ZERO){ swap(i,j,n); swapping++; //determine * -1 or not } } } } double determine = (swapping%2)? -1:1; det(n,&determine); //calculate determine if(abs(determine)<=ZERO) fprintf(fout,"There is no solution or infinite solution, determine of matrix is approximate to 0\n"); solve(n,determine); //solve the matrix findans(n); //find x,y,z,.... printMat(n,determine,fout); //print the matrix if(correct(n)) fprintf(fout,"Answer is correct\n"); //judge the ans is correct or not else if(determine>=ZERO) fprintf(fout,"Answer is not correct\n"); } return 0; } void det(int n,double *determine){ if(n==2){ *determine = mat[0][0] * mat[1][1] - mat[0][1] * mat[1][0]; return ; } if(n==3){ double a1 = mat[0][0] * (mat[1][1]*mat[2][2]-mat[2][1]*mat[1][2]); double a2 = mat[0][1] * (mat[1][2]*mat[2][0]-mat[2][2]*mat[1][0]); double a3 = mat[0][2] * (mat[1][0]*mat[2][1]-mat[2][0]*mat[1][1]); *determine = a1+a2+a3; return; } } void swap(int row1,int row2,int n){ double tmp; int i,j; for(i=0;i<n;i++){ tmp = mat[row1][i]; mat[row1][i] = mat[row2][i]; mat[row2][i] = tmp; } return; } void solve(int n,double determine){ int i,j,k; for(i=0;i<n;i++){ double target = mat[i][i]; for(j=0;j<=n;j++) mat[i][j] /= target; // let all divide by [i][i] } for(i=0;i<n;i++){ double tmp = 1/mat[i][i]; for(j=0;j<=n;j++) mat[i][j]*=tmp; for(j=0;j<n;j++){ if(i==j) continue; if(mat[j][i]==0) continue; tmp = mat[j][i]/mat[i][i]; for(k=0;k<=n;k++) mat[j][k]-=tmp*mat[i][k]; } } return ; } void findans(int n){ int i,j; int flag = 0; for(i=0;i<n;i++){ for(j=0;j<n;j++){ if(i==j) continue; if(mat[i][j]>ZERO) flag=1; } if(!flag) sol[i] = mat[i][n]; } return ; } void printMat(int n,double determine,FILE *fout){ int i,j; for(i=0;i<n;i++){ for(j=0;j<=n;j++) fprintf(fout,"%f\t",mat[i][j]); fprintf(fout,"\n"); } fprintf(fout,"determine = %f\n",determine); for(i=0;i<n;i++) fprintf(fout,"%f\t",sol[i]); fprintf(fout,"\n"); return; } int correct(int n){ int i,j; for(i=0;i<n;i++){ double a = 0; for(j=0;j<n;j++) a+=mat[i][j]*sol[i]; if(a != mat[i][n]) return 0; } return 1; }
C
/* ** EPITECH PROJECT, 2018 ** poor_realoc.c ** File description: ** realloc where adress change */ #include "my.h" char *poor_realloc(char *s) { int number = my_strlen(s); char *dest = malloc(sizeof(char) * number + 1); dest = my_strcpy(s, dest); free(s); return (dest); }
C
//bailian.openjudge.cn/practice/2797/ #include <stdio.h> #include <string.h> #include <stdlib.h> typedef struct tree { struct tree *next[26]; int below; } Node; void MarkWord(char word[]); void CheckWord(char word[]); Node *root; int main() { root=(Node *)malloc(sizeof(Node)); for(int i=0;i<26;i++) root->next[i]=NULL; root->below=0; char wordlist[1000][21]; int count=0,i; gets(wordlist[count]); while(wordlist[count][0]!=0 && count<1000) { MarkWord(wordlist[count]); gets(wordlist[++count]); } for(i=0;i<count;i++) { printf("%s ",wordlist[i]); CheckWord(wordlist[i]); } return 0; } void MarkWord(char word[]) { int i=0,len=strlen(word); Node *p=root; p->below++; for(i=0;i<len;i++) { if(p->next[word[i]-'a']==NULL) { p->next[word[i]-'a']=(Node *)malloc(sizeof(Node)); for(int j=0;j<26;j++) p->next[word[i]-'a']->next[j]=NULL; p->next[word[i]-'a']->below=0; } p=p->next[word[i]-'a']; p->below++; } } void CheckWord(char word[]) { Node *p=root; int i,len=strlen(word); for(i=0;i<len;i++) { p=p->next[word[i]-'a']; if(p->below==1) { for(int j=0;j<=i;j++) putchar(word[j]); printf("\n"); return; } } puts(word); }
C
#include<stdio.h> #include"headerfile.h" int main(int argc, char **argv) { if(argc==2) { int nNum; nNum=atoi(argv[1]); if(nNum >= 1 && nNum <= 41) computeGoodNumber(nNum); else printf("\nError: no of digit should be > 0"); } else printf("\nError: no of digit should be > 0"); printf("\n\n"); return 0; }
C
#include <cs50.h> #include <stdio.h> #include <string.h> #include <ctype.h> int main(int argc, string argv[]) // check if there are two arguments { if (argc == 2) { // iterate over the second argument, argv[1] for (int i=1; i<argc; i++) { // iterate over each element of second argument. This is to check if key is integer. for (int j=0, n = strlen(argv[1]); j<n; j++) { // if there's any alphabets, terminate the program if (isalpha(argv[1][j])) { printf("Usage: ./caesar key\n"); return 1; } } // prompt the user here to terminate the program when argv is wrong // Done with checking argv[1] validity at this point. string plaintext = get_string("plaintext: "); string copytext = plaintext; for (int q = 0, m = strlen(plaintext); q<m; q++) { // convert ASCII to alph index if (isupper(plaintext[q])) { copytext[q] = plaintext[q] - 65; copytext[q] = (copytext[q]+atoi(argv[1])) % 26; plaintext[q] = copytext[q] + 65; } else if (islower(plaintext[q])) { copytext[q] = plaintext[q] - 97; copytext[q] = (copytext[q]+atoi(argv[1])) % 26; plaintext[q] = copytext[q] + 97; } } printf("ciphertext: %s\n", plaintext); } } else { printf("Usage: ./caesar key\n"); } }
C
#include<stdio.h> void main() { int fact=1,n; printf("Enter any Number : - "); scanf("%d",&n); printf("\nFactorial of %d is ",n); while(n>1) { fact=fact*n; n--; } printf("%d",fact); getch(); } /* Enter any Number : - 7 Factorial of 7 is 5040 */
C
#ifndef MATRICES_RESOLVER_MATRIXLIBRARY_H #define MATRICES_RESOLVER_MATRIXLIBRARY_H #include <stdbool.h> #include <stdint.h> uint8_t ** new_matrix(int n, int m); void freeMatrix(uint8_t ** matrix, int n, int m); void add_matrix (uint8_t ** matrix1, int n1, int m1, uint8_t ** matrix2, uint8_t ** answer); void substract_matrix (uint8_t ** matrix1, int n1, int m1, uint8_t ** matrix2, uint8_t ** answer); void productoEscalar(uint8_t ** matrix, int n, int m, uint8_t num, uint8_t ** answer); void copyMatrix (uint8_t ** matrixToCopy, int n, int m, uint8_t ** dest); void multiply_matrix(uint8_t ** matrix1, int n1, int m1, uint8_t ** matrix2, int n2, int m2, uint8_t** answer); void transpose_matrix ( uint8_t ** matrix, int n, int m, uint8_t ** answer); void power_matrix (uint8_t ** matrix, int n, int m, int power, uint8_t ** answer); void multiplyRow(uint8_t ** matrix, int n1, int m1, int rowIndex, uint8_t num); void divideRow(uint8_t ** matrix, int n, int m, int rowIndex, uint8_t num); void matrixSolver (uint8_t ** matrix1, int n1, int m1, uint8_t * answer); void solve_matrix (uint8_t ** matrix, int n, int m); void getResult(uint8_t ** matrix, int n1, int m1, uint8_t * answer); void swapRows(uint8_t ** matrix, int n1, int m1, int rowIndex1, int rowIndex2); void swapInNonZeroRow(uint8_t ** matrix, int n1,int m1, int rowIndex); void subtractRow(uint8_t ** matrix, int n1, int m1, int rowIndexChanged, int rowIndex); void printMatrixWithResults(uint8_t ** matrix, int n, int m); void printMatrix (uint8_t ** matrix, int n, int m); void getInvertibleMatrix (uint8_t ** matrix, int n, int m, uint8_t ** answer); bool areEqualMatrix(uint8_t ** matrix1, int n, int m, uint8_t ** matrix2); bool areResultOfMatrix(uint8_t ** matrix, int n, int m, uint8_t * answer); uint8_t * newVector (int n); void printVector(uint8_t * vector, int n); #endif //MATRICES_RESOLVER_MATRIXLIBRARY_H
C
#pragma once #include <stdint.h> enum data_publish_types { data_publish_imu = 1, data_publish_flow = 2, data_publish_baro = 4, data_publish_gps = 8, data_publish_binary = 0x8000, }; typedef struct { uint32_t timestamp; // all time unit is microsecond (μs). int16_t acc[3]; // all acceleration unit is milli-meter per sencond per second(mm/s^2) int16_t gyro[3]; // all angular velocity unit is centi-degree degress per second (0.01°/s) int16_t acc2[3]; int16_t gyro2[3]; int16_t mag[3]; // all magnet unit is milli-gauss }usb_imu_data; typedef struct { uint32_t timestamp; // all time unit is microsecond (μs). int16_t flow[2]; // unit: pixel int16_t sonar; // unit: milli-meter } usb_flow_data; typedef struct { uint32_t timestamp; // all time unit is microsecond (μs). int pressure; // unit: pascal int16_t temperature; // unit: centi-degree celsius (0.01°C) } usb_baro_data; typedef struct { uint32_t timestamp; // all time unit is microsecond (μs). double longitude; double latitude; int16_t altitude; // unit: centi-meter (cm). int16_t hdop; // unit: 0.01 int16_t speed_over_ground; // unit: center-meter per second (cm/s) int16_t heading; // } usb_gps_data;
C
#include <ctype.h> #include <stdio.h> #include <sys/resource.h> #include <sys/time.h> bool load(const char* dictionary) { //open dictionary to read from FILE* dictionary = fopen(dictionary, "r"); //base for a trie node* root; node* curr; node* next; char* storage[1]; int maxChars = 45, i = 0; bool isLoaded = false; //loops through all lines in the dictionary while(fscanf(dictionary, "%s", storage)) { isLoaded = true; //reset back to main node every new word curr = root; //loop through every characters until end of string while(storage[i] != '\0') { next = curr->alphabet[tolower(storage[i] - 'a')]; //if letter does not exist in the trie yet else if(next == NULL) { //make a new node if one does not currently exist struct node *n; n = malloc(sizeof(node)); for(int j = 0; j < 26; j++) { n -> alphabet[j] = NULL; } //sets pointer to new node for every letter curr->alphabet[towlower(storage[i] - 'a')] = &n; //set current node to the new one curr = n; } else { //else just move into the already existing node curr = curr->alphabet[tolower(storage[i] - 'a')]; } i++; } //after every word set it to true curr->is_word = true; } return isLoaded; } int main(int argc, char* argv[]) { // check for correct number of args if (argc != 2) { printf("Usage: speller [dictionary] text\n"); return 1; } char* dictionary = argv[1]; bool loaded = load(dictionary); }
C
/** * @author Karen Troiano 09-10855 * @author Yeiker Vazquez 09-10855 * @grupo * * Archivo: Lista.h * * Descripcion: Contiene las definiciones y librerias utilizadas * por las listas. */ #include <pthread.h> /** * Estructuras utilizadas. */ /** * @struct Item * Tipo de dato para manejar los elementos de las listas. * Incluye: * * El nombre del cliente (el cual es unico). * * El socket correspondiente al cliente. * * Un apuntador a una lista interna. * * Un apuntador al siguiente elemento de la lista. */ typedef struct Item { char *name; int sockfd; struct Lista *listaInterna; struct Item *ApSig; } Item; /** * @struct Lista * Tipo de dato para manejar una lista. * Incluye: * * Es un mutex para manejar la lista de forma correta * * en concurrencia. * * Un apuntador al primer elemento de la lista. */ typedef struct Lista { pthread_mutex_t bodyguard; Item *primero; } Lista; /** * Fin de structuras utilizadas. */ /** * Definiciones de funciones para lista. */ Item *buscar(Lista *cabeza, char *tesoro); int insertar(Lista *cabeza, char *name, int sockfd); void eliminar(Lista *cabeza, Item *sentenciado); void liberarCompleta(Lista *Completa); char *listar(Lista *cabeza); /** * Fin de definiciones de funciones para lista. */
C
/* * NOMBRE: esshell.h * AUTOR: Carlos Cotta * FECHA: 4-02-99 * PROPOSITO: Fichero de cabecera del frontend para el uso de ES. * */ #ifndef __ES_SHELL_H__ #define __ES_SHELL_H__ #include "es.h" #include "esindiv.h" /*----------------*\ | Funciones | \*----------------*/ /* * Lleva a cabo un ciclo del algoritmo. * Devuelve TRUE si se ha llegado a la terminacion. * */ TerminationStatus StepUp (ES mi_es); /* * Ejecuta el algoritmo hasta su terminacion. * */ void RunES (ES mi_es); /* * Devuelve la mejor solucion encontrada por el algoritmo. * */ Variable* BestSolutionES (ES mi_es); /* * Devuelve el mejor individuo encontraoa por el algoritmo. * */ Individuo* BestIndividualOfES (ES mi_es); /* * (ANTONIO BUENO MOLINA) v.NOV/1999 * Return the individual i in the sorted list of Individuals. * */ Individuo* GetSortedIndividual (ES mi_es, int i); #endif
C
#include "sac_a_dos.h" int CalculMeilleurChargement (int nomb, int pmax, int*p, int*V) /*Calcul le meilleur chargement*/ { int i,j; for(j=0;j<=pmax;j++) if(p[0]>j) Matrice_Sac[0][j]=0; else Matrice_Sac[0][j]=V[0]; for(i=0;i<nomb;i++) for(j=1;j<=pmax;j++) { Matrice_Sac[i+1][j]=Matrice_Sac[i][j]; if((p[i+1]<=j) && (Matrice_Sac[i][j-p[i+1]]+V[i+1]>Matrice_Sac[i][j])) { Matrice_Sac[i+1][j]=Matrice_Sac[i][j-p[i+1]]+V[i+1]; } } return 0; } int PrintSol (int nomb, int*p, int pmax){ /* Sauvegarde le meilleur remplissage */ int i=nomb, j=pmax, m=0,rg=0; while(Matrice_Sac[i][j]!=0 && i!=0){ if(Matrice_Sac[i-1][j]!=Matrice_Sac[i][j] && j>0){ rg++; NoFree[i]=1; num_Bande[i]=prof; rang[i]=rg; j-=p[i]; } i--; } if ((i==0) && Matrice_Sac[i][j]!=0) { if(Matrice_Sac[i][j] !=Matrice_Sac[i+1][j] && j>0) { rg++; NoFree[i]=1; num_Bande[i]=prof; rang[i]=rg; j-=p[i]; } } return m; } void Sac_A_Dos(int e,int **Occ_largeur,int H,int *p,int *V) { int i,j,pmax=H; for(i=0;i<n;i++) { p[i]=0; V[i]=0; } j=0; for(i=0;i<n;i++){ if(Est_Valide(Objet[i],e,i)) { p[i]=Objet[i]->h; V[i]=Objet[i]->surface; j++; /*printf("objet %d selectionne\n",i);*/ } } /*printf("\n");*/ CalculMeilleurChargement (j,pmax,p,V); PrintSol (j,p,pmax); }
C
/* * pnguy092_lab7.c * * Created: 4/24/2019 9:40:20 PM * Author : iiNza */ #include <avr/io.h> #include "io.c" int main(void) { DDRC = 0xFF; PORTC = 0x00; // LCD data lines DDRD = 0xFF; PORTD = 0x00; // LCD control lines const unsigned char *string = "Hello"; // Initializes the LCD display LCD_init(); // Starting at position 1 on the LCD screen, writes Hello World LCD_DisplayString(1, string); while(1) {continue;} }
C
#include "Keypad.h" void Keypad_Init(KEYPAD_HANDLER * key){ key->Key=HICH; key->output_turn=0; key->reading_state=MAKE_OUTPUT; key->Number=0; key->k_pin[0].pin=K1_PIN; key->k_pin[0].port=K1_PORT; key->k_pin[1].pin=K2_PIN; key->k_pin[1].port=K2_PORT; key->k_pin[2].pin=K3_PIN; key->k_pin[2].port=K3_PORT; key->k_pin[3].pin=K4_PIN; key->k_pin[3].port=K4_PORT; key->k_pin[4].pin=K5_PIN; key->k_pin[4].port=K5_PORT; key->k_pin[5].pin=K6_PIN; key->k_pin[5].port=K6_PORT; key->k_pin[6].pin=K7_PIN; key->k_pin[6].port=K7_PORT; key->k_pin[7].pin=K8_PIN; key->k_pin[7].port=K8_PORT; key->k_pin[8].pin=K9_PIN; key->k_pin[8].port=K9_PORT; } void Keypad_Update(KEYPAD_HANDLER * key){ if(key->reading_state==END_OF_CYCLE); else if(key->reading_state==MAKE_OUTPUT){ GPIO_InitTypeDef init; init.Pin = key->k_pin[key->output_turn].pin; init.Mode = GPIO_MODE_OUTPUT_PP; init.Pull = GPIO_NOPULL; init.Speed = GPIO_SPEED_FREQ_HIGH; HAL_GPIO_Init(key->k_pin[key->output_turn].port, &init); key->reading_state=SET_1; } else if(key->reading_state==SET_1){ HAL_GPIO_WritePin(key->k_pin[key->output_turn].port,key->k_pin[key->output_turn].pin, GPIO_PIN_SET); key->reading_state=CHECK; } else if(key->reading_state==CHECK){ for(uint8_t ii=0;ii<9;ii++){ if(HAL_GPIO_ReadPin(key->k_pin[ii].port,key->k_pin[ii].pin)){ if(key->output_turn>ii){ key->Key=ii*9+key->output_turn; break; } else if(key->output_turn<ii){ key->Key=ii+key->output_turn*9; break; } } } key->reading_state=SET_0; } else if(key->reading_state==SET_0){ HAL_GPIO_WritePin(key->k_pin[key->output_turn].port,key->k_pin[key->output_turn].pin, GPIO_PIN_RESET); key->reading_state=MAKE_INPUT; } else if(key->reading_state==MAKE_INPUT){ GPIO_InitTypeDef init; init.Pin = key->k_pin[key->output_turn].pin; init.Mode = GPIO_MODE_INPUT; init.Pull = GPIO_PULLDOWN; HAL_GPIO_Init(key->k_pin[key->output_turn].port, &init); key->output_turn++; if(key->output_turn==9)key->output_turn=0; if((key->Key==HICH) && (key->output_turn!=0)) key->reading_state=MAKE_OUTPUT; else key->reading_state=END_OF_CYCLE; } } void Keypad_Restart(KEYPAD_HANDLER * key){ key->number_state=START_OF_NUM; if(key->Pre_Key==HICH && key->Key!=HICH){ switch(key->Key){ case SEFR: key->Number=key->Number*10+0; break; case YEK: key->Number=key->Number*10+1; break; case DOW: key->Number=key->Number*10+2; break; case SEH: key->Number=key->Number*10+3; break; case CHAHAR: key->Number=key->Number*10+4; break; case PANJ: key->Number=key->Number*10+5; break; case SHESH: key->Number=key->Number*10+6; break; case HAFT: key->Number=key->Number*10+7; break; case HASHT: key->Number=key->Number*10+8; break; case NOH: key->Number=key->Number*10+9; break; case HF: key->number_state=END_OF_NUM; break; case DEL: key->Number/=10; break; default: key->Number=key->Number; } } key->reading_state=MAKE_OUTPUT; key->Pre_Key=key->Key; key->Key=HICH; key->output_turn=0; if(key->Number==0)key->number_state=START_OF_NUM; else if(key->number_state==END_OF_NUM); else key->number_state=MIDDLE_OF_NUM; }
C
#include <ctype.h> #include <stdbool.h> #include <stdio.h> #include <string.h> #define MSG_LEN 50 bool is_palindrome(const char* message); void reverse(char* message); void tolower_string(char* message); int main(void) { char msg[MSG_LEN + 1]; printf("Enter a message: "); gets(msg); if (is_palindrome(msg)) printf("Palindrome\n"); else printf("Not a Palindrome\n"); return 0; } // The function first extracts just the alphabets. It then stores it // into two strings s and t, reverses t and then compares it to s. // If they are equal it means we have a palindrome in our midst ;) bool is_palindrome(const char *message) { char s[MSG_LEN + 1], t[MSG_LEN + 1]; const char *p = message; // array parameters are const objects so need a const pointer // Do note that const is for the object being pointed and not // for p itself. We are changing p but not the object its // pointing to. int i = 0; while (*p) { if (isalpha((int) *p)) if (*p != ' ') s[i++] = tolower((int) *p); p++; } strcpy(t, s); reverse(t); if (strcmp(s,t) == 0) return true; else return false; return false; } // This one is from the previous question. A good example of reusing // code. It reverses the string t for us. void reverse(char *message) { char temp; char *p = message, *q = p + (strlen(p) - 1); while (p < q) { temp = *p; *p++ = *q; *q-- = temp; } } void tolower_string(char *message) { while (*message) { *message = tolower((int) *message); *message++; } }
C
case 1: printf("nU`h пJjwXoƦr\n"); scanf("%d", &c); printf("nj٤p jO1pO2 2\n"); scanf("%d", &a); b = rand() % 10 + 1; e = rand() % 10 + 1; printf("AIƬO%d aoIƬO%d\n",b,e); if (a = 1) { if (b > e) { money = money + c * 2; printf("ĹF\n"); winlose(money); } else { money = money - c; printf("F\n"); winlose(money); } } else if (a = 2) { if (b < e) { money = money + c * 2; printf("ĹF\n"); winlose(money); } else { money = money - c; printf("F\n"); winlose(money); } } break;
C
#include <stdio.h> #include <stdlib.h> #include <time.h> #include <string.h> #define SWAP(a,b){int tmp; tmp=a; a=b; b=tmp;} void algorithm1(int* list, int n); //bubble sort void algorithm2(int* list, int left, int right); //quick sort void algorithm3(int* list, int left, int right); //merge sort void algorithm4(int* list, int n, int* temp); //radix sort void merge(int* list, int left, int middle, int right); int* elem;// element's list int* temp;// temporary list int main(int argc,char* argv[]) { char* filename = argv[1]; //input file name int algo_num = atoi(argv[2]); // algorithm number that will be used int elem_num; int i; FILE *fp = fopen(filename, "r"); //file open error if (!fp) { printf("No such file!\n"); return -1; } //get element's number fscanf(fp, "%d", &elem_num); elem = (int*)malloc(sizeof(int)*elem_num); temp = (int*)malloc(sizeof(int)*elem_num); //save elemnt in array for (i = 0; i < elem_num; i++) { fscanf(fp, "%d", &elem[i]); } //recode program start time clock_t start_time = clock(); switch (algo_num) { case 1: algorithm1(elem, elem_num); break; case 2: algorithm2(elem, 0, elem_num-1); break; case 3: algorithm3(elem, 0, elem_num - 1); break; case 4: algorithm4(elem,elem_num,temp); break; default: printf("%d is wrong algorithm number. Please choose number 1~4\n", algo_num); return -1; } //record program end time clock_t end_time = clock(); fclose(fp); //output to file char output_filename[100] = "result_"; char s[5]; sprintf(s, "%d", algo_num); strcat(output_filename, s); strcat(output_filename, "_"); strcat(output_filename, filename); fp = fopen(output_filename, "w"); fprintf(fp, "%s\n", filename); fprintf(fp, "%d\n", algo_num); fprintf(fp, "%d\n", elem_num); fprintf(fp, "%lf\n", (double)(end_time - start_time) / (CLOCKS_PER_SEC)); for (i = 0; i < elem_num; i++) { fprintf(fp, "%d ", elem[i]); } fclose(fp); free(elem); free(temp); return 0; } //bubbel sort void algorithm1(int* list, int n) { int i, j; for (i = 0; i < n - 1; i++) { for (j = n - 1; j > i; j--) { if (list[j] < list[j - 1]) SWAP(list[j], list[j - 1]); } } } //quick sort void algorithm2(int* list, int left, int right) { int pivot, i; if (right - left > 0) { //partition pivot = left; for (i = left; i < right; i++) { if (list[i] < list[right]) { SWAP(list[i], list[pivot]); pivot++; } } SWAP(list[right], list[pivot]); algorithm2(list, left, pivot - 1); algorithm2(list, pivot + 1, right); } } //merge sort void algorithm3(int* list,int left,int right) { int middle; if (left < right) { middle = (left + right) / 2; algorithm3(list, left, middle); algorithm3(list, middle + 1, right); merge(list, left, middle, right); } } //radix sort void algorithm4(int* list,int n, int* temp) { int max_val = 0, min_val = 0, sig_digit = 1; int bin_count[10]; //radix sort for positive numbers and for negative numbers int* negative_list = (int*)malloc(sizeof(int)*n); int* positive_list = (int*)malloc(sizeof(int)*n); int pos_idx = 0, neg_idx = 0; int i; //separate positive and negative for (i = 0; i < n; i++) { if (list[i] >= 0) { positive_list[pos_idx++] = list[i]; if (list[i] > max_val) max_val = list[i]; } else { negative_list[neg_idx++] = list[i]; if (list[i] < min_val) min_val = list[i]; } } //radix sort for positive while (max_val / sig_digit > 0) { for (i = 0; i < 10; i++) bin_count[i] = 0; for (i = 0; i < pos_idx; i++) bin_count[(positive_list[i] / sig_digit) % 10]++; for (i = 1; i < 10; i++) bin_count[i] += bin_count[i - 1]; for (i = pos_idx - 1; i >= 0; i--) temp[--bin_count[(positive_list[i] / sig_digit) % 10]] = positive_list[i]; for (i = 0; i < pos_idx; i++) positive_list[i] = temp[i]; sig_digit *= 10;//go to next significant digit } //radix sort for negative sig_digit = 1; while ((-min_val) / sig_digit > 0) { for (i = 0; i < 10; i++) bin_count[i] = 0; for (i = 0; i < neg_idx; i++) bin_count[((-negative_list[i]) / sig_digit) % 10]++; for (i = 1; i < 10; i++) bin_count[i] += bin_count[i - 1]; for (i = neg_idx - 1; i >= 0; i--) temp[--bin_count[((-negative_list[i]) / sig_digit) % 10]] = negative_list[i]; for (i = 0; i < pos_idx; i++) negative_list[i] = temp[i]; sig_digit *= 10;//go to next significant digit } for (i = 0; i < neg_idx; i++) { list[i] = negative_list[neg_idx-1-i]; } for (i = 0; i < pos_idx; i++) { list[i + neg_idx] = positive_list[i]; } } void merge(int* list, int left, int middle, int right) { int i_left, i_right, i; memcpy(temp + left, list + left, sizeof(int)*(right - left + 1)); i_left = left; i_right = middle + 1; i = left; while ((i_left <= middle) && (i_right <= right)) { if (temp[i_left] < temp[i_right]) list[i++] = temp[i_left++]; else list[i++] = temp[i_right++]; } while (i_left <= middle) list[i++] = temp[i_left++]; while (i_right <= right) list[i++] = temp[i_right++]; }
C
#include <stdio.h> #include <stdlib.h> #define TAM 2 typedef struct { //campos o atributos. int leg; char name[25];//porque es un solo nombre; float prom;//promedio. int estado; /*LA ESTRUCTURA: -NO es un vector. -guarda la direccion de memoria del primer elemento. -son datos por valor. */ } sAlumno;//alias sAlumno cargarAlumno(void); void mostrarUnAlumno(sAlumno); void cargarListadoAlumnos(sAlumno vec [], int tam); void mostrarListadoAlumnos(sAlumno vec[], int tam); int main() { sAlumno miAlumno[TAM];//local del main for(int i = 0; i < TAM; i++) { miAlumno[i].estado = 0; } //miAlumno[TAM] = cargarAlumno(); //mostrarUnAlumno(miAlumno); cargarListadoAlumnos(miAlumno,TAM); mostrarListadoAlumnos(miAlumno,TAM); //mostrarAlumnos(miAlumno,TAM); /* //sAlumno es el tipo de dato //miAlumno es la variable sAlumno miAlumno;//= {1000,"Yago",7,66};//EN ORDEN A COMO ESTA LA ESTRUCTURA. sAlumno otroAlumno; printf("Ingrese legajo: "); scanf("%d",&miAlumno.leg); printf("Ingrese nombre: "); fflush(stdin); scanf("%[^\n]",&miAlumno.name); //^ = ALT + 94 printf("Ingrese promedio: "); scanf("%f",&miAlumno.prom); //otroAlumno = miAlumno; //SE PUEDE ASIGNAR USAMOS EL OPERADOR PUNTO me permite acceder a cada campo //printf("%d--%s--%.2f",otroAlumno.leg,otroAlumno.name,otroAlumno.prom); mostrarUnAlumno(miAlumno); //printf("%d",sizeof(sAlumno));//te dice cuanto pesa una variable del tipo sAlumno en esta arquitectura. */ return 0; } void mostrarUnAlumno(sAlumno miAlumno)//SI LE PASO UNA ESTRUCTURA A UN FUNCION LA COPIA. { printf("%d--%s--%.2f\n",miAlumno.leg,miAlumno.name,miAlumno.prom); } sAlumno cargarAlumno(void) { sAlumno miAlumno;//= {1000,"Yago",7,66};//EN ORDEN A COMO ESTA LA ESTRUCTURA. //variable local a la funcion. printf("Ingrese legajo: "); scanf("%d",&miAlumno.leg); printf("Ingrese nombre: "); fflush(stdin); scanf("%[^\n]",&miAlumno.name); //^ = ALT + 94 printf("Ingrese promedio: "); scanf("%f",&miAlumno.prom); return miAlumno; } void cargarListadoAlumnos(sAlumno vec [], int tam) { for(int i = 0; i < tam; i++) { vec[i] = cargarAlumno(); } } void mostrarListadoAlumnos(sAlumno vec[], int tam) { for(int i = 0; i < tam; i++) { if(vec[i].estado != 0) { mostrarUnAlumno(vec[i]); } } }
C
#include <stdio.h> #include <math.h> int main () { float x, x2, y, y2; float distancia; printf("DIGITE O PRIMEIRO PONTO\n"); scanf("%f %f", &x, &y); printf("DIGITE O SEGUNDO PONTO\n"); scanf("%f %f", &x2, &y2); distancia = sqrt (pow(x2-x, 2) + pow(y2-y, 2)); printf("%.4f\n", distancia); return 0; }
C
#include <stdio.h> #include<math.h>//为了使用sin(),cos()函数 在VS Code上编译需要指明路径 gcc xx -lm int main () { double R1, P1, R2, P2; printf("请输入R1"); scanf("%lf", &R1); printf("请输入P1"); scanf("%lf", &P1); printf("请输入R2"); scanf("%lf", &R2); printf("请输入P2"); scanf("%lf", &P2); double A1 = R1 * cos(P1); double B1 = R1 * sin(P1); double A2 = R2 * cos(P2); double B2 = R2 * sin(P2); double A = (A1 * A2) - (B1 * B2); double B = (A1 * B2) + (A2 * B1); printf("%.2f%.2fi", A, B); return 0; }
C
//IN THIS PROGRAM WE TRY TO STORE SPARSE MATRIX BY STORING ONLY THE NON-ZERO ELEMENTS AS THE (POSITION,ELEMENT) TUPPLE AND AFTER THAT WE ALSO HAVE DONE ADDITION OF 2 SPARSE MATRICES // NOTE::: While taking input to create a matrix, store the elements in order of their row and column positions. EXAMPLE: For storing elements at positions : (1,1),(2,1),(1,2), First store element at (1,1) then (1,2) and at last (2,1) [order should be mantained] #include<stdio.h> struct element{ int i; int j; int x; }; struct sparse{ int m; int n; int num; struct element *A; }; void create(struct sparse* mat) { printf("Enter the dimension of the sparse matrix you wanna create :"); scanf("%d%d",&mat->m,&mat->n); printf("Enter the number of non zero elements :"); scanf("%d",&mat->num); mat->A = (struct element*)malloc(mat->num*sizeof(struct element)); printf("\nEnter the position of the non zero elements and as well the non zero element itself :\n"); for(int k=0;k<mat->num;k++) { printf("\nEnter for element number %d:\n",k+1); scanf("%d%d%d",&mat->A[k].i,&mat->A[k].j,&mat->A[k].x); } } void display(struct sparse matrix) { int k=0; for(int a=0;a<matrix.m;a++) { for(int b=0;b<matrix.n;b++) { if(matrix.A[k].i==(a+1) && matrix.A[k].j==(b+1)) { printf("%d ",matrix.A[k++].x); } else{ printf("0 "); } } printf("\n"); } } struct sparse add(struct sparse mat1, struct sparse mat2) { int k=0,u=0,v=0; struct sparse matrix; (mat1.m>mat2.m)?(matrix.m=mat1.m):(matrix.m=mat2.m); (mat1.n>mat2.n)?(matrix.n=mat1.n):(matrix.n=mat2.n); matrix.A=(struct element*)malloc((mat1.num+mat2.num)*sizeof(struct element)); while(u<mat1.num && v<mat2.num) { if(mat1.A[u].i<mat2.A[v].i) { matrix.A[k++]=mat1.A[u++]; } else if(mat2.A[v].i<mat1.A[u].i) { matrix.A[k++]=mat2.A[v++]; } else{ //if row number of the non zero element of both the sparse matrix are equal, we will check the column number then if(mat1.A[u].j<mat2.A[v].j) { matrix.A[k++]=mat1.A[u++]; } else if(mat2.A[v].j<mat1.A[u].j) { matrix.A[k++]=mat2.A[v++]; } else{ //if column number of the non zero element of both the sparse matrix are also equal we would then add the similar position elements of both the matrices and then increment the counter of the array of both the matrices matrix.A[k]=mat1.A[u++]; //first matrix element is copied matrix.A[k++].x+=mat2.A[v++].x; //second matrix element is added to it } } } for(;u<mat1.num;u++) { matrix.A[k++]=mat1.A[u]; } for(;v<mat2.num;v++) { matrix.A[k++]=mat2.A[v]; } matrix.num=k; return matrix; } void main() { struct sparse mat1,mat2; create(&mat1); printf("\n\nMTRIX YOU CREATED =\n"); display(mat1); printf("\n\n"); create(&mat2); printf("\n\nMTRIX YOU CREATED =\n"); display(mat2); struct sparse mat=add(mat1,mat2); //calling sparse matrix addition function printf("\n\n\n\nTHE MATRIX CREATED AFTER ADDING BOTH THE MATRICES IS:\n"); display(mat); printf("\n\nXXXXXXXXXXXXXXXXXXXXXXX MATRICES ADDED SUCCESSFULLY XXXXXXXXXXXXXXXXXXXXXXX"); free(mat1.A); free(mat2.A); free(mat.A); }
C
/* set-length.c -- vector - flexible array */ #include <stdlib.h> #ifdef FORTIFY #include "fortify/fortify.h" #endif #include "datastruct/vector.h" #include "impl.h" result_t vector_set_length(vector_t *v, unsigned int length) { void *newbase; newbase = realloc(v->base, length * v->width); if (newbase == NULL) return result_OOM; v->used = length; // FIXME: Looks wrong. v->allocated = length; v->base = newbase; return result_OK; }
C
#include <stdio.h> #include <string.h> void DecToBinary(int n){ if(n < 2) printf("값 : %d\n",n); else{ DecToBinary(n/2); printf("%d",n%2); } } int main(void){ int d; printf("정수입력 : "); scanf("%d",&d); DecToBinary(d); printf("\n"); return 0; }
C
/** * @file setitimer.c * @brief * @author Airead Fan <[email protected]> * @date 2013/01/14 10:04:10 */ #include <sys/time.h> #include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <signal.h> #include <string.h> #include <errno.h> #if 0 int getitimer(int which, struct itimerval *curr_value); int setitimer(int which, const struct itimerval *new_value, struct itimerval *old_value); #endif static int is_print; static void signal_handler(int sig) { is_print = 1; } int main(int argc, char *argv[]) { struct sigaction act, oact; struct itimerval tick; memset(&act, 0, sizeof(act)); act.sa_handler = signal_handler; //int sigemptyset(sigset_t *set); sigemptyset(&act.sa_mask); act.sa_flags = 0; //int sigaction(int signum, const struct sigaction *act, struct sigaction *oldact); if (sigaction(SIGALRM, &act, &oact) < 0) { fprintf(stderr, "Install new signal handler for SIGINT failed: %s\n", strerror(errno)); } memset(&tick, 0, sizeof(tick)); tick.it_value.tv_sec = 1; tick.it_interval.tv_sec = 1; if (setitimer(ITIMER_REAL, &tick, NULL) < 0) { fprintf(stderr, "setitimer failed: %s\n", strerror(errno)); exit(1); } while (1) { sleep(2); if (is_print == 1) { fprintf(stdout, ".\n"); is_print = 0; } } return 0; }
C
#include <linux/init.h> #include <linux/kernel.h> #include <linux/module.h> #include <linux/interrupt.h> #include <linux/slab.h> /** * Struct to describe the IDTR register structure. * * addr: Base address of Interrupt Descriptor Table (8 bytes) * limit: Size of Interrupt Descriptor Table (2 bytes) */ typedef struct __attribute__((__packed__)) idtr { uint16_t limit; uint64_t addr; uint64_t xs; } idtr_t; /** * Load the IDTR register into memory. * * @return A struct idtr with the value of the IDTR register. */ static idtr_t* get_idtr(void) { idtr_t* idtr = (idtr_t *) kmalloc(sizeof(idtr_t), GFP_KERNEL); idtr->xs = 0; idtr->limit = 0; idtr->addr = 0; __asm__("sidt %0" : "=m" (*idtr)); return idtr; } /** * Set the IDTR register's value. * * @param idtr An IDTR struct with base address and limit (xs unused). */ static void set_idtr(idtr_t* idtr) { __asm__("lidt %0" : : "m" (*idtr)); } /** * Print out an IDTR struct in a friendly way. * If xs has been modified, send a warning since this might be a sign of an overflow. * * @param idtr The IDTR value to be printed. */ static void print_idtr(idtr_t* idtr) { printk("ADDRESS: %llx, LIMIT: %x", idtr->addr, idtr->limit); if (idtr->xs) { printk("Warning: extra space in IDTR struct has been modified."); } } /** * Initialize the module. * * Set the IDTR's limit to 0 to cause a triple fault and an immediate restart. */ static int __init test_init(void) { idtr_t* idtr; printk("Loading test module...\n"); idtr = get_idtr(); print_idtr(idtr); // IDTR size = 0 idtr->limit = 0; set_idtr(idtr); return 0; } /** * Unload the module. * * This will never run since loading the module immediately restarts the system. */ static void __exit test_exit(void) { printk("Goodbye World\n"); } module_init(test_init); module_exit(test_exit); MODULE_LICENSE("GPL"); MODULE_AUTHOR("Spencer Colton"); MODULE_DESCRIPTION("Destroys the entire kernel"); MODULE_VERSION("1.0");
C
#include "veclib.h" void print(vector vec_a) { printf("["); for (int i=0;i<DIM;i++) printf("%f ",vec_a[i]); printf("]"); printf("\n"); } void input(vector vec_a) { for (int i=0;i<DIM;i++) scanf("%f",&vec_a[i]); } int main() { vector vecA, vecB, vecC, vecD; // read vectors A and B printf("Enter vector A with dimension %d\n", DIM); input(vecA); printf("Enter vector B with dimension %d\n", DIM); input(vecB); printf("Vector A : "); print(vecA); printf("Vector B : "); print(vecB); //Test for norm of vectors float norm_of_vectors = norm(vecA , vecB); printf("Norm of A and B: %f\n",norm_of_vectors); // Test for addition of vectors add(vecA, vecB, vecD); printf("Addition of A and B : "); print(vecD); // Test for element wise prod eleProd(vecA, vecB, vecC); printf("Element-wise product of A and B : "); print(vecC); //Test for Dot product of vectors printf("Dot Product of A and B : "); printf("%f \n",dotProd(vecA,vecB)); //Test for angle b/w 2 vectors printf("Angle b/w A and B : "); printf("%f",angle(vecA,vecB)); } // end main
C
#include <stdlib.h> #include <stdio.h> #include <string.h> int main() { // fopen("$HOME/.diary", "r"); -> fails git a // get $HOME char* home_location = getenv("HOME"); if (home_location == NULL) { fprintf(stderr, "Failed to get HOME"); } char * diary_string = "/.diary"; size_t path_size = strlen(diary_string) + strlen(home_location) + 1; char path[path_size]; snprintf(path, path_size, "%s%s", home_location, diary_string); FILE *fp = fopen(path, "r"); if (fp == NULL) { perror(""); exit(1); } int c = fgetc(fp); while (c != EOF) { printf("%c", c); c = fgetc(fp); } fclose(fp); return 0; }
C
/* ** EPITECH PROJECT, 2018 ** . ** File description: ** . */ #include <stdlib.h> #include "navy.h" #include "tools.h" void init_sigaction_sig(struct sigaction *action1, struct sigaction *action2) { action1->sa_sigaction = (void *) success1; action1->sa_flags = SA_SIGINFO; sigemptyset(&action1->sa_mask); action2->sa_sigaction = (void *) success2; action2->sa_flags = SA_SIGINFO; sigemptyset(&action2->sa_mask); } char *defend(void) { struct sigaction action1; struct sigaction action2; char *str = malloc(sizeof(char) * 9); int verif; if (str == NULL) return (NULL); str[8] = '\0'; global = 0; init_sigaction_sig(&action1, &action2); for (int i = 0; i != 8; i++) { verif = global; while (global == verif) { sigaction(SIGUSR1, &action1, NULL); sigaction(SIGUSR2, &action2, NULL); } check_signal(str, i, verif); } convert_bin_ascii(str); return (str); } void hit_player1(map_t *map, char *str, int pid) { if (map->map1[str[1] - '1'][str[0] - '1'] != '.' && map->map1[str[1] - '1'][str[0] - '1'] != 'x' && map->map1[str[1] - '1'][str[0] - '1'] != 'o') { my_putstr(": hit\n"); (map->map1[str[1] - '1'][str[0] - '1'] = 'x'); usleep(10000); kill(pid, SIGUSR2); map->loose = map->loose + 1; } else { my_putstr_back(": missed\n"); (map->map1[str[1] - '1'][str[0] - '1'] = 'o'); usleep(10000); kill(pid, SIGUSR1); } } void hit_player2(map_t *map, char *str, int pid) { if (map->map2[str[1] - '1'][str[0] - '1'] != '.' && map->map2[str[1] - '1'][str[0] - '1'] != 'x' && map->map2[str[1] - '1'][str[0] - '1'] != 'o') { my_putstr_back(": hit\n"); (map->map2[str[1] - '1'][str[0] - '1'] = 'x'); usleep(10000); kill(pid, SIGUSR2); map->loose = map->loose + 1; } else { my_putstr_back(": missed\n"); (map->map2[str[1] - '1'][str[0] - '1'] = 'o'); usleep(10000); kill(pid, SIGUSR1); } } int hit_or_not_defence(map_t *map, char *str, int pid, int player) { my_putchar(str[0] - '0' + 'A' - 1); my_putchar(str[1]); if (player == PLAYER1) { hit_player1(map, str, pid); } else { hit_player2(map, str, pid); } return (0); }
C
#include "max7221.h" //************************************* // MAX7221 //************************************* void Send_Byte_7221(uint8_t dat) { uint8_t i; for (i = 0; i < 8; i++) { if (dat & 0x80) DAT_MAX = 1; else DAT_MAX = 0; CLK_MAX = 1; // __delay_ms(1); asm("nop"); // asm("nop"); // asm("nop"); // asm("nop"); // asm("nop"); // asm("nop"); // asm("nop"); CLK_MAX = 0; dat <<= 1; } } //************************************* // MAX7221 //************************************* void Cmd7221(uint8_t adr, uint8_t val ) { uint8_t i; CS_MAX = 0; for (i = 0; i < COUNT_MATRIX; i++ ) { Send_Byte_7221(adr); Send_Byte_7221(val); } CS_MAX = 1; } //************************************* // //************************************* void Update_Matrix(uint8_t *buf) { uint8_t i, j, data; for (i = 0; i < 8; i++) // 8 (8 DIG) { // CS_MAX = 0; // for (j = 0; j < COUNT_MATRIX; j++) // { data = buf[8 * (COUNT_MATRIX - 1 - j) + i]; // , Send_Byte_7221((unsigned)1 + i); // Send_Byte_7221(data); // } CS_MAX = 1; } } //************************************* // MAX7221 //************************************* void Init7221() { CS_MAX = 1; Cmd7221(SHUTDOWN_R,1); //Shutdown Register - Normal Mode Cmd7221(DECODE_R,0); //Decode-Mode Register - No decode for digits 70 Cmd7221(SCAN_R,7); //Scan-Limit Register - Display digits 0 1 2 3 4 5 6 7 Cmd7221(INTENSITY_R,0x02);//Intensity Register - 5/16 Cmd7221(TEST_R,0); //test - Normal Operation }
C
//#include <stdio.h> /* int main() { int num = 3; int *pnum = &num; printf("num = %d \n", num); printf("&num = %d \n", &num); printf("pnum = %d \n", pnum); printf("*pnum = %d \n", *pnum); printf("&pnum = %d \n", &pnum); getchar(); getchar(); return 0; } */ // 12-1 (1) /* int main() { int num = 10; int *ptr1 = &num; int *ptr2 = ptr1; (*ptr1)++; (*ptr2)++; printf("%d \n", num); getchar(); getchar(); return 0; } */ // 12-1 (2) /* int main() { int num1 = 10, num2 = 20; int *ptr1 = &num1, *ptr2 = &num2; *ptr1 = *ptr1 + 10; *ptr2 = *ptr2 - 10; printf("*ptr1 = %d \n", *ptr1); printf("*ptr2 = %d \n", *ptr2); ptr1 = &num2; ptr2 = &num1; printf("*ptr1 = %d \n", *ptr1); printf("*ptr2 = %d \n", *ptr2); getchar(); getchar(); return 0; } */
C
#include "main.h" /* Пример кнопки с срограмной проверкой на дребезг */ int main(void){ DDRD |= (1 << PD7);//Седьмой пин порта D на выход PORTD &=~(1 << PD7);//Низкий уровень на седьмом пине порта D DDRB &=~(1 << PB0);//Нулевой пин порта B на вход PORTB |= (1 << PB0);//Высокий логический уровень на нулевом пине порта B uint8_t button=0;//Пеерменная для счётчика антидребезга while (1){ if (!(PINB&(1 << PB0)))//Если на нулевом пине порта B низкий уровень { if (button < 5)//Если button меньше 5 то { button++;//к button прибовляем еденицу } else//в противном случае { //Выполнить код при нажатой кнопке. Высокий уровень на пине PORTD |= (1 << PD7);//Пример: Высокий уровень на седьмом пине порта D } } else//в противном случае { if (button > 0)//Если button больше нуля то { button--;//от button отнимаем еденицу } else//в противном случае { //Выполнить код при отпущенной кнопке. Низкий уровень на пине PORTD &=~(1 << PD7);//Пример: низкий уровень на седьмом пине порта D } } } }
C
//pythonԴʼ /* C 궨: #ı滻 ##ı滻ǰַ do-while(0) #define XXXX(i) do {a(xxx); b(xxx)} while (0) ɱ: #ifdef _M_ALPHA typedef struct { char *a0; int offset; } va_list; #else typedef char * va_list; #endif _M_ALPHAָDEC ALPHAAlpha AXPܹһva_listΪַָ롣 INTSIZEOF ,ȡռõĿռ䳤ȣСռóΪint #define _INTSIZEOF(n) ( (sizeof(n) + sizeof(int) - 1) & ~(sizeof(int) - 1) ) VA_START꣬ȡɱбĵһĵַapΪva_listָ룬vǿɱߵIJ #define va_start(ap,v) ( ap = (va_list)&v + _INTSIZEOF(v) ) VA_ARG꣬ȡɱĵǰָͲָָһt˵ǰͣ #define va_arg(ap,t) ( *(t *)((ap += _INTSIZEOF(t)) - _INTSIZEOF(t)) ) VA_END꣬va_listɱб #define va_end(ap) ( ap = (va_list)0 ) */ //ӷ x = (long)((unsigned long)a + b); ((x^a) >= 0 || (x^b) >= 0)û(λͬ) //ȡtypeṹmemberƫ #define offsetof(type, member) ((size_t)(&((type *)0)->member))
C
#include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <signal.h> #include <unistd.h> #include <string.h> static unsigned long long fm_count; static volatile bool proceed = false; static void done(int unused) { proceed = false; unused = unused; } typedef struct rat rat; struct rat { int a; int b; }; void reduce(int* a, int* b); int gcd(int a, int b); rat addq(rat* r1, rat* r2); rat subq(rat* r1, rat* r2); rat mulq(rat* r1, rat* r2); rat divq(rat* r1, rat* r2); int sign(rat* r1); unsigned long long make_solution(int n1, int n2, int rows, rat* c); unsigned long long fm_elim(int rows, int cols, int** a, int* c); unsigned long long danielUlricaNils_fm(char* aname, char* cname, int seconds) { FILE* afile = fopen(aname, "r"); FILE* cfile = fopen(cname, "r"); fm_count = 0; if (afile == NULL) { fprintf(stderr, "could not open file A\n"); exit(1); } if (cfile == NULL) { fprintf(stderr, "could not open file c\n"); exit(1); } int rows; int cRows; int cols; fscanf(afile, "%d", &rows); fscanf(afile, "%d", &cols); fscanf(cfile, "%d", &cRows); int k; int** a = malloc(rows*sizeof(int*)); for (k = 0; k < rows; k++) { a[k] = malloc(cols*sizeof(int)); } int* c = malloc(cRows*sizeof(int)); int j; for (k = 0; k < rows; k++) { for (j = 0; j < cols; j++) { fscanf(afile, "%d", &a[k][j]); } fscanf(cfile, "%d", &c[k]); } if (seconds == 0) { unsigned long long elim = fm_elim(rows, cols, a, c); for (k = 0; k < rows; k++) { free(a[k]); } free(a); free(c); fclose(afile); fclose(cfile); return elim; } /* Tell operating system to call function DONE when an ALARM comes. */ signal(SIGALRM, done); alarm(seconds); /* Now loop until the alarm comes... */ proceed = true; while (proceed) { fm_elim(rows, cols, a, c); fm_count++; } for (k = 0; k < rows; k++) { free(a[k]); } free(a); free(c); fclose(afile); fclose(cfile); return fm_count; } unsigned long long fm_elim(int rows, int cols, int** a, int* c) { int r = rows; int s = cols; int k = 0; int i = 0; rat** T = malloc(rows*sizeof(rat*)); for (i = 0; i < rows; i++) { T[i] = malloc(cols*sizeof(rat)); } rat* q = malloc(rows*sizeof(rat)); for (k = 0; k < r; k++) { for (i = 0; i < s; i++) { T[k][i].a = a[k][i]; T[k][i].b = 1; } q[k].a = c[k]; q[k].b = 1; } while (1) { int n1 = 0; int n2 = 0; int k = 0; int i = 0; int j = 0; int sig = 0; for (k = 0; k < r; k++) { sig = sign(&(T[k][s-1])); if (sig == 1) { n1++; } else if (sig == -1) { n2++; } } n2 += n1; int currentPosRow = 0; int currentNegRow = n1; int currentZerRow = n2; rat** temp = malloc(r*sizeof(rat*)); for (i = 0; i < r; i++) { temp[i] = malloc(s*sizeof(rat)); } rat* qTemp = malloc(r*sizeof(rat)); for (k = 0; k < r; k++) { sig = sign(&T[k][s-1]); if (sig > 0) { for (i = 0; i < s; i++) { temp[currentPosRow][i] = T[k][i]; } qTemp[currentPosRow] = q[k]; currentPosRow++; } else if (sig < 0) { for (i = 0; i < s; i++) { temp[currentNegRow][i] = T[k][i]; } qTemp[currentNegRow] = q[k]; currentNegRow++; } else { for (i = 0; i < s; i ++) { temp[currentZerRow][i] = T[k][i]; } qTemp[currentZerRow] = q[k]; currentZerRow++; } } for (k = 0; k < r; k++) { for (i = 0; i < s; i++) { T[k][i] = temp[k][i]; } q[k] = qTemp[k]; } for (i = 0; i < r; i++) { free(temp[i]); } free(temp); free(qTemp); for (i = 0; i < n2; i++) { q[i] = divq(&q[i], &T[i][s-1]); for (j = 0; j < s; j++) { T[i][j] = divq(&T[i][j], &T[i][s-1]); } } if (s == 1) { unsigned long long sol = make_solution(n1, n2, r, q); for (i = 0; i < r; i++) { free(T[i]); } free(T); free(q); return sol; } /* Elimination */ int oldR = r; r = r - n2 + n1*(n2 - n1); if (r == 0) { for (i = 0; i < r; i++) { free(T[i]); } free(T); free(q); return 1; } s = s - 1; rat(** elim) = malloc(r*sizeof(rat*)); for (i = 0; i < r; i++) { elim[i] = malloc(s*sizeof(rat)); } rat* cTemp = malloc(r*sizeof(rat)); int curRow = 0; for (k = 0; k < n1; k++) { for (j = n1; j < n2; j++) { for (i = 0; i < s; i++) { elim[curRow][i] = subq(&T[k][i], &T[j][i]); } cTemp[curRow] = subq(&q[k], &q[j]); curRow++; } } for (k = n2; k < oldR; k++) { for (i = 0; i < s; i++) { elim[curRow][i] = T[k][i]; } cTemp[curRow] = q[k]; curRow++; } for (i = 0; i < oldR; i++) { free(T[i]); } T = realloc(T, r*sizeof(rat*)); for (i = 0; i < r; i++) { T[i] = malloc(s*sizeof(rat)); } q = realloc(q, r*sizeof(rat)); if (T == NULL) { fprintf(stderr, "T out of memory \n"); exit(1); } if (q == NULL) { fprintf(stderr, "q out of memory \n"); exit(1); } for (k = 0; k < r; k++) { for (i = 0; i < s; i++) { T[k][i] = elim[k][i]; } q[k] = cTemp[k]; } for (i = 0; i < r; i++) { free(elim[i]); } free(elim); free(cTemp); } } unsigned long long make_solution(int n1, int n2, int rows, rat* c) { int k; int j; for (k = n2; k < rows; k++) { if (sign(&c[k]) < 0) { return (unsigned long long)0; } } rat rat; for (k = 0; k < n1; k++) { for (j = n1; j < n2; j++) { rat = subq(&c[k], &c[j]); if (sign(&rat) < 0) { return (unsigned long long)0; } } } return (unsigned long long)1; } void reduce(int* a, int* b) { int g = gcd(*a, *b); *a = *a/g; *b = *b/g; } int gcd(int a, int b) { if (b == 0) { return a; } else { int temp = a%b; return gcd(b, temp); } } rat addq(rat* r1, rat* r2) { rat r3; r3.a = (*r1).a*(*r2).b + (*r2).a*(*r1).b; r3.b = (*r1).b*(*r2).b; reduce(&(r3.a), &(r3.b)); return r3; } rat subq(rat* r1, rat* r2) { rat r3; r3.a = (*r1).a*(*r2).b - (*r2).a*(*r1).b; r3.b = (*r1).b*(*r2).b; reduce(&(r3.a), &(r3.b)); return r3; } rat mulq(rat* r1, rat* r2) { rat r3; r3.a = (*r1).a*(*r2).a; r3.b = (*r1).b*(*r2).b; reduce(&(r3.a), &(r3.b)); return r3; } rat divq(rat* r1, rat* r2) { rat r3; r3.a = (*r1).a*(*r2).b; r3.b = (*r1).b*(*r2).a; reduce(&(r3.a), &(r3.b)); return r3; } int sign(rat* r1) { if (r1->a == 0) { return 0; } if (!(r1->a < 0 ^ r1->b < 0)) { return 1; } return -1; }
C
/* re.c */ /* Henry Spencer's implementation of Regular Expressions, used for MiniScheme */ /* Refurbished by Stephen Gildea */ #include <sys/types.h> #include <stdlib.h> #include "regex.h" #include "miniscm.h" pointer foreign_re_match(pointer args) { pointer retval = F; int retcode; regex_t rt; pointer first_arg, second_arg; pointer third_arg = NIL; char *string; char *pattern; int num = 0; if (!((args != NIL) && is_string((first_arg = car(args))) && (args=cdr(args)) && is_pair(args) && is_string((second_arg = car(args))))) { return F; } pattern = strvalue(first_arg); string = strvalue(second_arg); args = cdr(args); if (args != NIL) { if (!(is_pair(args) && is_vector((third_arg = car(args))))) { return F; } else { num = ivalue(third_arg); } } if (regcomp(&rt, pattern, REG_EXTENDED) != 0) { return F; } if (num == 0) { retcode = regexec(&rt, string, 0, 0, 0); } else { regmatch_t *pmatch = malloc((num + 1) * sizeof(regmatch_t)); if (pmatch != 0) { retcode = regexec(&rt, string, num + 1, pmatch, 0); if (retcode == 0) { int i; for (i = 0; i < num; i++) { mark_x = mk_integer(pmatch[i].rm_so); mark_y = mk_integer(pmatch[i].rm_eo); set_vector_elem(third_arg, i, cons(mark_x, mark_y)); } } free(pmatch); } else { retcode = -1; } } if (retcode == 0) { retval = T; } regfree(&rt); return retval; } void init_re(void) { scheme_register_foreign_func("re-match", foreign_re_match); }
C
#include<stdlib.h> #include<stdio.h> #include<string.h> #include<sys/types.h> #include<sys/socket.h> #include <sys/un.h> #include<netinet/in.h> #define IP_FOUND "IP_FOUND" /*IP发现命令*/ //#define IP_FOUND "127.0.0.1" /*IP发现命令*/ #define MCAST_PORT 1333 #define IP_FOUND_ACK "IP_FOUND_ACK" /*IP发现应答命令*/ void HandleIPFound(void*arg) { #define BUFFER_LEN 32 int ret = -1; int sock = -1; struct sockaddr_in local_addr; /*本地地址*/ struct sockaddr_in from_addr; /*客户端地址*/ int from_len; int count = -1; fd_set readfd; char buff[BUFFER_LEN] = {0}; struct timeval timeout; timeout.tv_sec = 2; /*超时时间2s*/ timeout.tv_usec = 0; printf("==>HandleIPFound\n"); sock = socket(AF_INET, SOCK_DGRAM, 0); /*建立数据报套接字*/ if( sock < 0 ) { printf("HandleIPFound: socket init error\n"); return; } /*数据清零*/ memset((void*)&local_addr, 0, sizeof(struct sockaddr_in)); /*清空内存内容*/ local_addr.sin_family = AF_INET; /*协议族*/ local_addr.sin_addr.s_addr = htonl(INADDR_ANY);/*本地地址*/ local_addr.sin_port = htons(MCAST_PORT); /*侦听端口*/ /*绑定*/ ret = bind(sock, (struct sockaddr*)&local_addr, sizeof(local_addr)); if(ret != 0) { printf("HandleIPFound:bind error\n"); return; } /*主处理过程*/ while(1) { /*文件描述符集合清零*/ FD_ZERO(&readfd); /*将套接字文件描述符加入读集合*/ FD_SET(sock, &readfd); /*select侦听是否有数据到来*/ ret = select(sock+1, &readfd, NULL, NULL, &timeout); switch(ret) { case -1: /*发生错误*/ break; case 0: /*超时*/ //超时所要执行的代码 break; default: /*有数据到来*/ if( FD_ISSET( sock, &readfd ) ) { /*接收数据*/ count = recvfrom( sock, buff, BUFFER_LEN, 0,( struct sockaddr*) &from_addr, &from_len ); printf( "Recv msg is %s\n", buff ); if( strstr( buff, IP_FOUND ) ) /*判断是否吻合*/ { /*将应答数据复制进去*/ memcpy(buff, IP_FOUND_ACK,strlen(IP_FOUND_ACK)+1); /*发送给客户端*/ count = sendto( sock, buff, strlen( buff ),0, ( struct sockaddr*) &from_addr, from_len ); } } } } printf("<==HandleIPFound\n"); return; } void main() { HandleIPFound(NULL); }
C
#include "monty.h" /** * intcheck - checks if a char string is a 'pure' negative or positive number * Description: verifies a string only has digits, and if negative, a '-' at * only the beginning. * Return: -1 if not pure, 0 if pure */ int intcheck(void) { int count = 0; if (all.arr[1] == NULL) { all.errorcode = 5; return (-1); } if (all.arr[1][0] == '-' && all.arr[1][1] != '\0') count = 1; while (isdigit(all.arr[1][count]) > 0) count++; if (all.arr[1][count] != '\0') { all.errorcode = 5; return (-1); } return (0); }
C
/*Задача 3 Напишете функции, с помощта на които да реализирате динамичен масив от елементи, чиято големина може да се променя по време на изпълнение на програмата*/ #include<stdio.h> #include<stdlib.h> void resizeArr(){ int *p, i, n; printf("Initial size of the array is 4\n\n"); p = (int*)calloc(4, sizeof(int)); if(p==NULL) { printf("Memory allocation failed"); exit(1); // exit the program } for(i = 0; i < 4; i++) { printf("Enter element at index %d: ", i); scanf("%d", p+i); } printf("\nIncreasing the size of the array by 5 elements ...\n "); p = (int*)realloc(p, 9 * sizeof(int)); if(p==NULL) { printf("Memory allocation failed"); exit(1); // exit the program } printf("\nEnter 5 more integers\n\n"); for(i = 4; i < 9; i++) { printf("Enter element at index %d: ", i); scanf("%d", p+i); } printf("\nFinal array: \n\n"); for(i = 0; i < 9; i++) { printf("%d ", *(p+i) ); } } int main() { resizeArr(); return 0; }
C
/* ** op_pos.c for raytracer2 in /home/guts/Projects/MUL_2016/raytracer2/parser_Lucas/src_options ** ** Made by Guts ** Login <[email protected]> ** ** Started on Fri Apr 28 14:07:00 2017 Guts ** Last update Fri May 26 17:50:39 2017 Guts */ #include "raytracer.h" int check_syntax_pos(char *cpy, char *s, int line_n) { int i; int count; i = -1; count = 0; while (cpy[++i]) { if (cpy[i] == ',') count++; if ((cpy[i] < '0' || cpy[i] > '9') && cpy[i] != ',' && cpy[i] != '-' && cpy[i] != '.') return (print_error_syntax(line_n, s)); } if (count != 2) return (print_error_syntax(line_n, s)); return (0); } int op_pos(t_parsing *parsing, char *s, int line_n) { char *cpy; int i; int mem; i = -1; mem = 0; cpy = my_strdup(&s[4]); if ((check_syntax_pos(cpy, s, line_n)) == -1) return (-1); while (cpy[++i] && cpy[i] != ','); if (cpy[i] == ',') parsing->objects->pos.x = my_atof(&cpy[mem]); mem = i + 1; while (cpy[++i] && cpy[i] != ','); if (cpy[i] == ',') parsing->objects->pos.y = my_atof(&cpy[mem]); mem = i + 1; parsing->objects->pos.z = my_atof(&cpy[mem]); free(cpy); return (0); }
C
#include <stdio.h> #include <string.h> #include <stdlib.h> int main() { char input_buffer[513]; char delimit[]=" \t\r\n\v\f"; char *ch_ptr, *token; ch_ptr = fgets(input_buffer, 512 + 1, stdin); puts(ch_ptr); puts(input_buffer); token = strtok(input_buffer, delimit); while(token) { printf("token: %s",token); if (strcmp(token, "exit") == 0) { puts("exit"); } token = strtok(NULL, " "); } return 0; }
C
/* * floatPoint_nr_mainTest.c * * Created on: Sep 9, 2012 * Author: BLEE * * Description: This is the test program for spectrum subtraction noise reduction experiment * * For the book "Real Time Digital Signal Processing: * Fundamentals, Implementation and Application, 3rd Ed" * By Sen M. Kuo, Bob H. Lee, and Wenshun Tian * Publisher: John Wiley and Sons, Ltd * */ #include <stdio.h> #include <stdlib.h> #include "tistdtypes.h" #include "floatPoint_nr.h" NR_VAR nrvar; NR_VAR *pnr; Int16 input1[FrameSize]; Int16 input2[FrameSize]; Int8 temp[2*FrameSize]; void main(void) { FILE *fpIn,*fpOut1,*fpOut2; Int16 i,j; Uint32 n; pnr = &nrvar; if ((fpIn = fopen("..//data//speech.wav","rb")) == NULL ) { printf("Can't open input wave file\n"); exit(0); } fpOut1 = fopen("..//data//nr_output.wav","wb"); fpOut2 = fopen("..//data//nr_ref.xls","wt"); nrvar.L = 256; // FFT size nrvar.Atten = (float)0.1; // NR attenuation factor fread(temp,sizeof(Int8), 22*2, fpIn); // Skip wave header fwrite(temp,sizeof(Int8), 22*2, fpOut1); // Create wave header for output file fprintf(fpOut2, "%s\t%s\n", "Original speech", "SS NR result"); nrvar.N = nrvar.L >> 1; // Frame size = 1/2 window size nr_hwindow(pnr); // Generate Hanning window nrvar.pwindow = nrvar.window; nrvar.pIn = input1; nr_init(pnr); n = 0; printf("Exp --- spectrum subtraction noise reduction\n"); while(fread(temp, sizeof(Int8), nrvar.N*2, fpIn) == (Uint16)(2*nrvar.N)) { for (i=0;i<nrvar.N;i++) // Get input data { input1[i] = (temp[2*i]&0xFF)|(temp[2*i+1]<<8); input2[i] = input1[i]; } nrvar.vadFlag = nr_ss(pnr); nr_proc(pnr); for (j=0, i=0;i<nrvar.N;i++) { temp[j++] = input1[i]&0xFF; temp[j++] = (input1[i]>>8)&0xFF; } fwrite(temp, sizeof(Int8), nrvar.N*2, fpOut1); // Save output wave data for (i=0; i<nrvar.N; i++) { fprintf(fpOut2, "%d\t%d\n", input2[i], input1[i]); } n += nrvar.N; printf("%ld data words processed\n", n); } fclose(fpOut1); fclose(fpOut2); fclose(fpIn); printf("Exp --- completed\n"); }
C
/* * ctrlUnit.c * * Created on: Dec 9, 2019 * Author: OmarG */ #include "tempCOntroller.h" #include "PIR.h" #include "LDR.h" int main(void){ CLEAR_BIT(PTR_STATE_DIR , PA7 ); SET_BIT(PIR_CTRL_PORT_DIR,INPUT1); SET_BIT(PIR_CTRL_PORT_DIR,INPUT2); SET_BIT(LED_CTRL_DIR,LED); Stop_motor(); uint8 TCtrl[2] = {0,127}; uint8 DCtrl[2] = {0,0}; uint8 LCtrl[2] = {1,1}; uint8 *tempStatePtr ; uint8 *doorStatePtr ; uint8 *ledStatePtr ; while(1){ tempStatePtr =temp(TCtrl); doorStatePtr=CTR_pir(DCtrl); ledStatePtr=CTR_ldr(LCtrl); } return 0 ; }
C
#include <ctype.h> #include <stdio.h> #include <string.h> /* * Exercise: 18 * Page: 126 * Make dcl recover from input errors * */ /* * Recover from input errors is interrupted here as continue to operate after * faulty declarator without affecting the next declarator, * it doesn't try to correct the error or even identify it. * */ #define MAXTOKEN 1000 #define MAXLEN 10000 enum { NAME, PARENS, BRACKETS }; static void dcl(void); static void dirdcl(void); static int gettoken(void); static int tokentype; static char token[MAXTOKEN]; static char name[MAXTOKEN]; static char datatype[MAXTOKEN]; static char out[MAXLEN]; int main(void) { while (gettoken() != EOF) { if (tokentype != (int)'\n') { /* handle empty lines*/ strcpy(datatype, token); out[0] = '\0'; dcl(); if (tokentype != (int)'\n') { printf("Syntax Error\n"); } else { /* handles not printing faulty results*/ printf("%s: %s %s\n", name, out, datatype); } } } return 0; } /*dcl: parse a declarator */ void dcl(void) { int ns; for (ns = 0; gettoken() == (int)'*';) { ns++; } dirdcl(); while (ns-- > 0) { strcat(out, " pointer to"); } } /*dirdcl: parse a direct delarator */ void dirdcl(void) { int type; if (tokentype == (int)'(') { dcl(); if (tokentype != (int)')') { printf("error: missing )\n"); } } else if (tokentype == (int)')') { /* handles non-empty function parans*/ printf("error:missing ) \n"); } else { if (tokentype == NAME) { strcpy(name, token); } else { printf("error: expected name or (dcl)\n"); } } while ((type = gettoken()) == PARENS || type == BRACKETS) { if (type == PARENS) { strcat(out, " function returning"); } else { strcat(out, " array"); strcat(out, token); strcat(out, " of "); } } } #define BUFSIZE 10000 static int buf[BUFSIZE]; static int bufp = 0; static int getch(void) { return (bufp > 0) ? (int)buf[--bufp] : getchar(); } static void ungetch(int c) { if (bufp >= BUFSIZE) printf("ungetch: too many characters\n"); else buf[bufp++] = c; } int gettoken(void) { int c; char *p = token; while ((c = getch()) == (int)' ' || c == (int)'\t') { ; } if (c == (int)'(') { if ((c = getch()) == (int)')') { strcpy(token, "()"); return (tokentype = PARENS); } else { ungetch(c); return (tokentype = (int)'('); } } else if (c == (int)'[') { for (*p++ = (char)c; (*p++ = (char)getch()) != ']';) { if (*(p - 1) == '\n') { /* handles unexpected end of the line, a better handling would be allowing only numbers between brackets */ printf("error: expected ] before end of line\n"); return (tokentype = (int)('\0')); } } *p = '\0'; return (tokentype = BRACKETS); } else if (isalpha(c) || c == (int)'_') { for (*p++ = (char)c; isalnum(c = getch()) || c == (int)'_';) { *p++ = (char)c; } *p = '\0'; ungetch(c); return (tokentype = NAME); } else { return (tokentype = c); } }
C
/****************************************************************************** * Filename : tcpclient.c * Author : Pranit Ekatpure * Description : This file contain TCP client-server example's client * implementation. *******************************************************************************/ /****************************************************************************** * Includes *******************************************************************************/ #include <sys/socket.h> #include <netinet/in.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <arpa/inet.h> #include <stdio.h> /****************************************************************************** * Macros *******************************************************************************/ #define SERV_PORT 9877 #define IP_ADDR "127.0.0.1" #define MAXLINE 4096 /****************************************************************************** * Function Prototypes *******************************************************************************/ int str_cli(FILE* , int ); /****************************************************************************** * Function Definitions *******************************************************************************/ /****************************************************************************** * Function : main * Description : TCP echo client: main function * * Parameters : void * Return value : int * *******************************************************************************/ int main() { int sockfd, return_val; struct sockaddr_in servaddr; /* Create a socket that uses an internet IPv4 address, * Set the socket to be stream based (TCP), * choose the default protocol */ if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) { fprintf(stderr, "ERROR: failed to create the socket\n"); return -1; } /* Initialize the server address struct with zeros */ bzero(&servaddr, sizeof(servaddr)); /* Fill in the server address */ servaddr.sin_family = AF_INET; /* using IPv4 */ servaddr.sin_port = htons(SERV_PORT); if(inet_pton(AF_INET, IP_ADDR, &servaddr.sin_addr) == -1) { fprintf(stderr, "ERROR: invalid address\n"); return -1; } /* Connect to the server */ if(connect(sockfd, (struct sockaddr*)&servaddr, sizeof(servaddr)) == -1) { fprintf(stderr, "ERRRO: failed to connect\n"); return -1; } /* Call client processing function */ return_val = str_cli(stdin, sockfd); if(return_val == -1) /* Error in client processing */ { fprintf(stderr, "ERROR: failed client processing"); /* Close connection to the server */ close(sockfd); return -1; } else if(return_val == 0) /* End of client processing */ { fprintf(stdout, "END: end of client processing"); /* Close connection to the server */ close(sockfd); exit(0); } exit(0); } /****************************************************************************** * Function : str_cli * Description : TCP echo client: str_cli function * * Parameters : * FILE* fp : file pointer * int sockfd : socket fd * Return value : int * *******************************************************************************/ int str_cli(FILE* fp, int sockfd) { char sendline[MAXLINE], recvline[MAXLINE]; int n; /* Get input line from standard input */ while(fgets(sendline, MAXLINE,fp) != NULL) { /* write line to server */ if(write(sockfd, sendline, strlen(sendline)) == -1) { fprintf(stderr, "ERROR: failed to write to server\n"); return -1; } /* read from server */ if((n = read(sockfd, recvline, MAXLINE)) == -1) { fprintf(stderr, "ERROR: failed to read from server\n"); return -1; } /* null terminate */ recvline[n] = 0; /* write line to standard output */ if(fputs(recvline, stdout) == EOF) { fprintf(stderr, "ERROR: failed to put to standard output"); return -1; } } return 0; } /******************************************************************************/
C
// MIT License, Copyright (c) 2020 Marvin Borner #include <assert.h> #include <def.h> #include <fs.h> #include <ide.h> #include <mem.h> #include <print.h> #include <random.h> #include <str.h> /** * VFS */ static struct list *mount_points = NULL; char *vfs_normalize_path(const char *path) { char *fixed = strdup(path); int len = strlen(fixed); if (fixed[len - 1] == '/' && len != 1) fixed[len - 1] = '\0'; return fixed; } u32 vfs_mounted(struct device *dev, const char *path) { struct node *iterator = mount_points->head; while (iterator) { if (((struct mount_info *)iterator->data)->dev->id == dev->id || !strcmp(((struct mount_info *)iterator->data)->path, path)) return 1; iterator = iterator->next; } return 0; } struct mount_info *vfs_recursive_find(char *path) { struct node *iterator = mount_points->head; char *fixed = vfs_normalize_path(path); free(path); // Due to recursiveness while (iterator) { struct mount_info *m = iterator->data; if (!strcmp(m->path, fixed)) { free(fixed); return m; } iterator = iterator->next; } if (strlen(fixed) == 1) { free(fixed); return NULL; } *(strrchr(fixed, '/') + 1) = '\0'; return vfs_recursive_find(fixed); } struct mount_info *vfs_find_mount_info(const char *path) { assert(path[0] == '/'); return vfs_recursive_find(strdup(path)); } struct device *vfs_find_dev(const char *path) { assert(path[0] == '/'); struct mount_info *m = vfs_find_mount_info(path); return m && m->dev ? m->dev : NULL; } const char *vfs_resolve_type(enum vfs_type type) { switch (type) { case VFS_DEVFS: return "devfs"; case VFS_TMPFS: return "tmpfs"; case VFS_PROCFS: return "procfs"; case VFS_EXT2: return "ext2"; default: return "unknown"; } } void vfs_list_mounts() { struct node *iterator = mount_points->head; while (iterator) { struct mount_info *m = iterator->data; printf("%s on %s type %s\n", m->dev->name, m->path, vfs_resolve_type(m->dev->vfs->type)); iterator = iterator->next; } } u32 vfs_mount(struct device *dev, const char *path) { // TODO: Check if already mounted if (!dev || !dev->id || vfs_mounted(dev, path)) return 0; char *fixed = vfs_normalize_path(path); struct mount_info *m = malloc(sizeof(*m)); m->path = fixed; m->dev = dev; list_add(mount_points, m); return 1; } u32 vfs_read(const char *path, void *buf, u32 offset, u32 count) { if (count == 0 || offset > count) return 0; struct mount_info *m = vfs_find_mount_info(path); assert(m && m->dev && m->dev->vfs && m->dev->vfs->read); u32 len = strlen(m->path); if (len > 1) path += len; struct device *dev = m->dev; return dev->vfs->read(path, buf, offset, count, dev); } u32 vfs_write(const char *path, void *buf, u32 offset, u32 count) { struct device *dev = vfs_find_dev(path); assert(dev && dev->vfs && dev->vfs->write); return dev->vfs->write(path, buf, offset, count, dev); } u32 vfs_stat(const char *path, struct stat *buf) { struct device *dev = vfs_find_dev(path); assert(dev && dev->vfs && dev->vfs->stat); return dev->vfs->stat(path, buf, dev); } void vfs_install(void) { mount_points = list_new(); } /** * Device */ static struct list *devices = NULL; void device_add(struct device *dev) { dev->id = rand() + 1; list_add(devices, dev); } struct device *device_get(u32 id) { struct node *iterator = devices->head; while (iterator) { if (((struct device *)iterator->data)->id == id) return iterator->data; iterator = iterator->next; } return NULL; } u32 devfs_read(const char *path, void *buf, u32 offset, u32 count, struct device *dev) { assert(dev && dev->read); printf("%s - off: %d, cnt: %d, buf: %x, dev %x\n", path, offset, count, buf, dev); return dev->read(buf, offset, count, dev); } void device_install(void) { devices = list_new(); struct vfs *vfs; struct device *dev; vfs = malloc(sizeof(*vfs)); vfs->type = VFS_DEVFS; vfs->read = devfs_read; dev = malloc(sizeof(*dev)); dev->name = "dev"; dev->vfs = vfs; device_add(dev); vfs_mount(dev, "/dev/"); /* vfs_list_mounts(); */ } /** * EXT2 */ void *buffer_read(u32 block, struct device *dev) { void *buf = malloc(BLOCK_SIZE); dev->read(buf, block * SECTOR_COUNT, SECTOR_COUNT, dev); return buf; } struct ext2_superblock *get_superblock(struct device *dev) { struct ext2_superblock *sb = buffer_read(EXT2_SUPER, dev); if (sb->magic != EXT2_MAGIC) return NULL; return sb; } struct ext2_bgd *get_bgd(struct device *dev) { return buffer_read(EXT2_SUPER + 1, dev); } struct ext2_inode *get_inode(u32 i, struct device *dev) { struct ext2_superblock *s = get_superblock(dev); assert(s); struct ext2_bgd *b = get_bgd(dev); assert(b); u32 block_group = (i - 1) / s->inodes_per_group; u32 index = (i - 1) % s->inodes_per_group; u32 block = (index * EXT2_INODE_SIZE) / BLOCK_SIZE; b += block_group; u32 *data = buffer_read(b->inode_table + block, dev); struct ext2_inode *in = (struct ext2_inode *)((u32)data + (index % (BLOCK_SIZE / EXT2_INODE_SIZE)) * EXT2_INODE_SIZE); return in; } u32 read_indirect(u32 indirect, u32 block_num, struct device *dev) { char *data = buffer_read(indirect, dev); return *(u32 *)((u32)data + block_num * sizeof(u32)); } u32 read_inode(struct ext2_inode *in, void *buf, u32 offset, u32 count, struct device *dev) { // TODO: Support read offset (void)offset; if (!in || !buf) return 0; u32 num_blocks = in->blocks / (BLOCK_SIZE / SECTOR_SIZE); if (!num_blocks) return 0; // TODO: memcpy block chunks until count is copied while (BLOCK_SIZE * num_blocks > count) num_blocks--; u32 indirect = 0; u32 blocknum = 0; char *data = 0; // TODO: Support triply indirect pointers // TODO: This can be heavily optimized by saving the indirect block lists for (u32 i = 0; i < num_blocks; i++) { if (i < 12) { blocknum = in->block[i]; data = buffer_read(blocknum, dev); memcpy((u32 *)((u32)buf + i * BLOCK_SIZE), data, BLOCK_SIZE); } else if (i < BLOCK_COUNT + 12) { indirect = in->block[12]; blocknum = read_indirect(indirect, i - 12, dev); data = buffer_read(blocknum, dev); memcpy((u32 *)((u32)buf + i * BLOCK_SIZE), data, BLOCK_SIZE); } else { indirect = in->block[13]; blocknum = read_indirect(indirect, (i - (BLOCK_COUNT + 12)) / BLOCK_COUNT, dev); blocknum = read_indirect(blocknum, (i - (BLOCK_COUNT + 12)) % BLOCK_COUNT, dev); data = buffer_read(blocknum, dev); memcpy((u32 *)((u32)buf + i * BLOCK_SIZE), data, BLOCK_SIZE); } /* printf("Loaded %d of %d\n", i + 1, num_blocks); */ } return count; } u32 find_inode(const char *name, u32 dir_inode, struct device *dev) { if (!dir_inode) return (unsigned)-1; struct ext2_inode *i = get_inode(dir_inode, dev); char *buf = malloc(BLOCK_SIZE * i->blocks / 2); memset(buf, 0, BLOCK_SIZE * i->blocks / 2); for (u32 q = 0; q < i->blocks / 2; q++) { char *data = buffer_read(i->block[q], dev); memcpy((u32 *)((u32)buf + q * BLOCK_SIZE), data, BLOCK_SIZE); } struct ext2_dirent *d = (struct ext2_dirent *)buf; u32 sum = 0; do { // Calculate the 4byte aligned size of each entry sum += d->total_len; if (strlen(name) == d->name_len && strncmp((void *)d->name, name, d->name_len) == 0) { free(buf); return d->inode_num; } d = (struct ext2_dirent *)((u32)d + d->total_len); } while (sum < (1024 * i->blocks / 2)); free(buf); return (unsigned)-1; } struct ext2_inode *find_inode_by_path(const char *path, struct device *dev) { if (path[0] != '/') return 0; char *path_cp = strdup(path); char *init = path_cp; // For freeing path_cp++; u32 current_inode = EXT2_ROOT; int i = 0; while (1) { for (i = 0; path_cp[i] != '/' && path_cp[i] != '\0'; i++) ; if (path_cp[i] == '\0') break; path_cp[i] = '\0'; current_inode = find_inode(path_cp, current_inode, dev); path_cp[i] = '/'; if (current_inode == 0) { free(init); return 0; } path_cp += i + 1; } u32 inode = find_inode(path_cp, current_inode, dev); free(init); if ((signed)inode <= 0) return 0; return get_inode(inode, dev); } u32 ext2_read(const char *path, void *buf, u32 offset, u32 count, struct device *dev) { struct ext2_inode *in = find_inode_by_path(path, dev); if (in) return read_inode(in, buf, offset, count, dev); else return 0; } u32 ext2_stat(const char *path, struct stat *buf, struct device *dev) { if (!buf) return 1; struct ext2_inode *in = find_inode_by_path(path, dev); if (!in) return 1; u32 num_blocks = in->blocks / (BLOCK_SIZE / SECTOR_SIZE); u32 sz = BLOCK_SIZE * num_blocks; buf->dev_id = dev->id; buf->size = sz; // Actually in->size but ext2.. return 0; }
C
/* averaged_perceptron_tagger.h ---------------------------- An averaged perceptron tagger is a greedy sequence labeling algorithm which uses features of the current token, surrounding tokens and n (typically n=2) previous predictions to predict the current value. */ #ifndef AVERAGED_PERCEPTRON_TAGGER_H #define AVERAGED_PERCEPTRON_TAGGER_H #include <stdlib.h> #include <stdint.h> #include <stdbool.h> #include <string.h> #include "averaged_perceptron.h" #include "tokens.h" #define START "START" #define START2 "START2" // Arguments: tagger, context, tokenized str, index, i-1 tag, i-2 tag typedef bool (*ap_tagger_feature_function)(void *, void *, tokenized_string_t *, uint32_t, char *, char *); bool averaged_perceptron_tagger_predict(averaged_perceptron_t *model, void *tagger, void *context, cstring_array *features, cstring_array *labels, ap_tagger_feature_function feature_function, tokenized_string_t *tokenized); #endif
C
#include <stdio.h> #include <stdlib.h> struct Graph { int V; int E; int adj[2001][2001]; }; struct Edge { int v; int w; }; typedef struct Graph *Graph; typedef struct Edge *Edge; // int ** matrix_init(int l, int c) { // int ** matrix; // matrix = (int **) calloc(l, sizeof(int *)); // for(int i = 0; i < l; i++) { // matrix[i] = (int *) calloc(c, sizeof(int)); // } // return matrix; // } Graph graph_init(int v) { Graph G = malloc(sizeof(*G)); G->V = v; G->E = 0; // G->adj = matrix_init(v, v); return G; } Edge edge_init(int v, int w) { Edge E = malloc(sizeof(*E)); E->v = v; E->w = w; return E; } void graph_insert_edge(Graph G, Edge E) { int v = E->v; int w = E->w; if (G->adj[v][w] == 0) G->E++; G->adj[v][w] = 1; G->adj[w][v] = 1; } void show_graph(Graph G) { int v, w; printf(" | "); for (int i = 0; i < G->V; i++) printf("%d| ", i); printf("\n"); for (int i = 0; i <= G->V; i++) printf("---"); printf("\n"); for (v = 0; v < G->V; v++) { printf("%d| ", v); for (w = 0; w < G->V; w++) printf("%d| ", G->adj[v][w]); printf("\n"); } } int main() { int N, M, J; int vizinhos, local_proximo; int *locais_juliano; Graph graph; Edge edge; scanf("%d %d %d", &N, &M, &J); graph = graph_init(N); locais_juliano = (int *)calloc(N, sizeof(int)); for (int i = 0; i < N; i++) { scanf("%d", &vizinhos); for (int j = 0; j < vizinhos; j++) { scanf("%d", &local_proximo); edge = edge_init(i, local_proximo); graph_insert_edge(graph, edge); } } for (int i = 0; i < M; i++) { scanf("%d", &local_proximo); locais_juliano[i] = local_proximo; } for (int i = 0; i < J; i++) { scanf("%d", &local_proximo); for (int j = 0; j < M; j++) { if (graph->adj[locais_juliano[j]][local_proximo] == 1 || locais_juliano[j] == local_proximo) printf("Eu vou estar la\n"); else printf("Nao vou estar la\n"); } } // show_graph(graph); return 0; }
C
#include <stdio.h> #include <wiringPiI2C.h> int main(void) { int fd[2]; int i, ret; for (i=0; i<2; i++) { fd[i] = wiringPiI2CSetup (i); ret = wiringPiI2CReadReg8 (fd[i], 0x7a); //device_id printf("fd[%d]:%d, DEV_ID:0x%x\n", i, fd[i], ret); } return 0; }
C
#include<stdio.h> #include<conio.h> void main() { char leter; printf("the character is":): scanf("%d",&letter); if(letter==a||letter==e||letter==i||letter==o||letter==u) { printf("vowel"); } else { printf("constant"); } getch(); }
C
typedef struct { int key; // the key for deciding position in heap int dataIndex; // the payload index provided by the calling program } HeapItem; typedef struct { HeapItem *H; // the underlying array int small_large; // smallest val on top int *map; // map[i] is index into H of location of payload with dataIndex == i int n; // the number of items currently in the heap int size; // the maximum number of items allowed in the heap } Heap; // returns a pointer to a new, empty heap Heap *CreateHeap(int small_large); void HeapPrint(Heap *h); //inserts dataIndex into h. Returns //HEAP SUCCESS if it has inserted, or HEAP FAIL otherwise. int HeapInsert(Heap *h, int dataIndex, int key); //returns the data index of the root. int HeapPeek(Heap *h); //returns the key of the root. int HeapPeekKey(Heap *h); //removes the root, returns the data index to it, and re-heapifies //(possibly changing other items map values) int HeapRemoveMin(Heap *h); //adds delta to the key of dataIndex //and then re-heapifies. void HeapChangeKeyValue(Heap *h, int dataIndex, int new_val); //adds delta to the key of dataIndex //and then re-heapifies. void HeapChangeKeyDelta(Heap *h, int dataIndex, int delta); //free any memory you might of alloced in heap creation. void HeapDestroyHeap(Heap *h); int HeapPeekKey_val(Heap *h, int n);
C
#include <stdlib.h> #include <stdio.h> #include <errno.h> #include <limits.h> #include "utils.h" /********************************************************************* * * fibonacci function. * * This is the target program to be profiled. * *********************************************************************/ #include <stdio.h> int fib(int i) { if (i <= 1) { return 1; } fib_logger(i-1, 1); return fib(i-1) + fib(i-2); } int main(int argc, char *argv[]) { int value; char *end; if (argc != 2) { fprintf(stderr, "usage: %s <value>\n", argv[0]); exit(1); } value = strtol(argv[1], &end, 10); if (((errno == ERANGE) && ((value == LONG_MAX) || (value == LONG_MIN))) || ((errno != 0) && (value == 0))) { perror("strtol"); exit(1); } if (end == argv[1]) { fprintf(stderr, "error: %s is not an integer\n", argv[1]); exit(1); } if (*end != '\0') { fprintf(stderr, "error: junk at end of parameter: %s\n", end); exit(1); } value = fib(value); printf("%d\n", value); exit(0); }
C
int main(){ int k,n,j,i; double x[100],t,s; scanf("%d",&k); for ( i=0;i<k;i++){ scanf("%d",&n); t=0; for ( j=0;j<n;j++){ scanf("%lf",&x[j]); t+=x[j]; } t/=n; s=0; for ( j=0;j<n;j++){ s+=(x[j]-t)*(x[j]-t); } s/=n; s=sqrt(s); printf("%.5lf\n",s); } return 0; }
C
#include "transform.h" #include <assert.h> aout_transform aout_transform_add( aout_transform a, aout_transform b) { return (aout_transform) { .position = aout_vec2_add(a.position, b.position), // TODO: Maybe clamp rotation to [0,2pi] .rotation = a.rotation + b.rotation, .scale = aout_vec2_add(a.scale, b.scale) }; } aout_transform aout_transform_sub( aout_transform a, aout_transform b) { return (aout_transform) { .position = aout_vec2_sub(a.position, b.position), // TODO: Maybe clamp rotation to [0,2pi] .rotation = a.rotation - b.rotation, .scale = aout_vec2_sub(a.scale, b.scale) }; } aout_transform aout_transform_mul( aout_transform t, float32_t f) { return (aout_transform) { .position = aout_vec2_mul(t.position, f), .rotation = t.rotation * f, .scale = aout_vec2_mul(t.scale, f) }; } aout_transform aout_transform_div( aout_transform t, float32_t f) { assert(f != 0.0f); return (aout_transform) { .position = aout_vec2_div(t.position, f), .rotation = t.rotation / f, .scale = aout_vec2_div(t.scale, f) }; } aout_transform aout_transform_lerp( aout_transform a, aout_transform b, float32_t t) { return aout_transform_add( aout_transform_mul(a, t), aout_transform_mul(b, 1.0f - t) ); }
C
#include <stdio.h> #include <stdlib.h> /** * @brief an example struct */ struct example { int a; }; /** * @brief database record struct grouping a row id, an age and a salary. */ struct dbRecord { int rowId; int age; float salary; }; struct dbRecord newEmployee(); int main() { // to declare a struct the syntax is as follows // struct Tag name_of_struct; struct example myExample; // to access members of the struct you use the following syntax // name_of_struct.member myExample.a = 7; printf("The value of the member in the struct is: %d\n", myExample.a); // a struct can have many members but access remains the same. struct dbRecord record; // a struct can also be used as the return value of a function record = newEmployee(); record.rowId = 1; record.age = 32; record.salary = 180000.00; // you can also use structs with pointers struct dbRecord *rowAlias; // give the pointer the address of a variable rowAlias = &record; // to access members when using a struct pointer you must use the -> syntax printf("The employees age is: %d\n", rowAlias->age); printf("The employees salary is %f\n", rowAlias->salary); // you can even dynamically allocate a struct struct dbRecord *fng = malloc(sizeof(*fng)); fng->age = 21; fng->salary = 64000.00; printf("The employees age is: %d\n", fng->age); printf("The employees salary is %f\n", fng->salary); free(fng); fng = 0; return 0; } /** * @brief The function returns a new employee of type dbRecord. All parameters * Are initialized to a zero value. * * @return */ struct dbRecord newEmployee() { struct dbRecord new; new.rowId = 0; new.age = 0; new.salary = 0.0; return new; }
C
#include <stdio.h> #include <stdlib.h> #include <sys/stat.h> #ifndef NULL #define NULL ((void*)0) #endif typedef struct r_node { int value; struct r_node *prev; struct r_node *next; } cpu_f_node; cpu_f_node *top=NULL; int insert( int val ) { //ptr cur 초기화 cpu_f_node *ptr = NULL; cpu_f_node *cur = NULL; int i=0; ptr = malloc(sizeof(cpu_f_node)); if ( ptr == NULL ) { return -1; } ptr->value = val; if ( top==NULL ) { top = ptr; top->next = NULL; } else { cur = top; while(1) { if ( cur->next==NULL ) { cur->next = ptr; ptr->next = NULL; break; } else { cur = cur->next; } } } return 1; } int delete( int val ) { cpu_f_node *ptr = NULL; cpu_f_node *next = NULL; cpu_f_node *prev= NULL; if ( top == NULL ) { return -1; } if ( top && top->value == val ) { if ( top->next ) { ptr = top; top = top->next; free(ptr); } else { free(top); top = NULL; } return 1; } if ( top->next ) { prev = top; ptr = top->next; } else { return -2; } while(1){ if ( ptr->value==val ) { if ( ptr->next ) { prev->next = ptr->next; free(ptr); } else { prev->next = NULL; free(ptr); } return 1; } else { if ( ptr->next == NULL ) { return -3; } prev = ptr; ptr = ptr->next; } #if 0 // 첫번째 주소를 삭제할때 if(ptr->next == NULL && ptr->value == val){ free(ptr); ptr=NULL; top=NULL; break; }else if(ptr->next ==NULL){ return -1; }else if(ptr->next != NULL && ptr->value == val){ next=ptr->next; free(ptr); top=next; break ; }else // 첫번째 이외의 주소에 있는 데이터 삭제 if((ptr->next)->value == val){ prev = ptr; ptr=ptr->next; }else if(ptr->value == val){ next=ptr->next; prev->next=next; free(ptr); ptr=NULL; break; } #endif } return 1; } void print_ll( void ) { cpu_f_node *ptr = NULL; ptr = top; while(1) { if ( ptr==NULL ) { break; } else { printf("value %d\n", ptr->value); ptr = ptr->next; } } } void freeall( void ) { cpu_f_node *ptr = NULL; cpu_f_node *next = NULL; ptr = top; while(1) { if ( ptr==NULL ) { break; } else { next = ptr->next; free(ptr); ptr = next; } } top = NULL; } int main( int argc, char *argv[] ) { insert(1); insert(10); print_ll(); printf("\n"); insert(1); insert(2); insert(3); insert(1); delete(1); insert(4); insert(5); insert(6); print_ll(); freeall(); return 1; }
C
#include <stdlib.h> #include <stdio.h> #include "line-arg.h" lnA_Parser* par = NULL; lnA_Usage* usg = NULL; void helpCb( char* opt, void* udata ) { lnA_printUsage( par ); exit( 1 ); } void paramCb( char* arg, void* udata ) { printf( "Got argument: %s\n", arg ); } int main( int argc, char** argv ) { par = lnA_makeParser( "programName", NULL ); usg = lnA_addUsage( par, "{ params... | [-h | --help] }" ); lnA_addOption( par, "h", "help", "Displays usage info", &helpCb ); lnA_addParam( par, "params", &paramCb ); lnA_setHeader( par, "Header text" ); lnA_setFooter( par, "Footer text" ); char* err = lnA_tryUsage( par, usg, &argv[1] ); if( err ) { fprintf( stderr, "Error: %s\n", err ); lnA_freeParser( par ); exit( 1 ); } lnA_freeParser( par ); return 0; }
C
int main() { float pi=3.14,radius,area; printf("Enter the radius of circle \n "); scanf("%f",&radius); area=pi*radius*radius; printf("\nArea of a circle=%f\n",area); }
C
/** * A short and concise description goes here. * ************************************************* * * Author: Shuo Yang * Email: [email protected] */ #include "bitvector.h" #include "protos.h" #include "syntax-tree.h" #include "basic_block.h" extern void printtac( TAC *tac ); extern void print_bv( const char *name, bitvec *bv, int len ); extern TAC *newTAC( SyntaxNodeType optype, address *operand1, address *operand2, address *dest ); /** * total number of local variables/tmps * inside the current processed function. */ extern int num_vars; /** * total number of definitions/uses of local vars/tmps * inside the current processed function. */ extern int num_defuses; /** * header to the basic block list of the current function. */ extern bbl *bhead; /** * The set of all expressions appearing on the RHS of some * instruction in the current processed procedure. */ bitvec *uset; /** * stack size for the current processed function. * This may change since we will introduce new tmps for common * subexpressions. */ int stack_size; //static bool debug = true; static bool debug = false; /** * Check if 'var' is in a valid expression. */ static bool is_in_valid_expr( address *var ) { if ( is_valid_local( var ) || (var->atype == AT_Intcon || var->atype == AT_Charcon) ) { return true; } return false; } /** * Check if 'tac' contains a valid expression. */ static bool is_valid_expr( TAC *tac ) { if ( (tac->optype == UnaryMinus && is_valid_local(tac->operand1)) || (is_in_valid_expr(tac->operand1) && is_in_valid_expr(tac->operand2)) ) { return true; } return false; } /** * For each local var/tmp compute the set of expressions that involve it. */ static void compute_expr_bv( TAC_seq *tacseq ) { TAC *tac = tacseq->start; while ( tac != NULL ) { if ( is_arith_op(tac->optype) ) { if ( tac->optype == UnaryMinus ) { if ( is_valid_local(tac->operand1) ) { if ( tac->operand1->val.stptr->expr_bv == NULL ) { tac->operand1->val.stptr->expr_bv = NEW_BV( num_defuses-1 ); } SET_BIT( tac->operand1->val.stptr->expr_bv, tac->id-1 ); SET_BIT( uset, tac->id-1 ); } } else { if ( is_in_valid_expr(tac->operand1) && is_in_valid_expr(tac->operand2) ) { if ( is_valid_local(tac->operand1) ) { if ( tac->operand1->val.stptr->expr_bv == NULL ) { tac->operand1->val.stptr->expr_bv = NEW_BV( num_defuses-1 ); } SET_BIT( tac->operand1->val.stptr->expr_bv, tac->id-1 ); } if ( is_valid_local(tac->operand2) ) { if ( tac->operand2->val.stptr->expr_bv == NULL ) { tac->operand2->val.stptr->expr_bv = NEW_BV( num_defuses-1 ); } SET_BIT( tac->operand2->val.stptr->expr_bv, tac->id-1 ); } SET_BIT( uset, tac->id-1 ); } } } tac = tac->next; } } /** * Compute gen and kill set for the basic block 'bb' * using its local information. */ static void compute_expr_gen_kill( bbl *bb ) { TAC *tac = bb->first_tac; bitvec *bvtmp; int iternum = 0; while ( iternum < bb->numtacs ) { if ( is_arith_op(tac->optype) ) { if ( is_valid_expr(tac) ) { SET_BIT( bb->expr_gen, tac->id-1 ); // add current tac to gen set. CLEAR_BIT( bb->expr_kill, tac->id-1 ); // remove current tac from kill set. if ( is_valid_local(tac->dest) && tac->dest->val.stptr->expr_bv ) { /* current tac kills all expression involving its destination variable. */ bvtmp = bb->expr_gen; bb->expr_gen = bv_diff( bb->expr_gen, tac->dest->val.stptr->expr_bv, num_defuses-1 ); free( bvtmp ); bvtmp = bb->expr_kill; bb->expr_kill = bv_union( bb->expr_kill, tac->dest->val.stptr->expr_bv, num_defuses-1 ); free( bvtmp ); } } } else if ( tac->optype == Assg || tac->optype == Retrieve ) { /* redefining a local var/tmp kills all expressions involving this local var/tmp. */ if ( is_valid_local(tac->dest) && tac->dest->val.stptr->expr_bv ) { bvtmp = bb->expr_gen; bb->expr_gen = bv_diff( bb->expr_gen, tac->dest->val.stptr->expr_bv, num_defuses-1 ); free( bvtmp ); bvtmp = bb->expr_kill; bb->expr_kill = bv_union( bb->expr_kill, tac->dest->val.stptr->expr_bv, num_defuses-1 ); free( bvtmp ); } } // printtac( tac ); // putchar( '\n' ); tac = tac->next; ++iternum; } } static bitvec *compute_expr_in_bb( bbl *bb ) { bitvec *bvtmp; bitvec *res = NEW_BV( num_defuses-1 ); control_flow_list *cfl = bb->pred; while ( cfl != NULL ) { bvtmp = res; res = bv_union( res, cfl->bb->expr_out, num_defuses-1 ); free( bvtmp ); cfl = cfl->next; } return res; } static bitvec *compute_expr_out_bb( bbl *bb ) { bitvec *bvtmp; bitvec *res; res = bv_diff( bb->expr_in, bb->expr_kill, num_defuses-1 ); bvtmp = res; res = bv_union( res, bb->expr_gen, num_defuses-1 ); free( bvtmp ); return res; } /** * Compute in and out set for each basic block of the current * processed function. */ static void compute_expr_in_out() { bbl *bbl_run; bitvec *bvtmp, *oldout; bool change; /* Initialize in and out set for each basic block. */ bbl_run = bhead; while( bbl_run != NULL ) { bbl_run->expr_in = NEW_BV( num_defuses-1 ); bbl_run->expr_out = NEW_BV( num_defuses-1 ); bvtmp = bbl_run->expr_out; bbl_run->expr_out = bv_diff( uset, bbl_run->expr_kill, num_defuses-1 ); free( bvtmp ); bbl_run = bbl_run->next; } /* Iteratively compute in and out set until they converge. */ change = true; while ( change ) { //printf( "Computing inout: iteration\n" ); change = false; bbl_run = bhead; while( bbl_run != NULL ) { bbl_run->expr_in = compute_expr_in_bb( bbl_run ); oldout = bbl_run->expr_out; bbl_run->expr_out = compute_expr_out_bb( bbl_run ); if ( bv_unequal_check(oldout, bbl_run->expr_out, num_defuses-1) == true ) { change = true; } free( oldout ); bbl_run = bbl_run->next; } } // printf( "Converge!\n" ); } /** * Carry out global available expression analysis. */ void avail_expr( TAC_seq *tacseq ) { bbl *bbl_run; if ( debug ) { printf( "Number of local variables/tmps = %d\n", num_vars ); printf( "Number of defs/uses of local vars/tmps = %d\n", num_defuses ); } uset = NEW_BV( num_defuses-1 ); /* For each local var/tmp compute the set of expressions that involve it. */ compute_expr_bv( tacseq ); //print_bv( "Uset", uset, num_defuses-1 ); /* For each block, compute its gen and kill set. */ bbl_run = bhead; while( bbl_run != NULL ) { bbl_run->expr_gen = NEW_BV( num_defuses-1 ); bbl_run->expr_kill = NEW_BV( num_defuses-1 ); compute_expr_gen_kill( bbl_run ); bbl_run = bbl_run->next; } compute_expr_in_out(); } /** * Check if two addresses 'x' and 'y' are equal. * If they are symbol table entries, the pointers to symbol table * entry should match. * If they are constant, their value should equal. */ static bool operands_equal_check( address *x, address *y ) { /* Note that for UnaryMinus, operand2 is NULL. So check this specially. */ if ( x == NULL && y == NULL ) { return true; } if ( x->atype == AT_StRef && y->atype == AT_StRef ) { if ( x->val.stptr == y->val.stptr ) { return true; } } if ( (x->atype == AT_Intcon || x->atype == AT_Charcon) && (y->atype == AT_Intcon || y->atype == AT_Charcon)) { if ( x->val.iconst == y->val.iconst ) { return true; } } return false; } /** * Match available expressions in the set 'avail' with the expression in * the target tac 'target' by traversing 'tacseq' forwardly. * * For each match found, transform its code in place; return the address * for holding the expression. * If no match found, return NULL. */ static address *expr_match( TAC *target, bitvec *avail, TAC_seq *tacseq ) { TAC *tac_next, *newtac; TAC *tac = tacseq->start; /* Tmp varaible used to hold the value of common subexpression if any. */ symtabnode *tmpvar = newtmp_var(); symtabnode *tmpdest; // used to hold dest of common subexpression if any. SyntaxNodeType optype; address *dest, *operand1, *operand_ret; bool match_found = false; while ( tac != NULL ) { if ( tac == target ) { tac = tac->next; continue; } if ( is_arith_op(tac->optype) && is_valid_expr(tac) ) { if ( TEST_BIT(avail, tac->id-1) ) { // see if 'tac' is in 'avail' set. // see if expression in 'tac' matches expression in 'target' if ( operands_equal_check(target->operand1, tac->operand1) && operands_equal_check(target->operand2, tac->operand2) ) { if ( debug ) { printf( "A match of common subexpr found: " ); printtac( tac ); printf( "For: "); printtac( target ); putchar( '\n' ); } match_found = true; tac_next = tac->next; /* Transform 'tac' that contains a common subexpression. */ tmpdest = tac->dest->val.stptr; tac->dest->val.stptr = tmpvar; // store value of common subexpression to 'tmpvar'. tmpvar->varid = ++num_vars; // assign 'varid' to 'tmpvar' and update 'num_var' /* allocate stack space for 'tmpvar'. */ stack_size += 4; // increment size of stack by 4. tmpvar->offset2fp = stack_size; /* create a new tac for assigning 'tmpvar' to 'tmpdest'. */ optype = Assg; dest = (address *) zalloc( sizeof(address) ); dest->atype = AT_StRef; dest->val.stptr = tmpdest; operand1 = (address *) zalloc( sizeof(address) ); operand1->atype = AT_StRef; operand1->val.stptr = tmpvar; newtac = newTAC( optype, operand1, NULL, dest ); newtac->id = ++num_defuses; /* chain instructions together. */ tac->next = newtac; newtac->prev = tac; newtac->next = tac_next; tac_next->prev = newtac; } } } tac = tac->next; } if ( match_found ) { operand_ret = (address *) zalloc( sizeof(address) ); operand_ret->atype = AT_StRef; operand_ret->val.stptr = tmpvar; return operand_ret; } else { return NULL; } } static void common_subexpr_elimination_bb( bbl *bb, TAC_seq *tacseq ) { TAC *tac = bb->first_tac; int iternum = 0; bitvec *bvtmp; address *rhs = NULL; /* Use to keep the set of available expressions at each point just before every instruction in the current basic block. */ bitvec *avail = NEW_BV( num_defuses-1 ); avail = bv_union( avail, bb->expr_in, num_defuses-1 ); while ( iternum < bb->numtacs ) { if ( is_arith_op(tac->optype) && is_valid_expr(tac) ) { rhs = expr_match( tac, avail, tacseq ); if ( rhs != NULL ) { /* Transform 'tac' into an assignment. */ tac->optype = Assg; tac->operand1 = rhs; tac->operand2 = NULL; } /* update 'avail' set. */ SET_BIT( avail, tac->id-1 ); // add current tac to avail set. if ( is_valid_local(tac->dest) && tac->dest->val.stptr->expr_bv ) { /* current tac kills all expression involving its destination variable. */ bvtmp = avail; avail = bv_diff( avail, tac->dest->val.stptr->expr_bv, num_defuses-1 ); free( bvtmp ); } } else if ( is_arith_op(tac->optype) && is_valid_local(tac->dest) ) { if ( tac->dest->val.stptr->expr_bv ) { /* current tac kills all expression involving its destination variable. */ bvtmp = avail; avail = bv_diff( avail, tac->dest->val.stptr->expr_bv, num_defuses-1 ); free( bvtmp ); } } else if ( (tac->optype == Assg || tac->optype == Retrieve) && is_valid_local(tac->dest) ) { if ( tac->dest->val.stptr->expr_bv ) { /* current tac kills all expression involving its destination variable. */ bvtmp = avail; avail = bv_diff( avail, tac->dest->val.stptr->expr_bv, num_defuses-1 ); free( bvtmp ); } } ++iternum; tac = tac->next; } free( avail ); } /** * Perform common subexpression elimination after carrying * out available expression analysis. */ void common_subexpr_elimination( TAC_seq *tacseq ) { bbl *bbl_run; TAC *tac = tacseq->start->next; // 'enter func stack size' tac stack_size = tac->operand2->val.iconst; // operand2 is the size of stack. if ( debug ) { printf( "stack size before cse: %d\n", stack_size ); } bbl_run = bhead; while( bbl_run != NULL ) { common_subexpr_elimination_bb( bbl_run, tacseq ); bbl_run = bbl_run->next; } tac->operand2->val.iconst = stack_size; // update stack size. if ( debug ) { printf( "stack size after cse: %d\n", stack_size ); } }
C
#include "heap.h" #include <pthread.h> #include <stddef.h> #include <sys/mman.h> #include "debug/log.h" heap_chunk_t start; void* curr_addr = HEAP_START; pthread_mutex_t heap_mutex = PTHREAD_MUTEX_INITIALIZER; size_t roundUp(size_t numToRound, size_t multiple) { // assert(multiple && ((multiple & (multiple - 1)) == 0)); return (numToRound + multiple - 1) & -multiple; } size_t paged_size(size_t size) { size_t minSize = size + sizeof(heap_chunk_t*); return roundUp(minSize, PAGE_SIZE); } void* get_user_addr(heap_chunk_t* chunk) { size_t pagedSize = paged_size(chunk->size); void* end_addr = chunk->addr + pagedSize; void* chunk_addr = end_addr - chunk->size; return chunk_addr; } void initialize_chunk(heap_chunk_t *chunk) { chunk->addr = 0; chunk->snapshot = NULL; chunk->mapped = false; chunk->next = chunk; chunk->prev = chunk; } // assumes we have the mutex void insert_chunk(heap_chunk_t *chunk) { heap_chunk_t* prev = start.prev; start.prev = chunk; chunk->next = &start; chunk->prev = prev; prev->next = chunk; } // assumes we have the mutex void remove_chunk(heap_chunk_t *chunk) { heap_chunk_t* prev = chunk->prev; prev->next = chunk->next; chunk->next->prev = prev; } void* map_chunk(heap_chunk_t* chunk) { void* user_addr = get_user_addr(chunk); if (chunk->mapped) return user_addr; size_t pagedSize = paged_size(chunk->size); void* res = mmap(chunk->addr, pagedSize, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED, -1, 0); if (res != chunk->addr) { log_error("FAILED TO ALLOCATE PAGE AT %p", chunk->addr); abort(); } heap_chunk_t** chunk_ptr = (heap_chunk_t**)(user_addr - sizeof(heap_chunk_t*)); *chunk_ptr = chunk; chunk->mapped = true; return user_addr; } void unmap_chunk(heap_chunk_t *chunk) { if (!chunk->mapped) return; size_t pagedSize = paged_size(chunk->size); int res = munmap(chunk->addr, pagedSize); if (res != 0) { log_error("FAILED TO UNMAP PAGE AT %p", chunk->addr); abort(); } chunk->mapped = false; } void* checked_heap_alloc(size_t size) { // log_warn("heap_alloc(0x%x)", size); heap_chunk_t* chunk = calloc(1, sizeof(heap_chunk_t)); chunk->size = size; size_t pagedSize = paged_size(chunk->size); pthread_mutex_lock(&heap_mutex); chunk->addr = curr_addr; insert_chunk(chunk); // Should have guard page! curr_addr += pagedSize + PAGE_SIZE; void* user_addr = map_chunk(chunk); pthread_mutex_unlock(&heap_mutex); return user_addr; } // not actually necessary for securerom. void* checked_heap_memalign(size_t size, size_t constraint) { void* addr = checked_heap_alloc(size); // log_debug("heap_memalign(0x%x, 0x%x) = %p", size, constraint, addr); return addr; } void checked_heap_free(void *ptr) { // bruh why if (ptr == NULL) return; void* user_addr = ptr; heap_chunk_t** chunk_ptr = (heap_chunk_t**)(user_addr - sizeof(heap_chunk_t*)); heap_chunk_t* chunk = *chunk_ptr; // log_warn("heap_free(%p)", chunk->addr); pthread_mutex_lock(&heap_mutex); unmap_chunk(chunk); pthread_mutex_unlock(&heap_mutex); } void init_heap() { initialize_chunk(&start); } void snapshot_heap() { pthread_mutex_lock(&heap_mutex); for (heap_chunk_t* curr = start.next; curr != &start; curr = curr->next) { if (curr->snapshot == NULL && curr->mapped) { size_t pagedSize = paged_size(curr->size); void* snapshot = mmap(0, pagedSize, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); curr->snapshot = snapshot; memcpy(curr->snapshot, curr->addr, pagedSize); } } pthread_mutex_unlock(&heap_mutex); } void restore_snapshot() { // we need a fake here, so that we can safely delete chunks while traversing! heap_chunk_t fake; pthread_mutex_lock(&heap_mutex); for (heap_chunk_t* curr = start.next; curr != &start; curr = curr->next) { // we had the page before if (curr->snapshot != NULL) { // ensure it is mapped map_chunk(curr); memcpy(curr->addr, curr->snapshot, paged_size(curr->size)); } else { // We did not have it before, remove chunk from list and free it. unmap_chunk(curr); remove_chunk(curr); heap_chunk_t* to_free = curr; curr = &fake; curr->next = to_free->next; curr->prev = to_free->prev; free(to_free); } } pthread_mutex_unlock(&heap_mutex); }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <limits.h> #include <errno.h> /* Define Section */ #define PATH_SEPERATOR "/" #define DIRECTORY_ENV_NAME "HW1DIR" #define FILE_ENV_NAME "HW1TF" #define PRINT_REPLACED_FRMT "%s" #define OLD_STRING_ARG_INDEX 1 #define NEW_STRING_ARG_INDEX 2 /* Methods Section */ char* getEnvironmentVariable(char* strName) { /* Variable Section */ char* strVariable; /* Code Section */ /* Getting environment variable */ strVariable = getenv(strName); /* If no variable exit failure */ if (NULL == strVariable) { /* Exit Failure */ exit(EXIT_FAILURE); } /* Return environment variable */ return strVariable; } char* buildFilePath(char* strDirectory, char* strFileName) { /* Variable Definition */ char* strFilePath; /* Code Section */ /* Allocating the file path */ strFilePath = (char *)malloc( strlen(strDirectory) + strlen(PATH_SEPERATOR) + strlen(strFileName) + 1); /* Validating allocation */ if (NULL == strFilePath) { /* Exit Failure */ exit(EXIT_FAILURE); } /* Building the file path */ strcpy(strFilePath, strDirectory); strcat(strFilePath, PATH_SEPERATOR); strcat(strFilePath, strFileName); /* Returning file path */ return strFilePath; } /* Read file and return it's contetnt as string */ char* readFile(char* strFilePath) { /* Variable Definition */ struct stat fsFileStat; ssize_t stBytesRead; ssize_t stTotalBytesRead; char* strFileContent; int fdFileDescriptor; long lFileSize; long lContentSize; /* Code Section */ /* Opening file */ fdFileDescriptor = open(strFilePath, O_RDONLY); /* Validating file openning succedded */ if (0 > fdFileDescriptor) { /* Free the memory of file path allocation */ free(strFilePath); /* Exit Failure */ exit(EXIT_FAILURE); } /* Get file status */ if (0 > stat(strFilePath, &fsFileStat)) { /* Free the memory of file path allocation */ free(strFilePath); /* Close file */ close(fdFileDescriptor); /* Exit Filure */ exit(EXIT_FAILURE); } /* Fetching file size */ lFileSize = fsFileStat.st_size; lContentSize = lFileSize + 1L; /* Allocating memory for file */ strFileContent = (char *)malloc(lContentSize); /* Validating allocation */ if (NULL == strFileContent) { /* Free the memory of file path allocation */ free(strFilePath); /* Close file */ close(fdFileDescriptor); /* Exit failure */ exit(EXIT_FAILURE); } /* Read file */ stBytesRead = 0; stTotalBytesRead = 0; /* While there are bytes to read */ while (stTotalBytesRead < lFileSize) { stBytesRead = read(fdFileDescriptor, strFileContent + stTotalBytesRead, lFileSize); stTotalBytesRead += stBytesRead; /* Checking bytes has been read */ if ((0 > stBytesRead) || (lFileSize < stTotalBytesRead)) { /* Free the memory of file path allocation */ free(strFilePath); /* Free the memory of file content */ free(strFileContent); /* Exit failure */ exit(EXIT_FAILURE); } } /* Setting zero-terminator to set as string */ strFileContent[lContentSize-1]='\0'; /* Returning file size */ return strFileContent; } /* Counting number of needles in haystack */ int countOccurences(char* strHaystack, const char* strNeedle) { /* Variable Definition */ int nOccurences; int nNeedleLength; char* pCurrent; char* pFirstOccurence; /* Code Section */ nNeedleLength = strlen(strNeedle); /* Iterating on the haystack, and counting occurences */ pCurrent = strHaystack; for (nOccurences = 0; (pFirstOccurence = strstr(pCurrent, strNeedle)); ++nOccurences) { pCurrent = pFirstOccurence + nNeedleLength; } /* Return number of occurences */ return nOccurences; } /* Replace all occurences of old with new in original, and return replaced */ char* replaceString(char* strOriginal, char* strOld, char* strNew) { /* Variable Definition */ char* strReplaced; char* pCurrentReplaced; char* pCurrentOriginal; char* pNextOld; int nOldLength; int nNewLength; int nOccurences; int nReplacedLength; int nRegularToCopy; int nCopyIterations; /* Code Section */ /* Getting length of old & new */ nOldLength = strlen(strOld); nNewLength = strlen(strNew); /* Iterating over the text and */ nOccurences = countOccurences(strOriginal, strOld); /* Calculating replaced length, based on diffrence between replacments */ nReplacedLength = strlen(strOriginal) + (nOccurences * (nNewLength - nOldLength)) + 1; /* Allocating memory for the replaced string */ strReplaced = (char*)malloc(nReplacedLength); /* If allocation error for replaced */ if (NULL == strReplaced) { /* Free original */ free(strOriginal); /* Exit failure */ exit(EXIT_FAILURE); } /* Copying original and replacing old by new */ pCurrentReplaced = strReplaced; pCurrentOriginal = strOriginal; for(nCopyIterations = nOccurences; 0 < nCopyIterations; --nCopyIterations) { /* Finding the next occurence of string to replace */ pNextOld = strstr(pCurrentOriginal, strOld); /* Copying all chars till that next occurence and adjusting pointers */ nRegularToCopy = pNextOld - pCurrentOriginal; pCurrentReplaced = strncpy(pCurrentReplaced, pCurrentOriginal, nRegularToCopy); pCurrentReplaced += nRegularToCopy; pCurrentOriginal += nRegularToCopy; /* Copying new string chars and adjusting pointers */ pCurrentReplaced = strcpy(pCurrentReplaced, strNew); pCurrentReplaced += nNewLength; pCurrentOriginal += nOldLength; } /* Copying the rest of the original string */ strcpy(pCurrentReplaced, pCurrentOriginal); /* Setting zero-terminator to set as string */ strReplaced[nReplacedLength-1] = '\0'; /* Returning replaced string */ return strReplaced; } /* Main Function */ /* Print content of file, where every occurence of old is replaced by new */ int main(int argc, char *argv[]) { /* Variable Section */ char* strOld; char* strNew; char* strFilePath; char* strDirectory=NULL; char* strFileName=NULL; char* strFileOriginalContent; char* strFileReplacedContent; /* Code Section*/ // Setting old and new strings to replace strOld = argv[OLD_STRING_ARG_INDEX]; strNew = argv[NEW_STRING_ARG_INDEX]; /* Getting directory environment variable, if non-exsistant exit error*/ strDirectory = getEnvironmentVariable(DIRECTORY_ENV_NAME); /* Getting file environment variable, if non-exsistant exit error*/ strFileName = getEnvironmentVariable(FILE_ENV_NAME); /* Building file path */ strFilePath = buildFilePath(strDirectory, strFileName); /* Read file content */ strFileOriginalContent = readFile(strFilePath); /* Free the memory of file path allocation */ free(strFilePath); /* Replace in content old with new */ strFileReplacedContent = replaceString(strFileOriginalContent, strOld, strNew); /* Free original content */ free(strFileOriginalContent); /* Printing replaced content */ printf(PRINT_REPLACED_FRMT, strFileReplacedContent); /* Free replaced content */ free(strFileReplacedContent); /* Return Success */ return EXIT_SUCCESS; }
C
#include<stdio.h> void swap(int*,int*); void main() { int a=10,b=20; printf("before swapping:%d\t%d\n",a,b); swap(&a,&b); } void swap(int* x,int* y) { int temp=*x; *x=*y; *y=temp; printf("after swapping:\t%d\t%d",*x,*y); }
C
#include<stdio.h> #include<stdlib.h> #include<string.h> #define NEW(p,n){p=malloc((n)*sizeof(p[0]));if(p==NULL){printf("not enough memory\n");exit(1);};} //pの型の変数n個の要素分のメモリを確保し、そのアドレスをpに代入するマクロ #define MAX(a, b) ((a) > (b) ? (a) : (b)) #define MIN(a, b) ((a) < (b) ? (a) : (b)) #define SWAP(type, x, y) do { type tmp = x; x = y; y = tmp; } while (0) #define MOD 1000000007 //最大公約数 long long gcd(long long a, long long b){ //a>bになるように入れ替え if(a<b){ long tmp=a; a=b; b=tmp; } //ユークリッドの互除法 if(a%b==0) return b; return gcd(b,a%b); } //最小公倍数 long long lcm(long long a,long long b){ return a*(b/gcd(a,b)); } int main(void){ int N; scanf("%d",&N); //A[0]~A[N-1]に格納する long long* T; NEW(T,N); for(int i=0;i<N;i++){ scanf("%lld",&T[i]); } long long ans=1; for(int i=0;i<N;i++){ ans=lcm(ans,T[i]); } printf("%lld\n",ans); return 0; }
C
/* ======================================== * * Copyright YOUR COMPANY, THE YEAR * All Rights Reserved * UNPUBLISHED, LICENSED SOFTWARE. * * CONFIDENTIAL AND PROPRIETARY INFORMATION * WHICH IS THE PROPERTY OF your company. * * ======================================== */ #include "SerialCom.h" uint8 errorStatus = 0u; /******************************************************************************* * Function Name: RxIsr ******************************************************************************** * * Summary: * Interrupt Service Routine for RX portion of the UART * * Parameters: * None. * * Return: * None. * *******************************************************************************/ CY_ISR(RxIsr) { uint8 rxStatus; uint8 rxData; do { /* Read receiver status register */ rxStatus = UART_RXSTATUS_REG; if((rxStatus & (UART_RX_STS_BREAK | UART_RX_STS_PAR_ERROR | UART_RX_STS_STOP_ERROR | UART_RX_STS_OVERRUN)) != 0u) { /* ERROR handling. */ errorStatus |= rxStatus & ( UART_RX_STS_BREAK | UART_RX_STS_PAR_ERROR | UART_RX_STS_STOP_ERROR | UART_RX_STS_OVERRUN); } if((rxStatus & UART_RX_STS_FIFO_NOTEMPTY) != 0u) { /* Read data from the RX data register */ rxData = UART_RXDATA_REG; if(errorStatus == 0u) { /* Send data backward */ UART_TXDATA_REG = rxData; } } }while((rxStatus & UART_RX_STS_FIFO_NOTEMPTY) != 0u); } /** * @function SerialCom_Init(void) * @param None * @return None * @brief Initializes hardware components necessary Serial Communication * through UART and KitProg * @author Barron Wong 01/26/19 */ void SerialCom_Init(){ UART_Start(); isr_rx_StartEx(RxIsr); } /** * @function _write(void) * @param None * @return None * @brief Overriding _write function for printf redirection to UART * @author Barron Wong 01/26/19 */ /* For GCC compiler revise _write() function for printf functionality */ int _write(int file, char *ptr, int len) { int i; file = file; for (i = 0; i < len; i++) { UART_PutChar(*ptr++); } return (len); } /* [] END OF FILE */
C
/*H****************************************************** *<<<<<<<<<<<<<<<<<<< C Language Tasks >>>>>>>>>>>>>>>>>>> * TASK NO. : 24 * AUTHOR : AlHasan Sameh * DATE : May 3rd 2019 * COMPILER : gcc * DESCRIPTION : * Program to find the greatest common divisor of 2 numbers *H*/ #include <stdio.h> #include <stdlib.h> #include <math.h> /* Function Prototypes */ int findGCD( int num1 , int num2 ); int main() { int num1, num2; printf("Enter Number 1 (Non-Zero) : "); scanf("%d" , &num1 ); printf("\n"); printf("Enter Number 2 (Non-Zero) : "); scanf("%d" , &num2 ); printf("\n"); printf("GCD Of %d And %d = %d\n" , num1 , num2 , findGCD( num1 , num2 ) ); return 0; } int findGCD( int num1 , int num2 ) { int greater_num; int smaller_num; int remainder; /* Drop any -ve signs */ num1 = abs( num1 ); num2 = abs( num2 ); /* Determine greatest and smallest numbers */ if(num1 > num2) { greater_num = num1; smaller_num = num2; } else if(num1 < num2) { greater_num = num2; smaller_num = num1; } else //Numbers are equal return num1; //Return the same number immediately /* Eucledian Algorithm */ do { remainder = greater_num % smaller_num; greater_num = smaller_num; smaller_num = remainder; }while(remainder != 0); return greater_num; }