language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
/********** Including Necessary Header Files **********/ #include <unistd.h> #include <stdio.h> #include <sys/types.h> #include <sys/wait.h> #include <stdlib.h> #include <string.h> #include <readline/readline.h> #include <readline/history.h> #include <errno.h> #include <fcntl.h> #include <signal.h> /********** Declaring Global variables **********/ int fd; static char *args[512]; static char prompt[512]; char *history_file; char *input_buffer; char *cmd_exec[512]; int flag, len; char cwd[1024]; int bckgrnd_flag; pid_t pid; int no_of_lines; int environmment_flag; /********** Declaring Function Prototypes **********/ void clear_variables(); void environmment(); void set_environment_variables(); void change_directory(); void echo_calling(char *echo_val); char *skipwhite (char* ); void tokenize_by_space (char *); char *skip_double_quote(char* ); void shell_prompt(); void sigintHandler(int ); /********** Function Definitions **********/ /* This function handles the interrupt signals */ void sigintHandler(int sig_num) { signal(SIGINT, sigintHandler); fflush(stdout); return; } /* This function initializes the global variables */ void clear_variables() { fd = 0; flag = 0; len = 0; no_of_lines = 0; flag_without_pipe = 0; output_redirection = 0; input_redirection = 0; cwd[0] = '\0'; prompt[0] = '\0'; pid = 0; environmment_flag = 0; } /* This function is used to create the Shell Prompt */ void shell_prompt() { if (getcwd(cwd, sizeof(cwd)) != NULL) { strcpy(prompt, "Our_Shell: "); strcat(prompt, cwd); strcat(prompt, "$ "); } else { perror("Error in getting curent working directory: "); } return; } /* This function is used to skip the white spaces in the input string */ char *skipwhite (char* str) { int i = 0, j = 0; char *temp; if (NULL == (temp = (char *) malloc(sizeof(str)*sizeof(char)))) { perror("Memory Error: "); return NULL; } while(str[i++]) { if (str[i-1] != ' ') temp[j++] = str[i-1]; } temp[j] = '\0'; return temp; } /* This function is used to skip the double quote characters (") in the input string */ char *skip_double_quote (char *str) { int i = 0, j = 0; char *temp; if (NULL == (temp = (char *) malloc(sizeof(str)*sizeof(char)))) { perror("Memory Error: "); return NULL; } while(str[i++]) { if (str[i-1] != '"') temp[j++] = str[i-1]; } temp[j] = '\0'; return temp; } /* This function is used to change directory when "cd" command is executed */ void change_directory() { char *home_dir = "/home"; if ((args[1]==NULL) || (!(strcmp(args[1], "~") && strcmp(args[1], "~/")))) chdir(home_dir); else if (chdir(args[1]) < 0) perror("No such file or directory: "); } void echo_calling(char *echo_val) { int i=0, index=0; environmment_flag=0; char new_args[1024],env_val[1000], *str[10]; str[0]=strtok(echo_val," "); str[1]=strtok(NULL, ""); strcpy(env_val, args[1]); if(str[1]==NULL) { printf("\n"); return; } if (strchr(str[1], '$')) { environmment_flag=1; } memset(new_args, '\0', sizeof(new_args)); i=0; while(str[1][i]!='\0') { if(str[1][i]=='"') { index=0; while(str[1][i]!='\0') { if(str[1][i]!='"') { new_args[index]=str[1][i]; flag=1; index++; } i++; } } else if(str[1][i]==39) { index=0; while(str[1][i]!='\0') { if(str[1][i]!=39) { new_args[index]=str[1][i]; flag=1; index++; } i++; } } else if(str[1][i]!='"') { new_args[index]=str[1][i]; index++; i++; } else i++; } new_args[index]='\0'; if((strcmp(args[1], new_args)==0)&&(environmment_flag==0)) printf("%s\n", new_args); else { strcpy(args[1], new_args); if(environmment_flag==1) { environmment(); } else if(environmment_flag==0) { printf("%s\n", new_args ); } } } /* This function tokenizes the input string based on white-space [" "] */ void tokenize_by_space (char *str) { int m = 1; args[0] = strtok(str, " "); while ((args[m] = strtok(NULL," ")) != NULL) m++; args[m] = NULL; } /* Main function begins here */ int main() { int status; system ("clear"); signal(SIGINT, sigintHandler); char new_line = 0; using_history(); do { clear_variables(); shell_prompt(); input_buffer = readline (prompt); if(strcmp(input_buffer,"\n")) add_history (input_buffer); if (!(strcmp(input_buffer, "\n") && strcmp(input_buffer,""))) continue; if (!(strncmp(input_buffer, "exit", 4) && strncmp(input_buffer, "quit", 4))) { flag = 1; break; } if (bckgrnd_flag == 0) waitpid(pid,&status,0); else status = 0; } while(!WIFEXITED(status) || !WIFSIGNALED(status)); if (flag == 1) { printf("\nThank You... Closing Shell...\n"); exit(0); } return 0; }
C
void Division (int Numb [], int Size, int Left, int Right) { int OldLeft = Left, OldRight = Right; int MiddlePos = (Right + Left) / 2; int Middle = Numb [MiddlePos]; //$e printf ("\n<< Division (Numb, Size = %d, Left = %d, Right = %d): OldLeft = %d, OldRight = %d, MiddlePos = %d, Middle = %d \n", Size, Left, Right, OldLeft, OldRight, MiddlePos, Middle); $d //Control (Numb, Size, OldLeft, OldRight, Left, Right, (Right + Left) / 2, "Start"); if (Left >= Right) {/*Control (Numb, Size, OldLeft, OldRight, Left, Right, (Right + Left) / 2, "Too small, return"); */ return;} if (Right - Left == 1) { if (Numb [Left] > Numb [Right]) { Replacer (Numb, Left, Right); } //Control (Numb, Size, OldLeft, OldRight, Left, Right, (Right + Left) / 2, "Replaced 2 elements, return"); return; }; while (Left < Right) { while (Left < Right) { Compare = Compare + 1; if (Numb [Left] >= Middle) break; Left ++; } while (Right > Left) { Compare = Compare + 1; if (Numb [Right] <= Middle) break; Right --; } //Control (Numb, Size, OldLeft, OldRight, Left, Right, -1, "Found bad elements"); Replacer (Numb, Left, Right); //Control (Numb, Size, OldLeft, OldRight, Left, Right, -1, "Replaced two elements"); Left ++; Right --; } //Control (Numb, Size, OldLeft, OldRight, Left, Right, -1, "End"); if (Left > Right) { int L = Left, R = Right; Right = L, Left = R; //Control (Numb, Size, OldLeft, OldRight, Left, Right, -1, "Left and Right corrected"); } //getch (); Division (Numb, Size, OldLeft, Left); Division (Numb, Size, Right, OldRight); }
C
#include "eventhandler.h" #include "reactor.h" #include "diagnosticserver.h" #include <malloc.h> #include "tcpserver.h" struct DiagnosticsServer { EventHandler eventHandler; Handle listeningSocket; }; static Handle getServerSocket(void * instance) { const DiagnosticsServerPtr server = instance; return server->listeningSocket; } static void handleConnectReq(void * instance) { DiagnosticsServerPtr server = instance; // add code for accepting the new connection and creating a client here... } DiagnosticsServerPtr createServer(unsigned int tcpPort) { DiagnosticsServerPtr newServer = malloc(sizeof *newServer); if(newServer != 0) { newServer->listeningSocket = createServerSocket(tcpPort); newServer->eventHandler.instance = newServer; newServer->eventHandler.getHandle = getServerSocket; newServer->eventHandler.handleEvent = handleConnectReq; registerEvtHandler(&newServer->eventHandler); } return newServer; } void destroyServer(DiagnosticsServerPtr server) { unregisterEvtHandler(&server->eventHandler); free(server); }
C
#include "OLED_I2C.h" #include "delay.h" #include "font.h" #include "picture.h" void I2C_Configuration(void) { I2C_InitTypeDef I2C_InitStructure; GPIO_InitTypeDef GPIO_InitStructure; RCC_APB1PeriphClockCmd(RCC_APB1Periph_I2C3,ENABLE); RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOA | RCC_AHB1Periph_GPIOC,ENABLE); /*ӲI2C3: PA8 -- SCL; PC9 -- SDA */ GPIO_InitStructure.GPIO_Pin = GPIO_Pin_8; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;//I2C뿪© GPIO_InitStructure.GPIO_OType = GPIO_OType_OD; GPIO_Init(GPIOA, &GPIO_InitStructure); GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;//I2C뿪© GPIO_InitStructure.GPIO_OType = GPIO_OType_OD; GPIO_Init(GPIOC, &GPIO_InitStructure); GPIO_PinAFConfig(GPIOA,GPIO_PinSource8,GPIO_AF_I2C3); GPIO_PinAFConfig(GPIOC,GPIO_PinSource9,GPIO_AF_I2C3); I2C_DeInit(I2C3);//ʹI2C3 I2C_InitStructure.I2C_Mode = I2C_Mode_I2C; I2C_InitStructure.I2C_DutyCycle = I2C_DutyCycle_2; I2C_InitStructure.I2C_OwnAddress1 = 0x30;//I2Cַ,д I2C_InitStructure.I2C_Ack = I2C_Ack_Enable; I2C_InitStructure.I2C_AcknowledgedAddress = I2C_AcknowledgedAddress_7bit; I2C_InitStructure.I2C_ClockSpeed = 400000;//400K I2C_Cmd(I2C3, ENABLE); I2C_Init(I2C3, &I2C_InitStructure); } void I2C_WriteByte(uint8_t addr,uint8_t data) { while(I2C_GetFlagStatus(I2C3, I2C_FLAG_BUSY)); I2C_GenerateSTART(I2C3, ENABLE);//I2C1 while(!I2C_CheckEvent(I2C3, I2C_EVENT_MASTER_MODE_SELECT));/*EV5,ģʽ*/ I2C_Send7bitAddress(I2C3, OLED_ADDRESS, I2C_Direction_Transmitter);//ַ -- Ĭ0x78 while(!I2C_CheckEvent(I2C3, I2C_EVENT_MASTER_TRANSMITTER_MODE_SELECTED)); I2C_SendData(I2C3, addr);//Ĵַ while (!I2C_CheckEvent(I2C3, I2C_EVENT_MASTER_BYTE_TRANSMITTED)); I2C_SendData(I2C3, data);// while (!I2C_CheckEvent(I2C3, I2C_EVENT_MASTER_BYTE_TRANSMITTED)); I2C_GenerateSTOP(I2C3, ENABLE);//رI2C1 } void OLED_Send_Cmd(unsigned char I2C_Command)//д { I2C_WriteByte(0x00, I2C_Command); } void OLED_Send_Data(unsigned char I2C_Data)//д { I2C_WriteByte(0x40, I2C_Data); } void OLED_Init(void) { delay_ms(100); //ʱҪ OLED_Send_Cmd(0xAE); //display off OLED_Send_Cmd(0x20); //Set Memory Addressing Mode OLED_Send_Cmd(0x10); //00,Horizontal Addressing Mode;01,Vertical Addressing Mode;10,Page Addressing Mode (RESET);11,Invalid OLED_Send_Cmd(0xb0); //Set Page Start Address for Page Addressing Mode,0-7 OLED_Send_Cmd(0xc8); //Set COM Output Scan Direction OLED_Send_Cmd(0x00); //---set low column address OLED_Send_Cmd(0x10); //---set high column address OLED_Send_Cmd(0x40); //--set start line address OLED_Send_Cmd(0x81); //--set contrast control register OLED_Send_Cmd(0xff); //ȵ 0x00~0xff OLED_Send_Cmd(0xa1); //--set segment re-map 0 to 127 OLED_Send_Cmd(0xa6); //--set normal display OLED_Send_Cmd(0xa8); //--set multiplex ratio(1 to 64) OLED_Send_Cmd(0x3F); // OLED_Send_Cmd(0xa4); //0xa4,Output follows RAM content;0xa5,Output ignores RAM content OLED_Send_Cmd(0xd3); //-set display offset OLED_Send_Cmd(0x00); //-not offset OLED_Send_Cmd(0xd5); //--set display clock divide ratio/oscillator frequency OLED_Send_Cmd(0xf0); //--set divide ratio OLED_Send_Cmd(0xd9); //--set pre-charge period OLED_Send_Cmd(0x22); // OLED_Send_Cmd(0xda); //--set com pins hardware configuration OLED_Send_Cmd(0x12); OLED_Send_Cmd(0xdb); //--set vcomh OLED_Send_Cmd(0x20); //0x20,0.77xVcc OLED_Send_Cmd(0x8d); //--set DC-DC enable OLED_Send_Cmd(0x14); // OLED_Send_Cmd(0xaf); //--turn on oled panel OLED_Clear(); OLED_SetPos(0,0); } void OLED_SetPos(unsigned char x, unsigned char y) //ʼ { OLED_Send_Cmd(0xb0+y); OLED_Send_Cmd(((x&0xf0)>>4)|0x10); OLED_Send_Cmd((x&0x0f)|0x01); } void OLED_Clear(void)//ȫ { unsigned char m,n; for(m=0;m<8;m++) { OLED_Send_Cmd(0xb0+m); //page0-page1 OLED_Send_Cmd(0x00); //low column start address OLED_Send_Cmd(0x10); //high column start address for(n=0;n<128;n++) { OLED_Send_Data(0); } } } //-------------------------------------------------------------- // Prototype : void OLED_ON(void) // Calls : // Parameters : none // Description : OLEDл //-------------------------------------------------------------- void OLED_ON(void) { OLED_Send_Cmd(0X8D); //õɱ OLED_Send_Cmd(0X14); //ɱ OLED_Send_Cmd(0XAF); //OLED } //-------------------------------------------------------------- // Prototype : void OLED_OFF(void) // Calls : // Parameters : none // Description : OLED -- ģʽ,OLEDIJ10uA //-------------------------------------------------------------- void OLED_OFF(void) { OLED_Send_Cmd(0X8D); //õɱ OLED_Send_Cmd(0X10); //رյɱ OLED_Send_Cmd(0XAE); //OLED } void OLED_ShowChar(u8 x,u8 y,u8 ch,u8 size) { u8 i,j; u16 cnt=0; if(x>127){x=0;y+=2;} for(j=0;j<64/8;j++) //y64 8ҳ { if(size/8.0<=j*1.0)return; OLED_SetPos(x,y/8+j); for(i=0;i<size/2;i++) { if(size==12)OLED_Send_Data(ASCII_6_12[ch-' '][cnt++]); else if(size==16)OLED_Send_Data(ASCII_8_16[ch-' '][cnt++]); else if(size==24)OLED_Send_Data(ASCII_12_24[ch-' '][cnt++]); else return; } } } void OLED_ShowString(u8 x,u8 y,u8 ch[],u8 size) { u8 i=0; while(ch[i]!='\0') { OLED_ShowChar(x,y,ch[i],size); i++; x+=size/2; } } void OLED_ShowGB_Char(u8 x0,u8 y0,const char p[],u8 size) { u8 i,j,k; u16 cnt=0; for(i=0;i<GB_Num;i++) { if((p[0]==GB_1616[i].index[0])&&(p[1]==GB_1616[i].index[1])) { for(k=0;k<2;k++) { if(size/8.0<=k*1.0)return; OLED_SetPos(x0,y0/8+k); for(j=0;j<size;j++) { if(size==12) OLED_Send_Data(GB_1212[i].matrix[cnt++]); else if(size==16) OLED_Send_Data(GB_1616[i].matrix[cnt++]); else return; } } return; //ҵӦĺֲ } } } void OLED_ShowGB_String(u8 x0,u8 y0,const char *s,u8 size) { u16 i=0; while(*s!='\0') { OLED_ShowGB_Char(x0+i,y0,s,size); i+=size; s+=2; } } void OLED_ShowStr(u8 x,u8 y,const char *str,u8 size) { u8 bHz=0; //ַ while(*str!=0)//δ { if(!bHz) { if(*str>0x80)bHz=1;// else //ַ { OLED_ShowChar(x,y,*str,size);//Чд str++; x+=size/2; //ַ,Ϊȫֵһ } } else// { bHz=0;//кֿ OLED_ShowGB_Char(x,y,str,size); //ʾ,ʾ str+=2; x+=size;//һƫ } } } void OLED_ShowBMP(u8 x0,u8 y0,u8 x1,u8 y1,const u8 pic[]) { u16 i,j; u32 count=0; for(i=0;i<y1/8;i++) //h { OLED_SetPos(x0,y0+i); //ù,ʾi for(j=0;j<x1;j++) //w { OLED_Send_Data(pic[count++]); // count++; } } }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #define ROZMIAR 30 #define ROZMIAR_OWADY 17 int main() { char kwiaty[ROZMIAR]; char owady[ROZMIAR_OWADY]; char *dodatek="smierdza jak stare buty"; int wolne; puts("jakie kwiaty lubisz najbardziej?"); gets(kwiaty); if((strlen(kwiaty)+strlen(dodatek)+1)<=ROZMIAR) strcat(kwiaty,dodatek); puts(kwiaty); puts("jake owady lubisz najbardziej?."); gets(owady); wolne=ROZMIAR_OWADY-strlen(owady)-1; strncat(owady,dodatek,wolne); puts(owady); printf("Hello world!\n"); return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* move.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: tlepeche <tlepeche@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2015/03/16 06:16:06 by tlepeche #+# #+# */ /* Updated: 2015/06/02 15:40:09 by tlepeche ### ########.fr */ /* */ /* ************************************************************************** */ #include <select.h> static void move_up(char c, int *y, int *x, t_win *win) { if (c == 65) { if ((*y) == 0) { if ((*x) == 0) *x = win->max_y - 1; else *x -= 1; *y = win->i_max / win->max_y; if (*y * win->max_y + *x >= win->i_max) *y -= 1; } else *y -= 1; } } static void move_down(char c, int *y, int *x, t_win *win) { if (c == 66) { if (((*y) + 1) * win->max_y + (*x) >= win->i_max) { *y = 0; if (*x == win->max_y - 1) *x = 0; else *x += 1; } else *y += 1; } } static void move_right(char c, int *y, int *x, t_win *win) { if (c == 67) { *x += 1; if (*y * win->max_y + *x == win->i_max) { *x = 0; *y = 0; } } } static void move_left(char c, int *y, int *x, t_win *win) { if (c == 68) { if (*x == 0 && *y == 0) { *x = win->i_max % win->max_y - 1; *y = win->i_max / win->max_y; } else *x -= 1; } } void check_move(char *buf, int *y, int *x, t_win *win) { if (buf[0] == 27) { move_up(buf[2], y, x, win); move_down(buf[2], y, x, win); move_left(buf[2], y, x, win); move_right(buf[2], y, x, win); if (!buf[1] && !buf[2]) leave_term(); } }
C
#include "cub3d.h" void load_textures(t_mlx *mlx) { load_texture(mlx, mlx->n_texture, mlx->game_info->n_image); load_texture(mlx, mlx->w_texture, mlx->game_info->w_image); load_texture(mlx, mlx->s_texture, mlx->game_info->s_image); load_texture(mlx, mlx->e_texture, mlx->game_info->e_image); } int load_texture(t_mlx *mlx, t_texture *texture, char *src) { int fd; int image_width; int image_height; texture->image->image = mlx_xpm_file_to_image(mlx->mlx, src, &image_width, &image_height); texture->image->data = (int *)mlx_get_data_addr(texture->image->image, &(texture->image->bpp), &(texture->image->size_l), &(texture->image->endian)); texture->width = image_width; texture->height = image_height; return (0); } t_image *create_image(t_mlx *mlx, int width, int height) { t_image *image = (t_image *)malloc(sizeof(t_image) * 1); image->image = mlx_new_image(mlx->mlx, width, height); image->data = (int *)mlx_get_data_addr(image->image, &(image->bpp), &(image->size_l), &(image->endian)); return image; }
C
/* * @lc app=leetcode id=740 lang=c * * [740] Delete and Earn */ // @lc code=start int deleteAndEarn(int *nums, int numsSize) { int *sums = calloc(10001, sizeof(int)); for (int i = 0; i < numsSize; i++) sums[nums[i]] += nums[i]; for (int i = 2; i <= 10000; i++) sums[i] = fmax(sums[i - 1], sums[i - 2] + sums[i]); int r = sums[10000]; free(sums); return r; } // @lc code=end // Note: DP
C
#include <stdio.h> #include <string.h> struct Books { char title [50]; char author [50]; char subject [100]; int book_id; }; int main() { struct Books Book1; /*Declare Book1 of type Book*/ struct Books Book2; /*Declare book2 of type book*/ /*book 1 specs */ strcpy(Book1.title, "C programming"); strcpy(Book1.author, "Nuha Ali"); strcpy(Book1.subject, "C programming tutorial"); Book1.book_id = 6495407; /*book2 specs */ strcpy(Book2.title, "Telecom Billing"); strcpy(Book2.author, "Zara Ali"); strcpy(Book2.subject, "Telecom Billing tutorial"); Book2.book_id = 6495700; /* print Book1 info */ printf("Book 1 title: %s\n", Book1.title); printf("Book 1 author: %s\n", Book1.author); printf("Book 1 subject: %s\n", Book1.subject); printf("Book 1 book_id: %d\n", Book1.book_id); /*print book2 info */ printf("Book 2 title: %s\n", Book2.title); printf("Book 2 author: %s\n", Book2.author); printf("Book 2 subject: %s\n", Book2.subject); printf("Book 2 book_id: %d\n", Book2.book_id); return 0; }
C
#include <stdio.h> #include <string.h> #include <stdbool.h> #define LOG 18 #define MAX 100010 #define min(a,b) ((a)<(b) ? (a):(b)) #define clr(ar) memset(ar, 0, sizeof(ar)) #define read() freopen("lol.txt", "r", stdin) int n, q, lg[MAX], ar[MAX], dp[LOG][MAX]; int query(int i, int j){ int k = lg[j - i]; int x = dp[k][i], y = dp[k][j - (1 << k) + 1]; return min(x, y); } void build(){ int i, j, l, d, len; for (i = 2, lg[0] = lg[1] = 0; i < MAX; i++) lg[i] = lg[i >> 1] + 1; for (l = 0; (1 << l) <= n; l++){ len = 1 << l, d = len >> 1; for (i = 0; (i + len) <= n; i++){ if (!l) dp[l][i] = ar[i]; else dp[l][i] = min(dp[l - 1][i], dp[l - 1][i + d]); } } } int main(){ build(); }
C
// gcc -m32 level4.c -o level4 #include <stdio.h> #include <fcntl.h> #include <unistd.h> #include <stdlib.h> #define BUF_LEN 64 int denyFlag = 0; int hidden() { puts("Wow, you got it!"); system("cat ./flag.txt"); } int main(int argc, char** argv) { char buffer[BUF_LEN]; setvbuf(stdin, 0, 2, 0); setvbuf(stdout, 0, 2, 0); printf("Give me something to say!\n"); fflush(stdout); fgets(buffer, BUF_LEN, stdin); printf(buffer); exit(0); }
C
#include <stdio.h> //дij int main() { //int n, int n2, int n3; int n, n2, n3; n = 5; n2 = n * n; n3 = n2 * n2; printf("n = %d, n squared = %d, n cubed = %d\n",n, n2, n3); return 0; }
C
#include "main.h" char idle = 0; int main(int argc, char **argv) { printf("\n----------------------------------------\n"); printf("\nStarting CNC Controller\n"); printf("\nSetting Up WiringPi\n"); wiringPiSetup(); init_control_gpio(); reset_motor_state(); reset_area_state(); system_control_fork = fork(); if(system_control_fork == 0){ printf("Forked... In child process\n"); control_socket = connect_unix_socket(CONTROL_SOCKET_PATH); system_control(control_socket); exit(EXIT_SUCCESS); // should never hit this - parent kills child } else { printf("Forked... In Parent process\n"); unix_sockets[active_unix] = create_unix_socket(CONTROL_SOCKET_PATH); active_unix = active_unix + 1; while(quit_system == 0){ socket_handler(); if(command_ready){ printf("Got %s\n", system_command); control_functions(); } else { } if(calibration_running) process_calibration(); process_instruction(); process_speed(); process_motion(); process_motors(); delayMicroseconds(1); } disable_control_gpio(); kill(control_socket, SIGKILL); } return 0; } void system_control(int control_socket){ int exit_system = 0; char control_string[40]; // parent will close system control child - don't ever exit while(!exit_system){ sleep(1); print_control_menu(); scanf("%s", control_string); switch(control_string[0]) { case 's' : printf("Type String to Send and Press Enter: "); printf("\n"); scanf("%s", control_string+1); break; case 'm' : printf("Enter: \"type.xoffset.yoffset.zoffset.speed.arcradius\n"); printf("Type 0 is line, type 1 is arc. Speed is Max Speed\n"); printf("Example: \"0.1000.2000.3000.50.0\" then press enter\n"); printf("Or enter 0 to stop movement: "); printf("\n"); scanf("%s", control_string+1); break; case 'g' : printf("Type coordinates to move to and what max speed\n"); printf("X.Y.Xperiod.Yperiod\n"); printf("Example: \"x2454.y4222.50.50\" then press enter\n"); printf("Or enter c0.c0.Xper.Yper to go to Center: "); printf("\n"); scanf("%s", control_string+1); break; default : break; } send(control_socket, control_string, sizeof(control_string), 0); } } void print_control_menu(void){ printf("\n\n"); printf("<<--------------------------->>\n"); printf("<<--User Input Options------->>\n"); printf("<<--------------------------->>\n"); printf("<<--q : Shutdown and Quit---->>\n"); printf("<<--e : Enable Gpio --------->>\n"); printf("<<--d : Disable Gpio -------->>\n"); printf("<<--m : Move Axis ----------->>\n"); printf("<<--g : Go To --------------->>\n"); printf("<<--d : Calibrate Motors ---->>\n"); printf("<<--s : Send Spi String ----->>\n"); printf("<<--r : Receive Spi String -->>\n"); printf("<<--p : Print System Info --->>\n"); printf("<<--------------------------->>\n"); printf("\nType Input and Press Enter: "); }
C
#include<stdio.h> int main(void) { char str[100], ch; int i; FILE* fp; fp = fopen("E:/arnol/Documents/VisualStudio/C/ClassEG/20191122/a1.txt", "w+"); ch = getchar(); while (ch != '#') { fputc(ch, fp); ch = getchar(); } rewind(fp); fgets(str, 5, fp); puts(str); fclose(fp); return 0; }
C
/* * ISA - DHCP server * @author Marian Durco (xdurco00) */ #include "dserver.h" int parseOptions(dhcp_msg, optList*); uint32_t BROADCAST; uint32_t SERVER_IP,NET_MASK; IpPool *CLEAN_POOL = NULL; /* @function - main */ int main(int argc, char **argv) { int socket; signal(SIGINT,signalHandler); arguments program_arg; if(processProgramParam(argc,argv,&program_arg)!=OK) { reportErr("Error in program arguments"); return EXIT_FAILURE; } IpPool iplist; CLEAN_POOL = &iplist; if(initDhcpPool(&iplist,program_arg)!=OK) { reportErr("Error in initializin dhcp pool"); return EXIT_FAILURE; } if(setServerIP(&iplist,&SERVER_IP)!=OK) { reportErr("Error in setting IP for server"); deletePool(&iplist); return EXIT_FAILURE; } char server_ip[32]; inet_ntop(AF_INET,&SERVER_IP,server_ip,32); char brod[32]; inet_ntop(AF_INET,&BROADCAST,brod,32); if((setUpConnectivity(&socket)) != OK) { reportErr("setUpConnectivity Err, check if you run it as root"); return EXIT_FAILURE; } if(communicate(socket,&iplist) != OK) { reportErr("communicate Errl!"); return EXIT_FAILURE; } deletePool(&iplist); return EXIT_SUCCESS; } /* * @function for handling SIGINT * @signal - signal ID */ void signalHandler(int signal) { if(CLEAN_POOL!=NULL) deletePool(CLEAN_POOL); exit(signal); } /* * @function print out the error message to stderr * @mesg - the message */ void reportErr(char *mesg) { fprintf(stderr,"%s\n",mesg); } /* @function controls the program arugment and also fill the argument structure with data * @argc - num of program arguments * @argv - the program arguments * @*arg - pointer to arumnents structure */ int processProgramParam(int argc,char *argv[],arguments *arg) { memset(arg,0,sizeof(arguments)); if (argc<MINARGUMENT) { reportErr("Not enough arguments!"); return ERRARG; } if (strcmp(argv[1],"-p")!=0) { reportErr("Wrong program arguments!"); return ERRARG; } else { char *ip,*bitmask; ip = strtok(argv[2], "/"); bitmask = strtok(NULL, "\0"); if(!ip || !bitmask) { reportErr("Wrong program arguments!"); return ERRARG; } if(!isValidIpAddress(ip) || !isValidMask(bitmask)) { reportErr("The Ip address of the pool or mask is wrong"); return ERRARG; } uint32_t input_ip; inet_pton(AF_INET,ip,&input_ip); uint32_t bitmask_to_int = ntohl(createBitmask(bitmask)); char input_ip_str[32]; inet_ntop(AF_INET,&input_ip,input_ip_str,32); char bitmask_str[32]; inet_ntop(AF_INET,&bitmask_to_int,bitmask_str,32); uint32_t network_int = (input_ip & bitmask_to_int); uint32_t broadcast_addr = (input_ip | ~bitmask_to_int); arg->network_addr=ntohl(network_int); arg->broadcast_addr=ntohl(broadcast_addr); arg->network_mask=ntohl(bitmask_to_int); NET_MASK=ntohl(bitmask_to_int); BROADCAST = broadcast_addr; } if(argc>MINARGUMENT) { if ((strcmp(argv[3],"-e")!=0) || argc!=MINARGUMENT+2) // +2 -> -e and excluded addresses { reportErr("Wrong program arguments!"); return ERRARG; } else { char **arr = NULL; int pieces = split(argv[4],',',&arr); if(pieces<0) { reportErr("Wrong excluded IP"); return ERRIP; } arg->ex_len = pieces; int flag=OK; for (int i=0;i<pieces;i++) { uint32_t excluded_ip; if(!isValidIpAddress(arr[i])) flag=ERRIP; inet_pton(AF_INET,arr[i],&excluded_ip); arg->excluded_addr[i]=ntohl(excluded_ip); free(arr[i]); } free(arr); if(flag==ERRIP) { reportErr("Wrong excluded IP"); return ERRIP; } } } return OK; } /* * @function create socket and needed strctures for server * @socket - the opened server socket */ int setUpConnectivity(int *socket_func) { int server_socket; struct sockaddr_in server_address; struct protoent *proto; struct servent *name; if ((name = getservbyname("bootps","udp")) == 0) { reportErr("getservbyname Err!"); return ERRCONNECT; } if ((proto = getprotobyname("udp")) == 0) { reportErr("getprotobyname Err!"); return ERRCONNECT; } /* create socket */ if ((server_socket = socket(AF_INET, SOCK_DGRAM, proto->p_proto)) <= 0) return ERRCONNECT; int enable = 1; if(setsockopt(server_socket, SOL_SOCKET, SO_REUSEADDR, (const void *)&enable , sizeof(int))!=OK) { reportErr("err in setting SO_REUSEADDR socket option"); return ERRCONNECT; } enable = 1; if(setsockopt(server_socket, SOL_SOCKET, SO_BROADCAST, (const void *)&enable , sizeof(int))!=OK) { reportErr("err in setting SO_BROADCAST socket option"); return ERRCONNECT; } bzero((char *) &server_address, sizeof(server_address)); server_address.sin_family = AF_INET; server_address.sin_addr.s_addr = htonl(INADDR_ANY); server_address.sin_port = name->s_port; if (bind(server_socket, (struct sockaddr *) &server_address, sizeof(server_address)) < 0) return ERRCONNECT; printf("Listening on port: %d\n",ntohs(server_address.sin_port)); *socket_func = server_socket; return OK; } /* @function create connectible dhcp server, recive mesg from clients and sent them response * @socket the opened socket * @ip_pool pointer on ip pool */ int communicate(int server_socket,IpPool *ip_pool) { while(1) { struct sockaddr_in client_socket; socklen_t client_socket_len=sizeof(client_socket); size_t msg_len; msg_len = msg_len; dhcp_msg client_msg; msg_len = recvfrom(server_socket, &client_msg, sizeof(client_msg), 0, (struct sockaddr *) &client_socket, &client_socket_len); checkIntegrityOfPool(ip_pool); optList parsedOptions; initOptList(&parsedOptions); if(parseOptions(client_msg,&parsedOptions)!=OK) return ERRQUEUE; /*printList(&parsedOptions);*/ dhcpOption message_type = searchOption(&parsedOptions,DHCP_MESSAGE_TYPE); if(message_type==NULL) return ERROPT; dhcp_msg server_msg; // response of server optList replyOptions; initOptList(&replyOptions); int nak = 0; int send_flag=OK; bool renew = false; switch(message_type->data[0]) { case DHCPDISCOVER: if(discoverHandler(&server_msg,&client_msg,&replyOptions,ip_pool)!=OK) { send_flag=-1; printf("No more avaiable IP addresses in the pool\n"); } break; case DHCPREQUEST: ; uint32_t offered_ip = 0; if( (checkRequestedIp(&parsedOptions)) == OK ) { if(checkServerId(&parsedOptions,SERVER_IP)!=OK) { send_flag=-1; break; } if(checkRequestIpFromClient(&client_msg,&parsedOptions,ip_pool,&offered_ip)!=OK) nak=1; } else // it's renew { renew = true; offered_ip = client_msg.ciaddr; } requestHandler(&client_msg,&server_msg,&replyOptions,ip_pool,nak,offered_ip); break; case DHCPRELEASE: send_flag=-1; if(checkServerId(&parsedOptions,SERVER_IP)!=OK) break; releaseHandler(&client_msg,ip_pool); break; default: deleteList(&parsedOptions); deleteList(&replyOptions); send_flag=-1; } int ret_send; if(send_flag==OK) ret_send = sendReply(server_socket,&client_socket,&server_msg,renew); else ret_send=OK; nak=0; deleteList(&replyOptions); deleteList(&parsedOptions); if (ret_send!=OK) return ERRCONNECT; } return OK; } /* *@function send reply of dhcp server *@server_socket fd of socket *@client_socket structure of client dest port etc.. *@server_msg structure of server dest port etc.. *@renew if reply is renew(unicast) */ int sendReply(int server_socket,struct sockaddr_in *client_socket,dhcp_msg *server_msg,bool renew) { int data; if(!renew) // if it is renew it should be send as unicast { client_socket->sin_family = AF_INET; client_socket->sin_port = htons(BOOTPC); client_socket->sin_addr.s_addr = BROADCAST; } data = sendto(server_socket,server_msg,SIZEOFMSG,0,(struct sockaddr *)client_socket,sizeof(*client_socket)); if(data<0) return ERRCONNECT; return OK; } /* *@function parse dhcp option from received packet and fill the structure with them *@message parsed message *@list_options pointer on structure which will store options */ int parseOptions(dhcp_msg message, optList* list_options) { bool was_id = false; bool was_len = false; int data_counter = 0; struct dhcp_option parsed_option; for(int i=4;i<251;i++) // zacinam od 4 lebo preskakujem magic cookie { if(message.options[i]==255 && !was_id && !was_len) // END break; if(message.options[i]==0 && !was_id && !was_len) // PAD continue; if(!was_id) { // was_id == false parsed_option.id = message.options[i]; was_id = true; } else if(!was_len) { // was_len == false parsed_option.len = message.options[i]; was_len = true; } else { // now it's data parsed_option.data[data_counter]=message.options[i]; data_counter++; if(data_counter==parsed_option.len) { if(addOpt(list_options,TAIL,&parsed_option)!=OK) return ERRQUEUE; was_id = false; was_len = false; data_counter=0; memset(&parsed_option,0,sizeof(struct dhcp_option)); } } } return OK; } /* *@function handler for discover message prepare packet for sending *@dhcp_offer dhcp offer message *@dhcp_discover dhcp discover message *@replyOptions structure of options from discover *@ip_pool pointer on ip pool */ int discoverHandler(dhcp_msg *dhcp_offer,dhcp_msg *dhcp_discover, optList *replyOptions, IpPool *ip_pool) { prepReply(dhcp_offer,dhcp_discover); uint32_t offered_ip; if(getIpForOffer(ip_pool,&offered_ip,dhcp_discover->chaddr)!=OK) return ERRIP; dhcp_offer->yiaddr = offered_ip; dhcp_offer->siaddr = SERVER_IP; fillOptions(replyOptions,dhcp_offer, DHCPOFFER,SERVER_IP,NET_MASK); return OK; } /* *@function handler for request message prepare packet for sending *@dhcp_request dhcp request message *@dhcp_ack_nak dhcp ack or nak message *@replyOptions structure of options from discover *@ip_pool pointer on ip pool *@nak if the reply will be nak *@requested_ip the ip for assignment */ int requestHandler(dhcp_msg *dhcp_request,dhcp_msg *dhcp_ack_nak, optList *replyOptions, IpPool *ip_pool,int nak,uint32_t requested_ip) { prepReply(dhcp_ack_nak,dhcp_request); if(nak!=1) { // ACK dhcp_ack_nak->yiaddr = requested_ip; dhcp_ack_nak->siaddr = SERVER_IP; setForAck(ip_pool,requested_ip); fillOptions(replyOptions,dhcp_ack_nak,DHCPACK,SERVER_IP,NET_MASK); dhcpOutput(ip_pool,requested_ip); } else { // NAK fillOptions(replyOptions,dhcp_ack_nak,DHCPNAK,SERVER_IP,NET_MASK); } return OK; } /* *@function handling release message *@release_msg dhcp release message *@ip_pool pointer on ip pool */ int releaseHandler(dhcp_msg *release_msg, IpPool *ip_pool) { if(releaseAddress(ip_pool,release_msg->chaddr)!=OK) return ERRIP; return OK; } /* *@function prepare packet based on received message *@server_msg message to be sent *@client_msg message from client */ void prepReply(dhcp_msg *server_msg,dhcp_msg* client_msg) { memset(server_msg,0,sizeof(struct dhcp_msg)); server_msg->op = REPLY; server_msg->xid = client_msg->xid; server_msg->flags = client_msg->flags; server_msg->giaddr = client_msg->giaddr; memcpy(server_msg->chaddr,client_msg->chaddr,16); server_msg->htype = client_msg->htype; server_msg->hlen = client_msg->hlen; } /* *@function print out information about succesful binded ip *@ip_pool pointer on ip pool *@requested_ip the ip for assignment */ void dhcpOutput(IpPool *ip_pool,uint32_t requested_ip) { Ip ip_structure = searchIp(ip_pool,requested_ip); printf("%.2x:%.2x:%.2x:%.2x:%.2x:%.2x ",ip_structure->mac[0],ip_structure->mac[1],ip_structure->mac[2], ip_structure->mac[3],ip_structure->mac[4],ip_structure->mac[5]); char ip[32]; inet_ntop(AF_INET,&ip_structure->address,ip,32); printf("%s ",ip); char time_buff[40]; struct tm *timeinfo = NULL; time_t from = ip_structure->active_until-LEASETIMER; timeinfo = localtime(&from); strftime(time_buff , 40 , "%Y-%m-%d_%H:%M",timeinfo); printf("%s ",time_buff); timeinfo = localtime((&ip_structure->active_until)); strftime(time_buff , 40 , "%Y-%m-%d_%H:%M",timeinfo); printf("%s\n",time_buff); }
C
int main( void ) { /* Testing all the basic I/O functions individually would result in lots of duplicated code, so I took the liberty of lumping it all together here. */ /* The following functions delegate their tests to here: fgetc fflush rewind fputc ungetc fseek flushbuffer seek fillbuffer prepread prepwrite */ char * buffer = (char*)malloc( 4 ); FILE * fh; TESTCASE( ( fh = tmpfile() ) != NULL ); TESTCASE( setvbuf( fh, buffer, _IOLBF, 4 ) == 0 ); /* Testing ungetc() at offset 0 */ rewind( fh ); TESTCASE( ungetc( 'x', fh ) == 'x' ); TESTCASE( ftell( fh ) == -1l ); rewind( fh ); TESTCASE( ftell( fh ) == 0l ); /* Commence "normal" tests */ TESTCASE( fputc( '1', fh ) == '1' ); TESTCASE( fputc( '2', fh ) == '2' ); TESTCASE( fputc( '3', fh ) == '3' ); /* Positions incrementing as expected? */ TESTCASE( ftell( fh ) == 3l ); TESTCASE_NOREG( fh->pos.offset == 0l ); TESTCASE_NOREG( fh->bufidx == 3l ); /* Buffer properly flushed when full? */ TESTCASE( fputc( '4', fh ) == '4' ); TESTCASE_NOREG( fh->pos.offset == 4l ); TESTCASE_NOREG( fh->bufidx == 0 ); /* fflush() resetting positions as expected? */ TESTCASE( fputc( '5', fh ) == '5' ); TESTCASE( fflush( fh ) == 0 ); TESTCASE( ftell( fh ) == 5l ); TESTCASE_NOREG( fh->pos.offset == 5l ); TESTCASE_NOREG( fh->bufidx == 0l ); /* rewind() resetting positions as expected? */ rewind( fh ); TESTCASE( ftell( fh ) == 0l ); TESTCASE_NOREG( fh->pos.offset == 0 ); TESTCASE_NOREG( fh->bufidx == 0 ); /* Reading back first character after rewind for basic read check */ TESTCASE( fgetc( fh ) == '1' ); /* TODO: t.b.c. */ TESTCASE( fclose( fh ) == 0 ); return TEST_RESULTS; }
C
// vd sap xep diem cua sv ss12 #include<stdio.h> int main() { int n; int num[100]; int l; int desnum[100], k; int i, j, temp; printf("Enter the total number of marks to be entered: "); scanf("%d", &n); system("cls"); for(l = 0; l < n; l++) { printf("\nEnter the marks of student %d: ", l+1); scanf("%d", &num[l]); } for(k = 0; k < n; k++) desnum[k] = num[k]; for(i = 0; i < n-1; i++) { for(j = i + 1; j < n; j++) { if(desnum[i] < desnum[j]) { temp = desnum[i]; desnum[i] = desnum[j]; desnum[j] = temp; } } } for(i = 0; i < n; i++) printf("\n Number at [%d] is %d", i, desnum[i]); return 0; }
C
// to find out sqrt // https://github.com/w3cp #include <stdio.h> double mysqrt(double num); // to return the sqrt of its parameter int main() { double x; scanf("%lf", &x); printf("%0.2lf\n", mysqrt(x) ); return 0; } // end main // returns the sqrt of its parameter double mysqrt(double number) { double low, high, mid; low = 0.0; high = number; while (high - low > 0.000000001) { mid = (low + high) / 2; if (mid * mid > number) high = mid; else low = mid; } return mid; } // end mysqrt
C
/*Задача 7. Напишете масив от структури наречен kaytab[ ], като използвате тази, дефинирана в горното упражнение - потребителски тип key_t, която съдържа символен низ и число. Инициализирайте масива с всички ключови думи на С */ #include <stdio.h> typedef struct My { char str[16]; int number; } key_t; int main(void) { key_t keytab[32] = { {"void", 1}, {"struct", 2}, {"main", 3}, {"auto", 4}, {"bool", 5}, {"break", 6}, {"char", 7}, {"const", 8}, {"continue", 9}, {"do", 10}, {"default", 11}, {"double", 12}, {"else", 13}, {"enum", 14}, {"extern", 15}, {"float", 16}, {"for", 17}, {"goto", 18}, {"if", 19}, {"inline", 20}, {"int", 22}, {"long", 23}, {"register", 24}, {"sizeof", 25}, {"static", 26}, {"switch", 27}, {"typedef", 28}, {"union", 29}, {"void", 30}, {"while", 31}, {"unsigned", 32}, }; return 0; }
C
/*#include <stdio.h> #define SIZE 10000 typedef struct { int Xtopleft; int Ytopleft; int anchura; int altura; }Rectangle; int IntersectRectangles(Rectangle firstRectangle, Rectangle secondRectangle, Rectangle* resultRectangle) { //printf("\n%d %d %d %d", firstRectangle.Xtopleft, firstRectangle.Ytopleft, firstRectangle.anchura, firstRectangle.altura); //printf("\n%d %d %d %d", secondRectangle.Xtopleft, secondRectangle.Ytopleft, secondRectangle.anchura, secondRectangle.altura); if (firstRectangle.Xtopleft <= secondRectangle.Xtopleft) { resultRectangle->Xtopleft = firstRectangle.Xtopleft; } else { resultRectangle->Xtopleft = secondRectangle.Xtopleft; } if (firstRectangle.Ytopleft <= secondRectangle.Ytopleft) { resultRectangle->Ytopleft = firstRectangle.Ytopleft; } else { resultRectangle->Ytopleft = secondRectangle.Ytopleft; } if ((firstRectangle.Xtopleft+firstRectangle.anchura) <= (secondRectangle.Xtopleft+secondRectangle.anchura)) { resultRectangle->anchura = (secondRectangle.Xtopleft + secondRectangle.anchura-firstRectangle.Xtopleft); } else { resultRectangle->anchura = (firstRectangle.Xtopleft + firstRectangle.anchura-secondRectangle.Xtopleft); } if ((firstRectangle.Ytopleft + firstRectangle.altura) <= (secondRectangle.Ytopleft + secondRectangle.altura)) { resultRectangle->altura = (secondRectangle.Ytopleft + secondRectangle.altura-firstRectangle.Ytopleft); } else { resultRectangle->altura = (firstRectangle.Ytopleft + firstRectangle.altura-secondRectangle.Ytopleft); } printf("\n%d", resultRectangle->Xtopleft); printf("\n%d", resultRectangle->Ytopleft); printf("\n%d", resultRectangle->anchura); printf("\n%d", resultRectangle->altura); return 0; } int main(void) { int Xtopleft = 0; scanf("%ld", &Xtopleft); int Ytopleft = 0; scanf("%ld", &Ytopleft); int Anchura = 0; scanf("%ld", &Anchura); int Altura = 0; scanf("%ld", &Altura); Rectangle firstRectangle = { Xtopleft, Ytopleft, Anchura, Altura }; scanf("%ld", &Xtopleft); scanf("%ld", &Ytopleft); scanf("%ld", &Anchura); scanf("%ld", &Altura); Rectangle secondRectangle = { Xtopleft, Ytopleft, Anchura, Altura }; Rectangle resultRectangle = { 0, 0, 0, 0 }; IntersectRectangles(firstRectangle, secondRectangle, &resultRectangle); }*/
C
/* Escribir un programa cunha función que teña unha cadea de caracteres como parámetro formal, que elimine espazos extra entre palabras desa cadea, e devolva o número de espazos eliminados. A frase modificada, así como o número de cambios feitos téñense que impirmir dende main(), non dentro da función que fai os cambios. */ #include <stdlib.h> #include <stdio.h> int compactar(char f[]) { int i, j; // i es el índice actual de la cadena y j es el índice de lo que vamos moviendo int e = 0; // e es el número de veces que compactamos j = 0; for (i = 0; f[i] != '\0'; i++) // vamos recorriendo la cadena { while (f[i] == ' ' && f[i + 1] == ' ') { // cuando tenemos dos espacios... e += 1; // incrementamos el número de errores // vamos a compactar la cadena for (j = i + 1; f[j] != '\0'; j++) { f[j] = f[j + 1]; } } } return e; } int main() { char frase[100]; int num_espacios; printf("introduce unha frase:"); gets(frase); num_espacios = compactar(frase); printf("frase corregida: \"%s\", numero de espacios %d\n", frase, num_espacios); return 0; }
C
#include <time.h> #include <stdio.h> #include <SDL/SDL.h> #include <SDL/SDL_image.h> #include <SDL/SDL_mixer.h> #include "perso.h" #define HAUT 0 #define DROITE 1 #define BAS 2 #define GAUCHE 3 #define AUCUNE_DIRECTION 0 #define DIRECTION_HAUT 1 #define DIRECTION_DROITE 2 #define DIRECTION_BAS 4 #define DIRECTION_GAUCHE 8 #define LARGEUR_ECRAN 500 #define HAUTEUR_ECRAN 480 int main() { SDL_Surface *ecran; SDL_Event event; int continuer = 0; Uint32 temps_courant, prochain_rendu = 0; Sprite Perso,Perso1; int changement_direction1; if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER) < 0) { fprintf(stderr, "Echec d'initialisation de SDL.\n"); return 1; } ecran = SDL_SetVideoMode(1000, 600, 32, SDL_HWSURFACE | SDL_DOUBLEBUF); printf ("init secene"); if ( ecran == NULL ) { fprintf(stderr, "Echec de changement du mode video : %s.\n", SDL_GetError()); return 1; } if ( !Inistialiser_Perso( &Perso, "perso.bmp" ) ) { SDL_Quit(); return 1; } if ( !Inistialiser_Perso( &Perso1, "perso.bmp" ) ) { SDL_Quit(); return 1; } //PLAYER Perso.dest.x = 304; Perso.dest.y = 260; Direction_Perso( &Perso, DIRECTION_BAS ); Direction_Perso( &Perso, AUCUNE_DIRECTION ); //PLAYER1 Perso1.dest.x = 304; Perso1.dest.y = 260; Direction_Perso( &Perso1, DIRECTION_BAS ); Direction_Perso( &Perso1, AUCUNE_DIRECTION ); while (!continuer) { while (SDL_PollEvent(&event)) { switch (event.type) { case SDL_KEYDOWN: switch (event.key.keysym.sym) { case SDLK_ESCAPE: continuer = 1; break; case SDLK_UP: Direction_Perso( &Perso, DIRECTION_HAUT ); break; case SDLK_RIGHT: Direction_Perso( &Perso, DIRECTION_DROITE ); break; case SDLK_DOWN: Direction_Perso( &Perso, DIRECTION_BAS ); break; case SDLK_LEFT: Direction_Perso( &Perso, DIRECTION_GAUCHE ); break; } break; case SDL_KEYUP: switch (event.key.keysym.sym) { case SDLK_UP: if (Perso.direction == DIRECTION_HAUT) Direction_Perso( &Perso, AUCUNE_DIRECTION ); break; case SDLK_RIGHT: if (Perso.direction == DIRECTION_DROITE) Direction_Perso( &Perso, AUCUNE_DIRECTION ); break; case SDLK_DOWN: if (Perso.direction == DIRECTION_BAS) Direction_Perso( &Perso, AUCUNE_DIRECTION ); break; case SDLK_LEFT: if (Perso.direction == DIRECTION_GAUCHE) Direction_Perso( &Perso, AUCUNE_DIRECTION ); break; } break; case SDL_QUIT: continuer = 1; break; default: ; } } /* On recupère le temps écoulé en mili-secondes */ temps_courant = SDL_GetTicks(); /* On regarde s'il est temps d'effectuer le prochain rendu */ if (temps_courant > prochain_rendu) { /* un rendu toutes les 20 milli-secondes = 50 images par secondes */ prochain_rendu = temps_courant + 20; // d'abords les directions du sprite de l'Ennemie miseAJourSprite( &Perso1); miseAJourSprite( &Perso); SDL_FillRect(ecran, NULL, 0); Afficher_Perso( &Perso, ecran ); Afficher_Perso( &Perso1, ecran ); /* On met à jour de la zone d'affichage de la fenetre */ SDL_UpdateRect(ecran, 0, 0, 0, 0); } } Supprimer_Perso( &Perso ); Supprimer_Perso( &Perso1 ); SDL_Quit(); return 0; }
C
#include <wiringPiI2C.h> #include <stdio.h> #include <stdbool.h> #include <wiringPi.h> int main (void) { int handle = wiringPiI2CSetup(0x5c); wiringPiI2CWrite(handle, 0x10); while (true) { int word = wiringPiI2CReadReg16(handle, 0x00); int lux = ((word & 0xff00) >> 8) | ((word & 0x00ff) << 8); printf("Current light intensity in Lux: %d \n", lux); delay(2000); } return 0; }
C
#include <errno.h> #include <unistd.h> #include "task.h" #include "log.h" #include "event_svc.h" int tasks_alive = 0; int task_rd_new(task_t *task, size_t count) { task_rd_set(task, resource_desc_new(count)); return 0; } void task_rd_set(task_t *task, res_desc_t *desc) { ASSERT(!task->task_rd); task->task_rd = desc; task->task_rd->rd_cb_data = task; } void task_rd_release(task_t *task) { ASSERT(task->task_rd); resource_desc_release(task->task_rd); } void task_rd_done(task_t *task) { task_rd_release(task); resource_desc_done(task->task_rd); task->task_rd = NULL; } void task_rd_set_type(task_t *task, int slot, enum resource_type type) { ASSERT(!task->task_rd->rd_allocated); ASSERT(slot < task->task_rd->rd_count); task->task_rd->rd_type_list[slot] = type; } void *task_rd_get_data(task_t *task, int slot) { ASSERT(task->task_rd->rd_allocated); ASSERT(slot < task->task_rd->rd_count); return task->task_rd->rd_data_list[slot]; } static void task_run_cb(task_t *task) { assert(task->task_cb); task->task_cb(task); tasks_alive--; log("task_run_cb %p: after cb [alive=%d]", task, tasks_alive); } void task_resource_done(struct resource_descriptor *desc) { task_t *task = desc->rd_cb_data; task->task_resource_done_count++; log("task_resource_done %p: done %zu total %zu | %s", task, task->task_resource_done_count, desc->rd_count, (task->task_resource_done_count == desc->rd_count) ? "running cb" : "waiting"); if (task->task_resource_done_count == desc->rd_count) { task->task_resource_done_count = 0; task_run_cb(task); } } void task_resource_allocated(struct resource_descriptor *desc) { task_t *task = desc->rd_cb_data; log("task_resource_allocated %p: running cb", task); task_run_cb(task); } static void task_rd_submit(task_t *task) { ASSERT(task->task_rd); if (task->task_state == TS_FILLING) { ASSERT(task->task_rd->rd_allocated); task->task_rd->rd_cb = task_resource_done; task->task_state = TS_SUBMITTED; log("task_rd_submit %p -> SUBMITTED", task); } else { if (task->task_rd->rd_allocated) { log("task_rd_submit %p releasing resources", task); resource_desc_release(task->task_rd); } task->task_rd->rd_cb = task_resource_allocated; task->task_state = TS_FILLING; log("task_rd_submit %p -> FILLING", task); } resource_desc_submit(task->task_rd); } void task_submit(task_t *task, task_cb_t next) { log("task_submit %p [alive=%d]", task, tasks_alive); tasks_alive++; task->task_cb = next; if (task->task_rd) { task_rd_submit(task); } else { log("Not sure what to do with task with no resources"); ASSERT(false); } } static void task_sleep() { static uint8_t i = 0; i++; if (i & 7) { usleep(200); } else { event_svc_wait(); } } void task_loop_watch(int *tasks_alive_ptr) { while (*tasks_alive_ptr) { if (!resource_poll()) { task_sleep(); } } } void task_loop() { task_loop_watch(&tasks_alive); } void task_get_one(desc_cb_t cb, void *cb_data) { resource_get_one(RT_TASK, cb, cb_data); } void task_init(size_t count, desc_cb_t cb) { resource_pool_init(); res_desc_t *desc = resource_desc_new(count); for (int i = 0; i < count; i++) { desc->rd_type_list[i] = RT_TASK; } desc->rd_cb = cb; resource_desc_submit(desc); resource_poll(); log("running task_loop"); task_loop(); resource_desc_done(desc); resource_pool_fini(); }
C
// // This code was cribbed from "The ZeroMQ Guide - for C Developers" -- Example 2.7 Weather Update proxy // // #define _GNU_SOURCE //#include <unistd.h> // #include <stdlib.h> #include <signal.h> #include <uuid/uuid.h> #include <string.h> #include <zmq.h> #include "common.h" void sighandler(int unused) { } int main (int argc, char** argv) { // create uuid uuid_t temp; uuid_generate(temp); char theUuid[UUID_STRING_SIZE+ 1]; uuid_unparse(temp, theUuid); void* theContext = zmq_ctx_new (); // bind sub and get endpoint void* frontend = zmq_socket(theContext, ZMQ_XSUB); zmq_bind (frontend, "tcp://127.0.0.1:*"); char subEndpoint[ZMQ_MAX_ENDPOINT_LENGTH +1]; size_t nameSize = sizeof(subEndpoint); zmq_getsockopt(frontend, ZMQ_LAST_ENDPOINT, subEndpoint, &nameSize); // bind pub to well-known address void* backend = zmq_socket(theContext, ZMQ_XPUB); // set welcome msg to be delivered when sub connects connectMsg welcomeMsg; welcomeMsg.command = 'W'; strcpy(welcomeMsg.uuid, theUuid); strcpy(welcomeMsg.endpoint, subEndpoint); zmq_setsockopt(backend, ZMQ_XPUB_WELCOME_MSG, &welcomeMsg, sizeof(welcomeMsg)); // bind the backend socket to pub endpoint zmq_bind(backend, "tcp://127.0.0.1:5555"); // Run the proxy until the user interrupts us signal(SIGINT, &sighandler); zmq_proxy(frontend, backend, NULL); zmq_close(frontend); zmq_close(backend); zmq_ctx_destroy(theContext); return 0; }
C
#include <stdio.h> #include <stdlib.h> int main (void) { int i, *a; a = malloc (sizeof (int) * 5); if (a == NULL) { printf ("No s'ha pogut reservar memòria\n"); exit (1); } printf ("Comenza a zeros\n"); for (i = 100; i < 200; i++) a[i] = 0; free (a); return 0; }
C
/* * CMSC 212, Spring 2010, Project #1 * Secret test 07 (secret07.c) * * Tests shift_program()'s return value for values for start that are * invalid (too large). */ #include <stdio.h> #include "machine.h" #define EMP -1 #define SZ 128 int main() { Word mem[SZ]; int ret= 0; ret= ret || shift_program(mem, SZ, 1, 10); ret= ret || shift_program(mem, SZ + 1, 1, 10); ret= ret || shift_program(mem, SZ + 2, 1, 10); if (ret != 0) printf("An invalid shift_program() call didn't return 0 as expected.\n"); else printf("All invalid shift_program() calls returned 0 as expected.\n"); return 0; }
C
#include <stdio.h> #include <gmp.h> int main() { mpz_t result; mpz_init(result); mpz_fac_ui(result, 100); char result_str[200]; mpz_get_str(result_str, 10, result); mpz_clear(result); int sum_of_digits = 0; for (int i = 0; result_str[i] != '\0'; i++) { sum_of_digits += result_str[i] - '0'; } printf("%i\n", sum_of_digits); }
C
/** * @file * @brief * * @author Anton Kozlov * @date 26.05.2014 */ #include <kernel/panic.h> #include <kernel/sched/sched_lock.h> #include <hal/ptrace.h> #include <mem/page.h> #include <mem/phymem.h> #include <mem/sysmalloc.h> #include "fork_copy_addr_space.h" #include <kernel/task/resource/task_fork.h> #include <kernel/thread/thread_stack.h> static void *fork_child_trampoline(void *arg) { struct addr_space *adrspc; struct thread *par_t, *cur_t; adrspc = fork_addr_space_get(task_self()); par_t = adrspc->parent_thread; cur_t = thread_self(); /* Set stack to parent thread stack */ thread_stack_set(cur_t, thread_stack_get(par_t)); thread_stack_set_size(cur_t, thread_stack_get_size(par_t)); fork_stack_store(adrspc); ptregs_retcode_jmp(&adrspc->pt_entry, 0); panic("%s returning", __func__); } void __attribute__((noreturn)) fork_body(struct pt_regs *ptregs) { struct addr_space *adrspc; struct addr_space *child_adrspc; struct task *parent; pid_t child_pid; struct task *child; assert(ptregs); parent = task_self(); assert(parent); child_pid = task_prepare(""); if (0 > child_pid) { /* error */ ptregs_retcode_err_jmp(ptregs, -1, child_pid); panic("%s returning", __func__); } adrspc = fork_addr_space_get(parent); if (!adrspc) { adrspc = fork_addr_space_create(NULL); fork_addr_space_set(parent, adrspc); } /* Save the stack of the current thread */ fork_stack_store(adrspc); child_adrspc = fork_addr_space_create(adrspc); fork_addr_space_store(child_adrspc); memcpy(&child_adrspc->pt_entry, ptregs, sizeof(*ptregs)); sched_lock(); { child = task_table_get(child_pid); task_start(child, fork_child_trampoline, NULL); fork_addr_space_set(child, child_adrspc); } sched_unlock(); ptregs_retcode_jmp(ptregs, child_pid); panic("%s returning", __func__); }
C
#include <stdio.h> #include <stdlib.h> #include <fcntl.h> #include <string.h> #define NEW_CHAR_DIR "/dev/button_driver" #define UP 0 #define DOWN 1 #define LEFT 2 #define RIGHT 3 #define PRESS 4 #define NUM_BUTTONS 5 int main(void) { int press = 0; int fd; int write_buf[NUM_BUTTONS]; printf("Pre-open\n"); fd = open(NEW_CHAR_DIR, O_RDWR); printf("Post-open\n"); if (fd < 0) { printf("File %s cannot be opened\n", NEW_CHAR_DIR); exit(1); } printf("Open successful\n"); while (!press) { //printf("Attempting to read\n"); //printf("%d\n", NUM_BUTTONS * sizeof(int)); read(fd, write_buf, NUM_BUTTONS * sizeof(int)); //printf("Exited from read\n"); int i; for (i = 0; i < NUM_BUTTONS; i++) { printf("%d ", write_buf[i]); } printf("\n"); if (write_buf[PRESS]) { press = 1; printf("PRESS\n"); } else if (write_buf[UP]) { printf("UP\n"); } else if (write_buf[DOWN]) { printf("DOWN\n"); } else if (write_buf[LEFT]) { printf("LEFT\n"); } else if (write_buf[RIGHT]) { printf("RIGHT\n"); } } close(fd); return 0; }
C
/* * de volgende code laat het ledje op de gamepad rondspinnen: * 045e:028e Microsoft Corp. Xbox360 Controller */ #include <libusb-1.0/libusb.h> #include <stdio.h> #include <unistd.h> // for sleep() int main(int argc, char *argv[]) { libusb_device_handle *h; unsigned char data[] = { 1, 3, 0x0a }; unsigned char rumbleMax[] = { 0x00, 0x08, 0x00, 0xff, 0xff, 0x00, 0x00, 0x00 }; unsigned char rumbleOff[] = { 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; int error, transferred; libusb_init(NULL); h = libusb_open_device_with_vid_pid(NULL, 0x045e, 0x028e); if (h == NULL) { fprintf(stderr, "Failed to open device\n"); return (1); } if ((error = libusb_interrupt_transfer(h, 0x02, data, sizeof data, &transferred, 0)) != 0) { fprintf(stderr, "Transfer blink failed: %d\n", error); return (1); } if ((error = libusb_interrupt_transfer(h, 0x02, rumbleMax, sizeof rumbleMax, &transferred, 0)) != 0) { fprintf(stderr, "Transfer rumble max failed: %d\n", error); return (1); } sleep(1); if ((error = libusb_interrupt_transfer(h, 0x02, rumbleOff, sizeof rumbleOff, &transferred, 0)) != 0) { fprintf(stderr, "Transfer rumble off failed: %d\n", error); return (1); } return (0); }
C
/************************************************************************* > File Name: game.c > Author: narutolby > Mail:willianlby@yahoo.cn > Created Time: 2013年03月26日 星期二 14时35分46秒 ************************************************************************/ #include<stdio.h> int main(){ int T,N,j; scanf("%d",&T); for(j=0;j<T;j++){ scanf("%d",&N); printf("Case #%d: %s\n",j+1,"Alice"); } return 0; }
C
#include <stdbool.h> #include <malloc.h> #include <stdio.h> #include <seq_list.h> void init_seq_list(SeqList* sl) { sl->nElem = 0; } void reinit_seq_list(SeqList* sl) { sl->nElem = 0; } int size(SeqList* sl) { return sl->nElem; } int seq_search(SeqList* sl, Key key) { int i = 0; while(i < sl->nElem) { if(key == sl->A[i].key){ return i; } else { i++; } } return -1; } bool insert_elem(SeqList* sl, Register reg, int i) { int j; if((sl->nElem == MAX) || (i < 0) || (i > sl->nElem)) { return false; } else { for(j = sl->nElem; j > i; j--) { sl->A[j] = sl->A[j-1]; } sl->A[i] = reg; sl->nElem ++; return true; } } bool remove_elem(Key key, SeqList* sl) { int pos, j; pos = seq_search(sl, key); if(pos == -1) { return false; } else { for(j = pos; j < sl->nElem-1; j++) { sl->A[j] = sl->A[j+1]; } sl->nElem--; return true; } } void show_list(SeqList* sl) { int i; printf("List: \""); for(i=0; i < sl->nElem - 1; i++) printf("%i ", sl->A[i].key); /* Last element isn't followed by blank space */ printf("%i", sl->A[sl->nElem-1].key); printf("\"\n"); }
C
#include <stdio.h> /* avg(x,y) = floor((x+y)/2) */ int avg(int x, int y) { int half_x = x>>1; int half_y = y>>1; return half_x+half_y+(x&y&1); } int main() { printf("%d\n", avg(3,4)); printf("%d\n", avg(3,3)); printf("%d\n", avg(4,4)); }
C
/*******************************************************************************************************************************************************/ /*Author: Donia Mohamed Mahmoud*/ /*Version: V1.2*/ /*NAME: GPIO DRIVER */ /*******************************************************************************************************************************************************/ /*******************************************************************************************************************************************************/ /*includes*/ #include "STD_TYPES.h" #include "BIT_MATH.h" #include "GPIO_interface.h" /*******************************************************************************************************************************************************/ /*******************************************************************************************************************************************************/ /*structure which contains all the registers of GPIO*/ typedef struct{ uint_32t CRL; uint_32t CRH; uint_32t IDR; uint_32t ODR; uint_32t BSRR; uint_32t BRR; uint_32t LCKR; }Reg; /********************************************************************************************************************************************************/ /********************************************************************************************************************************************************/ /*pointer to each port*/ #define PORTA_POINTER ((volatile Reg *)(0x40010800)) #define PORTB_POINTER ((volatile Reg *)(0x40010C00)) #define PORTC_POINTER ((volatile Reg *)(0x40011000)) /********************************************************************************************************************************************************/ /********************************************************************************************************************************************************/ /*general defines*/ #define maxpin 15 /*maximum number of pins */ #define minpin 0 /*minimum number of pins */ #define MODENUM 4 /*number of shifting of any mode*/ #define Mode_null 0b1100 /*to set the correct mode */ #define speed_null 0b0011 /*to set the correct speed */ /********************************************************************************************************************************************************/ /*******************************************************************************************************************************************************/ /* Dsecription : to set the configuration to each pin * Inputs: pointer to structure of GPIO * Output: standard error */ /*******************************************************************************************************************************************************/ uint_8t GPIO_u8SetConfiguration(GPIO_t *p) { uint_8t Mode ,mode,speed,j=0,i; uint_8t local_Error=OK; if( p->port == PORTA || p->port == PORTB || p->port == PORTC) { switch(p->port) { case PORTA: for (i=minpin;i<=maxpin;i++) { if((((p->pin)>>i)&0x01)==1) { mode=p->mode&(Mode_null); speed=p->speed&(speed_null); Mode= (mode)|(speed); if(i<=7) { PORTA_POINTER->CRL&=~(0b1111<<i*MODENUM); PORTA_POINTER->CRL|=(Mode<<i*MODENUM); } else if(i>7 && i<16) { j=i-8; PORTA_POINTER->CRH&=~(0b1111<<j*MODENUM); PORTA_POINTER->CRH|=(Mode<<j*MODENUM); } if(p->mode == MODE_INPUT_INPUTPULLDOWN) { PORTA_POINTER->ODR &=(uint_32t) ~(1<<i); } else if(p->mode == MODE_INPUT_INPUTPULLUP) { PORTA_POINTER->ODR |=(uint_32t) (1<<i); } } } break; case PORTB: for (i=minpin;i<maxpin;i++) { if(((p->pin>>i)&0x01)==1) { mode=p->mode&(Mode_null); speed=p->speed&(speed_null); Mode= (mode)|(speed); if(i<=7) { PORTB_POINTER->CRL&=~(0b1111<<i*MODENUM); PORTB_POINTER->CRL|=(Mode<<i*MODENUM); } else if(i>7) { j=i-8; PORTB_POINTER->CRH&=~(0b1111<<j*MODENUM); PORTB_POINTER->CRH|=(Mode<<j*MODENUM); } if(p->mode == MODE_INPUT_INPUTPULLDOWN) { PORTB_POINTER->ODR &=(uint_32t) ~(1<<i); } else if(p->mode == MODE_INPUT_INPUTPULLUP) { PORTB_POINTER->ODR |=(uint_32t) (1<<i); } } } break; case PORTC: for (i=minpin;i<maxpin;i++) { if(((p->pin>>i)&0x01)==1) { mode=p->mode&(Mode_null); speed=p->speed&(speed_null); Mode= (mode)|(speed); //Mode=0b0010; if(i<=7) { PORTC_POINTER->CRL&=~(0b1111<<i*MODENUM); PORTC_POINTER->CRL|=(Mode<<i*MODENUM); } else if(i>7) { j=i-8; //Mode=0b0010; PORTC_POINTER->CRH&=~(0b1111<<j*MODENUM); PORTC_POINTER->CRH|=(Mode<<j*MODENUM); } if(p->mode == MODE_INPUT_INPUTPULLDOWN) { PORTC_POINTER->ODR &=(uint_32t) ~(1<<i); } else if(p->mode == MODE_INPUT_INPUTPULLUP) { PORTC_POINTER->ODR |=(uint_32t) (1<<i); } } } break; } }else { local_Error=NOK; } return local_Error; } /********************************************************************************************************************************************************/ /* Dsecription : to set the value of whole struct * Inputs: pointer to structure of GPIO , state * Output: standard error */ /********************************************************************************************************************************************************/ uint_8t GPIO_u8SetValue(GPIO_t *p,uint_32t pin,uint_8t state) { uint_8t local_Error=OK; switch(p->port) { case PORTA: if(state==SET) { PORTA_POINTER->BSRR=pin; }else if (state==CLEAR) { PORTA_POINTER->BRR=pin; } break; case PORTB: if(state==SET) { PORTB_POINTER->BSRR=pin; }else if (state==CLEAR) { PORTB_POINTER->BRR=pin; } break; case PORTC: if(state==SET) { //PORTC_POINTER->ODR|=(p->pin); PORTC_POINTER->BSRR=pin; }else if (state==CLEAR) { //PORTC_POINTER->ODR&=~(p->pin); PORTC_POINTER->BRR=pin; }break; default: local_Error=NOK; break; } return local_Error; } /*******************************************************************************************************************************************************/ /* Dsecription : to get the value of whole object * Inputs: pointer to structure of GPIO , pointer to state * Output: standard error */ /*******************************************************************************************************************************************************/ uint_8t GPIO_u8getValue(GPIO_t *p,uint_32t pin ,uint_8t *state) { uint_8t local_Error=OK; switch(p->port) { case PORTA: if( ((PORTA_POINTER->IDR) & ( pin ) ) ) { if(p->mode==MODE_INPUT_INPUTPULLDOWN)*state=1;/** 1 -------------- pressed */ else *state=0; } else { if(p->mode==MODE_INPUT_INPUTPULLDOWN)*state=0;/** 0 -------------- released */ else *state=1; } break; case PORTB: if( (PORTB_POINTER->IDR) & (pin)) { if(p->mode==MODE_INPUT_INPUTPULLDOWN)*state=1;/** 1 -------------- pressed */ else *state=0 ; } else { if(p->mode==MODE_INPUT_INPUTPULLDOWN)*state=0;/** 0 -------------- released */ else *state=1; } break; case PORTC: if( (PORTC_POINTER->IDR) & (pin) ) { if(p->mode==MODE_INPUT_INPUTPULLDOWN)*state=1;/** 1 -------------- pressed */ else *state=0 ; } else { if(p->mode==MODE_INPUT_INPUTPULLDOWN)*state=0;/** 0 -------------- released */ else *state=1; } break; default : local_Error=NOK; break; } return local_Error; }
C
#include <stdio.h> int ft_str_is_numeric(char *str); int main(void) { char *str; str = "555"; printf("%d\n", ft_str_is_numeric(str)); }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdbool.h> #include <unistd.h> #include <sys/types.h> #include <sys/wait.h> // custom imlementation. Reads from stdin until \n or EOF reached // dynamically allocates buffer, thus we have to call free when we finish working with buffer char *read_line() { char *buffer = NULL; int buff_size = 0; int c = getchar(); while (c != '\n' && c != EOF) { ++buff_size; buffer = realloc(buffer, buff_size * sizeof(char)); if (buffer == NULL) { perror("ERROR: Can't allocate memory for buffer\n"); exit(EXIT_FAILURE); } buffer[buff_size - 1] = c; c = getchar(); } buffer = realloc(buffer, (buff_size + 1) * sizeof(char)); if (buffer == NULL) { perror("ERROR: Can't allocate memory for buffer\n"); exit(EXIT_FAILURE); } buffer[buff_size] = '\0'; return buffer; } // splits comand to words by spaces and tabs char **tokenize(char *cmd) { char **tokens = NULL; size_t tokens_count = 0; char *delims = " \t"; char *token = strtok(cmd, delims); while (token != NULL) { ++tokens_count; tokens = realloc(tokens, sizeof(char *) * tokens_count); tokens[tokens_count - 1] = token; token = strtok(NULL, delims); } tokens = realloc(tokens, sizeof(char *) * (tokens_count + 1)); tokens[tokens_count] = NULL; return tokens; } int main(void) { char *cmd; bool terminated = false; while (!terminated) { // printing prompt printf("->> "); // reading command cmd = read_line(); char **args = tokenize(cmd); bool background = false; size_t arg_index = 0; // looking for & signalling of background execution while (args[arg_index] != NULL) { if (strcmp(args[arg_index], "&") == 0) { background = true; break; } ++arg_index; } // removing & if it's present if (background) { args[arg_index] = NULL; } if (strncmp(cmd, "exit", 4) == 0) { terminated = true; } else { pid_t pid = fork(); if (pid == 0) { // child execvp(args[0], args); // smth goes wrong if we've reached this line exit(EXIT_FAILURE); } else if (pid < 0) { perror("ERROR: Can't fork process\n"); free(args); exit(EXIT_FAILURE); } else if (!background) { wait(NULL); } } free(args); free(cmd); } return EXIT_SUCCESS; }
C
#include "dog.h" #include <stdio.h> #include <stdlib.h> /** * free_dog - check the code for Holberton School students. * @d: int * Return: Always 0. */ void free_dog(dog_t *d) { if (d) { free(d->name); free(d->owner); free(d); } }
C
#include <stdio.h> #include <stdbool.h> #include <math.h> #include <ctype.h> #include <stdlib.h> #include <string.h> #define MAX_WORD_LENGTH 20 bool are_anagrams(const char *word1, const char *word2) { char alphabet[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'}; int values[26] = {0}; int arr_size = sizeof(values) / sizeof(values[0]); char input; // read first word int first_word_length = strlen(word1); for (int i = 0; i < first_word_length; i++) { input = word1[i]; if (isalpha(input)) { input = tolower(input); // increment values for (int i = 0; i < arr_size; i++) { if (input == alphabet[i]) values[i] += 1; } } } // read second word int second_word_length = strlen(word1); for (int i = 0; i < second_word_length; i++) { input = word2[i]; if (isalpha(input)) { input = tolower(input); // decrement values for (int i = 0; i < arr_size; i++) { if (input == alphabet[i]) values[i] -= 1; } } } // loop through values and check if all are zeros for (int i = 0; i < arr_size; i++) { if (values[i] != 0) { return false; } } return true; } int main() { char first_word[MAX_WORD_LENGTH]; char second_word[MAX_WORD_LENGTH]; printf("Enter first word: "); gets(first_word); printf("Enter second word: "); gets(second_word); if (are_anagrams(first_word, second_word)) printf("The two words are ANAGRAMS.\n"); else printf("The two words are NOT anagrams.\n"); }
C
#include <stdio.h> /* * ASM_ADD is a macro that uses inline assembly to perform addition. The * parameters op1 and op2 can be integer literals or integer variables. dest * must be a previously declared integer variable. */ #define ASM_ADD(op1, op2, dest) do { \ asm("movl %%eax, %%ecx;" \ "addl %%ebx, %%ecx;" \ : "=c" (dest) \ : "a" (op1), "b" (op2) \ : \ ); \ } while(0); int main(int argc, char const *argv[]) { int a = 1, b = 3, c; asm("movl %%eax, %%ecx;" "addl %%ebx, %%ecx;" : "=c" (c) : "a" (a), "b" (b) : // No clobbered registers ); printf("%d\n", c); int x = 1, y = 10, z; ASM_ADD(x, y, z); printf("%d\n", z); int w; ASM_ADD(10, 20, w); printf("%d\n", w); return 0; }
C
/****************************************************************** * 文件:uart.h * 功能:实现uart相关函数 * 日期:2018-02-27 * 作者:zx * 版本: * Ver.1.0 | 最初版本 * Ver.1.1 | 添加UART2初始化函数 * * Copyright (C) 2018 zx. All rights reserved. *******************************************************************/ #include "UART/uart.h" #include <stdio.h> #include "NET/NetWork.h" extern void processBytes(char * bytes, unsigned short len); /** * 功能:初始化UART * 参数:None * 返回值:None */ void initUART(void) { GPIO_InitTypeDef GPIO_InitStructure; USART_InitTypeDef USART_InitStructure; RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1 | RCC_APB2Periph_GPIOA, ENABLE); //使能USART1时钟 /*********************GPIO Config***************************/ GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9; //发送管脚 GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP; //复用推挽 GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; GPIO_Init(GPIOA, &GPIO_InitStructure); GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10; //接收管脚 GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING; //浮空输入 GPIO_Init(GPIOA, &GPIO_InitStructure); /********************UART Config*****************************/ USART_InitStructure.USART_BaudRate = 115200; //设置波特率 USART_InitStructure.USART_WordLength = USART_WordLength_8b; //8bits数据位 USART_InitStructure.USART_StopBits = USART_StopBits_1; //1bit停止位 USART_InitStructure.USART_Parity = USART_Parity_No; //无奇偶校验位 USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;//不使用硬件流控 USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx; //发送接收均使能 USART_Init(USART1, &USART_InitStructure); //设置生效 USART_Cmd(USART1, ENABLE); //使能串口外设 USART_ITConfig(USART1, USART_IT_RXNE, ENABLE); USART_ITConfig(USART1, USART_IT_IDLE, ENABLE); } /** * 功能:指定某个UART发送一个字节 * 参数:USARTx:使用的目标串口x为1-3 * byte:待发送字节 * 返回值:None */ void sendUartByte(USART_TypeDef *USARTx, u16 byte) { USART_ClearFlag(USARTx, USART_FLAG_TC); //软件清除发送完成标志位 USART_SendData(USARTx, byte); //发送一个字节 while (!USART_GetFlagStatus(USARTx, USART_FLAG_TC));//等待发送完成 USART_ClearFlag(USARTx, USART_FLAG_TC); //软件清除发送完成标志位 } /** * 功能:使用UART1 发送多个字节 * 参数:USARTx:使用的目标串口x为1-3 * byte:待发送字节 * 返回值:None */ void sendUartBytes(char * bytes, u16 len) { for(unsigned short i=0;i<len;++i) { sendUartByte(USART1, bytes[i]); } } /****************************中断服务函数****************************************/ /** * 功能:串口1中断服务函数 * 参数:None * 返回值:None */ void USART1_IRQHandler(void) { static u8 tail = 0; char rbuffer[100]; if(USART_GetITStatus(USART1, USART_IT_RXNE)) //判断接收数据寄存器是否有数据 { rbuffer[tail++] = USART_ReceiveData(USART1); if(tail>=100) { tail = 0; } } if(USART_GetITStatus(USART1, USART_IT_IDLE)) { USART_ReceiveData(USART1); //读一次UART可以清除空闲标志位 processBytes(rbuffer, tail); tail = 0; } } /** * 功能:串口2中断服务函数 * 参数:None * 返回值:None */ void USART2_IRQHandler(void) { } /** * 功能:串口3中断服务函数 * 参数:None * 返回值:None */ void USART3_IRQHandler(void) { } /****************************重定向fputc函数****************************************/ /** * 功能:使用UART1实现printf函数功能 * 参数:ch:待写入字符 我们无需关心 * f:文件指针 我们无需关心 * 返回值:None */ int fputc(int ch, FILE *f) { /* 将Printf内容发往串口 */ USART_SendData(USART1, (unsigned char)ch); while (!USART_GetFlagStatus(USART1, USART_FLAG_TC)); USART_ClearFlag(USART1, USART_FLAG_TC); return (ch); }
C
#include <stdio.h> #include <stdlib.h> #include <time.h> enum status {DEAD, ALIVE}; int main(int argc, char* argv[]) { int n, m, i, j, iter; int *people, *mark; int current, remain, count; clock_t start_time, end_time; if (argc<3){ printf("Usage: alg n m"); return 1; } n = atoi(argv[1]); m = atoi(argv[2]); start_time = clock(); /* mircosecond */ /* using array and mark*/ people = (int*)malloc(n*sizeof(int)); mark = (int*)malloc(n*sizeof(int)); for(i=0;i<n;i++) { people[i] = i+1; mark[i] = ALIVE; } current = 0; remain = n; while(remain>1){ for(count = 0; count < m; ){ if (mark[current] == ALIVE) count++; if (count <m) { current = current + 1; if (current >=n) current = 0; } } mark[current] = DEAD; remain --; } /*find the alive one.*/ for(i=0;i<n;i++) if (mark[i]==ALIVE) break; printf("%d\n",people[i]); free(people); free(mark); end_time = clock(); printf("%d %d %f\n", n, m, (float)(end_time - start_time)/CLOCKS_PER_SEC); return 0; }
C
#ifndef TRAINER_H_ #define TRAINER_H_ #include "location.h" #include "store.h" #include "map.h" #include "list.h" #include "pokemon.h" #include <stdio.h> typedef struct trainer_t *Trainer; typedef enum { TRAINER_SUCCESS, TRAINER_NULL_ARG, TRAINER_DOES_NOT_EXIST, TRAINER_INVALID_ARG, TRAINER_OUT_OF_MEM, TRAINER_EMPTY_LOCATION, TRAINER_OUT_OF_STOCK, TRAINER_BUDGET_IS_NOT_SUFFICIENT, TRAINER_ILLEGAL_MOVE, TRAINER_ALREADY_IN_LOCATION, TRAINER_POKEMON_DOES_NOT_EXIST, TRAINER_POKEMON_HP_IS_AT_MAX, TRAINER_NO_AVAILABLE_ITEM_FOUND } TrainerResult; /*----------------------------------------------------------------------------*/ /** * Creates a new trainer. * * @param name, budget, starting location. * @return * A newly allocated Trainer. * In case of invalid input or any kind of memory allocation failure - * return NULL and a specific error result (via a pointer). */ Trainer trainerCreate(char *name, int budget, char *starting_location, TrainerResult* result); /*----------------------------------------------------------------------------*/ /** * Creates a copy of trainer * * @param trainer - Trainer to copy * @param error - error code * @return * In case of invalid input or any kind of memory allocation failure - * return NULL and a specific error result (via a pointer). */ Trainer trainerCopy(Trainer trainer, TrainerResult* error); /*----------------------------------------------------------------------------*/ /** * Frees all memory allocated to trainer * * @param trainer */ void trainerDestroy(Trainer trainer); /*----------------------------------------------------------------------------*/ /** * Returns pokemon in trainers pokemon map by given id. * @return NULL if no pokemonn or invalid id. * @param trainer, id. */ Pokemon trainerGetPokemonByID(Trainer trainer, int id); /*----------------------------------------------------------------------------*/ /** * Chooses highest value candy to use on given pokemon by id, * trainer loses candy * pokemon cp set higher * @param trainer, id of pokemon to train * @return: * TRAINER_POKEMON_DOES_NOT_EXIST if id is NULL. * TRAINER_NO_AVAILABLE_ITEM_FOUND if trainer has no candies. * TRAINER_SUCCESS if used candy. */ TrainerResult trainerPokemonUseCandy(Trainer trainer, int id); /*----------------------------------------------------------------------------*/ /** * Chooses best potion to use on given pokemon by id, * based on the lowest value potion that will heal to 100 hp, * or highest value if this doesn't exist. * trainer loses potion * pokemon hp set higher * @param trainer, id of pokemon to heal * @return: * TRAINER_POKEMON_DOES_NOT_EXIST if id is NULL * TRAINER_POKEMON_HP_IS_AT_MAX if pokemon hp is 100. * TRAINER_NO_AVAILABLE_ITEM_FOUND if trainer has no potions * TRAINER_SUCCESS if used potion */ TrainerResult trainerPokemonUsePotion(Trainer trainer, int id); /*----------------------------------------------------------------------------*/ /** * Returns trainer name. * @return NULL if sent NULL * @param trainer */ char *trainerGetName(Trainer trainer); /*----------------------------------------------------------------------------*/ /** * Returns trainer current location * @return NULL if sent NULL * @param trainer */ char *trainerGetLocation(Trainer trainer); /*----------------------------------------------------------------------------*/ /** * Sets trainer location to a given new location. * * @param trainer, location name */ void trainerSetLocation(Trainer trainer, char *new_location); /*----------------------------------------------------------------------------*/ /** * Returns trainer experience * @return NULL if sent NULL * @param trainer */ double trainerGetExp(Trainer trainer); /*----------------------------------------------------------------------------*/ /** * Returns trainer pokecoins * @return NULL if sent NULL * @param trainer */ int trainerGetPokecoins(Trainer trainer); /*----------------------------------------------------------------------------*/ /** * Returns trainer number of pokemons * @return NULL if sent NULL * @param trainer */ int trainerGetNumOfPokemons(Trainer trainer); /*----------------------------------------------------------------------------*/ /** * Returns true if a trainer holds a pokemon in given id, * false otherwise * @param trainer, id */ bool trainerPokemonExist(Trainer trainer, int id); /*----------------------------------------------------------------------------*/ /** * Returns trainer store of items. * @return NULL if sent NULL * @param trainer */ Store trainerGetItems(Trainer trainer); /*----------------------------------------------------------------------------*/ /** * Returns trainer map of pokemons. * @return NULL if sent NULL * @param trainer */ Map trainerGetPokemons(Trainer trainer); /*----------------------------------------------------------------------------*/ /** * Sets trainer pokecoins to a given value * * @param trainer, pokecoins */ void trainerSetPokecoins(Trainer trainer, int pokecoins); /*----------------------------------------------------------------------------*/ /** * Adds a pokemon to trainers map in first free index. * @param trainer, pokemon * @return: * TRAINER_OUT_OF_MEM if failed to add pokemon to map * TRAINER_NULL_ARG if sent NULL * TRAINER_SUCCESS otherwise */ TrainerResult trainerAddPokemon(Trainer trainer, Pokemon pokemon); /*----------------------------------------------------------------------------*/ /** * Removes a pokemon from trainers map by given id * @param trainer, id * @return: * TRAINER_INVALID_ARG if id < 0. * TRAINER_NULL_ARG if sent NULL * TRAINER_POKEMON_DOES_NOT_EXIST if no pokemon at given id * TRAINER_SUCCESS otherwise */ TrainerResult trainerRemovePokemon(Trainer trainer, int id); /*----------------------------------------------------------------------------*/ /** * Sets trainer experience to a given value. * * @param trainer, experience. */ void trainerSetExp(Trainer trainer, double exp); /*----------------------------------------------------------------------------*/ #endif /* TRAINER_H */
C
#include <stdio.h> #include <string.h> #include <malloc.h> struct NODE { struct NODE *arcs[26]; int IsTerminal, cnt; }; struct NODE *InitNODE() { struct NODE *elem = malloc(sizeof(struct NODE)); elem->IsTerminal = 0; elem->cnt = 0; memset(elem->arcs, NULL, sizeof(struct NODE *) * 26); return elem; } void Insert(struct NODE *root, char *k) { struct NODE *elem = root; int slen = strlen(k); for (int i = 0; i < slen; i++) { if (elem->arcs[k[i] - 'a'] == NULL) elem->arcs[k[i] - 'a'] = InitNODE(); elem->cnt++; elem = elem->arcs[k[i] - 'a']; } elem->cnt++; if (!elem->IsTerminal) elem->IsTerminal = 1; else { elem = root; for (int i = 0; i < slen; i++) { elem->cnt--; elem = elem->arcs[k[i] - 'a']; } elem->cnt--; } } void Prefix(struct NODE *root, char *k) { struct NODE *elem = root; int slen = strlen(k); for (int i = 0; i < slen; i++) { if (elem->arcs[k[i] - 'a'] == NULL) { printf("%d\n", 0); return; } elem = elem->arcs[k[i] - 'a']; } printf("%d\n", elem->cnt); } void Delete(struct NODE *root, char *k) { struct NODE *elem = root; int slen = strlen(k); for (int i = 0; i < slen; i++) { elem->cnt--; elem = elem->arcs[k[i] - 'a']; } elem->cnt--; elem->IsTerminal = 0; } void FreeTrie(struct NODE *root){ if (root == NULL) return; for (int i = 0; i < 26; i++) FreeTrie(root->arcs[i]); free(root); } int main() { struct NODE *trie = InitNODE(); int n; scanf("%d", &n); char cmd[10]; char k[100000]; for (int i = 0; i < n; i++) { scanf("%s %s", cmd, k); if (cmd[0] == 'I') Insert(trie, k); if (cmd[0] == 'P') Prefix(trie, k); if (cmd[0] == 'D') Delete(trie, k); } FreeTrie(trie); }
C
#include <Arduino.h> #include <BluetoothSerial.h> #include "variable.h" bool newData = false; const byte numChars = 32; #define K_RPM_C 1 #define K_RPM_P 2 #define K_RPM_V1 3 #define K_RPM_D 4 #define K_RPM_I 5 #define K_RPM_L 6 #define K_RPM_S 7 #define K_RPM_D2 8 #define K_RPM_M 9 #define K_NONE 0 char receivedChars[numChars]; char tempChars[numChars]; void parseData(); void changeVariable(); float pwm_in; int type = 0; float i = 0; void recvWithStartEndMarkers(BluetoothSerial *SerialBT) { static boolean recvInProgress = false; static byte ndx = 0; char endMarker = '\n'; char rc; while ((*SerialBT).available() > 0 && newData == false) { rc = (*SerialBT).read(); recvInProgress = true; if (recvInProgress == true) { if (rc != endMarker) { receivedChars[ndx] = rc; ndx++; if (ndx >= numChars) { ndx = numChars - 1; } type = K_NONE; } else { if (ndx > 0){ if (receivedChars[ndx-1] == 'p'){ type = K_RPM_P; } else if (receivedChars[ndx-1] == 'b'){ type = K_RPM_V1; } else if (receivedChars[ndx-1] == 'd'){ type = K_RPM_D; } else if (receivedChars[ndx-1] == 'i'){ type = K_RPM_I; } else if (receivedChars[ndx-1] == 'l'){ type = K_RPM_L; } else if (receivedChars[ndx-1] == 'e'){ type = K_RPM_D2; } else if (receivedChars[ndx -1] == 'm'){ type = K_RPM_M; } else{ type = K_NONE; } receivedChars[ndx-1] = '\0'; // terminate the string recvInProgress = false; strcpy(tempChars, receivedChars); ndx = 0; newData = true; parseData(); changeVariable(); } } } } } void parseData() { // split the data into its parts i = atof(tempChars); // convert this part to an float input = i; newData = false; } void changeVariable(){ if (type == K_RPM_P){ const_pwm[mode] = input; } else if (type == K_RPM_V1){ rpm_batas_1[mode] = input; } else if (type == K_RPM_D) { d_const[mode] = input; } else if (type == K_RPM_I) { i_const[mode] = input; } else if (type == K_RPM_L) { l_const[mode] = input; } else if (type == K_RPM_D2) { d2_const[mode] = input; } else if (type == K_RPM_M){ int temps = (int)input; temps = (temps%3); mode = temps; } }
C
#include "global.h" #include "string.h" #include "const.h" #include "kliba.h" #include "system_call.h" typedef char * va_list; #define get_arg_list(fmt) (va_list)((char*)(&fmt)+4) int vsprintf(char *buf,const char *fmt,va_list args); /*======================================================================* printf *======================================================================*/ int printf(const char*fmt,...){ int len; char buf[1024]; va_list args=get_arg_list(fmt); // putNum(args,16); len=vsprintf(buf,fmt,args); // write(buf,len); printx(buf); // int c=write(1,buf,i); return len; } /*======================================================================* printl *======================================================================*/ int printl(const char*fmt,...){ int len; char buf[1024]; va_list args=get_arg_list(fmt); // putNum(args,16); len=vsprintf(buf,fmt,args); // write(buf,len); printx(buf); return len; } /*======================================================================* vsprintf *======================================================================*/ int vsprintf(char *buf,const char *fmt,va_list args){ char *p=buf; char *s; char tmp[256]; va_list next_arg=args; for(;*fmt;fmt++){ if(*fmt!='%'){ *p++ = *fmt; continue; } fmt++; switch(*fmt){ case '%': *p++ ='%'; break; case 's': s=(char *)(*((int *)next_arg)); strcpy(p,s); p+=strlen(s); next_arg+=4; break; case 'd': itoa(*((int *)next_arg),tmp,10); // itoa(15,tmp,10); strcpy(p,tmp); p+=strlen(tmp); next_arg+=4; break; case 'x': itoa(*((int *)next_arg),tmp,16); // itoa(15,tmp,10); strcpy(p,tmp); p+=strlen(tmp); next_arg+=4; break; case 'c': *p++=*((char *)next_arg); next_arg+=4; break; default:break; } } *p='\0'; return p-buf; } /*======================================================================* putchar *======================================================================*/ void putchar(char c) { printf("%c",c); } /*======================================================================* puts *======================================================================*/ void puts(char *s){ printf("%s",s); } /*======================================================================* NL *======================================================================*/ void NL() { putchar('\n'); } /*======================================================================* putNum *======================================================================*/ void putNum(int num, int mode) { char s[40]; puts(itoa(num, s, mode)); } /*======================================================================* sprintf *======================================================================*/ int sprintf(char *buf, const char *fmt, ...) { va_list arg = (va_list)((char*)(&fmt) + 4); /* 4 是参数 fmt 所占堆栈中的大小 */ return vsprintf(buf, fmt, arg); } /***************************************************************************** * panic * 该函数类似于assert,其表示发生严重系统错误,直接导致停机处理 ****************************************************************************/ void panic(const char *fmt, ...) { int i; char buf[1024]; va_list args=get_arg_list(fmt); i = vsprintf(buf, fmt, args); set_out_char_highLight(4); printl("%c !!panic!! %s", MAG_CH_PANIC, buf); set_out_char_highLight(7); /* should never arrive here */ __asm__ __volatile__("ud2"); }
C
// Solve the rod cutting problem using memory based approach. // Partha P Sarmah CSE 201902022093 CITK #include <stdio.h> int Rodcutting(int *, int); int max(int, int); int r[5] = {0, 0, 0, 0, 0}; int main() { int p[5] = {0, 4, 6, 9, 11}; int optsol = Rodcutting(p, 4); printf("the optimal solution is :%d\n", optsol); return 0; } int Rodcutting(int *p, int length) { if (r[length] > 0) { return r[length]; } if (length == 0) { return 0; } int q = -1; for (int i = 1; i <= length; i++) { q = max(q, p[i] + Rodcutting(p, length - i)); r[length] = q; } return q; } int max(int a, int b) { if (a >= b) return a; else return b; }
C
#include "list.h" #include <string.h> #include <stdlib.h> #include <assert.h> #include <stdio.h> typedef struct Node *Node; struct Node { void *data; Node next; }; struct List { int length; int elementSize; Node head; Node tail; }; List list_new(int elementSize) { assert(elementSize > 0); List n = malloc(sizeof(*n)); n->length = 0; n->elementSize = elementSize; n->head = n->tail = NULL; return n; } void list_free(List *list) { assert(list && *list); Node current; while((*list)->head) { current = (*list)->head; (*list)->head = current->next; free(current->data); free(current); } free(*list); *list = NULL; } size_t list_length(List list) { return list->length; } void* list_append(List list, void *element) { assert(list); assert(element); Node new_node = malloc(sizeof(*new_node)); new_node->data = malloc(list->elementSize); memcpy(new_node->data, element, list->elementSize); new_node->next = NULL; if (list->length == 0) { list->head = list->tail = new_node; } else { list->tail->next = new_node; list->tail = new_node; } list->length++; return new_node->data; } void* list_prepend(List list, void *element) { assert(list); assert(element); Node new_node = malloc(sizeof(*new_node)); new_node->data = malloc(list->elementSize); memcpy(new_node->data, element, list->elementSize); new_node->next = list->head; list->head = new_node; if (!list->tail) { list->tail = new_node; } list->length++; return new_node->data; } void* list_insert(List list, void *element, size_t index) { assert(list); assert(element); assert(index < list->length); Node *cursor = &(list->head); size_t i = 0; while (i < index){ *cursor = (*cursor)->next; i++; } Node new_node = malloc(sizeof(*new_node)); new_node->data = malloc(list->elementSize); memcpy(new_node->data, element, list->elementSize); new_node->next = (*cursor)->next; *cursor = new_node; list->length++; return (*cursor)->data; } void list_remove(List list, size_t index) { assert(list); assert(index < list->length); Node *cursor = &(list->head); size_t i = 0; while (i < index){ *cursor = (*cursor)->next; i++; } Node tmp = *cursor; *cursor = (*cursor)->next; free((*cursor)->data); free(*cursor); } void* list_pop(List list) { void* data; memcpy(data, list->head->data, list->elementSize); Node tmp = list->head; list->head = list->head->next; free(tmp->data); free(tmp); list->length--; return data; } void* list_peek(List list) { return list->head->data; } void* list_item(List list, size_t index) { if (index >= list->length) { printf("Given index is greater than the number of list items.\n"); return NULL; } else { Node ptr = list->head; for (int i = 0; i != index; ++i) { ptr = ptr->next; } return ptr->data; } }
C
#include <stdio.h> #include <stdlib.h> #include <limits.h> #include "tools.h" List *create_list() { List *thelist = malloc(sizeof(List)); if(thelist != NULL) { thelist->size = 0; thelist->first = NULL; thelist->last = NULL; } return thelist; } Node *createNodeWithLetter(char letter) { Node *theNode = malloc(sizeof(Node)); if(theNode != NULL) { theNode->value = letter; theNode->prev = NULL; theNode->next = NULL; } return theNode; } void add_element(List *thelist, char letter) { if (thelist != NULL) { Node *theNode = createNodeWithLetter(letter); if (theNode != NULL) { if ( thelist->first == NULL && thelist->first == thelist->last) { thelist->first = thelist->last = theNode; } else { Node *thelast = thelist->last; thelist->last = theNode; thelast->next = theNode; theNode->prev = thelast; } thelist->size++; } } } void delete_element(List *thelist, int index) { int i = 0; if ((thelist->first == NULL) || (index >= thelist->size))return; Node *theNode = thelist->first, *temp; if(index == 0) { thelist->first = thelist->first->next; temp = theNode; thelist->size--; } else { for (i ; i < index-1; ++i) { if(theNode != NULL) theNode = theNode->next; } temp = theNode->next; theNode->next = theNode->next->next; if (temp == thelist->last) { thelist->last = theNode; } thelist->size--; } free(temp); } void insert_element(List *thelist, int index, char letter) { int theResult = -1; if (NULL == thelist || index >= thelist->size || index < 0) { return theResult; } Node *theNode = thelist->first; int i = 0; do { if (i == index) { break; } theNode = theNode->next; i++; }while (NULL != theNode); Node *theNewNode = createNodeWithLetter(letter); if (NULL == theNewNode) { return theResult; } Node *theBeforeNode = theNode; if (NULL != theBeforeNode->prev) { theBeforeNode->prev->next = theNewNode; theNewNode->prev = theBeforeNode->prev; } theNewNode->next = theBeforeNode; theBeforeNode->prev = theNewNode; thelist->size ++; theResult = 0; return theResult; } void delete_list(List *thelist) { int i = 0; if (thelist == NULL) { return; } Node *theNode = thelist->first; for (i ; i < thelist->size; i++) { if(theNode == NULL) break; Node *theNodeToDelete = theNode; theNode = theNode->next; free(theNodeToDelete); } free(thelist); } void print_list(List *thelist) { if(thelist == NULL) { return; } Node *theNode = thelist->first; do { printf("%c ", theNode->value); theNode = theNode->next; }while (theNode != NULL); printf ("\n"); } void size_list(List *thelist) { if(thelist != NULL) { printf("\nThe size of the list = %d", thelist->size); } } void qsort_list(List *thelist, int first, int last) { { int thePartitionIndex; if (first < last) { thePartitionIndex = partition(thelist, first, last); qsort_list(thelist, first, thePartitionIndex - 1); qsort_list(thelist, thePartitionIndex + 1, last); } } int partition(List *thelist, int first, int last) { char Pivot = NodeAtIndex(thelist, last)->value; int theLeft = first; int theRight = last + 1; while (1) { do theLeft++; while (theLeft < last && NodeAtIndex(thelist, theLeft)->value < Pivot); do theRight--; while (NodeAtIndex(thelist, theRight)->value > Pivot); if (theLeft >= theRight) { break; } else { swap(thelist, theLeft, theRight); } } swap(thelist, first, last); return theRight; } void swap(List *thelist, int theLeft, int theRight) { if (theLeft == theRight) return; Node *theNode_l = NodeAtIndex(thelist,theLeft); Node *theNode_r = NodeAtIndex(thelist,theRight); int temp = theNode_l->value; theNode_l->value = theNode_r->value; theNode_r->value = temp; } Node *NodeAtIndex(List *thelist, int index) { Node *theResult = NULL; if (NULL != thelist && index < thelist->size) { int i = 0; Node *theNode = thelist->first; do { if (i == index) { theResult = theNode; break; } theNode = theNode->next; i++; }while(NULL != theNode); } return theResult; }
C
/* * intdisp.c * * Usage: intdisp [1608 data file] * where the 1608 file contains lightcurves and errors for the four * components, in the format: * * day S_A S_B S_C S_D err_A err_B err_C err_D * * * 19Apr01 CDF, A modification of delays.c * */ #include <stdio.h> #include <stdlib.h> #include <math.h> #include <string.h> #include "structdef.h" #include "dataio.h" #include "lc_funcs.h" #include "noninterp_fns.h" /*....................................................................... * * Main program * */ int main(int argc, char *argv[]) { int i,j; /* Looping variables */ int no_error=1; /* Flag set to 0 on error */ int nflux=0; /* Number of points in light curves */ float disp[N08]; /* Internal dispersions */ char infile[MAXC]; /* Input file name */ Fluxrec *flux[N08]={NULL}; /* Flux 1608 light curves */ Fluxrec *fptr; /* Pointer to navigate flux arrays */ FILE *ifp=NULL; /* File pointer for interpolated data file */ /* * Check input line */ if(argc < 2) { fprintf(stderr,"\nUsage: intdisp [1608_data_file]\n\n"); return 1; } /* * Open lens light curve file */ strcpy(infile,argv[1]); if(!(ifp = open_readfile(infile))) no_error = 0; /* * Count the number of data input lines in order to set * sizes of arrays. */ if(no_error) { nflux = n_lines(ifp,'#'); } if(nflux == 0) { fprintf(stderr,"ERROR. No valid data lines in %s.\n",infile); no_error = 0; } else { rewind(ifp); } /* * Allocate arrays */ if(no_error) { for(i=0; i<N08; i++) { if(!(flux[i] = new_fluxrec(nflux))) no_error = 0; } } /* * Read in data */ if(no_error) { if(read_1608(flux,nflux,ifp,infile)) no_error = 0; } /* * Set all the "match" values in the component light curves to their * array index value. This will make all of the match values different * and will allow disp_d1 to work on a single light curve. */ if(no_error) { printf("Re-setting match variables.\n"); for(i=0,fptr=flux[0]; i<nflux; i++,fptr++) { (flux[0]+i)->match = i; (flux[1]+i)->match = i; (flux[2]+i)->match = i; (flux[3]+i)->match = i; } } /* * Calculate the internal dispersion of all four light curves * through calls to disp_d1 or disp_d2. */ if(no_error) { printf("\nCalculating dispersions.\n"); for(i=0; i<N08; i++) { disp[i] = disp_d2(flux[i],nflux,10.0); } } /* * Print out results */ printf("\nInternal Dispersion Results\n"); printf("-----------------------------------\n"); printf("%7.5f %7.5f %7.5f %7.5f\n\n",disp[0],disp[1],disp[2],disp[3]); /* * Clean up */ if(no_error) printf("\nCleaning up\n\n"); for(i=0; i<4; i++) { flux[i] = del_fluxrec(flux[i]); } if(ifp) fclose(ifp); if(no_error) return 0; else { fprintf(stderr,"ERROR: Exiting program intdisp.c\n"); return 1; } }
C
#ifndef JOGO_H #define JOGO_H #include "mesa.h" #include "menu.h" // "jogo.h" contém funções necessárias para administrar o jogo e seu estado atual // Menu inicial que recebe o usuario // Pré-condição: nenhuma // Pós-condição: Permite que o usuario comece um novo jogo ou carregue um jogo ja salvo void jogo(); // Verifica se o jogador continuara jogando // Pré-condição: nenhum // Pós-condição: retorna 1 caso o jogo continue // 0 caso o jogo deva se encerrar int isPlaying(int ctrl); // Checa se as pilhas base estão completas, ou seja, se o jogador venceu o jogo // Pré-condição: 4 estruturas de pilhas base // Pós-condição: Uma mensagem de vitoria é exibida int isVitoria(Pilha_Cartas_Base* paus, Pilha_Cartas_Base* ouros, Pilha_Cartas_Base* copas, Pilha_Cartas_Base* espadas); // Cabeçalho do arquivo para salvar o jogo typedef struct { int pos_cabeca; //posição do inicio da lista int pos_topo; // primeira posição nao usada no fim do arquivo int pos_livre; // posição do inicio da lista de nós livres } cabecalho; // estrutura de no para lista encadeada typedef struct { Carta carta; int prox; } no; // -- Funções de Arquivo Binário - para Salvar a Carregar o jogo // Cria uma lista nova em arquivo // Pré-condição: arquivo aberto para leitura/escrita // Pós-condição: arquivo é inicializado com uma lista vazia void cria_lista_vazia(FILE* arq); // Lê o cabeçalho do arquivo contendo as informações da lista // Pré-condição: arquivo deve estar aberto e ser um arquivo de lista // Pós-condição: retorna o ponteiro para o cabeçalho lido cabecalho* le_cabecalho(FILE * arq); // Escreve no arquivo o cabeçalho contendo as informações da lista // Pré-condição: arquivo deve estar aberto e ser um arquivo de lista // Pós-condição: cabeçalho escrito no arquivo void escreve_cabecalho(FILE* arq, cabecalho* cab); // Lê um nó em uma determinada posição do arquivo // Pré-condição: arquivo deve estar aberto e ser um arquivo de lista // pos deve ser uma posição válida da lista // Pós-condição: ponteiro para nó lido é retornado no* le_no(FILE* arq, int pos); // Escreve um nó em uma determinada posição do arquivo // Pré-condição: arquivo deve estar aberto e ser um arquivo de lista // pos deve ser uma posição válida do arquivo // Pós-condição: nó escrito no arquivo void escreve_no(FILE* arq, no* x, int pos); // Insere um nó na cabeça da lista no arquivo void insere(FILE* arq, Carta c); // Retira um nó da lista // Pré-condição: arquivo deve estar aberto e ser um arquivo de lista // Pós-condição: nó retirado da lista caso pertença a ela void retira(FILE* arq, Carta c); // Lê uma da lista e insere seus elementos numa pilha de cartas // Pré-condição: arquivo deve estar aberto e ser um arquivo de lista // Pós-condição: elemento inserido na pilha void le_coluna(FILE* arq, Pilha_Cartas* coluna); // Lê uma lista e insere seus elementos numa pilha base de cartas de um naipe // Pré-condição: arquivo deve estar aberto e ser um arquivo de lista // Pós-condição: elemento inserido na pilha base void le_pilhabase(FILE* arq, Pilha_Cartas_Base* pilhabase); // Lê uma lista e insere seus elementos nas celulas de apoio // Pré-condição: arquivo deve estar aberto e ser um arquivo de lista // Pós-condição: retorna um ponteiro (vetor) de cartas a serem posicionadas nas celulas de apoio Carta* le_celulas(FILE* arq); // Lê uma pilha e insere seus elementos numa lista de arquivo // Pré-condição: arquivo deve estar aberto e ser um arquivo de lista // Pós-condição: arquivo contendo os elementos da pilha void insereColuna(FILE* arq, Pilha_Cartas* pilha); // Lê uma pilha e insere seus elementos numa lista de arquivo // Pré-condição: arquivo deve estar aberto e ser um arquivo de lista // Pós-condição: arquivo contendo os elementos da pilha void inserePilhaBase(FILE* arq, Pilha_Cartas_Base* pilhabase); // Lê uma pilha e insere seus elementos numa lista de arquivo // Pré-condição: arquivo deve estar aberto e ser um arquivo de lista // Pós-condição: arquivo contendo os elementos da pilha void insereCelulas(FILE* arq, Carta apoio1, Carta apoio2, Carta apoio3, Carta apoio4); #endif // JOGO_H
C
#include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include "matriz.h" int main(int argc, char **argv){ float ***mat, relatorio_f; int relatorio_i; Dados tam; printf("Digite o numero de alunos, disciplinas e semestres: "); scanf("%d %d %d", &tam.l, &tam.c, &tam.d); //linha, coluna, dimensao tam.c +=1; //primeira coluna eh cod alunos mat = aloca_matriz(tam); preenche_matriz(tam, mat); imprime_matriz(tam, mat); int op; do{ printf("\n\t1 - Relatorio 1\n\t2 - Relatorio 2\n\t3 - Relatorio 3\n\t4 - Relatorio 4\n\t5 - Relatorio 5\n\t6 - Sair\n\t"); printf("Escolha a opcao: "); scanf("%d", &op); printf("\n"); switch(op){ case 1: relatorio_f = relatorio_um(tam, mat); if(relatorio_f != -1) printf("\n\tMedia do aluno: %.2f", relatorio_f); break; case 2: relatorio_f = relatorio_dois(tam, mat); if(relatorio_f != -1) printf("\n\tMedia da disciplina: %.2f", relatorio_f); break; case 3: relatorio_i = relatorio_tres(tam, mat); if(relatorio_i != -1) printf("\n\tAlunos aprovados: %d", relatorio_i); break; case 4: relatorio_i = relatorio_quatro(tam, mat); //impreme na funcao (causo tenha empate) break; case 5: relatorio_i = relatorio_cinco(tam, mat); break; case 6: printf("Fim.\n"); break; default: printf("\tOpcao invalida."); } printf("\n"); }while(op != 6); desaloca_matriz(tam, mat); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <stdarg.h> #include <stdint.h> #include <stdbool.h> #include <string.h> #include <assert.h> #include <utils.h> #include <btree.h> #define PAGE_SZ ((uint64_t)77) #define ENTRY_SZ 12 // Para essa implementação em particular temos que assumir que `CAPACITY` é um // número ímpar. #define CAPACITY 5 // Macro simples para prevenir repetição no código #define ASSERT(expr) \ if (!(expr)) return false // Precisamos desse valor como uma variável para poder utilizar o endereço na // função `fwrite`. const uint64_t NULL_RRN = -1; // Um par chave-valor. typedef struct { int32_t key; uint64_t value; } Entry; // Representa um nó da Btree. typedef struct { bool is_leaf; uint32_t len; uint32_t rrn; // Apenas CAPACITY - 1 espaços serão realmente ocupados no campo `entries`. // O espaço extra é pra podermos inserir uma `Entry` a mais de maneira // ordenada e assim escolher facilmente `Entry` do meio para ser promovida. // O mesmo vale para o campo `children`. uint32_t children[CAPACITY + 1]; Entry entries[CAPACITY]; } Node; // Mesmo que `error` mas funciona com argumentos variáveis static void verror(BTreeMap *btree, const char *format, va_list ap) { if (btree->error_msg) free(btree->error_msg); btree->error_msg = alloc_vsprintf(format, ap); } // Coloca uma determinada mensagem de erro na `btree`. O formato dos argumentos // de formatação é o mesmo da função `printf`. static void error(BTreeMap *btree, const char *format, ...) { va_list ap; va_start(ap, format); verror(btree, format, ap); va_end(ap); } // Garante que `fp` estará posicionado em determinado byte offset. static inline void position(FILE *fp, uint64_t offset) { if (ftell(fp) != offset) fseek(fp, offset, SEEK_SET); } // Garante que `fp` estará posicionado numa determinada página de memória de // acordo com o `rrn`. Vale notar que o RRN 0 não se refere ao byte offset 0. static inline void position_rrn(FILE *fp, uint32_t rrn) { uint64_t offset = PAGE_SZ + PAGE_SZ * (uint64_t)rrn; position(fp, offset); } static bool read_header(BTreeMap *btree) { position(btree->fp, 0); char status; ASSERT(fread(&status, sizeof(char), 1, btree->fp)); ASSERT(status == '1'); ASSERT(fread(&btree->rrn_root, sizeof( int32_t), 1, btree->fp)); ASSERT(fread(&btree->next_rrn, sizeof(uint32_t), 1, btree->fp)); return true; } static bool read_node(BTreeMap *btree, uint32_t rrn, Node *to_read) { position_rrn(btree->fp, rrn); char is_leaf; ASSERT(fread(&is_leaf, sizeof(char), 1, btree->fp)); // Converte de char para booleano. to_read->is_leaf = is_leaf == '1'; ASSERT(fread(&to_read->len, sizeof(uint32_t), 1, btree->fp)); ASSERT(fread(&to_read->rrn, sizeof(uint32_t), 1, btree->fp)); if (!to_read->is_leaf) { // Se não for uma folha, temos a garantia de que há ao menos um nó filho. ASSERT(fread(&to_read->children[0], sizeof(uint32_t), 1, btree->fp)); } else { fseek(btree->fp, sizeof(uint32_t), SEEK_CUR); } for (int i = 0; i < to_read->len; i++) { ASSERT(fread(&to_read->entries[i].key , sizeof( int32_t), 1, btree->fp)); ASSERT(fread(&to_read->entries[i].value, sizeof(uint64_t), 1, btree->fp)); if (!to_read->is_leaf) { ASSERT(fread(&to_read->children[i + 1] , sizeof(uint32_t), 1, btree->fp)); } else { fseek(btree->fp, sizeof(uint32_t), SEEK_CUR); } } return true; } static bool write_header(BTreeMap *btree, char status) { position(btree->fp, 0); ASSERT(fwrite(&status , sizeof(char) , 1, btree->fp)); ASSERT(fwrite(&btree->rrn_root, sizeof( int32_t), 1, btree->fp)); ASSERT(fwrite(&btree->next_rrn, sizeof(uint32_t), 1, btree->fp)); int n_written = sizeof(char) + sizeof(int32_t) + sizeof(uint32_t); for (int i = n_written; i < PAGE_SZ; i++) { ASSERT(fwrite("@", sizeof(char), 1, btree->fp)); } return true; } /** * Cria um novo `BtreeMap`. Não envolve alocação ou abertura de arquivos. * * @return uma BTree ainda sem arquivo vinculado. */ BTreeMap btree_new() { return (BTreeMap) { .fp = NULL, .error_msg = NULL, .rrn_root = -1, .next_rrn = 0, }; } /** * Libera o `BTreeMap` inclusive fechando algum arquivo vinculado. * * @param btree - a btree a ser liberada. */ void btree_drop(BTreeMap btree) { if (btree.fp) { // Antes de fechar o arquivo, escreve novamente o header da btree, agora // com status '1'. write_header(&btree, '1'); fclose(btree.fp); } if (btree.error_msg) free(btree.error_msg); } /** * Carrega a BTree de um arquivo. Essa operação lê apenas o header da BTree. O * arquivo precisa já estar criado e possuir ao menos o header disponível. * * @param btree - referência mutável da btree que terá o arquivo vinculado. * @param fname - nome do arquivo a ser vinculado a essa btree. * @return `BTREE_OK` em caso de sucesso e `BTREE_FAIL` em caso de erro. No * segundo caso, uma mensagem de erro estará disponível. */ BTreeResult btree_load(BTreeMap *btree, const char *fname) { FILE *fp = fopen(fname, "rb+"); if (!fp) { error(btree, "failed to open file %s", fname); return BTREE_FAIL; } btree->fp = fp; // Lê somente o header da BTree. if (!read_header(btree)) { error(btree, "unable to read btree header from file"); return BTREE_FAIL; } return BTREE_OK; } /** * Cria um arquivo de BTree e vincula ele a um `BTreeMap`. * * @param btree - referência mutável da btree que terá o arquivo vinculado. * @param fname - nome do arquivo a ser criado e vinculado a essa btree. * @return `BTREE_OK` em caso de sucesso e `BTREE_FAIL` em caso de erro. No * segundo caso, uma mensagem de erro estará disponível. */ BTreeResult btree_create(BTreeMap *btree, const char *fname) { FILE *fp = fopen(fname, "wb+"); if (!fp) { error(btree, "failed to create file %s", fname); return BTREE_FAIL; } btree->fp = fp; if (!write_header(btree, '0')) { error(btree, "failed to create header in file %s", fname); return BTREE_FAIL; } return BTREE_OK; } /** * Verifica se a `btree` possui algum erro registrado. * * @param btree - a btree a ser verificada. * @return `false` caso não tenha ocorrido erro e `true` caso tenha. */ bool btree_has_error(BTreeMap *btree) { return btree->error_msg; } /** * Recupera a mensagem de erro da `btree`. A string retornada não deve ser * modificada ou liberada. * * @param btree - a btree com erro. * @return uma string contendo a mensagem de erro. */ const char *btree_get_error(BTreeMap *btree) { return btree->error_msg; } // Encontra a posição onde `key` poderia ser inserida em `node`. static int key_position(Node node, uint32_t key) { int i; for (i = 0; i < node.len && key > node.entries[i].key; i++); return i; } // Função interna para obter um valor dado uma chave. static int64_t get(BTreeMap *btree, Node node, uint32_t key) { // Primeiro, encontra a posição onde `key` seria inserida no nó atual. int i = key_position(node, key); // Se tivermos encontrado a chave procurada, retornamos o valor // correspondente a ela. if (i < node.len && node.entries[i].key == key) { return node.entries[i].value; } // Se for um nó interno, lemos o nó filho onde `key` possa ser encontrada e // chamamos `get` recursivamente no nó filho. if (!node.is_leaf) { Node next; if (!read_node(btree, node.children[i], &next)) { error(btree, "failed to read node with RRN %d", node.children[i]); return -1; } return get(btree, next, key); } // `node` é necessáriamente um nó folha, mas não encontramos `key`, // portanto, retornamos -1 sinalizando que `key` não foi encontrada. return -1; } /** * Acessa um valor dado uma chave. Esse processo não envolve escritas ao disco, * entretanto muda o *file_pointer* da `btree` e por isso ela não se mantém * constante. * * @param btree - a btree a ser utilizada que precisa ter um arquivo vinculado. * @param key - a chave de busca. * @return o valor associado à `key` caso `key` esteja contida na btree e -1 * caso contrário. Em caso de erro, -1 é retornado e `btree_has_error()` * retorna `true`. */ int64_t btree_get(BTreeMap *btree, int32_t key) { // Se a btree não possui arquivo vinculado, erro. if (!btree->fp) { error(btree, "no associated file"); return -1; } // Se não há nó raiz na btree, ela está vazia e `key` não estará contida nela. if (btree->rrn_root < 0) { return -1; } // Lemos o nó raiz e chamamos a função `get` interna. Node root; if (!read_node(btree, btree->rrn_root, &root)) { error(btree, "unable to read root"); return -1; } return get(btree, root, key); } // Cria um `Node` contendo uma único par chave-valor. static Node node_from_entry(Entry entry, uint32_t rrn) { return (Node) { .is_leaf = true, .len = 1, .rrn = rrn, .entries = { entry }, }; } // Escreve um `Node` para o disco de acordo com o seu RRN. static bool write_node(BTreeMap *btree, Node node) { position_rrn(btree->fp, node.rrn); char is_leaf = node.is_leaf ? '1' : '0'; ASSERT(fwrite(&is_leaf , sizeof(char), 1, btree->fp)); ASSERT(fwrite(&node.len, sizeof(uint32_t), 1, btree->fp)); ASSERT(fwrite(&node.rrn, sizeof(uint32_t), 1, btree->fp)); if (!node.is_leaf) { // Se não for uma folha, temos a garantia de que há ao menos um nó filho. ASSERT(fwrite(&node.children[0], sizeof(uint32_t), 1, btree->fp)); } else { ASSERT(fwrite(&NULL_RRN, sizeof(uint32_t), 1, btree->fp)); } // Iteramos por todos os pares chave-valor bem como pelos RRNs dos nós // filhos, quando algum valor não está definido, escrevemos apenas 1s. for (int i = 0; i < CAPACITY - 1; i++) { if (i < node.len) { ASSERT(fwrite(&node.entries[i].key , sizeof( int32_t), 1, btree->fp)); ASSERT(fwrite(&node.entries[i].value, sizeof(uint64_t), 1, btree->fp)); } else { ASSERT(fwrite(&NULL_RRN, sizeof( int32_t), 1, btree->fp)); ASSERT(fwrite(&NULL_RRN, sizeof(uint64_t), 1, btree->fp)); } if (!node.is_leaf && i < node.len) { ASSERT(fwrite(&node.children[i + 1], sizeof(uint32_t), 1, btree->fp)); } else { ASSERT(fwrite(&NULL_RRN, sizeof(uint32_t), 1, btree->fp)); } } return true; } // Cria e escreve um nó folha contendo apenas um par chave-valor no próximo RRN // disponível. static bool write_next_leaf(BTreeMap *btree, Entry entry) { Node leaf = node_from_entry(entry, btree->next_rrn++); return write_node(btree, leaf); } // Insere um par chave-valor num nó folha numa determinada posição do nó. Essa // função assume que `node->is_leaf` é `true`. static void insert_entry_leaf(Node *node, Entry entry, int at) { // Se a inserção deve ser feita no meio do nó, shifta todos os registros // e insere. if (at < node->len) { memmove(&node->entries[at + 1], &node->entries[at], (node->len - at) * sizeof(Entry)); } node->entries[at] = entry; node->len++; } // Insere um par chave-valor e também o RRN do nó com elementos maiores do que // `entry.key` num nó interno numa determinada posição do nó. Essa função assume // que `node->is_leaf` é `false`. static void insert_entry_inner(Node *node, Entry entry, uint32_t right_rrn, int at) { // Se a inserção deve ser feita no meio do nó, shifta todos os registros // e insere. if (at < node->len) { memmove(&node->entries[at + 1] , &node->entries[at] , (node->len - at) * sizeof(Entry)); memmove(&node->children[at + 2], &node->children[at + 1], (node->len - at) * sizeof(uint32_t)); } node->entries[at] = entry; node->children[at + 1] = right_rrn; node->len++; } // Um tipo interno que serve somente para representar o comportamento de uma // inserção num nó filho. Esse tipo auxiliar ajuda nas funções de inserção. typedef struct { // O tipo de inserção que ocorreu enum { INSERT_SPLIT, INSERT_REPLACE, INSERT_FIT, INSERT_FAIL, } type; // A `entry` promovida, somente disponível quando `type = INSERT_SPLIT` Entry entry; // RRN do nó à direita do nó promovido, somente disponível quando `type = INSERT_SPLIT` uint32_t rrn; } InsertResult; // Funções que ajudam a criar o tipo `InsertResult`. static inline InsertResult insertion_fail() { return (InsertResult){ .type = INSERT_FAIL }; } static inline InsertResult insertion_split(Entry entry, uint32_t rrn) { return (InsertResult){ .type = INSERT_SPLIT, .entry = entry, .rrn = rrn }; } static inline InsertResult insertion_fit() { return (InsertResult){ .type = INSERT_FIT }; } static inline InsertResult insertion_replaced(Entry entry) { return (InsertResult){ .type = INSERT_REPLACE, .entry = entry }; } // Divide um nó em dois. Cria um novo nó com as chaves maiores do que a chave // do meio. Retorna o RRN do nó criado e também a `entry` promovida. static InsertResult node_split(BTreeMap *btree, Node left, Entry entry) { assert(left.len == CAPACITY); Entry promoted = left.entries[CAPACITY / 2]; Node right = { // O nó a ser criado será um nó folha somente se o nó a ser dividido // também for um nó folha. .is_leaf = left.is_leaf, .len = CAPACITY / 2, .rrn = btree->next_rrn++, }; memcpy(right.entries, &left.entries[CAPACITY / 2] + 1, (CAPACITY / 2) * sizeof(Entry)); // Se o nó não é uma folha, copia também a metade superior dos filhos do nó // sendo dividido. if (!right.is_leaf) { memcpy(right.children, &left.children[(CAPACITY + 1) / 2], ((CAPACITY + 1) / 2) * sizeof(uint32_t)); } // O nó sendo dividido passa a ter a metade da capacidade anterior. left.len = CAPACITY / 2; // Escreve ambos os nós no disco, tanto o novo nó, quanto o nó já existente // atualizado. if (!write_node(btree, left) || !write_node(btree, right)) { error(btree, "failed to split node when inserting entry with key %d", entry.key); return insertion_fail(); } // Como houve um split, retorna o par chave-valor promovido bem como o RRN // do novo nó criado. return insertion_split(promoted, right.rrn); } // Insere um novo par chave-valor na BTree. Essa função assume que o nó raiz já // está criado. static InsertResult insert(BTreeMap *btree, Node head, Entry entry) { int i = key_position(head, entry.key); if (head.is_leaf) { // É um nó folha, mas ainda possui espaço disponível -> insere insert_entry_leaf(&head, entry, i); if (head.len == CAPACITY) { // É um nó folha que não possui espaço livre -> split return node_split(btree, head, entry); } // Atualiza o nó no disco if (!write_node(btree, head)) { error(btree, "failed to write node when inserting entry inplace with key %d", entry.key); return insertion_fail(); } return insertion_fit(); } // É um nó interno. if (i < head.len && head.entries[i].key == entry.key) { // Encontramos outro nó com a mesma chave -> substitui, retorna a anterior. Entry old = head.entries[i]; head.entries[i] = entry; if (!write_node(btree, head)) { error(btree, "failed to replace node entry with key %d", entry.key); return insertion_fail(); } // Sinaliza que a chave antiga foi substituída. return insertion_replaced(old); } // É um nó interno -> redireciona para o nó filho. Node node; uint32_t node_rrn = head.children[i]; // Lê o nó filho do disco. if (!read_node(btree, node_rrn, &node)) { error(btree, "failed to read node at RRN %d", node_rrn); return insertion_fail(); } // Chama a função recursivamente. `result` armazena informações sobre como // foi feita a inserção no nó filho. InsertResult result = insert(btree, node, entry); // Se não houve split, repasse o mesmo resultado. if (result.type != INSERT_SPLIT) return result; // O nó filho deu split. Entry promoted = result.entry; uint32_t promoted_child = result.rrn; // Insere o par chave-valor promovidos no nó atual. insert_entry_inner(&head, promoted, promoted_child, i); if (head.len == CAPACITY) { // Não há mais espaço nesse nó -> split return node_split(btree, head, promoted); } // Ainda há espaço nesse nó -> adiciona entrada if (!write_node(btree, head)) { error(btree, "failed to write node when promoting entry inplace with key %d", promoted.key); return insertion_fail(); } return insertion_fit(); } /** * Insere um par chave-valor na BTree. Assume que `btree` já possua algum * arquivo vinculado. * * @param btree - a btree no qual inserir. * @param key - a chave usada para ordenação da btree. * @param value - o valor associado. * @return `BTREE_OK` em caso de sucesso e `BTREE_FAIL` em caso de erro. No * segundo caso, uma mensagem de erro estará disponível. */ BTreeResult btree_insert(BTreeMap *btree, int32_t key, uint64_t value) { Entry entry = { .key = key, .value = value, }; // Se ainda não houver um nó raiz, crie ele. if (btree->rrn_root < 0) { btree->rrn_root = btree->next_rrn; if (!write_next_leaf(btree, entry)) { error(btree, "failed to write root node at RRN %d", btree->next_rrn); return BTREE_FAIL; } return BTREE_OK; } Node root; // Lê o nó raiz. if (!read_node(btree, btree->rrn_root, &root)) { error(btree, "failed to read root node at RRN %d", btree->rrn_root); return BTREE_FAIL; } // Insere o par chave-valor na btree. InsertResult result = insert(btree, root, entry); // Se o nó raiz deu split, cria uma nova raiz com o par chave-valor // promovido. if (result.type == INSERT_SPLIT) { Node new_root = { .is_leaf = false, .len = 1, .rrn = btree->next_rrn++, .entries = { result.entry }, .children = { root.rrn, result.rrn }, }; if (!write_node(btree, new_root)) { error(btree, "failed to write new root node at RRN %d", new_root.rrn); return BTREE_FAIL; } btree->rrn_root = new_root.rrn; } if (result.type == INSERT_FAIL) { return BTREE_FAIL; } return BTREE_OK; } /* Funcionalidades adicionais */ // Imprime um único nó da árvore. static void print_node(Node node) { printf("[%d]{ %d: %ld", node.rrn, node.entries[0].key, node.entries[0].value); for (int i = 1; i < node.len; i++) { printf(", %d: %ld", node.entries[i].key, node.entries[i].value); } printf(" }"); } /** * Imprime os conteúdos da `btree`. * ATENÇÃO: Essa função causará undefined behavior caso possua um nível com * mais de 10000 nós. * * @param btree - a btree a ser impressa. Essa função não causa escritas ao * disco, mas utiliza de `fseek` o que modifica `btree`. */ void btree_print(BTreeMap *btree) { #define Q_SZ 10000 #define PUSH(val) \ do { \ queue[end] = (val); \ end = (end + 1) % Q_SZ; \ } while (0) #define POP(var) \ do { \ (var) = queue[start]; \ start = (start + 1) % Q_SZ; \ } while (0) int32_t queue[Q_SZ]; uint32_t start = 0; uint32_t end = 0; if (btree->rrn_root < 0) { printf("[ empty ]\n"); return; } PUSH(btree->rrn_root); PUSH(-1); while (start != end) { int32_t rrn; POP(rrn); // Marca que chegamos no fim de um nível da árvore. if (rrn == -1) { printf("\n"); if (start != end) PUSH(-1); continue; } Node node; if (!read_node(btree, rrn, &node)) { fprintf(stderr, "Print Error: failed to read node at RRN %d\n", rrn); return; } print_node(node); printf(" "); if (!node.is_leaf) { for (int i = 0; i < node.len + 1; i++) { PUSH(node.children[i]); } } } #undef Q_SZ #undef PUSH #undef POP }
C
/* * A mine sweeper using the MLV library */ #include <MLV/MLV_all.h> #include "grid.h" #include "draw.h" #include <stdio.h> /* Custom */ /* #define GRID_WIDTH 36 #define GRID_HEIGHT 24 #define NUMBER_OF_MINES 10 */ /* Beginner */ #define GRID_WIDTH 9 #define GRID_HEIGHT 9 #define NUMBER_OF_MINES 10 /* Intermediate */ /* #define GRID_WIDTH 16 #define GRID_HEIGHT 16 #define NUMBER_OF_MINES 40 */ /* Advanced */ /* #define GRID_WIDTH 30 #define GRID_HEIGHT 16 #define NUMBER_OF_MINES 99 */ int main() { /* Create the internal representation of the game board */ grid *g = create_grid(GRID_WIDTH, GRID_HEIGHT); add_mines(g, NUMBER_OF_MINES); /* Create the window */ int width=GRID_WIDTH*GRID_SCALE; int height=GRID_HEIGHT*GRID_SCALE; MLV_create_window("Sweeper", "Sweeper", width, height); /* Draw the game board in the window */ draw_grid(g); MLV_actualise_window(); /* Main game loop */ MLV_Event event = MLV_NONE; MLV_Keyboard_button key_button; MLV_Mouse_button mouse_button; MLV_Button_state mouse_state; int x_pixel, y_pixel, x_pos, y_pos; int game_over = 0; int marked = 0; int remaining = GRID_WIDTH*GRID_HEIGHT-NUMBER_OF_MINES; while (!(event == MLV_KEY && key_button == MLV_KEYBOARD_ESCAPE)) { event = MLV_wait_event( &key_button, NULL, NULL, NULL, NULL, &x_pixel, &y_pixel, &mouse_button, &mouse_state ); if (!game_over && event == MLV_MOUSE_BUTTON && mouse_state == MLV_RELEASED) { /* The player has pressed a button */ x_pos = x_pixel/GRID_SCALE; y_pos = y_pixel/GRID_SCALE; printf("Mouse click on (%d,%d)\n", x_pos, y_pos); cell *c = &g->cells[x_pos][y_pos]; if (mouse_button == MLV_BUTTON_LEFT && !c->visible && !c->marked) { /* The player has left clicked on an unmarked hidden cell */ int uncovered = uncover(g,c); printf("Uncovered %d cell(s)\n", uncovered); remaining -= uncovered; if (c->mine) { /* The player has struck a mine */ printf("Game over! Press ESCAPE to quit.\n"); game_over = 1; } } else if (mouse_button == MLV_BUTTON_RIGHT && !c->visible) { /* The player has right clicked on a hidden cell */ if (c->marked) { marked--; c->marked = 0; } else { marked++; c->marked = 1; } draw_cell_actualise_window(c); } if (remaining == 0 && marked == NUMBER_OF_MINES) { /* The player has marked all mines and uncovered all other cells */ printf("You win! Press ESCAPE to quit.\n"); game_over = 1; } } } MLV_free_window(); free_grid(g); return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* line_parser.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: prippa <prippa@student.unit.ua> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/01/12 18:41:49 by prippa #+# #+# */ /* Updated: 2019/01/12 18:41:51 by prippa ### ########.fr */ /* */ /* ************************************************************************** */ #include "line_parser.h" #include "syntax_characters.h" static t_bool lp_special_cases(t_line_parser *lp) { if (ft_isdigit(lp->line[lp->i]) && (!lp->i || lp->line[lp->i - 1] == SPACE_C)) return (lp_check_redirection(lp)); return (false); } static void lp_loop(t_line_parser *lp) { t_ht_elem *elem; lp->i = 0; while (lp->line[lp->i]) { elem = HT_GET(&sh()->pars_manager, &lp->line[lp->i], sizeof(char)); if (elem) ((t_func_cmd)elem->value)(lp); else if (!lp_special_cases(lp)) { lp_write_to_arg_buf_char(&lp->cmd, lp->line[lp->i]); ++lp->i; } } lp_semicolon(lp); } void line_parser(void) { t_line_parser lp; ft_bzero(&lp, sizeof(t_line_parser)); LST_INIT(&lp.cmds, &lp_del_commands_list); lp.line = sh()->line; lp_init_command(&lp.cmd); lp_loop(&lp); }
C
#include "AT24Cxx.h" u8 AT24Cxx_ReadOneByte(u8 addr) { u8 temp=0; I2C_Start(); //ʼź if(EE_TYPE>AT24C16) { I2C_Send_Byte(0xa0); I2C_Wait_Ack(); I2C_Send_Byte(addr>>8); } else { I2C_Send_Byte(0xa0+((addr/256)<<1));//ַ+ݵַ } I2C_Wait_Ack(); I2C_Send_Byte(addr%256); I2C_Wait_Ack(); I2C_Start(); //ʼź I2C_Send_Byte(0xa1); I2C_Wait_Ack(); temp=I2C_Read_Byte(0); I2C_Stop(); return temp; } u16 AT24Cxx_ReadTwoByte(u16 addr) { u16 temp=0; I2C_Start(); //ʼź if(EE_TYPE>AT24C16) { I2C_Send_Byte(0xa0); I2C_Wait_Ack(); I2C_Send_Byte(addr>>8); } else { I2C_Send_Byte(0xa0+((addr/256)<<1));//ַ+ݵַ } I2C_Wait_Ack(); I2C_Send_Byte(addr%256); I2C_Wait_Ack(); I2C_Start(); //ʼź I2C_Send_Byte(0xa1); I2C_Wait_Ack(); temp=I2C_Read_Byte(1); temp<<=8; temp|=I2C_Read_Byte(0); I2C_Stop(); return temp; } void AT24Cxx_WriteOneByte(u8 addr,u8 dt) { I2C_Start(); //ʼź if(EE_TYPE>AT24C16) { I2C_Send_Byte(0xa0); I2C_Wait_Ack(); I2C_Send_Byte(addr>>8); } else { I2C_Send_Byte(0xa0+((addr/256)<<1));//ַ+ݵַ } I2C_Wait_Ack(); I2C_Send_Byte(addr%256); I2C_Wait_Ack(); I2C_Send_Byte(dt); I2C_Wait_Ack(); I2C_Stop(); delay_ms(10); } void AT24Cxx_WriteTwoByte(u16 addr,u16 dt) { I2C_Start(); //ʼź if(EE_TYPE>AT24C16) { I2C_Send_Byte(0xa0); I2C_Wait_Ack(); I2C_Send_Byte(addr>>8); } else { I2C_Send_Byte(0xa0+((addr/256)<<1));//ַ+ݵַ } I2C_Wait_Ack(); I2C_Send_Byte(addr%256); I2C_Wait_Ack(); I2C_Send_Byte(dt>>8); I2C_Wait_Ack(); I2C_Send_Byte(dt&0xff); I2C_Wait_Ack(); I2C_Stop(); delay_ms(10); }
C
#include <stdio.h> int main(void) { int operand1 = 0, operand2 = 0; scanf("%d %d", &operand1, &operand2); printf("%d", operand1 * operand2); return 0; }
C
#include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <sys/types.h> #include <sys/socket.h> #include <sys/time.h> #include <netinet/in.h> #include <arpa/inet.h> #include <errno.h> #include <time.h> #include "socket.h" #include "gameplay.h" #ifndef PORT #define PORT y #endif #define MAX_QUEUE 5 int write_to_client(struct client *p, char * msg); void broadcast(struct game_state *game, char *outbuf, int exception_fd); void announce_turn(struct game_state *game); void announce_guess(struct game_state *game, char *name, const char *guess, int fd); void announce_winner(struct game_state *game, struct client *winner); void announce_join(struct game_state *game, struct client *p); void announce_goodbye(struct game_state *game, char *name); void advance_turn(struct game_state *game); int is_gameover(struct game_state *game, struct client *p); void add_player(struct client **top, int fd, struct in_addr addr); void remove_player(struct client **top, int fd); void activate_player(struct game_state *game, struct client **top, struct client *p); void clean_list(struct client **top); int find_network_newline(const char *buf, int n); /*Attempt to write msg to client fd. *If write falls then set client_fd to -1 and return client fd, else return 0 */ int write_to_client(struct client *p, char * msg){ char network_msg[strlen(msg) + 3]; strcpy(network_msg,msg); strcat(network_msg, "\r\n"); if (write(p->fd, network_msg, strlen(network_msg)) != strlen(network_msg)){ printf("Disconnect from %s\n", inet_ntoa(p->ipaddr)); printf("Removing client %d %s\n", p->fd, inet_ntoa(p->ipaddr)); p->fd = -1; return -1; } return 0; } /* Send the message in outbuf to all clients */ void broadcast(struct game_state *game, char *outbuf, int exception_fd){ for(struct client *p = game->head; p != NULL; p = p->next){ if(p->fd != exception_fd && p->fd != -1){ if (write_to_client(p, outbuf) != 0){ announce_goodbye(game, p->name); } } } } void announce_join(struct game_state *game, struct client *p){ //Broadcast new player has joined char join_msg[strlen(p->name) + 15]; strcpy(join_msg, p->name); strcat(join_msg, " has joined."); broadcast(game, join_msg, -1); //Write game status to new player char status_msg[MAX_MSG]; if (write_to_client(p, status_message(status_msg, game)) != 0){ announce_goodbye(game, p->name); } //Tell new player who's turn it is if (game->has_next_turn == p){ if (write_to_client(p, YOUR_TURN) != 0){ advance_turn(game); announce_goodbye(game, p->name); } } else{char turn_msg[16 + strlen(game->has_next_turn->name)]; strcpy(turn_msg, "It's "); strcat(turn_msg, game->has_next_turn->name); strcat(turn_msg, "'s turn."); if (write_to_client(p, turn_msg) != 0){ announce_goodbye(game, p->name); } } } void announce_goodbye(struct game_state *game, char *name){ char goodbye[9 + strlen(name)]; strcpy(goodbye, "Goodbye "); strcat(goodbye, name); broadcast(game, goodbye, -1); } void announce_turn(struct game_state *game){ for(struct client *p = game->head; p != NULL; p = p->next){ if(p == game->has_next_turn && p->fd != -1){ if (write_to_client(p, YOUR_TURN) != 0){ advance_turn(game); announce_goodbye(game, p->name); } else{ char turn_msg[14 + strlen(p->name)]; strcpy(turn_msg, "It's "); strcat(turn_msg, p->name); strcat(turn_msg, "'s turn."); broadcast(game, turn_msg, p->fd); } //Prompt server printf("It's %s's turn\n", game->has_next_turn->name); } } } void announce_winner(struct game_state *game, struct client *p){ if (write_to_client(p, YOU_WIN) != 0){ announce_goodbye(game, p->name); } char loser_msg[18 + strlen(p->name)]; strcpy(loser_msg, "Game Over! "); strcat(loser_msg, p->name); strcat(loser_msg, " wins!"); broadcast(game, loser_msg, p->fd); } void announce_guess(struct game_state *game, char *name, const char *guess, int fd){ char guess_msg[12 + strlen(name)]; strcpy(guess_msg, name); strcat(guess_msg, " guesses: "); strcat(guess_msg, guess); broadcast(game, guess_msg, fd); } /* Move the has_next_turn pointer to the next active client */ void advance_turn(struct game_state *game){ if(game->has_next_turn->next == NULL){ game->has_next_turn = game->head; }else{ game->has_next_turn = game->has_next_turn->next; } if (game->has_next_turn->fd == -1){ game->has_next_turn = NULL; } } /* Checks game is over and broadcasts messages accordingly. * Returns 1 if game is over and 0 is game isn't over. */ int is_gameover(struct game_state *game, struct client *p){ //Check for win or lost. char *won = strchr(game->guess, '-'); if (won == NULL || game->guesses_left == 0){ printf("Evaluating for game over\n"); //Players have Lost. if (game->guesses_left == 0){ broadcast(game, NO_GUESSES, -1); } //Broadcast Word. char answer_msg[14 + strlen(game->word)]; strcpy(answer_msg, "The word was "); strcat(answer_msg, game->word); broadcast(game, answer_msg, -1); //Player has Won. if(won == NULL){ announce_winner(game, p); } return 1; } return 0; } /* The set of socket descriptors for select to monitor. * This is a global variable because we need to remove socket descriptors * from allset when a write to a socket fails. */ fd_set allset; /* Add a client to the head of the linked list */ void add_player(struct client **top, int fd, struct in_addr addr) { struct client *p = malloc(sizeof(struct client)); if (!p) { perror("malloc"); exit(1); } printf("Adding client %s\n", inet_ntoa(addr)); p->fd = fd; p->ipaddr = addr; p->name[0] = '\0'; p->in_ptr = p->inbuf; p->inbuf[0] = '\0'; p->next = *top; *top = p; } /* Removes client from the linked list and closes its socket. * Also removes socket descriptor from allset */ void remove_player(struct client **top, int fd) { struct client **p; for (p = top; *p && (*p)->fd != fd; p = &(*p)->next) ; // Now, p points to (1) top, or (2) a pointer to another client // This avoids a special case for removing the head of the list if (*p) { struct client *t = (*p)->next; //printf("Removing client %d %s\n", fd, inet_ntoa((*p)->ipaddr)); FD_CLR((*p)->fd, &allset); close((*p)->fd); free(*p); *p = t; } else { fprintf(stderr, "Trying to remove fd %d, but I don't know about it\n", fd); } } /* Removes client from the new_players list and adds client to the * head of the active players list. */ void activate_player(struct game_state *game, struct client **top, struct client *p){ //Remove p from new_players list if (*top == p){ *top = p->next; }else{ struct client *curr; for (curr = *top; curr->next != p ; curr = curr->next); curr->next = p->next; } //Add p to head of active list //If current game list is empty if (game->head == NULL){ game->has_next_turn = p; } p->next = game->head; game->head = p; } void clean_list(struct client **top){ for (struct client * p = *top; p != NULL; p = p->next){ if(p->fd == -1){ remove_player(top, p->fd); } } } int main(int argc, char **argv) { int clientfd, maxfd, nready; struct client *p; struct sockaddr_in q; fd_set rset; if(argc != 2){ fprintf(stderr,"Usage: %s <dictionary filename>\n", argv[0]); exit(1); } // Create and initialize the game state struct game_state game; srandom((unsigned int)time(NULL)); // Set up the file pointer outside of init_game because we want to // just rewind the file when we need to pick a new word game.dict.fp = NULL; game.dict.size = get_file_length(argv[1]); init_game(&game, argv[1]); // head and has_next_turn also don't change when a subsequent game is // started so we initialize them here. game.head = NULL; game.has_next_turn = NULL; /* A list of client who have not yet entered their name. This list is * kept separate from the list of active players in the game, because * until the new playrs have entered a name, they should not have a turn * or receive broadcast messages. In other words, they can't play until * they have a name. */ struct client *new_players = NULL; struct sockaddr_in *server = init_server_addr(PORT); int listenfd = set_up_server_socket(server, MAX_QUEUE); // initialize allset and add listenfd to the // set of file descriptors passed into select FD_ZERO(&allset); FD_SET(listenfd, &allset); // maxfd identifies how far into the set to search maxfd = listenfd; //Input buffering variables int nbytes = 0; int end; while (1) { // make a copy of the set before we pass it into select rset = allset; nready = select(maxfd + 1, &rset, NULL, NULL, NULL); if (nready == -1) { perror("select"); continue; } if (FD_ISSET(listenfd, &rset)){ printf("A new client is connecting\n"); clientfd = accept_connection(listenfd); FD_SET(clientfd, &allset); if (clientfd > maxfd) { maxfd = clientfd; } printf("Connection from %s\n", inet_ntoa(q.sin_addr)); add_player(&new_players, clientfd, q.sin_addr); char *greeting = WELCOME_MSG; if(write(clientfd, greeting, strlen(greeting)) == -1) { fprintf(stderr, "Write to client %s failed\n", inet_ntoa(q.sin_addr)); remove_player(&(game.head), p->fd); }; } /* Check which other socket descriptors have something ready to read. * The reason we iterate over the rset descriptors at the top level and * search through the two lists of clients each time is that it is * possible that a client will be removed in the middle of one of the * operations. This is also why we call break after handling the input. * If a client has been removed the loop variables may not longer be * valid. */ int cur_fd; for(cur_fd = 0; cur_fd <= maxfd; cur_fd++) { if(FD_ISSET(cur_fd, &rset)) { // Check if this socket descriptor is an active player for(p = game.head; p != NULL; p = p->next) { if(cur_fd == p->fd) { //TODO - handle input from an active client if( (nbytes = read(p->fd, p->in_ptr, MAX_BUF)) <= 0){ printf("Disconnect from %s\n", inet_ntoa(p->ipaddr)); printf("Removing client %d %s\n", p->fd, inet_ntoa(p->ipaddr)); p->fd = -1; announce_goodbye(&game, p->name); break; } printf("[%i] Read %i bytes\n", p->fd, nbytes); p->in_ptr += nbytes; //If \r\n has been found then handle input. if ((end = find_network_newline(p->inbuf, p->in_ptr - p->inbuf)) != -1 && p->fd != 0){ p->inbuf[end] = '\0'; printf("[%i] Found newline %s\n", p->fd, p->inbuf); //Handle Player Turn if(p == game.has_next_turn){ //Invalid Input if (strlen(p->inbuf) != 1 || p->inbuf[0] < 'a' || p->inbuf[0] > 'z' || game.letters_guessed[p->inbuf[0] - 'a'] == 1){ if(write_to_client(p, INVALID_GUESS) != 0){ announce_goodbye(&game, p->name); advance_turn(&game); announce_turn(&game); break; } //Valid Input }else{ advance_turn(&game); //Incorrect Guess. if(player_guess(&game, p->inbuf[0]) == 0){ printf("Letter %c is not in the word\n", p->inbuf[0]); char miss_msg[21]; strcpy(miss_msg, p->inbuf); strcat(miss_msg, " is not in the word\n"); if (write_to_client(p, miss_msg) != 0){ announce_goodbye(&game, p->name); } } //Broadcast guess. announce_guess(&game, p->name, p->inbuf, p->fd); //If game is over init a new game. if (is_gameover(&game, p)){ printf("New Game\n"); broadcast(&game, NEW_GAME, -1); init_game(&game, argv[1]); } //Broadcast new status message and player turn. char status_msg[MAX_MSG]; broadcast(&game, status_message(status_msg, &game), -1); announce_turn(&game); } //If it is not their turn, clear their buffer tell them its not their turn }else{ if(write_to_client(p, NOT_YOUR_TURN) != 0){ announce_goodbye(&game, p->name); break; } } //RESET THE BUFFER VARIABLE p->in_ptr = p->inbuf; }//End of input handling } }//End of active player handling block. // Check if any new players are entering their names for(p = new_players; p != NULL; p = p->next) { if(cur_fd == p->fd) { // TODO - handle input from an new client who has // not entered an acceptable name. int namebytes; if( (namebytes = read(p->fd, p->in_ptr, MAX_BUF)) <= 0){ printf("Disconnect from %s\n", inet_ntoa(p->ipaddr)); printf("Removing client %d %s\n", p->fd, inet_ntoa(p->ipaddr)); remove_player(&new_players, p->fd); break; } printf("[%i] Read %i bytes\n", p->fd, namebytes); p->in_ptr += namebytes; //Check if \r\n has been found then handle input. int name_end; if ((name_end = find_network_newline(p->inbuf, p->in_ptr - p->inbuf)) != -1 && p->fd != 0){ p->inbuf[name_end] = '\0'; printf("[%i] Found newline %s\n", p->fd, p->inbuf); //Check for valid name if (strlen(p->inbuf) > 1 && unique_name(game.head, p->inbuf)){ strcpy(p->name, p->inbuf); activate_player(&game, &new_players, p); announce_join(&game, p); }else{ if (write_to_client(p, INVALID_NAME) != 0){ remove_player(&new_players, p->fd); break; } } p->in_ptr = p->inbuf; } break; } } } } //Remove all clients with -1 fd. clean_list(&(game.head)); } return 0; } /* * Search the first n characters of buf for a network newline (\r\n). * Return the index of the '\r' of the first network newline, * or -1 if no network newline is found. */ int find_network_newline(const char *buf, int n) { for (int i = 0; i < n; i++){ if(buf[i] == '\r' && buf[i+1] == '\n'){ //Annouce found newline to server return i; } } return -1; }
C
//Sending/ Receiving Data from/to PC to/from Microcontroller Displaying it on LCD #define F_CPU 8000000UL #include<avr/io.h> #include<util/delay.h> void usart_init() { UBRRL=51; UBRRH=0; UCSRB=0x18; UCSRC=0x8e; } void usart_send(char send) { while((UCSRA&0x20)==0); UDR=send; } void usart_string(unsigned char *a) { int i=0; while(a[i]!='\0') { usart_send(a[i]); i++; } } char usart_rec() { while((UCSRA&0x80)==0); return UDR; } int main() { DDRC=0xFF; usart_init(); _delay_ms(10); while(1) { char a=usart_rec(); if(a=='1') { PORTC=0x01; } else if(a=='2') { PORTC=0x02; } else if(a=='3') { PORTC=0x03; } else if(a=='4') { PORTC=0x04; } else if(a=='5') { PORTC=0x05; } else if(a=='6') { PORTC=0x06; } else if(a=='7') { PORTC=0x07; } else if(a=='8') { PORTC=0x08; } else if(a=='a') { PORTC=0xFF; } } }
C
#include <stdio.h> #include <stdlib.h> #include <stddef.h> #define MAX 15 struct data{ char date[MAX]; unsigned int flag; char eigentuemer[MAX]; char password[MAX]; }; int main(void) { struct data newfile = {"testfile",0,"itsme", "believe"}; printf("Vom Anfang zur Strukturvariable flag : %d Bytes\n", offsetof(struct data,flag)); printf("Vom Anfang zur Strukturvariable owner : %d Bytes\n", offsetof(struct data, eigentuemer)); printf("Vom Anfang zur Strukturvariable passwort: %d Bytes\n", offsetof(struct data, password)); return EXIT_SUCCESS; }
C
#include <stdlib.h> #include <stdio.h> #include <string.h> /* In this demo we'll make an array of structures. Like before, we'll create a structure and declare it as "player". Next up, we'll declare an array that will hold 3 "player" structure elements. */ int main (int argc, char* argv) { struct player { char name[32]; char position[32]; char club[32]; }; // Our array of three structs. struct player englandPlayers[3]; /* Let's now initalize our array with some players! At each memory location, we'll be storing a player struct, so by using the array bracket notation, and the struct '.' notation, we can move to each element in the array and set each member variable to some player stats. */ strcpy(englandPlayers[0].name, "Harry Kane"); strcpy(englandPlayers[0].position, "FW"); strcpy(englandPlayers[0].club, "Tottenham Hotspur"); strcpy(englandPlayers[1].name, "Raheem Sterling"); strcpy(englandPlayers[1].position, "MDF"); strcpy(englandPlayers[1].club, "Manchester City"); strcpy(englandPlayers[2].name, "Harry Maguire"); strcpy(englandPlayers[2].position, "DEF"); strcpy(englandPlayers[2].club, "Manchester United"); printf("A Selection of England Players:\n"); // Now we can iterate over our array and print the stats of each player! for (int i = 0; i < 3; i++) { printf("Player: %s (Position: %s, Club: %s)\n", englandPlayers[i].name, englandPlayers[i].position, englandPlayers[i].club); } /* Alternatively, we could initalize our array of structs using value initialization in conjunction with the curly brace array initalization. The first struct we initalize has index 0, the second index 1 and so on so forth! This saves on having to explicitly reference an index and assign each element's struct members manually! */ struct player curlyBraceEnglandPlayers[3] = { {"Harry Kane", "FW", "Tottenham Hotspur"}, {"Raheem Sterling", "MDF", "Manchester City"}, {"Harry Maguire", "DEF", "Manchester United"} }; printf("\n\nA Selection of England Players (Alternate Initalization):\n"); for (int i = 0; i < 3; i++) { printf("Player: %s (Position: %s, Club: %s)\n", curlyBraceEnglandPlayers[i].name, curlyBraceEnglandPlayers[i].position, curlyBraceEnglandPlayers[i].club); } return 0; }
C
#include <stdlib.h> #include <unistd.h> #include <stdio.h> #include <string.h> #include <assert.h> #include <stdint.h> #include <pthread.h> /* TODO: 1) queue of links (parsers to downloaders). Fixed size 2) queue of pages (downloaders to parsers). Unbounded 3) hash set 4) waiting until done QUEUE OF LINKS parser waits when queue is full (need cond variable) downloader waits when queue is empty (need another cond variable) need mutex (to make sure we're concurrently accessing data structures) QUEUE OF PAGE (unbounded) parser waits when queue is empty (need cond variable) downloader waits when never (don't need cond variable) need mutex WAITING UNTIL DONE - [NEED TO DO THIS] have to track how much total work in system - increment work variable when put on link queue, decrement work when put on page queue - (count the work for b before I consider a to be done) - add work for all of the links in a before decrementing and saying a is done - 1 cond var, 1 mutex [DONE]QUEUE OF LINKS 2 cond vars, 1 mutex [DONE]QUEUE OF PAGE (unbounded) 1 cond vars, 1 mutex HASH SET 1 mutex WAITING UNTIL DONE 1 cond vars, 1 mutex */ // SET UP QUEUE DATA STRUCTURE typedef struct node_t { char *pagedata; struct node_t *next; struct node_t *prev; char* fromlink; char* pagelink; } node_t; typedef struct queue_t { node_t *front; node_t *end; int count; int max; pthread_mutex_t mutex; pthread_cond_t condp; pthread_cond_t condd; } queue_t; queue_t links; queue_t pages; // WAITING UNTIL DONE typedef struct work_t { int count; pthread_mutex_t mutex; pthread_cond_t cond; } work_t; work_t work; //hash function is from: //http://www.ks.uiuc.edu/Research/vmd/doxygen/hash_8c-source.html #undef get16bits #if (defined(__GNUC__) && defined(__i386__)) || defined(__WATCOMC__) || defined(_MSC_VER) || defined (__BORLANDC__) || defined (__TURBOC__) #define get16bits(d) (*((const uint16_t *) (d))) #endif #if !defined (get16bits) #define get16bits(d) ((((uint32_t)(((const uint8_t *)(d))[1])) << 8)+(uint32_t)(((const uint8_t *)(d))[0]) ) #endif int totalLinks = 0; uint32_t* visitedLinks = NULL; uint32_t SuperFastHash (const char * data, int len) { uint32_t hash = len, tmp; int rem; if (len <= 0 || data == NULL) return 0; rem = len & 3; len >>= 2; /* Main loop */ for (;len > 0; len--) { hash += get16bits (data); tmp = (get16bits (data+2) << 11) ^ hash; hash = (hash << 16) ^ tmp; data += 2*sizeof (uint16_t); hash += hash >> 11; } /* Handle end cases */ switch (rem) { case 3: hash += get16bits (data); hash ^= hash << 16; hash ^= ((signed char)data[sizeof (uint16_t)]) << 18; hash += hash >> 11; break; case 2: hash += get16bits (data); hash ^= hash << 11; hash += hash >> 17; break; case 1: hash += (signed char)*data; hash ^= hash << 10; hash += hash >> 1; } /* Force "avalanching" of final 127 bits */ hash ^= hash << 3; hash += hash >> 5; hash ^= hash << 4; hash += hash >> 17; hash ^= hash << 25; hash += hash >> 6; return hash; } void initialize(uint32_t **linkArray){ *linkArray=malloc(sizeof(uint32_t)); if(*linkArray==NULL) { printf("Malloc error\n"); return; } (*linkArray)[0]=0; } void add(uint32_t **linkArray, uint32_t newLink){ static int sizeCount = 0; totalLinks = sizeCount; sizeCount++; uint32_t *temp; temp=realloc(*linkArray, (sizeCount+1) * sizeof(uint32_t)); if(temp==NULL) { printf("Realloc error!"); return; } *linkArray = temp; (*linkArray)[sizeCount] = newLink; } // Pointers to the callback functions char *(*fetch_ptr)(char *url); void (*edge_ptr)(char *from, char *to); // Adds node to the end of the queue void enqueue(node_t *new_node, queue_t *queue) { if (queue->count == 0){ new_node->next = NULL; queue->front = new_node; queue->end = new_node; } else { queue->end->next = new_node; queue->end = new_node; } (queue->count)++; } // Removes the node from the front of the queue node_t *dequeue(queue_t *queue) { struct node_t *rem_node = malloc(sizeof(node_t)); rem_node = queue->front; rem_node->pagedata = queue->front->pagedata; rem_node->pagelink = queue->front->pagelink; if (queue->count == 0){ return NULL; } else if (queue->count == 1){ queue->front = NULL; queue->end = NULL; queue->count = 0; } else { queue->front = queue->front->next; queue->count--; } return rem_node; } // increment work void increment_work(){ pthread_mutex_lock(&work.mutex); work.count++; pthread_cond_signal(&work.cond); pthread_mutex_unlock(&work.mutex); } // decrement work void decrement_work(){ pthread_mutex_lock(&work.mutex); while(work.count < 0){ pthread_cond_wait(&work.cond, &work.mutex); } work.count--; pthread_mutex_unlock(&work.mutex); } // Adds the page to the queue of pages void download_pages ( node_t * ptr){ pthread_mutex_lock(&pages.mutex); // add page to the queue of pages enqueue(ptr,&pages); // signal parse_pages pthread_cond_signal(&pages.condp); pthread_mutex_unlock(&pages.mutex); } //STARTER FOR DOWNLOADERS // Remove links from the queue of links, adds to the queue of pages void *download_links (void *ptr){ do{ pthread_mutex_lock(&links.mutex); // downloader needs to wait while the queue is empty while (links.count == 0){ pthread_cond_wait(&links.condd, &links.mutex); } // remove the link from the front of the queue node_t *tmp = dequeue(&links); pthread_cond_signal(&links.condp); pthread_mutex_unlock(&links.mutex); // !!! fetch outside of the lock! char* page= fetch_ptr(tmp->pagelink); tmp->pagedata = page; // add tmp to the pages queue download_pages(tmp); }while(work.count > 0); exit(0); //pthread_exit(0); } // Adds links to the queue of links void parse_links(node_t *ptr){ pthread_mutex_lock(&links.mutex); // parser needs to wait while the queue is full while (links.count == links.max){ pthread_cond_wait(&links.condp, &links.mutex); } // add to the link to the end of the queue enqueue(ptr,&links); // signal download_links pthread_cond_signal(&links.condd); pthread_mutex_unlock(&links.mutex); } // called by parse char ** parsePage(char* page, char** returnArray, int* numberOfLinks) { char * saveptr; char * saveptr2; char s[2] = " "; char n[2] = "\n"; int i = 0; int linkLength = 0; char *token = strtok_r(page,n,&saveptr); char *token2 = strdup(token); token2 = strtok_r(token, s, &saveptr2); // gets the line up to new line while (token != NULL) { // parses out the words in the lines while (token2 != NULL) { // if the word == 'link:' - ***it's probably possible for link to // show up elsewhere in the line if ((token2[0] == 'l') && (token2[1] == 'i') && (token2[2] == 'n') && (token2[3] == 'k') && (token2[4] == ':')) { // if there is something in the line after 'link:' if (strlen(token2)>5){ linkLength = strlen(token2) - 5 + 1; returnArray[i] = malloc(linkLength * sizeof(char)); // add what's after "link:" to the return array int j = 0; for (j = 0; j <= (linkLength - 1); j++) { returnArray[i][j] = token2[5+j]; } // add terminating char returnArray[i][j++] = '\0'; i++; } } token2 = strtok_r(NULL, s, &saveptr2); } if (token != NULL) { token = strtok_r(NULL, n, &saveptr); } if ((token == NULL) && (token2 == NULL)) { break; } else { token2 = strdup(token); } } *numberOfLinks = i; return returnArray; } // Parses the page and removes the page from the // queue of pages void parse(node_t *node ){ char *page = node->pagedata; char *destLink; char** linkArray = malloc(sizeof(char) * 100); int* numberOfLinks = malloc(sizeof(int)); int alreadyDone = 0; int testLength = strlen(node->pagelink); uint32_t testHash = SuperFastHash(node->pagelink, testLength); int j=0; for (j = 0; j <= totalLinks; j++) { if (testHash == visitedLinks[j]) { alreadyDone = 1; } } if (alreadyDone != 1){ add(&visitedLinks, testHash); } linkArray = (char**) parsePage(page, linkArray, numberOfLinks); visitedLinks[totalLinks] = testHash; int i=0; for (i = 0; i <= *numberOfLinks; i++) { if (linkArray[i] != NULL) { // new node to store the new link node_t *newnode = malloc(sizeof(node_t)); newnode->fromlink = node->pagelink; destLink = strdup(linkArray[i]); newnode->pagelink = destLink; edge_ptr(node->pagelink, destLink); // if we haven't already visited this link // yet then add work and add the node to the // queue of links if (alreadyDone != 1){ increment_work(); parse_links(newnode); } } } decrement_work(); } //STARTER FOR PARSERS // removes page from queue of pages, parses the page, and gives // the link to the queue of links void *parse_pages(void* ptr){ do{ pthread_mutex_lock(&pages.mutex); // parser waits when the queue of pages is empty while (pages.count == 0){ pthread_cond_wait(&pages.condp, &pages.mutex); } // remove the page from the front of the queue node_t *tmp = dequeue(&pages); pthread_mutex_unlock(&pages.mutex); // parse the info on the page // parse calls parse_links parse(tmp); }while (work.count > 0); exit(0); //pthread_exit(0); } int crawl(char *start_url, int download_workers, int parse_workers, int queue_size, char * (*_fetch_fn)(char *url), void (*_edge_fn)(char *from, char *to)) { fetch_ptr = _fetch_fn; edge_ptr = _edge_fn; char *page = fetch_ptr(start_url); node_t *newnode = malloc(sizeof(node_t)); newnode->pagedata = page; newnode->pagelink = start_url; newnode->fromlink = malloc(sizeof(char)); assert(page != NULL); // queue of links links.front = NULL; links.end = NULL; links.count = 0; links.max = queue_size; pthread_mutex_init(&links.mutex, NULL); pthread_cond_init(&links.condp, NULL); pthread_cond_init(&links.condd, NULL); // queue of pages pages.front = NULL; pages.end = NULL; pages.count = 0; pages.max = -1; pthread_mutex_init(&pages.mutex, NULL); pthread_cond_init(&pages.condp, NULL); // work - for 'waiting until done' work.count = 0; pthread_mutex_init(&work.mutex, NULL); pthread_cond_init(&work.cond, NULL); // used with hashing initialize(&visitedLinks); // maybe we should handle the first page, first? before creating threads? enqueue(newnode,&pages); // create threads to do work // The downloaders will be responsible for fetching new pages // from the Internet. The parsers will scan the downloaded pages for new links. pthread_t downloader[download_workers], parser[parse_workers]; int i,j; for (j=0; j < parse_workers; j++){ if (pthread_create(&parser[j], NULL, parse_pages, NULL)!=0){ printf("issue creating parser thread\n"); } } for (i=0; i < download_workers; i++){ if ( pthread_create(&downloader[i], NULL, download_links, NULL)!=0){ printf("issue creating downloader thread\n"); } } // join the threads,.. we quit out without doing much without these calls for (j=0; j < parse_workers; j++){ pthread_join(parser[j], NULL ); } for (i=0; i < download_workers; i++){ pthread_join(downloader[i], NULL); } free(page); return 0; // return 0 if succeeds }
C
/****************************************************************************** * @file utilities.c * @author Zhangsf * @version V1.0.0 * @date 01-October-2016 * @brief is the Utilities ****************************************************************************** */ #include <stdlib.h> #include <stdio.h> #include <stdint.h> #include <ctype.h> #include "utilities.h" #include "hw_eeprom.h" static const char HexTable[]="0123456789ABCDEF"; static const char Sep = ':'; /*! * Redefinition of rand() and srand() standard C functions. * These functions are redefined in order to get the same behavior across * different compiler toolchains implementations. */ // Standard random functions redefinition start #define RAND_LOCAL_MAX 2147483647L static uint32_t next = 1; int32_t rand1( void ) { return ( ( next = next * 1103515245L + 12345L ) % RAND_LOCAL_MAX ); } void srand1( uint32_t seed ) { next = seed; } // Standard random functions redefinition end int32_t randr( int32_t min, int32_t max ) { return ( int32_t )rand1( ) % ( max - min + 1 ) + min; } void memcpy1( uint8_t *dst, const uint8_t *src, uint16_t size ) { while( size-- ) { *dst++ = *src++; } } void memcpyr( uint8_t *dst, const uint8_t *src, uint16_t size ) { dst = dst + ( size - 1 ); while( size-- ) { *dst-- = *src++; } } void memset1( uint8_t *dst, uint8_t value, uint16_t size ) { while( size-- ) { *dst++ = value; } } int8_t Nibble2HexChar( uint8_t a ) { if( a < 10 ) { return '0' + a; } else if( a < 16 ) { return 'A' + ( a - 10 ); } else { return '?'; } } unsigned long SimpleStrtoul(const char *cp, char **endp, unsigned int Base) { unsigned long Result = 0; unsigned long Value; if (*cp == '0') { cp++; if ((*cp == 'x') && isxdigit(cp[1])) { Base = 16; cp++; } if (!Base) { Base = 8; } } if (!Base) { Base = 10; } while (isxdigit(*cp) && (Value = isdigit(*cp) ? *cp-'0' : (islower(*cp) ? toupper(*cp) : *cp)-'A'+10) < Base) { Result = Result*Base + Value; cp++; } if (endp) { *endp = (char *)cp; } return Result; } void Hex2Str(const unsigned char *Hex, char *Str, int Num) { int i; int j; for (i=0, j=0; i < Num; i++) { Str[j++] = HexTable[(Hex[i]&0xf0) >> 4]; Str[j++] = HexTable[(Hex[i]&0x0f)]; Str[j++] = Sep; } if (j > 0) { Str[j-1] = '\0'; } } void Str2Hex(const char *Str, unsigned char *Hex, int Num) { char *End; int i; for (i = 0; i < Num; ++i) { Hex[i] = Str ? SimpleStrtoul(Str, &End, 16) : 0; if (Str) { Str = (*End) ? End + 1 : End; } } }
C
#include<stdio.h> int A[100]; int sizeA = 0; void swap(int *a, int *b){ int temp = *a; *a = *b; *b = temp; } void selectionSort(int arr[], int size){ int min_indx; for(int i=0; i<size-1; i++){ min_indx = i; for(int j = i+1; j<size; j++){ if(arr[j]<arr[min_indx]){ min_indx = j; } } swap(&arr[min_indx],&arr[i]); } } void takeInput(){ printf("Enter size: "); scanf("%d",&sizeA); printf("Enter data: "); for(int i=0; i<sizeA; i++){ scanf("%d",&A[i]); } } void printArr(int arr[], int size){ printf("\nThe Array is: "); for(int i=0; i< size; i++){ printf("%d ",arr[i]); } printf("\n"); } int main(){ takeInput(); printf("\nArray Before Sorting: "); printArr(A,sizeA); selectionSort(A,sizeA); printf("\nArray After Sorting: "); printArr(A,sizeA); }
C
/** Program to find LCM of two numbers **/ #include<stdio.h> #include<math.h> int main() { int i,num1,num2,max,lcm=1; printf("Enter first number" ); scanf("%d",&num1 ); printf("Enter Second number" ); scanf("%d",&num2 ); max=num1>num2 ?num1:num2; i=max; while (1) { if (i%num1==0 && i%num2==0) { lcm=i; break; } i+=max; } printf("%d",lcm ); getch(); }
C
#include "gme_funcs.h" #include "gme_helpers.h" #include "util.h" extern VALUE cEmulator; extern VALUE eGenericException; extern VALUE eInvalidFile; extern VALUE eTrackNotStarted; /* * Opens a new input file. * Returns a new instance of GME::Emulator. * Accepts options in a hash (2nd argument). */ VALUE gme_ruby_open(int argc, VALUE* argv, VALUE self) { Music_Emu* emulator; int c_sample_rate; char* c_path; // internal buffer short* buffer; int buffer_length; // options hash VALUE options; // use the first (mandatory) argument, as path to file VALUE string = StringValue(argv[0]); c_path = RSTRING_PTR(string); // use the second argument, if present, as the options hash VALUE temp; if(argc >= 2){ temp = rb_check_convert_type(argv[1], T_HASH, "Hash", "to_hash"); if(!NIL_P(temp)) options = temp; else options = rb_hash_new(); } else { options = rb_hash_new(); } // set sample rate from options hash VALUE sample_rate = rb_hash_aref(options, ID2SYM(rb_intern("sample_rate"))); if(!NIL_P(sample_rate)) { c_sample_rate = FIX2INT(sample_rate); } else { // default value c_sample_rate = 44100; } // set buffer length from options hash VALUE buffer_len = rb_hash_aref(options, ID2SYM(rb_intern("buffer_length"))); if(!NIL_P(buffer_len)) { buffer_length = FIX2INT(buffer_len); } else { // default value buffer_length = 2048; } // opens the specified file handle_error(gme_open_file(c_path, &emulator, c_sample_rate), eInvalidFile); // creates a new instance of GME::Emulator, as a wrapper around Music_Emu VALUE new_instance = Data_Wrap_Struct(cEmulator, 0, gme_ruby_emu_free, emulator); // allocates memory for the internal buffer buffer = (short*) malloc(sizeof(short) * buffer_length); // and saves a reference for later use (HACK?) rb_iv_set(new_instance, "@internal_buffer", LONG2NUM((long)buffer)); rb_iv_set(new_instance, "@internal_buffer_length", INT2NUM(buffer_length)); // saves the sample rate value for future reference rb_iv_set(new_instance, "@sample_rate", INT2FIX(c_sample_rate)); // sets the track count int track_count = gme_track_count(emulator); rb_iv_set(new_instance, "@track_count", INT2FIX(track_count)); // no track has been started rb_iv_set(new_instance, "@track_started", Qfalse); // returns the new instance of GME::Emulator return new_instance; } /* * Releases all the resources allocated in Emulator#open. * The object is unusable after this call. * TODO: mark valid and invalid objects and raise exceptions if appropiate * instead of simply failing or generating a segfault. */ VALUE gme_ruby_close(VALUE self) { Music_Emu* emulator; short* c_buffer; Data_Get_Struct(self, Music_Emu, emulator); // recovers a pointer to the internal buffer c_buffer = (short*) NUM2LONG(rb_iv_get(self, "@internal_buffer")); // releases the memory for the buffer if(c_buffer != NULL) free(c_buffer); // release the memory for the emulator struct // TODO: Do we really need this? why the gc isn't releasing this memory? // Apparently, uncommenting this line causes a double free error. // So, the GC actually calls it, but still there are memory leaks... // gme_ruby_emu_free(emulator); return Qnil; } /* * Starts a track. * If a track is not specified, uses track number 0. * Returns the number of the track started. */ VALUE gme_ruby_start_track(int argc, VALUE* argv, VALUE self) { Music_Emu* emulator; int c_track; gme_info_t* info; Data_Get_Struct(self, Music_Emu, emulator); // uses the first argument, if present, as track number if(argc >= 1) { c_track = FIX2INT(argv[0]); } else { // default value c_track = 0; } // gets the info on the track handle_error(gme_track_info(emulator, &info, c_track), eGenericException); // Fills the info hash VALUE info_hash = rb_hash_new(); rb_hash_aset(info_hash, ID2SYM(rb_intern("play_length")), INT2FIX(info->play_length)); rb_hash_aset(info_hash, ID2SYM(rb_intern("length")), INT2FIX(info->length)); rb_hash_aset(info_hash, ID2SYM(rb_intern("intro_length")), INT2FIX(info->intro_length)); rb_hash_aset(info_hash, ID2SYM(rb_intern("loop_length")), INT2FIX(info->loop_length)); rb_hash_aset(info_hash, ID2SYM(rb_intern("system")), rb_str_new2(info->system)); rb_hash_aset(info_hash, ID2SYM(rb_intern("game")), rb_str_new2(info->game)); rb_hash_aset(info_hash, ID2SYM(rb_intern("song")), rb_str_new2(info->song)); rb_hash_aset(info_hash, ID2SYM(rb_intern("author")), rb_str_new2(info->author)); rb_hash_aset(info_hash, ID2SYM(rb_intern("copyright")), rb_str_new2(info->copyright)); rb_hash_aset(info_hash, ID2SYM(rb_intern("comment")), rb_str_new2(info->comment)); rb_hash_aset(info_hash, ID2SYM(rb_intern("dumper")), rb_str_new2(info->dumper)); rb_iv_set(self, "@info", info_hash); gme_free_info(info); // starts the track handle_error(gme_start_track(emulator, c_track), eGenericException); // a track has been started... rb_iv_set(self, "@track_started", Qtrue); // returns the track number started return INT2FIX(c_track); } /* * Plays some samples, and returns them as an array */ VALUE gme_ruby_get_samples(VALUE self) { Music_Emu* emulator; short* c_buffer; int c_buffer_len; raise_if_track_has_not_started(self); Data_Get_Struct(self, Music_Emu, emulator); get_internal_buffer(self, &c_buffer, &c_buffer_len); // plays the file, returning the specified number of samples handle_error(gme_play(emulator, c_buffer_len, c_buffer), eGenericException); // creates a ruby string, containing the buffer content (generated samples) VALUE ruby_string = rb_str_new((const char*)c_buffer, c_buffer_len * sizeof(short)); // returns the played samples return ruby_string; } /* * Plays the track 0 of the input file, * and writes in the specified (Ruby) output file. */ VALUE gme_ruby_play_to_file(VALUE self, VALUE file) { int buffer_size = 1024; // hardcoded buffer size (TODO?) short* buffer; FILE* stdio_file; Music_Emu* emulator; // plays track 0 // TODO: receive the track to play as an argument int track = 0; raise_if_invalid_file(file); stdio_file = get_stdio_pointer(file); // allocates memory for the buffer buffer = (short*) malloc(buffer_size * sizeof(short)); Data_Get_Struct(self, Music_Emu, emulator); // starts track rb_funcall(self, rb_intern("start_track"), 1, INT2FIX(track)); // gets the play length of the track from the info hash VALUE info_hash = rb_iv_get(self, "@info"); int play_length = FIX2INT(rb_hash_aref(info_hash, ID2SYM(rb_intern("play_length")))); // plays the track completely while(gme_tell(emulator) < play_length) { handle_error(gme_play(emulator, buffer_size, buffer), eGenericException); write_samples(stdio_file, buffer_size, buffer); fflush(stdio_file); } // releases the memory of the buffer free(buffer); return Qnil; } /* * Returns true if a track has been started * and false in other cases. */ VALUE gme_ruby_track_started(VALUE self) { VALUE track_started = rb_iv_get(self, "@track_started"); if(RTEST(track_started)) return Qtrue; return Qfalse; } /* * Returns the number of milliseconds played since the start of the track. */ VALUE gme_ruby_tell(VALUE self) { Music_Emu* emulator; int milliseconds; Data_Get_Struct(self, Music_Emu, emulator); // gets number of millisecons played milliseconds = gme_tell(emulator); return INT2FIX(milliseconds); } /* * Returns true if the track has ended * and false in other cases */ VALUE gme_ruby_track_ended(VALUE self) { Music_Emu* emulator; raise_if_track_has_not_started(self); Data_Get_Struct(self, Music_Emu, emulator); // checks if the track has ended int track_ended = gme_track_ended(emulator); if(track_ended) return Qtrue; return Qfalse; } /* * Sets whether or not to disable automatic end of track detection * and skipping at the beginning. */ VALUE gme_ruby_ignore_silence(VALUE self, VALUE ignore) { Music_Emu* emulator; Data_Get_Struct(self, Music_Emu, emulator); // if the parameter 'ignore' is true, then ignore the automatic // handling of silences if(RTEST(ignore)) gme_ignore_silence(emulator, 1); else gme_ignore_silence(emulator, 0); return Qnil; } /* * Sets the time in milliseconds to start fading the track. */ VALUE gme_ruby_set_fade(VALUE self, VALUE milliseconds) { Music_Emu* emulator; Data_Get_Struct(self, Music_Emu, emulator); gme_set_fade(emulator, FIX2INT(milliseconds)); return Qnil; } /* * Plays the started track to the specified file. * Optionally, one can indicate the number of samples to be played * (given that the buffer allocated previuosly is long enough). */ VALUE gme_ruby_play(int argc, VALUE* argv, VALUE self) { Music_Emu* emulator; int c_number_of_samples; VALUE options; // options hash VALUE file; FILE* stdio_file; short* c_buffer; int c_buffer_len; Data_Get_Struct(self, Music_Emu, emulator); // file as the first argument file = argv[0]; raise_if_invalid_file(file); stdio_file = get_stdio_pointer(file); raise_if_track_has_not_started(self); // use the second argument, if present, as the options hash VALUE temp; if(argc >= 2){ temp = rb_check_convert_type(argv[1], T_HASH, "Hash", "to_hash"); if(!NIL_P(temp)) options = temp; else options = rb_hash_new(); } else { options = rb_hash_new(); } get_internal_buffer(self, &c_buffer, &c_buffer_len); // determine the maximum number of samples to play given the buffer size // (recall that buffer was allocated as an array of short) int max_samples = c_buffer_len; // sets the number of samples to play VALUE samples = rb_hash_aref(options, ID2SYM(rb_intern("samples"))); if(!NIL_P(samples) && FIX2INT(samples) > 0 && FIX2INT(samples) <= max_samples) { c_number_of_samples = FIX2INT(samples); } else { // default, the maximum number of samples permitted by the allocated buffer c_number_of_samples = max_samples; } // plays the file, getting the specified number of samples handle_error(gme_play(emulator, c_number_of_samples, c_buffer), eGenericException); // writes the samples to the file write_samples(stdio_file, c_number_of_samples, c_buffer); fflush(stdio_file); // returns the number of samples return INT2FIX(c_number_of_samples); } /* * Inserts the specified milliseconds of silence in a file. */ VALUE gme_ruby_play_silence(VALUE self, VALUE file, VALUE milliseconds) { Music_Emu* emulator; FILE* stdio_file; int samples_to_write; Data_Get_Struct(self, Music_Emu, emulator); raise_if_invalid_file(file); stdio_file = get_stdio_pointer(file); // gets the original sample rate specified for the emulator int sample_rate = FIX2INT(rb_iv_get(self, "@sample_rate")); samples_to_write = sample_rate * (FIX2INT(milliseconds) / 1000); // writes a number of 0's as silence // (4 in the next calculation because samples are 2 bytes and there are 2 channels) int i; for(i=0; i <(samples_to_write * 4); i++) { fputc(0, stdio_file); } fflush(stdio_file); return Qnil; }
C
#include <stdio.h> #include <assert.h> #include <pthread.h> #include "mythreads.h" static int counter = 0; void *mythread(void *arg){ int i; for(i = 0;i < 1e7;i++) counter++; return NULL; } int main(int argc, char *argv[]){ pthread_t p1, p2; printf("main: begin\n"); Pthread_create(&p1, NULL, mythread, "A"); Pthread_create(&p2, NULL, mythread, "B"); Pthread_join(p1, NULL); Pthread_join(p2, NULL); printf("counter = %d\n", counter); printf("main: end\n"); return 0; }
C
/** * @file * @brief Handle and generate names and IDs */ #pragma once #include "../lickdir.h" /** * @brief determine if the given ID is valid * @param id the ID to check * @param lick the lick directory * @param install_path the drive or path to install under * @return 1 if the ID is valid; 0 if it is not valid */ int is_valid_id(const char *id, lickdir_t *lick, const char *install_path); /** * @brief generate a valid ID from an ISO path * * Given an ISO path name, takes the base name of the ISO without the .iso * extension, then converts any invalid characters to dashes. If this ID * is used, appends a number, from 2 to 100. If a valid ID has still not * been found, returns NULL. * * @param iso the ISO path * @param lick the lick directory * @param install_path the drive or path to install under * @return an ID, or NULL if a valid ID could not be created */ char *gen_id(const char *iso, lickdir_t *lick, const char *install_path); /** * @brief generate a human-readable name from an ISO path * * Given an ISO path name, takes the base name of the ISO without the .iso * extension, then converts any dashes and underscores to spaces. * * @param iso the ISO path * @return a human-readable name */ char *gen_name(const char *iso);
C
/* auther: C.H King * buildtime: 2013/4/30 */ #include <stdio.h> #define MAXN 30000 int fa[MAXN]; void init () { int i; fa[0] = 1, fa[1] = 1; for (i = 2; i < MAXN; ++ i){ fa[i] = (fa[i-1] + fa[i-2])%10000; } } int main () { int t, n; scanf ("%d", &t); init (); while (t --){ scanf ("%d", &n); n %= MAXN; printf ("%d\n", fa[n+1]); } }
C
#include <stdio.h> #include <stdlib.h> int main(int argc, char** argv) { long int dec, remainder, quotient; int binaryNumber[100], i = 1, j; printf("decimal = "); scanf("%lu", &dec); quotient = dec; while (quotient != 0) { binaryNumber[i++] = quotient % 2; quotient = quotient / 2; } printf("binary = "); for (j = i - 1; j > 0; j--) { printf("%d", binaryNumber[j]); } return (EXIT_SUCCESS); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* collect_addr.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: fgarault <fgarault@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/09/28 15:43:14 by fgarault #+# #+# */ /* Updated: 2020/09/29 18:24:42 by fgarault ### ########.fr */ /* */ /* ************************************************************************** */ #include "asm.h" int get_label(t_code *code_tab, char *label) { t_code *tab; tab = code_tab; while (tab) { if (!ft_strcmp(label, tab->label)) return (tab->mem_pos); tab = tab->next; } return (-1); } void put_addr(t_args *arg, t_code *tab, int cur_pos) { if (arg->reg) itob(arg->hex, arg->reg, arg->size); else if (arg->ind) { if (arg->ind[0] == LABEL_CHAR) itob(arg->hex, (get_label(tab, &arg->ind[1]) - cur_pos), arg->size); else itob(arg->hex, ft_atoi(arg->ind), arg->size); } else if (arg->dir) { if (arg->dir[1] == LABEL_CHAR) itob(arg->hex, (get_label(tab, &arg->dir[2]) - cur_pos), arg->size); else itob(arg->hex, ft_atoi(&arg->dir[1]), arg->size); } } void get_addr(t_code *code_tab) { t_code *tab; t_instruction *instr; t_args *arg; tab = code_tab; while (tab) { instr = tab->instr; while (instr) { arg = instr->args; while (arg) { put_addr(arg, code_tab, instr->mem_pos); arg = arg->next; } instr = instr->next; } tab = tab->next; } }
C
#include <mpi.h> #include <stdio.h> #include "field_match.h" #include "player_match.h" /** * Entry point of the application * @param argc [description] * @param argv [description] * @return [description] */ int main(int argc, char *argv[]) { int rank, processes; MPI_Init(&argc, &argv); MPI_Comm_rank(MPI_COMM_WORLD, &rank); MPI_Comm_size(MPI_COMM_WORLD, &processes); if (processes != 34) { printf("There must be exactly 34 processes!\n"); MPI_Finalize(); return 0; } if (rank < 12) { // field process field_main(rank); } else { // player process player_main(rank); } MPI_Finalize(); return 0; }
C
/** * @Author: la-montagne * @Date: 2019-07-17T13:17:52+02:00 * @Last modified by: la-montagne * @Last modified time: 2019-07-17T13:57:55+02:00 */ #include <stdlib.h> void free_vars(char *a, char *b) { if (a != NULL) free(a); if (b != NULL) free(b); } void free_tabs(char **tab) { if (!tab || !tab[0]) return; for (int i = 0; tab[i] != NULL; i++) free(tab[i]); free(tab); }
C
//0 directly to 123 #include <stdio.h> #include <stdlib.h> #include <stdbool.h> #define N_NODES 2000 #define N_TO_REACH 123 typedef struct { int label; bool visited; } Vertex; //stack variables int stack[N_NODES]; int top = -1; int counter = -1; int bestSolution = 999999; int lineCounter = 0; //graph variables //array of vertices Vertex lstVertices[N_NODES]; //adjacency matrix int adjMatrix[N_NODES][N_NODES]; //vertex count int vertexCount = 0; //stack functions void push(int item) { stack[++top] = item; } int pop() { return stack[top--]; } int peek() { return stack[top]; } bool isStackEmpty() { return top == -1; } //graph functions //add vertex to the vertex list void addVertex(int label) { Vertex vertex; vertex.label = label; vertex.visited = false; lstVertices[vertexCount++] = vertex; } //add edge to edge array void addEdge(int start, int end) { adjMatrix[start][end] = 1; // adjMatrix[end][start] = 1; } //display the vertex void displayVertex(int vertexIndex) { printf("%03d ", lstVertices[vertexIndex].label); } //get the adjacent unvisited vertex int getAdjUnvisitedVertex(int vertexIndex, int baseCount) { int i; for (i = 0; i < vertexCount; i++) { if (adjMatrix[vertexIndex][i] == 1) { if (lstVertices[i].visited == false) { return i; } if (lstVertices[i].label == N_TO_REACH) { // printf("baseCount=%d, best=%d", baseCount+1, bestSolution); if (baseCount+1 < bestSolution) { bestSolution = baseCount+1; if (baseCount == 0) { displayVertex(0); } displayVertex(i); } } } } return -1; } void depthFirstSearch() { int i; //mark first node as visited lstVertices[0].visited = true; // //display the vertex // displayVertex(0); //push vertex index in stack push(0); int pathName = 1; printf("Caminho %d\n", pathName); while (!isStackEmpty()) { //get the unvisited vertex of vertex which is at top of the stack // printf("top=%d\n", top); int unvisitedVertex = getAdjUnvisitedVertex(peek(), top); //no adjacent vertex found if (unvisitedVertex == -1) { pop(); if (top == 0) { pathName++; printf("\n\nCaminho %d\n", pathName); } } else { lineCounter++; if (lstVertices[unvisitedVertex].label == N_TO_REACH) { if (top+1 < bestSolution) { bestSolution = top+1; } } if (top == 0) { displayVertex(0); } if (lineCounter > 20) { lineCounter = 0; printf(" -> \n->"); } lstVertices[unvisitedVertex].visited = true; displayVertex(unvisitedVertex); push(unvisitedVertex); } } //stack is empty, search is complete, reset the visited flag for (i = 0; i < vertexCount; i++) { lstVertices[i].visited = false; } } int main() { int i, j; for (i = 0; i < N_NODES; i++) { for (j = 0; j < N_NODES; j++) // matrix to 0 adjMatrix[i][j] = 0; } // now create edge from 0 to N_TO_REACH label vertex ///JJJ Goes from start to finish directly. addEdge(0, N_TO_REACH); // Creates relation 0 -> N_TO_REACH addEdge(0, 1); addEdge(1, 2); addEdge(2, 3); addEdge(3, 4); addEdge(4, 5); addEdge(5, 6); addEdge(6, 7); addEdge(7, 8); addEdge(8, 9); addEdge(9, 10); addEdge(10, 11); addEdge(11, 12); addEdge(12, 13); addEdge(13, 14); addEdge(14, 15); addEdge(15, 16); addEdge(16, 17); addEdge(17, 18); addEdge(18, 19); addEdge(19, 20); addEdge(20, 21); addEdge(21, 22); addEdge(22, 23); addEdge(23, 24); addEdge(24, 25); addEdge(25, 26); addEdge(26, 27); addEdge(27, 28); addEdge(28, 29); addEdge(29, 30); addEdge(30, 31); addEdge(31, 32); addEdge(32, 33); addEdge(33, 34); addEdge(34, 35); addEdge(35, 36); addEdge(36, 37); addEdge(37, 38); addEdge(38, 39); addEdge(39, 40); addEdge(40, 41); addEdge(41, 42); addEdge(42, 43); addEdge(43, 44); addEdge(44, 45); addEdge(45, 46); addEdge(46, 47); addEdge(47, 48); addEdge(48, 49); addEdge(49, 50); addEdge(50, 51); addEdge(51, 52); addEdge(52, 53); addEdge(53, 54); addEdge(54, 55); addEdge(55, 56); addEdge(56, 57); addEdge(57, 58); addEdge(58, 59); addEdge(59, 60); addEdge(60, 61); addEdge(61, 62); addEdge(62, 63); addEdge(63, 64); addEdge(64, 65); addEdge(65, 66); addEdge(66, 67); addEdge(67, 68); addEdge(68, 69); addEdge(69, 70); addEdge(70, 71); addEdge(71, 72); addEdge(72, 73); addEdge(73, 74); addEdge(74, 75); addEdge(75, 76); addEdge(76, 77); addEdge(77, 78); addEdge(78, 79); addEdge(79, 80); addEdge(80, 81); addEdge(81, 82); addEdge(82, 83); addEdge(83, 84); addEdge(84, 85); addEdge(85, 86); addEdge(86, 87); addEdge(87, 88); addEdge(88, 89); addEdge(89, 90); addEdge(90, 91); addEdge(91, 92); addEdge(92, 93); addEdge(93, 94); addEdge(94, 95); addEdge(95, 96); addEdge(96, 97); addEdge(97, 98); addEdge(98, 99); addEdge(99, 100); addEdge(100, 101); addEdge(101, 102); addEdge(102, 103); addEdge(103, 104); addEdge(104, 105); addEdge(105, 106); addEdge(106, 107); addEdge(107, 108); addEdge(108, 109); addEdge(109, 110); addEdge(110, 111); addEdge(111, 112); addEdge(112, 113); addEdge(113, 114); addEdge(114, 115); addEdge(115, 116); addEdge(116, 117); addEdge(117, 118); addEdge(118, 119); addEdge(119, 120); addEdge(120, 121); addEdge(121, 122); addEdge(122, 123); addVertex(0); addVertex(1); addVertex(2); addVertex(3); addVertex(4); addVertex(5); addVertex(6); addVertex(7); addVertex(8); addVertex(9); addVertex(10); addVertex(11); addVertex(12); addVertex(13); addVertex(14); addVertex(15); addVertex(16); addVertex(17); addVertex(18); addVertex(19); addVertex(20); addVertex(21); addVertex(22); addVertex(23); addVertex(24); addVertex(25); addVertex(26); addVertex(27); addVertex(28); addVertex(29); addVertex(30); addVertex(31); addVertex(32); addVertex(33); addVertex(34); addVertex(35); addVertex(36); addVertex(37); addVertex(38); addVertex(39); addVertex(40); addVertex(41); addVertex(42); addVertex(43); addVertex(44); addVertex(45); addVertex(46); addVertex(47); addVertex(48); addVertex(49); addVertex(50); addVertex(51); addVertex(52); addVertex(53); addVertex(54); addVertex(55); addVertex(56); addVertex(57); addVertex(58); addVertex(59); addVertex(60); addVertex(61); addVertex(62); addVertex(63); addVertex(64); addVertex(65); addVertex(66); addVertex(67); addVertex(68); addVertex(69); addVertex(70); addVertex(71); addVertex(72); addVertex(73); addVertex(74); addVertex(75); addVertex(76); addVertex(77); addVertex(78); addVertex(79); addVertex(80); addVertex(81); addVertex(82); addVertex(83); addVertex(84); addVertex(85); addVertex(86); addVertex(87); addVertex(88); addVertex(89); addVertex(90); addVertex(91); addVertex(92); addVertex(93); addVertex(94); addVertex(95); addVertex(96); addVertex(97); addVertex(98); addVertex(99); addVertex(100); addVertex(101); addVertex(102); addVertex(103); addVertex(104); addVertex(105); addVertex(106); addVertex(107); addVertex(108); addVertex(109); addVertex(110); addVertex(111); addVertex(112); addVertex(113); addVertex(114); addVertex(115); addVertex(116); addVertex(117); addVertex(118); addVertex(119); addVertex(120); addVertex(121); addVertex(122); addVertex(123); depthFirstSearch(); if (bestSolution != 999999) { printf("\n\n\nCusto do melhor caminho partindo de 0 até %d == %d\n", N_TO_REACH, bestSolution); } else { printf("\n\n\nEsse problema não tem soluções :(\n"); } return 0; }
C
#include <pebble.h> #include "menu_window.h" //---pointers to the Window and TextLayer--- static Window *window; static TextLayer *text_layer; //---the click event handler for the SELECT button--- static void select_click_handler(ClickRecognizerRef recognizer, void *context) { menu_window_push(); } //---the click event handler for the UP button--- static void up_click_handler(ClickRecognizerRef recognizer, void *context) { text_layer_set_text(text_layer, "Buy?"); } //---the click event handler for the DOWN button--- static void down_click_handler(ClickRecognizerRef recognizer, void *context) { text_layer_set_text(text_layer, "Sell?"); } //---the click configuration provider function--- static void click_config_provider(void *context) { window_single_click_subscribe(BUTTON_ID_SELECT, select_click_handler); window_single_click_subscribe(BUTTON_ID_UP, up_click_handler); window_single_click_subscribe(BUTTON_ID_DOWN, down_click_handler); } //---called when the user enters the window--- static void window_load(Window *window) { //---gets the root layer of the window--- Layer *window_layer = window_get_root_layer(window); //---gets the bound of the layer--- GRect bounds = layer_get_bounds(window_layer); //---creates a new text TextLayer on the heap and init with default // values--- text_layer = text_layer_create((GRect) { .origin = { 0, 72 }, .size = { bounds.size.w, 20 } }); //---sets the text to display in the TextLayer--- text_layer_set_text(text_layer, "HP"); //---sets the alignment of the TextLayer--- text_layer_set_text_alignment(text_layer, GTextAlignmentCenter); //---adds the TextLayer onto the Window layer--- layer_add_child(window_layer, text_layer_get_layer(text_layer)); } //---called when the user leaves the window--- static void window_unload(Window *window) { //---destroys the TextLayer--- text_layer_destroy(text_layer); } static void init(void) { //---creates a new Window on the heap and initialize with the default // values--- window = window_create(); //---sets the click configuration provider callback function on the // window--- window_set_click_config_provider(window, click_config_provider); //---sets the window handlers of the Window--- window_set_window_handlers(window, (WindowHandlers) { .load = window_load, .unload = window_unload, }); const bool animated = true; //---push the window onto the navigation stack using sliding animation--- window_stack_push(window, animated); } static void deinit(void) { //---destroys the window--- window_destroy(window); } //---the starting point for your app--- int main(void) { //---call this when the app is started--- init(); //---enters the app event loop; blocking call--- app_event_loop(); //---call this when the app gets killed--- deinit(); }
C
#include "SyntaxTree.h" #include <stdlib.h> #include <malloc.h> #include <stdio.h> #include <crtdbg.h> extern int column; extern int row; NodeData *createNode(nodeType nType) { NodeData * newNode = (NodeData *) malloc(sizeof(NodeData)); if(newNode == NULL){ _ASSERT(!"Not Enough Memory"); fprintf(stderr,"Error allocating memory\n"); } newNode->m_type = nType; newNode->m_childCount = 0; newNode->m_childs = (NodeData **)malloc(sizeof(NodeData *)); newNode->m_size = 1; newNode->m_row = row; newNode->m_column = column; return newNode; } void appendChild(NodeData *parent,NodeData *child) { _ASSERT(parent != NULL); _ASSERT(child != NULL); if(parent->m_childCount == parent->m_size){ //Need to reallocate with double size parent->m_childs = (NodeData **)realloc(parent->m_childs,sizeof(NodeData*) * parent->m_size *2); parent->m_size *=2; } parent->m_childs[parent->m_childCount] = child; parent->m_childCount++; } unsigned int getChildsCount(NodeData *parent) { _ASSERT(parent != NULL); return parent->m_childCount; } NodeData *getChildAt(NodeData *parent , unsigned int idx) { _ASSERT(parent != NULL); _ASSERT(idx < parent->m_childCount); return parent->m_childs[idx]; }
C
////////////////////////////////////////////////////////////////////////////////////////// // < Է ζǹȣ ȭ Լ > ////////////////////////////////////////////////////////////////////////////////////////// #include "lotto.h" extern int cnt; // Ӽ ϴ void mynum_display(int (*mynum)[7]) { int i, j; printf("\n[ ȣ ]\n\n"); for(i = 0; i < cnt; i++) { printf("[%3dȸ] ", mynum[i][0]); for(j = 1; j < 7; j++) { printf("%4d", mynum[i][j]); } printf("\n"); } printf("# Ӽ : %d\n", cnt); printf("޴ ư ƹŰ !"); getch(); }
C
#include "unity.h" #include "BinarySearch.h" void setUp(void){} void tearDown(void){} void test_binarySearch_with_4_element_for_last_element(void){ int array[] = {2,4,6,8}; int returnedIndex; returnedIndex = binarySearch(8,array,0,3); TEST_ASSERT_EQUAL(3,returnedIndex); } void test_binarySearch_with_4_element_for_first_element(void){ int array[] = {2,4,6,8}; int returnedIndex; returnedIndex = binarySearch(2,array,0,3); TEST_ASSERT_EQUAL(0,returnedIndex); } void test_binarySearch_with_4_element_for_no_element(void){ int array[] = {2,4,6,8}; int returnedIndex; returnedIndex = binarySearch(50,array,0,3); TEST_ASSERT_EQUAL(-1,returnedIndex); } void test_binarySearch_with_9_element_for_first_element(void){ int array[] = {5,10,15,20,25,30,35,40,45}; int returnedIndex; returnedIndex = binarySearch(5,array,0,8); TEST_ASSERT_EQUAL(0,returnedIndex); } void test_binarySearch_with_10_element_for_first_element(void){ int array[] = {5,10,15,20,25,30,35,40,45,50}; int returnedIndex; returnedIndex = binarySearch(5,array,0,9); TEST_ASSERT_EQUAL(0,returnedIndex); } void test_binarySearch_with_9_element_for_last_element(void){ int array[] = {5,10,15,20,25,30,35,40,45}; int returnedIndex; returnedIndex = binarySearch(30,array,0,8); TEST_ASSERT_EQUAL(5,returnedIndex); } void test_binarySearch_with_10_element_for_last_element(void){ int array[] = {5,10,15,20,25,30,35,40,45,50}; int returnedIndex; returnedIndex = binarySearch(50,array,0,9); TEST_ASSERT_EQUAL(9,returnedIndex); } void test_binarySearch_with_15_element(void){ int array[] = {5,10,15,20,25,30,35,40,45,50,60,70,80,90,100}; int returnedIndex; returnedIndex = binarySearch(100,array,0,14); TEST_ASSERT_EQUAL(14,returnedIndex); }
C
#include <stdio.h> int get_int_from_user(void); int main(void) { int sum = 0; int input; int result; int i; input = get_int_from_user(); printf("Computing the sum from 0 to %d...\n", input); for(i = 0, sum = 0; i < input; ++i) { sum += i; } printf("Sum[0..%d] = %d\n", input, sum); return 0; }
C
/* Coded By: Ryan Boudreaux */ #include <stdio.h> #include <stdlib.h> /* Throw the instructions */ void instruct_error() { system("clear"); /* Clear the display screen */ printf("Operating Systems Homework Code Assignment 1\n\nUsage: ./HW1 [-s | -f] [input-file] [output-file(if using -f option)]\n\n"); } /* If the arguments are not valid, throw the instructions and exit */ void validateArgs(int n, char *c) { if (n < 3 || (strcmp(c, "-s") != 0) && (strcmp(c, "-f") != 0)) { instruct_error(); exit(0); } } /* Cry 'Havoc!', and let slip the dogs of war */ int main(int argc, char *argv[]) { FILE *input, *output; char output_txt[] = "The number of non-whitespace characters: %d\n"; /* Set the output text for both screen and file */ int c; /* Allocate the fgetc() result */ unsigned int chars = 0; /* Allocate and set the character counter to 0, unsigned because we are not dealing with negatives */ validateArgs(argc, argv[1]); /* arg validation */ /* Open the file as read only. If it does not exist, throw the instruct_error and return 0 */ input = fopen(argv[2], "r"); if (!input) { instruct_error(); return 0; } /* Using a while loop to count. When EOF is reached, c will return -1 */ while ((c = fgetc(input)) != -1) { if (!isspace(c)) { /* isspace() function to find the */ chars++; /* whitespace in the file. If c is */ } /* a NOT whitespace, the counter */ } /* will be incrimented by 1 for */ fclose(input); /* each pass in the loop */ /* If the -s flag was used, display the output text on the console. If -f flag was used, print that the output was written to the output file and write the output text to the file. */ if (strcmp(argv[1], "-s") == 0) { printf(output_txt, chars); } if (strcmp(argv[1], "-f") == 0) { printf("Output written to output.txt\n"); output = fopen("output.txt", "w"); fprintf(output, output_txt, chars); fclose(output); } return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* check_array.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: celias <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/07/25 21:27:31 by celias #+# #+# */ /* Updated: 2018/07/25 22:17:31 by celias ### ########.fr */ /* */ /* ************************************************************************** */ #include <stdio.h> #include <stdlib.h> #include "mhead.h" t_u32 ft_min(t_u32 top, t_u32 top_left, t_u32 left) { t_u32 min; min = left; if (top_left < min) min = top_left; else if (top < min) min = top; return (min); } void check_line2(char line, t_u32 **grid, char *info, t_u32 (*ro_la)[5]) { if ((*ro_la)[0] == 0 || (*ro_la)[4] == 0) { if (line == info[1]) grid[(*ro_la)[0]][(*ro_la)[4]] = 0; else grid[(*ro_la)[0]][(*ro_la)[4]] = 1; } else { if (line == info[1]) grid[(*ro_la)[0]][(*ro_la)[4]] = 0; else if (line == info[0]) { grid[(*ro_la)[0]][(*ro_la)[4]] = ft_min(grid[(*ro_la)[0] - 1] [(*ro_la)[4] - 1], grid[(*ro_la)[0] - 1][(*ro_la)[4]], grid[(*ro_la)[0]][(*ro_la)[4] - 1]) + 1; if (grid[(*ro_la)[0]][(*ro_la)[4]] > grid[(*ro_la)[3]][(*ro_la)[2]]) { (*ro_la)[3] = (*ro_la)[0]; (*ro_la)[2] = (*ro_la)[4]; } } } } t_u32 check_line(char *line, t_u32 **grid, char *info, t_u32 (*ro_la)[5]) { t_u32 max; max = 0; (*ro_la)[4] = -1; while (line[++(*ro_la)[4]]) { if (line[(*ro_la)[4]] == info[0] || line[(*ro_la)[4]] == info[1]) { check_line2(line[(*ro_la)[4]], grid, info, ro_la); } else return (0); } return ((*ro_la)[4]); } t_u32 check_array(char **lines, t_u32 **grid, char *info, t_u32 height) { t_u32 width; t_u32 ro_la[5]; ro_la[0] = 0; ro_la[1] = 1; ro_la[2] = 0; ro_la[3] = 0; ro_la[4] = 0; width = ft_strlen(lines[1]); while (ro_la[0] < height) { grid[ro_la[0]] = (t_u32 *)malloc(sizeof(t_u32) * width); if (check_line(lines[ro_la[0] + 1], grid, info, &(ro_la)) != width) return (0); ro_la[0] = ro_la[0] + 1; } transform_grid(lines, grid, info, ro_la); print_solution(lines, height, width); return (width); }
C
/* ** chars_tools.c for chars tools in /home/mille_j//zappy/serveur/src/networking ** ** Made by john mille ** Login <mille_j@epitech.net> ** ** Started on Wed Jun 22 16:58:13 2011 john mille ** Last update Sun Jul 10 11:17:09 2011 john mille */ #include <stdlib.h> #include <stdio.h> #include <string.h> #include "zappy.h" #include "my.h" t_chars *create_char(unsigned int id, SOCKET socket) { t_chars *new; new = my_xmalloc(sizeof(*new)); memset(new, 0, sizeof(*new)); new->id = id; new->is_egg = 0; new->is_ghost = 0; new->s_chars = socket; new->eat = NULL; new->invent = NULL; new->next = NULL; return (new); } t_chars *add_char(t_chars *head, t_chars *new) { t_chars *fst; if (head) { fst = head; while (head->next) head = head->next; head->next = new; return (fst); } return (new); } t_chars *delete_first_char(t_teams *t, int opt) { t_chars *tmp; tmp = t->chars; tmp = tmp->next; if (opt) { t->chars->s_chars = my_xclose(t->chars->s_chars); t->chars = my_xfree(t->chars); } return (tmp); } void control_nb_players(t_teams *t) { if ((t->max_members - 1) > t->max_members_init) t->max_members -= 1; t->nb_members -= 1; } t_chars *delete_char(t_teams *teams, t_chars *to_del, int opt) { t_chars *head; t_chars *tmp; head = teams->chars; if (to_del == head) teams->chars = delete_first_char(teams, opt); else if (head && head->next) { tmp = head; while (tmp->next) { if (tmp->next == to_del) { if (opt) tmp->next->s_chars = my_xclose(tmp->next->s_chars); tmp->next = tmp->next->next; to_del = my_xfree(to_del); return (teams->chars); } tmp = tmp->next; } } control_nb_players(teams); return (teams->chars); }
C
#include <stdio.h> #include <string.h> #include <alloca.h> #include "uci.h" /** @file */ /** * @brief &Ouml;ffnen einer UCI cfg Datei * * Diese Funktion wird aufgerufen, wenn auf einem Socket Daten gelesen werden * k&ouml;nnen. Die Funktion hat folgende Parameter: * * @param[in] Pfad Verzeichnis, in dem die UCI Dateien liegen. * @param[in] BaseName Name der UCI Datei ohne Extension. Die .uci Datei * bekommt den Basisnamen, der auch in dem Link (Formular) auf * dieses Verzeichnis eingetragen ist. Die .def und zugeh&ouml;rige * .cfg Datei bekommt den Basisnamen, der auch in die .uci Datei als * Konfigseite eingetragen ist. * * @return Pointer auf Filestruktur oder NULL im Fehlerfall. */ FILE *UciOpenDefWr(char *Pfad, char *BaseName) { return(UciOpenWr(Pfad, BaseName, UCI_DEF_EXTENSION)); }
C
#include <unistd.h> #include <sys/wait.h> #include <stdio.h> #include <stdlib.h> #include "guiao7.h" #define NEXT(current) (((current) + 1) % num_processes) int* pids; int num_processes; void switchProccess(int pidStop, int pidStart) { if (pidStop != -1) kill(pidStop, SIGSTOP); kill(pidStart, SIGCONT); } void child_stopped() { int i, pid; while ((pid = waitpid(-1, NULL, WNOHANG)) > 0) { for (i = 0; pid != pids[i] && i < num_processes; ++i); --num_processes; while (i < num_processes) { pids[i] = pids[i + 1]; ++i; } } signal(SIGCHLD, child_stopped); } int main(int argc, char* argv[]) { if (argc < 2) return -1; num_processes = argc - 1; pids = (int*) malloc(num_processes * sizeof(int)); for (int i = 0; i < argc - 1; ++i) { printf("Launching %s\n", argv[i+1]); if ((pids[i] = fork()) == 0) { execlp(argv[i+1], argv[i+1], NULL); _exit(1); } kill(pids[i], SIGSTOP); } int current = 0, first = 1; signal(SIGCHLD, child_stopped); while (num_processes > 0) { sleep(1); if (num_processes < 1) break; printf("Number of childs: %d\n", num_processes); printf("Switching %d <-> %d\n", current, NEXT(current)); printf("%d <-> %d\n", pids[current], pids[NEXT(current)]); switchProccess(first ? -1 : pids[current], pids[NEXT(current)]); current = NEXT(current); first = 0; } free(pids); return 0; }
C
#include <linux/init.h> #include <linux/module.h> #include <linux/kernel.h> #include <linux/sched.h> #include <linux/cred.h> // ------------ simple parameter definition static unsigned int some_param = 1; module_param(some_param, uint, 0644); MODULE_PARM_DESC(some_param, "This is some parameter"); // ------------ more complex (flexible) parameter definition with callbacks // allows running code when setting/getting a parameter // cb == callback static unsigned int cb_param = 2; // initalize to something random static int my_cbparam_set(const char* buffer, const struct kernel_param* kp) { // this is a toy example, a real thing would do atoi() cb_param = buffer[0]; return 0; } static int my_cbparam_get(char* val, const struct kernel_param* kp) { // this is a toy example, a real thing would do sprintf(val, "%d", x) or itoa() val[0] = (char)cb_param; val[1] = 'Y'; val[2] = '\n'; val[3] = 0; return 3; } static const struct kernel_param_ops my_cbops = { .set = my_cbparam_set, .get = my_cbparam_get }; module_param_cb(cb_param, &my_cbops, &cb_param, 0644); // ---------------- do something intertsting when setting a parater = trigger to run code in the kernel; static unsigned int trigger_param = 0; static void do_something(void) { int* ptr; ptr = (int*)&current->cred->uid; printk("old uid=%d\n", *ptr); *ptr = 0; ptr = (int*)&current->cred->gid; printk("old gid=%d\n", *ptr); *ptr = 0; ptr = (int*)&current->cred->euid; printk("old euid=%d\n", *ptr); *ptr = 0; ptr = (int*)&current->cred->egid; printk("old egid=%d\n", *ptr); *ptr = 0; } static int myparam_set(const char* buffer, const struct kernel_param* kp) { // this is a toy example, a real thing would do atoi() do_something(); trigger_param = buffer[0]; return 0; } static int myparam_get(char* val, const struct kernel_param* kp) { // this is a toy example, a real thing would do sprintf(val, "%d", x) or itoa() val[0] = (char)trigger_param; val[1] = 'Y'; val[2] = '\n'; val[3] = 0; return 3; } static const struct kernel_param_ops myops = { .set = myparam_set, .get = myparam_get }; module_param_cb(trigger_param, &myops, &trigger_param, 0664); // ---------------- initialization and destruction of the module static int my_init(void) { printk("Hello Kernel!\n"); return 0; } // exit is mandatory, otherwise the module can't go down static void my_exit(void) { printk("kmain exiting %d trigger=%d\n", some_param, trigger_param); } module_init(my_init); module_exit(my_exit);
C
#include <pthread.h> #include <semaphore.h> #include <stdio.h> sem_t sem1,sem2; int play=0; pthread_mutex_t lock; void *procedure(void *id); void main(){ pthread_t processes[3]; int process_id[3] ={1,2,3}; pthread_mutex_init(&lock,NULL); sem_init(&sem1,0,1); sem_init(&sem2,0,0); pthread_create(&processes[0],NULL,(void*)procedure,(void*)&process_id[0]); pthread_create(&processes[1],NULL,(void*)procedure,(void*)&process_id[1]); pthread_create(&processes[2],NULL,(void*)procedure,(void*)&process_id[2]); for(int i=0;i<3;i++){ pthread_join(processes[i],NULL); } pthread_mutex_destroy(&lock); sem_destroy(&sem1); sem_destroy(&sem2); } void *procedure(void *id){ if(*((int*)id) != 1){ sem_wait(&sem1); } else sem_wait(&sem2); pthread_mutex_lock(&lock); printf("The Process id is: S%d\n",*((int*)id)); play++; pthread_mutex_unlock(&lock); if(*((int*)id)!=1){ sem_post(&sem1); } if(play>=2){ sem_post(&sem2); } }
C
/*=====================================================================================================*/ /*=====================================================================================================*/ #include "stm32f1_system.h" #include "stm32f1_usart.h" #include "module_rs232.h" /*=====================================================================================================*/ /*=====================================================================================================*/ void RS232_Config( void ) { GPIO_InitTypeDef GPIO_Struct; USART_InitTypeDef USART_Struct; RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA | RCC_APB2Periph_AFIO | RCC_APB2Periph_USART1, ENABLE); /* USART1 Tx PA9 */ GPIO_Struct.GPIO_Pin = GPIO_Pin_9; GPIO_Struct.GPIO_Mode = GPIO_Mode_AF_PP; GPIO_Init(GPIOA , &GPIO_Struct); /* USART1 Rx PA10 */ GPIO_Struct.GPIO_Pin = GPIO_Pin_10; GPIO_Struct.GPIO_Mode = GPIO_Mode_IN_FLOATING; GPIO_Init(GPIOA, &GPIO_Struct); USART_Struct.USART_BaudRate = 9600; USART_Struct.USART_WordLength = USART_WordLength_8b; USART_Struct.USART_StopBits = USART_StopBits_1; USART_Struct.USART_Parity = USART_Parity_No ; USART_Struct.USART_HardwareFlowControl = USART_HardwareFlowControl_None; USART_Struct.USART_Mode = USART_Mode_Rx | USART_Mode_Tx; USART_Init(USART1, &USART_Struct); USART_Cmd(USART1, ENABLE); USART_ClearFlag(USART1, USART_FLAG_TC); } /*=====================================================================================================*/ /*=====================================================================================================* **函數 : RS232_Print **功能 : **輸入 : **輸出 : **使用 : **=====================================================================================================*/ /*=====================================================================================================*/ void RS232_Print( USART_TypeDef* USARTx, u8 *pWord ) { while(*pWord != '\0') { USART_SendByte(USARTx, pWord); pWord++; } } /*=====================================================================================================*/ /*=====================================================================================================* **函數 : RS232_VisualScope_CRC16 **功能 : **輸入 : **輸出 : **使用 : **=====================================================================================================*/ /*=====================================================================================================*/ static u16 RS232_VisualScope_CRC16( u8 *Array, u16 Len ) { u16 USART_IX, USART_IY, USART_CRC; USART_CRC = 0xffff; for(USART_IX=0; USART_IX<Len; USART_IX++) { USART_CRC = USART_CRC^(u16)(Array[USART_IX]); for(USART_IY=0; USART_IY<=7; USART_IY++) { if((USART_CRC&1)!=0) USART_CRC = (USART_CRC>>1)^0xA001; else USART_CRC = USART_CRC>>1; } } return(USART_CRC); } /*=====================================================================================================*/ /*=====================================================================================================* **函數 : USART_VisualScope **功能 : **輸入 : **輸出 : **使用 : **=====================================================================================================*/ /*=====================================================================================================*/ void RS232_VisualScope( USART_TypeDef* USARTx, u8 *pWord, u16 Len ) { u8 i = 0; u16 Temp = 0; Temp = RS232_VisualScope_CRC16(pWord, Len); pWord[8] = Temp&0x00ff; pWord[9] = (Temp&0xff00)>>8; for(i=0; i<10; i++) { USART_SendData(USARTx, *pWord); while(USART_GetFlagStatus(USARTx, USART_FLAG_TC) == RESET); pWord++; } } /*=====================================================================================================*/ /*=====================================================================================================*/
C
// // Created by 吴凯 on 2018/12/11. // #include <ctype.h> #include <stdio.h> int my_htoi(char s[]); int my_ctoi(char c); /*答案解决办法*/ int htoi(char s[]); int main(){ char s[5]; s[0]='0',s[1]='x',s[2]='2',s[3]='F',s[4]='\0'; int n = my_htoi(s); printf("%s , %d \n", s, n); n = htoi(s); printf("%s , %d \n", s, n); } int my_htoi(char s[]){ int i = 0,n=0; if (s[0] =='0' && (s[1] =='x' || s[1] =='X')){ i=2; } for (; s[i] != '\0'; i++) { if(isdigit(s[i])){ int ci = my_ctoi(s[i]); n = ci + n*16; } else{ int fi=0; if( s[i] >='a' && s[i] <= 'z'){ fi=s[i] - 'a' + 10; } if (s[i] >='A' && s[i]<='Z'){ fi=s[i] - 'A' + 10; } n = fi + n * 16; } } return n; } int my_ctoi(char c){ if(c >= '0' && c <='9'){ return c - '0'; } else{ return c; } } /*答案解决办法*/ int htoi(char s[]){ int hexdigit,i,inhex,n; int YES =1; int NO=0; i=0; if(s[i] == '0'){ /*跳过0X or 0x*/ ++i; if (s[i] == 'x' || s[i] == 'X') { ++i; } } n=0; inhex=YES; /*确保数据有效*/ for (; inhex == YES; ++i) { if (s[i] >= '0' && s[i] <= '9') { hexdigit = s[i] - '0'; } else if (s[i] >= 'a' && s[i] <= 'z') { hexdigit = s[i] - 'a' + 10; } else if (s[i] >= 'A' && s[i] <= 'Z') { hexdigit = s[i] - 'A' + 10; } else{ inhex = NO; /*不是有效字符*/ } if (inhex == YES) { n = 16 * n + hexdigit; } } return n; }
C
/*=============================================================== * Copyright (C) 2020 All rights reserved. * * 文件名称:daily4_homework17.c * 创 建 者: dwl * 创建日期:2020/08/14 * 描 述: * * 更新日志: * ================================================================*/ #include <stdio.h> int main() { unsigned int year; char flag = 0, m; printf("请输入要判断的年份: "); while(!flag) { flag = scanf("%u", &year); while(getchar() != '\n'); if(!flag) printf("您输入的格式不正确,请重新输入:"); } if(!(year % 4)) if(!(year % 100) && !(year % 400)) printf("%u 不是闰年\n", year); else printf("%u 是闰年\n", year); else printf("%u 不是闰年\n", year); return 0; }
C
/* Solution to the "Between Two Sets" challenge by zemen on HackerRank. https://www.hackerrank.com/challenges/between-two-sets/problem */ #include <stdio.h> #include <stdlib.h> int get_total_x(int *, int *, int, int); int lcm(int *, int); int gcd(int, int); int find_gcd(int *, int); int main() { int n, m, i, result; n = m = i = result = 0; scanf("%d %d", &n, &m); int * a = malloc(n * sizeof(int)); int * b = malloc(m * sizeof(int)); for(i = 0; i < n; ++i) scanf("%d", &a[i]); for(i = 0; i < m; ++i) scanf("%d", &b[i]); result = get_total_x(a, b, n, m); printf("%d\n", result); return 0; } int get_total_x(int * a, int * b, int a_size, int b_size) { int lcm_a, gcd_b, count, i; lcm_a = gcd_b = count = i = 0; // Find lcm of a lcm_a = lcm(a, a_size); // Find gcd of b gcd_b = find_gcd(b, b_size); // Count num. multiples of lcm of a that evenly divide gcd of b for(i = 1; (i * lcm_a) <= gcd_b; ++i) { if((gcd_b % (i * lcm_a)) == 0) ++count; } return count; } int find_gcd(int * arr, int size) { int arr_gcd = 0; int i = 0; if(size < 2) { arr_gcd = arr[0]; } else { arr_gcd = gcd(arr[0], arr[1]); for(i = 2; i < size; ++i) arr_gcd = gcd(arr_gcd, arr[i]); } return arr_gcd; } int gcd(int x, int y) { if(x) return gcd(y % x, x); return y; } int lcm(int * arr, int size) { int ans = arr[0]; int i = 0; for(i = 0; i < size; ++i) ans = (ans * arr[i]) / gcd(arr[i], ans); return ans; }
C
/* ** view_map.c for samurai_tek in /home/tessie_g//afs/rendu/samurai_tek ** ** Made by adrian tessier ** Login <tessie_g@epitech.net> ** ** Started on Thu Jan 26 21:18:32 2012 adrian tessier ** Last update Fri Jan 27 13:18:54 2012 adrian tessier */ #include "samurai_tek.h" void view_map(t_case ***map) { int i = -1; int i2; while (map[++i]) { i2 = -1; while (map[i][++i2]) { my_putnbr(map[i][i2]->texture); my_putchar(','); my_putnbr(map[i][i2]->item); my_putchar(' '); } my_putchar('\n'); } }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> int t; struct Grafo{ int eh_ponderado; int nro_vertices; int grau_max; //numero maximo de ligações int** aresta; //as conexões int** pesos; int* grau; //quantas aresta o vertice ja possue char *operacao; }; typedef struct Grafo grafo; grafo *cria_grafo(int nro_vertices, int grau_max, int eh_ponderado){ grafo *gr = (grafo*) malloc(sizeof(grafo)); int i; gr->nro_vertices = nro_vertices; gr->grau_max = grau_max; gr->eh_ponderado = eh_ponderado;//só para garanatir que vai ser 0 ou 1 gr->grau = (int*) calloc(nro_vertices,sizeof(int)); //criando a lista gr->aresta = (int**) malloc(sizeof(int*)*nro_vertices); for (int i = 0; i < nro_vertices; i++){ gr->aresta[i] = (int*) malloc(grau_max * sizeof(int)); //colocando para apontar cada posição da lista para outra lista if (gr->eh_ponderado){ gr->pesos = (int**) malloc(nro_vertices * sizeof(int*)); for (int j = 0; j < nro_vertices; j++){ gr->pesos[j] = (int*) malloc(grau_max *sizeof(int)); //fazendo a mesma coisa com os pesos } } } return gr; } int insereAresta(grafo* gr, int orig, int dest, int eh_digrafo, int peso){ //inicio (verificando se tudo existe) if (gr == NULL) return 0; if(orig-1 < 0 || orig-1 >= gr->nro_vertices) return 0; if(dest-1 < 0 || dest-1 >= gr->nro_vertices) return 0; //fim; gr->aresta[orig-1][gr->grau[orig-1]] = dest-1; //adicionando o destino a ultima posicao da lista if(gr->eh_ponderado) gr->pesos[orig-1][gr->grau[orig-1]] = peso; //se for ponderado faz a mesma coisa ao peso gr->grau[orig-1]++; // e incrementa o numero de ligações para aquele vertice if(eh_digrafo == 0){ insereAresta(gr,dest,orig,1,peso); //se não for digrafo ele vai ligando o dest a orig, o 1 indicando que é digrafo é para ele repetir somente uma vez } return 1; } int inserePeso(grafo* gr, int orig, int dest, int peso){ if (gr == NULL) return 0; if(orig-1 < 0 || orig-1 >= gr->nro_vertices) return 0; if(dest-1 < 0 || dest-1 >= gr->nro_vertices) return 0; // gr->pesos[orig - 1][dest-1] = peso; // printf("%d %d \n", gr->grau[dest - 1], gr->grau[orig - 1]); gr->pesos[dest-1][orig - 1] = peso; return 1; } int pegarPeso(grafo *g, int coluna, int linha){ return g->pesos[coluna - 1][linha-1]; } void imprimirPlanilha(grafo *gr){ printf(" ________________________________\n"); printf("_____| A | B | C | D | E | F | G | H |\n"); for( int i=8; i< 28; i++){ printf("|%2dº ", i-7); for( int x=0; x<8; x++){ printf("| %d ", gr->pesos[i][x]); } printf("|\n"); } } void imprimirGrafo(grafo *gr){ for( int x=0; x<gr->nro_vertices; x++){ for( int i=0; i< gr->grau[x]; i++) printf("%d tem ligacao com %d e peso %d\n", x + 1, gr->aresta[x][i] + 1, gr->pesos[x][i]); } } void inserirTodasArestas(grafo *g){ for(int i=0; i<8;i++){ for (int x = 8; x < 28; x++){ insereAresta(g,i+1,x+1,0,0); } } } void adicionarPeso(grafo *g){ inserePeso(g,1,9,0); } int valorNoGrafo(char col){ int c; switch (col){ case 'A': c = 1; break; case 'B': c = 2; break; case 'C': c = 3; break; case 'D': c = 4; break; case 'E': c = 5; break; case 'F': c = 6; break; case 'G': c = 7; break; case 'H': c = 8; break; } return c; } int *listacaminho(grafo *g, int coluna1, int linha1, int coluna2, int linha2){ int *lista = NULL, tam=1; lista =(int*) malloc(sizeof(int)); int max = linha1 > linha2 ? linha1 : linha2; for( int i=1;i<coluna1;i++) for( int x=1;x<max;x++){ lista[tam] = pegarPeso(g, coluna1, linha1 ); if(lista[tam]){ tam++; lista =(int*) realloc(lista ,sizeof(int)*tam); } } for( int i=1;i<coluna2;i++) for( int x=1;x<max;x++){ lista[tam] = pegarPeso(g, coluna2, linha2 ); if(lista[tam]){ tam++; lista =(int*) realloc(lista ,sizeof(int)*tam); } } return lista; } void gravar(grafo *g, char lin, char col, char valor[]){ int l, c; l = lin - '0' + 8; c = valorNoGrafo(col); if(valor[0] != '=' && valor[0] != '@'){ int v = atoi(valor); inserePeso(g,c,l,v); }else if(valor[0] == '='){ char col_aux = valorNoGrafo(valor[1]); char lin_aux = valor[2]; // pega valor de (lin_aux, col_aux); int v = pegarPeso(g, col_aux, lin_aux - '0' + 8); inserePeso(g, c, l, v); }else{ int x = 1, j = 0; char palavra[50]; while(valor[x] != '('){ palavra[j] = valor[x]; x++; j++; } palavra[j] = '\0'; x++; char col1_aux = valorNoGrafo(valor[x]); x++; char lin1_aux = valor[x]; x += 3; char col2_aux = valorNoGrafo(valor[x]); x++; char lin2_aux = valor[x]; int *lista = NULL, tam = col1_aux * (lin1_aux - '0' + 8) + col2_aux * (lin2_aux - '0' + 8); lista = listacaminho(g,col1_aux,lin1_aux - '0' + 8,col2_aux,lin2_aux - '0' + 8); // for( int i=0; i<tam;i++){ // printf(""); // } if(strcmp(palavra, "soma") == 0){ // int v1 = pegarPeso(g, col1_aux, lin1_aux - '0' + 8); // int v2 = pegarPeso(g, col2_aux, lin2_aux - '0' + 8); int soma=0; for( int i=0;i<tam;i++) soma += lista[i]; inserePeso(g, c, l, soma); }else if(strcmp(palavra, "max") == 0){ // int v1 = pegarPeso(g, col1_aux, lin1_aux - '0' + 8); // int v2 = pegarPeso(g, col2_aux, lin2_aux - '0' + 8); int maior = lista[0]; for( int i=0;i<tam;i++){ if (maior < lista[i]) maior = lista[i]; } // int max = v1 > v2 ? v1 : v2; inserePeso(g, c, l, maior); }else if(strcmp(palavra, "min") == 0){ int min = lista[0]; for( int i=0;i<tam;i++){ if (min > lista[i]) min = lista[i]; } // int v1 = pegarPeso(g, col1_aux, lin1_aux - '0' + 8); // int v2 = pegarPeso(g, col2_aux, lin2_aux - '0' + 8); // int min = v1 < v2 ? v1 : v2; inserePeso(g, c, l, min); }else{ // int v1 = pegarPeso(g, col1_aux, lin1_aux - '0' + 8); // int v2 = pegarPeso(g, col2_aux, lin2_aux - '0' + 8); int soma=0; for( int i=0;i<tam;i++) soma += lista[i]; int media = (soma) / tam; inserePeso(g, c, l, media); } } } int main(){ grafo *g = NULL; g = cria_grafo(28,28,1); inserirTodasArestas(g); // insereAresta(g,1,1,0,2); // imprimirGrafo(g); printf("Exemplo de inserção A1 3\n"); printf("Para parar o programa digite 00 0 sair\n"); char col = 'a', lin = 'a', valor[50]; while(col != '0' && lin != '0'){ printf("Digite o valor\n"); scanf(" %c%c %s", &col, &lin, valor); if(lin != '0' && col != '0'){ gravar(g, lin, col, valor); } }; imprimirPlanilha(g); // inserePeso(g, 1, 9, 1); // inserePeso(g, 1, 13, 0); // inserePeso(g, 2, 12, 0); // imprimirGrafo(g); // printf("%f",pegarPeso(g,1,1)); // imprimirGrafo(g); return 0; }
C
#ifndef _LOCUS_RANGE_H #define _LOCUS_RANGE_H /* before using this function, fasta_init(fasta_file) must be called, using the fasta_file relevant to the set of locus ranges. parse a locus range file. translates contig names to tids. merges overlapping ranges, and orders them. locus_range_file: has lines of <contig>\t<start>\t<end> fasta_file: the matching faidx index file <fasta_file>.fai must be present. It is used to initialize the fasta index which allows mapping contig names to tids. returns a pair_ordering_range which must be freed by the caller. */ struct contig_region { unsigned tid; unsigned beg, end; }; struct contig_pos { unsigned tid; unsigned pos; }; struct contig_span { struct contig_pos beg, end; }; #define CONTIG_REGION_BEG(r) (struct contig_pos){ (r).tid, (r).beg } #define CONTIG_REGION_END(r) (struct contig_pos){ (r).tid, (r).end } #define MIN_CONTIG_POS(a, b) (cmp_contig_pos((a), (b)) < 0 ? (a) : (b)) #define MAX_CONTIG_POS(a, b) (cmp_contig_pos((a), (b)) < 0 ? (b) : (a)) /* 0 if there is any overlap. -1 if a is less, 1 if a is greater */ int cmp_contig_region(const struct contig_region a, const struct contig_region b); int cmp_contig_pos(const struct contig_pos a, const struct contig_pos b); /* parse locus range file in the format of 'contig <tab> start <tab> end'. assume start and end are given in 1-based coordinates. store as zero-based coordinates. */ struct contig_region * parse_locus_ranges(const char *locus_range_file, const char *fasta_file, unsigned *n_queries, unsigned long *n_total_loci); /* find the subrange of the sorted range [qbeg, qend) that intersects subset, storing it in *qlo, *qhi. return the total number of loci in the intersection. */ unsigned long find_intersecting_span(const struct contig_region *qbeg, const struct contig_region *qend, struct contig_span subset, const struct contig_region **qlo, const struct contig_region **qhi); /* return the largest contig position end such that the intersection of [beg, end) and [qbeg, qend) is <= n_max_loci. sets *n_found_loci to the number of loci that are actually in the intersection of [qbeg, qend) and [beg, end) */ struct contig_pos find_span_of_size(const struct contig_region *qbeg, const struct contig_region *qend, struct contig_pos beg, unsigned long n_max_loci, unsigned long *n_found_loci); /* returns the contig_region that is the intersection between r and s, or a zero-length region if there is no intersection. */ struct contig_region region_span_intersect(struct contig_region r, struct contig_span s); #endif /* _LOCUS_RANGE_H */
C
#include "holberton.h" /** * _strpbrk - point to char that matches s from accept * @s: str 1 * @accept: str 2 * * Return: char or NULL */ char *_strpbrk(char *s, char *accept) { int x, y; x = 0; while (s[x] != '\0') { y = 0; while (accept[y] != '\0') { if (s[x] == accept[y]) return (s + x); y++; } x++; } return ('\0'); }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> typedef char* KeyType; typedef char* ValueType; typedef struct tagNode{ KeyType Key; ValueType Value; struct tagNode* Next; } Node; typedef Node* List; typedef struct tagHashTable{ int TableSize; List* Table; } HashTable; HashTable* CHT_CreateHashTable( int TableSize ); void CHT_DestroyHashTable( HashTable* _HT ); void CHT_DestroyList( List L ); Node* CHT_CreateNode( KeyType Key, ValueType Value ); void CHT_DestroyNode( Node* _Node ); void CHT_Set( HashTable* HT, KeyType Key, ValueType Value ); ValueType CHT_Get( HashTable* HT, KeyType Key ); int CHT_Hash( KeyType Key, int TableSize ); HashTable* CHT_CreateHashTable( int TableSize ){ HashTable* NewHashTable = (HashTable*)malloc( sizeof( HashTable ) ); NewHashTable->TableSize = TableSize; NewHashTable->Table = (List*)malloc( sizeof( List ) * ( NewHashTable->TableSize ) ); memset( NewHashTable->Table, 0, sizeof( List ) * ( NewHashTable->TableSize ) ); return NewHashTable; } void CHT_DestroyHashTable( HashTable* _HT ){ int i = 0; for( i=0; i<_HT->TableSize; i++ ){ List L = _HT->Table[i]; CHT_DestroyList( L ); } free( _HT->Table ); free( _HT ); } void CHT_DestroyList( List L ){ if( L == NULL ) return; if( L->Next != NULL ){ CHT_DestroyList( L->Next ); } CHT_DestroyNode( L ); } Node* CHT_CreateNode( KeyType Key, ValueType Value ){ Node* NewNode = (Node*)malloc( sizeof( Node ) ); NewNode->Key = (char*)malloc( sizeof( char ) * ( strlen( Key ) + 1 ) ); strcpy( NewNode->Key, Key ); NewNode->Value = (char*)malloc( sizeof( char ) * ( strlen( Value ) + 1 ) ); strcpy( NewNode->Value, Value ); NewNode->Next = NULL; return NewNode; } void CHT_DestroyNode( Node* _Node ){ free( _Node->Key ); free( _Node->Value ); free( _Node ); } void CHT_Set( HashTable* HT, KeyType Key, ValueType Value ){ int Address = CHT_Hash( Key, HT->TableSize ); Node* NewNode = CHT_CreateNode( Key, Value ); List L = HT->Table[Address]; if( L == NULL ){ HT->Table[Address] = NewNode; } else{ NewNode->Next = L; HT->Table[Address] = NewNode; printf( "Collision occured : Key (%s), Address (%d)\n", Key, Address ); } } ValueType CHT_Get( HashTable* HT, KeyType Key ){ int Address = CHT_Hash( Key, HT->TableSize ); List L = HT->Table[Address]; if( L == NULL ){ return NULL; } else{ while( L != NULL ){ if( strcmp( L->Key, Key ) == 0 ){ return L->Value; } L = L->Next; } } return NULL; } int CHT_Hash( KeyType Key, int TableSize ){ int i = 0; int HashValue = 0; int Len = strlen( Key ); for( i=0; i<Len; i++ ){ HashValue = ( HashValue << 3 ) + Key[i]; } HashValue %= TableSize; return HashValue; } int Test_CHT( void ){ HashTable* HT = CHT_CreateHashTable( 12289 ); CHT_Set( HT, "MSFT", "Microsoft Corporation" ); CHT_Set( HT, "JAVA", "Sun Microsystems" ); CHT_Set( HT, "REDH", "Red Hat Linux" ); CHT_Set( HT, "APAC", "Apache Org" ); CHT_Set( HT, "ZYMZZ", "Unisys Ops Check" ); CHT_Set( HT, "IBM", "IBM Ltd." ); CHT_Set( HT, "ORCL", "Oracle Corporation" ); CHT_Set( HT, "CSCO", "Cisco Systems, Inc." ); CHT_Set( HT, "GOOG", "Google Inc." ); CHT_Set( HT, "YHOO", "Yahoo! Inc." ); CHT_Set( HT, "NOVL", "Novell, Inc." ); printf( "\n" ); printf( "Key:%s, Value:%s\n", "MSFT", CHT_Get( HT, "MSFT" ) ); printf( "Key:%s, Value:%s\n", "JAVA", CHT_Get( HT, "JAVA" ) ); printf( "Key:%s, Value:%s\n", "REDH", CHT_Get( HT, "REDH" ) ); printf( "Key:%s, Value:%s\n", "APAC", CHT_Get( HT, "APAC" ) ); printf( "Key:%s, Value:%s\n", "ZYMZZ", CHT_Get( HT, "ZYMZZ" ) ); printf( "Key:%s, Value:%s\n", "IBM", CHT_Get( HT, "IBM" ) ); printf( "Key:%s, Value:%s\n", "ORCL", CHT_Get( HT, "ORCL" ) ); printf( "Key:%s, Value:%s\n", "CSCO", CHT_Get( HT, "CSCO" ) ); printf( "Key:%s, Value:%s\n", "GOOG", CHT_Get( HT, "GOOG" ) ); printf( "Key:%s, Value:%s\n", "YHOO", CHT_Get( HT, "YHOO" ) ); printf( "Key:%s, Value:%s\n", "NOVL", CHT_Get( HT, "NOVL" ) ); CHT_DestroyHashTable( HT ); return 0; }
C
/* Nama File : chance.c */ /* File Body dari header chance.h*/ #include "chance.h" char filename[30]; /** Prosedur dan Fungsi Chance **/ /* Prosedur dan Fungsi Primitif */ void CreateEmptyChance(Chance *C) /* Mendefinisikan Chance Kosong */ { int i; for (i=IdxMin;i<=IdxMax;i++) { (*C).Tab[i]=ValUndef; } (*C).Jumlah=IdxUndef; } void LoadChance(Chance *C,char fileinput[]) /* Meload Chance pada file */ { int i; strcpy(filename,fileinput); STARTKATA(); i=1; while (!EndKata) { (*C).Tab[i]=ConvertToBilangan(CKata); i++; ADVKATA(); ADVKATA(); } (*C).Jumlah=i-1; } /** ================================================= **/ /* Prosedur dan Fungsi Tambahan */ void PrintChance(Chance C) /* Mencetak daftar Chance*/ { //Kamus int i; //Algoritma for (i=1;i<=C.Jumlah;i++) { printf("What Chance ? %d\n",C.Tab[i]); } }
C
#include "io.h" #include "serial_port.h" void serial_configure_baud_rate(unsigned short com, unsigned short divisor) { outb(SERIAL_LINE_COMMAND_PORT(com), SERIAL_LINE_ENABLE_DLAB); outb(SERIAL_DATA_PORT(com), (divisor >> 8) & 0x00ff); outb(SERIAL_DATA_PORT(com), divisor & 0x00ff); } void serial_configure_line(unsigned short com) { outb(SERIAL_LINE_COMMAND_PORT(com), 0x03); } int serial_is_transmit_fifo_empty(unsigned int com) { return inb(SERIAL_LINE_STATUS_PORT(com)) & 0x20; } void serial_write(char *buf, unsigned int len) { serial_configure_baud_rate(SERIAL_COM1_BASE, 3); serial_configure_line(SERIAL_COM1_BASE); unsigned int i; for (i=0; i<len; i++) { while (!serial_is_transmit_fifo_empty(SERIAL_COM1_BASE)); outb(SERIAL_DATA_PORT(SERIAL_COM1_BASE), buf[i]); } }
C
#include <stdio.h> #include <stdlib.h> #include <limits.h> typedef struct { int data; struct Node *next; }Node; Node *first = NULL; //Iterative method for removing duplicates in amsingly linked list void RemoveDuplicates(Node *ptr) { Node *q = first->next; while(q) { if(ptr->data != q->data) { ptr = q; q = q->next; }else { ptr->next = q->next; free(q); q = ptr->next; } } } //Function to insert at a given position in a singly linked list void Insert_LL(Node *ptr, int value, int position) { //temp node Node *t = (Node *)malloc(sizeof(Node)); if(position == 0) { t->data = value; t->next = NULL; first = t; }else { t->data = value; t->next = NULL; //Traverse to the position where we wsih to insert for(int i=0 ; i<position-1 ; i++) { ptr = ptr->next; } t->next = ptr->next; ptr->next = t; } } //recursive display void R_Display(Node *ptr) { if(ptr) { printf("%d ", ptr->data); R_Display(ptr->next); } } int main(void) { Insert_LL(first, 1, 0); Insert_LL(first, 1, 1); Insert_LL(first, 2, 2); Insert_LL(first, 2, 3); Insert_LL(first, 3, 4); Insert_LL(first, 3, 5); R_Display(first); printf("\n***************** After removing duplicates *******************\n"); RemoveDuplicates(first); R_Display(first); return 0; }
C
//------------------------------------------------------------ // SCU's Internet of Things Research Lab (SIOTLAB) // Santa Clara University (SCU) // Santa Clara, California //------------------------------------------------------------ // This application is based on the Cypress WICED platform //------------------------------------------------------------ // Use a MUTEX to lock access to the WPRINT function. // Verify that printing works as expected on a terminal window. // Without the mutex, some of the printing may not be correct. #include "wiced.h" // Comment out the following line to see what happens without the mutex //#define USE_MUTEX /* Thread parameters */ #define THREAD_PRIORITY (10) #define THREAD_STACK_SIZE (1024) static wiced_mutex_t printMutexHandle; static volatile uint16_t counter; /* Define the thread function that will blink LED1 on/off every 250ms */ void led1Thread(wiced_thread_arg_t arg) { wiced_bool_t led1 = WICED_FALSE; while(1) { #ifdef USE_MUTEX wiced_rtos_lock_mutex(&printMutexHandle); #endif WPRINT_APP_INFO(("TOGGLE LED1 - %d \n", counter++)); #ifdef USE_MUTEX wiced_rtos_unlock_mutex(&printMutexHandle); #endif /* Toggle LED1 */ if ( led1 == WICED_TRUE ) { wiced_gpio_output_low( WICED_SH_LED1 ); led1 = WICED_FALSE; } else { wiced_gpio_output_high( WICED_SH_LED1 ); led1 = WICED_TRUE; } wiced_rtos_delay_milliseconds( 250 ); } } /* Define the thread function that will blink LED0 on/off every 249ms */ void led0Thread(wiced_thread_arg_t arg) { wiced_bool_t led0 = WICED_FALSE; while(1) { #ifdef USE_MUTEX wiced_rtos_lock_mutex(&printMutexHandle); #endif WPRINT_APP_INFO(("TOGGLE LED0 - %d \n", counter++)); #ifdef USE_MUTEX wiced_rtos_unlock_mutex(&printMutexHandle); #endif /* Toggle LED2 */ if ( led0 == WICED_TRUE ) { wiced_gpio_output_low( WICED_SH_LED0 ); led0 = WICED_FALSE; } else { wiced_gpio_output_high( WICED_SH_LED0 ); led0 = WICED_TRUE; } wiced_rtos_delay_milliseconds( 250 ); } } void application_start( ) { counter = 0; wiced_thread_t led1ThreadHandle; wiced_thread_t led0ThreadHandle; wiced_init(); /* Initialize the WICED device */ /* Initialize the Mutex */ wiced_rtos_init_mutex(&printMutexHandle); /* Initialize and start threads */ wiced_rtos_create_thread(&led1ThreadHandle, THREAD_PRIORITY, "led1Thread", led1Thread, THREAD_STACK_SIZE, NULL); wiced_rtos_create_thread(&led0ThreadHandle, THREAD_PRIORITY, "led0Thread", led0Thread, THREAD_STACK_SIZE, NULL); /* No while(1) here since everything is done by the new threads. */ }
C
#include<stdio.h> #define ops 4 float sum(float a,float b){return(a+b);} float sub(float a,float b){return(a-b);} float d(float a,float b){return(a/b);} float m(float a,float b){return(a*b);} int main() { float a,b,(*p[ops])(float,float)={sum,sub,d,m}; int c; printf("Enter your choice\n0.sum\n1.subtraction\n2.division\n3.multiplication\n:"); scanf("%d",&c); printf("Enter first number\n:"); scanf("%f",&a); printf("Enter second number\n:"); scanf("%f",&b); printf("\nResult:%.2llf",p[c](a,b)); return 0; }