language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
#include <stdio.h> #include <stdlib.h> typedef struct { char isim[10]; int x_ekseni; int y_ekseni; }nokta; void ekranayazdir(nokta p[],int n) { int i; for(i=0;i<n;i++) { printf("%s = ( %d , %d )\n",p[i].isim,p[i].x_ekseni,p[i].y_ekseni); } } int main() { nokta can[5]={{"Canan",1,2},{"Hakan",3,4},{"Osman",5,6},{"Deniz",7,8},{"Merve",9,0}}; ekranayazdir(can,5); }
C
#include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <stdlib.h> #include <sys/wait.h> #include <stdio.h> int main(void) { pid_t pid; pid = fork(); if ( pid < 0) { perror("Fail to fork process:"); exit(-1); } else if (pid == 0) { int fd; char buf[256]; printf("child process %d\n", getpid()); fd = open("testfile.txt", O_RDONLY); read(fd, buf, 256); printf("buf: %s\n", buf); } else { //parent wait(NULL); printf("child process %d is exit\n", pid); } return 0; }
C
#include <unistd.h> #include <stdio.h> void ft_putchar(char c) { write(1,&c,1); } void ft_putstr(char *str) { int i; i=0; while (str[i]) { ft_putchar(str[i++]); } ft_putchar('\n'); } void ft_swap(char **s1,char **s2) { char *c; c=*s1; *s1=*s2; *s2=c; } int ft_cmp(char *str, char *str2) { int i; i=0; while (str[i] || str2[i]) { if (str[i] != str2[i]) { return(str[i]-str2[i]); } else i++; } return(0); } int main(int argc, char** argv) { int j; j=1; if (argc == 2) { ft_putstr(argv[1]); return(0); } while (j < argc-1) { if (ft_cmp(argv[j], argv[j+1]) > 0) { ft_swap(&argv[j],&argv[j+1]); j=1; } else j++; } j=0; while (argc > ++j) ft_putstr(argv[j]); return(0); }
C
#include<stdio.h> #include<conio.h> #include<string.h> #define MAX 5 struct stack { int top; char data[MAX]; }typedef stack; void push(stack *,char); char pop(stack*); void main() { stack my_stack; char pal; int i,flag; char data[MAX]="madam"; my_stack.top=-1; clrscr(); for(i=0;data[i]!='\0';i++) push(&my_stack,data[i]); for(i=0;i<=MAX-1;i++) { pal=pop(&my_stack); if(pal==-1) break; if(pal==data[i]) flag=1; else { flag=0; break; } } if(flag==1) { printf("palindrom"); } else { printf("not palin"); } getch(); } void push(stack *sp,char elem) { if(sp->top==MAX-1) { printf("stack is overflow"); return; } sp->top=sp->top+1; sp->data[sp->top]=elem; return; } char pop(stack *sp) { char pop; if(sp->top==-1) { printf("stack is underflow"); return -1; } else pop=sp->data[sp->top]; sp->top=sp->top-1; return pop; }
C
#include <stdio.h> #include <stdlib.h> #include <locale.h> int system(); struct produtos { char nome[20]; int quant_atual; int min_estoque; char validade[6]; }; typedef struct produtos produtos; void menu(); void limpar(); int tamanho_arquivo(); void entra_produto(produtos *produto); void lista_produto(produtos *produto); void pesquisa_produto(produtos *produto); void pesquisa_letra(produtos *produto); void pesquisa_data(produtos *produto); void lista_abaixo_min(produtos *produto); void altera_estoque(produtos *produto); void altera_produto(produtos *produto); void exclui_produto(produtos *produto); main() { setlocale(LC_ALL, "Portuguese"); produtos produto; char escolha; int i; for(;;) { system("cls"); menu(); escolha = getchar(); setbuf(stdin,NULL); switch(escolha) { case '1': { entra_produto(&produto); break; } case '2': { lista_produto(&produto); break; } case '3': { pesquisa_produto(&produto); break; } case '4': { pesquisa_letra(&produto); break; } case '5': { pesquisa_data(&produto); break; } case '6': { lista_abaixo_min(&produto); break; } case '7': { altera_estoque(&produto); break; } case '8': { altera_produto(&produto); break; } case '9': { exclui_produto(&produto); break; } case '0': { exit(0); } default: { printf("Opo invlida\n"); limpar(); break; } } } } void menu() { printf("\tDesafo 2\n"); printf("1. Entrada de produto\n"); printf("2. Lista todos os produtos\n"); printf("3. Pesquisa produto por nome\n"); printf("4. Pesquisa produto por letra\n"); printf("5. Lista produtos vencidos por data de validade\n"); printf("6. Lista produtos abaixo do estoque mnimo\n"); printf("7. Movimenta quantidade em estoque\n"); printf("8. Altera produto pesquisado por nome\n"); printf("9. Exclui produto pesquisado por nome\n"); printf("0. Sair\n"); } void limpar() { system("pause"); system("cls"); } int tamanho_arquivo() { FILE *p; int tamanho_struct = sizeof(produtos); long int posicao; p = fopen("C11.txt", "rb"); fseek(p, 0, 2); posicao = ftell(p); fclose(p); return (posicao/tamanho_struct); } void entra_produto(produtos *produto) { FILE *p; p = fopen("C11.txt","ab"); printf("Insira o nome do produto: "); gets(produto->nome); setbuf(stdin,NULL); printf("Insira a quantidade atual do produto: "); scanf("%d", &produto->quant_atual); setbuf(stdin,NULL); printf("Insira a quantidade mnima do produto: "); scanf("%d", &produto->min_estoque); setbuf(stdin,NULL); printf("Insira a data de validade(mm/aa): "); gets(produto->validade); setbuf(stdin,NULL); fwrite(produto,sizeof(*produto),1,p); fclose(p); limpar(); } void lista_produto(produtos *produto) { FILE *p; int i; p = fopen("C11.txt","rb"); for (i = 0; i < tamanho_arquivo(); i++) { fread(produto,sizeof(*produto),1,p); if (produto->nome[0] != '*') printf("Produto: %-19s Quantidade atual: %-6d Quantidade mnima: %-6d Validade: %-6s\n",produto->nome,produto->quant_atual,produto->min_estoque,produto->validade); } if (tamanho_arquivo() == 0) printf("Nenhum registro encontrado\n"); fclose(p); limpar(); } void pesquisa_produto(produtos *produto) { FILE *p; char nome[20]; int i, q, n, x = 0; p = fopen("C11.txt", "rb"); printf("Insira o nome a ser pesquisado: "); gets(nome); setbuf(stdin,NULL); for (i = 0; i < tamanho_arquivo(); i++) { fread(produto, sizeof(*produto), 1, p); q = 0; for (n = 0; n < 20; n++) { if (nome[n] == '\0' && produto->nome[n] == '\0' && q == n) { printf("Produto: %-19s Quantidade atual: %-6d Quantidade mnima: %-6d Validade: %-6s\n",produto->nome,produto->quant_atual,produto->min_estoque,produto->validade); x++; break; } if (nome[n] == produto->nome[n]) q++; } } if (tamanho_arquivo() == 0 || x == 0) printf("Nenhum registro encontrado\n"); fclose(p); limpar(); } void pesquisa_letra(produtos *produto) { FILE *p; char c; int i, x = 0; p = fopen("C11.txt", "rb"); printf("Insira a letra a ser pesquisada: "); c = getchar(); setbuf(stdin,NULL); for (i = 0; i < tamanho_arquivo(); i++) { fread(produto, sizeof(*produto), 1, p); if (c == produto->nome[0]) { printf("Produto: %-19s Quantidade atual: %-6d Quantidade mnima: %-6d Validade: %-6s\n",produto->nome,produto->quant_atual,produto->min_estoque,produto->validade); x++; } } if (tamanho_arquivo() == 0 || x == 0) printf("Nenhum registro encontrado\n"); fclose(p); limpar(); } void pesquisa_data(produtos *produto) { FILE *p; char data[6]; int i, n, x = 0, Idata, Iproduto; p = fopen("C11.txt", "rb"); printf("Insira a data atual(mm/aa): "); gets(data); Idata = data[3]*1000 + data[4]*100 + data[0]*10 + data[1]; setbuf(stdin,NULL); for (i = 0; i < tamanho_arquivo(); i++) { fread(produto, sizeof(*produto), 1, p); Iproduto = produto->validade[3]*1000 + produto->validade[4]*100 + produto->validade[0]*10 + produto->validade[1]; if (Iproduto <= Idata && produto->nome[0] != '*') { printf("Produto: %-19s Quantidade atual: %-6d Quantidade mnima: %-6d Validade: %-6s\n",produto->nome,produto->quant_atual,produto->min_estoque,produto->validade); x++; } } if (tamanho_arquivo() == 0 || x == 0) printf("Nenhum registro encontrado\n"); fclose(p); limpar(); } void lista_abaixo_min(produtos *produto) { FILE *p; int i, x = 0; p = fopen("C11.txt", "rb"); for (i = 0; i < tamanho_arquivo(); i++) { fread(produto, sizeof(*produto), 1, p); if (produto->min_estoque > produto->quant_atual && produto->nome[0] != '*') { printf("Produto: %-19s Quantidade atual: %-6d Quantidade mnima: %-6d Validade: %-6s\n",produto->nome,produto->quant_atual,produto->min_estoque,produto->validade); x++; } } if (tamanho_arquivo() == 0 || x == 0) printf("Nenhum registro encontrado\n"); fclose(p); limpar(); } void altera_estoque(produtos *produto) { FILE *p; char nome[20]; int i, q, n, x = 0; p = fopen("C11.txt", "rb+"); printf("Insira o nome a ser pesquisado: "); gets(nome); setbuf(stdin,NULL); for (i = 0; i < tamanho_arquivo(); i++) { fread(produto, sizeof(*produto), 1, p); q = 0; for (n = 0; n < 20; n++) { if (nome[n] == '\0' && produto->nome[n] == '\0' && q == n) { printf("Produto: %-19s Quantidade atual: %-6d Quantidade mnima: %-6d Validade: %-6s\n",produto->nome,produto->quant_atual,produto->min_estoque,produto->validade); x++; break; } if (nome[n] == produto->nome[n]) q++; } if (x != 0) break; } if (tamanho_arquivo() == 0 || x == 0) { printf("Nenhum registro encontrado\n"); fclose(p); limpar(); return; } printf("Insira a quantidade a ser adicionada(use nmero negativo para remover): "); scanf("%d", &x); produto->quant_atual += x; printf("Nova quantidade atual: %d\n", produto->quant_atual); fseek(p,sizeof(*produto)*i,0); fwrite(produto,sizeof(*produto),1,p); limpar(); fclose(p); } void altera_produto(produtos *produto) { FILE *p; char nome[20]; int i, q, n, x = 0; p = fopen("C11.txt", "rb+"); printf("Insira o nome a ser pesquisado: "); gets(nome); setbuf(stdin,NULL); for (i = 0; i < tamanho_arquivo(); i++) { fread(produto, sizeof(*produto), 1, p); q = 0; for (n = 0; n < 20; n++) { if (nome[n] == '\0' && produto->nome[n] == '\0' && q == n) { printf("Produto: %-19s Quantidade atual: %-6d Quantidade mnima: %-6d Validade: %-6s\n",produto->nome,produto->quant_atual,produto->min_estoque,produto->validade); x++; break; } if (nome[n] == produto->nome[n]) q++; } if (x != 0) break; } if (tamanho_arquivo() == 0 || x == 0) { printf("Nenhum registro encontrado\n"); fclose(p); limpar(); return; } printf("Insira o nome do produto: "); gets(produto->nome); setbuf(stdin,NULL); printf("Insira a quantidade atual do produto: "); scanf("%d", &produto->quant_atual); setbuf(stdin,NULL); printf("Insira a quantidade mnima do produto: "); scanf("%d", &produto->min_estoque); setbuf(stdin,NULL); printf("Insira a data de validade(mm/aa): "); gets(produto->validade); setbuf(stdin,NULL); fseek(p,sizeof(*produto)*i,0); fwrite(produto,sizeof(*produto),1,p); fclose(p); limpar(); } void exclui_produto(produtos *produto) { FILE *p; char nome[20]; char c; int i, q, n, x = 0; p = fopen("C11.txt", "rb+"); printf("Insira o nome a ser pesquisado: "); gets(nome); setbuf(stdin,NULL); for (i = 0; i < tamanho_arquivo(); i++) { fread(produto, sizeof(*produto), 1, p); q = 0; for (n = 0; n < 20; n++) { if (nome[n] == '\0' && produto->nome[n] == '\0' && q == n) { printf("Produto: %-19s Quantidade atual: %-6d Quantidade mnima: %-6d Validade: %-6s\n",produto->nome,produto->quant_atual,produto->min_estoque,produto->validade); x++; break; } if (nome[n] == produto->nome[n]) q++; } if (x != 0) break; } if (tamanho_arquivo() == 0 || x == 0) { printf("Nenhum registro encontrado\n"); fclose(p); limpar(); return; } printf("Deseja mesmo deletar esse produto(s/n)? "); c = getchar(); setbuf(stdin,NULL); if (c == 's' || c == 'S') { fseek(p,sizeof(*produto)*i,0); produto->nome[0] = '*'; fwrite(produto,sizeof(*produto),1,p); fclose(p); } limpar(); }
C
#include<stdio.h> #include<stdlib.h> void fill_mx(int row, int col, int (*buff)[col]){ for(int i=0; i<row; i++){ for(int j=0; j<col; j++){ scanf("%d", &buff[i][j]); } } } /* void fill_rec_rev(int row, int col, int (*buff)[col]){ if(row==0) return; for(int i=0; i<col; i++){ scanf("%d", &buff[row-1][i]); } fill_rec(row-1, col, buff); } void fill_rec(int r, int col, int (*buff)[col], int cmp){ if(r==cmp) return; for(int i=0; i<col; i++){ scanf("%d", &buff[r][i]); } fill_rec(r+1, col, buff, cmp); } */ void print_mx(int row, int col, int (*buff)[col]){ for(int i=0; i<row; i++){ for(int j=0; j<col; j++){ printf("%d ", buff[i][j]); } printf("\n"); } } /* void print_rec_mx_rev(int row, int col, int (*buff)[col]){ if(row==0) return; //printf("row=%d, col=%d", row, col); for(int i=0; i<col; i++){ printf("%d ", buff[row-1][i]); } printf("\n"); print_rec_mx(row-1, col, buff); } void print_rec_mx(int r, int col, int (*buff)[col], int row){ if(r==row) return; for(int i=0; i<col; i++){ printf("%d ", buff[r][i]); } printf("\n"); print_rec_mx(r+1, col, buff, row); } */ void print_diagonal_main_and_secondary(int row, int col, int (*buff)[col]){ printf("main diagonal:\n"); for(int i=0; i<row; i++){ for(int j=0; j<col; j++){ if(i==j){ printf("%d", buff[i][j]); } else{ printf(" "); } } printf("\n"); } printf("\nsecondary diagonal:\n"); for(int i=0; i<row; i++){ for(int j=0; j<col; j++){ if(i+j==row-1){ printf("%d", buff[i][j]); } else{ printf(" "); } } printf("\n"); } } void mult_mx1_and_mx2(int row1, int col1, int (*buff1)[col1], int row2, int col2, int (*buff2)[col2]){ int buff3[row1][col2]; for(int z=0; z<col2; z++){ for(int i=0; i<row1; i++){ int m=0; for(int j=0; j<col1; j++){//or j<row2 m+=buff1[i][j]*buff2[j][z]; } buff3[i][z]=m; } } print_mx(row1, col2, buff3); } int max_num(int row, int col, int (*buff)[col]){ int max=-1e9; for(int i=0; i<row; i++){ for(int j=0; j<col; j++){ if(buff[i][j]>max){ max=buff[i][j]; } } } return max; } int main(){ printf("FIRST MATRIX\n"); int row1, col1; printf("enter row_num: "); scanf("%d", &row1); printf("enter col_num: "); scanf("%d", &col1); int buff1[row1][col1]; //fill_rec(0, col, buff, row); fill_mx(row1, col1, buff1); //print_diagonal_main_and_secondary(row, col, buff); //print_mx(row, col, buff); //print_rec_mx_rev(row, col, buff); //print_rec_mx(0, col, buff, row); /* printf("SECOND MATRIX\n"); int row2, col2; printf("enter row_num: "); scanf("%d", &row2); printf("enter col_num: "); scanf("%d", &col2); int buff2[row2][col2]; fill_mx(row2, col2, buff2); if(col1==row2){ mult_mx1_and_mx2(row1, col1, buff1, row2, col2, buff2); } else{ printf("warning: not correct dimensions\n"); } */ int max=max_num(row1, col1, buff1); printf("max = %d\n", max); return 0; }
C
#include <ansi.h> int main(string str) { object obj; object wep; if(!str) { write("Repair which newbie's weapon?\n"); return 1; } if(!(obj = present(str, environment(this_player())))) { write("You don't see \""+str+"\" here.\n"); return 1; } if((int)obj->query_level() >= 8) { write(capitalize(str)+" is not a newbie.\n"+ "Level 7 and under please!\n"); return 1; } if(!(wep = (object)obj->query_weapon())) { write(capitalize(str)+" is not wielding a weapon.\n"); return 1; } if(!wep->query_broke()) { write(capitalize(str)+"'s weapon is not broken.\n"); return 1; } command("unwield "+(string)wep->query_name(), obj); wep->fix_weapon(); write("You have repaired "+(string)obj->query_name() +"'s "+(string)wep->query_short()+".\n"); tell_room(environment(obj), HIB+"Newbie Helper"+NORM+" "+ (string)this_player()->query_name()+" has repaired "+ (string)obj->query_name()+"'s "+(string)wep->query_short()+".\n", ({ obj, this_player() })); tell_object(obj, HIB+"Newbie Helper"+NORM+" "+ (string)this_player()->query_name()+" has repaired your "+ (string)wep->query_short()+".\n"); command("wield "+(string)wep->query_name(), obj); return 1; }
C
#include<stdio.h> #define damp 1 void main() { int n,i,j,k,outlink[10],iter; float pr[10],prNew[10]; int adj[10][10]; printf("Enter number of nodes:"); scanf("%d",&n); for(i=0;i<n;i++) { printf("Enter the number of outlinks for node %d: ",i); scanf("%d",&outlink[i]); } //Adjacency Matrix printf("\n----CREATING ADJACENCEY MATRIX----\n"); for(i=0;i<n;i++) for(j=0;j<n;j++) { printf("Link between %d and %d ?: ",i,j); scanf("%d",&adj[i][j]); } printf("\nAdjacency Matrix\n\n"); for(i=0;i<n;i++) { for(j=0;j<n;j++) printf("%d\t",adj[i][j]); printf("\n"); } for(i=0;i<n;i++) { pr[i] = 1/(float)n; prNew[i] = 0; } printf("\nEnter number of iterations required: "); scanf("%d",&iter); for(k=0;k<iter;k++)//iter { for(i=0;i<n;i++)//all nodes for(j=0;j<n;j++) if(adj[j][i] == 1) prNew[i] += ((1-damp) + (damp * (pr[j]/(float)outlink[j]))); } for(i=0;i<n;i++) printf("\nPage Rank of Node %d is %f",i,prNew[i]); }
C
/* Pseudocode for a MP3 record and playback using the specs required for question 2. * For ECEN 449 Assignment 3. * @Yinwei Zhang */ //assuming we're writing OS code mp3* recordMP3(int numBytes) { //assuming mp3 is the data struct we use to store sound mp3* sound = malloc(numBytes); int count = 0; while (numBytes != count) { if (R3 == 1) { //want to wait until the next time there's new data mp3[count] = R4; R3 = 0; count++; } } return sound; } mp3* playMP3(mp3* sound, int numBytes) { //numBytes is size int count = 0; while (numBytes != count) { if (R1 == 0) { mp3[count] = R2; R1 = 1; count++ } } return sound; }
C
#include <stdio.h> void stringAndPoint(){ char c = 'a'; printf("%c\n", c); // char s = "hello"; // printf("%s\n", s); // error and warning : why? 1bit만 저장가능하기 때문 char *s = "hello"; // hello 라는 문자열을 가르킨다 printf("%s\n", s); } void accessPoint(){ char *s = "hello"; printf("%c\n", s[0]); printf("%c\n", s[2]); printf("%c\n", s[5]); // null // s[2] = 'A'; // printf("%c\n", s[2]); // error!! why? 읽기전용이기 때문! 포인터형 문자열은 수정불가하다~ } void stringAndArr(){ char s[10] = "hello"; printf("%s\n", s); // char s2[10]; // s2 = "hello"; // wrong! 이미 선언된 것에 할당불가! // s2[0] = 'A'; // <- 이런식으로 할당하는 수 밖에 없다 } void accessArr(){ char s[10] = "hello"; printf("%c\n", s[0]); printf("%c\n", s[2]); printf("%c\n", s[5]); s[0] = 'H'; // 주의 "" 가 아니라 '' 이다! printf("%s\n", s); } int main(){ // stringAndPoint(); // accessPoint(); // stringAndArr(); accessArr(); return 0; }
C
/* output a string to a string, and return a pointer to the end of the string. */ #include <stdio.h> char *sputs (str, s) char *str, *s; { while (*s++ = *str++); return (--s); }
C
#include <stdio.h> #include <stdlib.h> void disp_rip(char *val, int pos, int *mark, char *sol, int N, int n); int checkSol(char *val,int *mark, char *sol, int N, int n); int main() { char val[5] = {'A','E','I','O','U'},*sol; int mark[5] = {0,0,0,0,0},N; printf("Inserisci N: "); scanf("%d", &N); sol=malloc(N*sizeof(char)); disp_rip(val,0,mark,sol,N,5); return 0; } void disp_rip(char *val, int pos, int *mark, char *sol, int N, int n){ int i; if(pos>=N){ if(checkSol(val,mark,sol,N,n)){ for(i=0; i<N;i++){ printf("%c ", sol[i]); } printf("\n"); } return; } for(i=0; i<n;i++){ sol[pos] = val[i]; disp_rip(val,pos+1,mark,sol,N,n); } return; } int checkSol(char *val,int *mark, char *sol, int N, int n){ int i,j,is_sol = 1; for(i=0;i<N;i++) for(j=0;j<n;j++) if(sol[i]==val[j] && i!=j) mark[j]++; for(i=0;i<n;i++) if(mark[i]==0) is_sol = 0; for(i=0; i<n; i++) mark[i] = 0; if(is_sol) return 1; return 0; }
C
#include "testing.h" void pop_test(void) { cpu_state_t state; int *test; int tests[][7] = { {0xfffc, 0x5f, 0xfffd, 0x3c, 0xfffe} }; for(uint32_t i = 0; i < sizeof(tests) / sizeof(*tests); i++) { test = tests[i]; state.sp = test[0]; cpu_store8(&state, test[0], test[1]); cpu_store8(&state, test[2], test[3]); REG_INPUT input = { .r16 = REG16_BC }; cpu_pop(&state, input); if(state.sp == test[4] && state.b == test[3] && state.c == test[1]) { printf("Tests passed.\n"); } else { printf("Tests failed.\n"); printf("0x%04x 0x%04x\n", state.bc, state.sp); } } }
C
/* * vec_mat.h * Header file for library of vector and matrix maths functions * * This file is part of esgmkt (OpenGL ES 2.0 Game Kit), * Copyright Matthew Livesey 2013 (matt.computes@gmail.com) * * This work is distributed under the BSD licence, a copy of which is * distributed with this work. * * esgmkt is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. */ #ifndef VEC_MAT #define VEC_MAT #include "types.h" typedef ft vec4[4]; typedef ft vec3[3]; /* *!! Need to be stored column major !! */ typedef vec4 mat4[4]; /* Vector functions */ void create_vec3(vec3 a, ft a1, ft a2, ft a3); void create_vec4(vec4 a, ft a1, ft a2, ft a3, ft a4); void add_vec3(vec3 a, vec3 b, /*return*/vec3 c); void add_vec4(vec4 a, vec4 b, /*return*/vec4 c); void mag_vec3(vec3 a, float* mag); void scale_vec3(vec3 a, float factor); void dotprod_vec3(vec3 a, vec3 b, ft* result); void crossprod_vec3(vec3 a, vec3 b, /*return*/vec3 c); void normalize_vec3(vec3 a); void copy_vec3(vec3 a, /*return*/vec3 b); void copy_vec4(vec4 a, /*return*/vec4 b); /* Matrix functions */ void create_mat4(/*return*/mat4 a, vec4 col0, vec4 col1, vec4 col2, vec4 col3); void getidentity_mat4(/*return*/mat4 a); void add_mat4(mat4 a, mat4 b, mat4 c); void copy_mat4(mat4 a, mat4 b); void mult_mat4(mat4 a, mat4 b, mat4 c); void mult_mat4vec4(mat4 a, vec4 b, vec4 c); #endif
C
#include <stdio.h> int main() { char ac[1005], bc[1005]; int a[1005], b[1005], add[1005]; int times, size, carry, div; int i, j, k; int ans, remainder; k = 1; scanf("%d", &times); while (k<=times) { scanf("%s", ac); scanf("%s", bc); scanf("%d", &div); i = 0; while (ac[i]!='\0') { a[i] = ac[i] - '0'; b[i] = bc[i] - '0'; i++; } size = i; carry = 0; for (i=0; i<size; i++) { add[i] = carry + a[size-i-1] + b[size-i-1]; carry = add[i] / 10; add[i]%=10; } if (carry>0) { size+=1; add[size-1] = carry; } remainder = add[size-1]; i = size - 1; ans = remainder / div; i-=1; /* eat the padding */ while (ans==0&&i>=0) { remainder = 10 * (remainder-ans*div) + add[i]; ans = remainder / div; i--; } printf("%d", ans); for ( ;i>=0; i--) { remainder = 10 * (remainder-ans*div) + add[i]; ans = remainder / div; printf("%d", ans); } printf("\n"); k++; } }
C
#include<stdio.h> #include<string.h> #include<stdlib.h> char num[32]; int value[32]; int change[10][10]; int node[10], factor, multilen; void DFS(int n) { int j; if(node[n]) return ; else { node[n] = 1; factor++; } for(j = 0; j <= 9; j++) if(change[n][j]) DFS(j); } void multiply() { int carry = 0; for(int i = 1; i <= multilen; i++) { value[i] = value[i] * factor + carry; carry = value[i] / 10; value[i] %= 10; } if(carry > 0) value[++multilen] = carry; } int main() { int k, i, j, length; while(scanf("%s%d", num, &k) != EOF) { value[0]=0; value[1]=1; multilen=1; memset(change, 0, sizeof(change)); while(k--) { scanf("%d%d", &i, &j); change[i][j] = 1; } length = strlen(num); for(i = 0; i < length; i++) { memset(node, 0, sizeof(node)); factor = 0; DFS(num[i] - '0'); multiply(); } for(i = multilen; i >= 1; i--) printf("%d", value[i]); printf("\n"); } return 0; }
C
#include<stdio.h> #include<stdlib.h> #include<errno.h> #include<unistd.h> #include<sys/stat.h> #include<sys/types.h> int count = 0; int frobcmp(const void *a, const void *b){ count++; char* aa = *(char **) a; char* bb = *(char **) b; int i; for (i = 0; aa[i] != ' ' && bb[i] != ' '; i++) { // unfrob_a = *(unsigned char *)a ^ 42; // unfrob_b = *(unsigned char *)b ^ 42; char unfrob_aa = aa[i] ^ 42; char unfrob_bb = bb[i] ^ 42; if (unfrob_aa != unfrob_bb) { return (unfrob_aa - unfrob_bb); } } if (aa[i] != ' ') return 1; if (bb[i] != ' ') return -1; return 0; } int main(void){ int array_size = 100; int string_size = 50; int array_i = 0; int char_i = 0; /* Retrieve file information */ struct stat st; if (fstat(0,&st) < 0) { fprintf(stderr, "Fail to retrive file information."); exit(1); } if (ferror(stdin)) { fprintf(stderr, "Fail to read from standard input."); exit(1); } /* Check if file is regular, and determine the size */ if (S_ISREG(st.st_mode) && st.st_size > 0) { array_size = st.st_size + 1; } /* Allocate 1st dimension space */ char** ptr = (char**)malloc(array_size * sizeof(char*)); if (ptr == NULL) { fprintf(stderr, "Fail to allocate memory."); exit(1); } /* Allocate 2nd dimension space */ ptr[array_i] = (char*)malloc(string_size*sizeof(char)); if (ptr[array_i] == NULL) { fprintf(stderr, "Fail to allocate memory."); exit(1); } /* Read */ char c; while (read(0, &c, 1) > 0){ ptr[array_i][char_i] = c; if (ferror(stdin)) { fprintf(stderr, "Fail to read from input."); exit(1); } /* end of a word */ if (c == ' ') { array_i++; /* reallocate array */ if (array_i >= array_size) { array_size *= 2; ptr = (char **)realloc(ptr, array_size*sizeof(char*)); if (ptr == NULL) { fprintf(stderr, "Fail to reallocate memory."); exit(1); } } char_i = 0; /* allocate space for next word */ ptr[array_i] = (char*)malloc(string_size*sizeof(char)); if (ptr[array_i] == NULL) { fprintf(stderr, "Fail to allocate memory."); exit(1); } } /* continue reading from word */ else if (c != ' ') { char_i++; if (char_i >= string_size) { string_size *= 2; ptr[array_i] = (char *)realloc(ptr[array_i],string_size*sizeof(char)); } } } /* Append a space at the end if needed. */ if (char_i > 0 && ptr[array_i][char_i-1] != ' ') { ptr[array_i][char_i] = ' '; } /* Sort recorded array of words */ qsort(ptr, (size_t)(array_i+1), (size_t)sizeof(char*), frobcmp); /* Write sorted words */ int i,j; for (i = 0; i < array_i+1; i++) { for (j = 0; j < string_size; j++) { write(1, &ptr[i][j], 1); if (ferror(stdout)) { fprintf(stderr, "Fail to write to output."); exit(1); } if (ptr[i][j] == ' ') { break; } } } /* Free allocated space */ for (i = 0; i < array_i+1; i++) { free(ptr[i]); } free(ptr); fprintf(stderr, "Comparisons: %d\n", count); return 0; }
C
/* * Wrapper function to load a DLL out of c:\windows\system32 without * going through the full DLL search path. (Hence no attack is * possible by placing a substitute DLL earlier on that path.) */ #include "putty.h" HMODULE load_system32_dll(const char *libname) { /* * Wrapper function to load a DLL out of c:\windows\system32 * without going through the full DLL search path. (Hence no * attack is possible by placing a substitute DLL earlier on that * path.) */ static char *sysdir = NULL; static size_t sysdirsize = 0; char *fullpath; HMODULE ret; if (!sysdir) { size_t len; while ((len = GetSystemDirectory(sysdir, sysdirsize)) >= sysdirsize) sgrowarray(sysdir, sysdirsize, len); } fullpath = dupcat(sysdir, "\\", libname); ret = LoadLibrary(fullpath); sfree(fullpath); return ret; }
C
#include "serial_binary_sort.h" #include <string.h> #include <stdio.h> static int binary_search(int arr[], size_t start, size_t stop, int value); void serial_binary_sort(int arr[], size_t size) { int i; for(i = 1; i < size; ++i) { int value = arr[i]; int insert_loc = binary_search(arr, 0, i, value); if(insert_loc < i) { memmove(arr + insert_loc + 1, arr + insert_loc, (i - insert_loc) * sizeof(int)); } arr[insert_loc] = value; } } int binary_search(int arr[], size_t start, size_t stop, int value) { size_t middle = start + (stop - start)/2; if((stop - start) <= 1) { //Base case return (value > arr[start]) ? (start + 1) : start; } if(value < arr[middle]) { //Recursively search through lower half return binary_search(arr, start, middle, value); } else { //Recursively search through upper half return binary_search(arr, middle, stop, value); } }
C
/***************** AUTHORS: Steve Patterson, Ethan Johnson CLASS: COMP 340 DATE: 4/30/13 DESCRIPTION: Monitors system memory usage and notifies the user when it passes a defined threshold (75% by default). COMPILE: "gcc -o task3 task3.c -std=gnu99" RUN: "./task3" *****************/ #include <sys/types.h> #include <sys/wait.h> #include <unistd.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <stdbool.h> #define MEM_THRESHOLD 0.75f // fraction of system memory usage we want to watch for #define CHECK_FREQUENCY 1 // number of seconds to wait between checking system memory usage // Check periodically to see if system memory usage exceeds a defined threshold; when it goes over that threshold, print a message to the console reflecting this. int main() { printf("Monitoring memory usage; press Ctrl-C to quit.\n"); bool previouslyOverThreshold = false; // Main loop - continue running until the user presses Ctrl-C while(true) { //// Read from /proc/meminfo to determine system memory usage FILE *meminfo = fopen("/proc/meminfo", "r"); // open /proc/meminfo for reading size_t lineLength = 0; char *memTotalLine = (char*)0; char *memFreeLine = (char*)0; // Read the first two lines (MemTotal and MemFree) int result1 = getline(&memTotalLine, &lineLength, meminfo); int result2 = getline(&memFreeLine, &lineLength, meminfo); if(result1 == -1 || result2 == -1 || ferror(meminfo)) { fprintf(stderr, "Error while reading from /proc/meminfo!\n"); // Sleep for CHECK_FREQUENCY seconds and proceed to the next check (the error might be a transient condition, so we don't want to quit) sleep(CHECK_FREQUENCY); continue; } // Parse the total/free memory values from the lines int memTotal, memFree; result1 = result2 = -1; result1 = sscanf(memTotalLine, "MemTotal: %d kB", &memTotal); result2 = sscanf(memFreeLine, "MemFree: %d kB", &memFree); if(result1 != 1 || result2 != 1) { fprintf(stderr, "Error: failed to parse MemTotal and MemFree from /proc/meminfo contents!\n"); free(memTotalLine); free(memFreeLine); fclose(meminfo); // Sleep for CHECK_FREQUENCY seconds and proceed to the next check (the error might be a transient condition, so we don't want to quit) sleep(CHECK_FREQUENCY); continue; } free(memTotalLine); free(memFreeLine); fclose(meminfo); // If system memory usage is over MEM_THRESHOLD%, and this wasn't the case on the last iteration, print a message to the console float memFreePct = (float)memFree / (float)memTotal; if(memFreePct < 1.0f - MEM_THRESHOLD) // threshold exceeded { if(!previouslyOverThreshold) { printf("Memory usage exceeded threshold (%f%%): %f\n", 100*MEM_THRESHOLD, 100*(1.0f - memFreePct)); previouslyOverThreshold = true; } } else previouslyOverThreshold = false; // Sleep for CHECK_FREQUENCY seconds before checking again sleep(CHECK_FREQUENCY); } return 0; }
C
/* * MetaCall Embedding NodeJS Example by Parra Studios * An example of embedding NodeJS into C/C++. * * Copyright (C) 2016 - 2020 Vicente Eduardo Ferrer Garcia <vic798@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include <metacall/metacall.h> #include <stdio.h> static int cleanup(int code) { if (metacall_destroy() != 0) { return code != 0 ? -code : -255; } return code; } int sum(double a, double b) { // Parameters to be passed to the sum function void * args[] = { metacall_value_create_double(a), metacall_value_create_double(b) }; void * ret = NULL; // Call to sum function ret = metacallv("sum", args); // Clean up arguments for (size_t it = 0; it < sizeof(args) / sizeof(args[0]); ++it) { metacall_value_destroy(args[it]); } if (ret == NULL) { return 1; } printf("Function sum returned: %f\n", metacall_value_to_double(ret)); // Clean up return value metacall_value_destroy(ret); return 0; } int main(int argc, char *argv[]) { struct metacall_log_stdio_type log_stdio = { stdout }; printf(metacall_print_info()); // Define log stream if (metacall_log(METACALL_LOG_STDIO, (void *)&log_stdio) != 0) { return cleanup(1); } // Initialize MetaCall if (metacall_initialize() != 0) { return cleanup(2); } // NodeJS { // Array of scripts to be loaded by MetaCall const char * js_scripts[] = { "script.js" }; // Load scripts if (metacall_load_from_file("node", js_scripts, sizeof(js_scripts) / sizeof(js_scripts[0]), NULL) != 0) { return cleanup(3); } // Execute sum function if (sum(3, 4) != 0) { return cleanup(4); } } return cleanup(0); }
C
#include <stdio.h> int main() { int n, i; int sum = 0; int step_count[51]={0}; scanf("%d", &n); step_count[2] = 1; step_count[3] = 1; for (i = 3; i <= n; i++) { step_count[i] = step_count[i - 2] + step_count[i - 3]; sum += step_count[i - 3]; } if (n == 0 || n == 1) printf("0"); else printf("%d", sum + 1); return 0; }
C
#include <stdlib.h> #include <stdio.h> #include "lfsr.h" int main(int argc,char** argv){ if(argc < 4){ printf("usage: lfsr_encrypt seed tap message [outfile]\n"); return 1; } FILE* dest = 0; if(argc == 5){ dest = fopen(argv[4],"w"); if(!dest){ printf("Error: Could not open file: %s\n",argv[4]); exit(1); } } BYTE seed = (BYTE)atoi(argv[1]); BYTE tap = (BYTE)atoi(argv[2]); char c; int i = 0; while((c=argv[3][i++])!=0){ seed = advance(seed,tap); if(dest){ fputc(seed^(BYTE)c,dest); } //printf("Seed: 0x%x\tEncrypted: 0x%x\n",seed,seed^(BYTE)c); } printf("Done.... Encrypted %d chars\n",i); if(dest){ fclose(dest); } return 0; }
C
#include<stdio.h> #include<stdlib.h> #include<string.h> int num; int stack[20]; int pos; int isPal(int base){ static int digit[66]; int n = num; int len = 0; int i; while(n){ digit[len++] = n % base; n /= base; } i = 0, len --; while(i < len){ if(digit[i] != digit[len]){ return 0; } i ++, len--; } return 1; } void fun(){ int i; pos = 0; for(i=2; i<= 16;i++){ if(isPal(i)){ stack[pos ++] = i; } } if(pos ==0){ printf("Number %d is not a palindrom\n",num); return; } printf("Number %d is palindrom in basis", num); for(i=0;i<pos;i++){ printf(" %d", stack[i]); } printf("\n"); } int main(){ scanf("%d", &num); while(num){ fun(); scanf("%d", &num); } return 0; }
C
#include <detpic32.h> void putc(char); void send2display(unsigned char); static const unsigned char val[] = {0x77,0x41,0x3b,0x6b,0x4d,0x6e,0x7e,0x43,0x7f,0x6f,0x5f,0x7c,0x36,0x79,0x3e,0x1e}; unsigned char v = 0x0; unsigned int show = 1; int main(void){ // Digital ports configuration TRISE = TRISE | 0xF0; // RE7-4 configured as input TRISB = TRISB & 0xFC00; // RB9-0 configured as output // UART1 configuration U1BRG = ((PBCLK +8*115200)/(16*115200))-1; // 115200 baudrate U1MODEbits.PDSEL = 0; // 8 bits, no parity U1MODEbits.STSEL = 0; // 1 stop bit U1STAbits.URXEN = 1; // Receiver enable U1STAbits.URXISEL = 0; // Receiver interrupt mode IEC0bits.U1RXIE = 1; // Enable receiver interrupts IPC6bits.U1IP = 4; // Receiver interrupt priority IFS0bits.U1RXIF = 0; // Reset receiver interrupt flag U1MODEbits.ON = 1; // Enable UART // Timer 3 configuration T3CONbits.TCKPS = 7; // 1:256 prescaler PR3 = PBCLK/256/2-1; // 2Hz frequency TMR3 = 0; // Reset T3 counter register IEC0bits.T3IE = 1; // Enable T3 interrupts IPC3bits.T3IP = 5; // T3 interrupt priority IFS0bits.T3IF = 0; // Reset T3 interupt flag T3CONbits.TON = 1; // Enable T3 EnableInterrupts(); // Global interrupt enable while(1); return 0; } void putc(char c){ while(U1STAbits.UTXBF); // Wait while transmitter buffer full U1TXREG = c; // Copy char to transmitter register } void send2display(unsigned char value){ static int changeFlag = 0; LATBbits.LATB9 = 0; LATBbits.LATB8 = 0; LATB = LATB & 0xFF00; if(show || changeFlag){ LATBbits.LATB9 = 1; LATB |= val[value]; } changeFlag = !changeFlag; } void _int_(_UART_1_VECTOR) isr_uart1(void){ if(IFS0bits.U1RXIF){ char reg = U1RXREG; if(reg == 'p'){ show = !show; // Toggle show flag }else{ unsigned char c = (reg+((PORTE & 0xF0) >> 4)) % 16; v = c; // Update value c = c > 0x9 ? 'A'+(c - 0xA) : '0'+ c ; // Convert RE7-4 to hexadecimal char putc(c); // Send RE7-4 to serial port putc('\n'); } IFS0bits.U1RXIF = 0; // Reset receiver interrupt flag } } void _int_(_TIMER_3_VECTOR) isr_t3(void){ send2display(v); // Send value to display IFS0bits.T3IF = 0; // Reset T3 interupt flag }
C
/** * @file signdict.h * @brief SignDict interface. * **/ #ifndef __SIGNDICT_H_ #define __SIGNDICT_H_ #include <ul_def.h> #include <stdio.h> struct SignDict; typedef struct SignDict SignDict_t; const int SIGNDICT_OK = 0; const int SIGNDICT_FAIL = -1; const int SIGNDICT_ERR_DUPLICATE_KEY = -2; const int SIGNDICT_ERR_DISORDERED_KEY = -3; const int SIGNDICT_ERR_DICT_FULL = -4; const int SIGNDICT_ERR_NOT_FOUND = -2; /** * @brief Create a new SignDict instance. * * @param size num of entries in dict. should be greater than zero. * @param prefix_width bytes of prefix used as index. should be in [0, 3]. * Pass in 0 to let itself work out the optimal value. * @param value_width bytes of value. Current implementation supports up to 1024 bytes. * * @return * @li pointer to a new SignDict instance if success * @li @c NULL if failed (memory allocation failed, invalid arguments, etc.) **/ SignDict_t* signdict_new(u_int size, u_int prefix_width, u_int value_width); /** * @brief Delete SignDict instance and deallocated memory. * * @param dict SignDict instance to be deleted. * * @return * @li @c SIGNDICT_OK if success * @li @c SIGNDICT_FAIL if failed **/ int signdict_delete(SignDict_t *dict); /** * @brief Get value width of SignDict. * * @param dict pointer to SignDict instance. * * @return * @li value width of dict if success * @li @c SIGNDICT_FAIL if failed **/ u_int signdict_value_width(const SignDict_t *dict); /** * @brief Get dict size of SignDict. * * @param dict pointer to sSignDict instance. * * @return * @li size of dict if success * @li @c SIGNDICT_FAIL if failed **/ u_int signdict_size(const SignDict_t *dict); /** * @brief Insert one a dict entry into SignDict. The @c sign[2] is key of the entry. * @c dict->value_width_ bytes in @c value_buf is copied into dict. * * @param dict pointer to SignDict instance. * @param sign[2] 64bit sign of key. * @param value_buf pointer to value buffer. * * @return * @li @c SIGNDICT_OK on success * @li @c SIGNDICT_FAIL on general failure * @li @c SIGNDICT_ERR_DUPLICATE_KEY on key duplicated * @li @c SIGNDICT_ERR_DISORDERED_KEY on key disordered * @li @c SIGNDICT_ERR_DICT_FULL on dict is full * * @note The key @b MUST be greater than last inserted key, i.e. dict entries * should be in ascending order of key. * @note Caller should guarantee that the @c value_buf is at least as long as @c * dict->value_width_. * * @attention No thread-safety guaranteed! @b NEVER attempt to build SignDict * within a multi-threading context. **/ int signdict_insert_one(SignDict_t *dict, const u_int sign[2], const u_char *value_buf); /** * @brief Insert all dict entries into SignDict at a time. * * @param dict pointer to SignDict instance. * @param signs signs of dict entries that stored in sequence. * @param values fix-width values stored in sequnce. * @param count number of dict entries. * * @return * @li @c SIGNDICT_OK on success * @li @c SIGNDICT_FAIL on general failure * @li @c SIGNDICT_ERR_DUPLICATE_KEY on key duplicated * @li @c SIGNDICT_ERR_DISORDERED_KEY on key disordered * @li @c SIGNDICT_ERR_DICT_FULL on dict is full * * @note The key @b MUST be greater than last inserted key, i.e. dict entries * should be in ascending order of key. * @note Caller should guarantee that the @c value_buf is at least as long as @c * dict->value_width_. * * @attention No thread-safety guaranteed! @b NEVER attempt to build SignDict * within a multi-threading context. **/ int signdict_insert_batch(SignDict_t *dict, const u_int *signs, const u_char *values, u_int count); /** * @brief Finalize insertion of dict entries. Should be called after all entries * are inserted. No entry is allowed to be added any more. * * @param dict pointer to SignDict instance. * * @return * @li @c SIGNDICT_OK on success * @li @c SIGNDICT_FAIL on failure **/ int signdict_finalize_insertion(SignDict_t *dict); /** * @brief Search in Signdict for an dict entry given the sign of key. If found, * the value is copied into @c value_buf. * * @param dict pointer to SignDict instance. * @param sign[2] key of sign. * @param value_buf[out] buffer to store found value. * * @return * @li @c SIGNDICT_OK on success * @li @c SIGNDICT_FAIL on general failure * @li @c SIGNDICT_ERR_NOT_FOUND on key not found * * @note Caller should guarantee that the @c value_buf is at least as long as @c dict->value_width_ * @note This function is reentrant and is safe to use in multi-threading contexts. **/ int signdict_search(const SignDict_t *dict, const u_int sign[2], u_char *value_buf); /** * @brief Dump SignDict to binary file. * * @param dict pointer to SignDict instance. * @param fp pointer of file to dump to. * * @return * @li @c SIGNDICT_OK on success * @li @c SIGNDICT_FAIL on failure **/ int signdict_dump(const SignDict_t *dict, FILE *fp); /** * @brief Load SignDict from binary file. * * @param fp pointer of file to load from. * * @return * @li pointer to SignDict instance on success * @li @c NULL on failure **/ SignDict_t* signdict_load(FILE *fp); /** * @brief Decide if two SignDict instance is equal. * * @param lhs lhs SignDict instance. * @param rhs rhs SignDict instance. * * @return * @li @c 0 if two SignDict instance is equal * @li @c -1 if is not equal * * @note two SignDict is equal only if: @n * 1. both pointers point to the same SignDict instance. @n * 2. both pointers point to valid SignDict instance and all members equals to each other. **/ int signdict_is_equal(const SignDict_t *lhs, const SignDict_t *rhs); #endif //__SIGNDICT_H_ /* vim: set expandtab ts=4 sw=4 sts=4 tw=100: */
C
#include <stdio.h> #include <math.h> #include <stdint.h> #include <time.h> int main(){ //uint16_t myNumber = 3; //printf("%d\n", myNumber); //printf("%f\n", sqrt(myNumber)); //printf("%f\n", sin(myNumber)); //printf("%f\n", cos(myNumber)); //printf("%f\n", exp(myNumber)); //printf("%f\n", pow(myNumber, myNumber)); time_t myTime; time_t otherTime; myTime = time(NULL); printf("%u\n", myTime); for(int i = 0; i < 10000; i++){ printf("%d\n", i); } otherTime = time(NULL); printf("%u\n", otherTime - myTime); }
C
// // catalan.c // Step1 // // Created by GiPyeong Lee on 2015. 1. 8.. // Copyright (c) 2015년 com.devsfolder.jsonToSQL. All rights reserved. // #include <stdio.h> #include <stdlib.h> typedef struct StackNode{ int data; struct StackNode *nextStackNode; }StackNode; typedef struct Stack{ StackNode *list; StackNode *top; }Stack; // 스택 노드 생성 StackNode *createStackNode(int inputData){ StackNode *node = (StackNode *)malloc(sizeof(StackNode)); node->data = inputData; node->nextStackNode = NULL; return node; } // 노드 삽입 void pushNode(Stack* stack,StackNode* node){ if(stack->list==NULL){ stack->list = node; }else{ stack->top->nextStackNode = node; } stack->top = node; } // 노드 팝 StackNode* popNode(Stack* stack){ StackNode *node = stack->top; if(stack->list==stack->top){ stack->list=NULL; stack->top= NULL; }else{ StackNode* oldTopNode = stack->list; while(oldTopNode->nextStackNode!=stack->top){ oldTopNode = oldTopNode->nextStackNode; } stack->top = oldTopNode; oldTopNode->nextStackNode = NULL; } return node; } void createStack(Stack **stack){ (*stack) = (Stack*)malloc(sizeof(Stack)); (*stack)->list = NULL; (*stack)->list = NULL; } int main(void){ Stack *stack; createStack(&stack); Stack *goalStack; createStack(&goalStack); fflush(stdin); int i,input; scanf("%d",&input); int size = input; int *intArray = (int *)malloc(sizeof(int)*input); for(i=0; i < size; i++){ scanf("%d", &intArray[i]); } int index=size; while(index-->0){ int data = intArray[index]; if(data<size){ pushNode(stack,createStackNode(data)); }else{ size = size-1; while(stack->top!=NULL&&size==stack->top->data){ popNode(stack); size = size-1; } } } printf("%s",(size==0)?"YES":"NO"); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <errno.h> #include <string.h> #include <fcntl.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <stdint.h> #include <signal.h> #define FIFO_NAME "myfifo" #define BUFFER_SIZE 300 #define MESGUSR1 "SIGN:1 " #define MESGUSR2 "SIGN:2 " char outputBuffer[BUFFER_SIZE]; uint32_t bytesWrote; int32_t fd; void user1(int sig) { if ((bytesWrote = write(fd, MESGUSR1, strlen(MESGUSR1)-1)) == -1) { perror("write"); } else { printf("writer: wrote %d bytes\n", bytesWrote); } } void user2(int sig) { if ((bytesWrote = write(fd, MESGUSR2, strlen(MESGUSR2)-1)) == -1) { perror("write"); } else { printf("writer: wrote %d bytes\n", bytesWrote); } } int main(void) { //Configuración de receptores de señales del sistema struct sigaction sa; sa.sa_handler = user1; sa.sa_flags = 0; // SA_RESTART; // sigemptyset(&sa.sa_mask); sigaction(SIGUSR1,&sa,NULL); struct sigaction se; se.sa_handler = user2; se.sa_flags = 0; // SA_RESTART; // sigemptyset(&se.sa_mask); sigaction(SIGUSR2,&se,NULL); char outputBufferAux[BUFFER_SIZE]; int32_t returnCode; /* Create named fifo. -1 means already exists so no action if already exists */ if ( (returnCode = mknod(FIFO_NAME, S_IFIFO | 0666, 0) ) < -1 ) { printf("Error creating named fifo: %d\n", returnCode); exit(1); } /* Open named fifo. Blocks until other process opens it */ printf("waiting for readers...\n"); if ( (fd = open(FIFO_NAME, O_WRONLY) ) < 0 ) { printf("Error opening named fifo file: %d\n", fd); exit(1); } /* open syscalls returned without error -> other process attached to named fifo */ printf("got a reader--type some stuff\n"); /* Loop forever */ while (1) { /* Get some text from console */ if(NULL!=(fgets(outputBufferAux, BUFFER_SIZE, stdin))) { sprintf(outputBuffer,"DATA:%s",outputBufferAux); /* Write buffer to named fifo. Strlen - 1 to avoid sending \n char */ if ((bytesWrote = write(fd, outputBuffer, strlen(outputBuffer)-1)) == -1) { perror("write"); } else { printf("writer: wrote %d bytes\n", bytesWrote); } } } //close named fifo close(fd); return 0; }
C
#include <stdio.h> #include <wordexp.h> void test(const char *s, int flags) { wordexp_t p; size_t i; wordexp(s, &p, flags); printf("%s ->\n", s); for (i = 0; i < p.we_wordc; i++) { printf("\t%s\n", p.we_wordv[i]); } wordfree(&p); printf("\n"); } int main(void) { test("~", 0); test("~root", 0); test("$HOME", 0); test("$PATH", 0); test("#abc", 0); test("/home/*", 0); test("/etc/\?\?\?\?\?\?/", 0); return 0; }
C
/* ** replace_alias.c for replace in /home/said_p/Work/PSU_2015_42sh/srcs/alias ** ** Made by pierre said ** Login <said_p@epitech.net> ** ** Started on Sun Jun 5 01:11:57 2016 pierre said ** Last update Sun Jun 5 09:01:49 2016 pierre said */ #include <stdio.h> #include <string.h> #include <stdlib.h> #include "kala.h" #include "utils.h" static char *get_first(char *str, int *cut) { char *first; int i; t_bool quote; i = 0; quote = FALSE; if ((first = malloc(sizeof(char) * (strlen(str) + 1))) == NULL) return (NULL); while (str[i] && ((str[i] != ' ' && str[i] != '\t') || quote == TRUE)) { if (str[i] == '\"') quote = (quote == TRUE) ? FALSE : TRUE; first[i] = str[i]; i = i + 1; } first[i] = '\0'; *cut = i; return (first); } static int rep_lex_str(t_lexem **lex, char *str, int cutted) { if (cut((*lex)->str, 0, cutted) == -1 || ((*lex)->str = insert((*lex)->str, 0, str)) == NULL) return (FALSE); return (TRUE); } static int loop_detect(char *first, t_alias *last, t_alias *tmp) { free(first); if (last != NULL && last == tmp) return (CONTINUE); return (3); } int replace_alias(t_lexem **lex, t_alias *alias, t_alias **replaced, t_alias *last) { t_alias *tmp; char *first; int cut; tmp = alias; if ((first = get_first((*lex)->str, &cut)) == NULL) return (FALSE); while (tmp) { if (strcmp(tmp->alias, first) == 0) { if (tmp->replaced == TRUE) return (loop_detect(first, last, tmp)); *replaced = tmp; tmp->replaced = TRUE; free(first); if ((first = strdup(tmp->input)) == NULL || rep_lex_str(lex, first, cut) == FALSE) return (FALSE); return (TRUE); } tmp = tmp->next; } free(first); return (CONTINUE); }
C
/************************* * Vaibhav Kashyap * * 2012A3PS143P * *************************/ #include <sys/types.h> #include <unistd.h> #include <sys/wait.h> #include <stdio.h> #include <stdlib.h> #include <errno.h> int main() { int n; printf("Enter n\n"); scanf("%d",&n); if(n==0) { printf("N cannot be 0. Enter another no.\n"); scanf("%d",&n); } printf("********* Master pid %d *********\n",getpid()); printf("Position pid \t ppid \t Level dots \n"); create_node(n,n,1);//calling recursive node creating function printf("********* All Children Executed *********\n"); return 0; } create_node(int k,int n,int pos) { int status,i,j;pid_t pid;//initialization if(k!=1) //recursive cases { for(i=1;i<=k;i++)//creates k no. of nodes wher each have k-1 childs. { if((pid=fork())<0) perror ("fork"); else if(pid==0)//child process goes futher to create more nodes(acts both like parent and child). { create_node(k-1,n,1); printf("%d \t %d \t %d \t %d \t",pos,(int)getpid(),(int)getppid(),n+1-k); //recursive case child prints AFTER creation of smaller nodes(based on no. of child processes), then prints and exits. for(j=1;j<=pos;j++) printf("."); // level is calculated by no.of children in node i.e k; position is calculated with no. of similar nodes. printf("\n"); exit(0); } else { wait(&status); //parent behaviour of node is to wait for child processes to get over. pos++; //after each child process next child's position is incremented. if(i==k) //all parallel nodes have been created. return ; } } } else //base case where k=1 { if((pid=fork())<0) perror ("fork"); else if(pid==0) //base case child directly exits after printing. { printf("%d \t %d \t %d \t %d \t.\n",1,(int)getpid(),(int)getppid(),n); exit(0); } else { wait(&status); //base case parent waits for child to finish then returns. return; } } }
C
#include "../inc/minilibmx.h" void mx_printint(int n) { int count = 0, num, f = n; char a = '0'; if (n < 0) { a = '-'; n = n * (-1); mx_printchar(a); } if (n == 0) count = 1; while (f != 0){ count++; f = f / 10; } long int t; for (int index = count; index > 0; index--) { t = 1; for (int in = 1; in < index; in++) { t *= 10; } num = (n / t) + 48; n -= (n / t) * t; mx_printchar(num); } }
C
#include "matrix.h" void transform_vector(t_matrix3x3 matrix, t_vector3 vector, t_vector3 result) { int i; int k; i = 0; while (i < 3) result[i++] = 0; i = 0; while (i < 3) { k = 0; while (k < 3) { result[i] += matrix[i][k] * vector[k]; k++; } i++; } }
C
#include <u.h> #include <libc.h> #include <draw.h> #include <event.h> #include "game.h" /* Traditional dimensions in tenth of mm */ enum{ Gobanw = 4242, Gobanh = 4545, Line = 10, Linew = 220, Lineh = 237, Hoshidiam = 40, Stonediam = 225 }; enum{ DGoban = 0xD79C5EFF }; static Point ogoban; /* Origin of the lines of the goban. */ static double scale; int drawgoban(void) { int i, j; int l, hr, sr; char s[Maxgobansize]; /* Just need a length */ int hoshi[3]; Point o; Point p, q; Rectangle r; Point poly[4]; Image *bg; Font *font; o = screen->r.min; if(Dx(screen->r) * Gobanh < Dy(screen->r) * Gobanw){ scale = (double)Dx(screen->r) / Gobanw; }else{ scale = (double)Dy(screen->r) / Gobanh; } /* The line function uses 1 + 2 * width as its thickness. */ l = (Line * scale - 1) / 2; /* Fill goban background. */ p = Pt(o.x + (int)(scale * Gobanw), o.y + (int)(scale * Gobanh)); r = Rpt(o, p); poly[0] = r.min; poly[1] = Pt(r.max.x, r.min.y); poly[2] = r.max; poly[3] = Pt(r.min.x, r.max.y); bg = allocimage(display, Rect(0, 0, 1, 1), RGB24, 1, DGoban); fillpoly(screen, poly, 4, ~0, bg, ZP); freeimage(bg); /* Draw lines. */ ogoban = Pt(o.x + scale * (Gobanw - (sgoban - 1) * Linew) / 2, o.y + scale * (Gobanh - (sgoban - 1) * Lineh) / 2); for(i = 0; i < sgoban; i++){ p = Pt(ogoban.x + (int)(i * scale * Linew), ogoban.y); q = Pt(ogoban.x + (int)(i * scale * Linew), ogoban.y + (int)(scale * (sgoban - 1) * Lineh)); line(screen, p, q, Enddisc, Enddisc, l / 2, display->black, ZP); p = Pt(ogoban.x, ogoban.y + (int)(i * scale * Lineh)); q = Pt(ogoban.x + (int)(scale * (sgoban - 1) * Linew), ogoban.y + (int)(i * scale * Lineh)); line(screen, p, q, Enddisc, Enddisc, l / 2, display->black, ZP); } /* Draw hoshi; only meaningful for 19x19, 13x13 and 9x9. */ hr = scale * Hoshidiam / 2; switch(sgoban){ case 19: hoshi[0] = 3; hoshi[1] = 9; hoshi[2] = 15; break; case 13: hoshi[0] = 3; hoshi[1] = 6; hoshi[2] = 9; break; case 9: hoshi[0] = 2; hoshi[1] = 4; hoshi[2] = 6; break; default: hoshi[0] = 0; } for(i = 0; i < 3 && hoshi[0] != 0; i++){ for(j = 0; j < 3; j++){ p = Pt(ogoban.x + (int)(hoshi[i] * scale * Linew), ogoban.y + (int)(hoshi[j] * scale * Lineh)); fillellipse(screen, p, hr, hr, display->black, ZP); } } /* Draw stones. */ sr = scale * Stonediam / 2; for(i = 0; i < sgoban * sgoban; i++){ switch(goban[i]){ case Black: p = Pt(ogoban.x + i % sgoban * scale * Linew, ogoban.y + i / sgoban * scale * Lineh); fillellipse(screen, p, sr, sr, display->black, ZP); break; case White: p = Pt(ogoban.x + i % sgoban * scale * Linew, ogoban.y + i / sgoban * scale * Lineh); ellipse(screen, p, sr, sr, 0, display->black, ZP); fillellipse(screen, p, sr-1, sr-1, display->white, ZP); break; } } /* Draw text: turn, prisonners, later on byo-yomi & time. */ if((font = openfont(display, "/lib/font/bit/dejavu/unicode.18.font")) == nil){ werrstr("Could not open font."); return -1; } p = addpt(o, Pt(ogoban.x - o.x, scale * (Gobanh + Lineh))); sprint(s, "To play: %s", turn == Black ? "Black " : "White "); stringbg(screen, p, display->black, ZP, font, s, display->white, ZP); p = addpt(p, Pt(0, font->height)); sprint(s, "Black prisonners: %d", nblackcaptured); stringbg(screen, p, display->black, ZP, font, s, display->white, ZP); p = addpt(p, Pt(0, font->height)); sprint(s, "White prisonners: %d", nwhitecaptured); stringbg(screen, p, display->black, ZP, font, s, display->white, ZP); return 0; } /* Pixel coordinates to Go move. */ int px2move(Point px) { Point p; Rectangle r; p = Pt(ogoban.x - scale * Linew / 2, ogoban.y - scale * Lineh / 2); r = Rect(p.x, p.y, p.x + scale * sgoban * Linew, p.y + scale * sgoban * Lineh); if(ptinrect(px, r) == 0){ werrstr("Click out of the goban."); return -1; } p = subpt(px, r.min); p.x /= scale * Linew; p.y /= scale * Lineh; return p.y * sgoban + p.x; }
C
#include <stdio.h> #include <stdlib.h> int main(void) { int array[20000] = {0}; int ptr = 0; ++ptr; ++ptr; array[ptr]+=7; while(array[ptr]){ --ptr; array[ptr]+=10; ++ptr; --array[ptr]; } --ptr; printf("%c",array[ptr]); fflush(stdout); --ptr; ++ptr; ++ptr; array[ptr]+=3; while(array[ptr]){ --ptr; array[ptr]+=5; ++ptr; --array[ptr]; } --ptr; printf("%c",array[ptr]); fflush(stdout); --ptr; ++ptr; ++ptr; array[ptr]+=3; while(array[ptr]){ --ptr; array[ptr]-=6; ++ptr; --array[ptr]; } --ptr; printf("%c",array[ptr]); fflush(stdout); --ptr; ++ptr; ++ptr; array[ptr]+=2; while(array[ptr]){ --ptr; array[ptr]+=4; ++ptr; --array[ptr]; } --ptr; printf("%c",array[ptr]); fflush(stdout); --ptr; ++ptr; ++ptr; ++array[ptr]; while(array[ptr]){ --ptr; array[ptr]-=10; array[ptr]-=10; array[ptr]-=10; array[ptr]-=10; array[ptr]-=3; ++ptr; --array[ptr]; } --ptr; printf("%c",array[ptr]); fflush(stdout); --ptr; ++ptr; ++ptr; array[ptr]+=4; while(array[ptr]){ --ptr; array[ptr]+=10; array[ptr]+=3; ++ptr; --array[ptr]; } --ptr; printf("%c",array[ptr]); fflush(stdout); --ptr; ++ptr; ++ptr; array[ptr]+=3; while(array[ptr]){ --ptr; array[ptr]-=4; ++ptr; --array[ptr]; } --ptr; printf("%c",array[ptr]); fflush(stdout); --ptr; ++ptr; ++ptr; ++array[ptr]; while(array[ptr]){ --ptr; ++array[ptr]; ++ptr; --array[ptr]; } --ptr; printf("%c",array[ptr]); fflush(stdout); --ptr; ++ptr; ++ptr; array[ptr]+=2; while(array[ptr]){ --ptr; array[ptr]+=5; ++ptr; --array[ptr]; } --ptr; printf("%c",array[ptr]); fflush(stdout); --ptr; ++ptr; ++ptr; array[ptr]+=3; while(array[ptr]){ --ptr; array[ptr]-=10; array[ptr]-=7; ++ptr; --array[ptr]; } --ptr; printf("%c",array[ptr]); fflush(stdout); --ptr; ++ptr; ++ptr; array[ptr]+=3; while(array[ptr]){ --ptr; array[ptr]+=10; array[ptr]+=7; ++ptr; --array[ptr]; } --ptr; printf("%c",array[ptr]); fflush(stdout); --ptr; ++ptr; ++ptr; ++array[ptr]; while(array[ptr]){ --ptr; array[ptr]-=10; --array[ptr]; ++ptr; --array[ptr]; } --ptr; printf("%c",array[ptr]); fflush(stdout); --ptr; ++ptr; ++ptr; ++array[ptr]; while(array[ptr]){ --ptr; ++array[ptr]; ++ptr; --array[ptr]; } --ptr; printf("%c",array[ptr]); fflush(stdout); --ptr; ++ptr; ++ptr; ++array[ptr]; while(array[ptr]){ --ptr; array[ptr]+=10; ++array[ptr]; ++ptr; --array[ptr]; } --ptr; printf("%c",array[ptr]); fflush(stdout); --ptr; ++ptr; ++ptr; array[ptr]+=3; while(array[ptr]){ --ptr; array[ptr]-=10; array[ptr]-=7; ++ptr; --array[ptr]; } --ptr; printf("%c",array[ptr]); fflush(stdout); --ptr; ++ptr; printf("%c",array[ptr]); fflush(stdout); --ptr; ++ptr; printf("%c",array[ptr]); fflush(stdout); --ptr; ++ptr; printf("%c",array[ptr]); fflush(stdout); --ptr; ++ptr; printf("%c",array[ptr]); fflush(stdout); --ptr; ++ptr; printf("%c",array[ptr]); fflush(stdout); --ptr; ++ptr; printf("%c",array[ptr]); fflush(stdout); --ptr; ++ptr; printf("%c",array[ptr]); fflush(stdout); --ptr; ++ptr; printf("%c",array[ptr]); fflush(stdout); --ptr; ++ptr; printf("%c",array[ptr]); fflush(stdout); --ptr; ++ptr; printf("%c",array[ptr]); fflush(stdout); --ptr; ++ptr; printf("%c",array[ptr]); fflush(stdout); --ptr; ++ptr; printf("%c",array[ptr]); fflush(stdout); --ptr; ++ptr; printf("%c",array[ptr]); fflush(stdout); --ptr; ++ptr; printf("%c",array[ptr]); fflush(stdout); --ptr; ++ptr; ++ptr; array[ptr]+=3; while(array[ptr]){ --ptr; array[ptr]-=10; --array[ptr]; ++ptr; --array[ptr]; } --ptr; --ptr; return 0; }
C
#pragma once #include "GlorvGE_BaseV1.h" #define WINDOW_X 1440 #define WINDOW_Y 1080 #define IND_SIZE 1 * sizeof(unsigned int) #define VERTEX_LENGTH 6//The length of the vertices, 6 entries per, x/y/z r/g/b #define VERTEX_SIZE VERTEX_LENGTH * sizeof(float)//The size in bytes of a vertex, currently 6 because x/y/z r/g/b #define DEPTH_ADJUSTER 2000000//How much to divide user input by when making 2d objects and layering #define EQFLOAT 1/2000000 const int AdjustCharToArrayInt = '0' + 1; //Objects/ //Vertices.txt //Indices.txt //ObjData.txt struct ShapeData createShape(float vertices[], unsigned int indices[], int vertSize, int indSize, int saveAll) { struct ShapeData Returns; glGenVertexArrays(1, &Returns.VAO); glGenBuffers(1, &Returns.VBO); glGenBuffers(1, &Returns.EBO); // bind the Vertex Array Object first, then bind and set vertex buffer(s), and then configure vertex attributes(s). glBindVertexArray(Returns.VAO); glBindBuffer(GL_ARRAY_BUFFER, Returns.VBO); glBufferData(GL_ARRAY_BUFFER, vertSize * VERTEX_SIZE, vertices, GL_DYNAMIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, &Returns.EBO); glBufferData(GL_ELEMENT_ARRAY_BUFFER, indSize * IND_SIZE, indices, GL_DYNAMIC_DRAW); // position attribute glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(float), (void*)0); glEnableVertexAttribArray(0); // color attribute glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(float), (void*)(3 * sizeof(float))); glEnableVertexAttribArray(1); if (saveAll == 1) { Returns.fulldata = 1; //Returns.indices = malloc(sizeof(unsigned int) * indSize); Returns.indices = indices; //Returns.vertices = malloc(sizeof(float) * vertSize); Returns.vertices = vertices; Returns.vertexcount = vertSize; Returns.indexcount = indSize; } return(Returns); } struct ShapeData createShapeFromFile(char filename[], int saveAll) { char vertFileFixed[100] = "Objects/"; char indFileFixed[100] = "Objects/"; strcat(vertFileFixed, filename); strcat(vertFileFixed, "Vertices.txt"); strcat(indFileFixed, filename); strcat(indFileFixed, "Indices.txt"); //Vertex reading FILE* verts = fopen(vertFileFixed, "r"); float* vertices; vertices = (float*)calloc(10, sizeof(float)); int counter = 0; int freespaces = 10; while (1) {//Vertex reading //Read entry from file if (fscanf(verts, "%f", &vertices[counter]) == EOF) { break; } //printf("%f\n", vertices[counter]);//DEBUG VERTICE PRINTING counter++; freespaces--;//Keep track of how many spaces we have left if (freespaces == 0) {//No more spaces = ADD MOAR SPACE freespaces = 10; //printf("Had to allocate %d more blocks of memory for createShapeFromFile Vertices.\n", counter/10); vertices = (float*)realloc(vertices, (10 + counter) * sizeof(float));//Hush, nobody cares if it fails } } printf("Had to allocate %d bytes of memory for CreateShapeFromFile Vertices.\n", counter); int vertSize = counter / VERTEX_LENGTH; vertices = (float*)realloc(vertices, vertSize * sizeof(float) * VERTEX_LENGTH); fclose(verts); //Indice reading counter = 0;//Reset the tracking variables freespaces = 10; FILE* inds = fopen(indFileFixed, "r"); unsigned int* indices; indices = (unsigned int*)calloc(10, sizeof(unsigned int)); while (1) {//Indice reading //Read entry from file if (fscanf(inds, "%u", &indices[counter]) == EOF) { break; } //printf("%f\n", vertices[counter]);//DEBUG VERTICE PRINTING counter++; freespaces--;//Keep track of how many spaces we have left if (freespaces == 0) {//No more spaces = ADD MOAR SPACE freespaces = 10; //printf("Had to allocate %d more blocks of memory for createShapeFromFile Indices.\n", counter / 10); indices = (unsigned int*)realloc(indices, (10 + counter) * sizeof(unsigned int));//Hush, nobody cares if it fails } } printf("Had to allocate %d bytes of memory for CreatShapeFromFile Indices.\n", counter); int indSize = counter; indices = (unsigned int*)realloc(indices, indSize*sizeof(unsigned int)); fclose(inds); struct ShapeData newshape = createShape(vertices, indices, vertSize, indSize, saveAll); return(newshape); } //Saves given shape to filen, shape given by raw data. void saveRawShapeToFile(float vertices[], unsigned int indices, int vertSize, int indSize, char fileName) { //char* token; char vertFile[100] = "Objects/";//Get to the right directory strcat(vertFile, fileName);//Put the name of the file as the folder name strcat(vertFile, "Vertices.txt");//All vertice files are named this FILE* vertSaveFile = fopen(vertFile, "w");//The place being written to is OurProgram/Objects/FilenameVertices.txt fputs(vertices, vertFile);//Write the data to the file char indfile[100] = "Objects/";//Get to the right directory strcat(indfile, fileName);//Put the name of the file as the folder name strcat(indfile, "Indices.txt");//All indice files are named this FILE* indSaveFile = fopen(indfile, "w");//The place being written to is OurProgram/Objects/FilenameIndices.txt fputs(indices, indfile);//Write the data to the file } //Saves given shape to filen, shape given by raw data. void saveShapeToFile(struct ShapeData savedata) { char vertFile[100] = "Objects/";//Get to the right directory strcat(vertFile, savedata.filename);//Put the name of the file as the folder name strcat(vertFile, "Vertices.txt");//All vertice files are named this FILE* vertSaveFile = fopen(vertFile, "w");//The place being written to is OurProgram/Objects/FilenameVertices.txt for (int counter = 0; counter < savedata.vertexcount * VERTEX_LENGTH; counter++) { fprintf(vertSaveFile, "%f", savedata.vertices[counter]);//May the lack of the multiplication by vertex length never haunt this program again. if (counter != savedata.vertexcount - 1) {//Add a space so long as this isnt the last element fprintf(vertSaveFile, " "); } } fclose(vertSaveFile); char indfile[100] = "Objects/";//Get to the right directory strcat(indfile, savedata.filename);//Put the name of the file as the folder name strcat(indfile, "Indices.txt");//All indice files are named this FILE* indSaveFile = fopen(indfile, "w");//The place being written to is OurProgram/Objects/FilenameIndices.txt for (int counter = 0; counter < savedata.indexcount; counter++) { fprintf(indSaveFile, "%d", savedata.indices[counter]); if (counter != savedata.indexcount - 1) {//Add a space so long as this isnt the last element fprintf(indSaveFile, " "); } } fclose(indSaveFile); //TO DO: Get this to save layer data //char objdatafile[100] = "Objects/"; //strcat(objdatafile, savedata.filename);//Put the name of the file as the folder name //strcat(objdatafile, ObjDataText);//All vertice files are named this //FILE* objdataSaveFile = fopen(objdatafile, "w");//The place being written to is OurProgram/Objects/FilenameObjData.txt ////write the data to the file //fprintf(objdataSaveFile, "%d", savedata.) } //DRAWING SHAPE BY HAND //Returns the closest vertice to the mouse in terms of WHICH vertice, not the array value. So vertice 0, 1, 2 etc not position 0, 6, 12 int closestVert(struct ShapeData* givenshape, int points, GLFWwindow* window) { int closestPointNumber = 0; double* xy = calloc(2, sizeof(double)); glfwGetCursorPos(window, &xy[0], &xy[1]); xy[0] = (xy[0] - (.5 * WINDOW_X)) / (.5 * WINDOW_X); xy[1] = -(xy[1] - (.5 * WINDOW_Y)) / (.5 * WINDOW_Y); float closestDistance = 100000;//Literally no way to get past this because ITS SUPPOSED TO BE -1 -> 1 CORDS for (int counter = 0; counter < points; counter++) {//Run through each entry and find the distance storing the closest one and its position in the array. double currentDistance = distanceTwoDD(givenshape->vertices[counter * VERTEX_LENGTH], xy[0], givenshape->vertices[(counter * VERTEX_LENGTH) + 1], xy[1]);//Find the current distance if (currentDistance < closestDistance) {//If the current distance is so far the shortest, save it closestDistance = currentDistance; closestPointNumber = counter; } } return(closestPointNumber); } //Deletes all indice references to given point void deleteIndice(struct ShapeData* givenShape, int vert) { for (int currentThree = 0; currentThree < givenShape->indexcount; currentThree = currentThree + 3) {//Run through all indices 3 at a time if ((givenShape->indices[currentThree] == vert) || (givenShape->indices[currentThree + 1] == vert) || (givenShape->indices[currentThree + 2] == vert)) {//Do any of the three point to the removed vertex? if (currentThree != givenShape->indexcount - 3) {//Make sure that we aren't on the final three, if we are its just time to chop the memory off already for (int counter = currentThree; counter < givenShape->indexcount - 3; counter += 3) {//Shift everything back a trio overwriting the useless entry givenShape->indices[counter] = givenShape->indices[counter + 3]; givenShape->indices[counter + 1] = givenShape->indices[counter + 4]; givenShape->indices[counter + 2] = givenShape->indices[counter + 5]; } currentThree = currentThree - 3;//Just back this up to make sure we dont skip any, because if it goes entry 1, 2, 3 and we remove 1 it becomes 2, 3, 3 with the last 3 being cutoff but we're now in POSITION 2, past 2 } givenShape->indexcount = givenShape->indexcount - 3;//We have removed a trio of entries so keep track of it } } givenShape->indices = realloc(givenShape->indices, IND_SIZE * givenShape->indexcount);//Re-allocate the memory now that we're done shifting } //Deletes given vertice and all index entries pointing to it. Vert is in nonadjusted position, so not 0, 6, 12, its just in vertex 0, 1, 2, 3 etc void deleteVertice(struct ShapeData* givenShape, int vert, int updateOpenGL) { for (int currentvert = vert * VERTEX_LENGTH; currentvert < givenShape->vertexcount * VERTEX_LENGTH; currentvert += VERTEX_LENGTH) {//Run through all vertices at and past the given one for (int swapsies = 0; swapsies < VERTEX_LENGTH; swapsies++) {//because then we run through and copy the next vertice into the current one, overwriting the one to be deleted givenShape->vertices[currentvert + swapsies] = givenShape->vertices[currentvert + swapsies + VERTEX_LENGTH]; } } givenShape->vertices = realloc(givenShape->vertices, givenShape->vertexcount * VERTEX_SIZE);//'lower' the memory assigned to the array givenShape->vertexcount--;//we deleted a vertice, so keep track of it if (updateOpenGL) {//Do we update opengl from in here? glBufferData(GL_ARRAY_BUFFER, givenShape->vertexcount * VERTEX_SIZE, givenShape->vertices, GL_DYNAMIC_DRAW);//Reallocate all the memory used by opengl } for (int currentThree = 0; currentThree < givenShape->indexcount; currentThree = currentThree + 3) {//Run through all indices 3 at a time if ((givenShape->indices[currentThree] == vert) || (givenShape->indices[currentThree + 1] == vert) || (givenShape->indices[currentThree + 2] == vert)) {//Do any of the three point to the removed vertex? if (currentThree != givenShape->indexcount - 3) {//Make sure that we aren't on the final three, if we are its just time to chop the memory off already for (int counter = currentThree; counter < givenShape->indexcount - 3; counter += 3) {//Shift everything back a trio overwriting the useless entry givenShape->indices[counter] = givenShape->indices[counter + 3]; givenShape->indices[counter + 1] = givenShape->indices[counter + 4]; givenShape->indices[counter + 2] = givenShape->indices[counter + 5]; } currentThree = currentThree - 3;//Just back this up to make sure we dont skip any, because if it goes entry 1, 2, 3 and we remove 1 it becomes 2, 3, 3 with the last 3 being cutoff but we're now in POSITION 2, past 2 } givenShape->indexcount = givenShape->indexcount - 3;//We have removed a trio of entries so keep track of it } } givenShape->indices = realloc(givenShape->indices, IND_SIZE * givenShape->indexcount);//Re-allocate the memory now that we're done shifting for (int current = 0; current < givenShape->indexcount; current++) {//Run through all indices that remain and if any were referencing a vertex past the deleted one, lower the value they point to if (givenShape->indices[current] > vert) {//The reason for this is because if we have vertex 0, 1, 2 ,3 ,4 and remove 2, 3 becomes 2, 4 becomes 3 and we need the pointer to 4 to point to 3 givenShape->indices[current] --; } } } //Plan for how it will work: Get all the vertices while rendering them as points, then the user clicks on pairs of 3 vertices to connect them as a triangle. //Lastly the user should be able to click a vertex and then have it follow the mouse until they click again, and a way to switch between these 3 modes of 'vector creation' 'vector connection' and 'vector changing' struct ShapeData drawShape(GLFWwindow* window, int shaderID) { printf("\nNow drawing a shape.\n\n\n"); printf("\nMode: Vertex Creation\n\n");//default mode glfwSetCharCallback(window, character_callback);//For tippy typing glPointSize(10.0f);//For the vertex rendering //Variable stack //OPTIONS int drawVertices = 1;//whether to draw the endpoints as blocks int AutoSelectLayers = 1;//Whether to automatically select newly created layers int Confirmations = 1;//Whether to ask the user to confirm certain actions int SnapToGrid = 0; int GridSize = 10; //END OF OPTIONS const double TIME_BETWEEN_MODES = .25;//The minimum time between switching modes. //VERTEX AUXILLERY DATA, CARRIES THROUGH TO MANY VERTICES float red, green, blue;//Currently selected colour red = 1.0; green = 0.0; blue = 0.0; struct LayerNames* userLayerNames; int currentLayer = -1;//Keeps track of the current layer userLayerNames = malloc(sizeof(struct LayerNames) * 10);//Allows the user to store 10 layers for (int counter = 0; counter < 10; counter++) { userLayerNames[counter].name = NULL; } //VERTEX AUXILLERY DATA, CARRIES THROUGH TO MANY VERTICES //USED FOR VERTEX MOVING int selectedPoint = 0;//Do we have a selected point int selectedPointPos = 0;//The position in the array of the selected point int closestPointNumber = 0;//Which one in the array is the closest point, points to the X value //END OF USED FOR VERTEX MOVING //SHAPEDATA struct ShapeData drawnshape;//The structure that we will return and render from drawnshape.vertices = malloc(sizeof(float));//Initalize each drawnshape.indices = malloc(sizeof(unsigned int)); drawnshape.vertexcount = 0; drawnshape.indexcount = 0; //END OF SHAPEDATA glfwSetMouseButtonCallback(window, mouseclickCallback);//So when we click we can update the processing click global variable //modes const int VERT_CREATE = 1; const int VERT_CONNECT = 2; const int VERT_CHANGE = 3; const int VERT_COLOUR = 4; const int END_OF_CREATION = 0; const int MENU = -1; //SET DEFAULT MODE int mode = VERT_CREATE;//Set the mode to vertex creation so that we can actually start with making vertices //end of modes //VERTEX CONNECTION VARIABLES int tempIndices[3];//To temporarily store the indices until we have 3 int indiceConnections = 0;//To indicate when we have 3 indices stored. //END OF VERTEX CONNECTION VARIABLES double time = 0; double timeAtLastPrintf = 0;//Used to make sure we dont spam the crap out of the 'Mode is: x' text //End of variable stack while (1) {//While we are still creating the shape, lets us loop between the 3 modes until we are finished. //START OF VERTEX CREATION if (mode == VERT_CREATE) { //IF WE HAVE A LEFT CLICK TO CREATE, SAVE ALL VERTICIES NO LONGER SAVES INDICES BECAUSE CONNECT MODE if (processingClick == 1) {//we have a click processingClick = 0;//reset as we are now dealing with it drawnshape.vertexcount++; double xpos, ypos;//We had a click so get the x/y glfwGetCursorPos(window, &xpos, &ypos); if (SnapToGrid) { xpos = xpos - (double)((int)xpos % GridSize); ypos = ypos - (double)((int)ypos % GridSize); } drawnshape.vertices = realloc(drawnshape.vertices, drawnshape.vertexcount * VERTEX_SIZE);//give more memory in prep of storing the x/y forever, *6 is because 6 entries per vertice //start to store all the new data, for now just make the shape red drawnshape.vertices[(drawnshape.vertexcount - 1) * 6] = (xpos - (.5 * WINDOW_X)) / (.5 * WINDOW_X);//x drawnshape.vertices[((drawnshape.vertexcount - 1) * 6) + 1] = -(ypos - (WINDOW_Y / 2)) / (WINDOW_Y / 2);//y if (currentLayer == -1) {//No layer set, default to zero drawnshape.vertices[((drawnshape.vertexcount - 1) * 6) + 2] = 0;//z } else { drawnshape.vertices[((drawnshape.vertexcount - 1) * 6) + 2] = userLayerNames[currentLayer].depth;//z } drawnshape.vertices[((drawnshape.vertexcount - 1) * 6) + 3] = red;//red drawnshape.vertices[((drawnshape.vertexcount - 1) * 6) + 4] = green;//green drawnshape.vertices[((drawnshape.vertexcount - 1) * 6) + 5] = blue;//blue //end of storing data } //VERTEX DELETION else if (processingClick == 2) {//Right click deletes vertices processingClick = 0;//Reset the click if (!Confirmations) { int vertToDelete = closestVert(&drawnshape, drawnshape.vertexcount, window);//Find the closest vertice to the click deleteVertice(&drawnshape, vertToDelete, drawnshape.vertexcount, 1); } else if (extendedConfirmationDialog(window, "Deleting vertex\n", "Vertex remains.\n", "Are you sure you want to delete the vertex?\n")){ int vertToDelete = closestVert(&drawnshape, drawnshape.vertexcount, window);//Find the closest vertice to the click deleteVertice(&drawnshape, vertToDelete, drawnshape.vertexcount, 1); } //END OF VERTEX DELETION } //END OF CLICK REGISTERING //CREATE SHAPEDATA IF WE CREATE A VERTEX if (drawnshape.vertexcount == 1) {//If we have our first point, create the actual data in opengl for it drawnshape = createShape(drawnshape.vertices, drawnshape.indices, drawnshape.vertexcount, drawnshape.indexcount, 1); } //OTHERWISE UPDATE THE SHAPE else if(drawnshape.vertexcount > 1) {//BUG Potential, if you place one point and try to move it drawnshape wont have the updated info, MAYBE glBufferData(GL_ARRAY_BUFFER, drawnshape.vertexcount * VERTEX_SIZE, drawnshape.vertices, GL_DYNAMIC_DRAW); //glBufferData(GL_ELEMENT_ARRAY_BUFFER, points * IND_SIZE, drawnshape.indices, GL_DYNAMIC_DRAW); } }//END OF IF STATEMENT //END OF VERTEX CREATION //START OF VERTEX CHANGING else if (mode == VERT_CHANGE) { if (processingClick == 1) {//Left click, so let us see whats goin on processingClick = 0; //START OF FINDING POINT if (selectedPoint == 0) {//We do NOT have a point selected yet SO LETS FIND ONE HOOAH double* xy = calloc(2, sizeof(double)); glfwGetCursorPos(window, &xy[0], &xy[1]); float XY[2]; XY[0] = (xy[0] - (.5 * WINDOW_X)) / (.5 * WINDOW_X); XY[1] = -(xy[1] - (.5 * WINDOW_Y)) / (.5 * WINDOW_Y); float closestDistance = 100000;//Literally no way to get past this because ITS SUPPOSED TO BE -1 -> 1 CORDS for (int counter = 0; counter < drawnshape.vertexcount; counter++) {//Run through each entry and find the distance storing the closest one and its position in the array. float currentDistance = distanceTwoD(drawnshape.vertices[counter * VERTEX_LENGTH], XY[0], drawnshape.vertices[(counter * VERTEX_LENGTH) + 1], XY[1]);//Find the current distance if (currentDistance < closestDistance) {//If the current distance is so far the shortest, save it closestDistance = currentDistance; closestPointNumber = counter * VERTEX_SIZE; } } selectedPoint = 1; } //END OF FINDING POINT //END OF LEFT CLICK //START OF RIGHT CLICK } else if (processingClick == 2) {//Right click stops the movement of the point processingClick = 0; selectedPoint = 0;//Deselects the point } //END OF RIGHT CLICK //START OF MOVING POINT, FOLLOW THE CURSOUR if (selectedPoint == 1) {//Do we have a point selected? double* xy = calloc(2, sizeof(double)); glfwGetCursorPos(window, &xy[0], &xy[1]);//Get the x/y in pixles float XY[2]; if (SnapToGrid) { xy[0] = xy[0] - (double)((int)xy[0] % GridSize); xy[1] = xy[1] - (double)((int)xy[1] % GridSize); } XY[0] = (xy[0] - (.5 * WINDOW_X)) / (.5 * WINDOW_X);//convert the double x/y in pixles to float x/y in graph XY[1] = -(xy[1] - (.5 * WINDOW_Y)) / (.5 * WINDOW_Y); drawnshape.vertices[closestPointNumber/ sizeof(float)] = XY[0];//save in the shapedata drawnshape.vertices[(closestPointNumber / sizeof(float)) + 1] = XY[1]; glBufferSubData(GL_ARRAY_BUFFER, closestPointNumber, 2 * sizeof(float), XY);//update opengl } //END OF MOVING POINT } //END OF VERTEX CHANGING SEGMENT //START OF VERTEX CONNECTING else if (mode == VERT_CONNECT) { int closestPointNumber = 0;//The closest vertex entry if (processingClick == 1) {//left click, find the closest point and its array value and save an index to it processingClick = 0; //FIND CLOSEST POINT TO CLICK closestPointNumber = closestVert(&drawnshape, drawnshape.vertexcount, window); //Now we have the closest point, so make a temp index out of it. //BUG CURRENTLY SAVES INDICES EVEN IF NOT FULLY CREATED. NEEDS TO GATHER THREE THEN SAVE ALL THREE AT ONCE tempIndices[indiceConnections] = closestPointNumber; indiceConnections++; if (indiceConnections == 3) { indiceConnections = 0; drawnshape.indexcount += 3;//we're adding three indices drawnshape.indices = realloc(drawnshape.indices, sizeof(unsigned int) * drawnshape.indexcount);//Grab more memory to store em in drawnshape.indices[drawnshape.indexcount - 3] = tempIndices[0];//then store all three drawnshape.indices[drawnshape.indexcount - 2] = tempIndices[1]; drawnshape.indices[drawnshape.indexcount - 1] = tempIndices[2]; } } else if (processingClick == 2) {//Right click. Disconnects all connections to the point printf("Are you sure you wish to disconnect this point?\n"); if (!Confirmations) { deleteIndice(&drawnshape, closestVert(&drawnshape, drawnshape.vertexcount, window)); }else if (confirmationDialog(window, "Disconnected.\n\n", "Cancled.\n\n")) { deleteIndice(&drawnshape, closestVert(&drawnshape, drawnshape.vertexcount, window)); } } } //END OF VERTEX CONNECTION //VERT COLOUR CHANGING else if (mode == VERT_COLOUR) { int closestPointNumber = 0;//The closest vertex entry //Left click paints colour if (processingClick == 1) {//left click, find the closest point and switch its colour to the currently active colour processingClick = 0; //FIND CLOSEST POINT TO CLICK closestPointNumber = closestVert(&drawnshape, drawnshape.vertexcount, window); //End of tracking left click, we have a point now //so now that we have a point, update its colour to the active colour //update shapedata drawnshape.vertices[(closestPointNumber * VERTEX_LENGTH) + 3] = red; drawnshape.vertices[(closestPointNumber * VERTEX_LENGTH) + 4] = green; drawnshape.vertices[(closestPointNumber * VERTEX_LENGTH) + 5] = blue; //end of update shapedata //update openGLs data next float datashifter[3]; datashifter[0] = red; datashifter[1] = green; datashifter[2] = blue;// Get to the right portion of the vertices, then go to the third one (Start of RGB) glBufferSubData(GL_ARRAY_BUFFER, (closestPointNumber * VERTEX_SIZE) + (sizeof(float) * 3), 3 * sizeof(float), datashifter);//update opengl //End of processing left click } //Right click copies the nearest colour else if (processingClick == 2) { processingClick = 0; //FIND CLOSEST POINT TO CLICK int vertToCopy = closestVert(&drawnshape, drawnshape.vertexcount, window); if (Confirmations) { float tred = drawnshape.vertices[(vertToCopy * VERTEX_LENGTH) + 3]; float tgreen = drawnshape.vertices[(vertToCopy * VERTEX_LENGTH) + 4]; float tblue = drawnshape.vertices[(vertToCopy * VERTEX_LENGTH) + 5]; printf("Copied colour: %0.0f, %0.0f, %0.0f.\n", tred * 255, tgreen * 255, tblue * 255); if (confirmationDialog(window, "Colour copied.\n\n", "Colour unchanged.\n\n")) { red = tred; green = tgreen; blue = tblue; } }else{ red = drawnshape.vertices[(vertToCopy * VERTEX_LENGTH) + 3]; green = drawnshape.vertices[(vertToCopy * VERTEX_LENGTH) + 4]; blue = drawnshape.vertices[(vertToCopy * VERTEX_LENGTH) + 5]; printf("Copied colour: %0.0f, %0.0f, %0.0f.\n", red * 255, green * 255, blue * 255); } }//END OF RIGHT CLICK } //END OF VERT COLOUR //MENU TO SELECT STUFF else if (mode == MENU) { //SELECT COLOUR if (lastPressedKey == '1' && handlingLastPress) { handlingLastPress = 0; int twoFiftyFive = 0;//Declare our variables char numInput[3]; if (!Confirmations) { //GET RED typingLimited(window, 1, 0, numInput, 3); printf(" ");//add some space //Now we have a string with numbers in it, convert to number numbers and store in red and BOOM, done. //100s 10s 1s twoFiftyFive = (int)(((numInput[0] - '0') * 100) + ((numInput[1] - '0') * 10) + (numInput[2] - '0'));//Convert the three char string into an int red = (float)twoFiftyFive / 255;//Then convert the int to a float and BOOM //END OF GET RED //GET GREEN typingLimited(window, 1, 0, numInput, 3); //Now we have a string with numbers in it, convert to number numbers and store in red and BOOM, done. //100s 10s 1s twoFiftyFive = (int)(((numInput[0] - '0') * 100) + ((numInput[1] - '0') * 10) + (numInput[2] - '0'));//Convert the three char string into an int green = (float)twoFiftyFive / 255;//Then convert the int to a float and BOOM //END OF GET GREEN printf(" ");//add some space //GET BLUE typingLimited(window, 1, 0, numInput, 3); //Now we have a string with numbers in it, convert to number numbers and store in red and BOOM, done. //100s 10s 1s twoFiftyFive = (int)(((numInput[0] - '0') * 100) + ((numInput[1] - '0') * 10) + (numInput[2] - '0'));//Convert the three char string into an int blue = (float)twoFiftyFive / 255;//Then convert the int to a float and BOOM //END OF GET BLUE } else if(extendedConfirmationDialog(window, "New colour: ","Colour unchanged.\n","Confirm colour change?\n")){ //GET RED typingLimited(window, 1, 0, numInput, 3); printf(" ");//add some space //Now we have a string with numbers in it, convert to number numbers and store in red and BOOM, done. //100s 10s 1s twoFiftyFive = (int) (((numInput[0] - '0') * 100) + ((numInput[1] - '0') * 10) + (numInput[2] - '0'));//Convert the three char string into an int red = (float) twoFiftyFive / 255;//Then convert the int to a float and BOOM //END OF GET RED //GET GREEN typingLimited(window, 1, 0, numInput, 3); //Now we have a string with numbers in it, convert to number numbers and store in red and BOOM, done. //100s 10s 1s twoFiftyFive = (int)(((numInput[0] - '0') * 100) + ((numInput[1] - '0') * 10) + (numInput[2] - '0'));//Convert the three char string into an int green = (float)twoFiftyFive / 255;//Then convert the int to a float and BOOM //END OF GET GREEN printf(" ");//add some space //GET BLUE typingLimited(window, 1, 0, numInput, 3); //Now we have a string with numbers in it, convert to number numbers and store in red and BOOM, done. //100s 10s 1s twoFiftyFive = (int)(((numInput[0] - '0') * 100) + ((numInput[1] - '0') * 10) + (numInput[2] - '0'));//Convert the three char string into an int blue = (float)twoFiftyFive / 255;//Then convert the int to a float and BOOM //END OF GET BLUE }//End of switching colour mode = VERT_CREATE;//Back out of menu now that we are done here. printf("\nMode: Vertex Creation\n\n"); } //END OF SELECT COLOUR //CREATE LAYER else if (lastPressedKey == '2' && handlingLastPress) { handlingLastPress = 0; int layersRemain = -1; for (int counter = 0; counter < 9; counter++) {//check if we have any layers remaining, do so by seeing if any are un-named if (userLayerNames[counter].name == NULL) { layersRemain = counter; break; } } if (layersRemain >= 0) {//We have at least one layer remaining int Confirmed = 0; if (Confirmations) { Confirmed = extendedConfirmationDialog(window, "What would you like to name this layer? 24 Character Max. ", "Layer creation cancled.\n\n", "Are you sure you wish to create a new layer?\n"); } else { printf("What would you like to name this layer ? 24 Character Max. "); Confirmed = 1; } //CREATE THE LAYER if (Confirmed) { userLayerNames[layersRemain].name = malloc(sizeof(char) * 25);//Give it some memory typingLimited(window, 1, 1, userLayerNames[layersRemain].name, 25);//Get some typing input and save it to the name printf("\n\n");//add some spacing //END OF NAMING THE LAYER printf("What depth would you like to make it? 0 - 9. "); while (1) {//while loop because we might get invalid depth from user int validdepth = 1;//variable to see if we got a valid depth userLayerNames[layersRemain].depth = (float)keyReader(window, 1) - '0';//Get the number the user inputs as a number rather than a character printf(" ");//In case its not a valid number add some space userLayerNames[layersRemain].depth = userLayerNames[layersRemain].depth / DEPTH_ADJUSTER;//then adjust the number to get it really smol so as to not look 3d for (int counter = 0; counter < layersRemain; counter++) {//Run through all the other layers and see if one is already on this height if (fabs(userLayerNames[layersRemain].depth - userLayerNames[counter].depth) < 0.000000000001) {//if any are on the height invalidate the run validdepth = 0; printf("Not a valid layer height, already taken.\n"); break;//and break out of the for loop to save time } } if (validdepth == 1) { break; } } printf("\n\n"); if (AutoSelectLayers) { currentLayer = layersRemain; printf("Selected Layer: %s", userLayerNames[layersRemain].name); } } //END OF CREATING THE LAYER } else { printf("No more layers remain.\n"); } mode = VERT_CREATE;//Back out of menu now that we are done here. printf("\nMode: Vertex Creation\n\n"); } //END OF CREATE LAYER //SWITCH LAYER else if (lastPressedKey == '3' && handlingLastPress) { handlingLastPress = 0;//Handled int counter = 0; printf("What layer would you like to select?\n"); while (userLayerNames[counter].name != NULL) { printf("%d) %s, depth %f\n", counter + 1, userLayerNames[counter].name, userLayerNames[counter].depth * DEPTH_ADJUSTER); counter++; } char number = keyReader(window, 0); //We have the selected layer now (Hopefully) so we can select it currentLayer = number - AdjustCharToArrayInt;//Since we are selecting a layer, copy the key pressed (1 = 0, 2 = 1, etc) to the layer (0-9) printf("Selected Layer: %s %d\n\n", userLayerNames[currentLayer].name, currentLayer); mode = VERT_CREATE;//Back out of menu now that we are done here. printf("\nMode: Vertex Creation\n\n"); } //END OF SWITCHING LAYERS //RENAME LAYER else if (lastPressedKey == '4' && handlingLastPress) { handlingLastPress = 0;//Handled int counter = 0; int Confirmed = 0; if (!Confirmations) { Confirmed = 1; } else if (extendedConfirmationDialog(window, "What layer would you like to select?\n", "Layer unchanged.\n", "Are you sure you wish to rename a layer?")) { Confirmed = 1; } if (Confirmed) { printf("What layer would you like to select?\n"); while (userLayerNames[counter].name != NULL) {//Print the layers out printf("%d) %s, depth %.0f\n", counter + 1, userLayerNames[counter].name, userLayerNames[counter].depth * DEPTH_ADJUSTER); counter++; } handlingLastPress = 0;//Make sure its clear waitForKeyPress(window, 0); //Now we have a number keypress to select it currentLayer = (int)lastPressedKey - AdjustCharToArrayInt;//Since we are selecting a layer, copy the key pressed (1 = 0, 2 = 1, etc) to the layer (0-9) printf("%d\n", currentLayer); printf("Selected Layer: %s\n\n", userLayerNames[currentLayer].name); //RE-NAMING THE LAYER printf("What would you like to re-name this layer to? "); typingLimited(window, 1, 1, userLayerNames[currentLayer].name,1); handlingLastPress = 0;//Handled //END OF RE-NAMING THE LAYER //DO NOT re-height the layer } mode = VERT_CREATE;//Back out of menu now that we are done here. printf("\nMode: Vertex Creation\n\n"); } //END OF RENAME LAYER //DELETE LAYER else if (lastPressedKey == '5' && handlingLastPress) { handlingLastPress = 0;//Handled int counter = 0; if(extendedConfirmationDialog(window, "What layer would you like to delete?\n", "\n", "Are you sure you wish to delete a layer?\n")){//Confirm that the user wishes to delete a layer while (userLayerNames[counter].name != NULL) {//Print the layers out printf("%d) %s, depth %.0f\n", counter + 1, userLayerNames[counter].name, userLayerNames[counter].depth * DEPTH_ADJUSTER); counter++; } waitForKeyPress(window, 1); //Now we have a number keypress to select it then delete it int currentlayer = lastPressedKey - AdjustCharToArrayInt; float layerheight = userLayerNames[currentlayer].depth;//The z value we need to remove points on for (int current = 0; current < drawnshape.vertexcount; current++) {//Run through each vertice and see if we need to delete it if (fabs(drawnshape.vertices[(current * VERTEX_LENGTH) + 2] - layerheight) < EQFLOAT) {//Is this vertice on the correct z value to be on this layer? //if so we need to delete it, but then also pull back current so as to not skip any vertices (Because if we delete it all vertices get shifted back 1 deleteVertice(&drawnshape, current, 0); current--; } } //Since we aren't reallocating in the delete vertice, as that would potentially be a crapton of updates, update now. glBufferData(GL_ARRAY_BUFFER, drawnshape.vertexcount * VERTEX_SIZE, drawnshape.vertices, GL_DYNAMIC_DRAW); counter = currentlayer;//Start at the given layer while (userLayerNames[counter].name != NULL) {//Overwrite the current layer and then delete the last if(userLayerNames[counter+1].name != NULL){ userLayerNames[counter].name = userLayerNames[counter + 1].name; userLayerNames[counter].depth = userLayerNames[counter + 1].depth; } else { userLayerNames[counter].name = NULL; userLayerNames[counter].depth = -10; } counter++; } } } //END OF DELETE LAYER //SWITCH DRAW VERTICE MODE else if (lastPressedKey == '6' && handlingLastPress) { handlingLastPress = 0; printf("Vertex rendering has been flipped.\n\n"); if (drawVertices == 1) { drawVertices = 0; } else { drawVertices = 1; } mode = VERT_CREATE;//Back out of menu now that we are done here. printf("\nMode: Vertex Creation\n\n"); } //END OF SWITCH DRAW VERTICE MODE //OPTIONS else if (lastPressedKey == '7' && handlingLastPress) { handlingLastPress == 0;//As always reset this mode = VERT_CREATE;//This is a oneoff lock in path that shouldnt be looped through printf("1) Layers select upon creation. Currently %d\n", AutoSelectLayers); printf("2) Confirmations required to perform certain actions. Currently %d\n", Confirmations); printf("3) Snap to Grid. Currently %d\n", SnapToGrid); printf("4) Grid Size. Currently %d\n", GridSize); char action = keyReader(window, 0); if (action == '1') { AutoSelectLayers = !AutoSelectLayers; } else if (action == '2') { Confirmations = !Confirmations; } else if (action == '3') { SnapToGrid = !SnapToGrid; } else if (action == '4') { printf("What size would you like the grid to be? "); char newgridsize[2] = {0, 0}; typingLimited(window, 1, 0, &newgridsize, 2); GridSize = ((newgridsize[0] - '0') * 10) + (newgridsize[1] - '0'); printf("\nNew grid size: %d\n", GridSize); } handlingLastPress = 0;//extra safety printf("\nMode: Vertex Creation\n\n"); } //END OF OPTIONS } //END OF MENU //S9 E1 else if (mode == END_OF_CREATION) { mode = VERT_CREATE; printf("Are you sure you would like to end the shape creation? Y/N "); char yesno = keyReader(window, 0); if (yesno == 'y') {//We are ending the shape creation drawnshape.ShapeLayers = userLayerNames;//Copy the layer data over printf("\nWhat would you like to name the object? Max 50 characters. "); drawnshape.filename = malloc(sizeof(char)*51); typingLimited(window, 1, 1, drawnshape.filename,51); saveShapeToFile(drawnshape);//Save it return(drawnshape); } else { printf("\nMode: Vertex Creation\n\n"); mode = VERT_CREATE; } } //S9 E24 //END OF MODES, ONTO UPDATES //DRAWING glEnable(GL_DEPTH_TEST); //Make sure we have stuff to draw... if (drawnshape.vertexcount > 0) { //Draw our new stuff //glPointSize(10.0f); glBindVertexArray(drawnshape.VAO); if (drawVertices == 1) { glDrawArrays(GL_POINTS, 0, drawnshape.vertexcount); } glDrawElements(GL_TRIANGLES, drawnshape.indexcount, GL_UNSIGNED_INT, drawnshape.indices); glBindVertexArray(0); //glfwSwapBuffers(window); //End of drawing new stuff } glfwPollEvents(); glfwSwapBuffers(window); glClearColor(0.0, 0.1, 0.9, 0.5);//clear the frame that was shown and just got pulled back glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); //END OF DRAWING //MODE SELECTOR CODE if (mode != MENU) { //create/delete mode if (lastPressedKey == '1' && handlingLastPress) { handlingLastPress = 0;//Dealt with keypress if (mode != VERT_CREATE) { printf("\nMode: Vertex Creation\n\n"); mode = VERT_CREATE; //cleanup variables selectedPoint = 0; indiceConnections = 0; } }//Vertex creation mode //move mode else if (lastPressedKey == '2' && handlingLastPress) { handlingLastPress = 0;//Dealt with keypress if (mode != VERT_CHANGE) { printf("\nMode: Vertex Changing\n\n"); mode = VERT_CHANGE; //cleanup variables selectedPoint = 0; indiceConnections = 0; } } //Vertex connect mode else if (lastPressedKey == '3' && handlingLastPress) { handlingLastPress = 0;//Dealt with keypress if (mode != VERT_CONNECT) { timeAtLastPrintf = time; printf("\nMode: Vertex Connection.\n\n"); mode = VERT_CONNECT; //cleanup variables selectedPoint = 0; indiceConnections = 0; } } //vertex connect mode //vertex colour change else if (lastPressedKey == '4' && handlingLastPress) { handlingLastPress = 0; time = glfwGetTime(); if (time - timeAtLastPrintf > TIME_BETWEEN_MODES) { timeAtLastPrintf = time; mode = VERT_COLOUR; printf("\nMode: Vertex Colour Changing.\n\n"); //cleanup variables selectedPoint = 0; indiceConnections = 0; } } //Old style below for things that arent characters //menu else if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS) {//Escape 'brings up menu' time = glfwGetTime(); if (time - lastSpecialPressTime > TIME_BETWEEN_MODES) { if (mode == MENU) { mode = VERT_CREATE; printf("\nMode: Vertex Creation\n\n"); selectedPoint = 0; indiceConnections = 0; } else { lastSpecialPressTime = time; printf("\nWhat would you like to do?\n1) Select colour.\n2) Create Layer\n3) Switch Layer\n4) Edit Layer\n5) Delete Layer\n6) Switch Vertex Rendering\n7) Options\n\n"); mode = MENU; selectedPoint = 0; indiceConnections = 0; } } } //end creation else if (glfwGetKey(window, GLFW_KEY_END) == GLFW_PRESS) { time = glfwGetTime(); if (time - lastSpecialPressTime > TIME_BETWEEN_MODES) { lastSpecialPressTime = time; mode = END_OF_CREATION; //cleanup variables selectedPoint = 0; indiceConnections = 0; } } } //END OF MODE SELECTOR } }
C
#include "packet.h" bool pdr_func(){ int ra=rand()%100; if(ra>=PDR) return true; return false; } int max(int a,int b){ if(a>b)return a; return b; } int main(void) { int opt = true; int listenfd = 0; int connfd1= 0,connfd2=0; struct sockaddr_in serv_addr; //char sendBuff[1025]; int numrv; listenfd = socket(AF_INET, SOCK_STREAM, 0); // printf("Socket retrieve success\n"); memset(&serv_addr, '0', sizeof(serv_addr)); //memset(sendBuff, '0', sizeof(sendBuff)); serv_addr.sin_family = AF_INET; serv_addr.sin_addr.s_addr = htonl(INADDR_ANY); serv_addr.sin_port = htons(5001); if( setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, (char *)&opt, sizeof(opt)) < 0 ) { perror("setsockopt"); exit(EXIT_FAILURE); } bind(listenfd, (struct sockaddr*)&serv_addr,sizeof(serv_addr)); if(listen(listenfd, 10) == -1) { printf("Failed to listen\n"); return -1; } FILE *fp=fopen("output.txt","w"); int nxt_sqno=0; struct packet ack1,ack2,p1,p2; //buff.last_packet=false; //buff.offset=-1; p1.last_packet=false; p2.last_packet=false; // unsigned char offset_buffer[10] = {'\0'}; // unsigned char command_buffer[2] = {'\0'}; // int offset; // int command; connfd1 = accept(listenfd, (struct sockaddr*)NULL ,NULL); connfd2 = accept(listenfd, (struct sockaddr*)NULL ,NULL); // printf("both sockets connected\n"); fd_set rfds; while(1){ FD_ZERO(&rfds); FD_SET(connfd1,&rfds); FD_SET(connfd2,&rfds); int sret=select(max(connfd1,connfd2)+1,&rfds,NULL,NULL,NULL); if(FD_ISSET(connfd1,&rfds)){ memset(&p1,0,sizeof(p1)); read(connfd1,&p1,sizeof(p1)); if(p1.pkt_size==0) break; printf("RCVD PKT: Seq.No %lu of size %zu bytes from channel %lu\n",p1.offset,p1.pkt_size,p1.id); if(pdr_func()){ fseek(fp,p1.offset,SEEK_SET); fwrite(p1.sendBuff,1,p1.pkt_size,fp); ack1.last_packet=p1.last_packet; ack1.offset=p1.offset; write(connfd1,&ack1,sizeof(ack1)); printf("SENT ACK:for PKT with Seq.No %lu from channel %lu \n",p1.offset,p1.id ); } } if(FD_ISSET(connfd2,&rfds)){ memset(&p2,0,sizeof(p2)); read(connfd2,&p2,sizeof(p2)); if(p2.pkt_size==0) break; printf("RCVD PKT: Seq.No %lu of size %zu bytes from channel %lu \n",p2.offset,p2.pkt_size,p2.id ); if(pdr_func()){ ack2.last_packet=p2.last_packet; ack2.offset=p2.offset; fseek(fp,p2.offset,SEEK_SET); fwrite(p2.sendBuff,1,p2.pkt_size,fp); write(connfd2,&ack2,sizeof(ack2)); printf("SENT ACK:for PKT with Seq.No %lu from channel %lu \n",p2.offset,p2.id ); } } } fclose(fp); return 0; }
C
/* * udpclient.c - A simple UDP client * usage: udpclient <host> <port> */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> #define BUFSIZE 1024 int option; char input_user[5]; /* * error - wrapper for perror */ void error(char *msg) { perror(msg); exit(0); } void command() { printf("Get user command:\n"); printf("\n1. get\n2. put\n3. delete\n4. ls\n5. exit\n"); scanf("%s",input_user); printf("%s\n",input_user); if(!(strcmp(input_user,"get"))) { option=1; } else if(!(strcmp(input_user,"put"))) { option=2; } else if(!(strcmp(input_user,"delete"))) { option=3; } else if(!(strcmp(input_user,"ls"))) { option=4; } else if(!(strcmp(input_user,"exit"))) { option=5; } } int main(int argc, char **argv) { int sockfd, portno, n; int serverlen; struct sockaddr_in serveraddr; //struct sockaddr_in serveraddr; /* server's addr */ struct sockaddr_in clientaddr; struct hostent *server; char *hostname; char buf[BUFSIZE]; char filename[100]; char delfile[100]; int loop,i,j,count=0; int ack; char length[10]; char list[65000]; int length_file,residue; int nlists; FILE *fp; /* check command line arguments */ if (argc != 3) { fprintf(stderr,"usage: %s <hostname> <port>\n", argv[0]); exit(0); } hostname = argv[1]; portno = atoi(argv[2]); /* socket: create the socket */ sockfd = socket(AF_INET, SOCK_DGRAM, 0); if (sockfd < 0) error("ERROR opening socket"); /* gethostbyname: get the server's DNS entry */ server = gethostbyname(hostname); if (server == NULL) { fprintf(stderr,"ERROR, no such host as %s\n", hostname); exit(0); } /* build the server's Internet address */ bzero((char *) &serveraddr, sizeof(serveraddr)); serveraddr.sin_family = AF_INET; bcopy((char *)server->h_addr, (char *)&serveraddr.sin_addr.s_addr, server->h_length); serveraddr.sin_port = htons(portno); /* --------------------------- * get a message from the user * ---------------------------*/ while(1) { bzero(buf, 100); com: command(); strcpy(buf,input_user); printf("%d",option); /*now depending on the option do different commands*/ /* send the message to the server */ serverlen = sizeof(serveraddr); n = sendto(sockfd, buf, 100, 0, &serveraddr, serverlen); if (n < 0) error("ERROR in sendto"); /* * print the server's reply */ /* n = recvfrom(sockfd, buf, strlen(buf), 0, &serveraddr, &serverlen); if (n < 0) error("ERROR in recvfrom"); printf("Echo from server: %s", buf); */ switch(option) { /*----------------------------------- * Client commands the server to send * the required file * ----------------------------------*/ case 1: //Clearing the buffer to avoid data corruption bzero(buf,100); bzero(length,10); bzero(filename,100); //Asking the filename printf("Enter filename\n"); scanf("%s",filename); /*Sending the file name and getting the size from * the server*/ n=sendto(sockfd,filename,100,0,&serveraddr,serverlen); if(n<0) error("ERROR in sendto"); n = recvfrom(sockfd, length, 10, 0, (struct sockaddr *) &serveraddr, &serverlen); if (n < 0) error("ERROR in recvfrom"); length_file=atoi(length); printf("%d",length_file); bzero(buf,100); loop=length_file/100; residue=length_file%100; fp=fopen("foo_test","w+"); /* File reception*/ for(i=0;i<loop;i++) { bzero(length,10); bzero(buf,100); ackgive: n = recvfrom(sockfd, buf, 100, 0, (struct sockaddr *) &serveraddr, &serverlen); if (n < 0) error("ERROR in recvfrom"); n=recvfrom(sockfd,length,10,0,(struct sockaddr *)&serveraddr,&serverlen); n=sendto(sockfd,length, 10,0,&serveraddr,serverlen); ack=atoi(length); if(ack==count) { fwrite(buf,1,100,fp); printf("ack=%ld\n",ack); printf("count=%d\n",count); count++; } else { printf("\nFile not recived\n"); goto ackgive; } } //Running for the last bytes of the file if(residue!=0) { recack: bzero(buf,100); bzero(length,10); n=sendto(sockfd,length,10,0,&serveraddr,serverlen); if(n<0) error("ERROR in sendto"); n = recvfrom(sockfd, buf, residue, 0,(struct sockaddr *) &serveraddr, &serverlen); if (n < 0){ error("ERROR in recvfrom"); } // clientlen=sizeof(clientaddr); fwrite(buf,1,residue,fp); printf("Acknowledgement=%s\n",length); fclose(fp); break; } /*------------------------------------ * The client gives the file to the server * -------------------------------------*/ case 2: bzero(buf, 100); bzero(length,10); bzero(filename,100); /*Filename to transmit the file*/ printf("Enter filename\n"); scanf("%s",filename); fp=fopen(filename,"r"); if(fp==NULL) { printf("File does not exist\n"); exit(0); } /*----------------------------- * The file size is determined and * transmitted via the socket * -----------------------------*/ fseek(fp,0,SEEK_END); length_file=ftell(fp); printf("%ld\n",length_file); sprintf(length,"%ld",length_file); serverlen = sizeof(serveraddr); fseek(fp,0,SEEK_SET); n=sendto(sockfd,length,10,0,&serveraddr,serverlen); if(n<0) error("Error in sendto"); loop=length_file/100; residue=length_file%100; for(i=0;i<loop;i++) { bzero(buf,100); bzero(length,10); // sprintf(length,"%d",count); fread(buf,1,100,fp); /* send the message to the server */ // serverlen = sizeof(serveraddr); ackrec: sprintf(length,"%ld",count); n = sendto(sockfd, buf, 100, 0, &serveraddr, serverlen); if (n < 0) error("ERROR in sendto1"); n = sendto(sockfd,length,10,0,&serveraddr,serverlen); if(n<0) error("ERROR in sendto2"); bzero(length,10); n = recvfrom(sockfd,length,10,0,(struct sockaddr *)&serveraddr,&serverlen); if(n<0) error("ERROR in recvfrom"); ack=atoi(length); printf("Packet=%ld\n",ack); if(ack==count) { printf("count = %ld\n",count); count++; } else { printf("\nPacket not recived\n"); /* n=sendto(sockfd,"send",4,0,&serveraddr,serverlen); if(n<0) error("ERROR in sendto3"); */ goto ackrec; } } if(residue!=0) { cliack: bzero(buf,100); fread(buf,1,residue,fp); n=sendto(sockfd,buf,residue,0,&serveraddr,serverlen); if(n<0) error("Residue send error"); bzero(length,10); n=recvfrom(sockfd,length,10,0,(struct sockaddr *)&serveraddr,&serverlen); if(n<0) error("ERROR in recvfrom"); n=sendto(sockfd,length,10,0,&serveraddr,serverlen); if(n<0) error("ERROR in sendto"); if(strcmp(length,"ack")) { printf("not recived\n"); goto cliack; } fclose(fp); } break; /*------------------------------------- * Command the server to delete the given or exit * or exit if the file does not exist * ------------------------------------*/ case 3: filedelete: bzero(delfile,100); printf("Enter the path to delete the file\n"); scanf("%s",delfile); n=sendto(sockfd,delfile,100,0,&serveraddr,serverlen); if(n<0) error("ERROR in sendto1"); bzero(delfile,100); n=recvfrom(sockfd,delfile,3,0,(struct sockaddr *)&serveraddr,&serverlen); if(n<0) error("ERROR in recvfrom"); n=sendto(sockfd,delfile,3,0,&serveraddr,serverlen); if(n<0) error("ERROR in sendto"); if(strcmp(delfile,"ack")!=0) { printf("No acknowledgement"); goto filedelete; } break; /*------------------------------------ * Command the server to send the list * of files to the client and save in * a file * -----------------------------------*/ case 4: listfile: printf("Requesting entry of files\n"); bzero(list,100); FILE *fp2=fopen("lists1","a+"); n=sendto(sockfd,length,10,0,&serveraddr,serverlen); if(n<0) error("ERROR in sendto"); bzero(length,10); n=recvfrom(sockfd,length,10,0,(struct sockaddr *)&serveraddr,&serverlen); if(n<0) error("ERROR in recvfrom"); length_file=atoi(length); for(i=0;i<length_file;i++) { n=recvfrom(sockfd,list,1,0,(struct sockaddr *)&serveraddr,&serverlen); if(n<0) error("ERROR in recvfrom"); fwrite(list,1,1,fp2); n=sendto(sockfd,"ack",strlen("ack"),0,&serveraddr,serverlen); if(n<0) error("ERROR in sendto"); bzero(length,10); n=recvfrom(sockfd,length,3,0,(struct sockaddr *)&serveraddr,&serverlen); if(n<0) error("ERROR in recvfrom"); if(strcmp(length,"ack")!=0) { printf("list not available"); goto listfile; } } fclose(fp2); break; /*-------------------- * Exit gracefully * ------------------*/ case 5: printf("\nThank You\n"); exit(0); break; default: bzero(buf,100); n=sendto(sockfd,length,10,0,&serveraddr,serverlen); if(n<0) error("ERROR in sendto"); n=recvfrom(sockfd,buf,10,0,(struct sockaddr *)&serveraddr,&serverlen); if(n<0) error("ERROR in recvfrom"); goto com; break; } } close(sockfd); }
C
#ifdef HAVE_CONFIG_H #include "config.h" #endif #include "newsfeed_private.h" #include <string.h> #include "mailimf.h" #include "timeutils.h" static inline time_t get_date(struct mailimf_date_time * date_time) { struct tm tmval; time_t timeval; tmval.tm_sec = date_time->dt_sec; tmval.tm_min = date_time->dt_min; tmval.tm_hour = date_time->dt_hour; tmval.tm_sec = date_time->dt_sec; tmval.tm_mday = date_time->dt_day; tmval.tm_mon = date_time->dt_month - 1; tmval.tm_year = date_time->dt_year - 1900; timeval = mail_mkgmtime(&tmval); timeval -= date_time->dt_zone * 36; return timeval; } time_t newsfeed_rfc822_date_parse(char * text) { time_t date; struct mailimf_date_time * date_time; size_t current_pos; int r; date = (time_t) -1; current_pos = 0; r = mailimf_date_time_parse(text, strlen(text), &current_pos, &date_time); if (r == MAILIMF_NO_ERROR) { date = get_date(date_time); mailimf_date_time_free(date_time); } return date; }
C
#include <stdio.h> #include <stdlib.h> #include <time.h> int main() { srand(time(NULL)); //int comp=rand()%99+1; int a=1,b=99; char answer; do { printf("%d\n",(a+b)/2); printf("Is it less/more than your number or equal?\n""l/m/e\n",answer); scanf(" %c",&answer); if(answer=='l') { a=(a+b)/2+1; } else if(answer=='m') { b=(a+b)/2-1; } }while(answer!='e'); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "api.h" #include "http.h" #include "todo.h" static unsigned int id; static todo_t *todo_head; static todo_t *todo_tail; /** * api_route - dispatch an API call to the appropriate function * * @request: HTTP request to dispatch * * Return: If memory allocation fails, return NULL. * Otherwise, return a response to send to the client. */ char *api_route(http_request_t *request) { static api_endpoint_t api_endpoints[] = { {PATH_TODOS, HTTP_GET, get_todos}, {PATH_TODOS, HTTP_POST, post_todos}, {PATH_TODOS, HTTP_DELETE, delete_todos}, {NULL, NULL, NULL} }; api_endpoint_t *api_endpoint = api_endpoints; while (api_endpoint->path) { if (!strcasecmp(request->path, api_endpoint->path) && !strcasecmp(request->method, api_endpoint->method)) return (api_endpoint->fn(request)); api_endpoint += 1; } return (strdup(HTTP_404)); } /** * post_todos - POST request to todos endpoint * * @request: HTTP request * * Return: If memory allocation fails, return NULL. * Otherwise, return a response to send to the client. */ char *post_todos(http_request_t *request) { char *query, *key, *value, *body_save, *query_save; char *title = NULL, *description = NULL; char buf1[BUF_SZ] = {0}, buf2[BUF_SZ] = {0}; todo_t *todo = NULL; dict_item_t *content_length_item = dict_get(request->headers, CONTENT_LENGTH); unsigned long int content_length = 0; if (content_length_item) content_length = strtoul(content_length_item->value, NULL, 10); if (content_length == 0) return (strdup(HTTP_411)); request->body[content_length] = '\0'; query = strtok_r(request->body, "&", &body_save); while (query) { key = strtok_r(query, "=", &query_save); value = strtok_r(NULL, "=", &query_save); printf("Body param: \"%s\" -> \"%s\"\n", key, value); if (!strcasecmp(key, TODO_TITLE)) title = value; if (!strcasecmp(key, TODO_DESCRIPTION)) description = value; query = strtok_r(NULL, "&", &body_save); } if (!title || !description) return (strdup(HTTP_422)); todo = calloc(1, sizeof(*todo)); if (!todo) return (NULL); todo->id = id++; todo->title = strdup(title); todo->description = strdup(description); if (todo_tail) todo_tail->next = todo, todo_tail = todo; else todo_tail = todo_head = todo; sprintf(buf2, "{\"" TODO_ID "\":%d,\"" TODO_TITLE "\":\"%s\",\"" TODO_DESCRIPTION "\":\"%s\"}", todo->id, todo->title, todo->description); sprintf(buf1, HTTP_201_NOCRLF CRLF CONTENT_LENGTH ": %lu" CRLF CONTENT_TYPE ": " CONTENT_TYPE_JSON CRLF CRLF "%s", strlen(buf2), buf2); return (strdup(buf1)); } /** * get_todos - GET request to todos endpoint * * @request: HTTP request * * Return: If memory allocation fails, return NULL. * Otherwise, return a response to send to the client. */ char *get_todos(http_request_t *request) { char buf1[BUF_SZ] = {0}, buf2[BUF_SZ] = {0}; todo_t *todo = todo_head; dict_item_t *param_id = dict_get(request->params, "id"); char *id_end = NULL; ssize_t id = -1; if (param_id) { id = strtoul(param_id->value, &id_end, 10); if (!*param_id->value || *id_end) id = -1; while (todo && todo->id != id) todo = todo->next; if (!todo) return (strdup(HTTP_404)); sprintf(buf2, "{\"" TODO_ID "\":%d,\"" TODO_TITLE "\":\"%s\",\"" TODO_DESCRIPTION "\":\"%s\"}", todo->id, todo->title, todo->description); } else { buf2[0] = '['; while (todo) { sprintf(buf2 + strlen(buf2), "{\"" TODO_ID "\":%d,\"" TODO_TITLE "\":\"%s\",\"" TODO_DESCRIPTION "\":\"%s\"}%s", todo->id, todo->title, todo->description, todo->next ? "," : ""); todo = todo->next; } buf2[strlen(buf2)] = ']'; } sprintf(buf1, HTTP_200_NOCRLF CRLF CONTENT_LENGTH ": %lu" CRLF CONTENT_TYPE ": " CONTENT_TYPE_JSON CRLF CRLF "%s", strlen(buf2), buf2); return (strdup(buf1)); } /** * delete_todos - DELETE request to todos endpoint * * @request: HTTP request * * Return: If memory allocation fails, return NULL. * Otherwise, return a response to send to the client. */ char *delete_todos(http_request_t *request __attribute__((unused))) { todo_t *todo = todo_head, **todo_prev = &todo_head; dict_item_t *param_id = dict_get(request->params, "id"); char *id_end = NULL; ssize_t id = -1; if (!param_id) return (strdup(HTTP_404)); id = strtoul(param_id->value, &id_end, 10); if (!*param_id->value || *id_end) return (strdup(HTTP_404)); while (todo && todo->id != id) { todo_prev = &todo->next; todo = todo->next; } if (!todo) return (strdup(HTTP_404)); *todo_prev = todo->next; free(todo->title); free(todo->description); free(todo); return (strdup(HTTP_204)); }
C
#include <stdio.h> #include <stdlib.h> typedef struct unitdata { char unitType; char player; float health; char ammo1; char ammo2; short fuel; } unit; typedef struct playerdata { int money; short buildingsOwned; short unitData; } player; typedef struct buildingdata { char buildingType; char player; } building; typedef struct gamedata { int turnNum; char whoseTurn; unsigned char mapData[MAP_WIDTH][MAP_HEIGHT]; // MAX_UNITS won't be overflowed, set this to a high enough level that people won't reach it. player p1; player p2; unit unitData[5]; } game; void doThis (game *data); void doThat (game *data); int main (int argc, char *argv[]) { game data; game *dataPtr = &data; data.p1.money = 1; printf("%d\n", data.p1.money); doThis (dataPtr); printf("%d\n", data.p1.money); return EXIT_SUCCESS; } void doThis (game *data) { data->p1.money = 2; printf("%d\n", data->p1.money); doThat (data); printf("%d\n", data->p1.money); } void doThat (game *data) { data->p1.money = 3; }
C
#include <stdio.h> #include <stdlib.h> #include <math.h> int main(int argc, char*argv[]) { /* Programa para calcular o MDC usando laos de repetio*/ printf("Programa para calcular o MDC entre 4 numeros inteiros (Questao 6 letra c ) \n\n"); int num1, num2, num3, num4, resto1, resto2, resto3; printf("Digite quatro numeros: "); scanf("%d %d %d %d", &num1, &num2, &num3, &num4); resto1 = num1%num2; while(resto1!=0)//Lao para calcular o MDC entre os primeiros dois inteiros// { num1 = num2; num2 = resto1; resto1 = num1%num2; } resto2 = num3%num2; while(resto2!=0)//Lao para calcular o MDC // { num3 = num2; num2 = resto2; resto2 = num3%num2; } resto3 = num4%num2; while(resto2!=0)//Lao para calcular o MDC // { num4 = num2; num2 = resto3; resto3 = num4%num2; } printf("O MDC dos quatro numeros = %d\n", num2); return 0; }
C
#include "holberton.h" #include <stdio.h> #include <stdlib.h> /** * main - multiplies two integers * @argc: ammount of arguments * @argv: arguments * Return: always 0 on succes */ int main(int argc, char *argv[]) { int multReslt, a, b; if (argc < 3) { printf("Error\n"); return (-1); } a = atoi(argv[1]); b = atoi(argv[2]); multReslt = a * b; printf("%d\n", multReslt); return (0); }
C
#include<stdio.h> void main() { int A[10][10],B[10][10],sum[10][10]; int m,n,p,q,i,j,k; printf("Enter the no of rows and columns: A\n"); scanf("%d%d",&m,&n); printf("Enter the no of rows and columns : B\n"); scanf("%d%d",&p,&q); if (n!=p) {printf("Matrix Multiplication is not Possible \n"); } else{ printf("Enter the elements of 1st matrix\n"); for(i=0;i<m;i++) for(j=0;j<n;j++) scanf("%d",&A[i][j]); printf("Enter the elements of 2nd matrix\n"); for(i=0;i<p;i++) for(j=0;j<q;j++) scanf("%d",&B[i][j]); //Matrix Multiplication operation for(i=0;i<m;i++) for(j=0;j<n;j++) sum[i][j]=0; for(i=0;i<m;i++){ for(j=0;j<q;j++){ for(k=0;k<n;k++){ sum[i][j]+= A[i][k]*B[k][j]; }}} printf("Multiplied Matrix\n"); for(i=0;i<m;i++){ for(j=0;j<q;j++){ printf("%d ",sum[i][j]); } printf("\n"); } } }
C
/** * strings -- prints out all the character strings in an executable file. * * Usage: strings [-xaop] [-nnn] [file ...] * * Options: * -x print offset of each string in the file in hex * -a print offset of each string in the file in ASCII * -o print offset of each string in the file in octal * -p mask out the parity bit */ #include <sys/stat.h> #include <l.out.h> #include <stdio.h> #include <canon.h> #include <ctype.h> /* The lamentable <rico.h>... */ #define bool char #define TRUE (0 == 0) #define FALSE (!TRUE) int nchars = 4; /* minimum character string length */ bool flag; /* input condition: FALSE for redirection, else TRUE */ bool aflag; /* option flags: ascii line numbering */ bool xflag; /* hex line numbering */ bool oflag; /* octal line numbering */ int pbit; /* parity bit mask */ long addr; /* current seek position in data space segment */ long count; /* size of data space segment */ char * buff; /* string to store beginning NCHARS characters in character string */ bool printstr(); bool lookfor(); extern FILE * freopen(); extern char * malloc(); main( argc, argv ) int argc; char * argv[]; { char * malloc(); char * s; while( (--argc > 0) && ((*++argv)[0] == '-') ) { /* * Read options declared. */ for( s = argv[0] + 1 ; *s != '\0'; s++ ) { /* * Set minimum string length for recognizing * character strings. */ if( isdigit( *s ) ) { if( (nchars = atoi( s )) <= 0 ) fatal( "string length must be greater than 0" ); break; } /* * Set appropriate flags or bit mask according to * option declared. */ switch( *s ) { case 'x': if( aflag | oflag | xflag ) usage(); xflag = TRUE; break; case 'a': if( aflag | oflag | xflag ) usage(); aflag = TRUE; break; case 'o': if( aflag | oflag | xflag ) usage(); oflag = TRUE; break; case 'p': pbit = 0200; break; default: usage(); } } } /* * Get memory for string buffer. */ if( (buff = malloc( nchars )) == NULL ) fatal( "not enough memory" ); /* * Set input condition: * FALSE if input is through indirection, else TRUE. */ if( argc > 0 ) flag = TRUE; else { argc++; flag = FALSE; } /* * Examine each file for strings of the required length. */ while( argc-- ) { /* * Test for read permission in file. */ if( flag && freopen( *argv, "r", stdin ) == NULL ) fatal( "can't open %s", argv[0] ); /* * Test if file is an executable file. */ if( checklout( stdin ) < 0 ) { if( flag ) { fprintf( stderr, "strings: '%s' not executable\n", *argv); ++argv; continue; } else { fprintf( stderr, "strings: not executable\n" ); exit( 1 ); } } /* * Display file name if available. */ if( flag ) fprintf( stderr, "%s:\n", *argv ); /* * Display all character strings in file. */ while( printstr() ) ; ++argv; } free( buff ); exit( 0 ); } /** * bool * printstr() * * Input: None. * * Action: Display character strings in file. * * Return: FALSE on error or no character strings available, * otherwise TRUE. * * Note: None. * */ bool printstr() { char c; char * p; char * q; p = buff; q = p + nchars; /* * Check if character strings are available in file. */ if( ! lookfor() ) return( FALSE ); /* * Display line number according to the format option specified. * Ignore if no format option is set. */ if( aflag ) printf( "%-6D: ", addr-nchars ); else if( oflag ) printf( "0%-6O: ", addr-nchars ); else if( xflag ) printf( "0x%-6X: ", addr-nchars ); /* * Display printable characters found. */ do { putchar( *p++ ); } while( p < q ); /* * Display remaining printable characters in file. */ for ( ;; ) { if( --count <= 0L ) return( FALSE ); ++addr; c = getchar(); if( c == EOF ) return( FALSE ); if( ! (isascii( (c) & ~pbit ) && isprint( (c) & ~pbit )) ) break; putchar( c ); } putchar( '\n' ); return( TRUE ); } /** * bool * lookfor() * * Input: None. * * Action: Look for the first character string in file. * * Return: TRUE if a character string is found, else FALSE. * * Note: None. * */ bool lookfor() { char c; char * p; char * q; q = buff + nchars; for( ;; ) { /* * Seek in data space segment of file until a printable * character is encountered. */ do { if( --count <= 0L ) return( FALSE ); ++addr; c = getchar(); if( c == EOF ) return( FALSE ); } while( ! (isascii( (c) & ~pbit ) && isprint( (c) & ~pbit )) ); p = buff; /* * Check for valid character string. */ do { *p++ = c; if( p >= q ) return( TRUE ); if( --count <= 0L ) return( FALSE ); ++addr; c = getchar(); if( c == EOF ) return( FALSE ); } while( isascii( (c) & ~pbit ) && isprint( (c) & ~pbit ) ); } } /** * int * checklout( f ) * * register FILE * f; * * Input: f - file pointer to stdin. * * Action: Check if executable (l.out) file. * * Return: Returns -1 on error or file is not executable, otherwise 0. * * Note: None. * */ int checklout( f ) register FILE * f; { register int i; /* counter variable */ int ret = -1; /* returning error value */ struct stat s; /* file attributes */ struct ldheader l; /* file header information */ if( fstat( fileno( f ), &s ) == -1 ) return( ret ); /* * File type check. Return unless regular file. */ if( (s.st_mode & S_IFMT) != S_IFREG ) return( ret ); /* * Get file header information. */ if( fread( &l, sizeof( l ), 1, f ) != 1 ) { rewind( f ); return( ret ); } rewind( f ); if( l.l_magic != L_MAGIC ) return( ret ); /* * Correct canonical effect on file format information. */ for( i = 0 ; i < NLSEG ; ++i ) canlong(l.l_ssize[i]); /* * Get seek position to the beginning memory location of the * data space segment in the executable file. */ fseek( f, (long)sizeof(l) + l.l_ssize[L_SHRI] + l.l_ssize[L_PRVI], 0 ); addr = ftell( f ); /* * Get size of data space segment of file. */ count = l.l_ssize[L_SHRD] + l.l_ssize[L_PRVD]; if( count == 0L ) { fatal( "zero-length data segments" ); /* NOTREACHED */ } ++count; return( 0 ); } /** * void * fatal( arg0 ) * * char * arg0; * * Input: arg0 - pointer to string containing the error message. * * Action: Display fatal error message and exit. * * Return: Never return, always exit. * * Note: None. * */ fatal( arg0 ) char * arg0; { fflush( stdout ); fprintf( stderr, "strings: %r\n", &arg0 ); exit( 1 ); } /** * void * usage() * * Input: None. * * Action: Display command usage format. * * Return: Never return, always exit. * * Note: None. * */ usage() { fprintf( stderr, "Usage: strings [-xaop] [-nnn] [file ...]\n" ); exit( 1 ); }
C
#include <stdio.h> unsigned getbits(unsigned, int, int); main() { unsigned a = getbits(255, 3, 4); printf("%d\n", a); unsigned b = getbits(3, 1, 2); printf("%d\n", b); } unsigned getbits(unsigned x, int p, int n) { return (x >> (p+1-n)) & ~(~0 << n); } /* * Output * * 15 * 3 */
C
// // Created by liu on 17-7-25. // #include "sha3.h" #include <time.h> #include <stdio.h> void sha3_generate_rc() { for (int i = 0; i < 255; i++) { uint8_t R[9] = {1, 0, 0, 0, 0, 0, 0, 0, 0}; for (int j = 1; j <= i; j++) { for (int k = 8; k > 0; k--) R[k] = R[k - 1]; R[0] = 0; R[0] ^= R[8]; R[4] ^= R[8]; R[5] ^= R[8]; R[6] ^= R[8]; } printf("%d,", R[0]); if (i % 16 == 15)printf("\n"); } printf("\n"); } double sha3_test(size_t length) { sha3_string M = malloc(length); for (int i = 0; i < length; i++) { M[i] = rand() % 2; } long time1 = clock(); sha3_string result = sha3_hash(M, length, SHA3_512); long time2 = clock(); sha3_string_print(result, 512); free(M); free(result); return difftime(time2, time1); } int main() { //srand(time(0)); int count = 8; size_t mb = 1 << 23; size_t size = 1; size_t length = mb * size; double t = 0; for (int i = 0; i < count; i++) t += sha3_test(length); printf("The average running speed is %lf MB/s\n", size / (t / CLOCKS_PER_SEC / count)); return 0; }
C
// prints the list of types of airplanes capable of operating flights over 10,000 Km in length // may have some difference at distance of two airports because choose pi as 3.14 // fail to separate the line #include <stdio.h> #include <stdlib.h> #include <sqlite3.h> int main(int argc, char *argv[]) { sqlite3 *db; //the database sqlite3_stmt *stmt; //the select statement int rc; if( argc!=2 ) { fprintf(stderr, "Usage: %s <database> \n", argv[0]); return(1); } rc = sqlite3_open(argv[1], &db); //open a connnection to an SQLite database file if( rc ) { fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db)); sqlite3_close(db); return(1); } sqlite3_enable_load_extension(db,1); sqlite3_load_extension(db,"libsqlitefunctions",0,0); /******************************************************************* * calculate the distance of each routes with commercial flights ** * part of the formular ** * cites from http://www.movable-type.co.uk/scripts/latlong.html ** ********************************************************************/ char *sql_stmt = "create table length as select r.Source_airport, r.Destination_airport, \ (sin((p2.Latitude-p1.Latitude)/2*3.14/180)*sin((p2.Latitude-p1.Latitude)/2*3.14/180) \ +cos(p1.Latitude*3.14/180)*cos(p2.Latitude*3.14/180)*sin((p2.Longitude-p1.Longitude)/2*3.14/180)* \ sin((p2.Longitude-p1.Longitude)/2*3.14/180)) as a, r.Equipments \ from airports p1, airports p2, routes r, airlines l \ where r.Source_airport_ID = p1.Airport_ID and \ r.Destination_airport_ID = p2.Airport_ID and \ r.Airline_ID = l.Airline_ID"; rc = sqlite3_prepare_v2(db, sql_stmt, -1, &stmt, 0); if (rc != SQLITE_OK) { fprintf(stderr, "Preparation failed1: %s\n", sqlite3_errmsg(db)); sqlite3_close(db); return 1; } while((rc = sqlite3_step(stmt)) == SQLITE_ROW) { int col; for(col=0; col<sqlite3_column_count(stmt)-1; col++) { printf("%s|", sqlite3_column_text(stmt, col)); } printf("%s", sqlite3_column_text(stmt, col)); printf("\n"); } sqlite3_finalize(stmt); //always finalize a statement /*********************************************************** * calculate the complete distance from two airports and ** * choose the distance >= 10000km ** ***********************************************************/ char *stmt2 = "select l.Equipments, \ 6371*2*atan2(sqrt(a),sqrt(1-a)) \ as distance from length l \ where distance >= 10000 group by distance \ order by distance desc"; rc = sqlite3_prepare_v2(db, stmt2, -1, &stmt, 0); if (rc != SQLITE_OK) { fprintf(stderr, "Preparation failed2: %s\n", sqlite3_errmsg(db)); sqlite3_close(db); return 1; } while((rc = sqlite3_step(stmt)) == SQLITE_ROW) { int col; for(col=0; col<sqlite3_column_count(stmt)-1; col++) { printf("%s|", sqlite3_column_text(stmt, col)); } printf("%s", sqlite3_column_text(stmt, col)); printf("\n"); } sqlite3_finalize(stmt); //always finalize a statement char *zErrMsg = 0; char *drop = "drop table length"; rc = sqlite3_exec(db, drop, 0, 0, &zErrMsg); sqlite3_close(db); return 0; }
C
#include <stdio.h> int main(void) { int t,n,a,res; scanf("%d",&t); while(t--) { res=0; scanf("%d",&n); while(n--) { scanf("%d",&a); res^=a; } printf("%d\n",res); } return 0; }
C
#include<stdio.h> #include<stdlib.h> struct nodemain { struct nodemain *next; int data; struct node *adjmain; int visited; int visitedcoloring; int color; struct nodecolor *adjcolorlist; }; struct node { int data; struct nodemain *mainaddr; struct node *adj; }; struct nodecolor { int data; struct nodecolor *nodecolornext; }; struct dftsequence { int data; struct dftsequence *dftnext; struct nodemain *nodeaddr; }; struct nodemain *makenode(struct nodemain *root,int x){ if(root==NULL) return root; struct nodemain *s=(struct nodemain*)malloc(sizeof(struct nodemain)); struct nodemain *p=root; while(root->next!=NULL){ root=root->next; } root->next=s; s->next=NULL; s->data=x; s->adjmain=NULL; s->visited=0; s->visitedcoloring=0; s->adjcolorlist=NULL; printf("%d:%d:%u:%u:",s->data,s->visited,s,s->next); return p; } struct nodemain *findnode(struct nodemain *root,int x){ if(root==NULL) return root; while(root->next!=NULL&& root->data!=x){ root=root->next; } if(root->data==x){ return root; }else{ printf("wrong vertex inserted!! No such vertex as %d exists",x); exit(1); } } void createandlink(int x,struct nodemain *p,struct nodemain *c){ struct node *aux,*aux1; aux=(struct node*)malloc(sizeof(struct node)); aux->data=x; aux->mainaddr=findnode(p,x); aux->adj=NULL; if(c->adjmain==NULL){ c->adjmain=aux; }else{ aux1=c->adjmain; while(aux1->adj!=NULL){ aux1=aux1->adj; } aux1->adj=aux; } } void makedft(struct dftsequence *aux,int x,struct nodemain *root){ while(aux->dftnext!=NULL){ aux=aux->dftnext; } struct dftsequence *aux1; aux1=(struct dftsequence*)malloc(sizeof(struct dftsequence)); aux->dftnext=aux1; aux1->nodeaddr=root; aux1->data=x; aux1->dftnext=NULL; } void dft(struct nodemain *root,struct nodemain *root1,struct dftsequence *aux){ struct node *first; root->visited=1; if(root==root1){ aux->data=root->data; aux->dftnext=NULL; aux->nodeaddr=root; printf("%u\n",root ); }else{ makedft(aux,root->data,root); } printf("%d\n",root->data); if(root->adjmain!=NULL){ first=root->adjmain; while(first!=NULL){ if(first->mainaddr->visited!=1){ dft(first->mainaddr,root1,aux); } first=first->adj; } return; }else{ return; } } int valuenotpresent(struct nodecolor *p,int x){ while(p->nodecolornext!=NULL&&p->data!=x){ printf("%u\n",p); p=p->nodecolornext; } if(p->data==x){ return 0; }else{ return 1; } } int findminimum(struct nodemain *s,int n){ struct nodecolor *p; int x; if(s->adjcolorlist==NULL){ return 0; } p=s->adjcolorlist; for(int i=0;i<n;i++){ x=valuenotpresent(p,i); if(x==1){ return i; } } } void addcolornode(struct nodemain *p,int x){ struct nodecolor *p1,*p2; p1=(struct nodecolor*)malloc(sizeof(struct nodecolor)); p1->data=x; p1->nodecolornext=NULL; if(p->adjcolorlist==NULL){ p->adjcolorlist=p1; return; } p2=p->adjcolorlist; while(p2->nodecolornext!=NULL){ p2=p2->nodecolornext; } p2->nodecolornext=p1; } void graphcoloring(struct dftsequence *d,int n){ struct nodemain *s; struct node *s1; int x; s=d->nodeaddr; s1=s->adjmain; s->visitedcoloring=1; if(s->adjcolorlist==NULL){ s->color=0; }else{ x=findminimum(s,n); s->color=x; } while(s1!=NULL){ if(s1->mainaddr->visitedcoloring!=1){ addcolornode(s1->mainaddr,s->color); } s1=s1->adj; printf("%u\n",s1); } } int main(){ int n,n1,a; struct nodemain *head,*s; struct node *aux,*aux1; printf("hello world"); printf("\nhow many nodes you have?"); scanf("%d",&n); for(int i=1;i<=n;i++){ if(i==1){ head=(struct nodemain*)malloc(sizeof(struct nodemain)); printf("%u\n",head ); head->next=NULL; head->data=i; head->visited=0; head->visitedcoloring=0; head->adjcolorlist=NULL; head->adjmain=NULL; }else{ head=makenode(head,i); } } s=head; for(int i=1;i<=n;i++){ printf("\n%d:%d:%u:%u:%u\n",s->data,s->visited,s,s->next,s->adjmain); s=s->next; } s=head; for(int i=1;i<=n;i++){ printf("\nenter number of adjacent nodes for node %d",i); scanf("%d",&n1); printf("\n enter adjacency list for node %d",i); for(int j=1;j<=n1;j++){ printf("\n enter node %d:",j); scanf("%d",&a); printf("%d is ajacent",a); printf("\n"); createandlink(a,head,s); /*if(j==1){ s=head; aux=(struct node*)malloc(sizeof(struct node)); s->adjmain=aux; aux->data=a; aux->mainaddr=findnode(head,a); aux->adj=NULL; }else{ aux1=(struct node*)malloc(sizeof(struct node)); s->adjmain=aux1; aux->adj=aux1; aux1->data=a; aux1->mainaddr=findnode(head,a); aux1->adj=NULL; aux=aux1; }*/ } s=s->next; printf("hello world"); } s=head; for(int i=1;i<=n;i++){ printf("\n%d node list\n",i); printf("\n%d:%d:%u:%u:%u\n",s->data,s->visited,s,s->next,s->adjmain); aux=s->adjmain; while(aux!=NULL){ printf("\n%d:%u:%u:%u\n",aux->data,aux,aux->mainaddr,aux->adj); aux=aux->adj; } s=s->next; } printf("%u calling dfs\n",head ); struct dftsequence *auxi,*auxihead; auxi=(struct dftsequence*)malloc(sizeof(struct dftsequence)); auxihead=auxi; dft(head,head,auxi); printf(" calling auxihead\n"); while(auxihead!=NULL){ printf("%d:%u:%u:%u\n",auxihead->data,auxihead ,auxihead->dftnext,auxihead->nodeaddr); auxihead=auxihead->dftnext; } auxihead=auxi; printf("%u is auxihead value\n",auxihead ); while(auxihead!=NULL){ graphcoloring(auxihead,n); auxihead=auxihead->dftnext; } s=head; struct nodecolor *ptr; while(s!=NULL){ ptr=s->adjcolorlist; printf("\n %d colorlist is:",s->data); while(ptr!=NULL){ printf("%d",ptr->data); ptr=ptr->nodecolornext; } s=s->next; } s=head; printf("\n"); while(s!=NULL){ printf("%d color is:%d\n",s->data,s->color ); s=s->next; } return 0; }
C
#include<stdio.h> #define SIZE 10 void generate_maze(char array[SIZE][SIZE]); int find_route(char array[SIZE][SIZE],int y,int x); int main(void) { char array[SIZE][SIZE]; int i,j,y=1, x= 0; generate_maze(array); for (i=0;i<SIZE;i++){ for(j=0;j<SIZE;j++){ printf("%c",array[i][j]); } printf("\n"); } if(find_route(array,y,x)==1){ printf("find the rounte\n"); }else{ printf("cannot find the route\n"); } for (i=0;i<SIZE;i++){ for(j=0;j<SIZE;j++){ printf("%c",array[i][j]); } printf("\n"); } return 0; } void generate_maze(char array[SIZE][SIZE]) { int i,j; for (i=0;i<SIZE;i++){ for(j=0;j<SIZE;j++){ if(i==1&&j!=2&&j!=9){ array[i][j]= ' '; }else if (i==2&&j!=0&&j!=2&&j!=4&&j!=6&&j!=7&&j!=9){ array[i][j]= ' '; }else if (i==3&&j!=0&&j!=2&&j!=4&&j!=6&&j!=5&&j!=7&&j!=9){ array[i][j]= ' '; }else if(i==4&&j!=0&&j!=2&&j!=7&&j!=9){ array[i][j]= ' '; }else if (i==5&&j!=0&&j!=2&&j!=4&&j!=5 && j!=6&&j!=7&&j!=9){ array[i][j]= ' '; }else if (i==6&&j!=0&&j!=2&&j!=7&&j!=9){ array[i][j]= ' '; }else if(i==7&&j!=0&&j!=2&&j!=3&&j!=4&&j!=5&&j!=7&&j!=9){ array[i][j]= ' '; } else if (i==8&&j!=0&&j!=7){ array[i][j]= ' '; } else{ array[i][j] ='#'; } } } } int find_route(char array[SIZE][SIZE],int y,int x) { if(x==9&&y==8){ array[y][x]='1'; return 1; } array[y][x]='1'; if(array[y][x+1]==' '){ if(find_route(array,y,x+1)==1) { return 1; } } if(array[y+1][x]==' '){ if(find_route(array,y+1,x)==1){ return 1; } } if(array[y-1][x]==' '){ if(find_route(array,y-1,x)==1){ return 1 ; } } if (array[y][x-1]==' ') { if(find_route(array,y,x-1)==1) { return 1; } } array[y][x]=' '; return -1; }
C
#include "Gra.h" #include "Konsola.h" // funkcja odpowiada za czyszczene planszy przed rozpoczeciem rozgrywki void CzyszczeniePlanszy(int **wysokosc, int **szerokosc) { int i, j; for (i = 0; i < **szerokosc;i++) for (j = 0;j < **wysokosc;j++) pole[i][j] = '\0'; } // funkcja odpowiada za usuwanie weza i jedzenia z talicy pole void CzyszczenieWeza(int **wysokosc, int **szerokosc) { int i, j; for (i = 0; i < **szerokosc;i++) for (j = 0;j < **wysokosc;j++) if (pole[i][j] == 'w' || pole[i][j] == 'j') pole[i][j] = '\0'; } // funkcja odpowiada za wyswietlenie poczatkowego stanu planszy wraz z ramkami void RysujPlansze(int szerokosc, int wysokosc) { //czyszczenie konsoli pod wyswietlenie gry CzyscEkran(); // rysowanie gornej krawedzi //printf(""); for (int i = 0;i <= szerokosc;i++) printf(""); printf("\n"); // rysowanie bocznych krawedzi for (int i = 0; i < wysokosc;i++) { printf(""); for (int j = 0;j < szerokosc;j++) { if (pole[j][i] == '\0') printf(" "); // wyswietla puste pole else if (pole[j][i] == 'w') printf(""); // wyswietla ikonke weza else if (pole[j][i] == 'j') printf(""); // wyswietla ikonke jedzenia else if (pole[j][i] == 'b') printf(""); //rysowanie blokow przeszkod else printf("cc"); // wyswietla 'cc'. Ma to za zadanie pokazac bledy w wyswietlaniu tablicy } if (wysokosc > 15) { if (i == 1) printf("S\n"); else if (i == 2) printf("N\n"); else if (i == 3) printf("A\n"); else if (i == 4) printf("K\n"); else if (i == 5) printf("E\n"); else if (i == 7) printf("B\n"); else if (i == 8) printf("Y\n"); else if (i == 10) printf("F\n"); else if (i == 11) printf("I\n"); else if (i == 12) printf("L\n"); else if (i == 13) printf("I\n"); else if (i == 14) printf("P\n"); else printf("\n"); } else if (wysokosc >= 5) { if (i == 0) printf("S\n"); else if (i == 1) printf("N\n"); else if (i == 2) printf("A\n"); else if (i == 3) printf("K\n"); else if (i == 4) printf("E\n"); else printf("\n"); } } // rysowanie dolej krawedzi //printf(""); for (int i = 0;i <= szerokosc;i++) printf(""); //printf(""); } // funkcja wyswietla glowe weza, dodawanie jej do pola i historii void WywietlGlowe(int *XWeza, int *YWeza, int *XMapy, int *YMapy, int *liczbaObrotowPetli, int *dlugoscWeza) { *XMapy = *XWeza * 2 + 1; *YMapy = *YWeza + 1; IdzDo(&XMapy, &YMapy); printf(""); // wyswietlanie wyswietlanieglowy weza historiaX[*liczbaObrotowPetli] = *XWeza; historiaY[*liczbaObrotowPetli] = *YWeza; } // funkcja odpowiada za czyszczenie glowy weza void UsunOgon(int *XMapy, int *YMapy, int *liczbaObrotowPetli, int *dlugoscWeza) { if (*dlugoscWeza >= 4) //warunek pozwala nie usuwac ogona, zanim nie zostanie wygenerowany caly { if (*liczbaObrotowPetli < *dlugoscWeza) { *XMapy = 2 * historiaX[abs(100 - (*dlugoscWeza - *liczbaObrotowPetli))] + 1; *YMapy = historiaY[abs(100 - (*dlugoscWeza - *liczbaObrotowPetli))] + 1; } else { *XMapy = 2 * historiaX[abs(*liczbaObrotowPetli - *dlugoscWeza)] + 1; *YMapy = historiaY[abs(*liczbaObrotowPetli - *dlugoscWeza)] + 1; } if (*dlugoscWeza >= 4) { if (*liczbaObrotowPetli < *dlugoscWeza) { pole[historiaX[abs(100 - (*dlugoscWeza - *liczbaObrotowPetli))]][historiaY[abs(100 - (*dlugoscWeza - *liczbaObrotowPetli))]] = '\0'; } else pole[historiaX[abs(*liczbaObrotowPetli - *dlugoscWeza)]][historiaY[abs(*liczbaObrotowPetli - *dlugoscWeza)]] = '\0'; } IdzDo(&XMapy, &YMapy); printf(" "); } } // funkcja odpowiada za wyswietlanie planszy wyniku void WyswietlWynik(int *XMapy, int *YMapy, int *wynik) { *XMapy = 0; *YMapy = 0; IdzDo(&XMapy, &YMapy); printf("Zjadles: %d", *wynik); } // funkcja odpowiada za losowanie startowej pozycji weza void LosujGlowe(int **wysokosc, int **szerokosc, int *XWeza, int *YWeza) { srand(time(NULL)); do { *XWeza = rand() % (**szerokosc - 2); *YWeza = rand() % **wysokosc; } while (pole[*XWeza][*YWeza] == 'b' || pole[*XWeza+1][*YWeza] == 'b'); pole[*XWeza][*YWeza] = 'w'; } // funkcja odpowiada za losowanie pokarmu dla weza void LosujPokarm(int ** wysokosc, int ** szerokosc, int * XMapy, int *YMapy, int * XJedzenia, int * YJedzenia, int * dlugoscWeza) { srand(time(NULL)); do { *YJedzenia = rand() % **wysokosc; *XJedzenia = rand() % **szerokosc; } while (pole[*XJedzenia][*YJedzenia] == 'w' || pole[*XJedzenia][*YJedzenia] == 'b'); pole[*XJedzenia][*YJedzenia] = 'j'; *XMapy = 2 * (*XJedzenia) + 1; *YMapy = *YJedzenia + 1; IdzDo(&XMapy, &YMapy); printf(""); } // funkcja odpowiada za "przechodzenie przez sciany" lub zgon przy zderzeniu sie z nimi int KolizjaZeScianami(int *XWeza, int *YWeza, int **szerokosc, int **wysokosc, int przechodzeniePrzezSciany) { if (przechodzeniePrzezSciany != 1) { if (*XWeza == **szerokosc) *XWeza = 0; else if (*XWeza == -1) *XWeza = **szerokosc - 1; if (*YWeza == **wysokosc) *YWeza = 0; else if (*YWeza == -1) *YWeza = **wysokosc - 1; } else if (przechodzeniePrzezSciany == 1) { if (*XWeza == **szerokosc) return 0; else if (*XWeza == -1) return 0; if (*YWeza == **wysokosc) return 0; else if (*YWeza == -1) return 0; } return 1; } // funkcja odpowiada za rysowanie ramki na ekranie int Main_UruchomSnake // elementy remki: -lewy gorny, -gorny, -prawy gorny, -bok, -lewy dolny, -dolny, -rawy dolny (int *const szerokosc, int *const wysokosc, int *przechodzeniePrzezSciany) //szerokosc i wysokosc pola, po ktorym rusza sie waz + przechodzenie przez sciany { //********************ZMIENNE******************************************************** int klawisz; int XMapy, YMapy; //wspolrzedne mapy int liczbaObrotowPetli = 0; //liczba obrocen petli gry int dlugoscWeza = 0; // dlugosc aktualna weza float szybkosc = 1.0; // szybkosc weza char kierunek = 'p'; // okresla kierunek, w ktorym m sie poruszac waz int XWeza, YWeza; // polozenie glowy int XJedzenia, YJedzenia; // polozenie jedzenia //*********************************************************************************** wynik = 0; //Losuj pozycje, a ktorej zacznie grac gracz LosujGlowe(&wysokosc, &szerokosc, &XWeza, &YWeza); //Wyswietlenie pokarmy LosujPokarm(&wysokosc, &szerokosc, &XMapy, &YMapy, &XJedzenia, &YJedzenia, &dlugoscWeza); //Rysowanie poczatkowego stanu gry RysujPlansze(*szerokosc, *wysokosc); do // rozpoczecie wlasciwych mechanizmow gry { //Zerowanie tablicy hisotorii w celu zwiekszenia ilosci wykonanych ruchow i zaoszczedzenia pamieci if ((liczbaObrotowPetli + 1) >= 100) liczbaObrotowPetli = 0; else liczbaObrotowPetli++; //Wyswietlanie glowy weza, dodawanie go do pola i historii WywietlGlowe(&XWeza, &YWeza, &XMapy, &YMapy, &liczbaObrotowPetli, &dlugoscWeza); pole[XWeza][YWeza] = 'w'; // czyszczenie ogona weza (nadpisywanie) UsunOgon(&XMapy, &YMapy, &liczbaObrotowPetli, &dlugoscWeza); // wyswietlanie planszy wyniku WyswietlWynik(&XMapy, &YMapy, &wynik); // "szybkosc" poruszania weza Czekaj(&szybkosc); // pobiera uderzenie przez uzytkownika PobierzJesliIstnieje(&klawisz, &kierunek); // okreslenie kierunku rochu weza if (kierunek == 'g') YWeza--; else if (kierunek == 'd') YWeza++; else if (kierunek == 'p') XWeza++; else if (kierunek == 'l') XWeza--; // zjadanie "samego siebie" lub przeszkody if (pole[XWeza][YWeza] == 'w' || pole[XWeza][YWeza] == 'b') { CzyszczenieWeza(&wysokosc, &szerokosc); return 1; } // zjadanie pokarmu if (YWeza == YJedzenia && XWeza == XJedzenia) { LosujPokarm(&wysokosc, &szerokosc, &XMapy, &YMapy, &XJedzenia, &YJedzenia, &dlugoscWeza); szybkosc += 0.2; dlugoscWeza++; wynik += 1; } // przechodzenie od scian lub klizja if (!KolizjaZeScianami(&XWeza, &YWeza, &szerokosc, &wysokosc, *przechodzeniePrzezSciany)) { CzyszczenieWeza(&wysokosc, &szerokosc); return 1; } // poczarkowe generowanie dlugosci ogona if (dlugoscWeza < 4) dlugoscWeza++; // warunki wyjscia z gry if (wynik == 100 || kierunek == 0) { CzyszczenieWeza(&wysokosc, &szerokosc); return 1; } } while (wynik != 100); } //*********************Funkcje z Menu.c, ktore wymagaja dostepu do tablicy pole[][]********************* // funckja pozwala edytowa, rysowac wlasna mape int EdytorMapy(int ** szerokosc, int ** wysokosc) { RysujPlansze(**szerokosc, **wysokosc); int klawisz = 13; int x = 2, y = 0; int *XMapy, *YMapy; XMapy = malloc(sizeof(int)); YMapy = malloc(sizeof(int)); x = 0; *XMapy = x * 2 + 1; *YMapy = y + 1; IdzDo(&XMapy, &YMapy); printf(""); while (1) { if (klawisz != 13) { if (pole[(*XMapy - 1) / 2][*YMapy - 1] == 'b') { IdzDo(&XMapy, &YMapy); printf(""); } else { IdzDo(&XMapy, &YMapy); printf(" "); } *XMapy = x * 2 + 1; *YMapy = y + 1; IdzDo(&XMapy, &YMapy); printf(""); } klawisz = Pobierz(); //obsluga strzalem i f1...f12 if (klawisz == 224) klawisz += Pobierz(); else if (klawisz == 0) klawisz -= Pobierz(); //warunki klawiszy if (klawisz == 224 + 72 && y != 0) y--; // gora else if (klawisz == 224 + 80 && y != **wysokosc - 1) y++; // dol else if (klawisz == 224 + 77 && x != **szerokosc - 1) x++; // prawo else if (klawisz == 224 + 75 && x != 0) x--; // lewo else if (klawisz == 27) // esc { if (PoprawnoscPlanszy(**szerokosc, **wysokosc)) { CzyscEkran(); free(XMapy); free(YMapy); return 1; } else { int i = 2, j =0; CzyscEkran(); RysujPlansze(**szerokosc, **wysokosc); WyswieltKomunikat(&i, &j, "Musisz zostawic miejsce dla weza i jedzenia !"); } } else if (klawisz == 13) // enter { if (pole[x][y] == 'b') pole[x][y] = '\0'; else if (pole[x][y] == '\0') pole[x][y] = 'b'; } else if (klawisz == 'r') // r { int *tX = malloc(sizeof(int)), *tY = malloc(sizeof(int)); *tX = **szerokosc, *tY = **wysokosc; CzyszczeniePlanszy(&tX, &tY); RysujPlansze(**szerokosc, **wysokosc); x = 2, y = 0; WyswieltKomunikat(&x, &y, "r - reset, esc - zapisz i wyjdz, enter - postaw/usun, z - ukryj podpowiedzi"); x = 0; *XMapy = x * 2 + 1; *YMapy = y + 1; free (tX); free (tY); } } free(XMapy); free(YMapy); } int PoprawnoscPlanszy(int szerokosc, int wysokosc) { int licznikW = 0; // licznik mozliwych pozycji generowania weza int i = 0, j = 0; for(i = 0 ; i < szerokosc - 1 ; i++) for (j = 0; j < wysokosc; j++) { if (pole[i][j] == '\0' && pole[i+1][j] == '\0') licznikW++; if (licznikW >= 1) return 1; } return 0; }
C
#include <sys/socket.h> #include <sys/types.h> #include <netinet/in.h> #include <netdb.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <unistd.h> #include <errno.h> int main() { int sock; char send_data[1024]; struct hostent *host; struct sockaddr_in server_socket_address; host = gethostbyname("192.168.1.5"); if ((sock = socket(AF_INET, SOCK_STREAM, 0)) == -1) { perror("Socket"); exit(1); } server_socket_address.sin_family = AF_INET; server_socket_address.sin_port = htons(5000); server_socket_address.sin_addr = *((struct in_addr *)host->h_addr); bzero(&(server_socket_address.sin_zero),8); if (connect(sock, (struct sockaddr *)&server_socket_address, sizeof(struct sockaddr)) == -1) { perror("Connect"); exit(1); } while(1) { printf("\nSEND (q to quit) : "); gets(send_data); if (strcmp(send_data , "q") == 0 ) { send(sock,send_data,strlen(send_data), 0); close(sock); break; } else send(sock,send_data,strlen(send_data), 0); } return 0; }
C
#include <stdio.h> #include <stdlib.h> extern char* ParseUserAgent(const char *); extern void FreeUserAgent(char *); int main(int argc, const char *argv[]) { const char *s = "Mozilla/5.0 (Linux; U; en-US) AppleWebKit/528.5+ (KHTML, like Gecko, Safari/528.5+) Version/4.0 Kindle/3.0 (screen 600×800; rotate)"; if (argc > 1) s = argv[1]; char *ua = ParseUserAgent(s); printf("input: %s\nresult: %s\n", s, ua); FreeUserAgent(ua); return 0; }
C
#include "data_buffer.h" db_state db_init() { db_state state; state.next_id = 0; state.full = 0; osSemaphoreDef(dbSemaphore); state.semaphore = osSemaphoreCreate(osSemaphore(dbSemaphore), 1); return state; } uint8_t db_add_entry(db_state* state, db_entry entry) { if(osSemaphoreWait(state->semaphore, UINT32_MAX) == osOK) { memcpy(&(state->data_array[state->next_id++]), &entry, sizeof(db_entry)); if(state->next_id == DB_BUFFER_SIZE) { state->next_id = 0; state->full = 1; } osSemaphoreRelease(state->semaphore); return 1; } return 0; } uint8_t db_lock_for_adding(db_state* state) { if(osSemaphoreWait(state->semaphore, UINT32_MAX) == osOK) return 1; else return 0; } void db_unlock_for_adding(db_state* state) { osSemaphoreRelease(state->semaphore); } void db_read_entry_as_json(db_state* state, uint16_t position, char* output) { db_entry entry = state->data_array[position]; if(entry.date_mounth == 0 || entry.date_day == 0) sprintf(output, DB_ENTRY_TEMPLATE, entry.date_year, 1, 1, entry.time_hour, entry.time_min, entry.time_sec, entry.latitude, entry.longitude, entry.temperature, entry.pressure, entry.altitude, entry.humidity); else sprintf(output, DB_ENTRY_TEMPLATE, entry.date_year, entry.date_mounth, entry.date_day, entry.time_hour, entry.time_min, entry.time_sec, entry.latitude, entry.longitude, entry.temperature, entry.pressure, entry.altitude, entry.humidity); } void db_reset_counters(db_state* state) { state->next_id = 0; state->full = 0; osSemaphoreRelease(state->semaphore); }
C
// Copyright 2015 Universidade Federal de Minas Gerais (UFMG) #ifndef PRIORITY_QUEUE_H_ #define PRIORITY_QUEUE_H_ #include <stdbool.h> // Tipo dos elementos na fila de prioridades. typedef float PQType; // Tipo de dado priority_queue (fila de prioridade). // Para garantir o ecapsulamento, 'struct PQStruct' só é definido em priority_queue.c. typedef struct PQStruct* priority_queue; // Cria uma fila vazia. priority_queue new_priority_queue(); // Testa se a fila está vazia. bool empty(priority_queue q); // Retorna o número de elementos na fila. int size(priority_queue q); // Retorna o menor elemento da fila. // Precondição: a fila não pode estar vazia. PQType top(priority_queue q); // Insere k na fila. void push(PQType k, priority_queue q); // Remove o menor elemento da fila. // Precondição: a fila não pode estar vazia. void pop(priority_queue q); // Faz a fila p ficar igual a q. void copy(priority_queue p, priority_queue q); // Troca o conteúdo da fila p com o da fila q. void swap(priority_queue p, priority_queue q); // Libera a memória alocada para a fila. void delete_priority_queue(priority_queue q); #endif // PRIORITY_QUEUE_H_
C
//Writer.c //Chris Choi //Assignment 2 #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdbool.h> #include <syslog.h> #include <ctype.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <errno.h> #include <unistd.h> int main(int argc, char *argv[]) { //start logging openlog(NULL, LOG_CONS, LOG_USER); //ensure number of input arguments is correct if(argc != 3) { syslog(LOG_ERR, "Invalid function arguments - ex:<directory>,<string-to-write>\n"); return 1; } //save argument 1 and 2 locally char *path = argv[1]; char *str = argv[2]; //open file int fd = open(path, O_CREAT | O_RDWR | O_TRUNC, S_IRWXU); //check to see if file open if(fd == -1) { syslog(LOG_ERR, "Cannot open or touch file %s\n", path); return 1; } //count bytes while writing to ensure correct write ssize_t byte_count = write(fd, str, strlen(str)); //error out if failed to write successfully or log if successful if(byte_count != strlen(str)) { syslog(LOG_ERR, "Failed to write <%s> in <%s>\n", str, path); } else { syslog(LOG_DEBUG, "Successfully wrote <%s> to <%s>\n", str, path); } //close file close(fd); //if failed to close, log, exit if(fd == -1) { syslog(LOG_ERR, "File cannot be closed\n"); return 1; } //close log closelog(); return 0; }
C
#include <stdio.h> int main(int arg, char *argv[]) { int nums[] = { 10, 11, 12, 13, 14 }; int *num_start = nums; int *num_ptr = nums; int num_size = sizeof(nums) / sizeof(int); printf("num_size = %d\n", num_size); printf("start_position = %p\n", (void *) num_start); printf("\n"); while ((num_ptr - num_start) < num_size) { printf("Value = %d\n", *num_ptr); printf("Address = %p\n", (void *) num_ptr); printf("position difference = %d\n", (int) (num_ptr - num_start)); printf("\n"); num_ptr++; } return 0; }
C
/* Structure for a tableau pile */ typedef struct { int buildsuit; /* One of the S_* values below */ int buildstep; /* Usually -1 */ int movesuit; /* Suit rule for moving stacks */ int movestep; /* Step for moving stacks - npip means no rule */ int basecard; /* Low pip value - if 0, we enable wrapping */ int fillblank; /* Can only fill blanks with kings? */ int nobreak; /* Don't break sequences when moving off */ int beginset; /* First column of this tableau set */ int id; /* ID number of stack with current contents */ } TableauStack; #define F_NONE 0 #define F_ANYTHING 1 #define F_KINGONLY 2 #define F_KINGLEFT 3 /* King only, or full stack from next column */ /* Deal Flip valeus */ #define FLIP_NONE 0 #define FLIP_ONE 1 #define FLIP_TWO 2 #define FLIP_THREE 3 #define FLIP_FOUR 4 #define FLIP_ALL 100 /* NoBreak values */ #define BREAK_ANYWHERE 0/* Break sequences anywhere */ #define BREAK_NOFIT 1 /* Break sequences where they don't fit build rule */ #define BREAK_NOWHERE 2 /* Move longest possible movable sequence */ extern TableauStack *tableau; void makeTableau(int ndeal, int dealflip, Stack *deal, int buildsuit, int buildstep, int movesuit, int movestep, int basecard, int fillblank, int nobreak, int beginset); void printTableau(FILE *f, Stack *stks); void cleanTableau(void); void gatherTableau(Stack *s); int tableau_firstMove(Stack *stack, int *index1, int *len); int tableau_nextMove(Stack *stack, int *index1, int *len); int isfaceup(int dealflip, int i);
C
#include <stdio.h> #include <stdlib.h> #include <assert.h> #include <stdbool.h> #include "util.h" /********* SET *********/ #define SIZE 20 struct set { bool elements[SIZE]; }; /* set_create: create a set * * Returns: a set */ set_t *set_create() { set_t *set = (set_t*)malloc(sizeof(set_t)); for(int i = 0; i < SIZE; i++) { set->elements[i] = false; } return set; } /* set_add: add a number to the set * * set: the set * num: the number to add to the set */ void set_add(set_t *set, int num) { assert(set != NULL); assert(num < SIZE); set->elements[num] = true; } /* set_query: determines whether a number is in the set * * set: the set * num: the number to query * * Returns: true if the number is in the set, false otherwise */ bool set_query(set_t *set, int num) { assert(set != NULL); assert(num < SIZE); return set->elements[num]; } /* set_free: free a set * * set: the set * */ void set_free(set_t *set) { assert(set != NULL); free(set); } /* set_print: print the elements in a set * * set: the set * */ void set_print(set_t *set) { printf("set:\n"); for(int i = 0; i < SIZE; i++) { if(set->elements[i]) { printf(" %d\n", i); } } } /********* PRIORITY QUEUE *********/ typedef struct queue_element qelement_t; struct queue_element { int num; double priority; qelement_t *next; }; struct queue { qelement_t *front; }; /* queue_create: create a priority queue * * Returns: a priority queue */ queue_t *queue_create() { queue_t *q = (queue_t*)malloc(sizeof(queue_t)); q->front = NULL; return q; } /* new_element: create a new element in the priority queue * * num: the number to add to the queue * priority: the priority of num * * Returns: the new element */ qelement_t *new_element(int num, double priority) { qelement_t *element = (qelement_t*)malloc(sizeof(qelement_t)); element->num = num; element->priority = priority; element->next = NULL; return element; } /* queue_add: add an element to the priority queue * * q: the priority queue * num: the number to add to the queue * priority: priority of num */ void queue_add(queue_t *q, int num, double priority) { assert(q != NULL); qelement_t *element = new_element(num, priority); // the queue is empty if(q->front == NULL) { q->front = element; return; } // the queue is not empty if(q->front->priority > priority) { // new front element->next = q->front; q->front = element; } else { qelement_t *curr = q->front; while((curr->next != NULL) && (curr->next->priority < priority)){ // find position curr = curr->next; } element->next = curr->next; curr->next = element; } } /* queue_remove: remove an element from the priority queue * * q: the priority queue * * Returns: the number removed from the priority queue */ int queue_remove(queue_t *q) { assert(q != NULL); assert(q->front != NULL); // queue is empty // previous front qelement_t *temp = q->front; q->front = q->front->next; // return numue of first int num = temp->num; free(temp); return num; } /* queue_query: determines whether a number is in the priority queue * * q: the priority queue * num: the number to query * * Returns: true if num is in the queue, false otherwise */ bool queue_query(queue_t *q, int num) { assert(q != NULL); qelement_t *curr = q->front; while(curr != NULL){ if(curr->num == num) { return true; } curr = curr->next; } return false; } /* queue_is_empty: determines whether or not the queue is empty * * q: the priority queue * * Returns: true if the queue is empty, false otherwise */ bool queue_is_empty(queue_t *q) { assert(q != NULL); return q->front == NULL; } /* queue_change_priority: change the priority of an element * in the priority queue * * q: the priority queue * num: the number to change * new_priority: new priority of num * */ void queue_change_priority(queue_t *q, int num, double new_priority) { assert(q != NULL); qelement_t *prev; qelement_t *curr = q->front; // first element if(curr->num == num) { queue_remove(q); queue_add(q, num, new_priority); return; } prev = curr; curr = curr->next; while(curr != NULL){ if(curr->num == num){ // found the element prev->next = curr->next; free(curr); queue_add(q, num, new_priority); return; } prev = curr; curr = curr->next; } } /* queue_free: free a priority queue and its elements * * q: the priority queue * */ void queue_free(queue_t *q) { assert(q != NULL); qelement_t *curr = q->front; qelement_t *next; while(curr != NULL){ next = curr->next; free(curr); curr = next; } free(q); } /* queue_print: print the elements in a priority queue * * q: the priority queue * */ void queue_print(queue_t *q) { assert(q != NULL); printf("queue:\n"); if(q->front == NULL) { printf(" empty\n"); } else { qelement_t *curr = q->front; while(curr != NULL){ printf(" (%d, %.2f)\n", curr->num, curr->priority); curr = curr->next; } } }
C
#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 */ typedef struct TYPE_4__ TYPE_1__ ; /* Type definitions */ struct TYPE_4__ {size_t bottom; size_t top; int* err_flags; } ; typedef TYPE_1__ ERR_STATE ; /* Variables and functions */ int ERR_FLAG_MARK ; int ERR_NUM_ERRORS ; int /*<<< orphan*/ err_clear (TYPE_1__*,size_t,int /*<<< orphan*/ ) ; TYPE_1__* err_get_state_int () ; int ERR_pop_to_mark(void) { ERR_STATE *es; es = err_get_state_int(); if (es == NULL) return 0; while (es->bottom != es->top && (es->err_flags[es->top] & ERR_FLAG_MARK) == 0) { err_clear(es, es->top, 0); es->top = es->top > 0 ? es->top - 1 : ERR_NUM_ERRORS - 1; } if (es->bottom == es->top) return 0; es->err_flags[es->top] &= ~ERR_FLAG_MARK; return 1; }
C
#include <stdio.h> #include <string.h> char *mx_strcpy(char *dst, const char *src) { for (int i = 0; src[i] != '\0'; i++) { dst[i] = src[i]; } return dst; } int main() { const char src[12] = "Hello world"; char dst[12]; mx_strcpy(dst, src); printf("%s\n", src); printf("%s\n", dst); return 0; }
C
//串口相关的头文件 #include<stdio.h> /*标准输入输出定义*/ #include<stdlib.h> /*标准函数库定义*/ #include<unistd.h> /*Unix 标准函数定义*/ #include<sys/types.h> #include<sys/stat.h> #include<fcntl.h> /*文件控制定义*/ #include<termios.h> /*PPSIX 终端控制定义*/ #include<errno.h> /*错误号定义*/ #include<string.h> char str[] = "{\"albumName\":\"狂想曲(夏日狂欢庆功限量影音版)\",\"authorName\":\"萧敬腾\",\"displayName\":\"06.怎么说我不爱你\",\"musicName\":\"06.怎么说我不爱你\",\"musicId\":20,\"musicTime\":268}]}"; static size_t _str_u8_len(char *str){ char *ptr = str; unsigned char tmp = 0; size_t len = 0; int u8_len = 0; int num = 0; while(*ptr != '\0'){ if(*ptr & 0x80){ ++u8_len; #if 0 num = 0; while(*ptr & 0x80){ ++ptr; ++num; } printf("num is %d\n", num); #else num = 0; tmp = *ptr; // tmp <<= 1; while(tmp & 0x80){ ++num; tmp <<= 1; } printf("num is %d\n", num); ptr += num; #endif }else{ ++ptr; } ++len; } printf("strlen is %d, u8 is %d, final is %d\n", strlen(str), u8_len, len); return len; } void main(){ unsigned int i = 0; unsigned int out; unsigned int back; for(i; i <= 15; i++){ out = (i << 3) / 3; back = (out * 3 + 2) >> 3; printf("[%d]: (%d:%d)\n", i, out, back); } }
C
#include <stdio.h> #include <time.h> enum Type { DINNER, BREAKFAST, CAR_RENTAL }; struct Expense { enum Type type; int amount; }; void printExpenses(struct Expense *expenses[], size_t numExpenses) { int total = 0; int mealExpenses = 0; time_t now; if (time(&now) == -1) return; printf("Expenses %s\n", ctime(&now)); for (size_t i = 0; i < numExpenses; i++) { struct Expense *expense = expenses[i]; if (expense->type == DINNER || expense->type == BREAKFAST) { mealExpenses += expense->amount; } char *expenseName; switch (expense->type) { case DINNER: expenseName = "Dinner"; break; case BREAKFAST: expenseName = "Breakfast"; break; case CAR_RENTAL: expenseName = "Car Rental"; break; } char *mealOverExpensesMarker = ((expense->type == DINNER && expense->amount > 5000) || (expense->type == BREAKFAST && expense->amount > 1000)) ? "X" : " "; printf("%s\t%d\t%s\n", expenseName, expense->amount, mealOverExpensesMarker); total += expense->amount; } printf("Meal expenses: %d\n", mealExpenses); printf("Total expenses: %d\n", total); }
C
#include <unistd.h> #include <stdlib.h> #include <stdio.h> #include <stdbool.h> #include <string.h> #define INPUT_SIZE 100 /* Gets a substring of '_str' from index '_begin' to '_end'. Stores resultant string into '_dest' */ void substring(char* _dest, char* _src, int _begin, int _end) { int i; for (i = _begin; i < _end; i++) _dest[i - _begin] = _src[i]; _dest[i - _begin] = '\0'; } /* Gets the first index of the character '_c' after index '_startIndex' within the string '_str' */ int indexof(char* _str, int _startIndex, char _c) { int output = -1; int len = strlen(_str); for (int i = _startIndex; i < len; i++) { if (_str[i] == _c) { output = i; i = len + 1; } } return output; } /* Splits the '_input' string into three '_cm', '_arg1', and '_arg2' strings */ void getArgs(char* _input, char* _cmd, char* _arg1, char* _arg2) { int delim = indexof(_input, 0, ' '); //printf("delim0: %d\n", delim); if (delim > -1) { substring(_cmd, _input, 0, delim); char buffer0[INPUT_SIZE]; substring(buffer0, _input, delim + 1, strlen(_input) - 1); //printf("buffer0: %s\n", buffer0); int delim = indexof(buffer0, 0, ' '); //printf("delim1: %d\n", delim); if (delim > -1) { substring(_arg1, buffer0, 0, delim); substring(_arg2, buffer0, delim + 1, strlen(buffer0)); } else strcpy(_arg1, buffer0); } else substring(_cmd, _input, 0, strlen(_input) - 1); } void unixcmd(const char* _cmd, char* _arg1, char* _arg2) { char buffer[INPUT_SIZE]; sprintf(buffer, _cmd, _arg1, _arg2); system(buffer); } int main() { bool loop = true; while (loop) { char input[INPUT_SIZE]; char command[INPUT_SIZE], arg1[INPUT_SIZE], arg2[INPUT_SIZE]; input[0] = '\0'; command[0] = '\0'; arg1[0] = '\0'; arg2[0] = '\0'; printf("Input a command (Type Ctrl-C to exit): "); fgets(input, INPUT_SIZE, stdin); getArgs(input, command, arg1, arg2); if (!strcmp("cd", command)) { //unixcmd("cd %s %s", arg1, arg2); chdir(arg1); } else if (!strcmp("dir", command)) { unixcmd("ls %s %s", arg1, arg2); } else if (!strcmp("type", command)) { unixcmd("cat %s %s", arg1, arg2); } else if (!strcmp("del", command)) { unixcmd("rm %s %s", arg1, arg2); } else if (!strcmp("ren", command)) { unixcmd("mv %s %s", arg1, arg2); } else if (!strcmp("copy", command)) { unixcmd("cp %s %s", arg1, arg2); } else printf("Unknown command!"); printf("\n\n"); } }
C
#include<stdio.h> int main(){ long long k = 1; int i; printf("int C[200] = {"); for(i = 1; i < 201; i++){ k *= i; k %= 1000000007; printf("%lld, ", k); } printf("}\n"); return 0; }
C
#include<stdio.h> void swapStrings(char **destination,char **source); int main() { char *str1="joker"; char *str2="cool"; printf("str1:%s,str:%s\n",str1,str2); swapStrings(&str1,&str2); printf("str1:%s,str2:%s\n",str1,str2); return 0; } void swapStrings(char **destination,char **source) { char *temp=*destination; *destination=*source; *source=temp; }
C
#ifndef TREE_H_ #define TREE_H_ #include <stdlib.h> #include <stdio.h> extern const char tree_ok; extern const char tree_memerror; extern const char tree_under; typedef char base_type; typedef struct e node; typedef struct e{ base_type data; node *left_son; node *right_son; }; typedef node tree; char tree_error; tree* node_init(); // инициализация — создается элемент, который будет содержать корень дерева void node_write(tree *t, base_type e); //запись данных void node_read(tree *t,base_type *e);//чтение void node_delete(tree *t);//удаление листа void move_left(tree *t);//перейти к левому сыну void move_right(tree *t);//перейти к правому сыну int check_left_son(tree *t);//1 — есть левый сын, 0 — нет int check_right_son(tree *t);//1 — есть правый сын, 0 — нет int tree_empty(tree *t);//1 — пустое дерево,0 — не пустое unsigned count_node_lvl(tree *t,char lvl); void tree_data_set(tree* t,int data); #endif
C
#include <stdio.h> #include <stdlib.h> void fprime(int nb) { int i = 2; if (nb == 1) printf("1"); else { while (nb != 1) { if (nb % i == 0) { printf("%d", i); nb /= i; if (nb != 1) printf("*"); } else ++i; } } } int main(int argc, char **argv) { if (argc == 2) fprime(atoi(argv[1])); printf("\n"); return 0; }
C
/*** includes ***/ // feature test macro ?? #define _DEFAULT_SOURCE #define _BSD_SOURCE #define _GNU_SOURCE #include <ctype.h> #include <errno.h> #include <fcntl.h> #include <stdio.h> #include <stdarg.h> #include <stdlib.h> #include <string.h> #include <sys/ioctl.h> // Input/Output ConTroL #include <sys/types.h> #include <termios.h> #include <time.h> #include <unistd.h> /*** defines ***/ // Cool ascii thing, clearing bits 5 and 6 gets the control sequence associated with that character // Also bit five toggles lowercase and uppercase #define CTRL_KEY(k) ((k) & 0x1f) #define PICO_VERSION "0.0.1" #define PICO_TAB_STOP 8 #define PICO_QUIT_TIMES 3 enum EditorKey { BACKSPACE = 127, ARROW_LEFT = 1000, ARROW_RIGHT, ARROW_UP, ARROW_DOWN, DEL_KEY, HOME_KEY, END_KEY, PAGE_UP, PAGE_DOWN, }; enum EditorHighlight { HL_NORMAL = 0, HL_COMMENT, HL_MLCOMMENT, HL_KEYWORD1, HL_KEYWORD2, HL_STRING, HL_NUMBER, HL_MATCH }; #define HL_HIGHLIGHT_NUMBERS (1<<0) #define HL_HIGHLIGHT_STRINGS (1<<1) /*** data ***/ typedef struct { char* filetype; char** filematch; char** keywords; char* singleline_comment_start; char* multiline_comment_start; char* multiline_comment_end; int flags; } EditorSyntax; typedef struct { int idx; int size; int rsize; // The size of the render of the row (tabs are more than one character) char *chars; char *render; unsigned char* hl; // Highlight int hl_open_comment; } Row; struct EditorConfig { int cx, cy; int rx; // index into the render field int rowoff; int coloff; int screenrows; int screencols; int numrows; Row *row; int dirty; char *filename; char statusmsg[80]; time_t statusmsg_time; EditorSyntax* syntax; struct termios orig_termios; }; struct EditorConfig E; /*** filetypes ***/ char* C_HL_extensions[] = { ".c", ".h", ".cpp", NULL }; char* C_HL_keywords[] = { "switch", "if", "while", "for", "break", "continue", "return", "else", "struct", "union", "typedef", "static", "enum", "case", "int|", "long|", "double|", "float|", "char|", "float|", "unsigned|", "signed|", "void|", NULL }; EditorSyntax HLDB[] = { { "c", C_HL_extensions, C_HL_keywords, "//", "/*", "*/", HL_HIGHLIGHT_NUMBERS | HL_HIGHLIGHT_STRINGS } }; // HighLight DataBase Entries #define HLDB_ENTRIES (sizeof(HLDB) / sizeof(HLDB[0])) /*** prototypes ***/ /* c was meant to be compiled in a single pass */ void editor_set_status_message(const char *fmt, ...); void editor_refresh_screen(); char* editor_prompt(char* prompt, void (*callback)(char*, int)); /*** terminal ***/ void die(const char *s) { // Clear screen write(STDOUT_FILENO, "\x1b[2J", 4); write(STDOUT_FILENO, "\x1b[H", 3); // Most libc functions that fail set the global errno variable to indicate what the error was. // `perror` looks at errno and prints a descriptive error message for it. // It also prints the given string. perror(s); // Exit with status of 1, indicating error, like an non-zero exit code. exit(1); } void disable_raw_mode() { if (tcsetattr(STDIN_FILENO, TCSAFLUSH, &E.orig_termios) == -1) die("tcsetattr"); } void enable_raw_mode() { if (tcgetattr(STDIN_FILENO, &E.orig_termios) == -1) die("tcgetattr"); atexit(disable_raw_mode); struct termios raw = E.orig_termios; // Flags documented with * are usually already off and/or don't apply, but good practices // IXON: When on enables C-s and C-q, which involve "software control flow". // stands for input XON because C-s and C-q are XON and XOFF. // ICRNL: When on enables coercing a \r without a \n to a \n (C-m is \r and C-j is \n). // stands for input carriage return new line. // *BRKINT: When on a "break condition" will cause a SIGINT signal to be sent. // *INPCK: When on enables parity checking, which doesn't seem to apply to modern terminal emulators. // *ISTRIP: When on enables causes the high bit to be 0 for every input byte. raw.c_iflag &= ~(IXON | ICRNL | BRKINT | INPCK | ISTRIP); // OPOST: When on enables output processing, in reality the only feature would be coercing \n into \r\n. // This means whenever we want a new line we have to do \r\n, otherwise the cursor will not // go to the start of the line and will just move down. raw.c_oflag &= ~(OPOST); // *CS8: not a flag, a mask. Sets the character size to 8=bits per bytes, lmao, imagine needing this. raw.c_cflag |= (CS8); // ECHO: When on enables echoing back of input. // ICANON: When on enables reading line by line (we want it byte by byte). // ISIG: When on enables SIGINT and SIGTSTP from C-c and C-z, respectively. // these are signal interrupt and signal temporary stop. // IEXTEN: When on enables C-v to send another character "literally" (e.g. C-v and C-c would only send a literal 3 and not SIGINT). raw.c_lflag &= ~(ECHO | ICANON | ISIG | IEXTEN); // cc stands for control characters // Both measured in tenths of a second. // Minimum amount of time before read returns. raw.c_cc[VMIN] = 0; // Maximum amount of time to wait before read returns. // On time out read() returns 0. raw.c_cc[VTIME] = 1; if (tcsetattr(STDIN_FILENO, TCSAFLUSH, &raw) == -1) die("tcsetattr"); } int editor_read_key() { // read in character int nread; char c; while ((nread = read(STDIN_FILENO, &c, 1)) != 1) { if (nread == -1 && errno != EAGAIN) die("read"); } // Process character if escape character if (c == '\x1b') { char seq[3]; if (read(STDIN_FILENO, &seq[0], 1) != 1) return '\x1b'; if (read(STDIN_FILENO, &seq[1], 1) != 1) return '\x1b'; if (seq[0] == '[') { if (seq[1] >= '0' && seq[1] <= '9') { if (read(STDIN_FILENO, &seq[2], 1) != 1) return '\x1b'; if (seq[2] == '~') { switch (seq[1]) { case '1': return HOME_KEY; case '3': return DEL_KEY; case '4': return END_KEY; case '5': return PAGE_UP; case '6': return PAGE_DOWN; case '7': return HOME_KEY; case '8': return END_KEY; } } } else { switch (seq[1]) { case 'A': return ARROW_UP; case 'B': return ARROW_DOWN; case 'C': return ARROW_RIGHT; case 'D': return ARROW_LEFT; case 'H': return HOME_KEY; case 'F': return END_KEY; } } } else if (seq[0] == 'O') { switch (seq[1]) { case 'H': return HOME_KEY; case 'F': return END_KEY; } } return '\x1b'; } else { return c; } } int get_cursor_position(int *rows, int *cols) { char buf[32]; unsigned int i = 0; if (write(STDOUT_FILENO, "\x1b[6n", 4) != 4) return -1; while (i < sizeof(buf) -1) { if (read(STDIN_FILENO, &buf[i], 1) != 1) break; if (buf[i] == 'R') break; i++; } // printf expected a null byte at the end buf[i] = '\0'; if (buf[0] != '\x1b' || buf[1] != '[') return -1; if (sscanf(&buf[2], "%d;%d", rows, cols) != 2) return -1; return 0; } int get_window_size(int *rows, int *cols) { struct winsize ws; // Terminal IOCtl Get Window Size if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == -1 || ws.ws_col == 0) { if (write(STDOUT_FILENO, "\x1b[999C\x1b[999B", 12) != 12) return -1; return get_cursor_position(rows, cols); } else { *cols = ws.ws_col; *rows = ws.ws_row; return 0; } } /*** syntax highlighting ***/ int is_separator(int c) { return isspace(c) || c == '\0' || strchr(",.()+-/*=~%<>[];", c) != NULL; } void editor_update_syntax(Row* row) { row->hl = realloc(row->hl, row->rsize); memset(row->hl, HL_NORMAL, row->rsize); if (E.syntax == NULL) return; char** keywords = E.syntax->keywords; char* scs = E.syntax->singleline_comment_start; char* mcs = E.syntax->multiline_comment_start; char* mce = E.syntax->multiline_comment_end; int scs_len = scs ? strlen(scs) : 0; int mcs_len = scs ? strlen(mcs) : 0; int mce_len = scs ? strlen(mce) : 0; int prev_sep = 1; int in_string = 0; int in_comment = (row->idx > 0 && E.row[row->idx - 1].hl_open_comment); int i = 0; while (i < row->rsize) { char c = row->render[i]; unsigned char prev_hl = (i > 0) ? row->hl[i - 1] : HL_NORMAL; if (scs_len && !in_string && !in_comment) { if (!strncmp(&row->render[i], scs, scs_len)) { memset(&row->hl[i], HL_COMMENT, row->rsize - i); break; } } if (mcs_len && mce_len && !in_string) { if (in_comment) { row->hl[i] = HL_MLCOMMENT; if (!strncmp(&row->render[i], mce, mce_len)) { memset(&row->hl[i], HL_MLCOMMENT, mce_len); i += mce_len; in_comment = 0; prev_sep = 1; continue; } else { i++; continue; } } else if (!strncmp(&row->render[i], mcs, mcs_len)) { memset(&row->hl[i], HL_MLCOMMENT, mcs_len); i += mcs_len; in_comment = 1; continue; } } if (E.syntax->flags & HL_HIGHLIGHT_STRINGS) { if (in_string) { row->hl[i] = HL_STRING; // backslash escapes strings if (c == '\\' && i + 1 < row->rsize) { row->hl[i + 1] = HL_STRING; i += 2; continue; } if (c == in_string) in_string = 0; i++; prev_sep = 1; continue; } else { if (c == '"' || c == '\'') { in_string = c; row->hl[i] = HL_STRING; i++; continue; } } } if (E.syntax->flags & HL_HIGHLIGHT_NUMBERS) { if ( (isdigit(c) && (prev_sep || prev_hl == HL_NUMBER)) || (c == '.' && prev_hl == HL_NUMBER) ) { row->hl[i] = HL_NUMBER; i++; prev_sep = 0; continue; } } if (prev_sep) { int j; for (j = 0; keywords[j]; j++) { int klen = strlen(keywords[j]); int kw2 = keywords[j][klen-1] == '|'; if (kw2) klen--; if ( !strncmp(&row->render[i], keywords[j], klen) && is_separator(row->render[i + klen]) ) { memset(&row->hl[i], kw2 ? HL_KEYWORD2 : HL_KEYWORD1, klen); i += klen; // this break gets us to the if statement to continue break; } } // Triggered on break if (keywords[j] != NULL) { prev_sep = 0; continue; } } prev_sep = is_separator(c); i++; } // update next rows if this line has the start of a multiline comment int changed = (row->hl_open_comment != in_comment); row->hl_open_comment = in_comment; if (changed && row->idx + 1 < E.numrows) editor_update_syntax(&E.row[row->idx + 1]); } int editor_syntax_to_color(int hl) { switch (hl) { case HL_COMMENT: case HL_MLCOMMENT: return 36; case HL_STRING: return 35; case HL_KEYWORD1: return 33; case HL_KEYWORD2: return 32; case HL_NUMBER: return 31; case HL_MATCH: return 34; default: return 37; } } void editor_select_syntax_highlight() { E.syntax = NULL; if (E.filename == NULL) return; char* ext = strrchr(E.filename, '.'); for (unsigned int j = 0; j < HLDB_ENTRIES; j++) { EditorSyntax* s = &HLDB[j]; unsigned int i = 0; while (s->filematch[i]) { int is_ext = (s->filematch[i][0] == '.'); if ( (is_ext && ext && !strcmp(ext, s->filematch[i])) || (!is_ext && strstr(E.filename, s->filematch[i])) ) { E.syntax = s; int filerow; for (filerow = 0; filerow < E.numrows; filerow++) { editor_update_syntax(&E.row[filerow]); } return; } i++; } } } /*** row operations ***/ int editor_row_cx_to_rx(Row *row, int cx) { int rx = 0; int j; for (j = 0; j < cx; j++) { if (row->chars[j] == '\t') rx += (PICO_TAB_STOP - 1) - (rx % PICO_TAB_STOP); rx++; } return rx; } int editor_row_rx_to_cx(Row* row, int rx) { int cur_rx = 0; int cx; for (cx = 0; cx < row->size; cx++) { if (row->chars[cx] == '\t') { cur_rx += (PICO_TAB_STOP - 1) - (cur_rx % PICO_TAB_STOP); } cur_rx++; if (cur_rx > rx) return cx; } return cx; } void editor_update_row(Row* row) { // used for iteration twice int j; int tabs = 0; for (j = 0; j < row->size; j++) if (row->chars[j] == '\t') tabs++; free(row->render); row->render = malloc(row->size + tabs * (PICO_TAB_STOP - 1) + 1); int idx = 0; for (j = 0; j < row->size; j++) { if (row->chars[j] == '\t') { row->render[idx++] = ' '; // get us to the next tab spot while (idx % PICO_TAB_STOP != 0) row->render[idx++] = ' '; } else { row->render[idx++] = row->chars[j]; } } row->render[idx] = '\0'; row->rsize = idx; editor_update_syntax(row); } void editor_insert_row(int at, char* s, size_t len) { if (at < 0 || at > E.numrows) return; // Allocate space for the new row E.row = realloc(E.row, sizeof(Row) * (E.numrows + 1)); memmove(&E.row[at + 1], &E.row[at], sizeof(Row) * (E.numrows - at)); for (int j = at + 1; j <= E.numrows; j++) E.row[j].idx++; E.row[at].idx = at; E.row[at].size = len; E.row[at].chars = malloc(len + 1); memcpy(E.row[at].chars, s, len); E.row[at].chars[len] = '\0'; E.row[at].rsize = 0; E.row[at].render = NULL; E.row[at].hl = NULL; E.row[at].hl_open_comment = 0; editor_update_row(&E.row[at]); E.numrows++; E.dirty++; } void editor_free_row(Row* row) { free(row->render); free(row->chars); free(row->hl); } void editor_del_row(int at) { if (at < 0 || at >= E.numrows) return; editor_free_row(&E.row[at]); memmove(&E.row[at], &E.row[at + 1], sizeof(Row) * (E.numrows - at - 1)); for (int j = at; j < E.numrows - 1; j++) E.row[j].idx--; E.numrows--; E.dirty++; } void editor_row_insert_char(Row* row, int at, int c) { if (at < 0 || at > row->size) at = row->size; // allocate one more byte for the new character, and one more byte for the null byte row->chars = realloc(row->chars, row->size + 2); // like memcpy, but safe to use if the source and destination places overlap memmove(&row->chars[at + 1], &row->chars[at], row->size - at + 1); row->size++; row->chars[at] = c; editor_update_row(row); E.dirty++; } void editor_row_append_string(Row* row, char* s, size_t len) { row->chars = realloc(row->chars, row->size + len + 1); memcpy(&row->chars[row->size], s, len); row->size += len; row->chars[row->size] = '\0'; editor_update_row(row); E.dirty++; } void editor_row_del_char(Row* row, int at) { if (at < 0 || at >= row->size) return; // include the NULL byte! memmove(&row->chars[at], &row->chars[at + 1], row->size - at); row->size--; editor_update_row(row); E.dirty++; } /*** editor operations ***/ void editor_insert_char(int c) { if (E.cy == E.numrows) { editor_insert_row(E.numrows, "", 0); } editor_row_insert_char(&E.row[E.cy], E.cx, c); E.cx++; } void editor_insert_newline() { if (E.cx == 0) { editor_insert_row(E.cy, "", 0); } else { Row* row = &E.row[E.cy]; editor_insert_row(E.cy + 1, &row->chars[E.cx], row->size - E.cx); // Reassign because memmove might invalidate it (uhhhhh) row = &E.row[E.cy]; row->size = E.cx; row->chars[row->size] = '\0'; editor_update_row(row); } E.cy++; E.cx = 0; } void editor_del_char() { if (E.cy == E.numrows) return; if (E.cx == 0 && E.cy == 0) return; Row* row = &E.row[E.cy]; if (E.cx > 0) { editor_row_del_char(row, E.cx - 1); E.cx--; } else { E.cx = E.row[E.cy - 1].size; editor_row_append_string(&E.row[E.cy - 1], row->chars, row->size); editor_del_row(E.cy); E.cy--; } } /*** file i/o ***/ // Returns a string of all the rows // also modifies buflen to be the length of the string char* editor_rows_to_string(int* buflen) { int totlen = 0; int j; for (j = 0; j < E.numrows; j++) { totlen += E.row[j].size + 1; } *buflen = totlen; char* buf = malloc(totlen); char* p = buf; for (j = 0; j < E.numrows; j++) { memcpy(p, E.row[j].chars, E.row[j].size); p += E.row[j].size; *p = '\n'; p++; } return buf; } void editor_open(char *filename) { free(E.filename); E.filename = strdup(filename); editor_select_syntax_highlight(); FILE *fp = fopen(filename, "r"); if (!fp) die("fopen"); char *line = NULL; size_t linecap = 0; // This type is used for sizes of objects ssize_t linelen; // This type is used for indicating errors (and also success ig) // Read line from file into `line` into buffer of current size `linecap` from `fp`. while ((linelen = getline(&line, &linecap, fp)) != -1) { // strip \r and \n while (linelen > 0 && (line[linelen - 1] == '\n' || line[linelen - 1] == '\r')) linelen--; editor_insert_row(E.numrows, line, linelen); } free(line); fclose(fp); E.dirty = 0; } void editor_save() { if (E.filename == NULL) { E.filename = editor_prompt("Save as: %s", NULL); if (E.filename == NULL) { editor_set_status_message("Save aborted"); return; } editor_select_syntax_highlight(); } int len; char* buf = editor_rows_to_string(&len); // 0644 is file perms, user read/write, group read int fd = open(E.filename, O_RDWR | O_CREAT, 0644); if (fd != -1) { // will cut off excess, or add 0 until file is of length len // by using ftruncate and not the O_TRUNC flag for open() (which automatically clears the file) // we keep the old file if the write fails, but the open doesn't // If we were cooler, we'd write to another file, and only if everything is good, rename it if (ftruncate(fd, len) != 1) { if (write(fd, buf, len) == len) { close(fd); free(buf); E.dirty = 0; editor_set_status_message("%d bytes written to disk", len); return; } } close(fd); } free(buf); editor_set_status_message("Can't save! I/O error: %s", strerror(errno)); } /*** find ***/ void editor_find_callback(char* query, int key) { static int last_match = -1; static int direction = 1; static int saved_hl_line; static char* saved_hl = NULL; if (saved_hl) { memcpy(E.row[saved_hl_line].hl, saved_hl, E.row[saved_hl_line].rsize); free(saved_hl); saved_hl = NULL; } if (key == '\r' || key == '\x1b') { last_match = -1; direction = 1; return; } else if (key == ARROW_RIGHT || key == ARROW_DOWN) { direction = 1; } else if (key == ARROW_LEFT || key == ARROW_UP) { direction = -1; } else { last_match = -1; direction = 1; } if (last_match == -1) direction = 1; int current = last_match; int i; for (i = 0; i < E.numrows; i++) { // start from last match and wrap around current += direction; if (current == -1) current = E.numrows - 1; else if (current == E.numrows) current = 0; Row* row = &E.row[current]; char* match = strstr(row->render, query); if (match) { last_match = current; E.cy = current; E.cx = editor_row_rx_to_cx(row, match - row->render); E.rowoff = E.numrows; saved_hl_line = current; saved_hl = malloc(row->rsize); memcpy(saved_hl, row->hl, row->rsize); memset(&row->hl[match - row->render], HL_MATCH, strlen(query)); break; } } } void editor_find() { int saved_cx = E.cx; int saved_cy = E.cy; int saved_coloff = E.coloff; int saved_rowoff = E.rowoff; char* query = editor_prompt("Search: %s", editor_find_callback); if (query) { free(query); } else { E.cx = saved_cx; E.cy = saved_cy; E.coloff = saved_coloff; E.rowoff = saved_rowoff; } } /*** append buffer ***/ // Avoid many small calls to write typedef struct { char *b; int len; } AppendBuf; #define ABUF_INIT {NULL, 0} void ab_append(AppendBuf *ab, const char *s, int len) { char *new = realloc(ab->b, ab->len + len); if (new == NULL) return; memcpy(&new[ab->len], s, len); ab->b = new; ab->len += len; } void abFree(AppendBuf *ab) { free(ab->b); } /*** input ***/ // callback function called after every keypress char* editor_prompt(char* prompt, void (*callback)(char*, int)) { size_t bufsize = 128; char* buf = malloc(bufsize); size_t buflen = 0; buf[0] = '\0'; for (;;) { editor_set_status_message(prompt, buf); editor_refresh_screen(); int c = editor_read_key(); if (c == DEL_KEY || c == CTRL_KEY('h') || c == BACKSPACE) { if (buflen != 0) buf[--buflen] = '\0'; } else if (c == '\x1b') { // escape editor_set_status_message(""); if (callback) callback(buf, c); free(buf); return NULL; } else if (c == '\r') { if (buflen != 0) { editor_set_status_message(""); if (callback) callback(buf, c); return buf; } } else if (!iscntrl(c) && c < 128) { if (buflen == bufsize - 1) { bufsize *= 2; buf = realloc(buf, bufsize); } buf[buflen++] = c; buf[buflen] = '\0'; } if (callback) callback(buf, c); } } void editor_move_cursor(int key) { Row *row = (E.cy >= E.numrows) ? NULL : &E.row[E.cy]; switch (key) { case ARROW_LEFT: if (E.cx != 0) { E.cx--; } else if (E.cy > 0) { E.cy--; E.cx = E.row[E.cy].size; } break; case ARROW_RIGHT: if (row && E.cx < row->size) { E.cx++; } else if (row && E.cx == row->size) { E.cy++; E.cx = 0; } break; case ARROW_UP: if (E.cy != 0) { E.cy--; } break; case ARROW_DOWN: if (E.cy < E.numrows) { E.cy++; } break; } // Correct row if we moved down/up to a row that was shorter row = (E.cy >= E.numrows) ? NULL : &E.row[E.cy]; int rowlen = row ? row->size : 0; if (E.cx > rowlen) { E.cx = rowlen; } } void editor_process_keypress() { static int quit_times = PICO_QUIT_TIMES; int c = editor_read_key(); switch (c) { case '\r': editor_insert_newline(); break; case CTRL_KEY('q'): if (E.dirty && quit_times > 0) { editor_set_status_message("WARNING!!! File has unsaved changes. " "Press Ctrl-Q %d more times to quit.", quit_times); quit_times--; // We return so that the quit number reset at the end of the function // doesn't happen return; } // Clear screen write(STDOUT_FILENO, "\x1b[2J", 4); write(STDOUT_FILENO, "\x1b[H", 3); // exit exit(0); break; case CTRL_KEY('s'): editor_save(); break; case HOME_KEY: E.cx = 0; break; case END_KEY: if (E.cy < E.numrows) E.cx = E.row[E.cy].size; break; case CTRL_KEY('f'): editor_find(); break; case BACKSPACE: case CTRL_KEY('h'): case DEL_KEY: if (c == DEL_KEY) editor_move_cursor(ARROW_RIGHT); editor_del_char(); break; case PAGE_UP: case PAGE_DOWN: // Create code block so that we can delcare a variable { if (c == PAGE_UP) { E.cy = E.rowoff; } else if (c == PAGE_DOWN) { E.cy = E.rowoff + E.screenrows - 1; if (E.cy > E.numrows) E.cy = E.numrows; } int times = E.screenrows; while (times--) editor_move_cursor(c == PAGE_UP ? ARROW_UP : ARROW_DOWN); } break; case ARROW_LEFT: case ARROW_RIGHT: case ARROW_UP: case ARROW_DOWN: editor_move_cursor(c); break; case CTRL_KEY('l'): case '\x1b': break; default: editor_insert_char(c); break; } quit_times = PICO_QUIT_TIMES; } /*** output ***/ void editor_scroll() { E.rx = 0; if (E.cy < E.numrows) { E.rx = editor_row_cx_to_rx(&E.row[E.cy], E.cx); } if (E.cy < E.rowoff) { E.rowoff = E.cy; } if (E.cy >= E.rowoff + E.screenrows) { E.rowoff = E.cy - E.screenrows + 1; } if (E.rx < E.coloff) { E.coloff = E.rx; } if (E.rx >= E.coloff + E.screencols) { E.coloff = E.rx - E.screencols + 1; } } void editor_draw_rows(AppendBuf *ab) { int y; for (y = 0; y < E.screenrows; y++) { int filerow = y + E.rowoff; // I think the tutorial as `>=` here but it drew an extra tilde for me and now it just // has a blank line for appending a line to the file which is much better. // Is this undefined behavior or correct code ?!?! // It was UB... the bug is still here... Only crashes with no file input if (filerow >= E.numrows) { if (E.numrows == 0 && filerow == E.screenrows / 3) { // Create welcome message char welcome[80]; int welcomelen = snprintf(welcome, sizeof(welcome), "Pico editor -- version %s", PICO_VERSION); if (welcomelen > E.screencols) welcomelen = E.screencols; // Add padding int padding = (E.screencols - welcomelen) / 2; if (padding) { ab_append(ab, "~", 1); padding--; } while (padding--) ab_append(ab, " ", 1); ab_append(ab, welcome, welcomelen); // THIS SEEMED TO FIX IT!!!!! // used to just be else } else if (E.numrows == 0 || filerow == E.screenrows) { ab_append(ab, "~", 1); } } else { // Otherwise print the text at the yth row int len = E.row[filerow].rsize - E.coloff; if (len < 0) len = 0; if (len > E.screencols) len = E.screencols; char* c = &E.row[filerow].render[E.coloff]; unsigned char* hl = &E.row[filerow].hl[E.coloff]; // -1 indicates the default color int current_color = -1; int j; for (j = 0; j < len; j++) { if (iscntrl(c[j])) { // Non-printable characters // Capital letters come after the '@' character char sym = (c[j] <= 26) ? '@' + c[j] : '?'; // invert colors for printing ab_append(ab, "\x1b[7m", 4); ab_append(ab, &sym, 1); ab_append(ab, "\x1b[m", 3); if (current_color != -1) { char buf[16]; int clen = snprintf(buf, sizeof(buf), "\x1b[%dm", current_color); ab_append(ab, buf, clen); } } else if (hl[j] == HL_NORMAL) { if (current_color != -1) { ab_append(ab, "\x1b[39m", 5); current_color = -1; } ab_append(ab, &c[j], 1); } else { int color = editor_syntax_to_color(hl[j]); if (color != current_color) { current_color = color; char buf[16]; int clen = snprintf(buf, sizeof(buf), "\x1b[%dm", color); ab_append(ab, buf, clen); } ab_append(ab, &c[j], 1); } } ab_append(ab, "\x1b[39m", 5); } ab_append(ab, "\x1b[K", 3); ab_append(ab, "\r\n", 2); } } void editor_draw_status_bar(AppendBuf *ab) { // inverted colors ab_append(ab, "\x1b[7m", 4); char status[80], rstatus[80]; int len = snprintf(status, sizeof(status), "%.20s - %d lines %s", E.filename ? E.filename : "[No Name]", E.numrows, E.dirty ? "(modified)" : ""); int rlen = snprintf(rstatus, sizeof(rstatus), "%s | %d/%d", E.syntax ? E.syntax->filetype : "no ft", E.cy + 1, E.numrows); if (len > E.screencols) len = E.screencols; ab_append(ab, status, len); // Fill with spaces until right aligned line numbers while (len < E.screencols) { if (E.screencols - len == rlen) { ab_append(ab, rstatus, rlen); break; } else { ab_append(ab, " ", 1); len++; } } // normal text formatting ab_append(ab, "\x1b[m", 3); ab_append(ab, "\r\n", 2); } void editor_draw_message_bar(AppendBuf *ab) { ab_append(ab, "\x1b[K", 3); int msglen = strlen(E.statusmsg); if (msglen > E.screencols) msglen = E.screencols; if (msglen && time(NULL) - E.statusmsg_time < 5) ab_append(ab, E.statusmsg, msglen); } void editor_refresh_screen() { editor_scroll(); AppendBuf ab = ABUF_INIT; // Hide the cursor ab_append(&ab, "\x1b[?25l", 6); // 0x1b is 27 in hexidecimal which is the escape character // the other three bytes are "[2j" // Escape sequences start with an escape character (\x1b) // and then '['. They instruct the terminal to do various things. // 'J' is erase and '2' means to erase the entire screen (0 is default argument). // `ab_append(&ab, "\x1b[2J", 4);` // The 3 means write four bytes // 'H' is the cursor position command. // takes 2 arguments we could use "\x1b[12;40H" to move the curosr to the 12th row and 40th col // multiple arguments are separated by a ';'. Default arguments are 1 and 1. ab_append(&ab, "\x1b[H", 3); editor_draw_rows(&ab); editor_draw_status_bar(&ab); editor_draw_message_bar(&ab); // move cursor char buf[32]; snprintf(buf, sizeof(buf), "\x1b[%d;%dH", (E.cy - E.rowoff) + 1, (E.rx - E.coloff) + 1); ab_append(&ab, buf, strlen(buf)); // Show the cursor ab_append(&ab, "\x1b[?25h", 6); write(STDOUT_FILENO, ab.b, ab.len); abFree(&ab); } // This is how you do variable arguments in C, this is now a "variadic function" // All the cool va shit comes from <stdarg.h> // printf comes from <stdio.h> and time, obviously <time.h> void editor_set_status_message(const char *fmt, ...) { va_list ap; va_start(ap, fmt); vsnprintf(E.statusmsg, sizeof(E.statusmsg), fmt, ap); va_end(ap); E.statusmsg_time = time(NULL); } /*** init ***/ void editor_init() { E.cx = 0; E.cy = 0; E.rx = 0; E.rowoff = 0; E.coloff = 0; E.numrows = 0; E.row = NULL; E.dirty = 0; E.filename = NULL; E.statusmsg[0] = '\0'; E.statusmsg_time = 0; E.syntax = NULL; if (get_window_size(&E.screenrows, &E.screencols) == -1) die("get_window_size"); E.screenrows -= 2; } int main(int arc, char *argv[]) { enable_raw_mode(); editor_init(); if (arc >= 2) { editor_open(argv[1]); } editor_set_status_message("HELP: Ctrl-S to save | Ctrl-Q to quit | Ctrl-F to find"); for (;;) { editor_refresh_screen(); editor_process_keypress(); } return 0; }
C
#include<stdio.h> #include<stdlib.h> struct node { int data; struct node *left; struct node *right; }; struct node* insert(struct node *root,int data) { if(root==NULL) { root=(struct node *)malloc(sizeof(struct node)); root->data=data; root->left=NULL; root->right=NULL; } else { if(root->data>data) root->left=insert(root->left,data); else { root->right=insert(root->right,data); } } } void print(struct node *root) { if(root!=NULL) { printf("%d ",root->data); print(root->left); print(root->right); } } int main() { struct node *root=NULL; printf("Do you wanna enter data in binary search tree?(y/n)\n"); char choice; scanf("%c",&choice); while(choice=='y') { int data; printf("Enter data that you wanna store:"); scanf("%d",&data); root=insert(root,data); printf("Wanna enter more?(y/n)\n"); scanf(" %c",&choice); } printf("Your inorder traversal of tree is:\n"); print(root); printf("\n"); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "parser.h" /* private functions */ static void assignment(ParserState*); static void binary(ParserState*); static void expression(ParserState*); static void grouping(ParserState*); static void identifier(ParserState*); static void number(ParserState*); static void string(ParserState*); static void unary(ParserState*); BytecodeArray *parse(VirtualMachine *vm, TokenArray *tokens) { ArrayIterator iter = { tokens->count, 0 }; BytecodeArray *bytecode = create_bytecode_dynarray(); bytecode->names = &vm->names; ParserState s; s.current = tokens->tokens; s.prev = NULL; s.bytecode = bytecode; s.iter = &iter; s.error = 0; expression(&s); // statement(&s); #ifdef DEBUG_PARSER printf("index at %ld out of %d\n", s.current - tokens->tokens, tokens->count); #endif return bytecode; } /* private functions */ const static Rule rules[] = { [T_NONE] = { NULL, NULL, PREC_NONE }, [T_EOF] = { NULL, NULL, PREC_NONE }, [T_ERROR] = { NULL, NULL, PREC_NONE }, [T_NIL] = { NULL, NULL, PREC_NONE }, [T_IDENTIFIER] = { identifier, NULL, PREC_NONE }, [T_STRING] = { string, NULL, PREC_NONE }, [T_NUMBER] = { number, NULL, PREC_NONE }, [T_BOOLEAN] = { NULL, NULL, PREC_NONE }, [T_AND] = { NULL, NULL, PREC_NONE }, [T_OR] = { NULL, NULL, PREC_NONE }, [T_FUN] = { NULL, NULL, PREC_NONE }, [T_IF] = { NULL, NULL, PREC_NONE }, [T_ELSE] = { NULL, NULL, PREC_NONE }, [T_FOR] = { NULL, NULL, PREC_NONE }, [T_WHILE] = { NULL, NULL, PREC_NONE }, [T_VAR] = { assignment, NULL, PREC_NONE }, [T_TRUE] = { NULL, NULL, PREC_NONE }, [T_FALSE] = { NULL, NULL, PREC_NONE }, [T_LPAREN] = { grouping, NULL, PREC_NONE }, [T_RPAREN] = { NULL, NULL, PREC_NONE }, [T_LBRACKET] = { NULL, NULL, PREC_NONE }, [T_RBRACKET] = { NULL, NULL, PREC_NONE }, [T_LCURLY] = { NULL, NULL, PREC_NONE }, [T_RCURLY] = { NULL, NULL, PREC_NONE }, [T_QUOTE] = { NULL, NULL, PREC_NONE }, [T_DBL_QUOTE] = { NULL, NULL, PREC_NONE }, [T_SEMICOLON] = { NULL, NULL, PREC_NONE }, [T_COMMA] = { NULL, NULL, PREC_NONE }, [T_DOT] = { NULL, NULL, PREC_NONE }, [T_HASHTAG] = { NULL, NULL, PREC_NONE }, [T_CARET] = { NULL, NULL, PREC_NONE }, [T_PIPE] = { NULL, NULL, PREC_NONE }, [T_AMP] = { NULL, NULL, PREC_NONE }, [T_EQL] = { NULL, NULL, PREC_NONE }, [T_DBL_EQL] = { NULL, binary, PREC_COMPARISON }, [T_BANG] = { NULL, NULL, PREC_NONE }, [T_BANG_EQL] = { NULL, NULL, PREC_NONE }, [T_GREATER] = { NULL, NULL, PREC_NONE }, [T_LESS] = { NULL, NULL, PREC_NONE }, [T_GREATER_EQL] = { NULL, NULL, PREC_NONE }, [T_LESS_EQL] = { NULL, NULL, PREC_NONE }, [T_PLUS] = { NULL, binary, PREC_TERM }, [T_MINUS] = { unary, binary, PREC_TERM }, [T_ASTERISK] = { NULL, binary, PREC_FACTOR }, [T_SLASH] = { NULL, binary, PREC_FACTOR }, [T_PLUS_PLUS] = { NULL, NULL, PREC_NONE }, [T_MINUS_MINUS] = { NULL, NULL, PREC_NONE }, [T_PLUS_EQL] = { NULL, NULL, PREC_NONE }, [T_MINUS_EQL] = { NULL, NULL, PREC_NONE }, [T_ASTERISK_EQL] = { NULL, NULL, PREC_NONE }, [T_SLASH_EQL] = { NULL, NULL, PREC_NONE }, }; /* helper functions */ static const Rule *const get_rule(Token *token) { return &rules[token->type]; } static void advance(ParserState *parser) { parser->prev = parser->current; parser->current++; } static int expect(ParserState *parser, TokenType type) { if (parser->current == NULL || parser->current->type != type) { parser->error = 1; return 0; } return 1; } static int at_end(ParserState *parser) { return parser->current->type == T_EOF; } static void index_of(NameArray *names, char *str, int *ind) { for (unsigned int i = 0; i < names->elements; i++) { if (strcmp(names->array[i], str) == 0) { *ind = i; return; } } *ind = -1; } static void emit_opcode(BytecodeArray *array, opcode_t op) { append_to_bytecode_dynarray(array, op); } static void emit_constant(BytecodeArray *array, Value val) { append_to_bytecode_dynarray(array, OP_CONSTANT); append_to_bytecode_dynarray(array, array->constants->elements); // index of constant append_to_value_dynarray(array->constants, val); } static void emit_set_name(ParserState *parser, char *str) { BytecodeArray *code = parser->bytecode; int ind = -1; index_of(code->names, str, &ind); append_to_bytecode_dynarray(code, OP_SET_GLOBAL); if (ind == -1) { append_to_bytecode_dynarray(code, code->names->elements); // index of constant append_to_name_dynarray(code->names, str); } else { append_to_bytecode_dynarray(code, ind); } } static void emit_get_name(ParserState *parser, char *str) { BytecodeArray *code = parser->bytecode; int ind = -1; index_of(code->names, str, &ind); append_to_bytecode_dynarray(code, OP_GET_GLOBAL); if (ind == -1) { append_to_bytecode_dynarray(code, code->names->elements); // index of constant append_to_name_dynarray(code->names, str); } else { append_to_bytecode_dynarray(code, ind); } } /* parsing functions */ static void parse_precedence(ParserState *parser, Precedence prec) { #ifdef DEBUG_PARSER printf("in parse_precedence\n"); #endif ParsingFunction prefix = get_rule(parser->current)->prefix; if (prefix == NULL) { printf("expected expression\n"); return; } prefix(parser); while (!at_end(parser) && prec <= get_rule(parser->current)->precedence) { ParsingFunction infix = get_rule(parser->current)->infix; infix(parser); } } static void expression(ParserState *parser) { parse_precedence(parser, PREC_ASSIGNMENT); } static void binary(ParserState *parser) { #ifdef DEBUG_PARSER printf("in binary\n"); #endif Token *operator = parser->current; advance(parser); parse_precedence(parser, get_rule(operator)->precedence + 1); switch (operator->type) { case T_PLUS: emit_opcode(parser->bytecode, OP_ADD); break; case T_MINUS: emit_opcode(parser->bytecode, OP_SUB); break; case T_ASTERISK: emit_opcode(parser->bytecode, OP_MULT); break; case T_SLASH: emit_opcode(parser->bytecode, OP_DIV); break; case T_DBL_EQL: emit_opcode(parser->bytecode, OP_CMP); break; default: break; } #ifdef DEBUG_PARSER printf("out of binary\n"); #endif } static void unary(ParserState *parser) { #ifdef DEBUG_PARSER printf("in unary\n"); #endif Token *operator = parser->current; advance(parser); parse_precedence(parser, get_rule(operator)->precedence + 1); switch (operator->type) { case T_MINUS: emit_opcode(parser->bytecode, OP_SUB); break; default: break; } #ifdef DEBUG_PARSER printf("out of unary\n"); #endif } static void identifier(ParserState *parser) { emit_get_name(parser, parser->current->value); advance(parser); } static void number(ParserState *s) { #ifdef DEBUG_PARSER printf("in number\n"); #endif emit_constant(s->bytecode, double_value(atof(s->current->value))); advance(s); #ifdef DEBUG_PARSER printf("out of number\n"); #endif } static void string(ParserState *s) { #ifdef DEBUG_PARSER printf("in number\n"); #endif emit_constant(s->bytecode, string_value(s->current->value)); advance(s); #ifdef DEBUG_PARSER printf("out of number\n"); #endif } static void grouping(ParserState *s) { advance(s); expression(s); if (!expect(s, T_RPAREN)) { report_error("SyntaxError", "Expected closing parenthesis ')'"); return; } else { advance(s); } } /* var x = expr */ static void assignment(ParserState *parser) { advance(parser); /* expect identifier, push name */ if (!expect(parser, T_IDENTIFIER)) { report_error("SyntaxError", "Expected identifier in assignment statement"); return; } Token *name = parser->current; advance(parser); if (!expect(parser, T_EQL)) { report_error("SyntaxError", "Expected '=' after variable in assignment statement"); return; } advance(parser); expression(parser); emit_set_name(parser, name->value); }
C
/** * Motion profiles. * */ #include "global.h" typedef struct { // Maximum values float maximum_acceleration; // tick/Tech^2 float maximum_deceleration; // tick/Tech^2 float maximum_speed; // tick/Tech float distance; // tick // Current values float acceleration; float deceleration; float speed; // Position information float distance_left; // Internal values and flags float old_speed; bool start_flag; bool busy_flag; bool direction; bool stop_flag; } PROFILE; /** * Initialize profile * @param handle Handle of this bangbang calculation * @param acceleration Maximum acceleration [1.15] (tr/sec^2) * @param deceleration Maximum deceleration [1.15] (tr/sec^2) * @param nom_speed Nominal velocity [1.15] (tr/min) * @param final_pos Final position [64.0] (ticks) * @param current_pos Current position [64.0] (ticks) */ void init_profile(PROFILE *h, float acceleration, float deceleration, float maximum_speed, float distance, float tech) { volatile int toto = (float)tech; h->maximum_acceleration = acceleration; h->maximum_deceleration = deceleration; h->maximum_speed = maximum_speed; h->distance = distance; if (h->busy_flag != true) h->old_speed = 0.0; h->busy_flag = true; h->start_flag = true; h->stop_flag = 0; } /** * Move profile processing. * @param handle Handle of this bangbang calculation * @param meas_position Position Measurement * @return Next position */ float profile_process(PROFILE *h, float position) { return h->distance + position; } /** * BangBang reset values * @param handle Handle of this bangbang calculation * @param meas_position Position Measurement * @return Next position */ void profile_reset(PROFILE *h) { h->speed = 0; h->busy_flag = false; h->start_flag = false; } /** * BangBang smooth stop * @param handle Handle of this bangbang calculation */ void profile_smooth_stop(PROFILE *h) { h->stop_flag = true; }
C
#include <stdio.h> void func1(int [], int); void func2(int *, int); void func1(int x[], int n){ // Equivalently, void func1(int * x, int n){ int i; for (i=0; i<n; i++) printf("%d ", x[i]); // Equivalently, printf("%d ", *(x+i)); } void func2(int x[], int n){ // Equivalently, void func2(int * x, int n){ x=x+n-1; int i; for (i=0; i<n; i++) printf("%d ", *(x-i)); // Equivalently, printf("%d ", *(x-i)); } int main(){ int a[]={1,2,3,4}; func1(a, sizeof(a)/sizeof(a[0])); printf("\n"); func2(a, sizeof(a)/sizeof(a[0])); return 0; }
C
#include "fallocator.h" /* * Fallocator is again a simple allocator which is used to manage temporary memory. * It does a 4KB alloc using malloc and returns memory by simply incrementing the * used pointer by whatever size is required. For memory bigger than 4KB, it * depends on malloc. If the new allocation cannot be fulfilled from the * current buffer, new buffer is allocated. * * None of the memory allocated by fallocator is reused. Calling free simply * decrements refcount on the parent buffer and when refcount becomes 0, the * buffer is freed in one shot. * * All buffers used by fallocator are tracked. So even if caller forgets to * free memory, it is finally freed when the fallocator is destroyed. * * It is not good to use fallocator for allocating memory which will be retained * for long time as this will just increase memory pressure on the system. * * We use it at two places. * 1) A single fallocator for lua scripts as they only use memory temporarily. * Once the script is executed, all used memory will be freed by lua GC. * 2) For the connection buffer and subsequent parsing of the request, * generating response, etc. Again this memory is usually released very fast, * and any pending stuff is cleared when connection is closed. * * Instead of bothering malloc again and again, we also cache the fallocator * buffer (only 4KB buffers). The default size of cache is 16MB but can be * increased/decreased as required via command line parameter -i. */ /* 8 bytes are for the malloc header so that the whole thing is in 1 page */ #define DEFAULT_BUFFER_SIZE (4096 -(8+sizeof(memoryBuffer_t))) typedef struct memoryBuffer_t { struct memoryBuffer_t* pNext; struct memoryBuffer_t* pPrev; u_int32_t size; u_int32_t used; u_int32_t refCount; char data[0]; } memoryBuffer_t; //TODO : not good...globals are bad static int MAX_BUFFER_COUNT = 4096; static int freeCount = 0; static memoryBuffer_t* pGlobalFreeList = 0; /* Every pointer that we give to the user has a 8/4 bytes overhead to keep track of the * memoryBuffer_t it belongs to. We can optimize on this is many ways (make this zero) * but this simple approach makes sure that we don't need to make any assumptions about * the address we are working with. */ typedef struct memoryPointer_t { memoryBuffer_t* pBuffer; char data[0]; } memoryPointer_t; typedef struct fallocatorImpl_t { memoryBuffer_t* pDefaultBuffers; memoryBuffer_t* pLargeBuffers; u_int32_t allocCount; u_int32_t freeCount; u_int32_t allocSize; } fallocatorImpl_t; #define FALLOCATOR(x) ((fallocatorImpl_t*)(x)) static memoryBuffer_t* allocateMemoryBuffer(u_int32_t size) { memoryBuffer_t* pBuffer = 0; if ((size == DEFAULT_BUFFER_SIZE) && freeCount) { pBuffer = pGlobalFreeList; pGlobalFreeList = pGlobalFreeList->pNext; if (pGlobalFreeList) { pGlobalFreeList->pPrev = 0; } freeCount--; memset(pBuffer, 0, size + sizeof(memoryBuffer_t)); pBuffer->size = size; }else { pBuffer = (memoryBuffer_t*)malloc(size + sizeof(memoryBuffer_t)); if (pBuffer) { memset(pBuffer, 0, size + sizeof(memoryBuffer_t)); pBuffer->size = size; } } return pBuffer; } static void freeMemoryBuffer(memoryBuffer_t* pBuffer) { if (pBuffer) { if ((pBuffer->size == DEFAULT_BUFFER_SIZE) && (freeCount < MAX_BUFFER_COUNT)) { memset(pBuffer, 0, DEFAULT_BUFFER_SIZE + sizeof(memoryBuffer_t)); pBuffer->pNext = pGlobalFreeList; pBuffer->pPrev = 0; if (pGlobalFreeList) { pGlobalFreeList->pPrev = pBuffer; } pGlobalFreeList = pBuffer; freeCount++; pBuffer = 0; }else { free(pBuffer); } } } /* calls free on all the pointers in the memoryBuffer list */ static int freeBufferList(memoryBuffer_t* pBufferList) { memoryBuffer_t* pNext = 0; int count = 0; while(pBufferList) { pNext = pBufferList->pNext; freeMemoryBuffer(pBufferList); pBufferList = pNext; count++; } return count; } static void linkBuffer(memoryBuffer_t* pBuffer, memoryBuffer_t** ppHead) { if (!(*ppHead)) { *ppHead = pBuffer; pBuffer->pNext = 0; pBuffer->pPrev = 0; }else { pBuffer->pNext = *ppHead; (*ppHead)->pPrev = pBuffer; *ppHead = pBuffer; } } static void delinkBuffer(memoryBuffer_t* pBuffer, memoryBuffer_t** ppHead) { if (pBuffer->pNext) { if (pBuffer->pPrev) { pBuffer->pPrev->pNext = pBuffer->pNext; pBuffer->pNext->pPrev = pBuffer->pPrev; }else { pBuffer->pPrev->pNext = 0; } }else { if (pBuffer->pPrev) { pBuffer->pPrev->pNext = 0; }else { *ppHead = 0; } } pBuffer->pNext = 0; pBuffer->pPrev = 0; } static void* getPointerFromBuffer(memoryBuffer_t* pBuffer, u_int32_t alignedSize) { memoryPointer_t* pMP = (memoryPointer_t*)(pBuffer->data + pBuffer->used); pMP->pBuffer = pBuffer; pBuffer->refCount++; pBuffer->used+= alignedSize; return pMP->data; } //////////////////////////////////////////////////////////////////////////////////////////////////// fallocator_t fallocatorCreate(void) { fallocatorImpl_t* pPool = (fallocatorImpl_t*)malloc(sizeof(fallocatorImpl_t)); IfTrue(pPool, ERR, "Out of memory"); memset(pPool, 0, sizeof(fallocatorImpl_t)); goto OnSuccess; OnError: if (pPool) { fallocatorDelete(pPool); pPool = NULL; } OnSuccess: return pPool; } void fallocatorDelete(fallocator_t fallocator) { fallocatorImpl_t* pPool = FALLOCATOR(fallocator); if (pPool) { int bufferCount = 0, largeBufferCount = 0; bufferCount = freeBufferList(pPool->pDefaultBuffers); largeBufferCount = freeBufferList(pPool->pLargeBuffers); LOG(DEBUG, "Deleting pool %p with bufferCount %d largeBufferCount %d allocCount %d freeCount %d allocSize %d", pPool, bufferCount, largeBufferCount, pPool->allocCount, pPool->freeCount, pPool->allocSize); free(pPool); pPool = 0; } } void* fallocatorMalloc(fallocator_t fallocator, u_int32_t size) { fallocatorImpl_t* pPool = FALLOCATOR(fallocator); void* pointer = 0; u_int32_t alignedSize = (size + sizeof(void*)+ 7) & (~0x07); IfTrue(pPool, ERR, "Pool is NULL"); if (alignedSize > DEFAULT_BUFFER_SIZE) { memoryBuffer_t* pBuffer = allocateMemoryBuffer(alignedSize); IfTrue(pBuffer, WARN, "Error allocating memory"); linkBuffer(pBuffer, &pPool->pLargeBuffers); pointer = getPointerFromBuffer(pBuffer, alignedSize); pPool->allocCount++; pPool->allocSize+=alignedSize; }else { memoryBuffer_t* pBuffer = 0; if (!pPool->pDefaultBuffers) { /* NO buffer - allocate one */ pBuffer = allocateMemoryBuffer(DEFAULT_BUFFER_SIZE); IfTrue(pBuffer, WARN, "Out of memory"); linkBuffer(pBuffer, &pPool->pDefaultBuffers); }else { pBuffer = pPool->pDefaultBuffers; } if (alignedSize <= (pBuffer->size - pBuffer->used)) { pointer = getPointerFromBuffer(pBuffer, alignedSize); pPool->allocCount++; pPool->allocSize+=alignedSize; }else { /* current buffer cannot handle the new request, we need to add another one */ memoryBuffer_t* pNew = allocateMemoryBuffer(DEFAULT_BUFFER_SIZE); IfTrue(pNew, WARN, "Out of memory"); linkBuffer(pNew, &pPool->pDefaultBuffers); pointer = getPointerFromBuffer(pNew, alignedSize); pPool->allocCount++; pPool->allocSize+=alignedSize; } } goto OnSuccess; OnError: pointer = 0; OnSuccess: return pointer; } /* Free a pointer returned by fallocatorMalloc once it is no longer needed. * We have two choices here. One is to use this as a NO-OP. Life is simple in * this case, but we might run into issues where memory is being alloced and * freed in a tight loop. */ void fallocatorFree(fallocator_t fallocator, void* pointer) { fallocatorImpl_t* pPool = FALLOCATOR(fallocator); memoryPointer_t* pMP = (memoryPointer_t*)(pointer - sizeof(void*)); memoryBuffer_t* pBuffer = pMP->pBuffer; if (!pBuffer) { LOG(WARN, "double free detected ? pointer %p pool %p stats allocCount %d freeCount %d allocSize %d", pointer, pPool, pPool->allocCount, pPool->freeCount, pPool->allocSize); return; } if (pBuffer->size > DEFAULT_BUFFER_SIZE) { delinkBuffer(pBuffer, &pPool->pLargeBuffers); freeMemoryBuffer(pBuffer); pPool->freeCount++; }else { /* This is a pointer from a normal default buffers */ pMP->pBuffer = 0; //set to null or track double free pBuffer->refCount--; pPool->freeCount++; if (pBuffer->refCount == 0) { if (pBuffer == pPool->pDefaultBuffers) { pBuffer->used = 0; memset(pBuffer->data, 0, pBuffer->size); /* this makes sure that the next set of allocations go fine*/ }else { delinkBuffer(pBuffer, &pPool->pDefaultBuffers); freeMemoryBuffer(pBuffer); } } } } void* fallocatorRealloc(fallocator_t fallocator, void* pointer, u_int32_t osize, u_int32_t nsize) { fallocatorImpl_t* pPool = FALLOCATOR(fallocator); void* newPointer = 0; newPointer = fallocatorMalloc(pPool, nsize); if (newPointer) { int size = osize > nsize ? nsize : osize; memcpy(newPointer, pointer, size); fallocatorFree(pPool, pointer); return newPointer; } return NULL; } void fallocatorInit(u_int32_t bufferCount) { MAX_BUFFER_COUNT = bufferCount; }
C
int main() { int x; if(x>=0) while(x>0) x=x-1; else while(x<0) x=x+1; assert(x>0); }
C
#include <stdlib.h> #include <stdio.h> #include <string.h> int letrasDiferentes(char texto[]){ int len = strlen(texto); if(texto[len-1] == '\n') texto[--len] = 0; int diferentes = 0; char letras[128]; for(int i=0; texto[i] != '\0'; i++){ if (texto[i] != 32){ int novaLetra = 1; for (int j=0; letras[j] != '\0'; j++){ if(texto[i] == letras[j]){ novaLetra--; } } if(novaLetra == 1){ letras[strlen(letras)] = texto[i]; diferentes++; } } } return diferentes; } int main(){ char frase[256]; printf("Digite uma frase:\n"); fgets(frase, 255, stdin); printf("Existem %d letras diferentes na sua frase\n", letrasDiferentes(frase)); return 0; }
C
#include <sys/select.h> #include <stdio.h> #include <stdlib.h> #include <sys/ioctl.h> #include <sys/socket.h> #include <sys/time.h> #include <netinet/in.h> #include <errno.h> #include <unistd.h> #include <string.h> #define SERVER_PORT 12345 #define TRUE 1 #define FALSE 0 int main (int argc, char* argv[]) { int i, len, rc, on = 1; int listen_sd, max_sd, new_sd; int desc_ready, end_server = FALSE; int close_conn; char buffer[80]; struct sockaddr_in addr; struct timeval timeout; fd_set master_set, working_set; // Create the socket listen_sd = socket(AF_INET, SOCK_STREAM, 0); if (listen_sd < 0) { perror("socket() failed"); exit(-1); } // Allow socket descriptor to be reusable rc = setsockopt(listen_sd, SOL_SOCKET, SO_REUSEADDR, (char *) &on, sizeof(on)); if (rc < 0) { perror("setsockopt() failed"); close(listen_sd); exit(-1); } // Set socket to be nonblocking. Sockets for incoming connections will be // nonblocking as well (they will inherit from this one) rc = ioctl(listen_sd, FIONBIO, (char *) &on); if (rc < 0) { perror("ioctl() failed"); close(listen_sd); exit(-1); } // Bind the socket memset(&addr, 0, sizeof(addr)); addr.sin_family = AF_INET; addr.sin_addr.s_addr = htonl(INADDR_ANY); addr.sin_port = htons(SERVER_PORT); rc = bind(listen_sd, (struct sockaddr *) &addr, sizeof(addr)); if (rc < 0) { perror("bind() failed"); close(listen_sd); exit(-1); } // Set the listen back log rc = listen(listen_sd, 5); if (rc < 0) { perror("listen() failed"); close(listen_sd); exit(-1); } // Initialize the master fd_set FD_ZERO(&master_set); max_sd = listen_sd; FD_SET(listen_sd, &master_set); // Initialize the timeval struct to 3 minutes // If there's no activity for three minutes, program will end timeout.tv_sec = 3*60; timeout.tv_usec = 0; // Loop waiting for incoming connections do { // Copy master fd_set to working fd_set memcpy(&working_set, &master_set, sizeof(master_set)); // Call select and wait 3 minutes for it to complete printf("Waiting on select()...\n"); rc = select(max_sd+1, &working_set, NULL, NULL, &timeout); if (rc < 0) { perror(" select() failed"); break; } if (rc == 0) { printf(" select() timed out. End program.\n"); break; } // If it makes it hear, one or more descriptors are readable // Need to determine which are readable desc_ready = rc; for ( i = 0; i <= max_sd && desc_ready > 0; ++i) { // Check to see if the descriptor is ready if (FD_ISSET(i, &working_set)) { // Found a readable descriptor, so decrease the number // of descriptors we're looking for. desc_ready -= 1; if (i == listen_sd) { printf(" Listening socket is readable\n"); // Accept all incoming connections that are // queued up on the listener before we loop back // and call select again do { // Accept each incoming connection. If accept // failes with EWOULDBLOCK, then we have accepted // all of them. Any other failure will cause an exit new_sd = accept(listen_sd, NULL, NULL); if (new_sd < 0) { if (errno != EWOULDBLOCK) { perror(" accept() failed"); end_server = TRUE; } break; } // Add the new incoming connection to the master read set printf(" New incoming connection - %d\n", new_sd); FD_SET(new_sd, &master_set); if (new_sd > max_sd) max_sd = new_sd; // Loop back up and accept another incoming connection } while (new_sd != -1); } // This is not the listening socket, therefore an existing connection // must be readable else { printf(" Descriptor %d is readable\n", i); close_conn = FALSE; // Receive all incoming data before we loop back do { // Receive data until recv fails with EWOULDBLOCK rc = recv(i, buffer, sizeof(buffer), 0); if (rc < 0) { if (errno != EWOULDBLOCK) { perror(" recv() failed"); close_conn = TRUE; } break; } // Check to see if connection has been closed if (rc == 0) { printf(" Connection closed.\n"); close_conn = TRUE; break; } len = rc; printf(" %d bytes received\n", len); // Echo data back to the client rc = send(i, buffer, len, 0); if (rc < 0) { perror(" send() failed"); close_conn = TRUE; break; } } while (TRUE); // If the close_conn flag was turned on, we need to clean // up this active connection. This means removing the descriptor // from the master set and determining the new max descriptor value // based on the bits that are still turned on in the master set if (close_conn) { close(i); FD_CLR(i, &master_set); if (i == max_sd) { while (FD_ISSET(max_sd, &master_set) == FALSE) max_sd -=1; } } } // End of existing connection is readable } // End of if (FD_ISSET(i, &working_set)) } // End of loop through selectable descriptors } while (end_server == FALSE); // Clean up all of the sockets that are open for (i = 0; i <= max_sd; ++i) { if (FD_ISSET(i, &master_set)) close(i); } }
C
#include <stdio.h> int main(int argc, char **argv) { int i; for(i=0; argc; i++) { if(argc>i + 1) printf("%s", argv[i]); } return 0; }
C
// A first program in C. #include <stdio.h> // function main begins program execution int main() { printf("Welcome to C!\n"); } // end function main
C
#include <stdio.h> #include <pthread.h> #include <malloc.h> //#include <> #define CONSUME_COUNT 2 #define MANUFACTURE_COUNT 5 pthread_mutex_t mutex; int warehouse = 1000; static void* manufacturer() { while(1) { pthread_mutex_lock(&mutex); printf("Manufacturer created: %d items; warehouse: %d\n", MANUFACTURE_COUNT, warehouse += MANUFACTURE_COUNT); pthread_mutex_unlock(&mutex); sleep(1); } pthread_exit(NULL); } static void* consumer() { while(1) { pthread_mutex_lock(&mutex); if(warehouse >= CONSUME_COUNT) printf("Consumer consumed: %d items; warehouse: %d\n", CONSUME_COUNT, warehouse -= CONSUME_COUNT); else printf("Too small items!\n"); pthread_mutex_unlock(&mutex); sleep(1); } pthread_exit(NULL); } // входные параметры: // 1. количество производителей // 2. количество потребителей // 3. количество продукции на складе int main(int argc, char *argv[]) { int i; int manufacturer_count = atoi(argv[1]); int consumer_count = atoi(argv[2]); warehouse = atoi(argv[3]); pthread_t* manufacturer_thread = (pthread_t*) malloc(manufacturer_count * sizeof(pthread_t)); pthread_t* consumer_thread = (pthread_t*) malloc(consumer_count * sizeof(pthread_t)); pthread_mutex_init(&mutex, 0); for(i = 0; i < manufacturer_count; ++i) pthread_create(&manufacturer_thread[i], NULL, manufacturer, NULL); for(i = 0; i < consumer_count; ++i) pthread_create(&consumer_thread[i], NULL, consumer, NULL); pthread_mutex_destroy(&mutex); pthread_exit(NULL); }
C
#include <stdio.h> #include "string.h" #include "stdlib.h" /*дĸתСдĸ*/ static int tolower(int c) { if (c >= 'A' && c <= 'Z') { return c + 'a' - 'A'; } else { return c; } } static char htoi(char s[]) { int i = 0; int n = 0; if (s[0] == '0' && (s[1]=='x' || s[1]=='X')) { i = 2; } else { i = 0; } for (; (s[i] >= '0' && s[i] <= '9') || (s[i] >= 'a' && s[i] <= 'z') || (s[i] >='A' && s[i] <= 'Z');++i) { if (tolower(s[i]) > '9') { n = 16 * n + (10 + tolower(s[i]) - 'a'); } else { n = 16 * n + (tolower(s[i]) - '0'); } } return n; } void HexToChar(char *src,char * des) { volatile int i,length = 0; char chStr[2]; char *str1; str1 = strstr(src,"+CHTTPNMIC"); str1 = strstr(str1,","); str1++; str1 = strstr(str1,","); str1++; str1 = strstr(str1,","); str1++; str1 = strstr(str1,","); str1++; //printf("%s",str1); length = strlen(str1); for( i =0 ; i < length/2 ; i++) { chStr[0] = str1[i*2]; chStr[1] = str1[i*2+1]; des[i] = htoi(chStr); chStr[0] = '\0'; chStr[1] = '\0'; } des[i] = '\0'; }
C
/* * Tasks: * 1) Timer0 (Normal Mode) * 2) Toggle a led every 1 second using INTOVF (interrupt overflow) * 3)generate PWM using Timer0 -> takes 3 arguments : On period(msec), Total period(msec), Peak of signal(mv) * * clk=8MHz * Time of one tick = 1/clk = 1/8000000 = 0.125 usec * prescalar= 64 * clk/prescalar = 8000000/64 = 125000 * Time of one tick(prescalar) = 1/125000 = 8 usec * timer register resolution = 8 bits ,so it makes 256 ticks to overflow * Time of overflow = 2^resolution * time of one tick = 2^8 * 8 = 256*8 = 2048 usec * desired time in this application = 1 msec * 1 msec = 1000 usec which is < 2048 * 1000/8 = desired time/time of one tick = 125 ticks * preload value = 256-125 = 131 * *PWM: * * * * * * */
C
/* ****************************************************************** */ /* _____ _ __ */ /* By: Sergey Nikolaev / ___// | / / */ /* Сontacts: sn.prog@yandex.ru \__ \/ |/ / */ /* Created: 2020.09.19 (YYYY.MM.DD) ___/ / /| / */ /* Updated: 2020.10.21 (YYYY.MM.DD) /____/_/ |_/ */ /* */ /* ****************************************************************** */ #include "class_list.h" t_list_element *class_list_create_element( const t_class_list *p_list, const void *p_content) { t_list_element *p_element; if ((p_element = malloc(sizeof(*p_element))) == NULL) return (NULL); p_element->p_content = NULL; p_element->p_last = NULL; p_element->p_next = NULL; if (p_content == NULL) return (p_element); if ((p_element->p_content = p_list->copy_list_content(p_content)) == NULL) { free(p_element); return (NULL); } return (p_element); } t_list_element *class_list_create_element_to_end( t_class_list *p_list, const void *p_content) { t_list_element *p_element; if ((p_element = class_list_create_element(p_list, p_content)) == NULL) return (NULL); class_list_add_to_end(p_list, p_element); return (p_element); } t_list_element *class_list_create_element_to_start( t_class_list *p_list, const void *p_content) { t_list_element *p_element; if ((p_element = class_list_create_element(p_list, p_content)) == NULL) return (NULL); class_list_add_to_start(p_list, p_element); return (p_element); }
C
#ifndef queue_h_ #define queue_h_ #include "./header.h" struct queue_node { void *data; struct queue_node *next; struct queue_node *previous; }; struct queue { struct queue_node *head; struct queue_node *tail; unsigned int length; }; struct queue *initialize_queue(); void push_head_queue(struct queue **, void *); void push_tail_queue(struct queue **, void *); void *pop_head_queue(struct queue **); void *pop_tail_queue(struct queue **); unsigned int get_length_queue(struct queue *); void free_queue(struct queue **); #endif
C
#include "linklist.h" #include <stdlib.h> void inity (assem * asmb, unsigned int id) { asmb->beginy = asmb->endy = asmb->currenty = (linklist *) 0; asmb->idy = id; } void addy (assem * asmb, linklist * lst) { lst->prevy = lst->forwy = (linklist *) 0; if (!asmb->beginy) { asmb->beginy = lst; asmb->endy = lst; lst->idy = 0; } else { asmb->endy->forwy = lst; lst->prevy = asmb->endy; asmb->endy = lst; lst->idy = lst->prevy->idy + 1; } } void freey (assem * asmb) { linklist *tmp; asmb->currenty = asmb->beginy; while (asmb->currenty) { tmp = asmb->currenty; asmb->currenty = asmb->currenty->forwy; free (tmp); } } void freeally (assem * asmb) { linklist *tmp; asmb->currenty = asmb->beginy; while (asmb->currenty) { tmp = asmb->currenty; asmb->currenty = asmb->currenty->forwy; free (tmp->ptr); free (tmp); } } unsigned int numelementy (assem * asmb) { return (asmb->endy->idy + 1); } linklist * findbyidy (assem * asmb, unsigned int id) { asmb->currenty = asmb->beginy; while (asmb->currenty) { if (id == asmb->currenty->idy) { return (asmb->currenty); } asmb->currenty = asmb->currenty->forwy; } return (0); } int replacey (assem * asmb, linklist * lst, unsigned int id) { linklist *tmp; if (!(tmp = findbyidy (asmb, id))) { return (0); } if (asmb->beginy == asmb->endy) { asmb->beginy = asmb->endy = (linklist *) 0; addy (asmb, lst); } else if (tmp == asmb->beginy) { tmp->forwy->prevy = lst; lst->prevy = tmp->prevy; lst->forwy = tmp->forwy; asmb->beginy = lst; } else if (tmp == asmb->endy) { tmp->prevy->forwy = lst; lst->prevy = tmp->prevy; lst->forwy = tmp->forwy; asmb->endy = lst; } else { tmp->prevy->forwy = lst; tmp->forwy->prevy = lst; lst->prevy = tmp->prevy; lst->forwy = tmp->forwy; } lst->idy = tmp->idy; free (tmp); return (1); } int deletey (assem * asmb, unsigned int id) { linklist *tmp; if (!(tmp = findbyidy (asmb, id))) { return (0); } else if (asmb->beginy == asmb->endy) { asmb->beginy = asmb->endy = (linklist *) 0; } else if (tmp == asmb->beginy) { tmp->forwy->prevy = tmp->prevy; asmb->beginy = tmp->forwy; } else if (tmp == asmb->endy) { tmp->prevy->forwy = tmp->forwy; asmb->endy = tmp->prevy; } else { tmp->prevy->forwy = tmp->forwy; tmp->forwy->prevy = tmp->prevy; } asmb->currenty = tmp->forwy; while (asmb->currenty) { asmb->currenty->idy--; asmb->currenty = asmb->currenty->forwy; } free (tmp); return (1); } int inserty (assem * asmb, linklist * lst, unsigned int id) { linklist *tmp; if (!(tmp = findbyidy (asmb, id))) { return (0); } if ((asmb->beginy == asmb->endy) || (tmp == asmb->endy)) { addy (asmb, lst); return (1); } else { lst->prevy = tmp; lst->forwy = tmp->forwy; tmp->forwy->prevy = lst; tmp->forwy = lst; } asmb->currenty = lst; while (asmb->currenty) { asmb->currenty->idy = asmb->currenty->prevy->idy + 1; asmb->currenty = asmb->currenty->forwy; } return (1); }
C
/* Author: Miguel Osuna Purpose: Implement the output funcitons for file handling Date: 2/6/19 */ #include <stdio.h> #include <stdlib.h> #include <string.h> int main() { FILE *filePtr = NULL; char *fileName = "myfile.txt"; char day[] = "Wednesday"; char name[] = "My name is Miguel"; int hours = 6; int minutes = 40; filePtr = fopen(fileName, "w"); //If there is no file named "myfile.txt", fopen() will create one because of "w" mode if(!filePtr) //Check for NULL character { printf("Failed to open file"); return STDERR_FILENO; } fputs("Today is: \n", filePtr); //Ads a character string to the first line of the file fprintf(filePtr, "%s %d %d\n", day, hours, minutes); //Add the formatted output to the file until a new line is found. Then a new line is specified for(int i = 0; i < strlen(name); i++) //Adding 'name' string to "myfile.txt" on the third line fputc(name[i], filePtr); //Has to be added character by character (inefficient) fclose(filePtr); filePtr = NULL; return 0; }
C
#include <stdio.h> int main () { float f; printf("Enter your float number: "); scanf("%f", &f); printf("The float number you enter: %0.4f", f); return 0; }
C
#include <stdio.h> #include <ctype.h> #include <math.h> //ֽ׶λûõ #include "stack.h" int main() { Stack infix = create(); Stack postfix = create(); double num[MAXSTACKSIZE] = {0}; //numڴ int cnt = 0; //cntnumindex //ݲֱתΪ׺ʽ char ch; while ((ch = getchar()) != '\n') { if (isspace(ch)) //ո continue; switch (ch) { case '+': case '-': case '(': push(infix, ch); //ȼֱѹջinfix break; case '*': case '/': while (peek(infix) == '+' || peek(infix) == '-') push(postfix, pop(infix)); //ȼȽinfixеȼijջpostfixѹջinfix push(infix, ch); break; case ')': while (peek(infix) != '(') //infixеջֱ'('ע'('ҲҪջpostfix push(postfix, pop(infix)); pop(infix); break; case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case '0': case '.': ungetchar(ch); scanf("%lf", num[cnt++]); //һֵĴ棬Աdouble͵ʵ֣cntǸָ루Ҳջֱӽʵ֣ push(postfix, -cnt + 1); //ֱӽpostfix break; } } while (peek(infix)) //postfixʣԪؽinfix push(postfix, pop(infix)); // double re; //ڴÿһεĽ while ((ch = pop(postfix))) { if (isspace(ch)) //ո continue; if (isdigit(ch)) //ֱѹջinfix { push(infix, ch); continue; } switch (ch) //postfixӼ˳ֱӽ㣬ѹջinfix { case '+': re = num[-pop(infix)] + num[-pop(infix)]; num[cnt++] = re; push(infix, -cnt + 1); break; case '-': re = num[-pop(infix)] - num[-pop(infix)]; num[cnt++] = re; push(infix, -cnt + 1); break; case '*': re = num[-pop(infix)] + num[-pop(infix)]; num[cnt++] = re; push(infix, -cnt * 1); break; case '/': re = num[-pop(infix)] / num[-pop(infix)]; num[cnt++] = re; push(infix, -cnt + 1); break; } } printf("%.6f\n", num[pop(infix)]); //infix destroy(infix); destroy(postfix); }
C
#include<stdio.h> #include<stdlib.h> #include<string.h> #include<sys/types.h> #include<sys/socket.h> #include<netinet/in.h> #include<arpa/inet.h> #include<unistd.h> #include<errno.h> #define PORT 5561 #define BUF_SIZE 2000 #define CLADDR_LEN 100 char *itoaa(int val, int base); int main(){ struct sockaddr_in addr, cl_addr; int sockfd, len, ret, newsockfd; char buffer[BUF_SIZE]; pid_t childpid; char clientAddr[CLADDR_LEN]; int num, rem, sum; char *str; //domain, type, protocol sockfd = socket(AF_INET, SOCK_STREAM, 0); if (sockfd < 0) { printf("Error creating socket!\n"); exit(1); } printf("Socket created...\n"); memset(&addr, 0, sizeof(addr)); addr.sin_family = AF_INET; addr.sin_addr.s_addr = INADDR_ANY; addr.sin_port = PORT; ret = bind(sockfd, (struct sockaddr *) &addr, sizeof(addr)); if (ret < 0) { printf("Error binding!\n"); exit(1); } else printf("Binding done...\n"); printf("Waiting for a connection...@ port no : %d\n",PORT );listen(sockfd, 5); for (;;) //infinite loop { len = sizeof(struct sockaddr_in); newsockfd = accept(sockfd, (struct sockaddr*)&cl_addr,(socklen_t *)&len); if (newsockfd < 0) { printf("Error accepting connection!\n"); exit(1); } else printf("Connection accepted from "); inet_ntop(AF_INET, &(cl_addr.sin_addr), clientAddr, CLADDR_LEN); printf("Port %d of %sClient\n",ntohs(cl_addr.sin_port),inet_ntoa(cl_addr.sin_addr)); if ((childpid = fork()) == 0) //creating a child process { close(sockfd); //stop listening for new connections by the main process. //the child will continue to listen. //the main process now handles the connected client. for (;;) { memset(buffer, 0, BUF_SIZE); ret = recvfrom(newsockfd, buffer, BUF_SIZE, 0, (struct sockaddr *) &cl_addr, (socklen_t *)&len); if(ret < 0) { printf("Error receiving data!\n"); exit(1); } else printf("Received data from Port No %d of Client %s : %s\n ", ntohs(cl_addr.sin_port),clientAddr, buffer); num=atoi(buffer); sum=0; while(num>0) { sum = sum + (num % 10); num = num / 10; } strcat(buffer,"= sum of digits = "); str=itoaa(sum,10); strcat(buffer,str); ret = sendto(newsockfd, buffer, BUF_SIZE, 0,(struct sockaddr *) &cl_addr, len); if (ret < 0) { printf("Error sending data!\n"); exit(1); } else printf("\tSent data to %s on Port No %d :%s\n", clientAddr,ntohs(cl_addr.sin_port), buffer); printf("-----------------------------------------\n"); } } close(newsockfd); } return(0); } char *itoaa(int val, int base) { static char buf[32] = {0}; int i = 30; for( ; val && i ; --i, val /= base) buf[i]="0123456789abcdef"[val % base]; return &buf[i+1]; }
C
#include<stdio.h> //OUMAROU Abas /*exercice 1 : l'Algorithme d'Eratosthne ce programme permet d'afficher des nombres premiers infrieurs au nombre entr par l'utilisateur : */ int main(int argc,char**argv) // cration d'un tableau qui contiendra toutes les valeurs // vrification du nombre entr par l utilisateur { int n, i,j; printf("ce programme effectue l'algoritme d'Eratosthne \n\n"); printf("entrer un nombre suprieur ou gal 2\n"); scanf("%d",&n); int tab[n+1]; /* initialisation du tableau : toutes les cases sont 1 si un nombre n'est pas prmier, il est multiple d'un nombre premier il suffit donc d'liminer les multiples des nombres premiers */ for(i=0;i<=n;i++) { tab[i]=1; } if(n<2) { printf("erreur, impossible"); } else for(i=2;i<=n/2;i++) for(j=2;j<=n/i;j++) { tab[i*j]=0; } // impression des nombres premiers for(i=2;i<=n;i++) if(tab[i]) { printf("%d \n\n",i); } }
C
#include <stdio.h> #include <stdlib.h> /*Напишете програма, която да създаде стек (LIFO) по подобие на този от лекция 18, който обаче да бъде реализиран с динамично с динамично заделяне на памет съобразно желанието на потребителя с функциите malloc(), и free(). Стека да има следните функции (следното API): struct Stack{ int *contents; int top; }; Stack create(int size); void destroy(Stack s); int pop(); void push() int top() int isFull(); int isEmpty(void)*/ struct Stack { int *contents; int top; }; int main(void) { return 0; }
C
/* Filename: st_parsetime2.c * This is a version of st_parsetime.c that has been cleaned up * and upgraded to use STDTIME2 structures. All routines herein * now end with a 2. */ #include <stdio.h> #include <dcc_std.h> #include <dcc_time.h> static STDTIME2 setuptime; static BOOL dateset,timeset; extern UBYTE _dmsize[]; void timeload2(int hour, int minute, int second, LONG tenth_msec) { timeset = TRUE; setuptime.hour = hour; setuptime.minute = minute; setuptime.second = second; setuptime.tenth_msec = tenth_msec; } void _setyear2(void) { int y, f; y = setuptime.year; if (y > 1900) return; /* Its probably ok */ f = 0; if (y > 99) f = TM_CENT; else if (y > 9) f = TM_DECADE; setuptime.year = _calyear(y, 0, f); } void juldateset2(int year, int day) { dateset = TRUE; setuptime.year = year; _setyear2(); setuptime.day = day; } void nordate2(int month, int day, int year) { int ct, i; dateset = TRUE; setuptime.year = year; _setyear2(); _dmsize[1] = _tleap(setuptime.year)?29:28; ct = 0; for (i = 0; i < month-1; i++) { ct += _dmsize[i]; } ct += day; setuptime.day = ct; } STDTIME2 ST_CleanDate2(STDTIME2 indate, WORD epoch, ULONG timflgs); STDTIME2 ST_ParseTime2(UBYTE *inbuff) { int getbuf,i; int year, doy, hour, minute, second, tmsec; int iArg; UBYTE trsbuf[120]; for (i = 0; i < strlen(inbuff); i++) { if (isupper(inbuff[i])) trsbuf[i] = tolower(inbuff[i]); else trsbuf[i] = inbuff[i]; } trsbuf[i++] = '\0'; year = 0; doy = 0; hour = 0; minute = 0; second = 0; tmsec = 0; iArg = sscanf(trsbuf, "%d,%d,%d:%d:%d.%d", &year, &doy, &hour, &minute, &second, &tmsec); setuptime.year = year; setuptime.day = doy; setuptime.hour = hour; setuptime.minute = minute; setuptime.second = second; setuptime.tenth_msec = tmsec; dateset = timeset = FALSE; return(ST_CleanDate2(setuptime, 0, TM_MILEN)); }
C
#include<stdio.h> void filecopy(FILE *ifp, FILE *ofp); int main(int argc, char const *argv[]) { if(argc == 1){ filecopy(stdin, stdout); return 0; }else if (argc == 3) { FILE* fp_in = fopen(argv[1], "r"); FILE* fp_out = fopen(argv[2], "w+"); filecopy(fp_in, fp_out); } return 0; } void filecopy(FILE *ifp, FILE *ofp){ int c; while ((c = getc(ifp)) != EOF){ printf("%c", c); putc(c, ofp); } }
C
#include <stdio.h> #include "../inc/myheader.h" int main(){ int y=triple(3); printf("Result of triple(3) is %d\n",y); return 0; }
C
#include <linux/module.h> #include <linux/mm.h> #include <linux/slab.h> struct page *pages; static char *vptr; int init_module(void) { pr_info("size of a page is %lu\n", PAGE_SIZE); pages = alloc_pages(GFP_KERNEL, 2); if (!pages) { pr_err("unable to allocate requested pages\n"); return ENOMEM; } vptr = page_address(pages); strcpy(vptr ,"Hi Page how are you\n"); pr_info("sucessfull init module\n"); return 0; } void cleanup_module(void) { if (vptr) pr_info("page contents are: %s\n", vptr); if (pages) __free_pages(pages, 2); pr_info("unloading page example module\n"); } MODULE_LICENSE("GPL"); MODULE_AUTHOR("Ganji Aravind"); MODULE_DESCRIPTION("Example about struct pages");
C
// C program to implement Bubble Sort #include <stdio.h> #include <conio.h> //function to perform Swapping of elements using pointers void swap(int *rowEle, int *colEle) { int temp; temp = *rowEle; *rowEle = *colEle; *colEle = temp; } //function to Bubble Sort void bubbleSort(int ar[], int n) { int row, col; for(row = 0; row < n-1; row++) { for(col = 0; col < n-row-1; col++) { if(ar[col] > ar[col+1]) swap(&ar[col], &ar[col+1]); } } } //function to display elements of the Sorted Array void displayArray(int ar[], int len) { int i; for(i = 0; i < len; i++) printf("%d ", ar[i]); printf("\n"); } //main function to control program execution by calling other functions int main() { int ar[20], len; //initialising the length of the array printf("Enter the length of the array \n"); scanf("%d", &len); printf("The elements are: \n"); //filling array with elements for(int i = 0; i < len; i++) scanf("%d", &ar[i]); bubbleSort(ar, len); printf("Sorted Array: \n"); displayArray(ar, len); return 0; }
C
#include <iostream> #include <vector> #include <chrono> #include <ctime> #include <iomanip> struct Date{ int year; int month; int day; }; int main(){ std::cout << "\nProblem 1:\n"; Date date1 {}; std::cout << "\nProblem 2:\n"; date1.year = 1996; date1.month = 4; date1.day = 25; std::cout << "\nProblem 3:\n"; Date date2 {}; date2.year = 1906; date2.month = 4; date2.day = 25; if( date1.year > date2.year){ std::cout << date1.year << "-" << date1.month << "-" << date1.day << std::endl; } else if ( date2.year > date1.year){ std::cout << date2.year << "-" << date2.month << "-" << date2.day << std::endl; } else{ if( date1.month > date2.month){ std::cout << date1.year << "-" << date1.month << "-" << date1.day << std::endl; } else if ( date2.month > date1.month) { std::cout << date2.year << "-" << date2.month << "-" << date2.day << std::endl; } else{ if( date1.day > date2.day){ std::cout << date1.year << "-" << date1.month << "-" << date1.day << std::endl; } else if ( date2.day > date1.day){ std::cout << date2.year << "-" << date2.month << "-" << date2.day << std::endl; } else{ std::cout << "SAME DATES\n"; } } } std::cout << "\nProblem 4:\n"; Date date3 {}; date3.year = 2008; date3.month = 8; date3.day = 5; std::vector<Date> dates {date1, date2, date3}; std::cout << dates[1].year << "-" << dates[1].month << "-" << dates[1].day << std::endl; std::cout << "\nProblem 5:\n"; dates[1].year = 1984; dates[1].month = 2; dates[1].day = 28; std::cout << dates[1].year << "-" << dates[1].month << "-" << dates[1].day << std::endl; std::cout << "\nProblem 6:\n"; Date *datePtr = &date1; datePtr->year = 1997; std::cout << date1.year << "-" << date1.month << "-" << date1.day << std::endl; std::cout << "\nProblem 7:\n"; auto now = std::chrono::system_clock::now(); auto now_c = std::chrono::system_clock::to_time_t(now); std::cout << "The time now is: " << std::put_time(std::localtime(&now_c), "%F %T") << std::endl; }