language
string
src_encoding
string
length_bytes
int64
score
float64
int_score
int64
detected_licenses
sequence
license_type
string
text
string
C
UTF-8
1,279
4.09375
4
[]
no_license
#include <stdio.h> #include <time.h> int binsearch(int x, int v[], int n); int binsearch_better(int x, int v[], int n); int main() { int sorted_array[] = {0,1,2,3,4,5,6,7,8,9}; clock_t start, end; start = clock(); int bin1res = binsearch(4,sorted_array,10); end = clock(); double time_taken = (double)(start - end) / CLOCKS_PER_SEC; printf("Result is %d, took %f sec to execute.\n", bin1res, time_taken); start = clock(); int bin2res = binsearch_better(6,sorted_array,10); end = clock(); time_taken = (double)(start - end) / CLOCKS_PER_SEC; printf("Result is %d, took %f sec to execute\n", bin2res, time_taken); return 0; } // Binary search but better int binsearch_better(int x, int v[], int n) { int low, high, mid; low = 0; high = n -1; mid = (low + high)/2; while(low <= high) { if(x < v[mid]) { high = mid - 1; } else { low = mid + 1; } mid = (low + high) / 2; } if(x == v[mid]) { return mid; } else return -1; } // Binary search: Find x in v[0] <= v1 <= .... v[n-1] int binsearch(int x, int v[], int n) { int low, high, mid; low = 0; high = n - 1; while(low <= high) { mid = (low + high)/2; if(x < v[mid]) { high = mid + 1; } else if(x > v[mid]) { low = mid + 1; } else return mid; } return -1; }
C
UTF-8
356
2.796875
3
[]
no_license
#include <stdio.h> #include <math.h> int main(){ int a,b,tmp,k,a_lose; while(2==scanf("%d%d",&a,&b)){ if(a>b){tmp=a;a=b;b=tmp;} k = b-a; /* 2012-9-11 * Found the mysterious formula here * http://blog.csdn.net/manio/article/details/589172 */ if(a==(int)(k*(1.0+sqrt(5))/2.0)){ printf("%d\n",0); }else{ printf("%d\n",1); } } }
C
UTF-8
3,315
2.546875
3
[]
no_license
#include "data_link_layer.h" char* lastData; int serial_fd; int turnPacket = 0; void createErrors(unsigned char* buffer, int size); unsigned char generateBCC(unsigned char* buf, int size); int destuffing(unsigned char* tram, unsigned char* buf, int size); void processTram(unsigned char* tram, unsigned char* buf, int size, statistics_t *stats); void sendREJ(); void sendRR(); int llread(int fd, unsigned char* buf, statistics_t *stats) { serial_fd = fd; int reading = TRUE; int nread; unsigned char* buffer = malloc(BUF_SIZE*2*sizeof(unsigned char)); lastData = calloc(BUF_SIZE, sizeof(char)); int i = 0; while (reading) { nread = read(serial_fd, buffer + i, 1); if (nread < 0) { printf("Error reading from serial port on llread"); return 1; } if (i != 0 && buffer[i] == 0x7E){ reading = FALSE; stats->packets += 1; //createErrors(buffer, i); processTram(buffer, buf, i, stats); } i += nread; } return i; } void createErrors(unsigned char* buffer, int size){ int chanceData = rand() % 100; if(chanceData < PROBABILITY_DATA){ int byte = rand() % (size - 3) + 4; buffer[byte] = ~buffer[byte]; } int chanceHeader = rand() % 100; if(chanceHeader < PROBABILITY_HEADER){ int byteH = rand() % 3 + 1; buffer[byteH] = ~buffer[byteH]; } } int destuffing(unsigned char* tram, unsigned char* buf, int size) { int destuffing = 1; int i = 4, j = 0; while(destuffing){ if (i == size || j == size) return j; if(tram[i] == 0x7E){ destuffing = 0; return j; } else if(tram[i] == 0x7D && tram[i + 1] == 0x5E){ buf[j] = 0x7E; j++; i+=2; } else if(tram[i] == 0x7D && tram[i + 1] == 0x5D){ buf[j] = 0x7D; j++; i+=2; } else { buf[j] = tram[i]; j++; i++; } } return j; } void processTram(unsigned char* tram, unsigned char* buf, int size, statistics_t * stats){ char bcc1 = tram[3]; if (bcc1 != (tram[1] ^ tram[2])) { sendREJ(&stats->rej); return; } int j = destuffing(tram, buf, size); unsigned char bcc2 = buf[j - 1]; int check = generateBCC(buf, j); if (bcc2 != check) { free(buf); sendREJ(&stats->rej); return; } int isNew = memcmp(buf, lastData, j - 1) == 0 ? FALSE : TRUE; if(((turnPacket == 0 && tram[2] == 0x00) || (turnPacket == 1 && tram[2] == 0x40)) && isNew){ turnPacket = turnPacket == 1 ? 0 : 1; sendRR(&stats->rr); memcpy(lastData, buf, j - 1); return; } else if(((turnPacket == 1 && tram[2] == 0x00) || (turnPacket == 0 && tram[2] == 0x40)) && !isNew){ free(buf); sendRR(&stats->rr); return; } else { free(buf); sendREJ(&stats->rej); return; } } unsigned char generateBCC(unsigned char* buf, int size) { unsigned char bcc = buf[0]; int i; for (i = 1; i < size - 1; i++) { bcc ^= buf[i]; } return bcc; } void sendREJ(int * c_rej) { unsigned char rej[] = { 0x7E, 0x03, 0x01, 0x03, 0x7E }; rej[2] = (turnPacket == 0 ? 0x01 : 0x81); rej[3] = rej[1] ^ rej[2]; int n = write(serial_fd, rej, 5); if (n < 0) perror("Failed to write to serial port in sendREJ\n"); *c_rej += 1; } void sendRR(int * c_rr) { unsigned char rr[] = { 0x7E, 0x03, 0x05, 0xF3, 0x7E }; rr[2] = (turnPacket == 0 ? 0x05 : 0x85); rr[3] = rr[1] ^ rr[2]; int n = write(serial_fd, rr, 5); if (n < 0) perror("Failed to write to serial port in sendRR\n"); *c_rr += 1; }
C
UTF-8
1,590
3.40625
3
[]
no_license
#include "common.h" // Echoes back whatever client sends to this UDP server int mat_ind = -1; int *matrix[MAX_ROWS]; void displayMatrix() { printf("\nDisplay Matrix\n"); if (mat_ind == -1) { printf("Empty Matrix\n"); return; } for (int i = 0; i <= mat_ind; i++) { for (int j = 0; j < ROW_LEN; j++) { printf("%d ", matrix[i][j]); } printf("\n"); } } int main() { int sockfd; struct sockaddr_in serv_addr, cli_addr; int buffer[ROW_LEN]; memset(&serv_addr, 0, sizeof(serv_addr)); serv_addr.sin_family = AF_INET; serv_addr.sin_addr.s_addr = htonl(INADDR_ANY); serv_addr.sin_port = htons(PORT); if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) == -1) { perror("Error creating socket: "); exit(EXIT_FAILURE); } if (bind(sockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) == -1) { perror("Error binding socket: "); exit(EXIT_FAILURE); } printf("Server listening on PORT %d\n", PORT); while (1) { unsigned int cli_len = sizeof(cli_addr); size_t len_recvd = recvfrom(sockfd, buffer, sizeof(buffer), 0, (struct sockaddr *)&cli_addr, &cli_len); if (len_recvd > 0) { mat_ind++; matrix[mat_ind] = calloc(ROW_LEN, sizeof(int)); for (int i = 0; i < ROW_LEN; i++) { matrix[mat_ind][i] = buffer[i]; } displayMatrix(); } } printf("Server shutting down\n"); return 0; }
C
UTF-8
2,622
3.03125
3
[]
no_license
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* get_next_line.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: onapoli- <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/08/15 13:36:25 by onapoli- #+# #+# */ /* Updated: 2020/09/02 11:10:10 by onapoli- ### ########.fr */ /* */ /* ************************************************************************** */ #include "get_next_line.h" static char *ft_get_line(char *s) { int i; int j; char *line; i = 0; while (s[i] && s[i] != '\n') i++; if (s[i] != '\n') return (0); if (!(line = malloc(sizeof(char) * (i + 1)))) return (0); line[i] = 0; j = 0; while (j < i) { line[j] = s[j]; j++; } return (line); } static char *ft_get_after_line(char *s) { int i; i = 0; while (s[i] && s[i] != '\n') i++; return (&s[++i]); } static void ft_save_buffer(char **s_memory, char *buffer, int fd) { char *aux; aux = ft_strjoin(s_memory[fd], buffer); free(s_memory[fd]); s_memory[fd] = ft_strdup(aux); free(aux); } static int ft_line_result(char **s_memory, char **line, int fd) { char *aux; if (ft_check_nl(s_memory[fd])) { if (*line) free(*line); *line = ft_get_line(s_memory[fd]); aux = ft_strdup(ft_get_after_line(s_memory[fd])); free(s_memory[fd]); s_memory[fd] = ft_strdup(aux); free(aux); return (1); } if (*line) free(*line); *line = ft_strdup(s_memory[fd]); free(s_memory[fd]); s_memory[fd] = 0; return (0); } int get_next_line(int fd, char **line) { static char *s_memory[4096]; char *buffer; int bytes_read; if (fd < 0 || !line || BUFFER_SIZE <= 0) return (-1); if (!s_memory[fd]) s_memory[fd] = ft_strdup(""); else if (ft_check_nl(s_memory[fd])) return (ft_line_result(s_memory, line, fd)); if (!(buffer = malloc(sizeof(char) * (BUFFER_SIZE + 1)))) return (-1); bytes_read = 1; while (bytes_read != 0) { if ((bytes_read = read(fd, buffer, BUFFER_SIZE)) == -1) return (-1); buffer[bytes_read] = 0; ft_save_buffer(s_memory, buffer, fd); if (ft_check_nl(s_memory[fd])) break ; } free(buffer); return (ft_line_result(s_memory, line, fd)); }
C
UTF-8
1,377
3.359375
3
[]
no_license
#include <stdio.h> #include<conio.h> #define column 1 #define row 1 #define ENTER 13 #define ESC 27 #define UP 72 #define DOWN 80 void main (void) { int i, counter=0, flag=0; char c, n[20]; clrscr(); while (flag==0) { gotoxy(column,row); printf("Name:"); gotoxy(column,row+1); printf("Number:"); gotoxy(column,row+2); printf("Address:"); gotoxy(column,row+3); printf("Exit"); gotoxy(column,row); c = getch(); while(c!=ESC) { if(c == NULL) { c = getch(); switch (c) { case DOWN : counter++; //((row+counter) = cursor position) if((counter+row)>4) {counter=0;} gotoxy(column,row+counter); break; case UP : counter--; if((row+counter)<1) {counter=3;} gotoxy(column,row+counter); break; } } else if (c == ENTER) { if((row+counter)==1) { clrscr(); printf("please enter your name:"); gets(n); clrscr(); break; } if((row+counter)==2) { clrscr(); printf("please enter your number:"); gets(n); clrscr(); break; } if((row+counter)==3) { clrscr(); printf("please enter your Address:"); gets(n); clrscr(); break; } if((row+counter)==4) { clrscr(); flag=1; break; } } c = getch(); } } }
C
UTF-8
4,215
3
3
[]
no_license
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <signal.h> #include <sys/wait.h> #include <sys/types.h> #include <fcntl.h> struct Node{ int id; int connections[10]; char* comp; struct Node *prox; }; typedef struct Node node; char **split(char *buf){ int i = 0, n = 0; char **result; result = malloc(10*sizeof(char*)); result[n++] = buf; while(buf[i]){ if(buf[i] == ' '){ buf[i] = '\0'; result[n++] = buf+1+i; } i++; } return result; } int readLine(int fd, char **line, int *size){ char buff, *str = *line; int elems, res; elems = res = 0; while((res = read(fd, &buff, 1)) > 0 && buff != '\n' && buff != '\0'){ if(elems > *size){ if(realloc(str, (*size)*2)==NULL){ return -1; } *size *= 2; } str[elems++] = buff; } if(elems > *size){ if(realloc(str, (*size) + 1) == NULL){ return -1; } *size += 1; } str[elems] = '\0'; *line = str; if(res > 0) return elems; else if (res == 0) return 0; else return -1; } void iniciaLista(node *REDE, int id, char* comp){ node* aux = REDE; aux->id = id; aux->connections[0] = '\0'; aux->comp = malloc(100*sizeof(char)); aux->comp = comp; aux->prox = NULL; } void insereLista(node *REDE, int id, char* comp){ node* aux = REDE; node* newnode = (node*)malloc(sizeof(node)); newnode->id = id; newnode->connections[0] = '\0'; newnode->comp = malloc(100*sizeof(char)); newnode->comp = comp; while(aux->prox != NULL){ aux = aux->prox; } aux->prox = newnode; aux->prox->prox = NULL; } void lerLista(node *REDE){ node *aux = REDE; while(aux){ printf("%d, %s\n", aux->id, aux->comp); aux = aux->prox; } } char* agrupaWinFil(char **linha){ char *line = malloc(100*sizeof(char)); strcpy(line, linha[2]); strcat(line, " "); strcat(line, linha[3]); strcat(line, " "); strcat(line, linha[4]); strcat(line, " "); strcat(line, linha[5]); return line; } char* agrupaConstTee(char **linha){ char *line = malloc(100*sizeof(char)); strcpy(line, linha[2]); strcat(line, " "); strcat(line, linha[3]); return line; } char* agrupaSpawn(char **linha){ char *line = malloc(100*sizeof(char)); strcpy(line, linha[2]); strcat(line, " "); strcat(line, linha[3]); strcat(line, " "); strcat(line, linha[4]); return line; } void insereConnections(node *REDE, char **linha){ node* aux = REDE; int idA, i, j, num; idA = atoi(linha[1]); while(aux){ if(aux->id == idA){ for(i=2,j=0; linha[i] != '\0'; i++,j++){ num = atoi(linha[i]); aux->connections[j] = num; } aux->connections[j]='\0'; } aux = aux->prox; } } void lerApenas(node *REDE){ int i; node* aux = REDE; while(aux){ for(i = 0; aux->connections[i] != '\0'; i++){ printf("id: %d------> connections :%d\n", aux->id ,aux->connections[i]); } aux = aux->prox; } } void inserirStruct(char **line, node *REDE, int flag){ int num; char *linha = malloc(100*sizeof(char)); char **linhaFich = (char**) malloc(100*sizeof(char*)); linhaFich = line; if(!strcmp(line[0], "node")){ if(!strcmp(line[2], "window") || !strcmp(line[2], "filter")){ linha = agrupaWinFil(linhaFich); num = atoi(line[1]); if(!flag) iniciaLista(REDE, num, linha); else insereLista(REDE, num, linha); } else{ if(!strcmp(line[2], "const") || !strcmp(line[2], "tee")){ linha = agrupaConstTee(linhaFich); num = atoi(line[1]); insereLista(REDE, num, linha); } else{ linha = agrupaSpawn(linhaFich); num = atoi(line[1]); insereLista(REDE, num, linha); } } } else{ if(!strcmp(line[0], "connect")){ insereConnections(REDE, linhaFich); } } } void lerInserir(){ char *nome = "testes.txt"; node *REDE = (node*)malloc(sizeof(node)); int file, size, size_line = 100, flag = 0; char *line, **strcomp = (char**) malloc(100*sizeof(char*)); line = calloc(size_line, sizeof(char)); file = open(nome, O_RDWR); while((size = readLine(file, &line, &size_line)) > 0){ strcomp = split(line); if(!flag){ inserirStruct(strcomp, REDE, flag); flag = 1; } else{ inserirStruct(strcomp, REDE, flag); } } //lerLista(REDE); //lerApenas(REDE); }
C
UTF-8
99
2.5625
3
[]
no_license
#include<stdio.h> int main() { int a=10; a<5?printf("Hai"):printf("Bye"); return 0; }
C
UTF-8
4,153
2.65625
3
[]
no_license
// Pure C String and Parsing Utilities, Paul D. Senzee (c) 2000-2011 #ifndef _STRS_C_H #define _STRS_C_H #include <string.h> #define _bool int #define _true 1 #define _false 0 #ifdef __cplusplus extern "C" { #endif #ifndef WIN32 #define stricmp strcasecmp #define strnicmp strncasecmp int memicmp(const void *s1, const void *s2, size_t n); #endif char *strs_strdup(const char *s); int strs_strlistcount(const char **p); char **strs_strlistdup(const char **p); void strs_destroy_strlist(char **p); void strs_skip_space(const char **s); void strs_skip_space_not_newline(const char **s); // the strs_is*() and strs_read*() functions below skip preceeding whitespace // strs_is*() - is it a string followed by '\0' or: // a space (is), // one of the characters specified (is_and_followed_by_any), // or not one of the characters specified (is_and_not_followed_by_any)? _bool strs_is(const char **s, const char *match, _bool ignorecase); _bool strs_is_and_followed_by_space(const char **s, const char *match, _bool ignorecase); _bool strs_is_and_followed_by_any_of(const char **s, const char *match, const char *after, _bool ignorecase); _bool strs_is_and_not_followed_by_any_of(const char **s, const char *match, const char *after, _bool ignorecase); _bool strs_read_quoted(const char **s, char quote, char *buffer, _bool escape); _bool strs_read_identifier_of(const char **s, char *buffer, const char *of); _bool strs_read_float(const char **s, float *u); _bool strs_read_int(const char **s, int *u); _bool strs_read_uint(const char **s, unsigned *u); const char *strs_find(const char *s, const char *f, _bool ignorecase); unsigned strs_count(const char *s, const char *f, _bool ignorecase); _bool strs_ends(const char *data, const char *substr, _bool ignorecase); _bool strs_starts(const char *data, const char *substr, _bool ignorecase); char **strs_split_char_of(const char *in, const char *of); char **strs_split_char_of_keep_empty(const char *in, const char *of); const char *strs_extension(const char *filename); void strs_replace_char(char *s, char f, char r); void strs_replace_chars(char *s, const char *f, char r); char *strs_replace(const char *s, const char *f, const char *r, _bool ignorecase); _bool strs_isspace(const char *s); _bool strs_isdigit(const char *s); _bool strs_isupper(const char *s); _bool strs_islower(const char *s); unsigned strs_count_char(const char *p, char c); unsigned strs_count_char_of(const char *s, const char *of); _bool strs_composed_of(const char *s, const char *of); char *strs_first_not_of(char *p, const char *of); char *strs_first_of(char *p, const char *of); char *strs_last_not_of(char *p, const char *of); char *strs_last_of(char *p, const char *of); char *strs_first_not_space(char *p); void strs_destructive_rtrim(char *p); void strs_destructive_ltrim(char *p); void strs_destructive_rtrim_of(char *p, const char *of); void strs_destructive_ltrim_of(char *p, const char *of); void strs_destructive_trim(char *p); void strs_destructive_trim_of(char *p, const char *of); void strs_destructive_trim_of_lr(char *p, const char *of_l, const char *of_r); char *strs_trim(const char *p); char *strs_trim_of(const char *p, const char *of); typedef int (*strs_char_transform_fn)(int ch); void strs_destructive_transform(char *s, strs_char_transform_fn fn); void strs_destructive_toupper(char *s); void strs_destructive_tolower(char *s); void strs_copy_transform(const char *s, char *t, strs_char_transform_fn fn); void strs_copy_toupper(const char *s, char *t); void strs_copy_tolower(const char *s, char *t); #ifdef __cplusplus } #endif #endif // _STRS_H
C
UTF-8
2,184
2.75
3
[]
no_license
#include "irobotsensors.h" /// Checks all of the sensors on the iRobot body (Cliff, Bump, Wheel drop, Virtual Wall) and stops /// the robot if it detects any of these sensors. /** * Checks the sensor son the iRobot and stops movement if it detects a condition where it * needs to stop. If it detects such an event, it will transmit a description via bluetooth to the computer * * @return the constant value (as defined in irobotsensors.h) defining which sensor caused the stop. 0 if * the robot didn't stop */ int checkSensors() { oi_update(iBambi); char str[30]; int sense = 0; if (iBambi->wheeldrop_right) { oi_set_wheels(0, 0); sprintf(str, "Wheel Drop Right\n\r"); usart_transmit(str); sense = WHEEL_RIGHT; } if (iBambi->wheeldrop_left) { oi_set_wheels(0, 0); sprintf(str, "Wheel Drop Left\n\r"); usart_transmit(str); sense = WHEEL_LEFT; } if (iBambi->wheeldrop_caster) { oi_set_wheels(0, 0); sprintf(str, "Wheel Drop Caster\n\r"); usart_transmit(str); sense = WHEEL_CASTER; } if (iBambi->cliff_frontright) { oi_set_wheels(0, 0); sprintf(str, "Cliff Right Front\n\r"); usart_transmit(str); sense = CLIFF_RIGHT; } if (iBambi->cliff_frontleft) { oi_set_wheels(0, 0); sprintf(str, "Cliff Left Front\n\r"); usart_transmit(str); sense = CLIFF_LEFT; } if (iBambi->cliff_left) { oi_set_wheels(0, 0); sprintf(str, "Cliff Left\n\r"); usart_transmit(str); sense = CLIFF_LEFT; } if (iBambi->cliff_right) { oi_set_wheels(0, 0); sprintf(str, "Cliff Right\n\r"); usart_transmit(str); sense = CLIFF_RIGHT; } if (iBambi->virtual_wall) { oi_set_wheels(0, 0); sprintf(str, "Virt Wall\n\r"); usart_transmit(str); sense = VIRTUAL_WALL; } if (iBambi->bumper_left && iBambi->bumper_right) { oi_set_wheels(0, 0); sprintf(str, "Front Bumper\n\r"); usart_transmit(str); sense = BUMPER_CENTER; } else if (iBambi->bumper_left) { oi_set_wheels(0, 0); sprintf(str, "Left Bumper\n\r"); usart_transmit(str); sense = BUMPER_LEFT; } else if (iBambi->bumper_right) { oi_set_wheels(0, 0); sprintf(str, "Right Bumper\n\r"); usart_transmit(str); sense = BUMPER_RIGHT; } return sense; }
C
UTF-8
2,432
3.71875
4
[]
no_license
/*循环三要素:循环变量的初值、循环变量的判断、循环变量的更新 while循环的特点:先判断,再执行 */ #include <stdio.h> int main() { int i=0; while(i<10) { i++; //通过控制i的值来控制循环的次数 printf("第%d遍\n",i); } return 0; } //计算1-100累加和 #include <stdio.h> int main() { int i=0; int sum=0; while(i<100) { i++; sum=sum+i; } printf("sum=%d",sum); return 0; } //使用循环实现三次密码输入,输错就退出 #include <stdio.h> int main() { int i=0; int password; while(i<3) { printf("请输入密码:\n"); scanf("%d",&password); if(123456!=password) { printf("输入错误!\n"); } if(i==2) { printf("密码输错3次,强制退出系统!"); exit(0); //告诉操作系统,程序正常退出 } i++; } return 0; } //某宝双2015年双11交易额为800亿,每年递增25%,哪年交易额到2000亿 #include <stdio.h> int main() { double money=800; double rate=1.25; int year=2015; while(money<2000) { money=money*rate; year++; } printf("year=%d",year); return 0; } *************************************************** //补充:随机数种子 #include <stdio.h> #include <stdlib.h> #include <time.h> int main() { //srand用时间做种子,每次产生随机数不一样 srand((unsigned) time(NULL)); //rand()取值范围:0-32767 printf("%d\n",rand()); return 0; } //使用循环实现玩家对战 //双方初始HP均为100,每次攻击5-15中随机,HP最先到0或以下的被KO #include <stdio.h> #include <stdlib.h> //标准库 #include <time.h> //time #include <windows.h> //sleep int main() { int hp1=100; int hp2=100; int i=0; //对战轮数 int att1,att2; while(hp1>=0 && hp2>=0) { //默认1p首先攻击 //x % 5 取值0-4 x % 10 取值0-9 以此类推 //x % 16+5 取值5-15 att1=rand()%11+5; //取值为5-15之间 if(att1==15) //暴击 att1*2; att2=rand()%11+5; if(att2==15) att2*2; hp2=hp2-att1; hp1=hp1-att2; printf("************************\n"); printf("第%d轮\n",i+1); printf("玩家一攻击力%d,玩家二剩余血量:%d\n",att1,hp2); printf("玩家二攻击力%d,玩家一剩余血量:%d\n",att2,hp1); printf("************************\n"); i++; Sleep(500); //每隔500毫秒打印一次 } printf("游戏结束!玩家一的血量:%d\t玩家二的血量%d\n",hp1,hp2); return 0; }
C
UTF-8
1,085
3.28125
3
[]
no_license
/* * diagnostic.c * * Created on: Apr 17, 2019 * Author: messi */ #include "diagnostic.h" // Display Queue xQueueHandle Q_Display ; void Init_DisplayDiagnostic(void){ /* * Description: * Initialize Empty Queue for Messages to be sent on * Usage: * 1-create variable of type "DisplayStruct_t" * 2-use "Diagnostics_Display('your message')" function * NOTE: always keep ur message below 16 character */ Q_Display = xQueueCreate(5,sizeof(DisplayStruct_t)); // Display Queue , up to 5 Messages } void Diagnostics_Display(char *str){ /* * Description: * Used to send Diagnostic Messages to be displayed by Display Task * Also used in case of an error message should be displayed */ DisplayStruct_t Message; // Message Structure // msg length should always be less than 16 characters for(int index=0;index<16;index++){ Message.content[index]=str[index]; // load message content } // Send Message into Queue (Q_Display) xQueueSend(Q_Display,&Message,TIMEOUT_200ms); // Now Display Function will Handle all incoming Messages }
C
UTF-8
529
3.40625
3
[ "MIT" ]
permissive
#include <stdio.h> #include <string.h> #include <math.h> #include <stdlib.h> int main() { char *s; s = malloc(1024 * sizeof(char)); scanf("%[^\n]", s); s = realloc(s, strlen(s) + 1); //Write your logic to print the tokens of the sentence here. //Extract first token char * token = strtok(s , " "); //Extract all possible tokens while(token!=NULL) { //print each token printf("%s \n" , token); token = strtok(NULL , " "); } return 0; }
C
UTF-8
3,323
2.53125
3
[]
no_license
/* $Revision: 1.2 $ */ #include "common.h" #include "cpu.h" #include "kern.h" #include "sem.h" #include "shell.h" #include "string.h" #define SHELL_PRI 1000 /* pretty high */ char shell_stack[1024]; tcb_t shell_tcb; extern char *optarg; extern int optind; extern int dump(); extern int trap(); int help(void); int do_trap(int argc, char **argv); int md(int argc, char **argv); #define MAX_ARGS 10 static cmd_t builtins[] = { {"help", "", help, "help command"}, {"?", "", help, "help command"}, {"ps", "", ps, "list status of all tasks"}, {"md", "addr len", md, "display memory"}, {"trap", "num", do_trap, "trap instruction"}, {0} }; int help(void) { cmd_t *cp = builtins; kprintf("%20s %20s %30s\n", "COMMAND", "ARGUMENTS", "DESCRIPTION"); while (cp->name) { if (cp->help) kprintf("%20s %20s %30s\n", cp->name, cp->args ? cp->args : "", cp->help); cp++; } } int md(int argc, char **argv) { if (argc < 3) { kprintf("usage: md addr len\n"); return; } dump(atoi(argv[1]), atoi(argv[2])); } int do_trap(int argc, char **argv) { if (argc < 2) { kprintf("usage: trap num\n"); return; } trap(atoi(argv[1])); } cmd_t * valid_cmd(char *s) { int i; cmd_t *cp = builtins; int len; if (!s) return 0; while (cp->name) { len = strlen(cp->name); if (strncmp(cp->name, s, len) == 0) return cp; cp++; } return 0; } char * skip_spaces(char *str) { if (!str) return 0; while (*str && isspace(*str)) str++; if (*str) return str; return 0; } void exec_cmd(cmd_t * cp, char *arg) { int len; int i; char *save; char *argv[MAX_ARGS + 1]; if (!cp->func) return; if (!arg) return; len = strlen(cp->name); arg += len; argv[0] = cp->name; for (i = 1; i < MAX_ARGS; i++) { arg = skip_spaces(arg); if (arg) { save = argv[i] = arg; if (arg = index(arg, ' ')) { argv[i][arg - save] = '\0'; arg++; } } else break; } argv[i] = 0; (*cp->func) (i, argv); } void shell_init(void) { if (spawn(&shell_tcb, "shell", shell_stack, shell_task, sizeof(shell_stack), SHELL_PRI, 0) < 0) panic("shell_init: spawn failed for shell\n"); exec(&shell_tcb); } int shell_task(void) { char buf[BUFSIZ]; /* XXX */ char *cp = buf; cmd_t *kp; for (;;) { kprintf("> "); if (readline(cp) < 0) continue; if (kp = valid_cmd(cp)) exec_cmd(kp, cp); else if (strlen(cp)) kprintf("Invalid command <%s>\n", cp); } } void backspace(void) { kputchar(''); kputchar(' '); kputchar(''); } int readline(char *s) { char *cp = s; char ch = '\0'; while (!isnewline(ch)) { *cp++ = ch = getchar(); switch (ch) { case '': /* bs */ case 0x7f: /* del */ if (--cp > s) { backspace(); cp--; } break; case '': while (--cp > s) backspace(); break; case '': return -1; default: kputchar(ch); break; } } *--cp = '\0'; return (int) (cp - s); }
C
GB18030
493
3.5
4
[]
no_license
//ʾַַƶм #include<stdio.h> #include<windows.h> #include<stdlib.h> int main() { char arr1[] = "Welcome to my room!!!"; char arr2[] = "######################"; int left = 0; int right= (sizeof(arr1) / sizeof(arr1[0])) - 2; while (left <= right) { arr2[left] = arr1[left]; arr2[right] = arr1[right]; printf("%s\n",arr2); Sleep(1000); system("cls"); left++; right--; } printf("Welcome to my room!!!\n"); return 0; }
C
UTF-8
463
3.609375
4
[]
no_license
#include "binary_trees.h" /** *binary_tree_sibling-finds the sibling of a node *@node:a pointer to the node to find the sibling * *Return: a pointer to the sibling node or NULL if faileur */ binary_tree_t *binary_tree_sibling(binary_tree_t *node) { if (!node || !node->parent) return (NULL); if (!node->parent->left && !node->parent->right) return (NULL); if (node->parent->right == node) return (node->parent->left); else return (node->parent->right); }
C
UTF-8
3,268
2.90625
3
[ "BSD-2-Clause" ]
permissive
/* Operations: - 6 shifts - 4 bit-and - 3 bit-or */ uint32_t nibble_expand_naive(uint32_t x) { assert(x <= 0xffff); const uint32_t n0 = x & 0x0f; const uint32_t n1 = (x >> 4) & 0x0f; const uint32_t n2 = (x >> 8) & 0x0f; const uint32_t n3 = (x >> 12) & 0x0f; return n3 | (n2 << 8) | (n1 << 16) | (n0 << 24); /* This function is compiled to (GCC 4.8.2): 83 e0 0f and $0xf,%eax c1 e9 0c shr $0xc,%ecx 83 e1 0f and $0xf,%ecx c1 e0 18 shl $0x18,%eax 09 c8 or %ecx,%eax 89 d1 mov %edx,%ecx 81 e1 00 0f 00 00 and $0xf00,%ecx c1 e2 0c shl $0xc,%edx 09 c8 or %ecx,%eax 81 e2 00 00 0f 00 and $0xf0000,%edx 09 d0 or %edx,%eax Looks like nibble_expand_naive_handcrafted. */ } uint32_t nibble_expand_naive_handcrafted(uint32_t x) { assert(x <= 0xffff); const uint32_t n0 = (x & 0x000f) << 24; const uint32_t n1 = (x & 0x00f0) << 12; const uint32_t n2 = (x & 0x0f00); const uint32_t n3 = (x & 0xf000) >> 12; return n3 | n2 | n1 | n0; } /* Operations: - 2 multiplications - 4 bit-and - 1 bit-or - 1 bswap */ uint32_t nibble_expand_mul(uint32_t x) { assert(x <= 0xffff); // 1. isolate nibble 0 and 2 const uint32_t n02 = x & 0x0f0f; // 2. isolate nibble 1 and 3 const uint32_t n13 = x & 0xf0f0; // 3. move nibble 2 to 3rd byte // n02 = 0x00000a0b const uint32_t tmp1 = n02 * 0x00000101; // tmp1 = 0x000a???b const uint32_t tmp2 = tmp1 & 0x00ff00ff; // tmp2 = 0x000a000b // 4. move nibble 1 to 1st byte and 3 to the 4th byte const uint32_t tmp3 = n13 * 0x00001010; // tmp3 = 0x0c???f00 const uint32_t tmp4 = tmp3 & 0xff00ff00; // tmp4 = 0x0c000f00 return bswap(tmp2 | tmp4); } /* Operations: - 1 interleave (kind of shift) - 1 shift - 2 bit-and */ #define SIMD_ALIGN __attribute__((aligned(16))) #define packed_byte(x) {x, x, x, x, x, x, x, x, x, x, x, x, x, x, x, x} uint8_t LSB_mask[16] SIMD_ALIGN = packed_byte(0x0f); uint32_t nibble_expand_simd(uint32_t x) { assert(x <= 0xffff); uint32_t result; __asm__ __volatile__ ( "movd %0, %%xmm0 \n" "movdqa %%xmm0, %%xmm1 \n" // 1. isolate even nibbles "movdqa %2, %%xmm2 \n" "pand %%xmm2, %%xmm0 \n" // 2. isolate odd nibbles "psrlw $4, %%xmm1 \n" "pand %%xmm2, %%xmm1 \n" // 3. intereleave nibble "punpcklbw %%xmm1, %%xmm0 \n" // store "movd %%xmm0, %0 \n" "bswap %0 \n" : "=r" (result) : "0" (x), "m" (LSB_mask) // 2 ); return result; } // --- PDEP version ------------------------------------------------------- uint32_t nibble_expand_pdep(uint32_t x) { assert(x <= 0xffff); return bswap(pdep(0x0f0f0f0f, x)); }
C
UTF-8
1,956
3.71875
4
[]
no_license
#ifndef __DAYLIGHT_H__ #define __DAYLIGHT_H__ /*-------------------------------------------------------------------------- FUNC: 6/11/11 - Returns day of week for any given date PARAMS: year, month, date RETURNS: day of week (0-7 is Sun-Sat) NOTES: Sakamoto's Algorithm http://en.wikipedia.org/wiki/Calculating_the_day_of_the_week#Sakamoto.27s_algorithm Altered to use char when possible to save microcontroller ram --------------------------------------------------------------------------*/ char dow(int y, char m, char d) { static char t[] = {0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4}; y -= m < 3; return (y + y/4 - y/100 + y/400 + t[m-1] + d) % 7; } /*-------------------------------------------------------------------------- FUNC: 6/11/11 - Returns the date for Nth day of month. For instance, it will return the numeric date for the 2nd Sunday of April PARAMS: year, month, day of week, Nth occurence of that day in that month RETURNS: date NOTES: There is no error checking for invalid inputs. --------------------------------------------------------------------------*/ char NthDate(int year, char month, char DOW, char NthWeek){ char targetDate = 1; char firstDOW = dow(year,month,targetDate); while (firstDOW != DOW){ firstDOW = (firstDOW+1)%7; targetDate++; } //Adjust for weeks targetDate += (NthWeek-1)*7; return targetDate; } char lastSunday(int year, char month) { char switchd = NthDate(year, month, 0, 5); if (switchd > 31) { switchd = NthDate(year, month, 0, 4); } } bool IsDST(int year, int month, int day) { //January, february, and december are out. if (month < 3 || month > 10) { return false; } //April to October are in if (month > 3 && month < 10) { return true; } char switchd = lastSunday(year, month); if (day >= switchd) { return month == 3 ? true : false; } else { return month == 3 ? false : true; } } #endif // __DAYLIGHT_H__
C
UTF-8
7,219
3.203125
3
[]
no_license
// autor: Pedro Vitor Valença Mizuno // arquivo: projeto.c // atividade extraclasse #include <stdio.h> #include <stdlib.h> #include <pthread.h> #include <unistd.h> #include <time.h> #include <semaphore.h> int pratos = 0, est_forno = 0, tamanho, cont = 0; int num_pratos[5] = {0,0,0,0,0}; int* sorteio = 0; struct fila f; sem_t sem_fogao, sem_balcao, sem_forno; pthread_mutex_t mutex, mutex_forno, dentro_forno; struct fila{ // Struct que compõe a fila int id_chef; int saloudoce; int inicio, fim; }; void inserir(struct fila *f, int id, int salgadoce){ // Inclui na fila if((f->fim + 1) < tamanho){ f->fim++; f->saloudoce = salgadoce; f->id_chef = id; } } struct fila consumir(struct fila *f){ // Tira da fila struct fila aux; if(f->inicio < tamanho){ aux.id_chef = f->id_chef; aux.saloudoce = f->saloudoce; f->inicio++; } return aux; } void balcao(int id){ // Função do balcão sem_wait(&sem_balcao); printf("\t\t\t\t | Chef %d sovando a massa. |\n", id); sleep(3); sem_post(&sem_balcao); } void fogao(int id){ // Função do fogão sem_wait(&sem_fogao); printf("\t\t\t\t | Chef %d cozinhando o arroz/massa. |\n", id); sleep(2); sem_post(&sem_fogao); } void forno(int id, int salgadoce){ // Função do forno pthread_mutex_lock(&mutex_forno); inserir(&f, id, salgadoce); // Empilha na fila pthread_mutex_unlock(&mutex_forno); struct fila proximo; sem_wait(&sem_forno); proximo = consumir(&f); // Desempilha if(((proximo.saloudoce == 1 && est_forno == 2) || (proximo.saloudoce == 2 && est_forno == 1)) && cont == 1){ // Se o próximo for diferente do tipo do atual no forno printf("\t\t\t\t | Chef %d esperando acesso ao forno. |\n", id); pthread_mutex_lock(&dentro_forno); printf("\t\t\t\t | Forno liberado para uso. |\n"); } cont = 1; est_forno = salgadoce; // Define o tipo do prato atual no forno (salgado ou doce) printf("\t\t\t\t | Chef %d assando a massa. |\n", id); sleep(4); cont = 0; sem_post(&sem_forno); pthread_mutex_unlock(&dentro_forno); } void *cozinha(void *args){ int id = *((int *) args); int cardapio; while(pratos > 0){ pthread_mutex_lock(&mutex); if(pratos == 0) break; pratos--; pthread_mutex_unlock(&mutex); switch(sorteio[pratos]){ // Cada caso é um prato diferente case 0: printf("O chef %d preparará uma lasanha. |\t\t\t\t |\n", id); balcao(id); fogao(id); forno(id, 1); printf("\t\t\t\t | \t\t\t\t | Pedido de lasanha do chef %d saindo!\n", id); num_pratos[0]++; break; case 1: printf("O chef %d preparará um espaguete. |\t\t\t\t |\n", id); balcao(id); fogao(id); printf("\t\t\t\t | \t\t\t\t | Pedido de espaguete do chef %d saindo!\n", id); num_pratos[1]++; break; case 2: printf("O chef %d preparará um risoto. |\t\t\t\t |\n", id); fogao(id); printf("\t\t\t\t | \t\t\t\t | Pedido de risoto do chef %d saindo!\n", id); num_pratos[2]++; break; case 3: printf("O chef %d preparará um cannoli. |\t\t\t\t |\n", id); balcao(id); fogao(id); printf("\t\t\t\t | \t\t\t\t | Pedido de cannoli do chef %d saindo!\n", id); num_pratos[3]++; break; case 4: printf("O chef %d preparará um zeppole. |\t\t\t\t |\n", id); balcao(id); fogao(id); forno(id, 2); printf("\t\t\t\t | \t\t\t\t | Pedido de zeppole do chef %d saindo!\n", id); num_pratos[4]++; break; } } } int main(){ printf(" ____ ______ ____ ____ ____ ____ ____ ____ ____ ___\n"); printf("| __|| __ ||_ _||_ _|| ___|| ___|| ___|| __||_ _| / _ \\ \n"); printf("| \\ | |__| | || _||_ |___ ||___ || _|_ | \\ _||_ / |_| \\ \n"); printf("|_\\_\\ |______| || |____||____||____||____||_\\_\\ |____|/__| |__\\ \n\n"); printf(" ____ ______ _ _ ____ ______ ____ ____ ____ _ _ ____ ____\n"); printf("| __|| __ || \\| || __|| __ || __|| __|| ___|| \\| ||_ _|| ___|\n"); printf("| |__ | |__| || \\ || |__ | |__| || \\ | \\ | _|_ | \\ | || | _|_\n"); printf("|____||______||_|\\_||____||______||_\\_\\ |_\\_\\ |____||_|\\_| || |____|\n\n\n"); printf("Bem-vindo à Rotisseria Concorrente!\nHoje você estará responsável pela contratação dos chefs e dizer quantos clientes serão servidos.\n"); int n, *id; printf("Quantos chefs serão contratados? "); scanf("%d", &n); pthread_t chef[n]; pthread_mutex_init(&mutex,0); // Mutex para o controle de pratos já feitos pthread_mutex_init(&mutex_forno,0); // Mutex para o incremento da fila do forno pthread_mutex_init(&dentro_forno,0); // Mutex para o controle dos pratos dentro do forno sem_init(&sem_fogao, 0, 8); // Semáforo para o fogão, com máximo de 8 sem_init(&sem_balcao,0,6); // Semáforo para o balcão, com máximo de 6 sem_init(&sem_forno,0,2); // Semáforo para o forno, com máximo de 2 printf("Quantos pratos serão feitos nesse serviço? "); scanf("%d", &pratos); tamanho = pratos; // Variável para o tamanho máximo da fila printf("\n____________________________________________________________________________________________________________\n"); printf(" | | \n"); sorteio = (int*) malloc(pratos * sizeof(int)); srand(time(0)); for(int i = 0; i < pratos; i++){ sorteio[i] = rand() % 5; // Sorteia os pratos que serão pedidos } for(int i = 0; i < n; i++){ id = (int *) malloc(sizeof(int)); *id = i; pthread_create(&chef[i], NULL, cozinha, (void *)id); // Cria as threads chefs } for(int i = 0; i < n; i++){ pthread_join(chef[i], NULL); } printf("_________________________________|____________________________________|_____________________________________\n\n"); printf("\nAo todo, foram servidos:\n"); printf("%d Lasanhas\n%d Espaguetes\n%d Risotos\n%d Cannolis\n%d Zeppoles\n", num_pratos[0], num_pratos[1], num_pratos[2], num_pratos[3], num_pratos[4]); sem_destroy(&sem_fogao); sem_destroy(&sem_balcao); sem_destroy(&sem_forno); pthread_mutex_destroy(&mutex); pthread_mutex_destroy(&mutex_forno); pthread_mutex_destroy(&dentro_forno); free(sorteio); return 0; }
C
UTF-8
3,709
2.703125
3
[ "Apache-2.0" ]
permissive
/** ***************************************************************************************** * * @name main.c * @author yuzrain * ***************************************************************************************** */ #include "stdio.h" #include "ARMCM3.h" #define TASK_1_STK_SIZE 1024 #define TASK_2_STK_SIZE 1024 typedef void (*os_task_handler_t)(void); //------------------------------------------------------------------------------ // Task control block //------------------------------------------------------------------------------ typedef struct os_tcb { uint32_t *stack_addr; }os_tcb,*os_tcb_p; //------------------------------------------------------------------------------ // Hold task 1/2 task control block //------------------------------------------------------------------------------ static os_tcb task1_tcb; static os_tcb task2_tcb; static uint32_t task1_stack[TASK_1_STK_SIZE]; static uint32_t task2_stack[TASK_2_STK_SIZE]; //------------------------------------------------------------------------------ // Hold task 1/2 task shedule //------------------------------------------------------------------------------ extern os_tcb_p os_current_tcb; extern os_tcb_p os_high_ready_tcb; extern void os_start(void); extern void os_shedule_trigger(void); /** * @brief switch task [task1->task2->task1...] * */ void Task_Switch() { if(os_current_tcb == &task1_tcb) os_high_ready_tcb=&task2_tcb; else os_high_ready_tcb=&task1_tcb; os_shedule_trigger(); } /** * @brief task1 * */ void task_1() { uint32_t i; while (1) { i = 1000; while (i--); Task_Switch(); i = 1000; while (i--); Task_Switch(); } } /** * @brief task2 * */ void task_2() { uint32_t i; while (1) { i = 1000; while (i--); Task_Switch(); i = 1000; while (i--); Task_Switch(); } } void Task_End(void) { /* We can not reach here */ while(1); } /** * @brief Create task stack * */ void Task_Create(os_tcb *tcb, os_task_handler_t task, uint32_t *stk) { uint32_t *p_stk; p_stk = stk; p_stk = (uint32_t *)((uint32_t)(p_stk) & 0xFFFFFFF8u); *(--p_stk) = (uint32_t)0x01000000uL; //xPSR *(--p_stk) = (uint32_t)task; // Entry Point *(--p_stk) = (uint32_t)Task_End; // R14 (LR) *(--p_stk) = (uint32_t)0x12121212uL; // R12 *(--p_stk) = (uint32_t)0x03030303uL; // R3 *(--p_stk) = (uint32_t)0x02020202uL; // R2 *(--p_stk) = (uint32_t)0x01010101uL; // R1 *(--p_stk) = (uint32_t)0x00000000u; // R0 *(--p_stk) = (uint32_t)0x11111111uL; // R11 *(--p_stk) = (uint32_t)0x10101010uL; // R10 *(--p_stk) = (uint32_t)0x09090909uL; // R9 *(--p_stk) = (uint32_t)0x08080808uL; // R8 *(--p_stk) = (uint32_t)0x07070707uL; // R7 *(--p_stk) = (uint32_t)0x06060606uL; // R6 *(--p_stk) = (uint32_t)0x05050505uL; // R5 *(--p_stk) = (uint32_t)0x04040404uL; // R4 tcb->stack_addr=p_stk; } /** * @brief Test * */ int main() { Task_Create(&task1_tcb,task_1,&task1_stack[TASK_1_STK_SIZE-1]); Task_Create(&task2_tcb,task_2,&task2_stack[TASK_1_STK_SIZE-1]); os_high_ready_tcb=&task1_tcb; os_start(); while(1) {} }
C
UTF-8
556
3.171875
3
[]
no_license
#include <stdio.h> #include <stdlib.h> struct node{ int data; struct node *sonraki; }; int main() { int a,b; struct node *ilkdugum=malloc(sizeof(struct node)); struct node *ikincidugum=malloc(sizeof(struct node)); printf("ilk elemani giriniz: "); scanf("%d",&a); printf("ikinci elemani giriniz: "); scanf("%d",&b); ilkdugum->data=a; ilkdugum->sonraki=ikincidugum; ikincidugum->data=b; ikincidugum->sonraki=NULL; printf("%d\n%d",ilkdugum->data,ikincidugum->data); getchar(); getchar(); return 0; }
C
UTF-8
3,002
2.78125
3
[]
no_license
#include "stm32_uart.h" #include "stdio.h" #include "math.h" #include "errno.h" #include "main.h" #include "stm32f1xx_hal_gpio.h" #include "stm32f1xx_hal_tim.h" #include "string.h" UART_HandleTypeDef Uart3Handle; /* Buffer used for transmission */ uint8_t aTxBuffer[80]; uint8_t aRxBuffer[80]; uint8_t aLastLine[80]; void Uart_Init(uint32_t baudrate) { GPIO_InitTypeDef GPIO_InitStructure; __GPIOB_CLK_ENABLE(); __HAL_RCC_AFIO_CLK_ENABLE(); __USART3_CLK_ENABLE(); //pb10 GPIO_InitStructure.Pin = GPIO_PIN_10; GPIO_InitStructure.Pull = GPIO_PULLUP; GPIO_InitStructure.Speed = GPIO_SPEED_HIGH; GPIO_InitStructure.Mode = GPIO_MODE_AF_PP; HAL_GPIO_Init(GPIOB, &GPIO_InitStructure); // PB11 GPIO_InitStructure.Pin = GPIO_PIN_11; GPIO_InitStructure.Mode = GPIO_MODE_INPUT; HAL_GPIO_Init(GPIOB, &GPIO_InitStructure); HAL_NVIC_SetPriority(USART3_IRQn, 0, 1); HAL_NVIC_EnableIRQ(USART3_IRQn); Uart3Handle.Instance = USART3; Uart3Handle.Init.BaudRate = baudrate; Uart3Handle.Init.WordLength = UART_WORDLENGTH_8B; Uart3Handle.Init.StopBits = UART_STOPBITS_1; Uart3Handle.Init.Parity = UART_PARITY_NONE; Uart3Handle.Init.HwFlowCtl = UART_HWCONTROL_NONE; Uart3Handle.Init.Mode = UART_MODE_TX_RX; if(HAL_UART_DeInit(&Uart3Handle) != HAL_OK) { Error_Handler(); } if(HAL_UART_Init(&Uart3Handle) != HAL_OK) { Error_Handler(); } if(HAL_UART_String_Listener(&Uart3Handle, aRxBuffer, sizeof(aRxBuffer)) != HAL_OK) { Error_Handler(); } } //-------------------------------------------------------------- // ein Byte per UART senden //-------------------------------------------------------------- void Uart_SendByte(uint16_t wert) { aTxBuffer[0] = (uint8_t) wert; HAL_UART_Transmit(&Uart3Handle, (uint8_t*)aTxBuffer, 1, 1000); } void Uart_SendString(char *ptr) { HAL_UART_Transmit(&Uart3Handle, (uint8_t*)ptr, strlen(ptr), 1000); } void Uart_SendBuffer(uint8_t *ptr, uint16_t len) { HAL_UART_Transmit(&Uart3Handle, ptr, len, 1000); } uint16_t Uart_ReceiveString(char *ptr, uint16_t maxsize) { return HAL_UART_String_Getter(&Uart3Handle, (uint8_t *) ptr, maxsize); } /** * @brief Tx Transfer completed callback * @param UartHandle: UART handle. * @note This example shows a simple way to report end of IT Tx transfer, and * you can add your own implementation. * @retval None */ void HAL_UART_TxCpltCallback(UART_HandleTypeDef *UartHandle) { } /** * @brief Rx Transfer completed callback * @param UartHandle: UART handle * @note This example shows a simple way to report end of DMA Rx transfer, and * you can add your own implementation. * @retval None */ void HAL_UART_RxCpltCallback(UART_HandleTypeDef *UartHandle) { } /** * @brief UART error callbacks * @param UartHandle: UART handle * @note This example shows a simple way to report transfer error, and you can * add your own implementation. * @retval None */ void HAL_UART_ErrorCallback(UART_HandleTypeDef *UartHandle) { }
C
UTF-8
149
2.9375
3
[]
no_license
#include<stdio.h> struct node { //int a; int b; char c[20]; }; struct node *p=0; main() { p++; printf("size of struct :%d \n",p); }
C
UTF-8
617
3.921875
4
[ "MIT" ]
permissive
/* You will be given 3 integers as input. The inputs may or may not be different from each other. You have to output 1 if all three inputs are different from each other, and 0 if any input is repeated more than once. This is code-golf, so make your code as short as possible! */ #include <assert.h> int distinct(int a, int b, int c) { return !(a == b || a == c || b == c); } int main(void) { assert(distinct(3, 2, 1) == 1); assert(distinct(1, 2, 3) == 1); assert(distinct(-5, 2, 5) == 1); assert(distinct(3, 3, 2) == 0); assert(distinct(3, 3, 3) == 0); assert(distinct(-33, -3, -3) == 0); return 0; }
C
UTF-8
539
2.625
3
[ "MIT" ]
permissive
#include "../libraries/xxh64.c" uint64_t get_pointer_hash(const void *ptr) { return XXH64(&ptr, sizeof(void *), 0); } uint64_t get_buffer_hash(const void *ptr, size_t size) { return XXH64(ptr, size, 0); } uint64_t get_string_hash(const char *string) { return get_buffer_hash(string, strlen(string)); } uint64_t get_2D_buffer_hash(const void **ptr, size_t size, size_t count) { int i; XXH64_state_t state; XXH64_reset(&state, 0); for (i=0; i < count; i++) XXH64_update(&state, ptr[i], size); return XXH64_digest(&state); }
C
UTF-8
1,928
4.15625
4
[]
no_license
#include <stdio.h> #include <stdlib.h> struct StackElem { int value; struct StackElem *older; struct StackElem *greater; }; typedef struct { int size; struct StackElem *head; struct StackElem *min; } MinStack; MinStack *minStackCreate() { MinStack *stack = (MinStack *) malloc(sizeof(MinStack)); stack->size = 0; stack->head = NULL; stack->min = NULL; return stack; } void minStackPush(MinStack *obj, int x) { struct StackElem *new_elem = (struct StackElem *) malloc( sizeof(struct StackElem)); struct StackElem *min_elem = obj->min; new_elem->value = x; new_elem->older = obj->head; obj->head = new_elem; if ((obj->size)++ == 0) { new_elem->greater = NULL; min_elem = new_elem; } else if (new_elem->value < min_elem->value) { new_elem->greater = min_elem; min_elem = new_elem; } obj->min = min_elem; } void minStackPop(MinStack *obj) { if (obj->size == 0) return; if (obj->head == obj->min) obj->min = obj->min->greater; struct StackElem *prev = obj->head->older; free(obj->head); obj->head = prev; (obj->size)--; } int minStackTop(MinStack *obj) { if (obj->size == 0) { printf("stack\'s empty\n"); return -1; } return obj->head->value; } int minStackGetMin(MinStack *obj) { if (obj->size == 0) { printf("stack\'s empty\n"); return -1; } return obj->min->value; } void minStackFree(MinStack *obj) { int cur_size; while ((cur_size = obj->size) != 0) { minStackPop(obj); } free(obj); } /** * Your MinStack struct will be instantiated and called as such: * MinStack* obj = minStackCreate(); * minStackPush(obj, x); * minStackPop(obj); * int param_3 = minStackTop(obj); * int param_4 = minStackGetMin(obj); * minStackFree(obj); */
C
UTF-8
386
3.75
4
[]
no_license
#include <stdio.h> #include "lists.h" /** * sum_listint - function that returns the sum * of all the data (n) * @head: reference (pointer to pointer) to the head * of a list * Return: sum of all the data */ int sum_listint(listint_t *head) { int count = 0; if (head == NULL) return (0); while (head) { count = count + head->n; head = head->next; } return (count); }
C
UTF-8
127
2.984375
3
[]
no_license
#include <assert.h> #include "utils.h" unsigned char char_to_byte(char c) { assert(c >= '0' && c <= '9'); return c - '0'; }
C
UTF-8
3,310
3.859375
4
[]
no_license
#include "Calendar.h" int isYear(int year) { if (year < 0 || year > 9999){ return -1; } return 1; } int isLeapYear(int year) { if ((year % 4 == 0) && (year % 100 != 0) || (year % 400 == 0)){ return 1; } return -1; } int isMonth(int month) { if (month < 0 || month > 12){ return -1; } return 1; } int getDayOfMonth(int year, int month) { if (isLeapYear(year) < 0){ return dayOfMonth[0][month -1]; }else{ return dayOfMonth[1][month -1]; } } int isDay(int year, int month, int day) { if (day < 0 || day > getDayOfMonth(year, month)){ return -1; } return 1; } int getDayOfYear(int year) { if (isLeapYear(year) < 0){ return 365; }else { return 366; } } int getWeekDay(int year, int month, int day) { int i = 0; int sumDay = 0; for (i=1; i < month; i++){ sumDay += getDayOfMonth(year, i); // printf("sum = %d\n", sumDay); } sumDay += day; // printf("sumDay = %d\n", sumDay); int week = ((year -1) * 365) + ((year-1)/4) - ((year-1)/100) + ((year-1)/400) + sumDay; // printf("week = %d\n", week); int weekday = (int)(week % 7); // printf("week %% 7 = %d\n", weekday); //0 sunday 1 return weekday; } void showTheWeekDay(int week) { if (week == 0){ printf("星期日\n\n"); }else if (week == 1){ printf("星期一\n\n"); }else if (week == 2){ printf("星期二\n\n"); }else if (week == 3){ printf("星期三\n\n"); }else if (week == 4){ printf("星期四\n\n"); }else if (week == 5){ printf("星期五\n\n"); }else if (week == 6){ printf("星期六\n\n"); } } void printMonthHead() { printf("日\t一\t二\t三\t四\t五\t六\t\n"); printf("==================================================\n"); } void showMonth(int year, int month) { int week = getWeekDay(year, month, 1); int i, j; printf("%d年%d月\n\n",year, month); printMonthHead(); for (j = 0; j < week; j++){ printf(" \t"); } for (j = 1; j <= getDayOfMonth(year, month); j++){ printf("%d\t", j); if (getWeekDay(year, month, j) == 6){ printf("\n\n\n"); } } printf("\n\n"); } void showDayInMonth(int year, int month, int day) { int week = getWeekDay(year, month, 1); int i, j; printf("%d年%d月%d日 ",year, month, day); showTheWeekDay(week); printMonthHead(); for (j = 0; j < week; j++){ printf(" \t"); } for (j = 1; j <= getDayOfMonth(year, month); j++){ if (j == day){ printf("\33[47;31m%d\t\33[0m", day); }else { printf("%d\t", j); } if (getWeekDay(year, month, j) == 6){ printf("\n\n\n"); } } printf("\n\n"); } void printMenu() { printf("\t\t\t万年历\n\n"); printf("1."); } void showYear(year, month, day) { int i, j, k; int m, n, o; printf("\t\t\t\t\t%d\n\n", year); int week1, week2, week3; int count1, count2, count3; for (i = 1; i < 13; i+=3){ printf("\t\t%d年%d月\t\t\t\t\t\t%d年%d月\t\t\t\t\t\t%d年%d月\n\n",year, i, year, i+1, year, i+2); printf("日\t一\t二\t三\t四\t五\t六\t"); printf("日\t一\t二\t三\t四\t五\t六\t"); printf("日\t一\t二\t三\t四\t五\t六\t\n\n"); week1 = getWeekDay(year, i, 1); week2 = getWeekDay(year, i+1, 1); week3 = getWeekDay(year, i+2, 1); count1 = getDayOfMonth(year, i); count2 = getDayOfMonth(year, i+1); count3 = getDayOfMonth(year, i+2); for (j = 0; j < week1; j++){ printf(" \t"); } // printf("") } }
C
UTF-8
1,969
2.75
3
[]
no_license
#define __USE_MINGW_ANSI_STDIO 1 #include "utils.h" int main(int argc, char *argv[]) { setbuf(stdout, NULL); if (argc != 3 && argc != 4) return ARG_ERR; char mode[3]; strncpy(mode, argv[1], 2); mode[2] = '\0'; size_t size = 0; int rc = OUT_ERR; if (argc == 4) { if (!strcmp(mode, "sb")) { FILE *in; FILE *out; in = fopen(argv[2], "rb+"); out = fopen(argv[3], "wb+"); if (!in || !out) return OPEN_ERR; rc = struct_sort(in, out, &size); fclose(in); fclose(out); return rc; } else if (!strcmp(mode, "fb")) { const char *end = argv[3]; FILE *in; in = fopen(argv[2], "rb"); if (!in) return OPEN_ERR; rc = find_str(in, end, &size); fclose(in); return rc; } else return ARG_ERR; } else if (argc == 3) { if (!strcmp(mode, "do")) { FILE *in; in = fopen(argv[2], "ab+"); if (!in) return READ_ERR; rc = write_struct(in); fclose(in); return rc; } else if (!strcmp(mode, "pr")) { FILE *in; in = fopen(argv[2], "rb"); if (!in) return READ_ERR; rc = print(in, &size); fclose(in); return rc; } else if (!strcmp(mode, "ab")) { FILE *in; in = fopen(argv[2], "rb+"); if (!in) return READ_ERR; rc = add_struct(in, &size); fclose(in); return rc; } else return ARG_ERR; } return EXIT_SUCCESS; }
C
UTF-8
458
3.96875
4
[]
no_license
#include "holberton.h" /** * _memset - function that fills the memory * @s: pointer to the block of memory to fill * @b: character to fill s with * @n: the first bytes of the memory area pointed to by s * * Description: function that fills memory with a constant byte * Return: a pointer to the memory area s */ char *_memset(char *s, char b, unsigned int n) { unsigned int ind; for (ind = 0; ind < n; ind++) { s[ind] = b; } return (s); }
C
UTF-8
371
3.171875
3
[]
no_license
#include <stdio.h> char *ft_strcapitalize(char *str); int main(void) { char src[15]; src[0] = 'o'; src[1] = 'i'; src[2] = ','; src[3] = ' '; src[4] = 't'; src[5] = 'd'; src[6] = '?'; src[7] = '4'; src[8] = 'P'; src[9] = ';'; src[10] = ' '; src[11] = 'c'; src[12] = '+'; src[13] = 'u'; src[14] = '\0'; printf("retorno: %s\n", ft_strcapitalize(src)); }
C
UTF-8
1,178
4.21875
4
[]
no_license
/* Using qsort() and bsearch() with values.*/ #include <stdio.h> #include <stdlib.h> #define MAX 20 int intcmp(const void *v1, const void *v2); main() { int arr[MAX], count, key, *ptr; /* Enter some integers from the user. */ printf("Enter %d integer values; press Enter after each.\n", MAX); for (count = 0; count < MAX; count++) scanf("%d", &arr[count]); puts("Press a key to sort the values."); getch(); /* Sort the array into ascending order. */ qsort(arr, MAX, sizeof(arr[0]), intcmp); /* Display the sorted array. */ for (count = 0; count < MAX; count++) printf("\narr[%d] = %d.", count, arr[count]); puts("\nPress a key to continue."); getch(); /* Enter a search key. */ printf("Enter a value to search for: "); scanf("%d", &key); /* Perform the search. */ ptr = (int *)bsearch(&key, arr, MAX, sizeof(arr[0]),intcmp); if ( ptr != NULL ) printf("%d found at arr[%d].", key, (ptr - arr)); else printf("%d not found.", key); } int intcmp(const void *v1, const void *v2) { return (*(int *)v1 - *(int *)v2); }
C
UTF-8
1,039
2.609375
3
[]
no_license
#ifndef __HMAC_SHA256_H__ #define __HMAC_SHA256_H__ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdint.h> //sha256.h typedef size_t uint64_t; typedef unsigned int uint32_t; typedef unsigned char uint8_t; #define SHA256_HASH_SIZE 32 /* Hash size in 32-bit words */ #define SHA256_HASH_WORDS 8 struct _SHA256Context { uint64_t totalLength; uint32_t hash[SHA256_HASH_WORDS]; uint32_t bufferLength; union { uint32_t words[16]; uint8_t bytes[64]; } buffer; #ifdef RUNTIME_ENDIAN int littleEndian; #endif /* RUNTIME_ENDIAN */ }; typedef struct _SHA256Context SHA256Context; #ifdef __cplusplus extern "C" { #endif void SHA256Init (SHA256Context *sc); void SHA256Update (SHA256Context *sc, const void *data, uint32_t len); void SHA256Final (SHA256Context *sc, uint8_t hash[SHA256_HASH_SIZE]); #ifdef __cplusplus } #endif #endif
C
UTF-8
2,150
2.78125
3
[]
no_license
#include <stdio.h> #include <math.h> #include <stdlib.h> #include "utils.h" #ifndef __FAT_LU_H__ #define __FAT_LU_H__ typedef double * MatRow; // Estrutura para armazenar uma matriz A, decompola em LU a fim de calcular a matriz inversa typedef struct { unsigned int n; // Ordem da matriz double **A; // matrix A double **L; // L*U =A double **U; // double *b; // vetor b tal que LUx = b, double *y; // vetor y tal que Ux = y e Ly= b unsigned int *trocas; //Armazena para cada posição, onde se encontra o valor original para o mesmo } FatoracaoLU; //---Alocaçao e desalocação de memória // aloca matriz quadrada double **alocaMatrizQ(int n); // libera matriz quadrada void liberaMatrizQ(double **M, int n); // Aloca fatoração LU FatoracaoLU *alocaFatoracaoLU(unsigned int n); // Libera fatoração LU void liberaFatoracaoLU(FatoracaoLU *LU); //---Leitura e impressão de sistemas lineares // Leitura dos inputs FatoracaoLU *lerMatriz(); // Exibe estrutura de fatoração LU void printFatoracaoLU(FatoracaoLU *lu, bool soMatriz); // Exibe resultado final no padão especificado void printResultado(FatoracaoLU *LU, double **Transp_INV, metricas *m); //---Gerenciamento do algoritmo e funções auxiliares // Troca duas linhas de um FatoracaoLU.A, armazenado a troca executada void trocaLinha(FatoracaoLU *LU, int A, int B); // Reverte todas as trocas de linha efetivadas void reverteTrocaLinha(FatoracaoLU *lu); //---Funções objetivo do projeto //Resolução de sistemas diagonais void resolveSisTriangular(double **ST, double *x, double *b, int n, bool superior); // Calcula Inversa de uma matriz (armazenando resultado como transposta) void calculaInversa(FatoracaoLU *LU, double **Transp_INV, metricas *m, bool pivota); // Triangulação de uma matriz A em L*U int triangulaLU(FatoracaoLU *LU, bool pivota); int calculaY(FatoracaoLU *LU); int calculaX(FatoracaoLU *LU, double *X); // Retorna a normaL2 do resíduo. Parâmetro 'res' deve ter o resíduo. double normaL2Inversa(FatoracaoLU *LU, double **Transp_INV); #endif // __FAT_LU_H__
C
UTF-8
336
3.296875
3
[]
no_license
#include <stdio.h> #include <stdlib.h> void squeeze(char *str, char *pat); int main(int argc, char **argv) { return 0; } /* Removes any substring matching pat * from str. */ void squeeze(char str[], char pat[]) { int i, j; for (i = 0; str[i]; i++) { for (j = 0; pat[j]; j++) { if (pat[j] != str[i + j]) break; } } }
C
UTF-8
958
2.765625
3
[]
no_license
/* -------------------------------------------------------------------------------- # # Discretize continuous time output # Sean Wu ([email protected]) # March 2020 # -------------------------------------------------------------------------------- */ #include "discretize.h" SEXP discretize_C(SEXP out, SEXP dt_r){ int dt = Rf_asInteger(dt_r); double* out_ptr = REAL(out); int ncol = Rf_ncols(out); int events = Rf_nrows(out); double end = out_ptr[(events-1) + events*0]; double start = out_ptr[0 + events*0]; int len = ((int)(end - start)) / dt + 1; SEXP x = PROTECT(Rf_allocMatrix(REALSXP,len,ncol)); double* x_ptr = REAL(x); double target = 0.; int j = 0; for(int i=1; i<events; i++){ while(out_ptr[i + events*0] >= target){ x_ptr[j + len*0] = target; for(int k=1; k<ncol; k++){ x_ptr[j + len*k] = out_ptr[i + events*k]; } j += 1; target += dt; } } UNPROTECT(1); return x; };
C
UTF-8
212
3.40625
3
[]
no_license
#include<stdio.h> void main() { int n,m,a,b,gcd; printf("\n enter two numbers "); scanf("%d %d",&a,&b); n=a; m=b; while(n!=m) { if(n>m) n=n-m; else m=m-n; } gcd=n; printf("\n GCD of %d and %d is=%d",a,b,gcd); }
C
UTF-8
2,717
2.609375
3
[ "LicenseRef-scancode-other-permissive" ]
permissive
#pragma once #include "mpi.h" #include "adios.h" #include "util.h" /* Global variables */ extern int commsize; extern int myrank; /* The main entry point for the worker */ int worker(int argc, char* argv[]); /* The main computation for the worker */ int compute (int iteration); /* make sure only rank 0 prints output */ #define my_printf(...) if (myrank == 0) { printf(__VA_ARGS__); fflush(stdout); } static inline int get_left_neighbor() { if (myrank == 0) { return commsize-1; } return myrank-1; } static inline int get_right_neighbor() { if (myrank == (commsize-1)) { return 0; } return myrank+1; } static inline void do_neighbor_exchange(void) { int outdata[100] = {1}; int indata[100] = {0}; int thistag = 1; if (commsize < 2) return; MPI_Status status; if (myrank % 2 == 0) { // send to left neighbor MPI_Send(outdata, /* message buffer */ 100, /* one data item */ MPI_INT, /* data item is an integer */ get_left_neighbor(), /* destination process rank */ thistag, /* user chosen message tag */ MPI_COMM_WORLD); /* default communicator */ int thistag = 2; // receive from right neighbor MPI_Recv(indata, /* message buffer */ 100, /* one data item */ MPI_INT, /* of type double real */ get_right_neighbor(), /* receive from any sender */ thistag, /* any type of message */ MPI_COMM_WORLD, /* default communicator */ &status); /* info about the received message */ } else { // receive from right neighbor MPI_Recv(indata, /* message buffer */ 100, /* one data item */ MPI_INT, /* of type double real */ get_right_neighbor(), /* receive from any sender */ thistag, /* any type of message */ MPI_COMM_WORLD, /* default communicator */ &status); /* info about the received message */ int thistag = 2; // send to left neighbor MPI_Send(outdata, /* message buffer */ 100, /* one data item */ MPI_INT, /* data item is an integer */ get_left_neighbor(), /* destination process rank */ thistag, /* user chosen message tag */ MPI_COMM_WORLD); /* default communicator */ } }
C
UTF-8
1,618
3.8125
4
[]
no_license
/* Generate.c - Generates a given number of random values and stores them * in the files small_test.txt, medium_test.txt, and large_test.txt * DO NOT MODIFY THIS FILE. When I test your program I will use the same * files generated by this program. * * Format of *_test.txt files are: * N * #1 #2 ... #N * * Compile and execute this program by: * >> gcc -o gen.ex generate.c * >> ./gen.ex */ #include <stdio.h> #include <stdlib.h> #define N_SMALL 100 // Amount of random numbers to generate for small test case #define N_MEDIUM 100000 // Amount of random numbers to generate for medium test case #define N_LARGE 10000000 // Amount of random numbers to generate for large test case #define MAX 10000 // Max random number value int main() { FILE *fp_small = fopen("small_test.txt", "w+"); FILE *fp_medium = fopen("medium_test.txt", "w+"); FILE *fp_large = fopen("large_test.txt", "w+"); int i; // --- SMALL TEST --- fprintf(fp_small, "%i\n", N_SMALL); // Print total amount of numbers for(i = 0; i < N_SMALL; i++) fprintf(fp_small, "%i ", rand()%MAX); // Print N random numbers // --- MEDIUM TEST --- fprintf(fp_medium, "%i\n", N_MEDIUM); // Print total amount of numbers for(i = 0; i < N_MEDIUM; i++) fprintf(fp_medium, "%i ", rand()%MAX); // Print N random numbers // --- LARGE TEST --- fprintf(fp_large, "%i\n", N_LARGE); // Print total amount of numbers for(i = 0; i < N_LARGE; i++) fprintf(fp_large, "%i ", rand()%MAX); // Print N random numbers fclose(fp_small); fclose(fp_medium); fclose(fp_large); }
C
UTF-8
500
4.25
4
[]
no_license
//to find the largest among 'm' elements. #include<stdio.h> void main() { int a[20],n,m,i,j,t,b; printf("ENTER THE TOTAL NO.OF.ARRAY ELEMENTS:\n"); scanf("%d",&n); printf("ENTER THE ARRAY ELEMENTS:\n"); for(i=0;i<n;i++) { scanf("%d",&a[i]); } printf("ENTER THE m VALUE:\n"); scanf("%d",&m); for(i=0;i<m;i++) { for(j=i+1;j<m;j++) { if(a[i]>a[j]) { t=a[i]; a[i]=a[j]; a[j]=t; } } b=a[m-1]; } printf("\n\nTHE LARGEST AMONG FIRST %d ELEMENTS IS %d",m,b); }
C
UHC
1,146
4.125
4
[]
no_license
/* Ȧ ¦ Ǻ 2 0̸ ¦, 1̸ Ȧ̴. 0 0 ͼ ¦ Ǻ, ¦ ָϴ!! 0 Է ߰ "0 ָؿ~!" ! [°] Էּ : 0 ԷϽ 0() ¦Դϴ. 0 ָؿ~! Էּ : 1 ԷϽ 1() ȦԴϴ. */ #include <stdio.h> void main() { /*int iV = 0; printf(" Էּ : "); scanf("%d", &iV); if (iV == 0) { printf("0 ָؿ~!\n"); } else { switch (iV % 2) { case 0: printf("ԷϽ 0() ¦Դϴ.\n"); break; case 1: printf("ԷϽ 1() ȦԴϴ.\n"); break; // default: printf("0 ָؿ~!\n"); } }*/ int iNum = 0; printf(" Էּ : "); scanf("%d", &iNum); if (iNum % 2 == 0) { printf("ԷϽ %d() ¦Դϴ.\n", iNum); if (iNum == 0) { printf("0 ָؿ~!\n"); } } else { printf("ԷϽ %d() ȦԴϴ.\n", iNum); } }
C
UTF-8
959
3.078125
3
[]
no_license
/* 10/2/2017 Authors: Connor Lundberg, Gardner Gomes In this assignment we are creating a PCB (Process Control Block), ReadyQueue, and PriorityQueue. Each is made in sequence and then used to make the next one. The PCB is being held within the ReadyQueue, and the PriorityQueue holds 16 ReadyQueues. This is going to be used for scheduling in the final OS project. In this file we are declaring the PriorityQueue struct, its length, and the functions it will use. */ //includes #include "readyqueue.h" //defines #define PRIORITY_QUEUE_LENGTH 16 //structs typedef struct priority_queue { ReadyQueue priorities[PRIORITY_QUEUE_LENGTH]; } priority_queue_s; typedef priority_queue_s * PriorityQueue; //declarations PriorityQueue priorityQueueConstructor(); int priorityQueueInitializer(PriorityQueue); int priorityQueueDeconstructor(PriorityQueue); void addProcess(PCB, PriorityQueue); PCB getNextProcess(); void toStringPriorityQueue(PriorityQueue);
C
UTF-8
536
2.625
3
[]
no_license
#include <SDL/SDL.h> #include <stdio.h> #include <stdlib.h> #include <assert.h> int main() { SDL_Surface* screen; SDL_Surface* image; SDL_Rect src,dest; assert (SDL_Init(SDL_INIT_VIDEO) == 0); atexit(SDL_Quit); screen=SDL_SetVideoMode(320,240,16,0); image = SDL_LoadBMP("image.bmp"); assert(image!=NULL); src.x=dest.x=0; src.y=dest.y=0; src.w=dest.w=image->w; src.h=dest.h=image->h; SDL_BlitSurface(image,&src,screen,&src); SDL_UpdateRect(screen,0,0,0,0); SDL_Delay(3000); SDL_FreeSurface(image); return 0; }
C
UTF-8
305
3.328125
3
[]
no_license
#include <stdio.h> int main(void) { double mileage; int time, cost; scanf("%lf %d", &mileage, &time); if ( mileage<=3 ) cost = 10; else if ( mileage <= 10 ) cost = 10 + (mileage-3) * 2.0 + 0.5; else cost = 10 + (10-3) * 2 + ( mileage-10) * 3.0 + 0.5; printf("%d\n", cost+time/5*2); return 0; }
C
UTF-8
465
3.625
4
[]
no_license
#include<stdio.h> #define N 100 #define IN 1 #define OUT 0 int main() { char a[N]; while(gets(a)) { printf("%d\n",count_word(a)); } return 0; } int count_word(const char a[]) { int i,state,count = 0; state = OUT; for(i = 0; a[i] != '\0'; i++) if(a[i] == ' ' || a[i] == '\t') state = OUT; else if(state == OUT) { count ++; state = IN; } if(state == IN) putchar(a[i]); return count; }
C
ISO-8859-1
654
3.421875
3
[]
no_license
#include <stdio.h> int main() { int ig,gg,t,m=0,iv=0,gv=0; while(1) { scanf("%d %d",&ig,&gg); m++; if(ig>gg) iv++; else if(ig<gg) gv++; printf("Novo grenal (1-sim 2-nao)\n"); scanf("%d",&t); if(t!=1) break; } printf("%d grenais\n",m); printf("Inter:%d\n",iv); printf("Gremio:%d\n",gv); printf("Empates:%d\n",m-(iv+gv)); if(iv==gv) printf("No houve vencedor\n"); else if(iv>gv) printf("Inter venceu mais\n"); else printf("Gremio venceu mais\n"); return 0; }
C
UTF-8
16,333
2.640625
3
[]
no_license
/* * PrimitivasAnSISOP.c * * Created on: 17/5/2016 * Author: utnso */ #include "PrimitivasAnSISOP.h" #include <sockets/EscrituraLectura.h> #include <sockets/OpsUtiles.h> #include "ProcesoCpu.h" #define TAMANIO_VARIABLE 4 extern t_log* ptrLog; t_pcb* pcb; void setPCB(t_pcb * pcbDeCPU) { pcb = pcbDeCPU; } void freePCBDePrimitivas() { int a, b; if(pcb->ind_etiq != NULL) { free(pcb->ind_etiq); } for(a = 0; a < list_size(pcb->ind_codigo); a ++) { t_indice_codigo * indice = list_get(pcb->ind_codigo, a); list_remove(pcb->ind_codigo, a); free(indice); } free(pcb->ind_codigo); for(a = 0; a < list_size(pcb->ind_stack); a ++) { t_stack* linea = list_get(pcb->ind_stack, a); uint32_t cantidadArgumentos = list_size(linea->argumentos); for(b = 0; b < cantidadArgumentos; b++) { t_argumento *argumento = list_get(linea->argumentos, b); list_remove(linea->argumentos, b); free(argumento); } free(linea->argumentos); int32_t cantidadVariables = list_size(linea->variables); for(b = 0; b < cantidadVariables; b++) { t_variable *variable = list_get(linea->variables, b); list_remove(linea->variables, b); free(variable->idVariable); free(variable); } } free(pcb->ind_stack); free(pcb); } bool esArgumento(t_nombre_variable identificador_variable){ if(isdigit(identificador_variable)){ return true; }else{ return false; } } t_puntero definirVariable(t_nombre_variable identificador_variable) { if(!esArgumento(identificador_variable)){//si entra a este if es porque es una variable, si no entra es porque es un argumento, me tengo que fijar si es del 0 al 9, no solo del 0 log_debug(ptrLog, "Definir variable %c", identificador_variable); t_variable* nuevaVar = malloc(sizeof(t_variable)); t_stack* lineaStack = list_get(pcb->ind_stack, pcb->numeroContextoEjecucionActualStack); if(pcb->stackPointer + 4 > tamanioPagina && pcb->paginaStackActual - pcb->primerPaginaStack == tamanioStack -1){ if(!huboStackOver){ log_error(ptrLog, "StackOverflow. Se finaliza el proceso"); huboStackOver = true; } return -1; }else{ if(lineaStack == NULL){ //el tamaño de la linea del stack seria delos 4 ints mas uint32_t tamLineaStack = 7*sizeof(uint32_t)+1; lineaStack = malloc(tamLineaStack); lineaStack->retVar = NULL; lineaStack->direcretorno = 0; lineaStack->argumentos = list_create(); lineaStack->variables = list_create(); //lineaStack->variables = malloc((sizeof(uint32_t)*3)+1); //pcb->ind_stack = malloc(tamLineaStack); list_add(pcb->ind_stack, lineaStack); } //me fijo si el offset de la ultima + el tamaño superan o son iguales el tamaño de la pagina, si esto sucede, tengo que pasar a una pagina nueva if(pcb->stackPointer + TAMANIO_VARIABLE > tamanioPagina){ nuevaVar->idVariable = identificador_variable; pcb->paginaStackActual++; nuevaVar->pagina = pcb->paginaStackActual; nuevaVar->size = TAMANIO_VARIABLE; nuevaVar->offset = 0; pcb->stackPointer = TAMANIO_VARIABLE; list_add(lineaStack->variables, nuevaVar); }else{ nuevaVar->idVariable = identificador_variable; nuevaVar->pagina = pcb->paginaStackActual; nuevaVar->size = TAMANIO_VARIABLE; nuevaVar->offset = pcb->stackPointer; pcb->stackPointer+= TAMANIO_VARIABLE; list_add(lineaStack->variables, nuevaVar); } //calculo el desplazamiento desde la primer pagina del stack hasta donde arranca mi nueva variable uint32_t posicionRet = (nuevaVar->pagina * tamanioPagina) + nuevaVar->offset; log_debug(ptrLog, "%c %i %i %i", nuevaVar->idVariable, nuevaVar->pagina, nuevaVar->offset, nuevaVar->size); return posicionRet; } }else{ //en este caso es un argumento, realizar toda la logica aca y tambien en obtener posicion variable, asignar imprimir y retornar log_debug(ptrLog, "Definir variable - argumento %c", identificador_variable); t_argumento* nuevoArg = malloc(sizeof(t_argumento)); t_stack* lineaStack = list_get(pcb->ind_stack, pcb->numeroContextoEjecucionActualStack); if(pcb->stackPointer + 4 > tamanioPagina && pcb->paginaStackActual - pcb->primerPaginaStack == tamanioStack -1){ if(!huboStackOver){ log_error(ptrLog, "StackOverflow. Se finaliza el proceso"); huboStackOver = true; } return -1; }else{ //me fijo si el offset de la ultima + el tamaño superan o son iguales el tamaño de la pagina, si esto sucede, tengo que pasar a una pagina nueva if(pcb->stackPointer + TAMANIO_VARIABLE > tamanioPagina){ pcb->paginaStackActual++; nuevoArg->pagina = pcb->paginaStackActual; nuevoArg->size = TAMANIO_VARIABLE; nuevoArg->offset = 0; pcb->stackPointer = TAMANIO_VARIABLE; list_add(lineaStack->argumentos, nuevoArg); }else{ nuevoArg->pagina = pcb->paginaStackActual; nuevoArg->size = TAMANIO_VARIABLE; nuevoArg->offset = pcb->stackPointer; pcb->stackPointer += TAMANIO_VARIABLE; list_add(lineaStack->argumentos, nuevoArg); } //calculo el desplazamiento desde la primer pagina del stack hasta donde arranca mi nueva variable uint32_t posicionRet = (nuevoArg->pagina * tamanioPagina) + nuevoArg->offset; log_debug(ptrLog, "%c %i %i %i", identificador_variable, nuevoArg->pagina, nuevoArg->offset, nuevoArg->size); return posicionRet; } } } t_puntero obtenerPosicionVariable(t_nombre_variable identificador_variable) { if(!esArgumento(identificador_variable)){ t_variable* variable = malloc(sizeof(t_variable)); int i = 0; char* nom = calloc(1, 2); nom[0] = identificador_variable; log_debug(ptrLog, "Obtener posicion variable '%c'", identificador_variable); //obtengo la linea del stack del contexto de ejecucion actual... t_stack* lineaActualStack = list_get(pcb->ind_stack, pcb->numeroContextoEjecucionActualStack); //me posiciono al inicio de esta linea del stack //me fijo cual variable de la lista coincide con el nombre que me estan pidiendo if(list_size((t_list*)lineaActualStack->variables) > 0){ for(i = 0; i<list_size(lineaActualStack->variables); i++){ variable = list_get(lineaActualStack->variables, i); if(variable->idVariable == identificador_variable ){ free(nom); uint32_t posicionRet = (variable->pagina * tamanioPagina) + variable->offset; return posicionRet; } } } //devuelvo -1 uint32_t posicionRetError = -1; free(variable); free(nom); return posicionRetError; }else{ t_argumento* arg = malloc(sizeof(t_argumento)); int i = 0; char* nom = calloc(1, 2); nom[0] = identificador_variable; log_debug(ptrLog, "Obtener posicion variable '%c'", identificador_variable); //obtengo la linea del stack del contexto de ejecucion actual... t_stack* lineaActualStack = list_get(pcb->ind_stack, pcb->numeroContextoEjecucionActualStack); //me posiciono al inicio de esta linea del stack //me fijo cual variable de la lista coincide con el nombre que me estan pidiendo if(list_size((t_list*)lineaActualStack->argumentos) > 0){ int lineaArg = identificador_variable - '0'; arg = list_get(lineaActualStack->argumentos, lineaArg); free(nom); uint32_t posicionRet = (arg->pagina * tamanioPagina) + arg->offset; return posicionRet; } //devuelvo -1 uint32_t posicionRetError = -1; free(arg); free(nom); return posicionRetError; } } t_valor_variable dereferenciar(t_puntero direccion_variable) { //calculo el la posicion de la variable en el stack mediante el desplazamiento t_posicion_stack posicionRet; posicionRet.pagina = (direccion_variable/tamanioPagina); posicionRet.offset = direccion_variable%tamanioPagina; posicionRet.size = TAMANIO_VARIABLE; t_valor_variable valor = 0; log_debug(ptrLog, "Dereferenciar %d", direccion_variable); t_solicitarBytes* solicitar = malloc(sizeof(t_solicitarBytes)); solicitar->pagina = posicionRet.pagina; solicitar->offset = TAMANIO_VARIABLE; solicitar->start = posicionRet.offset; char* buffer = enviarOperacion(LEER_VALOR_VARIABLE, solicitar, socketUMC); if(buffer != NULL) { t_instruccion * instruccion = deserializarInstruccion(buffer); if(strcmp(instruccion, "FINALIZAR") == 0) { log_error(ptrLog, "La variable no pudo dereferenciarse. Se finaliza el Proceso."); finalizarProcesoPorErrorEnUMC(); return 0; }else{ int valueAsInt = atoi(instruccion->instruccion); memcpy(&valor, &valueAsInt, sizeof(t_valor_variable)); log_debug(ptrLog, "Variable dereferenciada. Valor: %d", valor); free(buffer); } } free(solicitar); return valor; } void asignar(t_puntero direccion_variable, t_valor_variable valor) { log_debug(ptrLog, "Asignar. Posicion %d - Valor %d", direccion_variable, valor); //calculo el la posicion de la variable en el stack mediante el desplazamiento t_enviarBytes* enviar = malloc(sizeof(uint32_t) * 4); enviar->pagina = (direccion_variable / tamanioPagina); enviar->offset = direccion_variable % tamanioPagina; enviar->tamanio = TAMANIO_VARIABLE; enviar->pid = pcb->pcb_id; enviar->buffer = malloc(sizeof(uint32_t)); sprintf(enviar->buffer, "%d", valor); char* resp = enviarOperacion(ESCRIBIR, enviar, socketUMC); if(resp != NULL && resp[0] == -1){ operacion = ERROR; free(enviar->buffer); free(enviar); return; }else{ uint32_t result = deserializarUint32(resp); if(result == SUCCESS) { log_info(ptrLog, "Variable asignada"); }else if(result == ERROR){ log_error(ptrLog, "La variable no pudo asignarse. Se finaliza el Proceso."); finalizarProcesoPorErrorEnUMC(); } } free(resp); free(enviar->buffer); free(enviar); return; } t_valor_variable obtenerValorCompartida(t_nombre_compartida variable) { char* buffer; uint32_t id = CPU; t_valor_variable valor = 0; uint32_t lon = strlen(variable)+1; operacion = LEER_VAR_COMPARTIDA; log_debug(ptrLog, "Obtener valor compartida '%s'", variable); if (enviarDatos(socketNucleo, variable, lon, operacion, id) < 0) return -1; buffer = recibirDatos(socketNucleo, &operacion, &id); if (strcmp("ERROR", buffer) == 0) { free(buffer); return -1; } else { memcpy(&valor, buffer, sizeof(t_valor_variable)); log_debug(ptrLog, "Valor compartida '%s' obtenido. Valor: %d", variable, valor); free(buffer); return valor; } } t_valor_variable asignarValorCompartida(t_nombre_compartida variable, t_valor_variable valor) { uint32_t op = ASIG_VAR_COMPARTIDA; uint32_t id = CPU; log_debug(ptrLog, "Asignar valor compartida. Variable compartida: '%s' - Valor: %d", variable, valor); t_op_varCompartida* varCompartida = malloc(sizeof(t_op_varCompartida)); varCompartida->longNombre = strlen(variable) + 1; varCompartida->nombre = malloc(strlen(variable) + 1); strcpy(varCompartida->nombre, variable); varCompartida->valor = valor; t_buffer_tamanio * tamanio_buffer = serializar_opVarCompartida(varCompartida); if (enviarDatos(socketNucleo, tamanio_buffer->buffer, tamanio_buffer->tamanioBuffer, op, id) < 0) return -1; free(tamanio_buffer->buffer); free(tamanio_buffer); free(varCompartida->nombre); free(varCompartida); log_debug(ptrLog, "Valor compartida '%s' asignada", variable); return valor; } void irAlLabel(t_nombre_etiqueta etiqueta) { //devuelvo la primer instruccion ejecutable de etiqueta o -1 en caso de error //necesito el tamanio de etiquetas, lo tendria que agregar al pcb //en vez de devolverla me conviene agregarla al program counter log_debug(ptrLog, "Ir al Label '%s'", etiqueta); t_puntero_instruccion numeroInstr = metadata_buscar_etiqueta(etiqueta, pcb->ind_etiq, pcb->tamanioEtiquetas); pcb->PC = numeroInstr - 1; return; } void llamarConRetorno(t_nombre_etiqueta etiqueta, t_puntero donde_retornar) { log_debug(ptrLog, "Llamar con Retorno. Reservando espacio y cambiando al nuevo contexto de ejecucion"); uint32_t tamLineaStack = 4*sizeof(uint32_t)+2*sizeof(t_list); t_stack * nuevaLineaStackEjecucionActual; t_argumento* varRetorno = malloc(sizeof(t_argumento)); varRetorno->pagina = (donde_retornar/tamanioPagina); varRetorno->offset = donde_retornar%tamanioPagina; varRetorno->size = TAMANIO_VARIABLE; if(nuevaLineaStackEjecucionActual == NULL){ //el tamaño de la linea del stack seria delos 4 ints mas nuevaLineaStackEjecucionActual = malloc(tamLineaStack); nuevaLineaStackEjecucionActual->argumentos = list_create(); nuevaLineaStackEjecucionActual->variables = list_create(); nuevaLineaStackEjecucionActual->retVar = varRetorno; nuevaLineaStackEjecucionActual->direcretorno = pcb->PC; list_add(pcb->ind_stack, nuevaLineaStackEjecucionActual); pcb->numeroContextoEjecucionActualStack++; } irAlLabel(etiqueta); return; } void retornar(t_valor_variable retorno) { //agarro contexto actual y anterior int a = pcb->numeroContextoEjecucionActualStack; t_stack* contextoEjecucionActual = list_get(pcb->ind_stack, a); //Limpio el contexto actual int i = 0; for(i = 0; i < list_size(contextoEjecucionActual->argumentos); i++){ t_argumento* arg = list_get(contextoEjecucionActual->argumentos, i); pcb->stackPointer=pcb->stackPointer-4; free(arg); } for(i = 0; i <list_size(contextoEjecucionActual->variables); i++){ t_variable* var = list_get(contextoEjecucionActual->variables, i); pcb->stackPointer=pcb->stackPointer-4; free(var); } t_argumento* retVar = contextoEjecucionActual->retVar; t_puntero direcVariable = (retVar->pagina * tamanioPagina) + retVar->offset; //calculo la direccion a la que tengo que retornar mediante la direccion de pagina start y offset que esta en el campo retvar asignar(direcVariable, retorno); //elimino el contexto actual del indice del stack //Seteo el contexto de ejecucion actual en el anterior pcb->PC = contextoEjecucionActual->direcretorno; free(contextoEjecucionActual); list_remove(pcb->ind_stack, pcb->numeroContextoEjecucionActualStack); pcb->numeroContextoEjecucionActualStack = pcb->numeroContextoEjecucionActualStack -1; t_stack* contextoEjecNuevo = list_get(pcb->ind_stack, pcb->numeroContextoEjecucionActualStack); log_debug(ptrLog, "Llamada a retornar"); return; } void imprimir(t_valor_variable valor_mostrar) { log_debug(ptrLog, "Envio a Nucleo valor %d para que Consola imprima por pantalla.", valor_mostrar); t_buffer_tamanio* buff = serializar(valor_mostrar); uint32_t op = IMPRIMIR_VALOR; uint32_t id = CPU; int bytesEnviados = enviarDatos(socketNucleo, buff->buffer, buff->tamanioBuffer, op, id); free(buff->buffer); free(buff); } void imprimirTexto(char* texto) { log_debug(ptrLog, "Envio la cadena '%s' a Nucleo para que Consola imprima por pantalla", texto); texto = _string_trim(texto); uint32_t op = IMPRIMIR_TEXTO; uint32_t id = CPU; uint32_t lon = strlen(texto)+1; int bytesEnviados = enviarDatos(socketNucleo, texto, lon, op, id); } void entradaSalida(t_nombre_dispositivo dispositivo, int tiempo) { operacion = IO; uint32_t id = CPU; uint32_t lon = strlen(dispositivo)+1+sizeof(uint32_t) + sizeof(int); log_debug(ptrLog, "Entrada/Salida. Dispositivo: '%s' - Tiempo: %d", dispositivo, tiempo); t_dispositivo_io* op_IO = malloc(sizeof(t_dispositivo_io)); op_IO->nombre = malloc(strlen(dispositivo)+1); strcpy(op_IO->nombre, dispositivo); op_IO->tiempo = tiempo; char* buffer; buffer = (char *)serializar_opIO(op_IO); enviarDatos(socketNucleo, buffer, lon, operacion, id); free(buffer); free(op_IO->nombre); free(op_IO); } void wait(t_nombre_semaforo identificador_semaforo) { char* buffer; uint32_t op = WAIT; uint32_t id = CPU; uint32_t lon = strlen(identificador_semaforo)+1; log_debug(ptrLog, "Wait. Semaforo: '%s'", identificador_semaforo); enviarDatos(socketNucleo, identificador_semaforo, lon, op, id); log_debug(ptrLog, "Esperando respuesta del Nucleo para Wait."); buffer = recibirDatos(socketNucleo, &op, &id); if(operacion != NOTHING){ operacion = op; log_debug(ptrLog,"Proceso no queda bloqueado por Semaforo '%s'", identificador_semaforo); } if (op == WAIT){ operacion = op; log_debug(ptrLog,"Proceso bloqueado por Semaforo '%s'", identificador_semaforo); } free(buffer); } void ansisop_signal(t_nombre_semaforo identificador_semaforo) { uint32_t op = SIGNAL; uint32_t id = CPU; uint32_t lon = strlen(identificador_semaforo)+1; log_debug(ptrLog, "Signal. Semaforo: '%s'", identificador_semaforo); enviarDatos(socketNucleo, identificador_semaforo, lon, op, id); return; }
C
UTF-8
1,618
3.28125
3
[ "MIT" ]
permissive
#include "1hardest.h" void printBin(FILE *fout, unsigned char *buff, char *cnt, unsigned char a) // Вывод бита { *cnt = (*cnt + 1) % 8; *buff = *buff * 2 + a; if (*cnt == 0) { fwrite(buff, 1, 1, fout); *buff = 0; } } void printChar(FILE *fout, unsigned char *buff, char *cnt, unsigned char a) // Вывод стандартного бинарного кода символа { for (int i = 0; i < 8; i++) { printBin(fout, buff, cnt, a / 128); a = a << 1; } } void printTree(FILE *fout, unsigned char *buff, char *cnt, node *tree) // Вывод дерева (побитовый) { if (tree->data != -1) { printBin(fout, buff, cnt, 1); printChar(fout, buff, cnt, tree->data); } else { // Иначе выводим 0 и рекурсивно продолжаем алгоритм для левого и правого поддерева printBin(fout, buff, cnt, 0); printTree(fout, buff, cnt, tree->left); printTree(fout, buff, cnt, tree->right); } } void printCode(FILE *fout, unsigned char *buff, char *cnt, char *code) // Вывод кода (побитовый) { for (int i = 0; i < strlen(code); i++) printBin(fout, buff, cnt, code[i] - '0'); } void printTail(FILE *fout, unsigned char *buff, char *cnt) // Вывод остатка буфера { for (int i = *cnt; i < 8; i++) *buff *= 2; fwrite(buff, 1, 1, fout); } void printFile(FILE *fin, FILE *fout, unsigned char *buff, char *cnt, char **code) // Кодирование символов { unsigned char a; while (fread(&a, 1, 1, fin)) printCode(fout, buff, cnt, code[a]); printTail(fout, buff, cnt); }
C
UTF-8
3,537
3.046875
3
[ "Unlicense", "LicenseRef-scancode-public-domain" ]
permissive
/* NAME: autoregressive.c DESCRIPTION: Calculates AR coefficients for a sequence of images in a time series. AUTHOR: Will Grey VERSION: 2015-11-22 LICENSE: This is free and unencumbered software released into the public domain. */ #include "earth.h" int autoregressive(int argc, char **argv){ metaData hdrData; FILE **fin1, **fin2, *fout, *ftext; int nFiles, file; hdrData.ignoreValue = 1; hdrData.nullValue = 0.0; hdrData.ar = 0; if (argc < 5) arUsage(); ftext=openFile("",argv[2],"rb"); fin1=openMultipleFiles(ftext, &nFiles); ftext=openFile("",argv[3],"rb"); fin2=openMultipleFiles(ftext, &nFiles); fout=openFile("",argv[4],"wb"); if (argc >= 6) hdrData.ar = atoi(argv[5]); if (argc >= 7) hdrData.ignoreValue = atoi(argv[6]); if (argc >= 8) hdrData.nullValue = atoi(argv[7]); if((fin1 = malloc (sizeof(FILE *) * MAX_NUM_FILES)) == NULL) memoryCheck(); if((fin2 = malloc (sizeof(FILE *) * MAX_NUM_FILES)) == NULL) memoryCheck(); if (hdrData.ar>=nFiles-1){ fprintf(stderr,"AR shift is greater than length of sequence"); exit(EXIT_FAILURE); } autor(fin1, fin2, fout, &hdrData, nFiles); for(file = 0; file < nFiles; file++){ fclose(fin1[file]); fclose(fin2[file]); } free(fin1); free(fin2); fclose(fout); fclose(ftext); return (EXIT_SUCCESS); } void arUsage(){ fprintf(stderr,"Usage: earth -autoregressive infile1 infile2 outfile [arNum default=0] [dataType] [IgnoreValue] [nullValue]\n\n"); fprintf(stderr, " infile1 input textfile of image list 1\n"); fprintf(stderr, " infile2 input textfile of image list 2\n"); fprintf(stderr, " outfile output image\n"); fprintf(stderr, " arNum Auto Regression shift \n"); fprintf(stderr, " IgnoreValues 0: No, 1: yes (default)\n"); fprintf(stderr, " nullValue 0.0 \n\n"); exit(EXIT_FAILURE); } int autor(FILE **fin1, FILE **fin2, FILE *fout, metaData *hdrData, int nFiles){ float *inImg1[MAX_NUM_FILES], *inImg2[MAX_NUM_FILES]; float col1[MAX_NUM_FILES], col2[MAX_NUM_FILES]; float *outImg; int x, file, remainderPixels; for (x=0;x<nFiles;x++){ if((inImg1[x] = (float *) calloc(PIXELS,sizeof(float)))== NULL) memoryCheck(); if((inImg2[x] = (float *) calloc(PIXELS,sizeof(float)))== NULL) memoryCheck(); } if((outImg = (float *) calloc(PIXELS,sizeof(float)))== NULL) memoryCheck(); while ((remainderPixels=fread(inImg1[0],sizeof(float),PIXELS,fin1[0])) == PIXELS){ for(x = 1; x < nFiles; x++) fread(inImg1[x],sizeof(float),PIXELS,fin1[x]); for(x = 0; x < nFiles; x++) fread(inImg2[x],sizeof(float),PIXELS,fin2[x]); for(x = 0; x < PIXELS; x++){ for(file = 0; file < nFiles; file++){ col1[file]=*(inImg1[file] + x); col2[file]=*(inImg2[file] + x); } *(outImg + x) = correlation (col2+hdrData->ar, col1, nFiles-hdrData->ar); } fwrite(outImg, sizeof(float), PIXELS, fout); } for(x = 0; x < nFiles; x++){ fread(inImg1[x],sizeof(float),remainderPixels,fin1[x]); fread(inImg2[x],sizeof(float),remainderPixels,fin2[x]); } for(x = 0; x < remainderPixels; x++){ for(file = 0; file < nFiles; file++){ col1[file]=*(inImg1[file] + x); col2[file]=*(inImg2[file] + x); } *(outImg + x) = correlation (col2+hdrData->ar, col1, nFiles-hdrData->ar); } fwrite(outImg,sizeof(float),remainderPixels,fout); for (x=0;x<nFiles;x++){ free(inImg1[x]); free(inImg2[x]); } free(outImg); return (EXIT_SUCCESS); }
C
UTF-8
807
3.59375
4
[]
no_license
#include<stdio.h> #include<stdlib.h> int main() { int i,p,j,sum,diff,n; float div; while(1) { printf("\t\t MENU"); printf("\n\t ADDITION"); printf("\n\t SUBSTRACTION"); printf("\n\t MULTIPLICATION"); printf("\n\t DIVISION"); printf("\n\t EXIT"); printf("\n enter any number"); scanf("%d",&n); switch(n) { case 1: printf("\n enter the value of i,j"); scanf("%d%d",&i,&j); sum=i+j; printf("sum=%d",sum); break; case 2: printf("\n enter the value of i,j"); scanf("%d%d",&i,&j); diff=i-j; printf("diff=%d",diff); break; case 3: printf("\n enter the value of i,j"); scanf("%d%d",&i,&j); p=i*j; printf("product is:%d",p); break; case 4: printf("\n enter the value of i,j"); scanf("%d%d",&i,&j); div=i/(float)j; printf("div=%f",div); break; default: printf("invalid option"); exit(0); } } return 0; }
C
UTF-8
1,775
3.28125
3
[]
no_license
// (c) 1992 Allen I. Holub #include <stdio.h> #include <ctype.h> #include "lex.h" #include "name.h" #include "retval.h" char *expression(void); char *term(void); char *factor(void); void statements(void) { // statements -> expression SEMICOLON | expression SEMICOLON statements char *tempvar; while (!match(EOI)) { tempvar = expression(); if (match(SEMICOLON)) advance(); else fprintf(stderr, "%d: Inserting missing semicolon\n", yylineno); freename(tempvar); } } char *expression(void) { // expression -> term expression' // expression' -> PLUS term expression' | epsilon char *tempvar, *tempvar2; tempvar = term(); while (match(PLUS)) { advance(); tempvar2 = term(); printf(" %s += %s\n", tempvar, tempvar2); freename(tempvar2); } return tempvar; } char *term(void) { char *tempvar, *tempvar2 ; tempvar = factor(); while (match(TIMES)) { advance(); tempvar2 = factor(); printf(" %s *= %s\n", tempvar, tempvar2); freename(tempvar2); } return tempvar; } char *factor(void) { char *tempvar; if (match(NUM_OR_ID)) { tempvar = newname(); printf(" %s = %s%.*s\n", tempvar, (isalpha(*yytext) ? "_" : " "), yyleng, yytext); advance(); } else if (match(LPAREN)) { advance(); tempvar = expression(); if (match(RPAREN)) advance(); else fprintf(stderr, "%d: Mismatched parenthesis\n", yylineno); } else { tempvar = newname(); // because it will be freed fprintf(stderr, "%d: Number or identifier expected\n", yylineno); } return tempvar; }
C
UTF-8
1,290
4.03125
4
[]
no_license
#include <stdio.h> /* Write a C program which is used to keep track of the number of cars in the local multistory carpark. The program should have four functions, one which is called when a car enters the carpark and one which is called when a car leaves the carpark. It costs €5 to enter the carpark and a separate function should keep a track of the total amount of money that has been taken and print that to the screen. The final function should report the current number of cars in the carpark. Provide test code in the main function ( by calling your functions) to demonstrate the program. The program must demonstrate the use of a global variable and a local static variable. */ int car_count = 0; double money = 0; #define COST 5 void EnteredCarPark(); void LeavesCarPark(); int AmountOfCars(); void AmountOfMoney(); int main(void){ EnteredCarPark(); EnteredCarPark(); EnteredCarPark(); AmountOfMoney(); return 0; } void EnteredCarPark(){ car_count++; } int AmountOfCars(){ return car_count; } void AmountOfMoney(){ double total = 0; for (int i = 1; i < car_count; i++) { printf("%d €%d\n",i,COST); total += COST; } printf("TOTAL : €%.2lf\n\n",total); }
C
UTF-8
1,351
3.828125
4
[ "MIT" ]
permissive
#include "acronym.h" #include <stdio.h> #include <string.h> #include <stdlib.h> #include <ctype.h> #include <stdbool.h> char *concat(char *s1, const char *letter){ int size = strlen(s1)+1+1; //+1=letter, +1=null-terminator char *result = strncat(s1, letter, size); return result; } char *chartoupper(char letter){ unsigned char cu; cu = toupper(letter); char *u = malloc(2); sprintf(u, "%c", cu); return u; } char *abbreviate(const char *phrase){ if(phrase == NULL || phrase[0] == '\0'){ return NULL; } else { int len = strlen(phrase); char *abbreviation = chartoupper(phrase[0]); bool take_letter_flag = false; // Already taken first char above for(int i = 1; i < len; i++){ char charletter = phrase[i]; printf("[%c]", charletter); if(take_letter_flag && (charletter != ' ' || charletter != '-' || charletter != '_')){ char *strletter = chartoupper(charletter); abbreviation = concat(abbreviation, strletter); take_letter_flag = false; // unset flag } if(charletter == ' ' || charletter == '-' || charletter == '_'){ printf("Take Letter\n"); take_letter_flag = true; } } return abbreviation; } }
C
UTF-8
507
2.609375
3
[]
no_license
// VTUCS /* Write a C/C++ program to avoid zombie process by forking twice. */ #include<stdio.h> #include<stdlib.h> #include<errno.h> #include<sys/wait.h> int main(void) { pid_t pid; if((pid=fork())<0) { printf("\n fork error"); } else if(pid==0) { if((pid=fork())<0) printf("fork error"); else if(pid>0) exit(0); sleep(2); printf("\nsecond child parent pid=%d\n",getppid()); exit(0); } if(waitpid(pid,NULL,0)!=pid) priintf("waitpid error"); exit(0); }
C
UTF-8
1,137
3.421875
3
[]
no_license
#include <stdio.h> #include <math.h> #include "simpson.h" #define Pi 3.141592653589793238462643383279502884197169399375105820974944592307816406286 double f1(double x) { return x/(sqrt(x * x + 9)); } double f2(double x) { return exp((-(x*x))/2); } double f3(double x) { return exp(-(x*x)); } int main () { double v; printf("Teste f1\n"); printf("Erro simpson = %.12f\n",DoubleSimpson(0,1,f1,&v)); printf("Valor da integral = %.12f\n\n",v); printf("Teste f2\n"); printf("Erro simpson = %.12f\n",DoubleSimpson(-1,1,f2,&v)); printf("Valor da integral = %.12f\n\n",(1/(sqrt(2 * Pi))) * v); printf("Teste f3\n"); printf("Erro simpson = %.12f\n",DoubleSimpson(0,3,f3,&v)); printf("Valor da integral = %.12f\n\n",(2/sqrt(Pi))* v); printf("Teste Simpson adaptativo\n"); printf("Teste f1\n"); printf("Simpson adaptativo = %.12f\n",AdaptiveSimpson(0,1,f1,0.0000016)); printf("\nTeste Quadratura de Gauss adaptativo\n"); printf("Quadratura2 de f1= %.12f\n",Quadratura2 ( 0, 1, f1 )); printf("Quadratura3 de f1= %.12f\n",Quadratura3 ( 0, 1, f1 )); return 0; }
C
UTF-8
8,547
2.53125
3
[ "MIT", "Zlib", "Unlicense" ]
permissive
// MIT License, Copyright (c) 2021 Marvin Borner // Mostly by Durand Miller, released into public domain #include <assert.h> #include <mem.h> #ifdef KERNEL #include <mm.h> static void *liballoc_alloc(u32 p) { return memory_alloc(virtual_kernel_dir(), p, MEMORY_CLEAR); } static int liballoc_free(void *ptr, u32 p) { memory_free(virtual_kernel_dir(), memory_range((u32)ptr, (u32)p)); return 0; } #else #include <sys.h> static void *liballoc_alloc(u32 p) { u32 addr; assert(sys_alloc(p, &addr) == EOK); return (void *)addr; } static int liballoc_free(void *ptr, u32 p) { UNUSED(p); assert(sys_free(ptr) == EOK); return 0; } #endif static int liballoc_lock(void) { return 0; } static int liballoc_unlock(void) { return 0; } #define ALIGNMENT 16 #define USE_CASE1 #define USE_CASE2 #define USE_CASE3 #define USE_CASE4 #define USE_CASE5 #define LIBALLOC_MAGIC 0x900df00d #define LIBALLOC_DEAD 0xbaadf00d struct liballoc_major { struct liballoc_major *prev; struct liballoc_major *next; u32 pages; u32 size; u32 usage; struct liballoc_minor *first; }; struct liballoc_minor { struct liballoc_minor *prev; struct liballoc_minor *next; struct liballoc_major *block; u32 magic; u32 size; u32 req_size; }; #define MAJOR_SIZE (ALIGN_UP(sizeof(struct liballoc_major), 16)) #define MINOR_SIZE (ALIGN_UP(sizeof(struct liballoc_minor), 16)) static struct liballoc_major *l_mem_root = NULL; static struct liballoc_major *l_best_bet = NULL; static u32 l_page_size = 4096; static u32 l_page_count = 16; static struct liballoc_major *allocate_new_page(u32 size) { u32 st = size + MAJOR_SIZE + MINOR_SIZE; if ((st % l_page_size) == 0) st = st / l_page_size; else st = st / l_page_size + 1; st = MAX(st, l_page_count); struct liballoc_major *maj = (struct liballoc_major *)liballoc_alloc(st * l_page_size); if (maj == NULL) return NULL; maj->prev = NULL; maj->next = NULL; maj->pages = st; maj->size = st * l_page_size; maj->usage = MAJOR_SIZE; maj->first = NULL; return maj; } void *_malloc(u32 req_size) { req_size = ALIGN_UP(req_size, 16); u32 best_size = 0; u32 size = req_size; liballoc_lock(); if (size == 0) { liballoc_unlock(); return _malloc(1); } if (l_mem_root == NULL) { l_mem_root = allocate_new_page(size); if (l_mem_root == NULL) { liballoc_unlock(); panic("Malloc failed!\n"); } } struct liballoc_major *maj = l_mem_root; u8 started_bet = 0; if (l_best_bet != NULL) { best_size = l_best_bet->size - l_best_bet->usage; if (best_size > (size + MINOR_SIZE)) { maj = l_best_bet; started_bet = 1; } } while (maj != NULL) { u32 diff = maj->size - maj->usage; if (best_size < diff) { l_best_bet = maj; best_size = diff; } #ifdef USE_CASE1 if (diff < (size + MINOR_SIZE)) { if (maj->next != NULL) { maj = maj->next; continue; } if (started_bet == 1) { maj = l_mem_root; started_bet = 0; continue; } maj->next = allocate_new_page(size); if (maj->next == NULL) break; maj->next->prev = maj; maj = maj->next; } #endif #ifdef USE_CASE2 if (maj->first == NULL) { maj->first = (struct liballoc_minor *)((u32)maj + MAJOR_SIZE); maj->first->magic = LIBALLOC_MAGIC; maj->first->prev = NULL; maj->first->next = NULL; maj->first->block = maj; maj->first->size = size; maj->first->req_size = req_size; maj->usage += size + MINOR_SIZE; void *p = (void *)((u32)(maj->first) + MINOR_SIZE); liballoc_unlock(); return p; } #endif #ifdef USE_CASE3 diff = (u32)(maj->first); diff -= (u32)maj; diff -= MAJOR_SIZE; if (diff >= (size + MINOR_SIZE)) { maj->first->prev = (struct liballoc_minor *)((u32)maj + MAJOR_SIZE); maj->first->prev->next = maj->first; maj->first = maj->first->prev; maj->first->magic = LIBALLOC_MAGIC; maj->first->prev = NULL; maj->first->block = maj; maj->first->size = size; maj->first->req_size = req_size; maj->usage += size + MINOR_SIZE; void *p = (void *)((u32)(maj->first) + MINOR_SIZE); liballoc_unlock(); return p; } #endif #ifdef USE_CASE4 struct liballoc_minor *min = maj->first; while (min != NULL) { if (min->next == NULL) { diff = (u32)(maj) + maj->size; diff -= (u32)min; diff -= MINOR_SIZE; diff -= min->size; if (diff >= (size + MINOR_SIZE)) { min->next = (struct liballoc_minor *)((u32)min + MINOR_SIZE + min->size); min->next->prev = min; min = min->next; min->next = NULL; min->magic = LIBALLOC_MAGIC; min->block = maj; min->size = size; min->req_size = req_size; maj->usage += size + MINOR_SIZE; void *p = (void *)((u32)min + MINOR_SIZE); liballoc_unlock(); return p; } } if (min->next != NULL) { diff = (u32)(min->next); diff -= (u32)min; diff -= MINOR_SIZE; diff -= min->size; if (diff >= (size + MINOR_SIZE)) { struct liballoc_minor *new_min = (struct liballoc_minor *)((u32)min + MINOR_SIZE + min->size); new_min->magic = LIBALLOC_MAGIC; new_min->next = min->next; new_min->prev = min; new_min->size = size; new_min->req_size = req_size; new_min->block = maj; min->next->prev = new_min; min->next = new_min; maj->usage += size + MINOR_SIZE; void *p = (void *)((u32)new_min + MINOR_SIZE); liballoc_unlock(); return p; } } min = min->next; } #endif #ifdef USE_CASE5 if (maj->next == NULL) { if (started_bet == 1) { maj = l_mem_root; started_bet = 0; continue; } maj->next = allocate_new_page(size); if (maj->next == NULL) break; maj->next->prev = maj; } #endif maj = maj->next; } liballoc_unlock(); panic("Malloc failed!\n"); } void _free(void *ptr) { liballoc_lock(); struct liballoc_minor *min = (struct liballoc_minor *)((u32)ptr - MINOR_SIZE); if (min->magic != LIBALLOC_MAGIC) { liballoc_unlock(); return; } struct liballoc_major *maj = min->block; maj->usage -= (min->size + MINOR_SIZE); min->magic = LIBALLOC_DEAD; if (min->next != NULL) min->next->prev = min->prev; if (min->prev != NULL) min->prev->next = min->next; if (min->prev == NULL) maj->first = min->next; if (maj->first == NULL) { if (l_mem_root == maj) l_mem_root = maj->next; if (l_best_bet == maj) l_best_bet = NULL; if (maj->prev != NULL) maj->prev->next = maj->next; if (maj->next != NULL) maj->next->prev = maj->prev; liballoc_free(maj, maj->pages * l_page_size); } else { if (l_best_bet != NULL) { int best_size = l_best_bet->size - l_best_bet->usage; int maj_size = maj->size - maj->usage; if (maj_size > best_size) l_best_bet = maj; } } liballoc_unlock(); } void *_realloc(void *ptr, u32 size) { size = ALIGN_UP(size, 16); if (size == 0) { _free(ptr); return NULL; } if (ptr == NULL) return _malloc(size); liballoc_lock(); struct liballoc_minor *min = (struct liballoc_minor *)((u32)ptr - MINOR_SIZE); if (min->magic != LIBALLOC_MAGIC) { liballoc_unlock(); panic("Malloc failed!\n"); } if (min->size >= size) { min->req_size = size; liballoc_unlock(); return ptr; } liballoc_unlock(); void *new_ptr = _malloc(size); memcpy(new_ptr, ptr, min->req_size); _free(ptr); return new_ptr; } void *_zalloc(u32 size) { void *ret = _malloc(size); memset(ret, 0, size); return ret; } #ifdef KERNEL #define PREFIX "K" #define FUNC printf #else #define PREFIX "U" #define FUNC log #endif #define LIMIT(size) assert(size < (100 << 20)) // Don't brag with memory pls void *realloc_debug(void *ptr, u32 size, const char *file, int line, const char *func, const char *inp0, const char *inp1) { LIMIT(size); void *ret = _realloc(ptr, size); FUNC(PREFIX "REALLOC\t%s:%d: %s: 0x%x %dB (%s; %s)\n", file, line, func, ret, size, inp0, inp1); return ret; } void *zalloc_debug(u32 size, const char *file, int line, const char *func, const char *inp) { LIMIT(size); void *ret = _zalloc(size); FUNC(PREFIX "ZALLOC\t%s:%d: %s: 0x%x %dB (%s)\n", file, line, func, ret, size, inp); return ret; } void *malloc_debug(u32 size, const char *file, int line, const char *func, const char *inp) { LIMIT(size); void *ret = _malloc(size); FUNC(PREFIX "MALLOC\t%s:%d: %s: 0x%x %dB (%s)\n", file, line, func, ret, size, inp); return ret; } void free_debug(void *ptr, const char *file, int line, const char *func, const char *inp) { _free(ptr); FUNC(PREFIX "FREE\t%s:%d: %s: 0x%x (%s)\n", file, line, func, ptr, inp); }
C
UTF-8
329
2.875
3
[]
no_license
#include<stdio.h> int main() { FILE *fp = fopen("./Nymph\'s_fault", "r"); FILE *fp2 = fopen("./Nymph\'s_fault_encrypt", "w"); char ch, ch1, ch2; fread(&ch, 1, 1, fp); printf("%c",ch); while(0 < fread(&ch1, 1, 1, fp)) { printf("%c",ch1); fputc(ch ^ ch1, fp2); ch = ch1; } fclose(fp); fclose(fp2); return 0; }
C
UTF-8
292
3.71875
4
[]
no_license
/** *clear_bit - sets the value of a bit to 0 at an index *@n:pointer to no. *@index:index *Return:0(success), (-1),otherwise */ int clear_bit(unsigned long int *n, unsigned int index) { if (index > sizeof(unsigned long int) * 8) return (-1); *n = *n & ~(1 << index); return (1); }
C
UTF-8
269
2.875
3
[]
no_license
#include "../include/ft_printf.h" #include "../libft/includes/libft.h" char *ft_strrev(char *str) { int i; int len; char tmp; i = -1; len = strlen(str); while (++i < --len) { tmp = str[i]; str[i] = str[len]; str[len] = tmp; } return (str); }
C
UTF-8
1,566
3.140625
3
[]
no_license
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_display_file.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: asun <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2016/07/28 10:49:53 by asun #+# #+# */ /* Updated: 2016/07/28 10:49:53 by asun ### ########.fr */ /* */ /* ************************************************************************** */ #include <stdlib.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/uio.h> #include <unistd.h> #include <fcntl.h> #include "ft.h" #define BUF_SIZE 10 void display(char *file_name) { int fd; char buf[BUF_SIZE + 1]; int ret; fd = open(file_name, O_RDONLY); if (fd != -1) { while ((ret = read(fd, buf, BUF_SIZE))) { buf[ret] = '\0'; ft_putstr(buf); } } close(fd); ft_putchar('\n'); } int main(int argc, char **argv) { char *file_name; if (argc < 2) { ft_puterr("File name missing.\n"); return (0); } else if (argc > 2) { ft_puterr("Too many arguments\n"); return (0); } file_name = argv[1]; display(file_name); return (0); }
C
UTF-8
1,476
2.640625
3
[ "BSD-3-Clause" ]
permissive
#include <gx.h> #include <string.h> #include <stdlib.h> #include <sys/sys.h> #define null 0 gx_hand_t *create_window (int x, int y, int w, int h, unsigned int style) { gx_hand_t *g = (gx_hand_t *)malloc(sizeof(gx_hand_t)); memset(g, 0, sizeof(gx_hand_t)); g->x = x; g->y = y; g->w = w; g->h = h; g->flag = 0; g->style = style; g->type = GX_TYPE_WINDOW; g->vmm = (void *) G->BankBuffer; g->next = null; g->tail = null; // font gx_font_init (&g->font, "font.tf", 1); // ps g->ps = (struct ps *) calloc (sizeof(struct ps),512); memset(g->ps, 0, sizeof(struct ps)*512); g->spin_lock = 0; g->pid = getpid(); // add list window_add_list(g); return (gx_hand_t *) g; } void exit_window(gx_hand_t *w) { if(!w) return; gx_hand_t *tail = w->tail; while(w->spin_lock); w->flag |= 1; window_remove_list(w); // rmover todos os objectos while(tail) { switch (tail->type) { case GX_TYPE_TITLE: exit_title(tail); break; case GX_TYPE_BOX: exit_box(tail); break; case GX_TYPE_LABEL: exit_label(tail); break; case GX_TYPE_EDITBOX: exit_editbox(tail); break; case GX_TYPE_BUTTON: exit_button(tail); break; } tail = tail->tail; } gx_font_end(&w->font); free(w); } int update_window(gx_hand_t *w) { if(w->flag&1) return (-1); int x = w->x; int y = w->y; gx_rect( x, y, w->w, w->h, 0x80808000 /*bg*/, w->vmm); gx_border (x, y, w->w, w->h, 1, 0xE0FFFF00, w->vmm); return (0); }
C
UTF-8
8,190
2.6875
3
[ "LGPL-2.1-or-later", "LicenseRef-scancode-unknown-license-reference", "MIT", "LicenseRef-scancode-generic-cla" ]
permissive
// Copyright (c) Microsoft Corporation. All rights reserved. // SPDX-License-Identifier: MIT #include "az_test_definitions.h" #include <az_result.h> #include <az_span.h> #include <az_span_private.h> #include <limits.h> #include <setjmp.h> #include <stdarg.h> #include <cmocka.h> #include <_az_cfg.h> /* void az_span_append_uint8_NULL_out_span_fails() { uint8_t raw_buffer[15]; az_span buffer = AZ_SPAN_FROM_BUFFER(raw_buffer); assert_true(az_span_append_uint8(buffer, 'a', NULL) == AZ_ERROR_ARG); } */ static void az_single_char_ascii_lower_test() { for (uint8_t i = 0; i <= SCHAR_MAX; ++i) { uint8_t buffer[1] = { i }; az_span span = AZ_SPAN_LITERAL_FROM_INITIALIZED_BUFFER(buffer); // Comparison to itself should return true for all values in the range. assert_true(az_span_is_content_equal_ignoring_case(span, span)); // For ASCII letters, verify that comparing upper and lower case return true. if (i >= 'A' && i <= 'Z') { uint8_t lower[1] = { (uint8_t)(i + 32) }; az_span lowerSpan = AZ_SPAN_LITERAL_FROM_INITIALIZED_BUFFER(lower); assert_true(az_span_is_content_equal_ignoring_case(span, lowerSpan)); assert_true(az_span_is_content_equal_ignoring_case(lowerSpan, span)); } else if (i >= 'a' && i <= 'z') { uint8_t upper[1] = { (uint8_t)(i - 32) }; az_span upperSpan = AZ_SPAN_LITERAL_FROM_INITIALIZED_BUFFER(upper); assert_true(az_span_is_content_equal_ignoring_case(span, upperSpan)); assert_true(az_span_is_content_equal_ignoring_case(upperSpan, span)); } else { // Make sure that no other comparison returns true. for (uint8_t j = 0; j <= SCHAR_MAX; ++j) { uint8_t other[1] = { j }; az_span otherSpan = AZ_SPAN_LITERAL_FROM_INITIALIZED_BUFFER(other); if (i == j) { assert_true(az_span_is_content_equal_ignoring_case(span, otherSpan)); } else { assert_false(az_span_is_content_equal_ignoring_case(span, otherSpan)); } } } } } static void az_span_append_uint8_overflow_fails() { uint8_t raw_buffer[2]; az_span buffer = AZ_SPAN_FROM_BUFFER(raw_buffer); assert_true(az_succeeded(az_span_append_uint8(buffer, 'a', &buffer))); assert_true(az_succeeded(az_span_append_uint8(buffer, 'b', &buffer))); assert_true(az_failed(az_span_append_uint8(buffer, 'c', &buffer))); } static void az_span_append_uint8_succeeds() { uint8_t raw_buffer[15]; az_span buffer = AZ_SPAN_FROM_BUFFER(raw_buffer); assert_true(az_succeeded(az_span_append_uint8(buffer, 'a', &buffer))); assert_true(az_succeeded(az_span_append_uint8(buffer, 'b', &buffer))); assert_true(az_succeeded(az_span_append_uint8(buffer, 'c', &buffer))); assert_true(az_span_is_content_equal(buffer, AZ_SPAN_FROM_STR("abc"))); } static void az_span_append_i32toa_succeeds() { int32_t v = 12345; uint8_t raw_buffer[15]; az_span buffer = AZ_SPAN_FROM_BUFFER(raw_buffer); az_span out_span; assert_true(az_succeeded(az_span_append_i32toa(buffer, v, &out_span))); assert_true(az_span_is_content_equal(out_span, AZ_SPAN_FROM_STR("12345"))); } static void az_span_append_i32toa_negative_succeeds() { int32_t v = -12345; uint8_t raw_buffer[15]; az_span buffer = AZ_SPAN_FROM_BUFFER(raw_buffer); az_span out_span; assert_true(az_succeeded(az_span_append_i32toa(buffer, v, &out_span))); assert_true(az_span_is_content_equal(out_span, AZ_SPAN_FROM_STR("-12345"))); } static void az_span_append_i32toa_zero_succeeds() { int32_t v = 0; uint8_t raw_buffer[15]; az_span buffer = AZ_SPAN_FROM_BUFFER(raw_buffer); az_span out_span; assert_true(az_succeeded(az_span_append_i32toa(buffer, v, &out_span))); assert_true(az_span_is_content_equal(out_span, AZ_SPAN_FROM_STR("0"))); } static void az_span_append_i32toa_max_int_succeeds() { int32_t v = 2147483647; uint8_t raw_buffer[15]; az_span buffer = AZ_SPAN_FROM_BUFFER(raw_buffer); az_span out_span; assert_true(az_succeeded(az_span_append_i32toa(buffer, v, &out_span))); assert_true(az_span_is_content_equal(out_span, AZ_SPAN_FROM_STR("2147483647"))); } static void az_span_append_i32toa_NULL_span_fails() { int32_t v = 2147483647; uint8_t raw_buffer[15]; az_span buffer = AZ_SPAN_FROM_BUFFER(raw_buffer); az_span out_span; assert_true(az_succeeded(az_span_append_i32toa(buffer, v, &out_span))); assert_true(az_span_is_content_equal(out_span, AZ_SPAN_FROM_STR("2147483647"))); } static void az_span_append_i32toa_overflow_fails() { int32_t v = 2147483647; uint8_t raw_buffer[4]; az_span buffer = AZ_SPAN_FROM_BUFFER(raw_buffer); az_span out_span; assert_true(az_span_append_i32toa(buffer, v, &out_span) == AZ_ERROR_INSUFFICIENT_SPAN_CAPACITY); } static void az_span_append_u32toa_succeeds() { uint32_t v = 12345; uint8_t raw_buffer[15]; az_span buffer = AZ_SPAN_FROM_BUFFER(raw_buffer); az_span out_span; assert_true(az_succeeded(az_span_append_u32toa(buffer, v, &out_span))); assert_true(az_span_is_content_equal(out_span, AZ_SPAN_FROM_STR("12345"))); } static void az_span_append_u32toa_zero_succeeds() { uint32_t v = 0; uint8_t raw_buffer[15]; az_span buffer = AZ_SPAN_FROM_BUFFER(raw_buffer); az_span out_span; assert_true(az_succeeded(az_span_append_u32toa(buffer, v, &out_span))); assert_true(az_span_is_content_equal(out_span, AZ_SPAN_FROM_STR("0"))); } static void az_span_append_u32toa_max_uint_succeeds() { uint32_t v = 4294967295; uint8_t raw_buffer[15]; az_span buffer = AZ_SPAN_FROM_BUFFER(raw_buffer); az_span out_span; assert_true(az_succeeded(az_span_append_u32toa(buffer, v, &out_span))); assert_true(az_span_is_content_equal(out_span, AZ_SPAN_FROM_STR("4294967295"))); } static void az_span_append_u32toa_NULL_span_fails() { uint32_t v = 2147483647; uint8_t raw_buffer[15]; az_span buffer = AZ_SPAN_FROM_BUFFER(raw_buffer); az_span out_span; assert_true(az_succeeded(az_span_append_u32toa(buffer, v, &out_span))); assert_true(az_span_is_content_equal(out_span, AZ_SPAN_FROM_STR("2147483647"))); } static void az_span_append_u32toa_overflow_fails() { uint32_t v = 2147483647; uint8_t raw_buffer[4]; az_span buffer = AZ_SPAN_FROM_BUFFER(raw_buffer); az_span out_span; assert_true(az_span_append_u32toa(buffer, v, &out_span) == AZ_ERROR_INSUFFICIENT_SPAN_CAPACITY); } static void az_span_to_lower_test() { az_span a = AZ_SPAN_FROM_STR("one"); az_span b = AZ_SPAN_FROM_STR("One"); az_span c = AZ_SPAN_FROM_STR("ones"); az_span d = AZ_SPAN_FROM_STR("ona"); assert_true(az_span_is_content_equal_ignoring_case(a, b)); assert_false(az_span_is_content_equal_ignoring_case(a, c)); assert_false(az_span_is_content_equal_ignoring_case(a, d)); } static void az_span_to_uint64_return_errors() { // sample span az_span sample = AZ_SPAN_FROM_STR("test"); uint64_t out = 0; assert_true(az_span_to_uint64(sample, &out) == AZ_ERROR_PARSER_UNEXPECTED_CHAR); } static void az_span_to_uint32_test() { az_span number = AZ_SPAN_FROM_STR("1024"); uint32_t value = 0; assert_return_code(az_span_to_uint32(number, &value), AZ_OK); assert_int_equal(value, 1024); } static void az_span_to_str_test() { az_span sample = AZ_SPAN_FROM_STR("hello World!"); char str[20]; assert_return_code(az_span_to_str(str, 20, sample), AZ_OK); assert_string_equal(str, "hello World!"); } void test_az_span(void** state) { (void)state; // az_span_append_uint8_NULL_out_span_fails(); az_span_append_uint8_overflow_fails(); az_span_append_uint8_succeeds(); az_span_append_i32toa_succeeds(); az_span_append_i32toa_negative_succeeds(); az_span_append_i32toa_max_int_succeeds(); az_span_append_i32toa_zero_succeeds(); az_span_append_i32toa_NULL_span_fails(); az_span_append_i32toa_overflow_fails(); az_span_append_u32toa_succeeds(); az_span_append_u32toa_zero_succeeds(); az_span_append_u32toa_max_uint_succeeds(); az_span_append_u32toa_NULL_span_fails(); az_span_append_u32toa_overflow_fails(); az_single_char_ascii_lower_test(); az_span_to_lower_test(); az_span_to_uint32_test(); az_span_to_str_test(); az_span_to_uint64_return_errors(); }
C
UTF-8
245
3.734375
4
[]
no_license
#include <stdio.h> int main(){ //standard input //use 'scanf' to read an integer value (number) printf("Enter a number: "); int number; scanf("%d", &number); //stdin --> number printf("You have entered %d\n", number); }
C
UTF-8
2,160
3.140625
3
[]
no_license
/******************************************************************************* ** C program for LZW Decompression ** ** created by: Deepanshu Bhatia ** ** Roll No. : 11-css-15 ** *******************************************************************************/ #include<stdio.h> #include<stdlib.h> #include<string.h> #define MAX 2000 init_dict(); int i=0; static char dictab[4096][32]; void main() { int count=0; init_dic(); int j,k[MAX]; static char str[MAX],temp[32],c[2]; printf("\n\tEnter the compressed data in integers : \n\t(enter 0 to terminate the input)\n"); /**************************Decompression**********************************/ /*******Decoding first value.Its always present in the dictionary*********/ scanf("%d",&k[count]); strcpy(str,dictab[k[count]]); strcpy(temp,dictab[k[count]]); count++; /*******************Decoding subsequent values****************************/ while(temp[0]!=NULL) { scanf("%d",&k[count]); strcat(str,dictab[k[count]]); j=strlen(temp); temp[j]=dictab[k[count]][0]; temp[j+1]=0; strcpy(dictab[i],temp); i++; strcpy(temp,dictab[k[count]]); count++; } printf("\n\tAfter decompressing the input\n\tString : "); puts(str); printf("\n\tSize of compressed String = %3.f bytes\n",(count-1)*1.5); printf("\n\tSize of decompressed string = %d bytes\n",strlen(str)); system("pause"); return; } /**********Initialising the Dictionary Table********/ init_dic() { char a[32]; while(i<256) { a[0]=i; a[1]=0; strcpy(dictab[i],a); i++; } }
C
UTF-8
981
3.890625
4
[]
no_license
#include <stdio.h> #include <stdlib.h> #include <ctype.h> int main(int argc, char *argv[]){ //affine cipher : (ax + b) mod26 int shift = 0, mult = 1, ch, letter; // take in ch as an int so we can do operations on it if(argc>1) shift = atoi(argv[1]); // we put shift first since if we dont want to use affine then we can just do a shift if(argc>2) mult = atoi(argv[2]); // if both parameters are entered then it will be an affine cipher while( (ch=getchar())!= EOF ){ if( isalpha(ch) ){ letter = ch & 0x1f; // converts alphabets to 1 - 26 with a at 1z letter = ((mult*letter)+shift)%26; if(letter==0) letter=26; // done so we dont get zero after we mod26(same as z or 26th alphabet) ch = (ch&0xe0)+letter; // based off ascii table. This is for lower case so we need the alpha to start at 0x60 so first three bits of 11100000 stay // change to 0xc0 for upper case. starts ar 0x40 instead of 0x60 } putchar(ch); } return 0; }
C
UTF-8
12,999
2.640625
3
[ "BSD-3-Clause", "BSD-2-Clause" ]
permissive
/* * Title: Syn Scan Network * Description: Scan if some ports are open by sending SYN packets to all IP(s) in a network * Date: 24-Apr-2018 * Author: William Chanrico * Git: https://github.com/williamchanrico/c-syn-scan-network */ #include <arpa/inet.h> #include <ctype.h> #include <errno.h> #include <inttypes.h> #include <limits.h> #include <math.h> #include <netdb.h> #include <netinet/in.h> #include <netinet/ip.h> #include <netinet/tcp.h> #include <pthread.h> #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <unistd.h> unsigned short check_sum(unsigned short*, int); const char* dotted_quad(const struct in_addr*); char* hostname_to_ip(char*); void ip_to_host(const char*, char*); void* receive_ack(void*); void process_packet(unsigned char*, int, char*); void str_to_int(int*, char*, int); void get_local_ip(char*); void err_exit(char*, ...); void prepare_datagram(char*, const char*, struct iphdr*, struct tcphdr*); void parse_target(char*, struct in_addr*, int64_t*); int parse_cidr(const char*, struct in_addr*, struct in_addr*); struct pseudo_header { //Needed for checksum calculation unsigned int source_address; unsigned int dest_address; unsigned char placeholder; unsigned char protocol; unsigned short tcp_length; struct tcphdr tcp; }; struct in_addr dest_ip; unsigned total_open_host = 0; int main(int argc, char* argv[]) { if (argc != 3) { printf("usage: %s <IP/CIDR> <Port1,Port2,...>\n", argv[0]); printf("example:\n"); printf("\t%s 166.104.0.0/16 80,443,8080\n", argv[0]); printf("\t%s 35.186.153.3 80,443,8080\n", argv[0]); printf("\t%s 166.104.177.24 80\n", argv[0]); return 1; } char* port_list = malloc(strlen(argv[2]) + 1); //Store the original of the selected port list strcpy(port_list, argv[2]); int64_t num_hosts; struct in_addr target_in_addr; parse_target(argv[1], &target_in_addr, &num_hosts); //Parse the selected target hosts char source_ip[INET6_ADDRSTRLEN]; get_local_ip(source_ip); //Get machine's local IP for IP header information in datagram packet int sockfd = socket(AF_INET, SOCK_RAW, IPPROTO_TCP); //This is the main socket to send the SYN packet if (sockfd < 0) err_exit("Error creating socket. Error number: %d. Error message: %s\n", errno, strerror(errno)); //Set IP_HDRINCL socket option to tell the kernel that headers are included in the packet int oneVal = 1; if (setsockopt(sockfd, IPPROTO_IP, IP_HDRINCL, &oneVal, sizeof(oneVal)) < 0) err_exit("Error setting IP_HDRINCL. Error number: %d. Error message: %s\n", errno, strerror(errno)); int host_count; for (host_count = 0; host_count < num_hosts; host_count++) { dest_ip.s_addr = inet_addr(dotted_quad(&target_in_addr)); //Current iteration's target host address if (dest_ip.s_addr == -1) err_exit("Invalid address\n"); char datagram[4096]; struct iphdr* iph = (struct iphdr*)datagram; //IP header struct tcphdr* tcph = (struct tcphdr*)(datagram + sizeof(struct ip)); //TCP header prepare_datagram(datagram, source_ip, iph, tcph); pthread_t sniffer_thread; if (pthread_create(&sniffer_thread, NULL, receive_ack, NULL) < 0) //Thread to listen for just one SYN-ACK packet from any of the selected ports err_exit("Could not create sniffer thread. Error number: %d. Error message: %s\n", errno, strerror(errno)); strcpy(port_list, argv[2]); char* pch = strtok(port_list, ","); while (pch != NULL) { //Iterate all selected ports and send SYN packet all at once struct sockaddr_in dest; struct pseudo_header psh; dest.sin_family = AF_INET; dest.sin_addr.s_addr = dest_ip.s_addr; int port; str_to_int(&port, pch, 10); tcph->dest = htons(port); tcph->check = 0; psh.source_address = inet_addr(source_ip); psh.dest_address = dest.sin_addr.s_addr; psh.placeholder = 0; psh.protocol = IPPROTO_TCP; psh.tcp_length = htons(sizeof(struct tcphdr)); memcpy(&psh.tcp, tcph, sizeof(struct tcphdr)); tcph->check = check_sum((unsigned short*)&psh, sizeof(struct pseudo_header)); // printf("[DEBUG] Sending SYN packet to %s:%d\n", target, port); // fflush(stdout); if (sendto(sockfd, datagram, sizeof(struct iphdr) + sizeof(struct tcphdr), 0, (struct sockaddr*)&dest, sizeof(dest)) < 0) err_exit("Error sending syn packet. Error number: %d. Error message: %s\n", errno, strerror(errno)); pch = strtok(NULL, ","); } pthread_join(sniffer_thread, NULL); //Will wait for the sniffer to receive a reply, host is considered closed if there aren't any target_in_addr.s_addr = htonl(ntohl(target_in_addr.s_addr) + 1); } close(sockfd); return total_open_host; } /** Initialize the datagram packet */ void prepare_datagram(char* datagram, const char* source_ip, struct iphdr* iph, struct tcphdr* tcph) { memset(datagram, 0, 4096); //Fill in the IP Header iph->ihl = 5; iph->version = 4; iph->tos = 0; iph->tot_len = sizeof(struct ip) + sizeof(struct tcphdr); iph->id = htons(46156); //Id of this packet iph->frag_off = htons(16384); iph->ttl = 64; iph->protocol = IPPROTO_TCP; iph->check = 0; //Set to 0 before calculating checksum iph->saddr = inet_addr(source_ip); //Spoof the source ip address iph->daddr = dest_ip.s_addr; iph->check = check_sum((unsigned short*)datagram, iph->tot_len >> 1); //TCP Header tcph->source = htons(46156); //Source Port tcph->dest = htons(80); tcph->seq = htonl(1105024978); tcph->ack_seq = 0; tcph->doff = sizeof(struct tcphdr) / 4; //Size of tcp header tcph->fin = 0; tcph->syn = 1; tcph->rst = 0; tcph->psh = 0; tcph->ack = 0; tcph->urg = 0; tcph->window = htons(14600); //Maximum allowed window size tcph->check = 0; //If you set a checksum to zero, your kernel's IP stack should fill in the correct checksum during transmission tcph->urg_ptr = 0; } /** Parse target IP into usable format Fill target_in_addr with first target IP and num_hosts with number of hosts */ void parse_target(char* target, struct in_addr* target_in_addr, int64_t* num_hosts) { // char min_ip[INET_ADDRSTRLEN], max_ip[INET_ADDRSTRLEN]; struct in_addr parsed_in_addr, mask_in_addr, wildcard_in_addr, network_in_addr, broadcast_in_addr, min_in_addr, max_in_addr; int bits = parse_cidr(target, &parsed_in_addr, &mask_in_addr); if (bits == -1) err_exit("Invalid network address: %s\nValid example: 166.104.0.0/16\n", target); wildcard_in_addr = mask_in_addr; wildcard_in_addr.s_addr = ~wildcard_in_addr.s_addr; network_in_addr = parsed_in_addr; network_in_addr.s_addr &= mask_in_addr.s_addr; broadcast_in_addr = parsed_in_addr; broadcast_in_addr.s_addr |= wildcard_in_addr.s_addr; min_in_addr = network_in_addr; max_in_addr = broadcast_in_addr; if (network_in_addr.s_addr != broadcast_in_addr.s_addr) { min_in_addr.s_addr = htonl(ntohl(min_in_addr.s_addr) + 1); max_in_addr.s_addr = htonl(ntohl(max_in_addr.s_addr) - 1); } *target_in_addr = min_in_addr; *num_hosts = (int64_t)ntohl(broadcast_in_addr.s_addr) - ntohl(network_in_addr.s_addr) + 1; fflush(stdout); } /** Convert string s to integer */ void str_to_int(int* out, char* s, int base) { if (s[0] == '\0' || isspace((unsigned char)s[0])) return; char* end; errno = 0; long l = strtol(s, &end, base); if (l > INT_MAX || (errno == ERANGE && l == LONG_MAX)) return; if (l < INT_MIN || (errno == ERANGE && l == LONG_MIN)) return; if (*end != '\0') return; *out = l; return; } /** Parse CIDR notation address. Return the number of bits in the netmask if the string is valid. Return -1 if the string is invalid. */ int parse_cidr(const char* cidr, struct in_addr* addr, struct in_addr* mask) { int bits = inet_net_pton(AF_INET, cidr, addr, sizeof addr); mask->s_addr = htonl(~(bits == 32 ? 0 : ~0U >> bits)); return bits; } /** Format the IPv4 address in dotted quad notation, using a static buffer. */ const char* dotted_quad(const struct in_addr* addr) { static char buf[INET_ADDRSTRLEN]; return inet_ntop(AF_INET, addr, buf, sizeof buf); } /** Exit the program with EXIT_FAILURE code */ void err_exit(char* fmt, ...) { va_list ap; char buff[4096]; va_start(ap, fmt); vsprintf(buff, fmt, ap); fflush(stdout); fputs(buff, stderr); fflush(stderr); exit(EXIT_FAILURE); } /** Method to sniff incoming packets and look for Ack replies */ int start_sniffer() { int sock_raw; socklen_t saddr_size, data_size; struct sockaddr_in saddr; unsigned char* buffer = (unsigned char*)malloc(65536); //Create a raw socket that shall sniff sock_raw = socket(AF_INET, SOCK_RAW, IPPROTO_TCP); if (sock_raw < 0) { printf("Socket Error\n"); fflush(stdout); return 1; } saddr_size = sizeof(saddr); //Receive a packet data_size = recvfrom(sock_raw, buffer, 65536, 0, (struct sockaddr*)&saddr, &saddr_size); if (data_size < 0) { printf("Recvfrom error, failed to get packets\n"); fflush(stdout); return 1; } process_packet(buffer, data_size, inet_ntoa(saddr.sin_addr)); close(sock_raw); return 0; } /** Method to sniff incoming packets and look for Ack replies */ void* receive_ack(void* ptr) { start_sniffer(); return NULL; } /** Method to process incoming packets and look for Ack replies */ void process_packet(unsigned char* buffer, int size, char* source_ip) { struct iphdr* iph = (struct iphdr*)buffer; //IP Header part of this packet struct sockaddr_in source, dest; unsigned short iphdrlen; if (iph->protocol == 6) { struct iphdr* iph = (struct iphdr*)buffer; iphdrlen = iph->ihl * 4; struct tcphdr* tcph = (struct tcphdr*)(buffer + iphdrlen); memset(&source, 0, sizeof(source)); source.sin_addr.s_addr = iph->saddr; memset(&dest, 0, sizeof(dest)); dest.sin_addr.s_addr = iph->daddr; if (tcph->syn == 1 && tcph->ack == 1 && source.sin_addr.s_addr == dest_ip.s_addr) { char source_host[NI_MAXHOST]; ip_to_host(source_ip, source_host); // printf("Port %d open\n", ntohs(tcph->source)); printf("%s\t%s\n", source_ip, source_host); fflush(stdout); ++total_open_host; } } } /** Checksums - IP and TCP */ unsigned short check_sum(unsigned short* ptr, int nbytes) { register long sum; register short answer; unsigned short oddbyte; sum = 0; while (nbytes > 1) { sum += *ptr++; nbytes -= 2; } if (nbytes == 1) { oddbyte = 0; *((u_char*)&oddbyte) = *(u_char*)ptr; sum += oddbyte; } sum = (sum >> 16) + (sum & 0xffff); sum = sum + (sum >> 16); answer = (short)~sum; return answer; } /** Get ip from domain name */ char* hostname_to_ip(char* hostname) { struct hostent* he; struct in_addr** addr_list; if ((he = gethostbyname(hostname)) == NULL) err_exit("gethostbyname"); addr_list = (struct in_addr**)he->h_addr_list; int a; for (a = 0; addr_list[a] != NULL; a++) return inet_ntoa(*addr_list[a]); //Return the first one; return NULL; } /** Get source IP of the system running this program */ void get_local_ip(char* buffer) { int sock = socket(AF_INET, SOCK_DGRAM, 0); const char* kGoogleDnsIp = "8.8.8.8"; int dns_port = 53; struct sockaddr_in serv; memset(&serv, 0, sizeof(serv)); serv.sin_family = AF_INET; serv.sin_addr.s_addr = inet_addr(kGoogleDnsIp); serv.sin_port = htons(dns_port); if (connect(sock, (const struct sockaddr*)&serv, sizeof(serv)) != 0) err_exit("Failed to get local IP\n"); struct sockaddr_in name; socklen_t namelen = sizeof(name); if (getsockname(sock, (struct sockaddr*)&name, &namelen) != 0) err_exit("Failed to get local IP"); inet_ntop(AF_INET, &name.sin_addr, buffer, INET6_ADDRSTRLEN); close(sock); } /** Get hostname of an IP address */ void ip_to_host(const char* ip, char* buffer) { struct sockaddr_in dest; memset(&dest, 0, sizeof(dest)); dest.sin_family = AF_INET; dest.sin_addr.s_addr = inet_addr(ip); dest.sin_port = 0; if (getnameinfo((struct sockaddr*)&dest, sizeof(dest), buffer, NI_MAXHOST, NULL, 0, NI_NAMEREQD) != 0) strcpy(buffer, "Hostname can't be determined"); }
C
UTF-8
5,851
2.578125
3
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
/** ** This source file is lifted directly from the FiSH project. ** I'm not happy having to use this, as not only are we linked ** against libcrypto, but lion has base64. But for some reason ** they went with non-standard functions for this. **/ #if HAVE_CONFIG_H #include <config.h> #endif #include "blowfish.h" /* #define S(x,i) (bf_S[i][x.w.byte##i]) */ #define S0(x) (bf_S[0][x.w.byte0]) #define S1(x) (bf_S[1][x.w.byte1]) #define S2(x) (bf_S[2][x.w.byte2]) #define S3(x) (bf_S[3][x.w.byte3]) #define bf_F(x) (((S0(x) + S1(x)) ^ S2(x)) + S3(x)) #define ROUND(a,b,n) (a.word ^= bf_F(b) ^ bf_P[n]) /* Each box takes up 4k so be very careful here */ //#define BOXES 3 /* Keep a set of rotating P & S boxes static struct box_t { u_32bit_t *P; u_32bit_t **S; char key[81]; char keybytes; } box[BOXES];*/ //static u_32bit_t *bf_P; //static u_32bit_t **bf_S; static u_32bit_t bf_P[bf_N+2]; static u_32bit_t bf_S[4][256]; static void blowfish_encipher(u_32bit_t * xl, u_32bit_t * xr) { union aword Xl; union aword Xr; Xl.word = *xl; Xr.word = *xr; Xl.word ^= bf_P[0]; ROUND(Xr, Xl, 1); ROUND(Xl, Xr, 2); ROUND(Xr, Xl, 3); ROUND(Xl, Xr, 4); ROUND(Xr, Xl, 5); ROUND(Xl, Xr, 6); ROUND(Xr, Xl, 7); ROUND(Xl, Xr, 8); ROUND(Xr, Xl, 9); ROUND(Xl, Xr, 10); ROUND(Xr, Xl, 11); ROUND(Xl, Xr, 12); ROUND(Xr, Xl, 13); ROUND(Xl, Xr, 14); ROUND(Xr, Xl, 15); ROUND(Xl, Xr, 16); Xr.word ^= bf_P[17]; *xr = Xl.word; *xl = Xr.word; } static void blowfish_decipher(u_32bit_t * xl, u_32bit_t * xr) { union aword Xl; union aword Xr; Xl.word = *xl; Xr.word = *xr; Xl.word ^= bf_P[17]; ROUND(Xr, Xl, 16); ROUND(Xl, Xr, 15); ROUND(Xr, Xl, 14); ROUND(Xl, Xr, 13); ROUND(Xr, Xl, 12); ROUND(Xl, Xr, 11); ROUND(Xr, Xl, 10); ROUND(Xl, Xr, 9); ROUND(Xr, Xl, 8); ROUND(Xl, Xr, 7); ROUND(Xr, Xl, 6); ROUND(Xl, Xr, 5); ROUND(Xr, Xl, 4); ROUND(Xl, Xr, 3); ROUND(Xr, Xl, 2); ROUND(Xl, Xr, 1); Xr.word ^= bf_P[0]; *xl = Xr.word; *xr = Xl.word; } static void blowfish_init(u_8bit_t * key, int keybytes) { int i, j; u_32bit_t data; u_32bit_t datal; u_32bit_t datar; union aword temp; // Fixes crash if key is longer than 80 char. This may cause the key // to not end with \00 but that's no problem. if (keybytes > 80) keybytes = 80; // Reset blowfish boxes to initial state for (i = 0; i < bf_N + 2; i++) bf_P[i] = initbf_P[i]; for (i = 0; i < 4; i++) for (j = 0; j < 256; j++) bf_S[i][j] = initbf_S[i][j]; j = 0; if (keybytes > 0) { for (i = 0; i < bf_N + 2; ++i) { temp.word = 0; temp.w.byte0 = key[j]; temp.w.byte1 = key[(j + 1) % keybytes]; temp.w.byte2 = key[(j + 2) % keybytes]; temp.w.byte3 = key[(j + 3) % keybytes]; data = temp.word; bf_P[i] = bf_P[i] ^ data; j = (j + 4) % keybytes; } } datal = 0x00000000; datar = 0x00000000; for (i = 0; i < bf_N + 2; i += 2) { blowfish_encipher(&datal, &datar); bf_P[i] = datal; bf_P[i + 1] = datar; } for (i = 0; i < 4; ++i) { for (j = 0; j < 256; j += 2) { blowfish_encipher(&datal, &datar); bf_S[i][j] = datal; bf_S[i][j + 1] = datar; } } } /* decode base64 string */ static int base64dec(char c) { int i; for (i = 0; i < 64; i++) if (B64[i] == c) return i; return 0; } /* Returned string must be freed when done with it! */ int encrypt_string(char *key, char *str, char *dest, int len) { u_32bit_t left, right; unsigned char *p; char *s, *d; int i; /* Pad fake string with 8 bytes to make sure there's enough */ s = (char *) malloc(len + 9); strncpy(s, str, len); s[len]=0; if ((!key) || (!key[0])) return 0; p = s; while (*p) p++; for (i = 0; i < 8; i++) *p++ = 0; blowfish_init((unsigned char *) key, strlen(key)); p = s; d = dest; while (*p) { left = ((*p++) << 24); left += ((*p++) << 16); left += ((*p++) << 8); left += (*p++); right = ((*p++) << 24); right += ((*p++) << 16); right += ((*p++) << 8); right += (*p++); blowfish_encipher(&left, &right); for (i = 0; i < 6; i++) { *d++ = B64[right & 0x3f]; right = (right >> 6); } for (i = 0; i < 6; i++) { *d++ = B64[left & 0x3f]; left = (left >> 6); } } *d = 0; free(s); return 1; } int decrypt_string(char *key, char *str, char *dest, int len) { u_32bit_t left, right; char *p, *s, *d; int i; /* Pad encoded string with 0 bits in case it's bogus */ if ((!key) || (!key[0])) return 0; s = (char *) malloc(len + 12); strncpy(s, str, len); s[len]=0; p = s; while (*p) p++; for (i = 0; i < 12; i++) *p++ = 0; blowfish_init((unsigned char *) key, strlen(key)); p = s; d = dest; while (*p) { right = 0L; left = 0L; for (i = 0; i < 6; i++) right |= (base64dec(*p++)) << (i * 6); for (i = 0; i < 6; i++) left |= (base64dec(*p++)) << (i * 6); blowfish_decipher(&left, &right); for (i = 0; i < 4; i++) *d++ = (left & (0xff << ((3 - i) * 8))) >> ((3 - i) * 8); for (i = 0; i < 4; i++) *d++ = (right & (0xff << ((3 - i) * 8))) >> ((3 - i) * 8); } *d = 0; free(s); return 1; } #if 0 int decrypt_key(char *theData) { int i; unsigned char theContactKey[500]; i=strlen(theData); if(i >= 500) return; if(strncmp(theData, "+OK ", 4) != 0) return; // key is stored plain-text strcpy(theContactKey, theData+4); decrypt_string(iniKey, theContactKey, theData, i-4); ZeroMemory(theContactKey, sizeof(theContactKey)); } int encrypt_key(char *theData) { int i; unsigned char theContactKey[500]; i=strlen(theData); if(i >= 500) return; strcpy(theContactKey, theData); strcpy(theData, "+OK "); encrypt_string(iniKey, theContactKey, theData+4, i); ZeroMemory(theContactKey, sizeof(theContactKey)); } #endif
C
UTF-8
533
3.34375
3
[]
no_license
#include <stdio.h>//(Chp02: #4) int main() { //variables,calculation float mealCost = 88.67; float tax = mealCost * 0.0675; //calc. tax @ 6.75% float subTotal = mealCost + tax; //calc meal incl.tax float tip = subTotal * 0.20;//calc tip,giving subtotal float finalTotal = subTotal + tip;//final cost //display printf ("\nMeal cost: $%5.2f", mealCost); printf ("\nTax amount: $%5.2f", tax); printf ("\nTip amount: $%5.2f", tip); printf ("\nTotal bill: $%5.2f",finalTotal); return 0; }
C
GB18030
365
2.53125
3
[]
no_license
# include<stdio.h> # include"head.h" # include<stdlib.h> Puser creatuser(); PStack creatstack(); void putmenu_one(Puser); void putmenu_two(Puser , PStack); int main(void) { Puser one = creatuser();//û PStack two = creatstack();// putmenu_one(one);//һ¼ putmenu_two(one,two);//ڶѡִв return 0; }
C
UTF-8
550
3.765625
4
[]
no_license
/* Read floating point numbers from the keyboard. Lecture: IE-B1-SO1 (Software construction 1) Author: Marc Hensel */ #define _CRT_SECURE_NO_DEPRECATE // Else MSVC++ prevents using scanf() (concern: buffer overflow) #include <stdio.h> int main(void) { float radius, pi = 3.141592; printf("Please enter a radius: "); scanf("%f", &radius); getchar(); printf("\nRadius : %.2f units\n", radius); printf("Circumference: %.2f units\n", 2.0 * pi * radius); printf("Area : %.2f units^2\n", pi * radius * radius); getchar(); return 0; }
C
UTF-8
1,966
2.8125
3
[]
no_license
#include "header.h" int check_back_slash(char *cur_arg, t_pars *pa, int i) { if (cur_arg[1 + i] == 0) return (write_error(MULTI_LINE_COMMAND, pa->s)); if (pa->quot_flag == 0) cur_arg[i] = EMPTY_BACK_SLASH; if (pa->quot_flag == 1) { if (cur_arg[i + 1] == '$') cur_arg[i] = EMPTY_BACK_SLASH; } if (cur_arg[i + 1] == ' ') cur_arg[i + 1] = EMPTY_SPACE; return (0); } int check_quotes(char *cur_arg, t_pars *pa, int i) { if (cur_arg[i] == S_QUOT && pa->quot_flag == 0) { cur_arg[i] = EMPTY_S_QUOT; pa->quot_flag = 2; } else if (cur_arg[i] == S_QUOT && pa->quot_flag == 2) { cur_arg[i] = EMPTY_S_QUOT; pa->quot_flag = 0; } else if (cur_arg[i] == W_QUOT && pa->quot_flag == 0) { cur_arg[i] = EMPTY_W_QUOT; pa->quot_flag = 1; } else if (cur_arg[i] == W_QUOT && pa->quot_flag == 1) { cur_arg[i] = EMPTY_W_QUOT; pa->quot_flag = 0; } return (0); } static int check_pipes_in_pre(char **cur_arg, t_pars *pa, int *i) { char *del; if (pa->quot_flag == 0) { del = *cur_arg; *cur_arg = find_substr_in_str_and_replace("|", *cur_arg, " \005 ", i); free(del); *i += 2; } return (0); } static int check_redirects(char **cur_arg, t_pars *pa, int *i) { if (pa->quot_flag == 0) { if (cur_arg[0][*i] == '<') cur_arg[0][*i] = RVRS_RDRCT; if (cur_arg[0][*i] == '>') cur_arg[0][*i] = FRWRD_RDRCT; } return (0); } int check_char(char **cur_arg, t_pars *pa, int *i) { if (cur_arg[0][*i] == '\\') { if (0 > check_back_slash(*cur_arg, pa, *i)) return (1); *i += 1; } else if (cur_arg[0][*i] == S_QUOT || cur_arg[0][*i] == W_QUOT) check_quotes(*cur_arg, pa, *i); else if (cur_arg[0][*i] == '$') check_envp(cur_arg, pa, i, STAGE_SECOND); else if (cur_arg[0][*i] == ' ' && pa->quot_flag != 0) cur_arg[0][*i] = EMPTY_SPACE; else if (cur_arg[0][*i] == '|') check_pipes_in_pre(cur_arg, pa, i); else if (cur_arg[0][*i] == '<' || cur_arg[0][*i] == '>') check_redirects(cur_arg, pa, i); return (0); }
C
UTF-8
763
2.71875
3
[]
permissive
#include <sys/klog.h> #include <sys/libkern.h> #include <sys/ktest.h> #include <sys/malloc.h> #include <sys/taskqueue.h> static unsigned counter; static void func(void *arg) { int n = *(int *)arg; /* Access to counter is intentionally not synchronized. */ counter += n; } static int test_taskqueue(void) { taskqueue_t tq; int N[] = {1, 2, 3}; task_t task0 = TASK_INIT(func, &N[0]); task_t task1 = TASK_INIT(func, &N[1]); task_t task2 = TASK_INIT(func, &N[2]); counter = 0; taskqueue_init(&tq); taskqueue_add(&tq, &task0); taskqueue_add(&tq, &task1); taskqueue_add(&tq, &task2); taskqueue_run(&tq); assert(counter == 1 + 2 + 3); taskqueue_destroy(&tq); return KTEST_SUCCESS; } KTEST_ADD(taskqueue, test_taskqueue, 0);
C
UTF-8
2,969
4.15625
4
[]
no_license
#include <stdio.h> // a bit of revision int main() { char c = 'S'; char *p; //pointer to char p = &c; printf("\n char c = 'S' \n char *p \n p = &c"); printf("\n {c} value of char c: %c ", c); printf("\n {&c} address of char c: %d ", &c); printf("\n {p} address which pointer p is pointing at -> address of c: %d ", p); printf("\n {*p} content of address of pointer p, which is the value of c: %c ", *p); printf("\n {&p} address of the pointer p: %d ", &p); char *p2; p2 = malloc(6); //memory allocated with malloc, is allocated in the heap printf("\n\n char *p2 \n p2 = malloc(6)"); printf("\n {p2} address that pointer p2 is pointing at %d ", p2); printf("\n {&p2} address of p2: %d ", &p2); *(p2+0) = 'h'; *(p2+1) = 'e'; *(p2+2) = 'l'; *(p2+3) = 'l'; *(p2+4) = 'o'; *(p2+5) = 0; printf("\n *(p2+0) = 'h' \n *(p2+1) = 'e' \n *(p2+2) = 'l' \n *(p2+3) = 'l' \n *(p2+4) = 'o' \n *(p2+5) = 0 "); printf("\n {p2} p2 printed as a string: %s ", p2); printf("\n {p2} p2 printed as a decimal: %d ", p2); printf("\n {0} value of the zero char, different from null char: %d ", '0'); *(p2+2) = 0; printf("\n *(p2+2) = 0"); printf("\n {p2} string created: %s ", p2); char *p3 = &"hello"; printf("\n\n char *p3 = &\"hello\""); printf("\n {p3} content pointed by p3 as string: %s ", p3); printf("\n {p3} content pointed by p3 as decimal: %d ", p3); printf("\n {*p3} content pointed by p3: %d ", *p3); char **pp; pp = &p; printf("\n\n char **pp \n pp = &p"); printf("\n {&pp} address in which pp is allocated, the address of the first box: %d ", &pp); printf("\n {pp} address pp points at, the content of the first box: %d ", pp); printf("\n {*pp} content of the second box: %d ", *pp); printf("\n {**p} content of the thirdbox: %c ", **pp); char ***ppp; ppp = &pp; printf("\n\n char ***ppp \n ppp = &pp"); printf("\n {***p} This is the content of ***ppp: %c ", ***ppp); char **pp2 = malloc(100); *pp2 = &"hi"; *(pp2+1) = &"carnegie"; *(pp2+2) = &"mellon"; printf("\n\n char **pp2 = malloc(100) \n *pp2 = &\"hi\" \n *(pp2+1) = &\"carnegie\" \n *(pp2+2) = &\"mellon\""); printf("\n {*pp2} This is hi: %s ", *pp2); printf("\n {*(pp2+1)} This is carnegie: %s ", *(pp2+1)); printf("\n {*(pp2+2)} This is mellon: %s ", *(pp2+2)); char arr[5] = "hello"; printf("\n char arr[5] = \"hello\""); printf("\n {arr[0]} arr[0]: %c ", arr[0]); printf("\n {*(arr + 0)} *arr: %c ", *(arr + 0)); printf("\n {arr[1]} arr[0]: %c ", arr[1]); printf("\n {*(arr+1)} *(arr+0): %c ", *(arr + 1)); printf("\n {arr[2]} arr[1]: %c ", arr[2]); printf("\n {*(arr+2)} *(arr+1): %c ", *(arr + 2)); printf("\n {arr[3]} arr[2]: %c ", arr[3]); printf("\n {*(arr+3)} *(arr+2): %c ", *(arr + 3)); printf("\n {arr[4]} arr[3]: %c ", arr[4]); printf("\n {*(arr+4)} *(arr+3): %c ", *(arr + 4)); printf("\n {1[arr]} 1[arr]: %c ", 1[arr]); // *(1 + arr) printf("\n \n"); return 0; }
C
UTF-8
712
4.375
4
[]
no_license
/* (5) Write a C function to return the index of FIRST occurrence of a number in a given array. Array index start from 0. If the item is not in the list return -1. (Linear Search Algorithm) Example: Array = {1,2,3,4,4,4} The required number is 4 it should return 3 */ #define SIZE 6 #include <stdio.h> char FirstOccurrence(int num , int arr[] , int size) ; int main(void) { int arr[SIZE] = {1 , 2 , 3 , 4 , 4 , 4 } ; printf("First Occurrence For 4 at a[ %d ]\n" , FirstOccurrence(4 , arr , SIZE ) ); while(1); return 0 ; } char FirstOccurrence(int num , int arr[] , int size) { for(int i = 0 ; i<size ; i++) { if(num == arr[i]) { return i ; } } return -1 ; }
C
UTF-8
3,608
2.875
3
[ "MIT" ]
permissive
#include "zapis_odczyt.h" #include "main.h" #include "edycja.h" #include "sortowanie.h" int wczytaj_baze(char nazwa_pliku[]) { FILE *f=fopen(nazwa_pliku,"r"); if (f==NULL) return -1; char pom; int i=0, poziom=1; liczba_wierszy_bazy=1; poczatek = malloc(sizeof(struct t_pole_listy)); struct t_pole_listy *aktualny=poczatek, *poprzedni=NULL; while(fscanf(f,"%c", &pom)!=EOF) { if (pom=='\n') { poprzedni=aktualny; aktualny->nastepny=malloc(sizeof(struct t_pole_listy)); aktualny=aktualny->nastepny; i=0; poziom=1; liczba_wierszy_bazy++; } else { switch(poziom) { case 1: (aktualny->imie)[i]=pom; i++; if (pom==' ') { (aktualny->imie)[i]='\0'; poziom=2, i=0; } if (i>=MAX_IMIE+1) return -1; break; case 2: (aktualny->nazwisko)[i]=pom; i++; if (pom==' ') { (aktualny->nazwisko)[i]='\0'; poziom=3, i=0; } if (i>=MAX_NAZWISKO+1) return -1; break; case 3: (aktualny->ugrupowanie)[i]=pom; i++; if (pom==' ') { (aktualny->ugrupowanie)[i]='\0'; poziom=4, i=0; } if (i>=MAX_UGRUPOWANIE+1) return -1; break; case 4: (aktualny->liczba_glosow)[i]=pom; i++; if (pom==' ') { (aktualny->liczba_glosow)[i]='\0'; poziom=5, i=0; } if (i>=MAX_LICZBA_GLOSOW+1) return -1; break; case 5: (aktualny->wiek)[i]=pom; i++; if (pom==' ') { (aktualny->wiek)[i]='\0'; poziom=6, i=0; } if (i>=MAX_WIEK+1) return -1; break; case 6: (aktualny->okreg_wyborczy)[i]=pom; i++; if (pom==' ') { (aktualny->okreg_wyborczy)[i]='\0'; poziom=7; } if (i>=MAX_OKREG_WYBORCZY+1) return -1; break; } } } if (poziom!=7) { free(aktualny); aktualny=poprzedni; liczba_wierszy_bazy--; } if(poprzedni==NULL) { fclose(f); poczatek=NULL; return -1; } aktualny->nastepny=NULL; fclose(f); return 0; } int zapisz (char nazwa[]) { FILE* f; f=fopen(nazwa,"w"); if(f==NULL) return -1; struct t_pole_listy* aktualny; for(aktualny=poczatek; aktualny!=NULL; aktualny=aktualny->nastepny) fprintf(f, "%s%s%s%s%s%s\n", aktualny->imie, aktualny->nazwisko, aktualny->ugrupowanie, aktualny->liczba_glosow, aktualny->wiek, aktualny->okreg_wyborczy); fclose(f); return 0; }
C
UTF-8
2,462
3.109375
3
[]
no_license
/* ** MODF.C - split floating point number into int and fractional parts ** ** (c) Copyright Ken Harrenstien 1989 ** ** This code does NOT conform to the description of the modf function ** as defined in Harbison and Steele's "C: A Reference Manual", ** section 11.3.18. H&S is wrong in saying that the ** 2nd arg to "modf" is an (int *); both ANSI and BSD say it is a ** (double *). Otherwise the description is accurate. ** ** Note that this only works for normalized values. In particular, a number ** with only the sign bit set is unnormalized. Fortunately the hardware never ** generates such numbers. */ #include <c-env.h> /* So can see what format we're using */ #if CPU_PDP10 /* Currently PDP-10 only */ double modf(x, iptr) double x, *iptr; /* Note 2nd arg is ptr to double, not int! */ { #if CENV_DFL_H /* PDP-10 hardware double precision fmt */ #asm EXTERN $ZERO /* From CRT */ DMOVE 1,-2(17) /* Get double arg */ SKIPGE 7,1 /* Check for neg number, remember sign in 7 */ DMOVN 1,1 /* Negative, so turn it over */ CAMG 1,[201000,,0] /* Do we have an integer part? */ JRST [ SETZB 3,4 /* No, set integer part to (double) 0 */ DMOVEM 3,@-3(17) /* Store via pointer */ CAIG 7,0 /* If arg was negative, */ DMOVN 1,1 /* must return negative result. */ POPJ 17,] CAML 1,[276000,,0] /* Do we have a fraction part? */ JRST [ CAIG 7,0 /* No, just store arg as integer part */ DMOVN 1,1 DMOVEM 1,@-3(17) SETZB 1,2 /* And return zero fractional part! */ POPJ 17,] /* Have both integer and fraction part. Find fraction bit mask. */ LDB 4,[331000,,1] /* Get exponent */ MOVNI 4,-200(4) /* Find -<# bits in integral part> */ MOVSI 5,400000 /* Get a sign-bit-set doubleword mask */ SETZ 6, ASHC 5,-10(4) /* Shift mask over exponent & integer bits */ DMOVE 3,1 /* Copy positive # for integer part */ AND 3,5 AND 4,6 /* Mask out fract bits, leave integer bits */ TLZ 5,777000 /* After ensuring that exponent preserved, */ ANDCM 1,5 /* apply reverse mask to get fraction bits. */ ANDCM 2,6 JUMPL 7,[ /* If negation needed, */ DMOVNM 3,@-3(17) /* store negated integer part, and */ DMOVN 1,1 /* negate returned fractional part */ JRST .+2] /* Skip over DMOVEM */ DMOVEM 3,@-3(17) /* Store integer part */ DFAD 1,$ZERO /* and normalize returned fraction. */ /* Drop thru to return */ #endasm #else #error modf() not implemented for this double-precision format. #endif } #endif /* CPU_PDP10 */
C
UTF-8
1,806
2.734375
3
[]
no_license
/** * @file tan_09.c * @brief tangent * * @since 2003-07-17 * @author D. Andoleit * * Copyright (c) 2003 by dSPACE GmbH, Paderborn, Germany * All Rights Reserved * */ /* * $Workfile: TAN_09.c $ * $Revision: 4 $ * $Date: 28.10.03 14:34 $ */ #include "dsfxp.h" /****************************************************************************** * * FUNCTION: * F__I32TANI32_LT9(v, ysh) * * DESCRIPTION: * Calculates tan as sin/cos using table. * Output scaling is 2^-ysh * * PARAMETERS: * Int32 v input value * Int8 ysh exponent of output LSB negate * * RETURNS: * Int32 y return value * * NOTE: * * ******************************************************************************/ Int32 F__I32TANI32_LE9(Int32 v, Int8 ysh) { Int32 y_sin; Int32 y_cos; Int32 y = 1; Int32 y_sin_h; UInt32 y_sin_l; Int32 y_cos_h; UInt32 y_cos_l; if (v == -2147483648) { y = 0x80000000; } else { if (v < 0) { v = -v; y = -1; } v = v >> 1; y_sin = F__I32SINI32_LE9(v); y_cos = F__I32SINI32_LE9(v + 0x40000000); C__I64COPYI32(y_sin, y_sin_h, y_sin_l); C__I64SHLI32C6_LT32(y_cos, 31 - ysh, 1 + ysh, y_cos_h, y_cos_l); if C__LT64(y_sin_h, y_sin_l, y_cos_h, y_cos_l) { y *= y_sin; C__I64SHLI32C6_LT32(y, ysh, (32-ysh), y_sin_h, y_sin_l); C__I32DIVI64I32(y_sin_h, y_sin_l, y_cos, y); } else { if (y == 1) { y = 0x7fffffff; } else { y = 0x80000000; } } } return y; } /* END F__I32TANI32_LE9() */
C
UTF-8
400
2.90625
3
[]
no_license
#include <stdio.h> void fibo(int, int,int); void fibo(int x, int y,int n) { int c; //static int n = 3; if (n <= 24) { if (x == 1 && y == 1) { printf("%d %d", x, y); } printf(" %d ", x + y); n++; fibo(y, x + y,n); ; } else { return; } } int main() { fibo(1, 1,2); return 0; }
C
UTF-8
1,128
2.71875
3
[]
no_license
/** @mainpage pdfToText documentation * * @author Jonas Bujok (bujon(at)centrum.cz) * * @section intro Introduction * This is documentation for pdfToText program for extractin text information from pdf files. * I hope this documentation will provide enough information to understand all classes and it's purpouse. * <br><br> * You can find whole project in <A HREF="http://code.google.com/p/pdf-to-text/source/browse?repo=default"> git repository </A> * of <A HREF="http://code.google.com/p/pdf-to-text/"> Google code project page</A>. <br> * In <A HREF="http://code.google.com/p/pdf-to-text/source/browse/?repo=docs"> docs </A> repository there is bechelor work * for this project in czech language and pdf specification in english language if you need some informations about pdf file and * how extraction works. <br> * It is recomanded to get familiar with pdf file structure, syntax and objects before playing around with the code. * The extraction procedure is very complicated and probably can not be understood from looking at code. * <br><hr><br> * Feel free to contact author about issues connected with this project. */
C
UTF-8
540
3.4375
3
[]
no_license
// W3Q9 // Alvin Fujito #include <stdio.h> int main (void) { int size; printf("Enter size: "); scanf("%d", &size); int row = 1; while (row <= size) { int col = 1; while (col <= size) { if (col == row) { printf("*"); } else { printf("-"); } col++; } printf("\n"); row++; } return 0; }
C
BIG5
1,003
4.15625
4
[]
no_license
/* ܱƧ */ #include <stdio.h> void select_sort(int[], int); void main() { int data[20]; int size = 0, i; /* nDJƪJs */ printf("\nPlease enter number to sort ( enter 0 when end ):\n"); printf("Number : "); do { scanf("%d", &data[size]); } while(data[size++] != 0); for(i = 0; i < 60; i++) printf("-"); printf("\n"); select_sort(data, --size); for(i = 0; i < 60; i++) printf("-"); printf("\nSorting: "); for(i = 0; i < size; i++) printf("%d ", data[i]); } void select_sort(int data[], int size) { int base, compare, min, temp, i; for(base = 0; base < size-1; base++) { /* NثeƻP᭱Ƥ̤p */ min = base; for(compare = base+1; compare < size; compare++) if(data[compare] < data[min]) min = compare; temp = data[min]; data[min] = data[base]; data[base] = temp; printf("Access : "); for(i = 0; i < size; i++) printf("%d ", data[i]); printf("\n"); } }
C
UTF-8
1,079
2.6875
3
[]
no_license
#define NULL ((void*)0) typedef unsigned long size_t; // Customize by platform. typedef long intptr_t; typedef unsigned long uintptr_t; typedef long scalar_t__; // Either arithmetic or pointer type. /* By default, we understand bool (as a convenience). */ typedef int bool; #define false 0 #define true 1 /* Forward declarations */ /* Type definitions */ typedef int /*<<< orphan*/ cam_pinfo ; /* Variables and functions */ scalar_t__ queue_cmp (int /*<<< orphan*/ **,int,int) ; int /*<<< orphan*/ swap (int /*<<< orphan*/ **,int,int) ; __attribute__((used)) static void heap_down(cam_pinfo **queue_array, int index, int num_entries) { int child; int parent; parent = index; child = parent << 1; for (; child <= num_entries; child = parent << 1) { if (child < num_entries) { /* child+1 is the right child of parent */ if (queue_cmp(queue_array, child + 1, child) < 0) child++; } /* child is now the least child of parent */ if (queue_cmp(queue_array, parent, child) <= 0) break; swap(queue_array, child, parent); parent = child; } }
C
UTF-8
1,949
3.875
4
[]
no_license
#include <stdio.h> #include <stdlib.h> void get_number(void); void process_num(int x); int main(int argc,char **argv){ get_number(); return EXIT_SUCCESS; } void get_number(void){ int num; printf("Input a 2-digits number: "); scanf("%d", &num); process_num(num); } void process_num(int x){ int tens=x/10; int ones=x%10; if(tens==1){ switch(ones){ case 0: printf("Ten"); break; case 1: printf("Eleven"); break; case 2: printf("Twelve"); break; case 3: printf("Thirteen"); break; case 4: printf("Fourteen"); break; case 5: printf("Fifteen"); break; case 6: printf("Sixteen"); break; case 7: printf("Seventeen"); break; case 8: printf("Eighteen"); break; case 9: printf("Nighteen"); break; } }else { switch(tens){ case 2:printf("Twenty-"); break; case 3:printf("Thirty-"); break; case 4:printf("Forty-"); break; case 5:printf("Fifty-"); break; case 6:printf("Sixty-"); break; case 7:printf("Seventy-"); break; case 8:printf("Eighty-"); break; case 9:printf("Ninty-"); break; } switch(ones){ case 1: printf("One"); break; case 2: printf("Two"); break; case 3: printf("Three"); break; case 4: printf("Four"); break; case 5: printf("Five"); break; case 6: printf("Six"); break; case 7: printf("Seven"); break; case 8: printf("Eight"); break; case 9: printf("Nine"); break; } } printf("\n"); }
C
UTF-8
458
4.125
4
[]
no_license
#include <stdio.h> main() { int x, y; printf("Introduza dois inteiros: "); scanf("%d%d", &x, &y); printf("O resultado de %d == %d : %d\n", x, y, x==y); printf("O resultado de %d > %d : %d\n", x, y, x>y); printf("O resultado de %d >= %d : %d\n", x, y, x>=y); printf("O resultado de %d < %d : %d\n", x, y, x<y); printf("O resultado de %d <= %d : %d\n", x, y, x<=y); printf("O resultado de %d != %d : %d\n", x, y, x!=y); }
C
UTF-8
40,231
2.78125
3
[ "MIT" ]
permissive
/* * Testing for Chess implementation in C * Created by thearst3rd on 8/6/2020 */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "tests.h" #include "chesslib/squareset.h" #include "chesslib/movelist.h" #include "chesslib/board.h" #include "chesslib/piecemoves.h" #include "chesslib/boardlist.h" const char *currTest; #define RUN_TEST(testName) currTest=#testName; testName(); // Runs tests. Will halt when one is failed int main(int argc, char *argv[]) { // Test Square RUN_TEST(testSqI); RUN_TEST(testSqS); RUN_TEST(testSqGetStr); RUN_TEST(testSqIsDark); // Test Move RUN_TEST(testMoveCreate); RUN_TEST(testMoveGetUci); RUN_TEST(testMoveFromUci); // Test Move List RUN_TEST(testMoveList); // Test Board RUN_TEST(testBoardCreate); RUN_TEST(testBoardCreateFromFen); //RUN_TEST(testBoardEq); // Test Piece Moves RUN_TEST(testPawnMoves); RUN_TEST(testKnightMoves); RUN_TEST(testBishopMoves); RUN_TEST(testRookMoves); RUN_TEST(testQueenMoves); RUN_TEST(testKingMoves); // Test Attacked Squares RUN_TEST(testIsSquareAttacked); RUN_TEST(testIsInCheck); // Test playing moves RUN_TEST(testBoardPlayMove); // Test board move generation RUN_TEST(testBoardGenerateMoves); RUN_TEST(testBoardGenerateMovesCastling); // Test FEN generation RUN_TEST(testBoardGetFen); // Test draw by insufficient material RUN_TEST(testBoardIsInsufficientMaterial); // Test board list RUN_TEST(testBoardList); // Test square set RUN_TEST(testSqSetSet); RUN_TEST(testSqSetGet); // We made it to the end printf("Success - all tests passed!\n"); return 0; } ////////////////////// // HELPER FUNCTIONS // ////////////////////// // Fail the currently running test and halt the program. NULL for no message void failTest(const char *msg) { if (msg == NULL) fprintf(stderr, "TEST FAILED - %s\n", currTest); else fprintf(stderr, "TEST FAILED - %s: %s\n", currTest, msg); exit(1); } void validateString(const char *actual, const char *expected) { if (strcmp(actual, expected) != 0) { int len1 = strlen(actual); int len2 = strlen(expected); char *str = (char *) malloc(35 + len1 + len2); sprintf(str, "Actual \"%s\", but expected \"%s\"", actual, expected); failTest(str); // This doesn't actually get run because failTest exits, but it just feels like the right thing to do free(str); } } ///////////////// // TEST SQUARE // ///////////////// void testSqI() { for (uint8_t rank = 1; rank <= 8; rank++) { for (uint8_t file = 1; file <= 8; file++) { sq s = sqI(file, rank); if (s.file != file || s.rank != rank) { char msg[50]; sprintf(msg, "Actual (%d, %d), but expected (%d, %d)", s.file, s.rank, file, rank); failTest(msg); } } } } void testSqS() { for (uint8_t rank = 1; rank <= 8; rank++) { for (uint8_t file = 1; file <= 8; file++) { char str[3] = {'a' + file - 1, '0' + rank, 0}; sq s = sqS(str); if (s.file != file || s.rank != rank) { char msg[60]; sprintf(msg, "Actual (%d, %d), but expected (%d, %d) from \"%s\"", s.file, s.rank, file, rank, str); failTest(msg); } } } } void testSqGetStr() { for (uint8_t rank = 1; rank <= 8; rank++) { for (uint8_t file = 1; file <= 8; file++) { sq s = sqI(file, rank); char str[3] = {'a' + file - 1, '0' + rank, 0}; validateString(sqGetStr(s), str); } } } void testSqIsDark() { uint8_t expectedIsDark = 1; // a1 is expected to be dark for (uint8_t rank = 1; rank <= 8; rank++) { for (uint8_t file = 1; file <= 8; file++) { sq s = sqI(file, rank); uint8_t actualIsDark = sqIsDark(s); if (actualIsDark != expectedIsDark) { char message[50]; sprintf(message, "Square %s was %s, expected %s", sqGetStr(s), actualIsDark ? "dark" : "light", expectedIsDark ? "dark" : "light"); failTest(message); } expectedIsDark = !expectedIsDark; } expectedIsDark = !expectedIsDark; } } /////////////// // TEST MOVE // /////////////// void validateMove(move m, sq expectedFrom, sq expectedTo, pieceType expectedPromotion) { if (!sqEq(m.from, expectedFrom) || !sqEq(m.to, expectedTo) || m.promotion != expectedPromotion) { char msg[55]; sprintf(msg, "Actual (%s, %s, %d), but expected (%s, %s, %d)", sqGetStr(m.from), sqGetStr(m.to), m.promotion, sqGetStr(expectedFrom), sqGetStr(expectedTo), expectedPromotion); failTest(msg); } } void testMoveCreate() { // maybe TODO - make this test more thorough move m = moveSq(sqI(5, 8), sqI(5, 7)); validateMove(m, sqI(5, 8), sqI(5, 7), ptEmpty); m = movePromote(sqI(3, 2), sqI(2, 1), ptQueen); validateMove(m, sqI(3, 2), sqI(2, 1), ptQueen); } void testMoveGetUci() { // maybe TODO - make this test more thorough move m = moveSq(sqI(5, 8), sqI(5, 7)); validateString(moveGetUci(m), "e8e7"); m = movePromote(sqI(3, 2), sqI(2, 1), ptQueen); validateString(moveGetUci(m), "c2b1q"); } void testMoveFromUci() { // maybe TODO - make this test more thorough move m = moveFromUci("e8e7"); validateMove(m, sqI(5, 8), sqI(5, 7), ptEmpty); m = moveFromUci("c2b1q"); validateMove(m, sqI(3, 2), sqI(2, 1), ptQueen); } /////////////////// // TEST MOVELIST // /////////////////// void testMoveList() { move m1 = moveFromUci("e2e4"); move m2 = moveFromUci("e7e5"); move m3 = moveFromUci("e1e2"); moveList *list = moveListCreate(); moveListAdd(list, m1); moveListAdd(list, m2); moveListAdd(list, m3); move m11 = moveListGet(list, 0); move m12 = moveListGet(list, 1); move m13 = moveListGet(list, 2); char *uci; char *expected; uci = moveGetUci(m11); expected = "e2e4"; if (strcmp(uci, expected) != 0) { char failStr[30]; sprintf(failStr, "Actual \"%s\" but, expected \"%s\"", uci, expected); failTest(failStr); } free(uci); uci = moveGetUci(m12); expected = "e7e5"; if (strcmp(uci, expected) != 0) { char failStr[30]; sprintf(failStr, "Actual \"%s\" but, expected \"%s\"", uci, expected); failTest(failStr); } free(uci); uci = moveGetUci(m13); expected = "e1e2"; if (strcmp(uci, expected) != 0) { char failStr[30]; sprintf(failStr, "Actual \"%s\" but, expected \"%s\"", uci, expected); failTest(failStr); } free(uci); moveListFree(list); } //////////////// // TEST BOARD // //////////////// void assertPiece(piece actual, piece expected) { if (actual != expected) { char actualL = pieceGetLetter(actual); char expectedL = pieceGetLetter(expected); char message[45]; sprintf(message, "Actual piece '%c' found, expected '%c'", actualL, expectedL); failTest(message); } } void testBoardCreate() { board *b = boardCreate(); if (b == NULL) failTest("Created board was NULL"); assertPiece(b->pieces[0], pWRook); assertPiece(b->pieces[1], pWKnight); assertPiece(b->pieces[2], pWBishop); assertPiece(b->pieces[3], pWQueen); assertPiece(b->pieces[4], pWKing); assertPiece(b->pieces[5], pWBishop); assertPiece(b->pieces[6], pWKnight); assertPiece(b->pieces[7], pWRook); for (int i = 8; i < 16; i++) assertPiece(b->pieces[i], pWPawn); for (int i = 16; i < 48; i++) assertPiece(b->pieces[i], pEmpty); for (int i = 48; i < 56; i++) assertPiece(b->pieces[i], pBPawn); assertPiece(b->pieces[56], pBRook); assertPiece(b->pieces[57], pBKnight); assertPiece(b->pieces[58], pBBishop); assertPiece(b->pieces[59], pBQueen); assertPiece(b->pieces[60], pBKing); assertPiece(b->pieces[61], pBBishop); assertPiece(b->pieces[62], pBKnight); assertPiece(b->pieces[63], pBRook); if (b->currentPlayer != pcWhite) failTest("Actual: black to play, expected: white to play"); if (b->castleState != 0b1111) failTest("Not all castling flags enabled"); if (!sqEq(b->epTarget, SQ_INVALID)) failTest("EP target square was not SQ_INVALID"); if (b->halfMoveClock != 0) { char message[50]; sprintf(message, "Half move clock was %u, expected 0", b->halfMoveClock); failTest(message); } if (b->moveNumber != 1) { char message[50]; sprintf(message, "Full move number was %u, expected 1", b->moveNumber); failTest(message); } free(b); } void testBoardCreateFromFen() { board *b = boardCreateFromFen("8/8/3k4/8/4Pp2/2K5/8/5QQQ b - e3 0 46"); if (b == NULL) failTest("Created board was NULL"); for (int i = 0; i < 64; i++) { // Special case out the pieces that are actually there if ((i == 5) || (i == 6) || (i == 7) || (i == 18) || (i == 28) || (i == 29) || (i == 43)) continue; assertPiece(b->pieces[i], pEmpty); } assertPiece(b->pieces[5], pWQueen); assertPiece(b->pieces[6], pWQueen); assertPiece(b->pieces[7], pWQueen); assertPiece(b->pieces[28], pWPawn); assertPiece(b->pieces[29], pBPawn); assertPiece(b->pieces[18], pWKing); assertPiece(b->pieces[43], pBKing); if (b->currentPlayer != pcBlack) failTest("Actual: white to play, expected: black to play"); if (b->castleState != 0b0000) failTest("Not all castling flags disabled"); if (!sqEq(b->epTarget, sqI(5, 3))) { char message[50]; sprintf(message, "Actual EP target square: %s, expected: e3", sqGetStr(b->epTarget)); failTest(message); } if (b->halfMoveClock != 0) { char message[50]; sprintf(message, "Half move clock was %u, expected 0", b->halfMoveClock); failTest(message); } if (b->moveNumber != 46) { char message[50]; sprintf(message, "Full move number was %u, expected 46", b->moveNumber); failTest(message); } free(b); } void testBoardEq() { failTest("Not yet implemented"); // TODO //board *b1 = boardCreateFromFen("") } ///////////////////// // TEST PIECEMOVES // ///////////////////// // Helper function - checks if given UCI string exists in moveList void validateUciIsInMovelist(moveList *list, char *expectedUci) { for (moveListNode *n = list->head; n; n = n->next) { char *actualUci = moveGetUci(n->move); int cmp = strcmp(actualUci, expectedUci); free(actualUci); if (cmp == 0) return; } char message[60]; sprintf(message, "Expected %s to be in move list but was absent", expectedUci); failTest(message); } // Helper function - validates the size of the list void validateListSize(moveList *list, size_t expectedSize) { if (list->size != expectedSize) { char message[70]; sprintf(message, "Actual list was %zu element(s), expected %zu", list->size, expectedSize); failTest(message); } } void testPawnMoves() { board *b; moveList *list; // Lone white pawn on starting rank b = boardCreateFromFen("8/8/8/8/8/8/4P3/8 w - - 0 1"); list = pmGetPawnMoves(b, sqS("e2")); validateListSize(list, 2); validateUciIsInMovelist(list, "e2e3"); validateUciIsInMovelist(list, "e2e4"); moveListFree(list); // Pawn with captures boardInitFromFenInPlace(b, "8/8/8/8/8/3q1n2/4P3/8 w - - 0 1"); list = pmGetPawnMoves(b, sqS("e2")); validateListSize(list, 4); validateUciIsInMovelist(list, "e2e3"); validateUciIsInMovelist(list, "e2e4"); validateUciIsInMovelist(list, "e2d3"); validateUciIsInMovelist(list, "e2f3"); moveListFree(list); // Pawn blocked boardInitFromFenInPlace(b, "8/8/8/8/8/4N3/4P3/8 w - - 0 1"); list = pmGetPawnMoves(b, sqS("e2")); validateListSize(list, 0); moveListFree(list); // Pawn not on first rank boardInitFromFenInPlace(b, "8/8/8/8/4P3/8/8/8 w - - 0 1"); list = pmGetPawnMoves(b, sqS("e4")); validateListSize(list, 1); validateUciIsInMovelist(list, "e4e5"); moveListFree(list); // White pawn about to promote boardInitFromFenInPlace(b, "8/6P1/8/8/8/8/8/8 w - - 0 1"); list = pmGetPawnMoves(b, sqS("g7")); validateListSize(list, 4); validateUciIsInMovelist(list, "g7g8q"); validateUciIsInMovelist(list, "g7g8r"); validateUciIsInMovelist(list, "g7g8b"); validateUciIsInMovelist(list, "g7g8n"); moveListFree(list); // Black pawn on first rank boardInitFromFenInPlace(b, "8/6p1/8/8/8/8/8/8 b - - 0 1"); list = pmGetPawnMoves(b, sqS("g7")); validateListSize(list, 2); validateUciIsInMovelist(list, "g7g6"); validateUciIsInMovelist(list, "g7g5"); moveListFree(list); // Pawn blocked with one free spot, opp color boardInitFromFenInPlace(b, "8/6p1/8/6P1/8/8/8/8 b - - 0 1"); list = pmGetPawnMoves(b, sqS("g7")); validateListSize(list, 1); validateUciIsInMovelist(list, "g7g6"); moveListFree(list); // Black pawn about to promote, with capturing ability boardInitFromFenInPlace(b, "8/8/8/8/8/8/p7/1Q6 b - - 0 1"); list = pmGetPawnMoves(b, sqS("a2")); validateListSize(list, 8); validateUciIsInMovelist(list, "a2a1q"); validateUciIsInMovelist(list, "a2a1r"); validateUciIsInMovelist(list, "a2a1b"); validateUciIsInMovelist(list, "a2a1n"); validateUciIsInMovelist(list, "a2b1q"); validateUciIsInMovelist(list, "a2b1r"); validateUciIsInMovelist(list, "a2b1b"); validateUciIsInMovelist(list, "a2b1n"); moveListFree(list); // White with opportunity to capture en passant boardInitFromFenInPlace(b, "8/8/8/4Pp2/8/8/8/8 w - f6 0 1"); //b->currentPlayer = pcWhite; //b->epTarget = sqS("f6"); list = pmGetPawnMoves(b, sqS("e5")); validateListSize(list, 2); validateUciIsInMovelist(list, "e5e6"); validateUciIsInMovelist(list, "e5f6"); moveListFree(list); // Black with opportunity to capture en passant boardInitFromFenInPlace(b, "8/8/8/8/6Pp/8/8/8 b - g3 0 1"); //b->currentPlayer = pcBlack; //b->epTarget = sqS("g3"); list = pmGetPawnMoves(b, sqS("h4")); validateListSize(list, 2); validateUciIsInMovelist(list, "h4h3"); validateUciIsInMovelist(list, "h4g3"); moveListFree(list); free(b); } void testKnightMoves() { board b; moveList *list; // Lone knight boardInitFromFenInPlace(&b, "8/8/8/8/8/2N5/8/8 w - - 0 1"); list = pmGetKnightMoves(&b, sqS("c3")); validateListSize(list, 8); validateUciIsInMovelist(list, "c3d5"); validateUciIsInMovelist(list, "c3e4"); validateUciIsInMovelist(list, "c3e2"); validateUciIsInMovelist(list, "c3d1"); validateUciIsInMovelist(list, "c3b1"); validateUciIsInMovelist(list, "c3a2"); validateUciIsInMovelist(list, "c3a4"); validateUciIsInMovelist(list, "c3b5"); moveListFree(list); // Knight near the edge boardInitFromFenInPlace(&b, "8/7n/8/8/8/8/8/8 b - - 0 1"); list = pmGetKnightMoves(&b, sqS("h7")); validateListSize(list, 3); validateUciIsInMovelist(list, "h7g5"); validateUciIsInMovelist(list, "h7f6"); validateUciIsInMovelist(list, "h7f8"); moveListFree(list); // Knight with some blocks boardInitFromFenInPlace(&b, "6N1/3BQQQn/4QnQ1/4QQQ1/4b3/8/8/8 b - - 0 1"); list = pmGetKnightMoves(&b, sqS("f6")); validateListSize(list, 6); validateUciIsInMovelist(list, "f6g8"); validateUciIsInMovelist(list, "f6h5"); validateUciIsInMovelist(list, "f6g4"); validateUciIsInMovelist(list, "f6d5"); validateUciIsInMovelist(list, "f6d7"); validateUciIsInMovelist(list, "f6e8"); moveListFree(list); } void testBishopMoves() { board b; moveList *list; // Lone bishop boardInitFromFenInPlace(&b, "8/4b3/8/8/8/8/8/8 b - - 0 1"); list = pmGetBishopMoves(&b, sqS("e7")); validateListSize(list, 9); validateUciIsInMovelist(list, "e7f8"); validateUciIsInMovelist(list, "e7f6"); validateUciIsInMovelist(list, "e7g5"); validateUciIsInMovelist(list, "e7h4"); validateUciIsInMovelist(list, "e7d6"); validateUciIsInMovelist(list, "e7c5"); validateUciIsInMovelist(list, "e7b4"); validateUciIsInMovelist(list, "e7a3"); validateUciIsInMovelist(list, "e7d8"); moveListFree(list); // Position with some blocks captures boardInitFromFenInPlace(&b, "8/8/5n2/8/1r6/2B5/3Q4/N7 w - - 0 1"); list = pmGetBishopMoves(&b, sqS("c3")); validateListSize(list, 5); validateUciIsInMovelist(list, "c3d4"); validateUciIsInMovelist(list, "c3e5"); validateUciIsInMovelist(list, "c3f6"); validateUciIsInMovelist(list, "c3b2"); validateUciIsInMovelist(list, "c3b4"); moveListFree(list); } void testRookMoves() { board b; moveList *list; // Lone rook boardInitFromFenInPlace(&b, "8/3R4/8/8/8/8/8/8 w - - 0 1"); list = pmGetRookMoves(&b, sqS("d7")); validateListSize(list, 14); validateUciIsInMovelist(list, "d7d8"); validateUciIsInMovelist(list, "d7e7"); validateUciIsInMovelist(list, "d7f7"); validateUciIsInMovelist(list, "d7g7"); validateUciIsInMovelist(list, "d7h7"); validateUciIsInMovelist(list, "d7d6"); validateUciIsInMovelist(list, "d7d5"); validateUciIsInMovelist(list, "d7d4"); validateUciIsInMovelist(list, "d7d3"); validateUciIsInMovelist(list, "d7d2"); validateUciIsInMovelist(list, "d7d1"); validateUciIsInMovelist(list, "d7c7"); validateUciIsInMovelist(list, "d7b7"); validateUciIsInMovelist(list, "d7a7"); moveListFree(list); // Rook with some stuff around boardInitFromFenInPlace(&b, "8/3R4/8/2k1r1BQ/8/8/3n1R2/4b3 b - - 0 1"); list = pmGetRookMoves(&b, sqS("e5")); validateListSize(list, 9); validateUciIsInMovelist(list, "e5e6"); validateUciIsInMovelist(list, "e5e7"); validateUciIsInMovelist(list, "e5e8"); validateUciIsInMovelist(list, "e5f5"); validateUciIsInMovelist(list, "e5g5"); validateUciIsInMovelist(list, "e5e4"); validateUciIsInMovelist(list, "e5e3"); validateUciIsInMovelist(list, "e5e2"); moveListFree(list); } void testQueenMoves() { board b; moveList *list; // Lone queen boardInitFromFenInPlace(&b, "8/8/8/8/8/8/1Q6/8 w - - 0 1"); list = pmGetQueenMoves(&b, sqS("b2")); validateListSize(list, 23); validateUciIsInMovelist(list, "b2b3"); validateUciIsInMovelist(list, "b2b4"); validateUciIsInMovelist(list, "b2b5"); validateUciIsInMovelist(list, "b2b6"); validateUciIsInMovelist(list, "b2b7"); validateUciIsInMovelist(list, "b2b8"); validateUciIsInMovelist(list, "b2c3"); validateUciIsInMovelist(list, "b2d4"); validateUciIsInMovelist(list, "b2e5"); validateUciIsInMovelist(list, "b2f6"); validateUciIsInMovelist(list, "b2g7"); validateUciIsInMovelist(list, "b2h8"); validateUciIsInMovelist(list, "b2c2"); validateUciIsInMovelist(list, "b2d2"); validateUciIsInMovelist(list, "b2e2"); validateUciIsInMovelist(list, "b2f2"); validateUciIsInMovelist(list, "b2g2"); validateUciIsInMovelist(list, "b2h2"); validateUciIsInMovelist(list, "b2c1"); validateUciIsInMovelist(list, "b2b1"); validateUciIsInMovelist(list, "b2a1"); validateUciIsInMovelist(list, "b2a2"); validateUciIsInMovelist(list, "b2a3"); moveListFree(list); // Queen with stuff around boardInitFromFenInPlace(&b, "8/1Q3N2/2br4/2Rq2P1/2Rr4/6p1/5P2/8 b - - 0 1"); list = pmGetQueenMoves(&b, sqS("d5")); validateListSize(list, 11); validateUciIsInMovelist(list, "d5e6"); validateUciIsInMovelist(list, "d5f7"); validateUciIsInMovelist(list, "d5e5"); validateUciIsInMovelist(list, "d5f5"); validateUciIsInMovelist(list, "d5g5"); validateUciIsInMovelist(list, "d5e4"); validateUciIsInMovelist(list, "d5f3"); validateUciIsInMovelist(list, "d5g2"); validateUciIsInMovelist(list, "d5h1"); validateUciIsInMovelist(list, "d5c4"); validateUciIsInMovelist(list, "d5c5"); moveListFree(list); } void testKingMoves() { // NOTE: pmGetKingMoves DOES NOT CONSIDER CHECK! // The king will be able to move into check since pmGetKingMoves() does not consider the legality of a move. board b; moveList *list; // Lone king boardInitFromFenInPlace(&b, "8/2k5/8/8/8/8/8/8 b - - 0 1"); list = pmGetKingMoves(&b, sqS("c7")); validateListSize(list, 8); validateUciIsInMovelist(list, "c7c8"); validateUciIsInMovelist(list, "c7d8"); validateUciIsInMovelist(list, "c7d7"); validateUciIsInMovelist(list, "c7d6"); validateUciIsInMovelist(list, "c7c6"); validateUciIsInMovelist(list, "c7b6"); validateUciIsInMovelist(list, "c7b7"); validateUciIsInMovelist(list, "c7b8"); moveListFree(list); // King in corner boardInitFromFenInPlace(&b, "8/8/8/8/8/8/8/K7 w - - 0 1"); list = pmGetKingMoves(&b, sqS("a1")); validateListSize(list, 3); validateUciIsInMovelist(list, "a1a2"); validateUciIsInMovelist(list, "a1b2"); validateUciIsInMovelist(list, "a1b1"); moveListFree(list); // King with stuff around boardInitFromFenInPlace(&b, "8/2B2R2/3nb3/3k4/2BRn3/8/3q4/8 b - - 0 1"); list = pmGetKingMoves(&b, sqS("d5")); validateListSize(list, 5); validateUciIsInMovelist(list, "d5e5"); validateUciIsInMovelist(list, "d5d4"); validateUciIsInMovelist(list, "d5c4"); validateUciIsInMovelist(list, "d5c5"); validateUciIsInMovelist(list, "d5c6"); moveListFree(list); } ///////////////////////////////////// // TEST ATTACKED SQUARES AND CHECK // ///////////////////////////////////// void testIsSquareAttacked() { board b; // Knight in corner and pawn boardInitFromFenInPlace(&b, "7N/8/8/8/8/8/1P6/8 w - - 0 1"); for (int i = 0; i < 64; i++) { sq s = sqIndex(i); uint8_t expectedAttacked = sqEq(s, sqS("a3")) || sqEq(s, sqS("c3")) || sqEq(s, sqS("f7")) || sqEq(s, sqS("g6")); uint8_t actualAttacked = boardIsSquareAttacked(&b, s, pcWhite); if (expectedAttacked != actualAttacked) { char message[50]; sprintf(message, "Actual %s attacked: %u, expected: %u", sqGetStr(s), actualAttacked, expectedAttacked); failTest(message); } } // Lone rook boardInitFromFenInPlace(&b, "8/8/8/3r4/8/8/8/8 b - - 0 1"); for (int i = 0; i < 64; i++) { sq s = sqIndex(i); uint8_t expectedAttacked = (s.file == 4) ^ (s.rank == 5); uint8_t actualAttacked = boardIsSquareAttacked(&b, s, pcBlack); if (expectedAttacked != actualAttacked) { char message[50]; sprintf(message, "Actual %s attacked: %u, expected: %u", sqGetStr(s), actualAttacked, expectedAttacked); failTest(message); } } // Rook with blocks/captures boardInitFromFenInPlace(&b, "8/8/8/8/1p6/8/8/1r1R4 w - - 0 1"); for (int i = 0; i < 64; i++) { sq s = sqIndex(i); uint8_t expectedAttacked = sqEq(s, sqS("a1")) || sqEq(s, sqS("c1")) || sqEq(s, sqS("d1")) || sqEq(s, sqS("b2")) || sqEq(s, sqS("b3")) || sqEq(s, sqS("a3")) || sqEq(s, sqS("c3")); uint8_t actualAttacked = boardIsSquareAttacked(&b, s, pcBlack); if (expectedAttacked != actualAttacked) { char message[50]; sprintf(message, "Actual %s attacked: %u, expected: %u", sqGetStr(s), actualAttacked, expectedAttacked); failTest(message); } } } void testIsInCheck() { board b; // Simple example - in check by a rook boardInitFromFenInPlace(&b, "8/8/1k6/1r2K3/8/8/8/8 w - - 0 1"); if (!boardIsInCheck(&b)) failTest("Board was not in check, expected board to be in check"); if (boardIsPlayerInCheck(&b, pcBlack)) failTest("Board was in check, expected board to be not in check"); // Scholar's mate boardInitFromFenInPlace(&b, "r1bqkb1r/pppp1Qpp/2n2n2/4p3/2B1P3/8/PPPP1PPP/RNB1K1NR b KQkq - 0 4"); if (!boardIsInCheck(&b)) failTest("Board was not in check, expected board to be in check"); if (boardIsPlayerInCheck(&b, pcWhite)) failTest("Board was in check, expected board to be not in check"); // Checks blocked by knights boardInitFromFenInPlace(&b, "7k/3q4/1q3q2/2NNN3/q1NKN1q1/2NNN3/1q3q2/3q4 w - - 0 1"); if (boardIsInCheck(&b)) failTest("Board was in check, expected board to be not in check"); if (boardIsPlayerInCheck(&b, pcBlack)) failTest("Board was in check, expected board to be not in check"); } //////////////////////// // TEST PLAYING MOVES // //////////////////////// // HELPER FUNCTION - validates that two boards are equal and fails the test if they are not // Do not make message "name" more than 65ish characters pls :) void validateBoardEq(const char *name, board *b1, board *b2) { if (!boardEq(b1, b2)) { char message[100]; sprintf(message, "%s boards were not exactly the same", name); failTest(message); } } void testBoardPlayMove() { board *b = boardCreate(); board *bCheck; // 1. e4 boardPlayMoveInPlace(b, moveSq(sqS("e2"), sqS("e4"))); bCheck = boardCreateFromFen("rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR b KQkq e3 0 1"); board *bCheckFuzzy = boardCreateFromFen("rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR b KQkq - 32 53"); validateBoardEq("1. e4", b, bCheck); // Manually check for fuzziness if (boardEq(b, bCheckFuzzy)) failTest("1. e4 boards were EXACTLY equal - they should have differed in EP target and move counts"); if (!boardEqContext(b, bCheckFuzzy)) failTest("1. e4 boards were not contextually the same, expected the same board"); free(bCheckFuzzy); // 1... Nf6 boardPlayMoveInPlace(b, moveSq(sqS("g8"), sqS("f6"))); boardInitFromFenInPlace(bCheck, "rnbqkb1r/pppppppp/5n2/8/4P3/8/PPPP1PPP/RNBQKBNR w KQkq - 1 2"); validateBoardEq("1... Nf6", b, bCheck); // Test capturing // Rook captures rook boardInitFromFenInPlace(b, "4k3/8/8/8/2R2r2/8/8/4K3 w - - 0 1"); boardPlayMoveInPlace(b, moveFromUci("c4f4")); boardInitFromFenInPlace(bCheck, "4k3/8/8/8/5R2/8/8/4K3 b - - 0 1"); validateBoardEq("Rook captures rook", b, bCheck); // Bishop captures pawn in opening boardInitFromFenInPlace(b, "rnbqkbnr/pppp1ppp/8/4p3/4P3/P7/1PPP1PPP/RNBQKBNR b KQkq - 0 2"); boardPlayMoveInPlace(b, moveFromUci("f8a3")); boardInitFromFenInPlace(bCheck, "rnbqk1nr/pppp1ppp/8/4p3/4P3/b7/1PPP1PPP/RNBQKBNR w KQkq - 0 3"); validateBoardEq("Bishop captures pawn", b, bCheck); // Really bad draw boardInitFromFenInPlace(b, "8/5k2/4q3/8/8/8/1K6/8 b - - 0 1"); boardPlayMoveInPlace(b, moveFromUci("e6b3")); boardInitFromFenInPlace(bCheck, "8/5k2/8/8/8/1q6/1K6/8 w - - 1 2"); validateBoardEq("Really bad draw move 1", b, bCheck); boardPlayMoveInPlace(b, moveFromUci("b2b3")); boardInitFromFenInPlace(bCheck, "8/5k2/8/8/8/1K6/8/8 b - - 0 2"); validateBoardEq("Really bad draw move 2", b, bCheck); // Check castling // White O-O boardInitFromFenInPlace(b, "rnbqk2r/pppp1ppp/5n2/2b1p3/2B1P3/5N2/PPPP1PPP/RNBQK2R w KQkq - 4 4"); boardPlayMoveInPlace(b, moveFromUci("e1g1")); boardInitFromFenInPlace(bCheck, "rnbqk2r/pppp1ppp/5n2/2b1p3/2B1P3/5N2/PPPP1PPP/RNBQ1RK1 b kq - 5 4"); validateBoardEq("White O-O", b, bCheck); // Black O-O boardPlayMoveInPlace(b, moveFromUci("e8g8")); boardInitFromFenInPlace(bCheck, "rnbq1rk1/pppp1ppp/5n2/2b1p3/2B1P3/5N2/PPPP1PPP/RNBQ1RK1 w - - 6 5"); validateBoardEq("Black O-O", b, bCheck); // White O-O-O boardInitFromFenInPlace(b, "r3kbnr/ppp1pppp/2nq4/3p1b2/3P1B2/2NQ4/PPP1PPPP/R3KBNR w KQkq - 6 5"); boardPlayMoveInPlace(b, moveFromUci("e1c1")); boardInitFromFenInPlace(bCheck, "r3kbnr/ppp1pppp/2nq4/3p1b2/3P1B2/2NQ4/PPP1PPPP/2KR1BNR b kq - 7 5"); validateBoardEq("White O-O-O", b, bCheck); // Black O-O-O boardPlayMoveInPlace(b, moveFromUci("e8c8")); boardInitFromFenInPlace(bCheck, "2kr1bnr/ppp1pppp/2nq4/3p1b2/3P1B2/2NQ4/PPP1PPPP/2KR1BNR w - - 8 6"); validateBoardEq("Black O-O-O", b, bCheck); // Test En Passant // White EP - black moves boardInitFromFenInPlace(b, "rnbqkbnr/ppppppp1/7p/4P3/8/8/PPPP1PPP/RNBQKBNR b KQkq - 0 2"); boardPlayMoveInPlace(b, moveFromUci("f7f5")); boardInitFromFenInPlace(bCheck, "rnbqkbnr/ppppp1p1/7p/4Pp2/8/8/PPPP1PPP/RNBQKBNR w KQkq f6 0 3"); validateBoardEq("White EP - black moves", b, bCheck); // White EP - capture boardPlayMoveInPlace(b, moveFromUci("e5f6")); boardInitFromFenInPlace(bCheck, "rnbqkbnr/ppppp1p1/5P1p/8/8/8/PPPP1PPP/RNBQKBNR b KQkq - 0 3"); validateBoardEq("White EP - capture", b, bCheck); // Black EP - black moves boardInitFromFenInPlace(b, "rnbqkbnr/pppp1ppp/8/8/4p2P/8/PPPPPPP1/RNBQKBNR w KQkq - 0 3"); boardPlayMoveInPlace(b, moveFromUci("d2d4")); boardInitFromFenInPlace(bCheck, "rnbqkbnr/pppp1ppp/8/8/3Pp2P/8/PPP1PPP1/RNBQKBNR b KQkq d3 0 3"); validateBoardEq("Black EP - white moves", b, bCheck); // Black EP - capture boardPlayMoveInPlace(b, moveFromUci("e4d3")); boardInitFromFenInPlace(bCheck, "rnbqkbnr/pppp1ppp/8/8/7P/3p4/PPP1PPP1/RNBQKBNR w KQkq - 0 4"); validateBoardEq("Black EP - capture", b, bCheck); // Free boards free(b); free(bCheck); } //////////////////////////////// // TEST BOARD MOVE GENERATION // //////////////////////////////// // Helper function - asserts that given UCI string does NOT in moveList. For castling tests void validateUciIsNotInMovelist(moveList *list, char *expectedUci) { for (moveListNode *n = list->head; n; n = n->next) { char *actualUci = moveGetUci(n->move); int cmp = strcmp(actualUci, expectedUci); free(actualUci); if (cmp == 0) { char message[60]; sprintf(message, "Expected %s to be absent but was in movelist", expectedUci); failTest(message); return; } } // All good, was not hit } void testBoardGenerateMoves() { board b; moveList *list; // Test all 20 moves on initial board boardInitInPlace(&b); list = boardGenerateMoves(&b); validateListSize(list, 20); // Pawn moves validateUciIsInMovelist(list, "a2a3"); validateUciIsInMovelist(list, "a2a4"); validateUciIsInMovelist(list, "b2b3"); validateUciIsInMovelist(list, "b2b4"); validateUciIsInMovelist(list, "c2c3"); validateUciIsInMovelist(list, "c2c4"); validateUciIsInMovelist(list, "d2d3"); validateUciIsInMovelist(list, "d2d4"); validateUciIsInMovelist(list, "e2e3"); validateUciIsInMovelist(list, "e2e4"); validateUciIsInMovelist(list, "f2f3"); validateUciIsInMovelist(list, "f2f4"); validateUciIsInMovelist(list, "g2g3"); validateUciIsInMovelist(list, "g2g4"); validateUciIsInMovelist(list, "h2h3"); validateUciIsInMovelist(list, "h2h4"); // Knight moves validateUciIsInMovelist(list, "b1a3"); validateUciIsInMovelist(list, "b1c3"); validateUciIsInMovelist(list, "g1f3"); validateUciIsInMovelist(list, "g1h3"); moveListFree(list); // Board with some moves played boardInitFromFenInPlace(&b, "r1bqkbnr/ppp2ppp/2np4/4p3/2B1P3/3P4/PPP2PPP/RNBQK1NR w KQkq - 1 4"); list = boardGenerateMoves(&b); validateListSize(list, 12 + 5 + 11 + 6 + 3); // Pawn moves, 12 validateUciIsInMovelist(list, "a2a3"); validateUciIsInMovelist(list, "a2a4"); validateUciIsInMovelist(list, "b2b3"); validateUciIsInMovelist(list, "b2b4"); validateUciIsInMovelist(list, "c2c3"); validateUciIsInMovelist(list, "d3d4"); validateUciIsInMovelist(list, "f2f3"); validateUciIsInMovelist(list, "f2f4"); validateUciIsInMovelist(list, "g2g3"); validateUciIsInMovelist(list, "g2g4"); validateUciIsInMovelist(list, "h2h3"); validateUciIsInMovelist(list, "h2h4"); // Knight moves, 6 validateUciIsInMovelist(list, "b1a3"); validateUciIsInMovelist(list, "b1c3"); validateUciIsInMovelist(list, "b1d2"); validateUciIsInMovelist(list, "g1e2"); validateUciIsInMovelist(list, "g1f3"); validateUciIsInMovelist(list, "g1h3"); // Bishop moves, 11 // (Light square) validateUciIsInMovelist(list, "c4b5"); validateUciIsInMovelist(list, "c4a6"); validateUciIsInMovelist(list, "c4b3"); validateUciIsInMovelist(list, "c4d5"); validateUciIsInMovelist(list, "c4e6"); validateUciIsInMovelist(list, "c4f7"); // (Dark square) validateUciIsInMovelist(list, "c1d2"); validateUciIsInMovelist(list, "c1e3"); validateUciIsInMovelist(list, "c1f4"); validateUciIsInMovelist(list, "c1g5"); validateUciIsInMovelist(list, "c1h6"); // Queen moves, 5 validateUciIsInMovelist(list, "d1d2"); validateUciIsInMovelist(list, "d1e2"); validateUciIsInMovelist(list, "d1f3"); validateUciIsInMovelist(list, "d1g4"); validateUciIsInMovelist(list, "d1h5"); // King moves, 3 validateUciIsInMovelist(list, "e1d2"); validateUciIsInMovelist(list, "e1e2"); validateUciIsInMovelist(list, "e1f1"); moveListFree(list); // Less pieces on the board boardInitFromFenInPlace(&b, "8/1k4n1/4n3/8/5P2/6R1/3Q1K2/8 b - - 0 1"); list = boardGenerateMoves(&b); validateListSize(list, 7 + 3 + 8); // Knight e6 moves, 7 validateUciIsInMovelist(list, "e6f8"); validateUciIsInMovelist(list, "e6g5"); validateUciIsInMovelist(list, "e6f4"); validateUciIsInMovelist(list, "e6d4"); validateUciIsInMovelist(list, "e6c5"); validateUciIsInMovelist(list, "e6c7"); validateUciIsInMovelist(list, "e6d8"); // Knight g7 moves, 3 validateUciIsInMovelist(list, "g7h5"); validateUciIsInMovelist(list, "g7f5"); validateUciIsInMovelist(list, "g7e8"); // King moves, 8 validateUciIsInMovelist(list, "b7b8"); validateUciIsInMovelist(list, "b7c8"); validateUciIsInMovelist(list, "b7c7"); validateUciIsInMovelist(list, "b7c6"); validateUciIsInMovelist(list, "b7b6"); validateUciIsInMovelist(list, "b7a6"); validateUciIsInMovelist(list, "b7a7"); validateUciIsInMovelist(list, "b7a8"); moveListFree(list); // Test a pinned knight - it can't move boardInitFromFenInPlace(&b, "8/8/8/6k1/1K1N2q1/8/8/8 w - - 0 1"); list = boardGenerateMoves(&b); // should ONLY have king moves validateListSize(list, 8); validateUciIsInMovelist(list, "b4c4"); validateUciIsNotInMovelist(list, "d4e6"); moveListFree(list); // King is in check, but it can be blocked boardInitFromFenInPlace(&b, "3b3k/8/8/8/8/2Q5/4K3/8 b - - 0 1"); list = boardGenerateMoves(&b); validateListSize(list, 3); // Bishop can move to block the check... validateUciIsInMovelist(list, "d8f6"); // ...but it CANNOT make any other move validateUciIsNotInMovelist(list, "d8e7"); validateUciIsNotInMovelist(list, "d8g5"); validateUciIsNotInMovelist(list, "d8h4"); moveListFree(list); } void testBoardGenerateMovesCastling() { board b; moveList *list; // White O-O boardInitFromFenInPlace(&b, "rnbqk2r/pppp1ppp/3b1n2/4p3/4P3/3B1N2/PPPP1PPP/RNBQK2R w KQkq - 4 4"); list = boardGenerateMoves(&b); validateUciIsInMovelist(list, "e1g1"); moveListFree(list); // If we remove the castling flag? b.castleState = b.castleState & (~CASTLE_WK); list = boardGenerateMoves(&b); validateUciIsNotInMovelist(list, "e1g1"); moveListFree(list); // Black O-O b.currentPlayer = pcBlack; list = boardGenerateMoves(&b); validateUciIsInMovelist(list, "e8g8"); moveListFree(list); // White O-O-O boardInitFromFenInPlace(&b, "r3kbnr/ppp1pppp/2nqb3/3p4/3P4/2NQB3/PPP1PPPP/R3KBNR w KQkq - 6 5"); list = boardGenerateMoves(&b); validateUciIsInMovelist(list, "e1c1"); moveListFree(list); // Black O-O-O b.currentPlayer = pcBlack; list = boardGenerateMoves(&b); validateUciIsInMovelist(list, "e8c8"); moveListFree(list); // King is in check - no castling boardInitFromFenInPlace(&b, "4k3/8/4r3/8/8/8/8/R3K2R w KQ - 0 1"); list = boardGenerateMoves(&b); validateUciIsNotInMovelist(list, "e1g1"); validateUciIsNotInMovelist(list, "e1c1"); moveListFree(list); // Rook is checking the f1 square - no O-O but yes O-O-O boardInitFromFenInPlace(&b, "4k3/8/5r2/8/8/8/8/R3K2R w KQ - 0 1"); list = boardGenerateMoves(&b); validateUciIsNotInMovelist(list, "e1g1"); validateUciIsInMovelist(list, "e1c1"); moveListFree(list); // Rook is checking the g1 square - no O-O but yes O-O-O boardInitFromFenInPlace(&b, "4k3/8/6r1/8/8/8/8/R3K2R w KQ - 0 1"); list = boardGenerateMoves(&b); validateUciIsNotInMovelist(list, "e1g1"); validateUciIsInMovelist(list, "e1c1"); moveListFree(list); // Rook is attacking the h rook - both castlings allowed boardInitFromFenInPlace(&b, "4k3/8/7r/8/8/8/8/R3K2R w KQ - 0 1"); list = boardGenerateMoves(&b); validateUciIsInMovelist(list, "e1g1"); validateUciIsInMovelist(list, "e1c1"); moveListFree(list); // Rook is checking d8, no O-O-O boardInitFromFenInPlace(&b, "r3k2r/8/8/8/8/3R4/8/4K3 b kq - 0 1"); list = boardGenerateMoves(&b); validateUciIsInMovelist(list, "e8g8"); validateUciIsNotInMovelist(list, "e8c8"); moveListFree(list); // Rook is checking c8, no O-O-O boardInitFromFenInPlace(&b, "r3k2r/8/8/8/8/2R5/8/4K3 b kq - 0 1"); list = boardGenerateMoves(&b); validateUciIsInMovelist(list, "e8g8"); validateUciIsNotInMovelist(list, "e8c8"); moveListFree(list); // Rook is checking b8, both castlings allowed boardInitFromFenInPlace(&b, "r3k2r/8/8/8/8/1R6/8/4K3 b kq - 0 1"); list = boardGenerateMoves(&b); validateUciIsInMovelist(list, "e8g8"); validateUciIsInMovelist(list, "e8c8"); moveListFree(list); // Rook is attacking a rook, both castlings allowed boardInitFromFenInPlace(&b, "r3k2r/8/8/8/8/R7/8/4K3 b kq - 0 1"); list = boardGenerateMoves(&b); validateUciIsInMovelist(list, "e8g8"); validateUciIsInMovelist(list, "e8c8"); moveListFree(list); // Subtle case - PINNED piece is checking d1, but O-O-O still NOT allowed!! boardInitFromFenInPlace(&b, "8/8/8/8/1k6/2n5/3B4/R3K3 w Q - 0 1"); list = boardGenerateMoves(&b); validateUciIsNotInMovelist(list, "e8c8"); moveListFree(list); } ///////////////////////// // TEST FEN GENERATION // ///////////////////////// // HELPER - takes in a FEN string, creates board, validates output void validateBoardFen(char *fen) { board b; boardInitFromFenInPlace(&b, fen); char *actualFen = boardGetFen(&b); validateString(actualFen, fen); free(actualFen); } void testBoardGetFen() { validateBoardFen(INITIAL_FEN); validateBoardFen("rnb1kbnr/pppp1ppp/8/4p3/6Pq/5P2/PPPPP2P/RNBQKBNR w KQkq - 1 3"); // Fool's mate validateBoardFen("r1bqkb1r/pppp1Qpp/2n2n2/4p3/2B1P3/8/PPPP1PPP/RNB1K1NR b KQkq - 0 4"); // Scholar's mate validateBoardFen("r3r1k1/pp3pbp/1qp1b1p1/2B5/2BP4/Q1n2N2/P4PPP/3R1K1R w - - 4 18"); // GotC Be6!! validateBoardFen("r1q1k2r/8/8/8/3P4/8/8/R3K2R b Kq d3 0 1"); // Misc setup, varying castling states, EP } //////////////////////////////////////// // TEST DRAW BY INSUFFICIENT MATERIAL // //////////////////////////////////////// void validateBoardIsInsufficientMaterial(board *b, uint8_t expected) { uint8_t actual = boardIsInsufficientMaterial(b); if (actual != expected) { char message[100]; sprintf(message, "Board %s draw by insufficient material, expected board %s", actual ? "is" : "is not", expected ? "is" : "is not"); failTest(message); } } void testBoardIsInsufficientMaterial() { board b; // Initial board boardInitInPlace(&b); validateBoardIsInsufficientMaterial(&b, 0); // Bare kings, true boardInitFromFenInPlace(&b, "8/4k3/8/8/2K5/8/8/8 w - - 0 1"); validateBoardIsInsufficientMaterial(&b, 1); // K vs K+N, true boardInitFromFenInPlace(&b, "8/4k3/8/8/2K5/8/8/N7 w - - 0 1"); validateBoardIsInsufficientMaterial(&b, 1); // K vs K+N+N, false boardInitFromFenInPlace(&b, "8/4k1n1/8/7n/2K5/8/8/8 w - - 0 1"); validateBoardIsInsufficientMaterial(&b, 0); // K+B vs K+B, different colors, false boardInitFromFenInPlace(&b, "8/4kb2/8/8/2K5/6B1/8/8 w - - 0 1"); validateBoardIsInsufficientMaterial(&b, 0); // K+B vs K+B, same colors, true boardInitFromFenInPlace(&b, "8/4k1b1/8/8/2K5/6B1/8/8 w - - 0 1"); validateBoardIsInsufficientMaterial(&b, 1); // K+B+B+B+B vs K+B+B+B, all same colors, true boardInitFromFenInPlace(&b, "3b4/4k1b1/5b2/8/1BK5/6B1/3B1B2/8 w - - 0 1"); validateBoardIsInsufficientMaterial(&b, 1); } ///////////////////// // TEST BOARD LIST // ///////////////////// void testBoardList() { board *b1 = boardCreate(); board *b2 = boardPlayMove(b1, moveFromUci("e2e4")); board *b3 = boardPlayMove(b1, moveFromUci("c7c5")); boardList *l = boardListCreate(); boardListAdd(l, b1); boardListAdd(l, b2); boardListAdd(l, b3); if (boardListGet(l, 0) != b1) failTest("boardListGet(l, 0) didn't return b1"); if (boardListGet(l, 1) != b2) failTest("boardListGet(l, 1) didn't return b2"); if (boardListGet(l, 2) != b3) failTest("boardListGet(l, 2) didn't return b3"); // This also frees all boards boardListFree(l); } ///////////////////// // TEST SQUARE SET // ///////////////////// void testSqSetSet() { uint64_t ss = 0; sqSetSet(&ss, sqS("e4"), 1); if (ss != (uint64_t) 0x0000000010000000) failTest("Setting e4 didn't work"); sqSetSet(&ss, sqS("d5"), 1); if (ss != (uint64_t) 0x0000000810000000) failTest("Setting d5 didn't work"); sqSetSet(&ss, sqS("a1"), 1); if (ss != (uint64_t) 0x0000000810000001) failTest("Setting a1 didn't work"); sqSetSet(&ss, sqS("h8"), 1); if (ss != (uint64_t) 0x8000000810000001) failTest("Setting h8 didn't work"); } void testSqSetGet() { // The diagonal from a1 to h8 uint64_t ss = 0x8040201008040201; for (int i = 0; i < 64; i++) { sq s = sqIndex(i); uint8_t expected = (s.file == s.rank); uint8_t actual = sqSetGet(&ss, s); if (expected != actual) { char message[100]; sprintf("Square %s was %d in the set, expected %d", sqGetStr(s), actual, expected); failTest(message); } } // Entire c file, f file, 3 rank, and 6 rank ss = 0x2424FF2424FF2424; for (int i = 0; i < 64; i++) { sq s = sqIndex(i); uint8_t expected = (s.file == 3 || s.rank == 3 || s.file == 6 || s.rank == 6); uint8_t actual = sqSetGet(&ss, s); if (expected != actual) { char message[100]; sprintf("Square %s was %d in the set, expected %d", sqGetStr(s), actual, expected); failTest(message); } } }
C
UTF-8
11,416
3.703125
4
[]
no_license
// // S3_List.c // Basic Review // // Created by 徐伟达 on 2017/12/26. // Copyright © 2017年 徐伟达. All rights reserved. // #include "S3_List.h" //--------------------------------------------------------------------- // 3.6 单向链表 p40 //--------------------------------------------------------------------- //------------------------------------------------ // 链表的型声明 //------------------------------------------------ //typedef struct listNode { // int data; // struct listNode *next; //} ListNode; //------------------------------------------------ // 函数声明 //------------------------------------------------ void listTester(void); int listLength(struct listNode *head); void insertInLinkedList(struct listNode **head, int data, int position); void deleteNodeFromLinkedList(struct listNode **head, int position); void deleteLinkedList(struct listNode **head); //------------------------------------------------ // 基本运算 // 遍历, 插入元素, 删除元素 //------------------------------------------------ //------------------------ // 遍历 p40 // 获取长度 O(n) //------------------------ int listLength(struct listNode *head) { struct listNode *current = head; int count = 0; while (current->next != NULL) { // 问题: 第一个可能是NULL所以这种有问题 // TODO-PRO: weida fix here [上一行指出的问题] count++; current = current->next; } return ++count; // SHOW: SAMPLE [书上版本] // while (current != NULL) { // count++; // current = current->next; // } // return ++count; } //------------------------ // 插入: 开头, 末尾, 中间p41 //------------------------ // TODO-PRO: add [分别实现开头,末尾,中间三种 p43] void insertInLinkedList(struct listNode **head, int data, int position) { // SHOW: SAMPLE [书上版本] int k = 1; struct listNode *p, *q, *newNode; newNode = (struct listNode *)malloc(sizeof(struct listNode)); if (!newNode) { printf("MemoryError\n"); return; } newNode->data = data; p = *head; // 直接改变head会使得外部的参数也变化,所以建一个指针来操作 //插在开头 if (position == 1) { newNode->next = p; *head = newNode; } else { q = NULL; position = abs(position); while ((k < position) && (p != NULL)) { q = p; // 保存当前的节点 例:插到第五个的话,要在第四个操作 p = p->next; k++; } q->next = newNode; newNode->next = p; } } //------------------------ // 删除: 开头, 末尾, 中间p44 // 全部删除 p46 //------------------------ void deleteNodeFromLinkedList(struct listNode **head, int position) { // SHOW: SAMPLE [书上版本] int k = 1; struct listNode *p, *q; if (!head) { printf("List Empty\n"); return; } p = *head; if (position == 1) { // 删除开头节点 *head = (*head)->next; free(p); }else { q = NULL; // 初始化 while ((k < position) && (p != NULL)) { k++; q = p; p = p->next; } if (!p) { printf("Position does not exist.\n"); }else { q->next = p->next; free(p); } } } void deleteLinkedList(struct listNode **head) { // 全删除 // SHOW: SAMPLE [书上版本] // SHOW: SELF struct listNode *p, *q; p = *head; while (p) { q = p; p = p->next; free(q); } *head = NULL;// free()释放内存,不改变指针指向的地址 } //--------------------------------------------------------------------- // 3.7 双向链表 p47 //--------------------------------------------------------------------- //------------------------------------------------ // 链表的型声明 //------------------------------------------------ //struct dllNode { // int data; // struct dllNode *next; // struct dllNode *prev; //}; //------------------------------------------------ // 函数声明 //------------------------------------------------ void dllInsert(struct dllNode **head, int data, int position); void dllDelete(struct dllNode **head, int position); //------------------------------------------------ // 基本运算 // 遍历, 插入元素, 删除元素 //------------------------------------------------ // TODO-PRO: add [双向链表的遍历, 书上省略了] //------------------------ // 插入: 开头, 末尾, 中间p49 //------------------------ void dllInsert(struct dllNode **head, int data, int position) { // SHOW: SELF int k = 1; struct dllNode *p, *q, *newNode; newNode = (struct dllNode *)malloc(sizeof(struct dllNode)); if (!head || !(*head)) { printf("Head is NULL\n"); } if (!newNode) { printf("Memory Error\n"); return; } newNode->data = data; p = *head; if (position == 1) { newNode->prev = NULL; newNode->next = *head; (*head)->prev = newNode; *head = newNode; return; } else { q = NULL; while ((k < position) && p != NULL) { // 第一个条件为真才判断第二个,所以如果p为NULL则一定是指定位置超出长度 q = p; p = p->next; k++; } if (k < position) { // 跳出仅因为第二个条件 printf("指定的位置超过了当前链表长度\n"); return; } else { if (p != NULL) { // 中间的插入 newNode->next = p; newNode->prev = q; p->prev = newNode; q->next = newNode; } else { // 末尾 newNode->next = NULL; newNode->prev = q; q->next = newNode; } } } } //------------------------ // 删除: 开头, 末尾, 中间p //------------------------ void dllDelete(struct dllNode **head, int position) { // SHOW: SELF int k = 1; struct dllNode *p, *q; p = *head; if (position == 1) { (*head) = (*head)->next; if ((*head) != NULL) { (*head)->prev = NULL; } free(p); return; } else { q = NULL; while ((k < position) && p != NULL) { q = p; p = p->next; k++; } if (k < position) { printf("指定的位置超过了当前链表长度\n"); return; } else { if (p == NULL) { q->next = NULL; free(p); } else { q->next = p->next; (q->next)->prev = q; free(p); } } } } //--------------------------------------------------------------------- // 3.8 循环链表 p53 //--------------------------------------------------------------------- //------------------------------------------------ // 链表的型声明 //------------------------------------------------ //struct cllNode { // circular list // int data; // struct cllNode *next; //}; //------------------------------------------------ // 函数声明 //------------------------------------------------ int circularListLength(struct cllNode *head); void printCircularListData(struct cllNode *head); void insertAtEndInCll(struct cllNode *head, int data); void insertAtEndInCll_v2(struct cllNode **head, int data); void insertAtBeginInCll(struct cllNode **head, int data); void deleteLastNodeFromCll(struct cllNode **head); void deleteFrontNodeFromCll(struct cllNode **head); //------------------------------------------------ // 基本运算 // 遍历, 插入元素, 删除元素 //------------------------------------------------ //------------------------ // 遍历, 打印 p55 //------------------------ int circularListLength(struct cllNode *head) { // SHOW: SELF struct cllNode *current = head; int count = 0; if (!head) { return 0; } do { current = current->next; count++; } while (current != head); return count; } void printCircularListData(struct cllNode *head) { // SHOW: SELF struct cllNode *current = head; int count = 0; if (!head) { puts("NULL"); return; } do { printf("data[%d]: %d\n", count, current->data); current = current->next; count++; } while (current != head); } //------------------------ // 插入: 开头, 末尾 p55 //------------------------ //末尾 void insertAtEndInCll(struct cllNode *head, int data) { // SHOW: SELF [不用**head,用*head来尝试实现, 调整书上的循环执行位置] struct cllNode *current = head; struct cllNode *newNode = (struct cllNode*)(malloc(sizeof(struct cllNode))); if (!newNode) { puts("Memory Error\n"); } newNode->data = data; newNode->next = NULL; if (!head) { head = newNode; } else { do { current = current->next; } while (current != head); current->next = newNode; newNode->next = head; } } void insertAtEndInCll_v2(struct cllNode **head, int data) { // 还是末尾 // SHOW: SELF [用**head] struct cllNode *newNode, *current = *head, *preCurrent = *head; newNode = (struct cllNode*)malloc(sizeof(struct cllNode)); if (!newNode) { puts("Memory Error\n"); return; } newNode->data = data; newNode->next = NULL; if (!(*head) || !head) { head = &newNode; // TODO-PRO: problem [head = &newNode和 *head = newNode有什么区别] return; } do { preCurrent = current; current = current->next; } while (current != *head); newNode->next = *head; preCurrent->next = newNode; } //开头 void insertAtBeginInCll(struct cllNode **head, int data) { // SHOW: SELF struct cllNode *current = NULL, *newNode; newNode = (struct cllNode*)malloc(sizeof(struct cllNode)); if (!newNode) { puts("Memory Error\n"); return; } newNode->data = data; if (!head || !(*head)) { head = &newNode; newNode->next = newNode; return; } current = *head; while (current->next != *head) { current = current->next; } current->next = newNode; newNode->next = *head; } //------------------------ // 删除: 开头, 末尾 p57 //------------------------ void deleteLastNodeFromCll(struct cllNode **head) { // 末尾 // SHOW: SELF struct cllNode *current = *head, *preCurrent = *head; if (!head || !(*head)) { puts("List Empty\n"); return; } while (current->next != *head) { preCurrent = current; current = current->next; } preCurrent->next = *head; free(current); } void deleteFrontNodeFromCll(struct cllNode **head) { // 开头 // SHOW: SELF struct cllNode *current = *head, *temp = *head; if (!head || !(*head)) { puts("List Empty\n"); return; } while (current->next != *head) { current = current->next; } current->next = temp->next; free(temp); *head = current->next; } //--------------------------------------------------------------------- // 测试函数 //--------------------------------------------------------------------- void listTester(void) { printf("hello\n");// TODO-PRO: 删除这行 // struct listNode sample; // sample.data = 1; // sample.next = NULL; // printf("%d\n", listLength(&sample)); int *a, b = 1; a = &b; printf("*a: %d\na: %p\n&a: %p\n", *a, a, &a); }
C
UTF-8
2,631
2.671875
3
[]
no_license
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* input.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: pdespres <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/11/14 21:33:44 by pdespres #+# #+# */ /* Updated: 2017/11/21 18:52:03 by pdespres ### ########.fr */ /* */ /* ************************************************************************** */ #include "fillit.h" int check_links(char **str, int i) { int j; int links; int x; j = 0; links = 0; while (j++ != 4) { x = 0; while (++x <= 4) { if (str[i][j] - str[i][x] == 1) links += (x == 4 ? 2 : 1); if (str[i][j] - str[i][x] == -1) links += (x == 4 ? 2 : 1); if (str[i][j] - str[i][x] == 5) links += (x == 4 ? 22 : 1); if (str[i][j] - str[i][x] == -5) links += (x == 4 ? 2 : 1); } if (links >= 6) return (1); } return (0); } char **ft_alloc(char *str_base, int *piece_number) { int i; char **str; i = 0; while (str_base[i]) i++; *piece_number = i / 20 - (i / 20) / 20; i = 0; if (!(str = (char**)malloc(sizeof(*str) * (*piece_number + 2)))) return (0); while (*piece_number + 1 != i) if (!(str[i++] = (char*)malloc(sizeof(**str) * 5))) return (0); str[i] = 0; return (str); } void ft_refresh(int *refresh, int *first_place) { if (*refresh < 5) *first_place = 0; else if (*refresh >= 5 && *refresh <= 9) *first_place = 5; else if (*refresh >= 10 && *refresh <= 14) *first_place = 10; else if (*refresh >= 15 && *refresh <= 19) *first_place = 15; } char **check_tetri(char *str, int i, int j) { char **str_places; int piece_number; int first_place; int refresh; int x; x = -1; i = 1; str_places = ft_alloc(str, &piece_number); while (str[++x]) { ft_init(&j, &refresh); ft_find_hash(str, &x, &refresh); ft_refresh(&refresh, &first_place); str_places[i][j] = refresh - first_place; j++; while (refresh++ != 20 && str[x++]) if (str[x] == '#') str_places[i][j++] = refresh - first_place; ft_error(check_links(str_places, i) == 0); i++; if (x > (((piece_number) * 21) - 20)) break ; } return (str_places); }
C
UTF-8
1,928
2.734375
3
[ "MIT" ]
permissive
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* f_free_precision.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: aulopez <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/01/21 12:06:25 by aulopez #+# #+# */ /* Updated: 2019/01/21 12:06:27 by aulopez ### ########.fr */ /* */ /* ************************************************************************** */ #include "ft_printf.h" #include "ft_bigint.h" char *free_and_return_char(int *a, char *str) { if (a) free(a); return (str); } int free_and_return_int(int *a, int b) { if (a) free(a); return (b); } void finalize_precision(char **str, size_t j) { char *tmp; (*str)[j] = 0; if ((*str)[0] == '-' + 1 || (*str)[0] == '9' + 1) { if ((*str)[0] == '-' + 1) tmp = ft_strjoin("-1", (*str) + 1); else tmp = ft_strjoin("10", (*str) + 1); free(*str); if (!tmp) return ; *str = tmp; } } void handle_precision(char **str, size_t precision, uint32_t flags) { size_t i; size_t j; size_t b; size_t len; len = ft_strlen(*str); b = ft_strchri(*str, '.'); i = precision + b; if (i <= len) { j = i; (*str)[i] += 5; while (i > 0 && (*str)[i] > '9') { (*str)[i] -= 10; if ((*str)[i - 1] == '.' || (*str)[i - 1] == ',') i--; (*str)[--i] += 1; } finalize_precision(str, j); } if (precision == 0 && !(flags & F_SHARP)) (*str)[b - 1] = 0; else if (precision == 0) (*str)[b] = 0; }
C
UTF-8
485
3
3
[]
no_license
#include<stdio.h> #include<unistd.h> int brk(void *); void* sbrk(int); int isPrime(int a){ int i; for(i=2;i<a;i++) if(a%i==0) return -1; return 0; } int main(){ int i; int *r; int *p; p=(int *)sbrk(0); r=p; for(i=2;i<1000;i++) if(!isPrime(i)){ brk(r+1); *r=i; r=(int *)sbrk(0); } r=p; i=0; while(r!=(int *)sbrk(0)){ printf("%d\n",*r); r++; } }
C
UTF-8
2,654
3.53125
4
[]
no_license
#include <stdio.h> #include <getopt.h> #include <limits.h> #include <stdbool.h> #include <time.h> #include "linked_list.h" #define FLAG_FILE 1 int main(int argc, char *argv[]) { // Checking flags section int flags = 0, opt = 0; char* file = NULL; while ((opt = getopt(argc, argv, "f:")) != -1) { switch (opt) { case 'f': flags |= FLAG_FILE; file = optarg; break; default: fprintf(stderr, "Usage: %s [-f]\n", argv[0]); exit(EXIT_FAILURE); } } // List init section element* list = NULL; if (flags & FLAG_FILE) { load(&list, file); printf("Succesfully loaded from %s\n", file); } else from_stdin(&list); // Display list summary section printf("\nList info:\n"); printf("list_length = %d\n", list_length(list)); printf("list_sum = %d\n", list_sum(list)); printf("contents: "); print_list(list); printf("\n"); // Testing features section printf("list_add_back 19\n"); list_add_back(19, &list); print_list(list); printf("\nlist_add_front 29\n"); list_add_front(29, &list); print_list(list); printf("\nlist_length = %d\n", list_length(list)); printf("\nlist_get\n"); printf("list[0] = %d\n", list_get(0, list)); printf("list[4] = %d\n", list_get(4, list)); printf("\nTesting High-Order Functions\n"); printf("\nLets print our list elements with foreach (newlines)\n"); foreach(list, *print_with_newline); printf("\nLets print our list elements with foreach (spaces)\n"); foreach(list, *print_with_space); printf("\n\nLets square every element using map\n"); foreach(map(list, *square), *print_with_space); printf("\n\nLets cube every element using map\n"); foreach(map(list, *cube), *print_with_space); printf("\n\nLets get the sum of list using foldl\n"); printf("sum = %d\n", foldl(list, 0, *sum)); printf("\nLets find min and max element using foldl\n"); printf("min = %d", foldl(list, INT_MAX, *min)); printf("\nmax = %d", foldl(list, INT_MIN, *max)); printf("\n\nLets abs every element using map_mut\n"); map_mut(list, *abs); foreach(list, *print_with_space); printf("\n\nThe list of the first 10 powers of two using iterate\n"); foreach(iterate(1, 10, *mul_by_two), *print_with_space); printf("\nLets save our list to the output.txt\n"); save(list, "output.txt"); printf("\nLets serialize our list to serialized.txt\n"); serialize(list, "serialized.txt"); printf("\nLets deserialize our list\n"); list_free(&list); deserialize(&list, "serialized.txt"); foreach(list, *print_with_space); printf("\nClear list...\n"); list_free(&list); print_list(list); return 0; }
C
UTF-8
582
2.9375
3
[]
no_license
#include <stdio.h> #include <stdlib.h> #include <string.h> #define ROWS 3 #define COLUMNS 3 int displayGameNew( char boardNew[3][3] ) { system( "clear" ); int i = 0; int j = 0; for( i = 0; i < ROWS; ++i ) { for( j = 0; j < COLUMNS; ++j ) { printf( " %c ", boardNew[i][j] ); if( j < 2 ) { printf( "|" ); } } printf( "\n" ); if( i < 2 ) { printf( "-----------" ); printf( "\n" ); } } return 0; }
C
UTF-8
2,644
3.296875
3
[]
no_license
#include <pthread.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <linux/sched.h> char* buffer = NULL; int bufferIndex = 0; int bufferSize = 0; int nThreads = 0; int running = 0; pthread_mutex_t mutex; void *run(void *data) { /*Garante que todas as threads comecem ao mesmo tempo*/ running ++; while(running < nThreads){} intptr_t id = (intptr_t) data; while(bufferIndex < bufferSize) { pthread_mutex_lock(&mutex); buffer[bufferIndex] = 'A' + id; bufferIndex ++; pthread_mutex_unlock(&mutex); } return 0; } void print_sched(int policy) { int priority_min, priority_max; switch(policy){ case SCHED_DEADLINE: printf("SCHED_DEADLINE"); break; case SCHED_FIFO: printf("SCHED_FIFO"); break; case SCHED_RR: printf("SCHED_RR"); break; case SCHED_NORMAL: printf("SCHED_OTHER"); break; case SCHED_BATCH: printf("SCHED_BATCH"); break; case SCHED_IDLE: printf("SCHED_IDLE"); break; default: printf("unknown\n"); } priority_min = sched_get_priority_min(policy); priority_max = sched_get_priority_max(policy); printf(" PRI_MIN: %d PRI_MAX: %d\n", priority_min, priority_max); } int setpriority(pthread_t *thr, int newpolicy, int newpriority) { int policy, ret; struct sched_param param; if (newpriority > sched_get_priority_max(newpolicy) || newpriority < sched_get_priority_min(newpolicy)){ printf("Invalid priority: MIN: %d, MAX: %d", sched_get_priority_min(newpolicy), sched_get_priority_max(newpolicy)); return -1; } pthread_getschedparam(*thr, &policy, &param); printf("current: "); print_sched(policy); param.sched_priority = newpriority; ret = pthread_setschedparam(*thr, newpolicy, &param); if (ret != 0) perror("perror(): "); pthread_getschedparam(*thr, &policy, &param); printf("new: "); print_sched(policy); return 0; } int main(int argc, char **argv) { if (argc < 5){ printf("usage: ./%s <número_de_threads> <tamanho_do_buffer_global_em_kilobytes> <politica> <prioridade>\n\n", argv[0]); return 0; } pthread_mutex_init(&mutex, NULL); int policy; int priority; nThreads = atoi(argv[1]); bufferSize = atoi(argv[2]) * 1000; policy = atoi(argv[3]); priority = atoi(argv[4 ]); buffer = malloc(bufferSize); pthread_t thr [nThreads]; for(int i =0; i<nThreads; i++) pthread_create(&thr[i], NULL, run, (void *)(intptr_t)i); for(int i =0; i<nThreads; i++) pthread_join(thr[i], NULL); printf("Buffer: ["); for(int i=0; i<bufferSize; i++) printf(" %c", buffer[i]); printf(" ]"); // setpriority(&thr, SCHED_FIFO, 1); // sleep(timesleep); return 0; }
C
UTF-8
5,237
2.6875
3
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
#include <stdlib.h> #include <string.h> #include <openssl/evp.h> #include <openssl/err.h> #include <openssl/sha.h> #include <openssl/rand.h> #include "common.h" #include "params.h" #include "datacenter.h" /* Basic cryptographic parameters and wrappers around primitives. */ int min(int a, int b); inline int min (int a, int b) { return (a < b) ? a : b; } Params *Params_new() { int rv = ERROR; Params *params = NULL; CHECK_A (params = (Params *)malloc(sizeof(Params))); CHECK_A (params->base_prime = BN_new()); CHECK_A (params->order = BN_new()); CHECK_A (params->bn_ctx = BN_CTX_new()); CHECK_A (params->numLeaves = BN_new()); BN_hex2bn(&params->numLeaves, NUM_LEAVES_HEX_STR); CHECK_A (params->group = EC_GROUP_new_by_curve_name(NID_X9_62_prime256v1)); CHECK_C (EC_GROUP_get_order(params->group, params->order, params->bn_ctx)); CHECK_C (EC_GROUP_get_curve_GFp (params->group, params->base_prime, NULL, NULL, params->bn_ctx)); cleanup: if (rv == ERROR) { Params_free(params); return NULL; } return params; } void Params_free(Params *params) { BN_free(params->order); BN_free(params->base_prime); BN_free(params->numLeaves); BN_CTX_free(params->bn_ctx); EC_GROUP_free(params->group); free(params); } /* * Use SHA-256 to hash the string in `bytes_in` * with the integer given in `counter`. */ static int hash_once (EVP_MD_CTX *mdctx, uint8_t *bytes_out, const uint8_t *bytes_in, int inlen, uint16_t counter) { int rv = ERROR; CHECK_C (EVP_DigestInit_ex (mdctx, EVP_sha256 (), NULL)); CHECK_C (EVP_DigestUpdate (mdctx, &counter, sizeof counter)); CHECK_C (EVP_DigestUpdate (mdctx, bytes_in, inlen)); CHECK_C (EVP_DigestFinal_ex (mdctx, bytes_out, NULL)); cleanup: return rv; } /* * Output a string of pseudorandom bytes by hashing a * counter with the bytestring provided: * Hash(0|bytes_in) | Hash(1|bytes_in) | ... */ int hash_to_bytes (uint8_t *bytes_out, int outlen, const uint8_t *bytes_in, int inlen) { int rv = ERROR; uint16_t counter = 0; uint8_t buf[SHA256_DIGEST_LENGTH]; EVP_MD_CTX *mdctx = NULL; int bytes_filled = 0; CHECK_A (mdctx = EVP_MD_CTX_create()); do { const int to_copy = min (SHA256_DIGEST_LENGTH, outlen - bytes_filled); CHECK_C (hash_once (mdctx, buf, bytes_in, inlen, counter)); memcpy (bytes_out + bytes_filled, buf, to_copy); counter++; bytes_filled += SHA256_DIGEST_LENGTH; } while (bytes_filled < outlen); cleanup: if (mdctx) EVP_MD_CTX_destroy (mdctx); return rv; } /* aadLen must be <= 16 */ /* bytesIn, aadLen = 16, outLen = 32 */ int aesEncrypt(const void *key, const uint8_t *pt, int ptLen, uint8_t *iv, uint8_t *ct) { int rv = ERROR; int bytesFilled = 0; EVP_CIPHER_CTX *ctx; int len; CHECK_C (RAND_bytes(iv, AES256_IV_LEN)); CHECK_A (ctx = EVP_CIPHER_CTX_new()); CHECK_C (EVP_EncryptInit_ex(ctx, EVP_aes_256_ctr(), NULL, (const uint8_t *)key, iv)); CHECK_C (EVP_EncryptUpdate(ctx, ct, &bytesFilled, pt, ptLen)); len = bytesFilled; CHECK_C (EVP_EncryptFinal_ex(ctx, ct + len, &bytesFilled)); cleanup: if (rv != OKAY) printf("NOT OK ENCRYPT\n"); if (ctx) EVP_CIPHER_CTX_free(ctx); return rv; } int aesDecrypt(const void *key, uint8_t *pt, const uint8_t *iv, const uint8_t *ct, int ctLen) { int rv = ERROR; int bytesFilled = 0; EVP_CIPHER_CTX *ctx; CHECK_A (ctx = EVP_CIPHER_CTX_new()); CHECK_C (EVP_DecryptInit_ex(ctx, EVP_aes_256_ctr(), NULL, (const uint8_t *)key, iv)); CHECK_C (EVP_DecryptUpdate(ctx, pt, &bytesFilled, ct, ctLen)); CHECK_C (EVP_DecryptFinal_ex(ctx, pt + bytesFilled, &bytesFilled)); cleanup: if (rv != OKAY) printf("NOT OK DECRYPT\n"); if (ctx) EVP_CIPHER_CTX_free(ctx); return rv; } /* 33 bytes */ void Params_bytesToPoint(Params *params, const uint8_t *bytes, EC_POINT *pt) { EC_POINT_oct2point(params->group, pt, bytes, 33, params->bn_ctx); } /* 33 bytes */ void Params_pointToBytes(Params *params, uint8_t *bytes, const EC_POINT *pt) { EC_POINT_point2oct(params->group, pt, POINT_CONVERSION_COMPRESSED, bytes, 33, params->bn_ctx); } int intsToBignums(BIGNUM **bns, uint8_t *ints, int len) { int rv; for (int i = 0; i < len; i++) { CHECK_A (bns[i] = BN_bin2bn(&ints[i], 1, NULL)); } cleanup: return rv; } void hmac(uint8_t *key, uint8_t *out, uint8_t *in, int inLen) { uint8_t keyBuf[64]; uint8_t keyPadBuf[64]; uint8_t outBuf[32]; memset(keyBuf, 0, 64); memcpy(keyBuf, key, KEY_LEN); for (int i = 0; i < 64; i++) { keyPadBuf[i] = keyBuf[i] ^ 0x36; } memset(outBuf, 0, 32); memset(out, 0, 32); EVP_MD_CTX *mdctx = EVP_MD_CTX_create(); EVP_DigestInit_ex(mdctx, EVP_sha256(), NULL); EVP_DigestUpdate(mdctx, keyPadBuf, 64); EVP_DigestUpdate(mdctx, in, inLen); EVP_DigestFinal_ex(mdctx, outBuf, NULL); for (int i = 0; i < 64; i++) { keyPadBuf[i] = keyBuf[i] ^ 0x5c; } EVP_DigestInit_ex(mdctx, EVP_sha256(), NULL); EVP_DigestUpdate(mdctx, keyPadBuf, 64); EVP_DigestUpdate(mdctx, outBuf, 32); EVP_DigestFinal_ex(mdctx, out, NULL); }
C
UHC
30,454
3.4375
3
[]
no_license
#pragma warning(disable: 4996) #include <stdio.h> #include <stdlib.h> #include <time.h> #define MAX 1000 int cnt = 0; typedef enum { false, true } bool; typedef struct Node { //node int rsvNum; int rsvDate; int rsvTime; int rsvMovie; int rsvSeat; char payCard; char color; struct Node* right; struct Node* left; struct Node* parent; }Node; typedef struct queue_ { //Ʈ Ƴ Ȯϱ printTree queue( α׷ ) int front; int rear; int count; Node* items[MAX]; }Queue; typedef struct Tree { // tree root nil node Node* root; Node* NIL; }Tree; Node* createNode(int rsvNum, int rsvDate, int rsvTime, int rsvMovie, int rsvSeat, char payCard) { // tree insertϰų deleteϱ node Լ Node* n = malloc(sizeof(Node)); n->left = NULL; n->right = NULL; n->parent = NULL; n->rsvNum = rsvNum; n->rsvDate = rsvDate; n->rsvTime = rsvTime; n->rsvMovie = rsvMovie; n->rsvSeat = rsvSeat; n->payCard = payCard; n->color = 'r'; return n; } Tree* initTree() { // ó tree ʱȭŰ Լ Tree* t = malloc(sizeof(Tree)); Node* nil_node = malloc(sizeof(Node)); nil_node->left = NULL; nil_node->right = NULL; nil_node->parent = NULL; nil_node->color = 'b'; nil_node->rsvNum = 0; t->NIL = nil_node; t->root = t->NIL; return t; } void left_rotate(Tree* t, Node* x) { Node* y = x->right; x->right = y->left; if (y->left != t->NIL) { //y ڽ ϴ y->left->parent = x; } y->parent = x->parent; if (x->parent == t->NIL) { // root ǹ t->root = y; } else if (x == x->parent->left) { //x ڽ x->parent->left = y; } else { //x ڽ x->parent->right = y; } y->left = x; x->parent = y; } void right_rotate(Tree* t, Node* x) { Node* y = x->left; x->left = y->right; if (y->right != t->NIL) { //y ڽ ϴ y->right->parent = x; } y->parent = x->parent; if (x->parent == t->NIL) { //root ǹ t->root = y; } else if (x == x->parent->right) { //x ڽ x->parent->right = y; } else { //x ڽ x->parent->left = y; } y->right = x; x->parent = y; } void rbInsertFixup(Tree* t, Node* z) { //insertϰ rbtree property ֱ while (z->parent->color == 'r') { //θ r Ե 嵵 r̹Ƿ property if (z->parent == z->parent->parent->left) { // θ Ҿƹ ڽ Node* y = z->parent->parent->right; if (y->color == 'r') { z->parent->color = 'b'; y->color = 'b'; z->parent->parent->color = 'r'; z = z->parent->parent; } else { if (z == z->parent->right) { z = z->parent; left_rotate(t, z); } z->parent->color = 'b'; z->parent->parent->color = 'r'; right_rotate(t, z->parent->parent); } } else { // θ Ҿƹ ڽ Node* y = z->parent->parent->left; if (y->color == 'r') { z->parent->color = 'b'; y->color = 'b'; z->parent->parent->color = 'r'; z = z->parent->parent; } else { if (z == z->parent->left) { z = z->parent; right_rotate(t, z); } z->parent->color = 'b'; z->parent->parent->color = 'r'; left_rotate(t, z->parent->parent); } } } t->root->color = 'b'; } void rbInsert(Tree* t, int rsvNum, int rsvDate, int rsvTime, int rsvMovie, int rsvSeat, char payCard) { // Լ Node* z; z = createNode(rsvNum, rsvDate, rsvTime, rsvMovie, rsvSeat, payCard); Node* y = t->NIL; Node* temp = t->root; while (temp != t->NIL) { y = temp; if (z->rsvNum < temp->rsvNum) temp = temp->left; else temp = temp->right; } z->parent = y; if (y == t->NIL) { t->root = z; } else if (z->rsvNum < y->rsvNum) y->left = z; else y->right = z; z->right = t->NIL; z->left = t->NIL; //ϴ BST insert (NULL ƴ t->NIL ) rbInsertFixup(t, z); } void transplantNode(Tree* t, Node* u, Node* v) { //delete ϴ node Լ if (u->parent == t->NIL) t->root = v; else if (u == u->parent->left) u->parent->left = v; else u->parent->right = v; v->parent = u->parent; } Node* minimum(Tree* t, Node* x) { //delete ϴ subtree ּҰ ã Լ while (x->left != t->NIL) x = x->left; return x; } void rbDeleteFixup(Tree* t, Node* x) { //Ǵ 尡 b rbtree property ʱ Node* w; while (x != t->root && x->color == 'b') { if (x == x->parent->left) { w = x->parent->right; if (w->color == 'r') { w->color = 'b'; x->parent->color = 'r'; left_rotate(t, x->parent); w = x->parent->right; } if (w->left->color == 'b' && w->right->color == 'b') { w->color = 'r'; x = x->parent; } else { if (w->right->color == 'b') { w->left->color = 'b'; w->color = 'r'; right_rotate(t, w); w = x->parent->right; } w->color = x->parent->color; x->parent->color = 'b'; w->right->color = 'b'; left_rotate(t, x->parent); x = t->root; } } else { w = x->parent->left; if (w->color == 'r') { w->color = 'b'; x->parent->color = 'r'; right_rotate(t, x->parent); w = x->parent->left; } if (w->right->color == 'b' && w->left->color == 'b') { w->color = 'r'; x = x->parent; } else { if (w->left->color == 'b') { w->right->color = 'b'; w->color = 'r'; left_rotate(t, w); w = x->parent->left; } w->color = x->parent->color; x->parent->color = 'b'; w->left->color = 'b'; right_rotate(t, x->parent); x = t->root; } } } x->color = 'b'; } Node* findNode(Node* n, int value) { // ش node ã Լ - α׷ ȣ ش if (value < n->rsvNum) { if (n->left == NULL) { return NULL; } return findNode(n->left, value); } else if (value > n->rsvNum) { if (n->right == NULL) { return NULL; } return findNode(n->right, value); } else { return n; } } void rbDelete(Tree* t, int rsvNum) { //Ư node ϴ Լ if (t->root->left == t->NIL && t->root->right == t->NIL && t->root->parent == t->NIL) { t->root = t->NIL; } else { Node* z, * x, * y; z = findNode(t->root, rsvNum); y = z; char y_ogclr = y->color; if (z->left == t->NIL) { x = z->right; transplantNode(t, z, z->right); } else if (z->right == t->NIL) { x = z->left; transplantNode(t, z, z->left); } else { y = minimum(t, z->right); y_ogclr = y->color; x = y->right; if (y->parent == z) { x->parent = y; } else { transplantNode(t, y, y->right); y->right = z->right; y->right->parent = y; } transplantNode(t, z, y); y->left = z->left; y->left->parent = y; y->color = z->color; } if (y_ogclr == 'b') rbDeleteFixup(t, x); } } void inorder(Tree* t, Node* n) { //rbtree ȸϸ printϴ Լ - debugging if (n != t->NIL) { inorder(t, n->left); if (n->color == 'r') { printf("%d[R] ", n->rsvNum); } else if (n->color == 'b') { printf("%d[B] ", n->rsvNum); } inorder(t, n->right); } } int height(Tree* t, Node* n) { //Ʈ ̸ ˾Ƴ Լ if (n == t->NIL) return 0; else { int left = height(t, n->left); int right = height(t, n->right); if (left <= right) return right + 1; else return left + 1; } } void enqueue(Queue* q, Node* new) { //enqueue q->items[q->rear] = new; q->rear++; q->count++; } Node* dequeue(Queue* q) { //dequeue Node* temp; temp = q->items[q->front]; q->front++; q->count--; return temp; } void printTree(Tree* t, Queue* q) { //Ʈ Ÿ Լ - debugging Node* nl; nl = createNode(-1, 0, 0, 0, 0, 0); Node* temp; int cnt1 = 0; int cnt2 = 0; int h = height(t, t->root); if (t->root == NULL) { return; } enqueue(q, t->root); cnt1++; for (int i = 0; i < h; i++) { while (cnt1 != 0) { temp = dequeue(q); cnt1--; if (temp->rsvNum == -1) { printf("N "); } else { if (temp != NULL) { printf("%d[%c]", temp->rsvNum - 10000, temp->color); } if (temp->left == t->NIL) { enqueue(q, nl); } else { enqueue(q, temp->left); } if (temp->right == t->NIL) { enqueue(q, nl); } else { enqueue(q, temp->right); } cnt2 += 2; } } printf("\n"); cnt1 = cnt2; cnt2 = 0; } } void countNodes(Tree* t, Node* n) { //Ʈ Լ - inorder if (n != t->NIL) { countNodes(t, n->left); cnt++; countNodes(t, n->right); } } void randomInitSeat(int* A) { A[0] = rand() % 100 + 1; for (int i = 0; i < 33; i++) { A[i] = rand() % 100 + 1; for (int j = 0; j < i; j++) { if (A[i] == A[j]) i--; } } } void randomInitPay(int* P) { //1~2 33 for (int i = 0; i < 33; i++) { P[i] = rand() % 2 + 1; } } void randomInitBase(int* A, int* P) { randomInitSeat(A); //33 1~100 randomInitPay(P); // 33 1~2 } void inorderLeaves(Tree* t, Node* n) { //Ʈ ȸϸ leaf printϴ Լ if (n != t->NIL) { inorderLeaves(t, n->left); if (n->left == t->NIL && n->right == t->NIL) { printf("Reservation number : %d\n", n->rsvNum); printf("Date : %d\n", n->rsvDate); printf("Movie : %d\n", n->rsvMovie); printf("Time : %d\n", n->rsvTime); printf("Pay by card : %c\n\n", n->payCard); } inorderLeaves(t, n->right); } } void printRootLeaves(Tree* t) { //Ʈ root , Ʈ ֿ̼ȸϸ leaf printϴ Լ printf("key value of root : \n"); printf("Reservation number : %d\n", t->root->rsvNum); printf("Date : %d\n", t->root->rsvDate); printf("Movie : %d\n", t->root->rsvMovie); printf("Time : %d\n", t->root->rsvTime); printf("Pay by card : %c\n", t->root->payCard); printf("\n\n"); printf("Leaves (from left to right) : \n"); inorderLeaves(t, t->root); } void initQueue(Queue* queue) { //queue ʱȭ queue->front = 0; queue->rear = 0; queue->count = 0; } void randomInit(int* A, int* P, Tree* day1_t, Tree* day2_t, Tree* day3_t, int number[], int rsvNum) { // ȭ 33% ¼ ϰ ϴ Լ randomInitBase(A, P); for (int d = 0; d < 3; d++) { for (int n = 0; n < 3; n++) { for (int k = 0; k < 3; k++) { for (int i = 0; i < 33; i++) { if (d == 0) { if (P[i] == 1) { rbInsert(day1_t, number[rsvNum], 1, n + 1, k + 1, A[i], 'y'); rsvNum++; } else if (P[i] == 2) { rbInsert(day1_t, number[rsvNum], 1, n + 1, k + 1, A[i], 'n'); rsvNum++; } } else if (d == 1) { if (P[i] == 1) { rbInsert(day2_t, number[rsvNum], 2, n + 1, k + 1, A[i], 'y'); rsvNum++; } else if (P[i] == 2) { rbInsert(day2_t, number[rsvNum], 2, n + 1, k + 1, A[i], 'n'); rsvNum++; } } else if (d == 2) { if (P[i] == 1) { rbInsert(day3_t, number[rsvNum], 3, n + 1, k + 1, A[i], 'y'); rsvNum++; } else if (P[i] == 2) { rbInsert(day3_t, number[rsvNum], 3, n + 1, k + 1, A[i], 'n'); rsvNum++; } } } randomInitBase(A, P); } } } } void printSeatLayout(int* seatLayout) { //¼ printϴ Լ printf("\n\n [ S C R E E N ]\n\n\n"); for (int i = 0; i < 5; i++) { printf(" "); for (int j = (i * 20); j < (i * 20) + 20; j++) { if (seatLayout[j] == 0) { printf("[XX] "); } else { printf("[%02d] ", seatLayout[j]); } } printf("\n\n"); } for (int i = 0; i < 100; i++) { seatLayout[i] = i + 1; } } void inorderSeat(Tree* t, Node* n, int movie, int times, int* seatLayout) { //¼ ¼ ̸ ǥصδ Լ if (n != t->NIL) { if (n->rsvMovie == movie && n->rsvTime == times) { seatLayout[n->rsvSeat - 1] = 0; } inorderSeat(t, n->left, movie, times, seatLayout); inorderSeat(t, n->right, movie, times, seatLayout); } } void printMovie(int n) { //ȣ ȭ Ʈ Ʈ if (n == 1) { printf("Movie : About time\n"); } if (n == 2) { printf("Movie : The Avengers\n"); } if (n == 3) { printf("Movie : Frozen\n"); } } void printTimes(int n) { //ȣ ð Ʈ Ʈ if (n == 1) { printf("Time : 12 : 00\n"); } if (n == 2) { printf("Time : 15 : 00\n"); } if (n == 3) { printf("Time : 18 : 00\n"); } } void printDate(int n) { //ȣ Ʈ Ʈ if (n == 1) { printf("Date : 01.12.2020\n"); } if (n == 2) { printf("Date : 02.12.2020\n"); } if (n == 3) { printf("Date : 02.12.2020\n"); } } void printPay(char n) { //ڿ Ʈ if (n == 'y') { printf("Pay : Card\n"); } else { printf("Pay : Cash\n"); } } void printResult(int rsvNum, int date, int times, int seat, int movie, char pay) { //Ȯ Ʈ printf("Reservation Number : %d\n", rsvNum); printDate(date); printMovie(movie); printTimes(times); printf("Seat Number : %d\n", seat); printPay(pay); } void UI(Tree* day1_t, Tree* day2_t, Tree* day3_t, int* seatLayout, int number[]) { // UI Ÿ Լ int first, date, times, movie, seat, choice, cancelRsvNum, cancelDate; char payCard; int rsvNum = 890; while (1) { rsvNum++; printf("**********************\n"); printf("1. Make a reservation\n"); printf("2. Cancel a reservation\n"); printf("3. Exit\n"); printf("**********************\n"); printf("Enter your choice : "); scanf("%d", &first); system("cls"); if (first == 1) { // ϴ printf("*****************\n"); printf("1 : 01.12.2020\n"); printf("2 : 02.12.2020\n"); printf("3 : 03.12.2020\n"); printf("*****************\n"); printf("Select the date : "); //¥ scanf("%d", &date); system("cls"); printf("******************************************************\n"); printf("1. About time 2. The Avengers 3. Frozen\n"); printf("1. 12:00 12:00 12:00\n"); printf("2. 15:00 15:00 15:00\n"); printf("3. 18:00 18:00 18:00\n"); printf("******************************************************\n"); printf("Select the movie number : "); // ȭ scanf("%d", &movie); printf("Select the time number : "); // ð scanf("%d", &times); system("cls"); if (date == 1) { //01.12.2020 inorderSeat(day1_t, day1_t->root, movie, times, seatLayout); printSeatLayout(seatLayout); printf("Please select the seat number : "); //¼ scanf("%d", &seat); printf("Will you pay by card ? (if yes enter 'y', if no enter 'n') : "); scanf(" %c", &payCard); // system("cls"); printf("Your reservation has been made successfully !!\n"); printf("******************************************************\n"); printResult(number[rsvNum], date, times, seat, movie, payCard); // Ʈ printf("******************************************************\n"); rbInsert(day1_t, number[rsvNum], 1, times, movie, seat, payCard); //tree insert printRootLeaves(day1_t); //root, leaves countNodes(day1_t, day1_t->root); printf("Total number of nodes : %d", cnt); //tree Ʈ cnt = 0; printf("\n\nHeight of tree(day1_t) : %d\n\n\n", height(day1_t, day1_t->root)); //tree print printf("\n\n\n"); printf("1. Go to menu\n"); printf("2. exit\n"); printf("Press number : "); scanf("%d", &choice); // ȭ system("cls"); if (choice == 1) { continue; //1̸ ٽ ʱ ȭ } else if (choice == 2) { //2 α׷ printf("Thank you for visiting !!\n"); break; } } else if (date == 2) { //02.12.2020 ϴ - inorderSeat(day2_t, day2_t->root, movie, times, seatLayout); printSeatLayout(seatLayout); printf("Please select the seat number : "); scanf("%d", &seat); printf("Will you pay by card ? (if yes enter 'y', if no enter 'n') : "); scanf(" %c", &payCard); system("cls"); printf("Your reservation has been made successfully !!\n"); printf("******************************************************\n"); printResult(number[rsvNum], date, times, seat, movie, payCard); printf("******************************************************\n"); rbInsert(day2_t, number[rsvNum], 2, times, movie, seat, payCard); printRootLeaves(day2_t); countNodes(day2_t, day2_t->root); printf("Total number of nodes : %d", cnt); cnt = 0; printf("\n\nHeight of tree(day2_t) : %d\n\n\n", height(day2_t, day2_t->root)); printf("\n\n\n"); printf("1. Go to menu\n"); printf("2. exit\n"); printf("Press number : "); scanf("%d", &choice); system("cls"); if (choice == 1) { continue; } else if (choice == 2) { printf("Thank you for visiting !!\n"); break; } } else if (date == 3) {//03.12.2020 ϴ - inorderSeat(day3_t, day3_t->root, movie, times, seatLayout); printSeatLayout(seatLayout); printf("Please select the seat number : "); scanf("%d", &seat); printf("Will you pay by card ? (if yes enter 'y', if no enter 'n') : "); scanf(" %c", &payCard); system("cls"); printf("Your reservation has been made successfully !!\n"); printf("******************************************************\n"); printResult(number[rsvNum], date, times, seat, movie, payCard); printf("******************************************************\n"); rbInsert(day3_t, number[rsvNum], 3, times, movie, seat, payCard); printRootLeaves(day3_t); countNodes(day3_t, day3_t->root); printf("Total number of nodes : %d", cnt); cnt = 0; printf("\n\nHeight of tree(day3_t) : %d\n\n\n", height(day3_t, day3_t->root)); printf("\n\n\n"); printf("1. Go to menu\n"); printf("2. exit\n"); printf("Press number : "); scanf("%d", &choice); system("cls"); if (choice == 1) { continue; } else if (choice == 2) { printf("Thank you for visiting !!\n"); break; } } } else if (first == 2) { // ϴ Node* cancel; printf("Enter your reservation number : "); scanf("%d", &cancelRsvNum); // Źȣ Է system("cls"); while (1) { // Ʈ ش ȣ node ã´ cancel = findNode(day1_t->root, cancelRsvNum); if (cancel != NULL) break; cancel = findNode(day2_t->root, cancelRsvNum); if (cancel != NULL) break; cancel = findNode(day3_t->root, cancelRsvNum); if (cancel != NULL) break; break; // ã ׳ break ǰ cancel NULL ȴ. } if (cancel == NULL) { //ش node ã printf("You have typed the wrong reservation number. Please check once more !\n\n"); printf("1. Go to menu\n"); printf("2. exit\n"); printf("Enter number : "); scanf("%d", &choice); system("cls"); if (choice == 1) { continue; } else if (choice == 2) { printf("Thank you for visiting !!\n"); break; } } printf("Please check your reservation information\n\n"); //Է ȣ printf("****************************\n"); printResult(cancel->rsvNum, cancel->rsvDate, cancel->rsvTime, cancel->rsvSeat, cancel->rsvMovie, cancel->payCard); printf("****************************\n\n\n"); printf("1. Cancel above reservation\n"); printf("2. Go to menu\n"); printf("Enter number : "); scanf("%d", &choice); system("cls"); if (choice == 1) { // printf("Your reservation has been cancelled !\n\n\n"); if (cancel->payCard == 'y') { printf("!! Since you have selected to pay by card, refund will be made by card !!\n\n\n"); } else if (cancel->payCard != 'y') { printf("!! Since you have selected to pay by cash, refund will not be made !!\n\n\n"); } if (cancel->rsvDate == 1) { //01.12.2020 rbDelete(day1_t, cancelRsvNum); //tree delete printRootLeaves(day1_t); //tree root, leaves countNodes(day1_t, day1_t->root); //tree Ʈ printf("Total number of nodes : %d", cnt); cnt = 0; printf("\n\nHeight of tree(day1_t) : %d\n\n\n", height(day1_t, day1_t->root)); //Ʈ Ʈ printf("\n\n\n"); } else if (cancel->rsvDate == 2) { //02.12.2020 - rbDelete(day2_t, cancelRsvNum); printRootLeaves(day2_t); countNodes(day2_t, day2_t->root); printf("Total number of nodes : %d", cnt); cnt = 0; printf("\n\nHeight of tree(day2_t) : %d\n\n\n", height(day2_t, day2_t->root)); printf("\n\n\n"); } else if (cancel->rsvDate == 3) { //03.12.2020 - rbDelete(day3_t, cancelRsvNum); printRootLeaves(day3_t); countNodes(day3_t, day3_t->root); printf("Total number of nodes : %d", cnt); cnt = 0; printf("\n\nHeight of tree(day3_t) : %d\n\n\n", height(day3_t, day3_t->root)); printf("\n\n\n"); } printf("1. Go to menu\n"); printf("2. exit\n"); printf("Enter number : "); scanf("%d", &choice); system("cls"); if (choice == 1) { continue; } else if (choice == 2) { printf("Thank you for visiting !!\n"); break; } } else if (choice == 2) { // Ұ ƴ ʱ ȭ ưٴ ȣ Է continue; } } else if (first == 3) { //ŵ ƴϰ ҵ ƴϰ, α׷ printf("Thank you for visiting !\n\n\n"); break; } else { //1,2,3 ȣ Է printf("Sorry, you have entered the wrong number !\n\n\n"); continue; } } } int main() { Tree* day1_t = initTree(); Tree* day2_t = initTree(); Tree* day3_t = initTree(); srand(time(NULL)); int* A = (int*)malloc(sizeof(int) * 33); //random seat number int* P = (int*)malloc(sizeof(int)*33); //random pay method int number[2700]; number[0] = rand() % 20000 + 10000; for (int i = 0; i < 2700; i++) { number[i] = rand() % 20000 + 10000; for (int j = 0; j < i; j++) { if (number[i] == number[j]) i--; } } int rsvNum = 0; randomInit(A, P, day1_t, day2_t, day3_t, number, rsvNum); //ʱ 30% ¼ ä Queue* q; q = (Queue*)malloc(sizeof(Queue)); initQueue(q); int* seatLayout; seatLayout = (int*)malloc(sizeof(int) * 100); //¼ for (int i = 0; i < 100; i++) { seatLayout[i] = i + 1; } UI(day1_t, day2_t, day3_t, seatLayout, number); }
C
UTF-8
1,790
2.6875
3
[]
no_license
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* free.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: avongdar <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/04/29 18:00:52 by avongdar #+# #+# */ /* Updated: 2017/04/29 18:00:58 by avongdar ### ########.fr */ /* */ /* ************************************************************************** */ #include "ft_db.h" void free_map(char **map) { int i; i = 0; while (map[i]) { free(map[i]); i++; } free(map); } void free_mapn(char **map, int num) { int i; i = 0; while (i < num) { free(map[i]); i++; } free(map); } void free_fields(t_field *fields, int num_fields, int num_rows) { int i; i = -1; while (++i < num_fields) { if (strcmp(fields[i].data_type, FT_STRING) == 0) free_mapn(fields[i].str_rows, num_rows); else if (strcmp(fields[i].data_type, FT_INT) == 0) free(fields[i].int_rows); free(fields[i].name); } } void free_tables(t_table *tables, int num_tables) { int i; i = -1; while (++i < num_tables) { free_fields(tables[i].fields, tables[i].num_cols, tables[i].num_rows); free(tables[i].fields); free(tables[i].name); } free(tables); } void free_db(t_database *db) { free_tables(db->tables, db->num_tables); free(db->name); free(db); }
C
UTF-8
522
3.6875
4
[ "MIT" ]
permissive
// rot13.c: Encodes/decodes standard input to/from the ROT13 cipher #define EOF -1 int putchar(int c); char getchar(void); char c; int offset; int main (void) { for (;;) { c = getchar(); if (c == EOF) { break; } offset = 0; if (('a' <= c && c < 'n') || ('A' <= c && c < 'N')) { offset = 13; } else if (('n' <= c && c <= 'z') || ('N' <= c && c <= 'Z')) { offset = -13; } putchar(c + offset); } return 0; }
C
UTF-8
3,044
2.75
3
[]
no_license
/* * Copyright 2009 The Android Open Source Project * * Magic entries in /sys/power/. */ #include "Common.h" #include <stdlib.h> #include <string.h> #include <ctype.h> /* * Map filename to device index. * * [ not using DeviceIndex -- would be useful if we need to return something * other than a static string ] */ static const struct { const char* name; //DeviceIndex idx; const char* data; } gDeviceMap[] = { { "state", "mem\n" }, { "wake_lock", "\n" }, { "wake_unlock", "KeyEvents PowerManagerService radio-interface\n" }, }; /* * Power driver state. * * Right now we just ignore everything written. */ typedef struct PowerState { int which; } PowerState; /* * Figure out who we are, based on "pathName". */ static void configureInitialState(const char* pathName, PowerState* powerState) { const char* cp = pathName + strlen("/sys/power/"); int i; powerState->which = -1; for (i = 0; i < (int) (sizeof(gDeviceMap) / sizeof(gDeviceMap[0])); i++) { if (strcmp(cp, gDeviceMap[i].name) == 0) { powerState->which = i; break; } } if (powerState->which == -1) { wsLog("Warning: access to unknown power device '%s'\n", pathName); return; } } /* * Free up the state structure. */ static void freeState(PowerState* powerState) { free(powerState); } /* * Read data from the device. * * We don't try to keep track of how much was read -- existing clients just * try to read into a large buffer. */ static ssize_t readPower(FakeDev* dev, int fd, void* buf, size_t count) { PowerState* state = (PowerState*) dev->state; int dataLen; wsLog("%s: read %d\n", dev->debugName, count); if (state->which < 0 || state->which >= (int) (sizeof(gDeviceMap)/sizeof(gDeviceMap[0]))) { return 0; } const char* data = gDeviceMap[state->which].data; size_t strLen = strlen(data); while(strLen == 0) sleep(10); // block forever ssize_t copyCount = (strLen < count) ? strLen : count; memcpy(buf, data, copyCount); return copyCount; } /* * Ignore the request. */ static ssize_t writePower(FakeDev* dev, int fd, const void* buf, size_t count) { wsLog("%s: write %d bytes\n", dev->debugName, count); return count; } /* * Free up our state before closing down the fake descriptor. */ static int closePower(FakeDev* dev, int fd) { freeState((PowerState*)dev->state); dev->state = NULL; return 0; } /* * Open a power device. */ FakeDev* wsOpenSysPower(const char* pathName, int flags) { FakeDev* newDev = wsCreateFakeDev(pathName); if (newDev != NULL) { newDev->read = readPower; newDev->write = writePower; newDev->ioctl = NULL; newDev->close = closePower; PowerState* powerState = calloc(1, sizeof(PowerState)); configureInitialState(pathName, powerState); newDev->state = powerState; } return newDev; }
C
UTF-8
2,138
3.453125
3
[]
no_license
#include<stdio.h> #include<stdlib.h> #include<string.h> typedef struct node { int data; struct node* link; }node; node* list[27]; int visited[27],ans=0,flag[27]; void push(node** head,int dat) { node* temp =(node*)malloc(sizeof(node)); temp->data=dat; temp->link=*head; *head=temp; return; } void print(node** b,int x) { node* temp=b[x]; printf("%d =>",x); while(temp!=NULL) { printf("%d ",temp->data); temp=temp->link; } printf("\n"); return; } void cycle(node** b,int x) { node* temp; temp=list[x]; visited[x]=1; while(temp!=NULL) { int t=temp->data; if(flag[t]==1) ans=1; if(visited[t]==0) { if(flag[x]==0) flag[x]=1; else if(flag[t]==1) ans=1; cycle(b,t); } temp=temp->link; } //visited[x]=0; flag[x]=2; return; } int main() { int T; scanf("%d",&T); while(T--) { int n,i,j,a1,b1,l1,l2,t; ans=0; scanf("%d",&n); char string[505][505]; for(i=0;i<27;i++) { list[i]=NULL; visited[i]=0; flag[i]=0; } for(i=0;i<n;i++) scanf("%s",string[i]); for(i=0;i<n-1;i++) { l1=strlen(string[i]); l2=strlen(string[i+1]); t=l1<l2?l1:l2; for(j=0;j<=t;j++) if(string[i][j]!=string[i+1][j]) break; if(j<=t && l1<=l2) { a1=string[i][j]-'a'; b1=string[i+1][j]-'a'; //printf("%d %d\n",a1,b1); push(&list[a1],b1); } else if(l1>l2 && j==t) ans=1; } //for(i=0;i<26;i++) // print(list,i); for(i=0;i<26;i++) { if(visited[i]==0) cycle(list,i); } //printf("ans => %d\n",ans); if(ans==1) printf("Impossible\n"); else printf("Possible\n"); } return 0; }
C
UTF-8
6,858
2.859375
3
[]
no_license
#include <math.h> #include <stdlib.h> #include <stdio.h> #include <time.h> #include <omp.h> #include <string.h> #include <sys/sysinfo.h> unsigned int seed = 0; int NowYear; // 2020 - 2025 int NowMonth; // 0 - 11 float NowPrecip; // inches of rain per month float NowTemp; // temperature this month float NowHeight; // grain height in inches int NowNumDeer; // number of deer in the current population int NowNumMice; // number of mice in the current population const float GRAIN_GROWS_PER_MONTH = 12.0; const float ONE_DEER_EATS_PER_MONTH = 0.8; const float ONE_MOUSE_EATS_PER_MONTH = 0.05; const float AVG_PRECIP_PER_MONTH = 7.0; // average const float AMP_PRECIP_PER_MONTH = 6.0; // plus or minus const float RANDOM_PRECIP = 2.0; // plus or minus noise const float AVG_TEMP = 60.0; // average const float AMP_TEMP = 20.0; // plus or minus const float RANDOM_TEMP = 10.0; // plus or minus noise const float MIDTEMP = 40.0; const float MIDPRECIP = 10.0; omp_lock_t Lock; int NumInThreadTeam; int NumAtBarrier; int NumGone; void InitBarrier( int ); void WaitBarrier( ); FILE *fp; // specify how many threads will be in the barrier: // (also init's the Lock) void InitBarrier( int n ) { NumInThreadTeam = n; NumAtBarrier = 0; omp_init_lock( &Lock ); } // have the calling thread wait here until all the other threads catch up: void WaitBarrier() { omp_set_lock( &Lock ); { NumAtBarrier++; if( NumAtBarrier == NumInThreadTeam ) { NumGone = 0; NumAtBarrier = 0; // let all other threads get back to what they were doing // before this one unlocks, knowing that they might immediately // call WaitBarrier( ) again: while( NumGone != NumInThreadTeam-1 ); omp_unset_lock( &Lock ); return; } } omp_unset_lock( &Lock ); while( NumAtBarrier != 0 ); // this waits for the nth thread to arrive #pragma omp atomic NumGone++; // this flags how many threads have returned } float SQR( float x ) { return x*x; } float RandF( unsigned int *seedp, float low, float high ) { float r = (float) rand_r( seedp ); // 0 - RAND_MAX return( low + r * ( high - low ) / (float)RAND_MAX ); } int RandInt( unsigned int *seedp, int ilow, int ihigh ) { float low = (float)ilow; float high = (float)ihigh + 0.9999f; return (int)( RandF(seedp, low,high) ); } void printState() { char line[] = "--------------------------------------------------\n"; char timeStr[50]; char dataStr[150]; snprintf(timeStr, 50, "\tMonth: %i\t Year: %i\n", NowMonth, NowYear); snprintf(dataStr, 150, "Temp:\t\t\t%f\nPrecip:\t\t\t%f\nGrain Height:\t\t%f\nNumber of Deer:\t\t%i\nNumber of Mice:\t\t%i\n", NowTemp, NowPrecip, NowHeight, NowNumDeer, NowNumMice); printf("%s", line); printf("%s", timeStr); printf("%s", line); printf("%s", dataStr); printf("%s", line); } void GrainDeer() { while (NowYear < 2026) { int nextNumDeer = NowNumDeer; if (NowNumDeer > NowHeight) { nextNumDeer -= 1; } else if (NowNumDeer < NowHeight) { nextNumDeer += 1; } // DoneComputing barrier: WaitBarrier(); NowNumDeer = nextNumDeer; // DoneAssigning barrier: WaitBarrier(); // DonePrinting barrier: WaitBarrier(); } } void Grain() { while (NowYear < 2026) { float tempFactor = exp( -SQR( ( NowTemp - MIDTEMP ) / 10. ) ); float precipFactor = exp( -SQR( ( NowPrecip - MIDPRECIP ) / 10. ) ); float nextHeight = NowHeight; nextHeight += tempFactor * precipFactor * GRAIN_GROWS_PER_MONTH; nextHeight -= (float)NowNumDeer * ONE_DEER_EATS_PER_MONTH; nextHeight -= (float)NowNumMice * ONE_MOUSE_EATS_PER_MONTH; if (nextHeight < 0) { nextHeight = 0.0; } // DoneComputing barrier: WaitBarrier(); NowHeight = nextHeight; // DoneAssigning barrier: WaitBarrier(); // DonePrinting barrier: WaitBarrier(); } } void Mice() { while (NowYear < 2026) { int nextNumMice = NowNumMice; if (NowNumMice > 10.0*NowHeight) { nextNumMice -= 2; } else if (NowNumMice < 10.0*NowHeight) { nextNumMice += 2; } // DoneComputing barrier: WaitBarrier(); NowNumMice = nextNumMice; // DoneAssigning barrier: WaitBarrier(); // DonePrinting barrier: WaitBarrier(); } } void Watcher() { while (NowYear < 2026) { // DoneComputing barrier: WaitBarrier(); // DoneAssigning barrier: WaitBarrier(); printState(); // Save data to file fprintf(fp, "%i, %i, %f, %f, %f, %i, %i\n", NowMonth, NowYear, NowTemp, NowPrecip, NowHeight, NowNumDeer, NowNumMice); // Increment time NowMonth += 1; if (NowMonth > 11) { NowMonth = 0; NowYear += 1; } // Update env params float ang = ( 30.*(float)NowMonth + 15. ) * ( M_PI / 180. ); float temp = AVG_TEMP - AMP_TEMP * cos( ang ); NowTemp = temp + RandF( &seed, -RANDOM_TEMP, RANDOM_TEMP ); float precip = AVG_PRECIP_PER_MONTH + AMP_PRECIP_PER_MONTH * sin( ang ); NowPrecip = precip + RandF( &seed, -RANDOM_PRECIP, RANDOM_PRECIP ); if( NowPrecip < 0. ) NowPrecip = 0.; // DonePrinting barrier: WaitBarrier(); } } int main (int argc, char* argv[]) { fp = fopen("./sim_data.csv", "w+"); fprintf(fp, "Month, Year, Temp, Precip, Grain Height, Number of Deer, Number of Mice\n"); // starting date and time: NowMonth = 0; NowYear = 2020; // starting state (feel free to change this if you want): NowNumDeer = 2; NowHeight = 15.; NowNumMice = 6; float ang = ( 30.*(float)NowMonth + 15. ) * ( M_PI / 180. ); float temp = AVG_TEMP - AMP_TEMP * cos( ang ); NowTemp = temp + RandF( &seed, -RANDOM_TEMP, RANDOM_TEMP ); float precip = AVG_PRECIP_PER_MONTH + AMP_PRECIP_PER_MONTH * sin( ang ); NowPrecip = precip + RandF( &seed, -RANDOM_PRECIP, RANDOM_PRECIP ); if( NowPrecip < 0. ) NowPrecip = 0.; omp_set_num_threads(4); // same as # of sections InitBarrier(4); #pragma omp parallel sections { #pragma omp section { GrainDeer( ); } #pragma omp section { Grain(); } #pragma omp section { Watcher( ); } #pragma omp section { Mice( ); } } fclose(fp); return 0; }