language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
/* * This file is part of the AprilTag library. * * AprilTag is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * AprilTag is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with Libav; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301 USA */ #ifndef _MATD_H #define _MATD_H #define MATD_EPS 1e-8 typedef struct { int nrows, ncols; // data in row-major order (index = rows*ncols + col) double *data; } matd_t; #define MAT_EL(m, row, col) (m)->data[((row) * (m)->ncols + (col))] typedef struct { // was the input matrix singular? When a near-zero pivot is found, // it is replaced with a value of MATD_EPS so that an approximate inverse // can be found. This flag is set to indicate that this has happened. int singular; int *piv; // permutation indices int pivsign; matd_t *lu; // combined L and U matrices, permuted. } matd_lu_t; ////////////////////////////////// // Creating and Destroying matd_t *matd_create(int rows, int cols); matd_t *matd_create_data(int rows, int cols, const double *data); // NB: Scalars are different than 1x1 matrices (implementation note: // they are encoded as 0x0 matrices). For example: for matrices A*B, A // and B must both have specific dimensions. However, if A is a // scalar, there are no restrictions on the size of B. matd_t *matd_create_scalar(double v); matd_t *matd_copy(const matd_t *m); matd_t *matd_identity(int dim); void matd_destroy(matd_t *m); ////////////////////////////////// // Basic Operations // fmt is printf specifier for each individual element. Each row will // be printed on a separate newline. void matd_print(const matd_t *m, const char *fmt); matd_t *matd_add(const matd_t *a, const matd_t *b); matd_t *matd_subtract(const matd_t *a, const matd_t *b); matd_t *matd_scale(const matd_t *a, double s); matd_t *matd_multiply(const matd_t *a, const matd_t *b); matd_t *matd_transpose(const matd_t *a); // matd_inverse attempts to compute an inverse. Fast (and less // numerically stable) methods are used for 2x2, 3x3, and 4x4 // matrices. Nearly singular matrices are "patched up" by replacing // near-zero pivots or determinants with MATD_EPS. matd_t *matd_inverse(const matd_t *a); matd_t *matd_solve(matd_t *A, matd_t *b); double matd_det(const matd_t *a); matd_t *matd_op(const char *expr, ...); //////////////////////////////// // LU Decomposition // The matd_lu_t operation returned "owns" the enclosed LU matrix. It // is not expected that the returned object is itself useful to users. matd_lu_t *matd_lu(const matd_t *a); void matd_lu_destroy(matd_lu_t *mlu); double matd_lu_det(const matd_lu_t *lu); matd_t *matd_lu_l(const matd_lu_t *lu); matd_t *matd_lu_u(const matd_lu_t *lu); matd_t *matd_lu_solve(const matd_lu_t *mlu, const matd_t *b); #endif
C
/* Да се напише програма на С, която получава като параметър команда (без параметри) и при успешното ѝ изпълнение, извежда на стандартния изход името на командата. */ #include <err.h> #include <stdlib.h> #include <stdio.h> #include <sys/wait.h> #include <sys/types.h> #include <unistd.h> int main (int argc, char* argv[]) { if (argc != 2) { errx(1, "There must be 1 argument!"); } int status; int pid = fork(); if (pid > 0) { wait(&status); if ( WIFEXITED(status) ) { if ( WEXITSTATUS(status) == 0) { printf("%s\n", argv[1]); } } } else { if (execlp(argv[1], argv[1], (char *)NULL) == -1) { err(2, "Exec failed!"); } } exit(0); }
C
/* This is a function that calls * the code of Xiaoyu Hu, et al * to generate LDPC codes using * Progressive Edge Growth * Author: Hatef Monajemi ([email protected]) * Date : 11 Feb 2013 * PS: We are interested ONLY in regular graphs * therefore a degree value 'd' would suffice and * we do not require degFileName */ #include "GenerateLDPC.h" #include <assert.h> using namespace std; /* * M = number of rows * N = number of columns */ bool GenerateLDPC(int M, int N, char* codeName, int d,int sglConcent){ // Check the size of graph assert( M < N && "M must be smaller than N"); //cout << "M(#rows):" << M << endl; //cout << "N(#cols):" << N << endl; int *degSeq ; degSeq = new int[N]; // set all the enteries of degSeq to d for(int i=0;i<N; ++i){ degSeq[i] = d; } // default to non-strictly concentrated parity-check distribution // This is now given as a user input //int sglConcent=1; int targetGirth=100000; // default to greedy PEG version BigGirth *bigGirth = new BigGirth(M, N, degSeq, codeName, sglConcent, targetGirth); (*bigGirth).writeToFile_Hcompressed(); delete [] degSeq; return true; }
C
/** * intPDBOneShotTest.c * Programmable Delay Block (PDB) one shot interrupt test program * * ARM-based K70F120M microcontroller board * for educational purposes only * CSCI E-92 Spring 2014, Professor James L. Frankel, Harvard Extension School * * Written by James L. Frankel ([email protected]) */ /* * Important note: * * The file Project_Settings -> Startup_Code -> kinetis_sysinit.c needs to be modified so * that a pointer to the PDB0Isr function is in the vector table at vector 88 (0x0000_0160) * for Programmable Data Block (PDB). * * The following declaration needs to inserted earlier in the file: * extern void PDB0Isr(void); * * If using the GCC Toolchain, the vector table is named "InterruptVector", and the line: * Default_Handler, (comment delimiters removed) Vector 88: PDB * needs to be changed to: * PDB0Isr, (comment delimiters removed) Vector 88: PDB * * If using the Freescale Toolchain, the vector table is named "__vect_table", and the line: * (tIsrFunc)UNASSIGNED_ISR, (comment delimiters removed) 88 (0x00000160) (prior: -) * needs to be changed to: * (tIsrFunc)PDB0Isr, (comment delimiters removed) 88 (0x00000160) (prior: -) */ #include <stdio.h> #include "SVCPDBUserTimer.h" #include "PDB0.h" /** * this routine contains all actions to be performed when a PDBTimer 0 * interrupt occurs. * * alternate turning the orange LED on and off with each interrupt. */ void PDB0Action(void) { user_fcn.functionp(); } void SVCsetPDBTimerImpl(int time,void* myFcn,int continousOrOneShot) { /* convert the time to count and set the count for the timer and start the timer*/ uint16_t count = time*11718/1000; /* assuming time provided in milli seconds */ /* * fpheripheral = 60 MHz * * fprescalar = fpheripheral / Prescalor = 60 MHz / 128 = 468750 Hz * * fpdb = fprescalar / Mult = 468750 / 40 = 11718.75 Hz * * So PDB0 interrupt occurs at every 1/11718.75 seconds * * So providing count of 11718 should give interrupt at every one second. */ if(time==0) { /* Stop the timer */ PDB0Stop(); /* Set the User supplied function to NULL value.*/ user_fcn.functionp = myFcn; } else { /* set interval to 16384 1/16384 second periods or 1 second notice that continousOrOneShot is the mode specified by user*/ PDB0Init(count, continousOrOneShot); /* Set the User supplied function to call*/ user_fcn.functionp = myFcn; /* Start the timer */ PDB0Start(); } }
C
#include <cc_stats_log.h> #include <cc_debug.h> #include <cc_log.h> #include <cc_metric.h> #define STATS_LOG_MODULE_NAME "util::stats_log" #define STATS_LOG_FMT "%s: %s, " #define PRINT_BUF_LEN 64 static struct logger *slog = NULL; static bool stats_log_init = false; static char buf[PRINT_BUF_LEN]; void stats_log_setup(stats_log_options_st *options) { size_t log_nbuf = STATS_LOG_NBUF; char *filename = STATS_LOG_FILE; log_info("set up the %s module", STATS_LOG_MODULE_NAME); if (stats_log_init) { log_warn("%s has already been setup, overwrite", STATS_LOG_MODULE_NAME); if (slog != NULL) { log_destroy(&slog); } } if (options != NULL) { filename = option_str(&options->stats_log_file); log_nbuf = option_uint(&options->stats_log_nbuf); } if (filename != NULL) { slog = log_create(filename, log_nbuf); if (slog == NULL) { log_warn("Could not create logger"); } } stats_log_init = true; } void stats_log_teardown(void) { log_info("tear down the %s module", STATS_LOG_MODULE_NAME); if (!stats_log_init) { log_warn("%s has never been setup", STATS_LOG_MODULE_NAME); } if (slog != NULL) { log_destroy(&slog); } stats_log_init = false; } void stats_log(struct metric metrics[], unsigned int nmetric) { unsigned int i; if (slog == NULL) { return; } for (i = 0; i < nmetric; i++, metrics++) { int len = 0; len = metric_print(buf, PRINT_BUF_LEN, STATS_LOG_FMT, metrics); log_write(slog, buf, len); } log_write(slog, CRLF, CRLF_LEN); } void stats_log_flush(void) { if (slog == NULL) { return; } log_flush(slog); }
C
/* 1048. ּ(20) Ҫʵһּܷ ȹ̶һAһB ÿ1λAĶӦλϵֽ㣺 λӦλӺ13ȡࡪ J10Q11K12żλ BּȥA֣Ϊټ10 λΪ1λ ʽ һθABΪ100λ Կոָ ʽ һܺĽ 1234567 368782971 3695Q8118 */ #include<stdio.h> #include<string.h> int main(){ char s1[103],s2[103],s3[103]={'\0'}; int len1=0,len2=0,len3=0,i=0; scanf("%s",s1); scanf("%s",s2); len1=strlen(s1); len2=strlen(s2); if(len1<len2){ for(i=0;i<len2-len1;i++){ printf("%c",s2[i]); } } for(i=len1-1;i>=0;i--){ s3[len3++]=s1[i]; } strcpy(s1,s3); len3=0; for(i=len2-1;i>=0;i--){ s3[len3++]=s2[i]; } if(len1>len2){ for(i=len2;i<len1;i++){ s3[len3++]='0'; } } strcpy(s2,s3); len3=0; len3=len1-1; for(i=0;i<len1;i++){ if(i%2!=0){ int t=s2[i]-s1[i]; if(t<0){ t+=10; } s3[len3--]=t+'0'; } else{ int t=s2[i]+s1[i]-2*'0'; t=t%13; switch(t){ case 10: s3[len3--]='J'; break; case 11: s3[len3--]='Q'; break; case 12: s3[len3--]='K'; break; default: s3[len3--]=t+'0'; break; } } } s3[len1]='\0'; printf("%s",s3); return 0; }
C
#include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <errno.h> #include <string.h> #include <netinet/in.h> #include <sys/socket.h> #include <sys/wait.h> #include <arpa/inet.h> #include <openssl/ssl.h> #include <fcntl.h> #include <sys/epoll.h> #include <sys/time.h> #include <sys/resource.h> #define MAXBUF 1024 #define MAXEPOLLSIZE 10000 int setnonblocking(int sockfd) { if (fcntl(sockfd, F_SETFL, fcntl(sockfd, F_GETFD, 0) | O_NONBLOCK) == -1) { return -1; } return 0; } int handle_message(int new_fd) { char buf[MAXBUF + 1]; int len; bzero(buf, MAXBUF + 1); len = recv(new_fd, buf, MAXBUF, 0); if (len > 0) { printf("%d接收消息成功:%s,共%d个字节\n",new_fd, buf, len); } else { if (len < 0) { printf("接受消息失败!错误代码:%d,错误信息:%s\n",errno, strerror(errno)); close(new_fd); return -1; } } return len; } int main(int argc, char* argv[]) { int listener, new_fd, kdpfd, nfds, n, ret, curfds; socklen_t len; struct sockaddr_in my_addr, their_addr; unsigned int myport, lisnum; struct epoll_event ev; struct epoll_event events[MAXEPOLLSIZE]; struct rlimit rt; myport = 5000; lisnum = 2; rt.rlim_max = rt.rlim_cur = MAXEPOLLSIZE; if (setrlimit(RLIMIT_NOFILE, &rt) == -1) { perror("setrlimt"); exit(1); } else { printf("设置资源参数成功\n"); } if ((listener = socket(AF_INET, SOCK_STREAM, 0)) == -1) { perror("socket"); exit(1); } setnonblocking(listener); bzero(&my_addr, sizeof(my_addr)); my_addr.sin_family = AF_INET; my_addr.sin_port = htons(myport); my_addr.sin_addr.s_addr = INADDR_ANY; if (bind(listener, (struct sockaddr*)&my_addr, sizeof(struct sockaddr)) == -1) { perror("bind"); exit(1); } else { printf("IP地址和端口绑定成功\n"); } if (listen(listener, lisnum) == -1) { perror("listen"); exit(1); } else { printf("开启服务成功\n"); } kdpfd = epoll_create(MAXEPOLLSIZE); len = sizeof(struct sockaddr_in); ev.events = EPOLLIN | EPOLLET; ev.data.fd = listener; if (epoll_ctl(kdpfd, EPOLL_CTL_ADD, listener, &ev) < 0) { fprintf(stderr, "epoll set insertion error:fd = %d\n", listener); return -1; } else { printf("监听socket加入epoll成功\n"); } curfds = 1; while(1) { nfds = epoll_wait(kdpfd, events, curfds, -1); if (nfds == -1) { perror("epoll_wait"); break; } for (n = 0; n < nfds; n++) { if (events[n].data.fd == listener) { new_fd = accept(listener, (struct sockaddr*)&their_addr, &len); if (new_fd < 0) { perror("accept"); continue; } else { printf("有连接来自:%s ;%d, 分配socket为%d\n", inet_ntoa(their_addr.sin_addr), ntohs(their_addr.sin_port), new_fd); } setnonblocking(new_fd); ev.events = EPOLLIN | EPOLLET; ev.data.fd = new_fd; if (epoll_ctl(kdpfd, EPOLL_CTL_ADD, new_fd, &ev) < 0) { fprintf(stderr, "把socket ‘%d’加入epoll失败!%s \n", new_fd, strerror(errno)); return -1; } curfds++; } else { ret = handle_message(events[n].data.fd); if (ret < 1 && errno != 11) { epoll_ctl(kdpfd, EPOLL_CTL_DEL, events[n].data.fd, &ev); curfds--; } } } } close(listener); exit(0); }
C
/* * Nome: Rodrigo Villardi Cortezi * Matricula: 1511425 */ typedef struct page Page; Page *create_page(); void allocate_page(Page *page, unsigned int page_frame); void deallocate_page(Page *page); void set_modified(Page *page, int modified); void set_referenced(Page *page, int referenced); void set_last_access(Page *page, unsigned int ts); unsigned int get_page_frame(Page *page); int get_present(Page *page); int get_modified(Page *page); int get_referenced(Page *page); unsigned int get_last_access(Page *page);
C
//#include <stdio.h> // //int main(void) { // int i;//ݺ // char string[20] = "Dreams come true", string2[20], * ptr1, * ptr2;//迭 ʱȭ Ÿ 迭 , ׸ // ptr1 = string;//ʱȭ 迭 Ϳ Ҵ // printf("string ּ = %u \t ptr1=%u\n", string, ptr1);//Ҵ Ϳ 迭 ּҰ . // printf("\n string = %s \n ptr1=%s", string, ptr1);//Ϳ 迭 Ҵϸ 迭ó ִ. // printf("\n\n %s", ptr1 + 7);// 7° ض-->ſ ¹ // ptr2 = &string[7];//7° ּҰ // printf("\n %s \n\n", ptr2);// ּҰ // // for (i = 16; i >= 0; i--) { // putchar(*(ptr1+i));//۴ ȣȯ ſ ߿ Ѵ. Ųٷ // } // for (i = 0; i < 20; i++) { // string2[i] = *(ptr1 + i);//۴ Է ſ ߿ , ּҿ شϴ Ͱ ҷ 迭2 ҴѴ. // } // printf("\n\n string =%s", string); // printf("\n string2 =%s", string2); // // *ptr1 = 'P';// ּҹȣ Ҵ // *(ptr1 + 1) = 'e'; // *(ptr1 + 2) = 'a'; // *(ptr1 + 3) = 'c'; // *(ptr1 + 4) = 'e'; // printf("\n\n string = %s\n", string); // return 0; //} // ////۴ ׼ ܰ踦 Ÿ ڷ ü ƴϴ. ü Ÿ̴.
C
/*Faça um programa onde o valor da variável é alterado através do ponteiro e valor alterado é impresso na tela com printf.*/ #include <stdio.h> void main() { int variavel = 1; ///Nesse local tem que declarar o ponteiro e passar o endereço da variavel para o ponteiro] int * ponteiro = &variavel; //Nesse local tem que alterar o valor da variavel através do ponteiro *ponteiro = 5; printf("Valor alterado= %d (capturado pela variavel)\n", variavel); //1o forma printf("Valor alterado= %d (capturado pelo ponteiro)\n", *ponteiro); //2a forma }
C
/* * Spring 2019, COMP 211: Lab 2 * Examples of core C programming instructions * */ #include <stdio.h> int main(void) { /* * Arithmetic operations */ int u = 5 + 2; // 7 int v = 10 - 3; // = 7 int w = 5 / 2; // = 2 double x = 5 / 2; // = 1.5 int y = 5 * 2; // = 10 /* * Modulus operator in C: % */ int z = 5 % 2; // = 1 printf("------------------------------------------\n"); printf("u=%d, v=%d, w=%d, x=%f, y=%d, z=%d\n", u, v, w, x, y, z); /* * Conditional */ printf("------------------------------------------\n"); printf("Flow control statements\n"); if (u == v && u == y) { printf("%d == %d and %u == %d\n", u, v, u, y); } else if (u == v || u == y) { printf("%d == %d or %u == %d\n", u, v, u, y); } else if (u != v) { printf("%d != %d\n", u, v); } else { printf("nothing else\n"); } /* * Loops */ printf("------------------------------------------\n"); printf("For loop\n"); // i++ <-> i = i+1 // i-- <-> i = i-1 // for (int i = 0; i < 10; i++) { printf("i = %d\n", i); } printf("------------------------------------------\n"); printf("While loop\n"); int j = 10; while (j > 0) { j--; printf("j = %d\n", j); } printf("------------------------------------------\n"); printf("Do while loop\n"); j = 10; do { j--; printf("j = %d\n", j); } while (j > 0); /* * Bit shift */ unsigned int b = 10; printf("------------------------------------------\n"); printf("b = %u, b shifted left 2 bits = %u\n", b, b << 2); }
C
/*Nome: Victor Hugo Rodrigues da Silva; Matricula: 1512130063; exerccio: sem recurso fibonacci; vero:1; Turma: Quarta-feira / Noite;*/ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "code.h" /* run this program using the console pauser or add your own getch, system("pause") or input loop */ int main() { int num; printf("Digite um numero"); scanf("%d", &num); fibonacci(num); return 0; }
C
/* * * среда, 16 сентября 2015 г. 17:23:24 (EEST) * */ #ifndef _ARRAYS_H_ #define _ARRAYS_H_ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <stdint.h> #include "mem_pool.h" unsigned int hash32(char *key); /* * * arrays by key * */ typedef struct _array_key_node_t { struct _array_key_node_t *next; char *key; int type; void *val; int len; int flag; } *parray_key_node_t, array_key_node_t; typedef struct _array_key_t { struct _mem_pool_t *pool; struct _array_key_node_t **nodes; int size; int count; char *info; int flags; } *parray_key_t, array_key_t; array_key_t *array_key_init(size_t size); void *array_key_free(array_key_t *a); array_key_node_t *array_key_exist(array_key_t *a, char *key); void array_key_del(array_key_t *a, char *key); array_key_node_t * array_key_set(array_key_t *a, char *key, void *val, int type, int size); /* * * arrays by queue * */ typedef struct _array_queue_node_t { struct _array_queue_node_t *prev; struct _array_queue_node_t *next; int type; void *val; int len; int flag; } *parray_quiue_node_t, array_queue_node_t; typedef struct _array_queue_t { struct _mem_pool_t *pool; struct _array_queue_node_t *first; struct _array_queue_node_t *last; int count; char *info; int flags; } *parray_quiue_t, array_queue_t; array_queue_t *array_queue_init(void); void *array_queue_free(array_queue_t *a); array_queue_node_t * array_queue_push(array_queue_t *a, void *val, int type, int size); array_queue_node_t *array_queue_pop(array_queue_t *a); array_queue_node_t * array_queue_unshift(array_queue_t *a, void *val, int type, int size); array_queue_node_t *array_queue_shift(array_queue_t *a); /* упаковка double в int64 */ void *FLP(double a); /* распаковка int64 в double */ double FLU(void *a); #define EXP_ERROR_LEN 255 #define PREV_ASIZE 20 // массив предыдущих значений typedef struct _exp_data_t { array_key_t *current; array_key_t *prev[PREV_ASIZE]; /* run-time variables */ array_queue_t *code; array_key_t *local; array_queue_t *blocks_markers; array_queue_t *msg; int line; int err; char error[EXP_ERROR_LEN + 1]; } exp_data_t; #endif /* _ARRAYS_H_ */
C
#include <stdio.h> int main() { int x,y; printf ("Please enter integers x, y\n"); scanf("%d %d",&x,&y); if (x!=y) { printf ("\nx and y are different\n"); } else { printf ("\nx==y\n"); } return 0; }
C
#include <stdio.h> #include <stdlib.h> void read_n(int *); void PrintData(int, int *, int); void Split(int, int, int *, int); int input(const char *, int *); main() { /* Initializing variables */ int n, *A; /* I/O flow && VarCheck */ read_n(&n); /* Main part */ A = (int *) malloc(sizeof(int) * n); Split(n, n, A, 0); free(A); } void read_n(int *n) { /* I/O flow && VarCheck */ while (1) { input("Type natural number \"n\": ", n); if (*n > 0) { break; } else { printf("Error! \"n\" must be natural!\n\n"); continue; } } } void PrintData(int initial, int *Data, int N) { /* Initializing variables */ int i; /* Main part */ printf("%d =", initial); for (i = 0; i < N; i++ ) { printf(" %d %s", Data[i], (N - i == 1) ? "\n" : "+"); } } void Split(int initial, int R, int *A, int q) { /* Initializing variables */ int i, last = R; /* Main part */ if (!R) { PrintData(initial, A, q); } else { if (q > 0 && last > A[q-1]) { last = A[q-1]; } for (i = 1; i <= last; i ++ ) { A[q] = i; Split(initial, R - i, A, q + 1); } } } int input(const char *out, int *res) { /* This function allows you to assign some integer value to a variable. If you type something but integer, * the program asks you to type proper value. It's an endless loop, so you must type an integer */ /* Initializing variables */ int a, flag = -1, multiplier = 1, counter = 0, flag2 = 0; *res = 0; /* Main part */ while (1) { printf("%s", out); /* Prints user-specified string */ while (1) { a = getchar(); /* Gets one typed char at a time */ if (a == '-' && flag == -1 && !flag2) { /* Detects a negative sign */ multiplier = -1; flag2 = 1; continue; } else if (a == '+' && flag == -1 && !flag2) { /* Detects a positive sign */ multiplier = 1; flag2 = 1; continue; } else if (a >= '0' && a <= '9' && flag != 0) { /* Detects digits */ *res = (*res * 10) + (a - '0'); /* Making of the answer */ flag = 1; /* «1» if a digit was detected */ ++counter; /* Counts a number of successfully scanned digits */ } else if (a != '\n') { /* Detects «garbage» */ flag = 0; /* «0» if «garbage» was detected */ *res = 0; /* Answer is equals to zero now */ counter = 0; multiplier = 1; } else if (a == '\n') { /* Detects End-Of-Line char */ break; /* End-Of-Line («Enter button usually) is the only way to finish a number */ } } if (flag == 1) { /* Checks whether only digits were typed */ break; /* Congrats! Your number were successfully scanned */ } flag = -1; /* «-1» if a previous attempt to scan a number was a fail */ } *res *= multiplier; /* Applies negative sign, if necessary */ return counter; /* Returns a number of successfully scanned digits */ }
C
#include "mg_header.h" int client_num = 4; // 기본 값. int discussion_time = 10; // 기본 10초. int killnum = -1; // 죽는 자의 번호. struct mymsgbuf mesg; int msgid, len; key_t key; key_t sh_key; // 메세지 관련 변수들. struct sigaction act; // sigaction 구조체 포인터 변수. FILE *rfp, *wfp; // 파일 구조체 포인터 char * nameofjobs[5]={"host","mafia","citizen",}; // 직업 명 문자열을 가리키는 포인터 배열. int nopb_jobs[5] = {0,}; // 직업별 사람수. //0: host, 1: mafia, 2 : citizen ... int p_pids[MAX_PEOPLE] ; // people pids. char * p_nics[MAX_PEOPLE]={0,}; // peple nicknames int p_jobs[MAX_PEOPLE] ; // people jobs // 죽은 면 -1 로 저장하자. int b_p_jobs[MAX_PEOPLE]; // people jobs 의 backup 본. void print_start_message(); void receive_print_message(int mtype); void send_message(int mtype, char * message); void random_job_make(int client_num, int arr[MAX_PEOPLE]); void test_job_make(); void send_receive_first_message(); void write_user_data(); // 데이터를 실제로 쓰는 부분. void save_user_data_send_messages(); void save_final_data(); void print_kill_one_check_condition(); int check_end_condition(); // void print_kill~ 에서 쓰이는 함수. 종료 조건에 도달하면 1을 반환. 아니면 void become_night(); void become_day(); // 함수의 선언부. void print_start_message(){ printf("안녕하세요 마피아 게임입니다.\n"); printf("당신은 게임의 사회자로 선정되었습니다.\n"); printf("제작 자 : 강대훈, 이동석.\n"); printf("접속 할 사람수는 몇명입니까?\n"); printf("입력 : "); } void receive_print_message(int mtype){ len = msgrcv(msgid, &mesg, 800, mtype, 0); printf("Received Msg = %s \n", mesg.mtext); } void send_message(int mtype, char * message){ mesg.mtype = mtype; strcpy(mesg.mtext, message); if (msgsnd(msgid, (void *)&mesg, 800, IPC_NOWAIT) == -1) { perror("msgsnd"); exit(1); } } void random_job_make(int client_num, int arr[MAX_PEOPLE]){ for(int i=0;i<client_num;i++) { arr[i]=2; } int cnt = 0; int temp=0; srand(time(NULL)); if(client_num<=5) { int r = rand()%client_num; arr[r]=1; } else if(client_num>5) { int r = rand()%client_num; arr[r]=1; temp = r; cnt++; while(1) { r = rand()%client_num; if(cnt==2) break; if(temp == r) { continue; } arr[r]=1; temp = r; cnt++; } } } void test_job_make(){ for(int i=0;i<client_num;i++){ if(i==0) p_jobs[i] = Mafia; else p_jobs[i] = Citizen; } } void send_receive_first_message(){ key = ftok("mg", 1); // mg means "mafia game". // key를 만듭니다. if ((msgid = msgget(key, IPC_CREAT|0644)) < 0) { perror("msgget"); exit(1); } // 해당 키 값으로 message 식별자를 만듭니다. // 사람들 직업번호가 저장된 배열. nopb_jobs[Host] = 1; // 사회자는 항상 하나 if(client_num<=5){ nopb_jobs[Mafia] = 1; nopb_jobs[Citizen] = client_num -1; } if( client_num>=6){ nopb_jobs[Mafia] =2; nopb_jobs[Citizen] = client_num -2; } //인원수에 따라 마피아, 시민수를 조절하는 과정입니다. //test_job_make() random_job_make(client_num, p_jobs); // 클라이언트의 수에 따라 랜덤하게 마피아와 시민을 정하는 코드 입니다. for(int i=0;i<client_num;i++){ b_p_jobs[i] =p_jobs[i]; // 백업 해두기. } // b_p_jobs 에 p_jobs 에 있던 값을 저장합니다. // 그 이유는 특정 i 번호에 해당하는 프로세스가 죽으면, 해당 사람의 직업이 -1이 되기 때문입니다. for(int i=0;i<MAX_PEOPLE;i++){ p_nics[i] = malloc(sizeof(char) * 50); } // 닉네임을 저장할 공간을 할당하는 과정. int mafia_flag = 0 ; // 처음은 클라이언트. for(int i=0;i<client_num;i++){ receive_print_message(1); char * strptr = strtok(mesg.mtext, "-"); strcpy(p_nics[i],strptr); strptr = strtok(NULL, "-"); p_pids[i] = atoi(strptr); // 해당 메세지를 받아, 거기서 nicsname과 pid를 추출하는 과정. memset(mesg.mtext, 0, sizeof(mesg.mtext)); sprintf(mesg.mtext, "%d", i+3); send_message(2, mesg.mtext); // 참여자에게 관련 참여자가 사용할 mtype 번호를 메세지큐에 보냅니다. // 이때는 타입 2번 메세지를 사용하여 보내고 //참여자들은 3번부터 mtype을 부여받게 됩니다. memset(mesg.mtext, 0, sizeof(mesg.mtext)); sprintf(mesg.mtext, "%d", p_jobs[i]); send_message(i+3, mesg.mtext); // mtype i+3 번으로 직업번호를 보내주자. // 해당 프로세스의 mtype으로 직업번호를 보냅니다. if(p_jobs[i] == Mafia){ memset(mesg.mtext, 0, sizeof(mesg.mtext)); sprintf(mesg.mtext, "%d", nopb_jobs[Mafia]); send_message(i+3, mesg.mtext); // 보낸 프로세스의 직업이 마피아라면 // 마피아에게 보낼 첫번째 메세지 : 마피아 수. if(nopb_jobs[Mafia] >=2){ // 처음에 보내는 것은 당신이 mafia_client인가? mafia_server인가? // mafia_client면 0, mafia_server면 1. memset(mesg.mtext, 0, sizeof(mesg.mtext)); sprintf(mesg.mtext, "%d", mafia_flag); send_message(i+3, mesg.mtext); // 처음은 0보내고, 클라이언트. //두번쨰 녀석은 1. 서버 // 마피아에게 보낼 두번째 메세지 : 마피아 서버인가 클라이언트 인가?. //그다음 메세지. mafia_flag =1; char mafia_info[500] = {0,}; strcpy(mafia_info, "마피아 정보입니다.\n"); strcat(mafia_info, "처음에만 알려주니 잘 기억하세요.\n"); strcat(mafia_info, "번호\tnickname\n"); for(int j=0;j<client_num;j++){ if(p_jobs[j] == Mafia){ char numstr[10] = {0,}; sprintf(numstr, "%d", j); strcat(mafia_info, numstr); strcat(mafia_info,"\t"); strcat(mafia_info, p_nics[j]); strcat(mafia_info, "\n"); } } send_message(i+3, mafia_info); // 마피아에게 보낼 세번째 메세지 : 마피아 정보. } // 여기서 마피아가 두명 이상일 때 어떻게 처리할 지 고민해야 할 것이다. } } } void write_user_data(){ // 사용자들에게 공지할 자료 입니다. // process에 할당된 index 번호, nickname, pid , 살아있는 지 유무를 알수 있습니다. // 그런한 자료를 만드는 과정. printf("\n\nuser_data.txt 갱신을 시작합니다.\n"); if ((wfp = fopen("user_data.txt", "w")) == NULL) { perror("fopen: user_data.txt"); exit(1); } fprintf(wfp,"-------user_data_file------\n"); fprintf(wfp,"--num nic pid -----\n"); for(int i=0;i<client_num;i++){ if(p_jobs[i] == -1){ fprintf(wfp,"%d : %s %d DEAD\n", i, p_nics[i], p_pids[i]); } else { fprintf(wfp,"%d : %s %d ALIVE\n", i, p_nics[i], p_pids[i]); } } fclose(wfp); printf("user_data.txt 갱신되었습니다!\n"); } void save_user_data_send_messages(){ write_user_data(); // 사용자들에게 공지할 자료 입니다. // process에 할당된 index 번호, nickname, pid , 살아있는 지 유무를 알수 있습니다. // 그런한 자료를 만드는 과정. for(int i=0;i<client_num;i++){ if(p_jobs[i] == -1){ continue; } send_message(i+3, "User_data is sent by host"); } // 자료가 만들어졌다고 알려주는 과정. } void save_final_data(){ printf("save final data is called\n"); if ((wfp = fopen("user_data.txt", "w")) == NULL) { perror("fopen: user_data.txt"); exit(1); } fprintf(wfp,"-------user_data_file------\n"); fprintf(wfp,"--num nic pid job-----\n"); for(int i=0;i<client_num;i++) { if(p_jobs[i] == -1){ fprintf(wfp,"%d : %s %d %s DEAD\n", i, p_nics[i], p_pids[i], nameofjobs[b_p_jobs[i]]); } else { fprintf(wfp,"%d : %s %d %s ALIVE\n", i, p_nics[i], p_pids[i], nameofjobs[b_p_jobs[i]]); } } fclose(wfp); } int check_end_condition(){ if(nopb_jobs[Citizen]<=nopb_jobs[Mafia]){ save_final_data(); // 게임이 끝나서 직업 까지 알수 있는 정보를 게시. // 마피아 승리 조건. for(int i=0;i<client_num;i++){ if(p_jobs[i] == -1){ continue; } kill((pid_t)p_pids[i], SIGUSR1); } // 모든 client에게 SIGUSR1을 보냄. // 마피아의 승리를 의미. return 1; } else if(nopb_jobs[Mafia] <=0){ save_final_data(); // 시민승리 조건. for(int i=0;i<client_num;i++){ if(p_jobs[i] == -1){ continue; } kill((pid_t)p_pids[i], SIGUSR2); // 모든 client에게 SIGUSR2을 보냄. // 시민의 승리를 의미. } // 모든 client에게 signal을 보냄. return 1; } else return 0; } void print_kill_one_check_condition(){ printf("죽은 사람은 %d 입니다.\n", killnum); nopb_jobs[p_jobs[killnum]]--; p_jobs[killnum] = -1; // 해당 번호를 죽은 것으로 표시. kill((pid_t)p_pids[killnum], SIGQUIT); // 해당 pid로 시그널 보내기. //check_end_condition // 끝나는 조건에 도달했는지 확인. if(check_end_condition() == 1){ // 자신을 종료.. exit(1); } } void become_night(){ //2.1 모두에게 밤이 되었음을 알림. printf("밤이 되었습니다.\n모두 엎드려주세요.\n마피아는 고개를 들어 서로를 확인하시고\n토의시간을 거쳐 죽일 사람을 선택하세요.\n시민은 잠시 기다려주세요.\n사회자는 마피아의 선택을 기다립니다.\n"); for(int i=0;i<client_num;i++){ if(p_jobs[i] == -1){ continue; // 무시.. 죽었으니까. } send_message(i+3, "밤이 되었습니다.\n모두 엎드려주세요.\n마피아는 고개를 들어 서로를 확인하시고\n토의시간을 거쳐 죽일 사람을 선택하세요.\n시민은 잠시 기다려주세요.\n"); } //2.2 마피아가 신호를 보내주기를 기다림. for(int i=0;i<nopb_jobs[Mafia];i++){ receive_print_message(1); } //2.3 해당 넘버를 죽은 것으로 표시하고 종료 메세지를 보냄. killnum = atoi(mesg.mtext); // 여기서 print_kill_one_check_condition(); // 1명을 죽이고 종료 조건을 체크함. for(int i=0;i<client_num;i++){ if(p_jobs[i] == -1){ continue; // 무시.. 죽었으니까. } if(p_jobs[i] == Mafia){ memset(mesg.mtext, 0, sizeof(mesg.mtext)); sprintf(mesg.mtext, "%d", nopb_jobs[Mafia]); send_message(i+3, mesg.mtext); } // 보내는 메세지 받는 사람이 마피아면 현재 마피아 수를 추가적으로 보내준다. } write_user_data(); // 낮이 되기 전에 최신 정보를 저장함. } int vote_result(int whowilldie[]){ int maxindex = 0; int max = -1; int samecnt =0; for(int i=0;i<client_num;i++){ if(p_jobs[i] == -1){ continue; } if(max<whowilldie[i]){ samecnt = 0; max = whowilldie[i]; maxindex =i; } else if(max == whowilldie[i]){ samecnt =1; } } if(max <= 0){ return -1; } if(samecnt ==1){ return -1; } return maxindex; } void become_day(){ // 3. 낮이 됨 // 사회자가 마피아가 누구를 죽였다라고 말해줌 // 남아있는 사람들끼리 정해진 시간동안 토론을 한다. // 정해진 시간이 지나면 한명 씩 지목한다. // 사회자는 투표 중에서 동률이나 무효표가 아니면 // 그 사람을 처형하고 // 누군가 투표에 의해 죽었는지 알려준다. // (종료조건을 확인) printf("낮이 되었습니다.\n"); // 공유 메모리 만들기. int shmid = shmget(sh_key, MEMORY_SIZE, IPC_CREAT|0644); if (shmid == -1) { perror("shmget"); exit(1); } char day_message[300] = "낮이 되었습니다.\n 마피아는 밤에 "; strcat(day_message, p_nics[killnum]); strcat(day_message, "를 죽였습니다.\n정해진 "); char tempstr[10]={0,}; sprintf(tempstr, "%d", discussion_time); strcat(day_message, tempstr); strcat(day_message, "초 시간동안 대화를 시작해주세요. \n"); for(int i=0;i<client_num;i++){ if(p_jobs[i] == -1){ continue; // 무시.. 죽었으니까. } send_message(i+3, day_message); } sleep(discussion_time); // 정해진 시간 기다리기. printf("토론 시간이 종료되었습니다.\n 각 유저로 부터 I'm done메세지를 기다립니다.\n"); for(int i=0;i<client_num;i++){ if(p_jobs[i] == -1){ continue; } kill((pid_t)p_pids[i], SIGALRM); } // 토론이 끝났다는 시그널 날리기 // SIGALRM 메세지를 보낸다. sleep(1); // 1초 sleep for(int i=0;i<client_num;i++){ if(p_jobs[i] == -1){ continue; } // 죽은 아이디는 기다리지 않는다. receive_print_message(1); } //I'm done 메세지 기다리기 shmctl(shmid, IPC_RMID, NULL); // 공유 메모리 삭제하기 printf("모든 done 메세지를 받았고, 공유 메모리를 삭제하였습니다. \n 투표를 진행합니다.\n"); // 투표 시작하기. for(int i=0;i<client_num;i++){ if(p_jobs[i] == -1){ continue; } // 죽은 아이디는 기다리지 않는다. send_message(i+3, "이제 투표를 시작합니다.! \n특정 유저의 번호를 지정해주세요!\n죽은사람은 투표시 무효표가 됩니다~!\n"); } int whowilldie[client_num]; memset(whowilldie, 0, sizeof(whowilldie)); printf("사용자들로 부터 표를 기다립니다."); for(int i=0;i<client_num;i++){ if(p_jobs[i] == -1){ continue; } // 죽은 아이디는 기다리지 않는다. receive_print_message(1); whowilldie[atoi(mesg.mtext)]++; } printf("투표가 성공적으로 치뤄졌습니다.\n"); killnum = vote_result(whowilldie); printf("투표 결과가 나옵니다.\n"); if(killnum != -1){ // 아래에서 죽이고 종료조건을 체크함. print_kill_one_check_condition(); write_user_data(); // 선거 결과를 보내주기 전, 밤이 되기 전에 최신 데이터를 갱신. char day_killed_message[300] = "투표가 종료되었습니다.\n 선거 결과\n "; strcat(day_killed_message, p_nics[killnum]); strcat(day_killed_message, "를 죽였습니다.\n"); // 좀 이상하지만, 죽었음 알리고, for(int i=0;i<client_num;i++){ if(p_jobs[i] == -1){ continue; } send_message(i+3, day_killed_message); if(p_jobs[i] == Mafia){ memset(mesg.mtext, 0, sizeof(mesg.mtext)); sprintf(mesg.mtext, "%d", nopb_jobs[Mafia]); send_message(i+3, mesg.mtext); } // 보내는 메세지 받는 사람이 마피아면 현재 마피아 수를 추가적으로 보내준다. } } else{ write_user_data(); // 선거 결과를 보내주기 전, 밤이 되기 전에 최신 데이터를 갱신. for(int i=0;i<client_num;i++){ if(p_jobs[i] == -1){ continue; } send_message(i+3,"투표가 종료되었습니다. \n선거 결과 동률 또는 무효표로 인해 아무도 죽지 않았습니다.\n"); // 동률 또는 무효표에 의해서 아무도 죽지 않았음을 명시. if(p_jobs[i] == Mafia){ memset(mesg.mtext, 0, sizeof(mesg.mtext)); sprintf(mesg.mtext, "%d", nopb_jobs[Mafia]); send_message(i+3, mesg.mtext); } // 보내는 메세지 받는 사람이 마피아면 현재 마피아 수를 추가적으로 보내준다. } } } int main(void){ sh_key= ftok("shmfile", 1); // 공유 메모리를 위한 키 만들기. // 1. 초기설정. // 1-1. 접속 할 사람 수를 정하고, 사람 (process)의 접속을 기다린다.` // 1-2. 사회자가 마피아를 랜덤으로 2명 선정 //1-3. 접속 정보를 저장하고 신호를 보내준다. // (사회자 알려줘야 되요. 참여자 누구고 프로세스넘버 뭐있고, 닉네임뭐고.) print_start_message(); scanf("%d", &client_num); printf("토론 시간을 입력 해주세요. : "); scanf("%d", &discussion_time); printf("참여자의 접속을 기다립니다.\n"); send_receive_first_message(); // 위 함수에서 1-1 뒷부분과과 1-2 를 실행. // 1-1.뒷 부분. 사람 (process)의 접속을 기다린다.` // 1-2. 사회자가 마피아를 랜덤으로 2명 선정 printf("test success\n"); printf("-------user_data_file------\n"); printf("--num nic pid -----\n"); for(int i=0;i<client_num;i++){ if(p_jobs[i] == -1){ continue; } printf("%d : %s %d\n", i, p_nics[i], p_pids[i]); } save_user_data_send_messages(); //1-3. 접속 정보를 저장하고 신호를 보내준다. // (사회자 알려줘야 되요. 참여자 누구고 프로세스넘버 뭐있고, 닉네임뭐고.) while(1){ // 2. 밤이 되었습니다. // 마피아는 고개를 들어서 서로를 확인. // 마피아 2명 이상이면 토의 시간 거치고 // 죽일 사람을 선택 // 그 자를 죽임. // 종료 조건 확인. become_night(); // 3. 낮이 됨 // 사회자가 마피아가 누구를 죽였다라고 말해줌 // 남아있는 사람들끼리 정해진 시간동안 토론을 한다. // 정해진 시간이 지나면 한명 씩 지목한다. // 사회자는 투표 중에서 동률이나 무효표가 아니면 // 그 사람을 처형하고 // 누군가 투표에 의해 죽었는지 알려준다. // (종료조건을 확인) become_day(); } // 4. 2-3을 반복. }
C
/* logwatch.c - A very basic log watcher */ /* $Id$ */ #include "copyright.h" #include "autoconf.h" extern char *optarg; int main(argc, argv) int argc; char *argv[]; { char *searchstr = (char *) NULL; char *logfile = (char *) NULL; char *s = (char *) NULL; FILE *fptr; int c=0, delay=0, timeout=30; long pos=0, newpos; /* Parse the command line */ while ((c = getopt(argc, argv, "s:l:t:")) != -1) { switch(c) { case 's': searchstr = optarg; break; case 'l': logfile = optarg; break; case 't': timeout = atoi(optarg); if (timeout < 1) { fprintf( stderr, "Warning - Invalid timeout specified.\n"\ "Using default value of 30 seconds\n"); timeout = 30; } break; } } /* Die if we don't have everything we need */ if ( (searchstr == (char *) NULL ) || (logfile == (char *) NULL ) ) { fprintf( stderr, "Usage : %s -l <logfile> -s <searchstring> [-t <timeout>]\n", argv[0]); exit(1); } c = 0; /* Open the logfile, die if we can't */ if ( (fptr = fopen(logfile, "r")) == NULL) { fprintf( stderr, "Error - Unable to open %s.\n", logfile); exit(1); } s = (char *) malloc(1024); while( c == 0 ) { /* Find the length of the logfile */ fseek(fptr, (long) 0, SEEK_END); newpos=ftell(fptr); /* file grew? print the new content */ if ( newpos > pos ) { fseek(fptr, pos, SEEK_SET); while ( fgets(s, 1024, fptr) != NULL) { fprintf( stdout, "%s", s); if (strstr(s, searchstr) != NULL) { c++; break; } } pos = ftell(fptr); } else if(delay < timeout) { sleep(1); delay++; } else { fprintf( stderr, "Timeout - String '%s' not found in '%s'. Giving up.\n", searchstr, logfile); break; } } free(s); fclose(fptr); exit(0); }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #define MAX_STRING_LENGTH 15 // CONST: maximum length of a string #define OUTPUT_FILE "/home/brian/School/'07 - Fall/CSCI 1111/Assignment 11/output.dat" // CONST: output file disk path #define FILE_WRITE "w" // CONST: string that will open a file for writing /* * A simple program that removes a single user inputed character from * a inputed string and prints it to a file. * RETURNS: * int - EXIT_SUCCESS (0) */ int main() { char * rmchr(char *, char); int prompt(char *, int, char *); char string[MAX_STRING_LENGTH + 1]; // Input: user defined string char character; // Input: user defined char to remove FILE * output = fopen(OUTPUT_FILE, FILE_WRITE); // FILE: output of program if (output != NULL) { printf("All output is stored to file:\n %s\n", OUTPUT_FILE); printf("Enter: CTRL + Z, ENTER to exit.\n"); while (prompt(string, MAX_STRING_LENGTH, &character) == 2) { fprintf(output, "Before removing '%c': %s\n", character, string); rmchr(string, character); fprintf(output, "After: %s\n\n", string); if (ferror(output)) printf("ERROR! Could not print all data to file %s.\n", string); } if (!fclose(output)) { printf("ERROR! Could not close file %s.\n", OUTPUT_FILE); printf("Press ENTER to continue...\n"); getchar(); } } else { printf("ERROR! Could not open file %s.\n", OUTPUT_FILE); printf("Press ENTER to continue...\n"); getchar(); } return EXIT_SUCCESS; } /* * Edits the passed string by revoming the passed character then * returns string. A new string will NOT be created but the original * string will be edited. * PARAMETERS: * char * string - string to be edited * char character - character to remove * RETURNS: * char* - the string that was edited */ char * rmchr(char * string, char character) { if (character != '\0') { const char * const endptr = string + strlen(string); // Pointer: end of the string char * destptr, *srcptr; // Pointers: destination and source for (destptr = srcptr = string; srcptr <= endptr; destptr++, srcptr++) { while (*srcptr == character) srcptr++; *destptr = *srcptr; } } return string; } /* * Prompts the user for a string and single character. The string may * only be be as long as MAX_STRING_LENGTH. EOF will be returned if * the end of the file is reached. * PARAMETERS: * char * const string - address where inputed string will be stored * int max_length - max length of inputed string * char * character - address where inputed character will be stored * RETURNS: * int - number of currectly entered varibles or EOF */ int prompt(char * const string, int max_length, char * character) { int inString(char * const , int); int error_check; // Flag: if there was an error reading the user's input printf("Please enter a string with a max of %i characters: ", max_length); error_check = inString(string, max_length); if (error_check != EOF) { printf("Please enter a character to remove from the above string: "); *character = getchar(); if (*character != EOF) { error_check++; if (*character == '\n') printf("Warning! No characters entered!\n"); else if (getchar() != '\n') { while (getchar() != '\n') ; printf("Warning! Only using one character: %c.\n", *character); } } else error_check = EOF; } return error_check; } /* * Inputs a string with the given maximum length. * PARAMETERS: * char * const string - address where inputed string will be stored * int max_length - max length of inputed string * RETURNS: * int - 1 if successful in inputing string, EOF otherwise. */ int inString(char * const string, int max_length) { char * strptr = string; // Pointer: current position in stringl const char * const endptr = string + max_length; // Pointer: end of string char c; // Input: current character in user inputed string int char_count = 0; // Counter: number of characters in user inputed string while ((c = getchar()) != '\n' && c != EOF) { if (strptr < endptr) *strptr++ = c; char_count++; } *strptr = '\0'; if (char_count > max_length) printf("Warning! String to long, cropped to: %s.\n", string); return (c == EOF ? EOF : 1); }
C
#include <poll.h> #include <fcntl.h> #include <errno.h> #include <string.h> #include <stdint.h> #include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <err.h> #include <sys/timerfd.h> void error(const char* msg); void errorx(const char *msg); void ignore_lines(void); void wexecute(time_t sec, long nsec, const char *cmd); int main(int argc, const char *argv[]) { int argi = 1; const char *arg; const char *cmd = NULL; /* 1 second is 1000000000 nsecs */ time_t sec = 0; long nsec = 250000000; char *endptr; for (; argi < argc; ++argi) { arg = argv[argi]; if (!strcmp(arg, "-n") || !strcmp(arg, "--nanoseconds")) { if (argi > argc - 2) errorx("Invalid --nanoseconds argument."); nsec = strtol(argv[++argi], &endptr, 10); if (*endptr) errorx("Invalid --nanoseconds value."); } else if (!strcmp(arg, "-s") || !strcmp(arg, "--seconds")) { if (argi > argc - 2) errorx("Invalid --seconds argument."); sec = strtol(argv[++argi], &endptr, 10); if (*endptr) errorx("Invalid --seconds value."); } else if (!strcmp(arg, "-c") || !strcmp(arg, "--command")) { if (argi > argc - 2) errorx("Invalid --command argument."); cmd = argv[++argi]; } else { errorx("Invalid argument."); } } if (!cmd) errorx("Missing command."); /* Make sure stdin is non-blocking, so we can read everything. */ /*int flags = fcntl(STDIN_FILENO, F_GETFL, 0); fcntl(STDIN_FILENO, F_SETFL, flags | O_NONBLOCK); */ wexecute(sec, nsec, cmd); return EXIT_SUCCESS; } void wexecute(time_t sec, long nsec, const char *cmd) { int tfd = -1; struct itimerspec t; uint64_t tcount = 0; struct pollfd pfds[2]; int recent = 0; if (-1 == (tfd = timerfd_create(CLOCK_MONOTONIC, 0))) error("timerfd_create()"); t.it_interval.tv_sec = 0; t.it_interval.tv_nsec = 0; t.it_value.tv_sec = sec; t.it_value.tv_nsec = nsec; if (-1 == (timerfd_settime(tfd, 0, &t, NULL))) error("timerfd_settime()"); pfds[0].fd = STDIN_FILENO; pfds[0].events = POLLIN; pfds[0].revents = 0; pfds[1].fd = tfd; pfds[1].events = POLLIN; pfds[1].revents = 0; while (1) { if (-1 == poll(pfds, 2, -1)) error("poll()"); /* If there's no more standard input, stop. */ if (pfds[0].revents & POLLHUP) break; /* If there is input on standard in... */ if (pfds[0].revents & POLLIN) { ignore_lines(); recent = 1; if (-1 == (timerfd_settime(tfd, 0, &t, NULL))) error("timerfd_settime()"); } /* If the timer expired. */ if (pfds[1].revents & POLLIN) { read(tfd, &tcount, sizeof(tcount)); if (recent) { system(cmd); recent = 0; } } } close(tfd); } void error(const char* msg) { err(EXIT_FAILURE, "%s", msg); } void errorx(const char *msg) { errx(EXIT_FAILURE, "%s", msg); } void ignore_lines(void) { char *line = NULL; size_t size = 0; while (1) { getline(&line, &size, stdin); free(line); return; } }
C
#include <string.h> #include <stdio.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> //value should be for size of one request == 4*number of features in request (4 bc of 4bytes/word) #define MAXBUF 324 int main(){ //hardcode fifo names, these don't need to be flexible const char *fifoname = "/tmp/predictor"; const char *fifonameres = "/tmp/predictor-results"; int fifofd, fiforesfd; ssize_t didwrite, didread; int buf[MAXBUF] = {0}; buf[0] = 2; char response[MAXBUF]; //this fifo is for our requests fifofd = open(fifoname, O_WRONLY); if(fifofd < 0){ perror("Cannot open first fifo"); }else{ printf("Opened first fifo\n"); } //this fifo is for predictor responses fiforesfd = open(fifonameres, O_RDONLY); if(fiforesfd < 0){ perror("Cannot open second fifo"); }else{ printf("Opened second fifo\n"); didwrite = write(fifofd, buf, MAXBUF); if(didwrite < 0){ perror("Cannot write"); }else{ printf("Wrote to predictor, number of bytes:%u\n", didwrite); } } //setup listening for predictor response didread = read(fiforesfd, response, MAXBUF); if(didread < 0){ perror("Cannot read predictor response"); }else{ printf("Read from predictor:\n %s", response); } sleep(10); close(fifofd); close(fiforesfd); }
C
#include <stdio.h> #include <sys/types.h> #include <sys/stat.h> #include <dirent.h> #include <limits.h> void traverse(char const *dir) { char name[PATH_MAX]; DIR *d; struct dirent *dd; off_t o; struct stat s; char *delim = "/"; if (!strcmp(dir, "/")) delim = ""; if (!(d = opendir(dir))) { perror(dir); return; } while ((dd = readdir(d))) { if (!strcmp(dd->d_name, ".") || !strcmp(dd->d_name, "..")) continue; snprintf(name, PATH_MAX, "%s%s%s", dir, delim, dd->d_name); if (lstat(name, &s) < 0) continue; if (S_ISDIR(s.st_mode)) { o = telldir(d); closedir(d); traverse(name); if (!(d = opendir(dir))) { perror(dir); return; } seekdir(d, o); } else { printf("%s\n", name); } } closedir(d); } int main(void) { traverse("/"); return 0; }
C
#include<stdio.h> #define N 4 typedef struct Student{ int id, score; }Student; Student fun(Student s[]) { int score = 101; Student tmp; for(int i = 0; i < N; i++) { if(score > s[i].score) { score = s[i].score; tmp = s[i]; } } return tmp; } int main() { Student s[N] = { {111,22}, {222,55}, {444,2}, {555,88} }; Student low = fun(s); printf("%d : %d\n", low.id, low.score); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdbool.h> /** * Return an array of arrays of size *returnSize. * The sizes of the arrays are returned as *columnSizes array. * Note: Both returned array and *columnSizes array must be malloced, assume caller calls free(). */ bool is_palindrome(char *s, int start, int end) { while ((end > start) && (s[start] == s[end])) { end -= 1; start += 1; } return start >= end; } void dfs(char* s, char**** result, int** columnSize, int* returnSize, int* cut_point, int cut_number, int start) { int length = strlen(s); int i = 0, j = 0; int end = length - 1; int sub_string_length = 0; if (start == length) { *returnSize += 1; *columnSize = realloc(*columnSize, (*returnSize + 1) * sizeof(int)); *result = realloc(*result, (*returnSize + 1) * sizeof(char**)); (*result)[*returnSize - 1] = (char**)malloc((cut_number + 1) * sizeof(char*)); for (i = 0; i < cut_number; i++) { sub_string_length = cut_point[i + 1] - cut_point[i]; (*result)[*returnSize - 1][i] = (char*)malloc((sub_string_length + 1) * sizeof(char)); strncpy((*result)[*returnSize - 1][i], s + cut_point[i] + 1, sub_string_length); (*result)[*returnSize - 1][i][sub_string_length] = '\0'; (*columnSize)[*returnSize - 1] = cut_number; } } while (end >= start) { if (is_palindrome(s, start, end)) { cut_point[cut_number + 1] = end; dfs(s, result, columnSize, returnSize, cut_point, cut_number + 1, end + 1); } end -= 1; } } char*** partition(char* s, int** columnSizes, int* returnSize) { char ***result; int *cut_point; int s_length = strlen(s); cut_point = (int*)malloc(s_length * sizeof(int)); cut_point[0] = -1; result = (char***)malloc(sizeof(char**)); result[0] = (char**)malloc(sizeof(char*)); *columnSizes = (int*)malloc(sizeof(int)); (*columnSizes)[0] = 0; *returnSize = 0; if (NULL == s) { return NULL; } dfs(s, &result, columnSizes, returnSize, cut_point, 0, 0); return result; } int main() { // char s[] = "fff"; // char s[] = "aab"; // char s[] = "seeslaveidemonstrateyetartsnomedievalsees"; // char s[] = "aaaaa"; char s[] = "cbbbcc"; int *columnSizes; int returnSize; int i, j; char ***result; result = partition(s, &columnSizes, &returnSize); for (i = 0; i < returnSize; i++) { for (j = 0; j < columnSizes[i]; j++) { puts(result[i][j]); } printf("\n"); } return 0; }
C
#include "Wire.h" #define DS3231_I2C_ADDRESS 0x68 #define PINLED 13 #define PININTERRUPT 2 /* Permet de setter une alarme, de setter le temps, de lever une interruption si le temps et l'alarme s'égalent. Ca allume une LED pour le montrer Supposé fonctionner mais j'ai fait une petit erreur ajd (09-03-2017)*/ struct TimeAlarm { byte second; byte minute; byte hour; byte date; }; volatile bool clockInterrupt = false; // pour alarme // Convertir nombre decimal en Binary Coded Decimal. ex. 12 = 0001 0010 byte decToBcd(byte val){ return( (val/10*16) + (val%10) ); } // Convertir BCD en nombre decimal ex. 0001 0010 = 12 byte bcdToDec(byte val) { return( (val/16*10) + (val%16) ); } void setup() { Wire.begin(); Serial.begin(9600); setTime(0, 9, 21, 7, 22, 10, 16); TimeAlarm time; time.second = 10; time.minute = 9; time.hour = 21; time.date = 7; setAlarm1(time); pinMode(PINLED, OUTPUT); pinMode(PININTERRUPT, INPUT); digitalWrite(PINLED, HIGH); attachInterrupt(digitalPinToInterrupt(PININTERRUPT), clockTrigger, FALLING); Wire.beginTransmission(DS3231_I2C_ADDRESS); Wire.write(0x0E); Wire.write(0b00011101); Wire.write(0b10001000); Wire.endTransmission(); } void setTime(byte second, byte minute, byte hour, byte dayOfWeek, byte dayOfMonth, byte month, byte year) { byte timeToWrite[] = {decToBcd(second), decToBcd(minute), decToBcd(hour) & 0x3F, decToBcd(dayOfWeek), decToBcd(dayOfMonth), decToBcd(month), decToBcd(year)}; Wire.beginTransmission(DS3231_I2C_ADDRESS); Wire.write(0); // Lire la premiere adresse pour commencer 00h Wire.write(timeToWrite, 7); Wire.endTransmission(); } void readTime(byte *second, byte *minute, byte *hour, byte *dayOfWeek, byte *dayOfMonth, byte *month, byte *year){ Wire.beginTransmission(DS3231_I2C_ADDRESS); Wire.write(0); // set DS3231 register pointer to 00h Wire.endTransmission(); Wire.requestFrom(DS3231_I2C_ADDRESS, 7);// request seven bytes of data from DS3231 starting from register 00h *second = bcdToDec(Wire.read() & 0x7f); *minute = bcdToDec(Wire.read()); *hour = bcdToDec(Wire.read() & 0x3f); *dayOfWeek = bcdToDec(Wire.read()); *dayOfMonth = bcdToDec(Wire.read()); *month = bcdToDec(Wire.read()); *year = bcdToDec(Wire.read()); } void displayTime(int arg){ byte second, minute, hour, dayOfWeek, dayOfMonth, month, year; TimeAlarm time; if (arg == 1) { readTime(&second, &minute, &hour, &dayOfWeek, &dayOfMonth, &month, &year); } else { readAlarm1(time); second = time.second; minute = time.minute; hour = time.hour; dayOfWeek = time.date; dayOfMonth = 0; month = 0; year = 0; } Serial.print(hour, DEC); Serial.print(":"); if (minute < 10){ Serial.print("0"); } Serial.print(minute, DEC); Serial.print(":"); if (second < 10){ Serial.print("0"); } Serial.print(second, DEC); Serial.print(" "); Serial.print(dayOfMonth, DEC); Serial.print("/"); Serial.print(month, DEC); Serial.print("/"); Serial.print(year, DEC); Serial.print(" Day of week: "); switch(dayOfWeek){ case 1: Serial.println("Sunday"); break; case 2: Serial.println("Monday"); break; case 3: Serial.println("Tuesday"); break; case 4: Serial.println("Wednesday"); break; case 5: Serial.println("Thursday"); break; case 6: Serial.println("Friday"); break; case 7: Serial.println("Saturday"); break ; } Wire.beginTransmission(DS3231_I2C_ADDRESS); Wire.write(0x0F); Wire.endTransmission(); Wire.requestFrom(DS3231_I2C_ADDRESS, 1); byte register0Fh = Wire.read(); Serial.println(register0Fh, BIN); } void setAlarm1(const TimeAlarm& time) { Wire.beginTransmission(DS3231_I2C_ADDRESS); Wire.write(0x07); byte timeAlarm[] = { decToBcd(time.second) & 0b01111111u, decToBcd(time.minute) & 0b01111111u, decToBcd(time.hour) & 0b00111111u, decToBcd(time.date) | 0b11000000u }; Wire.write(timeAlarm, 4); Wire.endTransmission(); } void readAlarm1(TimeAlarm& time) { Wire.beginTransmission(DS3231_I2C_ADDRESS); Wire.write(0x07); Wire.endTransmission(); Wire.requestFrom(DS3231_I2C_ADDRESS, 4); time.second = bcdToDec(Wire.read() & 0x7F); time.minute = bcdToDec(Wire.read() & 0x7F); time.hour = bcdToDec(Wire.read() & 0x3F); time.date = bcdToDec(Wire.read() & 0x3F); } void clockTrigger() { clockInterrupt = true; } /*void disableAlarmFlag() { Wire.beginTransmission(0x68); Wire.write(0x0E); Wire.write(0b00011100); Wire.endTransmission(); }*/ void loop() { displayTime(1); displayTime(2); if (clockInterrupt) { digitalWrite(PINLED, LOW); Serial.print("interruption!!"); } Serial.println("_____"); delay(1000); }
C
// Author: Wheeler Law // Implementation of interp.h #define _GNU_SOURCE #include <unistd.h> #include <stdio.h> #include <stdlib.h> #include "parser.h" #include "interp.h" #include "symTbl.h" /** ** Runs the entire program. Takes in command line arguments, calls parser ** function as many times as specified. Prints out symbol table. Etc. ** @param argc The number of arguments including the command itself. ** @param *argv[] An array of strings of the arguments. **/ int main(int argc, char* argv[]){ int prompt=isatty(fileno(stdin)); if(argc==2){ buildTable(argv[1]); }else if(argc==1){ buildTable(NULL); }else{ fprintf(stderr,"Usage: interp [sym-table]\n"); exit(EXIT_FAILURE); } dumpTable(); char buff[MAX_LINE]; printf("Enter postfix expressions (CRTL-D to exit): \n"); while(1){ printf("> "); if(fgets(buff,MAX_LINE,stdin)==NULL){ return 1; } int j=0; while(buff[j]!='\0' && buff[j]!='\n'){ j++; } if(buff[j]=='\n'){ buff[j]='\0'; } parse(buff); ParserError pE=getParserError(); } return 0; }
C
#include<stdio.h> #include<fcntl.h> #include<unistd.h> //#include<sys/stat.h> //#include<sys/types.h> int main() { int ret; ret = fork(); //getpid(); ret = fork(); printf("ret=%d\n",ret); printf("ret=%d\n",ret); //printf("%d\n",getpid()); #if 0 if(ret==0) { // ret = fork(); // getpid(); // printf("%d\n",ret); printf("I am child\n"); } else { // ret = fork(); // getpid(); // printf("%d\n",ret); printf("I am parent\n"); } #endif return 0; }
C
#include<stdio.h> /* maximum of two integers */ int max(int a, int b) { return (a > b)? a : b; } // Returns capacity W int knapSack(int W, int weight[], int value[], int n) { int i, w; int K[n+1][W+1]; /* Build table K[][] in bottom up manner */ for (i = 0; i <= n; i++) { for (w = 0; w <= W; w++) { if (i==0 || w==0) K[i][w] = 0; else if (weight[i-1] <= w) K[i][w] = max(value[i-1] + K[i-1][w-weight[i-1]], K[i-1][w]); else K[i][w] = K[i-1][w]; } } return K[n][W]; } int main() { int n; printf("\nEnter the number of items : "); scanf("%d", &n); int value[n]; int weight[n]; int i; printf("\nEnter the items weight and its value \n"); for(i = 0; i < n; i++) { scanf("%d %d", &weight[i], &value[i]); } int W; printf("\nEnter the capacity of the knapsack :" ); scanf("%d", &W); printf("\nMaximum value in a 0-1 knapsack : %d\n", knapSack(W, weight, value, n)); return 0; }
C
#ifndef COMMON_STRUCTS_LINKED_LIST_H #define COMMON_STRUCTS_LINKED_LIST_H #ifdef __cplusplus extern "C" { #endif #include <stdlib.h> struct linked_list { struct linked_list *next; int value; }; typedef struct linked_list linked_list; // Constructor linked_list *linked_list_create(); // Operations void linked_list_union(linked_list *a, linked_list *b); void linked_list_push_back(linked_list *l, int x); // Destructor void linked_list_delete(linked_list *l); #ifdef __cplusplus } #endif #endif
C
#include <terezi.h> #include <stdlib.h> #include <string.h> #include "util.h" /*\ * Double Linked List \*/ tz_dlist *tz_dlist_init(void (*delete)(void *data)) { tz_dlist *l = malloc(sizeof(tz_dlist)); if (!l) die("tz_dlist_new(): malloc():"); memset(l, '\0', sizeof(tz_dlist)); l->destroy = delete; return l; } void tz_dlist_free(tz_dlist *l) { if (!l) return; tz_dlist_node *prev; tz_dlist_node *n = l->tail; while (n) { prev = n->prev; tz_dlist_del(l, n); n = prev; } free(l); } tz_dlist_node *tz_dlist_ins_next( tz_dlist *l, tz_dlist_node *prev, void *data) { if (!l || (!prev && l->size)) return NULL; tz_dlist_node *n = malloc(sizeof(tz_dlist_node)); if (!n) die("tz_dlist_ins_next(): malloc():"); memset(n, 0, sizeof(tz_dlist_node)); n->data = data; n->prev = prev; if (n->prev) { n->next = n->prev->next; n->prev->next = n; } if (n->next) { n->next->prev = n; } if (!l->head || !n->prev) l->head = n; if (!l->tail || !n->next) l->tail = n; l->size++; return n; } tz_dlist_node *tz_dlist_ins_prev( tz_dlist *l, tz_dlist_node *next, void *data) { if (!l || (!next && l->size)) return NULL; tz_dlist_node *n = malloc(sizeof(tz_dlist_node)); if (!n) die("tz_dlist_ins_prev(): malloc():"); memset(n, 0, sizeof(tz_dlist_node)); n->data = data; n->next = next; if (n->next) { n->prev = n->next->prev; n->next->prev = n; } if (n->prev) { n->prev->next = n; } if (!l->head || !n->prev) l->head = n; if (!l->tail || !n->next) l->tail = n; l->size++; return n; } static void dlist_delete(tz_dlist *l, tz_dlist_node *n, int destroy) { if (!l || !n) return; if (n->prev) n->prev->next = n->next; else l->head = n->next; if (n->next) n->next->prev = n->prev; else l->tail = n->prev; if (destroy && l->destroy) l->destroy(n->data); l->size--; free(n); } void tz_dlist_rm(tz_dlist *l, tz_dlist_node *n) { dlist_delete(l, n, 0); } void tz_dlist_del(tz_dlist *l, tz_dlist_node *n) { dlist_delete(l, n, 1); } /*\ * Stack \*/ tz_stack *tz_stack_init(void (*destroy)(void *data)) { return (tz_stack *)tz_dlist_init(destroy); } void tz_stack_free(tz_stack *s) { tz_dlist_free((tz_dlist *)s); } int tz_stack_push(tz_stack *s, void *data) { if (!s) return 0; tz_dlist *l = (tz_dlist *)s; return tz_dlist_ins_prev(l, l->head, data) ? 1 : 0; } void *tz_stack_peek(tz_stack *s) { if (!s) return NULL; tz_dlist *l = (tz_dlist *)s; if (!l->head) return NULL; return l->head->data; } void *tz_stack_pop(tz_stack *s) { if (!s) return NULL; tz_dlist *l = (tz_dlist *)s; if (!l->head) return NULL; void *rv = l->head->data; tz_dlist_rm(l, l->head); return rv; } /*\ * Queue \*/ tz_queue *tz_queue_init(void (*destroy)(void *data)) { return (tz_queue *)tz_dlist_init(destroy); } void tz_queue_free(tz_queue *q) { tz_dlist_free((tz_dlist *)q); } int tz_queue_push(tz_queue *q, void *data) { if (!q) return 0; tz_dlist *l = (tz_dlist *)q; return tz_dlist_ins_next(l, l->tail, data) ? 1 : 0; } void *tz_queue_peek(tz_queue *q) { if (!q) return NULL; tz_dlist *l = (tz_dlist *)q; if (!l->head) return NULL; return l->head->data; } void *tz_queue_pop(tz_queue *q) { if (!q) return NULL; tz_dlist *l = (tz_dlist *)q; if (!l->head) return NULL; void *rv = l->head->data; tz_dlist_rm(l, l->head); return rv; } /*\ * HashTable \*/ struct key_value { void *key; void *value; }; static unsigned int default_hash(const void *key) { /*\ * Credit for hash algorithm to P. J. Weinberger * referenced in `Compilers: Principles, Techniques, and Tools` * by Alfred V. Aho, Ravi Sethi, and Jeffrey D. Ullman \*/ if (!key) return 0; unsigned int tmp; unsigned int rv = 0; const char *c = key; while (*c != '\0') { rv = (rv << 4) + (*c); if ((tmp = (rv & 0xf0000000))) { rv = rv ^ (tmp >> 24); rv = rv ^ tmp; } c++; } return rv; } tz_table *tz_table_init( int (*match)(const void *key1, const void *key2), void (*destroy)(void *data)) { return tz_table_init_custom( TZ_TABLE_DEFAULT_LENGTH, default_hash, match, destroy); } tz_table *tz_table_init_custom( unsigned int length, unsigned int (*h)(const void *key), int (*match)(const void *key1, const void *key2), void (*destroy)(void *data)) { tz_table *t = malloc(sizeof(tz_table)); if (!t) die("tz_table_init_custom(): malloc():"); memset(t, 0, sizeof(tz_table)); t->h = h; t->match = match; t->length = length; t->destroy = destroy; t->array = malloc(sizeof(tz_dlist) * t->length); if (!t->array) die("tz_table_init_custom(): malloc():"); memset(t->array, 0, sizeof(tz_dlist) * t->length); for (int i = 0; i < t->length; i++) { t->array[i].destroy = t->destroy; } return t; } void tz_table_free(tz_table *t) { if (!t) return; tz_dlist *l; tz_dlist_node *n; tz_dlist_node *prev; for (int i = 0; i < t->length; i++) { l = &t->array[i]; if (!l) continue; n = l->tail; while (n) { prev = n->prev; // their_destory_function(their data) if (l->destroy) l->destroy( ((struct key_value *)n->data)->value ); // free(the copied key + our key_value *) free(((struct key_value *)n->data)->key); free(n->data); // manage list pointers tz_dlist_rm(&t->array[i], n); n = prev; } } free(t->array); free(t); } int tz_table_store(tz_table *t, const char *key, void *data) { if (!t || !t->array || !key) return 0; if (tz_table_fetch(t, key)) return 0; unsigned int index = t->h(key) % t->length; tz_dlist *l = &t->array[index]; tz_dlist_node *n = l->head; if (n) while (n->next) n = n->next; struct key_value *kv = malloc(sizeof(struct key_value)); if (!kv) die("tz_table_store: malloc():"); memset(kv, 0, sizeof(struct key_value)); size_t buf_size = sizeof(char) * TZ_TABLE_MAX_KEY_LENGTH + 1; kv->key = malloc(buf_size); if (!kv->key) die("tz_table_store: malloc():"); memset(kv->key, 0, buf_size); strncpy(kv->key, key, buf_size - 1); kv->value = data; return tz_dlist_ins_next(l, n, kv) ? ++t->size : 0; } void *tz_table_fetch(tz_table *t, const char *key) { if (!t || !t->array || !key) return NULL; unsigned int index = t->h(key) % t->length; tz_dlist *l = &t->array[index]; tz_dlist_node *n = l->head; struct key_value *kv; while (n) { kv = n->data; if (!kv) { n = n->next; continue; } if (!strncmp(kv->key, key, TZ_TABLE_MAX_KEY_LENGTH)) { break; } n = n->next; } return n ? kv->value : NULL; } void *tz_table_rm(tz_table *t, const char *key) { if (!t || !t->array || !key) return NULL; unsigned int index = t->h(key) % t->length; tz_dlist *l = &t->array[index]; tz_dlist_node *n = l->head; struct key_value *kv; while (n) { kv = n->data; if (!kv) { n = n->next; continue; } if (!strncmp(kv->key, key, TZ_TABLE_MAX_KEY_LENGTH)) { break; } n = n->next; } if (!n) return NULL; // save their data void *rv = kv->value; // free our data (copied key + struct key_value) free(kv->key); free(kv); // manage list pointers tz_dlist_rm(l, n); t->size--; return rv; } /*\ * Binary Tree \*/ tz_btree *tz_btree_init( void *data, int (*compare)(const void *key1, const void *key2), void (*destroy)(void *data)) { tz_btree *t = malloc(sizeof(tz_btree)); if (!t) die("tz_btree_init(): malloc():"); memset(t, 0, sizeof(tz_btree)); t->size = 1; t->data = data; t->compare = compare; t->destroy = destroy; return t; } static void increment_size(tz_btree *t) { t->size++; if (t->parent) increment_size(t->parent); } static void decrement_size(tz_btree *t) { t->size--; if (t->parent) decrement_size(t->parent); } void tz_btree_free(tz_btree *t, int destroy) { if (!t) return; if (destroy && t->destroy) t->destroy(t->data); if (t->left) tz_btree_free(t->left, destroy); if (t->right) tz_btree_free(t->right, destroy); if (t->parent) { decrement_size(t->parent); tz_btree **parent = NULL; parent = t->parent->left == t ? &t->parent->left : &t->parent->right; if (parent) *parent = NULL; } free(t); } tz_btree *tz_btree_ins_left(tz_btree *t, void *data) { if (!t || t->left) return NULL; t->left = tz_btree_init(data, t->compare, t->destroy); t->left->parent = t; increment_size(t); return t->left; } tz_btree *tz_btree_ins_right(tz_btree *t, void *data) { if (!t || t->right) return NULL; t->right = tz_btree_init(data, t->compare, t->destroy); t->right->parent = t; increment_size(t); return t->right; } tz_dlist *tz_btree_traverse_preorder(tz_btree *t, tz_dlist *l) { if (!t) return l; if (!l) l = tz_dlist_init(NULL); tz_dlist_ins_next(l, l->tail, t->data); if (t->left) tz_btree_traverse_preorder(t->left, l); if (t->right) tz_btree_traverse_preorder(t->right, l); return l; } tz_dlist *tz_btree_traverse_inorder(tz_btree *t, tz_dlist *l) { if (!t) return l; if (!l) l = tz_dlist_init(NULL); if (t->left) tz_btree_traverse_inorder(t->left, l); tz_dlist_ins_next(l, l->tail, t->data); if (t->right) tz_btree_traverse_inorder(t->right, l); return l; } tz_dlist *tz_btree_traverse_postorder(tz_btree *t, tz_dlist *l) { if (!t) return l; if (!l) l = tz_dlist_init(NULL); if (t->left) tz_btree_traverse_postorder(t->left, l); if (t->right) tz_btree_traverse_postorder(t->right, l); tz_dlist_ins_next(l, l->tail, t->data); return l; } /* // this method might not be what you think // there is no balancing going on in this method // if you push A B C D E F G you'll get // F // / \ // D G // / \ // B E // / \ // A C */ tz_btree *tz_btree_push(tz_btree *t, void *data) { if (!t) return NULL; if (!t->left) { if (!t->data) { t->data = data; increment_size(t); return t; } tz_btree_ins_left(t, t->data); t->data = data; return t; } if (!t->right) { tz_btree_ins_right(t, data); return t; } tz_btree *new_root = tz_btree_init(data, t->compare, t->destroy); new_root->size = t->size + 1; t->parent = new_root; return new_root; }
C
#include "draw.h" #include <GL/glut.h> void draw_model(const Model* model) { glPushMatrix(); glTranslatef(model->position.x, model->position.y, model->position.z); //modell mozgatsa glRotatef(model->rotation.z, 0, 0, 1); //modell forgatsa glRotatef(model->rotation.y, 0, 1, 0); glRotatef(model->rotation.x, 1, 0, 0); glBindTexture(GL_TEXTURE_2D, model->texture); //modell textrjnak bindolsa draw_triangles(model); //hromszgek kirajzolsa glPopMatrix(); } void draw_triangles(const Model* model) { int i, k; int vertex_index, texture_index, normal_index; float x, y, z, u, v; glBegin(GL_TRIANGLES); for (i = 0; i < model->n_triangles; ++i) { for (k = 0; k < 3; ++k) { normal_index = model->triangles[i].points[k].normal_index; x = model->normals[normal_index].x; y = model->normals[normal_index].y; z = model->normals[normal_index].z; glNormal3f(x, y, z); texture_index = model->triangles[i].points[k].texture_index; u = model->texture_vertices[texture_index].u; v = model->texture_vertices[texture_index].v; glTexCoord2f(u, 1.0 - v); vertex_index = model->triangles[i].points[k].vertex_index; x = model->vertices[vertex_index].x; y = model->vertices[vertex_index].y; z = model->vertices[vertex_index].z; glVertex3f(x, y, z); } } glEnd(); } void drawTexturedRectangle(GLuint texture, float pos_x, float pos_y, float pos_z, float rotate_x, float rotate_y, float rotate_z, float scale) { glPushMatrix(); //textra bindols glBindTexture(GL_TEXTURE_2D, texture); //pozcionls, forgats, tmretezs glTranslatef(pos_x, pos_y, pos_z); glRotatef(rotate_x, 1, 0, 0); glRotatef(rotate_y, 0, 1, 0); glRotatef(rotate_z, 0, 0, 1); glScalef(scale, scale, scale); //kirajzols glBegin(GL_QUADS); glNormal3f(0,0,1); glTexCoord2f(0.0,0.0); //bal fels sarok glVertex3f( -0.5f, -0.5f, 0); glTexCoord2f(1.0,0.0); //bal als sarok glVertex3f( 0.5f, -0.5f, 0); glTexCoord2f(1.0,1.0); //jobb als glVertex3f( 0.5f, 0.5f, 0); glTexCoord2f(0.0,1.0); //jobb fels glVertex3f( -0.5f, 0.5f, 0); glEnd(); glPopMatrix(); }
C
#include <stdio.h> #include <stdlib.h> int main() { //punteros int *punteroNumero; int numero; int numeroDos; numero=66; punteroNumero=&numero; numeroDos=&numero;// de memoria printf("\n a- %d",numeroDos); numeroDos=*punteroNumero; // de valor printf("\n b-%d",numeroDos); printf("\n%d",numero); printf("\n%d",&numero); printf("\n d-%p",punteroNumero); printf("\n c-%p",&punteroNumero); printf("\n d- %d",*punteroNumero); //*punteroNumero=&numero; //*punteroNumero=55; return 0; }
C
#include <unistd.h> #include <stdio.h> #include <signal.h> #include <stdlib.h> void c_response(int sig) { printf("Ctrl + C detected!\n"); sleep(5); } int main(void) { struct sigaction act; //建一个act 结构体 act.sa_handler = c_response; //挂上捕捉处理函数 sigemptyset(&act.sa_mask); //给一个空 mask sigaddset(&act.sa_mask, SIGQUIT); //在捕捉处理函数里屏蔽 Ctrl + \ act.sa_flags = 0; //flag 设 0,默认在捕捉处理函数内部屏蔽目标信号 act.sa_restorer = NULL; //废弃 int ret = sigaction(SIGINT, &act, NULL); //捕捉 Ctrl + C中断,这里就不保存原来的 sigaction 了 if (ret < 0) { perror("sigaction error"); exit(1); } while(1); return 0; } //[output] //^CCtrl + C detected! // ^\^\^C^C^CCtrl + C detected! #处理函数运行时 c q 都被屏蔽 // ^C^C^C^C^C^CCtrl + C detected! // ^\^\^\^C^C^CCtrl + C detected! // ^\Quit #处理函数不在运行时可以 q 出来
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* fillit.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: aimelda <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/10/30 16:59:46 by aimelda #+# #+# */ /* Updated: 2019/11/11 18:38:18 by aimelda ### ########.fr */ /* */ /* ************************************************************************** */ #include "fillit.h" static int freeing(t_pos **head, t_cell **cells, int n, int m) { t_pos *tmp_pos; t_cell *tmp_cell; while (n--) while (head[n]) { tmp_pos = head[n]; head[n] = head[n]->next; free(tmp_pos); } while (m--) while (cells[m]) { tmp_cell = cells[m]; cells[m] = cells[m]->next; free(tmp_cell); } return (1); } static t_pos *i_pos(t_pos *pos, t_tetr *tetrs, int a, int i) { if (pos) { if (!(pos->next = (t_pos*)malloc(sizeof(t_pos)))) return (NULL); pos->next->prev = pos; pos = pos->next; } else if (!(pos = (t_pos*)malloc(sizeof(t_pos)))) return (NULL); pos->a[0] = i + (tetrs->a[0] * a) + tetrs->a[1]; pos->a[1] = i + (tetrs->a[2] * a) + tetrs->a[3]; pos->a[2] = i + (tetrs->a[4] * a) + tetrs->a[5]; pos->a[3] = i + (tetrs->a[6] * a) + tetrs->a[7]; pos->tetrimino = tetrs->tetrimino; return (pos); } static int i_cell(t_pos *pos, t_cell **cells) { int i; t_cell *tmp; i = -1; while (++i < 4) { if ((tmp = cells[pos->a[i]])) { tmp = tmp->prev; if (!(tmp->next = (t_cell*)malloc(sizeof(t_cell)))) return (0); tmp->next->prev = tmp; tmp = tmp->next; } else if (!(cells[pos->a[i]] = (t_cell*)malloc(sizeof(t_cell)))) return (0); else tmp = cells[pos->a[i]]; tmp->pos = pos; tmp->next = NULL; cells[pos->a[i]]->prev = tmp; } return (1); } static int inits(t_pos **head, t_cell **cells, int a, t_tetr *tetrs) { int i; t_pos *pos; while (tetrs) { pos = NULL; i = -1; while (++i < a * a - 3) if (tetrs->a[6] * a + i < a * a && ((int)ft_max(ft_max(tetrs->a[3], tetrs->a[5]), tetrs->a[7]) + i) / a == i / a) { if (!(pos = i_pos(pos, tetrs, a, i)) || !(i_cell(pos, cells))) return (0); if (!(head[pos->tetrimino - 65])) head[pos->tetrimino - 65] = pos; } if (head[tetrs->tetrimino - 65]) { pos->next = NULL; head[tetrs->tetrimino - 65]->prev = NULL; } tetrs = tetrs->next; } return (1); } int fillit(int n, int a, t_tetr *tetrs) { t_cell *cells[a * a]; char flags[a * a + 1]; t_pos *head[n]; int i; i = 0; while (i <= n) head[i++] = NULL; i = 0; flags[0] = n; while (i < a * a) { cells[i++] = NULL; flags[i] = '.'; } if (!(inits(head, cells, a, tetrs))) return (freeing(head, cells, n, a * a)); if (tracking(head, cells, flags, head[0])) { print_square(flags, a); return (freeing(head, cells, n, a * a)); } else freeing(head, cells, n, a * a); return (0); }
C
#include<stdio.h> #include<string.h> void print_result(int n);/*配列を出力する関数*/ void des_sort(int array[],int N);/*配列を降順にする関数*/ void havel(int array[],int N);/*havel-hakimiの動作を行う関数*/ int have_minus(int array[],int N);/*最後の出力結果を決めるジャッジを行う*/ int juge_loop(int array[],int N);/*havel-hakimi自体をループで行うかどうかを判定する関数*/ int main(){ int N; printf("列数を入力してください"); scanf("%d",&N); int array[N]; printf("数列を入力してください\n"); for(int i = 0;i < N;i++) scanf("%d",&array[i]); des_sort(array,N);/*配列を降順*/ /*配列の中に,負の数と0が無い時に繰り返す*/ while(juge_loop(array,N)) havel(array,N); print_result(have_minus(array,N)); return 0; } /*配列を出力する関数*/ void print_data(int array[],int N){ for(int i=0;i<N;i++) printf("%d",array[i]); printf("\n"); } int juge_loop(int array[],int N){ int cnt=0; for(int i=0;i<N;i++)/*負の数か、すべての要素が0の時,0を返す */ if(array[i]<0 || (array[0]==0&&array[1]==0)) return 0; return 1; } void havel(int array[],int N){ print_data(array,N);/*現状を出力する*/ /*添字が0の配列要素の数だけ、次の配列をそれぞれ1を引く*/ for(int i = 1;i <= array[0];i++) array[i]--; array[0]=0;/*添字が0の配列に0を上書きする*/ des_sort(array,N);/*配列を降順にする*/ } void print_result(int n){ if(n) printf("次数列である\n"); else printf("次数列ではない\n"); } void des_sort(int array[],int N){ int i,j,tmp; for (i=0; i<N; i++) { for (j=i+1; j<N; j++) { if (array[i] < array[j]) { /*隣あう配列要素で,右のほうが小さければ入れ替える*/ tmp = array[i]; array[i] = array[j]; array[j] = tmp; } } } } /*配列中の要素にマイナスがあるかを判定*/ int have_minus(int array[],int N){ for(int i=0;i<N;i++) if(array[i]<0) return 0; return 1; }
C
#define MAX 9 static char* g_table[] = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; char **res = NULL; char* ans = NULL; int g_count = 0; //int vis[10][4] = {0}; void step(char *digits, int box, int box_max) { int i; if (box == box_max) { memcpy(res[g_count], ans, strlen(ans)); g_count++; return; } for (i = 0; i < strlen(g_table[digits[box] - '0']); i++) { //if (vis[digits[box] - '0'][i] == 0) { //vis[digits[box] - '0'][i] = 1; ans[box] = g_table[digits[box] - '0'][i]; step(digits, box + 1, box_max); //vis[digits[box] - '0'][i] = 0; //} } } char ** letterCombinations(char * digits, int* returnSize){ int sum = 1; int i, j, len; g_count = 0; len = strlen(digits); if (len == 0) { res = (char**)malloc(sizeof(char*)); *returnSize = 0; return res; } // ܹԷضٸַ for (i = 0; i < len; i++) { sum *= strlen(g_table[digits[i] - '0']); } *returnSize = sum; // ռ res = (char**)malloc(sum * sizeof(char*)); for (i = 0; i < sum; i++) { res[i] = malloc(sizeof(char) * MAX); memset(res[i], 0, sizeof(char) * MAX); } /*for (i = 0; i < 10; i++) { for (j = 0; j < 4; j++) { vis[i][j] = 0; } }*/ ans = (char*)malloc(MAX); memset(ans, 0 , MAX); step(digits, 0, len); return res; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* get_next_line.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dbud <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/02/18 18:17:28 by dbud #+# #+# */ /* Updated: 2017/03/01 14:59:07 by dbud ### ########.fr */ /* */ /* ************************************************************************** */ #include "get_next_line.h" static int ft_read_from_file(int fd, char **text) { int count_char; char *buffer; if (!(buffer = (char*)malloc(sizeof(*buffer) * (BUFF_SIZE + 1)))) return (-1); if ((count_char = read(fd, buffer, BUFF_SIZE)) > 0) { buffer[count_char] = '\0'; *text = ft_strjoin(*text, buffer); } return (count_char); } int get_next_line(int const fd, char **line) { static char *text = NULL; int count_char; char *pointer; if (fd < 0 || !line || (!text && (text = (char *)malloc(sizeof(*text))) == NULL)) return (-1); pointer = ft_strchr(text, '\n'); while (pointer == NULL) { count_char = ft_read_from_file(fd, &text); if (count_char == 0) { if (ft_strlen(text) == 0) return (0); text = ft_strjoin(text, "\n"); } if (count_char < 0) return (-1); else pointer = ft_strchr(text, '\n'); } *line = ft_strsub(text, 0, ft_strlen(text) - ft_strlen(pointer)); text = ft_strdup(pointer + 1); return (1); }
C
/************************************************************************** memleak.c: A simple module for debbuging memory leaks. ANSI C. Copyright (c) 2005, 2008 Stanislav Maslovski. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ************************************************************************* =================== Theory of operation =================== The program simply allocates a header together with a piece of data. The headers contain information about the calls and are organized in a bidirectional list. The history of malloc() - free() calls is collected in a separate place in a circular buffer. ============ Limitations: ============ I use unsigned long to store the block allocation sizes. The overall allocated memory count is stored as a long. In ANSI C there is no type modifier for printing unsigned long values, so they are printed by casting to unsigned long. Pointers are validated by simple linear search in the lists, do not expect it to be the same fast as the library routines. ============== How to use it: ============== include memleak.h into all modules of your program you want to debug. Place a call to dbg_init() somewhere in the beginning of execution. Add calls to dbg_mem_stat() or dbg_heap_dump() or others (see below) to any suspicious place of your code. You may use "keyword" argument to the dumping functions to reduce the amount of the output. =============================== void dbg_init(unsigned history_size) =============================== This initializes the debugger. history_size defines the maximum number of stored headers of the freed data. ======================== void dbg_zero_stat(void) ======================== clears statistics. ======================= dbg_catch_sigsegv(void) ======================= triggers on SIGSEGV signal handler. ================================================== int dbg_check_addr(char *msg, void *addr, int opt) ================================================== checks for addr in the tables given by opt. opt can be CHK_FREED or CHK_ALLOC or CHK_ALL; returns CHK_FREED, CHK_ALLOC, or 0 if not found. Also prints debugging message to stderr, prefixed with msg. ======================= void dbg_mem_stat(void) ======================= This function prints call statistics to stderr. The location of the call is printed at the beginning of the status line. The status line looks like this: file:line m:<num> c: <num> r:<num> f:<num> mem:<num> where m, c, r, f count malloc(), calloc(), realloc(), and free() calls. mem equals the total amount of requested and not yet freed memory (not exactly the same as the amount of actually allocated physical memory). ================================= void dbg_heap_dump(char *keyword) ================================= This function prints a dump of the current heap state to stderr. Every line of the dump corresponds to an allocated and not yet freed piece of data. Use "keyword" to narrower the dump: keyword = "" => entire heap is dumped, if not "", strstr() is used to select strings with keyword in them. ==================================== void dbg_history_dump(char *keyword) ==================================== dumps history of malloc() - free() calls. keyword is the same as above. */ #include <stdlib.h> #include <string.h> #include <signal.h> #include <limits.h> #include <stdio.h> #define die(msg) (puts(msg)) #define length(type) ((sizeof(type)*5)/2 + 1) char *dbg_file_name; unsigned long dbg_line_number; static long memory_cnt = 0; static int malloc_cnt = 0; static int memalign_cnt = 0; static int calloc_cnt = 0; static int realloc_cnt = 0; static int free_cnt = 0; static unsigned history_length = 0; struct head { void *addr; unsigned long size; char *file; unsigned long line; /* two addresses took the same space as an address and an integer on many archs => usable */ union { struct { struct head *prev, *next; } list; struct { char *file; unsigned long line; } free; } in; }; #define CHK_FREED 1 #define CHK_ALLOC 2 #define CHK_ALL (CHK_FREED | CHK_ALLOC) int dbg_check_addr(char *msg, void *addr, int opt); void dbg_abort(char *msg); static struct head *first = NULL, *last = NULL; static struct head *hist_base = NULL, *histp = NULL; #define HLEN sizeof(struct head) static struct head *add(void *buf, unsigned long s) { struct head *p; p = malloc(HLEN); if(p) { p->addr = buf; p->size = s; p->file = dbg_file_name; p->line = dbg_line_number; p->in.list.prev = last; p->in.list.next = NULL; if(last) last->in.list.next = p; else first = p; last = p; memory_cnt += s; } return p; } #define ADVANCE(p) {if(++(p) >= hist_base + history_length) (p) = hist_base;} static void del(struct head *p) { struct head *prev, *next; prev = p->in.list.prev; next = p->in.list.next; if(prev) prev->in.list.next = next; else first = next; if(next) next->in.list.prev = prev; else last = prev; memory_cnt -= p->size; /* update history */ if(history_length) { p->in.free.file = dbg_file_name; p->in.free.line = dbg_line_number; memcpy(histp, p, HLEN); ADVANCE(histp); } free(p); } static void replace(struct head *p, void *buf, unsigned long s) { memory_cnt -= p->size; p->addr = buf; p->size = s; p->file = dbg_file_name; p->line = dbg_line_number; memory_cnt += s; } void *dbg_malloc(unsigned long s) { void *buf; malloc_cnt++; buf = malloc(s); if(buf) { if(add(buf, s)) return buf; else free(buf); } printf( "%s:%lu: dbg_malloc: not enough memory\n", dbg_file_name, dbg_line_number); return NULL; } void *dbg_memalign(unsigned long alignment, unsigned long s) { memalign_cnt++; void *buf; buf = memalign(alignment, s); if(buf) { if(add(buf, s)) return buf; else free(buf); } printf( "%s:%lu: dbg_memalign: not support\n", dbg_file_name, dbg_line_number); return NULL; } void *dbg_calloc(unsigned long n, unsigned long s) { void *buf; s *= n; calloc_cnt++; buf = malloc(s); if(buf) { if(add(buf, s)) { /* standard calloc() sets memory to zero */ memset(buf, 0, s); return buf; } else free(buf); } printf( "%s:%lu: dbg_calloc: not enough memory\n", dbg_file_name, dbg_line_number); return NULL; } static struct head *find_in_heap(void *addr) { struct head *p; /* start search from lately allocated blocks */ for(p = last; p; p = p->in.list.prev) if(p->addr == addr) return p; return NULL; } static struct head *find_in_hist(void *addr) { struct head *p; int cnt; if(history_length) { if(histp->addr) { cnt = history_length; p = histp; } else { cnt = histp - hist_base; p = hist_base; } while(cnt--) { if(p->addr == addr) return p; ADVANCE(p); } } return NULL; } void dbg_free(void *buf) { struct head *p; free_cnt++; if(buf) if((p = find_in_heap(buf))) { del(p); free(buf); } else dbg_check_addr("dbg_free", buf, CHK_FREED); else printf( "%s:%lu: dbg_free: NULL\n", dbg_file_name, dbg_line_number); } void *dbg_realloc(void *buf, unsigned long s) { struct head *p; realloc_cnt++; if(buf) /* when buf is NULL do malloc. counted twice as r and m */ if(s) /* when s = 0 realloc() acts like free(). counted twice: as r and f */ if((p = find_in_heap(buf))) { buf = realloc(buf, s); if(buf) { replace(p, buf, s); return buf; } else printf( "%s:%lu: dbg_realloc: not enough memory\n", dbg_file_name, dbg_line_number); } else dbg_check_addr("dbg_realloc", buf, CHK_FREED); else dbg_free(buf); else return dbg_malloc(s); return NULL; } int dbg_check_addr(char *msg, void *addr, int opt) { struct head *p; if(opt & CHK_ALLOC) if((p = find_in_heap(addr))) { printf( "%s:%lu: %s: allocated (alloc: %s:%lu size: %lu)\n", dbg_file_name, dbg_line_number, msg, p->file, p->line, (unsigned long)p->size); return CHK_ALLOC; } if(opt & CHK_FREED) if((p = find_in_hist(addr))) { printf( "%s:%lu: %s: freed (alloc: %s:%lu size: %lu free: %s:%lu)\n", dbg_file_name, dbg_line_number, msg, p->file, p->line, (unsigned long)p->size, p->in.free.file, p->in.free.line); return CHK_FREED; } if(opt) printf( "%s:%lu: %s: unknown\n", dbg_file_name, dbg_line_number, msg); return 0; } void dbg_mem_stat(void) { printf( "%s:%lu: mem_stat -- malloc: %d, memalign: %d, calloc: %d, realloc: %d, free: %d, mem_leak: %ld\n", dbg_file_name, dbg_line_number, malloc_cnt, memalign_cnt, calloc_cnt, realloc_cnt, free_cnt, memory_cnt); } void dbg_heap_dump(char *key) { char *buf; struct head *p; printf( "***** %s:%lu: heap dump start\n", dbg_file_name, dbg_line_number); p = first; while(p) { buf = malloc(strlen(p->file) + 2*length(long) + 20); if (buf == NULL) { printf("heap dump err!\n"); return; } sprintf(buf, "(alloc: %s:%lu size: %lu)\n", p->file, p->line, (unsigned long)p->size); p = p->in.list.next; if(strstr(buf, key)) puts(buf); free(buf); } printf( "***** %s:%lu: heap dump end\n", dbg_file_name, dbg_line_number); } void dbg_history_dump(char *key) { int cnt; char *buf; struct head *p; if(history_length) { printf( "***** %s:%lu: history dump start\n", dbg_file_name, dbg_line_number); if(histp->addr) { cnt = history_length; p = histp; } else { cnt = histp - hist_base; p = hist_base; } if (p == NULL) { printf("p==NULL\n"); return; } while(cnt--) { buf = malloc(strlen(p->file) + strlen(p->in.free.file) + 3*length(long) + 30); if (buf == NULL) { printf("buf==NULL\n"); return; } sprintf(buf, "(alloc: %s:%lu size: %lu free: %s:%lu)\n", p->file, p->line, (unsigned long)p->size, p->in.free.file, p->in.free.line); if(strstr(buf, key)) puts(buf); free(buf); ADVANCE(p); } printf( "***** %s:%lu: history dump end\n", dbg_file_name, dbg_line_number); } } void dbg_abort(char *msg) { printf( "+++++ %s: aborting.\n+++++ last call at %s:%lu\n", msg, dbg_file_name, dbg_line_number); dbg_mem_stat(); dbg_heap_dump(""); if(history_length) dbg_history_dump(""); abort(); } void dbg_zero_stat(void) { memory_cnt = 0; malloc_cnt = 0; memalign_cnt = 0; calloc_cnt = 0; realloc_cnt = 0; free_cnt = 0; } #if 0 static void sigsegv_handler(int signal) { if(signal == SIGSEGV) dbg_abort("catched SIGSEGV"); } void dbg_catch_sigsegv(void) { signal(SIGSEGV, sigsegv_handler); } #endif void dbg_init(int hist_len) { history_length = hist_len; if(history_length) { histp = hist_base = calloc(history_length, HLEN); if(hist_base == NULL) die("cannot allocate history buffer"); } } #ifdef WITH_DBG_STRDUP /* Quick fix to support strdup() and strndup() calls. No checking of the pointers passed to these functions is done. Counted as m in the statistic. */ char *dbg_strndup(const char *str, unsigned long n) { unsigned long len; char *buf; len = strlen(str); if(len > n) len = n; buf = dbg_malloc(len + 1); if(buf) { memcpy(buf, str, len); buf[len] = 0; } return buf; } char *dbg_strdup(const char *str) { /* imposes a limit on the string length */ return dbg_strndup(str, ULONG_MAX); } #endif /* end */
C
#include <stdio.h> #include <float.h> int main(void) { float number, division; printf("Enter your number(a float number):"); scanf("%f %f", &number, &division); printf("the number:%10.3f \n", number/division); printf("the exponetial notation:%3.2e\n", number/division); printf("the double number:%7.6g \n", number/division); printf("the exponetial notation:%3.2e \n", number/division); printf("the long double number:%20.12lf\n", number/division); printf("the exponetial notation:%3.2E \n", number/division); printf("float-dig:%d \n", FLT_DIG); printf("double-dig:%d", DBL_DIG); return 0; }
C
#include<stdio.h> #include<stdlib.h> #define infinity 9999 #define MAX 20 int G[MAX][MAX],spanning[MAX][MAX],n; typedef struct edge{ int u,v,w; }edge; typedef struct edgelist{ edge data[MAX]; int n; }edgelist; edgelist elist; edgelist spanlist; int prims(); void kruskal(); int find(int belongs[],int vertexno); void union1(int belongs[],int c1,int c2); void sort(); void print(); int main(){ int i,j,total_cost; printf("Enter no. of vertices:"); scanf("%d",&n); printf("\nEnter the adjacency matrix:\n"); for(i=0;i<n;i++) for(j=0;j<n;j++) scanf("%d",&G[i][j]); total_cost=prims(); printf("\nPrim's algorithm:"); printf("\nspanning tree matrix:"); for(i=0;i<n;i++){ printf("\n"); for(j=0;j<n;j++) printf("%d\t",spanning[i][j]); } printf("\nTotal cost of spanning tree=%d\n",total_cost); printf("\nKrushal's algorithm:"); kruskal(); print(); return 0; } int prims(){ int cost[MAX][MAX]; int u,v,min_distance,distance[MAX],from[MAX]; int visited[MAX],no_of_edges,i,min_cost,j; for(i=0;i<n;i++) for(j=0;j<n;j++){ if(G[i][j]==0) cost[i][j]=infinity; else cost[i][j]=G[i][j]; spanning[i][j]=0; } distance[0]=0; visited[0]=1; for(i=1;i<n;i++){ distance[i]=cost[0][i]; from[i]=0; visited[i]=0; } min_cost=0; no_of_edges=n-1; while(no_of_edges>0){ min_distance=infinity; for(i=1;i<n;i++) if(visited[i]==0&&distance[i]<min_distance){ v=i; min_distance=distance[i]; } u=from[v]; spanning[u][v]=distance[v]; spanning[v][u]=distance[v]; no_of_edges--; visited[v]=1; for(i=1;i<n;i++) if(visited[i]==0&&cost[i][v]<distance[i]){ distance[i]=cost[i][v]; from[i]=v; } min_cost=min_cost+cost[u][v]; } return(min_cost); } void kruskal(){ int belongs[MAX],i,j,cno1,cno2; elist.n=0; for(i=1;i<n;i++) for(j=0;j<i;j++){ if(G[i][j]!=0){ elist.data[elist.n].u=i; elist.data[elist.n].v=j; elist.data[elist.n].w=G[i][j]; elist.n++; } } sort(); for(i=0;i<n;i++) belongs[i]=i; spanlist.n=0; for(i=0;i<elist.n;i++){ cno1=find(belongs,elist.data[i].u); cno2=find(belongs,elist.data[i].v); if(cno1!=cno2){ spanlist.data[spanlist.n]=elist.data[i]; spanlist.n=spanlist.n+1; union1(belongs,cno1,cno2); } } } int find(int belongs[],int vertexno){ return(belongs[vertexno]); } void union1(int belongs[],int c1,int c2){ int i; for(i=0;i<n;i++) if(belongs[i]==c2) belongs[i]=c1; } void sort(){ int i,j; edge temp; for(i=1;i<elist.n;i++) for(j=0;j<elist.n-1;j++) if(elist.data[j].w>elist.data[j+1].w){ temp=elist.data[j]; elist.data[j]=elist.data[j+1]; elist.data[j+1]=temp; } } void print(){ int i,cost=0; for(i=0;i<spanlist.n;i++){ printf("\n%d\t%d\t%d",spanlist.data[i].u,spanlist.data[i].v,spanlist.data[i].w); cost=cost+spanlist.data[i].w; } printf("\nCost of the spanning tree=%d\n",cost); }
C
#include <unistd.h> void ft_putchar(char c) { write(1, &c, 1); } /*void cross(char *tab, int o, char save, int x, char tall) { char tall2; int save2; tall2 = tall; save2 = save; while (tall2 > '0') { tab[save / x + 1] = 'x'; while (tall2 > '0') { tab[save2--] = 'x'; tall2--; } } } */ void cross(char *tab, char tall, int x, int save) { int carre; int mem; int suce; carre = tall - 48; mem = carre; suce = carre; while (save >= 0 && suce > 0) { while (carre > 0) { tab[save] = 'x'; carre--; save--; } save = save - x + mem; carre = mem; save--; suce--; } } void final(char *tab, char tall, int x, int o) { int save; save = 0; while (tab[o] != tall) o++; save = o; o = 0; while ((x * x + x) != o) { if (tab[o] == '0') tab[o] = 'o'; else if (tab[o] != '\n') tab[o] = '.'; o++; } cross(tab, tall, x, save); o = 0; while (tab[o] != '\0') { ft_putchar(tab[o]); o++; } } char superior(char left, char up, char diag) { char sup; sup = left; if (sup > up) sup = up; if (sup > diag) sup = diag; return (sup + 1); } void check(char *tab, int x) { int o; char tall; o = 0; tall = 0; while ((x * x + x) != o) { if (o < x && tab[o] != 'o') tab[o] = '1'; else if ((tab[o] == '\n') && tab[o + 1] != 'o' && tab[o + 1] != '\0') tab[o + 1] = '1'; else if (tab[o] == 'o') tab[o] = '0'; else if (tab[o] == '.') tab[o] = superior(tab[o - 1], tab[o - x - 1], tab[o - x - 2]); if (tall < tab[o]) tall = tab[o]; o++; } o = 0; final(tab, tall, x, o); } int main(void) { char tab[] = "ooo\nooo\nooo\n"; int i = 3; check(tab, i); return (0); }
C
#include "ush.h" static void set_fds(int *fds, int *savedFds) { savedFds[0] = dup(0); savedFds[1] = dup(1); if (fds) { dup2(fds[0], 0); dup2(fds[1], 1); } } static int mx_exec_buildin(t_token *token, int *fds, char operator_starus, t_info *info) { int savedFds[2]; int status = 0; set_fds(fds, savedFds); status = mx_buildin_list(token, info); mx_unset_fds(fds, savedFds, operator_starus); return status; } static int or_operator(t_tnode *root, int *fds, char operatorStatus, t_info *info) { int status = 0; status = mx_execute_tree(root->left, fds, operatorStatus, info); if (info->last_status != 0) status = mx_execute_tree(root->right, fds, operatorStatus, info); return status; } static int and_operator(t_tnode *root, int *fds, char operatorStatus, t_info *info) { int status = 0; status = mx_execute_tree(root->left, fds, operatorStatus, info); if (info->last_status == 0) status = mx_execute_tree(root->right, fds, operatorStatus, info); return status; } int mx_execute_tree(t_tnode *root, int *fds, char op_st, t_info *info) { int status = 0; if ((root == 0) || (info->is_exit)) return -1; if (mx_is_buildin(((t_token*)root->data)->value[0])) mx_exec_buildin((t_token*)root->data, fds, op_st, info); else if (((t_token*)root->data)->type == TYPE_COMMAND) status = exec_token(root->data, fds, op_st, info); if (mx_strcmp(((t_token*)root->data)->value[0], "|") == 0) status = mx_pipe_execute(root, fds, op_st, info); if (mx_strcmp(((t_token*)root->data)->value[0], ">") == 0) status = mx_exec_more(root, fds, op_st, info); if (mx_strcmp(((t_token*)root->data)->value[0], "<") == 0) mx_exec_less(root, fds, op_st, info); if (mx_strcmp(((t_token*)root->data)->value[0], ">>") == 0) mx_exec_dmore(root, fds, op_st, info); if (mx_strcmp(((t_token*)root->data)->value[0], "||") == 0) status = or_operator(root, fds, op_st, info); if (mx_strcmp(((t_token*)root->data)->value[0], "&&") == 0) status = and_operator(root, fds, op_st, info); return status; }
C
#include <stdio.h> int main() {//Найти в строке заданный символ. int i=0, k=0; char a, str [100]; scanf ("%c ", &a); fgets (str, 100, stdin); fflush (stdin); while (str[i]!='\n') { if (str[i]==a) {printf ("%d\n", i); k=1; break;} i++;} if (k==0) printf ("-1"); return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* builtin_setenv.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: gguiulfo <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/11/22 22:16:54 by gguiulfo #+# #+# */ /* Updated: 2018/01/12 14:32:46 by gguiulfo ### ########.fr */ /* */ /* ************************************************************************** */ #include "ft_sh.h" #include "libft.h" #define SENV_ERR_1 "setenv: Too many arguments." #define SENV_ERR_2 "setenv: Variable name must begin with a letter." #define SENV_ERR_3 "setenv: Variable name must contain alphanumeric characters." static void assign_var(char **av, char ***env) { char *str; int i; ft_asprintf(&str, "%s=%s", av[1], (av[2]) ? av[2] : ""); i = 0; while ((*env) && (*env)[i]) { if (ft_strcmp((*env)[i], av[1]) == '=' && ft_strlen(av[1]) == ft_strlenchr((*env)[i], '=')) { ft_strdel(&(*env)[i]); (*env)[i] = str; return ; } i++; } *env = ft_sstrpush(*env, str); ft_strdel(&str); } int builtin_setenv(char **av) { char ***env; if (!av || !av[0]) return (1); env = (!ft_strcmp(av[0], "local")) ? &sh_singleton()->localenv : &sh_singleton()->env; if (!av[1]) ft_sstrputs(*env); else if (av[1] && av[2] && av[3]) return (SH_ERR2_R1(SENV_ERR_1)); else if (!ft_isalpha(av[1][0]) && av[1][0] != '_' && av[1][0] != '/') return (SH_ERR2_R1(SENV_ERR_2)); else if (!ft_unixcase(av[1])) return (SH_ERR2_R1(SENV_ERR_3)); else assign_var(av, env); return (0); }
C
#include "holberton.h" #include <stdio.h> /** * reverse_array - reverses an array * @a: first parameter * @n: second parameter * * Description: where n is the no. of elements * Return: Always(0) Success */ void reverse_array(int *a, int n) { int hold, first, last; first = 0; last = n - 1; for (first = 0; first < last; first++, last--) { hold = *(a + first); *(a + first) = *(a + last); *(a + last) = hold; } }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "mylib.h" #include <math.h> #define MAX_NUM_OF_HOSPITALS 16 #define MAX_NUM_OF_BEDS 16 typedef struct { long int x; long int y; } coordinate_t; long int calculate_distance(coordinate_t, coordinate_t); typedef struct person { char surname[16]; coordinate_t coord; struct person *next; } person_t; typedef struct hospital { person_t *first; person_t *last; int num_of_beds; int num_of_empty_beds; coordinate_t coord; long int (*dist) (coordinate_t, coordinate_t); } hospital_t; hospital_t *read_information_for_hospitals(int *); char read_argument(int, char **); int add_patient(hospital_t *, int); int place_patient_to_the_hospital(hospital_t *, person_t *); int free_hospital_beds(hospital_t *, int); int find_better_hospital(hospital_t *, person_t *, int); int discharge_patient(hospital_t *); int print_information_of_hospitals(hospital_t *, int); int free_memory(hospital_t *, int); int main(int argc, char **argv) { int num_of_hospitals = 0; hospital_t *hosp; if (read_argument(argc, argv) == 'h') { print_manual(); return 0; } hosp = read_information_for_hospitals(&num_of_hospitals); printf("Do you want to see the information of hospitals?"); if(confirm_choice()) { print_information_of_hospitals(hosp, num_of_hospitals); } while (add_patient(hosp, num_of_hospitals)); print_information_of_hospitals(hosp, num_of_hospitals); free_memory(hosp, num_of_hospitals); return 0; } hospital_t *read_information_for_hospitals(int *num_of_hospitals) { int i; char input_buffer[128], *endptr; FILE *fp = fopen("Input.in", "r"); hospital_t *hosp; fgets(input_buffer, SIZE(input_buffer), fp); *num_of_hospitals = strtol(input_buffer, &endptr, 10); hosp = (hospital_t *) malloc(*num_of_hospitals * sizeof(*hosp)); if (!hosp) { printf("Memory isn't allocated"); exit(1); } for (i = 0; i < *num_of_hospitals; i++) { fgets(input_buffer,SIZE(input_buffer),fp); hosp[i].num_of_beds = strtol(input_buffer, &endptr, 10); hosp[i].num_of_empty_beds = hosp[i].num_of_beds; fgets(input_buffer,SIZE(input_buffer),fp); hosp[i].coord.x = strtol(input_buffer, &endptr, 10); hosp[i].coord.y = strtol(endptr, &endptr, 10); hosp[i].dist = calculate_distance; hosp[i].first = NULL; hosp[i].last = NULL; } fclose(fp); return hosp; } int add_patient(hospital_t * hosp, int num_of_hospitals) { int better_hosp_num = 0; person_t *patient; char input_buffer[128]; printf("Specify the surname of a patient(end, to exit): "); myfgets(input_buffer, 16); if (!(strcmp(input_buffer, "end"))) { printf("Shutdown\n"); return 0; } if (!(patient = (person_t *) malloc(sizeof(*patient)) )) { printf("Memory isn't allocated"); exit(1); } patient->next = NULL; strncpy(patient->surname, input_buffer, 16); printf("His coordinates:\n x = "); patient->coord.x = input_number_in_range(0, 180); printf(" y = "); patient->coord.y = input_number_in_range(0, 180); better_hosp_num = find_better_hospital(hosp, patient, num_of_hospitals); if (!better_hosp_num) { printf ("There is no places in hospitals, do you want to free some of it?\n"); if(confirm_choice()) { free_hospital_beds(hosp, num_of_hospitals); free(patient); return 1; } printf("Shutdown\n"); return 0; } place_patient_to_the_hospital(&hosp[better_hosp_num - 1], patient); hosp[better_hosp_num - 1].num_of_empty_beds--; return 1; } int free_hospital_beds(hospital_t * hosp, int num_of_hospitals) { int i; for (i = 0; i < num_of_hospitals; i++) { while (hosp[i].first) { printf("Do you want to delete %s from the %d hospital?\n", hosp[i].first->surname, i + 1); if (!(confirm_choice()) ) { break; } printf("Deleting...\n"); discharge_patient(&hosp[i]); hosp[i].num_of_empty_beds++; } } return 0; } int discharge_patient(hospital_t *hosp) { person_t *tmp; if(!hosp->first) { return 1; } tmp = hosp->first->next; free(hosp->first); hosp->first = tmp; return 0; } int find_better_hospital(hospital_t * hosp, person_t * patient, int num_of_hospitals) { int i, better_hosp_num = 0, FLAG = 0; for (i = 0; i < num_of_hospitals; i++) { if ((hosp[i].num_of_empty_beds > 0) && (hosp[i].dist(hosp[i].coord, patient->coord) <= hosp[better_hosp_num].dist(hosp[better_hosp_num].coord, patient->coord)) ) { better_hosp_num = i; FLAG = 1; } } if(!FLAG) { return 0; } return better_hosp_num + 1; } int place_patient_to_the_hospital(hospital_t * hospital, person_t * patient) { if (!(hospital->first)) { hospital->first = patient; } else { hospital->last->next = patient; } hospital->last = patient; return 0; } char read_argument(int argc, char **argv) { if (argc == 2) { if (!(strcmp(argv[1], "-h")) ) { return 'h'; } } return '0'; } long int calculate_distance(coordinate_t a, coordinate_t b) { long int square_dist; square_dist = (a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y); return square_dist; } int free_memory(hospital_t *hosp, int num_of_hospitals) { int i; for (i = 0; i < num_of_hospitals; i++) { while (!(discharge_patient(&hosp[i])) ); } free(hosp); return 0; } int print_information_of_hospitals(hospital_t *hosp, int num_of_hospitals) { int i; person_t *some_person; for (i = 0; i < num_of_hospitals; i++) { printf("Information of the %d hospital:\n", i + 1); printf(" Number of beds: %d\n", hosp[i].num_of_beds); printf(" Number of emty beds: %d\n", hosp[i].num_of_empty_beds); printf(" Coordinates: (%ld; %ld)\n", hosp[i].coord.x, hosp[i].coord.y); if(hosp[i].first) { some_person = hosp[i].first; printf(" List of patents:\n"); while (some_person) { printf(" %s\n",some_person->surname); some_person = some_person->next; } } } return 0; }
C
#include <stdlib.h> #include <unistd.h> #include <stdio.h> #include <fcntl.h> #include <time.h> #include <string.h> #include <sys/wait.h> #include <signal.h> pid_t pgid; //group pid static volatile pid_t latest_sending_chld_pid = 0; //who sent sigusr1 /* Queue for dead children */ struct chldQueue { siginfo_t status; pid_t chld_pid; struct chldQueue* next; }; struct chldQueue* queue = NULL; struct chldQueue* newChld = NULL; struct chldQueue* first = NULL; static volatile int chldNumber = 0; void push(siginfo_t status) { newChld = (struct chldQueue*)malloc(sizeof(struct chldQueue)); (*newChld).status = status; if(queue == NULL) first = newChld; else (*queue).next = newChld; queue = newChld; } void pop() { if(first != NULL) { newChld = (*first).next; /* Print obituary */ printf("\n [*] Child killed: %d\n", first->status.si_pid); if(first->status.si_pid == latest_sending_chld_pid) printf(" Darvin Award Granted\n"); printf("\n"); first = newChld; if(first == NULL) queue = NULL; } else printf("Queue is empty, cannot pop\n"); chldNumber--; } void free_queue() { while(first) { newChld = first; free(first); } } //--------------------------------------------------------------- void display_help() { printf("\nHow to use this program:\n a.out N:F:T\n N: int, children number\n F: float, time stamps\n T: text, should be in quotes!\n\n"); } /* Split string with ':' delimiter */ int split_str(char** result, char* str) { int i = 0; char* temp = strtok(str, ":"); while(temp) { *(result + i++) = strdup(temp); temp = strtok(0, ":"); } if(i != 3) return -1; return 0; } void nsleep() { struct timespec time; time.tv_sec = 1; time.tv_nsec = 0; nanosleep(&time, NULL); } static void sigusr1_handler(int signo, siginfo_t* status, void* context) { printf("\n * * * * * * * * * * * * * * * * * * * * * * * *\n\tThis program sent SIGUSR1: %d\n * * * * * * * * * * * * * * * * * * * * * * * *\n\n", status->si_pid); latest_sending_chld_pid = status->si_pid; //save who sent signal } static void sigchld_handler(int signo, siginfo_t* status, void* context) { siginfo_t status2; while(!waitid(P_PGID, pgid, &status2, WNOHANG | WEXITED)) { if((status2.si_code == CLD_KILLED) || (status2.si_code == CLD_EXITED)) push(status2); else break; } } //----------------------------------------------------- int main(int argc, char* argv[]) { if(argc != 2) { display_help(); return 1; } char parameters[100]; strcpy(parameters, argv[1]); /* Split str */ char* result[3]; if(split_str(result, parameters) == -1) { perror("Split str error, exiting...\n"); display_help(); return 1; } /* Set variables */ int n_chld = strtol(result[0], NULL, 0); char* t_text = malloc(sizeof(char) * strlen(result[2])); t_text = strdup(result[2]); /* Set global chldNumber */ chldNumber = n_chld; /* Signals handling */ struct sigaction usr1_act, chld_act; sigemptyset(&usr1_act.sa_mask); usr1_act.sa_sigaction = &sigusr1_handler; usr1_act.sa_flags = SA_SIGINFO; sigemptyset(&chld_act.sa_mask); chld_act.sa_sigaction = &sigchld_handler; chld_act.sa_flags = SA_SIGINFO; if(sigaction(SIGUSR1, &usr1_act, NULL) == -1) perror("SIGUSR1 sigaction error\n"); if(sigaction(SIGCHLD, &chld_act, NULL) == -1) perror("SIGCHLD sigaction error\n"); /* Ignore SIGUSR2 signal */ signal(SIGUSR2, SIG_IGN); /* Create process group */ if(setpgid(getpid(), 0) == -1) perror("Setpgid error\n"); pgid = getpgid(getpid()); /* Create children */ for(int i = 0; i<n_chld; i++) { pid_t chld_pid = fork(); if(setpgid(chld_pid, pgid) == -1) perror("Setpgid for chld error\n"); if(chld_pid == 0) { if(execl("./hools.out", "./hools.out", "-d", result[1], t_text, NULL) == -1) perror("Execl error\n"); exit(0); } } nsleep(); /* Send signal to all processes in this group */ if(killpg(pgid, SIGUSR2) == -1) perror("Sending SIGUSR2 error\n"); /* Do until all chilren are dead */ while(chldNumber > 0) { while(queue) pop(); nsleep(); } /* Free memory */ //free_queue(); return 0; }
C
#include "../src/ccobs.c" #include <stdbool.h> #include <stdio.h> #include "unity.h" void test_stuff_single_byte() { char unstuffed[1] = {0}; size_t unstuffed_length = 1; char stuffed_expected[3] = {1, 1, 0}; char stuffed_actual[999] = ""; size_t stuffed_actual_length = 0; // @todo // @todo Print bytes as hex (https://stackoverflow.com/questions/6357031/how-do-you-convert-a-byte-array-to-a-hexadecimal-string-in-c) // @todo printf("\nSTUFFED BEFORE TEST: \n%s", stuffed_actual); bool result = stuff(unstuffed, unstuffed_length, stuffed_actual, &stuffed_actual_length); TEST_ASSERT_EQUAL_BOOL(true, result) printf("\nSTUFFED AFTER TEST: \n%s", stuffed_actual); printf("\n"); // if (stuffed_expected != stuffed_actual) { // printf("Stuffing a single byte failed."); // return 1; // } } int main() { test_stuff_single_byte(); return 0; }
C
/* Convert a Stereo file into a Mono wave file by concatenating the left channel data together. Passes determined values from wav file into FFT function. Normalizes values based on the range, outputted values are from 0-1. Writes output to text file for use with the spectrogram display code. */ #include <stdio.h> #include <stdlib.h> #include <math.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <fcntl.h> #include <errno.h> //#include "fft.h" #include <fftw3.h> /********************** Global Variable ***************************************/ float hamWindow_Multiplier; static double old_an[129][2]; void fftw3 ( int N, double (*x)[2], double (*X)[2], double old_an[N/2+1][2]) { int i; double *in; double *in2; //int n = 100; int nc; fftw_complex *out; fftw_plan plan_backward; fftw_plan plan_forward; /* Set up an array to hold the data, and assign the data. */ in = fftw_malloc ( sizeof ( double ) * N ); // saving new data into input array to compute fft for ( i = 0; i < N; i++ ) { in[i] = x[i][0]; hamWindow_Multiplier = 0.5*(1-cos(2*3.1415*i/N)); in[i] = hamWindow_Multiplier*in[i]; // Apply hamming window to input (IIR Filter) } /* Set up an array to hold the transformed data, get a "plan", and execute the plan to transform the IN data to the OUT FFT coefficients. */ nc = ( N / 2 ) + 1; out = fftw_malloc ( sizeof ( fftw_complex ) * nc ); plan_forward = fftw_plan_dft_r2c_1d ( N, in, out, FFTW_ESTIMATE ); fftw_execute ( plan_forward ); /* AUTOMATIC GAIN COMPUTATION */ double mag=0.0; double newMag=0.0; // After this loop below, maximum magnitude of previous data set is found for ( i = 0; i < nc; i++ ) { newMag= (double)sqrt(((old_an[i][0])*(old_an[i][0])) + ((old_an[i][1])*(old_an[i][1]))); if(mag<newMag) mag=newMag; // new maximum magnitude } double maxFFT= mag; double scale = 1/maxFFT; // scaleFactorNew =1/maxFFTofnew double weightFactor = 0.9; /* Saving fftw3 output coefficient into X and old_an */ for ( i = 0; i < nc; i++ ) { old_an[i][0] = (double)((weightFactor) * out[i][0] + ((1-weightFactor)*scale)); old_an[i][1] = (double)((weightFactor) * out[i][1] + ((1-weightFactor)*scale)); X[i][0] = out[i][0]; X[i][1] = out[i][1]; } /* Release the memory associated with the plans. */ fftw_destroy_plan ( plan_forward ); fftw_free ( in ); fftw_free ( out ); return; } /******************************************************************************/ void genfft(float* fbuffer, int N) { int i=0,j,k,l=0; int wavbuffer[N]; double (*X)[2]; /* pointer to frequency-domain samples */ /* double */ double x[N][2]; /* double */ double mag, min, max, mag_norm; /* double */ X = malloc(2 * N * sizeof(double)); /* double */ while (i<N) { x[i][1]=0; i++; } /* initialize previous data set to 1 */ for ( i= 0; i < 129; i++ ) { old_an[i][0] = (double)1; old_an[i][1] = (double)1; } mkfifo("wavePipe", S_IRWXO); system("arecord -d1 -r44100 -D plughw:CARD=Snowflake,DEV=0 wavePipe"); int lSize; FILE * f = fopen("wavePipe", "r"); //opening the 2 channels wave file if(!f) printf("Error reading from wavePipe"); //just to see what we're dealing with fseek (f , 0 , SEEK_END); lSize = ftell (f); rewind (f); typedef struct wave { int chunkID; int chunkSize; int format; int subChunk1ID; int subChunk1size; int audio_num_ch; int sampleRate; int byteRate; int bckAli_bitPs; int subChunk2ID; int subChunk2size; int data[(lSize-40)/4]; } wave; wave * mywave; mywave=(wave *) malloc( lSize); fread(mywave,1,lSize,f); i=0,j=0; k=0; int mask=65535; double leftVa; // leftVa of old code is "int" while (i<((lSize-40)/4)) { leftVa=(mywave->data[i+1]<<16) | (mywave->data[i] & mask); mywave->data[j]=leftVa; x[k][0]=leftVa; wavbuffer[k] = leftVa; j++; k++; if (k==N) { fftw3(N, x, X, old_an); min = 0; max = sqrt((X[0][0]*X[0][0])+(X[0][1]*X[0][1])); for(l=0; l<((N/2)+1); l++) { mag=sqrt((X[l][0]*X[l][0])+(X[l][1]*X[l][1])); if(mag > max) { max = mag; } if(mag < min) { min = mag; } } for(l=0; l<((N/2)+1); l++) { mag=sqrt((X[l][0]*X[l][0])+(X[l][1]*X[l][1])); mag_norm = (mag - min)/(max - min); fbuffer[l] = mag_norm; } k=0; } i=i+2; } /* for(i = 0; i < N; i++) printf("wavbuffer[%d] is %12d, fbuffer[%d] is %12f\n", i, wavbuffer[i], i, fbuffer[i]); */ fclose (f); free(X); return; }
C
#include "libft.h" int ft_atoi(const char *str) { int x; long y; x = 1; y = 0; while (((*str > 8) && (*str < 14)) || *str == 32) str++; if (*str == 43 || *str == 45) { if (*str == 45) x = -x; str++; } if (*str < 48 || *str > 57) return (0); while ((*str > 47) && (*str < 58)) { y = y * 10 + (*str - '0'); if (y > 2147483647 && x == 1) return (-1); if (y > 2147483648 && x == -1) return (0); str++; } return (x * y); }
C
/* DESCRIPTION: implementation of LD AUTHOR: Jono Davis DATE: 10/17 */ #include <stdio.h> #include <string.h> #include <ctype.h> typedef struct { int address; char label[5]; } data; int main(int argc, char *argv[]) { /* LC3 FILE */ FILE *fp; fp = fopen(argv[1], "r"); char buff[255]; char *sep = ", "; int operands[3]; int imm; int haltReached = 0; int instrucCount = 0; data dataArray[10000]; int dataCount = 0; char labelHolder[5]; /* SYMBOL TABLE */ FILE *fp2; fp2 = fopen("SymbolTable", "w"); /* FIRST PASS */ while (fgets(buff, 255, fp) != NULL) { if (buff[0] == '.') { int orig; if (sscanf(buff, ".orig x%x", &orig) != 0) { instrucCount = orig; } continue; } char *opcode = strtok(buff, sep); char *phrase; if (haltReached == 1) { fprintf(fp2, "%s %x\n", opcode, instrucCount); dataArray[dataCount].address = instrucCount; strcpy(dataArray[dataCount].label, opcode); dataCount++; instrucCount++; } else if (strcmp(opcode, "halt\n") == 0) { haltReached = 1; instrucCount++; } else { instrucCount++; } } /* SECOND PASS */ haltReached = 0; rewind(fp); while (fgets(buff, 255, fp) != NULL) { if (buff[0] == '.') { int orig; if (sscanf(buff, ".orig x%x", &orig) != 0) { instrucCount = orig; } continue; } char *opcode = strtok(buff, sep); char *phrase; int i = 0; imm = 0; while ((phrase = strtok(NULL, sep)) != NULL) { if (phrase[0] == 'r') { sscanf(phrase, "r%d", &operands[i++]); imm = 0; } else if (phrase[0] == '#') { sscanf(phrase, "#%d", &operands[i++]); imm = 1; } if (isalpha(phrase[1])) { strncpy(labelHolder, phrase, 3); } } if (haltReached == 0) { int instruc = 0; if (imm == 0) { if (strcmp(opcode, "add") == 0) { instruc |= 0x1 << 0xc; instruc |= operands[0] << 0x9; instruc |= operands[1] << 0x6; instruc |= operands[2]; } else if (strcmp(opcode, "and") == 0) { instruc |= 0x5 << 0xc; instruc |= operands[0] << 0x9; instruc |= operands[1] << 0x6; instruc |= operands[2]; } else if (strcmp(opcode, "halt\n") == 0) { instruc |= 0xf << 0xc; instruc |= 0x25; haltReached = 1; } else if (strcmp(opcode, "jmp") == 0) { instruc |= 0xc << 0xc; instruc |= operands[0] << 0x6; } else if (strcmp(opcode, "ld") == 0) { instruc |= 0x2 << 0xc; instruc |= operands[0] << 0x9; for (int j = 0; j < dataCount; j++) { if (strcmp(labelHolder, dataArray[j].label) == 0) { instruc |= (dataArray[j].address - instrucCount - 1); } } } } else if (imm == 1) { if (strcmp(opcode, "add") == 0) { instruc |= 0x1 << 0xc; instruc |= operands[0] << 0x9; instruc |= operands[1] << 0x6; instruc |= 0x1 << 0x5; instruc |= operands[2] & 0x1f; } else if (strcmp(opcode, "and") == 0) { instruc |= 0x5 << 0xc; instruc |= operands[0] << 0x9; instruc |= operands[1] << 0x6; instruc |= 0x1 << 0x5; instruc |= operands[2] & 0x1f; } } instrucCount++; printf("%x\n", instruc); } } fclose(fp); fclose(fp2); }
C
#include "shell.h" /** * _getenv - This function looks for a path in the environment. * @command: The command of the environment variable. * Return: A pointer to path of the variable. */ char *_getenv(const char *command) { unsigned int length = 0, i = 0; char *pos = NULL, *str = NULL; length = _strlen(command); while (environ[i]) { str = environ[i]; pos = _strchr(str, '='); if (pos && (pos - str == length && !_strncmp(str, command, length))) return (pos + 1); i++; } return (NULL); } /** * _setenv - This function sets a environment variable. * @command: The standard input. * Return: Nothing. */ void _setenv(char **command) { char *s = _getenv(command[1]), *fil = NULL; if (s == NULL) { fil = fill(command[1], command[2]); putenv(fil); free(fil); } else { fil = fill(s, command[2]); putenv(fil); free(fil); } free_arr(command); } /** * _unsetenv - This function unsets a environment variable. * @command: The standard input. * Return: Nothing. */ void _unsetenv(char **command) { char **ep = NULL, **sp = NULL; int len = 0; if (command[1] == NULL || command[1] == NULL || _strchr(command[1], '=') != NULL) { write(STDOUT_FILENO, "not found\n", 11); free_arr(command); return; } len = _strlen(command[0]); ep = environ; while (*ep) { if (!(_strncmp(*ep, command[0], len)) && (*ep)[len + 1] == '=') { sp = ep; while (*sp) { *sp = *(sp + 1); sp++; } } else ep++; } free_arr(command); } /** * fill - This function concatenates a string with a '='. * @command: The string 1. * @value: The string 2. * Return: A pointer to string NULL terminated concatenated. */ char *fill(const char *command, const char *value) { unsigned int i = 0; char *buff = NULL; buff = malloc((strlen(command) + strlen(value) + 2) * sizeof(char)); if (buff == NULL) return (NULL); while (*command) { buff[i] = *command; command++; i++; } buff[i] = '='; i++; while (*value) { buff[i] = *value; value++; i++; } buff[i] = '\0'; return (buff); }
C
/* 461. Hamming Distance The Hamming distance between two integers is the number of positions at which the corresponding bits are different. Given two integers x and y, calculate the Hamming distance. Note: 0 x, y < 231. Example: Input: x = 1, y = 4 Output: 2 Explanation: 1 (0 0 0 1) 4 (0 1 0 0) The above arrows point to positions where the corresponding bits are different. */ #include <stdio.h> #include <math.h> #include <stdlib.h> #include <stdbool.h> #include <string.h> //#define A461 #ifdef A461 int hammingDistance(int x, int y) { unsigned int n=x^y, temp; temp = n - ((n >> 1) & 0x77777777) - ((n >> 2) & 0x33333333) - ((n >> 3) & 0x11111111); return ((temp + (temp>>4)) & 0x0f0f0f0f) % 255; //return bit_count(x^y); } int main(){ printf("%d", hammingDistance(1577962638, 1727613287)); getchar(); return 0; } #endif
C
#include<stdio.h> #include<stdlib.h> #include<math.h> #include<string.h> #define REP(i,a,b) for(i=a;i<b;i++) #define rep(i,n) REP(i,0,n) int dp[200][3][3]; int fg[3000]; int debug = 0; int mp[200][2]; int get_grundy(int n){ int i, j, k; int all, up, down; k = 0; rep(i,n){ if(mp[i][0] && mp[i][1]) continue; all = up = down = 0; if(!mp[i][0] && !mp[i][1]) all++; else if(!mp[i][0]) up = 1; else if(!mp[i][1]) up = 2; while(i<n){ i++; if(i>=n) break; if(mp[i][0] || mp[i][1]){ if(mp[i][0] && mp[i][1]) break; if(!mp[i][0]) down = 1; if(!mp[i][1]) down = 2; break; } else { all++; } } if(debug) printf("%d %d %d\n",all,up,down); k ^= dp[all][up][down]; } return k; } int main(int argc, char *argv[]){ int i,j,k,l,m,n; int all, up, down; int a, b; rep(all,103) rep(up,3) rep(down,3){ rep(i,3000) fg[i] = 0; n = all + 2; rep(i,n) rep(j,2) mp[i][j] = 0; if(up!=1) mp[0][0] = 1; if(up!=2) mp[0][1] = 1; if(down!=1) mp[n-1][0] = 1; if(down!=2) mp[n-1][1] = 1; rep(i,n) rep(j,n) if(mp[i][j]==0){ mp[i][j]++; if(i-1 >= 0) mp[i-1][1-j]++; mp[i][1-j]++; if(i+1 < n) mp[i+1][1-j]++; fg[get_grundy(n)]++; mp[i][j]--; if(i-1 >= 0) mp[i-1][1-j]--; mp[i][1-j]--; if(i+1 < n) mp[i+1][1-j]--; } rep(i,3000) if(!fg[i]) break; dp[all][up][down] = i; } scanf("%d%d",&n,&m); rep(i,n) rep(j,2) mp[i][j] = 0; while(m--){ scanf("%d%d",&i,&j); i--; j--; mp[i][j] = 1; if(i-1 >= 0) mp[i-1][1-j] = 1; mp[i][1-j] = 1; if(i+1 < n ) mp[i+1][1-j] = 1; } debug = 0; /* rep(i,n){ rep(j,2) printf("%d",mp[i][j]); puts(""); }*/ k = get_grundy(n); if(k==0) puts("LOSE"); else puts("WIN"); return 0; }
C
#define q14_h #include "library.h" // QUESTÃO 14 // Utilizando o algoritmo shellsort visto em aula, implemente‐o em C para que ordene // em ordem decrescente e obtenha o número de comparações e movimentações para o // seguinte vetor: 8,12,19,43,45,56,67,95 void shellSortDesc(int n, int* v){ clock_t tInicio, tFim; double tDecorrido; int i, j, h = 1, aux, troca = 0, comparacoes = 0; tInicio = clock(); do{ h = h * 3 + 1; }while (h < n); do{ h = (h - 1) / 3; for (i = h; i < n; i++){ aux = v[i]; j = i; comparacoes += 1; while (v[j-h] < aux){ troca += 1; v[j] = v[j-h]; j-=h; if (j<h) break; } v[j] = aux; } }while(h>0); tFim = clock(); tDecorrido = (((double)(tFim - tInicio))/ (CLOCKS_PER_SEC / 1000)); printf("Tempo decorrido: %lf s \n", tDecorrido); printf("Comparações: %d \n", comparacoes); printf("Trocas: %d \n", troca); } int q14(){ int i14, array_desordenadoq14[8] = {8,12,19,43,45,56,67,95}; printf("===========================================\n"); printf("QUESTÃO 14\n"); shellSortDesc(8, array_desordenadoq14); printf("Array Ordenado: \n"); for (i14 = 0; i14 < 8; i14++){ printf("%d ", array_desordenadoq14[i14]); } printf("\n"); printf("===========================================\n"); }
C
float medianArrays(int a[], int b[], int asize, int bsize) { int k=0, i=0, j=0, n=asize+bsize; int arr[n]; while(i<asize && j<bsize) { if(a[i]<=b[j]) arr[k++] = a[i++]; else arr[k++] = b[j++]; } while(i<asize) arr[k++] = a[i++]; while(j<bsize) arr[k++] = b[j++]; float m; if(n%2==0) m = ((float)(arr[n/2] + arr[(n/2)-1]))/2; else m = arr[n/2]; return m; }
C
/***************************************************************************** * hdb.c * * Computer Science 3357a - Fall 2015 * Author: Jerridan Quiring * * Implements the functions of libhdb ****************************************************************************/ #define _GNU_SOURCE #include <stdlib.h> #include <stdio.h> #include <string.h> #include <hiredis/hiredis.h> #include "hdb.h" #include "redis_queries.h" // Connect to the specified Hooli database server, returning the initialized // connection. hdb_connection* hdb_connect(const char* server) { redisContext *con; //Declare redis context variable const int port = 6379; //Connection port of redis server struct timeval timeout = {2, 0}; //2 sec timeout //Connect to redis server con = redisConnectWithTimeout(server, port, timeout); //Check if connection failed if(NULL == con || con->err) { if(con) { fprintf(stderr, "Connection error: %s\n", con->errstr); redisFree(con); } else { fprintf(stderr, "Connection error: unable to connect to specified server '%s'\n", server); } return NULL; } //Return connection return *(hdb_connection**)&con; } // Disconnect from the Hooli database server. void hdb_disconnect(hdb_connection* con) { redisFree((redisContext*)con); } // Store a file record in the Hooli database. void hdb_store_file(hdb_connection* con, hdb_record* record) { redis_hset(con, record->username, record->filename, record->checksum); } // Remove a file record from the Hooli database. int hdb_remove_file(hdb_connection* con, const char* username, const char* filename) { //Returns number of records deleted return redis_hdel(con, username, filename); } // If the specified file is found in the Hooli database, return its checksum. // Otherwise, return NULL. char* hdb_file_checksum(hdb_connection* con, const char* username, const char* filename) { return redis_hget(con, username, filename); } // Return a count of the user's files stored in the Redis server. int hdb_file_count(hdb_connection* con, const char* username) { return redis_hlen(con, username); } // Return a Boolean value indicating whether or not the user exists in // the Redis server (i.e. whether or not he/she has files stored). bool hdb_user_exists(hdb_connection* con, const char* username) { return redis_hexists(con, "usernames", username); } // Return a Boolean value indicating whether or not the file exists in // the Redis server. bool hdb_file_exists(hdb_connection* con, const char* username, const char* filename) { return redis_hexists(con, username, filename); } // Return a linked list of all of the specified user's file records stored // in the Hooli database hdb_record* hdb_user_files(hdb_connection* con, const char* username) { redisReply *reply = redis_hgetall(con, username); if(NULL == reply) { return NULL; } //Copy the username, as a constant will not work here char *usernameCpy = getStrCopyOfConst(username); //Set up the first(head) record in the linked list hdb_record *head = calloc(1, sizeof(hdb_record)); hdb_record *current; //Points to current node as we traverse the linked list head->username = usernameCpy; //Copy contents to head node, since reply will be freed head->filename = getStrCopy(reply->element[0]->str); head->checksum = getStrCopy(reply->element[1]->str); head->next = NULL; current = head; //Keep adding records to the list until we're through them all for(int i = 2; i < reply->elements; i+=2) { //Create a new node hdb_record *temp = malloc(sizeof(hdb_record)); //Copy contents to new node temp->username = usernameCpy; temp->filename = getStrCopy(reply->element[i]->str); temp->checksum = getStrCopy(reply->element[i+1]->str); temp->next = NULL; //Point current node's next to our new node current->next = temp; current = temp; } freeReplyObject(reply); return head; } // Free up the memory in a linked list allocated by hdb_user_files(). void hdb_free_result(hdb_record* record) { //Points to current node as we traverse the linked list hdb_record *current = record; hdb_record *next; //Will point to current node's next node free(current->username); //Because they all point to one shared username //Free up node's pointers and then node itself until we reach end of list while(current) { next = current->next; free(current->filename); free(current->checksum); free(current); current = next; } } // Delete the user and all of his/her file records from the Hooli database. int hdb_delete_user(hdb_connection* con, const char* username) { int del = redis_del(con, username); int hdel = redis_hdel(con, "usernames", username); return del + hdel; } // Authenticate a user by password and return a generated token char* hdb_authenticate(hdb_connection* con, const char* username, const char* password) { // NOTE: Passwords are stored under a hash called 'passwords', under the // field of the appropriate username ('passwords' username password) // NOTE: Tokens are stored as ('tokens' token username) // Non-constant copies of username and password char* usernameCpy = getStrCopyOfConst(username); char* passwordCpy = getStrCopyOfConst(password); // If the user exists, verify the specified password if(hdb_user_exists(con, usernameCpy)) { char* stored_pass = redis_hget(con, "usernames", usernameCpy); if(0 != strcmp(password, stored_pass)) { free(usernameCpy); free(passwordCpy); free(stored_pass); return NULL; } free(stored_pass); } else { redis_hset(con, "usernames", usernameCpy, passwordCpy); } // Create a 16-character token for user validation char* token = generateToken(16); // Store the token in redis and return it redis_hset(con, "tokens", token, usernameCpy); free(usernameCpy); free(passwordCpy); return token; } // Verify a specified token, returning the associated username if valid // or NULL otherwise char* hdb_verify_token(hdb_connection* con, const char* token) { if(redis_hexists(con, "tokens", token)) { return redis_hget(con, "tokens", token); } else { return NULL; } }
C
#include "holberton.h" /** * _strspn - the length of a string containing only chars from another * @s: pointer to the buffer (memory space) * @accept: pointer to string * Return: unsigned int with length */ unsigned int _strspn(char *s, char *accept) { unsigned int i, a, sum = 0; for (i = 0; s[i] != '\0'; i++) { for (a = 0; accept[a] != '\0'; a++) { if (s[i] == accept[a]) { sum = sum + 1; } } if (i == sum) break; } return (sum); }
C
#include<stdio.h> void main() { int a, b, c; printf("input a,b,c\n"); scanf_s("%d%d%d", &a, &b, &c); printf("a=%x,b=%x,c=%x", &a, &b, &c); }
C
#include <stdio.h> #include <stdint.h> #include <stdlib.h> #include <time.h> int main() { srand((unsigned int)time(0x0)); int counter = 53, j=0, x; while(counter) { do{ x = rand()%52; printf("%d , ", x); } while (x <= j); printf("%d , ", x); ++j; x=j; --counter; } return 0; }
C
#include <stdio.h> int main(void){ signed char c = -100; unsigned long nl; nl = -10 + c; printf("%lu\n",nl); }
C
#include "../inc/libmx.h" char *mx_strjoin(const char *s1, const char *s2) { char *join; if (NULL == s2 && NULL == s1) return NULL; if (NULL == s2 || NULL == s1) { join = !s2 ? mx_strnew(mx_strlen(s1)) : mx_strnew(mx_strlen(s2)); join = !s2 ? mx_strcpy(join, s1) : mx_strcpy(join, s2); return join; } join = mx_strnew(mx_strlen(s1) + mx_strlen(s2)); join = mx_strcat(join, s1); join = mx_strcat(join, s2); return join; }
C
#include<stdio.h> void inputnum(int *n,int *r) { printf("Enter the values of n and r to calculate ncr and npr\n"); scanf("%d%d",n,r); } void factorial(int n,int r,int *factn,int *factr,int *factnr) { int sum1=1,sum2=1,sum3=1,i; for(i=1;i<=n;i++) { sum1=sum1*i; } for(i=1;i<=r;i++) { sum2=sum2*i; } for(i=1;i<=n-r;i++) { sum3=sum3*i; } *factn=sum1; *factr=sum2; *factnr=sum3; } void computePNC(int factn,int factr,int factnr,float *ncr,float *npr) { *ncr=factn/(factr*factnr); *npr=factn/factnr; } void result(float ncr,float npr) { printf("The values after calculation are\n ncr=%.2f\n npr=%.2f",ncr,npr); } int main() { int n,r,factn,factr,factnr; inputnum(&n,&r); factorial(n,r,&factn,&factr,&factnr); float ncr,npr; computePNC(factn,factr,factnr,&ncr,&npr); result(ncr,npr); return 0; }
C
/*! * \file sketch_support.c * * \brief Support routines for managing bitmaps used in sketches */ /*! @addtogroup grp_desc_stats * * @par About: * MADlib provides a number of descriptive statistics to complement * SQL's builtin aggregation functions (COUNT, SUM, MAX, MIN, AVG, STDDEV). * When possible we try * to provide high-peformance algorithms that run in a single (parallel) * pass of the data without overflowing main memory. In some cases this * is achieved by approximation * algorithms (e.g. sketches) -- for those algorithms it's important to * understand that answers are guaranteed mathematically to be within * plus-or-minus a small epsilon of the right answer with high probability. * It's always good to go back the research papers cited in the documents to * understand the caveats involved. * * \par * In this module you will find methods for: * - order statistics (quantiles, median) * - distinct counting * - histogramming * - frequent-value counting */ /* @addtogroup grp_sketches */ #include <math.h> /* THIS CODE MAY NEED TO BE REVISITED TO ENSURE ALIGNMENT! */ #include <postgres.h> #include <utils/array.h> #include <utils/elog.h> #include <nodes/execnodes.h> #include <fmgr.h> #include <utils/builtins.h> #if PG_VERSION_NUM >= 100000 #include <common/md5.h> #else #include <libpq/md5.h> #endif #include <utils/lsyscache.h> #include "sketch_support.h" /*! * Simple linear function to find the rightmost bit that's set to one * (i.e. the # of trailing zeros to the right). * \param bits a bitmap containing many fm sketches * \param numsketches the number of sketches in the bits variable * \param sketchsz_bits the size of each sketch in bits * \param sketchnum the sketch number in which we want to find the rightmost one */ uint32 rightmost_one(uint8 *bits, size_t numsketches, size_t sketchsz_bits, size_t sketchnum) { (void) numsketches; /* avoid warning about unused parameter */ uint8 *s = &(((uint8 *)(bits))[sketchnum*sketchsz_bits/8]); int i; uint32 c = 0; /* output: c will count trailing zero bits, */ if (sketchsz_bits % (sizeof(uint32)*CHAR_BIT)) elog( ERROR, "number of bits per sketch is %u, must be a multiple of sizeof(uint32) = %u", (uint32)sketchsz_bits, (uint32)sizeof(uint32)); /* * loop through the chunks of bits from right to left, counting zeros. * stop when we hit a 1. * XXX currently we look at CHAR_BIT (8) bits at a time * which would seem to avoid any 32- vs. 64-bit concerns. * might be worth tuning this up to do 32 bits at a time. */ for (i = sketchsz_bits/(CHAR_BIT) -1; i >= 0; i--) { uint32 v = (uint32) (s[i]); if (!v) /* all CHAR_BIT of these bits are 0 */ c += CHAR_BIT /* * sizeof(uint32) */; else { c += ui_rightmost_one(v); break; /* we found a 1 in this value of i, so we stop looping here. */ } } return c; } /*! * Simple linear function to find the leftmost zero (# leading 1's) * Would be nice to unify with the previous -- e.g. a foomost_bar function * where foo would be left or right, and bar would be 0 or 1. * \param bits a bitmap containing many fm sketches * \param numsketches the number of sketches in the bits variable * \param the size of each sketch in bits * \param the sketch number in which we want to find the rightmost one */ uint32 leftmost_zero(uint8 *bits, size_t numsketches, size_t sketchsz_bits, size_t sketchnum) { uint8 * s = &(((uint8 *)bits)[sketchnum*sketchsz_bits/8]); unsigned i; uint32 c = 0; /* output: c will count trailing zero bits, */ uint32 maxbyte = pow(2,8) - 1; if (sketchsz_bits % (sizeof(uint32)*8)) elog( ERROR, "number of bits per sketch is %u, must be a multiple of sizeof(uint32) = %u", (uint32)sketchsz_bits, (uint32)sizeof(uint32)); if (sketchsz_bits > numsketches*8) elog(ERROR, "sketch sz declared at %u, but bitmap is only %u", (uint32)sketchsz_bits, (uint32)numsketches*8); /* * loop through the chunks of bits from left to right, counting ones. * stop when we hit a 0. */ for (i = 0; i < sketchsz_bits/(CHAR_BIT); i++) { uint32 v = (uint32) s[i]; if (v == maxbyte) c += CHAR_BIT /* * sizeof(uint32) */; else { /* * reverse and invert v, then do rightmost_one * magic reverse from http://graphics.stanford.edu/~seander/bithacks.html#ReverseByteWith32Bits */ uint8 b = ((s[i] * 0x0802LU & 0x22110LU) | (s[i] * 0x8020LU & 0x88440LU)) * 0x10101LU >> 16; v = (uint32) b ^ 0xff; c += ui_rightmost_one(v); break; /* we found a 1 in this value of i, so we stop looping here. */ } } return c; } /* * Given an array of n b-bit bitmaps, turn on the k'th most * significant bit of the j'th bitmap. * Both j and k are zero-indexed, BUT the bitmaps are indexed left-to-right, * whereas significant bits are (of course!) right-to-left within the bitmap. * * This function makes destructive updates; the caller should make sure to check * that we're being called in an agg context! * \param bitmap an array of FM sketches * \param numsketches # of sketches in the array * \param sketchsz_bits # of BITS per sketch * \param sketchnum index of the sketch to modify (from left, zero-indexed) * \param bitnum bit offset (from right, zero-indexed) in that sketch */ Datum array_set_bit_in_place(bytea *bitmap, int32 numsketches, int32 sketchsz_bits, int32 sketchnum, int32 bitnum) { char mask; char bytes_per_sketch = sketchsz_bits/CHAR_BIT; if (sketchnum >= numsketches || sketchnum < 0) elog(ERROR, "sketch offset exceeds the number of sketches (0-based)"); if (bitnum >= sketchsz_bits || bitnum < 0) elog( ERROR, "bit offset exceeds the number of bits per sketch (0-based)"); if (sketchsz_bits % sizeof(uint32)) elog( ERROR, "number of bits per sketch is %d, must be a multiple of sizeof(uint32) = %u", sketchsz_bits, (uint32)sizeof(uint32)); mask = 0x1 << bitnum%8; /* the bit to be modified within the proper byte (from the right) */ ((char *)(VARDATA(bitmap)))[sketchnum*bytes_per_sketch /* left boundary of the proper sketch */ + ( (bytes_per_sketch - 1) /* right boundary of the proper sketch */ - bitnum/CHAR_BIT /* the byte to be modified (from the right) */ ) ] |= mask; PG_RETURN_BYTEA_P(bitmap); } /*! * Simple linear function to find the rightmost one (# trailing zeros) in an uint32. * Based on * http://graphics.stanford.edu/~seander/bithacks.html#ZerosOnRightLinear * Look there for fancier ways to do this. * \param v an integer */ uint32 ui_rightmost_one(uint32 v) { uint32 c; v = (v ^ (v - 1)) >> 1; /* Set v's trailing 0s to 1s and zero rest */ for (c = 0; v; c++) { v >>= 1; } return c; } /*! * the postgres internal md5 routine only provides public access to text output * here we convert that text (in hex notation) back into bytes. * postgres hex output has two hex characters for each 8-bit byte. * so the output of this will be exactly half as many bytes as the input. * \param hex a string encoding bytes in hex * \param bytes out-value that will hold binary version of hex * \param hexlen the length of the hex string */ void hex_to_bytes(char *hex, uint8 *bytes, size_t hexlen) { uint32 i; for (i = 0; i < hexlen; i+=2) /* +2 to consume 2 hex characters each time */ { char c1 = hex[i]; /* high-order bits */ char c2 = hex[i+1]; /* low-order bits */ int b1 = 0, b2 = 0; if (isdigit(c1)) b1 = c1 - '0'; else if (c1 >= 'A' && c1 <= 'F') b1 = c1 - 'A' + 10; else if (c1 >= 'a' && c1 <= 'f') b1 = c1 - 'a' + 10; if (isdigit(c2)) b2 = c2 - '0'; else if (c2 >= 'A' && c2 <= 'F') b2 = c2 - 'A' + 10; else if (c2 >= 'a' && c2 <= 'f') b2 = c2 - 'a' + 10; bytes[i/2] = b1*16 + b2; /* i/2 because our for loop is incrementing by 2 */ } } /*! debugging utility to output strings in binary */ void bit_print(uint8 *c, int numbytes) { int j, i, l; char p[MD5_HASHLEN_BITS+2]; uint32 n; for (j = 0, l=0; j < numbytes; j++) { n = (uint32)c[j]; i = 1<<(CHAR_BIT - 1); while (i > 0) { if (n & i) p[l++] = '1'; else p[l++] = '0'; i >>= 1; } p[l] = '\0'; } elog(NOTICE, "bitmap: %s", p); } /*! * Run the datum through an md5 hash. No need to special-case variable-length types, * we'll just hash their length header too. * The POSTGRES code for md5 returns a bytea with a textual representation of the * md5 result. We then convert it back into binary. * \param dat a Postgres Datum * \param typOid Postgres type Oid * \returns a bytea containing the hashed bytes */ bytea *sketch_md5_bytea(Datum dat, Oid typOid) { // according to postgres' libpq/md5.c, need 33 bytes to hold // null-terminated md5 string char outbuf[MD5_HASHLEN*2+1]; bytea *out = palloc0(MD5_HASHLEN+VARHDRSZ); bool byval = get_typbyval(typOid); int len = ExtractDatumLen(dat, get_typlen(typOid), byval, -1); void *datp = DatumExtractPointer(dat, byval); /* * it's very common to be hashing 0 for countmin sketches. Rather than * hard-code it here, we cache on first lookup. In future a bigger cache here * would be nice. */ static bool zero_cached = false; static char md5_of_0_mem[MD5_HASHLEN+VARHDRSZ]; static bytea *md5_of_0 = (bytea *) &md5_of_0_mem; if (byval && len == sizeof(int64) && *(int64 *)datp == 0 && zero_cached) { return md5_of_0; } else pg_md5_hash(datp, len, outbuf); hex_to_bytes(outbuf, (uint8 *)VARDATA(out), MD5_HASHLEN*2); SET_VARSIZE(out, MD5_HASHLEN+VARHDRSZ); if (byval && len == sizeof(int64) && *(int64 *)datp == 0 && !zero_cached) { zero_cached = true; memcpy(md5_of_0, out, MD5_HASHLEN+VARHDRSZ); } return out; } /* TEST ROUTINES */ PG_FUNCTION_INFO_V1(sketch_array_set_bit_in_place); Datum sketch_array_set_bit_in_place(PG_FUNCTION_ARGS); PG_FUNCTION_INFO_V1(sketch_rightmost_one); Datum sketch_rightmost_one(PG_FUNCTION_ARGS); PG_FUNCTION_INFO_V1(sketch_leftmost_zero); Datum sketch_leftmost_zero(PG_FUNCTION_ARGS); #if defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)) /* * Unfortunately, the VARSIZE_ANY_EXHDR macro produces a warning because of the * way type promotion and artihmetic conversions works in C99. See §6.1.3.8 of * the C99 standard. */ #pragma GCC diagnostic push #endif #pragma GCC diagnostic ignored "-Wsign-compare" Datum sketch_rightmost_one(PG_FUNCTION_ARGS) { bytea *bitmap = (bytea *)PG_GETARG_BYTEA_P(0); size_t sketchsz = PG_GETARG_INT32(1); /* size in bits */ size_t sketchnum = PG_GETARG_INT32(2); /* from the left! */ char * bits = VARDATA(bitmap); size_t len = (size_t)(VARSIZE_ANY_EXHDR(bitmap)); return rightmost_one((uint8 *)bits, len, sketchsz, sketchnum); } Datum sketch_leftmost_zero(PG_FUNCTION_ARGS) { bytea *bitmap = (bytea *)PG_GETARG_BYTEA_P(0); size_t sketchsz = PG_GETARG_INT32(1); /* size in bits */ size_t sketchnum = PG_GETARG_INT32(2); /* from the left! */ char * bits = VARDATA(bitmap); size_t len = (size_t)(VARSIZE_ANY_EXHDR(bitmap)); return leftmost_zero((uint8 *)bits, len, sketchsz, sketchnum); } #if defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)) #pragma GCC diagnostic pop #endif Datum sketch_array_set_bit_in_place(PG_FUNCTION_ARGS) { bytea *bitmap = (bytea *)PG_GETARG_BYTEA_P(0); int32 numsketches = PG_GETARG_INT32(1); int32 sketchsz = PG_GETARG_INT32(2); /* size in bits */ int32 sketchnum = PG_GETARG_INT32(3); /* from the left! */ int32 bitnum = PG_GETARG_INT32(4); /* from the right! */ return array_set_bit_in_place(bitmap, numsketches, sketchsz, sketchnum, bitnum); } /* In some cases with large numbers, log2 seems to round up incorrectly. */ int32 safe_log2(int64 x) { int32 out = trunc(log2(x)); while ((((int64)1) << out) > x) out--; return out; } /* * We need process c string and var especially here, it is really ugly, * but we have to. * Because here the user can change the binary representations directly. */ size_t ExtractDatumLen(Datum x, int len, bool byVal, size_t capacity) { (void) byVal; /* avoid warning about unused parameter */ size_t size = 0; size_t idx = 0; char *data = NULL; if (len > 0) { size = len; if (capacity != (size_t)-1 && size > capacity) { elog(ERROR, "invalid transition state"); } } else if (len == -1) { if (capacity == (size_t)-1) { size = VARSIZE_ANY(DatumGetPointer(x)); } else { data = (char*)DatumGetPointer(x); if ((capacity >= VARHDRSZ) || (capacity >= 1 && VARATT_IS_1B(data))) { size = VARSIZE_ANY(data); } else { elog(ERROR, "invalid transition state"); } } } else if (len == -2) { if (capacity == (size_t)-1) { return strlen((char *)DatumGetPointer(x)) + 1; } else { data = (char*)DatumGetPointer(x); size = 0; for (idx = 0; idx < capacity && data[idx] != 0; idx ++, size ++) { } if (idx >= capacity) { elog(ERROR, "invalid transition state"); } size ++; } } else { elog(ERROR, "Datum typelength error in ExtractDatumLen: len is %u", (unsigned)len); return 0; } return size; } /* * walk an array of int64s and convert word order of int64s to big-endian * if force == true, convert even if this arch is big-endian */ void int64_big_endianize(uint64 *bytes64, uint32 numbytes, bool force) { uint32 i; uint32 *bytes32 = (uint32 *)bytes64; uint32 x; uint32 total = 0; #ifdef WORDS_BIGENDIAN bool small_endian = false; #else bool small_endian = true; #endif if (numbytes % 8) elog(ERROR, "illegal numbytes argument to big_endianize: not a multiple of 8"); if (small_endian || force) { for (i = 0; i < numbytes/8; i+=2) { x = bytes32[i]; bytes32[i] = bytes32[i+1]; bytes32[i+1] = x; total++; } } }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #define N 20000 void find_fruit(char input[],char fruit[][15]); int main(void) { char fruit[20][15] = { "guava", "litchi", "longan", "watermelon", "pomelo", "pear", "banana", "papaya", "pumpkin", "tomato", "mango", "kiwi", "persimmon", "cantaloupe", "strawberry", "grape", "peach", "orange", "coconut", "lemon" }; char input[N]; scanf("%s", input); find_fruit(input,fruit); return 0; } void find_fruit(char input[],char fruit[][15]){ // input is the fruit sequence eg: watermelon+_+watermelon+_+coconut+_+grape+_+coconut // fruit is 20 kinds of fruit name eg: fruit[0] is "guava", fruit[1] is litchi and so on. // you need to check the Loader code to understand above meaning int time[20]={0}; char *p=input; int i; char element[15]; while(*p!='\0') { i=0; memset(element,'\0',15); while (*p != '+'&&*p!='\0') { element[i++] = *p; p++; } // printf("%s ",element); for(int i=0;i<20;++i){ if(strcmp(fruit[i],element)==0){ time[i]++; // printf("time%d ",time[i]); } } p+=3; element[i] = '\0'; } int max=0; for(int i=0;i<20;i++){ if(time[i]>max) max=time[i]; } // printf("%d",max); for(int i=0;i<20;i++){ if(time[i]==max){ printf("%s\n",fruit[i]); } } }
C
/* * critical.c * * Created on: 2014-03-02 * Author: Jonah */ #include "critical.h" #include "basicmath.h" #include "qsort_small.h" #include <altera_avalon_pio_regs.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include "qsort_large.h" void write_led(int count) { IOWR_ALTERA_AVALON_PIO_DATA(0x10, count); } void critical_task(int priority) { // /* should get 3 solutions: 2, 6 & 2.5 */ fprint_enable_task(priority); basicmath_small(); // bitcnts(); // qsort_small(); // write_led(0xF); fprint_disable_task(priority); } void preempt_task(void* args){ int priority = *(int*)args; fprint_enable_task(priority); basicmath_small(); fprint_disable_task(priority); } void qsort_test(void* args){ QsortTestArgs* a = (QsortTestArgs*)args; fprint_enable_task(a->priority); qsort_large(a->vectors,a->size); fprint_disable_task(a->priority); } void testing_task(void* args) { int* a = (int*)args; int id = a[0]; args++; int length = a[1]; args++; int enable = a[2]; int i; //printf("Setup: id = %d, len = %d, fp_en = %d\n", id, length, enable); //if(enable) fprint_enable_task(id); for(i=0 ; i<length ; i++) basicmath_small(); //if(enable) fprint_disable_task(id); }
C
/* Takes a number and generates a factor tree */ #define _CRT_SECURE_NO_WARNINGS #include "PeggyUtil.h" #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <Windows.h> #define CON_BUFFER_SIZE 100 /* Struct defs */ typedef struct AFactor AFactor; struct AFactor { int number; bool hasFactors; AFactor* factor1; AFactor* factor2; }; /* Function defs */ // Frees a factor and it's daughter factors void freeAFactor(AFactor* factor); // Takes a factor and creates daughter factors until it hits a prime bool calculateFactors(AFactor* rootFactor); // Returns if a number is prime bool isPrime(int n); // Writes a tree to a file in a nice nested fashion void writeTreeToFile(const char* path, AFactor* rootFactor); // Write a factor to a file stream at the nested level and write it's daughters recursively void writeAFactor(FILE* file, AFactor* factor, int nestLevel); int main() { char conBuffer[CON_BUFFER_SIZE]; int gotChars = 0; int number = 0; while (true) { clearScreen(); printf("Enter a number to generate a tree (type 'quit' to exit):\n> "); gotChars = getConsoleLine(conBuffer, CON_BUFFER_SIZE); if (gotChars <= 0) { printf("Failed to get a valid input\n"); continue; } if (strcmp(conBuffer, "quit") == 0) { exit(EXIT_SUCCESS); } number = atoi(conBuffer); if (number < 0) { printf("This program only accepts positive integers\n"); continue; } if (number == 0) { // Factors are only 0 } else if (number == 1) { // Factors are only 1 } else { // Create the root factor AFactor* rootFactor = malloc(sizeof(AFactor)); if (rootFactor == NULL) { perror("Failed to allocate memory for root factor!"); continue; } rootFactor->number = number; bool success = calculateFactors(rootFactor); if (!success) { freeAFactor(rootFactor); printf("\n\nFAILED TO FIND FACTORS\n"); continue; } printf("1 = %i\n", number); printf("\nDo you wish to write the factor tree to file? (y/n)\n> "); gotChars = getConsoleLine(conBuffer, CON_BUFFER_SIZE); if (strcmp(conBuffer, "y") == 0) { printf("Enter the file path:\n> "); gotChars = getConsoleLine(conBuffer, CON_BUFFER_SIZE); // Write to file writeTreeToFile(conBuffer, rootFactor); } // Finally, free the factor freeAFactor(rootFactor); rootFactor = NULL; } } } bool calculateFactors(AFactor* rootFactor) { int factor1Num = 0; int factor2Num = 0; rootFactor->hasFactors = false; if (isPrime(rootFactor->number)) { // This factor is prime and thus we should not investigate it any more printf("%i x ", rootFactor->number); return true; }else // Test for 2 division if (rootFactor->number % 2 == 0) { // Is divisible by two, set the factors and continue down the tree rootFactor->hasFactors = true; // Factor 1 factor1Num = 2; factor2Num = rootFactor->number / 2; } else { for (int i = 3; i < rootFactor->number / 2; i++) { if (rootFactor->number % i == 0) { // We found our factors rootFactor->hasFactors = true; factor1Num = i; factor2Num = rootFactor->number / i; break; } } } // Create the lower factors if (rootFactor->hasFactors) { //printf(" - Number %i has factors %i and %i\n", rootFactor->number, factor1Num, factor2Num); // Create factor 1 rootFactor->factor1 = malloc(sizeof(AFactor)); if (rootFactor->factor1 == NULL) { // Failed to create factor, crash perror("Failed to create factor1 memory"); return false; } // Factor is okay, go forth rootFactor->factor1->number = factor1Num; if(!calculateFactors(rootFactor->factor1)) return false; // Create factor 2 rootFactor->factor2 = malloc(sizeof(AFactor)); if (rootFactor->factor2 == NULL) { // Failed to create factor, crash perror("Failed to create factor2 memory"); return false; } // Factor is okay, go forth rootFactor->factor2->number = factor2Num; if (!calculateFactors(rootFactor->factor2)) return false; } // Give a success value return true; } bool isPrime(int n) { if (n == 1) { // We'll treat 1 as a prime for this purpose return true; } bool flag = true; for (int i = 2; i <= n / 2; i++) { // condition for nonprime number if (n % i == 0) { flag = false; break; } } return flag; } void writeTreeToFile(const char* path, AFactor* rootFactor) { FILE* file; file = fopen(path, "w"); if (file == NULL) { perror("Failed to open file"); return; } // Write to the file writeAFactor(file, rootFactor, 0); fclose(file); } void writeAFactor(FILE* file, AFactor* factor, int nestLevel) { // Write the indentation for (int i = 0; i < nestLevel; i++) { fprintf(file, " "); } fprintf(file, "-> %i\n", factor->number); if (factor->hasFactors) { writeAFactor(file, factor->factor1, nestLevel + 1); writeAFactor(file, factor->factor2, nestLevel + 1); } } void freeAFactor(AFactor* factor) { if (factor->hasFactors) { // Free the lower factors accordingly freeAFactor(factor->factor1); factor->factor1 = NULL; freeAFactor(factor->factor2); factor->factor2 = NULL; } // Free this factor from memory free(factor); }
C
#include<stdio.h> #include<stdlib.h> #include<string.h> #include<time.h> /* * Lucas Melo e Mayko de Oliveira * * Programa de ordenao MergeSort * O vetor de elementos divido em pares de elementos e ento os pares so * ordenados, depois so agrupados de dois em dois pares e ento os valores do * grupo so ordenados. O processo de agrupamento ocorre at voltar ao tamanho do * vetor original e nesse ponto o vetor j estar ordenado. * */ /* * Realiza o merge (Conquista) */ void merge(int a[], int menor, int maior, int meio){ int i, j, k, c[maior]; i=menor; j=meio+1; k=menor; //Verifica se o piv i menor ou igual que o meio, e se o piv j menor ou igual ao tamanho maximo do vetor (maior) while((i<=meio)&&(j<=maior)){ if(a[i]<a[j]){ c[k]=a[i]; k++; i++; }else{ c[k]=a[j]; k++; j++; } } while(i<=meio){ c[k]=a[i]; k++; i++; } while(j<=maior){ c[k]=a[j]; k++; j++; } for(i=menor;i<k;i++){ a[i]=c[i]; } } /* * Merge Sort * Divide o vetor em pequenos subvetores (Diviso) */ void mergeSort(int a[], int menor, int maior){ int meio; if(menor<maior){ meio=(menor+maior)/2; mergeSort(a,menor,meio); mergeSort(a,meio+1,maior); merge(a,menor,maior,meio); } } /* * Funo de inicializao * argv[0] - Nome do arquivo atual (padro, no precisa explicitar) * argv[1] - Nome do arquivo de entrada */ int main(int argc, char *argv[]){ //Verifica se foi passado um nome de arquivo como parmetro if(argv[1] == NULL){ printf("\nFavor informar o nome do arquivo como primeiro argumento.\n"); exit(1); } FILE* fp; int* vetor; int tam, j; clock_t ini, fim; double tempo; //Abre o arquivo que foi passado por parmetro fp = fopen(argv[1],"r"); //Verifica se foi possvel abrir o arquivo if(fp == NULL){ printf("\nNome do arquivo '%s' invlido.\nVerifique se o arquivo existe na mesma pasta do executvel.\n", argv[1]); exit(1); } tam = 0; int aux = 0; while( (fscanf(fp, "%d", &aux)) != EOF ){ tam++; } //printf("%d \n", tam); //Fecha o arquivo fclose(fp); //Cria um vetor de tamanho dinmico vetor = (int*)malloc(tam*sizeof(int)); //Abre o arquivo que foi passado como argumento fp = fopen(argv[1],"r"); //L os dados do arquivo e insere no vetor for(j=0; j < tam; j++){ fscanf(fp, "%d ", &vetor[j]); } //Fecha o arquivo fclose(fp); //Clculo do tempo em Milisegundos ini = clock(); mergeSort(vetor, 0, tam-1); fim = clock(); tempo = ( (double) (fim - ini) ) / CLOCKS_PER_SEC; //Imprime o vetor ordenado for(j=0; j < tam; j++){ printf("%d ", vetor[j]); } //Imprime o tempo de execuo do merge printf("\n%5.2lfms\n",tempo); //Libera o vetor free(vetor); }
C
#include <stdio.h> #include <stdlib.h> #include <math.h> double calc(double x, double y, double z) { int n0=1; int n1=1; if ((n0+1)*abs(x+y)==0) {return NAN;}; if (z==0) {return NAN;}; if ((y-x)==0) {return NAN;}; if ((y-x)<0&&((1/z)-(int)(1/z))!=0) {return NAN;}; if (x<0&&((y+1)-(int)(y+1))!=0) {return NAN;}; if (sin(x)+1==0) {return NAN;}; if (pow((y-x),(1/z))==0) {return NAN;}; double a1 = (y/(n0+1)*abs(x+y)); double a2 = pow(abs(cos(y)/sin(x)+1),1/2); double a0 = (pow(x,(y+1))/pow((y-x),(1/z))); double a = a0 + a1 + a2; return a; } double main() { double x; double y; double z; printf("Enter x = "); scanf("%lf",&x); printf("Enter y = "); scanf("%lf",&y); printf("Enter z = "); scanf("%lf",&z); double r=calc(x,y,z); printf("%lf",r); return 0; }
C
#include "func.h" Queue *head1 = NULL, *tail1 = NULL, *head2 = NULL, *tail2 = NULL; List *head = NULL, *tail = NULL; /* ( )*/ void Enqueue(int queue_num, int amount, int *arr) { Queue *head, *tail; /* */ int i; Queue* p; /* */ if (queue_num == 1) { head = head1; tail = tail1; } if (queue_num == 2) { head = head2; tail = tail2; } for (i = 0; i < amount; i++) { p = (Queue *)malloc(sizeof(Queue)); p->data = arr[i]; p->next = NULL; /* */ if (head == NULL) /* ... */ head = p; /*head */ else tail->next = p; /* . */ tail = p; /* tail */ } /* . 1 2 */ if (queue_num == 1) { head1 = head; tail1 = tail; } if (queue_num == 2) { head2 = head; tail2 = tail; } } /* */ void Display_Queue(int queue_num) { Queue* p; /* */ if (queue_num == 1) p = head1; if (queue_num == 2) p = head2; if (p == NULL) printf("Queue is empty"); else printf("Queue %d:", queue_num); while (p != NULL) { printf("\n%d", p->data); p = p->next; } } /* */ void List_of_2_queues(int amount1, int amount2) { List_of_queue(amount1, 1); List_of_queue(amount2, 2); } /* 1 */ void List_of_queue(int amount, int queue_num) { List *p, *cur = head; Queue *p1; int i; /* */ if (queue_num == 1) p1 = head1; if (queue_num == 2) p1 = head2; for (i = 0; i < amount; i++) { p = (List *)malloc(sizeof(List)); p->data = p1->data; p->next = p->prev = NULL; if (head == NULL) /* */ { head = tail = p; /* head tail */ } else { /* */ while (cur != NULL && p1->data > cur->data) cur = cur->next; if (cur == head) /* */ { p->next = head; head->prev = p; head = p; } else if (cur == NULL) /* */ { tail->next = p; p->prev = tail; tail = p; } else /* */ { cur->prev->next = p; p->prev = cur->prev; cur->prev = p; p->next = cur; } } p1 = p1->next; } } /* */ void Display_List(void) { List *p = head; if (p == NULL) puts("List is empty"); else { printf("List:\n"); printf("NULL <-> "); while (p != NULL) { printf("%d <-> ", p->data); p = p->next; } printf("NULL"); } }
C
#include <stdio.h> #include <ctype.h> int main() { int c, i, sum; sum = 0; while ((c=getchar()) != EOF) { if (c == '\n') putchar(c); else if (c == '!') putchar('\n'); else if (isdigit(c)) sum += (c-'0'); else { for (i=0; i<sum; i++) { if (c == 'b') putchar (' '); else putchar(c); } sum = 0; } } return 0; }
C
#include <netdb.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/socket.h> #include <stdio.h> #include <sys/socket.h> #include <arpa/inet.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <signal.h> #include <netinet/in.h> #include <sys/time.h> #include <errno.h> volatile sig_atomic_t alarm_flag = 0; static void print_console (const char *s) { size_t len = 0; while (*s++){ len++; } write (STDOUT_FILENO, s, strlen(s)); } void handle_alarm( int sig ) { alarm_flag = 1; } void send_message(int sockfd()){ char buff[50]; int n; while ((buff[n++] = getchar()) != '\n') ; write(sockfd, buff, sizeof(buff)); } int char_to_int_4(char c[]){ int res = 0,temp = 0; for(int i = 0; i <= 3; i++){ temp = c[i] - '0'; res = res *10 + temp; } return res; } void error(char *errorMessage){ printf("%s\n",errorMessage); }; int main(int argc, char *argv[]) { fd_set fds; FD_ZERO(&fds); int max_fd = 0,nobat = 0; //print_console("salam\n"); int PORT = atoi(argv[1]),port = 0; int sockfd, connfd; struct sockaddr_in servaddr, cli; int max_player = 0; int max_size_string = 100; signal( SIGALRM, handle_alarm ); // socket create and varification sockfd = socket(AF_INET, SOCK_STREAM, 0); if (sockfd == -1) { printf("socket creation failed...\n"); exit(0); } else printf("Socket successfully created..\n"); bzero(&servaddr, sizeof(servaddr)); // assign IP, PORT servaddr.sin_family = AF_INET; servaddr.sin_addr.s_addr = inet_addr("127.0.0.1"); servaddr.sin_port = htons(PORT); // connect the client socket to server socket if (connect(sockfd, (struct sockaddr*)&servaddr, sizeof(servaddr)) != 0) { printf("connection with the server failed...\n"); exit(0); } else printf("connected to the server..\n"); // function for chat int sel = 0; FD_SET(sockfd, &fds); max_fd = sockfd; char projName[5][20] = { "Super Mario\n", "Maze\n", "Ping Pong\n", "TIC TAC TOE\n", "Snakes\n" }; int i,j; for(j = 0; j < 5; j++){ printf("%d - ",j+1); for(i = 0; projName[j][i] != '\0'; i++) { printf("%c",projName[j][i]); } } printf("Which Project do you prefer???\n"); int n = 0; char buff[50]; FD_SET(STDIN_FILENO, &fds); if(STDIN_FILENO > max_fd)max_fd = STDIN_FILENO; while(1){ sel = select(max_fd + 1, &fds, NULL, NULL, NULL); if(FD_ISSET(STDIN_FILENO, &fds)){ while ((buff[n++] = getchar()) != '\n') ; printf("%s\n",buff); write(sockfd, buff, sizeof(buff)); max_player = buff[0] - '0'; printf("You Choosed Project Number %d.\n",max_player); bzero(buff, sizeof(buff)); break; } } FD_ZERO(&fds); FD_SET(sockfd, &fds); max_fd = sockfd; while (1){ sel = select(max_fd + 1, &fds, NULL, NULL, NULL); if(FD_ISSET(sockfd, &fds)){ read(sockfd, buff, sizeof(buff)); printf("port: %s\n",buff); port = char_to_int_4(buff); printf("port : %d\n",port); break; } } sleep(1); while(1){ sel = select(max_fd + 1, &fds, NULL, NULL, NULL); if(FD_ISSET(sockfd, &fds)){ read(sockfd, buff, sizeof(buff)); nobat = buff[0] - '0'; printf("nobat: %d\n",nobat); break; } } int player_score[max_player]; sleep(1); printf("___________START____________\n"); for(int i = 0; i < max_player; i++){ player_score[i] = 0; } char recvString[max_size_string+1]; int recvStringLen; int new_sock; struct sockaddr_in broadcastAddr; char *broadcastIP; unsigned short broadcastPort; int broadcastPermission,reuse; memset(&broadcastAddr, 0, sizeof(broadcastAddr)); if ((new_sock = socket(AF_INET, SOCK_DGRAM, 0)) < 0) error("socket() failed"); broadcastPermission = 1; reuse = 1; if (setsockopt(new_sock, SOL_SOCKET, SO_BROADCAST,(void*) &broadcastPermission, sizeof(broadcastPermission)) < 0) error("setsockopt() failed"); if (setsockopt(new_sock, SOL_SOCKET, SO_REUSEADDR,(void*) &reuse, sizeof(reuse)) < 0) error("setsockopt() failed"); max_fd = new_sock; FD_SET(max_fd, &fds); broadcastAddr.sin_family = AF_INET; broadcastAddr.sin_addr.s_addr = inet_addr("127.255.255.255"); broadcastAddr.sin_port = htons(port); if (bind(new_sock, (const struct sockaddr *)&broadcastAddr, sizeof(broadcastAddr)) < 0)error("bind() failed"); char* str = argv[1]; char x,y,jahat; alarm_flag = 0; int tedad = 0; while (tedad < 5) { if(tedad % max_player == nobat){ alarm(10); char send_str[] = "x\n"; printf("its your turn:\n"); FD_ZERO(&fds); FD_SET(new_sock, &fds); max_fd = new_sock; sel = 0; while(1){ FD_SET(STDIN_FILENO, &fds); if(STDIN_FILENO > max_fd)max_fd = STDIN_FILENO; sel = select(max_fd + 1, &fds, NULL, NULL, NULL); if(alarm_flag == 1 || sel == -1){ send_str[0] = '999999'; printf("%s",send_str); sendto(new_sock, send_str, strlen(send_str), 0,(struct sockaddr *) &broadcastAddr, sizeof(broadcastAddr)); printf("your time end!!!!\n"); alarm_flag = 0; break; } else if(FD_ISSET(STDIN_FILENO, &fds)){ n = 0; while ((send_str[n++] = getchar()) != '\n'); sendto(new_sock, send_str, strlen(send_str), 0,(struct sockaddr *) &broadcastAddr, sizeof(broadcastAddr)); printf("%s\n",send_str); alarm(0); break; } } } while (1) { sel = select(max_fd + 1, &fds, NULL, NULL, NULL); if(FD_ISSET(new_sock, &fds)){ if ((recvStringLen = recvfrom(new_sock, recvString, max_size_string, 0, NULL, 0)) < 0) error("recvfrom() failed"); recvString[recvStringLen] = '\0'; printf("Received: %s\n", recvString); sleep(1); x = recvString[0]; player_score[tedad] = x; tedad ++; break; } } } int winer = 0; for(int temp = 0; temp < max_player; temp++){ if(player_score[temp] > player_score[winer])winer = temp; } printf("player %d win!!!\n",winer); // close the socket close(sockfd); }
C
#include <stdlib.h> #include <stdio.h> #include <string.h> #include "seed.h" #include "template.h" #include "debug.h" static template_t *template = NULL; typedef struct SP_entry { char entity[128]; char date[64]; char to[16]; char from[16]; char action[16]; char type[16]; #define SP_ENTRY_NEW 0x1 int flag; } SP_entry_t; /* * 1. Find "tabContent2" * 2. Find "Entity name" * 3. Find "<tbody> * 4. Find "<tr> * 5. Find "<td>" - Entity * 6. Find "<td>" - Date * 7. Find "<td>" - To * 8. Find "<td>" - From * 9. Find "<td>" - Action *10. Find "<td>" - Type */ #define TABCONTENT2 "tabContent2" #define ENTITYNAME "Entity Name" #define TBODYSTART "<tbody>" #define TBODYEND "</tbody>" static char *get_tbody_start(const char *buf, int len) { char *p; p = strstr(buf,TABCONTENT2); if (!p) { debug(1,"Cannot find %s\n",TABCONTENT2); return NULL; } p = strstr(p,ENTITYNAME); if (!p) { debug(1,"Cannot find %s\n",ENTITYNAME); return NULL; } p = strstr(p,TBODYSTART); if (!p) { debug(1,"Cannot find %s\n",TBODYSTART); return NULL; } return p; } static char *get_tbody_end(char *start) { char *p = NULL; p = strstr(start,TBODYEND); return p; } static int get_entry_num(char *start, char *end) { char *p = start; char *q; int ret = 0; while ( (q = strstr(p,"<tr>")) && (q < end)) { p = q + 4; ret++; } debug(8,"enter %s: start %p, end %p, num %d\n",__FUNCTION__,start,end,ret-1); return (ret - 1); } static void extract_data(const char *start, const char *end, char *data) { int i = 0; char *p = (char *)start; debug(8,"enter %s\n",__FUNCTION__); while (p < end) { if ( *p == '<') { p = strstr(p,">"); } else if ( *p == '\r') { ; } else if ( *p == '\n') { ; } else if ( *p == '\t') { ; } else { if ( (*p == ' ') && ((*(p+1) == ' ') || !i)) { ; } else { data[i] = *p; i++; } } p++; } data[i] = 0; debug(6,"extract data: %s\n",data); return; } static char *get_sp_entry(char *start, SP_entry_t *entry) { char *tr_start; char *tr_end; char *td_start; char *td_end; if (!start || !entry) return NULL; tr_start = strstr(start,"<tr>"); tr_end = strstr(start,"</tr>"); td_end = tr_start + 4; td_start = strstr(td_end,"<td"); if ( !td_start || (td_start > tr_end)) return NULL; td_start = strstr(td_start,">"); td_start++; td_end = strstr(td_start,"</td>"); extract_data(td_start, td_end, entry->entity); td_start = strstr(td_end,"<td"); if ( !td_start || (td_start > tr_end)) return NULL; td_start = strstr(td_start,">"); td_start++; td_end = strstr(td_start,"</td>"); extract_data(td_start, td_end, entry->date); td_start = strstr(td_end,"<td"); if ( !td_start || (td_start > tr_end)) return NULL; td_start = strstr(td_start,">"); td_start++; td_end = strstr(td_start,"</td>"); extract_data(td_start, td_end, entry->to); td_start = strstr(td_end,"<td"); if ( !td_start || (td_start > tr_end)) return NULL; td_start = strstr(td_start,">"); td_start++; td_end = strstr(td_start,"</td>"); extract_data(td_start, td_end, entry->from); td_start = strstr(td_end,"<td"); if ( !td_start || (td_start > tr_end)) return NULL; td_start = strstr(td_start,">"); td_start++; td_end = strstr(td_start,"</td>"); extract_data(td_start, td_end, entry->action); td_start = strstr(td_end,"<td"); if ( !td_start || (td_start > tr_end)) return NULL; td_start = strstr(td_start,">"); td_start++; td_end = strstr(td_start,"</td>"); extract_data(td_start, td_end, entry->type); return tr_end+5; } static void *parser(const char *buf, int len, void *seed) { char *tbody_start; char *tbody_end; char *p; int num = 0, i; TP_header_t *hdr = NULL; SP_entry_t *entry = NULL; debug(8,"enter %s\n",__FUNCTION__); tbody_start = get_tbody_start(buf,len); if (!tbody_start) { debug(1,"Cannot find tobody start\n"); return NULL; } tbody_end = get_tbody_end(tbody_start); if (!tbody_end) { debug(1,"Cannot find tobody end\n"); return NULL; } num = get_entry_num(tbody_start,tbody_end); if (num <= 0) { debug(1,"Cannot find entry\n"); return NULL; } hdr = (TP_header_t *)malloc(sizeof(TP_header_t)+ num * sizeof(SP_entry_t)); if (!hdr) { perror("Cannot alloc SP header and entry\n"); return NULL; } memset(hdr,0,sizeof(TP_header_t) + num * sizeof(SP_entry_t)); hdr->number = num; entry = (SP_entry_t *)hdr->data; p = tbody_start; for (i=0; i<num; i++) { p = get_sp_entry(p, &entry[i]); if (!p) break; } return hdr; } static void dump_entry(TP_header_t *hdr) { SP_entry_t *ep; int i; if (!hdr) return; ep = (SP_entry_t *)hdr->data; for (i=0; i<hdr->number; i++) { printf("<%d>: %s,%s,%s->%s,%s,%s\n",i,ep[i].entity,ep[i].date,ep[i].from,ep[i].to,ep[i].action,ep[i].type); } } static void *filter(void *data, void *s) { seed_t *seed = s; TP_header_t *old; TP_header_t *new; SP_entry_t *np; SP_entry_t *op; int i,j,match,debug = 0; if (!data) return NULL; if (!seed->private) { seed->private = data; return NULL; } old = (TP_header_t *)seed->private; new = (TP_header_t *)data; np = (SP_entry_t *)new->data; for (i=0; i< new->number; i++) { op = (SP_entry_t *)old->data; match = 0; for (j=0; j<old->number; j++) { if ( !memcmp(np->entity, op->entity, strlen(np->entity)) && !memcmp(np->date, op->date, strlen(np->date)) && !memcmp(np->to, op->to, strlen(np->to)) && !memcmp(np->from, op->from, strlen(np->from)) && !memcmp(np->action, op->action, strlen(np->action)) && !memcmp(np->type, op->type, strlen(np->type)) ) { match = 1; break; } op++; } if (!match && strstr(np->action,"Revised") && strstr(np->type,"Foreign")) { np->flag |= SP_ENTRY_NEW; debug = 1; } np++; } if (debug) { dump_entry(old); dump_entry(new); } free(seed->private); seed->private = data; return data; } static void notifier(void *data, void *s) { seed_t *seed = (seed_t *)s; TP_header_t *hdr; SP_entry_t *ep; int i, num = 0; char *buf; char *p; if (!data) return; debug(8,"enter %s: data %p\n",__FUNCTION__,data); hdr = (TP_header_t *)data; ep = (SP_entry_t *)hdr->data; buf = (char *)calloc(1, hdr->number * (sizeof(SP_entry_t) + 32)); if (!buf) { perror("No mem to alloc buf for notifier"); return; } p = buf; for (i=0; i<hdr->number; i++) { if (!(ep[i].flag & SP_ENTRY_NEW)) continue; debug(6, "Find new data\n"); num = sprintf(p,"[%d]: %s, %s, %s->%s\n",i,ep[i].entity,ep[i].date,ep[i].from,ep[i].to); p += num; } *p = 0; if (p != buf && seed->mail) tp_send_mail(seed->mail, "jnpr", "SP News", buf); free(buf); return; } int SP_init(void) { template = calloc(1,sizeof(template_t)); if (!template) { perror("Alloc SP template failed"); return -1; } INIT_LIST_HEAD(&template->list); template->name[0] = 'S'; template->name[1] = 'P'; template->parser = parser; template->filter = filter; template->notifier = notifier; register_template(template); return 0; }
C
/* Copyright (c) 1987, 1989, 2012 University of Maryland Department of Computer Science. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation, the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice, this permission notice and the disclaimer statement shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /* * SeekFile copies an input stdio file, if necessary, so that * it produces a stdio file on which fseek() works properly. * It returns NULL if this cannot be done; in that case, the * input file is closed (or otherwise rendered worthless). * * CopyFile copies an input file unconditionally. (On non-Unix * machines, it might `accidentally' not copy it.) * * On Unix machines, this means `if the input is a pipe or tty, * copy it to a temporary file'. On other systems, all stdio files * might happen to be seekable. */ #ifdef HAVE_CONFIG_H #include <config.h> #endif #ifdef KPATHSEA #include <kpathsea/c-fopen.h> #endif #include <stdio.h> #include "types.h" /* for BSD_FILE_SYSTEM */ #include "seek.h" #include "tempfile.h" #include <errno.h> #ifdef BSD_FILE_SYSTEM #include <sys/param.h> /* want MAXBSIZE */ #else #include <sys/types.h> #endif #include <sys/stat.h> #ifndef KPATHSEA long lseek(); char *malloc(); extern int errno; #endif /* * Make and return a version of `f' on which fseek works (unconditionally). * This code is somewhat Unix-specific. */ FILE * CopyFile(FILE *f) { register int tf, n, ifd, w; register char *p, *buf; register int blksize; #ifdef BSD_FILE_SYSTEM struct stat st; #endif int e; #ifdef MAXBSIZE #define BSIZE MAXBSIZE #else #define BSIZE BUFSIZ #endif char stackbuf[BSIZE]; #if defined(WIN32) || defined(MSDOS) int orig_fdmode; #endif const char *open_mode; /* get a read/write temp file which will vanish when closed */ if ((tf = MakeRWTempFile(stackbuf)) < 0) { e = errno; (void) fclose(f); errno = e; return (NULL); } /* compute buffer size and choose buffer */ ifd = fileno(f); buf = stackbuf; blksize = sizeof stackbuf; #ifdef BSD_FILE_SYSTEM if (fstat(tf, &st) == 0 && st.st_blksize > blksize) { /* * The output block size is the important one, * but the input block size is not irrelevant. * * This should actually compute the lcm, but we * will rely on block sizes being powers of two * (so that the larger is the lcm). */ blksize = st.st_blksize; if (fstat(ifd, &st) == 0 && st.st_blksize > blksize) blksize = st.st_blksize; if ((buf = malloc((unsigned)blksize)) == NULL) { buf = stackbuf; blksize = sizeof stackbuf; } } #endif #if defined(WIN32) || defined(MSDOS) /* make sure we open the temp file in the same mode that the original handle was open. */ orig_fdmode = setmode(ifd, 0); setmode(tf, orig_fdmode); #endif /* copy from input file to temp file */ (void) lseek(ifd, 0L, 0); /* paranoia */ while ((n = read(ifd, p = buf, blksize)) > 0) { do { if ((w = write(tf, p, n)) < 0) { (void) close(tf); (void) fclose(f); return (NULL); } p += w; } while ((n -= w) > 0); } e = errno; /* in case n < 0 */ if (buf != stackbuf) free(buf); if (n < 0) { (void) close(tf); (void) fclose(f); errno = e; return (NULL); } /* discard the input file, and rewind and open the temporary */ (void) fclose(f); (void) lseek(tf, 0L, 0); errno = 0; #if defined(WIN32) || defined(MSDOS) open_mode = orig_fdmode == O_BINARY ? FOPEN_RBIN_MODE : "r"; #else open_mode = "r"; #endif if ((f = fdopen(tf, open_mode)) == NULL) { if (errno == 0) e = EMFILE; (void) close(tf); errno = e; } return (f); } /* * Copy an input file, but only if necessary. */ FILE *SeekFile(FILE *f) { int fd = fileno(f); return (lseek(fd, 0L, 1) >= 0 && !isatty(fd) ? f : CopyFile(f)); }
C
#include "../../headers/global_header.h" /* Retourne un nouvel allié. */ Friend get_new_friend(Friend_Spawner *spawner, int posX, int posY) { Friend f; f.id_friend = spawner->id_friend; f.ability = spawner->ability; f.DELAY_ABILITY = spawner->DELAY_ABILITY; f.delay_ability = spawner->DELAY_ABILITY; f.life = spawner->life; f.attack = spawner->attack; f.range = spawner->range; f.posX = posX; f.posY = posY; f.animation_passive = MLV_create_animation_player(spawner->animation_passive); f.animation_ability = MLV_create_animation_player(spawner->animation_ability); set_friend_animation(&f, f.animation_passive); f.is_passive = true; return f; } /* Retourne vrai si le paramètre est un allié, faux sinon. */ bool is_friend(Friend *this) { return this->id_friend != -1; } /* Affecte une animation à un allié. */ void set_friend_animation(Friend *this, MLV_Animation_player *animation) { this->animation = animation; MLV_play_animation_player(this->animation); } /* Attaque tous les ennemies dans la range de l'allié. */ void attack_all_enemies_in_range(Friend *this, Row *row, Sound_Manager *SM, int *p1_score) { int i = 0; Enemy *e; play_sound(SM, &SM->spear); while (i<row->nb_enemies) { e = &row->enemies[i]; if (e->posX + e->padding < this->posX + this->range + row->rectsize && e->posX + e->padding + row->rectsize > this->posX) { e->life -= this->attack; if (e->life <= 0) { remove_enemy_from_row(row, i, SM, p1_score); i--; } } i++; } } /* Change le comportement de l'allié. */ void switch_friend_behavior(Friend *this) { if (this->is_passive) { set_friend_animation(this, this->animation_ability); this->delay_ability = this->DELAY_ABILITY; } else { set_friend_animation(this, this->animation_passive); } this->is_passive = !this->is_passive; } /* Utilise le pouvoir de l'allié */ void use_friend_ability(Friend *this, Row *row, Sound_Manager *SM, int *p1_score) { switch (this->ability) { case DEFENSE: attack_all_enemies_in_range(this, row, SM, p1_score); this->delay_ability = this->DELAY_ABILITY; break; case ATTACK: create_new_shot(row, this->posX/row->rectsize, this->posY/row->rectsize, this->attack, SM); this->delay_ability = this->DELAY_ABILITY; break; case MONEY: switch_friend_behavior(this); if (!this->is_passive) { create_new_gold(row, this->posX/row->rectsize, this->posY/row->rectsize, SM); this->delay_ability = 2000; } else { this->delay_ability = this->DELAY_ABILITY; } break; default: break; } } /* Met à jour l'allié. */ void update_friend(Friend *this, Row *row, Sound_Manager *SM, int *p1_score) { int i; bool enemy_in_range = false; if (this->ability == DEFENSE || this->ability == ATTACK) { for (i=0; i<row->nb_enemies; i++) { if (row->enemies[i].posX < this->posX) { continue; } if (row->enemies[i].posX < this->posX + this->range) { enemy_in_range = true; break; } } /* Si 'enemy_in_range && this->is_passive) || (!enemy_in_range && !this->is_passive) */ if (enemy_in_range ^ !this->is_passive) { switch_friend_behavior(this); } } if (this->ability == MONEY || !this->is_passive) { this->delay_ability -= DELAY_REFRESH; if (this->delay_ability <= 0) { use_friend_ability(this, row, SM, p1_score); } } MLV_update_animation_player(this->animation); } /* Recharge les animations de l'allié (utile pour le relancement des parties). */ void reset_friend_animations(Friend *this, Friend_Spawner *spawner) { this->animation_passive = MLV_create_animation_player(spawner->animation_passive); this->animation_ability = MLV_create_animation_player(spawner->animation_ability); if (this->is_passive) { set_friend_animation(this, this->animation_passive); } else { set_friend_animation(this, this->animation_ability); } }
C
// // Created by Sakura on 3/8/2021. // typedef struct { int day; int month; int year; }Date; typedef struct { char* type; char* destination; char* departure_date; Date detailed_date; double price; }Offer; Offer* create_offer(char*, char*, char*, double); Offer* copy_offer(Offer*); char* get_type_offer(Offer*); char* get_destination_offer(Offer*); char* get_departure_date_offer(Offer*); double get_price_offer(Offer*); int get_month_offer(Offer* offer); int get_day_offer(Offer* offer); int get_year_offer(Offer* offer); Date get_detailed_date(char* departure_date); void change_type(Offer *offer, char* new_type); void change_destination(Offer *offer, char* new_dest); void change_date(Offer *offer, char* new_date); void change_price(Offer *offer, double new_price); void destroy_offer(Offer*);
C
/** * @file ArrayBubbleSortStrategy.c * @brief Array Bubble Sort Strategy * @author Taro Hoshino * Copyright (C) 2017 Taro Hoshino. All Rights Reserved. */ #include "ArrayBubbleSortStrategy.h" #include "Array.h" /*************************** * Function ***************************/ /** * @fn array_bubble_sort_strategy_construct * @brief Constructor of the ArrayBubbleSortStrategy * @param sort_strtgy Array Bubble Sort Strategy * @return No return value * @details Constructor of the ArrayBubbleSortStrategy. */ void array_bubble_sort_strategy_construct( ArrayBubbleSortStrategy* sort_strtgy ) { sort_strategy_construct(&sort_strtgy->base, array_bubble_sort_strategy_sort); return; } /** * @fn array_bubble_sort_strategy_construct * @brief Array bubble sort * @param sort_strtgy Array Bubble Sort Strategy * @param collection Collection * @return No return value * @details Bubble Sort of Array. * It is necessary to set a comparison function in the array in advance. * By comparison functions, the contents of the array are arranged in ascending order. * The comparison function MUST return either an integer less than zero, * an integer greater than zero, or an integer greater than zero, depending on whether * the first argument is less than, equal to, or greater than the second argument. */ void array_bubble_sort_strategy_sort( void* sort_strtgy, void* const collection ) { Array* const array = (Array* const) collection; unsigned int i; unsigned int j; for (i = 0; i < array->max_size(array) - 1; i++) { for (j = array->max_size(array) - 1; i < j; j--) { if (0 < array->compare(array->comp_strtgy, array->iget(array, j - 1), array->iget(array, j))) { array->swap_index(array, j - 1, j); } } } return; }
C
/* ============================================================================ Name : INFO1MI2020_labo4.c Author : E.ZYSMAN Version : 1 Copyright : Your copyright notice Description : JOUER AUX DéS in C, Ansi-style ============================================================================ */ #include <stdio.h> #include <stdlib.h> void viderBuffer(void) { // méthode efficace pour vider le buffer clavier // il faut consommer tous les caractères présents dans ce buffer jusqu'à ce // qu'il soit vide !!! int c; do { c = getchar(); } while (c != '\n' && c != EOF); } int main(void) { char conserver[4] = {0}; char onContinue; do { printf("entrer votre choix: "); scanf("%s", conserver); viderBuffer(); // conserver[3]='\0'; printf("vous avez choisi %s \n", conserver); printf("détail de votre choix Dé1 = %c, Dé2=%c, Dé3=%c \n", conserver[0], conserver[1], conserver[2]); // chaque dé peut donc être testé séparément printf("voulez vous jouer taper y/n "); scanf("%c", &onContinue); } while (onContinue == 'y'); return EXIT_SUCCESS; }
C
int conta_bits_um_c(int x){ int i, aux = 0, count = 0; for (i = 0; i < 32; i++){ aux = x & 1; if (aux == 1){ count++; } x = (x >> 1); } return count; }
C
#include <stdio.h> int main() { int i,n1,n2; scanf("%d%d", &n1,&n2); if((n1 % 2) != 0) printf("O PRIMEIRO NAO E PAR\n"); else{ printf("%d ", n1); for(i=1; i < n2; i++){ n1 = n1+2; printf("%d ", n1);} } return 0; }
C
/*FUNCTION CODE TO DELETE A NODE TO WHICH A POINTER IS GIVEN IN A LINKED LIST AS THE ADDRESS WE CANNOT DEFINE SO ONLY CODE OF FUNCTION PRESENT*/ #include<stdio.h> typedef struct node { int info; struct node *next; }nodetype; void deleteForPointer(nodetype *ptr) { if(ptr!=NULL) { if(ptr->next!=NULL) { ptr->info=(ptr->next)->info; ptr->next=(ptr->next)->next; } } else printf("\nNode not present"); }
C
// // compressECGData.c // compressECGData // // Created by Realank on 2017/4/17. // Copyright © 2017年 Realank. All rights reserved. // #include "compressECGData.h" #define BufferSize 1024*16 uint8_t queue = 0; int position = 0; int pushToQueue(uint8_t data, uint8_t* popData){ if (position == 0) { queue = (data&0x0f); position++; return 0; }else{ queue <<= 4; queue += (data&0x0f); *popData = queue; queue = 0; position = 0; return 1; } } int forcePopQueue(uint8_t* popData){ if (position == 0) { //noting //reset queue = 0; position = 0; return 0; }else{ queue <<= 4; *popData = queue; //reset queue = 0; position = 0; return 1; } } int compressFile4bit(const char* readFilePath,const char* writeFilePath){ int ret = 1; FILE *readFp = fopen(readFilePath, "r"); FILE *writeFp = fopen(writeFilePath, "w"); if (!readFp || !writeFp) { printf("Can't open file\n"); ret = 0; goto CLOSEFILE; } size_t fileLength = 0; size_t onceReadLength = 0; uint8_t* readBuffer = malloc(sizeof(uint8_t) * BufferSize); uint8_t* writeBuffer = malloc(sizeof(uint8_t) * BufferSize*2); if (readBuffer == NULL || writeBuffer == NULL) { printf("Memmory Alloc Fail\n"); ret = 0; goto FREEMEM; } //header writeBuffer[0] = 0xf1; writeBuffer[1] = 0x04; writeBuffer[2] = 0x00;//sum high writeBuffer[3] = 0x00;//sum low writeBuffer[4] = 0x00;//TBD writeBuffer[5] = 0x00;//TBD if (fwrite(writeBuffer, sizeof(uint8_t), 6, writeFp) != 6) { printf("Write to file failed\n"); ret = 0; goto FREEMEM; } uint16_t previousValue = 0; long largeMarginCount = 0; uint16_t sum = 0; long deltaCount = 0;//count the delta datas after full size data while ((onceReadLength = fread(readBuffer, sizeof(uint8_t), BufferSize, readFp))) { size_t writeLength = 0; for (int i = 0; i < onceReadLength; i+=2) { uint16_t ecgValue = (readBuffer[i] << 8) + readBuffer[i+1]; int16_t delta = ecgValue - previousValue; if ((delta > 7 || delta < -7) || deltaCount >= BufferSize) { //pop full size data deltaCount = 0; largeMarginCount++; uint8_t dataToPush = 0; if (pushToQueue(0x8, &dataToPush)) { writeBuffer[writeLength] = dataToPush; writeLength ++; } if (forcePopQueue(&dataToPush)) { writeBuffer[writeLength] = dataToPush; writeLength ++; } writeBuffer[writeLength] = readBuffer[i]; writeBuffer[writeLength+1] = readBuffer[i+1]; writeLength += 2; }else{ deltaCount++; uint8_t dataToPush = 0; if (pushToQueue(delta, &dataToPush)) { writeBuffer[writeLength] = dataToPush; writeLength += 1; } } previousValue = ecgValue; sum += ecgValue; } fileLength += onceReadLength; size_t writtenLength = fwrite(writeBuffer, sizeof(uint8_t), writeLength, writeFp); if (writtenLength != writeLength) { printf("Write to file failed\n"); ret = 0; goto FREEMEM; } } uint8_t dataToPush = 0; size_t writeLength = 0; // end data if (pushToQueue(0x8, &dataToPush)) { writeBuffer[writeLength] = dataToPush; writeLength ++; } if (forcePopQueue(&dataToPush)) { writeBuffer[writeLength] = dataToPush; writeLength ++; } if (fwrite(writeBuffer, sizeof(uint8_t), writeLength, writeFp) != writeLength) { printf("Write to file failed\n"); ret = 0; goto FREEMEM; } //write sum if(fseek(writeFp, 2, SEEK_SET) != 0){ printf("Seek file failed\n"); ret = 0; goto FREEMEM; } writeBuffer[0] = sum / 0x100; writeBuffer[1] = sum % 0x100; if (fwrite(writeBuffer, sizeof(uint8_t), 2, writeFp) != 2) { printf("Write to file failed\n"); ret = 0; goto FREEMEM; } FREEMEM: free(readBuffer); free(writeBuffer); printf("file length: %ld\n",fileLength); printf("large margin count: %ld\n",largeMarginCount); CLOSEFILE: fclose(readFp); fclose(writeFp); return ret; } int decompressFile4bit(const char* readFilePath,const char* writeFilePath){ int ret = 1; FILE *readFp = fopen(readFilePath, "r"); FILE *writeFp = fopen(writeFilePath, "w"); if (!readFp || !writeFp) { printf("Can't open file\n"); ret = 0; goto CLOSEFILE; } size_t fileLength = 0; size_t onceReadLength = 0; uint8_t* readBuffer = malloc(sizeof(uint8_t) * BufferSize); uint8_t* writeBuffer = malloc(sizeof(uint8_t) * BufferSize * 4); if (readBuffer == NULL || writeBuffer == NULL) { printf("Memmory Alloc Fail\n"); ret = 0; goto FREEMEM; } //header onceReadLength = fread(readBuffer, sizeof(uint8_t), 6, readFp); if (onceReadLength != 6) { printf("Read failed\n"); ret = 0; goto FREEMEM; } if (readBuffer[0] != 0xf1 || readBuffer[1] != 0x04) { printf("Data Format Error\n"); ret = 0; goto FREEMEM; } uint16_t checkSum = (readBuffer[2] << 8) + readBuffer[3]; uint16_t previousValue = 0; uint16_t sum = 0; int nextIsFullSizeData = 0; int shouldUsePreviousBlockData = 0; uint8_t previousBlockData = 0x00; while ((onceReadLength = fread(readBuffer, sizeof(uint8_t), BufferSize, readFp))) { size_t writeLength = 0; for (int i = 0; i < onceReadLength; i++) { uint8_t data = readBuffer[i]; if (nextIsFullSizeData) { //full size data if (!shouldUsePreviousBlockData) { shouldUsePreviousBlockData = 1; previousBlockData = data; }else{ writeBuffer[writeLength] = previousBlockData; writeBuffer[writeLength+1] = data; writeLength += 2; uint16_t ecgValue = (previousBlockData << 8) + data; previousValue = ecgValue; sum += ecgValue; //reset flag previousBlockData = 0x00; shouldUsePreviousBlockData = 0; nextIsFullSizeData = 0; } continue; } uint8_t high4Bit = (data&0xf0) >> 4; uint8_t low4Bit = (data&0x0f); if (high4Bit == 0x8) { nextIsFullSizeData = 1; continue; } int16_t delta = (high4Bit > 7 ? high4Bit - 0x10 : high4Bit); uint16_t ecgValue = (previousValue + delta); previousValue = ecgValue; sum += ecgValue; writeBuffer[writeLength] = ecgValue / 0x100; writeBuffer[writeLength + 1] = ecgValue % 0x100; writeLength += 2; if (low4Bit == 0x8) { nextIsFullSizeData = 1; continue; } delta = (low4Bit > 7 ? low4Bit - 0x10 : low4Bit); ecgValue = (previousValue + delta); previousValue = ecgValue; sum += ecgValue; writeBuffer[writeLength] = ecgValue / 0x100; writeBuffer[writeLength + 1] = ecgValue % 0x100; writeLength += 2; } fileLength += writeLength; size_t writtenLength = fwrite(writeBuffer, sizeof(uint8_t), writeLength, writeFp); if (writtenLength != writeLength) { printf("Write to file failed\n"); ret = 0; goto FREEMEM; } } if (checkSum != sum) { printf("Sum Check Failed\n"); ret = 0; goto FREEMEM; } FREEMEM: free(readBuffer); free(writeBuffer); printf("file length: %ld\n",fileLength); CLOSEFILE: fclose(readFp); fclose(writeFp); return ret; } //int compressFile8bit(const char* readFilePath,const char* writeFilePath){ // int ret = 1; // FILE *readFp = fopen(readFilePath, "r"); // FILE *writeFp = fopen(writeFilePath, "w"); // if (!readFp || !writeFp) { // printf("Can't open file\n"); // ret = 0; // goto CLOSEFILE; // } // size_t fileLength = 0; // size_t onceReadLength = 0; // uint8_t* readBuffer = malloc(sizeof(uint8_t) * BufferSize); // uint8_t* writeBuffer = malloc(sizeof(uint8_t) * BufferSize); // if (!readBuffer || !writeBuffer) { // printf("Memmory Alloc Fail\n"); // ret = 0; // goto FREEMEM; // } // // //header // writeBuffer[0] = 0xf1; // writeBuffer[1] = 0x08; // if (fwrite(writeBuffer, sizeof(uint8_t), 2, writeFp) != 2) { // printf("Write to file failed\n"); // ret = 0; // goto FREEMEM; // } // // uint16_t previousValue = 0; // long largeMarginCount = 0; // uint16_t sum = 0; // while ((onceReadLength = fread(readBuffer, sizeof(uint8_t), BufferSize, readFp))) { // size_t writeLength = 0; // // for (int i = 0; i < onceReadLength; i+=2) { // uint16_t ecgValue = (readBuffer[i] << 8) + readBuffer[i+1]; // int16_t delta = ecgValue - previousValue; // // if (delta > 127 || delta < -127) { // largeMarginCount++; // writeBuffer[writeLength] = 0x80; // writeLength+=1; // if (writeLength%2 == 1) { // //need to fill a 0x00 to align // writeBuffer[writeLength] = 0x00; // writeLength+=1; // } // writeBuffer[writeLength] = readBuffer[i*2]; // writeBuffer[writeLength+1] = readBuffer[i*2+1]; // writeLength += 2; // }else{ // writeBuffer[writeLength] = delta; // writeLength += 1; // } // previousValue = ecgValue; // sum += ecgValue; // } // fileLength += onceReadLength; // size_t writtenLength = fwrite(writeBuffer, sizeof(uint8_t), writeLength, writeFp); // if (writtenLength != writeLength) { // printf("Write to file failed\n"); // } // } // writeBuffer[0] = sum / 0x100; // writeBuffer[1] = sum % 0x100; // if (fwrite(writeBuffer, sizeof(uint8_t), 2, writeFp) != 2) { // printf("Write to file failed\n"); // ret = 0; // goto FREEMEM; // } //FREEMEM: // free(readBuffer); // free(writeBuffer); // printf("\n file length: %ld\n",fileLength); // printf("large margin count: %ld\n",largeMarginCount); //CLOSEFILE: // fclose(readFp); // fclose(writeFp); // return ret; //}
C
#ifndef WORD_H #define WORD_H #define CHARSIZE (4) typedef struct char_s { unsigned char c[CHARSIZE]; } char_t; typedef struct word_s { char_t * w; // string int l; // length of the word } word_t; typedef struct words_s { word_t * w; // words array int l; // length of words list } words_t; /* Return number of bytes used to store a char in utf8 ** val: value to examine */ int nbOfBytesInChar(unsigned char val); /* Display a words ** word: words to print */ void printW(word_t * word); /* Compare two string, a word_t and an unsigned char ** return 1 if strings are the same, 0 else ** word: first string ** in: second string ** inLen: length of the second string */ int cmpWaUS(word_t * word, unsigned char * in, int inLen); /* Get number of chars from unsigned char array ** array: input array ** maxLen: max length of input */ int getUCLen(unsigned char * array, int maxLen); /* Get words from input file ** filename: input file name ** words: array to store words ** returns whether an error occured or not */ int getWords(char * filename, words_t * words); #endif // WORD_H
C
#include <stdio.h> #include <windows.h> #include <winioctl.h> int main(int argc, char *argv[ ]) { BOOL b; DWORD FsFlags; LPSTR lp; HANDLE hMod; UINT w; CHAR FileName[MAX_PATH]; HANDLE hFile; DWORD Nbytes; DWORD FileSize; WORD State; DWORD Length; DWORD wrap; b = GetVolumeInformation(NULL,NULL,0,NULL,NULL,&FsFlags,NULL,0); if ( !b ) { printf("compstrs: Failure getting volumeinformation %d\n",GetLastError()); return 0; } if ( !(FsFlags & FS_FILE_COMPRESSION) ) { printf("compstrs: File system does not support per-file compression %x\n",FsFlags); return 0; } // // Get a temp file // w = GetTempFileName(".","cstr",0,FileName); if ( !w ) { printf("compstrs: unable to get temp file name\n"); return 0; } // // Create the tempfile // hFile = CreateFile( FileName, GENERIC_WRITE | GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL ); if ( hFile == INVALID_HANDLE_VALUE ) { printf("compstrs: failure creating %s %d\n",FileName,GetLastError()); return 0; } // // Write the file that we want to compress. It is a copy of kernel32 and ntdll // hMod = GetModuleHandle("kernel32"); if ( !hMod ) { printf("compstrs: failure getting handle to kernel32.dll\n"); CloseHandle(hFile); DeleteFile(FileName); return 0; } lp = (LPSTR)hMod; b = TRUE; FileSize = 0; while(b) { b = WriteFile(hFile,lp,512, &Nbytes, NULL); if ( b ) { FileSize += Nbytes; lp += Nbytes; } } hMod = GetModuleHandle("ntdll"); if ( !hMod ) { printf("compstrs: failure getting handle to ntdll\n"); CloseHandle(hFile); DeleteFile(FileName); return 0; } lp = (LPSTR)hMod; b = TRUE; while(b) { b = WriteFile(hFile,lp,512, &Nbytes, NULL); if ( b ) { FileSize += Nbytes; lp += Nbytes; } } wrap = 0; while(1) { // // compress and de-compress this file forever // State = 1; b = DeviceIoControl( hFile, FSCTL_SET_COMPRESSION, &State, sizeof(WORD), NULL, 0, &Length, NULL ); if ( !b ) { printf("compstrs: compress failed %d\n",GetLastError()); wrap = 0; } else { FlushFileBuffers(hFile); printf("C"); wrap++; } Sleep(500); // // Decompress // State = 0; b = DeviceIoControl( hFile, FSCTL_SET_COMPRESSION, &State, sizeof(WORD), NULL, 0, &Length, NULL ); if ( !b ) { printf("compstrs: uncompress failed %d\n",GetLastError()); wrap = 0; } else { FlushFileBuffers(hFile); printf("U"); wrap++; } if ( wrap > 50 ) { printf("\n"); wrap = 0; } } CloseHandle(hFile); DeleteFile(FileName); }
C
#ifndef PS2_H #define PS2_H /* * Module that communicates with a PS2 device such as a keyboard * or mouse. * * Students implement this module in assignments 5 and 7. * * Author: Julie Zelenski <[email protected]> * * Last edited Feb 2021 */ #include <stdbool.h> typedef struct ps2_device ps2_device_t; /* * `ps2_new` * * Initializes a new PS2 device connected to specified clock and data GPIO * pins and returns pointer to device. * * To configure a new PS2 device in your code: * * ps2_device_t *dev = ps2_new(KEYBOARD_CLK, KEYBOARD_DATA); * * Notice that this interface is slightly different from the _init exposed by * other libpi modules. The _new pattern allows a client to create multiple PS2 * devices, such as one for a keyboard and another for a mouse. It also means * that clients of this module don't need to know the implementation details * (like size) of ps2_device_t, since they just keep a pointer. * * @param clock_gpio the gpio connected to the clock line of the PS2 device * @param data_gpio the gpio connected to the data line of the PS2 device * @return pointer to new PS2 device or NULL if failed to create * * Although `ps2_new` configures the requested clock and data GPIOs * to use the internal pull-up resistors, it is recommended to choose GPIO * pins whose default state is already pull-up. This avoid timing issues * if the device attempts to handshake with the Pi before `ps2_new` has * been called. */ ps2_device_t *ps2_new(unsigned int clock_gpio, unsigned int data_gpio); /* * `ps2_read` * * Read (blocking) a single scancode from the specifed PS2 device. * Bits are read on the falling edge of the clock. * * Reads 11 bits: 1 start bit, 8 data bits, 1 parity bit, and 1 stop bit * * Discards and restarts the scancode if: * (lab5) The start bit is incorrect * (assign5) or if parity or stop bit is incorrect * * Returns the 8 data bits of a well-formed PS2 scancode. * Will not return until it reads a complete and valid scancode. * * @param dev PS2 device from which to read * @return scancode read from PS2 device */ unsigned char ps2_read(ps2_device_t *dev); /* * `ps2_write`: optional extension * * Write a command scancode to the specifed PS2 device. * You do not need to implement this function unless you are * doing the mouse extension. * * @param dev PS2 device to which to write * @param command scancode to write * @return true if successful write, false otherwise */ bool ps2_write(ps2_device_t *dev, unsigned char command); /* * `ps2_use_interrupts` : reference-only * * The default behavior of `ps2_read` is to read scancode bits * by polling the clock GPIO and waiting for a falling edge. An * alternate mode would be to register for event detection * on the clock GPIO to be notified of each falling edge and use * an interrupt handler to read a bit. The interrupt handler would * enqueue a scancode to an internal queue to be later * dequeued by`ps2_read`. * * The reference implementation of this module has a switch to * change the mode for a ps2 device. The default is read-by-polling. * After creating a device with `ps2_new`, the client may call 8 `ps2_use_interrupts(device)` to change that device into * read-by-interrupt mode. * * The client must also globally enable interrupts at system level for * interrupts to be generated. * * The switchable mode is specific to the reference implementation. * The student's ps2 module does not have this function. * The initial implementation by student is polling-only (assign5) and * later changed to interrupt-only (assign7). */ void ps2_use_interrupts(ps2_device_t *dev); #endif
C
#include <gtk/gtk.h> #include "listOfProcess.h" #include <sys/sysinfo.h> #include <cairo/cairo.h> #include <stdio.h> #include <stdlib.h> #define WIDTH 640 #define HEIGHT 480 #define ZOOM_X 10.0 #define ZOOM_Y 10.0 static int cpus; typedef struct { GtkListStore * str; GtkTreeIter iter; GtkDrawingArea * da; }tree_widgets; //stuct that mantains info of the list while running typedef struct graph_node{ float x, y; double r,g,b; struct graph_node * next; }GraphNode; GraphNode **percs; //array of pointers containing all the values in the graph // graph related to cpus values void addGraphNode(GraphNode ** head, float y){ GraphNode * add = (GraphNode *) malloc(sizeof(GraphNode)); GraphNode * temp; GraphNode * a; add->next = NULL; add->y=y; if(*head == NULL) *head = add; else if((*head)->x == 40.0){ //clear the memory of the points over the graph a = (*head)->next; free(*head); *head = a; }else{ temp = *head; while(temp->next!=NULL){ temp->x++; temp = temp->next; } temp->x++; temp->next = add; } add->x = 1; } static gboolean on_draw (GtkWidget *widget, cairo_t *cr, gpointer user_data) { GdkRectangle da; /* GtkDrawingArea size */ gdouble dx, dy; /* Pixels between each point */ gdouble i, clip_x1 = 0.0, clip_y1 = 0.0, clip_x2 = 0.0, clip_y2 = 0.0; GdkWindow *window = gtk_widget_get_window(widget); /* Determine GtkDrawingArea dimensions */ gdk_window_get_geometry (window, &da.x, &da.y, &da.width, &da.height); dx = da.width/20; //there will be 20 points in the x axis dy = da.height/100; //and 100 points in the y axys /* Change the transformation matrix */ cairo_translate (cr, 0, da.height); cairo_scale (cr, ZOOM_X, -ZOOM_Y); /* Determine the data points to calculate (ie. those in the clipping zone */ cairo_device_to_user_distance (cr, &dx, &dy); cairo_clip_extents (cr, &clip_x1, &clip_y1, &clip_x2, &clip_y2); cairo_set_line_width (cr, 0.5); /* Draws x and y axis */ cairo_set_source_rgb (cr, 0.0, 1.0, 1.0); cairo_move_to (cr, clip_x1, 0.0); cairo_line_to (cr, clip_x2, 0.0); cairo_move_to (cr, 0.0, clip_y1); cairo_line_to (cr, 0.0, clip_y2); cairo_stroke (cr); if( percs[0] == NULL) cairo_move_to(cr,0,0); else{ int procs = get_nprocs(); GraphNode * temp; for(int i =0; i < procs+1; i++){ //draws the lists of temp = percs[i]; cairo_move_to(cr,clip_x2-temp->x*dx,temp->y*100*dy*-1); //multiplying for dx and dy to mantain proportion in maximized window while(temp!=NULL){ cairo_line_to(cr,clip_x2-temp->x*dx,temp->y*100*dy*-1); //-1 because dy is a negative number temp = temp->next; } cairo_set_source_rgba (cr, percs[i]->r, percs[i]->g, percs[i]->b, 0.8); cairo_stroke (cr); } } return FALSE; } gboolean calculatetemp(tree_widgets * ptr); void on_main_window_destroy(){ gtk_main_quit(); } void on_select_changed(){ } void on_tv_start_interactive_search(){ } int main (int argc, char *argv[]){ GtkWidget *main_window; GtkBuilder *builder; GtkTreeView *tv1; GtkTreeSelection *sel; GtkTreeViewColumn * cl2; tree_widgets * widgets = g_slice_new(tree_widgets); //allocating memory GtkBox * box; cpus = get_nprocs(); percs = (GraphNode **) malloc(sizeof(GraphNode **)*(cpus+1)); for(int i =0; i < cpus+1; i++) percs[i] = NULL; gtk_init(&argc,&argv); builder = gtk_builder_new(); gtk_builder_add_from_file(builder,"glade/ui.glade",NULL); //accessing the glade file to build the ui main_window = GTK_WIDGET(gtk_builder_get_object(builder,"main_window")); tv1 = GTK_TREE_VIEW(gtk_builder_get_object(builder,"tv")); widgets->str = GTK_LIST_STORE(gtk_builder_get_object(builder,"str")); cl2 = GTK_TREE_VIEW_COLUMN(gtk_builder_get_object(builder,"cl_perc")); sel = gtk_tree_view_get_selection(tv1); widgets->da = GTK_DRAWING_AREA(gtk_builder_get_object(builder,"drw_ar")); box = GTK_BOX(gtk_builder_get_object(builder,"g_box2")); gtk_builder_connect_signals(builder,widgets); g_signal_connect(G_OBJECT(widgets->da), "draw", G_CALLBACK(on_draw), NULL); g_timeout_add_seconds(2,(GSourceFunc)calculatetemp,widgets); //calling this func every second gtk_list_store_append(widgets->str,&widgets->iter); gtk_list_store_set(widgets->str,&widgets->iter,0,"asad",1,"3213",2,0.5,-1); gtk_list_store_append(widgets->str,&widgets->iter); gtk_list_store_set(widgets->str,&widgets->iter,0,"asad",-1); gtk_tree_view_column_clicked(cl2); gtk_tree_view_column_clicked(cl2); g_object_unref(builder); gtk_widget_show(main_window); gtk_main(); g_slice_free(tree_widgets,widgets); return EXIT_SUCCESS; } gboolean calculatetemp(tree_widgets * ptr){ int i = 0; float cpu_calc[cpus+1]; gtk_list_store_move_after(ptr->str,&ptr->iter,NULL); gtk_list_store_clear(ptr->str); calculate(cpu_calc); Node * temp = *getHead(); while (temp!=NULL) { gtk_list_store_append(ptr->str,&ptr->iter); gtk_list_store_set(ptr->str,&ptr->iter,0,temp->value.comm,1,temp->value.pid,2,temp->value.perc*100,-1); temp = temp->next; } for(;i < cpus +1; i++){ addGraphNode(&percs[i],cpu_calc[i]); if(percs[i]->next==NULL){ percs[i]->r = (float) (rand()%101)/100; percs[i]->g = (float) (rand()%101)/100; percs[i]->b = (float) (rand()%101)/100; }else{ GraphNode * temp = percs[i]; while(temp->next!=NULL) temp = temp->next; temp->r = percs[i]->r; temp->g = percs[i]->g; temp->b = percs[i]->b; } } gtk_widget_queue_draw(ptr->da); freeAll(); return TRUE; }
C
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <string.h> #include <locale.h> #define EPSILON 0.00000001 // Alocação, leitura e escrita de matrizes double **alocaMatriz(int l, int c) { // aloca espaço na memória para a alocação da matriz // Se houver espaço: aloca dinamicamente uma matriz[l][c] (sendo "l" linhas e "c" colunas), devolvendo um ponteiro para double. // Caso contrário: devolve nulo double **m; int i,j; m = malloc(sizeof(double *)*c); if(m == NULL) return NULL; // falta de memória for(i=0;i<c;i++) { m[i] = malloc(sizeof(double)*l); if(m[i] == NULL) { // falta de memória for(j = 0; j < i; j++) free(m[j]); free(m); return NULL; }; } return m; } void imprimeMatriz(double **m,int l, int c) { // mostra a matriz int i,j; for(i=0;i<l;i++) { for(j=0;j<c;j++) { printf("%6.2lf ",m[j][i]); } printf("\n"); } } double **leArquivo(double **m, int *nvar, FILE *fp) { // lê os dados de um arquivo int i, j; m = alocaMatriz(nvar[0],nvar[0]+1); for(j=0; j<nvar[0]; j++) { for(i=0; i<nvar[0]+1; i++) { fscanf(fp,"%lf",&m[i][j]); } } fclose (fp); return m; } // Conversão de bases sistemas de numeração char *giraString (char *k, int i){ // ESTA FUNÇÃO É UTILIZADA PARA INVERTER A ORDEM DA STRING UTILIZADA NA CONVERSÃO DA PARTE INTEIRA DO NÚMERO DECIMAL int n, t; // n É O LIMITE DO LAÇO DA INVERSÃO char swap; if(i%2 ==0) n=i/2; else n = (i-1)/2; for(t=0; t<n; t++){ // LAÇO DA INVERSÃO DA STRING swap = k[t]; k[t] = k[i-1-t]; k[i-1-t] = swap; } return k; } void converteNum(double num,int base){ // ESTA FUNÇÃO CONVERTE UM NUMÉRO DECIMAL num UM SISTEMA DE BASE k. NO PROGRAMA PRINCIPAL, AS BASES SOLICITADAS SÃO 2 (BINÁRIO), 8 (OCTAL) E 16 (HEXADECIMAL). int bitsConvertidos=0, casasDecimais, inteiro, bit, sinal=0; //t É O LIMITADOR DE DE CASAS DECIMAIS; double fracao; char *p; if (num < 0) { num = fabs(num); // deixa positivo sinal = 1; } inteiro = abs(num); // inteiro É A PARTE INTEIRA DE num fracao = num-inteiro; // fracao É A PARTE FRACIONÁRIA DE num p = malloc(sizeof(char *)*30); while(inteiro !=0){ // LAÇO DE CONVERSÃO DA PARTE INTEIRA bit = inteiro%base; if(bit > 9) bit += 7; p[bitsConvertidos] = bit + 48; inteiro/=base; bitsConvertidos++; //QUANTOS BITS JÁ FORAM CONVERTIDOS } p = giraString(p,bitsConvertidos); // A STRING p É MONTADA NA ORDEM EM QUE OS BITS SÃO OBTIDOS, PORÉM, ELES DEVEM SER LIDOS DA FORMA INVERSA. POR ISSO, A NECESSIDADE DA INVERSÃO DE p. p[bitsConvertidos] = 46; // UMA VEZ QUE A PARTE INTEIRA É FINALIZADA, INSERIMOS UM PONTO (. NO CÓDIGO ASCII É 46). bitsConvertidos++; casasDecimais= bitsConvertidos + 19; // t FIXA O MÁXIMO DE 20 CASAS DECIMAIS A SEREM CONVERTIDAS A PARTIR DE i while(bitsConvertidos <= casasDecimais){ fracao = fracao*base; bit = abs(fracao); if(bit > 9) bit += 7; p[bitsConvertidos] = bit + 48; if(bit >= 17) bit -= 7; fracao -= bit; bitsConvertidos++; if(fracao == 0) break; } p[bitsConvertidos] = '\0'; // CARACTERE NULO INSERIDO PARA DELIMITAR O FIM DA CONVERSÃO switch(base){ case 2: if (sinal == 0) printf("\n%lf em binario: %s",num,p); else printf ("\n-%lf em binario: -%s",num,p); break; case 8: if (sinal == 0) printf("\n%lf em octal: %s",num,p); else printf("\n-%lf em octal: -%s",num,p); break; case 16: if (sinal == 0) printf("\n%lf em hexadecimal: %s",num,p); else printf("\n-%lf em hexadecimal: -%s",num,p); break; } } // Resolução de sistemas lineares int achaSolucao(double **m,int n,double *x){ int i,j,tipo=0; for(i=0;i<n;i++){ if(m[i][i]==0){ if(m[n][i]==0){ /* SE O ELEMENTO DA DIAGONAL PRINCIPAL DA LINHA i NA MATRIZ DE COEFICIENTES E O TERMO INDEPENDENTE FOREM IGUAIS A 0, O SISTEMA É INDETERMINADO, POIS PARA QUALQUER VALOR DE X[i], A EQUAÇÃO SERÁ ATENDIDA. A SOLUÇÃO EXIBIDA, CONSIDERARÁ X[i] IGUAL A 0. */ tipo=1; x[i]=0; } else { /* SE O ELEMENTO DA DIAGONAL PRINCIPAL DA LINHA i NA MATRIZ DE COEFICIENTES FOR IGUAL A 0 E O TERMO INDEPENDENTE FOR DIFERENTE DE 0, O SISTEMA É IMPOSSÍVEL, POIS NÃO HÁ QUALQUER VALOR DE X[i] QUE ATENDA A ESTA CONDIÇÃO. */ return 2; } } else { x[i]=m[n][i]/m[i][i]; // CASO HAJA SOLUÇÃO, ESTÁ SE DÁ PELA DIVISÃO DO TERMO INDEPENDENTE PELO COEFICIENTE DA LINHA i DA DIAGONAL PRINCIPAL } } return tipo; } void jordan(double **m,int n,int *seqx){ // RESOLVE UM SISTEMA LINEAR DE n VARIÁVEIS E n EQUAÇÕES PELO MÉTODO DE JORDAN /* ESTA FUNÇÃO RESOLVE UM SISTEMA LINEAR CUJOS COEFICIENTES FORAM INCLUIDOS NA MATRIZ m DE n VARIAVEIS E n EQUAÇÕES PELO MÉTODO DE JORDAN */ int i,j,k,t,swapX,tipo; double *aux, *x, mult; x=malloc(sizeof(double *)*n); // x É O VETOR DE SOLUÇÕES DO SISTEMA LINEAR, CASO HAJA printf("\n"); for(i=0; i<n; i++) { if(fabs(m[i][i]) < EPSILON){ // CASO O PIVÔ SEJA 0, BUSCA EM COLUNAS A DIREITA UM VALOR NÃO NULO j=i; do { j++; } while(j<n && fabs(m[j][i])<EPSILON); if(j<n){ // SE ESSE VALOR FOR ENCONTRADO, É FEITA A TROCA DAS POSIÇÕES aux = m[i]; m[i] = m[j]; m[j] = aux; // PARA QUE AO FINAL DO PROCESSO, O USÁRIO SAIBA SE HOUVE OU NÃO TROCAS DE COLUNA, É FEITO UM REGISTRO swapX = seqx[i]; seqx[i] = seqx[j]; seqx[j] = swapX; } else { // CASO SEJA ENCONTRADA NA ITERAÇÃO i UMA LINHA DE ZEROS NA MATRIZ... for(t=0; t<n; t++) { m[i][t]=0; // ...A COLUNA i DEVERÁ SER TODA ZERADA. } } } // fim do if if(fabs(m[i][i]) >= EPSILON) { for(j=0; j<n; j++) { if(j == i) j++; if(j < n) { mult = -m[i][j]/m[i][i]; for(k=0; k<=n; k++) { m[k][j] += mult*m[k][i]; } } } } // fim do if } // fim do for printf("Matriz triangular: \n\n"); imprimeMatriz(m,n,n+1); for(t=0; t<n; t++){ printf(" x%d ",seqx[t]); // É EXIBIDA A ORDEM DAS VARIÁVEIS, PARA QUE O USUÁRIO SAIBA SE HOUVE OU NÃO TROCAS DE COLUNA } printf("\n-----------------------------\n"); printf("Resultado:\n\n"); tipo=achaSolucao(m,n,x); if(tipo == 2) printf("Sistema linear impossivel"); else { for(i=0; i<n; i++) { printf("x[%d]: %6.2lf\n",seqx[i],x[i]); } if(tipo==0) printf("\nSL determinado"); else printf("\nSL indeterminado"); } } void resolveSL() { // RESOLVE UM SISTEMA LINEAR CUJOS COEFICIENTES ESTÃO EM UM ARQUIVO .TXT INDICADO PELO USUÁRIO int *nvar,*seqx,tipo, t; char *nomeDoArquivo; double **m; FILE *fp; nomeDoArquivo = malloc(80); printf("Digite o caminho para o arquivo de texto que contem o sistema linear: \n"); do{ fgets(nomeDoArquivo, 80, stdin); } while(nomeDoArquivo[0] == '\n'); // RECEBE O NOME DO ARQUIVO E SUA EXTENSÃO nomeDoArquivo[strlen(nomeDoArquivo)-1] = '\0'; fp = fopen(nomeDoArquivo, "r"); // ABRE O ARQUIVO SOMENTE COMO LEITURA ("r" = READ) // printf("%s", fp); if (fp == NULL){ printf("\n------ AVISO: Nao foi possivel encontrar e/ou abrir o arquivo. ------\n"); } else { nvar = malloc(sizeof(int *)); fscanf(fp,"%d",nvar); // LÊ O PRIMEIRO PARÂMETRO: QUANTIDADE DE VARIÁVEIS E DE EQUAÇÕES seqx = malloc(sizeof(int *)*nvar[0]); // CRIA UM VETOR ORDENADO DE 1 A nvar PARA AUXILIAR NA RESOLUÇÃO DO SISTEMA LINEAR for(t=0; t<nvar[0]; t++) { seqx[t]=t+1; } m = leArquivo(m,nvar,fp); // COLETA OS DADOS DO ARQUIVO printf("Matriz do arquivo: \n\n"); imprimeMatriz(m,nvar[0],nvar[0]+1); jordan(m,nvar[0],seqx); // GERA A MATRIZ TRIANGULAR DO SISTEMA E PROPÕE UMA SOLUÇÃO, CASO EXISTA. } } // Equação algébrica double *alocaVetor ( int l ) { /* Se houver memoria disponivel aloca o vetor com l colunas e devolve endereço-base da matriz; caso contrário devolve ponteiro nulo.*/ int i ; double *v ; v = malloc ( l * sizeof ( double ) ) ; if ( v == NULL ) {/*memoria insuficiente*/ return NULL ; } return v ; }/*fim de alocaVetor*/ void lerVetor ( double*v, int l ) { /*Lê valores para o vetor de double com l colunas*/ int i ; for (i = l; i >= 0; i--){ printf ("Coeficiente da variavel de grau [%d]: ", i) ; scanf ("%lf", &v[i]) ; } }/*fim de lerVetor*/ double lagrange ( double*v , int l ) { /* Converte o vetor, caso an seja menor que zero */ if (v[l] < 0) { int i; for(i=l; i>=0; i--) { v[i] = fabs(v[i]); //* (-1) ; } }//Fim da conversao /*Calcula o B, K e L de Lagrange*/ /* B - dos negativos, o maior coeficiente em modulo */ int i, k; double b; b = (v[l]) ; for (i=l; i>=0; i--) { if(b > v[i]) { b = v[i]; } } if (b > 0) { b = 0 ; } double ax = abs(b) ; /* K - maior expoente dos coeficientes negativos*/ for (i=l; i>0; i--) { if (v[i] < 0) { k = i; i = 1; } else{ k = 0; } } /*L - calcula o limite pelo teorema de Lagrange */ double L, x, raiz ; x = v[l]; raiz = pow( (ax/x),(1.0/ (l-k) ) ) ; if (raiz < 0) { raiz = fabs(raiz);// * ( -1 ) ; } L = 1 + (raiz) ; return L; }//fim de Lagrange double *inverteVetor (double*v, int l) { /*Inverte os coeficientes do vetor*/ int i ; double *inverso ; inverso = malloc ( l * sizeof ( double ) ) ; for (i=0; i<=l; i++) { inverso[l-i] = v[i] ; } return inverso ; }/*fim de inverteVetor*/ double *trocaSinal ( double*v , int l ) { /*Troca o sinal dos expoentes impares*/ int i, resto; for (i=l; i>=0; i--) { resto = i%2; if (resto != 0) { v[i] = fabs(v[i]); //* ( -1 ) ; } } return v; }/*fim de trocaSinal*/ void equacao(double *v, int g){ double *Inv, lim[3]; lim[0]=lagrange(v, g); Inv=inverteVetor(v,g); lim[1]=lagrange(Inv,g); trocaSinal(v,g); lim[2]=lagrange(v,g); trocaSinal(Inv,g); lim[3]=lagrange(Inv,g); printf ( "\n Raizes positivas [%.4lf <= E+ <= %.4lf]\n" , 1 / lim[1] , lim[0] ) ; printf ( "\n Raizes negativas [%.4lf <= E- <= %.4lf]\n" , ( -1 ) * lim[2] , ( -1 ) / lim[3] ) ; //voltar vetor ao normal trocaSinal(v,g); } void bissecao (double *v, int n){ double a,b, f_a=0, f_b=0, m, f_m=0, erro; int i, iteracoes = 0; printf("Insira o início do intervalo: "); scanf("%lf", &a); printf("Insira o fim do intervalo: "); scanf("%lf", &b); for(i=0; i<=n; i++){ f_a = f_a + v[i]*(pow(a,i)); f_b = f_b + v[i]*(pow(b,i)); } printf("f(a): %lf\nf(b): %lf\n",f_a,f_b); if(f_a*f_b < 0){ printf("número ímpar de raízes.\n"); do{ m = (a+b)/2; for(i=0; i<=n; i++){ f_m = f_m + v[i]*pow(m,i); if (f_m == 0){ printf("%lf é a raiz exata de f.\n", m); } if (f_m*f_a < 0){ b = m; f_b = f_m; } else { a = m; f_a = f_m; } erro = fabs(a-b); //erro máximo } printf("iterações: %d\n",iteracoes); iteracoes++; if(erro < EPSILON){ iteracoes = 1000; //sair do while } } while(iteracoes < 1000 ); printf("Raiz aproximada: %lf\n", m); } else { printf("Não há número ímpar de raízes.\n"); } } //FIM Equações algébricas int menu(void){ char opcao; double numero, *V; int n; printf("\n\'C\' - Conversão, \n\'S\' - Sistema Linear, \n\'E\' - Equação Algébrica, \n\'F\' - Finalizar.\n"); scanf("%s", &opcao); switch(toupper(opcao)){ case 'C': printf("Conversão\n"); printf("Digite o número decimal a ser convertido:\n"); scanf("%lf", &numero); converteNum(numero,2); converteNum(numero,8); converteNum(numero,16); break; case 'S': printf("sistema linear\n"); resolveSL(); break; case 'E': printf("Digite o grau da equação: "); scanf ("%d", &n); V = alocaVetor(n) ; lerVetor(V , n) ; if (V[0] == 0){ printf("Erro. Equação inválida.") ; break; } equacao(V, n) ; bissecao(V,n); break; case 'F': printf("finalizar\n"); return 1; break; default: printf("opção inválida\n"); } } int main(void){ setlocale(LC_ALL, "Portuguese"); int flag = 0; while(1){ flag = menu(); //consertar finalização if (flag == 1){ return 0;} } }
C
#include <pthread.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> //#define _LOCK_ // == gcc -D_LOCK_ void *func(void *arg); pthread_mutex_t mutex; int count = 0; int value1, value2; int main() { pthread_t pthread; if(pthread_mutex_init(&mutex, NULL)<0) { perror("pthread_mutex_init"); exit(-1); } if(pthread_create(&pthread,NULL,func,NULL)!= 0) { perror("pthread_init"); exit(-1); } while(1) { count++; #ifdef _LOCK_ pthread_mutex_lock(&mutex); #endif value1 = count; value2 = count; #ifdef _LOCK_ pthread_mutex_unlock(&mutex); #endif } return 0; } void *func(void *arg) { while(1) { #ifdef _LOCK_ pthread_mutex_lock(&mutex); #endif if(value1 != value2) { printf("value1:%d, value2:%d\n", value1, value2); sleep(2); } #ifdef _LOCK_ pthread_mutex_unlock(&mutex); #endif } }
C
#include<stdio.h> int main() { float A,b,h; printf("Enter the value of base="); scanf("%f",&b); printf("Enter the value of height="); scanf("%f",&h); A=(b*h)/2; printf("Area of triangle=%f",A); return 0; }
C
//This program finds the all posible occurence of Sub string in Super String. #include <math.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <assert.h> #include <limits.h> #include <stdbool.h> int appearanceCount(int input1,int input2,char* input3,char* input4) { int i,j,k,count=0,x,y; for(i=0;i<input2;i++) { y=0; for(j=0;j<input1;j++) { x=input1; k=i; while(x!=0) { if(input3[j]==input4[k++]) { y++; break; } x--; } } if(y==input1) count++; } return count; } int main() { int output = 0; int ip1; scanf("%d", &ip1);//Input1=sub string length int ip2; scanf("%d", &ip2);//Input 2=Main String Length char* ip3; ip3 = (char *)malloc(512000 * sizeof(char)); scanf("\n%[^\n]",ip3);//Input 3=Sub string char* ip4; ip4 = (char *)malloc(512000 * sizeof(char)); scanf("\n%[^\n]",ip4);//Input 4=Main String output = appearanceCount(ip1,ip2,ip3,ip4); printf("%d\n", output); return 0; }
C
#incluir <> stdio.h #include <stdlib.h> // atoi, atof #incluir <stdbool.h> // break (creo) #definir TAM 10 //sin ; y = int lista[TAM]= {11,12,13,14,15,16,17,18,19,20}; int idx=0; int main(int argc, char** argv){ for( int index=1; índice <= TAM; índice++){ printf("Índice: %d, Valor: %d \n\a", índice, lista[]); } // while (lista[idx] != 17){ // idx++; //} mientras que(true){ if(lista[idx] == 17){ quebrar; } idx++; } printf("Idx encontrado: %d\n", idx); devolver 0; }
C
#include <pebble.h> static Window *s_main_window; static TextLayer *s_time_layer,*s_date_layer; static TextLayer *s_food_layer; static BitmapLayer *s_background_layer; static GBitmap *s_background_bitmap; static char date_buffer[16]; char* lunchToday(char* dateInput){ char *lunch; switch (dateInput[0]){ case 'M': lunch= "DC Burgers"; break; case 'T': lunch= "SLC Pizza"; break; case 'W': lunch= "DC Chopsticks"; break; case 'F': lunch = "V1 Cafe: Aunties Kitchen"; break; default: lunch = "V1 Cafe: ALL DAY BABY"; } return lunch; } static void update_time() { // Get a tm structure time_t temp = time(NULL); struct tm *tick_time = localtime(&temp); // Write the current hours and minutes into a buffer static char s_buffer[8]; strftime(s_buffer, sizeof(s_buffer), clock_is_24h_style() ? "%H:%M" : "%I:%M", tick_time); // Display this time on the TextLayer text_layer_set_text(s_time_layer, s_buffer); strftime(date_buffer, sizeof(date_buffer), "%a %d %b", tick_time); // Show the date text_layer_set_text(s_date_layer, date_buffer); //show whats for lunch text_layer_set_text(s_food_layer, lunchToday(date_buffer)); } static void tick_handler(struct tm *tick_time, TimeUnits units_changed) { update_time(); } static void main_window_load(Window *window) { // Create GBitmap s_background_bitmap = gbitmap_create_with_resource(RESOURCE_ID_SEXX_BACK); // Create BitmapLayer to display the GBitmap s_background_layer = bitmap_layer_create(GRect(0, 0, 144 , 168)); // Set the bitmap onto the layer and add to the window bitmap_layer_set_bitmap(s_background_layer, s_background_bitmap); // Get information about the Window Layer *window_layer = window_get_root_layer(window); GRect bounds = layer_get_bounds(window_layer); // Create the TextLayer with specific bounds s_time_layer = text_layer_create( GRect(0, 70, bounds.size.w, 50)); s_food_layer = text_layer_create( GRect(0,136, bounds.size.w,26)); //(move in x domain, , , changes height that displays) // Improve the layout to be more like a watchface text_layer_set_background_color(s_time_layer, GColorClear); text_layer_set_text_color(s_time_layer, GColorBlack); text_layer_set_font(s_time_layer, fonts_get_system_font(FONT_KEY_BITHAM_42_BOLD)); text_layer_set_text_alignment(s_time_layer, GTextAlignmentCenter); //stuff around the time text_layer_set_background_color(s_food_layer, GColorClear); text_layer_set_text_color(s_food_layer, GColorWhite); text_layer_set_font(s_food_layer, fonts_get_system_font(FONT_KEY_GOTHIC_14)); text_layer_set_text_alignment(s_food_layer, GTextAlignmentCenter); // Create date TextLayer s_date_layer = text_layer_create(GRect(0, 120, 154, 30)); text_layer_set_text_color(s_date_layer, GColorWhite); text_layer_set_background_color(s_date_layer, GColorClear); text_layer_set_text_alignment(s_date_layer, GTextAlignmentCenter); // Add it as a child layer to the Window's root layer layer_add_child(window_layer, bitmap_layer_get_layer(s_background_layer)); layer_add_child(window_layer, text_layer_get_layer(s_time_layer)); layer_add_child(window_layer, text_layer_get_layer(s_date_layer)); layer_add_child(window_layer, text_layer_get_layer(s_food_layer)); } static void main_window_unload(Window *window) { text_layer_destroy(s_date_layer); // Destroy TextLayer text_layer_destroy(s_time_layer); // Destroy GBitmap text_layer_destroy(s_food_layer); gbitmap_destroy(s_background_bitmap); // Destroy BitmapLayer bitmap_layer_destroy(s_background_layer); } static void init() { // Register with TickTimerService tick_timer_service_subscribe(MINUTE_UNIT, tick_handler); s_main_window = window_create(); // Show the Window on the watch, with animated=true // Set handlers to manage the elements inside the Window window_set_window_handlers(s_main_window, (WindowHandlers) { .load = main_window_load, .unload = main_window_unload }); if(s_main_window != NULL) { // Allocation was successful! window_stack_push(s_main_window, true); } else { // The Window could not be allocated! // Tell the user that the operation could not be completed } // Make sure the time is displayed from the start update_time(); } static void deinit() { // Destroy Window window_destroy(s_main_window); } int main(void) { init(); app_event_loop(); deinit(); }
C
#include <string.h> #include <stdio.h> #include <stdlib.h> #include <search.h> #include "chin_lib.h" #define MXLGH 1000000 void usage(); int nd_cmp(const void *x,const void *y); void action(const void *nodep, const VISIT which, const int depth); void remove_node(const void *x); typedef struct pattern_node{ char *pattern; int count_all; int count_seq; }PATTERN_NODE; long Total_length,Total_read; main(argc, argv, envp) int argc; char **argv, **envp; { char a[MXLGH],b[MXLGH],c,*seq; int i,j,pattern_size,lgh,seq_count; FILE *in,*out; PATTERN_NODE *ptr=NULL; void *root1=NULL,*root2=NULL,*p=NULL; pattern_size=5;in=stdin;out=stdout;Total_length=Total_read=0; for(i=1;i<argc;i++){ if(argv[i][0]!='-')continue;c=argv[i][1]; switch(c){ case 'o': i++; if((out=fopen(argv[i],"w"))==NULL){ fprintf(stderr, "Can't open output file %s\n",argv[i]);exit(2); }argv[i-1]=argv[i]=NULL;break; case 'i': i++; if((in=fopen(argv[i],"r"))==NULL){ fprintf(stderr, "Can't open input file %s\n",argv[i]);exit(2); }argv[i-1]=argv[i]=NULL;break; case 'w': i++;pattern_size=atoi(argv[i]);if(pattern_size<1)pattern_size=5; argv[i-1]=argv[i]=NULL;break; case 'h': usage(); } } while((seq=nextfasta(in,a))){ lgh=strlen(seq);Total_length+=(lgh-pattern_size+1);Total_read++; /* printf("%s %d %s\n",a,lgh,seq);fflush(stdout); */ for(i=0;i<=lgh-pattern_size;i++){ for(j=0;j<pattern_size;j++)a[j]=seq[i+j];a[j]='\0'; ptr=(PATTERN_NODE *)malloc((size_t)sizeof(PATTERN_NODE)); if(ptr==NULL){fprintf(out,"error: malloc==NULL, memory full at point A. Total_read=%ld, Total_length=%ld\n",Total_read,Total_length);exit(0);} ptr->pattern=strdup(a);ptr->count_all=ptr->count_seq=0; p=tsearch((void *)ptr,&root2,nd_cmp); if(p==NULL){fprintf(out,"error: p==NULL %s\n",ptr->pattern);exit(0);} if((*(PATTERN_NODE **)p)==ptr){ seq_count=1; /* printf("new %s\n",ptr->pattern);fflush(stdout); */ } else{ seq_count=0; /* printf("old %s\n",ptr->pattern);fflush(stdout); */ free(ptr->pattern);free(ptr); } ptr=(PATTERN_NODE *)malloc((size_t)sizeof(PATTERN_NODE)); if(ptr==NULL){fprintf(out,"error: malloc==NULL, memory full at point B. Total_read=%ld, Total_length=%ld\n",Total_read,Total_length);exit(0);} ptr->pattern=strdup(a);ptr->count_all=ptr->count_seq=1; p=tsearch((void *)ptr,&root1,nd_cmp); if(p==NULL){fprintf(out,"error: p==NULL %s\n",ptr->pattern);exit(0);} if((*(PATTERN_NODE **)p)==ptr){ ptr->count_seq=ptr->count_all=1; } else{ (*(PATTERN_NODE **)p)->count_all++; (*(PATTERN_NODE **)p)->count_seq+=seq_count; free(ptr->pattern);free(ptr); } } tdestroy(root2,remove_node);root2=NULL; } twalk(root1,action); } int nd_cmp(const void *x,const void *y) { return(strcmp( ((PATTERN_NODE *)x)->pattern,((PATTERN_NODE *)y)->pattern) ); } void remove_node(const void *x) { /* printf("remove: %s\n",((PATTERN_NODE *)x)->pattern);fflush(stdout); */ free(((PATTERN_NODE *)x)->pattern); free((PATTERN_NODE *)x); } void action(const void *nodep, const VISIT which, const int depth) { PATTERN_NODE *datap; int i,j,clusterbegin; double sump,sumn,sum,clustersum,clustersump,clustersumn,cluster_cutoff,pre_sum,max_sum; double uniq_sum,cluster_uniq_sum; cluster_cutoff=0.1; switch(which){ case postorder: case leaf: datap = *(PATTERN_NODE **)nodep; printf("%s\t%d\t%d\t%.10f\n",datap->pattern,datap->count_all,datap->count_seq,datap->count_all/(float)Total_length); break; case preorder: case endorder: break; } } void usage() { printf("generate_pattern [-i input_fasta_file] [-o output_file]\n"); printf(" -i: input fasta file. default: stdin\n"); printf(" -o: output file. default: stdout\n"); printf(" -w: pattern size. default: 5\n"); printf("\nExample: generate_pattern -i input.fasta -o pattern_count\n"); exit(2); }
C
#include <stdio.h> #include <stdlib.h> #include <SDL.h> #include <math.h> #define WIDTH 1000 #define HEIGHT 1000 #define BPP 4 #define DEPTH 32 #define NB 3000 void setpixel(SDL_Surface * screen, int x, int y, Uint8 r, Uint8 g, Uint8 b) { if(x >= WIDTH || y >= HEIGHT || x < 0 || y < 0) return; Uint32 *pixmem32; Uint32 colour; colour = SDL_MapRGB(screen->format, r, g, b); pixmem32 = (Uint32 *) screen->pixels + screen->w * y + x; *pixmem32 = colour; } int main(void){ SDL_Surface *screen; SDL_Event event; if (SDL_Init(SDL_INIT_VIDEO) < 0) return 1; if (!(screen = SDL_SetVideoMode(WIDTH, HEIGHT, DEPTH, SDL_HWSURFACE))) { SDL_Quit(); return 1; } int keypress = 0; int k, i, j; double ft, D, dx, dy; double *px; double *py; double *m; double *fx; double *fy; double *vx; double *vy; px = (double *) malloc(sizeof(double) * NB); py = (double *) malloc(sizeof(double) * NB); m = (double *) malloc(sizeof(double) * NB); fx = (double *) malloc(sizeof(double) * NB); fy = (double *) malloc(sizeof(double) * NB); vx = (double *) malloc(sizeof(double) * NB); vy = (double *) malloc(sizeof(double) * NB); srand(time(0)); for(i = 0; i < NB + 1; i++){ px[i] = rand() % WIDTH; py[i] = rand() % HEIGHT; m[i] = rand() % 10 + 1; fx[i] = 0; fy[i] = 0; vx[i] = 0; vy[i] = 0; } while(1){ for(i = 0; i < NB; i++){ for(j = 0; j < NB; j++){ if(i == j) continue; dx = px[j] - px[i]; dy = py[j] - py[i]; D = sqrt(dx * dx + dy * dy); if(D < 5) D = 5; ft = m[i] * m[j] / (D * D); fx[i] += ft * dx / D; fy[i] += ft * dy / D; } } for(i = 0; i < NB; i++){ vx[i] += fx[i] / m[i]; vy[i] += fy[i] / m[i]; fx[i] = 0; fy[i] = 0; px[i] += vx[i]; py[i] += vy[i]; setpixel(screen, px[i], py[i], 255, 255, 255); } SDL_Flip(screen); SDL_FillRect(screen, NULL, 0x000000); } return(0); }
C
#include<stdio.h> #include<string.h> int main() { char str[104]; int i,T,j,sum,l; scanf("%d",&T); for(i=1;i<=T;i++){ sum = 0; scanf(" %[^\n]",str); l = strlen(str); for(j=0;j<l;j++){ if((str[j]=='a')||(str[j]=='d')||(str[j]=='g')||(str[j]=='j')||(str[j]=='m')||(str[j]=='p')||(str[j]=='t')|| (str[j]=='w')||(str[j]==' ')) sum += 1; else if((str[j]=='b')||(str[j]=='e')||(str[j]=='h')||(str[j]=='k')||(str[j]=='n')||(str[j]=='q')||(str[j]=='u')||(str[j]=='x')) sum+=2; else if((str[j]=='c')||(str[j]=='f')||(str[j]=='i')||(str[j]=='l')||(str[j]=='o')||(str[j]=='r')||(str[j]=='v')||(str[j]=='y')) sum+=3; else if((str[j]=='s')||(str[j]=='z')) sum+=4; } printf("Case #%d: %d\n",i,sum); } return 0; }
C
/* stmnt.c af_statement functions */ #include "arpfit.h" #include <sstream> /* -------------------------------------------------- */ /* Print functions */ /* -------------------------------------------------- */ char *af_statement::parsed() const { std::ostringstream ss; printOn(ss); return strdup(ss.str().c_str()); } void af_stmnt_assign::printOn(std::ostream& strm) const { strm << lvalue << " = " << value << ";" << std::endl; } void af_stmnt_arr_assign::printOn(std::ostream& strm) const { strm << "[" << lvalues << "] = " << function << ";" << std::endl; } void af_stmnt_fit::printOn(std::ostream& strm) const { strm << "Fit " << lvalue << " to " << fitexpr << ";" << std::endl; } void af_stmnt_fixflt::printOn(std::ostream& strm) const { std::vector<af_fix *>::const_iterator pos; int first = 1; for ( pos = list.begin(); pos != list.end(); ++pos ) { if ( first ) first = 0; else strm << ", "; strm << (*pos)->lvalue; if ( (*pos)->value ) { strm << " = " << (*pos)->value; } } if ( condition ) { strm << " if " << condition; } strm << ";" << std::endl; } void af_stmnt_fix::printOn(std::ostream& strm) const { strm << "Fix "; af_stmnt_fixflt::printOn(strm); } void af_stmnt_float::printOn(std::ostream& strm) const { strm << "Float "; af_stmnt_fixflt::printOn(strm); } void af_stmnt_constraint::printOn(std::ostream& strm) const { strm << "Constain " << lvalue; switch ( op ) { case Constrain_GE: strm << " >= "; break; case Constrain_LE: strm << " <= "; break; default: message(DEADLY,"Invalid Constrain_Op", 0, def); break; } strm << limit << ";" << std::endl; } void af_stmnt_init::printOn(std::ostream& strm) const { strm << "Initialize " << lvalue << " = " << value << ";" << std::endl; } void af_stmnt_loop::printOn(std::ostream& strm) const { strm << "while ()" << std::endl; } std::ostream& operator << (std::ostream& strm, const af_decl_list *dl ) { std::vector<af_variable *>::const_iterator pos; int first = 1; for ( pos = dl->decls.begin(); pos != dl->decls.end(); ++pos ) { if ( first ) first = 0; else strm << ", "; strm << *pos; } return strm; } // Instantiate( instance, n_elts ) // makes sure the specified instance exists and that the specified // number of elements is consistent with the definitions. // The variable may have been declared as indexed with a specific // declared_length, in which case, n_elts must either match or be // zero. If the variable was not declared, then it's declared_length // must be zero, and we'll use n_elts, even if it's zero. void af_variable::Instantiate( const const int instance, int n_elts ) { int length = declared_length; if ( indexed ) { // Might need to allow n_elts == 1 in this case if ( n_elts != 0 && n_elts != declared_length ) { message( ERROR, CatStrInd( "Declared length does not match assignment: ", sym ), 0, NoPosition ); } } else if ( declared_length != 0 ) { message( DEADLY, CatStrInd( "Expected zero length on unindexed var: ", sym ), 0, NoPosition ); } else { length = n_elts; } while ( instances.size() <= instance ) { instances.push_back(new af_var_inst( length )); } // check that the actual length is correct (may have been instantiated // somewhere else in the code?) int realsize = instances[instance]->elements.size(); if ( realsize == 0 && length != 0 ) { instances[instance]->elements.resize(length,0); } else if ( realsize != 0 && length != 0 ) { message( DEADLY, CatStrInd( "Instance length mismatch: ", sym )); } } af_expression *af_variable::get_instance( const int instance, int index ) { if ( instances.size() <= instance ) { message( DEADLY, CatStrInd( "Attempt to get before instantiation: ", sym ), 0, NoPosition ); } af_var_inst *vi = instances[instance]; if ( vi->elements.size() <= index ) { message( DEADLY, CatStrInd( "Index out of range in get_instance: ", sym ), 0, NoPosition ); } return vi->elements[index]; } void af_variable::set_instance( const int instance, int index, af_expression *expr ) { if ( instances.size() <= instance ) { message( DEADLY, CatStrInd( "Attempt to set before instantiation: ", sym ), 0, NoPosition ); } af_var_inst *vi = instances[instance]; if ( vi->elements.size() <= index ) { message( DEADLY, CatStrInd( "Index out of range in set_instance: ", sym ), 0, NoPosition ); } vi->elements[index] = expr; } //---------------------------------------------------------------- // Instantiation // Check to make sure index is within range // Check to make sure var has not already been instantiated // I will use zero length to indicate an as-yet-undefined length //--------- // Perhaps I had better just disable assignment to declared vectors // INDEPENDENTs will be considered scalars. In the future, assignment // of a simple vector to an INDEPENDENT can be made legal, but for // now, that can only be done via the array assignment syntax. //---------------------------------------------------------------- void af_stmnt_assign::Instantiate( const int instance ) const { int lcl_indexed = indexed; int lcl_index = index; int lcl_length = lvalue->declared_length; if ( lvalue->indexed && ! indexed ) { message( DEADLY, CatStrInd( "Invalid array assignment syntax: ", sym ), 0, def ); } if ( indexed ) { if ( ! lvalue->indexed ) { message( ERROR, CatStrInd( "Variable not declared as vector: ", lvalue->sym ), 0, def ); lcl_indexed = 0; // so we can continue error checking } else if ( index >= lvalue->declared_length ) { message( ERROR, "Index out of range", 0, def ); lcl_index = 0; // so we can continue error checking } } else { if ( index != 0 ) message( DEADLY, "index should be zero when not indexed", 0, def ); } af_expr_instance *ei = value->Instantiate(instance); int rlen = ei->length(); if ( rlen > 1 ) { message( DEADLY, "RHS is not a scalar", 0, def ); } lvalue->Instantiate( instance, indexed ? lvalue->declared_length : 1 ); if ( lvalue->get_instance( instance, lcl_index ) ) message( DEADLY, CatStrInd( "Variable redefined: ", sym ), 0, def ); lvalue->set_instance( instance, lcl_index, ei ); } // LHS are all instantiated as INPUTs // All args must be INPUTs void af_stmnt_arr_assign::Instantiate( const int instance ) const { } void af_stmnt_fit::Instantiate( const int instance ) const { } void af_stmnt_fix::Instantiate( const int instance ) const { } void af_stmnt_float::Instantiate( const int instance ) const { } void af_stmnt_constraint::Instantiate( const int instance ) const { } void af_stmnt_init::Instantiate( const int instance ) const { } void af_stmnt_loop::Instantiate( const int instance ) const { }
C
#pragma once void multiply(int F[2][2], int M[2][2]) { int x = F[0][0]*M[0][0] + F[0][1]*M[1][0]; int y = F[0][0]*M[0][1] + F[0][1]*M[1][1]; int z = F[1][0]*M[0][0] + F[1][1]*M[1][0]; int w = F[1][0]*M[0][1] + F[1][1]*M[1][1]; F[0][0] = x; F[0][1] = y; F[1][0] = z; F[1][1] = w; } void power(int F[2][2], int n) { if (n < 2) return; int M[2][2] = {{1, 1},{1, 0}}; power(F, n/2); multiply(F, F); if (n & 1) multiply(F, M); } int Fibonacci(int n) { int F[2][2] = {{1, 1},{1, 0}}; if (n==0) return 0; power(F, n - 1); return F[0][0]; }
C
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include "types.h" SP_Answer splitPlainMsg(char *rcvBuffer);/*버퍼 내용을 구조체로 변환하는 함수*/ SP_Alternative splitModifiedMsg(char *rcvBuffer);/*버퍼 내용을 구조체로 변환하는 함수*/ void plainAnswerHandler(SP_Answer rcvdAnswer, int *loop);/*기본 응답 처리*/ void modifiedAnswerHandler(SP_Alternative rcvdModified);/*수정 응답 처리*/ /* 서버의 메세지를 Type에 따라 분류하는 함수 */ void typeCheckerRcvdMsg(char *rcvBuffer, int *loop){ SP_Answer rcvdAnswer;/*기본 응답 메세지 구조체*/ SP_Alternative rcvdModified;/*수정 응답 메세지 구조체*/ /* TYPE 헤더에 따른 처리 */ switch(rcvBuffer[0]){ case SP_ANSWER:/* plain answer */ printf("Answer>> "); /* 버퍼의 내용을 구조체로 변환 */ rcvdAnswer = splitPlainMsg(rcvBuffer); /* 구조체를 이용한 기본응답 처리 */ plainAnswerHandler(rcvdAnswer, loop); break; case SP_MODIFY:/* modified answer */ /* 버퍼 내용을 구조체로 변환 */ rcvdModified = splitModifiedMsg(rcvBuffer); /* 구조체를 이용한 수정응답 처리 */ modifiedAnswerHandler(rcvdModified); *loop = 0; break; default: return; } } /*기본응답: 버퍼 내용을 구조체로 변환*/ SP_Answer splitPlainMsg(char *rcvBuffer){ SP_Answer rcvdAnswer; /* type 처리 */ rcvdAnswer.type = *rcvBuffer++; /* result 처리 */ rcvdAnswer.result = *rcvBuffer++; /* detail 처리 */ rcvdAnswer.detail = *rcvBuffer++; /* data 처리 */ strcpy(rcvdAnswer.data, rcvBuffer); return rcvdAnswer; } /*수정응답: 버퍼 내용을 구조체로 변환*/ SP_Alternative splitModifiedMsg(char *rcvBuffer){ SP_Alternative rcvdModified; /* type 처리 */ rcvdModified.type = *rcvBuffer++; /* data 처리 */ strcpy(rcvdModified.data, rcvBuffer); return rcvdModified; } /*기본응답: 구조체를 이용한 기본응답 처리*/ void plainAnswerHandler(SP_Answer rcvdAnswer, int *loop){ /* result 값에 따른 처리 */ switch(rcvdAnswer.result){ case ANSWER_SUCCESS:/* Success */ printf(" Detail LV : %c\n\t %s\n", rcvdAnswer.detail, rcvdAnswer.data); break; case ANSWER_NOTFOUND:/* Not Found */ printf(" 요청에 대한 결과를 찾을 수 없습니다.\n"); *loop = 1; break; case ANSWER_GRADELOW:/* Permission deny */ printf(" 표시할 수 없는 응답입니다.\n"); break; } } /*수정응답: 구조체를 이용한 수정응답 처리*/ void modifiedAnswerHandler(SP_Alternative rcvdModified){ char *strToken; printf("\t<< 다른 검색어 제안 >>\n"); /* TOKEN으로 구분 */ strToken = strtok(rcvdModified.data, "|"); while(strToken != NULL){ printf("\t %s\n", strToken); strToken = strtok(NULL, "|"); } }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* copy_paste.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: mfamilar <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2016/05/11 15:08:25 by mfamilar #+# #+# */ /* Updated: 2016/07/19 12:46:22 by Marco ### ########.fr */ /* */ /* ************************************************************************** */ #include "../../include/minishell.h" void copy_tmpline(t_it *it) { ft_memdel((void**)&it->tmp_buffer); it->tmp_buffer = ft_strdup(it->line); } static void paste_existing_line(t_it *it) { char *tmp; char *tmp2; char *tmp3; tmp = ft_memalloc(sizeof(char) * it->len + ft_strlen(it->tmp_buffer) + 1); ft_strncpy(tmp, it->line, it->i); tmp2 = ft_strsub(it->line, it->i, it->len); tmp3 = ft_strjoin(tmp, it->tmp_buffer); ft_memdel((void**)&it->line); it->line = ft_strjoin(tmp3, tmp2); it->len = ft_strlen(it->line); free_elements(tmp, tmp2, tmp3, NULL); } void paste_line(t_it *it) { if (!it->tmp_buffer) return ; else if (!it->line) { it->line = ft_strdup(it->tmp_buffer); it->len = ft_strlen(it->line); } else paste_existing_line(it); multi_line_text(it); move_n_char(it, KR, ft_strlen(it->tmp_buffer)); }
C
#include <stdio.h> int main() { long long n; long long k; long long m; long long sum; scanf("%lld %lld", &n, &k); sum = n; m = sum; while (m - k >= 0) { m = m - k; sum++; m++; } printf("%lld", sum); return 0; }
C
/* ** EPITECH PROJECT, 2018 ** libmy ** File description: ** memset.c */ #include "my/memory.h" void *my_memset(void *dest, byte_t c, size_t n) { byte_t *d = dest; if (!dest || n == 0) return (NULL); while (n--) *d++ = c; return (dest); }