language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
#define _CRT_SECURE_NO_WARNINGS #pragma warning (disable:4996) #include <stdio.h> #include <stdlib.h> #define ROWT 4416 #define COLT 1 #define sep ";" #define MAX 100000; double flipmask = (double)0; void ue(double array[][COLT], int row, int col, const char *colstr) { double throw; int bit; long long flipmask = 0; long long data; array[row][col] = atof(colstr); //char buf[MAX]; //printf("%s%lf%s", col?"":"\n", array[row][col], sep); printf("%lf%s\n", array[row][col], sep); // original data throw = drand48(); bit = rand() % 64; // bit to flip bit = 62; // 63-0, 63 = sign bit printf("bit to flip = %d\n", bit); flipmask = flipmask | ((long long)1 << bit); data = *(long long *)&array[row][col]; data = data ^ flipmask; array[row][col] = *(double *)&data; printf("%lf%s\n", array[row][col], sep); } int main() { FILE *f = fopen("sedov_dens0001.csv", "r"); if (f) { double array[ROWT][COLT] = { 0 }; int n, row, col; char rowstr[100], colstr[100], *p; for (row = 0; row < ROWT && fgets(rowstr, 100, f); ++row) for (col = 0, n=*colstr=0, p=rowstr; col < COLT && sscanf(p, "%12[^"sep"]%n",colstr, &n)!=EOF; ++col,p+=n, *p?++p:0) ue(array, row, col, colstr); fclose(f); puts("\n"); } else return 1; return 0; }
C
#include "../includes/cub3d.h" void screen_resolution(t_game *game) { int max_w; int max_h; mlx_get_screen_size(game->data.mlx, &max_w, &max_h); if (game->file.width > max_w) game->file.width = max_w; if (game->file.height > max_h) game->file.height = max_h; } void get_resolution(t_game *game, char *line) { char **split; char *tmp; split = ft_split(line, ' '); if (ft_strlen_ptr(split) != 3 || !check_digit(split[1], "0123456789") || !check_digit(split[2], "0123456789")) { free(line); table_free(split); return_error(-20); } tmp = split[1]; split[1] = ft_substr(split[1], 0, 6); game->file.width = ft_atoi(split[1]); free(tmp); tmp = split[2]; split[2] = ft_substr(split[2], 0, 6); game->file.height = ft_atoi(split[2]); free(tmp); screen_resolution(game); if (game->file.width <= 0 || game->file.height <= 0) { table_free(split); return_error(-20); } table_free(split); } void get_texture(char *line, char **texture) { char *split; int tex_count; split = ft_strtrim(line, " "); *texture = ft_strdup(split); tex_count = (int)ft_strlen(*texture); //if (open(*texture, O_RDONLY) == -1 || split[tex_count - 1] != 'm' // || split[tex_count - 2] != 'p' || split[tex_count - 3] != 'x') //{ // free(split); // printf("ERROR: TEXTURE ERROR"); //} if (open(*texture, O_RDONLY) == -1) { free(split); free(*texture); return_error(-21); } if (split[tex_count - 1] != 'm' || split[tex_count - 2] != 'p' || split[tex_count - 3] != 'x') { free(split); return_error(-23); } free(split); } int check_param(char *line) { if ((ft_strstr(line, "R ") || ft_strstr(line, "R\t")) // talvez trocar por && && (ft_strstr(line, "SO ") || ft_strstr(line, "SO\t")) && (ft_strstr(line, "NO ") || ft_strstr(line, "NO\t")) && (ft_strstr(line, "WE ") || ft_strstr(line, "WE\t")) && (ft_strstr(line, "EA ") || ft_strstr(line, "EA\t")) && (ft_strstr(line, "F ") || ft_strstr(line, "F\t")) && (ft_strstr(line, "C ") || ft_strstr(line, "C\t")) && (ft_strstr(line, "S ") || ft_strstr(line, "S\t")) && (line[0] == '\0')) return (1); //else// acrescentamos 07-may //return_error(-18); return (0); } void get_param(t_game *game, char *line) { if (line[0] == ' ') { free(line); return_error(-18); } if (line[0] == 'R') get_resolution(game, line); else if (line[0] == 'N' && line[1] == 'O') get_texture(line + 2, &game->file.no_path); else if (line[0] == 'S' && line[1] == 'O') get_texture(line + 2, &game->file.so_path); else if (line[0] == 'W' && line[1] == 'E') get_texture(line + 2, &game->file.we_path); else if (line[0] == 'E' && line[1] == 'A') get_texture(line + 2, &game->file.ea_path); else if (line[0] == 'S' && line[1] == ' ') get_texture(line + 1, &game->file.s_path); else if (line[0] == 'F' && game->floor_bool == 0) { game->floor_bool = 1; game->file.color_floor = (int)get_color(line + 1); } else if (line[0] == 'C' && game->celling_bool == 0) { game->celling_bool = 1; game->file.color_ceiling = (int)get_color(line + 1); } }
C
#include <stdio.h> int main(int argc, char const *argv[]) { char a = 'a'; char b = 'b'; printf("%d\n",a-b); return 0; }
C
#include "binary_trees.h" /** * binary_tree_uncle - goes through tree * @node: a node * Return: 1 if a node is a leaf, 0 if not */ binary_tree_t *binary_tree_uncle(binary_tree_t *node) { binary_tree_t *parent, *gparent; if (node == NULL) return (NULL); if (node->parent == NULL) return (NULL); if (node->parent->parent == NULL) return (NULL); parent = node->parent; gparent = node->parent->parent; if (parent == gparent->left) return (gparent->right); return (gparent->left); }
C
#include <stdio.h> #include <signal.h> #include <stdlib.h> #include <fcntl.h> /* Gestion de señales en proceso padre. */ void gestion_padre(int segnal) { printf("Padre recibe señal.. %d\n", segnal); } void gestion_hijo (int segnal) { printf("Hijo recibe señal..%d\n", segnal); } int main() { int pid_padre, pid_hijo; pid_padre = getpid(); pid_hijo = fork(); //se crea el hijo switch(pid_hijo) { case -1: printf("Error al crear el proceso hijo...\n"); exit(-1); case 0: //tratamiento de señal en proceso hijo signal (SIGUSR1, gestion hijo); while(1){ sleep(1); kill(pid_padre, SIGUSR1) //ENVIA SEÑAL AL PADRE pause();//hijo espera hasta que llegue una señal de respuesta }//while break; default: //PADRE }//switch }//main
C
#include <avr/io.h> #include "MCP.h" #include "SPI.h" #include "util\delay.h" /** * Function bit modifies a content of register * Function bit modifies a content of register with given data using given mask * * @param Data new data to be written * @param Mask Mask used for modification * @param Address Address of register to modify */ void MCPmodify(uint8_t Data, uint8_t Mask, uint8_t Address){ SelectSlave(); //selectMCP SPIsend(MCP_BITMOD); //send bit modify command SPIsend(Address); //send register address SPIsend(Mask); //send mask SPIsend(Data); //send data DeselectSlave(); //deselect MCP } /** *Function returns information about tx and rx flags * * @return composed information about tx and rx flags * * @todo might be a good idea to add checking the repeated output */ uint8_t MCPstatus(void){ uint8_t Byte; SelectSlave(); //selectMCP SPIsend(MCP_READ_STATUS); //send read statud command Byte = SPIreceive(); //send data DeselectSlave(); //deselect MCP return Byte; } /** * Send request for content of TX buffers * @param Transmit_buffer Choose buffer 0,1,2 or all */ void MCPrequest(uint8_t Transmit_buffer){ SelectSlave(); //selectMCP SPIsend(Transmit_buffer); //define which buffers are enabled to transmit DeselectSlave(); //deselect MCP } /** * Function loading the TX buffer * * @param Data Pointer to data being loaded to TX buffer * @param Buffer Address of buffer to be loaded * @param length number of bytes to be loaded * @param OnlyData flag specifying if only data or the whole buffer is being loaded */ void MCPloadTX(uint8_t *Data, uint8_t Buffer,uint8_t length, uint8_t OnlyData){ SelectSlave(); //selectMCP SPIsend( Buffer | ( OnlyData) ); //send write address while(length) { SPIsend(*Data); //send data Data++; length--; } DeselectSlave(); //deselect MCP } /** *Basic function writing to MCP2515 * *@param Data Data to be written *@param Address Address where the data should be written */ void MCPwrite(uint8_t Data, uint8_t Address){ SelectSlave(); //selectMCP SPIsend(MCP_WRITE); //send write command SPIsend(Address); //send write address SPIsend(Data); //send data DeselectSlave(); //deselect MCP } /** * Function reading from MCP2515 RX buffer * * Function reads given RX buffer. SPI overhead is minimzed by not using specifying address in seperate byte.\ * After read operation RX buffer flag is cleared * * * @param Data pointer to place where buffer content will be stored * @param Buffer address of buffer being read * @param start_point flag if the whole buffer is read or only data_bytes */ void MCPreadRX(uint8_t *Data, uint8_t Buffer,uint8_t start_point){ uint8_t Byte; int i; int length; SelectSlave(); //selectMCP SPIsend(Buffer | ( start_point <<1)); if (start_point) length = 8; else length = 13; for(i=0;i<length;i++) { *Data=SPIreceive(); Data++; } DeselectSlave(); //deselect MCP } /** * Basic function reading from MCP2515 * * @param Address Address of register being read * * @return content of the read register */ uint8_t MCPread(uint8_t Address){ uint8_t Byte; SelectSlave(); //selectMCP SPIsend(MCP_READ); //send reading command SPIsend(Address); //send address Byte = SPIreceive();//read byte DeselectSlave(); //deselect MCP return Byte; } /** * Function resetting content of all MCP2515 registers */ void MCPreset(void){ SelectSlave(); //select MCP SPIsend(MCP_RESET); //send RESET vector _delay_ms(1); DeselectSlave(); //deselect MCP }
C
#include <CUnit/Basic.h> #include <CUnit/CUnit.h> #include "student_code.h" #include <setjmp.h> #include <signal.h> #define VALUE_A 500 // If we want to test some values #define VALUE_B 600 //Ces 2 variables sont à déclarer globalement car utilisées dans mymalloc.c int nb_times_malloc_used = 0; int let_malloc_fail = 0; int nb_times_free_used = 0; int nb_times_thread_create=0; int a = 25; int b = 25; int c = 0; int d = -5; void test_sameNumber(){ CU_ASSERT_EQUAL(gcd(a,b),a); } void test_zero(){ CU_ASSERT_EQUAL(gcd(c,b),0); } void test_negative(){ CU_ASSERT_EQUAL(gcd(c,d),0); } void test_malloc_equal_free(void) { nb_times_malloc_used = 0; //On remet la variable à 0 car CUnit a lui-même utilisé malloc nb_times_free_used = 0; gcd(3, 3); nb_times_free_used = nb_times_free_used-32; // 32 is the number of free call needed by the system // nb_times_malloc_used sera incrémenté par le malloc modifié de mymalloc.c CU_ASSERT_EQUAL(nb_times_malloc_used, nb_times_free_used); // Must be equal to 4. } void test_howmany_thread(void) { nb_times_thread_create = 0; //On remet la variable à 0 car CUnit a lui-même utilisé malloc gcd(3, 3); // nb_times_malloc_used sera incrémenté par le malloc modifié de mymalloc.c CU_ASSERT_EQUAL(nb_times_thread_create, 2); // Must be equal to 2 threads. } void test_times_malloc_used(void) { nb_times_malloc_used = 0; //On remet la variable à 0 car CUnit a lui-même utilisé malloc gcd(3, 3); // nb_times_malloc_used sera incrémenté par le malloc modifié de mymalloc.c CU_ASSERT_EQUAL(nb_times_malloc_used, 4); // Must be equal to 4. } jmp_buf label_test_malloc_fail; void sig_handler(int signo) { //Le signal handler a été exécuté, on a donc reçu un SIGSEGV //On provoque alors un jump vers le label avec le paramètre 1 longjmp(label_test_malloc_fail,1); } void test_malloc_fail(void) { let_malloc_fail = 1; //On indique qu'on veut que malloc utilisé par gcd échoue if (signal(SIGSEGV, sig_handler) == SIG_ERR) { CU_FAIL("Impossible d'enregistrer un signal handler."); return; } if(setjmp(label_test_malloc_fail)==0) { gcd(5,5); } else { /* IMPORTANT ! On remet let_malloc_fail à 0 pour que CUnit puisse réutiliser malloc par la suite. * Ici, si on ne pense pas à remettre cette variable à 0, CUnit ne prend pas en compte l'échec du test. */ let_malloc_fail = 0; CU_ASSERT_TRUE(0); } /* IMPORTANT ! On remet let_malloc_fail à 0 pour que CUnit puisse réutiliser malloc par la suite. */ let_malloc_fail = 0; signal(SIGSEGV, SIG_DFL); } int main() { CU_pSuite pSuite = NULL; /* initialize the CUnit test registry */ if (CUE_SUCCESS != CU_initialize_registry()) return CU_get_error(); /* add a suite to the registry */ pSuite = CU_add_suite("gcd_suite", NULL, NULL); if (NULL == pSuite) { CU_cleanup_registry(); return CU_get_error(); } /* add the tests to the suite */ if ((NULL == CU_add_test(pSuite, "test for same numbers", test_sameNumber)) || (NULL == CU_add_test(pSuite, "test if a number is 0", test_zero)) || (NULL == CU_add_test(pSuite, "Test if a number is negative", test_negative)) || (NULL == CU_add_test(pSuite, "Test the number of malloc call equal to number of divisors",test_times_malloc_used)) || (NULL == CU_add_test(pSuite, "Test if malloc fail",test_malloc_fail)) || (NULL == CU_add_test(pSuite, "Test if number of malloc and free are equal",test_malloc_equal_free)) || (NULL == CU_add_test(pSuite, "Test if number of thread create is equal to 2",test_howmany_thread))) { CU_cleanup_registry(); return CU_get_error(); } /* Run all tests using the CUnit Basic interface */ CU_basic_set_mode(CU_BRM_VERBOSE); CU_basic_run_tests(); CU_cleanup_registry(); int a=VALUE_A; int b=VALUE_B; int result = gcd(a,b); printf("PGCD of %d and %d : %d\n",a,b,result); return CU_get_error(); }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #define MAXLINE 1000 typedef enum { A_COMMAND = 1, C_COMMAND, L_COMMAND } command_type; // A parsed command typedef struct { command_type type; int error; // if any // For A or L commands char var[MAXLINE]; char label[MAXLINE]; // For C command char comp[10]; char dest[10]; char jump[10]; // A cleaned command for debugging char cln[MAXLINE]; } Command; // A symbol table entry typedef struct { char symbol[MAXLINE]; long value; } Entry; // A symbol table typedef struct { unsigned int len; unsigned int allocated; Entry *entries; } SymbolTable; int symbol_exists(SymbolTable *table, char *symbol) { if (!table->len) { return -1; } for (int i = 0; i < table->len; i++) { if (strcmp(symbol, table->entries[i].symbol) == 0) return i; } return -1; } void symbol_push(SymbolTable *table, char *symbol, long value) { if (table->entries == NULL) { // Allocate memory table->allocated = 100; table->entries = malloc(table->allocated * sizeof(Entry)); } if (table->len >= (table->allocated - 2)) { // Allocate more table->allocated = table->allocated * 2; table->entries = realloc(table->entries, table->allocated * sizeof(Entry)); } int pos = symbol_exists(table, symbol); if (pos == -1) { pos = table->len; // the next free position strcpy(table->entries[pos].symbol, symbol); table->len++; } table->entries[pos].value = value; } long symbol_get(SymbolTable *table, char *symbol) { int pos = symbol_exists(table, symbol); if (pos == -1) return -1; return table->entries[pos].value; } void load_special_vars(SymbolTable *table) { symbol_push(table, "R0", 0); symbol_push(table, "R1", 1); symbol_push(table, "R2", 2); symbol_push(table, "R3", 3); symbol_push(table, "R4", 4); symbol_push(table, "R5", 5); symbol_push(table, "R6", 6); symbol_push(table, "R7", 7); symbol_push(table, "R8", 8); symbol_push(table, "R9", 9); symbol_push(table, "R10", 10); symbol_push(table, "R11", 11); symbol_push(table, "R12", 12); symbol_push(table, "R13", 13); symbol_push(table, "R14", 14); symbol_push(table, "R15", 15); symbol_push(table, "SP", 0); symbol_push(table, "LCL", 1); symbol_push(table, "ARG", 2); symbol_push(table, "THIS", 3); symbol_push(table, "THAT", 4); symbol_push(table, "SCREEN", 16384); symbol_push(table, "KBD", 24576); } void reverse(char s[]) { int length = strlen(s) ; int c, i, j; for (i = 0, j = length - 1; i < j; i++, j--) { c = s[i]; s[i] = s[j]; s[j] = c; } } void itob(int n, char s[], int minlen) { int i, digit; i = 0; do { digit = n % 2; s[i++] = digit + '0'; } while ((n /= 2) != 0); while (i < minlen) s[i++] = '0'; s[i] = '\0'; reverse(s); } int string_in_array(char *array[], char *string, int len) { if (strcmp(string, "") == 0) return 0; for (int i = 0; i < len; i++) { if (strcmp(array[i], string) == 0) return i; } return -1; } int parse_line(char *source_line, Command *command) { char line[MAXLINE]; char *cln = line; int len = 0; // Cleaning source_line[strcspn(source_line, "\r\n")] = '\0'; // trim while (*source_line != 0) { if (*source_line == ' ') { source_line++; continue; } else if (*source_line == '/' && *(source_line + 1) == '/') { break; // don't copy the rest } *cln++ = *source_line++; } *cln = '\0'; if ((len = strlen(line)) == 0) return 0; strcpy(command->cln, line); // Parsing if (line[0] == '@') { sscanf(line, "@%s", command->var); command->type = A_COMMAND; return len; } if (line[0] == '(' && line[len-1] == ')') { sscanf(line, "(%s", command->label); command->label[len-2] = '\0'; // trim the closing bracket command->type = L_COMMAND; if (!strlen(command->label)) command->error = 1; return len; } char *eq = strchr(line, '='); if (eq != NULL) { strncpy(command->dest, line, eq - line); strcpy(command->comp, eq + 1); if (!strlen(command->dest) || !strlen(command->comp)) command->error = 1; command->type = C_COMMAND; return len; } char *semicolon = strchr(line, ';'); if (semicolon != NULL) { strncpy(command->comp, line, semicolon - line); strcpy(command->jump, semicolon + 1); if (!strlen(command->jump) || !strlen(command->comp)) command->error = 1; command->type = C_COMMAND; return len; } // Unknown command command->error = 1; return len; } int main(int argc, char *argv[]) { if (argc < 2) { printf("No source file specified.\n"); return 1; } char *filename = argv[1]; FILE *source = fopen(filename, "rb"); if (source == NULL) { printf("Cannot open file %s\n", filename); return 1; } SymbolTable symbol_table = {}; load_special_vars(&symbol_table); char line[MAXLINE]; Command command = {}; unsigned int line_num = 0; // source line num unsigned int ml_line = 0; // machine language line num while (fgets(line, MAXLINE, source)) { command = (Command){0}; // clear command line_num++; if (!parse_line(line, &command)) continue; if (command.error > 0) { printf("Syntax error at line %d\n", line_num); exit(1); } if (command.type == A_COMMAND || command.type == C_COMMAND) { ml_line++; } else if (command.type == L_COMMAND) { // Push symbol into the symbol table if (symbol_exists(&symbol_table, command.label) > 0) { printf("Value error: (%s) is repeated at line %d\n", command.label, line_num); exit(1); } symbol_push(&symbol_table, command.label, ml_line); // printf("{%s}={%d}={%d}\n", command.label, ml_line, symbol_get(&symbol_table, command.label)); } } // Rewind fseek(source, 0, SEEK_SET); // Generate the code char *code = malloc(17 * (line_num + 1) * sizeof(char)); // 16 'bits' + \n char code_line[MAXLINE]; line_num = 0; int free_mem = 16; char *COMPS[] = {"0", "1", "-1", "D", "A", "!D", "!A", "-D", "-A", "D+1", "A+1", "D-1", "A-1", "D+A", "A+D", "D-A", "A-D", "D&A", "A&D", "D|A", "A|D", "M", "!M", "-M", "M+1", "M-1", "D+M", "M+D", "D-M", "M-D", "D&M", "M&D", "D|M", "M|D"}; char *COMP_VALS[] = {"0101010", "0111111", "0111010", "0001100", "0110000", "0001101", "0110001", "0001111", "0110011", "0011111", "0110111", "0001110", "0110010", "0000010", "0000010", "0010011", "0000111", "0000000", "0000000", "0010101", "0010101", "1110000", "1110001", "1110011", "1110111", "1110010", "1000010", "1000010", "1010011", "1000111", "1000000", "1000000", "1010101", "1010101"}; char *DESTS[] = {"null", "M", "D", "MD", "DM", "A", "AM", "MA", "AD", "DA", "AMD", "MDA", "MAD", "DMA", "ADM", "DAM"}; char *DEST_VALS[] = {"000", "001", "010", "011", "011", "100", "101", "101", "110", "110", "111", "111", "111", "111", "111", "111"}; char *JUMPS[] = {"null", "JGT", "JEQ", "JGE", "JLT", "JNE", "JLE", "JMP"}; char *JUMP_VALS[] = {"000", "001", "010", "011", "100", "101", "110", "111"}; // for (int i = 0; i < symbol_table.len; i++) // { // printf("%s\n", symbol_table.entries[i].symbol); // } // printf("total: %d\n", symbol_table.len); while (fgets(line, MAXLINE, source)) { command = (Command){0}; // clear command line_num++; if (!parse_line(line, &command)) continue; if (command.type != A_COMMAND && command.type != C_COMMAND) continue; // we generate code only for those two if (command.type == A_COMMAND) { int number = atoi(command.var); if (number == 0 && isalpha(command.var[0])) { number = symbol_get(&symbol_table, command.var); if (number == -1) { number = free_mem++; symbol_push(&symbol_table, command.var, number); } } char binary[20]; itob(number, binary, 15); sprintf(code_line, "0%s\n", binary); } else if (command.type == C_COMMAND) { int comp = string_in_array(COMPS, command.comp, 34); int dest = string_in_array(DESTS, command.dest, 16); int jump = string_in_array(JUMPS, command.jump, 8); if (comp == -1 || dest == -1 || jump == -1) { printf("Value error: Unknown command '%s' at line %d\n", command.cln, line_num); exit(1); } sprintf(code_line, "111%s%s%s\n", COMP_VALS[comp], DEST_VALS[dest], JUMP_VALS[jump]); } strcat(code, code_line); *code_line = 0; } char dest_filename[MAXLINE]; strcpy(dest_filename, filename); strcat(dest_filename, ".hack"); FILE *dest = fopen(dest_filename, "wb"); fputs(code, dest); // finally fclose(source); fclose(dest); return 0; }
C
void TransferFile(int client_socket , char username[] , char filename[] , FILE * file){ char buffer[1024]; //buffer for transferring int option = -1; // used as a flag for tranfer //TRANSFER START printf("-> Transferring file : \"%s\" from User : \"%s\" ...\n" , filename , username); recv(client_socket , &option , sizeof(option) , 0); while(option == 1){ recv(client_socket , buffer , sizeof(buffer) , 0); fprintf(file , "%s" , buffer); recv(client_socket , &option , sizeof(option) , 0); } printf("-> Transfer completed successfully\n"); return; //TRANSFER COMPLETE } void getFile(char filename[] , int client_socket , char username[]){ int status = -1; // status : -1 : file already present // status : 1 : file can be uploaded int get_command; FILE * ptr; // pointer to the file //LOG FILE //TIME STRUCTURES to be used FILE * log_file; //adding time stamp to log file time_t TIME; struct tm tm; //checking if already such a file exists or not FILE * check_if_present = fopen(filename , "r"); if(check_if_present != NULL){ //ALREADY A FILE PRESENT WITH SUCH NAME printf("-> FILE \"%s\" ALREADY PRESENT\n" , filename); printf("-> Awaiting command from the user...\n"); // await command if status == -1 //closing check file fclose(check_if_present); send(client_socket , &status , sizeof(status) , 0); get_command = -1; //get the command to delete or rename the file // delete the present file (overwrite) : 0; // cancel the tranfer : -1 recv(client_socket , &get_command , sizeof(get_command) , 0); //time for log file if(get_command == 0){ // overwrite the file status = 1; ptr = fopen(filename , "w"); printf("-> Overwriting the file : \"%s\" ...\n" , filename); //calling transfer TransferFile(client_socket , username , filename , ptr); //time oprations for log file log_file = fopen("server_log.txt" , "a"); TIME = time(NULL); tm = *localtime(&TIME); printf("-> Logging operation...\n"); fprintf(log_file , "%d/%d/%d %d:%d:%d :: ", tm.tm_mday, tm.tm_mon + 1 , tm.tm_year + 1900 , tm.tm_hour , tm.tm_min , tm.tm_sec); fprintf(log_file , "User served : \"%s\"\n Overwrote the file : \"%s\"\n\n" , username , filename); printf("-> Logged successfully\n\n"); fclose(ptr); fclose(log_file); return; } else{ //INVALID COMMAND - we choose to abort the transfer printf("-> Aborting the transfer...\n"); //time oprations for log file log_file = fopen("server_log.txt" , "a"); TIME = time(NULL); tm = *localtime(&TIME); printf("-> Logging operation...\n"); fprintf(log_file , "%d/%d/%d %d:%d:%d :: ", tm.tm_mday, tm.tm_mon + 1 , tm.tm_year + 1900 , tm.tm_hour , tm.tm_min , tm.tm_sec); fprintf(log_file , "User served : \"%s\"\n Transfer cancelled as a file already present with name \"%s\"\n\n" , username , filename); printf("-> Logged successfully\n"); printf("-> Transfer aborted.\n\n"); fclose(log_file); return; } } else{ status = 1; send(client_socket , &status , sizeof(status) , 0); ptr = fopen(filename , "w"); //calling transfer TransferFile(client_socket , username , filename , ptr); //time oprations for log file log_file = fopen("server_log.txt" , "a"); TIME = time(NULL); tm = *localtime(&TIME); printf("-> Logging operation...\n"); fprintf(log_file , "%d/%d/%d %d:%d:%d :: ", tm.tm_mday, tm.tm_mon + 1 , tm.tm_year + 1900 , tm.tm_hour , tm.tm_min , tm.tm_sec); fprintf(log_file , "User served : \"%s\"\n Uploaded the file : \"%s\"\n\n" , username , filename); printf("-> Logged successfully\n\n"); fclose(ptr); fclose(log_file); return; } }
C
#include "synchro.h" #define DEBUG 1 static bool test_and_set(bool *lock) { cli(); bool rv = *lock; *lock = true; sei(); return rv; } void mutex_init(mutex_t *m) { m->lock = false; m->waitlist = Queue_create(8); } void mutex_lock(mutex_t *m) { while(test_and_set(&m->lock)) { // acquire cli(); thread_t *this_thread = &system_threads.thread_list[system_threads.current_thread]; this_thread->t_state = THREAD_WAITING; Queue_push(m->waitlist, this_thread); sei(); yield(get_next_thread()); } } void mutex_unlock(mutex_t *m) { m->lock = false; // release if (!Queue_empty(m->waitlist)) { thread_t *next_thread = Queue_pop(m->waitlist); next_thread->t_state = THREAD_READY; } } void sem_init(semaphore_t *s, int8_t value) { s->n = value; s->waitlist = Queue_create(8); } void sem_wait(semaphore_t *s) { s->n--; if (s->n < 0) { cli(); thread_t *this_thread = &system_threads.thread_list[system_threads.current_thread]; this_thread->t_state = THREAD_WAITING; Queue_push(s->waitlist, this_thread); sei(); yield(get_next_thread()); } } void sem_signal(semaphore_t *s) { s->n++; if (s->n <= 0) { thread_t *next_thread = Queue_pop(s->waitlist); next_thread->t_state = THREAD_READY; } } void sem_signal_swap(semaphore_t *s) { s->n++; if (s->n <= 0) { thread_t *next_thread = Queue_pop(s->waitlist); next_thread->t_state = THREAD_READY; yield(next_thread->thread_id); } }
C
#include <stdio.h> int main() { int value,j; scanf("%d",&value); for(int i=1;i<=value;i++,j=0) { printf("\n"); int k=i; while(k<=value) { printf("\t"); k=k+1; } j=i-1; j=j+j+1; while(j>0) { printf("*\t"); j--; } } return 0; }
C
#include <stdio.h> int searchNumFromArray(int arr[][4], int num); int searchNumFromArray2(const int * pArr, int cols, int rows, int num); int main() { int arr[4][4] = {.......}; int ret = searchNumFromArray(arr, 7); int iArr[] = {....}; int iRet = searchNumFromArray2(iArr, 4, 4, 7); if (TRUE == ret) printf("get it \r\n"); else printf("there is no such num\r\n"); return 0; } int searchNumFromArray2(const int * pArr, int cols, int rows, int num) { if (NULL == pArr || cols <= 0 || rows <= 0) return FALSE; int row = 0; int col = cols - 1; while(row < rows && col >= 0) { if (num > pArr[row * cols + col]) row++; else if(num < pArr[row * cols + col]) col--; else return TRUE; } return FALSE } int searchNumFromArray(int arr[][4], int num) { int col = 4 - 1; int row = 0; while(col >= 0 && row < 4) { if (num == arr[row][col]) return TRUE; else if (num > arr[row][col]) row++; else col--; } return FALSE; }
C
#include<stdio.h> int main() { float table[2][3] = { { 1.1,1.2,1.3 },{ 2.1,2.2,2.3 } }; printf("%p\n", table);//base address of table printf("%p\n", table+1);//1st row starting address printf("%p\n", *(table+1));//1st row ist element address printf("%p\n", (*(table + 1)+1));//1st row 1st element address printf("%p\n", (*(table) + 1));//address of 0th row 1st element printf("%f\n", *(*(table + 1) + 1));//1st row 1st element printf("%f\n", *(*(table)+1));//0th row 1st element printf("%f", *(*(table)+1)+ 1);//0th row first element +1 getch(); return 0; }
C
/* * main.c * * Created on: Apr 24, 2018 * Author: Batuhan Faik Derinbay */ #include <stdio.h> #include <string.h> #include <locale.h> #define MAXCHAR 1000 #define MAXWORD_LENGTH 48 /*onerilen uzunluklar * 20 - kisa kelimelerden olusan basit cumleler icin * 32 - turemis yapida kelimeler iceren basit cumleler icin * 48 - öntanımlı (default) değer * 64 - turemis yapida kelimeleri bolca iceren karmasik cumleler icin * 128 - kelimelerin wordlist'te bulunma ihtimali olmadigi ve * baglaclarla birlestirilmis uzun cumleler icin */ #define MAXCHAR_WORDLIST 610000 #define WORDLIST_LENGTH 610000 int main() { setlocale(LC_ALL, "Turkish"); FILE *atxt; FILE *btxt; FILE *wordList; char nonSpaced[MAXCHAR], wordListArray[MAXCHAR_WORDLIST], spaced[MAXCHAR]; char* fileAtxt = "/home/batuhanfaik/eclipse/workspace/cpp-oxygen/SozcukAyirma_BBG2/texts/a.txt"; char* fileBtxt = "/home/batuhanfaik/eclipse/workspace/cpp-oxygen/SozcukAyirma_BBG2/texts/b.txt"; char* fileWordList = "/home/batuhanfaik/eclipse/workspace/cpp-oxygen/SozcukAyirma_BBG2/texts/wordlist.txt"; //Dosyalari acma ve okuma atxt = fopen(fileAtxt, "r"); if (atxt == NULL) { printf("Dosya acilamadi %s", fileAtxt); return 1; } btxt = fopen(fileBtxt, "w+"); if (atxt == NULL) { printf("Dosya acilamadi %s", fileBtxt); return 1; } wordList = fopen(fileWordList, "r"); if (atxt == NULL) { printf("Dosya acilamadi %s", fileWordList); return 1; } //Degiskenleri tanimla int nonSpacedLoc, spacedLoc, wordListLoc, found = 0; // Okudugunu diziye alma ve alternatif olaraktan yazdirma (a.txt) while (fgets(nonSpaced, MAXCHAR, atxt) != NULL) { fscanf(atxt, "%c", nonSpaced); //Yazdirma //printf("%s", nonSpaced); } //a.txt'den okunanlari kucuk harfe cevirme for (int i = 0; i < strlen(nonSpaced); i++) { nonSpaced[i] = tolower(nonSpaced[i]); } // WordListArray olusturma (wordlist.txt) for (wordListLoc = 0; wordListLoc < WORDLIST_LENGTH; wordListLoc++) { wordListArray[wordListLoc] = fgetc(wordList); } /* Kelimeleri satir satir dizen kod --- Memory allocation ve C'de matris kullanim zorlugundan dolayi vazgectim int wordNo, wordEnds = 0; // WordListArray olusturma (wordlist.txt) for (wordListLoc = 0; wordListLoc < WORDLIST_LENGTH; wordListLoc++) { if (fgetc(wordList) == '\n') { wordNo++; wordEnds = 0; printf("\n"); } else { wordListArray[wordNo][wordEnds] = fgetc(wordList); wordEnds++; } printf("%c",wordListArray[wordNo][wordEnds]); } */ //nonSpaced ve spaced location baslatma spacedLoc = 0; nonSpacedLoc = 0; //isWord ve wordTemp dizileri ile locator'larini olusturma char isWord[MAXWORD_LENGTH], wordTemp[MAXWORD_LENGTH], number[MAXWORD_LENGTH] = { }; int isWordLoc, wordTempLoc = 1; int numberLoc = 0; //isWord'u ve wordTemp'i wordListArray'de aranabilcek formata getirme isWord[0] = '\n'; wordTemp[0] = '\n'; //Ilk harf atamasi wordTemp[1] = 'q'; wordTemp[wordTempLoc + 1] = '\n'; //wordListArray'de bulunmayan formata getirme //nonSpaced dizisini spaced dizisine donusturme while (nonSpaced[nonSpacedLoc] != NULL) { //nonSpaced'tee kelime koku bulup wordTemp'e atma while ((strstr(wordListArray, wordTemp) == '\0') && (found == 0) && (wordTempLoc <= MAXWORD_LENGTH)) { wordTemp[wordTempLoc] = nonSpaced[nonSpacedLoc]; wordTemp[wordTempLoc + 1] = '\n'; //wordListArray'de aranabilcek formata getirmek icin gerekli //Noktalama isaretleriyle karsilasirsa if (((wordTemp[wordTempLoc] >= 33) && (wordTemp[wordTempLoc] <= 47)) || (wordTemp[wordTempLoc] == 63 /*Soru isareti*/)) { found = 1; } wordTempLoc++; nonSpacedLoc++; } //found'i sifirla found = 0; //Bulunan koku isWord'e atip wordTemp'i bosaltma strcpy(isWord, wordTemp); isWordLoc = strlen(isWord); //wordTemp'i bosaltma (flush) memset(wordTemp, '\0', MAXWORD_LENGTH); wordTemp[0] = '\n'; wordTempLoc = 1; //Ilk harf atamasi wordTemp[1] = 'q'; wordTemp[wordTempLoc + 1] = '\n'; //wordListArray'de bulunmayan formata getirme isWordLoc--; //isWord'un "ilk" karakterinin NULL oldugu durumdaki bug icin if (isWord[1] == '\0') { isWordLoc++; } //isWord'te ve wordTemp'te birer kelime bulunana kadar nonSpaced'te ilerleme while ((strstr(wordListArray, wordTemp) == '\0') && (strlen(isWord) < MAXWORD_LENGTH) && (found == 0)) { //Sayilari direkt bastir, onune arkasina bosluk koy while ((nonSpaced[nonSpacedLoc] >= 48) && (nonSpaced[nonSpacedLoc] <= 57)) { number[numberLoc] = nonSpaced[nonSpacedLoc]; nonSpacedLoc++; numberLoc++; } //wordTemp'ten isWord'e tasima wordTemp[wordTempLoc] = nonSpaced[nonSpacedLoc]; isWord[isWordLoc] = wordTemp[wordTempLoc]; //Aranabilir hale getirme wordTemp[wordTempLoc + 1] = '\n'; isWord[isWordLoc + 1] = '\n'; //Noktalama isaretleriyle karsilasirsa if (((wordTemp[wordTempLoc] >= 33) && (wordTemp[wordTempLoc] <= 47)) || (wordTemp[wordTempLoc] == 63 /*Soru isareti*/)) { found = 1; } if (strstr(wordListArray, isWord) != '\0' || found == 1) { //isWord'deki anlamliysa wordTemp'i bosalt //wordTemp flush ve fill memset(wordTemp, '\0', MAXWORD_LENGTH); wordTemp[0] = '\n'; wordTemp[1] = 'q'; wordTempLoc = 1; } else { //isWord'teki anlamsizsa wordTemp'te ilerle wordTempLoc++; } //Birer adim ilerle nonSpacedLoc++; isWordLoc++; } //found'i sifirla found = 0; //Bu noktada kesinlikle bir kelime bulmus olduk bunu spaced'e tasiyalim //Tasima kolaylassin diye isWord'un formatini duzeltelim isWord[0] = '\0'; //Bastaki newline'i sil isWord[isWordLoc - wordTempLoc + 1] = ' '; //Sona bosluk //Kopyala v1 - Dongu ile kopyayi isleri kolaylastirdigindan ve kontrol edilebileceginden tercih ettim //strncat(spaced, isWord, isWordLoc - wordTempLoc + 2); //Kopyala v2 for (int i = 1; i <= isWordLoc - wordTempLoc + 1; i++) { //Cumlenin ilk harfini buyut if (spaced[spacedLoc - 2] == '.' || spaced[spacedLoc - 2] == '!' || spaced[spacedLoc - 2] == '?' || (spacedLoc - 1 < 0)){ isWord[i] = toupper(isWord[i]); } spaced[spacedLoc] = isWord[i]; spacedLoc++; } if (numberLoc != 0) { for (int i = 0; i < numberLoc; i++) { spaced[spacedLoc] = number[i]; spacedLoc++; } spaced[spacedLoc] = ' '; spacedLoc++; numberLoc = 0; } //isWord flush memset(isWord, '\0', MAXWORD_LENGTH); } //Ciktinin son kontrolu if (strstr(spaced, "q") != '\0') { strcat(spaced, "\n\nBIR SEYLER TERS GITTI! :("); } else { strcat(spaced, "\n\nCIKTI BASARILI! :)"); } spacedLoc = 0; //spaced dizisini b.txt belgesine aktarma while (spaced[spacedLoc] != '\0') { fprintf(btxt, "%c", spaced[spacedLoc]); spacedLoc++; } /*//WordList'i yazdirma (acma :D 63k kelime var) while (fgets(wordListArray, MAXCHAR_WORDLIST, wordList) != NULL){ //Yazdirma printf("%s", wordListArray); }*/ fclose(atxt); fclose(btxt); fclose(wordList); return 0; }
C
/* * nvic.h * * Created on: Jan 4, 2013 * Author: jon */ #include <stdint.h> #ifndef NVIC_H_ #define NVIC_H_ #ifdef __cplusplus #define __I volatile /*!< Defines 'read only' permissions */ #else #define __I volatile const /*!< Defines 'read only' permissions */ #endif #define __O volatile /*!< Defines 'write only' permissions */ #define __IO volatile /*!< Defines 'read / write' permissions */ #define __ASM __asm /*!< asm keyword for GNU Compiler */ #define __INLINE inline /*!< inline keyword for GNU Compiler */ #define __STATIC_INLINE static inline typedef struct { __IO uint32_t ISER[8]; /*!< Offset: 0x000 (R/W) Interrupt Set Enable Register */ uint32_t RESERVED0[24]; __IO uint32_t ICER[8]; /*!< Offset: 0x080 (R/W) Interrupt Clear Enable Register */ uint32_t RSERVED1[24]; __IO uint32_t ISPR[8]; /*!< Offset: 0x100 (R/W) Interrupt Set Pending Register */ uint32_t RESERVED2[24]; __IO uint32_t ICPR[8]; /*!< Offset: 0x180 (R/W) Interrupt Clear Pending Register */ uint32_t RESERVED3[24]; __IO uint32_t IABR[8]; /*!< Offset: 0x200 (R/W) Interrupt Active bit Register */ uint32_t RESERVED4[56]; __IO uint8_t IP[240]; /*!< Offset: 0x300 (R/W) Interrupt Priority Register (8Bit wide) */ uint32_t RESERVED5[644]; __O uint32_t STIR; /*!< Offset: 0xE00 ( /W) Software Trigger Interrupt Register */ } NVIC_Type; /* Software Triggered Interrupt Register Definitions */ #define NVIC_STIR_INTID_Pos 0 /*!< STIR: INTLINESNUM Position */ #define NVIC_STIR_INTID_Msk (0x1FFUL << NVIC_STIR_INTID_Pos) /*!< STIR: INTLINESNUM Mask */ #define SCS_BASE (0xE000E000UL) /*!< System Control Space Base Address */ #define NVIC_BASE (SCS_BASE + 0x0100UL) /*!< NVIC Base Address */ #define NVIC ((NVIC_Type *) NVIC_BASE ) /*!< NVIC configuration struct */ __STATIC_INLINE void NVIC_EnableIRQ(uint32_t IRQn) { NVIC->ISER[((uint32_t)(IRQn) >> 5)] = (1 << ((uint32_t)(IRQn) & 0x1F)); /* enable interrupt */ } __STATIC_INLINE void NVIC_DisableIRQ(uint32_t IRQn) { NVIC->ICER[((uint32_t)(IRQn) >> 5)] = (1 << ((uint32_t)(IRQn) & 0x1F)); /* disable interrupt */ } __STATIC_INLINE uint32_t NVIC_GetPendingIRQ(uint32_t IRQn) { return((uint32_t) ((NVIC->ISPR[(uint32_t)(IRQn) >> 5] & (1 << ((uint32_t)(IRQn) & 0x1F)))?1:0)); /* Return 1 if pending else 0 */ } __STATIC_INLINE void NVIC_SetPendingIRQ(uint32_t IRQn) { NVIC->ISPR[((uint32_t)(IRQn) >> 5)] = (1 << ((uint32_t)(IRQn) & 0x1F)); /* set interrupt pending */ } __STATIC_INLINE void NVIC_ClearPendingIRQ(uint32_t IRQn) { NVIC->ICPR[((uint32_t)(IRQn) >> 5)] = (1 << ((uint32_t)(IRQn) & 0x1F)); /* clear interrupt pending */ } __STATIC_INLINE uint32_t NVIC_GetActive(uint32_t IRQn) { return((uint32_t)((NVIC->IABR[(uint32_t)(IRQn) >> 5] & (1 << ((uint32_t)(IRQn) & 0x1F)))?1:0)); /* Return 1 if active else 0 */ } #endif /* NVIC_H_ */
C
#include "button_driver.h" /** * Function to initialize peripheral registers concerning the button. * Button connections: * Port: PIOB * Pin: PIO_PB26 (Arduino pin 22) */ void Init_Button(void) { #ifdef DEBUG trace_puts("Initializing button...\n"); #endif //Disable pmc writeprotect PMC->PMC_WPMR = 0x504D4300; //Enable PIOB peripheral clock PMC->PMC_PCER0 = PMC->PMC_PCSR0 | 1 << PIOB_IRQn; PIOB->PIO_WPMR = 0x50494F00; //Enable Button peripheral PIOB->PIO_PER = PIO_PB26; //Disable output PIOB->PIO_ODR = PIO_PB26; //Disable pullup PIOB->PIO_PUDR = PIO_PB26; } /** * Reads the current value of the button and * stores the value 0 in the memory adress pointed to by * *nButton if the button is pressed, else 1. * * Assumes that the button has been correctly initialized. */ void ReadButton(unsigned int* nButton) { //Read Output status register *nButton = (PIOB->PIO_PDSR & PIO_PB26) >> 26; } /** * Function to initialize peripheral registers concerning the button. * Together with interrupt and debounce. * Button connections: * Port: PIOB * Pin: PIO_PB26 (Arduino pin 22) */ void Init_Button_Interrupt(void) { //Disable pmc writeprotect PMC->PMC_WPMR = 0x504D4300; //Enable PIOB peripheral clock PMC->PMC_PCER0 = 1 << PIOB_IRQn; //Disable writeprotect PIOB->PIO_WPMR = 0x50494F00; //Enable Button peripheral PIOB->PIO_PER = PIO_PB26; //Disable output PIOB->PIO_ODR = PIO_PB26; //Disable pullup PIOB->PIO_PUDR = PIO_PB26; //Set up slow clock divide fo c:a 16ms debounce PIOB->PIO_SCDR = 261; //Enable the input filter in debounce mode PIOB->PIO_DIFSR = PIO_PB26; //Enable input filter PIOB->PIO_IFER = PIO_PB26; //Enable interrupts on edge PIOB->PIO_ESR = PIO_PB26; //Enable interrupts on falling edge PIOB->PIO_FELLSR = PIO_PB26; //Enable additional interrupts mode PIOB->PIO_AIMER = PIO_PB26; //Enable the pio to send IRQ to nvic PIOB->PIO_IER = PIO_PB26; //Enable interrupts in nvic NVIC_EnableIRQ(PIOB_IRQn); } /** * Handles entry of ISR * Should be called in beginning of ISR. * returns the value in the interrupt status register. */ uint32_t Button_Handler(void) { //Clear pending interrupt NVIC_ClearPendingIRQ(PIOB_IRQn); //Read PIOB ISR which also clears the flag return PIOB->PIO_ISR; }
C
/** * Program to implement the tower of hanoi function using Recursion. * Compilation: gcc -o recursion_3 recursion_3.c * Execution: ./recursion_3 * * Assignment_5 - Recursion * @Aanchal, 1910990158, 6/8/2021 */ #include <stdio.h> int count = 0; // Prints the movement of disk along with count of movements void tower_of_hanoi(int n, char from, char to, char aux) { if (n <= 1) { printf("%c to %c\n", from, to); count++; return; } tower_of_hanoi(n - 1, from, aux, to); printf("%c to %c\n", from, to); count++; tower_of_hanoi(n - 1, aux, to, from); } int main() { tower_of_hanoi(3,'A','C','B'); printf("Total movements required = %d",count); }
C
#include <stdio.h> #include <conio.h> #include <stdlib.h> main (){ int a[5][5]; int i,j; printf("Dame los valores de la matriz A \n"); for(i=1;i<=4;i++){ for(j=1;j<=4;j++){ printf("a[%d][%d] \n",i,j); scanf("%i",&a[i][j]); } printf("\n"); } printf("\n\n"); for(i=1;i<=4;i++){ for(j=1;j<=4;j++){ if (i==j)/*toma la diagonal principal*/ printf("a[%d][%d]= %d ",i,j,a[i][j]); } } printf("\n"); system("pause"); return 0; }
C
#include <stdio.h> #include <stdlib.h> int main() { char resp='s',preg; int conta=0,num,suma=0; float promedio; do{ printf("\nIngrese Numero: "); scanf("%d",&num); suma=suma+num; printf("\nDesea Ingresar otro Numero: 's' 'n'"); scanf("%s",&resp); conta++; }while(resp=='s'); printf("\nLa suma de los numeros es: %d",suma); promedio=(float)suma/conta; printf("\nEl promedio es: %.2f",promedio); return 0; }
C
#ifndef OPCODES_H #define OPCODES_H #include <stdio.h> #include <stdlib.h> #include <string.h> enum opcodes { HALT=-1, PUSH, POP, ADD, SUB, MUL, DIV, LOAD, STORE, JMP, JMP_EQ, }; int *program = NULL; int max = 0; int pc = 0; inline int nextOp(int *op) { if (pc < 0 || pc > max) { return -1; } *op = program[pc++]; return 0; } void loadProgram() { int len = 256; program = (int *)calloc(len, sizeof(int)); int i = 0; int op; while (scanf("%d", &op) == 1) { program[i] = op; i++; if (i >= len) { program = (int *)realloc(program, len*2); } } program[i] = -1; max = i; } #endif /* OPCODES_H */
C
#include<stdio.h> #include<stdlib.h> void main(void) { int **snail; int i = 0, j =0; int n; int count = 0; printf("사이즈를 입력하세요 : "); scanf("%d",&n); snail = malloc(sizeof(int *) * n); for(i = 0; i <= n; i++){ snail[i] = malloc(sizeof(int *) * n); } i = 0; while(j < n){ snail[i][j] = ++count; j++; } if(j == n){ i++; while(i < n) { snail[i][j-1] = ++count; i++; } } if(i == n){ j = j-2; while(j >= 0){ snail[i-1][j] = ++count; j--; } j++; } if(j == 0){ i = i-2; while(i > 0){ snail[i][j] = ++count; i--; } } //출력 for(i = 0; i < n; i++){ for(j = 0; j < n; j++) printf("| %d |",snail[i][j]); printf("\n"); } printf("\n"); }
C
#include <stdlib.h> #include <string.h> #include "assert.h" #include "except.h" #include "arena.h" #define T Arena_T const Except_T Arena_NewFailed = {"Arena Creation Failed"}; const Except_T Arena_Failed = {"Arena Allocation Failed"}; <macros 71> //<types 67> struct T { T prev; char *avail; char *limit; }; union align { int i; long l; long *lp; void *p; void (*fp)(void); float f; double d; long double ld; }; union header { struct T b; union align a; }; <data 70> //<functions 68> T Arena_new(void) { T arena = malloc(sizeof(*arena)); if (arena == NULL) { RAISE(Arena_NewFailed); } arena->prev = NULL; arena->limit = arena->avail = NULL; return arena; } void Arena_dispose(T *ap) { assert(ap && *ap); Arena_free(*ap); free(*ap); *ap = NULL; } void *Arena_alloc(T arena, long nbytes, const char *file, int line) { assert(arena); assert(nbytes > 0); //<round nbytes up to an alignment boundary 69> nbytes = ((nbytes + sizeof(union align) - 1)/sizeof(union align)) / (sizeof(union align)); while (nbytes > arena->limit - arena->avail) { //<get a new chunk 69> T ptr; char *limit; <ptr <- a new chunk 70> *ptr = *arena; arena->avail = (char *)((union header *)ptr + 1); arena->limit = limit; arena->prev = prev; } arena->avail += nbytes; return arena->avail - nbytes; }
C
/************************************************************************* > File Name: pipea.c > Author: > Mail: > Created Time: 2017年09月11日 星期一 22时13分19秒 ************************************************************************/ #include<stdio.h> #include<stdlib.h> #include<unistd.h> #include<fcntl.h> int main() { int fd = open("./a.pipe",O_WRONLY); if(fd == -1) perror("open"),exit(-1); for(int i = 0 ; i < 100;i++) { write(fd,&i,4); usleep(100000); } close(fd); }
C
/*1. Store information of a student using structure and dynamic memory allocation Information to be stored: Roll number Name Address Mark 1 Mark 2 Mark 3 */ #include<stdio.h> #include<stdlib.h> struct student { int roll, mark1, mark2, mark3; char name[30], address[150]; }; int main() { int i; struct student *ptr; ptr=(struct student *)malloc(1*sizeof(struct student)); if(ptr==NULL) { printf("Insufficient memory"); return 0; } printf("Enter the roll number "); scanf("%d", &(ptr)->roll); printf("Enter the name "); scanf("%s", (ptr)->name); printf("Enter the address "); scanf("%s", (ptr)->address); printf("Enter the mark 1: "); scanf("%d", &(ptr)->mark1); printf("Enter the mark 2: "); scanf("%d", &(ptr)->mark2); printf("Enter the mark 3: "); scanf("%d", &(ptr)->mark3); printf("\nDisplaying the information \n"); printf("\nRoll Number: %d", (ptr)->roll); printf("\nName: %s", (ptr)->name); printf("\nAddress: %s", (ptr)->address); printf("\nMark 1: %d", (ptr)->mark1); printf("\nMark 2: %d", (ptr)->mark2); printf("\nMark 3: %d", (ptr)->mark3); free(ptr); return 0; }
C
#include <stdint.h> #include <stddef.h> #include <string.h> #include "unicode.h" int utf8_last_size(const char *str) { int len = 0; char *pos = strchr(str, '\0'); while (pos > str) { --pos; ++len; if ((*pos & 0xc0) != 0x80) { return len; } } return 0; } size_t utf8_chsize(uint32_t ch) { if (ch < 0x80) { return 1; } else if (ch < 0x800) { return 2; } else if (ch < 0x10000) { return 3; } return 4; } size_t utf8_encode(char *str, uint32_t ch) { size_t len = 0; uint8_t first; if (ch < 0x80) { first = 0; len = 1; } else if (ch < 0x800) { first = 0xc0; len = 2; } else if (ch < 0x10000) { first = 0xe0; len = 3; } else { first = 0xf0; len = 4; } for (size_t i = len - 1; i > 0; --i) { str[i] = (ch & 0x3f) | 0x80; ch >>= 6; } str[0] = ch | first; return len; } static const struct { uint8_t mask; uint8_t result; int octets; } sizes[] = { { 0x80, 0x00, 1 }, { 0xE0, 0xC0, 2 }, { 0xF0, 0xE0, 3 }, { 0xF8, 0xF0, 4 }, { 0xFC, 0xF8, 5 }, { 0xFE, 0xF8, 6 }, { 0x80, 0x80, -1 }, }; int utf8_size(const char *s) { uint8_t c = (uint8_t)*s; for (size_t i = 0; i < sizeof(sizes) / sizeof(*sizes); ++i) { if ((c & sizes[i].mask) == sizes[i].result) { return sizes[i].octets; } } return -1; }
C
#include "hough.h" #include "window.h" #include "frame.h" #include "stdio.h" #include <opencv/cv.h> int templateMatch(struct window *window, int frame, int diam, CvMat *tmpl) { // Init struct frame *fr = get_frame(window->frames, frame); // printf("Guess is (%d, %d), diameter is %d\n", window->guess.x, window->guess.y, diam); float init_x = (float)window->guess.x-diam, init_y = (float)window->guess.y-diam; // See if we can guess were the ball might be CvRect rect = cvRect(init_x, init_y, diam*2, diam*2); // Make sure rect is with image rect.x = rect.x < 0 ? 0 : rect.x; rect.y = rect.y < 0 ? 0 : rect.y; rect.width = rect.x+rect.width > fr->image->cols ? fr->image->cols-rect.x : rect.width; rect.height = rect.y+rect.height > fr->image->rows ? fr->image->rows-rect.y : rect.height; // Get sub rect CvMat *sub = cvCreateMatHeader(rect.height, rect.width, CV_32F); cvGetSubRect(fr->image, sub, rect); CvMat *res = cvCreateMat(sub->rows - tmpl->rows+1, sub->cols - tmpl->cols+1, CV_32F); // Match cvMatchTemplate(sub, tmpl, res, CV_TM_SQDIFF); // Find value and location of min = upper-left corner of template match CvPoint pt; double val; cvMinMaxLoc(res, &val, 0, &pt, 0, 0); // printf("#%d: value of match is %f\n", frame, val); if (val > 20000000) { // Works on sample video // printf("Doubling search area\n"); templateMatch(window, frame, diam*2, tmpl); return 0; } // Match result struct MatchResult mr; mr.x = init_x+pt.x; mr.y = init_y+pt.y; mr.found = 1; fr->match = mr; window->guess.x = mr.x; window->guess.y = mr.y; return 0; }
C
// A noter : cet implémentation N'EST PAS la même que celle de la fonction disponible sur vos ordi // Ceci étant dit, on doit transformer une chaine de char en int, si jamais sont présents // des char qui représentent des chiffre à partir d'un moment précis. // Si vous êtes en piscine, rappelez-vous : on est dans la table ascii : 0 en chiffre ne correspond pas à // '0' en table ascii. int ft_isspace(char c) { if (c == '\t' || c == '\n' || c == '\v' || c == '\f' || c == '\r' || c == ' ') return (1); return (0); } int ft_atoi(char *str) { int res; int sign; res = 0; sign = 1; // tant qu'il y a des char correspond à la définition de isspace (man isspace) on incrémente while (*str && ft_isspace(*str)) str++; // tant qu'il y a des + ou - on incrémente. Si on a des moins, à chaque rencontre on multiplie par -1 notre signe while (*str && (*str == '+' || *str == '-')) { if (*str == '-') sign *= -1; str++; } //tant la chaîne existe, et que les char rencontrés sont entre 0 et 9, on fait la formule qui nous permet de passer de la valeur ascii // à la valeur en entier de type int. // Look here => https://www.geeksforgeeks.org/convert-base-decimal-vice-versa/ // généralement ce site est un super site. while (*str && *str >= '0' && *str <= '9') { res = res * 10 + *str - 48; str++; } return (res * sign); }
C
int main() { int n, i, pos; const int MAX = 200; unsigned an[MAX]={0}; an[0] = 1; cin >> n; if(n==0) cout << an[0]; else { while(n--) { for(i=0;i<MAX;i++) an[i] = an[i] * 2; for(i=0;i<MAX;i++) if(an[i]>9) { an[i+1]+=an[i]/10; an[i] = an[i] % 10 ; } } for(i=MAX-1;an[i]==0;i--); for(;i>=0;i--) cout << an[i] ; } return 0; }
C
#include "board.h" #include "io.h" #include <stdlib.h> #include <memory.h> void init_genrand(unsigned long s); unsigned long genrand_int32(void); static inline uint min(uint a, uint b) { return (a < b) ? a : b; } static inline uint max(uint a, uint b) { return (a > b) ? a : b; } void reset_to_boundary(board_t *board) { uint const width = board->width; uint const height = board->height; uint *const edge_h = board->edge_h; uint *const edge_v = board->edge_v; for (uint i = 0; i < width*(height + 1); ++i) { edge_h[i] = (edge_h[i] & EDGE_BOUNDARY) ? (EDGE_BOUNDARY | EDGE_BARRIER) : 0; } for (uint i = 0; i < (width + 1)*height; ++i) { edge_v[i] = (edge_v[i] & EDGE_BOUNDARY) ? (EDGE_BOUNDARY | EDGE_BARRIER) : 0; } } void copy_board(board_t *dst, board_t const *src) { uint const width = src->width; uint const height = src->height; dst->width = width; dst->height = height; dst->edge_h = (uint *)malloc(width*(height + 1)*sizeof(uint)); dst->edge_v = (uint *)malloc((width + 1)*height*sizeof(uint)); memcpy(dst->edge_h, src->edge_h, width*(height + 1)*sizeof(uint)); memcpy(dst->edge_v, src->edge_v, (width + 1)*height*sizeof(uint)); } void swap_board(board_t *a, board_t *b) { board_t tmp; tmp.width = a->width; tmp.height = a->height; tmp.edge_h = a->edge_h; tmp.edge_v = a->edge_v; a->width = b->width; a->height = b->height; a->edge_h = b->edge_h; a->edge_v = b->edge_v; b->width = tmp.width; b->height = tmp.height; b->edge_h = tmp.edge_h; b->edge_v = tmp.edge_v; } void free_board(board_t *board) { free(board->edge_h); free(board->edge_v); memset(board, 0, sizeof(board_t)); } void copy_edges_to_solver(solver_t const *solver, board_t const *board) { uint const width = board->width; uint const height = board->height; memcpy(solver->edge_h_old, board->edge_h, width*(height + 1)*sizeof(uint)); memcpy(solver->edge_v_old, board->edge_v, (width + 1)*height*sizeof(uint)); } void init_solver(solver_t *solver, board_t const *board) { uint const width = board->width; uint const height = board->height; memset(solver, 0, sizeof(solver_t)); solver->edge_h_old = (uint *)malloc(width*(height + 1)*sizeof(uint)); solver->edge_v_old = (uint *)malloc((width + 1)*height*sizeof(uint)); solver->tmp1 = (uint *)malloc((width + 1)*(height + 1)*sizeof(uint)); solver->tmp2 = (uint *)malloc((width + 1)*(height + 1)*sizeof(uint)); } bool check_single_cells(solver_t const *solver, board_t const *board) { uint const width = board->width; uint const height = board->height; uint *const edge_h = board->edge_h; uint *const edge_v = board->edge_v; uint *const cells = solver->tmp1; memset(cells, 0, width*height*sizeof(uint)); bool changed = false; for (uint y = 0; y < height; ++y) for (uint x = 0; x < width; ++x) { // check the number of useable edges uint *edges[4]; edges[0] = edge_h + y*width + x; edges[1] = edges[0] + width; edges[2] = edge_v + y*(width + 1) + x; edges[3] = edges[2] + 1; uint available_mask = 0; uint path_mask = 0; for (uint i = 0; i < 4; ++i) { uint const e = *edges[i]; if ((e & EDGE_BARRIER) == 0) { available_mask |= (1U << i); } if (e & EDGE_PATH) { path_mask |= (1U << i); } } uint const available_count = __builtin_popcount(available_mask); uint const path_count = __builtin_popcount(path_mask); if (available_count == 2 && path_count < 2) { for (uint i = 0; i < 4; ++i) { if (available_mask & (1U << i)) { *edges[i] |= EDGE_PATH; } else { *edges[i] |= EDGE_BARRIER; } } cells[y*width + x] = 1; changed = true; } else if (path_count == 2 && available_count > 2) { for (uint i = 0; i < 4; ++i) { if ((path_mask & (1U << i)) == 0) { *edges[i] |= EDGE_BARRIER; } } cells[y*width + x] = 1; changed = true; } } if (changed && solver->verbose) { fputs("\nsingle cells:\n", stdout); print_board(solver, board, EDGE_ALL | EDGE_HIGHLIGHT | EDGE_NEW); } return changed; } static inline uint parity(uint x, uint y) { return (x ^ y) & 1; } bool parity_check_block_island(solver_t const *solver, board_t const *board, uint x0, uint y0, uint x1, uint y1, uint island_index) { uint const width = board->width; uint const height = board->height; uint *const edge_h = board->edge_h; uint *const edge_v = board->edge_v; uint const *const cells = solver->tmp2; uint const w = x1 - x0; uint const h = y1 - y0; // count island cells uint cell_count[2] = { 0, 0 }; for (uint y = 0; y < h; ++y) for (uint x = 0; x < w; ++x) { if (cells[y*w + x] == island_index) { uint const p = parity(x0 + x, y0 + y); ++cell_count[p]; } } // count available edges uint available_count[2] = { 0, 0 }; uint path_count[2] = { 0, 0 }; for (uint i = 0; i < w; ++i) { if (cells[i] == island_index) { uint const k = y0*width + x0 + i; uint const p = parity(x0 + i, y0); if ((edge_h[k] & EDGE_BARRIER) == 0) { ++available_count[p]; } if (edge_h[k] & EDGE_PATH) { ++path_count[p]; } } if (cells[(h - 1)*w + i] == island_index) { uint const k = y1*width + x0 + i; uint const p = parity(x0 + i, y1 - 1); if ((edge_h[k] & EDGE_BARRIER) == 0) { ++available_count[p]; } if (edge_h[k] & EDGE_PATH) { ++path_count[p]; } } } for (uint i = 0; i < h; ++i) { if (cells[i*w] == island_index) { uint const k = (y0 + i)*(width + 1) + x0; uint const p = parity(x0, y0 + i); if ((edge_v[k] & EDGE_BARRIER) == 0) { ++available_count[p]; } if (edge_v[k] & EDGE_PATH) { ++path_count[p]; } } if (cells[i*w + (w - 1)] == island_index) { uint const k = (y0 + i)*(width + 1) + x1; uint const p = parity(x1 - 1, y0 + i); if ((edge_v[k] & EDGE_BARRIER) == 0) { ++available_count[p]; } if (edge_v[k] & EDGE_PATH) { ++path_count[p]; } } } uint const min_cell_count = min(cell_count[0], cell_count[1]); uint const extra_cells[2] = { cell_count[0] - min_cell_count, cell_count[1] - min_cell_count }; if (available_count[0] < 2*extra_cells[0] || available_count[1] < 2*extra_cells[1]) { fprintf(stderr, "odd parity block went wrong\n"); exit(-1); } uint const min_count[2] = { 1 + extra_cells[0] - extra_cells[1], 1 + extra_cells[1] - extra_cells[0], }; uint max_count[2] = { min(available_count[0], available_count[1] + 2*(extra_cells[0] - extra_cells[1])), min(available_count[1], available_count[0] + 2*(extra_cells[1] - extra_cells[0])) }; if (cell_count[0] + cell_count[1] == width*height) { max_count[0] = min(max_count[0], min_count[0]); max_count[1] = min(max_count[1], min_count[1]); } bool const only_path_min_available[2] = { available_count[0] == min_count[0] && path_count[0] < min_count[0], available_count[1] == min_count[1] && path_count[1] < min_count[1] }; bool const other_parity_used_path_max[2] = { path_count[1] == max_count[1] && available_count[0] == max_count[0] && path_count[0] < max_count[0], path_count[0] == max_count[0] && available_count[1] == max_count[1] && path_count[1] < max_count[1] }; bool const make_path[2] = { only_path_min_available[0] || other_parity_used_path_max[0], only_path_min_available[1] || other_parity_used_path_max[1], }; bool const make_barrier[2] = { path_count[0] == max_count[0] && available_count[0] > max_count[0], path_count[1] == max_count[1] && available_count[1] > max_count[1] }; if (!(make_path[0] || make_path[1] || make_barrier[0] || make_barrier[1])) { return false; } for (uint i = 0; i < w; ++i) { if (cells[i] == island_index) { uint const k = y0*width + x0 + i; uint const p = parity(x0 + i, y0); if (make_path[p] && (edge_h[k] & EDGE_BARRIER) == 0) { edge_h[k] |= EDGE_PATH; } else if (make_barrier[p] && (edge_h[k] & EDGE_PATH) == 0) { edge_h[k] |= EDGE_BARRIER; } } if (cells[(h - 1)*w + i] == island_index) { uint const k = y1*width + x0 + i; uint const p = parity(x0 + i, y1 - 1); if (make_path[p] && (edge_h[k] & EDGE_BARRIER) == 0) { edge_h[k] |= EDGE_PATH; } else if (make_barrier[p] && (edge_h[k] & EDGE_PATH) == 0) { edge_h[k] |= EDGE_BARRIER; } } } for (uint i = 0; i < h; ++i) { if (cells[i*w] == island_index) { uint const k = (y0 + i)*(width + 1) + x0; uint const p = parity(x0, y0 + i); if (make_path[p] && (edge_v[k] & EDGE_BARRIER) == 0) { edge_v[k] |= EDGE_PATH; } else if (make_barrier[p] && (edge_v[k] & EDGE_PATH) == 0) { edge_v[k] |= EDGE_BARRIER; } } if (cells[i*w + w - 1] == island_index) { uint const k = (y0 + i)*(width + 1) + x1; uint const p = parity(x1 - 1, y0 + i); if (make_path[p] && (edge_v[k] & EDGE_BARRIER) == 0) { edge_v[k] |= EDGE_PATH; } else if (make_barrier[p] && (edge_v[k] & EDGE_PATH) == 0) { edge_v[k] |= EDGE_BARRIER; } } } if (solver->verbose) { uint *const highlights = solver->tmp1; memset(highlights, 0, width*height*sizeof(uint)); for (uint y = 0; y < h; ++y) for (uint x = 0; x < w; ++x) { if (cells[y*w + x] == island_index) { highlights[(y0 + y)*width + (x0 + x)] = 1; } } fputs("\nparity check:\n", stdout); print_board(solver, board, EDGE_ALL | EDGE_HIGHLIGHT | EDGE_NEW); } return true; } bool parity_check_block(solver_t const *solver, board_t const *board, uint x0, uint y0, uint x1, uint y1) { uint const width = board->width; uint *const edge_h = board->edge_h; uint *const edge_v = board->edge_v; uint *const coords = solver->tmp1; uint *const cells = solver->tmp2; uint const w = x1 - x0; uint const h = y1 - y0; memset(cells, 0, w*h*sizeof(uint)); // colour all islands uint next_island_index = 1; for (uint sy = 0; sy < h; ++sy) for (uint sx = 0; sx < w; ++sx) { if (cells[sy*w + sx] != 0) { continue; } cells[sy*w + sx] = next_island_index; coords[0] = (sy << 16) | sx; uint start = 0; uint end = 1; while (start != end) { uint const x = coords[start] & 0xffffU; uint const y = coords[start] >> 16; uint const ic = y*w + x; uint const ih = (y0 + y)*width + (x0 + x); uint const iv = (y0 + y)*(width + 1) + (x0 + x); if (x > 0 && cells[ic - 1] == 0 && (edge_v[iv] & EDGE_BARRIER) == 0) { cells[ic - 1] = next_island_index; coords[end++] = (y << 16) | (x - 1); } if (x < w - 1 && cells[ic + 1] == 0 && (edge_v[iv + 1] & EDGE_BARRIER) == 0) { cells[ic + 1] = next_island_index; coords[end++] = (y << 16) | (x + 1); } if (y > 0 && cells[ic - w] == 0 && (edge_h[ih] & EDGE_BARRIER) == 0) { cells[ic - w] = next_island_index; coords[end++] = ((y - 1) << 16) | x; } if (y < h - 1 && cells[ic + w] == 0 && (edge_h[ih + width] & EDGE_BARRIER) == 0) { cells[ic + w] = next_island_index; coords[end++] = ((y + 1) << 16) | x; } ++start; } ++next_island_index; } // solve each one for (uint i = 1; i < next_island_index; ++i) { if (parity_check_block_island(solver, board, x0, y0, x1, y1, i)) { return true; } } return false; } bool parity_check_all_blocks(solver_t const *solver, board_t const *board, uint w, uint h) { uint const xn = board->width - w; uint const yn = board->height - h; for (uint y = 0; y <= yn; ++y) for (uint x = 0; x <= xn; ++x) { if (parity_check_block(solver, board, x, y, x + w, y + h)) { return true; } } return false; } bool parity_check_all_block_sizes(solver_t const *solver, board_t const *board) { uint const width = board->width; uint const height = board->height; for (uint h = 2; h <= height; ++h) for (uint w = 2; w <= width; ++w) { if (parity_check_all_blocks(solver, board, w, h)) { return true; } } return false; } bool check_loops(solver_t const *solver, board_t const *board, bool *is_solved) { uint const width = board->width; uint const height = board->height; uint *const edge_h = board->edge_h; uint *const edge_v = board->edge_v; uint *const coords = solver->tmp1; uint *const cells = solver->tmp2; uint *const highlights = coords; memset(cells, 0, width*height*sizeof(uint)); // colour all paths uint exit_path_count = 0; uint exit_path_indices[2] = { 0, 0 }; uint next_path_index = 1; for (uint sy = 0; sy < height; ++sy) for (uint sx = 0; sx < width; ++sx) { if (cells[sy*width + sx] != 0) { continue; } uint all_path_bits = 0; all_path_bits |= edge_h[sy*width + sx]; all_path_bits |= edge_h[(sy + 1)*width + sx]; all_path_bits |= edge_v[sy*(width + 1) + sx]; all_path_bits |= edge_v[sy*(width + 1) + sx + 1]; if ((all_path_bits & EDGE_PATH) == 0) { continue; } cells[sy*width + sx] = next_path_index; coords[0] = (sy << 16) | sx; uint start = 0; uint end = 1; while (start != end) { uint const x = coords[start] & 0xffffU; uint const y = coords[start] >> 16; uint const ic = y*width + x; uint const ih = ic; uint const iv = y*(width + 1) + x; if (edge_v[iv] & EDGE_PATH) { if (x == 0) { exit_path_indices[exit_path_count++] = next_path_index; } else if (cells[ic - 1] == 0) { cells[ic - 1] = next_path_index; coords[end++] = (y << 16) | (x - 1); } } if (edge_v[iv + 1] & EDGE_PATH) { if (x + 1 == width) { exit_path_indices[exit_path_count++] = next_path_index; } else if (cells[ic + 1] == 0) { cells[ic + 1] = next_path_index; coords[end++] = (y << 16) | (x + 1); } } if (edge_h[ih] & EDGE_PATH) { if (y == 0) { exit_path_indices[exit_path_count++] = next_path_index; } else if (cells[ic - width] == 0) { cells[ic - width] = next_path_index; coords[end++] = ((y - 1) << 16) | x; } } if (edge_h[ih + width] & EDGE_PATH) { if (y + 1 == height) { exit_path_indices[exit_path_count++] = next_path_index; } else if (cells[ic + width] == 0) { cells[ic + width] = next_path_index; coords[end++] = ((y + 1) << 16) | x; } } ++start; } ++next_path_index; } if (exit_path_count > 2) { fprintf(stderr, "exit path counting went wrong\n"); exit(-1); } memset(highlights, 0, width*height*sizeof(uint)); // count path lengths uint exit_path_length_total = 0; for (uint i = 0; i < width*height; ++i) { uint const index = cells[i]; if ((exit_path_count > 0 && exit_path_indices[0] == index) || (exit_path_count > 1 && exit_path_indices[1] == index)) { ++exit_path_length_total; } } // early out if solved completely *is_solved = (exit_path_count == 2 && next_path_index == 2 && exit_path_length_total == width*height); if (*is_solved) { return false; } // add barriers to prevent loops or short paths bool changed = false; for (uint y = 0; y < height; ++y) for (uint x = 0; x < width; ++x) { uint const index = cells[y*width + x]; if (index == 0) { continue; } bool const is_exit = (exit_path_length_total < width*height && exit_path_count == 2 && (index == exit_path_indices[0] || index == exit_path_indices[1])); uint const kv = y*(width + 1) + x + 1; uint const kh = (y + 1)*width + x; if (x + 1 < width && (edge_v[kv] & EDGE_PATH) == 0) { uint const other_index = cells[y*width + x + 1]; bool const other_is_exit = (exit_path_count == 2 && (other_index == exit_path_indices[0] || other_index == exit_path_indices[1])); if ((index == other_index || (is_exit && other_is_exit)) && (edge_v[kv] & EDGE_BARRIER) == 0) { edge_v[kv] |= EDGE_BARRIER; changed = true; } } if (y + 1 < height && (edge_h[kh] & EDGE_PATH) == 0) { uint const other_index = cells[(y + 1)*width + x]; bool const other_is_exit = (exit_path_count == 2 && (other_index == exit_path_indices[0] || other_index == exit_path_indices[1])); if ((index == other_index || (is_exit && other_is_exit)) && (edge_h[kh] & EDGE_BARRIER) == 0) { edge_h[kh] |= EDGE_BARRIER; changed = true; } } } // for cells where 2 out of 3 available edges would make a loop, add a path edge for the remaining one for (uint y = 0; y < height; ++y) for (uint x = 0; x < width; ++x) { if (cells[y*width + x] != 0) { continue; } // get adjacent edges uint *edges[4]; edges[0] = edge_h + y*width + x; edges[1] = edges[0] + width; edges[2] = edge_v + y*(width + 1) + x; edges[3] = edges[2] + 1; // get derived stuff uint available_count = 0; uint barrier_index = 0; uint barrier_count = 0; for (uint i = 0; i < 4; ++i) { uint const e = *edges[i]; if (e & EDGE_BARRIER) { ++barrier_count; barrier_index = i; } else if ((e & EDGE_PATH) == 0) { ++available_count; } } if (barrier_count != 1 || available_count != 3) { continue; } // get adjacent cells and their path index in matching order uint const *adj[4]; uint index[4]; for (int i = 0; i < 4; ++i) { uint const px = (uint)((int)x + ((i >= 2) ? (2*i - 5) : 0)); uint const py = (uint)((int)y + ((i < 2) ? (2*i - 1) : 0)); if (px < width && py < height) { adj[i] = cells + py*width + px; index[i] = *adj[i]; } else { adj[i] = NULL; index[i] = 0; } } // find two matching path ends over available edges, select the other available edge uint const offsets[] = { 1, 2, 3, 1, 2 }; uint new_index = 4; for (uint k = 0; k < 3; ++k) { uint const i0 = (barrier_index + offsets[k + 0]) % 4; uint const i1 = (barrier_index + offsets[k + 1]) % 4; uint const i2 = (barrier_index + offsets[k + 2]) % 4; if (index[i0] != 0 && index[i0] == index[i1]) { new_index = i2; break; } } // force the other edge to be a path if (new_index < 4) { *edges[new_index] |= EDGE_PATH; changed = true; if (solver->verbose) { highlights[y*width + x] = 1; for (uint i = 0; i < 4; ++i) { if (i == barrier_index || i == new_index) { continue; } if (adj[i]) { highlights[adj[i] - cells] = 1; } } } } } // add barrier to prevent early exits if (exit_path_count > 0 && exit_path_length_total < width*height) { if (exit_path_count == 1) { exit_path_indices[1] = exit_path_indices[0]; } for (uint x = 0; x < width; ++x) { uint const index0 = cells[x]; uint const index1 = cells[(height - 1)*width + x]; bool const is_exit0 = (index0 == exit_path_indices[0] || index0 == exit_path_indices[1]); bool const is_exit1 = (index1 == exit_path_indices[0] || index1 == exit_path_indices[1]); uint const k0 = x; uint const k1 = height*width + x; if (is_exit0 && (edge_h[k0] & (EDGE_BARRIER | EDGE_PATH)) == 0) { edge_h[k0] |= EDGE_BARRIER; changed = true; } if (is_exit1 && (edge_h[k1] & (EDGE_BARRIER | EDGE_PATH)) == 0) { edge_h[k1] |= EDGE_BARRIER; changed = true; } } for (uint y = 0; y < height; ++y) { uint const index0 = cells[y*width]; uint const index1 = cells[y*width + width - 1]; bool const is_exit0 = (index0 == exit_path_indices[0] || index0 == exit_path_indices[1]); bool const is_exit1 = (index1 == exit_path_indices[0] || index1 == exit_path_indices[1]); uint const k0 = y*(width + 1); uint const k1 = y*(width + 1) + width; if (is_exit0 && (edge_v[k0] & (EDGE_BARRIER | EDGE_PATH)) == 0) { edge_v[k0] |= EDGE_BARRIER; changed = true; } if (is_exit1 && (edge_v[k1] & (EDGE_BARRIER | EDGE_PATH)) == 0) { edge_v[k1] |= EDGE_BARRIER; changed = true; } } } if (solver->verbose && changed) { fputs("\navoid loops and short paths:\n", stdout); print_board(solver, board, EDGE_ALL | EDGE_HIGHLIGHT | EDGE_NEW); } return changed; } bool check_partitions(solver_t const *solver, board_t const *board) { uint const width = board->width; uint const height = board->height; uint *const edge_h = board->edge_h; uint *const edge_v = board->edge_v; uint *const corners = solver->tmp1; uint *const coords = solver->tmp2; memset(corners, 0, (width + 1)*(height + 1)*sizeof(uint)); // set initial state of flood fill from boundary uint end = 0; for (uint x = 1; x < width; ++x) { corners[x] = 1; corners[height*(width + 1) + x] = 1; coords[end++] = x; coords[end++] = (height << 16) | x; } for (uint y = 1; y < height; ++y) { corners[y*(width + 1)] = 1; corners[y*(width + 1) + width] = 1; coords[end++] = (y << 16); coords[end++] = (y << 16) | width; } // do flood fill along edges uint start = 0; while (start != end) { uint const x = coords[start] & 0xffffU; uint const y = coords[start] >> 16; uint const i = y*(width + 1) + x; uint const ih = y*width + x; uint const iv = i; uint const s = width + 1; if (x > 0 && corners[i - 1] == 0 && (edge_h[ih - 1] & EDGE_BARRIER)) { corners[i - 1] = 1; coords[end++] = (y << 16) | (x - 1); } if (x < width && corners[i + 1] == 0 && (edge_h[ih] & EDGE_BARRIER)) { corners[i + 1] = 1; coords[end++] = (y << 16) | (x + 1); } if (y > 0 && corners[i - s] == 0 && (edge_v[iv - s] & EDGE_BARRIER)) { corners[i - s] = 1; coords[end++] = ((y - 1) << 16) | x; } if (y < height && corners[i + s] == 0 && (edge_v[iv] & EDGE_BARRIER)) { corners[i + s] = 1; coords[end++] = ((y + 1) << 16) | x; } ++start; } // check for barriers that would partition the board bool changed = false; for (uint y = 1; y < height; ++y) for (uint x = 0; x < width; ++x) { uint const ih = y*width + x; uint const i = y*(width + 1) + x; uint const iv = i; if ((edge_h[ih] & (EDGE_BARRIER | EDGE_PATH)) == 0 && corners[iv] && corners[iv + 1]) { edge_h[ih] |= EDGE_PATH; changed = true; } } for (uint y = 0; y < height; ++y) for (uint x = 1; x < width; ++x) { uint const i = y*(width + 1) + x; uint const iv = i; uint const s = width + 1; if ((edge_v[iv] & (EDGE_BARRIER | EDGE_PATH)) == 0 && corners[iv] && corners[iv + s]) { edge_v[iv] |= EDGE_PATH; changed = true; } } if (changed && solver->verbose) { fputs("\navoid partitioning:\n", stdout); print_board(solver, board, EDGE_ALL | EDGE_NEW); } return changed; } uint solve(solver_t const *solver, board_t const *board, bool *is_solved) { if (solver->verbose) { fputs("\ninitial conditions:\n", stdout); print_board(solver, board, EDGE_BOUNDARY); } uint step_count = 0; for (;; ++step_count) { if (solver->verbose) { copy_edges_to_solver(solver, board); } if (check_single_cells(solver, board)) { continue; } if (check_loops(solver, board, is_solved)) { continue; } if (*is_solved) { break; } if (check_partitions(solver, board)) { continue; } if (parity_check_all_block_sizes(solver, board)) { continue; } break; } return step_count; } uint harden(solver_t const *solver, board_t *board) { // check boundary locations on initial board uint const width = board->width; uint const height = board->height; uint const *const edge_h = board->edge_h; uint const *const edge_v = board->edge_v; uint *const trials = (uint *)malloc(2*(width + 1)*(height + 1)*sizeof(uint)); uint trial_count = 0; for (uint y = 0; y <= height; ++y) { for (uint x = 0; x < width; ++x) { if (edge_h[y*width + x] & EDGE_BOUNDARY) { trials[trial_count++] = (y << 16) | (x << 1); } } } for (uint y = 0; y < height; ++y) { for (uint x = 0; x <= width; ++x) { if (edge_v[y*(width + 1) + x] & EDGE_BOUNDARY) { trials[trial_count++] = (y << 16) | (x << 1) | 1; } } } // shuffle order for (uint shuffle_index = 0; shuffle_index < 1000; ++shuffle_index) { uint const i = rand() % trial_count; uint const j = rand() % trial_count; uint const tmp = trials[i]; trials[i] = trials[j]; trials[j] = tmp; } // try and remove them in this order uint success_count = 0; for (uint trial_index = 0; trial_index < trial_count; ++trial_index) { // copy existing board initial conditions board_t test; copy_board(&test, board); reset_to_boundary(&test); // knock out the edge uint const tmp = trials[trial_index]; uint const x = (tmp >> 1) & 0x7fffU; uint const y = tmp >> 16; bool const is_vertical = ((tmp & 1) != 0); if (is_vertical) { test.edge_v[y*(width + 1) + x] &= ~(EDGE_BOUNDARY | EDGE_BARRIER); } else { test.edge_h[y*width + x] &= ~(EDGE_BOUNDARY | EDGE_BARRIER); } reset_to_boundary(&test); // keep if still solveable bool is_solved = false; solve(solver, &test, &is_solved); if (is_solved) { swap_board(board, &test); ++success_count; } free_board(&test); } reset_to_boundary(board); return success_count; } int main(int argc, char *argv[]) { FILE *fp = stdin; char const *puzzle = NULL; bool verbose = false; bool try_removing_edges = false; for (int i = 1; i < argc; ++i) { if (strcmp(argv[i], "-f") == 0) { ++i; if (i < argc) { fp = fopen(argv[i], "r"); if (!fp) { fprintf(stderr, "failed to open \"%s\" for reading!\n", argv[i]); return -1; } } } else if (strcmp(argv[i], "-v") == 0) { verbose = true; } else if (strcmp(argv[i], "-r") == 0) { try_removing_edges = true; } else { fprintf(stderr, "unknown option \"%s\"!\n", argv[i]); return -1; } } // read in a test level board_t board; if (!scan_board(&board, fp)) { return -1; } // set up solver solver_t solver; init_solver(&solver, &board); if (puzzle) { if (verbose) { fputs("\ndecoded puzzle:\n", stdout); print_board(&solver, &board, EDGE_ALL); } reset_to_boundary(&board); } // try to optimise if (try_removing_edges) { uint const success_count = harden(&solver, &board); printf("removed %d edges!\n", success_count); } // iterate until solved or not progressing solver.verbose = verbose; bool is_solved = false; uint step_count = solve(&solver, &board, &is_solved); printf("\n%s after %d steps!\n", is_solved ? "solved" : "given up", step_count); print_board(&solver, &board, EDGE_SOLUTION); return 0; }
C
#include <stdio.h> #include <stdarg.h> #include <stdlib.h> #include <string.h> #include "common.h" int delta( CASA tab1[8][8], CASA tab2[8][8]) { int diferentes = 0; FORVN(L, 8) FORVN(C, 8) { CASA fst = tab1[L][C]; CASA snd = tab2[L][C]; if(fst != snd) { if( (vazia(fst) && snd == BRANCA) || (fst == BRANCA && snd == PRETA) ) diferentes ++; else return 0; } } return diferentes == 2; } int main(int argc, char **argv) { CASA tab1[8][8]; CASA tab2[8][8]; char ultima[3]; char *movs[64]; int num_movs = 0; if(argc != 3) { printf("Uso %s <tabuleiro a ler> <tabuleiro a escrever>\n", argv[0]); return 0; } if( testar(ler(argv[1], tab1, ultima, movs, &num_movs), "Não consegui ler o tabuleiro %s\n", argv[1]) && testar(ler(argv[2], tab2, ultima, movs, &num_movs), "Não consegui ler o tabuleiro %s\n", argv[2]) && testar(delta(tab1, tab2), "O tabuleiro %s não corresponde a uma jogada depois do tabuleiro %s\n", argv[2], argv[1])) return 0; else return 1; }
C
void convert_double(double *number) { double fraction; *number = *number / (double)100; fraction = *number - (int)*number; fraction /= 0.6; *number = (int)*number + fraction; }
C
// // main.c // exe1 // // Created by НУРИЯ on 9/8/20. // Copyright © 2020 НУРИЯ. All rights reserved. // Nuriya Umirbekova exe1 #define _XOPEN_SOURCE 600 #include <stdio.h> #include <sys/types.h> #include <stdlib.h> int main() { int n=10; pid_t pid=fork(); for (int i=0; i<=n; ++i){ if (pid>0){ //parent printf("Hello from parent [%d - %d]\n", getpid(), i); } else if (pid==0) { //child printf("Hello from child [%d - %d]\n", getpid(), i); } else { return EXIT_FAILURE; } } return 0; } //from running this code several times we can see that "parent" and "child" are shuffled //If the parent process exits after the child process, the result will be as expected. //If the parent process exits before the child process, the output may be unexpected (before the parent no longer exists, the parent's ID will be different).
C
#include "LCD.h" #include "wiringPi.h" #include "LCD-RBPI.h" struct lcd_io * io; BYTE lcd_ioinit( void * iodata ) { int i = 0; BYTE iomode = 4; io= (struct lcd_io *)iodata; // Check if control signals have their pins defined if( io->rspin == 0 || io->epin == 0) return 0; pinMode (io->rspin, OUTPUT); pinMode (io->epin, OUTPUT); if( io->d4pin != 0, io->d5pin != 0, io->d6pin != 0, io->d7pin != 0) { pinMode (io->d4pin, OUTPUT); pinMode (io->d5pin, OUTPUT); pinMode (io->d6pin, OUTPUT); pinMode (io->d7pin, OUTPUT); if( io->d0pin != 0, io->d1pin != 0, io->d2pin != 0, io->d3pin != 0) { pinMode (io->d0pin, OUTPUT); pinMode (io->d1pin, OUTPUT); pinMode (io->d2pin, OUTPUT); pinMode (io->d3pin, OUTPUT); iomode = 8; } } else // at least the high nibble of the data bus should be defined return 0; // Set all the pins to "low" state for( i = 0; i < 11; i++ ) lcd_ioset( i, FALSE ); return iomode; } void lcd_ioset( enum enLCDControlPins pin, BOOL out ) { switch( pin ) { case E_D0_PIN: digitalWrite(io->d0pin,out); break; case E_D1_PIN: digitalWrite(io->d1pin,out); break; case E_D2_PIN: digitalWrite(io->d2pin,out); break; case E_D3_PIN: digitalWrite(io->d3pin,out); break; case E_D4_PIN: digitalWrite(io->d4pin,out); break; case E_D5_PIN: digitalWrite(io->d5pin,out); break; case E_D6_PIN: digitalWrite(io->d6pin,out); break; case E_D7_PIN: digitalWrite(io->d7pin,out); break; case E_RS_PIN: digitalWrite(io->rspin,out); break; case E_EN_PIN: digitalWrite(io->epin,out); break; case E_RW_PIN: digitalWrite(io->wrpin,out); break; } } void lcd_iowrite4( BYTE data ) { BYTE i; for( i = 4; i < 8; i++ ) lcd_ioset( i, ( data & ( 1 << i - 4 ) ) ? TRUE : FALSE ); lcd_iohigh( E_EN_PIN ); delay_us( 10 ); lcd_iolow( E_EN_PIN ); } void lcd_iowrite8( BYTE data ) { BYTE i; for( i = 0; i < 8; i++ ) lcd_ioset( i, ( data & ( 1 << i ) ) ? TRUE : FALSE ); lcd_iohigh( E_EN_PIN ); delay_us( 10 ); lcd_iolow( E_EN_PIN ); }
C
#include <stdio.h> int main() { int n; float avg; scanf("%d", &n); int num, sum = 0,i; for(i = 0; i < n; i++) { scanf("%d", &num); sum += num; } avg = (float)sum / n; printf("Sum: %d\n", sum); printf("Avg: %.2f\n", avg); return 0; }
C
#include<stdio.h> typedef struct student{ int rno; char nm[15]; }stu; stu a[10]; //hash table void init(){ for(int i=0;i<10;i++) a[i].rno=0; } int hash(int no){ return no%10; } void insert(){ int i=0,j=0,no; printf("\nRoll No :"); scanf("%d",&no); i=hash(no); if(a[i].rno==0){ //check if home address is empty a[i].rno=no; printf("\nEnter Name :");scanf("%s",a[i].nm); printf("\nINSERTION AT HOME ADDRESS.");return; } printf("\nCOLLISON OCCURED."); for(j=i+1;j<10;j++){ //checking ahead in array if(a[j].rno==0){ a[j].rno=no; printf("\nEnter Name :");scanf("%s",a[j].nm); break; } } if(j<10){ printf("\nInsertion on Collision Path.");return; } for(j=0;j<i;j++){ //checking from starting if(a[j].rno==0){ a[j].rno=no; printf("\nEnter Name :");scanf("%s",a[j].nm); break; } } if(j==i){ printf("\n< OVERFLOW >."); } else printf("\n INSERTION on Collision path."); } void search(){ int i=0,j=0,no; printf("\nEnter Value to be searched :");scanf("%d",&no); i=hash(no); if(a[i].rno==no){ printf("\nFOUND NAME at Home Address %d:%s",i,a[i].nm); return; } printf("\nSearching on Collision Path ..."); for(j=i+1;j<10;j++){ if(a[j].rno==no){ printf("\n FOUND ON COLLISON PATH AT %d",j); printf("\nNAME :%s",a[j].nm);return; } } for(j=0;j<i;j++){ if(a[j].rno==no){ printf("\n FOUND ON COLLISON PATH AT %d",j); printf("\nNAME :%s",a[j].nm);return; } } printf("\n<NOT FOUND >"); } int main(){ int opt; init(); while(1){ printf("\n1.Insert \n2 search \nOption :"); scanf("%d",&opt); if(opt==1) insert(); else if(opt==2) search(); else break; } }
C
/* ** EPITECH PROJECT, 2018 ** CPool_2018 ** File description: ** Maxence Carpentier */ #include "my.h" #include <stdlib.h> char *my_revnumber(char *str) { int i2 = my_strlen(str) - 1; char c; for (int i = 1; i < i2; i++) { c = str[i]; str[i] = str[i2]; str[i2] = c; i2--; } return (str); } char *my_converter(int nb, char *base_to, char *str, int saver) { int counter = 0; if (str == NULL) { for (int i = nb; i != 0; i /= 10) counter++; str = malloc(sizeof(char) * counter); } if (nb < 0) { str[saver] = '-'; saver++; my_converter(-nb, base_to, str, saver); } else if (nb > 0) { str[saver] = base_to[nb % 10]; saver++; my_converter(nb / 10, base_to, str, saver); } return (str); } int char_to_int(char c) { if (c >= '0' && c <= '9') return (c - '0'); else return (c - 'A' + 10); } char *make_tmp(char *nbr, char *base_from, int start_base) { int counter = 0; char *tmp = malloc(sizeof(char) * start_base); for (int i = 0; nbr[i] != '\0'; i++) { if (i == 0 && nbr[0] == '-') { tmp[0] = '-'; counter++; } for (int j = 0; base_from[j] != '\0'; j++) if (base_from[j] == nbr[i]) { tmp[counter] = j + '0'; counter++; } } return (tmp); } char *convert_base(char const *nbr, char const *base_from, char const *base_to) { int start_base = my_strlen(base_from); char *tmp = make_tmp(nbr, base_from, start_base); int to_convert; char *res; to_convert = from_base_to_deci(my_getnbr(tmp), start_base); to_convert = from_deci_to_base(to_convert, my_strlen(base_to)); res = my_converter(to_convert, base_to, res, 0); return (my_revnumber(res)); }
C
#include <stdio.h> #include <stdlib.h> #include <stdint.h> // int8_t, etc., intmax_t , uintmax_t, #include <inttypes.h> // uint8_t, ..., uintmax_t i = UINTMAX_MAX; // this type always exists #include <stddef.h> // offsetof(type, member-designator) #include <stdio.h> // remove, int rename(const char *old, const char *new); , #include <stdarg.h> #include <string.h> #include <assert.h> #include <math.h> // cosf, ..., int signbit(real-floating x); , isnormal(neither zero, subnormal, infinite, nor NaN)., int isnan(real-floating x); , int isinf(real-floating x); int isfinite(real-floating x); #include <ctype.h> // tolower, toupper #include <assert.h> // dépend de la valeur de la macro NDEBUG #ifndef __TINYC__ // For some reasons, TCC fails to read this file. #include <complex.h> // types «complex», «double complex», «long double complex», «float complex» #endif #include <ctype.h> #include <errno.h> #include <float.h> // limits #include <iso646.h> // Alternative spellings: and &&, xor ^, etc. #include <limits.h> #include <setjmp.h> #include <signal.h> #include <time.h> // clock & time --- #ifndef __PCC__ // For some reasons, PCC fails to read these files. #include <wchar.h> #include <wctype.h> #endif #include <locale.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <time.h> // time_t, time(), ctime() ; ("man 3 time") donne la date d'ajd #ifndef ctime_r # define ctime_r(a,b) ((b == NULL ? 0 : strcpy(b, "FAILED ")), *a = time(NULL), ctime(a)) #endif enum bool {true = (0 == 0), false = (0 != 0)}; typedef enum bool bool; static char * string_replace(const char * text, const char * old_str, const char * new_str); static int nb_occurrences(const char * text, const char * old_str); int main(const int argc, const char * argv[]) { if (4 != argc) { printf("usage: %s working-string old-str new-str\n", argv[0]); return -1; } char * contenu_filtre; contenu_filtre = string_replace(argv[1], argv[2], argv[3]); printf("%s\n", contenu_filtre); free(contenu_filtre); return 0; } char * string_replace(const char * text, const char * old_str, const char * new_str) { const size_t text_len = strlen(text); const size_t old_str_len = strlen(old_str); const size_t new_str_len = strlen(new_str); const int nb_occ = nb_occurrences(text, old_str); const size_t new_len = text_len + nb_occ * (new_str_len - old_str_len); #if 0 fprintf(stderr, "nb occ: %d\n", nb_occ); printf("old len: %lu\n", old_str_len); printf("new len: %lu\n", new_str_len); printf("text len: %lu\n", text_len); printf("new len: %lu\n", new_len); #endif char * nv_text = (char *) malloc((new_len + 1) * (sizeof (char))); nv_text[new_len] = '\0'; const char c = old_str[0]; size_t old_pos = 0; size_t new_pos = 0; while (text[old_pos] != '\0') { if ((text[old_pos] == c) && ((text_len - old_pos) >= old_str_len) && (0 == memcmp(&(text[old_pos]), old_str, old_str_len))) { memcpy(nv_text + new_pos, new_str, new_str_len); new_pos += new_str_len; //text += old_str_len; old_pos += old_str_len; } else { nv_text[new_pos] = text[old_pos]; new_pos++; old_pos++; } assert(new_pos <= new_len); assert(old_pos <= text_len); } assert(new_pos == new_len); nv_text[new_pos] = '\0'; return nv_text; } int nb_occurrences(const char * text, const char * old_str) { const size_t text_len = strlen(text); const size_t len = strlen(old_str); const char c = old_str[0]; int nb = 0; size_t pos = 0; while (text[pos] != '\0') { if ((text[pos] == c) && ((text_len - pos) >= len) && (0 == memcmp(&(text[pos]), old_str, len))) { nb++; pos += len; } else { pos++; } } assert(pos == text_len); return nb; }
C
#include <stdio.h> #include <stdlib.h> float get_pi(int N){ //Monte Carlo method of calculating pi the argument is the number of samples to use. int pi=0,n=0; float x,y; while(n<N){ x=((float)rand())/((float)RAND_MAX); y=((float)rand())/((float)RAND_MAX); ++n; if(x*x+y*y<=1.0){ ++pi; } } return 4.0*((float)pi)/((float)n); } int main(int argc,char *argv[]){ int N; sscanf(argv[1],"%d",&N); printf("%f\n",get_pi(N)); return 0; }
C
/* 루트가 0인 이진트리가 주어질 때, 이를 전위순회, 중위순회, 후위순회한 결과를 각각 출력하는 프로그램을 작성하시오. 아래 그림은 이진트리의 예제와, 이 이진트리를 전위순회, 중위순회, 후위순회 한 결과를 나타낸다. 입력 첫 번째 줄에 트리의 노드 개수 n이 주어진다. ( 1 ≤ n ≤ 100 ) 두 번째 줄부터 트리의 정보가 주어진다. 각 줄은 3개의 숫자 a, b, c로 이루어지며, 그 의미는 노드 a의 왼쪽 자식노드가 b, 오른쪽 자식노드가 c라는 뜻이다. 자식노드가 존재하지 않을 경우에는 -1이 주어진다. 출력 첫 번째 줄에 전위순회, 두 번째 줄에 중위순회, 세 번째 줄에 후위순회를 한 결과를 출력한다. 예제 입력 6 0 1 2 1 3 4 2 -1 5 3 -1 -1 4 -1 -1 5 -1 -1 예제 출력 0 1 3 4 2 5 3 1 4 0 2 5 3 4 1 5 2 0 */ #include <stdio.h> const int MAX = 100; struct Tree{ int left; int right; }; Tree tree[MAX]; void preorder(int x); void inorder(int x); void postorder(int x); int main() { int n; scanf("%d",&n); for(int i=0;i<n;i++){ int a,b,c; scanf("%d %d %d",&a,&b,&c); tree[a].left = b; tree[a].right = c; } preorder(0); printf("\n"); inorder(0); printf("\n"); postorder(0); return 0; } void inorder(int x) { if(tree[x].left == -1 && tree[x].right == -1){ printf("%d ",x); }else{ if(tree[x].left!=-1) inorder(tree[x].left); printf("%d ",x); if(tree[x].right!=-1) inorder(tree[x].right); } } void postorder(int x) { if(x == -1 && tree[x].right == -1){ printf("%d ",x); }else{ if(tree[x].left!=-1) postorder(tree[x].left); if(tree[x].right!=-1){ postorder(tree[x].right); } printf("%d ",x); } } void preorder(int x) { if(tree[x].left == -1 && tree[x].right == -1){ printf("%d ",x); }else{ printf("%d ",x); if(tree[x].left!=-1){ preorder(tree[x].left); } if(tree[x].right!=-1){ preorder(tree[x].right); } } }
C
#include <stdio.h> int main(void) { int x; printf("x = "); scanf("%d", &x); printf("the value of (3x^5 + 2x^4 - 5x^3 - x^2 + 7x - 6) = %d\n", ((((((((((3 * x) + 2) * x) - 5) * x) - 1) * x) + 7) * x) - (6))); return 0; }
C
//#include<stdio.h> //int main() //{ //// printf("\\" "\"Diptendu Karmakar\"\" "); // printf("\%cdiptendu karmakar\%c%c",'"','"','"'); // return 0; //} //#include <stdio.h> //int main() //{ // printf("%c%c%s%c%c",'\\','"',"your_name\\",'"','"'); // return 0; //} //#include <stdio.h> //int main() //{ // printf("%c%c",'%','d'); //} #include <stdio.h> int main() { printf("%c%s%c",'"',"your_name",'"'); return 0; }
C
#include "bsp.h" #ifdef KEY_ANFULAI static key_t s_tbtn[KEY_COUNT]; static key_fifo_t s_tkey; /* FIFO ,ṹ */ /* GPIOPIN */ static const x_gpio_t s_gpio_list[HARD_KEY_NUM] = { {KEY1_PORT, KEY1_PIN, 0}, /* K1 */ {KEY2_PORT, KEY2_PIN, 0}, /* K2 */ }; /* ********************************************************************************************************* FIFO ********************************************************************************************************* */ /* ********************************************************************************************************* * : bsp_putkey_fifo * ˵: 1 ֵѹ밴 FIFO ģһ * : _KeyCode : * ֵ: ********************************************************************************************************* */ void bsp_putkey_fifo(uint8_t keycode) { s_tkey.buf[s_tkey.write] = keycode; if(++s_tkey.write >= KEY_FIFO_SIZE) { s_tkey.write = 0; } } /* ********************************************************************************************************* * : bsp_GetKeyState * ˵: ȡ״̬ * : _ucKeyID : ID0ʼ * ֵ: 1 ʾ£ 0 ʾδ ********************************************************************************************************* */ uint8_t bsp_getkey_state(KEY_ID_E _ucKeyID) { return s_tbtn[_ucKeyID].state; } /* ********************************************************************************************************* * : bsp_GetKey * ˵: Ӱ FIFO ȡһֵ * : * ֵ: ********************************************************************************************************* */ uint8_t bsp_getkey(void) { uint8_t ret; if(s_tkey.read == s_tkey.write) { return KEY_NONE; } else { ret = s_tkey.buf[s_tkey.read]; if(++s_tkey.read >= KEY_FIFO_SIZE) { s_tkey.read = 0; } return ret; } } /* ********************************************************************************************************* * : bsp_GetKey2 * ˵: Ӱ FIFO ȡһֵ * : * ֵ: ********************************************************************************************************* */ uint8_t bsp_getkey2(void) { uint8_t ret; if(s_tkey.read2 == s_tkey.write) { return KEY_NONE; } else { ret = s_tkey.buf[s_tkey.read2]; if(++s_tkey.read2 >= KEY_FIFO_SIZE) { s_tkey.read2 = 0; } return ret; } } /* ********************************************************************************************************* * : bsp_ClearKey * ˵: հFIFO * Σ * ֵ: ********************************************************************************************************* */ void bsp_clearkey(void) { s_tkey.read = s_tkey.write; } /******************************************************************************************************** *********************************************************************************************************/ /* ********************************************************************************************************* * : bsp_SetKeyParam * ˵: ð * _uckeyid : ID0ʼ * _longtime : ¼ʱ * _repeatspeed : ٶ * ֵ: ********************************************************************************************************* */ void bsp_setkeyparam(uint8_t _uckeyid, uint16_t _longtime, uint8_t _repeatspeed) { s_tbtn[_uckeyid].longtime = _longtime; /* ʱ 0 ʾⳤ¼ */ s_tbtn[_uckeyid].repeatspeed = _repeatspeed; /* ٶȣ0ʾ֧ */ s_tbtn[_uckeyid].repeatcount = 0; /* */ } /* ********************************************************************************************************* * : bsp_initkey_hard * ˵: ðӦGPIO * : * ֵ: ********************************************************************************************************* */ static void bsp_initkey_hard(void) { gpio_init_t gpio_init; uint8_t i = 0; /* еİGPIO */ gpio_init.mode = GPIO_MODE_INPUT; gpio_init.odos = GPIO_PUSH_PULL; gpio_init.pupd = GPIO_PUSH_UP; gpio_init.odrv = GPIO_OUT_DRIVE_NORMAL; gpio_init.flt = GPIO_FILTER_DISABLE; gpio_init.type = GPIO_TYPE_CMOS; gpio_init.func = GPIO_FUNC_1; for (i = 0; i < HARD_KEY_NUM; i++) { ald_gpio_init(s_gpio_list[i].gpio,s_gpio_list[i].pin, &gpio_init); } } /* ********************************************************************************************************* * : bsp_initkeyvar * ˵: ʼ * : * ֵ: ********************************************************************************************************* */ static void bsp_initkeyvar(void) { uint8_t i; /* ԰FIFOдָ */ s_tkey.read = 0; s_tkey.write = 0; s_tkey.read2 = 0; /* ÿṹԱһȱʡֵ */ for (i = 0; i < KEY_COUNT; i++) { s_tbtn[i].longtime = KEY_LONG_TIME; /* ʱ 0 ʾⳤ¼ */ s_tbtn[i].count = KEY_FILTER_TIME / 2; /* Ϊ˲ʱһ */ s_tbtn[i].state = 0; /* ȱʡ״̬0Ϊδ */ s_tbtn[i].repeatspeed = 0; /* ٶȣ0ʾ֧ */ s_tbtn[i].repeatcount = 0; /* */ } /* ҪijIJڴ˵¸ֵ */ /* ҡңֳ֧1Զ */ // bsp_setkeyparam(KID_JOY_U, 100, 6); // bsp_setkeyparam(KID_JOY_D, 100, 6); // bsp_setkeyparam(KID_JOY_L, 100, 6); // bsp_setkeyparam(KID_JOY_R, 100, 6); } /* ********************************************************************************************************* * : bsp_initkey * ˵: ʼ. ú bsp_Init() á * : * ֵ: ********************************************************************************************************* */ void bsp_initkey(void) { bsp_initkeyvar(); /* ʼ */ bsp_initkey_hard(); /* ʼӲ */ } /* ********************************************************************************************************* * : keypin_active * ˵: жϰǷ * : * ֵ: ֵ1 ʾ(ͨ0ʾδ£ͷţ ********************************************************************************************************* */ static uint8_t keypin_active(uint8_t _id) { uint8_t level; if ((s_gpio_list[_id].gpio->DIN & s_gpio_list[_id].pin) == BIT_RESET) { level = 0; } else { level = 1; } if (level == s_gpio_list[_id].activelevel) { return 1; } else { return 0; } } /* ********************************************************************************************************* * : iskeydownfunc * ˵: жϰǷ¡ϼ֡¼¡ * : * ֵ: ֵ1 ʾ(ͨ0ʾδ£ͷţ ********************************************************************************************************* */ static uint8_t iskeydownfunc(uint8_t id) { uint8_t i = 0; uint8_t count = 0; uint8_t save = 255; if(id < HARD_KEY_NUM) { for(i = 0;i < HARD_KEY_NUM;i++) { if(keypin_active(i)) { count++; save = i; } } if(count == 1 && save == id) { return 1; /* ֻ1ʱЧ */ } return 0; } /* ϼ K1K2 */ if (id == HARD_KEY_NUM + 0) { if (keypin_active(KID_K1) && keypin_active(KID_K2)) { return 1; } else { return 0; } } return 0; } /* ********************************************************************************************************* * : bsp_DetectKey * ˵: һ״̬뱻Եĵá * : IOid 0ʼ * ֵ: ********************************************************************************************************* */ static void bsp_detectkey(uint8_t i) { key_t *pbtn; pbtn = &s_tbtn[i]; if(iskeydownfunc(i)) { if(pbtn->count < KEY_FILTER_TIME) pbtn->count = KEY_FILTER_TIME; else if(pbtn->count < 2 * KEY_FILTER_TIME) pbtn->count++; else { /* ̰ */ if(pbtn->state == 0) { pbtn->state = 1; /* ͰťµϢ */ bsp_putkey_fifo((uint8_t)(3 * i + 1)); } /* */ if(pbtn->longtime > 0) { if(pbtn->longcount < pbtn->longtime) { /* ͰťµϢ */ if (++pbtn->longcount == pbtn->longtime) { /* ֵ밴FIFO */ bsp_putkey_fifo((uint8_t)(3 * i + 3)); } } else { if (pbtn->repeatspeed > 0) { if (++pbtn->repeatcount >= pbtn->repeatspeed) { pbtn->repeatcount = 0; /* ÿ10ms1 */ bsp_putkey_fifo((uint8_t)(3 * i + 1)); } } } } } } else { if(pbtn->count > KEY_FILTER_TIME) { pbtn->count = KEY_FILTER_TIME; } else if(pbtn->count != 0) { pbtn->count--; } else { if (pbtn->state == 1) { pbtn->state = 0; /* ͰťϢ */ bsp_putkey_fifo((uint8_t)(3 * i + 2)); } } pbtn->longcount = 0; pbtn->repeatcount = 0; } } /* ********************************************************************************************************* * : bsp_KeyScan10ms * ˵: ɨаsystickжԵĵã10msһ * : * ֵ: ********************************************************************************************************* */ void bsp_keyscan10ms(void) { uint8_t i; for(i = 0;i < KEY_COUNT;i++) bsp_detectkey(i); } /* ********************************************************************************************************* * : bsp_detect_fastIO * ˵: ٵIO. 1msˢһ * : IOid 0ʼ * ֵ: ********************************************************************************************************* */ static void bsp_detect_fastIO(uint8_t i) { key_t *pbtn; pbtn = &s_tbtn[i]; if (iskeydownfunc(i)) { if (pbtn->state == 0) { pbtn->state = 1; /* ͰťµϢ */ bsp_putkey_fifo((uint8_t)(3 * i + 1)); } if (pbtn->longtime > 0) { if (pbtn->longcount < pbtn->longtime) { /* ͰťµϢ */ if (++pbtn->longcount == pbtn->longtime) { /* ֵ밴FIFO */ bsp_putkey_fifo((uint8_t)(3 * i + 3)); } } else { if (pbtn->repeatspeed > 0) { if (++pbtn->repeatcount >= pbtn->repeatspeed) { pbtn->repeatcount = 0; /* ÿ10ms1 */ bsp_putkey_fifo((uint8_t)(3 * i + 1)); } } } } } else { if (pbtn->state == 1) { pbtn->state = 0; /* ͰťϢ */ bsp_putkey_fifo((uint8_t)(3 * i + 2)); } pbtn->longcount = 0; pbtn->repeatcount = 0; } } /* ********************************************************************************************************* * : bsp_KeyScan1ms * ˵: ɨаsystickжԵĵã1msһ. * : * ֵ: ********************************************************************************************************* */ void bsp_KeyScan1ms(void) { uint8_t i; for (i = 0; i < KEY_COUNT; i++) { bsp_detect_fastIO(i); } } #else void bsp_initkey(void) { gpio_init_t gpio_init; exti_init_t exti_init; /* Initialize key exti pin as input */ gpio_init.mode = GPIO_MODE_INPUT; gpio_init.odos = GPIO_PUSH_PULL; gpio_init.pupd = GPIO_PUSH_UP; gpio_init.odrv = GPIO_OUT_DRIVE_NORMAL; gpio_init.flt = GPIO_FILTER_DISABLE; gpio_init.type = GPIO_TYPE_CMOS; gpio_init.func = GPIO_FUNC_1; ald_gpio_init(GPIOF, GPIO_PIN_0, &gpio_init); ald_gpio_init(GPIOF, GPIO_PIN_1, &gpio_init); /* Initialize external interrupt */ exti_init.filter = ENABLE; exti_init.cks = EXTI_FILTER_CLOCK_10K; exti_init.filter_time = 10; ald_gpio_exti_init(GPIOF, GPIO_PIN_0, &exti_init); ald_gpio_exti_init(GPIOF, GPIO_PIN_1, &exti_init); /* Clear interrupt flag */ ald_gpio_exti_clear_flag_status(GPIO_PIN_0); ald_gpio_exti_clear_flag_status(GPIO_PIN_1); /* Configure interrupt */ ald_gpio_exti_interrupt_config(GPIO_PIN_0, EXTI_TRIGGER_TRAILING_EDGE, ENABLE); ald_gpio_exti_interrupt_config(GPIO_PIN_1, EXTI_TRIGGER_TRAILING_EDGE, ENABLE); ald_mcu_irq_config(EXTI0_3_IRQn, 3, ENABLE); } #endif
C
/* ** EPITECH PROJECT, 2017 ** bootstrap my _ls ** File description: ** create list */ #include "my.h" #include "header_LS.h" #include <stdio.h> int comparaison(linked_list_t *buffer, linked_list_t *list); linked_list_t *search_greater(linked_list_t *list) { linked_list_t *buffer; buffer = list; list = list->next; while (list != NULL){ if (comparaison(buffer, list) == 2) buffer = list; list = list->next; } return (buffer); } void stock_new_list(linked_list_t **listt, linked_list_t *new, linked_list_t *buffer) { linked_list_t *list = *listt; while (new->next != NULL) new = new->next; if (list == buffer) { list = list->next; buffer->next = NULL; new->next = buffer; *listt = list; } else { while (list->next != buffer) list = list->next; list->next = list->next->next; new->next = buffer; buffer->next = NULL; } } linked_list_t *sort_list_alpha(linked_list_t *list) { linked_list_t *new = init_new_list(&list); linked_list_t *buffer; while (list != NULL) { buffer = search_greater(list); stock_new_list(&list, new, buffer); } return (new); }
C
/* ** EPITECH PROJECT, 2020 ** cpday09 ** File description: ** my.h */ #include <stdbool.h> #include <stddef.h> #include <stdarg.h> #include <stdbool.h> #ifndef MY_H #define MY_H #define CTOI(x) ((x) - '0') #define ITOC(x) ((x) + '0') #define GETBIG(x, y) (((x) < (y)) ? (y) : (x)) #define GETLOW(x, y) (((x) < (y)) ? (x) : (y)) #define ABS(value) ((value < 0) ? (-value) : (value)) #define EVAL_SUM(value) (number(value) + number(value)) #define EVAL_SUB(value) (number(value) - number(value)) #define EVAL_MUL(value) (number(value) * number(value)) #define EVAL_DIV(value) (number(value) / number(value)) #define EVAL_MOD(value) (number(value) % number(value)) #define CHAR_IS_NUM(c) (('0' <= (c) && (c) <= '9') ? (1) : (0)) #define CHAR_IS_ALPHALO(c) (((c) - 'a') <= ('z' - 'a') ? (1) : (0)) #define CHAR_IS_ALPHAUP(c) (((c) - 'A') <= ('Z' - 'A') ? (1) : (0)) #define CHAR_IS_ALPHA(c) (CHAR_IS_ALPHALO(c) || CHAR_IS_ALPHAUP(c)) #define CHAR_IS_ALPHANUM(c) (CHAR_IS_ALPHA(c) || CHAR_IS_NUM(c)) void my_put_nbr_base_ul(unsigned long int nb, const char *base); void my_put_nbr_base(unsigned int nb, const char *base); void my_put_nbr_bin(int nb); void my_put_nbr_un(unsigned int nb); void my_put_nbr_ul(unsigned long int nb); void my_put_nbr_unhex(unsigned int nb, bool maj, int neg); char *my_itoa(int nb); unsigned int my_itooct(unsigned int nb); unsigned long int my_u_itooct(unsigned long int nb); char *my_revstr_neg(char *str); char *rev_av(char *str); char *ret_malloc(char *s1, char *s2); bool my_str_is_numop(char *str); char calc_add(int *rtn, char b, char c); char *calc_neg_man(char *ret, char *s1, char *s2); char *calc_add_man(char *ret, char *s1, char *s2); char *infinadd_man(char *s1, char *s2); int my_compute_power_rec(int nb, int p); int my_compute_square_root(int nb); int my_is_prime(int nb); int my_find_prime_sup(int nb); int my_intlen(int nb); int my_u_intlen(unsigned int nb); int my_strlen(char const *str); int get_nbr_check(char const *str); int my_getnbr(char const *str); int my_isneg(int nb); int my_is_prio(char c); int my_showmem(char const *str, int size); int my_showstr(char const *str); int my_putchar(char c); void my_putstr(char const *str); char *my_revstr(char *str); void my_put_nbr(int nb); void my_sort_int_array(int *array, int size); void my_swap(int *a, int *b); char *my_strdup(char const *src); char *my_strcpy(char *dest, char const *src); char *my_strncpy(char *dest, char const *src, int n); char *my_strcat(char *dest, char const *src); char *my_strncat(char *dest, char const *src, int nb); char *my_strupcase(char *str); char *my_strlowcase(char *str); int my_strcmp(char const *s1, char const *s2); int my_strncmp(char const *s1, char const *s2, int n); int my_str_isalpha(char const *str); int my_str_isnum(char const *str); int my_is_alphanum(char c); int my_str_islower(char const *str); int my_str_isupper(char const *str); int my_str_isprintable(char const *str); int my_is_operator(char c); char *my_strcapitalize(char *str); char *my_strstr(char *str, char const *to_find); char *concat_params(int ac, char **av); int my_show_word_array(char * const * tab); char **my_str_to_word_array(char const *str); char *my_strdup(char const *src); #endif /* MY_H */
C
#include <icone.h> #include <stdio.h> #include <math.h> #include <dobble-config.h> #include <stdlib.h> #define MAX_SPEED 5 int estDansIcone(Icone I, Vect2 centreCarte, Vect2 posClic){ int dedans=0; // Si la distance entre posClic et centreCarte est inférieure au rayon de la carte, c'est qu'on a cliqué dedans if (distanceSquaredBetween(addVect2(I.position, centreCarte), posClic) < pow(I.scale * ICON_SIZE / 2, 2)){ dedans=1; } return dedans; } Icone nouvelIcone() { Icone icone; icone.image = 0; icone.position = newVect2Zero(); icone.speed = newVect2Zero(); icone.acceleration = newVect2Zero(); return icone; } void positionAleatoire(Icone* icone, int nbIcones, int i, int offset) { // Calcul en complexe car plus facile pour répartir équitablement autour du cercle float distance = rand() % CARD_RADIUS; float angle = 2 * M_PI * i / nbIcones; // Réparti équitablement autour du cercle // Conversion en cartésien icone -> position = newVect2(distance * cos(angle + offset),\ distance * sin(angle + offset)); } void scaleAleatoire(Icone* icone, int nbIcones) { // Un scale aléatoire qui varie en fonction du nombre d'icones : // Entre 0.5 et 1 pour 10 icones // Entre 1.2 et 1.7 pour 3 icones icone -> scale = (((float)rand())/((float) RAND_MAX))/2 + (0.5+(10-nbIcones)*0.1); } void rotationAleatoire(Icone* icone) { // Une rotation aléatoire entre 0 et 360 icone -> rotation = ((float)rand())/((float) RAND_MAX) * 360; }
C
#include <stdio.h> #include <stdarg.h> #include <string.h> #include <pb-tools/api.h> #include <pb-tools/wire.h> #include <pb-tools/usb.h> #include <pb-tools/socket.h> #include "tool.h" int pb_debug(struct pb_context *ctx, int level, const char *fmt, ...) { (void) ctx; va_list args; if (pb_get_verbosity() >= level) { va_start(args, fmt); if (level == 0) vfprintf(stderr, fmt, args); else vprintf(fmt, args); va_end(args); } return PB_RESULT_OK; } int transport_init_helper(struct pb_context **ctxp, const char *transport_name, const char *device_uuid) { int rc; char *t = (char *) transport_name; if (!t) t = (char *) "usb"; if (pb_get_verbosity() > 2) printf("Initializing transport: %s\n", t); struct pb_context *ctx = NULL; rc = pb_api_create_context(&ctx, pb_debug); if (rc != PB_RESULT_OK) return rc; *ctxp = ctx; if (strcmp(t, "usb") == 0) { rc = pb_usb_transport_init(ctx, device_uuid); } else if (strcmp(t, "socket") == 0) { #if PB_TOOLS_BUILD_SOCKET == 1 if (pb_get_verbosity() > 2) printf("Connecting to /tmp/pb.sock\n"); rc = pb_socket_transport_init(ctx, "/tmp/pb.sock"); #else fprintf(stderr, "Error: Socket support not built-in\n"); rc = -PB_RESULT_NOT_SUPPORTED; #endif } if (rc != PB_RESULT_OK) fprintf(stderr, "Error: Could not initialize transport\n"); return rc; } int bytes_to_string(size_t bytes, char *out, size_t size) { if (bytes > 1024*1024) snprintf(out, size, "%-4zu MB", bytes / (1024*1024)); else if (bytes > 1024) snprintf(out, size, "%-4zu kB", bytes / 1024); else snprintf(out, size, "%-4zu B ", bytes); return PB_RESULT_OK; }
C
/* Generic 7-segment 4-digit LED display driver. Takes a whole 16-line GPIO bank. */ /* COM0-7 are MSD to LSD. SEG 7 is DP, 6-0 is a to g. */ #include <stdbool.h> #include <libopencm3/stm32/gpio.h> #include <libopencm3/stm32/rcc.h> #include "disp.h" /* #define DISP_GPIO_BANK GPIOA #define DISP_PIN_COM0 9 #define DISP_PIN_COM1 10 #define DISP_PIN_COM2 13 #define DISP_PIN_COM3 14 #define DISP_COM_ANODE #define DISP_DUTY 100 // Additional dimming */ #define DISP_COM_0 (1 << DISP_PIN_COM0) #define DISP_COM_1 (1 << DISP_PIN_COM1) #define DISP_COM_2 (1 << DISP_PIN_COM2) #define DISP_COM_3 (1 << DISP_PIN_COM3) #define DISP_CATHODE(c) ((~c) & 0xff00) #define DISP_FONT_DP (1 << 7) #define DISP_FONT_E (0x79) #define DISP_FONT_BLANK (0x00) #if (DISP_DUTY > 100) || (DISP_DUTY < 0) #error "DISP_DUTY shoud be in [0, 100]" #endif #ifndef DISP_DUTY #define DISP_DUTY 100 #endif #define DISP_EXTRAS (4 * (100 - DISP_DUTY) / DISP_DUTY) #define DISP_GPIO_ALL (DISP_COM_0 | DISP_COM_1 | DISP_COM_2 | DISP_COM_3 | 0x00ff) static const uint8_t segment_font[10] = {0x3f, 0x06, 0x5b, 0x4f, 0x66, 0x6d, 0x7d, 0x07, 0x7f, 0x6f}; /* LED font 0-9, active high */ static const uint16_t coms[4] = { #ifdef DISP_COM_ANODE DISP_COM_0, DISP_COM_1, DISP_COM_2, DISP_COM_3, #else DISP_CATHODE(DISP_COM_0), DISP_CATHODE(DISP_COM_1), DISP_CATHODE(DISP_COM_2), DISP_CATHODE(DISP_COM_3), #endif }; static volatile uint8_t digit[4] = {DISP_FONT_BLANK, DISP_FONT_BLANK, DISP_FONT_BLANK, DISP_FONT_BLANK}; /* Rendered */ static volatile uint8_t current_digit = 0; void disp_setup(void) { rcc_periph_clock_enable(RCC_GPIOA); rcc_periph_clock_enable(RCC_GPIOB); gpio_port_write(DISP_GPIO_BANK, DISP_FONT_BLANK); gpio_set_output_options(DISP_GPIO_BANK, GPIO_OTYPE_PP, GPIO_OSPEED_LOW, DISP_GPIO_ALL); gpio_mode_setup(DISP_GPIO_BANK, GPIO_MODE_OUTPUT, GPIO_PUPD_NONE, DISP_GPIO_ALL); } void disp_update(uint32_t voltage_mv, bool blinker) { /* Rounding */ if ((voltage_mv > 9999) && ((voltage_mv % 10) > 4)) { voltage_mv ++; } while (true) { if (voltage_mv > 99999) { digit[0] = DISP_FONT_E; digit[1] = DISP_FONT_BLANK; digit[2] = DISP_FONT_BLANK; digit[3] = DISP_FONT_BLANK; break; } if (voltage_mv > 9999) { /* AB.CD */ digit[0] = segment_font[(voltage_mv / 10000) % 10]; digit[1] = segment_font[(voltage_mv / 1000) % 10] | DISP_FONT_DP; digit[2] = segment_font[(voltage_mv / 100) % 10]; digit[3] = segment_font[(voltage_mv / 10) % 10]; break; } /* Everything else */ { /* A.BCD */ digit[0] = segment_font[(voltage_mv / 1000) % 10] | DISP_FONT_DP; digit[1] = segment_font[(voltage_mv / 100) % 10]; digit[2] = segment_font[(voltage_mv / 10) % 10]; digit[3] = segment_font[(voltage_mv / 1) % 10]; break; } } digit[3] |= blinker ? DISP_FONT_DP : DISP_FONT_BLANK; } void disp_refresh(void) { current_digit ++; if (current_digit > (3 + DISP_EXTRAS)) { current_digit = 0; } if (current_digit < 4) { #ifdef DISP_COM_ANODE gpio_port_write(DISP_GPIO_BANK, ((~digit[current_digit]) & 0x00ff) | coms[current_digit]); #else /* DISP_COM_ANODE */ gpio_port_write(DISP_GPIO_BANK, digit[current_digit] | coms[current_digit]); #endif /* DISP_COM_ANODE */ } else { gpio_port_write(DISP_GPIO_BANK, DISP_FONT_BLANK); } }
C
#include<stdio.h> void square (int *x, int *y) { *x = (*x) * --(*y); } int main ( ) { int number = 30; square(&number, &number); printf("%d",number); return 0; }
C
#include <unistd.h> #include <string.h> #include <stdlib.h> typedef struct s_fd { int write; int read; int flag; } t_fd; int ft_strlen(char *str) { int i = 0; while (str[i]) i++; return (i); } int ft_d_strlen(char **av) { int i = 0; while (av[i]) i++; return (i); } void ft_error(char *str) { write(2, str, ft_strlen(str)); } void exit_fatal(void) { ft_error("error: fatal\n"); exit(EXIT_FAILURE); } void get_fd(t_fd *fd) { int fds[2]; if (pipe(fds) == -1) exit_fatal(); fd->write = fds[1]; fd->read = fds[0]; fd->flag = 1; } void cd(char **av) { if (ft_d_strlen(av) != 2) ft_error("error: cd: bad arguments\n"); else if (chdir(av[1])) { ft_error("error: cd: cannot change directory to "); ft_error(av[1]); ft_error("\n"); } } void start_process(char **av, char **envp) { pid_t pid; if ((pid = fork()) == -1) exit_fatal(); else if (pid == 0) { if (execve(av[0], av, envp) == -1) ft_error("error: cannot execute "); ft_error(av[0]); ft_error("\n"); exit(1); } else waitpid(pid, 0, 0); } void fork_process(char **av, t_fd *fd, char **envp) { pid_t pid; if ((pid = fork()) == -1) exit_fatal(); else if (pid == 0) { dup2(fd->write, 1); close(fd->read); start_process(av, envp); close(fd->write); } else { dup2(fd->read, 0); close(fd->write); waitpid(pid, 0, 0); close(fd->read); } } void exec_cmd(char **av, t_fd *fd, char **envp) { if (fd->flag) fork_process(av, fd, envp); else start_process(av, envp); } int mainv(int ac, char **av, char **envp) { t_fd fd; int i = 0; int tmp_fd = dup(0); (void)ac; av++; while (av[i++]) { if (!strcmp("|", av[1])) { av[i] = 0; if (i) { get_fd(&fd); exec_cmd(av, &fd, envp); } av += i + 1; i = 0; } else if (!strcmp(";", av[1])) { av[i] = 0; if (i) exec_cmd(av, &fd, envp); av += i + 1; i = 0; dup2(tmp_fd, 0); } else if (!av[i + 1]) { exec_cmd(av, &fd, envp); av += i + 1; i = 0; dup2(tmp_fd, 0); } else ++i; } close(tmp_fd); return (0); }
C
#include <stdio.h> /* THIS CODE IS MY OWN WORK, IT WAS WRITTEN WITHOUT CONSULTING A TUTOR OR CODE WRITTEN BY OTHER STUDENTS - Derek Liu */ #include <stdlib.h> #include <sys/shm.h> #include <sys/msg.h> #include <string.h> #include <signal.h> #include <unistd.h> #include <stdbool.h> #include "computer.h" int messageQID, sharedMID; sharedMemory *mem; static void apocalypse(int signum) { int pid; printf("Hello world! \n"); for(int i = 0; i < 20; i++) { pid = mem->processList[i].pid; if (pid != 0) { printf("Killing process %d \n",pid); int killed = kill(pid,SIGINT); if(killed != 0) { perror("Couldn't kill compute processes"); exit(-1); } } } sleep(5); //detach shared memory int success = shmdt(mem); if(success != 0) { perror("Couldn't detach shared memory"); exit(-1); } //remove shared memory success = shmctl(sharedMID, IPC_RMID, 0); if(success != 0) { perror("Couldn't remove shared memory"); exit(-1); } //remove message queue success = msgctl(messageQID, IPC_RMID, NULL); if(success != 0) { perror("Couldn't remove message queue"); exit(-1); } //exit cleanly exit(0); } //sort the perfect numbers as they are inserted int insertNum(int num, int idx) { bool done = false; for(int i = 0; i < 10; i++) { if( (num < mem->perfect[i]) && (mem->perfect[i] !=0) ) { for(int j = 9; j > i; j--) { mem->perfect[j] = mem->perfect[j-1]; } mem->perfect[i] = num; idx = i; done = true; } if(done) break; } while(!done) { if(mem->perfect[idx] == 0) { mem->perfect[idx] = num; done = true; break; } idx++; } return idx; } int main(int argc, char * argv[]) { int processIndex, perfectIndex, pid; //printf("Size = %d",sizeof(sharedMemory)); //create shared memory segment sharedMID = shmget(SHAREDM_KEY,sizeof(sharedMemory), IPC_CREAT | 0660); //check if shared memory has already been created if(sharedMID == -1) { perror("Shared memory already exists"); exit(-1); } //point to beginning of bitmap mem = shmat(sharedMID, NULL, 0); //clear shared memory before we get started memset(mem->bitmap, 0, sizeof(mem->bitmap)); memset(mem->perfect, 0, sizeof(mem->perfect)); memset(mem->processList, 0, sizeof(mem->processList)); //get shared message queue messageQID = msgget(MESSAGEQ_KEY, IPC_CREAT | 0660); //check if message queue already exists if(messageQID == -1) { perror("Message queue already exists"); exit(-1); } //create an empty sigaction struct sigaction act = {}; memset(&act,0,sizeof(act)); sigemptyset(&act.sa_mask); act.sa_flags = 0; //set up signal handler act.sa_handler = apocalypse; //setup signal handler if(sigaction(SIGINT, &act, NULL) != 0) { perror("SIGINT failed"); exit(1); } if(sigaction(SIGHUP, &act, NULL) != 0) { perror("SIGHUP failed"); exit(1); } if(sigaction(SIGQUIT, &act, NULL) != 0) { perror("SIGQUIT failed"); exit(1); } message msg; while(1) { //printf("Waiting for message... \n"); msgrcv(messageQID,&msg,sizeof(msg.body),-3,0); if(msg.type == PERFECTION) { //printf("PERFECT number is: %d\n",msg.body); int perfectNum = msg.body; int i = 0; bool foundBefore = false; //check to see if we've found this perfect number already while(i < perfectIndex) { if (mem->perfect[i] == perfectNum) { foundBefore = true; //printf("This perfect number has already been found: %d\n",msg.body); break; } i++; } //update if we have not found this before if(!foundBefore) { perfectIndex = insertNum(perfectNum,perfectIndex); perfectIndex = perfectIndex + 1; } } else if(msg.type == GET_INDEX) { int procID = msg.body; int idx; for(int i = 0; i < 20; i++) { //printf("Process at index %d is %d\n",i,mem->processList[i].pid); if(mem->processList[i].pid == 0) { idx = i; //update the process map with the correct PID mem->processList[idx].pid = procID; //send the corresponding index within the process map msg.type = INDEX_SUCCESS; msg.body = idx; if(msgsnd(messageQID, &msg, sizeof(msg.body), 0) != 0) { perror("Failed to send INDEX_SUCCESS message"); exit(-1); } break; } //handle the cases where more than 20 processes are attached if( (i == 19) && (mem->processList[i].pid != 0) ) { printf("You can only run up to 20 compute processes.\n"); kill(procID,SIGINT); break; } } //printf("Process at index %d is %d\n",idx,mem->processList[idx].pid); } else if(msg.type == REQUEST_MPID) { //set the PID of manage int mpid = getpid(); //printf("Manage PID = %d \n",mpid); //send the corresponding index within the process map msg.type = RECEIVE_MPID; msg.body = mpid; if(msgsnd(messageQID, &msg, sizeof(msg.body), 0) != 0) { perror("Failed to send RECEIVE_MPID message"); exit(-1); } break; } } }
C
/* * Serial_Interrupt.c * * Created: 25.04.2020 10:29:20 * Author : Denis Dengler, Maximilian Kürschner, David Schader * Description: Using serial pins for echo function */ /* includes */ #include "serial.h" /* function implementations */ void echo(){ usart_send(usart_receive()); } int main( void ) { usart_init(echo); //test string usart_send_string("hallo_test\n\r"); while(1) { // Main loop } }
C
#include "proj.h" extern Block* head; void READ_CURRENT_VALUE(int dataID, char* val){ // reading from the in memory cell storage // head is the linked list which is story cell data Block* temp = head ; while(temp != NULL){ if(temp->rec->dataID == dataID){ strcpy(val,temp->rec->dataVal); return; } temp = temp->next; } return ; }
C
int main() { int size = sizeof(all_tests)/sizeof(test_data); printf("Running %d tests:\n", size); printf("=====================\n\n"); int pass_count = 0; pid_t f1= fork(); pid_t f2 = -1; pid_t f3 = -1; if (f1!= 0){ f2 = fork(); if(f2!=0){ f3= fork(); } } pid_t w1; pid_t w2; pid_t w3; int wstatus1, wstatus2,wstatus3; // for (int i = 0; i < size; i++) { // } if (f1==0){ if (test1() >= 0) { printf("Teste 1 : [PASS]\n"); return 0; }; return -1; } if (f2==0){ if (test2() >= 0) { printf("Teste 2 : [PASS]\n"); return 0; }; return -1; } if (f3==0){ if (test3() >= 0) { printf("Teste 3 : [PASS]\n"); return 0; }; return -1; } w1 = waitpid(f1,&wstatus1,NULL); w2 = waitpid(f2,&wstatus2,NULL); w3 = waitpid(f3,&wstatus3,NULL); //printf("w1 /%d\n",w1); printf("wstatus2 /%d\n",wstatus3); /////////////////////////////////////////////// twste 1 if(WIFEXITED(wstatus1)){ printf("Teste 1 exited, status= %d\n",WEXITSTATUS(wstatus1)); } else{ printf("sucesso exit funcao 1 : %d \n",w1); } if(wstatus1 == 0){ pass_count++; } /////////////////////////////////////////////// teste 2 if(WIFEXITED(wstatus2)){ printf("Teste 2 exited, status= %d\n",WEXITSTATUS(wstatus2)); } else{ printf("sucesso exit funcao 2 : %d \n",w1); } if(wstatus2 == 0){ pass_count++; } /////////////////////////////////////////////// teste 3 if(WIFEXITED(wstatus3)){ printf("Teste 3 exited, status= %d\n",WEXITSTATUS(wstatus3)); } else{ printf("sucesso exit funcao 3 : %d \n",w1); } if(wstatus3 == 0){ pass_count++; } printf("\n\n=====================\n"); printf("%d/%d tests passed\n", pass_count, size); return 0; }
C
#include "pwm16.h" void pwm16_init() { /* Notes: Power Reduction TC1 bit in Power reduction Register needs to be cleared (set to 0) for TC1 module to work. TCNT1 */ /* PB1 ~ pin 9 on arduino uno */ DDRB = _BV(PB1) | _BV(PB2); ICR1 = 0xFFFF; TCNT1 = 0; /* TC1 Control Register A */ TCCR1A |= _BV(COM1A1) | _BV(COM1A0) | _BV(COM1B1) | _BV(COM1B0); TCCR1A |= _BV(WGM11); /* TC1 Control Register B */ TCCR1B |= _BV(WGM13) | _BV(WGM12); OCR1A = 0x0000; OCR1B = 0x0000; TCCR1B |= _BV(CS11) | _BV(CS10); } void pwm16a_set( uint16_t value ) { OCR1A = 0xFFFE - value; } void pwm16b_set( uint16_t value ) { OCR1B = 0xFFFE - value; }
C
#include <stdio.h> #include <stdlib.h> int V, E; typedef struct edge{ int u, v, w; } edge; int find(int* parent, int i){ if (parent[i] != i) parent[i] = find(parent, parent[i]); return parent[i]; } void Union(int* parent, int* rank, int x, int y){ int xroot = find(parent, x); int yroot = find(parent, y); if (rank[xroot] < rank[yroot]) parent[xroot] = yroot; else if (rank[xroot] > rank[yroot]) parent[yroot] = xroot; else { parent[yroot] = xroot; rank[xroot]++; } } int comp(const void* a, const void* b){ edge* u = (edge*) a; edge* v = (edge*) b; return u->w > v->w; } void kruskal(edge* G){ int parent[V], rank[V]; int sum = 0; for(int i = 0; i < V; i++) parent[i] = i, rank[i] = 0; qsort(G, E, sizeof(G[0]), comp); for (int i = 0, e = 0; e < V-1; ){ edge next = G[i++]; int u = find(parent, next.u); int v = find(parent, next.v); if (u != v){ Union(parent, rank, u, v); e++; printf("%d - %d\t%d\n", next.u , next.v, next.w); sum += next.w; } } printf("Minimum weight = %d\n", sum); } int main(int argc, char const *argv[]){ V = 4 , E = 5; int ed[5][3] ={{0,1,10}, {0,2,6}, {0,3,5}, {1,3,15}, {2,3,4}}; edge G[E]; for(int i = 0; i < E; i++) G[i].u = ed[i][0], G[i].v = ed[i][1], G[i].w = ed[i][2]; kruskal(G); return 0; }
C
#include <stdio.h> // prototype takes two pointers void swap(int*, int*); int main(void) { int num1 = 5; int num2 = 4; // pass address of variables swap(&num1, &num2); printf("%d - %d\n", num1, num2); return 0; } // function that takes two pointers void swap(int *a, int *b) { int tmp = *a; *a = *b; *b = tmp; }
C
#include <stdio.h> int main(void) { //define array a int a[] = { 1,2,3,4,5 }; int* p = a; //int형 포인터 변수 p에 배열 a의 시작 주소를 넣어줌 int i; //for문과 배열식 표현으로 a 출력 for (i = 0; i <= sizeof(a)/sizeof(int)-1; i++) printf("%d ", a[i]); printf("\n"); //while문과 포인터식 표현으로 a 출력 while (p<=a+sizeof(a)/sizeof(int)-1) { printf("%d ", *p++); } printf("\n"); return 0; }
C
#include <stdio.h> #include <string.h> #include <limits.h> #define MAX_SIZE 510 int matrix[MAX_SIZE][MAX_SIZE]; int distance[MAX_SIZE]; int paths[MAX_SIZE]; int inset[MAX_SIZE]; void Dijkstra(int start, int nodes) { for (int i = 1; i <= nodes; ++i) { distance[i] = -1; paths[i] = 0; inset[i] = 0; } int min_dist; int new_node = start; distance[start] = 0; inset[start] = 1; paths[start] = 1; for (int i = 1; i < nodes; ++i) { for (int j = 1; j <= nodes; ++j) if (!inset[j] && matrix[new_node][j] != 0) { if (distance[j] == -1) { distance[j] = distance[new_node] + matrix[new_node][j]; paths[j] = paths[new_node]; } else { if (distance[j] > distance[new_node] + matrix[new_node][j]) { distance[j] = distance[new_node] + matrix[new_node][j]; paths[j] = paths[new_node]; } else if (distance[j] == distance[new_node] + matrix[new_node][j]) { paths[j] += paths[new_node]; } } } min_dist = INT_MAX; for (int j = 1; j <= nodes; ++j) { if (!inset[j] && distance[j] != -1 && distance[j] < min_dist) { min_dist = distance[j]; new_node = j; } } inset[new_node] = 1; } } int main() { int n, m; int u, v, t; while (scanf("%d %d", &n, &m) != EOF) { memset(matrix, 0, sizeof(matrix)); while (--m >= 0) { scanf("%d %d %d", &u, &v, &t); if (matrix[u][v] == 0 || (matrix[u][v] != 0 && matrix[u][v] > t)) matrix[u][v] = matrix[v][u] = t; } Dijkstra(1, n); if (distance[n] == -1) printf("-1 -1\n"); else printf("%d %d\n", distance[n], paths[n]); } return 0; }
C
#ifndef __AUDIO_CLOCK_H__ #define __AUDIO_CLOCK_H__ #include <app/audio/audio_if.h> /*! file @brief Audio DSP Clock configuration ** */ #if TRAPSET_WAKE_ON_AUDIO /** * \brief Configures audio-DSP clock in different operation modes. * Application can configure audio-DSP clock in below operation modes: * 1) Active mode - Application can put audio-DSP in active mode by calling * OperatorFrameworkEnable(MAIN_PROCESSOR_ON). * 2) Low-power mode - Application can put audio-DSP in low-power mode by first * calling OperatorFrameworkTriggerNotificationStart() and then switching off * main processor by using OperatorFrameworkEnable(MAIN_PROCESSOR_OFF). * 3) Trigger Mode - If audio-DSP is configured to operate in low-power mode, * it needs a different clock configuration during transistion from low-power to * active mode. * The default clock frequency in different modes can be obtained by * using AudioDspGetClock(). * @note * 1) The application must power on audio-DSP by using * OperatorFrameworkEnable(MAIN_PROCESSOR_ON) before using this API. * 2) The clock configuration will reset to default settings if application * decides to power-off audio-DSP without enabling trigger notification in * low-power mode. Check OperatorFrameworkTriggerNotificationStart documentation * for more details. * 3) The active mode clock configuration must be selected carefully in order to * run the audio use case with optimum power consumption. * 4) The application must stop all operators while changing the active mode * clock configuration to avoid undesirable audio output. * * \param clock_config Pointer to audio-dsp clock configuration * \return TRUE if clock configuration request has succeeded, FALSE otherwise. * * \ingroup trapset_wake_on_audio */ bool AudioDspClockConfigure(audio_dsp_clock_configuration * clock_config); /** * \brief Read audio-DSP clock values in different operation modes. * Application can read audio-DSP clock values in different operation modes * by using this API. * * \param dsp_clock Pointer to location where clock values will be * written if read succeeds * \return TRUE if clock values have been read successfully, FALSE otherwise. * * \ingroup trapset_wake_on_audio */ bool AudioDspGetClock(audio_dsp_clock * dsp_clock); /** * \brief Maps abstract audio clock speed to frequencies. * This trap modifies the internal lookup table of Audio DSP clocks * speeds. * This allows the actual clock frequency for each of the modes in the * enum audio_dsp_clock_type to be set. * * \param clock_mode Audio DSP abstract clock speed. * \param freq Actual value of Audio DSP clock frequency specified in Hz. * \return TRUE if clock speed request has succeeded, FALSE otherwise. * * \ingroup trapset_wake_on_audio */ bool AudioMapCpuSpeed(audio_dsp_clock_type clock_mode, uint32 freq); #endif /* TRAPSET_WAKE_ON_AUDIO */ #endif
C
#include <GL/gl.h> #include <GL/glut.h> #include <stdarg.h> #include <stdio.h> #include "Text.h" /* WRITING */ int len(char* string){ int l = 0; while(string[l] != '\0') l++; return l; } String str(char* string){ String cString; int i, l = len(string); cString.value = (char*)malloc(sizeof(char) * (l+1)); for(i=0; i<l; i++){ cString.value[i] = string[i]; } cString.length = l; return cString; } String format(char* format, ...){ va_list ap; char* result; int size; va_start(ap, format); size = _vscprintf(format, ap); result = (char*)malloc(sizeof(char) * (size+1)); int r = vsnprintf(result, size+1, format, ap); return str(result); } /* OPENGL EXTENSION */ void _glText(String string, Vector c, void* font){ int i; glPushMatrix(); //glDisable(GL_DEPTH_TEST); glRasterPos3f(c.x, c.y, c.z); for(i=0; i< string.length; i++) glutBitmapCharacter(font, string.value[i]); //glEnable(GL_DEPTH_TEST); glPopMatrix(); } void var_glText(glText_args in){ String string = in.string; Vector c = in.c; void* font = in.font ? in.font : GLUT_BITMAP_8_BY_13; _glText(string, c, font); }
C
#include "myselect.h" /*Precondition: program starts *Postcondition: term caps are initiated */ char *get_term_cap(char* cap) { char *str; static char area[2048]; if(!(str=(char *)tgetstr(cap, (char**)(&area)))) { my_str("Error getting term cap"); my_char('\n'); exit(1); } return str; } /*Precondition: function is called *Postcondition: caps are initialized */ void init_caps() { char ex[2]; char *term; term = getenv("TERM"); if(!term) { my_str("Error initializing caps"); my_char('\n'); exit(1); } char bp[2048]; tgetent(bp,term); gl_env.clear = get_term_cap(CLEAR); gl_env.left = KL; gl_env.down = KD; gl_env.right = KR; gl_env.up = KU; ex[0] = (char) ESC; ex[1] = '\0'; gl_env.esc = ex; gl_env.underline = get_term_cap(UNDERLINE); gl_env.under_end = get_term_cap(UNDER_END); gl_env.standout = get_term_cap(STANDOUT); gl_env.stand_end = get_term_cap(STAND_END); gl_env.move = get_term_cap(MOVE); gl_env.cursoroff = VECAP; gl_env.cursoron = VICAP; } /*Precondition: program is started *Postcondition: function allows writing directly to the terminal */ int my_termprint(int n) { return write(1, &n, 1); } /*Precondition: terminal needs to be cleared *Postcondition: clears the terminal */ void term_clear() { tputs(gl_env.clear,1,my_termprint); }
C
#include <stdio.h> #include <malloc.h> typedef struct cell { //单链表结点结构体定义 int x; struct cell *next; } List; List *build(void) { //新建单链表,并将建好的单链表首结点地址返回 List *head, *tmp, *p; head = tmp = p = NULL; int n; //输入 scanf("%d", &n); getchar(); if (n == 0) return head; //头节点 head = (List *)malloc(sizeof(List)); p = head; p->x = n; p->next = NULL; while (1) { scanf("%d", &n); getchar(); if (n == 0) break; tmp = (List *)malloc(sizeof(List)); p->next = tmp; p = p->next; p->x = n; p->next = NULL; } return head; //返回单链表头 } //交换索引为m和n的两个结点,head是单链表首结点指针 List* swap(List* head,int m,int n) { if(head==NULL) return NULL; List* pm=head, *pn=head; List* pm0 = NULL, *pn0 = NULL; List* tmp; int i; for (i = 1;i < m && pm != NULL;i++) { pm0 = pm; pm = pm->next; } for (i = 1;i < n && pn != NULL;i++) { pn0 = pn; pn = pn->next; } //索引为m,n的结点位于链表中间 if (pm != NULL && pn != NULL && m != n) { //均不在头尾 if (pm0 != NULL && pn0 != NULL) { tmp=pm->next; pm->next=pn->next; pn->next=tmp; pm0->next=pn; pn0->next=pm; } //m在头 else if (pm0 == NULL && pn0 != NULL) { tmp=pn->next; pn->next=pm->next; head=pn; pn0->next=pm; pm->next=tmp; } //n在头 else if (pm0 != NULL && pn0 == NULL) { tmp=pm->next; pm->next=pn->next; head=pm; pm0->next=pn; pn->next=tmp; } } return head; } void print(List *head) { //打印整个单链表,head是指向单链表首结点的指针 List *p = head; while (1) { printf("%d", p->x); p = p->next; if (p == NULL) break; printf(" "); } } void release(List *head) { //释放单链表空间,head是指向单链表首结点的指针 List *p = head; List *tmp = NULL; while (p != NULL) { tmp = p; p = p->next; free(tmp); } } int main(void) { List *head; int m=0,n=0; head = build(); scanf("%d %d", &m, &n); head = swap(head,m,n); if (head != NULL) print(head); else printf("NULL"); release(head); }
C
#include "Tenure.h" #include <iostream> using namespace std; Tenure::Tenure() { rank = ' '; YearOfExp = 0; } Tenure::Tenure(string name, string email, long facultyId, char r, int Exp ): CompSci(name, email, facultyId) { rank = r; YearOfExp = Exp; } void Tenure::getInfo(char r, int Exp) { } void Tenure::setInfo(char r, int Exp) { rank = r; YearOfExp = Exp; } void Tenure::print() const { cout << "Name: " << CompSci::name << endl << "Email: " << CompSci::email << endl << "Faculty ID: " << CompSci::facultyId << endl << "Rank: " << Tenure::rank << endl << "Years of Experience: " << Tenure::YearOfExp << endl; } float Tenure::findSalary() const { int salary = 0; int BSal = 0; if(Tenure::rank == 'A') BSal = 65000; else if(Tenure::rank == 'S') BSal = 80000; else BSal = 90000; return salary = (BSal * Tenure::YearOfExp); }
C
#include<stdio.h> #include<string.h> #define SIZE 100 void toggleString(char *str); int main(void) { char str[SIZE]; int i; scanf("%[^\n]s", str); toggleString(str); return 0; } void toggleString(char * str) { int length=strlen(str),i; for(i=0;i<length;i++) { if(str[i]>='a' && str[i]<='z') { str[i]=str[i]-32; } else if(str[i]>='A' && str[i]<='Z') { str[i]=str[i]+32; } } printf("%s",str); }
C
#ifndef PIQUE_KMERHASH #define PIQUE_KMERHASH #include "kmer.h" typedef struct kmerset_t_ kmerset_t; kmerset_t* kmerset_alloc(); void kmerset_free(kmerset_t*); size_t kmerset_size(const kmerset_t* H); void kmerset_add(kmerset_t* H, kmer_t x); /* Return the (one-based) index of the kmer in the set. * * Zero is returned if the kmer is not present in the set. */ uint32_t kmerset_get(const kmerset_t* H, kmer_t x); #endif
C
#include "my_display.h" void MY_DISPLAY_GPIO_Init() { GPIO_InitTypeDef GPIO_InitStruct_B; GPIO_InitTypeDef GPIO_InitStruct_C; GPIO_InitTypeDef GPIO_InitStruct_D; /* GPIO Ports Clock Enable */ __GPIOD_CLK_ENABLE(); /*For pins PD10/11/13/14: Display-RS,E,DB6,DB7 */ __GPIOC_CLK_ENABLE(); /*For pin PC7: Display-DB4*/ __GPIOB_CLK_ENABLE(); /*For pin PB7: Display-DB5*/ /*Configure GPIO pin : PB7 */ GPIO_InitStruct_B.Pin = GPIO_PIN_7; GPIO_InitStruct_B.Mode = GPIO_MODE_OUTPUT_PP; GPIO_InitStruct_B.Pull = GPIO_NOPULL; GPIO_InitStruct_B.Speed = GPIO_SPEED_LOW; HAL_GPIO_Init(GPIOB, &GPIO_InitStruct_B); /*Configure GPIO pin : PC7 */ GPIO_InitStruct_C.Pin = GPIO_PIN_7; GPIO_InitStruct_C.Mode = GPIO_MODE_OUTPUT_PP; GPIO_InitStruct_C.Pull = GPIO_NOPULL; GPIO_InitStruct_C.Speed = GPIO_SPEED_LOW; HAL_GPIO_Init(GPIOC, &GPIO_InitStruct_C); /*Configure GPIO pins : PD10 PD11 PD13 PD14 */ GPIO_InitStruct_D.Pin = GPIO_PIN_10 | GPIO_PIN_11 | GPIO_PIN_13 | GPIO_PIN_14; GPIO_InitStruct_D.Mode = GPIO_MODE_OUTPUT_PP; GPIO_InitStruct_D.Pull = GPIO_NOPULL; GPIO_InitStruct_D.Speed = GPIO_SPEED_LOW; HAL_GPIO_Init(GPIOD, &GPIO_InitStruct_D); } void MY_DISPLAY_START(Display *d) { /*Assign pin numbers*/ d->_rs_pin = GPIO_PIN_10; /*PD 10*/ d->_rw_pin = 255; /*GND (always write)*/ d->_enable_pin = GPIO_PIN_11; /*PD 11*/ d->_data_pins[4] = GPIO_PIN_7; /*PC 7*/ d->_data_pins[5] = GPIO_PIN_7; /*PB 7*/ d->_data_pins[6] = GPIO_PIN_13; /*PD 13*/ d->_data_pins[7] = GPIO_PIN_14; /*PD 14*/ /*Assign peripherals*/ d->_rs_GPIO_port = GPIOD; /*P D 10*/ d->_enable_GPIO_port = GPIOD; /*P D 11*/ d->_data_GPIO_ports[4] = GPIOC; /*P C 7*/ d->_data_GPIO_ports[5] = GPIOB; /*P B 7*/ d->_data_GPIO_ports[6] = GPIOD; /*P D 13*/ d->_data_GPIO_ports[7] = GPIOD; /*P D 14*/ /* 4 bit mode */ d->_displayfunction = LCD_4BITMODE | LCD_2LINE | LCD_5x8DOTS; MY_DISPLAY_CONNECT(d); } void MY_DISPLAY_CONNECT(Display *d) { // SEE PAGE 46 OF "HD44780U (LCD-II)" DATASHEET FOR INITIALIZATION SPECIFICATION! // According to datasheet, we need at least 40ms after power rises above 2.7V // before sending commands. We'll wait 50. HAL_Delay(50*1000); // Now we pull both RS and R/W low to begin commands HAL_GPIO_WritePin(d->_rs_GPIO_port, d->_rs_pin, GPIO_PIN_RESET); HAL_GPIO_WritePin(d->_enable_GPIO_port, d->_enable_pin, GPIO_PIN_RESET); if (d->_rw_pin != 255) { HAL_GPIO_WritePin(d->_rw_GPIO_port, d->_rw_pin, GPIO_PIN_RESET); } //put the LCD into 4 bit mode // figure 24, pg 46 // we start in 8bit mode, try to set 4 bit mode write4bits(d, 0x03); HAL_Delay(5*1000); // wait min 4.1ms // second try write4bits(d, 0x03); HAL_Delay(5*1000); // wait min 4.1ms // third try write4bits(d, 0x03); HAL_Delay(1*1000); // wait min 100 us // finally, set to 8-bit interface write4bits(d, 0x02); // finally, set # lines, font size, etc. command(d, LCD_FUNCTIONSET | d->_displayfunction); // turn the display on with a blinking cursor by default d->_displaycontrol = LCD_DISPLAYON | LCD_CURSOROFF | LCD_BLINKOFF; command(d, LCD_DISPLAYCONTROL | d->_displaycontrol); // clear it off clear(d); d->_ddram_mode = 1; // Initialize to default text direction (for romance languages) d->_displaymode = LCD_ENTRYLEFT | LCD_ENTRYSHIFTDECREMENT; // set the entry mode command(d, LCD_ENTRYMODESET | d->_displaymode); /* custom characters */ uint8_t charmap0[8] = {32-1, 16+1, 4, 8+4+2, 8+4+2, 4, 16+1, 32-1}; createChar(d, 0, charmap0); uint8_t charmap1[8] = {32-1, 16+1, 0, 0, 0, 0, 16+1, 32-1}; createChar(d, 1, charmap1); uint8_t charmap2[8] = {32-1, 32-1, 32-1, 32-1, 0, 0, 0, 0}; createChar(d, 2, charmap2); uint8_t charmap3[8] = {0, 0, 0, 0, 32-1, 32-1, 32-1, 32-1}; createChar(d, 3, charmap3); /* arrows for alarm menu*/ uint8_t charmap4[8] = {0, 4, 4, 8+4+2, 8+4+2, 32-1, 32-1, 0}; createChar(d, 4, charmap4); uint8_t charmap5[8] = {0, 4, 4, 8+2, 8+2, 16+1, 32-1, 0}; createChar(d, 5, charmap5); uint8_t charmap6[8] = {0, 32-1, 16+1, 8+2, 8+2, 4, 4, 0}; createChar(d, 6, charmap6); } void printSigByte(Display *d, uint8_t byte) { if (byte & 0x80){ byte = ~(byte-1); } printNumber(d, byte); } void printHex(Display *d, uint8_t num) { uint8_t numH, numL; write(d, '0'); write(d, 'x'); numH = (num & 0xF0) >> 4; if (numH > 9) numH = numH-10 + 'a'; else numH += '0'; write(d, numH); numL = num & 0x0F; if (numL > 9) numL = numL-10 + 'a'; else numL += '0'; write(d, numL); } void printStr(Display *d, const char str[]) { while (*str) write(d, *str++); } void printFloat(Display *d, double number, uint8_t digits) { if (digits > 1) digits = 1; // Handle negative numbers if (number < 0.0) { write(d, '-'); number = -number; } // Round correctly so that print(1.999, 2) prints as "2.00" double rounding = 0.5; uint8_t i; for (i=0; i<digits; ++i) rounding /= 10.0; number += rounding; // Extract the integer part of the number and print it unsigned long int_part = (unsigned long)number; double remainder = number - (double)int_part; printNumber(d, int_part); // Print the decimal point, but only if there are digits beyond if (digits > 0) write(d, '.'); // Extract digits from the remainder one at a time while (digits-- > 0) { remainder *= 10.0; int toPrint = (int) remainder; printNumber(d, (unsigned long)toPrint); remainder -= toPrint; } } void printNumber(Display *d, unsigned long n) { unsigned char buf[8 * sizeof(long)]; // Assumes 8-bit chars. unsigned long i = 0; if (n == 0) { write(d, '0'); return; } while (n > 0) { buf[i++] = n % 10; n /= 10; } for (; i > 0; i--) write(d, (char) (buf[i - 1] < 10 ? '0' + buf[i - 1] : 'A' + buf[i - 1] - 10)); } void printTemp(Display *d, float temp, char scale, uint8_t digits){ switch(scale) { default: case'c': case'C': break; case'f': case'F': temp = temp * 1.8 + 32; break; case'k': case'K': temp += 273.15; break; } if (digits > 1) digits = 1; printFloat(d, temp, digits); write(d, ' '); switch(scale) { default: case'c': case'C': write(d, 0xB2); write(d, 'C'); break; case'f': case'F': write(d, 0xB2); write(d, 'F'); break; case'k': case'K': write(d, 'K'); break; } } void clear(Display *d) { command(d, LCD_CLEARDISPLAY); // clear display, set cursor position to zero HAL_Delay(1600); } void home(Display *d) { command(d, LCD_RETURNHOME); // set cursor position to zero HAL_Delay(2*1000); } void setCursor(Display *d, uint8_t col, uint8_t row) { int row_offsets[] = { 0x00, 0x40 }; command(d, LCD_SETDDRAMADDR | (col + row_offsets[row])); } // These commands scroll the display without changing the RAM void scrollDisplayLeft(Display *d) { command(d, LCD_CURSORSHIFT | LCD_DISPLAYMOVE | LCD_MOVELEFT); } void scrollDisplayRight(Display *d) { command(d, LCD_CURSORSHIFT | LCD_DISPLAYMOVE | LCD_MOVERIGHT); } // Allows us to fill the first 8 CGRAM locations // with custom characters void createChar(Display *d, uint8_t location, uint8_t charmap[]) { location &= 0x7; // we only have 8 locations 0-7 command(d, LCD_SETCGRAMADDR | (location << 3)); int i; for (i=0; i<8; i++) { write(d, charmap[i]); } command(d, LCD_SETDDRAMADDR | d->_cursor_address); } /*********** mid level commands, for sending data/cmds */ inline void command(Display *d, uint8_t value) { send(d, value, GPIO_PIN_RESET); if (value == LCD_CLEARDISPLAY) d->_cursor_address = 0; if (value == LCD_RETURNHOME) d->_cursor_address = 0; if ((value & (LCD_ENTRYMODESET | LCD_ENTRYSHIFTDECREMENT)) != 0) d->_incNdec = 1; if ((value & (LCD_ENTRYMODESET | LCD_ENTRYSHIFTDECREMENT)) != 0) d->_incNdec = 0; if ((value & LCD_SETCGRAMADDR) != 0) d->_ddram_mode = 0; if ((value & LCD_SETDDRAMADDR) != 0) { d->_ddram_mode = 1; d->_cursor_address = value - LCD_SETDDRAMADDR; } } inline void write(Display *d, uint8_t value) { send(d, value, GPIO_PIN_SET); if (d->_ddram_mode) (d->_incNdec == 0)? d->_cursor_address++ : d->_cursor_address--; } /************ low level data pushing commands **********/ // write either command or data void send(Display *d, uint8_t value, GPIO_PinState PinState) { HAL_GPIO_WritePin(d->_rs_GPIO_port, d->_rs_pin, PinState); // if there is a RW pin indicated, set it low to Write if (d->_rw_pin != 255) { HAL_GPIO_WritePin(d->_rw_GPIO_port, d->_rw_pin, GPIO_PIN_RESET); } write4bits(d, value>>4); write4bits(d, value); } void write4bits(Display *d, uint8_t value) { int i; for (i = 0; i < 4; i++) { HAL_GPIO_WritePin(d->_data_GPIO_ports[i+4], d->_data_pins[i+4], (value >> i) & 0x01); } pulseEnable(d); } void pulseEnable(Display *d) { HAL_GPIO_WritePin(d->_enable_GPIO_port, d->_enable_pin, GPIO_PIN_RESET); HAL_Delay(1*1000); HAL_GPIO_WritePin(d->_enable_GPIO_port, d->_enable_pin, GPIO_PIN_SET); HAL_Delay(1*1000); // enable pulse must be >450ns HAL_GPIO_WritePin(d->_enable_GPIO_port, d->_enable_pin, GPIO_PIN_RESET); HAL_Delay(1*1000); // commands need > 37us to settle }
C
#include <stdio.h> #include <stdlib.h> #include <fcntl.h> #include <iostream> #include <unistd.h> #include <linux/input.h> //#include <time.h> #include <sys/time.h> #include <math.h> #define PI M_PI//3.141592653589793 //3.141593 #define MIN(a,b) \ ({ __typeof__ (a) _a = (a); \ __typeof__ (b) _b = (b); \ _a < _b ? _a : _b; }) using namespace std; double X_R_curr=0, Y_R_curr=0, X_L_curr=0, Y_L_curr=0, THETAcurr=0; double m1y; double m2y; double m1x; double m2x; double mouse_left_tilt; double mouse_right_tilt; double sign(double a){ if(0 == (int)(a*1000000) ) return 1; return (a/fabs(a)); } bool isPI(double x){ if( ((int)(x*1000)) == ((int)(PI*1000)) ) true; else false; } double getAng(double x1, double y1, double x2, double y2){ return atan2(y2-y1, x2-x1); } double getDistance(double x1, double y1, double x2, double y2){ // Using pythagoras statement to get the distance between two points return sqrt(pow(y2-y1,2)+pow(x2-x1,2)); } double calibrateY(double x, double y, double tilt){ return (getDistance(0,0,x,y) * sin( getAng(0,0,x,y) - tilt ) ); } double calibrateX(double x, double y, double tilt){ return (getDistance(0,0,x,y) * cos(getAng(0,0,x,y) - tilt) ); } double pyt(double x1, double y1, double x2, double y2){ return sqrt(pow((x2-x1),2) + pow((y2-y1),2)); } void localToGlobal(double right_x, double right_y, double left_x, double left_y){ // translating the local points to global // double X_R_curr=0, Y_R_curr=0, X_L_curr=0, Y_L_curr=0, THETAcurr=0; X_R_curr += (getDistance(0,0,right_x,right_y) * (cos(THETAcurr + (getAng(0, 0, right_x, right_y))))); Y_R_curr += (getDistance(0,0,right_x,right_y) * (sin(THETAcurr + (getAng(0, 0, right_x, right_y))))); X_L_curr += (getDistance(0,0,left_x,left_y) * (cos(THETAcurr + (getAng(0, 0, left_x, left_y))))); Y_L_curr += (getDistance(0,0,left_x,left_y) * (sin(THETAcurr + (getAng(0, 0, left_x, left_y))))); double car_x = (X_R_curr/m2x + X_L_curr/m1x)/2; double car_y = (Y_R_curr/m2y + Y_L_curr/m1y)/2; printf("%f,%f\n", car_x,car_y); } double newX(double xRatio, double x1, double y1, double offsetAng){ return (pyt(0,0,x1*xRatio,y1) * cos(getAng(0,0,y1,x1*xRatio)+offsetAng)); //double distM1 = pyt(0,0,x1*xRatio1,y1); //double angM1 = getAng(y1,x1*xRatio1); //double newCordM1X = dist * cos(ang+offsetAng); //double newCordM1Y = dist * sin(ang+offsetAng); } double newY(double xRatio, double x1, double y1, double offsetAng){ return (pyt(0,0,x1*xRatio,y1) * sin(getAng(0,0,y1,x1*xRatio)+offsetAng)); } int main(void){ int i; int x1Buff=0; int y1Buff=0; int x2Buff=0; int y2Buff=0; int j; int k; int x1=0; int y1=0; int x2=0; int y2=0; int x1Tot=0; int y1Tot=0; int x2Tot=0; int y2Tot=0; double ALPHAv=0, ALPHAh=0, lv=0, Xv=0, XvCurr=0, Yv=0, YvCurr=0, lh=0, Xh=0, XhCurr=0, Yh=0, YhCurr=0, GAMMA=0, Rv=0, Rh=0, DELTA_THETA=0, XDELTAh=0, YDELTAh=0, XDELTAv=0, YDELTAv=0, DELTAX=0, DELTAY=0, D=100, xRatioM1=0, offsetAngM1=0, xRatioM2=0, offsetAngM2=0, m2Ratio=0; int m1y1Cal=0, m1x1Cal=0, m1y2Cal=0, m1x2Cal=0, m2y1Cal=0, m2x1Cal=0, m2y2Cal=0, m2x2Cal=0; FILE *file1; FILE *file2; FILE *file3; timeval first, next; //if((fd = open(MOUSEFILE, O_RDONLY)) == -1) { // perror("opening device"); // exit(EXIT_FAILURE); //} gettimeofday(&first, NULL); cout << " Started!\n"; i=0; file1 = fopen("1.txt","r"); file2 = fopen("2.txt","r"); fscanf(file1,"%d#%d",&x1Buff,&y1Buff); fclose(file1); fscanf(file2,"%d#%d",&x2Buff,&y2Buff); fclose(file2); file3 = fopen("Calibration.txt","r"); fscanf(file3,"%d#%d#%d#%d#%d#%d#%d#%d", &m1x1Cal, &m1y1Cal, &m2x1Cal, &m2y1Cal, &m1x2Cal, &m1y2Cal, &m2x2Cal, &m2y2Cal); fclose(file3); mouse_left_tilt = atan2(m1y1Cal,m1x1Cal) - PI/2; mouse_right_tilt = atan2(m2y1Cal,m2x1Cal) - PI/2; printf("%d \n%d \n%d \n%d \n%d \n%d \n%d \n%d \n\n", m1x1Cal, m1y1Cal, m2x1Cal, m2y1Cal, m1x2Cal, m1y2Cal, m2x2Cal, m2y2Cal); xRatioM1 = abs(m1y1Cal)/abs(m1x2Cal); offsetAngM1 = getAng(0,0,m1y1Cal,abs(m1x1Cal*xRatioM1)); xRatioM2 = m2y1Cal/m2x2Cal; offsetAngM2 = getAng(0,0,m2y1Cal,abs(m2x1Cal*xRatioM2)); m2Ratio = abs(m1y1Cal)/abs(m2y1Cal); // printf("%d \n%d \n%d \n%d \n%d \n%d \n%d \n%d \n\n", m1y1Cal, m1x1Cal, m2y1Cal, m2x1Cal, m1y2Cal, m1x2Cal, m2y2Cal, m2x2Cal); m1y = m1y1Cal/850; m2y = m2y1Cal/850; m1x = fabs(m1x2Cal)/745; m2x = fabs(m2x2Cal)/745; j=0; k=0; while(1){ i++; if( (i % 100) == 0){ //read(fd, &ie, sizeof(struct input_event))) { //cout << " \n" << i%10 << "loops.\n" << i; file1 = fopen("1.txt","r"); j=fscanf(file1,"%d#%d",&x1,&y1); fclose(file1); file2 = fopen("2.txt","r"); k=fscanf(file2,"%d#%d",&x2,&y2); fclose(file2); if( (j == 2) && ( k == 2) ){ x1Tot += (XvCurr = x1 - x1Buff); y1Tot += (YvCurr = y1 - y1Buff); x2Tot += (XhCurr = x2 - x2Buff); y2Tot += (YhCurr = y2 - y2Buff); x1Buff = x1; y1Buff = y1; x2Buff = x2; y2Buff = y2; Xv += (XvCurr/1.0); Yv += (YvCurr/1.0); Xh += (XhCurr/1.0); Yh += (YhCurr/1.0); if((abs(Xv)>1) && (abs(Yv)>1) && (abs(Xh)>1) && (abs(Yh)>1)){ gettimeofday(&next, NULL); //cout << (next.tv_usec - first.tv_usec) << " ms."; //Xv *= m1x; //newX(xRatioM1, Xv, Yv, offsetAngM1); //Yv *= m1y; //newY(xRatioM1, Xv, Yv, offsetAngM1); //Xh *= m2x; //newX(xRatioM2, Xh, Yh, offsetAngM2)*m2Ratio; // Yh *= m2y; //newY(xRatioM2, Xh, Yh, offsetAngM2)*m2Ratio; //Xcurr=0, Ycurr=0, THETAcurr=0; Yv = calibrateY(Xv, Yv, mouse_left_tilt); Xv = calibrateX(Xv, Yv, mouse_left_tilt); Yh = calibrateY(Xh, Yh, mouse_right_tilt); Xh = calibrateX(Xh, Yh, mouse_right_tilt); double start_right_x = 50; double start_right_y = 0; double start_left_x = -50; double start_left_y = 0; //double D=200, Xv=100, Xh=100, Yv=100, Yh=150, X_R_curr=0, Y_R_curr=0, X_L_curr=0, Y_L_curr=0; double traveld_X = MIN(fabs(Xv), fabs(Xh)) * (fabs(Xv)/Xv); double traveld_Y = MIN(fabs(Yv), fabs(Yh)) * (fabs(Yv)/Yv); double curr_right_X = traveld_X + start_right_x; double curr_right_Y = traveld_Y + start_right_y; double curr_left_X = traveld_X + start_left_x; double curr_left_Y = traveld_Y + start_left_y; cout << Xv << " , " << Yv << " ---- " << Xh << " , " << Yh << endl; //double angle = Math.atan2(Y_R_curr - Y_L_curr, X_R_curr - X_L_curr); if(fabs(Yv) > fabs(Yh)) { double delta_Y = Yv - Yh; curr_left_X = curr_right_X - D * cos(((delta_Y/D)* PI)); curr_left_Y = curr_right_Y + D * sin(((delta_Y/D)* PI)); } if(fabs(Yv) < fabs(Yh)) { double delta_Y = Yh - Yv; curr_right_X = curr_left_X - D * cos(PI - ((delta_Y/D) * PI)); curr_right_Y = curr_left_Y + D * sin(PI - ((delta_Y/D) * PI)); } double end_right_x = curr_right_X; double end_right_y = curr_right_Y; double end_left_x = curr_left_X; double end_left_y = curr_left_Y; double center_x = (end_right_x + end_left_x) / 2; double center_y = (end_right_y + end_left_y) / 2; //localToGlobal(end_right_x, end_right_y, end_left_x, end_left_y); X_R_curr += Xh; Y_R_curr += Yh; X_L_curr += Xv; Y_L_curr += Yv; double car_x = (X_R_curr + X_L_curr)/2; double car_y = (Y_R_curr + Y_L_curr)/2; printf("%f,%f\n", car_x,car_y); //double angle = Math.atan2(Y_R_curr - Y_L_curr, X_R_curr - X_L_curr); Xv = 0; Yv = 0; Xh = 0; Yh = 0; first = next; } } } } return 0; }
C
#include "mess_treat.h" int stoi(char* buff, int buff_size) { if (buff_size > 5) return -1; int res = 0, i; for(i=0; i<buff_size; i++){ if (buff[i] > 47 && buff[i]<58) { res = res * 10 + ( buff[i] - '0' ); } else { printf("contain: %c\n", buff[i]); return -1; } } return res; } unsigned short etos(char c0, char c1) { return (uint)c0 << 0 | (uint)c1 << 8; } int get_key(char* buff, char* key, int buff_size) { char *ch; ch = strtok(buff, " "); strncpy(key, ch, buff_size); return 1; } int get_games(char* buff) { if (strlen(buff)<8) return -1; char *ch; ch = strtok(buff, " "); if (strcmp(ch, "GAMES")==0) { /* int nb_game = stoi(&buff[6], 2); if (nb_game <= 0) return -1; return nb_game; */ return etos(buff[0], buff[1]); } else return -1; } int get_game(char* buff, int* num_salle, int* nb_player) { if (strlen(buff) < 10) return -1; char* ch; ch = strtok(buff, " "); if(strcmp(ch, "GAME")==0) { /* int r = stoi(&buff[5], 2); if (r >= 0) *num_salle = r; else return r; r = stoi(&buff[8], 2); if (r >= 0) *nb_player = r; else return r; */ *num_salle = etos(buff[5], buff[6]); *nb_player = etos(buff[8], buff[9]); return 1; } else return -1; } int isREGOK(char *buff, int *num_salle) { char *REGOK = "REGOK"; if (strlen(buff) < 8) return -1; if (strncmp(buff, REGOK, strlen(REGOK)) == 0) { *num_salle = etos(buff[6], buff[7]); return 1; } return -1; } int treat_unreg(char *buff) { if (strlen(buff) < 7) return -1; char *UNREGOK = "UNREGOK" ; if (strncmp(buff, UNREGOK, strlen(UNREGOK)) == 0) { return 1; } return 0; } int treat_list(char *buff) { if (strlen(buff) < 11) return -1; char *ch; ch = strtok(buff, " "); if (ch != NULL) { if (strcmp(ch, "LIST!") == 0) { return etos(buff[9], buff[10]); } } return -1; } int treat_player(char *buff, char *id) { if (strlen(buff) < 8) return -1; char *ch; ch = strtok(buff, " "); if (ch != NULL) { if (strcmp(ch, "PLAYER") != 0) return -1; ch = strtok(NULL, " "); if (ch == NULL) return -1; strncpy(id, ch, 8); id[8] = '\0'; return 1; } return 0; } int treat_size(char *buff, int *num_game, int *height, int *weight) { if (strlen(buff) < 14) return -1; char *ch; ch = strtok(buff, " "); if (ch != NULL) { if (strcmp(ch, "SIZE!") != 0) return -1; *num_game = etos(buff[6], buff[7]); *height = etos(buff[9], buff[10]); *weight = etos(buff[12], buff[13]); return 1; } return 0; } int treat_welcome(char *buff, int *num_game, int *height, int *weight, int *nb_fantom,char* ip, int *port) { if (strlen(buff) < 41) return -1; char *ch; ch = strtok(buff, " "); if (ch != NULL) { if (strcmp(ch, "WELCOME") != 0) return -1; *num_game = etos(buff[7], buff[8]); *height = etos(buff[10], buff[11]); *weight = etos(buff[13], buff[14]); *nb_fantom = etos(buff[16], buff[17]); strncpy(ip, &buff[19], 15); ip[15] = '\0'; int r = stoi(&buff[36], 4); if ( r == -1) return -1; *port = r; return 1; } return -1; } int treat_pos(char *buff, char *id, int *posX, int *posY) { if (strlen(buff) < 41) return -1; char *ch; int r; ch = strtok(buff, " "); if (ch != NULL) { if (strcmp(ch, "POS") != 0) return -1; //get id ch = strtok(NULL, " "); if (ch == NULL) return -1; strncpy(id, ch, 8); id[8] = '\0'; ch = strtok(NULL, " "); if (ch == NULL) return -1; r = stoi(ch, strlen(ch)); if (r == -1) return -1; *posX = r; ch = strtok(NULL, " "); if (ch == NULL) return -1; r = stoi(ch, strlen(ch)); if (r == -1) return -1; *posY = r; return 1; } return -1; } int treat_mesp(char *buff, char *id2, char *mess) { char *ch; ch = strtok(buff, " "); if (ch != NULL) { ch = strtok(NULL, " "); ch = strtok(NULL, " "); if (ch == NULL) return -1; strncpy(id2, ch, 8); id2[8] = '\0'; ch = strtok(NULL, " "); if (ch == NULL) return -1; strncpy(mess, ch, 200); mess[200] = '\0'; return 1; } return -1; } int treat_mesa(char *buff, char *id, char *mess) { return treat_mesp(buff, id, mess); } int treat_fant(char *buff, int *x, int *y) { char *ch; int r; ch = strtok(buff, " "); if (ch != NULL) { ch = strtok(NULL, " "); if (ch == NULL) return -1; r = stoi(ch, strlen(ch)); if (r == -1) return -1; *x = r; ch = strtok(NULL, " "); if (ch == NULL) return -1; r = stoi(ch, strlen(ch)); if (r == -1) return -1; *y = r; return 1; } return -1; } int treat_scor(char *buff, char *id, int *point, int *x, int *y) { char *ch; int r; ch = strtok(buff, " "); if (ch != NULL) { //get id ch = strtok(NULL, " "); if (ch == NULL) return -1; strncpy(id, ch, 8); id[8] = '\0'; ch = strtok(NULL, " "); if (ch == NULL) return -1; r = stoi(ch, strlen(ch)); if (r == -1) return -1; *point = r; ch = strtok(NULL, " "); if (ch == NULL) return -1; r = stoi(ch, strlen(ch)); if (r == -1) return -1; *x = r; ch = strtok(NULL, " "); if (ch == NULL) return -1; r = stoi(ch, strlen(ch)); if (r == -1) return -1; *y = r; return 1; } return -1; } int treat_end(char *buff, char *id, int *point) { char *ch; int r; ch = strtok(buff, " "); if (ch != NULL) { //get id ch = strtok(NULL, " "); if (ch == NULL) return -1; strncpy(id, ch, 8); id[8] = '\0'; ch = strtok(NULL, " "); if (ch == NULL) return -1; r = stoi(ch, strlen(ch)); if (r == -1) return -1; *point = r; return 1; } return -1; } int treat_mov(char *buff,int *x, int *y, int *point) { char *ch; int r; int ret = 1; ch = strtok(buff, " "); if (ch != NULL) { if (strcmp(ch, "MOV") == 0) ret = 0; else if (strcmp(ch, "MOF") == 0) ret = 1; ch = strtok(NULL, " "); if (ch == NULL) return -1; r = stoi(ch, strlen(ch)); if (r == -1) return -1; *x = r; ch = strtok(NULL, " "); if (ch == NULL) return -1; r = stoi(ch, strlen(ch)); if (r == -1) return -1; *y = r; if ( ret ) { ch = strtok(NULL, " "); if (ch == NULL) return -1; r = stoi(ch, strlen(ch)); if (r == -1) return -1; *point = r; } return ret; } return -1; } int treat_glist(char *buff, int *nb_player) { char *ch; ch = strtok(buff, " "); int r; if (ch != NULL) { if (strcmp(ch, "GLIST!") != 0) return -1; ch = strtok(NULL, " "); if (ch == NULL) return -1; r = stoi(ch, strlen(ch)); if (r == -1) return -1; *nb_player = r; return 1; } return 0; } int treat_gplayer(char *buff, char *id, int *x, int *y, int *point) { char *ch; ch = strtok(buff, " "); int r; if (ch != NULL) { if (strcmp(ch, "GPLAYER") != 0) return -1; ch = strtok(NULL, " "); if (ch == NULL) return -1; strncpy(id, ch, 8); id[8] = '\0'; ch = strtok(NULL, " "); if (ch == NULL) return -1; r = stoi(ch, strlen(ch)); if (r == -1) return -1; *x = r; ch = strtok(NULL, " "); if (ch == NULL) return -1; r = stoi(ch, strlen(ch)); if (r == -1) return -1; *y = r; ch = strtok(NULL, " "); if (ch == NULL) return -1; r = stoi(ch, strlen(ch)); if (r == -1) return -1; *point = r; return 1; } return 0; }
C
#include <stdlib.h> #include <stdio.h> #include <string.h> struct inputValue { char name[4]; char orbit[4]; int hand; }; int calculateRows(FILE* file) { char name[4]; char orbiter[4]; int count = 0; while(fscanf(file, "%c%c%c)%c%c%c\n",&name[0], &name[1], &name[2], &orbiter[0], &orbiter[1], &orbiter[2])>0) { count++; } rewind(file); return count; } void readInput(FILE* file, struct inputValue* in) { char input[10] = {0}; struct inputValue value = { .name = "NUL", .orbit = "NUL", .hand = 0 }; int count = 0; while(fscanf(file, "%s\n",input)>0) { strncpy(value.name, strtok(input, ")"), 4); strncpy(value.orbit, strtok(NULL, ")"), 4); in[count] = value; count++; } } void printPlanets(struct inputValue* in, int len) { for(int i = 0; i < len; i++) { printf("%s)%s \n", in[i].name, in[i].orbit); } } int done(struct inputValue* in, int len) { for(int i = 0; i < len; i++) { if(in[i].hand == 0) { return 0; } } return 1; } void calculateOrbits(struct inputValue* in, int len) { int dir = 0; int indir = 0; char (*curr)[4] = malloc(len/3 * sizeof(char) * 4); char (*next)[4] = malloc(len/3 * 4); int nCounter = 0; int clen = 1; int level = 0; strncpy(curr[0], "COM", 4); while(!done(in, len) && level < 2350) { for(int i = 0; i<clen; i++) { for(int j = 0; j<len; j++) { if(strcmp(in[j].name, curr[i]) == 0) { in[j].hand = 1; strncpy(next[nCounter], in[j].orbit, 4); nCounter++; } } } clen = nCounter; nCounter = 0; dir += clen; level++; indir += (clen * (level)); memcpy(curr, next, len/3); memset(next, 0, len/3); } printf("Direct: %d, Indirect: %d, Sum: %d", dir, indir, dir+indir); } int main() { FILE* file; file = fopen("inputday6.txt", "r"); int length = calculateRows(file); struct inputValue* in = malloc(length*sizeof(struct inputValue)); readInput(file, in); calculateOrbits(in, length); printf("End of program"); return 0; }
C
/* Collector.c - A simple garbage collector. * Copyright (C) 2011 Rob King <[email protected]> * * This file is part of DPGC. * * DPGC is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * DPGC is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with DPGC. If not, see <http://www.gnu.org/licenses/>. */ #include <assert.h> #include <stddef.h> #include <stdlib.h> #include "collector.h" #ifndef STEP_FACTOR #define STEP_FACTOR 3 #endif enum{ WHITE, GRAY, BLACK }; #define validcollector(obj) \ do{ \ assert(obj != NULL); \ assert(obj->pauses == 0 ? obj->roots != NULL : 1); \ assert(obj->pauses == 0 ? obj->touch != NULL : 1); \ assert(obj->pauses == 0 ? obj->dispose != NULL : 1); \ } while(0) #define validlist(obj) \ do{ \ assert(obj != NULL); \ assert(obj->prev != NULL ? obj->prev->next == obj : 1); \ assert(obj->next != NULL ? obj->next->prev == obj : 1); \ } while(0) #define validobj(obj) \ do{ \ validlist(obj); \ assert(obj->color == WHITE || obj->color == GRAY \ || obj->color == BLACK); \ } while(0) #define remove(head, object) \ do{ \ assert(head != NULL); \ validlist(object); \ if(head == object){ \ head = object->next; \ if(object->next != NULL) \ object->next->prev = NULL; \ } else{ \ if(object->prev != NULL) \ object->prev->next = object->next; \ \ if(object->next != NULL) \ object->next->prev = object->prev; \ validlist(head); \ } \ object->next = NULL; \ object->prev = NULL; \ } while(0) #define insert(head, object) \ do{ \ assert(head != object); \ validlist(object); \ if(head == NULL){ \ head = NULL; \ object->prev = NULL; \ object->next = NULL; \ head = object; \ } else{ \ assert(head->prev == NULL); \ head->prev = object; \ object->next = head; \ object->prev = NULL; \ head = object; \ } \ validlist(head); \ } while(0) Collector * makecollector(Marker touch, Disposer dispose) { Collector *collector; collector = calloc(1, sizeof(Collector)); if(collector != NULL){ collector->deferrals = 0; collector->pauses = 1; collector->touch = touch; collector->dispose = dispose; } return collector; } int isroot(Collector *collector, Collectee *obj) { Root *root; validcollector(collector); validobj(obj); root = collector->roots; while(root != NULL && root->root != obj) root = root->next; return root != NULL && root->root == obj; } int addroot(Collector *collector, Collectee *obj) { Root *root; validcollector(collector); validobj(obj); assert(collector->pauses > 0); assert(!isroot(collector, obj)); root = calloc(1, sizeof(Root)); if(root != NULL){ obj->color = GRAY; insert(collector->grays, obj); root->root = obj; insert(collector->roots, root); } return root != NULL; } void removeroot(Collector *collector, Collectee *obj) { Root *root; validcollector(collector); validobj(obj); assert(collector->pauses > 0); assert(isroot(collector, obj)); assert(obj->color == GRAY || obj->color == BLACK); assert((((char *)obj) - offsetof(struct Root, root)) > 0); root = (Root *)(obj - offsetof(struct Root, root)); validobj(root->root); remove(collector->roots, root); assert(collector->roots != NULL); } void addobj(Collector *collector, Collectee *obj, Collectee *ref) { validcollector(collector); validobj(obj); assert(collector->pauses > 0); assert(STEP_FACTOR >= 0); assert(obj->prev == NULL); assert(obj->next == NULL); assert(obj->color == WHITE); insert(collector->whites, obj); obj->color = WHITE; collector->count++; if(ref != NULL){ validobj(ref); assert(isroot(collector, ref) || ref->prev != NULL || ref->next != NULL); addref(collector, ref, obj); } stepgc(collector, STEP_FACTOR); } void recolor(Collector *collector, Collectee *obj, int color) { validcollector(collector); validobj(obj); assert(color == WHITE || color == GRAY || color == BLACK); assert(obj->color == BLACK ? color == BLACK : 1); assert(obj->color == GRAY ? color == GRAY || color == BLACK : 1); assert(obj->color == WHITE ? color == GRAY || color == BLACK : 1); if(obj->color != color){ switch(obj->color){ case WHITE: remove(collector->whites, obj); break; case GRAY: remove(collector->grays, obj); break; case BLACK: remove(collector->blacks, obj); break; } switch(color){ case WHITE: insert(collector->whites, obj); break; case GRAY: insert(collector->grays, obj); break; case BLACK: insert(collector->blacks, obj); break; } obj->color = color; } } void touchobj(Collector *collector, Collectee *obj) { validcollector(collector); validobj(obj); if(obj->color == WHITE) recolor(collector, obj, GRAY); } void addref(Collector *collector, Collectee *referer, Collectee *referee) { validcollector(collector); validobj(referer); validobj(referee); assert(collector->pauses > 0); if(referer->color == GRAY || referer->color == BLACK) recolor(collector, referee, GRAY); } void stepgc(Collector *collector, unsigned int steps) { Collectee *next; Collectee *obj; Root *root; Root *nextroot; validcollector(collector); if(collector->pauses > 0) collector->deferrals += steps; else{ while(steps > 0 && collector->grays != NULL){ if(collector->touch(collector, collector->grays)) recolor(collector, collector->grays, BLACK); steps--; } if(collector->grays == NULL){ obj = collector->whites; while(obj != NULL){ assert(!isroot(collector, obj)); assert(obj->color == WHITE); next = obj->next; remove(collector->whites, obj); collector->dispose(collector, obj); collector->count--; obj = next; } root = collector->roots; while(root != NULL){ assert(root->root->color == BLACK); nextroot = root->next; remove(collector->blacks, root->root); insert(collector->grays, root->root); root->root->color = GRAY; root = nextroot; } obj = collector->blacks; while(obj != NULL){ assert(obj->color == BLACK); next = obj->next; remove(collector->blacks, obj); insert(collector->whites, obj); obj->color = WHITE; obj = next; } } } } void pausegc(Collector *collector) { validcollector(collector); collector->pauses++; } void unpausegc(Collector *collector) { validcollector(collector); assert(collector->pauses > 0); collector->pauses--; if(collector->pauses == 0){ stepgc(collector, collector->deferrals); collector->deferrals = 0; } } void * gcalloc(Collector *collector, size_t size) { void *rc; validcollector(collector); assert(size > 0); assert(STEP_FACTOR >= 0); rc = calloc(1, size); while(rc == NULL && collector->pauses == 0 && collector->grays != NULL){ stepgc(collector, STEP_FACTOR); rc = calloc(1, size); } return rc; }
C
/* * File: Programa_principal.c * Author: Wels * * Created on 20 de marzo de 2020, 05:14 PM */ #include "xc.h" #include <stdint.h> #include <stdio.h> #include "Configuracion.h" #include <libpic30.h> #include "LCD_Libreria.h" #include "ADC_Libreria.h" #include "Interrupcion_Libreria.h" uint16_t valor_adc = 0; float voltaje = 0.0; char datos[10]; int main(void) { ADC_Init(); INT0_Init(); LCD_Init(); LCD_XY(1,5); LCD_Caracter('E'); LCD_XY(0,1); LCD_String("Hola Como estas"); __delay_ms(500); LCD_XY(0,1); LCD_String(" Suscribete :D "); LCD_Comando(0x01); ADCON1bits.ASAM = 1; // Muestro automatico while(1){ /*** MUESTRO AUTOMATICO Y CONVERSION MANUAL ***/ // ADCON1bits.SAMP = 0; // valor_adc = ADCBUF0; // voltaje = valor_adc*(5.0/4096);// 5/ 4096 // sprintf(datos,"Voltaje es: %0.2F V",voltaje);//2.45 // LCD_XY(0,0); // LCD_String(datos); /*** MUESTRO AUTOMATICO Y CONVERSION INT0 ***/ while(!ADCON1bits.DONE); valor_adc = ADCBUF0; voltaje = valor_adc*(5.0/4096);// 5/ 4096 sprintf(datos,"Voltaje es: %0.2F V",voltaje);//2.45 LCD_XY(0,0); LCD_String(datos); } }
C
#include <stdio.h> #include <stdlib.h> #include "lists.h" /** *pop_listint - this function will print the value of the head and remove it *@head: the pointer to the current head *Return: returns the current value of the head before removing it */ int pop_listint(listint_t **head) { listint_t *temp = *head; int value = 0; if (temp == NULL) return (0); value = temp->n; *head = temp->next; free(temp); return (value); }
C
#include "eval.h" lval* lval_eval_sexpr(lenv* e, lval* v){ // evaluate children for (int i = 0; i < v-> count; i++) { v -> cell[i] = lval_eval(e, v -> cell[i]); } // error checking for (int i = 0; i < v-> count; i++) { if(v -> cell[i] -> type == LVAL_ERR){ return lval_take(v, i); } } // empty expression if(v -> count == 0){ return v; } // single expression if(v -> count == 1){ return lval_take(v, 0); } // ensure first element is symbol lval* f = lval_pop(v, 0); if(f -> type != LVAL_FUN) { return lval_err("S expr starts with incorrect type. Got %s, Expected %s", ltype_name(f -> type), ltype_name(LVAL_FUN)); lval_del(f); lval_del(v); } // calculate lval* result = lval_call(e, f, v); lval_del(f); return result; } lval* lval_eval(lenv* e, lval *v){ if(v -> type == LVAL_SYM){ lval* x = lenv_get(e, v); lval_del(v); return x; } // evaluate s expressions if (v -> type == LVAL_SEXPR) { return lval_eval_sexpr(e, v); } return v; } // calling a function (builtin or user defined) lval* lval_call(lenv* e, lval* f, lval* a){ // if builtin call func if(f -> builtin){ return f -> builtin(e, a); } // record number of args int given = a -> count; int total = f -> formals -> count; while(a -> count){ if(f -> formals -> count == 0){ lval_del(a); return lval_err("Function passed too many args. Got %i, Expected %i", given, total); } // pop symbol from formals lval* sym = lval_pop(f -> formals, 0); // special case of & if(strcmp(sym -> sym, "&") == 0){ // & has to be followed by another symbol if(f -> formals -> count != 1){ lval_del(a); return lval_err("Function format invalid. & should be followed by a single symbol"); } lval* nsym = lval_pop(f -> formals, 0); lenv_put(f -> env, nsym, builtin_list(e, a)); lval_del(sym); lval_del(nsym); break; } // pop the next arg from the list lval* val = lval_pop(a, 0); lenv_put(f -> env, sym, val); // clear up symbol and value lval_del(sym); lval_del(val); } lval_del(a); // if `&` remains in formal argument list, but no args are passed to func if(f -> formals -> count > 0 && (strcmp(f -> formals -> cell[0] -> sym, "&") == 0)){ // check for valid & formal args if(f -> formals -> count != 2){ return lval_err("Function format invalid. & should be followed by a single symbol"); } // remove and lval_del(lval_pop(f -> formals, 0)); lval* sym = lval_pop(f -> formals, 0); lval* val = lval_qexpr(); // bind to env and delete lenv_put(f -> env, sym, val); lval_del(sym); lval_del(val); } if(f -> formals -> count == 0){ // set parent env f -> env -> par = e; // eval and return return builtin_eval(f -> env, lval_add(lval_sexpr(), lval_copy(f -> body))); } else { // return copy of new func return lval_copy(f); } } lval* lval_pop(lval* v, int i){ // get item at i lval* x = v -> cell[i]; // shift memory after item i to i memmove(&v -> cell[i], &v -> cell[i + 1], sizeof(lval*) * (v -> count-i-1)); //decrement count v -> count--; // reallocate memory v -> cell = realloc(v->cell, sizeof(lval*) * v->count); return x; } lval* lval_take(lval* v, int i){ lval* x = lval_pop(v, i); lval_del(v); return x; } lval* builtin_head(lenv* e, lval* a){ // head should have only 1 args LASSERT(a, (a -> count == 1), "Function `head` has too many arguments"); // argument should be a q-epr LASSERT(a, (a -> cell[0] -> type == LVAL_QEXPR), "Function `head` passed incorrect type!"); // qexpr should not be empty LASSERT(a, (a -> cell[0] -> count != 0), "Function `head` passed empty q-epr!"); // otherwise take 1st child or qexpr lval* v = lval_take(a, 0); // delete all elements that are not head and return while( v -> count > 1){ lval_del(lval_pop(v, 1)); } return v; } lval* builtin_tail(lenv* e, lval* a){ // tail should have only 1 args LASSERT(a, (a -> count == 1), "Function `tail` has too many arguments"); // argument should be a q-epr LASSERT(a, (a -> cell[0] -> type == LVAL_QEXPR), "Function `tail` passed incorrect type!"); // qexpr should not be empty LASSERT(a, (a -> cell[0] -> count != 0), "Function `tail` passed empty q-epr!"); // otherwise take 1st arg lval* v = lval_take(a, 0); // delete first element and return lval_del(lval_pop(v, 0)); return v; } lval* builtin_list(lenv* e, lval* a){ a -> type = LVAL_QEXPR; return a; } lval* builtin_eval(lenv* e, lval* a){ LASSERT(a, (a -> count == 1), "Function `eval` passed too many arguments!"); LASSERT(a, (a -> cell[0] -> type == LVAL_QEXPR), "Function `eval` passed incorrect type!"); lval* x = lval_take(a, 0); x -> type = LVAL_SEXPR; return lval_eval(e, x); } lval* lval_join(lval* x, lval* y){ // push elements of y into x while(y -> count){ x = lval_add(x, lval_pop(y, 0)); } //delete y and return x lval_del(y); return x; } lval* builtin_join(lenv* e, lval* a){ for(int i = 0; i < a -> count; i++){ LASSERT(a, (a-> cell[i] -> type == LVAL_QEXPR), "Function `join` passed incorrtect type"); } lval* x = lval_pop(a, 0); while(a -> count){ x = lval_join(x, lval_pop(a, 0)); } lval_del(a); return x; } lval* builtin_op(lenv* e, lval* a, char* op){ // all args should be numbers for (int i = 0; i < a -> count; i++){ if(a -> cell[i] -> type != LVAL_NUM){ lval_del(a); return lval_err("%s cannot operate on non-number. Found %s, Expected %s", op, ltype_name(a -> cell[i] -> type), ltype_name(LVAL_NUM)); } } //pop first element lval* x = lval_pop(a, 0); //if no arguments and op is "-" negate value if((strcmp(op, "-") == 0) && (a -> count == 0)){ x -> num = - x -> num; } while(a -> count > 0){ lval* y = lval_pop(a, 0); if(strcmp(op, "+") == 0){ x -> num += y -> num; } if(strcmp(op, "-") == 0){ x -> num -= y -> num; } if(strcmp(op, "*") == 0){ x -> num *= y -> num; } if(strcmp(op, "/") == 0){ if(y -> num == 0){ lval_del(a); lval_del(y); return lval_err("divisions by zero"); } x -> num /= y -> num; } lval_del(y); } lval_del(a); return x; } lval* builtin_gt(lenv* e, lval* a){ return builtin_ord(e, a, ">"); } lval* builtin_lt(lenv* e, lval* a){ return builtin_ord(e, a, "<"); } lval* builtin_ge(lenv* e, lval* a){ return builtin_ord(e, a, ">="); } lval* builtin_le(lenv* e, lval* a){ return builtin_ord(e, a, "<="); } lval* builtin_ord(lenv* e, lval* a, char* op){ LASSERT_NUM(op, a, 2); LASSERT_TYPE(op, a, 0, LVAL_NUM); LASSERT_TYPE(op, a, 1, LVAL_NUM); int r; if (strcmp(op, ">") == 0) { r = (a->cell[0]->num > a->cell[1]->num); } if (strcmp(op, ">=") == 0) { r = (a->cell[0]->num >= a->cell[1]->num); } if (strcmp(op, "<") == 0) { r = (a->cell[0]->num < a->cell[1]->num); } if (strcmp(op, "<=") == 0) { r = (a->cell[0]->num <= a->cell[1]->num); } lval_del(a); return lval_num(r); } lval* builtin_cmp(lenv* e, lval* a, char *op){ LASSERT_NUM(op, a, 2); int r; if(strcmp(op, "==") == 0){ r = lval_eq(a -> cell[0], a -> cell[1]); } if(strcmp(op, "!=") == 0){ r = !lval_eq(a -> cell[0], a -> cell[1]); } lval_del(a); return lval_num(r); } lval* builtin_eq(lenv* e, lval* a){ return builtin_cmp(e, a, "=="); } lval* builtin_ne(lenv* e, lval* a){ return builtin_cmp(e, a, "!="); } lval* builtin_if(lenv* e, lval* a){ LASSERT_NUM("if", a, 3); LASSERT_TYPE("if", a, 0, LVAL_NUM); LASSERT_TYPE("if", a, 1, LVAL_QEXPR); LASSERT_TYPE("if", a, 2, LVAL_QEXPR); // convert noth expr to s-exp for evaluation a -> cell[1] -> type = LVAL_SEXPR; a -> cell[2] -> type = LVAL_SEXPR; lval* r; // if comdition true eval first if(a -> cell[0] -> num){ r = lval_eval(e, lval_pop(a, 1)); } else { r = lval_eval(e, lval_pop(a, 2)); } lval_del(a); return r; } lval* builtin_def(lenv* e, lval* a){ return builtin_var(e, a, "def"); } lval* builtin_put(lenv* e, lval* a){ return builtin_var(e, a, "="); } lval* builtin_var(lenv* e, lval* a, char* func){ LASSERT_TYPE(func, a, 0, LVAL_QEXPR); // first argument to symbol list, ie, name of variables lval* syms = a -> cell[0]; // all names should be symbols for (int i = 0; i < syms -> count; ++i) { LASSERT(a, (syms -> cell[i] -> type == LVAL_SYM), "Function %s cannot define non symbol. Got %s, Expected %s", func, ltype_name(syms -> cell[i] -> type), ltype_name(LVAL_SYM)); } LASSERT(a, (syms -> count == a -> count -1) , "Funtion %s passed incorrect number of values. Got %i, Expected %i ", syms -> count, a -> count -1); for (int i = 0; i < syms -> count; ++i) { // If 'def' define in globally. If 'put' define in locally if (strcmp(func, "def") == 0) { lenv_def(e, syms -> cell[i], a -> cell[i+1]); } if (strcmp(func, "=") == 0) { lenv_put(e, syms -> cell[i], a -> cell[i+1]); } } lval_del(a); return lval_sexpr(); } lval* builtin_lambda(lenv* e, lval* a){ // check 2 args, both q -expr LASSERT_NUM("\\", a, 2); LASSERT_TYPE("\\", a, 0, LVAL_QEXPR); LASSERT_TYPE("\\", a, 1, LVAL_QEXPR); // check first q expr only contains symbols for (int i = 0; i < a -> cell[0] -> count; i++) { LASSERT(a, (a -> cell[0] -> cell[i] -> type == LVAL_SYM), "Cannot define non symbol. Got %s, Expected %s", ltype_name(a -> cell[0] -> cell[i] -> type), ltype_name(LVAL_SYM)); } // pop first 2 args and make lval lambda lval* formals = lval_pop(a, 0); lval* body = lval_pop(a, 0); lval_del(a); return lval_lambda(formals, body); } lval* builtin_add(lenv* e, lval* a) { return builtin_op(e, a, "+"); } lval* builtin_sub(lenv* e, lval* a) { return builtin_op(e, a, "-"); } lval* builtin_mul(lenv* e, lval* a) { return builtin_op(e, a, "*"); } lval* builtin_div(lenv* e, lval* a) { return builtin_op(e, a, "/"); } lval* builtin_load(lenv* e, lval* a){ LASSERT_NUM("load", a, 1); LASSERT_TYPE("load", a, 0, LVAL_STR); mpc_parser_t* parser = e -> parser; lenv* env = e; while(env -> par && !parser){ if(env -> parser != NULL){ parser = env -> parser; } else { env = env -> par; } } if(!parser){ return lval_err("Min language parser not found in scope. Could not import file %s", a -> cell[0] -> str); } // parse file given by lval mpc_result_t r; if(mpc_parse_contents(a -> cell[0] -> str, parser, &r)){ // read contents lval* expr = lval_read(r.output); mpc_ast_delete(r.output); // eval each expression while(expr -> count){ lval* x = lval_eval(e, lval_pop(expr, 0)); // if error print error if(x -> type == LVAL_ERR){ lval_println(x); } lval_del(x); } // free expression and arguments lval_del(expr); lval_del(a); // return empty sexpr return lval_sexpr(); } else { // get lval_err from error message char* err_msg = mpc_err_string(r.error); lval* err = lval_err("Could not load file %s. \n %s", a -> cell[0] -> str, err_msg); free(err_msg); lval_del(a); return err; } } lval* builtin_print(lenv* e, lval* a){ // print each argument separated by spaces for (int i = 0; i < a -> count; i++) { lval_print(a -> cell[i]); putchar(' '); } putchar('\n'); lval_del(a); return lval_sexpr(); } lval* builtin_error(lenv* e, lval* a){ LASSERT_NUM("error", a, 1); LASSERT_TYPE("error", a, 0, LVAL_STR); lval* err = lval_err(a -> cell[0] -> str); lval_del(a); return err; } void lenv_add_builtins(lenv* e){ /* List Functions */ lenv_add_builtin(e, "list", builtin_list); lenv_add_builtin(e, "head", builtin_head); lenv_add_builtin(e, "tail", builtin_tail); lenv_add_builtin(e, "eval", builtin_eval); lenv_add_builtin(e, "join", builtin_join); //def function to define variables/ functions lenv_add_builtin(e, "\\", builtin_lambda); lenv_add_builtin(e, "def", builtin_def); lenv_add_builtin(e, "=", builtin_put); /* Mathematical Functions */ lenv_add_builtin(e, "+", builtin_add); lenv_add_builtin(e, "-", builtin_sub); lenv_add_builtin(e, "*", builtin_mul); lenv_add_builtin(e, "/", builtin_div); /* Comparison Functions */ lenv_add_builtin(e, "if", builtin_if); lenv_add_builtin(e, "==", builtin_eq); lenv_add_builtin(e, "!=", builtin_ne); lenv_add_builtin(e, ">", builtin_gt); lenv_add_builtin(e, "<", builtin_lt); lenv_add_builtin(e, ">=", builtin_ge); lenv_add_builtin(e, "<=", builtin_le); lenv_add_builtin(e, "import", builtin_load); lenv_add_builtin(e, "print", builtin_print); lenv_add_builtin(e, "error", builtin_error); }
C
#include <stdlib.h> #include <stdio.h> #include <string.h> #include <fcntl.h> #include "dbAccess.h" #include "../../database/src/db.h" static struct flock fl = {.l_start = 0, .l_whence = SEEK_SET, .l_len = 0}; List_Movies get_movies(){ int fd; List_Movies list; FILE *file = fopen(MOVIES_PATH, "rb+"); if( file == NULL ){ printf("Invalid movie code: not found in database\n"); return list; } fd=fileno(file); if( rdlockFile(fd) == -1){ printf("Impossible to show movies."); return list; } fread(list.movies_list, sizeof(Movie), CANT_MOVIES, file); unlockFile(fd); fclose(file); return list; } void get_moviePath(char* moviePath,char* id, char* time){ char movieID[10]; strcpy(movieID, id); strcat(movieID, "-"); strcat(movieID, time); sprintf(moviePath, MOVIE_PATH, movieID); } int get_seats(char* id, char* time){ FILE *file; int seats,fd; char moviePath[40]; get_moviePath(moviePath,id,time); file=fopen(moviePath, "rb+"); if(file==NULL){ printf("The entered data doesn´t correspond to an available screening. \n"); return -1; } fd=fileno(file); if( rdlockFile(fd) == -1){ printf("Reservation could not be completed. Please, try again later."); return -1; } fread(&seats, sizeof(int), 1, file); unlockFile(fd); fclose(file); return seats; } void reserve_seat(char* id, char* time, int n){ FILE * file; int seats, fd; char moviePath[40]; get_moviePath(moviePath,id,time); file=fopen(moviePath, "rb+"); if(file==NULL){ printf("The entered data doesn´t correspond to an available screening.hhh \n"); return; } fd=fileno(file); if( wrlockFile(fd) == -1){ printf("It was not possible to make the reservation. Try again later.\n"); return; } fread(&seats, sizeof(int), 1, file); if( seats < n ){ printf("Sorry, no seats available.\n"); return; } seats=seats-n; fseek(file, 0, SEEK_SET); fwrite(&seats, sizeof(int), 1, file); unlockFile(fd); fclose(file); printf("The seats have been successfully reserved.\n"); return; } int rdlockFile(int fd){ fl.l_type = F_RDLCK; return fcntl(fd, F_SETLKW, &fl); } int wrlockFile(int fd){ fl.l_type = F_WRLCK; return fcntl(fd, F_SETLKW, &fl); } int unlockFile(int fd){ fl.l_type = F_UNLCK; return fcntl(fd, F_SETLKW, &fl); } void get_times(char times[5][5]){ FILE *file = fopen(TIMES, "rb+"); if( file == NULL ){ printf("Invalid time: not found in database\n"); return ; } fread(times, 5, CANT_TIMES, file); fclose(file); }
C
#include <stdio.h> #include <stdlib.h> #include "Funciones.h" #define T 20 int main() { char nombre[T]; char apellido[T]; char apellidoNombre[T+T]; pedirCadena("NOMBRE",nombre, T); pedirCadena("APELLIDO",apellido, T); formatearCadena(apellidoNombre, nombre, apellido); printf("\n\nLa salida es: %s", apellidoNombre); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <time.h> #define N 10 /* */ int main() { int a[]={1,1,1,2,3,3,3,3,4,5}; /* a N */ int i,j,max,current,count; /* */ srand(time(NULL)); /* */ for(i = 0; i < N; i++){ printf(" %d", a[i]); } printf(";\n"); max = 0; for(i = 0; i < N; i++){ current = a[i]; count = 0; for(j = 0; j < N; j++){ if(a[j]==current){ count+=1; } } if(count>max){ max = count; } } printf("The most frequent number occurs %d times",max); return 0; }
C
#include <stdio.h> void main (){ float folhas = 0; float valor = 0.25; printf("Quantas folhas voce quer xerox? "); scanf("%f", &folhas); float res = folhas * valor; float resDesconto = folhas * (valor - 0.05); if(folhas < 100){ printf("Voce me deve %.2f\n", res); }else if(folhas >= 100){ printf("Voce me deve %.2f\n", resDesconto); }else{ printf("Deu ruim!"); } }
C
/*͂Ă邤NǂׂvOł*/ #include<stdio.h> int main(void) { int a; printf("͂Ă:"); scanf("%d",&a); if(a%4==0 && (a%100!=0 || a%400==0)){ printf("͂͂邤NłB"); } else{ printf("͂͂邤Nł͂܂B"); } return(0); }
C
#include<stdio.h> #include<string.h> int main() { char str1[100],str2[100]; int len1, len2, max, min, carry, i, sum=0, count=0,result[100]; printf("Enter your first number:\n"); scanf(" %s",str1); printf("Enter your second number:\n"); scanf(" %s",str2); len1=strlen(str1); len2=strlen(str2); max=len1; if(len1<len2) { max=len2; } strrev(str1); strrev(str2); carry=0; for(i=0; i<max; i++) { if(len1==len2 || (i<len1 && i<len2)) { sum= ((str1[i]-'0')+(str2[i]-'0')+carry); } else if(i>len1) { sum=carry+(str2[i]-'0'); } else if(i>len2) { sum=carry+(str1[i]-'0'); } result[i]=sum%10; count++; carry=sum/10; } if(carry!=0) { result[count+1]=carry; } for(i=count-1; i>=0; i--) { printf("%d",result[i]); } return 0; }
C
#include "common.h" #include "constants.h" #include "context-helpers.h" #include "objectMemory-objects.h" #include "objectMemory-smallIntegers.h" // optimization: replaced with macros #ifndef OPTIMIZED_MACROS OP fetchContextSender(OP context) { return fetchNamedPointer(context, METHODCONTEXT_SENDER); } OP fetchContextReceiver(OP context) { return fetchNamedPointer(context, METHODCONTEXT_RECEIVER); } OP fetchContextMethod(OP context) { return fetchNamedPointer(context, METHODCONTEXT_METHOD); } OP fetchContextClosure(OP context) { return fetchNamedPointer(context, METHODCONTEXT_CLOSURE); } OP fetchContextOuterContext(OP context) { return fetchNamedPointer(context, METHODCONTEXT_OUTER_CONTEXT); } OP fetchClosureOuterContext(OP closure) { return fetchNamedPointer(closure, BLOCKCLOSURE_OUTER_CONTEXT); } OP fetchMethodLiteral(OP method, int index) { return fetchIndexablePointer(method, index); } OP fetchContextTemporary(OP context, int index) { OP outerContext = fetchContextOuterContext(context); return fetchIndexablePointer(outerContext, index); } OP storeContextTemporary(OP context, int index, OP value) { OP outerContext = fetchContextOuterContext(context); storeIndexablePointer(outerContext, index, value); } #endif
C
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <fcntl.h> #include <ctype.h> #include <string.h> #define MAX 512 int main(int argc, char *argv[]) { if (argc < 3) { fprintf(stderr, "Za malo argumentow. Uzyj:\n%s <plik zrodlowy> <plik docelowy>\n", argv[0]); exit(1); } FILE *in, *out; in = fopen(argv[1], "r"); out = fopen(argv[2], "w"); if (in == NULL) { perror("Blad otwarcia pliku odczytu"); exit(1); } if (out == NULL) { perror("Blad otwarcia pliku zapisu"); exit(1); } printf("Plik zrodlowy: %s\n", argv[1]); printf("Plik docelowy: %s\n", argv[2]); char *c; while (!feof(in)) { char napis[MAX]; c = fgets(napis, MAX, in); if (c != NULL) { fputs(strrev(c), out); } } fclose(in); fclose(out); }
C
#include <stdio.h> void reverse(char s[]); int main(void) { char s[] = "hello"; reverse(s); printf("%s\n", s); reverse(s); printf("%s\n", s); return 0; } void reverse(char s[]) { static int i, j; char tmp; if (i == 0) { while (s[i] != '\0') ++i; --i; } if (i > j) { tmp = s[j]; s[j++] = s[i]; s[i--] = tmp; reverse(s); } else { i = j = 0; } }
C
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <omp.h> double initialCondition(double x, double y); void writeheader(int N, int end); void writerow(int N, double rawdata[]); void printArray(double **array, int local_N, int N); int main(int argc, char *argv[]) { int comm_sz = 1; int my_rank = 0; int N = 10; int local_N; int end = 2;//end=20N is roughly 1 period //int writeoutput = 1;//0 for false double x,y,local_x, local_y; int i,j; //comm_sz = omp_get_num_threads(); //my_rank = omp_get_thread_num(); local_N = N/comm_sz;//assuming divisible if (N%comm_sz!=0) { printf("ERROR N must be divisible by thread_count. Terminating."); exit(1); } if (local_N<2) { printf("ERROR N (%d) must be at least twice as large as number of processes (%d). Terminating.",N,comm_sz); exit(1); } double** f0 = (double**)malloc(sizeof(double*)*N); double** f1 = (double**)malloc(sizeof(double*)*N); double** fend = (double**)malloc(sizeof(double*)*N); f0[0] = (double*)malloc(sizeof(double) * local_N * N); f1[0] = (double*)malloc(sizeof(double) * local_N * N); fend[0] = (double*)malloc(sizeof(double) * local_N * N); for (i=1; i<local_N; i++){ f0[i] = (*f0 + local_N * i); f1[i] = (*f1 + local_N * i); fend[i] = (*fend + local_N * i); } double **originalf0 = f0; double **originalf1 = f1; double **originalfend = fend; local_x = 1.0/(N-1)*my_rank*local_N; local_y = 1.0/(N-1)*my_rank*local_N; for (i=0; i < local_N; i++){ for (j=0; j < N; j++){ x = local_x + (double)i*1.0/(N-1); y = local_y + (double)j*1.0/(N-1); f0[i][j] = initialCondition(x,y); f1[i][j] = initialCondition(x,y); } } //printArray(f1,local_N, N); f0 = originalf0; f1 = originalf1; fend = originalfend; free(f0); free(f1); free(fend); return 0; } double initialCondition(double x, double y) { //double sigma=0.01;//tight point double sigma=0.1;//wider point double mu=0.5;//center double max = (1.0/(2.0*M_PI*sigma*sigma))*exp(-0.5*( ((0.5-mu)/sigma)*((0.5-mu)/sigma) + ((0.5-mu)/sigma)*((0.5-mu)/sigma) )); double result = (1.0/(2.0*M_PI*sigma*sigma))*exp(-0.5*( ((x-mu)/sigma)*((x-mu)/sigma) + ((y-mu)/sigma)*((y-mu)/sigma) ))/max; return result; } void writeheader(int N, int end) { FILE *fp; fp = fopen("outfile.pgm", "w"); if (fp == NULL) { printf("sorry can't open outfile.pgm. Terminating.\n"); exit(1); } else { // print a table header fprintf(fp, "%s\n%d %d\n%s\n", "P2", N, end, "255"); fclose(fp); } } void writerow(int N, double rawdata[]) { FILE *fp; fp = fopen("outfile.pgm", "a"); if (fp == NULL) { printf("sorry can't open outfile.pgm. Terminating.\n"); exit(1); } else { for (int i=0; i<N; i++) { int val = rawdata[i]*127+127; fprintf(fp,"%d ",val); } fprintf(fp,"\n"); fclose(fp); } } void printArray(double **array, int local_N, int N){ int i,j; for (i=0; i<local_N; i++){ for(j=0; j<N; j++){ printf("%f ", array[i][j]); } printf("\n"); } printf("\n"); }
C
#include <stdio.h> int main() { printf("Pleas enter any number --> \n"); scanf("%d",&num ) } int palindrome(int arr[], int n) { int flag = 0; for (int i = 0; i <= n / 2 && n != 0; i++) { if (arr[i] != arr[n - i - 1]) { flag = 1; break; } } if (flag == 1) return 0; //Not else return 1; //Yes }
C
#ifndef KMER_PACKER_H #define KMER_PACKER_H typedef struct KmerPacker_struct{ unsigned char *packed_buffer; char *unpacked_buffer; unsigned char *scratch_pack_buffer; int kmer_size; int packed_buffer_size; }KmerPacker; KmerPacker *newKmerPacker(int kmersize); void freeKmerPacker(KmerPacker *packer); char *unpackKmer(KmerPacker *packer, const unsigned char *packed_kmer); unsigned char *packKmer(KmerPacker *packer, const char *kmer); /** *Compare packed kmers *@return standard comparator int return */ int comparePackedKmers(const unsigned char *packed_kmer1, const unsigned char *packed_kmer2, int size); /** *reads packed kmer from stream, stores into an internal buffer and * returns a pointer to internal buffer */ unsigned char *readPackedKmerFromStream(KmerPacker *packer, char *stream); #endif
C
#include <stddef.h> #include <stdlib.h> #include <stdio.h> #include <hidapi/hidapi.h> int main(int argc, char *argv[]) { int rc = 0; if ((rc = hid_init())) { fprintf(stderr, "hid_init: %d\n", rc); goto done; } struct hid_device_info *hid_devs = hid_enumerate(0x0d28, 0x0204); if (!hid_devs) { fprintf(stderr, "hid_enumerate: NULL\n"); rc = 1; goto done; } for (struct hid_device_info *dev = hid_devs; dev; dev = dev->next) { fprintf(stdout, "%s\n", dev->path); } done: if (hid_devs) { hid_free_enumeration(hid_devs); } hid_exit(); return -1; }
C
#include<stdio.h> int main(){ long long int i,a,b,c,n,t,j; scanf("%lld",&t); for(j=0;j<t;j++){ a=0; b=1; scanf("%lld",&n); for(i=0;i<=60;i++){ if(i==n) break; c=a+b; a=b; b=c;} printf("Fib(%lld) = %lld\n",n,a);}}
C
/* ****************************************************************** */ /* _____ _ __ */ /* By: Sergey Nikolaev / ___// | / / */ /* Сontacts: [email protected] \__ \/ |/ / */ /* Created: 2020.01.08 (YYYY.MM.DD) ___/ / /| / */ /* Updated: 2020.10.21 (YYYY.MM.DD) /____/_/ |_/ */ /* */ /* ****************************************************************** */ #include "ft_printf.h" void ft_fm_percent(t_format_list_el *lst) { size_t len; lst->str_size = 1; if ((lst->str = malloc(sizeof(*(lst->str)) * 2)) == NULL) { ft_fm_list_free(&lst); exit(0); } lst->str[0] = '%'; lst->str[1] = '\0'; len = (lst->str_size < (size_t)lst->modifiers.width) ? (size_t)lst->modifiers.width : lst->str_size; ft_fill_str(lst, len); } void ft_fm_char(t_format_list_el *lst) { size_t len; lst->str_size = 1; if ((lst->str = malloc(sizeof(*(lst->str)) * 2)) == NULL) { ft_fm_list_free(&lst); exit(0); } lst->str[0] = lst->param.c; lst->str[1] = '\0'; len = (lst->str_size < (size_t)lst->modifiers.width) ? (size_t)lst->modifiers.width : lst->str_size; ft_fill_str(lst, len); } void ft_fm_wchar(t_format_list_el *lst) { size_t len; lst->str_size = convert_utf32_to_utf8(lst->param.lc, &lst->str); len = (lst->str_size < (size_t)lst->modifiers.width) ? (size_t)lst->modifiers.width : lst->str_size; ft_fill_str(lst, len); } void ft_fm_wstr(t_format_list_el *lst) { size_t len; lst->str_size = calculate_wstrlen(lst->param.ls, lst->modifiers.accuracy, lst->modifiers.flags & FM_FLAG_ACCURACY); lst->modifiers.flags &= ~(int)FM_FLAG_ACCURACY; lst->modifiers.accuracy = 0; if (!(lst->str = (char *)malloc(sizeof(char) * (lst->str_size + 1)))) { ft_fm_list_free(&lst); exit(0); } convert_utf32_to_utf8_str(lst); lst->str[lst->str_size] = '\0'; len = (lst->str_size < (size_t)lst->modifiers.width) ? (size_t)lst->modifiers.width : lst->str_size; ft_fill_str(lst, len); } void ft_fm_str(t_format_list_el *lst) { size_t len; ft_check_str(lst); len = (lst->str_size < (size_t)lst->modifiers.width) ? (size_t)lst->modifiers.width : lst->str_size; ft_fill_str(lst, len); }
C
/**************************************************************************** Copyright (c) 2005 - 2015 Qualcomm Technologies International, Ltd. FILE NAME leds_rom_manager.c DESCRIPTION an leds_rom manager for leds display NOTES */ #include <stdlib.h> #include <print.h> #include "leds_manager.h" #include "leds_manager_if.h" /*the messaging interface*/ #include "leds_rom.h" #include "leds_rom_manager_common.h" /*the task message handler*/ static void rom_message_handler (Task task, MessageId id, Message message); /*the local message handling functions*/ static void handleLedsManagerMessage ( Task task , MessageId id, Message message ); static void LedsRomInit(Task clientTask, const void * params); static void LedsRomIndicateEvent(uint8 pEvent, bool can_queue); static void LedsRomIndicateState(uint8 pState); static void LedsRomEnableLEDS(void); static void LedsRomDisableLEDS(void); static void LedsRomResetLEDEventInds(void); static void LedsRomCheckTimeoutState(void); /*the led_rom manager task*/ const TaskData leds_rom_manager = { rom_message_handler }; /**************************************************************************** DESCRIPTION The main task message handler */ static void rom_message_handler ( Task task, MessageId id, Message message ) { if ( (id >= LEDS_PLUGIN_MESSAGE_BASE ) && (id <= LEDS_PLUGIN_MESSAGE_TOP) ) { handleLedsManagerMessage (task , id, message ) ; } else { PRINT(("LM: The id is [%x] from internal rom library\n", id)); handleLedsInternalMessage (task , id , message ) ; } } /**************************************************************************** DESCRIPTION messages from the leds manager library are received here. and converted into function calls to be implemented in the leds rom manager module */ static void handleLedsManagerMessage ( Task task , MessageId id, Message message ) { switch (id) { case (LEDS_INITIAL_MSG): { LEDS_INITIAL_MSG_T * msg = (LEDS_INITIAL_MSG_T *)message ; PRINT(("LM: LEDS_ROM_MANAGER: LEDS_INITIAL_MSG\n")); LedsRomInit(msg->clientTask, msg->params); } break ; case (LEDS_INDICATE_EVENT_MSG): { LEDS_INDICATE_EVENT_MSG_T * msg = (LEDS_INDICATE_EVENT_MSG_T *)message ; PRINT(("LEDS_ROM_MANAGER: LEDS_INDICATE_EVENT_MSG \n")); LedsRomIndicateEvent(msg->pEvent, msg->can_queue); } break ; case (LEDS_INDICATE_STATE_MSG): { LEDS_INDICATE_STATE_MSG_T * msg = (LEDS_INDICATE_STATE_MSG_T *)message ; PRINT(("LEDS_ROM_MANAGER: LEDS_INDICATE_STATE_MSG \n")); LedsRomIndicateState(msg->pState); } break ; case (LEDS_ENABLE_LEDS_MSG): { PRINT(("LEDS_ROM_MANAGER: LEDS_ENABLE_LEDS_MSG \n")); LedsRomEnableLEDS(); } break ; case (LEDS_DISABLE_LEDS_MSG): { PRINT(("LEDS_ROM_MANAGER: LEDS_DISABLE_LEDS_MSG \n")); LedsRomDisableLEDS(); } break ; case (LEDS_RESET_EVENT_IND_MSG): { PRINT(("LEDS_ROM_MANAGER: LEDS_RESET_EVENT_IND_MSG \n")); LedsRomResetLEDEventInds( ); } break ; case (LEDS_RESET_LEDS_TIMEOUT_MSG): { PRINT(("LEDS_ROM_MANAGER: LEDS_RESET_LEDS_TIMEOUT_MSG \n")); LedsRomCheckTimeoutState( ); } break ; default: { } break ; } } /**************************************************************************** NAME LedsRomInit DESCRIPTION Initialise the Leds ROM play system RETURNS void */ static void LedsRomInit(Task clientTask, const void * params) { leds_config = (leds_config_type *)params; leds_rom_ctl.clientTask = clientTask; } /**************************************************************************** NAME LedsRomIndicateEvent DESCRIPTION displays event notification This function also enables / disables the event filter actions - if a normal event indication is not associated with the event, it checks to see if a filer is set up for the event RETURNS void */ static void LedsRomIndicateEvent(uint8 pEvent, bool can_queue) { uint8 i,lPatternIndex; ledsPattern_t *lPattern = NULL; lPatternIndex = NO_STATE_OR_EVENT; /* search for a matching event */ for(i=0;i< leds_config->gNumEventPatternsUsed;i++) { PRINT(("LM: The config event:[%x], curr event [%x]\n", leds_config->gLedsEventPatterns[i].EventOrState, pEvent)); if(leds_config->gLedsEventPatterns[i].EventOrState == pEvent) { lPattern = &leds_config->gLedsEventPatterns[i]; lPatternIndex = i; break; } } /*if there is an event configured*/ if ( lPatternIndex != NO_STATE_OR_EVENT ) { /*only indicate if LEDs are enabled*/ if ((leds_config->gLedsRomEnabled ) || (lPattern->OverideDisable ) || LedActiveFiltersCanOverideDisable( )) { /*only update if wer are not currently indicating an event*/ if ( !leds_rom_ctl.gCurrentlyIndicatingEvent ) { /*Indicate the LED Pattern of Event/State*/ ledsIndicateLedsPattern(lPattern, lPatternIndex, LEDS_IND_EVENT); } else { if(leds_config->gLedsQueueLEDEvents && can_queue) { PRINT(("LM: Queue LED Event [%x]\n" , pEvent )) ; if( leds_config->gQueue.Event1 == 0) { leds_config->gQueue.Event1 = pEvent; } else if( leds_config->gQueue.Event2 == 0) { leds_config->gQueue.Event2 = pEvent; } else if( leds_config->gQueue.Event3 == 0) { leds_config->gQueue.Event3 = pEvent; } else if( leds_config->gQueue.Event4 == 0) { leds_config->gQueue.Event4 = pEvent; } else { PRINT(("LM: Err Queue Full!!\n")) ; } } } } else { PRINT(("LM : No IE[%x] disabled\n",pEvent )) ; } } else { PRINT(("LM: NoEvPatCfg\n")) ; } /*indicate a filter if there is one present*/ ledsCheckEventForActiveFilter( pEvent ) ; } /**************************************************************************** NAME LedsRomIndicateState DESCRIPTION displays state indication information RETURNS void */ static void LedsRomIndicateState(uint8 pState) { uint8 i,lPatternIndex; ledsPattern_t *lPattern = NULL; lPatternIndex = NO_STATE_OR_EVENT; /* search for a matching state */ for(i=0;i<leds_config->gNumStatePatternsUsed;i++) { if(LedsIsStateMatched(leds_config->gLedsStatePatterns[i].EventOrState, pState)) { lPattern = &leds_config->gLedsStatePatterns[i]; lPatternIndex = i; break; } } /* force indicated state to that of Low Battery configured pattern */ leds_rom_ctl.pStatePatternIndex = NO_STATE_OR_EVENT; if(lPatternIndex != NO_STATE_OR_EVENT) { /*if there is a pattern associated with the state and not disabled, indicate it*/ leds_rom_ctl.pStatePatternIndex = lPatternIndex; leds_rom_ctl.gStateCanOverideDisable = lPattern->OverideDisable; /* only indicate if LEDs are enabled*/ if ((leds_config->gLedsRomEnabled ) || (lPattern->OverideDisable ) || LedActiveFiltersCanOverideDisable( )) { uint8 LED_A_PIO = LedsToPioPin(lPattern->LED_A); uint8 LED_B_PIO = LedsToPioPin(lPattern->LED_B); uint8 LED_C_PIO = LedsToPioPin(lPattern->LED_C); if ( ( leds_config->gActiveLEDS[LED_A_PIO].Type != LEDS_IND_EVENT ) && ( leds_config->gActiveLEDS[LED_B_PIO].Type != LEDS_IND_EVENT ) && ( leds_config->gActiveLEDS[LED_C_PIO].Type != LEDS_IND_EVENT ) ) { ledsIndicateLedsPattern(lPattern, lPatternIndex, LEDS_IND_STATE); } } else { LedsIndicateNoState ( ) ; } } else { PRINT(("LM : DIS NoStCfg[%x]\n", pState)) ; LedsIndicateNoState ( ); } } /**************************************************************************** NAME LedsRomEnableLEDS DESCRIPTION Enable LED indications RETURNS void */ static void LedsRomEnableLEDS(void) { leds_config->gLedsRomEnabled = TRUE ; MessageSend(leds_rom_ctl.clientTask, LEDS_ENABLE_LEDS_CFM, 0); } /**************************************************************************** NAME LedsRomDisableLEDS DESCRIPTION Disable LED indications and turn off all current LED Indications if not overidden by state or filter RETURNS void */ static void LedsRomDisableLEDS(void) { /*Turn off all current LED Indications if not overidden by state or filter */ if (!leds_rom_ctl.gStateCanOverideDisable && !LedActiveFiltersCanOverideDisable()) { LedsIndicateNoState ( ) ; } leds_config->gLedsRomEnabled = FALSE ; MessageSend(leds_rom_ctl.clientTask, LEDS_DISABLE_LEDS_CFM, 0); } /**************************************************************************** NAME LedsRomResetLEDEventInds DESCRIPTION Resets the LED event Indications and reverts to state indications Sets the Flag to allow the Next Event to interrupt the current LED Indication Used if you have a permanent LED event indication that you now want to interrupt. RETURNS void */ static void LedsRomResetLEDEventInds(void) { LedsResetAllLeds ( ) ; leds_rom_ctl.gCurrentlyIndicatingEvent = FALSE ; MessageSend(leds_rom_ctl.clientTask, LEDS_STATE_IND_REQ, 0); } /**************************************************************************** NAME LedsRomCheckTimeoutState DESCRIPTION checks the led timeout state and resets it if required, this function is called from an event or volume button press to re-enable led indications as and when required to do so RETURNS void */ static void LedsRomCheckTimeoutState(void) { /*handles the LED event timeouts - restarts state indications if we have had a user generated event only*/ if (leds_config->gLEDSStateTimeout) { MAKE_LEDS_MESSAGE(LEDS_STATE_IND_TIMEOUT); message->status = FALSE; /* send message that can be used to show an led pattern when led's are re-enabled following a timeout */ MessageSend( leds_rom_ctl.clientTask, LEDS_STATE_IND_TIMEOUT, message); leds_config->gLEDSStateTimeout = FALSE; } else { /*reset the current number of repeats complete - i.e restart the timer so that the leds will disable after the correct time*/ LedsResetStateIndNumRepeatsComplete( ) ; } }
C
#include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <sys/socket.h> #include <netdb.h> #include <string.h> #include <errno.h> struct addrinfo * createAddressInfo(const char* address, const char* port) { printf("Creating address info for %s:%s\n", address, port); struct addrinfo *addr; int err=getaddrinfo(address,port,NULL,&addr); if (err==0) { printf("Successfully created address info.\n"); return addr; } printf("Error occurred in createAddressInfo with err=%ld.\n", err); return NULL; } int createSocket(struct addrinfo * addr) { printf("Creating new socket with given address info\n"); int sock=socket(addr->ai_family,addr->ai_socktype,addr->ai_protocol); if (sock==-1) { printf("Error occurred creating socket so now I am sad"); return -1; } printf("Successfully created socket: %ld\n", sock); return sock; } int main(int argc, char **argv) { char* pEnd; char str[15]; socklen_t fromlen; char buffer[512]; const char* ipTx = argv[1]; const char* ipRx = argv[2]; const char* portTx = argv[3]; const char* portRx = argv[4]; const int rateTx = strtol(argv[5], &pEnd, 10); printf("Transmit IP: %s\n", ipTx); printf("Receive IP: %s\n", ipRx); printf("Transmit Port: %s\n", portTx); printf("Receive Port: %s\n", portRx); printf("Transport Rate: %ld\n", rateTx); struct addrinfo *addr = createAddressInfo(ipRx,portRx); int socket = createSocket(addr); int success=recvfrom(socket,buffer,sizeof(buffer),0,addr->ai_addr,&fromlen); if(success==-1) { //int foo = getsockopt(socket, SOL_SOCKET,SO_ERROR ,NULL, NULL); //printf("ERROR: %ld\n",foo); printf ("Error: %s\n",strerror(errno)); printf("Error occurred sending so now I am sad"); return -1; } printf("%s\n",buffer); return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_abs.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: jboissy <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/11/08 00:01:15 by jboissy #+# #+# */ /* Updated: 2017/11/25 00:41:35 by jboissy ### ########.fr */ /* */ /* ************************************************************************** */ #include "template.h" void draw_rectangle(t_vect *coord, t_vect *size, int color_type) { SDL_Rect rect; SDL_Color color; rect.x = coord->x; rect.y = coord->y; rect.w = size->x; rect.h = size->y; color = get_color(color_type); SDL_SetRenderDrawColor(get_renderer(), color.r, color.g, color.b, color.a); SDL_RenderFillRect(get_renderer(), &rect); } void draw_border_rectangle(t_vect *coord, t_vect *size, int color_type, int i) { SDL_Rect rect1; SDL_Rect rect2; SDL_Color color1; SDL_Color color2; int border_size; rect1.x = coord->x; rect1.y = coord->y; rect1.w = size->x; rect1.h = size->y; color1 = get_color(color_type); color2 = get_color(color_type - 1); SDL_SetRenderDrawColor(get_renderer(), color1.r, color1.g, color1.b, color1.a); SDL_RenderFillRect(get_renderer(), &rect1); border_size = rect1.w / i < rect1.h / i ? rect1.w / i : rect1.h / i; rect2.x = coord->x + border_size; rect2.y = coord->y + border_size; rect2.w = size->x - border_size * 2; rect2.h = size->y - border_size * 2; SDL_SetRenderDrawColor(get_renderer(), color2.r, color2.g, color2.b, color2.a); SDL_RenderFillRect(get_renderer(), &rect2); }
C
// Created by David Zashkolny on 02.05.2020. // 3 course, comp math // Taras Shevchenko National University of Kyiv // email: [email protected] // #ifndef COMBINATORICAL_OPTIMIZATIONAL_MINHEAP_H #define COMBINATORICAL_OPTIMIZATIONAL_MINHEAP_H #include <stdlib.h> #include <stdio.h> #include <limits.h> #define HEAP_INDEX_TYPE size_t // -------------------- Abstract MinHeap implementation ----------------------- typedef void* MinHeapEl; typedef struct MinHeap { MinHeapEl* harr; HEAP_INDEX_TYPE capacity; HEAP_INDEX_TYPE heap_size; MinHeapEl (*getMin)(void); MinHeapEl (*getMax)(void); char (*compare)(MinHeapEl a, MinHeapEl b); void (*delete)(MinHeapEl* harr, HEAP_INDEX_TYPE heap_size); } MinHeap; // to heapify a subtree with the root at given index void MinHeapify(MinHeap* minHeap, HEAP_INDEX_TYPE root); HEAP_INDEX_TYPE parent(HEAP_INDEX_TYPE i); // to get index of left child of node at index i HEAP_INDEX_TYPE left(HEAP_INDEX_TYPE i); // to get index of right child of node at index i HEAP_INDEX_TYPE right(HEAP_INDEX_TYPE i); // to extract the root which is the minimum element MinHeapEl extractMin(MinHeap* minHeap); char isEmptyMinHeap(MinHeap* minHeap); // Decreases key value of key at index i to new_val void decreaseKeyMinHeap(MinHeap* minHeap, HEAP_INDEX_TYPE i, MinHeapEl new_val); // Returns the minimum key (key at root) from min heap MinHeapEl getMin(MinHeap* minHeap); // Deletes a key stored at index i void deleteKey(MinHeap* minHeap, HEAP_INDEX_TYPE index); // Inserts a new key 'k' void insertKey(MinHeap* minHeap, MinHeapEl key); void deleteHeap(MinHeap* minHeap); // ----------------------- MinHeap with integer pairs ------------------------- typedef struct IntPair { int priority; int data; } IntPair; static char compareIntPair(MinHeapEl x, MinHeapEl y); static MinHeapEl getMinIntPair(); static MinHeapEl getMaxIntPair(); static void deleteIntHeap(MinHeapEl* harr, HEAP_INDEX_TYPE heap_size) ; MinHeapEl createIntPair(int priority, int el); MinHeap* MinHeapIntPairs(HEAP_INDEX_TYPE capacity); #endif //COMBINATORICAL_OPTIMIZATIONAL_MINHEAP_H
C
/* Author: Thomas Royston * Partner(s) Name (if applicable): * Lab Section: 022 * Assignment: Lab #14 Exercise #2 * Exercise Description: [optional - include for your own benefit] * * I acknowledge all content contained herein, excluding template or example * code, is my own original work. * * Demo Link: https://www.youtube.com/watch?v=OqAtligdWlw&ab_channel=ThomasRoyston */ #include <avr/io.h> #include <avr/interrupt.h> #ifdef _SIMULATE_ #include "simAVRHeader.h" #include “usart_ATMEGA1284.h” #endif typedef struct task{ int state; unsigned long period; unsigned long elapsedTime; int(*tick_function)(int); } task; task tasks[2]; const unsigned short taskNum = 2; const unsigned long taskPeriod = 10; volatile unsigned char TimerFlag = 0; unsigned long _avr_timer_M = 1; unsigned long _avr_timer_cntcurr = 0; void TimerSet(unsigned long M) { _avr_timer_M = M; _avr_timer_cntcurr = _avr_timer_M; } void TimeOn() { TCCR1B = 0x0B; OCR1A = 125; TIMSK1 = 0x02; TCNT1 = 0; _avr_timer_cntcurr = _avr_timer_M; SREG |= 0x80; } void TimeOff() { TCCR1B = 0x00; } void TimeISR() { unsigned char i; for(i=0;i<taskNum;++i){ if(tasks[i].elapsedTime>=tasks[i].period){ tasks[i].state=tasks[i].tick_function(tasks[i].state); tasks[i].elapsedTime = 0; } tasks[i].elapsedTime += taskPeriod; } } ISR(TIMER1_COMPA_vect) { _avr_timer_cntcurr--; if (_avr_timer_cntcurr == 0) { TimeISR(); _avr_timer_cntcurr = _avr_timer_M; } } #define B0 (PINB&0x01) enum Led_Lead{init,lead}; int lead_tick(int state){ static unsigned char x = 0; static unsigned char temp = 0; switch(state){ case init: if(B0==1){ state = lead; } else{ state = init; } break; case lead: if(B0==1){ state = lead; PORTC = 0x01; } else if(B0==0){ state = init; } break; default: break; } switch(state){ case init: PORTC = 0; break; case lead: if(USART_IsSendReady(1)){ x =! x; PORTA = x; USART_Send(x,1); } break; default: break; } return state; } enum Led_Follow{init_follow,follow}; int follow_tick(int state1){ static unsigned char temp=0; switch(state1){ case init_follow: if(B0==0){ state1 = follow; } else{ state1 = init_follow; } break; case follow: if(B0==0){ state1 = follow; } else if(B0==1){ state1 = init_follow; } break; default: break; } switch(state1){ case init_follow: PORTC = 1; break; case follow: if(USART_HasReceived(0)){ temp = USART_Receive(0); PORTA = temp; } break; default: break; } return state1; } int main(void) { initUSART(0); USART_Flush(0); initUSART(1); USART_Flush(1); DDRA=0xFF; PORTA=0x00; DDRB=0x00; PORTB=0xFF; DDRC=0xFF; PORTC=0x00; unsigned char i=0; tasks[i].state = init; tasks[i].period = 1000; tasks[i].elapsedTime = 0; tasks[i].tick_function =& lead_tick; i++; tasks[i].state = init_follow; tasks[i].period = 20; tasks[i].elapsedTime = 0; tasks[i].tick_function =& follow_tick; TimerSet(10); TimeOn(); while (1) { } return 1; }
C
#include <stdio.h> int max(int a,int b ,int c){ if(a>b) if(a>c) return a; else return c; else if(b>c) return b; else return c; } int main() { int a,b,c; scanf("%d%d%d",&a,&b,&c); int s = a + b + c - 2*max(a,b,c); printf("%d",s); }
C
#include<linux/init.h> #include<linux/module.h> #include<linux/moduleparam.h> #include<linux/printk.h> #include<linux/device.h> #include<asm/uaccess.h> #include<linux/sched.h> #include<linux/slab.h> #include<linux/fs.h> /* For the character driver support */ #include<linux/semaphore.h> #include<linux/mutex.h> #define MAXLEN 100 #define TRUE 1 #define FALSE 0 MODULE_LICENSE("GPL"); static int majorNumber=164; static int size_of_message; static int numberOpens = 0; int N=1; module_param(N,int,0664); typedef struct data_def{ char message[MAXLEN]; }DATA; typedef struct node_def{ DATA* data; struct node_def* next; }NODE; typedef struct Queue { NODE *head; NODE *tail; int size; int limit; } Queue; Queue* my_queue; NODE* temp; DATA* msg; void ConstructQueue(int limit); void DestructQueue(void); int Enqueue( NODE *item); NODE *Dequeue(void); int isEmpty(void); void ConstructQueue(int limit) { my_queue = (Queue*) kzalloc(sizeof(Queue),GFP_KERNEL); if (my_queue == NULL) { }else{ if (limit <= 0) { limit = 100; } my_queue->limit = limit; my_queue->size = 0; my_queue->head = NULL; my_queue->tail = NULL; } } void DestructQueue(void) { NODE *pN; while (!isEmpty()) { pN = Dequeue(); kfree(pN); } kfree(my_queue); } int Enqueue( NODE *item) { printk(KERN_INFO"ENQUEING %s\n",item->data->message); /* Bad parameter */ if ((my_queue == NULL) || (item == NULL)) { return FALSE; } // if(my_queue->limit != 0) if (my_queue->size >= my_queue->limit) { return FALSE; } /*the queue is empty*/ item->next = NULL; if (my_queue->size == 0) { my_queue->head = item; my_queue->tail = item; printk(KERN_INFO"FIRST ENQUEING %s\n",my_queue->head->data->message); } else { /*adding item to the end of the queue*/ my_queue->tail->next = item; my_queue->tail = item; printk(KERN_INFO"ADDED %s\n",my_queue->tail->data->message); } my_queue->size++; return TRUE; } NODE * Dequeue() { /*the queue is empty or bad param*/ NODE *item=(NODE*) kzalloc(sizeof (NODE),GFP_KERNEL); if (isEmpty()) return NULL; item = my_queue->head; my_queue->head = (my_queue->head)->next; my_queue->size--; printk(KERN_INFO"DEQUEUING %s\n",item->data->message); return item; } int isEmpty() { if (my_queue == NULL) { return FALSE; } if (my_queue->size == 0) { return TRUE; } else { return FALSE; } } static DEFINE_SEMAPHORE(sem1); static DEFINE_SEMAPHORE(sem2); static DEFINE_MUTEX(mut); int linepipe_open(struct inode *pinode, struct file *pfile){ printk(KERN_ALERT "Inside the %s function\n", __FUNCTION__); numberOpens++; printk(KERN_INFO "process_list: Device has been opened %d time(s)\n", numberOpens); return 0; } ssize_t linepipe_read(struct file *pfile, char __user *buffer,size_t length, loff_t *offset){ int error_count = 0; down_interruptible(&sem2); mutex_lock_interruptible(&mut); printk(KERN_ALERT "Inside the %s function\n", __FUNCTION__); // copy_to_user has the format ( * to, *from, size) and returns 0 on success if(temp){ kfree(temp); } temp = (NODE*) kzalloc(sizeof (NODE),GFP_KERNEL); temp = Dequeue(); if(temp!=NULL){ if(access_ok(VERIFY_WRITE,buffer,size_of_message)>0){ error_count = copy_to_user(buffer, temp->data, sizeof(DATA)); }else{ printk(KERN_ALERT"sorry couldnt write to user space"); } if (error_count==0){ // if true then have success printk(KERN_INFO"SENT: %s\n",temp->data->message); printk(KERN_INFO "EBBChar: Sent %d characters to the user\n", size_of_message); mutex_unlock(&mut); up(&sem1); return (size_of_message=0); // clear the position to the start and return 0 } else { printk(KERN_INFO "EBBChar: Failed to send %d characters to the user\n", error_count); mutex_unlock(&mut); up(&sem1); return -EFAULT; // Failed -- return a bad address message (i.e. -14) } }else{ mutex_unlock(&mut); up(&sem1); return -EFAULT; } } ssize_t linepipe_write(struct file *pfile,const char __user *buffer,size_t length, loff_t *offset){ int error_count = 0; down_interruptible(&sem1); mutex_lock_interruptible(&mut); printk(KERN_ALERT "Inside the %s function\n", __FUNCTION__); if(temp){ kfree(temp); } temp = (NODE*) kzalloc(sizeof (NODE),GFP_KERNEL); temp->data=(DATA*) kzalloc(sizeof (DATA),GFP_KERNEL); if(msg){ kfree(msg); } msg=(DATA*)kzalloc(sizeof (DATA),GFP_KERNEL); if(access_ok(VERIFY_WRITE,buffer,length)>0){ error_count = copy_from_user(msg->message,(char*)buffer, length); }else{ printk(KERN_ALERT"sorry couldnt write to kernel space"); } if (error_count==0){ // if true then have success temp->data=msg; size_of_message = strlen(temp->data->message); printk(KERN_INFO "linepipe: Received %s\n",temp->data->message); printk(KERN_INFO "EBBChar: Received %d characters from user\n", size_of_message); if(Enqueue(temp)) printk(KERN_INFO"enqued properly\n"); mutex_unlock(&mut); up(&sem2); return size_of_message; // clear the position to the start and return 0 } else { printk(KERN_INFO "EBBChar: Failed to send %d characters to the user\n", error_count); mutex_unlock(&mut); up(&sem2); return -EFAULT; // Failed -- return a bad address message (i.e. -14) } } int linepipe_release(struct inode *pinode,struct file *pfile){ printk(KERN_ALERT "Inside the %s function\n", __FUNCTION__); return 0; } struct file_operations my_linepipe = { .owner = THIS_MODULE, .open = linepipe_open, .read = linepipe_read, .write = linepipe_write, .release = linepipe_release, }; int my_kernel_module_init(void){ printk(KERN_ALERT "Inside the %s function\n", __FUNCTION__); printk(KERN_ALERT "PARAMETER is %d\n",N); /*Register with the kernel and indicate that we are registering a character device driver*/ register_chrdev(majorNumber/*Major Number*/, "My linepipe"/*Name of the driver*/, &my_linepipe/*File Operations*/); ConstructQueue(N); sema_init(&sem1, N); sema_init(&sem2, 0); mutex_init(&mut); return 0; } void my_kernel_module_exit(void){ printk(KERN_ALERT "Inside the %s function\n", __FUNCTION__); DestructQueue(); /*Unregister the character device driver*/ unregister_chrdev(majorNumber,"My linepipe"); } module_init(my_kernel_module_init); module_exit(my_kernel_module_exit);
C
#include <stdio.h> #include <memory.h> enum { WIN, TOTAL }; int main() { int n, k, p1, p2, i, len1, len2, player1, player2; long total, table[102][2]; char s1[16], s2[16], *t1, *t2; float res; // 가위바위보 테이블; memset(table, 0, sizeof(table)); while ( scanf("%d %d", &n, &k)==2 ) { // many input; total = k; total *= n; total *= n-1; total >>= 1; while ( total-- ) { scanf("%d %s %d %s", &p1, s1, &p2, s2); // 가위(1)바위(2)보(4) 결정; switch ( *s1 ) { case 's': player1=1; break; case 'r': player1=2; break; case 'p': player1=4; break; } switch ( *s2 ) { case 's': player2=1; break; case 'r': player2=2; break; case 'p': player2=4; break; } // 가위, 보 일 경우; if ( (player1|player2)==5 ) { ++table[player1<player2?p1:p2][WIN]; ++table[p1][TOTAL]; ++table[p2][TOTAL]; } // 무승부가 아닐 경우; 큰 숫자가 이김; else if ( player1^player2 ) { ++table[player1>player2?p1:p2][WIN]; ++table[p1][TOTAL]; ++table[p2][TOTAL]; } } // 승률 출력; for ( i=1 ; i<=n ; ++i ) { if ( table[i][TOTAL] ) { res = (float)table[i][WIN]/(float)table[i][TOTAL]; printf("%.3f\n", res); } else puts("-"); // 테이블 초기화; table[i][WIN]=table[i][TOTAL]=0; } puts("");// '\n' } return 0; }
C
#include "holberton.h" #include <stdio.h> /** * palindrome_check - helper function for is_palindrome * * @l: length of string * @i: counter for palindrome * @s: string to check * Return: returns itself if incomplete, or 1 for palindrome, 0 for not */ int palindrome_check(char *s, int l, int i) { if (s[i] == s[l] && l != i) return (palindrome_check(s, --l, ++i)); if (s[i] == s[l] || i >= l) return (1); if (s[i] != s[l]) return (0); return (1); } /** * recursive_strlen - recursively checks string length * * @s: string to check length of * @i: counter * Return: returns itself if not complete, or length */ int recursive_strlen(char *s, int i) { if (s[i] != '\0') return (recursive_strlen(s, ++i)); return (--i); } /** * is_palindrome - determines if number inside string is a palindrome or not * * * * @s: string to check * Return: 1 if palindrome, 0 if not */ int is_palindrome(char *s) { int length; length = recursive_strlen(s, 0); return (palindrome_check(s, length, 0)); }
C
#include <math.h> #include <stdio.h> double func1(double x){ double y; y = x - 1.2*exp(-x); return y; } double func1_d(double x){ double y; y = 1 + 1.2*exp(-x); return y; } double func2(double x){ double y; y = x * sin(x) + log(x); return y; } double func2_d(double x){ double y; y = sin(x) + x * cos(x) + 1/x; return y; } int main(void){ double error, x, x_n; int i, max; x=1.0; error=1e-6; max=100; double (*f1)(double); double (*f1_d)(double); f1 = func1; f1_d = func1_d; double (*f2)(double); double (*f2_d)(double); f2 = func2; f2_d = func2_d; for(i=0; i<max; i++){ x_n = x- (*f1)(x)/(*f1_d)(x); if(fabs(x_n-x)<error){ break; } x = x_n; } if(i<max){ printf("OK %f\n", x); }else{ printf("NG"); } for(i=0; i<max; i++){ x_n = x- (*f2)(x)/(*f2_d)(x); if(fabs(x_n-x)<error){ break; } x = x_n; } if(i<max){ printf("OK %f\n", x); }else{ printf("NG"); } return 0; }
C
#include "ffinternal.h" #include "ffdatatype.h" int ffdatatype_size(ffdatatype_h datatype, size_t * size){ size_t unitsize; switch (datatype){ case FFINT32: unitsize = sizeof(int32_t); break; case FFINT64: unitsize = sizeof(int64_t); break; case FFDOUBLE: unitsize = sizeof(double); break; case FFFLOAT: unitsize = sizeof(float); break; case FFDATATYPE_NONE: unitsize = 0; break; default: FFLOG_ERROR("Operator not found!\n"); return FFINVALID_ARG; } *size = unitsize; return FFSUCCESS; }
C
#include <stdio.h> #define MAX_SIZE 1000000 long int sizes[MAX_SIZE]; int counts[MAX_SIZE]; long int check_for_size(long int); int main() { long int fileid, size; float timest; long int count = 0; long int temp; for (temp = 0; temp < MAX_SIZE; temp++) { sizes[temp] = -1; counts[temp] = -1; } while(scanf("%f %d %d\n", &timest, &fileid, &size) > 0) { temp = check_for_size(size); if (temp == -1) { //first time sizes[count] = size; counts[count] = 1; count++; } else { counts[temp] += 1; } } for (temp = 0; temp < MAX_SIZE; temp++) { if (sizes[temp] == -1) { return(0); } printf("%d - %d\n", sizes[temp], counts[temp]); } return(0); } long int check_for_size(long int size) { long int i; for (i = 0; i < MAX_SIZE; i++) { if (sizes[i] == -1) { return(-1); } if (sizes[i] == size) { return(i); } } printf("PANIC\n"); }