language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
#include "client.h" int is_signal_received(int is_signal) { static int status = FALSE; if (is_signal) status = TRUE; else if (status) { status = FALSE; return (TRUE); } return (FALSE); } void send_message(pid_t server_pid, char *msg) { int i; int ret; int mask; i = 0; while (1) { mask = 0b10000000; while (mask) { if (mask & msg[i]) ret = kill(server_pid, SIGUSR1); else ret = kill(server_pid, SIGUSR2); if (ret) exit(error_message("Couldn't send signal")); mask >>= 1; usleep(500); while (!is_signal_received(FALSE)) continue ; } if (!msg[i++]) break ; } } void handle_server_signal(int signum, siginfo_t *siginfo, void *context) { (void)context; (void)siginfo; if (signum == SIGUSR1) is_signal_received(TRUE); else if (signum == SIGUSR2) { ft_putstr_fd(GREEN_COLOR, STDERR_FILENO); ft_putstr_fd("[v] minitalk: ", STDERR_FILENO); ft_putstr_fd(NONE_COLOR, STDERR_FILENO); ft_putendl_fd("All data has been received.", STDOUT_FILENO); exit (SUCCESS); } } int catch_signal(int signum, void (*handler)(int, siginfo_t *, void *)) { struct sigaction s_action; ft_memset(&s_action, 0, sizeof(s_action)); s_action.sa_sigaction = handler; s_action.sa_flags = SA_SIGINFO; sigemptyset(&s_action.sa_mask); return (sigaction(signum, &s_action, NULL)); } int main(int argc, char *argv[]) { if (is_wrong_arg(argc, argv)) return (1); if (catch_signal(SIGUSR1, handle_server_signal) == -1 || catch_signal(SIGUSR2, handle_server_signal) == -1) return (error_message("Can't handle signal")); send_message(ft_atoi(argv[1]), argv[2]); while (1) continue ; return (SUCCESS); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_setinfo.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ssong <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/03/20 22:38:52 by ssong #+# #+# */ /* Updated: 2018/03/26 12:14:02 by ssong ### ########.fr */ /* */ /* ************************************************************************** */ #include "ft_printf.h" int isformat(char c) { if (c == 'd' || c == 'D' || c == 'p') return (1); else if (c == 'i' || c == 'o' || c == 'O') return (1); else if (c == 'u' || c == 'U' || c == 's' || c == 'S') return (1); else if (c == 'x' || c == 'X' || c == 'c' || c == 'C') return (1); else if (c == '%' || c == 'n') return (1); return (0); } int isplusminus(char c) { if (c == '+' || c == '-') return (1); return (0); } t_data *init_info(void) { t_data *data; data = malloc(sizeof(t_data)); data->info = malloc(sizeof(t_info)); data->info->left = 0; data->info->hash = 0; data->info->minus = 0; data->info->format = 0; data->info->zero = 0; data->info->sign = 0; data->info->plus = 0; data->info->space = 0; data->info->width = 0; data->info->precision = -1; data->info->modifier = 0; data->info->printed = 0; data->info->index = 0; data->info->end = 0; data->functions = malloc(sizeof(t_functions) * 16); data->functions = set_fptr(data->functions); return (data); } t_info *reset_info(t_info *info) { info->left = 0; info->precision = -1; info->minus = 0; info->plus = 0; info->zero = 0; info->width = 0; info->hash = 0; info->space = 0; info->format = 0; info->modifier = 0; info->sign = 0; return (info); }
C
/* ======================================================= * PCS 2056 - Linguagens e Compiladores * ======================================================= * * table_of_symbols.h - Symbol table * * Created on: 21/09/2011 * Authors: * Bruno Pezzolo dos Santos, 5948816 * Carla Guillen Gomes, 5691366 * */ #ifndef TABLE_OF_SYMBOLS_H_ #define TABLE_OF_SYMBOLS_H_ #include "linked_list.h" #define LEN_OF_RESERVED_TABLE 22 #define LEN_OF_SPECIAL_CHAR_TABLE 18 #define lenght(array) (sizeof(array)/sizeof(*array)) extern char * reserved_words_table[]; extern char * special_characters_table[]; extern List * identifiers_table; extern List * constants_table; int search_reserved_words_table(char * data); int search_special_characters_table(char * data); void enter_new_table_of_symbols(); void exit_current_table_of_symbols(); int search_identifiers_table(char * data); int add_identifiers_table(char * data); int add_if_new_identifiers_table(char * data); Node * get_identifier_at_index(int index); Node * get_identifier_for_data(char * data); Node * get_identifier_for_data_on_current_table(char * data); Node * get_identifier_for_label_on_current_table(char * label); int search_constants_table(char * data); int add_constants_table(char * data); int add_if_new_constants_table(char * data); Node * get_constant_at_index(int index); void display_identifiers_table(); void display_reserved_words_table(); void display_special_characters_table(); #endif /* TABLE_OF_SYMBOLS_H_ */
C
#include<stdio.h> #include<stdlib.h> #include<fcntl.h> #include<unistd.h> #define BUFSIZE 512 int main(int argc, char *argv[]) { char buffer[BUFSIZE]; int fd; ssize_t nread; long total = 0; if((fd = open(argv[1], O_RDONLY)) == -1) perror(argv[1]); while((nread = read(fd, buffer, BUFSIZE)) > 0) total +=nread; close(fd); printf("%s 파일 크기 : %ld 바이트 \n", argv[1], total); exit(0); }
C
#include <stdio.h> #define INF 100000000 #define min(x,y) ((x<y)?x:y) #define max(x,y) ((x>y)?x:y) int R, C, g[505][505], dp[505][505]; int main(){ int t, i, j, a, b; scanf("%d", &t); while(t--){ scanf("%d %d", &R, &C); for(i=0; i<R; i++) for(j=0; j<C; j++) scanf("%d", &g[i][j]); dp[R-1][C-1]=1; for(i=R-1; i>=0; i--) { for(j=C-1; j>=0; j--) { if(i==R-1&&j==C-1) continue; dp[i][j]=INF; if(i<R-1) dp[i][j] = dp[i+1][j]; if(j<C-1 && dp[i][j+1]<dp[i][j]) dp[i][j] = dp[i][j+1]; dp[i][j]-=g[i][j]; if(dp[i][j]<=0) dp[i][j]=1; } } printf("%d\n", dp[0][0]); } return 0; }
C
#include "dlist.h" int insert_before(data_t g_data,data_t n_data,DLink **head,DLink **tail) { //Check if list is empty if (*head == NULL) { return LIST_EMPTY; } DLink *temp = *head; //If not empty DLink *new = malloc(sizeof(DLink)); new -> data = n_data; new -> prev = NULL; new -> next = NULL; if (temp -> data == g_data) { new -> next = temp; temp -> prev = new; *head = new; return SUCCESS; } while (temp != NULL && temp -> data != g_data) { temp = temp -> next; } //If the given data is not found if (temp == NULL) { return DATA_NOT_FOUND; } temp = temp -> prev; //Establish the links DLink *temp1 = temp->next; temp->next = new; new->prev = temp; new->next = temp1; temp1->prev = new; return SUCCESS; }
C
/*============================================================================= | Title: server.c | | Author: Grace Miller | Language: C | To Compile: Run the Makefile in the server folder | | Class: CS 63 Programming Parallel Systems | Due Date: 10/15/2016 | +----------------------------------------------------------------------------- | | Description: A TCP server which takes in multiple clients and allows them | to talk like a chat room. Every client that it accepts becomes | a new thread within the server. This can be run on a different | ip address than the clients, you can discover the ip address of | the server by logging into it and then cat’ing the | file /etc/network/interfaces | | Input: ./server [PORT_NUM] | Takes in a port number to run the server | | Output: prints information on the server running, to end the server just control C | *===========================================================================*/ #include <stdio.h> #include <string.h> #include <stdlib.h> #include <sys/socket.h> #include <sys/types.h> #include <netinet/in.h> #include <arpa/inet.h> #include <unistd.h> #include <pthread.h> #include "queue.h" #include "lqueue.h" #define NAMELENGTH 100 #define BUFFERSIZE 2048 #define ADDRLENGTH 50 #define LISTENQ 8 #define MAXPEOPLE 1000 #define SWITCHCOUNT 4 #define PING 0 #define JOIN 1 #define LEAVE 2 #define WHO 3 /* message passed to server with the user name inside */ typedef struct Message{ char buffer[BUFFERSIZE]; char user_id[NAMELENGTH]; }Message; /* Struct to pass the socket information to the server thread*/ typedef struct Connection{ int csocket; }Connection; /* ChatUser struct which contains information to send messages back this information stored in the queue of users*/ typedef struct ChatUser{ char name[NAMELENGTH]; int usocket; } ChatUser; /* queue of users currently "joined" in the chatroom */ lqueue_t *myqueue; /* message to send to all users */ char public_message_tosend[BUFFERSIZE]; int sockfd; /* person sending the current message */ char curr_sender[NAMELENGTH]; /* socket of the person sending the current message */ int curr_sender_socket; void print(void* elementp){ ChatUser *c = (ChatUser*) elementp; printf("printq: %s\n", c->name); } /* * Function: find_user() * -------------------- * comparator method to be passed into lqsearch() and lqremove() to * compare if two chatusers are the same person, since each username is * unique they can compare names * * paramaters: * void* elementp: the element to see if it is the same element * const void* id: the element to find * * returns: 0 if user not found, 1 if user found */ int find_user(void* elementp, const void* id){ ChatUser *curr_user = (ChatUser *)elementp; ChatUser *search_user = (ChatUser *) id; if(strcmp(curr_user->name, search_user->name) == 0){ return TRUE; }else{ return FALSE; } } /* * Function: send_message_toall() * -------------------- * method to be applied to each every in the queue using lqapply() which * sends the current message out to all users, unless it is the user sending * the message * * paramaters: * void* elementp: the element containing the user to send the message to * * returns: NULL */ void send_message_toall(void* elementp){ int reclen; ChatUser *curr_user = (ChatUser*) elementp; if(strcmp(curr_user->name, curr_sender) != 0){ reclen = send(curr_user->usocket, public_message_tosend, BUFFERSIZE, 0); } if (reclen < 0) { perror("ERROR in sendto"); } } /* * Function: send_user_in_room() * -------------------- * method to be applied to each every in the queue using lqapply() which * sends the current user's name back to the user who requested it using the * '/who' request. It only sends the list of users to the user who requested it * * paramaters: * void* elementp: the element containing the user name to send * * returns: NULL */ void send_user_in_room(void *elementp){ int reclen; char user_tosend[BUFFERSIZE]; ChatUser *curr_user = (ChatUser*) elementp; if(strcmp(curr_user->name, curr_sender) != 0){ strcpy(user_tosend, curr_user->name); strcat(user_tosend, "\n"); reclen = send(curr_sender_socket, user_tosend, BUFFERSIZE, 0); } if (reclen < 0) { perror("ERROR in sendto"); } } /* * Function: combine_return_message() * -------------------- * helper method to synthesize the user's message with their user name * * paramaters: * Message *message: message struct containing the user name and the message * * returns: char *, the message with the username concatenated to the front */ char *combine_return_message(Message *message){ char *src = malloc(sizeof(char)*BUFFERSIZE); char *dest = malloc(sizeof(char)*BUFFERSIZE); strcpy(src, message->user_id); strcat(src, ": "); strcpy(dest, message->buffer); strcat(src, dest); return src; } /* * Function: add_user() * -------------------- * helper method to add a user to the queue of users if they are not already in it * * paramaters: * ChatUser *chat_user: the user to add into the queue * * returns: char *, the message to return to the user about whether they were * successfully added or not */ char *add_user(ChatUser *chat_user){ void *returned_user; char *add_status_message = malloc(sizeof(char)*BUFFERSIZE); returned_user = lqsearch(myqueue, find_user, chat_user); if(!returned_user){ lqput(myqueue, chat_user); add_status_message = "SERVER: successfully joined the chatroom, start typing!\n"; }else{ add_status_message = "SERVER ERROR: A user with this username already exists!\n"; } return add_status_message; } /* * Function: check_switches() * -------------------- * helper method to check whether a user's message is one of the installed messages * for the server client, which then responds accordingly: | /ping – tells the user that the server is running | /join – adds user to the chat room, messages not displayed otherwise | /leave – removes user from the chat room | /who – obtains the current list of ID’s in the chat room, return to the server * * paramaters: * ChatUser *chat_user: the user to add into the queue * Message *message: the user's message * * returns: int, 1 if the user's message was a switch case, 0 if it was not */ int check_switches(Message *message, ChatUser *chat_user){ int i; char sendback[BUFFERSIZE]; const char *switches[SWITCHCOUNT] = {"/ping", "/join", "/leave", "/who"}; for(i = 0; i < SWITCHCOUNT; i++){ if(strncmp(message->buffer, switches[i], (strlen(switches[i]) -1)) == 0){ strcpy(sendback,"\n"); if(i == WHO){ lqapply(myqueue, print); printf("IN WHO\n"); strcpy(curr_sender, message->user_id); curr_sender_socket = chat_user->usocket; lqapply(myqueue, send_user_in_room); } else if(i == PING){ strcpy(sendback,"SERVER: server is currently running...\n"); }else if(i == JOIN){ strcpy(sendback, add_user(chat_user)); }else if(i == LEAVE){ lqremove(myqueue, find_user, chat_user); lqapply(myqueue, print); strcpy(sendback,"SERVER: leaving the chat room..\n"); } /* send message back */ send(chat_user->usocket, sendback, BUFFERSIZE, 0); return TRUE; } } return FALSE; } /* * Function: send_out_message() * -------------------- * helper method to send a user's message to every other user, this checks * that the user is in the queue, concatinates the message, and calls lqapply() * to send that message to all other users * * paramaters: * ChatUser *chat_user: the user to add into the queue * Message *message: the user's message * * returns: NULL */ void send_out_message(Message *message, ChatUser *chat_user){ ChatUser *returned_user = (ChatUser *)malloc(sizeof(ChatUser)); returned_user = (ChatUser *)lqsearch(myqueue, find_user, chat_user); if(returned_user != NULL){ strcpy(public_message_tosend, combine_return_message(message)); strcpy(curr_sender, message->user_id); lqapply(myqueue, send_message_toall); } } /* * Function: new_connection() * -------------------- * A method to be called by a new thread to run asynchronously for every client * that requests a connection with the server, it continuously takes in and responds * to that client's messages * * paramaters: * void *newsocket: a Connection struct, which provides the socket have messages sent ot * * returns: 0 when the thread is finished */ void *new_connection(void *newsocket){ Connection *currsocket = (Connection *)newsocket; Message *message; int reclen; ChatUser *chat_user = (ChatUser *)malloc(sizeof(ChatUser)); message = (Message *)malloc(sizeof(Message)); while(1){ while ( (reclen = recv(currsocket->csocket, (struct Message *)message, sizeof(Message),0)) > 0) { printf("recieved message from %s: %s", message->user_id, message->buffer); strcpy(chat_user->name, message->user_id); chat_user->usocket = currsocket->csocket; if(check_switches(message, chat_user) == FALSE){ send_out_message(message, chat_user); } if (reclen < 0) { perror("Read error"); exit(1); } } } close(currsocket->csocket); return 0; } int main(int argc, char* argv[]){ int SERV_PORT = 0; struct sockaddr_in servaddr; struct sockaddr_in clientaddr; socklen_t addrlen = sizeof(servaddr); int newsocket, i, err; Connection *n_connection; /* user threads */ pthread_t tid[MAXPEOPLE]; /* current thread number */ int curr_conn_num = 0; myqueue = lqopen(); if(argc != 2){ printf("incorrect number of arguments."); return(0); } SERV_PORT = atoi(argv[1]); if ((sockfd = socket (AF_INET, SOCK_STREAM, 0)) <0) { perror("Problem in creating the socket"); exit(2); } /* create the socket */ memset((char *) &servaddr, 0, sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_addr.s_addr = htonl(INADDR_ANY); servaddr.sin_port = htons(SERV_PORT); /* bind the socket to the address */ if (bind(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr)) < 0) { printf("bind failed"); perror("bind failed"); return 0; } /* listen for incoming connections */ if(listen (sockfd, LISTENQ) == 0){ printf("server listening for clients...\n"); }else{ perror("listening failed...\n"); } /* accept all new connections from different clients, send them to a seperate thread */ while(1){ newsocket = accept(sockfd, (struct sockaddr *) &clientaddr, &addrlen); printf("Received new connection request, number %d...\n", curr_conn_num); n_connection = (Connection *)malloc(sizeof(Connection)); n_connection->csocket = newsocket; err = pthread_create(&tid[curr_conn_num], NULL, new_connection, n_connection); if (err != 0){ printf("\ncan't create thread"); return(1); } curr_conn_num++; } for(i = 0; i <= curr_conn_num; i++){ pthread_join(tid[i], NULL); } return(1); }
C
/*In the programming language of your choice, write a program generating the first n Fibonacci numbers F(n), printing ... - ... "Buzz" when F(n) is divisible by 3. - ... "Fizz" when F(n) is divisible by 5. - ... "BuzzFizz" when F(n) is prime. - ... the value F(n) otherwise. */ /* * Author : Navjot (Joti) Singh Dhalla * Date : 02/07/2016 */ #include <math.h> #include <stdio.h> #include <limits.h> #define ISPRIME 1 #define ISNOTPRIME 0 /*********************************************************************************** * Function: int isPrime(unsigned long long parm) * * PreCondition: none * * Input: parameter to checked * * Output: none * * Side Effects: none * * Overview: Test if number is prime. Algorithm is to check if parm * is divisible by any integer less than or equal to sqrt(parm). * If divisible, it's prime otherwise not * * Note: I could have used more complex algorithm such as "AKS", * but I think it's outside the scope of an interview question. ***********************************************************************************/ int isPrime(unsigned long long parm){ static unsigned long long numb; for(numb = 2; numb <= (unsigned long long)sqrt(parm); numb++){ if((parm%numb) == 0) return ISNOTPRIME; } return ISPRIME; } /*************************************************************************************** * Function: int main() * * PreCondition: none * * Input: none * * Output: none * * Side Effects: none * * Overview: This is the main function * * Note: The limitation of this program is that it could work max for F(93) ***************************************************************************************/ int main() { static unsigned long long t1, t2, n, qNumb, count; printf("Enter n for F(n) Fibonacci number of terms (n >= 0 and n <= 93):\r\n"); scanf("%llu", &n); /* For first two terms, just print the numbers */ if((n <= 1)&&(n > 0)){ printf("\r\n%llu", n); return 0; } else if(n == 2){ printf("\r\n%llu", (n-1)); return 0; } /* count is 3 because first three terms are already tested. */ count = 3; /* Initialize two terms t1 and t2; t0 was 0 */ t1 = 1; t2 = 1; /* Just basic implementation of Fibonacci Function F(n+1) = F(n) + F(n-1) */ while(count <= n){ qNumb = t1+t2; t1 = t2; t2 = qNumb; ++count; } /* Print the Fibonacci F(n) value */ printf("\r\nThe F(%llu) is %llu", n, qNumb); /* Test number for various conditions, and display as mentioned */ if(qNumb == 2){ /* 2 is prime number */ printf("\r\nBuzzFizz"); return 0; } else { if((qNumb % 3) == 0){ printf("\r\nBuzz"); if((qNumb % 5) == 0) printf("\r\nFizz"); } else if((qNumb % 5) == 0) printf("\r\nFizz"); else if((qNumb % 2) == 0) printf("\r\n%llu", qNumb); else if(isPrime(qNumb)) printf("\r\nBuzzFizz"); else printf("\r\n%llu", qNumb); return 0; } } /***********************************EOF***********************************************/
C
#include <stdarg.h> #include <stdio.h> int printf(const char *restrict s, ...) { int r; va_list ap; va_start(ap, s); r = vprintf(s, ap); va_end(ap); return r; }
C
#include "api.h" void police() { int y, x, z, color0, color1, i = -1; clearScreen(black); blink0: color0 = R; color1 = B; blink1: for (y = 0; y < (MAX_Y + ((i & 0x2)>>1))/2; y++) { for (x = 0; x < MAX_X; x++) { for (z = 0; z < MAX_Z; z++) { imag[z][y][x][color0] = 255; imag[z][y][x][color1] = 0; } } } for (y = (MAX_Y + ((i & 0x2)>>1))/2; y < MAX_Y; y++) { for (x = 0; x < MAX_X; x++) { for (z = 0; z < MAX_Z; z++) { imag[z][y][x][color0] = 0; imag[z][y][x][color1] = 255; } } } swapAndWait(120); clearScreen(black); swapAndWait(100); i++; if (0x1 & i) { goto blink1; } swapAndWait(300); if (i > 20) goto end; if (0x1 & i>>1) { color0 = B; color1 = R; goto blink1; } goto blink0; end: swapAndWait(5000); }
C
#include <string.h> #include "agile_chtbl.h" int agile_chtbl_init(agile_chtbl* htbl, int buckets, int(*h)(const void*), int(*match)(const void*,const void*), void(*destroy)(void*)) { int i; if ((htbl->table=(agile_list*)malloc(buckets*sizeof(agile_list)))==NULL) return -1; htbl->buckets = buckets; for (i = 0; i < buckets; ++i) { agile_list_init(&htbl->table[i], destroy); } htbl->h = h; htbl->match = match; htbl->destroy = destroy; htbl->size = 0; return 0; } void agile_chtbl_destroy(agile_chtbl* htbl) { int i; for (i=0; i<htbl->buckets; ++i) { agile_list_destroy(&htbl->table[i]); } free(htbl->table); memset(htbl, 0, sizeof(agile_chtbl)); } int agile_chtbl_insert(agile_chtbl* htbl, const void* data) { void* temp; int bucket; int retval; temp = (void*)data; if (agile_chtbl_lookup(htbl, &temp)==0) return 1; bucket = htbl->h(data) % htbl->buckets; if ((retval = agile_list_ins_next(&htbl->table[bucket],NULL,data))==0) htbl->size += 1; return retval; } int agile_chtbl_remove(agile_chtbl* htbl, void** data) { agile_list_element* element; agile_list_element* prev; int bucket; bucket = htbl->h(*data) % htbl->buckets; prev = NULL; for (element=agile_list_head(&htbl->table[bucket]); element!=NULL; element=agile_list_next(element)) { if (htbl->match(*data, agile_list_data(element))) { if (agile_list_rem_next(&htbl->table[bucket], prev, data)==0) { htbl->size -= 1; return 0; } else { return -1; } } prev = element; } return -1; } int agile_chtbl_lookup(const agile_chtbl* htbl, void** data) { agile_list_element* element; int bucket; bucket = htbl->h(*data) % htbl->buckets; for (element=agile_list_head(&htbl->table[bucket]); element!=NULL; element=agile_list_next(element)) { if (htbl->match(*data, agile_list_data(element))) { *data = agile_list_data(element); return 0; } } return -1; } ////////////////////////////// #include "test_common.h" #include "agile_hash.h" void test_agile_chtbl() { agile_chtbl htbl; agile_chtbl_init(&htbl, 10, agile_string_hash, string_match, free); char* data1 = get_data(1); agile_chtbl_insert(&htbl, data1); char* data2 = get_data(2); agile_chtbl_insert(&htbl, data2); char* data3 = get_data(3); agile_chtbl_insert(&htbl, data3); printf("lookup data2: %d\n", agile_chtbl_lookup(&htbl,(void**)&data2)); agile_chtbl_remove(&htbl,(void**)&data2); printf("lookup data2: %d\n", agile_chtbl_lookup(&htbl,(void**)&data2)); free(data2); agile_chtbl_destroy(&htbl); }
C
// Link of the problem (language PT-BR): http://br.spoj.com/problems/MINADO12/ // (Name of the problem) MINADO12 - Campo minado #include<stdio.h> int main(void){ int N; scanf("%d", &N); int mina[N]; int minar[N]; for (int i = 0; i < N; i++){ scanf("%d", &mina[i]); minar[i] = 0; } for (int i = 0; i < N; i++){ if (mina[i] == 1){ minar[i-1]+= 1; minar[i]+= 1; minar[i+1]+= 1; } } for (int i = 0; i < N; i++){ printf("%d\n", minar[i]); } return 0; }
C
/** Writes len bytes of value c (converted to an unsigned char) to the string b. **/ #include "libft.h" void *ft_memset(void *b, int c, size_t len) { unsigned char *tb; tb = (unsigned char*)b; tb[len] = '\0'; while (len--) { tb[len] = (unsigned char)c; } return (b); }
C
typedef struct no{ int moda; int quantidade; struct no * prox; }Dno; typedef struct { Dno * inicio; }Dlista; Dlista * Create_Lista(){ Dlista * novo = (Dlista*)malloc(sizeof(Dlista)); if(novo){ novo->inicio = NULL; }else puts("No Alocou\n"); return novo; } int Inserir_Lista(Dlista* L, int moda, int quantidade){ Dno* aux; aux = L->inicio; while(aux != NULL){ if(aux->moda == moda) return 0; aux = aux->prox; } Dno* novo = (Dno*)malloc(sizeof(Dno)); if(novo){ novo->moda = moda; novo->quantidade = quantidade; novo->prox = NULL; }else return 0; if(!L->inicio){ L->inicio = novo; return 1; }else{ aux = L->inicio; while(aux->prox != NULL) aux = aux->prox; aux->prox = novo; return 1; } } //void zerar_lista(Dlista* L){ // Dno * aux; // aux = L->inicio; // int i = 0; // // while(aux != NULL){ // aux = aux->prox; // } // free //} void imprimir(Dlista* L){ Dno * aux; int i = 0; aux = L->inicio; while(aux != NULL){ printf("\nO numero %d repetiu %d vezes na serie\n",aux->moda, aux->quantidade); aux = aux->prox; i++; } if(i == 0){ printf("\nNo tem Moda\n"); } else if(i == 1) printf("\nClassificao: Moda Normal\n"); else if(i == 2) printf("\nClassificao: Moda Bimodal\n"); else printf("\nClassificao: Multimodal\n"); } void ordenar(float *vetor, int k) { int i,j,aux; for(i=0;i<k-1;i++) for(j=0;j<k-1;j++) { if(vetor[j]>vetor[j+1]) { aux=vetor[j]; vetor[j]=vetor[j+1]; vetor[j+1]=aux; } } } float media(float *vetor, int tam) { float soma = 0,media; int i; for(i=0;i<tam;i++) soma+=vetor[i]; media=soma/tam; printf("\nA media = %.2f\n",media); return media; } float mediana(float *vetor, int tam) { float mediana; if(tam%2==0) { mediana=(vetor[(tam/2)-1]+vetor[((tam/2)+1)-1])/2; printf("\nA Mediana = %.2f\n",mediana); return mediana; } else { mediana=vetor[((tam+1)/2)-1]; printf("\nA Mediana = %.2f\n",mediana); return mediana; } } void ponto_medio(float *vetor, int tam) { float ponto_medio; ponto_medio=(vetor[tam-1]+vetor[0])/2; printf("\nO valor do Ponto Mdio = %.2f\n",ponto_medio); } void moda(float *vetor, int tam, Dlista* L) { int cont=0,i,j; for(i=0;i<tam;i++) { for(j=0;j<tam;j++) { if(vetor[i]==vetor[j]) cont++; } if(cont > 1){ Inserir_Lista(L,vetor[i],cont); } cont=0; } } void curtose(int tam){ float curtose, quartil1 = 25, decil1 = 10, quartil2 = 75, decil2 = 90; quartil1=(quartil1*tam)/100; decil1=(quartil1*tam)/100; quartil2=(quartil2*tam)/100; decil2=(quartil2*tam)/100; curtose = (((quartil2 - quartil1)) / 2*(decil2 - decil1)); if(curtose<0.263){ printf("\nCurva Leptocrtica %.2f \n",curtose); }else{ if(curtose>0.263){ printf("\nCurva Platicrtica%.2f \n",curtose); }else printf("\nCurva Mesocrtica %.2f \n",curtose); } } void Assimetria(float *vetor, int tam, Dlista * L){ float soma = 0,media; int i; for(i=0;i<tam;i++) soma+=vetor[i]; media=soma/tam; float mediana; if(tam%2==0) { mediana=(vetor[(tam/2)-1]+vetor[((tam/2)+1)-1])/2; } else { mediana=vetor[((tam+1)/2)-1]; } Dno * aux; i = 0; float maior, moda; aux = L->inicio; if(L->inicio){ moda = L->inicio->moda; maior = L->inicio->quantidade; } while(aux != NULL){ if(aux->quantidade > maior){ maior = aux->quantidade; moda = aux->moda; } aux = aux->prox; i++; } if(i == 0){ moda = 0; } printf("Moda = %d", moda); if((media == mediana) && (mediana == moda)) puts("\nA curva da distribuio SIMTRICA\n"); else if((media < mediana) && (mediana < moda)) puts("\nA curva da distribuio ASSIMETRIA NEGATIVA\n"); else if((media > mediana) && (mediana > moda)) puts("\nA curva da distribuio ASSIMETRIA POSITIVA\n"); else puts("No detectou Simetria"); } void amplitude(float *vetor,int tam){ int i; float maior,menor,result; maior=vetor[0]; menor=vetor[0]; for(i=0;i<tam;i++){ if(maior<vetor[i]){ maior=vetor[i]; } if(menor>vetor[i]){ menor=vetor[i]; } } result=maior-menor; printf("\nA amplitude = %.2f \n",result); } void desvio(float *vetor,int tam){ int i,tam2=tam-1; float soma = 0,media=0,desvio_a,desvio_p,result1,result2,cv; for(i=0;i<tam;i++) soma+=vetor[i]; media=soma/tam; for(i=0;i<tam;i++){ vetor[i]=vetor[i]-media; } for(i=0;i<tam;i++){ vetor[i]=vetor[i]*vetor[i]; } soma=0; for(i=0;i<tam;i++){ soma+=vetor[i]; } desvio_a=soma/tam2; desvio_p=soma/tam; result1=sqrt( desvio_a ); result2=sqrt(desvio_p); cv=desvio_a/media; printf("\nO coeficiente de variacao = %.2f\n",cv); printf("\nO desvio amostral ou padro = %.2f\n",result1); printf("\nO desvio populacional = %.2f\n",result2); } void desvio_medio(float *vetor,int tam){ int i; float soma = 0,media=0,desvio_m; for(i=0;i<tam;i++) soma+=vetor[i]; media=soma/tam; for(i=0;i<tam;i++){ vetor[i]=vetor[i]-media; } for(i=0;i<tam;i++){ soma+=vetor[i]; } desvio_m=soma/tam; printf("\nO desvio medio = %.2f\n",desvio_m); } void variancia(float *vetor,int tam){ int i,tam2=tam-1; float soma = 0,media=0,variancia_a,variancia_p; for(i=0;i<tam;i++) soma+=vetor[i]; media=soma/tam; for(i=0;i<tam;i++){ vetor[i]=vetor[i]-media; } for(i=0;i<tam;i++){ vetor[i]=vetor[i]*vetor[i]; } soma=0; for(i=0;i<tam;i++){ soma+=vetor[i]; } variancia_a=soma/tam2; variancia_p=soma/tam; printf("\nA variancia amostral = %.2f\n",variancia_a); printf("\nA variancia populacional = %.2f\n",variancia_p); }
C
#include<stdio.h> int main() { switch(cas()) { case 1: al(); break; case 2: apl(); break; case 3: exit(0); default : printf("Invalid Choice "); } } int cas() { int ch; printf("\n1.a"); printf("\n2.b"); printf("\n3.Exit"); printf("\nEnter Your Choice: "); scanf("%d",&ch); return(ch); } int ca() { int ch; printf("\n1.a"); printf("\n2.b"); printf("\nEnter Your Choice: "); scanf("%d",&ch); return(ch); } void al() { switch(ca()) { case 1: printf("a"); break; case 2: printf("b"); break; default : printf("Invalid Choice"); } } void apl() { switch(ca()) { case 1: printf("A"); break; case 2: printf("B"); break; default : printf("Invalid Choice"); } }
C
/* * (C) Iain Fraser - GPLv3 * Sythentic generic machine instructions. */ #include <stdarg.h> #include "emitter.h" #include "machine.h" void assign( struct machine_ops* mop, struct emitter* e, struct machine* m, vreg_operand d, vreg_operand s ) { mop->move( e, m, d.value, s.value ); mop->move( e, m, d.type, s.type ); } void loadim( struct machine_ops* mop, struct emitter* e, struct machine* m, int reg, int value ) { operand r = OP_TARGETREG( reg ); operand v = OP_TARGETIMMED( value ); mop->move( e, m, r, v ); } void pushn( struct machine_ops* mop, struct emitter* e, struct machine* m, int nr_operands, ... ){ va_list ap; const operand stack = OP_TARGETREG( m->sp ); va_start( ap, nr_operands ); if( nr_operands == 1 && mop->push ){ mop->push( e, m, va_arg( ap, operand ) ); } else { for( int i = 0; i < nr_operands; i++ ) mop->move( e, m, OP_TARGETDADDR( m->sp, -4 * ( i + 1 ) ), va_arg( ap, operand ) ); mop->add( e, m, stack, stack, OP_TARGETIMMED( -4 * nr_operands ) ); } va_end( ap ); } void popn( struct machine_ops* mop, struct emitter* e, struct machine* m, int nr_operands, ... ){ va_list ap; const operand stack = OP_TARGETREG( m->sp ); va_start( ap, nr_operands ); if( nr_operands == 1 && mop->pop ){ mop->pop( e, m, va_arg( ap, operand ) ); } else { for( int i = 0; i < nr_operands; i++ ) mop->move( e, m, va_arg( ap, operand ), OP_TARGETDADDR( m->sp, 4 * i ) ); mop->add( e, m, stack, stack, OP_TARGETIMMED( 4 * nr_operands ) ); } va_end( ap ); } // this function could be inline void syn_memcpyw( struct machine_ops* mop, struct emitter* e, struct machine* m, operand d, operand s, operand size ){ operand iter = OP_TARGETREG( acquire_temp( mop, e, m ) ); operand src = OP_TARGETREG( acquire_temp( mop, e, m ) ); operand dst = OP_TARGETREG( acquire_temp( mop, e, m ) ); // init iterator mop->move( e, m, iter, OP_TARGETIMMED( 0 ) ); mop->move( e, m, src, s ); mop->move( e, m, dst, d ); // start loop e->ops->label_local( e, 0 ); mop->beq( e, m, iter, size, LBL_NEXT( 0 ) ); // copy mop->move( e, m, OP_TARGETDADDR( dst.reg, 0 ), OP_TARGETDADDR( src.reg, 0 ) ); // update pointers mop->add( e, m, dst, dst, OP_TARGETIMMED( -4 ) ); // TODO: this is incorrect in general but correct for copyargs mop->add( e, m, src, src, OP_TARGETIMMED( -4 ) ); // update iterator mop->add( e, m, iter, iter, OP_TARGETIMMED( 1 ) ); mop->b( e, m, LBL_PREV( 0 ) ); e->ops->label_local( e, 0 ); release_tempn( mop, e, m, 3 ); } void syn_memsetw( struct machine_ops* mop, struct emitter* e, struct machine* m, operand d, operand v, operand size ){ operand iter = OP_TARGETREG( acquire_temp( mop, e, m ) ); operand dst = OP_TARGETREG( acquire_temp( mop, e, m ) ); // init iterator mop->move( e, m, iter, OP_TARGETIMMED( 0 ) ); mop->move( e, m, dst, d ); // start loop e->ops->label_local( e, 0 ); mop->beq( e, m, iter, size, LBL_NEXT( 0 ) ); // copy mop->move( e, m, OP_TARGETDADDR( dst.reg, 0 ), v ); // update pointers mop->add( e, m, dst, dst, OP_TARGETIMMED( 4 ) ); // update iterator mop->add( e, m, iter, iter, OP_TARGETIMMED( 1 ) ); mop->b( e, m, LBL_PREV( 0 ) ); e->ops->label_local( e, 0 ); release_tempn( mop, e, m, 2 ); } void syn_min( struct machine_ops* mop, struct emitter* e, struct machine* m, operand d, operand s, operand t ){ mop->blt( e, m, s, t, LBL_NEXT( 0 ) ); mop->move( e, m, d, t ); mop->b( e, m, LBL_NEXT( 1 ) ); e->ops->label_local( e, 0 ); mop->move( e, m, d, s ); e->ops->label_local( e, 1 ); } void syn_max( struct machine_ops* mop, struct emitter* e, struct machine* m, operand d, operand s, operand t ){ mop->blt( e, m, s, t, LBL_NEXT( 0 ) ); mop->move( e, m, d, t ); mop->b( e, m, LBL_NEXT( 1 ) ); e->ops->label_local( e, 0 ); mop->move( e, m, d, s ); e->ops->label_local( e, 1 ); }
C
#include<stdio.h> #include<string.h> #include<stdlib.h> int cmpfunc (const void * a, const void * b) { return ( *(int*)a - *(int*)b ); } int main() { int n,m,i,sum,sum1=0,temp,j; scanf("%d",&n); int a[n]; for(i=0;i<n;i++) { scanf("%d",&a[i]); sum1=sum1+a[i]; } scanf("%d",&m); int b[m]; for(i=0;i<m;i++) { scanf("%d",&b[i]); } qsort(a,n,sizeof (int),cmpfunc); for(j=0;j<m;j++) { sum=sum1-a[n-(b[j]-1+1)]; printf("%d\n",sum); } return 0; }
C
#include <android/log.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/stat.h> #include <sys/types.h> #include <fcntl.h> #include <unistd.h> #include <dirent.h> #include <linux/limits.h> #include <sys/sendfile.h> #include <dlfcn.h> #define MOD_PATH "/sdcard/Android/data/com.DefaultCompany.Mod_Test/files/mods/" #define MOD_TEMP_PATH "/data/data/com.DefaultCompany.Mod_Test/cache/curmod.so" void load_mods() { __android_log_write(ANDROID_LOG_INFO, "QuestHook", "Loading mods!"); const char* mods = "/sdcard/Android/data/com.beatgames.beatsaber.demo/files/mods/"; struct stat statBuf; //mkdir does not seem to work if (stat(mods, &statBuf) == 0) { __android_log_write(ANDROID_LOG_INFO, "QuestHook", "Directory for Mods exist"); } else { __android_log_write(ANDROID_LOG_INFO, "QuestHook", "Directory for Mods does not exist"); __android_log_print(ANDROID_LOG_INFO, "QuestHook", "mkdir = %d", mkdir("/sdcard/Android/data/com.beatgames.beatsaber.demo/files/mods/", 0777)); } DIR* dir; struct dirent* file_list; __android_log_write(ANDROID_LOG_INFO, "QuestHook", "Entry is created"); dir = opendir(mods); if (dir == NULL) { __android_log_write(ANDROID_LOG_INFO, "QuestHook", "No mod"); } else { file_list = readdir(dir); while (file_list != NULL) { // Only attempts to load .so files if (strlen(file_list->d_name) > 3 && !strcmp(file_list->d_name + strlen(file_list->d_name) - 3, ".so")) { char full_path[PATH_MAX] = "/sdcard/Android/data/com.beatgames.beatsaber.demo/files/mods/"; strcat(full_path, file_list->d_name); __android_log_print(ANDROID_LOG_INFO, "QuestHook", "Loading mod: %s", full_path); // Get filesize of mod int infile = open(full_path, O_RDONLY); off_t filesize = lseek(infile, 0, SEEK_END); lseek(infile, 0, SEEK_SET); // Unlink old file unlink(MOD_TEMP_PATH); // Creates temporary copy (we can't execute stuff in /sdcard so we need to copy it over) int outfile = open(MOD_TEMP_PATH, O_WRONLY | O_CREAT, 0600); sendfile(outfile, infile, 0, filesize); close(infile); close(outfile); // Mark copy as executable chmod(MOD_TEMP_PATH, S_IRUSR | S_IWUSR | S_IXUSR | S_IRGRP | S_IWGRP | S_IXGRP); // and load it dlopen(MOD_TEMP_PATH, RTLD_NOW); } file_list = readdir(dir); } closedir(dir); } __android_log_write(ANDROID_LOG_INFO, "QuestHook", "Done loading mods!"); } __attribute__((constructor)) void lib_main() { __android_log_write(ANDROID_LOG_INFO, "QuestHook", "Welcome Mod!"); load_mods(); }
C
/* ** EPITECH PROJECT, 2017 ** File Name : disp_env.c ** File description: ** by Arthur Teisseire */ #include <stddef.h> #include "my.h" void disp_env(char **env) { int i = 0; while (env[i] != NULL) { bufferize(env[i]); if (!is_char_in_str('=', env[i])) bufferize("="); bufferize("\n"); i++; } bufferize(NULL); }
C
// // Created by human on 29.02.2020. // #ifndef GRAPHICSTEST_FLOAT4_H #define GRAPHICSTEST_FLOAT4_H #include <math.h> #include <immintrin.h> typedef struct vec4_t { union { struct {float f0, f1, f2, f3;}; struct {unsigned u0, u1, u2, u3;}; float fdata[4]; }; }vec4_t; static inline struct vec4_t fvec4(float s0, float s1, float s2, float s3){ return (vec4_t) { s0, s1, s2, s3 }; } static inline struct vec4_t fvec4_p0000_init(float value){ return (vec4_t){ value, value,value,value }; } static inline float fvec4_length(struct vec4_t v){ return sqrtf(v.f0 * v.f0 + v.f1 * v.f1 + v.f2 * v.f2 + v.f3 * v.f3); } static inline float fvec4_sum(struct vec4_t v){ return v.f0 + v.f1 + v.f2 + v.f3; } static inline struct vec4_t fvec4_div(struct vec4_t nominator, struct vec4_t denominator){ struct vec4_t result; result.f0 = nominator.f0 / denominator.f0; result.f1 = nominator.f1 / denominator.f1; result.f2 = nominator.f2 / denominator.f2; result.f3 = nominator.f3 / denominator.f3; return result; } static inline struct vec4_t fvec4_mul(struct vec4_t nominator, struct vec4_t denominator){ struct vec4_t result; result.f0 = nominator.f0 * denominator.f0; result.f1 = nominator.f1 * denominator.f1; result.f2 = nominator.f2 * denominator.f2; result.f3 = nominator.f3 * denominator.f3; return result; } static inline struct vec4_t fvec4_add(struct vec4_t nominator, struct vec4_t denominator){ struct vec4_t result; result.f0 = nominator.f0 + denominator.f0; result.f1 = nominator.f1 + denominator.f1; result.f2 = nominator.f2 + denominator.f2; result.f3 = nominator.f3 + denominator.f3; return result; } static inline struct vec4_t fvec4_sub(struct vec4_t nominator, struct vec4_t denominator){ struct vec4_t result; result.f0 = nominator.f0 - denominator.f0; result.f1 = nominator.f1 - denominator.f1; result.f2 = nominator.f2 - denominator.f2; result.f3 = nominator.f3 - denominator.f3; return result; } static inline struct vec4_t fvec4_normalize(struct vec4_t v){ return fvec4_div(v,fvec4_p0000_init(fvec4_length(v))); } static inline struct vec4_t fvec4_cross3(struct vec4_t v0, struct vec4_t v1) { struct vec4_t result = fvec4( v0.f1 * v1.f2 - v1.f1 * v0.f2, v0.f2 * v1.f0 - v0.f0 * v1.f2, v0.f0 * v1.f1 - v0.f1 * v1.f0, 0 ); return result; } #endif //GRAPHICSTEST_FLOAT4_H
C
/******************************************************************************* * @author : Rohan Jyoti * @filename : mFileLib.h * @purpose : File Generator for Testing Purposes ******************************************************************************/ #ifndef mFileGen_h #define mFileGen_h #define _GNU_SOURCE #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdarg.h> #endif int main(int argc, char *argv[]) { if(argc != 3) { fprintf(stderr, "Input Error. Arguments must be as follows:\n"); fprintf(stderr, "argv[1] will be Filename to output to\n"); fprintf(stderr, "argv[2] will be File Size in MBs\n"); return -1; } char *filename = argv[1]; int fileSize = atoi(argv[2]); int total_bytes_written = 0; int total_bytes_needed = 1024 * 1024 * fileSize; //open file for binary writing FILE *mFile = fopen(filename, "wb"); if(mFile == NULL) { fprintf(stderr, "File Cannot be opened/created\n"); exit(1); } int line_num = 0; while(total_bytes_written < total_bytes_needed) { char *tempStr; asprintf(&tempStr, "This is a testfile testline for testing purposes. Line %d.\n", line_num); fwrite(tempStr, 1, strlen(tempStr), mFile); total_bytes_written += strlen(tempStr); line_num++; } fclose(mFile); printf("%d MB File: %s created.\n", fileSize, filename); return 0; }
C
/* * threadPool.c * lab05lect * * Created by AJ Bieszczad on 2/17/09. * Copyright 2009 CSUCI. All rights reserved. * */ /* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #if !defined(_GNU_SOURCE) #define _GNU_SOURCE #endif #include <pthread.h> #include <stdlib.h> #include <stdio.h> /* * <Variable Initialization> */ //task structure struct task { int task_id; void (*function_pointer)(void); struct task* next; }; //total tasks int total_tasks = 0; //request errors int request_errors = 0; //recursive mutex // DOES NOT COMPILE ON Mac // pthread_mutex_t task_queue_mutex = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP; pthread_mutex_t task_queue_mutex = PTHREAD_MUTEX_INITIALIZER; //conditional variable pthread_cond_t active_task = PTHREAD_COND_INITIALIZER; //thread ID's int thr_id[]; //thread array pthread_t p_threads[]; //linked list head struct task* tasks = NULL; //last node struct task* bottom_task = NULL; /* * </Variable Initializaiton> */ /* * <ThreadPool Methods> */ void *add_task(int task_num, pthread_mutex_t* mutex, pthread_cond_t* cond, void (*fp)(void)) { struct task* enqueue_task; int rs = 0; //return status enqueue_task = (struct task*)malloc(sizeof(struct task)); if (!enqueue_task) { request_errors++; return NULL; } enqueue_task->task_id = task_num; enqueue_task->function_pointer = fp; enqueue_task->next = NULL; rs = pthread_mutex_lock(mutex); if (total_tasks == 0) { tasks = enqueue_task; bottom_task = enqueue_task; } else { bottom_task->next = enqueue_task; bottom_task = enqueue_task; } total_tasks++; rs = pthread_mutex_unlock(mutex); rs = pthread_cond_signal(cond); return NULL; } struct task* get_task(pthread_mutex_t* mutex) { int rs; struct task* task; rs = pthread_mutex_lock(mutex); if (total_tasks > 0) { task = tasks; tasks = task->next; if (tasks == NULL) { bottom_task = NULL; } total_tasks--; } else { task = NULL; } rs = pthread_mutex_unlock(mutex); return task; } void execute_task(struct task* task, int thread_id) { if (task) { } } void* handle_requests_loop(void* data) { int rs; struct task* task; int thread_id = *((int*)data); rs = pthread_mutex_lock(&task_queue_mutex); while (1) { if (total_tasks > 0) { task = get_task(&task_queue_mutex); if (task) { rs = pthread_mutex_unlock(&task_queue_mutex); execute_task(task, thread_id); free(task); rs = pthread_mutex_lock(&task_queue_mutex); } else { rs = pthread_cond_wait(&active_task, &task_queue_mutex); } } } } int thread_pool_init(int num_threads) { int iterator; for (iterator = 0; iterator < num_threads; iterator++) { thr_id[iterator] = iterator; pthread_create(&p_threads[iterator], NULL, handle_requests_loop, (void *)&thr_id[iterator]); } return 0; } /* * </ThreadPool Methods> */ void func() { printf("Hello\n"); } int main() { thread_pool_init(8); int i; void (*x)(void); x = func; for (i = 0; i < 11; i++) { add_task(i, &task_queue_mutex, &active_task, *x); } return 0; }
C
/* * Shedular_program.c * * Created on: 12 Mar 2020 * Author: Basma Abdelhakim */ #include "../03-LIB/STD_TYPES.h" #include "../01-MCAL/01-RCC/RCC_interface.h" #include "../01-MCAL/03-SYSTIC/SYSTIC_interface.h" #include "Schedular_interface.h" typedef struct { basic_task_info * task; u32 periodicityTicksMs; u32 ticsToExec; u8 taskStatus; } SysTasks_t; /**************************************Global variables*******************************************/ extern basic_task_info sys_tasks_info [MAX_NUMBER_OF_TASKS]; static SysTasks_t sysTasks[MAX_NUMBER_OF_TASKS]; u8 currentTaskRunning=0; u8 OS_FLAG = 0; /************************************************************************************************/ /*****************************************Functions**********************************************/ /************************************************************************************************/ void setOs_Flag(void) { OS_FLAG = 1; } /************************************************************************************************/ void schedular_init(void) { u32 inputClock; u32 TicTimeUs; for(currentTaskRunning=0;currentTaskRunning<MAX_NUMBER_OF_TASKS;currentTaskRunning++){ sysTasks[currentTaskRunning].task= &sys_tasks_info[currentTaskRunning]; sysTasks[currentTaskRunning].periodicityTicksMs=(sys_tasks_info[currentTaskRunning].task->periodicity_ms) / Tic_Time_MS; sysTasks[currentTaskRunning].ticsToExec= sys_tasks_info[currentTaskRunning].firstDelay / Tic_Time_MS ; sysTasks[currentTaskRunning].taskStatus=READY_STATUS; } SysTic_init(); RCC_GetSystemClock(&inputClock); TicTimeUs=Tic_Time_MS*1000; SysTic_SetTime(TicTimeUs, inputClock); SysTic_SetCallBackFun(setOs_Flag); } /************************************************************************************************/ void schedular_start(void){ SysTic_start(); while(1){ if(OS_FLAG){ OS_FLAG=0; start_OS(); } } } /************************************************************************************************/ void start_OS(void){ u8 i=0; for(i=0;i<MAX_NUMBER_OF_TASKS;i++){ if(sysTasks[i].ticsToExec==0 && sysTasks[i].taskStatus==READY_STATUS){ sysTasks[i].task->task->taskRunnable(); sysTasks[i].ticsToExec=sysTasks[i].periodicityTicksMs; } sysTasks[i].ticsToExec--; } } /************************************************************************************************/
C
#include "holberton.h" /** * check - checks if n has a square root recursively * @n: number to check against * @x: potential square root, increments with recursion * * Return: square root of n, else -1 if no valid square root */ int check(int n, int x) { if ((float)n / (float)x == (float)x) return (x); if ((float)n / (float)x < (float)x) return (-1); return (check(n, x + 1)); } /** * _sqrt_recursion - returns the square root of n using recurison * @n: number to be.. square rooted? * * Return: square root of n, else -1 when n doesnt have one */ int _sqrt_recursion(int n) { if (n < 0) return (-1); if (n == 0) return (0); return (check(n, 1)); }
C
#ifndef VECTOR4D_D_H #define VECTOR4D_D_H #include <math.h> struct vector_4d { double x; double y; double z; double w; vector_4d (double _x = 0, double _y = 0, double _z = 0, double _w = 0) : x (_x), y (_y), z (_z), w (_w) { } static vector_4d subtract (vector_4d a, vector_4d b) { return {a.x - b.x, a.y - b.y, a.z - b.z, a.w - b.w}; } // static vector_4d // normal (vector_4d a, vector_4d b, vector_4d c) // { // auto x = subtract (b, a); // auto y = subtract (c, a); // vector_4d normal = {x.y * y.z - x.z * y.y, -x.x * y.z + x.z * y.x, // x.x * y.y - x.y * y.x}; // double len = normal.length (); // return {normal.x / len, normal.y / len, normal.z / len}; // } double length () { return sqrt (x * x + y * y + z * z + w * w); } void setZ (double z) { this->z = z; } void setX (double x) { this->x = x; } void setY (double y) { this->y = y; } void setW (double w) { this->w = w; } }; #endif // VECTOR4D_D_H
C
/* * File Name: client.c * version: 1.0 * Author: William Collins * Date: 1/30/2012 * Assignment: Lab #6 * Course: Real Time Programming * Code: CST8244 * Professor: Saif Terai * Due Date: 2/13/2012 * Submission * Type: Email Submission * Destination * Address: [email protected] * Subject Line: CST 8244, F11, Lab 6 * Description: Sends an x and y value to the server, and recieves a product in response */ #include <stdlib.h> #include <stdio.h> #include <sys/iofunc.h> #include <sys/dispatch.h> #include <sys/netmgr.h> #include <unistd.h> #include "prod.h" #define MY_PULSE_CODE _PULSE_CODE_MINAVAIL typedef union { struct _pulse pulse; /* your other message structures would go here too */ } my_message_t; void *run_thread1(void *); void *run_thread2(void *); struct prod msg1; //Message to hold variables and product struct prod msg2; /******************************************************************************************** * Function Name main() * Version 1.0 * Author William Collins * Purpose * Inputs command line arguments * Outputs Returns an integer, '0' on successful completion, '1' if an error * occurred. *********************************************************************************************/ int main(int argc, char *argv[]) { pthread_t t1, t2; // a place to hold the thread ID's pthread_attr_t attrib; // scheduling attributes struct sched_param param; // for setting priority int policy; /* * Create the new threads using Round Robin scheduling. The thread attribute structure * needs to be set up for creation. */ pthread_getschedparam( pthread_self(), &policy, &param ); pthread_attr_init (&attrib); pthread_attr_setinheritsched (&attrib, PTHREAD_EXPLICIT_SCHED); pthread_attr_setschedpolicy (&attrib, SCHED_RR); param.sched_priority = 10; // we don't want a very high priority pthread_attr_setschedparam (&attrib, &param); //Assign default values pthread_create(&t1, &attrib, run_thread1, NULL); pthread_create(&t2, &attrib, run_thread2, NULL); pthread_join(t1, NULL); pthread_join(t2, NULL); return EXIT_SUCCESS; } void *run_thread1(void *param){ int coid; int status; struct sigevent event; struct itimerspec itime; timer_t timer_id; int chid; int rcvid; my_message_t msg; chid = ChannelCreate(0); event.sigev_notify = SIGEV_PULSE; event.sigev_coid = ConnectAttach(ND_LOCAL_NODE, 0, chid, _NTO_SIDE_CHANNEL, 0); event.sigev_priority = getprio(0); event.sigev_code = MY_PULSE_CODE; timer_create(CLOCK_REALTIME, &event, &timer_id); itime.it_value.tv_sec = 1; /* 500 million nsecs = .5 secs */ itime.it_value.tv_nsec = 250000000; itime.it_interval.tv_sec = 1; /* 500 million nsecs = .5 secs */ itime.it_interval.tv_nsec = 250000000; timer_settime(timer_id, 0, &itime, NULL); /* * As of the timer_settime(), we will receive our pulse * in 1.5 seconds (the itime.it_value) and every 1.5 * seconds thereafter (the itime.it_interval) */ //Connect to the server printf("Thread 1: Connecting to server %s...\n",SERVER_NAME); coid = name_open(SERVER_NAME, 0); //Determine if the connection was successful if(-1 == coid) { //was there an error attaching to server? perror("ConnectAttach"); //look up error code and print exit(EXIT_FAILURE); } else { printf( "Successfully connected.\n"); } while(1) { rcvid = MsgReceive(chid, &msg, sizeof(msg), NULL); if (rcvid == 0) { /* we got a pulse */ if (msg.pulse.code == MY_PULSE_CODE) { msg1.x = rand(); msg1.y = rand(); //Send the message to server and get the reply status = MsgSend(coid, &msg1, sizeof msg1, &msg1.product, sizeof msg1.product); //Check for communication errors if(-1 == status) { //was there an error sending to server? perror("MsgSend"); exit(EXIT_FAILURE); } else { printf( "Thread 1: The product of %d and %d is %d\n", msg1.x, msg1.y, msg1.product ); }; } /* else other pulses ... */ } /* else other messages ... */ } //Make sure to close resources name_close(coid); return NULL; } void *run_thread2(void *param){ int coid; int status; struct sigevent event; struct itimerspec itime; timer_t timer_id; int chid; int rcvid; my_message_t msg; chid = ChannelCreate(0); event.sigev_notify = SIGEV_PULSE; event.sigev_coid = ConnectAttach(ND_LOCAL_NODE, 0, chid, _NTO_SIDE_CHANNEL, 0); event.sigev_priority = getprio(0); event.sigev_code = MY_PULSE_CODE; timer_create(CLOCK_REALTIME, &event, &timer_id); itime.it_value.tv_sec = 1; /* 500 million nsecs = .5 secs */ itime.it_value.tv_nsec = 750000000; itime.it_interval.tv_sec = 1; /* 500 million nsecs = .5 secs */ itime.it_interval.tv_nsec = 750000000; timer_settime(timer_id, 0, &itime, NULL); //Connect to the server printf("Thread 2: Connecting to server %s...\n",SERVER_NAME); coid = name_open(SERVER_NAME, 0); //Determine if the connection was successful if(-1 == coid) { //was there an error attaching to server? perror("ConnectAttach"); //look up error code and print exit(EXIT_FAILURE); } else { printf( "Successfully connected.\n"); } /* * As of the timer_settime(), we will receive our pulse * in 1.5 seconds (the itime.it_value) and every 1.5 * seconds thereafter (the itime.it_interval) */ while(1) { rcvid = MsgReceive(chid, &msg, sizeof(msg), NULL); if (rcvid == 0) { /* we got a pulse */ if (msg.pulse.code == MY_PULSE_CODE) { msg2.x = rand(); msg2.y = rand(); //Send the message to server and get the reply status = MsgSend(coid, &msg2, sizeof msg2, &msg2.product, sizeof msg2.product); //Check for communication errors if(-1 == status) { //was there an error sending to server? perror("MsgSend"); exit(EXIT_FAILURE); } else { printf( "Thread 2: The product of %d and %d is %d\n", msg2.x, msg2.y, msg2.product ); }; } /* else other pulses ... */ } /* else other messages ... */ } //Make sure to close resources name_close(coid); return NULL; } // eof: client.c
C
#include "bsp_basetime.h" BASETIME_PARA_T BaseTime_Para[BASETIME_NUM]; NVIC_InitTypeDef BaseTime_InitStruct; TIM_TimeBaseInitTypeDef TIM6_TimeBaseStruct; unsigned char BaseTime_Init(unsigned char id) { if(id > BASETIME_NUM) return BASETIME_ERROR; if(id == 0) { NVIC_PriorityGroupConfig(NVIC_PriorityGroup_0); BaseTime_InitStruct.NVIC_IRQChannel = TIM6_IRQn; BaseTime_InitStruct.NVIC_IRQChannelPreemptionPriority = 1; BaseTime_InitStruct.NVIC_IRQChannelSubPriority = 1; BaseTime_InitStruct.NVIC_IRQChannelCmd = ENABLE; NVIC_Init(&BaseTime_InitStruct); return BASETIME_SUCCESS; } else if(id == 1) { RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM6,ENABLE); TIM6_TimeBaseStruct.TIM_Period = 200; TIM6_TimeBaseStruct.TIM_Prescaler = 88; TIM_TimeBaseInit(TIM6,&TIM6_TimeBaseStruct); TIM_ClearFlag(TIM6,TIM_FLAG_Update); TIM_ITConfig(TIM6,TIM_IT_Update,ENABLE); TIM_Cmd(TIM6,ENABLE); return BASETIME_SUCCESS; } return BASETIME_ERROR; } unsigned char BaseTime_App_Init(BASETIME_PARA_T *p) { unsigned char BaseTime_Init(unsigned char ID); return BaseTime_Init(p->ID); } unsigned char BaseTime_App_Handle(unsigned char sum) { static unsigned char i; if(sum > BASETIME_NUM) return BASETIME_ERROR; for(i = 0; i < sum; i ++) { BaseTime_Para[i].ID = i; BaseTime_App_Init(&BaseTime_Para[i]); } if(i != sum) { return BASETIME_ERROR; } else { return BASETIME_SUCCESS; } }
C
#include "bsp_dataconvert.h" /* ********************************************************************************************************* * : BEBufToUint16 * ˵: 2ֽ(Big Endian򣬸ֽǰ)תΪ16λ * : _pBuf : * ֵ: 16λֵ * * (Big Endian)С(Little Endian) ********************************************************************************************************* */ int16_t BEBufToInt16(uint8_t *_pBuf) { return (((int16_t)_pBuf[0] << 8) | _pBuf[1]); } /* ********************************************************************************************************* * : LEBufToUint16 * ˵: 2ֽ(СLittle Endianֽǰ)תΪ16λ * : _pBuf : * ֵ: 16λֵ ********************************************************************************************************* */ int16_t LEBufToInt16(uint8_t *_pBuf) { return (((int16_t)_pBuf[1] << 8) | _pBuf[0]); } uint16_t BEBufToUint16(uint8_t *_pBuf) { return (((uint16_t)_pBuf[0] << 8) | _pBuf[1]); } /* ********************************************************************************************************* * : LEBufToUint16 * ˵: 2ֽ(СLittle Endianֽǰ)תΪ16λ * : _pBuf : * ֵ: 16λֵ ********************************************************************************************************* */ uint16_t LEBufToUint16(uint8_t *_pBuf) { return (((uint16_t)_pBuf[1] << 8) | _pBuf[0]); } /* ********************************************************************************************************* * : BEBufToUint32 * ˵: 4ֽ(Big Endian򣬸ֽǰ)תΪ16λ * : _pBuf : * ֵ: 16λֵ * * (Big Endian)С(Little Endian) ********************************************************************************************************* */ int32_t BEBufToInt32(uint8_t *_pBuf) { return (((int32_t)_pBuf[0] << 24) | ((int32_t)_pBuf[1] << 16) | ((int32_t)_pBuf[2] << 8) | _pBuf[3]); } /* ********************************************************************************************************* * : LEBufToUint32 * ˵: 4ֽ(СLittle Endianֽǰ)תΪ16λ * : _pBuf : * ֵ: 16λֵ ********************************************************************************************************* */ int32_t LEBufToInt32(uint8_t *_pBuf) { return (((int32_t)_pBuf[3] << 24) | ((int32_t)_pBuf[2] << 16) | ((int32_t)_pBuf[1] << 8) | _pBuf[0]); } uint32_t BEBufToUint32(uint8_t *_pBuf) { return (((uint32_t)_pBuf[0] << 24) | ((uint32_t)_pBuf[1] << 16) | ((uint32_t)_pBuf[2] << 8) | _pBuf[3]); } /* ********************************************************************************************************* * : LEBufToUint32 * ˵: 4ֽ(СLittle Endianֽǰ)תΪ16λ * : _pBuf : * ֵ: 16λֵ ********************************************************************************************************* */ uint32_t LEBufToUint32(uint8_t *_pBuf) { return (((uint32_t)_pBuf[3] << 24) | ((uint32_t)_pBuf[2] << 16) | ((uint32_t)_pBuf[1] << 8) | _pBuf[0]); }
C
/* * @file ADC.c * @brief ADCɼ * @author MAZY * @version v1.0 * @date 2019-04-03 */ /*Magic Don't touch !*/ /*ħ*/ #include "include.h" #include "ADC.h" #define MAXQSIZE 6 //ܴMAXQSIZE-1 = 5Ԫ //#define OK 1 #define ERROR 0 #define OVERFLOW -1 float weight[MAXQSIZE-1] = { 0.1 ,0.3 ,0.4 ,0.5 ,0.7};//Ȩر int16 L_AD = 0, R_AD = 0, LS_AD = 0, RS_AD = 0, LM_AD = 0, RM_AD = 0, M_AD = 0, MS_AD = 0; typedef uint32 Item; //ѭж typedef struct { Item *base; int front; int rear; }Queue; Queue Value[8]; //ʼ void InitQueue(Queue *q) { q->base = (uint32*)malloc(MAXQSIZE * sizeof(uint32)); if (q->base == NULL) exit(OVERFLOW); q->front = 0; q->rear = MAXQSIZE-1; } //ж϶ǷԱ uint8 IsFull(Queue q) { return (q.rear + 1) % MAXQSIZE == q.front; } //жǷΪ uint8 IsEmpty(Queue q) { return q.rear == q.front; } //Ԫصβ uint8 EnQueue(Queue *q, Item e) { if (IsFull(*q)) return ERROR; q->base[q->rear] = e; q->rear = (q->rear + 1) % MAXQSIZE; return 1; } //ɾײԪ uint8 DeQueue(Queue *q) { if(IsEmpty(*q)) return ERROR; q->front = (q->front + 1) % MAXQSIZE; return 1; } //ԪأɾȥԪ void Add_Value(uint32 value,Queue *q) { DeQueue(q);/* &q? */ EnQueue(q, value); } uint8 QueueLength(Queue q) { return (q.rear - q.front + MAXQSIZE) % MAXQSIZE; } //Ȩȡƽ uint32 Get_Value_Sum(Queue *q) { int i, j; uint32 sum = 0; for (i = 0, j = q->front; i < QueueLength(*q); i++, j = (j + 1) % MAXQSIZE) { sum += q->base[j] * weight[i]; } return sum/2; } /*! * @brief ADCʼ * @since V1.0 * @note */ void ADC_Init() { uint8 i; adc_init(ADC1); adc_init(ADC2); adc_init(ADC3); adc_init(ADC4); adc_init(ADC5); adc_init(ADC6); //2· adc_init(ADC7); adc_init(ADC8); //ʼж for(i = 0;i<8;i++) { InitQueue(&Value[i]); } } uint32 Get_Ntimes_average(ADCn_Ch_e adcn_ch, ADC_nbit bit,uint8 N) { uint32 value; uint8 i; for(i=0;i<N;i++) { value += adc_once(adcn_ch,bit);//get adc } return value/N; } /*! * @brief βADC˲ * @param ADCn_Ch_e adcn_ch ADCͨ * @param ADC_nbit bit ADCɼ * @param uint8 N ɼ * @since V1.0 * @note */ void Get_Smoothed_ADC() { Add_Value(Get_Ntimes_average(ADC1,ADC_10bit,3),&Value[0]); Add_Value(Get_Ntimes_average(ADC2,ADC_10bit,3),&Value[1]); Add_Value(Get_Ntimes_average(ADC3,ADC_10bit,3),&Value[2]); Add_Value(Get_Ntimes_average(ADC4,ADC_10bit,3),&Value[3]); Add_Value(Get_Ntimes_average(ADC5,ADC_10bit,3),&Value[4]); Add_Value(Get_Ntimes_average(ADC6,ADC_10bit,3),&Value[5]); Add_Value(Get_Ntimes_average(ADC7,ADC_10bit,3),&Value[6]); Add_Value(Get_Ntimes_average(ADC8,ADC_10bit,3),&Value[7]); } int16* ADC_Uniformization()//һʱûã { //static int16 MAX_value[8]; return 0; } /*! * @brief õȫֵ * @since V1.0 * @note */ void Read_ADC() { Get_Smoothed_ADC(); L_AD = Get_Value_Sum(&Value[0])-5; R_AD = Get_Value_Sum(&Value[7])-31; LS_AD = Get_Value_Sum(&Value[1])-12 ; RS_AD = Get_Value_Sum(&Value[6])-31; LM_AD = Get_Value_Sum(&Value[2])-41; RM_AD = Get_Value_Sum(&Value[5])-18; M_AD = Get_Value_Sum(&Value[3])-82; #if 0 L_AD = 200, R_AD = 0, LS_AD = 100, RS_AD = 0; #endif #ifdef ADC_UP_DATA UP_Value[0] = L_AD; UP_Value[1] = R_AD; UP_Value[2] = LS_AD; UP_Value[3] = RS_AD; UP_Value[4] = LM_AD; UP_Value[5] = RM_AD; UP_Value[6] = M_AD; //vcan_sendware(UP_Value, sizeof(UP_Value)); #endif }
C
#include "palette.h" Palette *Palette_New(int x,int y,int w,int sz,int idx,int numColors,...) { Palette *palette=malloc(sizeof(Palette)); if(palette) { palette->x=x; palette->y=y; palette->w=w; palette->sz=sz; palette->idx=idx; palette->numColors=numColors; palette->colors=malloc(sizeof(GLuint)*numColors); va_list args; va_start(args,numColors); for(int i=0;i<numColors;i++) { palette->colors[i]=va_arg(args,GLuint); } va_end(args); } return palette; } void Palette_Draw(Palette *palette) { for(int i=0;i<palette->numColors;i++) { int x0=(i%palette->w)*palette->sz+palette->x; int y0=(i/palette->w)*palette->sz+palette->y; int x1=x0+palette->sz; int y1=y0+palette->sz; glBoxFilled(x0+4,y0+4,x1-4,y1-4,palette->colors[i]); if(i==palette->idx) { glBox(x0,y0,x1,y1,palette->colors[3]); } } }
C
#include <stdio.h> #include <stdlib.h> #define DEBUG 1 //#define SHOW_ASM 1 #define NUM_REG 5 #define STACK_SIZE 1024 // ax, bx, cx, dx, ex unsigned int regs[NUM_REG + 1]; unsigned int stack[STACK_SIZE] = {0}; int pstack = 0; void push(int v) { pstack++; stack[pstack] = v; #ifdef DEBUG if(pstack == STACK_SIZE) { printf("Stack overflow.\n"); exit(EXIT_FAILURE); } #endif } int popv() { #ifdef DEBUG if(pstack == 0) { printf("Stack is empty.\n"); exit(EXIT_FAILURE); } #endif return stack[pstack--]; } unsigned int * program; int instrNum = 0; int reg1 = 0; int reg2 = 0; int reg3 = 0; int value = 0; void decode(int instr) { instrNum = (instr & 0xFF000000) >> 24; reg1 = (instr & 0x00FF0000) >> 16; reg2 = (instr & 0x0000FF00) >> 8; reg3 = (instr & 0x000000FF); } int pc = 0; void fetch(int * instr) { *instr = program[pc ]; value = program[pc+1]; pc += 2; } int running = 1; void eval() { enum {END=0, MOV, PUSH, LOAD, STORE, ADD, SUB, MUL, JMP, JZ, PRINT}; // Ajouter vérifications en mode DEBUG #ifdef SHOW_ASM printf("%d: ", pc/2); #endif switch(instrNum) { case END: running = 0; break; case MOV: if(reg2 == 0) { regs[reg1] = value; } else { regs[reg1] = regs[reg2]; } #ifdef SHOW_ASM printf("mov \n"); #endif break; case PUSH: push(value); #ifdef SHOW_ASM printf("push %d\n", value); #endif break; case LOAD: push(regs[reg1]); #ifdef SHOW_ASM printf("load %d(%d)\n", reg1 ,regs[reg1]); #endif break; case STORE: regs[reg1] = popv(); #ifdef SHOW_ASM printf("store %d(%d)\n", reg1, regs[reg1]); #endif break; case ADD: { int b = popv(); int a = popv(); push(a + b); #ifdef SHOW_ASM printf("add \n"); #endif break; } case SUB: { int b = popv(); int a = popv(); push(a - b); #ifdef SHOW_ASM printf("sub \n"); #endif break; } case MUL: { int b = popv(); int a = popv(); push(a * b); #ifdef SHOW_ASM printf("mul\n"); #endif break; } case JMP: pc = value * 2; #ifdef SHOW_ASM printf("jmp %d\n", value); #endif break; case JZ: { int v = popv(); if(v == 0) { pc = value * 2; } #ifdef SHOW_ASM printf("jz %d\n", v); #endif break; } case PRINT: { int v = popv(); printf("%d\n", v); #ifdef SHOW_ASM printf("print \n"); #endif break; } default: printf("Bad operation (%d).\n", instrNum); running = 0; } } void run() { int instr; while(running) { fetch(&instr); decode(instr); eval(); } } int main(int argc, char ** argv) { if(argc == 2) { FILE * f = fopen(argv[1], "rb"); if(!f) { fprintf(stderr, "An error occurred while opening the file.\n"); exit(EXIT_FAILURE); } fseek(f, 0, SEEK_END); int len = ftell(f); fseek(f, 0, SEEK_SET); program = malloc(len); fread(program, 1, len, f); fclose(f); run(); } else { printf("Usage: vm file\n"); } return EXIT_SUCCESS; }
C
/* # Name: <Jack Stephens> # Date: <April 22, 2019> # Title: Lab3 step2 # Description: This program uses pipe() to write the file called to the output */ /*sample C program for Lab assignment 3*/ #include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <string.h> #include <sys/wait.h> // main int main(int argc, char *argv[]) { int fds[2]; char buff[60]; int count; int i; pipe(fds); if (fork() == 0){ printf("\nWriter on the upstream end of the pipe -> %d arguments \n", argc); close(fds[0]); for(i = 0; i<argc; i++){ write(fds[1], argv[i], strlen(argv[i])); } exit(0); } else if(fork() ==0){ printf("\nReader on the downstream end of the pipe \n"); close(fds[1]); while((count=read(fds[0], buff, 60)) > 0) { for (i=0; i<count; i++){ write(1, buff+i, 1); write(1, " ", 1); } printf("\n"); } exit(0); } else { close(fds[0]); close(fds[1]); wait(0); wait(0); } return 0; }
C
// https://www.hackerrank.com/challenges/flipping-bits #include<stdio.h> #include<stdlib.h> #include <stdint.h> int j,n; int main(){ int32_t i; scanf("%d",&n); for(j=0;j<n;j++){ scanf("%u", &i); printf("%u\n", ~i ); } }
C
#include <stdio.h> int main() { float altura; printf("Digite sua altura: \n"); scanf("%f",&altura); printf("Sua altura é: %.2f", altura); return 0; }
C
/* this header file comes from libowfat, http://www.fefe.de/libowfat/ */ #ifndef BUFFER_H #define BUFFER_H #include "typedefs.h" #ifdef __cplusplus extern "C" { #endif typedef ssize_t(buffer_op_sys)(fd_t fd, void* buf, size_t len); typedef ssize_t(buffer_op_proto)(fd_t fd, void* buf, size_t len, void* arg); typedef ssize_t(buffer_op_fn)(/*fd_t fd, void* buf, size_t len, void* arg*/); typedef buffer_op_fn* buffer_op_ptr; typedef struct buffer { char* x; /* actual buffer space */ size_t p; /* current position */ size_t n; /* current size of string in buffer */ size_t a; /* allocated buffer size */ buffer_op_proto* op; /* use read(2) or write(2) */ void* cookie; /* used internally by the to-stralloc buffers, and for buffer chaini(ng */ void (*deinit)(); /* called to munmap/free cleanup, with a pointer to the buffer as argument */ fd_t fd; /* passed as first argument to op */ } buffer; #define BUFFER_INIT(op, fd, buf, len) \ { (buf), 0, 0, (len), (buffer_op_proto*)(void*)(op), NULL, NULL, (fd) } #define BUFFER_INIT_FREE(op, fd, buf, len) \ { (buf), 0, 0, (len), (buffer_op_proto*)(void*)(op), NULL, buffer_free, (fd) } #define BUFFER_INIT_READ(op, fd, buf, len) BUFFER_INIT(op, fd, buf, len) /*obsolete*/ #define BUFFER_INSIZE 65535 #define BUFFER_OUTSIZE 32768 void buffer_init(buffer*, buffer_op_proto*, fd_t fd, char* y, size_t ylen); void buffer_init_free(buffer*, buffer_op_proto*, fd_t fd, char* y, size_t ylen); void buffer_free(void* buf); void buffer_munmap(void* buf); int buffer_mmapread(buffer*, const char* filename); int buffer_mmapread_fd(buffer*, fd_t fd); int buffer_mmapprivate(buffer*, const char* filename); int buffer_mmapprivate_fd(buffer*, fd_t fd); int buffer_mmapshared(buffer*, const char* filename); int buffer_mmapshared_fd(buffer*, fd_t fd); void buffer_close(buffer* b); /* reading from an fd... if it is a regular file, then buffer_mmapread_fd is called, otherwise buffer_init(&b, read, fd, malloc(8192), 8192) */ int buffer_read_fd(buffer*, fd_t fd); int buffer_flush(buffer* b); int buffer_put(buffer*, const char* x, size_t len); int buffer_putalign(buffer*, const char* x, size_t len); ssize_t buffer_putflush(buffer*, const char* x, size_t len); int buffer_puts(buffer*, const char* x); int buffer_putsalign(buffer*, const char* x); ssize_t buffer_putsflush(buffer*, const char* x); #if defined(__GNUC__) && !defined(__LIBOWFAT_INTERNAL) && !defined(__dietlibc__) && !defined(NO_BUILTINS) /* as a little gcc-specific hack, if somebody calls buffer_puts with a * constant string, where we know its length at compile-time, call * buffer_put with the known length instead */ #define buffer_puts(b, s) (__builtin_constant_p(s) ? buffer_put(b, s, __builtin_strlen(s)) : buffer_puts(b, s)) #define buffer_putsflush(b, s) \ (__builtin_constant_p(s) ? buffer_putflush(b, s, __builtin_strlen(s)) : buffer_putsflush(b, s)) #endif int buffer_putm_internal(buffer* b, ...); int buffer_putm_internal_flush(buffer* b, ...); #ifdef __BORLANDC__ #define buffer_putm(b, args) buffer_putm_internal(b, args, (char*)0) #define buffer_putmflush(b, args) buffer_putm_internal_flush(b, args, (char*)0) #else #define buffer_putm(...) buffer_putm_internal(__VA_ARGS__, (char*)0) #define buffer_putmflush(b, ...) buffer_putm_internal_flush(b, __VA_ARGS__, (char*)0) #endif #define buffer_putm_2(b, a1, a2) buffer_putm_internal(b, a1, a2, (char*)0) #define buffer_putm_3(b, a1, a2, a3) buffer_putm_internal(b, a1, a2, a3, (char*)0) #define buffer_putm_4(b, a1, a2, a3, a4) buffer_putm_internal(b, a1, a2, a3, a4, (char*)0) #define buffer_putm_5(b, a1, a2, a3, a4, a5) buffer_putm_internal(b, a1, a2, a3, a4, a5, (char*)0) #define buffer_putm_6(b, a1, a2, a3, a4, a5, a6) buffer_putm_internal(b, a1, a2, a3, a4, a5, a6, (char*)0) #define buffer_putm_7(b, a1, a2, a3, a4, a5, a6, a7) buffer_putm_internal(b, a1, a2, a3, a4, a5, a6, a7, (char*)0) int buffer_putspace(buffer* b); ssize_t buffer_putnlflush(buffer* b); /* put \n and flush */ #define buffer_PUTC(s, c) (((s)->a != (s)->p) ? ((s)->x[(s)->p++] = (c), 0) : buffer_putc((s), (c))) ssize_t buffer_get(buffer*, char* x, size_t len); ssize_t buffer_feed(buffer* b); ssize_t buffer_getc(buffer*, char* x); ssize_t buffer_getn(buffer*, char* x, size_t len); /* read bytes until the destination buffer is full (len bytes), end of * file is reached or the read char is in charset (setlen bytes). An * empty line when looking for \n will write '\n' to x and return 0. If * EOF is reached, \0 is written to the buffer */ ssize_t buffer_get_token(buffer*, char* x, size_t len, const char* charset, size_t setlen); ssize_t buffer_getline(buffer*, char* x, size_t len); int buffer_skip_until(buffer*, const char* charset, size_t setlen); /* this predicate is given the string as currently read from the buffer * and is supposed to return 1 if the token is complete, 0 if not. */ typedef int (*string_predicate)(const char* x, size_t len, void* arg); /* like buffer_get_token but the token ends when your predicate says so */ ssize_t buffer_get_token_pred(buffer*, char* x, size_t len, string_predicate p, void*); char* buffer_peek(buffer* b); int buffer_peekc(buffer*, char* c); void buffer_seek(buffer*, size_t len); int buffer_skipc(buffer* b); int buffer_skipn(buffer*, size_t n); int buffer_prefetch(buffer*, size_t n); #define buffer_PEEK(s) ((s)->x + (s)->p) #define buffer_SEEK(s, len) ((s)->p += (len)) #define buffer_GETC(s, c) \ (((s)->p < (s)->n) ? (*(c) = *buffer_PEEK(s), buffer_SEEK((s), 1), 1) : buffer_get((s), (c), 1)) int buffer_putulong(buffer*, unsigned long int l); int buffer_put8long(buffer*, unsigned long int l); int buffer_putxlong(buffer*, unsigned long int l); int buffer_putlong(buffer*, signed long int l); int buffer_putdouble(buffer*, double d, int prec); int buffer_puterror(buffer* b); int buffer_puterror2(buffer*, int errnum); extern buffer* buffer_0; extern buffer* buffer_0small; extern buffer* buffer_1; extern buffer* buffer_1small; extern buffer* buffer_2; #ifdef STRALLOC_H /* write stralloc to buffer */ int buffer_putsa(buffer*, const stralloc* sa); /* write stralloc to buffer and flush */ int buffer_putsaflush(buffer*, const stralloc* sa); /* these "read token" functions return 0 if the token was complete or * EOF was hit or -1 on error. In contrast to the non-stralloc token * functions, the separator is also put in the stralloc; use * stralloc_chop or stralloc_chomp to get rid of it. */ /* WARNING! These token reading functions will not clear the stralloc! * They _append_ the token to the contents of the stralloc. The idea is * that this way these functions can be used on non-blocking sockets; * when you get signalled EAGAIN, just call the functions again when new * data is available. */ /* read token from buffer to stralloc */ int buffer_get_token_sa(buffer*, stralloc* sa, const char* charset, size_t setlen); /* read line from buffer to stralloc */ int buffer_getline_sa(buffer*, stralloc* sa); /* same as buffer_get_token_sa but empty sa first */ int buffer_get_new_token_sa(buffer*, stralloc* sa, const char* charset, size_t setlen); /* same as buffer_getline_sa but empty sa first */ int buffer_getnewline_sa(buffer*, stralloc* sa); typedef int (*sa_predicate)(stralloc* sa, void*); /* like buffer_get_token_sa but the token ends when your predicate says so */ int buffer_get_token_sa_pred(buffer*, stralloc* sa, sa_predicate p, void*); /* same, but clear sa first */ int buffer_get_new_token_sa_pred(buffer*, stralloc* sa, sa_predicate p, void*); /* make a buffer from a stralloc. * Do not change the stralloc after this! */ void buffer_fromsa(buffer*, const stralloc* sa); /* read from sa */ int buffer_tosa(buffer* b, stralloc* sa); /* write to sa, auto-growing it */ int buffer_gettok_sa(buffer*, stralloc* sa, const char* charset, size_t setlen); #endif void buffer_frombuf(buffer*, const char* x, size_t l); /* buffer reads from static buffer */ #ifdef ARRAY_H void buffer_fromarray(buffer*, array* a); /* buffer reads from array */ #endif void buffer_dump(buffer* out, buffer* b); int buffer_putc(buffer*, char c); int buffer_putnspace(buffer*, int n); int buffer_putptr(buffer*, void* ptr); int buffer_putulong0(buffer*, unsigned long l, int pad); int buffer_putlong0(buffer*, long l, int pad); int buffer_putxlong0(buffer*, unsigned long l, int pad); int buffer_skipspace(buffer* b); int buffer_skip_pred(buffer*, int (*pred)(int)); int buffer_put_escaped(buffer*, const char* x, size_t len); int buffer_puts_escaped(buffer*, const char* x); int buffer_freshen(buffer* b); int buffer_truncfile(buffer*, const char* fn); int buffer_lzma(buffer*, buffer*, int compress); int buffer_bz2(buffer*, buffer*, int compress); int buffer_putnc(buffer*, char c, int ntimes); int buffer_putns(buffer*, const char* s, int ntimes); int buffer_putspad(buffer*, const char* x, size_t pad); int buffer_deflate(buffer*, buffer* out, int level); int buffer_inflate(buffer*, buffer* in); int buffer_gunzip(buffer*, const char* filename); int buffer_gunzip_fd(buffer*, fd_t fd); int buffer_gzip(buffer*, const char* filename, int level); int buffer_gzip_fd(buffer*, fd_t fd, int level); int buffer_bunzip(buffer*, const char* filename); int buffer_bunzip_fd(buffer*, fd_t fd); int buffer_bzip(buffer*, const char* filename, int level); int buffer_bzip_fd(buffer*, fd_t fd, int level); int buffer_get_until(buffer*, char* x, size_t len, const char* charset, size_t setlen); int buffer_write_fd(buffer*, fd_t fd); #ifdef UINT64_H int buffer_putlonglong(buffer*, int64 l); int buffer_putulonglong(buffer*, uint64 l); int buffer_putxlonglong(buffer*, uint64 l); int buffer_putulonglong(buffer*, uint64 i); int buffer_putlonglong(buffer*, int64 i); int buffer_putxlonglong0(buffer*, uint64 l, int pad); #endif #ifdef TAI_H int buffer_puttai(buffer*, const struct tai*); #endif #ifdef __cplusplus } #endif #endif
C
#include <stdio.h> #include <stdlib.h> #include <sys/stat.h> #include <assert.h> #include <string.h> #include <ctype.h> typedef struct { char* pointer; unsigned lenght; } string; //=========================================================================================== unsigned size_of_file (); char* read_file (unsigned size_f, unsigned* number_of_strings); string* fill_strings (unsigned number_of_strings, unsigned size_f, char* text); int compare_strings_and_skip_spaces (const void* string_1, const void* string_2); void print_sorted_onegin (string* mass_of_strings, unsigned number_of_strings); void skip_spaces (string* str1, string* str2); //=========================================================================================== int main () { unsigned number_of_strings = 0; unsigned size_f = size_of_file (); char* text = read_file (size_f, &number_of_strings); string* mass_of_strings = fill_strings (number_of_strings, size_f, text); qsort (mass_of_strings, number_of_strings, sizeof(string), compare_strings_and_skip_spaces); print_sorted_onegin (mass_of_strings, number_of_strings); free (text); free (mass_of_strings); return 0; } //=========================================================================================== unsigned size_of_file () { struct stat file_info; stat ("onegin.txt", &file_info); return file_info.st_size; } //=========================================================================================== char* read_file (unsigned size_f, unsigned* number_of_strings) { FILE* onegin = fopen ("onegin.txt", "r"); assert (onegin != NULL); char* text = (char*) calloc (size_f, sizeof (char) ); for (unsigned i = 0; i < size_f; i++) { text[i] = (char) fgetc (onegin); if (text[i] == '\n') { text[i] = '\0'; (*number_of_strings)++; } } fclose (onegin); return text; } //=========================================================================================== string* fill_strings (unsigned number_of_strings, unsigned size_f, char* text) { string* mass_of_strings = (string*) calloc (number_of_strings, sizeof (string) ); unsigned i = 0; unsigned distance = 0; for (unsigned j = 0; j < size_f; j++) { if (text[j] == '\0') { mass_of_strings[i].pointer = text + distance; mass_of_strings[i].lenght = strlen (text + distance); i++; distance = j + 1; } } return mass_of_strings; } //=========================================================================================== int compare_strings_and_skip_spaces (const void* string_1, const void* string_2) { string* str1 = (string*) string_1; string* str2 = (string*) string_2; skip_spaces (str1, str2); unsigned i = 0; while (tolower (*(str1->pointer + i)) == tolower (*(str2->pointer + i)) && (*(str1->pointer + i) != '\0') && (*(str2->pointer + i) != '\0')) { i++; skip_spaces (str1, str2); } return tolower (*(str1->pointer + i)) - tolower (*(str2->pointer + i)); } //=========================================================================================== void print_sorted_onegin (string* mass_of_strings, unsigned number_of_strings) { FILE* sorted_onegin = fopen ("sorted_onegin.txt", "w"); for (unsigned i = 0; i < number_of_strings; i++) fprintf (sorted_onegin, "%s\n", mass_of_strings[i].pointer); fclose (sorted_onegin); } //=========================================================================================== void skip_spaces (string* str1, string* str2) { while (isalpha (*(str1->pointer)) == 0) str1->pointer++; while (isalpha (*(str2->pointer)) == 0) str2->pointer++; }
C
#include<stdio.h> #include<stdlib.h> int b[10000]; int visited[10000]; int top2 = -1; int min = 100000; int matrix[100][100]; void dfs(int matrix[100][100],int visited[],int source,int dest,int k,int n){ int m; if(source == dest){ if(top2 == k+1){ int j; int sum=0; for(j=0;j<top2;j++){ sum = sum + matrix[b[j]][b[j+1]]; } if(sum < min){ min = sum; } sum=0; } } int i=0; for(i=0;i<n;i++){ if(matrix[source][i]!=0 && visited[i]==0 ){ visited[i] = 1; b[++top2] = i; dfs(matrix,visited,i,dest,k,n); } } int h = b[top2]; if(top2>=1){ visited[h]=0; top2 = top2-1; } } int main(){ int n; int m; scanf("%d %d",&n,&m); int k1,k2,cost; int i=0,j=0; for(i=0;i<n;i++){ for(j=0;j<n;j++){ visited[i]=0; matrix[i][j]=0; } } for(i=0;i<m;i++){ scanf("%d %d %d",&k1,&k2,&cost); matrix[k1][k2] = cost; matrix[k2][k1] = cost; } int m2; scanf("%d",&m2); int source,dest,k; for(i=0;i<m2;i++){ scanf("%d %d %d",&source,&dest,&k); min = 100000; visited[source] = 1; b[++top2] = source; dfs(matrix,visited,source,dest,k,n); for(j=0;j<n;j++){ visited[j]=0; } top2=-1; printf("minimum sum is: %d",min); } }
C
#include <stdio.h> #include "functions.h" #define OK 0 #define ELEMENTS_ERROR -2 #define FILE_ERROR -3 #define N 5 #define M 7 int main(int argc, char **argv) { int size1, size2; int array[N][M]; int retVal; FILE *file; file = fopen(argv[argc - 1], "r"); retVal = fill_matrix(file, &size1, &size2, array); if (retVal == OK) { print(array, size1, size2); } else if (retVal == ELEMENTS_ERROR) { printf("Libo odin iz elementov raven ili menishe nulia, libo bolishe constanti"); } else { printf("Chto-to ne tak s failom"); } fclose(file); }
C
double findMedianSortedArrays(int* nums1, int nums1Size, int* nums2, int nums2Size) { int sum = nums1Size + nums2Size; // 数组总个数 int i = 0, j = 0; // i j - 游标 double chosed = 0; // 缓存每次选中的数 double m = 0, n = 0; // 有偶数个元素时,两个中位数的下标 while (i + j < sum) { if (j == nums2Size || (i < nums1Size && nums1[i] < nums2[j])) { // 如果nums1[i] < nums2[j],或者nums2已遍历完 chosed = nums1[i]; i++; } else if (j < nums2Size) { chosed = nums2[j]; j++; } if (sum%2 == 0) { // 如果有偶数个元素 if (i+j == sum/2) { m = chosed; } if (i+j == sum/2 + 1) { n = chosed; return (m + n)/2; } } if (sum%2 == 1) // 如果有奇数个元素 if (i+j == sum/2 + 1) return chosed; } return 0; } /** 1.同时遍历两个数组,遍历过程中,哪个元素小、取哪个放入chosed备用 2.如果元素总数是偶数,取中间两个数的平均值;如果元素总数是奇数,取中间的那个元素 **/
C
/************************************************************************* > File Name: diffork.c > Author: Zhanghaoran0 > Mail: [email protected] > Created Time: 2015年07月23日 星期四 19时06分39秒 ************************************************************************/ #include<stdio.h> #include<stdlib.h> #include<string.h> #include<sys/types.h> #include<sys/stat.h> #include<fcntl.h> #include<unistd.h> #include<errno.h> #include<grp.h> #include<pwd.h> #include<limits.h> #include<time.h> #include<dirent.h> int globVar = 5; int main(void){ pid_t pid; int var = 1, i; printf("fork is different with vfork\n"); //pid = fork(); pid = vfork(); switch(pid){ case 0: i = 3; while(i -- > 0){ printf("Child process is running\n"); globVar ++; var ++; sleep(1); } printf("Child's globVar = %d, var = %d\n", globVar, var); break; case -1: perror("process creation failes\n"); exit(0); default : i = 5; while(i -- > 0){ printf("Parent process is running\n"); globVar ++; var ++; sleep(1); } printf("Parent's globVar = %d, var = %d\n", globVar, var); } exit(0); } /* * 运行结果: * pid = fork(); * fork is different with vfork * Parent process is running * Child process is running * Parent process is running * Child process is running * Child process is running * Parent process is running * Child's globVar = 8, var = 4 * Parent process is running * Parent process is running * Parent's globVar = 10, var = 6 * * * pid = vfork() * fork is different with vfork * Child process is running * Child process is running * Child process is running * Child's globVar = 8, var = 4 * Parent process is running * Parent process is running * Parent process is running * Parent process is running * Parent process is running * Parent's globVar = 13, var = 32770 */
C
/*Raul P. Pelaez 2016. vector types algebra*/ #ifndef VECTOR_OVERLOADS_H #define VECTOR_OVERLOADS_H #include <cmath> typedef unsigned short ushort; typedef unsigned int uint; typedef unsigned long long int ullint; #ifndef CUDA_ENABLED #define VECATTR inline struct float2{float x,y;}; struct float3{ float x,y,z;}; struct float4{ float x,y,z,w;}; struct double2{double x,y;}; struct double3{ double x,y,z;}; struct double4{ double x,y,z,w;}; struct int2{int x,y;}; struct int3{int x,y,z;}; struct int4{int x,y,z,w;}; struct uint2{uint x,y;}; struct uint3{uint x,y,z;}; struct uint4{uint x,y,z,w;}; VECATTR float2 make_float2(float x, float y){ return {x,y};} VECATTR float3 make_float3(float x, float y, float z){ return {x,y,z};} VECATTR float4 make_float4(float x, float y, float z, float w){ return {x,y,z,w};} VECATTR double2 make_double2(double x, double y){ return {x,y};} VECATTR double3 make_double3(double x, double y, double z){ return {x,y,z};} VECATTR double4 make_double4(double x, double y, double z, double w){ return {x,y,z,w};} VECATTR int2 make_int2(int x, int y){ return {x,y};} VECATTR int3 make_int3(int x, int y, int z){ return {x,y,z};} VECATTR int4 make_int4(int x, int y, int z, int w){ return {x,y,z,w};} VECATTR uint2 make_uint2(uint x, uint y){ return {x,y};} VECATTR uint3 make_uint3(uint x, uint y, uint z){ return {x,y,z};} VECATTR uint4 make_uint4(uint x, uint y, uint z, uint w){ return {x,y,z,w};} #else #include<cuda_runtime.h> #define VECATTR inline __device__ __host__ #endif #ifndef SINGLE_PRECISION typedef double real ; typedef double2 real2; typedef double3 real3; typedef double4 real4; #else typedef float real ; typedef float2 real2; typedef float3 real3; typedef float4 real4; #endif /////////////////////FLOAT2/////////////////////////////// VECATTR int2 make_int2(float2 a){return make_int2((int)(a.x), (int)(a.y));} VECATTR float2 make_float2(float a){return make_float2(a, a);} VECATTR float2 make_float2(int2 a){return make_float2(a.x, a.y);} VECATTR float2 make_float2(float2 a){return make_float2(a.x, a.y);} VECATTR float2 operator +(const float2 &a, const float2 &b){return make_float2( a.x + b.x, a.y + b.y); } VECATTR void operator +=(float2 &a, const float2 &b){ a.x += b.x; a.y += b.y; } VECATTR float2 operator +(const float2 &a, const float &b){return make_float2( a.x + b, a.y + b); } VECATTR float2 operator +(const float &b, const float2 &a){return a+b;} VECATTR void operator +=(float2 &a, const float &b){ a.x += b; a.y += b; } VECATTR float2 operator -(const float2 &a, const float2 &b){return make_float2( a.x - b.x, a.y - b.y); } VECATTR void operator -=(float2 &a, const float2 &b){ a.x -= b.x; a.y -= b.y; } VECATTR float2 operator -(const float2 &a, const float &b){return make_float2( a.x - b, a.y - b); } VECATTR float2 operator -(const float &b, const float2 &a){return make_float2( b-a.x, b-a.y); } VECATTR void operator -=(float2 &a, const float &b){ a.x -= b; a.y -= b; } VECATTR float2 operator *(const float2 &a, const float2 &b){ return make_float2(a.x * b.x, a.y * b.y); } VECATTR void operator *=(float2 &a, const float2 &b){ a.x *= b.x; a.y *= b.y; } VECATTR float2 operator *(const float2 &a, const float &b){ return make_float2(a.x * b, a.y * b); } VECATTR float2 operator *(const float &b, const float2 &a){ return make_float2(a.x * b, a.y * b); } VECATTR void operator *=(float2 &a, const float &b){ a.x *= b; a.y *= b; } VECATTR float2 operator /(const float2 &a, const float2 &b){ return make_float2(a.x / b.x, a.y / b.y); } VECATTR void operator /=(float2 &a, const float2 &b){ a.x /= b.x; a.y /= b.y; } VECATTR float2 operator /(const float2 &a, const float &b){ return (1.0f/b)*a; } VECATTR float2 operator /(const float &b, const float2 &a){ return make_float2(b / a.x, b / a.y); } VECATTR void operator /=(float2 &a, const float &b){ a *= 1.0f/b; } VECATTR float2 floorf(const float2 &a){ return make_float2(floorf(a.x), floorf(a.y)); } /////////////////////FLOAT3/////////////////////////////// VECATTR int3 make_int3(float3 a){return make_int3((int)a.x, (int)a.y, (int)a.z);} VECATTR float3 make_float3(float a){return make_float3(a, a, a);} VECATTR float3 make_float3(int3 a){return make_float3(a.x, a.y, a.z);} VECATTR float3 make_float3(float3 a){return make_float3(a.x, a.y, a.z);} VECATTR float3 operator +(const float3 &a, const float3 &b){return make_float3( a.x + b.x, a.y + b.y, a.z + b.z); } VECATTR void operator +=(float3 &a, const float3 &b){ a.x += b.x; a.y += b.y; a.z += b.z; } VECATTR float3 operator +(const float3 &a, const float &b){return make_float3( a.x + b, a.y + b, a.z + b); } VECATTR float3 operator +(const float &b, const float3 &a){return a+b;} VECATTR void operator +=(float3 &a, const float &b){ a.x += b; a.y += b; a.z += b; } VECATTR float3 operator -(const float3 &a, const float3 &b){return make_float3( a.x - b.x, a.y - b.y, a.z - b.z); } VECATTR void operator -=(float3 &a, const float3 &b){ a.x -= b.x; a.y -= b.y; a.z -= b.z; } VECATTR float3 operator -(const float3 &a, const float &b){return make_float3( a.x - b, a.y - b, a.z - b); } VECATTR float3 operator -(const float &b, const float3 &a){return make_float3( b-a.x, b-a.y, b-a.z); } VECATTR void operator -=(float3 &a, const float &b){ a.x -= b; a.y -= b; a.z -= b; } VECATTR float3 operator *(const float3 &a, const float3 &b){ return make_float3( a.x * b.x, a.y * b.y, a.z * b.z ); } VECATTR void operator *=(float3 &a, const float3 &b){ a.x *= b.x; a.y *= b.y; a.z *= b.z; } VECATTR float3 operator *(const float3 &a, const float &b){ return make_float3( a.x * b, a.y * b, a.z * b ); } VECATTR float3 operator *(const float &b, const float3 &a){ return make_float3( a.x * b, a.y * b, a.z * b ); } VECATTR void operator *=(float3 &a, const float &b){ a.x *= b; a.y *= b; a.z *= b; } VECATTR float3 operator /(const float3 &a, const float3 &b){ return make_float3( a.x / b.x, a.y / b.y, a.z / b.z ); } VECATTR void operator /=(float3 &a, const float3 &b){ a.x /= b.x; a.y /= b.y; a.z /= b.z; } VECATTR float3 operator /(const float3 &a, const float &b){ return (1.0f/b)*a; } VECATTR float3 operator /(const float &b, const float3 &a){ return make_float3( b / a.x, b / a.y, b / a.z ); } VECATTR void operator /=(float3 &a, const float &b){ a *= 1.0f/b; } VECATTR float3 floorf(const float3 &a){return make_float3(floorf(a.x), floorf(a.y), floorf(a.z));} /////////////////////FLOAT4/////////////////////////////// VECATTR float4 make_float4(float a){return make_float4(a,a,a,a);} VECATTR float4 make_float4(float3 a){return make_float4(a.x, a.y, a.z, 0);} VECATTR float4 make_float4(float4 a){return make_float4(a.x, a.y, a.z, a.w);} VECATTR float4 operator +(const float4 &a, const float4 &b){return make_float4( a.x + b.x, a.y + b.y, a.z + b.z, a.w + b.w); } VECATTR void operator +=(float4 &a, const float4 &b){ a.x += b.x; a.y += b.y; a.z += b.z; a.w += b.w; } VECATTR float4 operator +(const float4 &a, const float &b){return make_float4( a.x + b, a.y + b, a.z + b, a.w + b); } VECATTR float4 operator +(const float &b, const float4 &a){return a+b;} VECATTR void operator +=(float4 &a, const float &b){ a.x += b; a.y += b; a.z += b; a.w += b; } VECATTR float4 operator -(const float4 &a, const float4 &b){return make_float4( a.x - b.x, a.y - b.y, a.z - b.z, a.w - b.w); } VECATTR void operator -=(float4 &a, const float4 &b){ a.x -= b.x; a.y -= b.y; a.z -= b.z; a.w -= b.w; } VECATTR float4 operator -(const float4 &a, const float &b){return make_float4( a.x - b, a.y - b, a.z - b, a.w - b); } VECATTR float4 operator -(const float &b, const float4 &a){return make_float4( b-a.x, b-a.y, b-a.z, b-a.w); } VECATTR void operator -=(float4 &a, const float &b){ a.x -= b; a.y -= b; a.z -= b; a.w -= b; } VECATTR float4 operator *(const float4 &a, const float4 &b){ return make_float4(a.x * b.x, a.y * b.y, a.z * b.z, a.w * b.w); } VECATTR void operator *=(float4 &a, const float4 &b){ a.x *= b.x; a.y *= b.y; a.z *= b.z; a.w *= b.w; } VECATTR float4 operator *(const float4 &a, const float &b){ return make_float4(a.x * b, a.y * b, a.z * b, a.w * b); } VECATTR float4 operator *(const float &b, const float4 &a){ return make_float4(a.x * b, a.y * b, a.z * b, a.w * b); } VECATTR void operator *=(float4 &a, const float &b){ a.x *= b; a.y *= b; a.z *= b; a.w *= b; } VECATTR float4 operator /(const float4 &a, const float4 &b){ return make_float4(a.x / b.x, a.y / b.y, a.z / b.z, a.w / b.w); } VECATTR void operator /=(float4 &a, const float4 &b){ a.x /= b.x; a.y /= b.y; a.z /= b.z; a.w /= b.w; } VECATTR float4 operator /(const float4 &a, const float &b){ return (1.0f/b)*a; } VECATTR float4 operator /(const float &b, const float4 &a){ return make_float4(b / a.x, b / a.y, b / a.z, b / a.w); } VECATTR void operator /=(float4 &a, const float &b){ a *= 1.0f/b; } VECATTR float4 floorf(const float4 &a){ return make_float4(floorf(a.x), floorf(a.y), floorf(a.z), floorf(a.w)); } VECATTR float dot(float4 a, float4 b){return a.x*b.x + a.y*b.y + a.z*b.z + a.w*b.w;} /////////////////REAL4//////////////////////////////// VECATTR real4 make_real4(real x, real y, real z, real w){ #ifdef SINGLE_PRECISION return make_float4(x,y,z,w); #else return make_double4(x,y,z,w); #endif } VECATTR real4 make_real4(real s){return make_real4(s, s, s, s);} VECATTR real4 make_real4(real3 a){ return make_real4(a.x, a.y, a.z, 0.0f);} VECATTR real4 make_real4(real3 a, real w){ return make_real4(a.x, a.y, a.z, w);} #ifdef SINGLE_PRECISION VECATTR real4 make_real4(double3 a, real w){return make_real4(a.x, a.y, a.z, w);} #else VECATTR real4 make_real4(float3 a, real w){ return make_real4(a.x, a.y, a.z, w);} #endif VECATTR real4 make_real4(int4 a){ return make_real4(real(a.x), real(a.y), real(a.z), real(a.w));} VECATTR real4 make_real4(uint4 a){return make_real4(real(a.x), real(a.y), real(a.z), real(a.w));} //////////////////REAL3/////////////////////////// VECATTR real3 make_real3(real x, real y, real z){ #ifdef SINGLE_PRECISION return make_float3(x,y,z); #else return make_double3(x,y,z); #endif } VECATTR real3 make_real3(real s){ return make_real3(s, s, s);} VECATTR real3 make_real3(real3 a){return make_real3(a.x, a.y, a.z);} #ifdef SINGLE_PRECISION VECATTR real3 make_real3(double3 a){return make_real3(a.x, a.y, a.z);} VECATTR real3 make_real3(double4 a){return make_real3(a.x, a.y, a.z);} #else VECATTR real3 make_real3(float3 a){return make_real3(a.x, a.y, a.z);} VECATTR real3 make_real3(float4 a){return make_real3(a.x, a.y, a.z);} #endif VECATTR real3 make_real3(real4 a){ return make_real3(a.x, a.y, a.z);} VECATTR real3 make_real3(real2 a, real z){return make_real3(a.x, a.y, z);} VECATTR real3 make_real3(int3 a){ return make_real3(real(a.x), real(a.y), real(a.z));} VECATTR real3 make_real3(uint3 a){return make_real3(real(a.x), real(a.y), real(a.z));} //////////////////REAL2/////////////////////////// VECATTR real2 make_real2(real x, real y){ #ifdef SINGLE_PRECISION return make_float2(x,y); #else return make_double2(x,y); #endif } VECATTR real2 make_real2(real s){ return make_real2(s, s);} VECATTR real2 make_real2(real2 a){return make_real2(a.x, a.y);} VECATTR real2 make_real2(real4 a){return make_real2(a.x, a.y);} VECATTR real2 make_real2(int3 a){ return make_real2(real(a.x), real(a.y));} VECATTR real2 make_real2(uint3 a){return make_real2(real(a.x), real(a.y));} ////////////////DOUBLE PRECISION////////////////////// #ifndef SINGLE_PRECISION VECATTR double3 make_double3(real3 a){return make_double3(a.x, a.y, a.z);} #endif VECATTR float4 make_float4(double4 a){return make_float4(float(a.x), float(a.y), float(a.z), float(a.w));} VECATTR double4 make_double4(double s){ return make_double4(s, s, s, s);} VECATTR double4 make_double4(double3 a){return make_double4(a.x, a.y, a.z, 0.0f);} VECATTR double4 make_double4(double3 a, double w){return make_double4(a.x, a.y, a.z, w);} VECATTR double4 make_double4(int4 a){return make_double4(double(a.x), double(a.y), double(a.z), double(a.w));} VECATTR double4 make_double4(uint4 a){return make_double4(double(a.x), double(a.y), double(a.z), double(a.w));} VECATTR double4 make_double4(float4 a){return make_double4(double(a.x), double(a.y), double(a.z), double(a.w));} //////DOUBLE4/////////////// VECATTR double4 operator +(const double4 &a, const double4 &b){ return make_double4(a.x + b.x, a.y + b.y, a.z + b.z, a.w + b.w ); } VECATTR void operator +=(double4 &a, const double4 &b){ a.x += b.x; a.y += b.y; a.z += b.z; a.w += b.w; } VECATTR double4 operator +(const double4 &a, const double &b){ return make_double4( a.x + b, a.y + b, a.z + b, a.w + b ); } VECATTR double4 operator +(const double &b, const double4 &a){ return a+b; } VECATTR void operator +=(double4 &a, const double &b){ a.x += b; a.y += b; a.z += b; a.w += b; } VECATTR double4 operator -(const double4 &a, const double4 &b){ return make_double4( a.x - b.x, a.y - b.y, a.z - b.z, a.w - b.w ); } VECATTR void operator -=(double4 &a, const double4 &b){ a.x -= b.x; a.y -= b.y; a.z -= b.z; a.w -= b.w; } VECATTR double4 operator -(const double4 &a, const double &b){ return make_double4( a.x - b, a.y - b, a.z - b, a.w - b ); } VECATTR double4 operator -(const double &b, const double4 &a){ return make_double4( b - a.x, b - a.y, b - a.z, b - a.w ); } VECATTR void operator -=(double4 &a, const double &b){ a.x -= b; a.y -= b; a.z -= b; a.w -= b; } VECATTR double4 operator *(const double4 &a, const double4 &b){ return make_double4( a.x * b.x, a.y * b.y, a.z * b.z, a.w * b.w ); } VECATTR void operator *=(double4 &a, const double4 &b){ a.x *= b.x; a.y *= b.y; a.z *= b.z; a.w *= b.w; } VECATTR double4 operator *(const double4 &a, const double &b){ return make_double4( a.x * b, a.y * b, a.z * b, a.w * b ); } VECATTR double4 operator *(const double &b, const double4 &a){ return a*b; } VECATTR void operator *=(double4 &a, const double &b){ a.x *= b; a.y *= b; a.z *= b; a.w *= b; } VECATTR double4 operator /(const double4 &a, const double4 &b){ return make_double4( a.x / b.x, a.y / b.y, a.z / b.z, a.w / b.w ); } VECATTR void operator /=(double4 &a, const double4 &b){ a.x /= b.x; a.y /= b.y; a.z /= b.z; a.w /= b.w; } VECATTR double4 operator /(const double4 &a, const double &b){return (1.0/b)*a;} VECATTR double4 operator /(const double &b, const double4 &a){ return make_double4( b / a.x, b / a.y, b / a.z, b / a.w ); } VECATTR void operator /=(double4 &a, const double &b){ a *= 1.0/b; } VECATTR double dot(double4 a, double4 b) { return a.x * b.x + a.y * b.y + a.z * b.z + a.w * b.w; } VECATTR double length(double4 v) { return sqrt(dot(v, v)); } VECATTR double4 normalize(double4 v) { double invLen = 1.0/sqrt(dot(v, v)); return v * invLen; } VECATTR double4 floorf(double4 v) { return make_double4(floor(v.x), floor(v.y), floor(v.z), floor(v.w)); } /////////////////////DOUBLE3/////////////////////////////// VECATTR int3 make_int3(double3 a){ return make_int3((int)a.x, (int)a.y, (int)a.z); } VECATTR double3 make_double3(double a){ return make_double3(a, a, a); } VECATTR double3 make_double3(int3 a){ return make_double3(a.x, a.y, a.z); } VECATTR double3 make_double3(float3 a){ return make_double3(a.x, a.y, a.z); } VECATTR double3 operator +(const double3 &a, const double3 &b){ return make_double3( a.x + b.x, a.y + b.y, a.z + b.z ); } VECATTR void operator +=(double3 &a, const double3 &b){ a.x += b.x; a.y += b.y; a.z += b.z; } VECATTR double3 operator +(const double3 &a, const double &b){ return make_double3( a.x + b, a.y + b, a.z + b ); } VECATTR double3 operator +(const double &b, const double3 &a){ return a+b; } VECATTR void operator +=(double3 &a, const double &b){ a.x += b; a.y += b; a.z += b; } VECATTR double3 operator -(const double3 &a, const double3 &b){ return make_double3( a.x - b.x, a.y - b.y, a.z - b.z ); } VECATTR void operator -=(double3 &a, const double3 &b){ a.x -= b.x; a.y -= b.y; a.z -= b.z; } VECATTR double3 operator -(const double3 &a, const double &b){ return make_double3( a.x - b, a.y - b, a.z - b ); } VECATTR double3 operator -(const double &b, const double3 &a){ return make_double3( b-a.x, b-a.y, b-a.z ); } VECATTR void operator -=(double3 &a, const double &b){ a.x -= b; a.y -= b; a.z -= b; } VECATTR double3 operator *(const double3 &a, const double3 &b){ return make_double3( a.x * b.x, a.y * b.y, a.z * b.z ); } VECATTR void operator *=(double3 &a, const double3 &b){ a.x *= b.x; a.y *= b.y; a.z *= b.z; } VECATTR double3 operator *(const double3 &a, const double &b){ return make_double3( a.x * b, a.y * b, a.z * b ); } VECATTR double3 operator *(const double &b, const double3 &a){ return a*b; } VECATTR void operator *=(double3 &a, const double &b){ a.x *= b; a.y *= b; a.z *= b; } VECATTR double3 operator /(const double3 &a, const double3 &b){ return make_double3( a.x / b.x, a.y / b.y, a.z / b.z ); } VECATTR void operator /=(double3 &a, const double3 &b){ a.x /= b.x; a.y /= b.y; a.z /= b.z; } VECATTR double3 operator /(const double3 &a, const double &b){return (1.0/b)*a;} VECATTR double3 operator /(const double &b, const double3 &a){ return make_double3( b / a.x, b / a.y, b / a.z ); } VECATTR void operator /=(double3 &a, const double &b){ a *= 1.0/b; } //DOUBLE2 VECATTR double2 operator -(const double2 &a, const double2 &b){ return make_double2( a.x - b.x, a.y - b.y ); } VECATTR void operator -=(double2 &a, const double2 &b){ a.x -= b.x; a.y -= b.y; } VECATTR double2 operator -(const double2 &a, const double &b){ return make_double2( a.x - b, a.y - b ); } VECATTR double2 operator -(const double &b, const double2 &a){ return make_double2( b - a.x, b - a.y ); } VECATTR void operator -=(double2 &a, const double &b){a.x -= b; a.y -= b;} VECATTR double2 operator *(const double2 &a, const double2 &b){ return make_double2(a.x * b.x, a.y * b.y); } VECATTR void operator *=(double2 &a, const double2 &b){ a.x *= b.x; a.y *= b.y; } VECATTR double2 operator *(const double2 &a, const double &b){ return make_double2(a.x * b, a.y * b); } VECATTR double2 operator *(const double &b, const double2 &a){ return a*b; } VECATTR void operator *=(double2 &a, const double &b){ a.x *= b; a.y *= b; } VECATTR double2 floorf(const double2 &a){ return make_double2(floor(a.x), floor(a.y)); } //////////////////////////// VECATTR double3 floorf(double3 v){return make_double3(floor(v.x), floor(v.y), floor(v.z));} VECATTR double3 floor(double3 v){return make_double3(floor(v.x), floor(v.y), floor(v.z));} VECATTR double dot(const double3 &a, const double3 &b){return a.x * b.x + a.y * b.y + a.z * b.z;} VECATTR float dot(const float3 &a, const float3 &b){return a.x * b.x + a.y * b.y + a.z * b.z;} VECATTR int dot(const int3 &a, const int3 &b){return a.x * b.x + a.y * b.y + a.z * b.z;} VECATTR double length(double3 v){return sqrt(dot(v, v));} VECATTR double3 normalize(double3 v) { double invLen = 1.0/sqrt(dot(v, v)); return v * invLen; } VECATTR double3 cross(double3 a, double3 b){ return make_double3(a.y*b.z - a.z*b.y, a.z*b.x - a.x*b.z, a.x*b.y - a.y*b.x); } ////////////////////////////////////////////////////////// /****************************************************************************************/ ///////////INT3///////////////// VECATTR int3 make_int3(int a){return make_int3(a,a,a);} VECATTR int3 operator /(int3 a, int3 b){ return make_int3( a.x/b.x, a.y/b.y, a.z/b.z); } VECATTR int3 operator +(const int3 &a, const int3 &b){ return make_int3(a.x + b.x, a.y + b.y, a.z + b.z); } VECATTR int3 operator +(const int3 &a, const int &b){ return make_int3(a.x + b, a.y + b, a.z + b); } VECATTR int3 operator *(const int3 &a, const int &b){return make_int3(a.x*b, a.y*b, a.z*b);} VECATTR int3 operator *(const int &b, const int3 &a){return a*b;} #endif
C
/** * @Author: GuillaumeLandre * @Date: 2018-10-26T14:41:10+01:00 * @Last modified by: GuillaumeLandre * @Last modified time: 2018-11-07T13:18:09+00:00 */ #include <stdio.h> #include <stdlib.h> int main(int argc, char const *argv[]) { int a = "0x2A"; int b = 0; printf("valeur de a en hexa = %x\n", a); return (0); }
C
#include "collection/lfcByteBuffer.h" #include "testing/lfcCriterionHelper.h" #define TEST_SUITE_NAME spec_lfcByteBuffer_write_uint32 Test( TEST_SUITE_NAME, return_0_after_start ) { lfcByteBuffer_t *tto = lfcByteBuffer_ctor(); should_be_same_int_wText(lfcByteBuffer_write_uint32(tto, 1), 4, "return 4"); delete(tto); } Test( TEST_SUITE_NAME, checkIf_capacity_is_incremented ) { lfcByteBuffer_t *tto = lfcByteBuffer_ctor(); lfcByteBuffer_write_uint32(tto, 1); should_be_same_int_wText(lfcByteBuffer_capacity(tto), 4, "should be incremented"); delete(tto); } Test( TEST_SUITE_NAME, read_correct ) { uint32_t result = 0; lfcByteBuffer_t *tto = lfcByteBuffer_ctor(); lfcByteBuffer_write_uint32(tto, 1145); lfcByteBuffer_read_uint32(tto, &result); should_be_same_int(result, 1145); delete(tto); }
C
/*working code*/ #include<stdio.h> int main(void){ int i; unsigned long long sum; unsigned long long sumsq; sum = (100 * 101 / 2)*(100*101/2); sumsq = (100 * 101 * 201)/6; printf("sum: %lld\n",sum); printf("sumsq: %lld\n",sumsq); printf("sum - sumsq: %lld\n",(sum - sumsq)); return(0); }
C
/** @file selection.c @author Andrew Dallow - ID: 56999204, Dan Orr - ID: 53440575 @date 11 Oct 2014 @brief Maps Navswitch buttons to Rock, Paper, or Scissors symbols and displays them on the led matrix. */ #include "navswitch.h" #include "tinygl.h" #include "RPS_shapes.h" #include "selection.h" static char character[3] = {ROCK, PAPER, SCISSORS}; static uint8_t option = 0; static uint8_t num_choices = 3; /** read character into buffer and display * text to screen */ void display_character (char character) { char buffer[2]; buffer[0] = character; buffer[1] = '\0'; tinygl_text (buffer); } /** Cycles through the options Paper, Rock and Sissors * with up/down navswitch option */ char get_choice(void) { tinygl_font_set (&RPS_shapes); if (navswitch_push_event_p (NAVSWITCH_NORTH)) { option = (option + 1) % num_choices; } if (navswitch_push_event_p (NAVSWITCH_SOUTH)) { if (option != 0) { option = (option - 1) % num_choices; } else { option = 2; } } display_character (character[option]); return character[option]; }
C
#include<stdio.h> #include<string.h> int regex2(char *string){ int i,j=0,state_transition[2][3]={{0,2,2},{1,1,2}}; int size = strlen(string); for(i=0;i<size;i++){ if(string[i]=='a'){ j = state_transition[0][j]; } else if(string[i]=='b'){ j = state_transition[1][j]; } } if(j==2){ return 0; } else if(j==0 || j==1){ return 1; } } int main(){ char string[1000]; printf("Enter the string "); scanf("%s",string); if(regex2(string)){ printf("String is of the form a*b*\n"); } else{ printf("String is not of the form a*b*\n"); } return 0; }
C
#include <stdio.h> #include <unistd.h> #include <sys/types.h> #include <ctype.h> #include <stdlib.h> #include <string.h> #include <sys/wait.h> #include <sys/ipc.h> #include <sys/shm.h> #include <signal.h> #define SHMKEY 314159 #define BUFF_SZ sizeof(2) void addSeconds(long* myClock); int main(int argc, char **argv){ long duration; duration = atol(argv[1]); int shmid = shmget ( SHMKEY, BUFF_SZ, 0775); if (shmid == -1){ perror("Child - ERROR in shmget"); exit(1); } /*attach the given shared memory segment, at a free position that will be allocated by the system*/ long * myClock = (long *)(shmat(shmid, 0, 0 )); int i; //read clock and add duration to it for(i = 0; i < duration; i++){ myClock[1] = myClock[1] + 1; addSeconds(myClock); } fprintf(stdout, "PID: %d - clock: [%d][%d] - Child TERMINATING\n", getpid(), myClock[0], myClock[1]); shmdt(myClock); exit(EXIT_SUCCESS); }//end main void addSeconds(long * myClock){ long leftOvers; long remainder; if(myClock[1] > 999999999){ leftOvers = myClock[1]/1000000000; myClock[0] = myClock[0] + leftOvers; remainder = myClock[1] % 1000000000; myClock[1] = remainder; } }
C
#include "main.h" #define INTERVAL 100 // Logging intverval in milliseconds FATFS FatFs; FIL logfile; int logtime = 0; int logging = 0; int buttonready = 1; void LED_Init(void) { RCC->AHBENR |= RCC_AHBENR_GPIOAEN; RCC->AHBENR |= RCC_AHBENR_GPIOBEN; RCC->AHBENR |= RCC_AHBENR_GPIOFEN; GPIOA->MODER |= (1 << (PIN_LED_1 << 1)) | (1 << (PIN_LED_2 << 1)) |\ (1 << (PIN_LED_3 << 1)) | (1 << (PIN_LED_4 << 1)) |\ (1 << (PIN_LED_5 << 1)); } void StartLogging(void) { FRESULT rc; rc = f_mount(&FatFs, "", 1); if(rc == FR_OK) { rc = f_open(&logfile, "log.csv", FA_WRITE | FA_CREATE_ALWAYS); if(rc == FR_OK) { f_printf(&logfile, "This file was written by a simple STM32F0 SD card example.\n" "More specifically, by build number %d, created on %d.\n" "The example provides a simple temperature logger:\n" "Time (ms), Temperature (°C)\n", BUILD_NUMBER, BUILD_DATE); // SD card is mounted and the log file open. // Everything went OK, so LED 1 can be turned off GPIOA->BRR |= (1 << PIN_LED_1); // Enable the timer TIM3->CR1 |= TIM_CR1_CEN; f_sync(&logfile); GPIOA->BSRR |= (1 << PIN_LED_2); logging = 1; } } } void StopLogging(void) { TIM3->CR1 &= ~TIM_CR1_CEN; f_sync(&logfile); f_close(&logfile); GPIOA->BRR |= (1 << PIN_LED_2); logging = 0; } int main(void) { LED_Init(); // LED 1 should be lit up during the initialisation GPIOA->BSRR |= (1 << PIN_LED_1); // Enable button pull-up GPIOA->PUPDR |= (1 << (PIN_BUTTON << 1)); // The ADC is used for simple and inaccurate temperature measurements RCC->APB2ENR |= RCC_APB2ENR_ADCEN; ADC1->CR |= ADC_CR_ADEN; while(~ADC1->ISR & ADC_ISR_ADRDY); ADC1->CHSELR = ADC_CHSELR_CHSEL16; ADC1->SMPR = 7; ADC->CCR |= ADC_CCR_TSEN; // It's time to initialise the timer for our logging purposes // It should issue an interrupt request every n seconds RCC->APB1ENR |= RCC_APB1ENR_TIM3EN; TIM3->PSC = INTERVAL - 1; TIM3->ARR = 48000; // Enable the overflow interrupt TIM3->DIER = TIM_DIER_UIE; NVIC_EnableIRQ(TIM3_IRQn); // Start logging immediately StartLogging(); while(1) { // Toggle logging on button presses if(GPIOA->IDR & (1 << PIN_BUTTON)) { buttonready = 1; } else if(buttonready) { buttonready = 0; if(logging) { StopLogging(); } else { StartLogging(); } } } return 0; } void TIM3_IRQHandler(void) { // Enable LED 5 to indicate the CPU's working GPIOA->BSRR |= (1 << PIN_LED_5); ADC1->CR |= ADC_CR_ADSTART; while(ADC1->CR & ADC_CR_ADSTART); //int temp = ((1.43f - (ADC1->DR / 4095.0f * 3.3f)) / 4.3e-3f + 25.0f) * 100; int temp = (3575580 - 1874 * ADC1->DR) / 100; f_printf(&logfile, "%08d, %d.%02d\n", logtime * INTERVAL, temp / 100, temp % 100); logtime++; // Disable LED 5 again and clear the interrupt flag GPIOA->BRR |= (1 << PIN_LED_5); TIM3->SR &= ~TIM_SR_UIF; }
C
#include <sys/time.h> #include <stdlib.h> #include <stdio.h> /*----------------------------------------------------------*/ /* time in sec */ /*----------------------------------------------------------*/ double util_gettime(){ struct timeval tp; gettimeofday(&tp, NULL); return((double)tp.tv_sec+(0.000001)*tp.tv_usec); }
C
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <pthread.h> #define MAX_THREADS 2 #define BUF 255 #define COUNTER (10 * 1000 * 1000) /* global var: Race Condition! */ static FILE *fz; static void open_file(const char* file) { fz = fopen(file, "w+"); if (fz == NULL) { printf("Konnte Datei %s nicht öffnen\n", file); exit(EXIT_FAILURE); } } static void thread_schreiben(void* name) { (void)name; char string[BUF]; printf("Bitte Eingabe machen: "); fgets(string, BUF, stdin); fputs(string, fz); fflush(fz); for (int i=0; i<COUNTER; ++i); pthread_exit((void*)pthread_self()); } static void thread_lesen(void* name) { (void)name; char string[BUF]; rewind(fz); fgets(string, BUF, fz); printf("Ausgabe Thread %ld: ", (long)pthread_self()); fputs(string, stdout); fflush(stdout); pthread_exit((void*)pthread_self()); } int main(void) { int i; static int ret[MAX_THREADS]; static pthread_t thread[MAX_THREADS]; printf("\n-> Main-Thread gestartet (ID:%ld)\n", (long)pthread_self()); open_file("testfile"); if (pthread_create(&thread[0], NULL, (void*)&thread_schreiben, NULL) != 0) { fprintf(stderr, "Konnte Thread nicht erzeugen ...!\n"); exit(EXIT_FAILURE); } if (pthread_create(&thread[1], NULL, (void*)&thread_lesen, NULL) != 0) { fprintf(stderr, "Konnte Thread nicht erzeugen ...!\n"); exit(EXIT_FAILURE); } for (i=0; i< MAX_THREADS; ++i) { pthread_join(thread[i], (void*)(&ret[i])); } for (i=0; i< MAX_THREADS; ++i) { printf("\t<-Thread %ld fertig\n", (long)thread[i]); } printf("<- Main-Thread beendet (ID:%ld)\n", (long)pthread_self()); return EXIT_SUCCESS; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* get_next_line.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: bpezeshk <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/02/09 11:05:59 by bpezeshk #+# #+# */ /* Updated: 2017/02/09 11:06:08 by bpezeshk ### ########.fr */ /* */ /* ************************************************************************** */ #include "get_next_line.h" #include <libft.h> static t_list *get_curr(t_list **lst, const int fd) { t_list *el; el = *lst; while (el) { if ((int)el->content_size == fd) return (el); el = el->next; } if (!(el = ft_lstnew("", 1))) return (el); el->content_size = fd; ft_lstadd(lst, el); return (*lst); } static int setnxtline(t_list *curr, char **line) { char *p1; char *p2; p1 = curr->content; if (!*p1) return ((int)(*line = NULL)); p2 = curr->content; while (*p2 != '\n' && *p2) p2++; if (!(*line = ft_strndup(p1, p2 - p1)) \ || !(curr->content = *p2 ? ft_strdup(p2 + 1) : "")) { free(*line); free(p1); return ((int)(*line = NULL) \ + (int)(curr->content = NULL) - 1); } free(p1); return (1); } static int read_in(t_list *curr) { char *tmp; char buf[BUFF_SIZE + 1]; int status; if (ft_strchr(curr->content, '\n')) return (0); while ((status = read(curr->content_size, buf, BUFF_SIZE)) > 0) { buf[status] = '\0'; tmp = curr->content; if (!(curr->content = ft_strjoin(tmp, buf))) { free(tmp); return (-1); } free(tmp); if (ft_strchr(buf, '\n')) return (1); } return (status); } int get_next_line(const int fd, char **line) { static t_list *lst; t_list *curr; if (!line) return (-1); if (fd < 0 || !(curr = get_curr(&lst, fd)) || !curr->content \ || read_in(curr) < 0) return ((int)(*line = NULL) - 1); return (setnxtline(curr, line)); }
C
#include <arpa/inet.h> #include "csapp.h" int main(int argc, char** argv) { if (argc != 2) { unix_error("Usage: ./exe <32 bit unsigned hex number>"); } struct in_addr addr; sscanf(argv[1], "%x", &addr.s_addr); const char* dotted_decimal_string = inet_ntoa(addr); printf("%s\n", dotted_decimal_string); }
C
#include <stdlib.h> #include <stdio.h> #include <ncurses.h> #include "board.h" #include "man.h" #include "physics.h" #define WIDTH 21 #define HEIGHT 21 #define DELAY 100 enum COLOUR_PAIRS { PLAYER_ONE=1, PLAYER_TWO, FLAMES }; void init(); void end(); WINDOW *create_window(int height, int width, int starty, int startx, bool borders); void destroy_window(WINDOW *local_win); void init_colours(); int main() { struct Board* board = new_board(HEIGHT, WIDTH); clear_board(board); generate_walls(board); start_physics(board); init(); refresh(); WINDOW* window = create_window(HEIGHT+2, WIDTH+2, 0, 0, 1); timeout(DELAY); init_colours(); struct Man* p1 = new_man(0, WIDTH-1, board, PLAYER_ONE); struct Man* p2 = new_man(0, 0, board, PLAYER_TWO); int ch = '\0'; struct Square* sq = NULL; do { switch(ch) { case KEY_DOWN: man_down(p1); break; case KEY_UP: man_up(p1); break; case KEY_RIGHT: man_right(p1); break; case KEY_LEFT: man_left(p1); break; case '\n': get_bomb(p1); break; case 's': man_down(p2); break; case 'w': man_up(p2); break; case 'd': man_right(p2); break; case 'a': man_left(p2); break; case ' ': get_bomb(p2); break; } for(int r = 0; r < HEIGHT; r++) { for(int c = 0; c < WIDTH; c++) { // Get board square sq = get_square(board, r, c); char display = sq->display; if(sq->type == MELTING || sq->type == MELTING_OBJ) { wattron(window, COLOR_PAIR(FLAMES)); } else if(sq->type == PLAYER) { struct Man* man = sq->data; wattron(window, COLOR_PAIR(man->colour)); } else if(sq->type == BLOCK) { wattron(window, WA_BOLD); } // Put into window mvwaddch(window, r+1, c+1, display); if(sq->type == MELTING || sq->type == MELTING_OBJ) { wattroff(window, COLOR_PAIR(FLAMES)); } else if(sq->type == PLAYER) { struct Man* man = sq->data; wattroff(window, COLOR_PAIR(man->colour)); } else if(sq->type == BLOCK) { wattroff(window, WA_BOLD); } } } refresh(); wrefresh(window); } while((ch = getch()) != 'q'); delete_man(p1, board); delete_man(p2, board); destroy_window(window); endwin(); stop_physics(); clear_board(board); delete_board(board); return 0; } void init() { initscr(); cbreak(); // Pass characters with generating signals noecho(); // Don't echo characters keypad(stdscr, TRUE); // Enable keypad function/arrow keys start_color(); } void end() { endwin(); } WINDOW *create_window(int height, int width, int starty, int startx, bool borders) { WINDOW *local_win; local_win = newwin(height, width, starty, startx); if (borders) { box(local_win, 0, 0); } wrefresh(local_win); return local_win; } void destroy_window(WINDOW *local_win) { wborder(local_win, ' ', ' ', ' ',' ',' ',' ',' ',' '); wrefresh(local_win); delwin(local_win); } void init_colours() { init_pair(FLAMES, COLOR_YELLOW, COLOR_RED); init_pair(PLAYER_ONE, COLOR_GREEN, COLOR_BLACK); init_pair(PLAYER_TWO, COLOR_CYAN, COLOR_BLACK); }
C
#include<stdio.h> int A[27]; char Word[11]; char Alpha[27] = { '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 T; int Max; void readCase() { int i; for (i = 0; i < 26; i++) { scanf("%d", &A[i]); } scanf(" %s", Word); } void solveCase() { int i, j; Max = 1; for (i = 0; Word[i] != '\0'; i++) { for (j = 0; j < 26; j++) { if (Word[i] == Alpha[j]) { T = A[j]; if (T > Max) { Max = T; } } } } printf("%d\n", i*Max); } void printCase() { } int main() { readCase(); solveCase(); printCase(); return 0; }
C
/*** * ***/ #include<stdio.h> int max(int x, int y) { return ((x>y)?x:y); } void ks(int cap,int wt[],int pf[],int n) { int t[n+1][cap+1], i, j; for(i=0;i<=n;++i) { for(j=0;j<=cap;++j) { if(i==0 || j==0) t[i][j]=0; else if(wt[i-1]<=j) t[i][j] = max((pf[i-1]+t[i-1][j-wt[i-1]]),t[i-1][j]); else t[i][j]=t[i-1][j]; } } printf("\n The matrix is : \n"); for(i=0;i<=n;++i) { for(j=0;j<=cap;++j) printf(" %2d",t[i][j]); printf("\n"); } printf("\n The max profit is: %d \n",t[n][cap]); } int main() { int i, n, cap; printf("\n Enter the value of n : "); scanf("%d",&n); int wt[n], pf[n]; printf("\n Enter the profits : "); for(i=0;i<n;++i) scanf("%d",&pf[i]); printf("\n Enter the weights : "); for(i=0;i<n;++i) scanf("%d",&wt[i]); printf("\n Enter the capacity of the knapsack : "); scanf("%d",&cap); ks(cap,wt,pf,n); return 0; }
C
class C { int a; int m(int b) { return this.a + b; } } int main() { class C c; int d; c = newC(); c.a = 1; d = c.m(1); return 0; }
C
/*Задача 3.Напишете функцията int linSearch(int a[], int l, int d), която получава като първи аргумент началото на масив а, втория аргумент е дължината на масива, а третия аргумент е числото, което търсим. Претърсете масива елемент по елемент и ако някой елемент съвпада с търсеното число върнете позицията на която се намира този елемент. В противен случай върнете – 1.*/ #include <stdio.h> int linSearch(int a[], int l, int d){ for (int i = 0; i < l; i++){ if (a[i]==d){ return i; } } return -1; } int main(){ int a[] = {1, 5, 2, 7, 7}; int len = sizeof(a)/sizeof(a[0]); int num =7; printf("%d", linSearch(a, len, num)); return 0; }
C
#include <stdio.h> #define MAX 4000000 int main(void) { int sum = 0; int prev = 1, cur = 2, temp; while (cur < MAX) { if (cur % 2 == 0) { sum += cur; } temp = cur; cur += prev; prev = temp; } printf("Sum: %d\n", sum); return 0; }
C
/********************************************************* ESCRIPTION: Test of implementation functions of stack. Athor: Gal Dahan Reviewer:--- **********************************************************/ #include <stdio.h>/*printf*/ #include <stddef.h> /* size_t */ #include <stdlib.h> #include "../include/stack.h" void StackCreateDestroyTest(void); void StackPushPopTest(void); void StackPeekTest(void); void StackSizeTest(void); void StackIsEmptyTest(void); void StackCapacityTest(void); int main() { StackCreateDestroyTest(); StackPushPopTest(); StackPeekTest(); StackSizeTest(); StackIsEmptyTest(); StackCapacityTest(); return 0; } void StackCreateDestroyTest(void) { size_t size = 11; size_t cap = 50; stack_t *ptr; ptr = StackCreate(size, cap); if(NULL == ptr) { printf("StackCreate FAILED***\n"); } else { printf("StackCreate SUCCESS\n"); StackDestroy(ptr); printf("StackDestroy SUCCESS (not crashed)\n"); ptr = NULL; } } void StackPushPopTest(void) { size_t size = sizeof(int); size_t cap = 50; stack_t *ptr; int element = 0; ptr = StackCreate(size, cap); /*push * 4*/ element = 5; if(0 != StackPush(ptr, &element)) { printf("StackPush FAILED***\n"); } else { printf("StackPush SUCCESS\n"); } element = 4; if(0 != StackPush(ptr, &element)) { printf("StackPush FAILED***\n"); } else { printf("StackPush SUCCESS\n"); } element = 3; if(0 != StackPush(ptr, &element)) { printf("StackPush FAILED***\n"); } else { printf("StackPush SUCCESS\n"); } element = 2; if(0 != StackPush(ptr, &element)) { printf("StackPush FAILED***\n"); } else { printf("StackPush SUCCESS\n"); } /*pop * 4*/ if(0 != StackPop(ptr)) { printf("StackPop FAILED***\n"); } else { printf("StackPop SUCCESS\n"); } if(0 != StackPop(ptr)) { printf("StackPop FAILED***\n"); } else { printf("StackPop SUCCESS\n"); } if(0 != StackPop(ptr)) { printf("StackPop FAILED***\n"); } else { printf("StackPop SUCCESS\n"); } if(0 != StackPop(ptr)) { printf("StackPop FAILED***\n"); } else { printf("StackPop SUCCESS\n"); } StackDestroy(ptr); } void StackPeekTest(void) { size_t size = sizeof(int); size_t cap = 50; stack_t *ptr; int element = 0; ptr = StackCreate(size, cap); /*push * 4*/ element = 5; StackPush(ptr, &element); element = 4; StackPush(ptr, &element); if(4 == *(int *) StackPeek(ptr)) { printf("StackPeek SUCCESS\n"); } else { printf("StackPeek FAILED***\n"); } StackPop(ptr); if(5 == *(int *) StackPeek(ptr)) { printf("StackPeek SUCCESS\n"); } else { printf("StackPeek FAILED***\n"); } StackPop(ptr); if(NULL == StackPeek(ptr)) { printf("StackPeek SUCCESS\n"); } else { printf("StackPeek (empty) FAILED***\n"); } StackDestroy(ptr); } void StackSizeTest(void) { size_t size = sizeof(int); size_t cap = 50; stack_t *ptr; int element = 19; ptr = StackCreate(size, cap); if(0 == StackSize(ptr)) { printf("StackSize SUCCESS\n"); } else { printf("StackSize (empty) FAILED***\n"); } StackPush(ptr, &element); if(1 == StackSize(ptr)) { printf("StackSize SUCCESS\n"); } else { printf("StackSize FAILED***\n"); } StackDestroy(ptr); } void StackIsEmptyTest(void) { size_t size = sizeof(int); size_t cap = 50; stack_t *ptr; int element = 19; ptr = StackCreate(size, cap); if (StackIsEmpty(ptr)) { printf("StackIsEmpty (empty) SUCCESS\n"); } else { printf("StackIsEmpty (empty) FAILED***\n"); } StackPush(ptr, &element); if (!StackIsEmpty(ptr)) { printf("StackIsEmpty SUCCESS\n"); } else { printf("StackIsEmpty FAILED***\n"); } StackDestroy(ptr); } void StackCapacityTest(void) { size_t size = sizeof(int); size_t cap = 50; stack_t *ptr; ptr = StackCreate(size, cap); if(cap == StackCapacity(ptr)) { printf("StackCapacity SUCCESS\n"); } else { printf("StackCapacity FAILED***\n"); } StackDestroy(ptr); }
C
#include "LinkedListApi.h" #include <stdlib.h> #include <assert.h> #include <stdio.h> struct _ll_{ ll_node *head; unsigned int node_count; int (*comparison_fn)(void*, void*); int (*order_comparison_fn)(void*, void*); }; struct _ll_node{ void* data; struct _ll_node *next; }; ll_t* get_singly_ll(ll_t* ll){ return ll; } int get_singly_ll_node_count(ll_t* ll){ return ll->node_count; } ll_node* get_singly_ll_head(ll_t* ll){ return ll->head; } ll_node* get_next_node(ll_node* node){ return node->next; } ll_node* get_node_data(ll_node* node){ return node->data; } void decrease_node_count(ll_t* ll){ ll->node_count--; } void increase_node_count(ll_t* ll){ ll->node_count++; } ll_t* init_singly_ll(){ ll_t *head = calloc(1, sizeof(ll_t)); return head; } int add_node_by_val(ll_t *ll , void *data){ ll_node *node = calloc(1, sizeof(ll_node)); node->data = data; if(!ll->head){ ll->head = node; ll->node_count++; return 0; } node->next = ll->head; ll->node_count++; return 0; } bool_t is_ll_empty(ll_t *ll){ if(!ll) assert(0); if(ll->node_count == 0) return LL_TRUE; return LL_FALSE; } int ll_remove_node(ll_t* ll, ll_node *node){ if(!ll || !ll->head ) return 0; if(!node){ printf("%s(%d) : Error: node is NULL\n", __FUNCTION__, __LINE__); return -1; } ll_node *head = ll->head; ll_node *prev = NULL; if(head == node){ ll->head = ll->head->next; ll->node_count--; node->next = NULL; return 0; } prev = head; head = head->next; for(int i=1; i< ll->node_count; i++){ if(head != node){ prev = head; head = head->next; continue; } prev->next = head->next; head->next = NULL; ll->node_count--; return 0; } printf("%s(%d) : Error: node is NULL\n", __FUNCTION__, __LINE__); return -1; } int ll_add_node(ll_t *ll, ll_node *node){ if(!ll) return -1; if(!node) return -1; if(!ll->head){ ll->head = node; ll->node_count++; return 0; } node->next = ll->head; ll->head = node; ll->node_count++; return 0; } int ll_delete_node(ll_t *ll, ll_node *node){ if(!ll) return -1; if(!ll->head || !node) return 0; ll_node *trav = NULL; if(node->next){ ll_node *temp = NULL; node->data = node->next->data; temp = node->next; node->next = node->next->next; free(temp); ll->node_count--; return 0; } if(ll->node_count == 1 && ll->head == node){ free(node); ll->head = NULL; ll->node_count--; return 0; } trav = ll->head; while(trav->next != node){ trav = trav->next; continue; } trav->next = NULL; free(node); ll->node_count--; return 0; }
C
#define str_len 100 #include <stdio.h> // fprintf() // printf() // stderr // getchar() // perror() #include <unistd.h> //chdir() // fork() // exec() // pid_t #include <string.h> // for tokenising // strcmp() // strtok() #include <sys/types.h> // for mkdir #include <dirent.h> #include <stdlib.h> // malloc() // realloc() // free() // exit() // execvp() // EXIT_SUCCESS, EXIT_FAILURE #include <sys/wait.h> // for wait() #include <sys/stat.h> //for open #include <fcntl.h> //for open int main(){ char* arr[2]; char str[] = "./exe/main"; arr[0]=str; arr[1]=NULL; if(fork()==0){ if(execvp(arr[0],arr)<0){ perror("execvp run"); } }else{ wait(NULL); } return 0; }
C
#include "prf.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include "digest.h" #include "hex.h" #include "hmac.h" #include "md5.h" #include "sha.h" /** * P_MD5 or P_SHA, depending on the value of the new_digest function * pointer. * HMAC_hash( secret, A(1) + seed ) + HMAC_hash( secret, A(2) + seed ) + ... * where + indicates concatenation and A(0) = seed, A(i) = * HMAC_hash( secret, A(i - 1) ) */ static void P_hash(const unsigned char *secret, int secret_len, const unsigned char *seed, int seed_len, unsigned char *output, int out_len, void (*new_digest)(digest_ctx *context)) { unsigned char *A; int hash_len; // length of the hash code in bytes digest_ctx A_ctx, h; int adv; int i; new_digest(&A_ctx); hmac(secret, secret_len, seed, seed_len, &A_ctx); hash_len = A_ctx.hash_len * sizeof(int); A = malloc(hash_len + seed_len); memcpy(A, A_ctx.hash, hash_len); memcpy(A + hash_len, seed, seed_len); i = 2; while (out_len > 0) { new_digest(&h); // HMAC_Hash( secret, A(i) + seed ) hmac(secret, secret_len, A, hash_len + seed_len, &h); adv = (h.hash_len * sizeof(int)) < out_len ? h.hash_len * sizeof(int) : out_len; memcpy(output, h.hash, adv); out_len -= adv; output += adv; // Set A for next iteration // A(i) = HMAC_hash( secret, A(i-1) ) new_digest(&A_ctx); hmac(secret, secret_len, A, hash_len, &A_ctx); memcpy(A, A_ctx.hash, hash_len); } free(A); } /** * P_MD5( S1, label + seed ) XOR P_SHA1(S2, label + seed ); * where S1 & S2 are the first & last half of secret * and label is an ASCII string. Ignore the null terminator. * * output must already be allocated. */ void PRF(const unsigned char *secret, int secret_len, const unsigned char *label, int label_len, const unsigned char *seed, int seed_len, unsigned char *output, int out_len) { int i; int half_secret_len; unsigned char *sha1_out = (unsigned char *)malloc(out_len); unsigned char *concat = (unsigned char *)malloc(label_len + seed_len); memcpy(concat, label, label_len); memcpy(concat + label_len, seed, seed_len); half_secret_len = (secret_len / 2) + (secret_len % 2); P_hash(secret, half_secret_len, concat, (label_len + seed_len), output, out_len, new_md5_digest); P_hash(secret + (secret_len / 2), half_secret_len, concat, (label_len + seed_len), sha1_out, out_len, new_sha1_digest); for (i = 0; i < out_len; i++) { output[i] ^= sha1_out[i]; } free(sha1_out); free(concat); } #ifdef TEST_PRF int main(int argc, char *argv[]) { unsigned char *output; int out_len, i; int secret_len; int label_len; int seed_len; unsigned char *secret; unsigned char *label; unsigned char *seed; if (argc < 5) { fprintf(stderr, "usage: %s [0x]<secret> [0x]<label> [0x]<seed> <output len>\n", argv[0]); exit(0); } secret_len = hex_decode(argv[1], &secret); label_len = hex_decode(argv[2], &label); seed_len = hex_decode(argv[3], &seed); out_len = atoi(argv[4]); output = (unsigned char *)malloc(out_len); PRF(secret, secret_len, label, label_len, seed, seed_len, output, out_len); for (i = 0; i < out_len; i++) { printf("%.02x", output[i]); } printf("\n"); free(secret); free(label); free(seed); free(output); return 0; } #endif /* [jdavies@localhost ssl]$ ./prf secret label seed 20 b5baf4722b91851a8816d22ebd8c1d8cc2e94d55 */
C
#include <stdlib.h> #include <SDL/SDL.h> #include "constantes.h" #include "jeu.h" #include "menu.h" int main(int argc, char *argv[]) { //Initialisation de la SDL SDL_Init(SDL_INIT_VIDEO); SDL_SetVideoMode(LARGEUR_FENETRE, HAUTEUR_FENETRE, 32, SDL_HWSURFACE | SDL_DOUBLEBUF); SDL_WM_SetCaption(":: Casse-briques - INSA-CVL - 2014 ::", NULL); // Mise 0 du classement liste classement = NULL; // On charge le classement prcdement tabli classement = readClassement(classement); //On initialise notre menu initMenu(classement); // Appel de la fonction de fermeture de la SDL close(); return 0; } void close(void) { // Fermeture SDL SDL_Quit(); }
C
#pragma warning(disable:4996) #include <stdio.h> #include <string.h> #include <stdlib.h> typedef struct node { int coef; int exp; struct node *next; }NODE; typedef struct list { struct node *header; }Dlist; NODE *getnode(); void initList(Dlist *list); void appendTerm(Dlist *list, int c, int e); Dlist addPoly(Dlist *list1, Dlist *list2); void print(Dlist *list); int main() { Dlist list1, list2, res; int n = 0, coef = 0, exp = 0; initList(&list1); initList(&list2); initList(&res); scanf("%d", &n); while (n > 0) { scanf("%d %d", &coef, &exp); appendTerm(&list1, coef, exp); n--; } scanf("%d", &n); while (n > 0) { scanf("%d %d", &coef, &exp); appendTerm(&list2, coef, exp); n--; } res = addPoly(&list1, &list2); print(&res); return 0; } NODE *getnode() { NODE *new_node; new_node = (NODE *)malloc(sizeof(NODE)); return new_node; } void initList(Dlist *list) { list->header = getnode(); list->header->next = NULL; } void appendTerm(Dlist *list, int c, int e) { NODE *new_node, *p; p = list->header; new_node = getnode(); new_node->coef = c; new_node->exp = e; while (p->next != NULL) { p = p->next; } p->next = new_node; new_node->next = NULL; } Dlist addPoly(Dlist *list1, Dlist *list2) { NODE *i, *j; Dlist res; int sum = 0; initList(&res); i = list1->header->next; j = list2->header->next; while ((i != NULL) && (j != NULL)) { if ((i->exp) > (j->exp)) { appendTerm(&res, i->coef, i->exp); i = i->next; } else if ((i->exp) < (j->exp)) { appendTerm(&res, j->coef, j->exp); j = j->next; } else { sum = i->coef + j->coef; if (sum != 0) appendTerm(&res, sum, i->exp); i = i->next; j = j->next; } } while (i != NULL) { appendTerm(&res, i->coef, i->exp); i = i->next; } while (j != NULL) { appendTerm(&res, j->coef, j->exp); j = j->next; } return res; } void print(Dlist *list) { NODE *p; p = list->header->next; while (p != NULL) { printf(" %d %d", p->coef, p->exp); p = p->next; } }
C
#ifndef _DCT_H #define _DCT_H #include <stdint.h> /** * 2-D Cosine Transform. * Naive and very slow version. */ void dct (int16_t* block, float destination[8][8]) ; /** * Inverse 2-D Cosine Transform. * Naive and very slow version. */ void idct (int16_t* block, float destination[8][8]) ; /** * Fast Cosine Transform. * Algorithm by Feig & Winograd. This is the scaled version. * (not working, not sure if it needs something else to be correct) */ void fdct (int16_t* block, float destination[8][8]) ; /** * Fast 2-D Cosine Transform. * Factorized version of the Feig & Winograd algorithm * which applies 1-D transform on columns first and then on the rows. */ void fdct2 (int16_t* block, float destination[8][8]) ; /** * Fast Inversed 2-D Cosine Transform. * Factorized version of the Feig & Winograd algorithm * which applies 1-D transform on columns first and then on the rows. */ void ifdct2 (int16_t* block, float destination[8][8]) ; #endif
C
#include "pipe.h" #include "sysfile.h" #include "spinlock.h" #include "slub.h" #include "sched.h" #include "put.h" extern struct file SysFTable[SYSOFILENUM]; extern struct spinlock SysFLock; int pipealloc(int *sfd0, int *sfd1) { struct pipe *pi; pi=NULL; if((*sfd0 = falloc()) == -1 || (*sfd1 = falloc()) == -1) goto bad; if((pi = (struct pipe*)kmalloc(sizeof(struct pipe))) == NULL) goto bad; pi->readopen = 1; pi->writeopen = 1; pi->nwrite = 0; pi->nread = 0; initlock(&pi->lock, "pipe"); struct file *f0 = &SysFTable[*sfd0]; struct file *f1 = &SysFTable[*sfd1]; acquire(&SysFLock); f0->f_type = DT_FIFO; f0->f_perm = READABLE; f0->pipe = pi; f1->f_type = DT_FIFO; f1->f_perm = WRITABLE; f1->pipe = pi; release(&SysFLock); return 0; bad: if(pi) kfree((char*)pi); if((*sfd0)!=-1) frelease(&SysFTable[*sfd0]); if((*sfd1)!=-1) frelease(&SysFTable[*sfd1]); return -1; } int pipeclose(struct file *f) { //struct file *f=current->FTable[fd]; struct pipe *pi=f->pipe; acquire(&pi->lock); if(f->f_perm==WRITABLE) { pi->writeopen=0; wakeup(&pi->nread); } else if(f->f_perm==READABLE) { pi->readopen = 0; wakeup(&pi->nwrite); } else return -1; if(pi->readopen == 0 && pi->writeopen == 0) { release(&pi->lock); kfree((char*)pi); } else release(&pi->lock); return 0; } int pipewrite(struct file *f, char *str, int n) { int i; //struct file *f=current->FTable[fd]; struct pipe *pi=f->pipe; acquire(&pi->lock); if(f->f_perm!=WRITABLE) { release(&pi->lock); return -1; } if(pi->writeopen == 0) { release(&pi->lock); return -2; } for(i = 0; i < n; i++){ while(pi->nwrite == pi->nread + PIPESIZE){ //DOC: pipewrite-full if(pi->readopen == 0){ release(&pi->lock); return -1; } wakeup(&pi->nread); sleep(&pi->nwrite, &pi->lock); } //if((uint64)str+i>=SZ) break; pi->data[pi->nwrite++ % PIPESIZE] = str[i]; } printf("%d\n",pi->nwrite); wakeup(&pi->nread); release(&pi->lock); return i; } int piperead(struct file *f, char *str, int n) { //struct file *f=current->FTable[fd]; struct pipe *pi=f->pipe; int i; acquire(&pi->lock); if(f->f_perm!=READABLE) { release(&pi->lock); return -1; } if(pi->readopen == 0) { release(&pi->lock); return -2; } while(pi->nread == pi->nwrite && pi->writeopen){ //DOC: pipe-empty sleep(&pi->nread, &pi->lock); //DOC: piperead-sleep } for(i = 0; i < n; i++){ //DOC: piperead-copy if(pi->nread == pi->nwrite) break; //if(str+i>=SZ) break; str[i]=pi->data[pi->nread++ % PIPESIZE]; } wakeup(&pi->nwrite); //DOC: piperead-wakeup release(&pi->lock); return i; } void pipe_test() { // int _pipe[2]; // int ret=pipealloc(_pipe,_pipe+1); // if(ret<0) // { // printf("pipe error\n"); // } // char mesg1[100]; // char *mesg2; // mesg2="ABCDEF"; // //pipeclose(&SysFTable[_pipe[1]]); // printf("1:%d\n",pipewrite(&SysFTable[_pipe[1]],mesg2,7)); // printf("2:%d\n",piperead(&SysFTable[_pipe[0]],mesg1,7)); // printf("%s\n",mesg1); // while(1); }
C
//헤더파일 #include <stdio.h> #include <string.h> typedef struct { char name[20]; //제품명 int weight; //중량 int price; //가격 int num; //별점개수 } Product; int createProduct(Product *p); // 제품을 추가하는 함수 void readProduct(Product p); // 하나의 제품 출력 함수 void listProduct(Product *p, int count); // 전체 등록된 제품 리스트 출력 int selectDataNo(Product *p, int count); // 번호 선택 int UpdateProduct(Product *p); //제품을 정보를 수정하는 함수 int deleteProduct(Product *p); //제품을 삭제하는 함수 int selectMenu(); //메뉴를 선택하는 함수 void saveData(Product *p, int count);//파일로 저장하는 함수 int loadData(Product *p);//파일을 로드하는함수 void searchName(Product *p, int count);//검색하는 함수
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* fill_cmdlist.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dcapers <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/03/04 12:21:05 by dcapers #+# #+# */ /* Updated: 2020/03/08 15:08:41 by dcapers ### ########.fr */ /* */ /* ************************************************************************** */ #include "push_swap.h" int fill_cmdlist(t_list **cmd) { char *command; int error; command = NULL; error = 0; *cmd = NULL; while (get_next_line(0, &command) > 0) { if (!(ft_strcmp(command, "sa") == 0 || ft_strcmp(command, "sb") == 0 || ft_strcmp(command, "ss") == 0 || ft_strcmp(command, "pa") == 0 || ft_strcmp(command, "pb") == 0 || ft_strcmp(command, "ra") == 0 || ft_strcmp(command, "rb") == 0 || ft_strcmp(command, "rr") == 0 || ft_strcmp(command, "rra") == 0 || ft_strcmp(command, "rrb") == 0 || ft_strcmp(command, "rrr") == 0)) { write(1, "Error\n", 6); exit(0); } ft_list_push(cmd, command); command = NULL; } return (!error); }
C
#include <stdio.h> #include <math.h> int main() { char line[100]; float num_grade; char letter_grade; char modifier; printf("Please enter your numeric grade: "); fgets(line, sizeof(line), stdin); sscanf_s(line, "%f", &num_grade); if (num_grade > 100 || num_grade < 0) { printf("Invalid grade entered."); return (0); } else { if (num_grade >= 91) { letter_grade = 'A'; if (fmodf(num_grade,10) == 0 || fmodf(num_grade, 10) >= 8) modifier = '+'; else if (fmodf(num_grade, 10)) modifier = '\0'; else modifier = '-'; } else if (num_grade >= 81) { letter_grade = 'B'; if (fmodf(num_grade, 10) == 0 || fmodf(num_grade, 10) >= 8) modifier = '+'; else if (fmodf(num_grade, 10) >= 4) modifier = '\0'; else modifier = '-'; } else if (num_grade >= 71) { letter_grade = 'C'; if (fmodf(num_grade, 10) == 0 || fmodf(num_grade, 10) >= 8) modifier = '+'; else if (fmodf(num_grade, 10) >= 4) modifier = '\0'; else modifier = '-'; } else if (num_grade >= 61) { letter_grade = 'D'; if (fmodf(num_grade, 10) == 0 || fmodf(num_grade, 10) >= 8) modifier = '+'; else if (fmodf(num_grade, 10) >= 4) modifier = '\0'; else modifier = '-'; } else letter_grade = 'F'; } printf("Your letter grade is: %c%c", letter_grade, modifier); return(0); }
C
#include "tree.h" // Morris Traversal void in_order_iterative(struct Tnode *root) { struct Tnode *current = root; struct Tnode *pre = NULL; printf("Inorder Traversal:"); while (current != NULL) { // if there is no left node, print the current node and advance to the right. if (current->left == NULL) { printf("%d,",current->data); current = current->right; } else { pre = current->left; // find the predecessor the current node in the left subtree. while (pre->right != NULL && pre->right != current) { pre = pre->right; } // if we need to print the left subtree, // the predecessor right will be null, so make it point to current node. // and advance to the left subtree. if (pre->right == NULL) { pre->right = current; current = current->left; } else { // if we already printed the left subtree, the predecessors right // will point to current. so make it nul. // print the current node and advance to right. pre->right = NULL; printf("%d,",current->data); current = current->right; } } } printf("\n"); } int main() { struct Tnode *root = NULL; root = create_node(1); root->left = create_node(2); root->left->left = create_node(4); root->left->right = create_node(5); root->right = create_node(3); in_order_iterative(root); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ps_getinfo2.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: akondaur <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/11/21 23:37:35 by akondaur #+# #+# */ /* Updated: 2018/11/21 23:38:10 by akondaur ### ########.fr */ /* */ /* ************************************************************************** */ #include "push_swap.h" int ft_find_prev_b(t_stack *l, int el) { t_stack *tmp; int prev; tmp = l; prev = (l->el < el) ? l->el : ft_find_min(l); tmp = tmp->next; while (tmp != l) { if (tmp->el > prev && tmp->el < el) prev = tmp->el; tmp = tmp->next; } if (el < ft_find_min(l) || el > ft_find_max(l)) return (ft_find_max(l)); return (prev); } int ft_find_prev_a(t_stack *l, int el) { t_stack *tmp; int prev; tmp = l; prev = (l->el < el) ? l->el : ft_find_min(l); tmp = tmp->next; while (tmp != l) { if (tmp->el > prev && tmp->el < el) prev = tmp->el; tmp = tmp->next; } if (el < ft_find_min(l) || el > ft_find_max(l)) return (ft_find_max(l)); return (prev); } int ft_check_sort(t_stack **a, t_stack **b, int el) { t_stack *tmp; if (ft_find_max(*b) > ft_find_min(*a)) return (0); tmp = *a; while (tmp->el != el) { if (tmp->el > tmp->next->el) return (0); tmp = tmp->next; } return (1); } int ft_is_sort_a(t_stack *a) { t_stack *tmp; if (!a) return (1); tmp = a; while (tmp->next != a) if (tmp->el > tmp->next->el) return (0); else tmp = tmp->next; return (1); } int ft_is_sort_b(t_stack *b) { t_stack *tmp; if (!b) return (1); tmp = b; while (tmp->next != b) if (tmp->el < tmp->next->el) return (0); else tmp = tmp->next; return (1); }
C
/* dibuja una grafica de barras horizontales */ /* Autor: Jose Luis Quijada */ #include <stdio.h> #include "grafico.h" #define MAX_BUFFER 5 int buffer[MAX_BUFFER] = {4, 6, 7, 11, 13}; void drawBar(int value) { for (int i = 1; i <= value; i++) { printf("*"); } printf("%2d ", value); } int drawGraph(int *data, char *labels, int datalength) { for (int i = 0; i < datalength; i++) { printf("%c: ",labels[i]); drawBar(data[i]); printf("\n"); } return 0; } /* int main(int argc, char const *argv[]) { for (int i = 0; i <= MAX_BUFFER; i++){ drawBar(buffer[i]); printf("\n"); } } */
C
//reversersing the string #include<stdio.h> char * count(char *p) { int i,j; char q; for(i=0;p[i];i++); for(i=i-1,j=0;i>j;i--,j++) { q=p[i];p[i]=p[j];p[j]=q; } } main() { char s[100]; printf("enter the first string..."); scanf("%[^\n]",s); printf("before... %s \n ",s); count(s); printf("after.... %s \n ",s); }
C
#include<stdio.h> #include<stdlib.h> #include<math.h> #include<limits.h> #define scan1(a) scanf("%d",&a) #define scan2(b,c) scanf("%d %d", &b, &c) #define scan3(d,e,f) scanf("%d %d %d", &d, &e, &f) #define pn() printf("\n"); #define print1(a) printf("%d\n", a) #define print2(a,b) printf("%d %d\n", a, b) #define print3(a,b,c) printf("%d %d %d\n", a, b, c) #define loop(i,n) for(int i=0;i<n;i++) #define min(a,b) (a<b)?a:b int a[100]; int main() { int n; scan1(n); int i, j, k; for(i=0;i<n;i++) { int t; scan1(t); int start = 0, end = i; int mid = (end - start) / 2; while(start != mid && mid != end) { if (a[mid] > t) end = mid; else if (a[mid] <= t) start = mid; mid = start + (end - start)/2; } for(j=mid; j < i; j++) { if (a[j] > t) break; } for(k = i; k >= j+1; k--) a[k] = a[k-1]; a[j] = t; if(i%2 == 0) printf("%.1f\n", (float)a[i/2]); else printf("%.1f\n", (float)(a[i/2] + a[(i+1)/2])/2.0); } return 0; }
C
int i = 0; while (i++ < 3) printf("%d ", i); for (; ; i++) { printf("%d\n",i); }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> void main() { char str[100]; FILE *fp1 = fopen("test1.txt","r"); FILE *fp2 = fopen("test2.txt","w"); if( fp1 == NULL && fp2 == NULL ) { printf("Error."); exit(0); } else { fgets(str,100,fp1); printf("%s, Written in a different file",str); fputs(str,fp2); fclose(fp1); fclose(fp2); } }
C
/* Created by tamarapple on 9/11/19 */ #include <stdio.h> #include "tests.h" void vectorCreate_test() { /* creates vector with capacity 1000 */ Vector *vector_3 = vectorCreate(1000); vectorDestroy(&vector_3); /* tries to create vector with capacity 0 */ /* Vector *vector_2 = vectorCreate(0); vectorDestroy(&vector_2); */ /* tries to create vector with negative capacity : program falls (vectorCreate gets size_t) */ /* Vector *vector_3 = vectorCreate(-2); vectorDestroy(&vector_2); */ } void vectorPush_test() { Vector *vector = vectorCreate(3); int i = 0; for (; i < 1000; ++i) { vectorPush(vector, i); } printVector(vector); vectorDestroy(&vector); } void vectorInsert_test() { ErrorCode errorCode; Vector *vector = vectorCreate(6); int i = 0; for (; i < 15; ++i) { vectorPush(vector, i); } printVector(vector); /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 */ /* adds value to the end of the vector*/ vectorInsert(vector, 111, 15); printVector(vector); /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 111 */ /* adds value to the beginning of the vector */ vectorInsert(vector, 222, 0); printVector(vector); /* 222 0 1 2 3 4 5 6 7 8 9 10 11 12 13 111 */ /* adds value to the middle of the vector */ vectorInsert(vector, 333, 8); printVector(vector); /* 222 0 1 2 3 4 5 6 333 7 8 9 10 11 12 13 111 */ /* adds value to invalid index */ errorCode = vectorInsert(vector, 333, 20); printf("Error Code: %d\n", errorCode); printVector(vector); /* 222 0 1 2 3 4 5 6 333 7 8 9 10 11 12 13 111 */ vectorDestroy(&vector); } void vectorPop_test() { int res; ErrorCode errorCode; Vector *vector = vectorCreate(15); int i = 0; for (; i < 7; ++i) { vectorPush(vector, i); } printVector(vector); /* 0 1 2 3 4 5 6 */ for (i = 0; i < 7; ++i) { vectorPop(vector, &res); printf("res: %d\n", res); printVector(vector); } /* tries to pop from an empty vector*/ errorCode = vectorPop(vector, &res); printf("Error Code: %d\n", errorCode); /* 2 = E_UNDERFLOW*/ printVector(vector); vectorDestroy(&vector); } void vectorRemove_test() { int res; ErrorCode errorCode; Vector *vector = vectorCreate(15); int i = 1; for (; i < 8; ++i) { vectorPush(vector, i); } printVector(vector); /* 1 2 3 4 5 6 7 */ /* remove last element */ vectorRemove(vector, 6, &res); printf("res: %d\n", res); /* 7 */ printVector(vector); /* 1 2 3 4 5 6 */ /* remove first element */ vectorRemove(vector, 0, &res); printf("res: %d\n", res); /* 1 */ printVector(vector); /* 2 3 4 5 6 */ /* remove middle element */ vectorRemove(vector, 2, &res); printf("res: %d\n", res); /* 4 */ printVector(vector); /* 1 2 5 6 */ /* tries to remove from invalid index*/ errorCode = vectorRemove(vector, 7, &res); printf("Error Code: %d\n", errorCode); /* 4 = E_BAD_INDEX */ printVector(vector); vectorDestroy(&vector); } void vectorGetAndVectorSetElement_test() { ErrorCode errorCode; int res; Vector *vector = vectorCreate(9); int i = 1; for (; i < 8; ++i) { vectorPush(vector, i); } printVector(vector); /* 1 2 3 4 5 6 7 */ /* sets first element */ vectorSetElement(vector, 0, 11); /* gets first element */ vectorGetElement(vector, 0, &res); printf("res: %d\n", res); /* 11 */ printVector(vector); /* 11 2 3 4 5 6 */ /* sets last element */ vectorSetElement(vector, vectorGetSize(vector) - 1, 66); /* gets last element */ vectorGetElement(vector, vectorGetSize(vector) - 1, &res); printf("res: %d\n", res); /* 66 */ printVector(vector); /* 11 2 3 4 5 66 */ /* sets middle element */ vectorSetElement(vector, vectorGetSize(vector) / 2, 44); /* gets middle element */ vectorGetElement(vector, vectorGetSize(vector) / 2, &res); printf("res: %d\n", res); /* 44 */ printVector(vector); /* 11 2 3 44 5 66 */ /* sets element at invalid index */ errorCode = vectorSetElement(vector, vectorGetSize(vector) + 2, 44); printf("Error Code: %d\n", errorCode); /* 4 = E_BAD_INDEX */ /* gets element from invalid index */ errorCode = vectorGetElement(vector, vectorGetSize(vector) + 2, &res); printf("Error Code: %d\n", errorCode); /* 4 = E_BAD_INDEX */ printf("res: %d\n", res); /* 66 */ printVector(vector); /* 11 2 3 44 5 66 */ vectorDestroy(&vector); } void vectorCount_test() { Vector *vector = vectorCreate(20); int i = 1; for (; i < 8; ++i) { vectorPush(vector, i); } printVector(vector); /* 1 2 3 4 5 6 7 */ printf("%ld\n", vectorCount(vector, 22)); /* 0 */ printf("%ld\n", vectorCount(vector, 1)); /* 1 */ printf("%ld\n", vectorCount(vector, 7)); /* 1 */ printf("%ld\n", vectorCount(vector, 4)); /* 1 */ for (i = 1; i < 8; ++i) { vectorPush(vector, 1); } printf("%ld\n", vectorCount(vector, 1)); /* 8 */ vectorDestroy(&vector); } void vector_test_temp() { int res; Vector *vector = vectorCreate(3); vectorPush(vector, 6); vectorPush(vector, 1); vectorPush(vector, 2); vectorPush(vector, 3); vectorPush(vector, 4); printVector(vector); /* 6,1,2,3,4 */ vectorInsert(vector, 7, 2); printf("after insert value of index 2:\n"); printVector(vector); /* 6,1,7,2,3,4 */ vectorPop(vector, &res); printf("after pop\n"); /* 4 */ printf("poped value: %d\n", res); printVector(vector); /* 6,1,7,2,3 */ vectorRemove(vector, 2, &res); printf("after remove value of index 2:\n"); printf("removed value: %d\n", res); /* 7 */ printVector(vector); /* 6,1,2,3 */ vectorRemove(vector, 1, &res); printf("removed value: %d\n", res); /* 1 */ printf("after remove values of index 1 \n"); printVector(vector); /* 6,2,3 */ vectorRemove(vector, 2, &res); printf("after remove values of index 2 \n"); printf("removed value: %d\n", res); /* 3 */ printVector(vector); /* 6,2 */ vectorPush(vector, 66); vectorPush(vector, 11); vectorPush(vector, 22); vectorPush(vector, 33); /* multiplies capacity */ vectorPush(vector, 44); printf("after adds 5 values:\n"); printVector(vector); /* 6,2,66,11,22,33,44 */ vectorGetElement(vector, 2, &res); printf("element in index 2: %d\n", res); /* 66 */ printf("set element in index 2:\n "); vectorSetElement(vector, 2, 77); printVector(vector); /* 6,2,77,11,22,33,44 */ printf("times of 11 value in vector: %ld\n", vectorCount(vector, 11)); /* 1 */ vectorDestroy(&vector); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* er_wrk.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: hgalazza <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/08/03 12:41:12 by hgalazza #+# #+# */ /* Updated: 2020/08/03 16:30:16 by hgalazza ### ########.fr */ /* */ /* ************************************************************************** */ #include "init_stacks.h" #define INT_MAX 2147483647 #define INT_MIN -2147483648 int is_num(char *s) { int min; min = 0; if (*s == '-') s++; while (*s) { if (!ft_isdigit(*s)) return (0); s++; min++; } if (!min) exit(1); return (1); } char *get_valid(char *s) { char *new; ft_printf("Invalid input %s\n", s); ft_printf("Input valid or skip:\t"); while (get_next_line(0, &new)) { if (is_num(new)) return (new); if (ft_isinteger(new, 1)) return (new); if (ft_strequ(new, "skip")) { free(new); return (NULL); } ft_printf("%s - invalid\n", new); ft_printf("Input valid or skip:\t"); free(new); } return (NULL); } char *num_convert(char *s) { if (!ft_strcmp(s, "zero")) return ("0"); else if (!ft_strcmp(s, "one")) return ("1"); else if (!ft_strcmp(s, "two")) return ("2"); else if (!ft_strcmp(s, "three")) return ("3"); else if (!ft_strcmp(s, "four")) return ("4"); else if (!ft_strcmp(s, "five")) return ("5"); else if (!ft_strcmp(s, "six")) return ("6"); else if (!ft_strcmp(s, "seven")) return ("7"); else if (!ft_strcmp(s, "eight")) return ("8"); else if (!ft_strcmp(s, "nine")) return ("9"); else if (!ft_strcmp(s, "ten")) return ("10"); else return (get_valid(s)); } char *ft_isinteger(char *nbr, int eflag) { long num; if ((!nbr || ft_strlen(nbr) > 11) && !eflag) return (NULL); else if (ft_strlen(nbr) > 11 && eflag) nbr = get_valid(nbr); num = ft_atoi_long(nbr); if (num <= (long)INT_MAX && num >= (long)INT_MIN) return (nbr); else return (NULL); } char *input_check(char *str, int eflag) { char *ret; ret = str; if (!(is_num(str))) { if (!eflag) ft_error("Error"); if (!(ret = num_convert(str))) return (NULL); } if (!(ret = ft_isinteger(ret, eflag))) { if (!eflag) ft_error("Error"); ft_error("Some arguments are bigger than an integer"); } return (ret); }
C
/* Authors: Ranger Beguelin and Vaishnavi Kulkarni Date: 2/25/19 Description: write.c of Project 1 for Principles of Embedded Software */ //Header files #include <stdio.h> #include <stdint.h> #include <stdlib.h> #include "write.h" #include "allocate.h" #include "fsl_debug_console.h" int32_t *write_pointer; uint32_t offset; uint32_t value; int32_t addressing_mode; int32_t *addressing_value; int32_t directflag; int32_t indirectflag; int32_t int_mem; int32_t valid_location_flag; int32_t *hold_pointer; int32_t *end_value; /** * Name: write_memory * Description: This function allows the user to write an integer of their choosing to a location of their choosing within the allocated block of memory */ int32_t write_memory() { addressing_value = NULL; //the pointer used to point to the memory location the user wants to write to in direct addressing mode write_pointer = NULL; //create a pointer that will later point to the specific location in memory you want to write to hold_pointer = NULL; //pointer later used to copy mem_pointer for a brief operation valid_location_flag = 0; //flag for if the user enters in a valid memory location in Direct Addressing Mode directflag = 0; //flag that will be used to indicate the selection of direct addressing mode indirectflag = 0; //flag that will be used to indicate the selection of indirect addressing mode addressing_mode = 0; if (mem_pointer != NULL) { PRINTF("\n\rEnter 1 for Direct Addressing Mode or 2 for Indirect Addressing Mode\n\r"); PRINTF("Direct Addressing Mode: Exact memory address of the pattern starting location required\n\r"); PRINTF("Indirect Addressing Mode: Offset value for the pattern starting location required\n\r"); SCANF("%d", &addressing_mode); PRINTF("%d\n\r", addressing_mode); if(addressing_mode == 1) { PRINTF("\n\rPlease enter the memory address you would like to write to\n\r"); SCANF("%x", &addressing_value); PRINTF("%p\n\r", addressing_value); hold_pointer = mem_pointer; //we dont want to mess with mem_pointer just yet, so "hold_pointer" will be used as a stand-in for the same information for(int i = 0; i < alloc; i++) //for every element in the allocated block of memory { if ((addressing_value) == (hold_pointer)) //if the value the user entered matches anything found in the allocated block { valid_location_flag = 1; //raise the flag indicating that the user has entered in a valid location directflag = 1;//raise the flag indicating direct addressing mode } else //if the user-entered value and the current index of the allocated block do not match { hold_pointer++; //increment hold_pointer to check the next element in the allocated block } } if (valid_location_flag == 0) { PRINTF("\n\rThis address is not within the allocated block.\n\r"); PRINTF("Please enter a valid address next time\n\r"); } } if(addressing_mode == 2) { PRINTF("\n\rPlease enter an offset value\n\r"); PRINTF("Offset: where in the allocated block you wish to store this value\n\r"); //instructions for user PRINTF("(Acceptable values are from 0 to %d):\n\r", (alloc - 1)); SCANF("%d", &offset); //allow the user to type something in PRINTF("%d\n\r", offset); if((offset > (alloc - 1)) || (offset < 0)) //if the user tries to write to a location outside of the allocated block { PRINTF("Sorry, %d is not a valid entry\n\r", offset); //error message } else { indirectflag = 1; //raise the flag indicating indirect addressing mode } } if((addressing_mode != 1) && (addressing_mode != 2)) //if the user doesnt make a valid selection right off the bat { PRINTF("\n\rError: That is not a valid selection\n\r"); PRINTF("Please select either 1 or 2 next time\n\r"); } if((indirectflag == 1)||(valid_location_flag == 1)) //if the user enters in a valid memory location (a valid offset value or memory address) { PRINTF("\n\rPlease enter an integer to store at this location:\n\r"); SCANF("%d", &value); //allow the user to type something in PRINTF("%d\n\r", value); if ((value < 0) || (value >= 2147483648)) //if the user tries to enter in a negative value or a value greater than or equal to (2^31) { PRINTF("\n\rError: This is not a valid entry\r\n"); //error message PRINTF("Acceptable values are between 0 and ((2^31) - 1)\r\n"); //explanation PRINTF("\n\rPlease enter next command\n\r"); return 0; } if(addressing_mode == 2) //if youre using indirect addressing mode (in other words, using offset values) { write_pointer = mem_pointer + offset; //direct the pointer to the specific location in memory that you want to write to by adding the offset to the zeroeth element of the block of memory } else //if youre using direct addressing mode (using specific memory locations) { write_pointer = addressing_value; //set the pointer where you will write a value equal to the one the user entered } *write_pointer = value; //assign the value at this location equal to the value you wanted to write } } else { PRINTF("WARNING: Memory is not allocated yet, Please allocate memory\r\n"); //error message } PRINTF("\n\rPlease enter next command\n\r"); return 0; }
C
#include <stdio.h> double mult(double a, int n) { int i; double res=0; if (n>0) { for (i=0;i<n;i++) { res=res+a; } return res; } else if (n<0) for (i=0;i>n;i--) { res=res+a; } return -res; } /* int main() { int a,b; double c; scanf("%d %d",&a,&b); c=puissance(a,b); printf("%lf",c); return 0; }*/
C
#include "sched.h" #include "heap.h" #include "panic.h" #include "asm.h" #include "screen.h" #include <stand.h> #include <queue.h> /* 4K stack */ #define STACK_SIZE 0x1000 typedef struct { uint32 esp, ebp, ebx, esi, edi, eflags; IrqRegs regs; uint32* stack; uint32 id; } ThreadContext; typedef struct ThreadNode { bool kern; ThreadContext ctx; LIST_ENTRY(ThreadNode) __node__; } ThreadNode; typedef struct ThreadList { uint32 count; ThreadNode* cursor; LIST_HEAD(__list__, ThreadNode) __list__; } ThreadList; static ThreadList _threadList = { 0, NULL }; static int _maxID = 0; static void OnThreadExit(void); extern void SwitchContext(ThreadContext* old, ThreadContext* next); extern void SwitchUserContext(ThreadContext* old, ThreadContext* next); extern void LoadContext(ThreadContext* next); void InitThreading(void) { _threadList.count = 0; _threadList.cursor = NULL; LIST_INIT(&_threadList.__list__); /* Main thread id is 0 */ ThreadNode* node = heap_calloc(sizeof(ThreadNode)); if (node == NULL) panic("InitThreading() OOM"); node->kern = true; node->ctx.id = _maxID++; _threadList.count++; _threadList.cursor = node; LIST_INSERT_HEAD(&_threadList.__list__, node, __node__); } void ThreadCreate(ThreadRoutine fn, void* arg, bool isKernel) { __asm__ volatile ("cli"); void* mem = NULL; if (isKernel) mem = heap_calloc(sizeof(ThreadNode) + STACK_SIZE); else mem = (void*)0x1000; if (mem == NULL) panic("ThreadCreate() OOM"); /* Memory Layout * * low high * memory: | fn | OnThreadExit | arg | 0xdeadc0de | * ^ ^ * scheduler: esp esp+4 * ^ ^ * thread: esp esp+4 * * */ uint32* stack = mem + sizeof(ThreadNode) + STACK_SIZE; *--stack = 0xdeadc0de; *--stack = (uint32)arg; *--stack = (uint32)OnThreadExit; *--stack = (uint32)fn; ThreadNode* node = mem; node->kern = isKernel; node->ctx.esp = (uint32)stack; node->ctx.ebp = (uint32)stack; node->ctx.eflags = (1 << 9); // set IF flag node->ctx.stack = stack; node->ctx.id = _maxID++; LIST_INSERT_AFTER(_threadList.cursor, node, __node__); _threadList.count++; __asm__ volatile ("sti"); } uint32 ThreadID(void) { return _threadList.cursor->ctx.id; } void Schedule(IrqRegs* regs) { ThreadNode* old = _threadList.cursor; ThreadNode* tmp = old; ThreadNode* next = NULL; next = LIST_NEXT(tmp, __node__); if (next == NULL) next = LIST_FIRST(&_threadList.__list__); if (!next->kern) { next->kern = true; _threadList.cursor = next; SwitchUserContext(&old->ctx, &next->ctx); } else { _threadList.cursor = next; SwitchContext(&old->ctx, &next->ctx); } } static void OnThreadExit(void) { __asm__ volatile ("cli"); ThreadNode* old = _threadList.cursor; ThreadNode* next = LIST_NEXT(old, __node__); if (next == NULL) next = LIST_FIRST(&_threadList.__list__); LIST_REMOVE(old, __node__); heap_release(old); _threadList.count--; _threadList.cursor = next; LoadContext(&next->ctx); /*NOTREACHED*/ } uint32 GetThreadCount(void) { return _threadList.count; }
C
#include "holberton.h" /** * swap_int - esta funcion intercambia el valor a y b * @a: a pues es a * @b: y b pues es b * * Return: no retorna nada como 472 */ void swap_int(int *a, int *b) { int e; e = *a; *a = *b; *b = e; }
C
#include "jaccard_weighted_aux.h" #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <assert.h> void make_lut16_chunk(double *weights, double *chunk) { /* Args: weights: 16 values of weights chunk: 2**16 values zeroed out Bits are numbered (w.r.t. weights), we keep the byte order but flip the bits Order: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] Original:[7, 6, 5, 4, 3, 2, 1, 0, 15, 14, 13, 12, 11, 10, 9, 8] */ uint32_t i; uint16_t j; for (i = 0; i < 65536; ++i) { for (j = 0; j < 16; ++j) if ((i >> j) & 1) chunk[i] += weights[j / 8 * 8 + (7 - j % 8)]; } } void jaccard_weighted_cmap_lut16_even(uint16_t *xs, uint16_t *ys, double *out, const int size_by_2, const int num_xs, const int num_ys, const double *chunks, const int num_chunks) { int i, j, k, l; uint16_t *ys_orig = ys; double *chunk; for (i = 0; i < num_xs; ++i, xs += size_by_2) for (j = 0, ys = ys_orig; j < num_ys; ++j, ++out, ys += size_by_2) { for (k = 0, chunk = chunks; k < size_by_2; ++k, chunk += 65536) { *out += chunk[xs[k] & ys[k]]; } } } void jaccard_weighted_cmap_lut16(uint8_t *xs, uint8_t *ys, double *out, const int size, const int num_xs, const int num_ys, const double *chunks, const int num_chunks) { assert(size % 2 == 0); jaccard_weighted_cmap_lut16_even((uint16_t *)xs, (uint16_t *)ys, out, size / 2, num_xs, num_ys, chunks, num_chunks); }
C
#define NULL ((void*)0) typedef unsigned long size_t; // Customize by platform. typedef long intptr_t; typedef unsigned long uintptr_t; typedef long scalar_t__; // Either arithmetic or pointer type. /* By default, we understand bool (as a convenience). */ typedef int bool; #define false 0 #define true 1 /* Forward declarations */ /* Type definitions */ struct sk_buff {unsigned int len; scalar_t__ data; } ; /* Variables and functions */ unsigned int ALIGN_SIZE (struct sk_buff*,unsigned int) ; unsigned int L2PAD_SIZE (unsigned int) ; int /*<<< orphan*/ memmove (scalar_t__,scalar_t__,unsigned int) ; int /*<<< orphan*/ skb_push (struct sk_buff*,unsigned int) ; int /*<<< orphan*/ skb_trim (struct sk_buff*,unsigned int) ; void rt2x00queue_insert_l2pad(struct sk_buff *skb, unsigned int header_length) { unsigned int payload_length = skb->len - header_length; unsigned int header_align = ALIGN_SIZE(skb, 0); unsigned int payload_align = ALIGN_SIZE(skb, header_length); unsigned int l2pad = payload_length ? L2PAD_SIZE(header_length) : 0; /* * Adjust the header alignment if the payload needs to be moved more * than the header. */ if (payload_align > header_align) header_align += 4; /* There is nothing to do if no alignment is needed */ if (!header_align) return; /* Reserve the amount of space needed in front of the frame */ skb_push(skb, header_align); /* * Move the header. */ memmove(skb->data, skb->data + header_align, header_length); /* Move the payload, if present and if required */ if (payload_length && payload_align) memmove(skb->data + header_length + l2pad, skb->data + header_length + l2pad + payload_align, payload_length); /* Trim the skb to the correct size */ skb_trim(skb, header_length + l2pad + payload_length); }
C
#include <stdio.h> int main() { int i; float a, b, c; printf("Digite um numero inteiro entre 1 e 3: "); scanf("%d", &i); printf("Valor de A: "); scanf("%f", &a); printf("Valor de B: "); scanf("%f", &b); printf("Valor de C: "); scanf("%f", &c); if(i == 1){ printf("\nOrdem crescente: "); if((a < b) && (b < c)){ printf("%.f -> %.f -> %.f\n",a,b,c); } else if((a < c) && (c < b)){ printf("%.f -> %.f -> %.f\n", a,c,b); } else if((b < a) && (a < c)){ printf("%.f -> %.f -> %.f\n",b,c,a); } else if((b < c) && (c < a)){ printf("%.f -> %.f -> %.f\n",b,a,c); } else if((c < a) && (a < b)){ printf("%.f -> %.f -> %.f\n",c,b,a); } else if((c < b) && (b < a)){ printf("%.f -> %.f -> %.f\n",c,a,b); } } else if(i == 2){ printf("\nOrdem decrecente -> "); if((a < b) && (b < c)){ printf("%.f -> %.f -> %.f\n", c,b,a); } else if((a < c) && (c < b)){ printf("%.f -> %.f -> %.f\n", b,c,a); } else if((b < a) && (a < c)){ printf("%.f -> %.f -> %.f\n",a,c,b); } else if((b < c) && (c < a)){ printf("%.f -> %.f -> %.f\n",c,a,b); } else if((c < a) && (a < b)){ printf("%.f -> %.f -> %.f\n",a,b,c); } else if((c < b) && (b < a)){ printf("%.f -> %.f -> %.f\n",b,a,c); } } else if(i == 3){ printf("\nMaior no meio -> "); if((a < b) && (b < c)){ printf("%.f -> %.f -> %.f\n",a,c,b); } else if((a < c) && (c < b)){ printf("%.f -> %.f -> %.f\n", a,b,c); } else if((b < a) && (a < c)){ printf("%.f -> %.f -> %.f\n",b,c,a); } else if((b < c) && (c < a)){ printf("%.f -> %.f -> %.f\n",b,a,c); } else if((c < a) && (a < b)){ printf("%.f -> %.f -> %.f\n",c,b,a); } else if((c < b) && (b < a)){ printf("%.f -> %.f -> %.f\n",c,a,b); } } return 0; }
C
#include <stdio.h> int ar[100]; int start, end; void option() { printf("Enter 1 for push\n"); printf("Enter 2 for pop\n"); printf("Enter 3 for top\n"); printf("Enter 4 for elements\n"); printf("Enter 0 for exit\n"); } void push(int num) { end++; ar[end] = num; return; } void pop() { start++; } int main() { int i, j, k; start = end = -1; int op, num; option(); start++; while(1){ scanf("%d", &op); if(op == 1){ printf("Enter push value\n"); scanf("%d", &num); push( num ); } else if(op == 2){ printf("pop value\n"); pop(); } else if(op == 3){ if(start <= end){ printf("frount value\n"); printf("%d", ar[start]); } else{ printf("Stack is empty\n"); } } else if(op == 4){ if(end == -1 || end < start){ printf("Stack is empty\n"); } else{ printf("all elements\n"); for(i = start; i <= end; i++){ printf("%d ", ar[i]); } } } else if(op == 0){ break; } printf("\n\n"); option(); } return 0; }
C
/*****************************************************************************/ /* Copyright YouDao, Inc. */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */ /* See the License for the specific language governing permissions and */ /* limitations under the License. */ /*****************************************************************************/ /****************************************************************************** * File: ARMCompareAndSwap.h * Description: Atomic compare and swap functions on ARM processors *****************************************************************************/ #include <stdint.h> /****************************************************************************** * Function: atomicCAS_U32 * Description: Atomic "compare and swap" of 32-bit integer in main memory. * Parameters: comp: the value to compare * write: the value to write * dst: the memory location of 32-bit integer * Operation: # atomic operation * { * uint32_t ret = *dst; * if (*dst == comp) *dst = write; * return ret; * } * Return: The original value of the 32-bit integer in memory *****************************************************************************/ uint32_t atomicCAS_U32(uint32_t comp, uint32_t write, uint32_t *dst); /****************************************************************************** * Function: atomicCAS_U64 * Description: Atomic "compare and swap" of 64-bit integer in main memory. * Parameters: comp: the value to compare * write: the value to write * dst: the memory location of 64-bit integer * Operation: # atomic operation * { * uint64_t ret = *dst; * if (*dst == comp) *dst = write; * return ret; * } * Return: The original value of the 64-bit integer in memory *****************************************************************************/ uint64_t atomicCAS_U64(uint64_t comp, uint64_t write, uint64_t *dst);
C
#include "ngg_tool.h" #include "neuralnet/neuralnet.h" #include "util/util.h" #include <stdlib.h> #include <stdio.h> #include <string.h> #include <argp.h> static int parse_opt (int key, char* arg, struct argp_state* state) { options_t* opts = state->input; switch (key) { case 'a': // action if (strcmp (arg, "create") == 0) { opts->action = create; opts->set_a = true; } else if (strcmp (arg, "gen-data") == 0) { opts->action = gen_data; opts->set_a = true; } else if (strcmp (arg, "train") == 0) { opts->action = train; opts->set_a = true; } else if (strcmp (arg, "calc") == 0) { opts->action = calc; opts->set_a = true; } else { argp_error (state, "action not in {calc,create,gen-data,train}"); } break; case 'b': // binary opts->b_in = true; opts->b_out = true; break; case 200: // binary-in opts->b_in = true; break; case 201: // binary-out opts->b_out = true; break; case 'i': // input if (strlen (arg) > 0) { opts->in_path = arg; opts->set_i = true; } else { argp_error (state, "input filename is empty"); } break; case 'l': // neuralnet layout { size_t buf_size = 10; size_t num_read = 0; opts->number_neurons = SAFE_MALLOC (buf_size * sizeof (size_t)); char* p = strtok (arg, " "); while (p) { size_t tmp = strtoul (p, NULL, 10); if (!tmp) break; ++num_read; if (num_read > buf_size) { buf_size += 10; opts->number_neurons = SAFE_REALLOC ( opts->number_neurons, buf_size * sizeof (size_t)); } opts->number_neurons[num_read - 1] = tmp; p = strtok (0, " "); } opts->number_layer = num_read; if (num_read > 1) { opts->set_l = true; } else { argp_error (state, "requires at least two nonempty layers"); } } break; case 'n': // number opts->n = strtoul (arg, NULL, 10); opts->set_n = true; break; case 'o': // output if (strlen (arg) > 0) { opts->out_path = arg; opts->set_o = true; } else { argp_error (state, "output filename is empty"); } break; case 's': // board-size { size_t tmp = strtoul (arg, NULL, 10); if (tmp > 1) { opts->board_size = tmp; opts->set_s = true; } else { argp_error (state, "a minimum board size of 2x2 is required"); } } break; case 't': // training-data if (strlen (arg) > 0) { opts->training_data_path = arg; opts->set_t = true; } else { argp_error (state, "training data filename is empty"); } break; case 'v': // netver { unsigned long ver = strtoul (arg, NULL, 10); if (ver < 2) opts->ver = ver; break; } } return 0; } int main (int argc, char** argv) { options_t opts; init_opts (&opts); struct argp_option options[] = { {"action", 'a', "STRING", 0, "create: creates a new neural network " "gen-data: generates training data " "train: trains a neural network with supervised " "learning " "calc: calculates output of a neural network given input", 0}, {"in", 'i', "FILE", 0, "load neuralnet(s) from file", 0}, {"out", 'o', "FILE", 0, "output neuralnet(s) to file", 0}, {"binary", 'b', 0, 0, "use binary files", 0}, {"binary-in", 200, 0, 0, "use binary input file", 0}, {"binary-out", 201, 0, 0, "use binary output file", 0}, {"number", 'n', "NUM", 0, "number of networks to create or training iterations", 0}, {"board-size", 's', "NUM", 0, "size of the used go board", 0}, {"training-data", 't', "FILE", 0, "training data to use", 0}, {"layer", 'l', "NUMS", 0, "number of neurons in each layer\n" "e.g. \"2 3 3 2\"", 0}, {"netver", 'v', "0", 0, "nnet player version", 0}, {0, 0, 0, 0, 0, 0}}; struct argp argp = {options, &parse_opt, 0, 0, 0, 0, 0}; argp_parse (&argp, argc, argv, 0, 0, &opts); int ret = EXIT_SUCCESS; switch (opts.action) { case calc: ret = calculate (&opts); break; case create: ret = create_networks (&opts); break; case gen_data: ret = generate_training_data (&opts); break; case train: ret = train_networks (&opts); break; default: break; } cleanup_opts (&opts); return ret; }
C
#include "injector.h" #define MIN(a,b) (((a)<(b))?(a):(b)) #define MAX(a,b) (((a)>(b))?(a):(b)) void* GetGP() { unsigned int gp; asm( "move %0, $gp\n" : "=r"(gp) ); return gp; } uintptr_t adjustAddress(uintptr_t addr) { return addr; } void WriteMemoryRaw(uintptr_t addr, void* value, size_t size) { memcpy(adjustAddress(addr), value, size); } void ReadMemoryRaw(uintptr_t addr, void* ret, size_t size) { memcpy(ret, adjustAddress(addr), size); } void MemoryFill(uintptr_t addr, uint8_t value, size_t size) { unsigned char* p = adjustAddress(addr); while (size--) { *p++ = (unsigned char)value; } } void WriteInstr(uintptr_t addr, uint32_t value) { *(uint32_t*)(adjustAddress(addr)) = value; } void WriteMemory8(uintptr_t addr, uint8_t value) { *(uint8_t*)(adjustAddress(addr)) = value; } void WriteMemory16(uintptr_t addr, uint16_t value) { *(uint16_t*)(adjustAddress(addr)) = value; } void WriteMemory32(uintptr_t addr, uint32_t value) { *(uint32_t*)(adjustAddress(addr)) = value; } void WriteMemory64(uintptr_t addr, uint64_t value) { *(uint64_t*)(adjustAddress(addr)) = value; } void WriteMemoryFloat(uintptr_t addr, float value) { *(float*)(adjustAddress(addr)) = value; } void WriteMemoryDouble(uintptr_t addr, double value) { *(double*)(adjustAddress(addr)) = value; } uint8_t ReadMemory8(uintptr_t addr) { return *(uint8_t*)(adjustAddress(addr)); } uint16_t ReadMemory16(uintptr_t addr) { return *(uint16_t*)(adjustAddress(addr)); } uint32_t ReadMemory32(uintptr_t addr) { return *(uint32_t*)(adjustAddress(addr)); } uint64_t ReadMemory64(uintptr_t addr) { return *(uint64_t*)(adjustAddress(addr)); } float ReadMemoryFloat(uintptr_t addr) { return *(float*)(adjustAddress(addr)); } double ReadMemoryDouble(uintptr_t addr) { return *(double*)(adjustAddress(addr)); } void MakeJMP(uintptr_t at, uintptr_t dest) { WriteMemory32(adjustAddress(at), (0x08000000 | ((adjustAddress(dest) & 0x0FFFFFFC) >> 2))); } void MakeJMPwNOP(uintptr_t at, uintptr_t dest) { WriteMemory32(adjustAddress(at), (0x08000000 | ((adjustAddress(dest) & 0x0FFFFFFC) >> 2))); MakeNOP(adjustAddress(at + 4)); } void MakeJAL(uintptr_t at, uintptr_t dest) { WriteMemory32(adjustAddress(at), (0x0C000000 | ((adjustAddress(dest)) >> 2))); } void MakeCALL(uintptr_t at, uintptr_t dest) { WriteMemory32(adjustAddress(at), (0x0C000000 | (((adjustAddress(dest)) >> 2) & 0x03FFFFFF))); } void MakeNOP(uintptr_t at) { MemoryFill(adjustAddress(at), 0x00, 4); } void MakeNOPWithSize(uintptr_t at, size_t size) { MemoryFill(adjustAddress(at), 0x00, size); } void MakeRangedNOP(uintptr_t at, uintptr_t until) { return MakeNOPWithSize(adjustAddress(at), (size_t)(until - at)); } uintptr_t MakeInline(size_t instrCount, uintptr_t at, ...) { uintptr_t functor = MakeCallStub(instrCount * 4 + 8); size_t i; va_list ap; va_start(ap, instrCount); for (i = 0; i < instrCount; i++) { uint32_t arg = va_arg(ap, uint32_t); WriteInstr(functor + i * 4, arg); } va_end(ap); injector.MakeJMP(functor + i * 4, at + 8); // should be +8, cuz next instruction is executed before jump i++; injector.WriteMemory32(functor + i * 4, injector.ReadMemory32(at + 4)); //so we write it here injector.MakeNOP(at + 4); //and nop here, so it won't be executed twice injector.MakeJMP(at, functor); return functor; } uintptr_t MakeCallStub(uintptr_t numInstr) { return AllocMemBlock(numInstr * sizeof(uintptr_t)); } void MakeLUIORI(uintptr_t at, RegisterID reg, float imm) { uintptr_t functor = MakeCallStub(4); // lui ori j nop injector.WriteMemory32(functor + 0, lui(reg, HIWORD(imm))); injector.WriteMemory32(functor + 4, ori(reg, reg, LOWORD(imm))); injector.MakeJMP(functor + 8, at + 4); // should be +8 as well, but it won't work, e.g. two lui instructions in a row injector.MakeNOP(functor + 12); injector.MakeJMP(at, functor); } void MakeLI(uintptr_t at, RegisterID reg, int32_t imm) { uintptr_t functor = MakeCallStub(4); // lui ori j nop injector.WriteMemory32(functor + 0, lui(reg, HIWORD(imm))); injector.WriteMemory32(functor + 4, ori(reg, reg, LOWORD(imm))); injector.MakeJMP(functor + 8, at + 4); // should be +8 as well, but it won't work as well injector.MakeNOP(functor + 12); injector.MakeJMP(at, functor); } uint32_t parseCommand(uint32_t command, uint32_t from, uint32_t to) { uint32_t mask = ((1 << (to - from + 1)) - 1) << from; return (command & mask) >> from; } uint32_t isDelaySlotNearby(uintptr_t at) { static const uint32_t instr_len = 4; uint8_t J = parseCommand(j(0x123456), 26, 31); uint8_t JAL = parseCommand(jal(0x123456), 26, 31); uint8_t B = parseCommand(b(10), 26, 31); uint8_t BEQ = parseCommand(beq(v0, v1, 1), 26, 31); uint8_t BNE = parseCommand(bne(v0, v1, 1), 26, 31); uint8_t BC1F = parseCommand(bc1f(10), 26, 31); uint8_t BC1FL = parseCommand(bc1fl(10), 26, 31); uint8_t BC1TL = parseCommand(bc1tl(10), 26, 31); uint32_t prev_instr = parseCommand(ReadMemory32(at - instr_len), 26, 31); uint32_t next_instr = parseCommand(ReadMemory32(at + instr_len), 26, 31); if (prev_instr == J || prev_instr == JAL || prev_instr == B || prev_instr == BEQ || prev_instr == BNE || prev_instr == BC1F || prev_instr == BC1FL || prev_instr == BC1TL) return 1; else if (next_instr == J || next_instr == JAL || next_instr == B || next_instr == BEQ || next_instr == BNE || next_instr == BC1F || next_instr == BC1FL || next_instr == BC1TL) return 1; return 0; } void MakeInlineLUIORI(uintptr_t at, float imm) { static const uint32_t instr_len = 4; uint8_t LUI = parseCommand(lui(0, 0), 26, 31); uint8_t ORI = parseCommand(ori(0, 0, 0), 26, 31); uint32_t bytes = ReadMemory32(at); uint8_t instr = parseCommand(bytes, 26, 31); uint8_t reg_lui = parseCommand(bytes, 16, 20); if (instr == LUI) { for (uintptr_t i = at + instr_len; i <= (at + instr_len + (5 * instr_len)); i += instr_len) { bytes = ReadMemory32(i); instr = parseCommand(bytes, 26, 31); uint8_t reg_ori = parseCommand(bytes, 16, 20); if (instr == ORI && reg_lui == reg_ori) { if (isDelaySlotNearby(i)) { WriteMemory16(at, HIWORD(imm)); WriteMemory16(i, LOWORD(imm)); return; } else return MakeLUIORI(i, reg_ori, imm); } } if (isDelaySlotNearby(at)) WriteMemory16(at, HIWORD(imm)); else return MakeLUIORI(at, reg_lui, imm); } } void MakeInlineLI(uintptr_t at, int32_t imm) { static const uint32_t instr_len = 4; uint8_t ORI = parseCommand(ori(0, 0, 0), 26, 31); uint8_t ZERO = parseCommand(ori(0, 0, 0), 21, 25); uint32_t bytes = ReadMemory32(at); uint8_t instr = parseCommand(bytes, 26, 31); uint8_t reg_ori = parseCommand(bytes, 16, 20); uint8_t reg_zero = parseCommand(bytes, 21, 25); if (instr == ORI && reg_zero == ZERO) { if (isDelaySlotNearby(at)) return WriteMemory16(at, LOWORD(imm)); else return MakeLI(at, reg_ori, imm); } } struct injector_t injector = { .GetGP = GetGP, .WriteMemoryRaw = WriteMemoryRaw, .ReadMemoryRaw = ReadMemoryRaw, .MemoryFill = MemoryFill, .WriteInstr = WriteInstr, .WriteMemory8 = WriteMemory8, .WriteMemory16 = WriteMemory16, .WriteMemory32 = WriteMemory32, .WriteMemory64 = WriteMemory64, .WriteMemoryFloat = WriteMemoryFloat, .WriteMemoryDouble = WriteMemoryDouble, .ReadMemory8 = ReadMemory8, .ReadMemory16 = ReadMemory16, .ReadMemory32 = ReadMemory32, .ReadMemory64 = ReadMemory64, .ReadMemoryFloat = ReadMemoryFloat, .ReadMemoryDouble = ReadMemoryDouble, .MakeJMP = MakeJMP, .MakeJMPwNOP = MakeJMPwNOP, .MakeJAL = MakeJAL, .MakeCALL = MakeCALL, .MakeNOP = MakeNOP, .MakeNOPWithSize = MakeNOPWithSize, .MakeRangedNOP = MakeRangedNOP, .MakeInline = MakeInline, .MakeInlineLUIORI = MakeInlineLUIORI, .MakeInlineLI = MakeInlineLI };
C
#include <stdlib.h> #include <stdio.h> /** * @author Lars Erik Storbukås * @mail [email protected] * @date 25/03 - 2015 * @course INF237 Algorithm Engineering * @task Movie - Set 5 * **/ int main() { // start here int nr_of_movies; int nr_of_request; scanf("%d%d", &nr_of_movies, &nr_of_request); // create array twice the size of movies // calculate tree structure // evaluate input and number of movies // on top of 'choosen' movie return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* execute_args.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: kchetty <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2016/07/07 08:57:56 by kchetty #+# #+# */ /* Updated: 2016/07/09 14:28:57 by kchetty ### ########.fr */ /* */ /* ************************************************************************** */ #include "minishell.h" int launch(void) { pid_t pid; pid_t wpid; int status; pid = fork(); if (pid == 0) { write(1, "Error-> Invalid Input.\n", 24); exit(EXIT_FAILURE); } else if (pid < 0) write(1, "ERROR\n", 7); else { while (1) { wpid = waitpid(pid, &status, WUNTRACED); if (!(!WIFEXITED(status) && !WIFSIGNALED(status))) break ; } } return (1); } int execute_args(char **args, t_global *g) { if (args[0] == NULL) return (1); if (ft_strcmp(args[0], "exit") == 0) return (0); if (ft_strcmp(args[0], "ls") == 0) return (ft_ls(args)); if (ft_strcmp(args[0], "echo") == 0) return (ft_echo(args)); if (ft_strcmp(args[0], "clear") == 0) { write(1, "\033c", 7); return (1); } if (ft_strcmp(args[0], "env") == 0) return (ft_env(g->environ)); if (ft_strcmp(args[0], "pwd") == 0) return (ft_pwd()); if (ft_strcmp(args[0], "cd") == 0) return (ft_cd(args, g->environ)); return (launch()); }
C
#include <stdio.h> #include <string.h> struct MS { char name[11]; char num[11]; int grade; }; int main() { int n = 0; int i = 0; int min = 0, max = 0; int mindex = 0; int maxdex = 0; struct MS *stu; scanf("%d", &n); stu = (struct MS *)malloc(n * sizeof(struct MS)); for (i = 0; i < n; i++) { scanf("%s %s %d", stu[i].name, stu[i].num, &stu[i].grade); } min = stu[0].grade; max = stu[0].grade; for (i = 0; i < n; i++) { if (stu[i].grade < min) { min = stu[i].grade; mindex = i; } if (stu[i].grade > max) { max = stu[i].grade; maxdex = i; } } printf("%s %s\n", stu[maxdex].name, stu[maxdex].num); printf("%s %s\n", stu[mindex].name, stu[mindex].num); return 0; }
C
void INT00_1(){ void *fp; int x; /* ... */ if (fscanf(fp, "%ld", &x) < 1) { /* handle error */ } } void INT00_2(){ unsigned int a, b; unsigned long c; /* Initialize a and b */ a = 9999999999; b = 9999999999; c = (unsigned long)a * b; /* not guaranteed to fit */ //@violation INTEGER_UNDERFLOW //@violation CAST_ALTERS_VALUE }
C
#include <ncurses.h> #include <stdbool.h> #include <string.h> #include <unistd.h> #include "common/ctx.h" #include "ui/print_functions.h" #include "cli/cmd.h" #include "cli/operations.h" // approximate length of chiventure banner #define BANNER_WIDTH (96) #define BANNER_HEIGHT (12) /* see print_functions.h */ void print_homescreen(window_t *win, const char *banner) { // hides cursor curs_set(0); // calculate the position of the banner so that is is approximately centered. // The -1 in the y position is to give space for the message below the banner // x_pos and y_pos indicate the x-y coordinates of the top left corner of the banner int x_pos = COLS / 2 - BANNER_WIDTH / 2; int y_pos = LINES / 4 - BANNER_HEIGHT / 2 - 1; if (x_pos < 0) { x_pos = 0; } // runs the animation of the banner (flashes a few times, the last couple a // a bit slower). usleep is used to control for how long the banner is on/off for (int i = 0; i < 7; i ++) { int x = x_pos; int y = y_pos; wclear(win->w); box(win->w, 0, 0); wrefresh(win->w); if (i > 4) { usleep(600 * 1000); } else { usleep(100 * 1000); } int len = strlen(banner); char temp[len]; strcpy(temp, banner); char *str = strtok(temp, "\n"); while (str != NULL) { mvwprintw(win->w, y, x, str); str = strtok(NULL, "\n"); y++; } box(win->w, 0, 0); wrefresh(win->w); if (i > 3) { usleep(600 * 1000); } else { usleep(100 * 1000); } if (i == 6) { y_pos = y; } } usleep(1000 * 1000); char help[] = "Type 'HELP' to show help menu"; // similarly, as above, calculates where to place the message so it's centered int help_x_pos = COLS /2 - strlen(help) / 2; mvwprintw(win->w, y_pos + 2, help_x_pos, help); curs_set(1); } void print_banner(window_t *win, const char *banner) { // calculate the position of the banner so that is is approximately centered. // The -1 in the y position is to give space for the message below the banner // x_pos and y_pos indicate the x-y coordinates of the top left corner of the banner int x_pos = COLS / 2 - BANNER_WIDTH / 2; int y_pos = LINES / 4 - BANNER_HEIGHT / 2 - 1; if (x_pos < 0) { x_pos = 0; } int x = x_pos; int y = y_pos; int len = strlen(banner); char temp[len]; strcpy(temp, banner); char *str = strtok(temp, "\n"); while (str != NULL) { mvwprintw(win->w, y, x, str); str = strtok(NULL, "\n"); y++; } } /* see print_functions.h */ void print_info(chiventure_ctx_t *ctx, window_t *win) { mvwprintw(win->w, 1, 2, "Main Window"); } /* see print_functions.h */ void print_cli(chiventure_ctx_t *ctx, window_t *win) { static bool first_run = true; int x, y; getyx(win->w, y, x); if (first_run) { first_run = false; mvwprintw(win->w, y + 1, 2, "> "); return; } echo(); char input[80]; int quit = 1; char *cmd_string; wgetnstr(win->w, input, 80); noecho(); cmd_string = strdup(input); if (!strcmp(cmd_string, "")) { return; } cmd *c = cmd_from_string(cmd_string, ctx); if (!c) { print_to_cli(ctx, "Error: Malformed input (4 words max)"); } else { do_cmd(c, &quit, ctx); } /* Note: The following statement should be replaced by a logging function * in order to properly implement the HIST command. Should take about * half an hour, tops for someone who's experienced. */ if (cmd_string) { free(cmd_string); } getyx(win->w, y, x); // scrolls the screen up if there is no space to print the next line int height = LINES / 2; if (y >= height - 2) { wscrl(win->w, y - height + 2); y = height - 2; } mvwprintw(win->w, y, 2, "> "); } /* see print_functions.h */ void print_map(chiventure_ctx_t *ctx, window_t *win) { // prints the word map in the window mvwprintw(win->w, 1,2, "map"); return; } /* see print_functions.h */ void print_to_cli(chiventure_ctx_t *ctx, char *str) { int x, y, height; static bool first_run = true; height = LINES / 2; WINDOW *cli = ctx->ui_ctx->cli_win->w; int len = strlen(str); char temp[len]; strcpy(temp, str); char *tmp = strtok(temp, "\n"); getyx(cli, y, x); // scrolls the screen up if there is no space to print the first line of output if (y >= height - 1) { wscrl(cli, y - height + 2); y = height - 2; } while (tmp != NULL) { if(first_run) { mvwprintw(cli, y + 1, 3, tmp); first_run = false; } else { mvwprintw(cli, y, 3, tmp); } tmp = strtok(NULL, "\n"); getyx(cli, y, x); y++; // if there is no space to print the next line, instruction to press ENTER // to see more or q to continue is given, if (y >= height - 1 && tmp != NULL) { mvwprintw(cli, y, 3, "Press ENTER to see more, 'q' to continue"); int ch; while ((ch = wgetch(cli)) != '\n' && ch != 'q') { /* wait until enter is pressed or q are pressed */ } wmove(cli, y, 2); wclrtoeol(cli); if (ch == 'q') { return; } // sets the cursor to the begining of the line just printed // ("Press ENTER to see more, 'q' to continue"), and then clears it // scrolls the screen up wscrl(cli, y - height + 2); y = height - 2; } } getyx(cli, y, x); wmove(cli, y+1, 2); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* matrix_rotate.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: stenner <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/07/10 11:47:23 by stenner #+# #+# */ /* Updated: 2019/08/03 09:43:48 by rcoetzer ### ########.fr */ /* */ /* ************************************************************************** */ #include <libvec.h> t_matrix matrix_rotate(t_vector v) { t_matrix m; t_matrix temp; m = matrix_rotate_x(v.x); temp = matrix_rotate_y(v.y); m = matrix_matrix_multiply(m, temp); temp = matrix_rotate_z(v.z); m = matrix_matrix_multiply(m, temp); return (m); } t_matrix matrix_rotate_x(double theta) { t_matrix m; theta = theta * M_PI / 180; init_to_zero(&m); m.m[0][0] = 1; m.m[1][1] = cos(theta); m.m[1][2] = sin(theta); m.m[2][1] = -sin(theta); m.m[2][2] = cos(theta); m.m[3][3] = 1; return (m); } t_matrix matrix_rotate_y(double theta) { t_matrix m; theta = theta * M_PI / 180; init_to_zero(&m); m.m[0][0] = cos(theta); m.m[0][2] = sin(theta); m.m[2][0] = -sin(theta); m.m[1][1] = 1; m.m[2][2] = cos(theta); m.m[3][3] = 1; return (m); } t_matrix matrix_rotate_z(double theta) { t_matrix m; theta = theta * M_PI / 180; init_to_zero(&m); m.m[0][0] = cos(theta); m.m[0][1] = sin(theta); m.m[1][0] = -sin(theta); m.m[1][1] = cos(theta); m.m[2][2] = 1; m.m[3][3] = 1; return (m); }
C
#include <stdlib.h> #include <stdio.h> #include "include/mul.h" #include "include/operations.h" #include <string.h> //-------------------------------------------------------- _object mulIntInt(_object o1, _object o2) { return createInt(o1->cont.num * o2->cont.num); } _object mulIntStr(_object o1, _object o2) { return mulStrInt(o2, o1); } _object mulIntDec(_object o1, _object o2) { return createDecimal(o1->cont.num * o2->cont.fl); } //_object mulIntArr(_object o1, _object o2) { // //TODO // return 1; //} //-------------------------------------------------------- _object mulStrInt(_object o1, _object o2) { int num = o2->cont.num; char * aux = multiplyString(o1->cont.str, abs(num)); if (num < 0) { invertStr(aux); } return createString(aux); } _object mulStrStr(_object o1, _object o2) { int len1 = strlen(o1->cont.str); int len2 = strlen(o2->cont.str); char* aux = calloc(1, len1*(len2 + 1) + 1); int i; for (i = 0; i < len1; i++) { aux[i*(len2+1)] = o1->cont.str[i]; strcat(aux,o2->cont.str); } return createString(aux); } _object mulStrDec(_object o1, _object o2) { float num = o2->cont.fl; float abs = (num > 0 ? num : num*(-1)); char * aux = multiplyString(o1->cont.str, abs); if (num < 0) { invertStr(aux); } return createString(aux); } //_object mulStrArr(_object o1, _object o2) { // //TODO // return 1; //} //-------------------------------------------------------- _object mulDecInt(_object o1, _object o2) { return createDecimal(o1->cont.fl * o2->cont.num); } _object mulDecStr(_object o1, _object o2) { float num = o1->cont.fl; float abs = (num > 0 ? num : num*(-1)); char * aux = multiplyString(o2->cont.str, abs); if (num < 0) { invertStr(aux); } return createString(aux); } _object mulDecDec(_object o1, _object o2) { return createDecimal(o1->cont.fl * o2->cont.fl); } //_object mulDecArr(_object o1, _object o2) { // //TODO // return 1; //} //-------------------------------------------------------- //_object mulArrInt(_object o1, _object o2) { // //TODO // return 1; //} // //_object mulArrStr(_object o1, _object o2) { // //TODO // return 1; //} // //_object mulArrDec(_object o1, _object o2) { // //TODO // return 1; //} // //_object mulArrArr(_object o1, _object o2) { // //TODO // return 1; //}
C
#include <stdio.h> #include <pthread.h> #include <stdlib.h> #include "pithread.h" int main () { pthread_t tid[10]; // ID thread scanf("%d", &inter); // For all threads for (int i = 0; i< NUMTHR ; i++){ // create thread pthread_create (&tid[i], NULL, docalc, &i); } // For each thread for (int i = 0; i< NUMTHR ; i++){ // wait for threads to finish pthread_join (tid[i], NULL); } printf("Valor de pi:%lf\n",pi()); return 0; }
C
#include "abstract_syntax_tree.h" #include <unistd.h> table_element * function_tracker; //function to create a new node of type "type" and value "value" struct node * create_node (char* type, char* value, int line, int column, int to_print) { struct node *new = (struct node *)malloc(sizeof(struct node)); new->value = value; new->type = type; new->number_children = 0; new->parent = NULL; new->bro = NULL; new->line = line; new->column = column; new->to_print = to_print; new->annotation = ""; //printf("created new node %s(%s)\n\n", type, value); return new; } //function to add a new child to the node parent, with type "type" and value "value" struct node * add_child (struct node *parent, struct node * child) { struct node * aux; if (child == NULL || parent == NULL) return NULL; parent->children[parent->number_children] = child; parent->number_children++; child->parent = parent; aux = child->bro; while (aux != NULL) { //iterates over child's siblings to add parent as a parent to them too aux->parent = parent; parent->children[parent->number_children] = aux; parent->number_children++; //printf("added child %s(%s) to parent %s(%s)\n\n", aux->type, aux->value, parent->type, parent->value); aux = aux->bro; } //printf("added child %s(%s) of parent %s(%s)\n\n", child->type, child->value, parent->type, parent->value); return parent; } struct node * add_sibling(struct node * s1, struct node * s2) { struct node * aux = s1; if (aux != NULL) { while (aux->bro != NULL) { aux = aux->bro; } aux->bro = s2; } //if(s1!=NULL && s2!=NULL) printf("added %s(%s) and %s(%s) as siblings\n", s1->type, s1->value,s2->type, s2->value); return s1; } //function to get the number of siblings of a given node int get_number_siblings(struct node* node) { if (node->parent != NULL) { return node->parent->number_children; } return 0; } //function to print the tree in order void print_node(struct node * root, int depth) { int i; if (root == NULL) return; //printf("node=%s children=%d\n", root->type, root->number_children); //puts the appropriate number of points for (i=0; i<depth; i++) { printf(".."); } if (!root->to_print) { printf("%s\n", root->type); } else { printf("%s(%s)\n", root->type, root->value); } for (int j=0; j<root->number_children; j++) { print_node(root->children[j], depth+1); } free(root); } void print_annotated_node(struct node * root, int depth) { int i; if (root == NULL) return; for (i=0; i<depth; i++) { printf(".."); } if (!root->to_print) { printf("%s", root->type); } else { printf("%s(%s)", root->type, root->value); } if (strcmp(root->annotation, "") != 0 && strcmp(root->parent->type, "ParamDecl") != 0 && strcmp(root->parent->type, "FuncHeader") != 0 && strcmp(root->parent->type, "VarDecl") != 0) printf(" - %s\n", root->annotation); else printf("\n"); for (int j=0; j<root->number_children; j++) { print_annotated_node(root->children[j], depth+1); } free(root); } void annotate_node(struct node ** node, char * annotation) { (*node)->annotation = (char*)malloc(strlen(annotation)*sizeof(char)); //strcpy((*node)->annotation, annotation); (*node)->annotation = strdup(annotation); //(*node)->annotation[strlen(annotation)] = '\0'; } void annotate_tree(struct node ** node, struct table_element * symtab) { if (strcmp((*node)->type, "IntLit") == 0) { annotate_node(node, "int"); } else if (strcmp((*node)->type, "RealLit") == 0) { annotate_node(node, "float32"); } else if (strcmp((*node)->type, "Id") == 0) { //search for the symbol in the symbol table struct table_element * symbol = search_element((*node)->value, symtab); if (symbol == NULL && symtab != global_symtab) { symbol = search_element((*node)->value, global_symtab); } if (symbol == NULL) { printf("Line %d, column %d: Cannot find symbol %s\n", (*node)->line, (*node)->column, (*node)->value); annotate_node(node, "undef"); } else { //annotate the node with the type of the symbol in the symbol table if (symbol->decl_type == var) { annotate_node(node, symbol->decl.var.type); } else { //the ID matches to a function /* if this ID matches a function, we want to start looking up things in the symbol table of that function, unless we're dealing with a funcinvocation */ if ((*node)->parent != NULL && strcmp((*node)->parent->type, "Call") != 0) function_tracker = symbol; annotate_node(node, symbol->decl.func.return_type); } } } else if (strcmp((*node)->type, "Call") == 0) { /* first, we have to annotate the nodes of the vars given as arguments, so that later on we can check if they match with the expected types */ for (int i=1; i<(*node)->number_children; i++) { annotate_tree(&((*node)->children[i]), symtab); } // node = Call // annotating the ID of the function Call with the types of the parameters struct node * functionID = (*node)->children[0]; /* searching for the function ID in table_element of the function where the call is */ table_element * functionID_symbol = search_element(functionID->value, symtab); //getting the types of the arguments in the function invocation char * arguments = (char*)malloc(500*sizeof(char)); strcat(arguments, "("); char * type; for (int i=1; i<(*node)->number_children; i++) { //the first child is the function ID type = (*node)->children[i]->annotation; strcat(arguments, type); strcat(arguments, ","); } if ((*node)->number_children > 1) arguments[strlen(arguments)-1] = '\0'; strcat(arguments, ")"); /* if the function symbol is null, now lets search it in the */ if (functionID_symbol == NULL) functionID_symbol = search_element(functionID->value, global_symtab); if (functionID_symbol == NULL) { printf("Line %d, column %d: Cannot find symbol %s%s\n", functionID->line, functionID->column, functionID->value, arguments); annotate_node(node, "undef"); annotate_node(&functionID, "undef"); } else { char * expected = (char*)malloc(500*sizeof(char)); strcat(expected, "("); table_element * aux = functionID_symbol->decl.func.function_vars; // what parameter types were expected? for (int i=0; i<functionID_symbol->decl.func.number_params; i++) { type = aux->decl.var.type; strcat(expected, type); strcat(expected, ","); aux = aux->next; } if (functionID_symbol->decl.func.number_params > 0) expected[strlen(expected)-1] = '\0'; strcat(expected, ")"); if (strcmp(expected, arguments) != 0) { // this means that the types used don't match to the ones expected, or the number of arguments is not correct printf("Line %d, column %d: Cannot find symbol %s%s\n", (*node)->line, (*node)->column, (*node)->children[0]->value, arguments); annotate_node(node, "undef"); } else { if (strcmp(functionID_symbol->decl.func.return_type, "none") != 0) annotate_node(node, functionID_symbol->decl.func.return_type); } annotate_node(&functionID, expected); } } else if(strcmp((*node)->type, "Assign") == 0) { annotate_tree(&(*node)->children[0], symtab); annotate_tree(&(*node)->children[1], symtab); if (strcmp((*node)->children[0]->annotation, (*node)->children[1]->annotation) != 0) { /* cannot be assigned */ printf("Line %d, column %d: Operator %s cannot be applied to types %s, %s\n", (*node)->line, (*node)->column, (*node)->value, (*node)->children[0]->annotation, (*node)->children[1]->annotation); annotate_node(node, "undef"); } else { annotate_node(node, (*node)->children[0]->annotation); } } else if(strcmp((*node)->type, "ParseArgs") == 0) { annotate_tree(&(*node)->children[0], symtab); annotate_tree(&(*node)->children[1], symtab); annotate_node(node, (*node)->children[0]->annotation); } else if (strcmp((*node)->type, "Not") == 0) { annotate_tree(&(*node)->children[0], symtab); annotate_node(node, (*node)->children[0]->annotation); } else if (strcmp((*node)->type, "Minus") == 0) { annotate_tree(&(*node)->children[0], symtab); annotate_node(node, (*node)->children[0]->annotation); } else if (strcmp((*node)->type, "Plus") == 0) { annotate_tree(&(*node)->children[0], symtab); annotate_node(node, (*node)->children[0]->annotation); } else if(strcmp((*node)->type, "Or") == 0) { annotate_tree(&(*node)->children[0], symtab); annotate_tree(&(*node)->children[1], symtab); annotate_node(node, "bool"); } else if(strcmp((*node)->type, "And") == 0) { annotate_tree(&(*node)->children[0], symtab); annotate_tree(&(*node)->children[1], symtab); annotate_node(node, "bool"); } else if(strcmp((*node)->type, "Lt") == 0) { annotate_tree(&(*node)->children[0], symtab); annotate_tree(&(*node)->children[1], symtab); annotate_node(node, "bool"); } else if(strcmp((*node)->type, "Gt") == 0) { annotate_tree(&(*node)->children[0], symtab); annotate_tree(&(*node)->children[1], symtab); annotate_node(node, "bool"); } else if(strcmp((*node)->type, "Eq") == 0) { annotate_tree(&(*node)->children[0], symtab); annotate_tree(&(*node)->children[1], symtab); annotate_node(node, "bool"); } else if(strcmp((*node)->type, "Ne") == 0) { annotate_tree(&(*node)->children[0], symtab); annotate_tree(&(*node)->children[1], symtab); annotate_node(node, "bool"); } else if(strcmp((*node)->type, "Le") == 0) { annotate_tree(&(*node)->children[0], symtab); annotate_tree(&(*node)->children[1], symtab); annotate_node(node, "bool"); } else if(strcmp((*node)->type, "Ge") == 0) { annotate_tree(&(*node)->children[0], symtab); annotate_tree(&(*node)->children[1], symtab); annotate_node(node, "bool"); } else if(strcmp((*node)->type, "Add") == 0) { annotate_tree(&(*node)->children[0], symtab); annotate_tree(&(*node)->children[1], symtab); if (strcmp((*node)->children[0]->annotation, (*node)->children[1]->annotation) != 0) { /* ERROR */ printf("Line %d, column %d: Operator %s cannot be applied to types %s, %s\n", (*node)->line, (*node)->column, (*node)->value, (*node)->children[0]->annotation, (*node)->children[1]->annotation); annotate_node(node, "undef"); } else { //same type annotate_node(node, (*node)->children[0]->annotation); } } else if(strcmp((*node)->type, "Sub") == 0) { annotate_tree(&(*node)->children[0], symtab); annotate_tree(&(*node)->children[1], symtab); if (strcmp((*node)->children[0]->annotation, (*node)->children[1]->annotation) != 0) { /* ERROR */ printf("Line %d, column %d: Operator %s cannot be applied to types %s, %s\n", (*node)->line, (*node)->column, (*node)->type, (*node)->children[0]->annotation, (*node)->children[1]->annotation); annotate_node(node, "undef"); } else { //same type annotate_node(node, (*node)->children[0]->annotation); } } else if(strcmp((*node)->type, "Mul") == 0) { annotate_tree(&(*node)->children[0], symtab); annotate_tree(&(*node)->children[1], symtab); if (strcmp((*node)->children[0]->annotation, (*node)->children[1]->annotation) != 0) { /* ERROR */ printf("Line %d, column %d: Operator %s cannot be applied to types %s, %s\n", (*node)->line, (*node)->column, (*node)->type, (*node)->children[0]->annotation, (*node)->children[1]->annotation); annotate_node(node, "undef"); } else { //same type annotate_node(node, (*node)->children[0]->annotation); } } else if(strcmp((*node)->type, "Div") == 0) { annotate_tree(&(*node)->children[0], symtab); annotate_tree(&(*node)->children[1], symtab); if (strcmp((*node)->children[0]->annotation, (*node)->children[1]->annotation) != 0) { /* ERROR */ printf("Line %d, column %d: Operator %s cannot be applied to types %s, %s\n", (*node)->line, (*node)->column, (*node)->type, (*node)->children[0]->annotation, (*node)->children[1]->annotation); annotate_node(node, "undef"); } else { //same type annotate_node(node, (*node)->children[0]->annotation); } } else if(strcmp((*node)->type, "Mod") == 0) { annotate_tree(&(*node)->children[0], symtab); annotate_tree(&(*node)->children[1], symtab); if (strcmp((*node)->children[0]->annotation, (*node)->children[1]->annotation) != 0) { /* ERROR */ printf("Line %d, column %d: Operator %s cannot be applied to types %s, %s\n", (*node)->line, (*node)->column, (*node)->type, (*node)->children[0]->annotation, (*node)->children[1]->annotation); annotate_node(node, "undef"); } else { //same type annotate_node(node, (*node)->children[0]->annotation); } } /* FuncDecls need to be treated specially */ else if (strcmp((*node)->type, "FuncDecl") == 0) { function_tracker = global_symtab; annotate_tree(&(*node)->children[0], function_tracker); //at this point, function_tracker has the symbol of the function annotate_tree(&(*node)->children[1], function_tracker->decl.func.function_vars); } else if (strcmp((*node)->type, "FuncHeader") == 0) { annotate_tree(&(*node)->children[0], function_tracker); /* after executing this, function_tracker will change to be the symbol of the function in the table */ for (int i=1; i<(*node)->number_children; i++) { annotate_tree(&(*node)->children[i], function_tracker->decl.func.function_vars); } } else if (strcmp((*node)->type, "Program") == 0) { function_tracker = global_symtab; for (int i=0; i<(*node)->number_children; i++) { annotate_tree(&(*node)->children[i], function_tracker); } } else { for (int i=0; i<(*node)->number_children; i++) { annotate_tree(&(*node)->children[i], symtab); } } } struct node *root = NULL;
C
#include<stdio.h> int main() { int i,j,n; printf("Enter a number= "); scanf("%d",&n); for(i=2;i<=n;i++) { if(n%i==0) { break; } } if(i==n) { printf("\t %d is a Prime Number.",n); } else { printf("\t %d is a Not a Prime Number.",n); } return 0; }
C
#include <stdio.h> int main() { char *s; char s1[4]; int i; int x; int z; i = 0; s = "0123456789abcdef"; x = 852; z = x; while (z) { z = z / 16; i++; } z = i; s1[z] = '\0'; while (z) { z--; s1[z] = s[(x % 16)]; printf("%c ", s1[z]); x = x / 16; //printf("%d\n", x); } printf("\nHexadecimal: %s\n", s1); return (0); }