language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
#include "matrix.h" int main(void) { puts("What is the size of the matrix?"); int r, c; scanf("%d %d", &r, &c); matrix_t *m = creatematrix(r, c); for (int r = 0; r < m->r; r++) { for (int c = 0; c < m->c; c++) { printf("(%d,%d):", r+1, c+1); scanf("%d", &(m->m[r][c])); } } savematrix(m); return 0; }
C
/* file_ts.c - write the current date/time to a file * Usage: file_tm filename * Action: writes the current time/date to filename * Note: uses fcntl() - based locking **/ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/file.h> #include <fcntl.h> #include <time.h> #define oops(m,x) {perror(m); exit(x);} void lock_operation(int, int); int main(int argc, char** argv) { if(argc != 2) { fprintf(stderr, "usage: file_ts filename\n"); exit(1); } int fd = open(argv[1], O_CREAT|O_TRUNC|O_WRONLY, 0644); if( fd == -1 ) oops(argv[1], 2); time_t now; char* message; printf("Storing time in %s...\n", argv[1]); while(1) { time(&now); message = ctime(&now); // compute time lock_operation(fd, F_WRLCK); // lock for writing if( lseek(fd, 0L, SEEK_SET) == -1 ) oops("lseek", 3); if( write(fd, message, strlen(message)) == -1 ) oops("write", 4); lock_operation(fd, F_UNLCK); // unlock file sleep(1); // wait for new time } return 0; } void lock_operation(int fd, int op) { struct flock lock; lock.l_whence = SEEK_SET; lock.l_start = lock.l_len = 0; lock.l_pid = getpid(); lock.l_type = op; if( fcntl(fd, F_SETLKW, &lock) == -1 ) oops("lock operation", 6) }
C
/* * This file is part of the IT security lesson sample set * Copyright (c) 2018 Mario Lombardo. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* DO NOT USE THIS SERVER (even not partially) FOR PRODUCTION PURPOSE * * Its intention is to demostrate weak software only. * * Compilation: * gcc hackme_kludge_server.c -o hackme_kludge_server -pthread * * ...or add the -g flag for debugging ;-) */ #include <arpa/inet.h> #include <netinet/in.h> #include <errno.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <unistd.h> #include <pthread.h> #include <signal.h> #include <ctype.h> #define SERVER_PORT 4711 struct client_worker_data_t { int sock; size_t input_buffer_pos; char input_buffer[1024]; int password_accepted; unsigned int port; char addr[16]; }; char *passkey = NULL; int mk_server_socket() { struct sockaddr_in server_address; int reuse = 1; int new_sock = -1; memset(&server_address, 0, sizeof(server_address)); /* prepare socket descriptor */ server_address.sin_family = AF_INET; server_address.sin_port = htons(SERVER_PORT); server_address.sin_addr.s_addr = INADDR_ANY; /* create listener socket */ if((new_sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) { fprintf(stderr, "could not create listen socket\n"); return -1; } if(setsockopt(new_sock, SOL_SOCKET, SO_REUSEADDR, (const char*)&reuse, sizeof(reuse)) < 0) { fprintf(stderr, "setsockopt(SO_REUSEADDR) failed\n"); return -1; } #ifdef SO_REUSEPORT if(setsockopt(new_sock, SOL_SOCKET, SO_REUSEPORT, (const char*)&reuse, sizeof(reuse)) < 0) { fprintf(stderr, "setsockopt(SO_REUSEPORT) failed\n"); return -1; } #endif if((bind(new_sock, (struct sockaddr *)&server_address, sizeof(server_address))) < 0) { fprintf(stderr, "could not bind socket\n"); return -1; } if(listen(new_sock, 8) < 0) { fprintf(stderr, "listen() failed\n"); return -1; } return new_sock; } void *client_worker(void *data) { struct client_worker_data_t *ctx = (struct client_worker_data_t*)data; char tmp_data[1024]; ssize_t n; sprintf(tmp_data, "Hello %s:%d\n\nPlease try to hack my password: ", ctx->addr, ctx->port); write(ctx->sock, tmp_data, strlen(tmp_data)); while(0 < (n = read(ctx->sock, ctx->input_buffer + ctx->input_buffer_pos, 1))) { if(strcmp(ctx->input_buffer, passkey) == 0) { ctx->password_accepted = 1; } if(strlen(ctx->input_buffer) > strlen(passkey) || ctx->input_buffer[ctx->input_buffer_pos] == '\n') { ctx->input_buffer[ctx->input_buffer_pos] = 0; break; } ctx->input_buffer_pos++; } if(ctx->password_accepted) { snprintf(tmp_data, sizeof(tmp_data), "Congratulations. Password '%s' accepted!\n\n", passkey); } else { snprintf(tmp_data, sizeof(tmp_data), "'%s' is wrong. Nice try fledgling...\n\n", ctx->input_buffer); } write(ctx->sock, tmp_data, strlen(tmp_data)); /* tidy up */ close(ctx->sock); free(ctx); return NULL; } void set_password(int sock) { char tmp_data[256]; char tmp_pass[256]; char *pass_ptr; ssize_t n; sprintf(tmp_data, "No password set. Please enter a password for this service: "); write(sock, tmp_data, strlen(tmp_data)); memset(tmp_pass, 0, sizeof(tmp_pass)); n = read(sock, tmp_pass, sizeof(tmp_pass) - 1); pass_ptr = tmp_pass; /* strip non printable chars */ while(*pass_ptr) { if(!isprint(*pass_ptr)) { *pass_ptr = 0; break; } pass_ptr++; } sprintf(tmp_data, "Thank you. Password set to: '%s'\nHappy hacking!\n\n", tmp_pass); write(sock, tmp_data, strlen(tmp_data)); close(sock); passkey = strdup(tmp_pass); } int main(int argc, char *argv[]) { (void)argc; (void)argv; struct sockaddr_in client_address; socklen_t client_address_len = 0; int listen_sock = 0, new_client = 0; struct client_worker_data_t *client_worker_data = NULL; pthread_t tid; pthread_attr_t attr; signal(SIGPIPE, SIG_IGN); if((listen_sock = mk_server_socket()) < 0) { return 1; } fprintf(stderr, "Listening with #%d on 0.0.0.0:%d\n", listen_sock, SERVER_PORT); while(1) { client_address_len = sizeof(struct sockaddr_in); memset(&client_address, 0, client_address_len); new_client = accept(listen_sock, (struct sockaddr *)&client_address, &client_address_len); /* check for error */ if(new_client == -1) { fprintf(stderr, "accept() failed with error %d: %s\n", errno, strerror(errno)); return 1; } fprintf(stderr, "New client on #%d: %s:%d\n", new_client, inet_ntoa(client_address.sin_addr), ntohs(client_address.sin_port)); /* let first client set secret password */ if(!passkey) { set_password(new_client); } /* create structure with all required data */ client_worker_data = calloc(1, sizeof(struct client_worker_data_t)); client_worker_data->port = ntohs(client_address.sin_port); strcpy(client_worker_data->addr, inet_ntoa(client_address.sin_addr)); client_worker_data->sock = new_client; /* start detached worker thread (pure botch!) */ pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); pthread_create(&tid, &attr, client_worker, client_worker_data); } /* tidy up*/ if(passkey) { free(passkey); } close(listen_sock); return 0; }
C
/* 输入一个非负整数,并进行逆向显示,同时显示输入的整数值。 */ #include <stdio.h> int main() { int no; do { printf("请输入一个整数:"); scanf("%d", &no); if (no <= 0) puts("请不要输入非正整数!!!"); } while (no <= 0); puts("该整数显示的逆向结果是:"); printf("%d\n", no); while (no > 0) { printf("%d ", no % 10); no /= 10; } puts("。"); return 0; }
C
#include "stdio.h" #include "stdlib.h" #include <dirent.h> int main(int argc,char *argv[]) { DIR *dp; struct dirent *dirp; if(argc != 2) { printf("error parament"); exit(1); } if((dp = opendir(argv[1])) == NULL) { printf("opendir error"); exit(1); } while((dirp = readdir(dp)) != NULL) { printf("\n dir name : %s",dirp->d_name); } closedir(dp); exit(0); }
C
#include <USART2.h> /* flag to indicate USART2 has been initialized */ /* toggled in init function */ static uint32_t initialized = 0; static uint8_t buffer[2]; static uint8_t buff_cnt = 0; /* module-global pointer to the callback function for rx'd bytes */ /* populated in init function. */ static void(*rx_callback_fn)(uint8_t byte); /* Rudimentary handler assumes the interrupt is due to a byte rx event */ void __attribute__ ((interrupt)) USART2_handler(void) { uint8_t byte; /* must read the USART2_DR to clear the interrupt */ byte = USART2->DR; if (rx_callback_fn) { rx_callback_fn(byte); } } void USART2_init(void(*USART2_rx_callback)(uint8_t byte)) { rx_callback_fn = USART2_rx_callback; /* Enable GPIOD, as USART2 TX is on PD5, and RX is on PD6 */ RCC->AHB1ENR |= RCC_AHB1ENR_GPIODEN; /* Configure PD5 as AF7 (Output, push-pull) */ GPIOD->AFRL &= GPIOx_AFRL_AFRL5_MASK; GPIOD->AFRL |= GPIOx_AFRL_AFRL5_AF7; GPIOD->MODER &= GPIOx_MODER_PIN5_MASK; GPIOD->MODER |= GPIOx_MODER_PIN5_AF; /* Configure PD6 as AF7 (Input) */ GPIOD->AFRL &= GPIOx_AFRL_AFRL6_MASK; GPIOD->AFRL |= GPIOx_AFRL_AFRL6_AF7; GPIOD->MODER &= GPIOx_MODER_PIN6_MASK; GPIOD->MODER |= GPIOx_MODER_PIN6_AF; /* Reset the USART peripheral and enable its clock */ RCC->APB1ENR &= ~RCC_APB1ENR_USART2; RCC->APB1RSTR |= RCC_APB1RSTR_USART2; RCC->APB1RSTR &= ~RCC_APB1RSTR_USART2; RCC->APB1ENR |= RCC_APB1ENR_USART2;// for part 1 // U /* Enable the USART peripheral */ USART2->CR1 |= USARTx_CR1_UE; /* Enable */ /* Configure for 8N1, 9600 baud (assuming 16MHz clock) */ USART2->BRR = 1667; /* 16MHz/1667 ~= 9600 */ /* Enable transmit */ USART2->CR1 |= (USARTx_CR1_TE); /* * If a callback function was registered, enable receive and the * receive interrupt. */ if( USART2_rx_callback ) { /* Configure Receive Interrupt */ NVIC_INTERRUPT_USART_2_ENABLE(); USART2->CR1 |= USARTx_CR1_RXNEIE; USART2->CR1 |= (USARTx_CR1_RE); } initialized = 1; } /* Send a single character out USART2 */ void USART2_putchar(uint8_t byte) { if( initialized ) { /* Wait for the transmit shift register to be free... */ while( !(USART2->SR & USARTx_SR_TXE) ); USART2->DR = byte; } } /* Send a null-terminated string out USART2 */ void USART2_putstr(uint8_t *buffer) { if( initialized ) { while( *buffer != '\0') { USART2_putchar(*buffer); buffer++; } } } /* Takes a 32-bit value and prints on console as hexadecimal number */ void printHex(uint32_t val) { uint32_t nibbles[8]; // array holding each nibble uint32_t mask = 0xF; // 1-nibble mask int i; // foreach nibble, get LSNibble, add offset, then LSR 4 bits to so next nibble is LSN for (i=0; i<8; ++i, val>>=4) { nibbles[i]= val & mask; // get nibble i // add ASCII offsets if (nibbles[i]< 10) { nibbles[i] += 48; } else { nibbles[i] += 55; } } // Print array in reverse order for (i=7; i>=0; i--) { USART2_putchar(nibbles[i]); } USART2_putchar('\n'); USART2_putchar('\r'); } /* * adds a byte to USART2 buffer */ void USART2_buffer_add(uint8_t byte) { buffer[buff_cnt] = byte; buff_cnt++; } void USART2_buffer_clr() { buff_cnt = 0; } /* * Returns number of chars in buffer */ uint32_t USART2_buffer_length() { return buff_cnt; } /* * Returns ASCII representation of buffer as an integer */ uint32_t* USART2_buffer_getInt() { return (uint32_t*) (10*(buffer[0]-48)+(buffer[1]-48)); } /* * returns ASCII representation of buffer as string of characters */ uint8_t* USART2_buffer_getStr() { return (uint8_t*)int2str(USART2_buffer_getInt()); }
C
#include "svdpi.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #define MAX_SIZE 2000 int instruction_array[MAX_SIZE]; int instruction_count; char script[30]; void set_compile_script(const char* lscript) { strcpy(script, lscript); } void compile_test(const char* testcase) { FILE* hexFile; int i = 0; char* int_ext = ".int"; char* asm_ext = ".s"; char* c_ext = ".c"; char* rm_cmd = "rm"; char * asm_file = malloc(strlen(testcase) + strlen(asm_ext) + 1); char * c_file = malloc(strlen(testcase) + strlen(c_ext) + 1); char* command_asm = malloc(strlen(script) + strlen(testcase) + strlen(asm_ext) + 2); char* command_c = malloc(strlen(script) + strlen(testcase) + strlen(c_ext) + 2); char * int_file = malloc(strlen(testcase) + strlen(int_ext) + 1); strcpy(asm_file, testcase); strcat(asm_file, asm_ext); strcpy(c_file, testcase); strcat(c_file, c_ext); strcpy(command_asm, script); strcat(command_asm, " " ); strcat(command_asm, asm_file); strcpy(command_c, script); strcat(command_c, " " ); strcat(command_c, c_file); if (access(asm_file, F_OK) != -1) { system(command_asm); } else if (access(c_file, F_OK) != -1) { system(command_c); } else { return; } strcpy(int_file, testcase); strcat(int_file, int_ext ); hexFile = fopen(int_file, "r"); while (fscanf(hexFile, "%08X", &instruction_array[i]) != EOF) ++i; instruction_count = i; char * rm_int = malloc(strlen(rm_cmd) + strlen(int_file) + 2); strcpy(rm_int, rm_cmd ); strcat(rm_int, " " ); strcat(rm_int, int_file); system(rm_int); } int get_instruction_count() { return instruction_count; } int get_instruction(int index) { return instruction_array[index]; }
C
#include "utils/cutil.h" #include "kernel/memory.h" #include "lib/string.h" #define CUTIL_CMD_STAT "stat" extern heap_meta *heap_hdr; static void heap_stat(void) { printf("__________MEMORY USAGE INFO__________\n"); printf("HEAP HEADER : 0x%X\n", heap_hdr); printf("NEXT FREE CELL : 0x%X\n", heap_hdr->free_cell); printf("FISRT USED CELL : 0x%X\n", heap_hdr->used_start); printf("HEAP HEADER SIZE : %d bytes\n", HEAP_HDR_SIZE); printf("CELL HEADER SIZE : %d bytes\n\n", CELL_HDR_SIZE); cell *cur_cell = heap_hdr->used_start; uint16_t counter_total = 0; uint16_t counter_used = 0; while (cur_cell) { printf("CELL %d:\n", counter_total); printf("ADDR : 0x%X\n", cur_cell); printf("MEM ADDR : 0x%X\n", cur_cell + 1); printf("MEM END : 0x%X\n", ((uint8_t*) (cur_cell + 1)) + cur_cell->size); if (cur_cell->used) { printf("USED : yes\n"); counter_used++; } else { printf("USED : no\n"); } printf("SIZE : %d bytes\n\n", cur_cell->size); cur_cell = cur_cell->ptr; counter_total++; } printf("TOTAL CELLS : %d\n", counter_total); printf("TOTAL USED CELLS : %d\n", counter_used); printf("TOTAL FREED CELLS : %d\n", counter_total - counter_used); } int cutil_cmd_handler(list_iface *args) { int size = args->size(args); if (size == 2 && strcmp(args->get(args, 1), CUTIL_CMD_STAT) == 0) { heap_stat(); return 0; } return -1; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_manage_p.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: malaoui <malaoui@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/11/21 04:28:41 by malaoui #+# #+# */ /* Updated: 2019/11/23 21:48:32 by malaoui ### ########.fr */ /* */ /* ************************************************************************** */ #include "libftprintf.h" int ft_manage_minus_p(t_combo *foo, va_list list) { int i; int len; char *p; long long l; i = 0; l = va_arg(list, long long); if (l == 0 && foo->flag == 1) p = ft_strdup("0x"); else p = ft_strjoin("0x", ft_hex(l)); ft_putstr_fd(p, 1); len = ft_strlen(p); i = ft_strlen(p); while ((foo->width) > len) { ft_putchar_fd(' ', 1); (foo->width)--; i++; } free(p); return (i); } int ft_manage_zero_p(t_combo *foo, va_list list) { int i; char *p; p = ft_strjoin("0x", ft_hex(va_arg(list, long long))); i = ft_strlen(p); while (i < (foo->width)) { ft_putchar_fd('0', 1); i++; } ft_putstr_fd(p, 1); return (i); } int ft_manage_norm_p(t_combo *foo, va_list list) { int i; char *p; long long l; l = va_arg(list, long long); i = 0; if (l == 0 && foo->flag == 1) p = ft_strdup("0x"); else if (!foo->width && !foo->precision) { p = ft_strjoin("0x", ft_hex(l)); ft_putstr_fd(p, 1); free(p); return (ft_strlen(p)); } else p = ft_strjoin("0x", ft_hex(l)); i = ft_strlen(p); while (i < (foo->width)) { ft_putchar_fd(' ', 1); i++; } ft_putstr_fd(p, 1); free(p); return (i); } int ft_manage_simple_p(va_list list) { char *p; int len; p = ft_hex((size_t)va_arg(list, void*)); if (p == NULL) p = ft_strdup("0x0"); else p = ft_strjoin("0x", p); len = ft_strlen(p); ft_putstr_fd(p, 1); return (len); }
C
// -------------------------------------------------------------------------------- // Name: Matthew Smith // Class: SET 151 // Abstract: Assignment 3 / This program tests loops // -------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- // Includes built-in libraries of functions // -------------------------------------------------------------------------------- #include <stdio.h> #include <stdlib.h> #include <conio.h> // -------------------------------------------------------------------------------- // Constants // -------------------------------------------------------------------------------- const long lngARRAY_SIZE = 100; // -------------------------------------------------------------------------------- // User Defined Types (UDT) // -------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- // Prototypes // -------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- // Name: main // Abstract: This is where the program starts // -------------------------------------------------------------------------------- void main() { // Variables needed for the loops int intIndex = 0; int intOddIndex = 0; int intNegativeEvenIndex = 0; int intThirdNumber = 0; int intThirdNumberCount = 0; int intTotal = 0; int intOddTotal = 0; int intEvenTotal = 0; int intThirdNumberTotal = 0; /* // -------------------------------------------------------------------------------- // Problem #1 - Print all the whole numbers from 1 to 100. // -------------------------------------------------------------------------------- printf( "Problem #1 - Print all the whole numbers from 1 to 100.\n" ); fflush(stdout); for ( intIndex = 1; intIndex <= 100; intIndex += 1 ) { printf("%d, ", intIndex); // Move to a new line every 10 numbers if (intIndex % 10 == 0) { printf( "\n" ); } } printf( "\n" ); printf( "\n" ); // -------------------------------------------------------------------------------- // Problem #2 - Add all the whole numbers from 1 to 100 and print the total // -------------------------------------------------------------------------------- printf("Problem #2 - Add all the whole numbers from 1 to 100 and print the total.\n"); for (intIndex = 1; intIndex <= 100; intIndex += 1) { intTotal += intIndex; } printf( "The sum of whole numbers is: %d\n", intTotal ); printf( "\n" ); printf( "\n" ); // -------------------------------------------------------------------------------- // Problem #3 - Add all Odd whole numbers from 7 to 313 and print the total // -------------------------------------------------------------------------------- printf("Problem #3 - Add all Odd whole numbers from 7 to 313 and print the total.\n"); for (intOddIndex = 7; intOddIndex <= 313; intOddIndex += 2) { intOddTotal += intOddIndex; } printf("The sum of all Odd whole numbers is: %d\n", intOddTotal); printf("\n"); printf("\n"); */ // -------------------------------------------------------------------------------- // Problem #4 - Add all Even whole numbers from -2 to -146 and print the total // -------------------------------------------------------------------------------- printf("Problem #4 - Add all Even whole numbers from -2 to -146 and print the total.\n"); for ( intNegativeEvenIndex = -2; intNegativeEvenIndex >= -146; intNegativeEvenIndex += -2 ) { intEvenTotal += intNegativeEvenIndex; } printf("The sum of all Even whole numbers is: %d\n", intEvenTotal); printf( "\n" ); printf( "\n" ); // -------------------------------------------------------------------------------- // Problem #5 - Add every 3rd number from 2000 to -60 and print total // -------------------------------------------------------------------------------- printf( "Problem #5 - Add all 3rd whole numbers from 2000 to -60 and print the total.\n" ); for ( intThirdNumber = 2000; intThirdNumber >= -60; intThirdNumber -= 3 ) { intThirdNumberCount += intThirdNumber; intThirdNumberTotal += intThirdNumberCount; } printf( "The sum of all Third numbers is: %d\n", intThirdNumberTotal ); printf( "\n" ); printf( "\n" ); // -------------------------------------------------------------------------------- // Problem #6 - Loop sum of numbers from 1 to 100 entered and print square root // -------------------------------------------------------------------------------- printf( "Problem #6 - Input a number from 1 to 100 and the square root of the sum will display.\n" ); // -------------------------------------------------------------------------------- // Problem #7 - // -------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- // Problem #8 - // -------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- // Problem #9 - // -------------------------------------------------------------------------------- system("pause"); }
C
#include <gtk/gtk.h> #include <glib.h> #include <stdlib.h> #include <stdint.h> #include <string.h> #include <time.h> static void text_changed(GtkWidget *millis_entry, gpointer data) { const gchar* currText = gtk_editable_get_chars (GTK_EDITABLE(millis_entry), 0, -1); char outtime[80]; time_t seconds; struct tm ts; if (strlen(currText) > 0) { /* Check that the character just added is a digit. */ if (!g_ascii_isdigit (currText[strlen(currText) - 1])) { g_print("Ignoring non-digit char\n"); /* Not a digit. Revert this change by cloning the text minus the last character. */ currText = g_strndup(currText, strlen(currText) - 1); /* Reset the input text */ gtk_entry_set_text(GTK_ENTRY(millis_entry), currText); } /* Convert milliseconds to seconds as time_t */ seconds = (time_t)(strtoll(currText, NULL, 0) / 1000); /* Get localized time */ ts = *localtime(&seconds); /* Print formatted time to string */ strftime(outtime, sizeof(outtime), "%Y-%m-%d %H:%M:%S %Z", &ts); /* Set the output text */ gtk_entry_set_text(GTK_ENTRY(data), outtime); } } static void init_time_to_now(GtkWidget *millis_entry, GtkWidget *date_label) { char intime[20]; uint64_t millis = time(NULL) * 1000; snprintf(intime, 20, "%llu", millis); gtk_entry_set_text(GTK_ENTRY(millis_entry), intime); } static void activate (GtkApplication *app, gpointer user_data) { GtkWidget *window; GtkWidget *main_box; GtkWidget *millis_entry; GtkWidget *date_label; GValue editable_false = G_VALUE_INIT; GValue max_chars = G_VALUE_INIT; /* Configuration for making field non editable */ g_value_init(&editable_false, G_TYPE_BOOLEAN); g_value_set_boolean(&editable_false, FALSE); /* Configuration for setting default field width */ g_value_init(&max_chars, G_TYPE_INT); g_value_set_int(&max_chars, 25); /* Main window */ window = gtk_application_window_new (app); gtk_window_set_title (GTK_WINDOW (window), "Epoch Converter"); gtk_window_set_default_size (GTK_WINDOW (window), 225, 50); gtk_window_set_icon_name(GTK_WINDOW (window), "applications-engineering"); /* Main container */ main_box = gtk_button_box_new (GTK_ORIENTATION_VERTICAL); gtk_container_add (GTK_CONTAINER (window), main_box); /* Input for timestamp in millis */ millis_entry = gtk_entry_new(); g_object_set_property(G_OBJECT(millis_entry), "width-chars", &max_chars); /* Output widget for date. I use a GtkEntry so you can select the text. */ date_label = gtk_entry_new(); g_object_set_property(G_OBJECT(date_label), "editable", &editable_false); g_object_set_property(G_OBJECT(date_label), "width-chars", &max_chars); /* Add the widgets to the container */ gtk_container_add(GTK_CONTAINER (main_box), millis_entry); gtk_container_add(GTK_CONTAINER (main_box), date_label); /* Connect the text change signal for the input to a method */ g_signal_connect (GTK_EDITABLE(millis_entry), "changed", G_CALLBACK (text_changed), date_label); /* Start by initializing the input to the current timestamp */ init_time_to_now(millis_entry, date_label); /* Begin display */ gtk_widget_show_all (window); } int main (int argc, char **argv) { GtkApplication *app; int status; app = gtk_application_new ("net.darkport.epoch", G_APPLICATION_FLAGS_NONE); g_signal_connect (app, "activate", G_CALLBACK (activate), NULL); status = g_application_run (G_APPLICATION (app), argc, argv); g_object_unref (app); return status; }
C
#include "bool.h" #include "wgraph.h" #include "triangle.h" #include <math.h> #include <stdio.h> initialize_graph(graph *g) { int i; g -> nvertices = 0; for (i=0; i<=MAXV; i++) g->degree[i] = 0; } int sqr(const int x) { return x * x; } double get_distance(const point src, const point dst) { return sqrt((double)(sqr(src.x - dst.x) + sqr(src.y - dst.y))); } int sign(const int x) { return x > 0 ? 1 : (0 == x ? 0 : -1); } bool check_intersection(const cut a, const cut b) { int A1 = a.p2.y - a.p1.y; int B1 = a.p1.x - a.p2.x; int C1 = -A1 * a.p1.x - B1 * a.p1.y; int A2 = b.p2.y - b.p1.y; int B2 = b.p1.x - b.p2.x; int C2 = -A2 * b.p1.x - B2 * b.p1.y; int f1 = A1 * b.p1.x + B1 * b.p1.y + C1; int f2 = A1 * b.p2.x + B1 * b.p2.y + C1; int f3 = A2 * a.p1.x + B2 * a.p1.y + C2; int f4 = A2 * a.p2.x + B2 * a.p2.y + C2; if (sign(f1) * sign(f2) < 0 && sign(f3) * sign(f4) < 0) { return TRUE; } return FALSE; } bool intersects(const point p1, const point p2, const triangleList * triangles) { int n; cut cut_to_check; cut_to_check.p1 = p1; cut_to_check.p2 = p2; for (n = 0; n < triangles->numTriangles; n++) { { cut triangle_cut; triangle_cut.p1 = triangles->triangles[n].points[0]; triangle_cut.p2 = triangles->triangles[n].points[1]; if (check_intersection(cut_to_check, triangle_cut) == TRUE) { return TRUE; } } { cut triangle_cut; triangle_cut.p1 = triangles->triangles[n].points[0]; triangle_cut.p2 = triangles->triangles[n].points[2]; if (check_intersection(cut_to_check, triangle_cut) == TRUE) { return TRUE; } } { cut triangle_cut; triangle_cut.p1 = triangles->triangles[n].points[1]; triangle_cut.p2 = triangles->triangles[n].points[2]; if (check_intersection(cut_to_check, triangle_cut) == TRUE) { return TRUE; } } { // \todo possibly if section is inside a triangle then forbid such edges. // if we are here we do not have any crosses with triangles. // But according to the task if section is inside a triangle then this path edge is not allowed. } } return FALSE; } void insert_edge( graph * const g, const int p1, // edge start point const int p2, // edge end point const double w) // edge weight { if (g->degree[p1] > MAXDEGREE) { printf("\nWarning: insertion(%d,%d) exceeds degree bound\n", p1, p2); } else { g->edges[p1][g->degree[p1]].weight = w; g->edges[p1][g->degree[p1]].endpoint_index = p2; ++g->degree[p1]; } } void build_graph( graph * g, /* graph to initialize */ const point src, const point dst, const triangleList * triangles) { int i = 0; int j = 0; initialize_graph(g); g->nvertices = triangles->numTriangles * 3 + 2; // add start end end points { g->points[j] = src; ++j; } { g->points[j] = dst; ++j; } // add traingle points for (i = 0; i < triangles->numTriangles; i++) { int k = 0; for (k = 0; k < 3; ++k) { g->points[j] = triangles->triangles[i].points[k]; ++j; } } // connect all points with edges for (i = 0; i < g->nvertices; ++i) { for (j = i + 1; j < g->nvertices; ++j) { if (FALSE == intersects(g->points[i], g->points[j], triangles)) { const double distance = get_distance(g->points[i], g->points[j]); insert_edge(g, i, j, distance); insert_edge(g, j, i, distance); } } } } print_graph(const graph *g) { int i,j; /* counters */ for (i = 0; i < g->nvertices; ++i) { printf("\n%d: ",i); for (j = 0; j < g->degree[i]; ++j) printf(" %d", g->edges[i][j].endpoint_index); printf("\n"); } }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_time_sort.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: glovichi <glovichi@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2015/02/20 15:02:26 by glovichi #+# #+# */ /* Updated: 2015/02/20 16:25:30 by glovichi ### ########.fr */ /* */ /* ************************************************************************** */ #include <time.h> #include <sys/stat.h> #include <stdio.h> #include "./includes/ls.h" void ft_sort_it(t_list *timy) { t_list *newl; unsigned int tmp; char *tempy; newl = timy->next; while (newl) { if (newl->str == NULL) break ; if (newl->prev->str != NULL) { if (newl->date > newl->prev->date) { tmp = newl->prev->date; tempy = newl->prev->str; newl->prev->date = newl->date; newl->prev->str = newl->str; newl->date = tmp; newl->str = tempy; newl = timy->next; } } newl = newl->next; } ft_print_list(&timy); } void ft_time_sort(void) { DIR *arep; struct dirent *within; struct stat st; t_list *timy; arep = opendir("."); while ((within = readdir(arep)) != NULL) { if ((within->d_name)[0] != '.') { stat(within->d_name, &st); ft_add_lnk(ft_nl(within->d_name, st.st_mtime), &timy); } } closedir(arep); ft_sort_it(timy); }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "crearParticionPrimaria.h" struct partition { char part_status; char part_type; char part_fit; int part_start; int part_size; char part_name[16]; }; struct mbr { int mbr_tamano; time_t mbr_fecha_creacion; int mbr_disk_signature; struct partition mbr_partition_1; struct partition mbr_partition_2; struct partition mbr_partition_3; struct partition mbr_partition_4; }; void crearParticionPrimaria(int size, char unit, char * path, char type, char fit, int num_add, char * name, char * borrar){ /*Primero valido si en el MBR se puede crear una particion*/ struct mbr test; FILE * prueba = fopen(path, "r+b"); fseek(prueba, 0, SEEK_SET); fread(&test, sizeof(test), 1, prueba); if(test.mbr_partition_1.part_status != 'A'){ printf("///////////////////////////////////////////////////////////////\n"); printf("Antes de la actualizacion:\n"); printf("Status: %c\n", test.mbr_partition_1.part_status); printf("Type: %c\n", test.mbr_partition_1.part_type); printf("Fit: %c\n", test.mbr_partition_1.part_fit); printf("Start: %d\n", test.mbr_partition_1.part_start); printf("Size: %d\n", test.mbr_partition_1.part_size); printf("Name: %s\n", test.mbr_partition_1.part_name); printf("///////////////////////////////////////////////////////////////\n"); /*STATUS*/ test.mbr_partition_1.part_status = 'A'; /*TYPE*/ test.mbr_partition_1.part_type = 'P'; /*FIT*/ test.mbr_partition_1.part_fit = fit; /*START*/ test.mbr_partition_1.part_start = sizeof(test); /*SIZE*/ if(unit == 'B'){ test.mbr_partition_1.part_size = size; }else if(unit == 'K'){ test.mbr_partition_1.part_size = size*1024; }else if(unit == 'M'){ test.mbr_partition_1.part_size = size*1048576; } /*NAME*/ strncpy(test.mbr_partition_1.part_name, name, 16); printf("///////////////////////////////////////////////////////////////\n"); printf("Despues de la actualizacion:\n"); printf("Status: %c\n", test.mbr_partition_1.part_status); printf("Type: %c\n", test.mbr_partition_1.part_type); printf("Fit: %c\n", test.mbr_partition_1.part_fit); printf("Start: %d\n", test.mbr_partition_1.part_start); printf("Size: %d\n", test.mbr_partition_1.part_size); printf("Name: %s\n", test.mbr_partition_1.part_name); printf("///////////////////////////////////////////////////////////////\n"); /*Agrego los cambios al MBR*/ fseek(prueba, 0, SEEK_SET); fwrite(&test, sizeof(test), 1, prueba); fflush(prueba); fclose(prueba); printf("********************************************************************\n"); printf("Particion creada exitosamente!\n"); printf("********************************************************************\n"); }else if(test.mbr_partition_2.part_status != 'A'){ printf("///////////////////////////////////////////////////////////////\n"); printf("Antes de la actualizacion:\n"); printf("Status: %c\n", test.mbr_partition_2.part_status); printf("Type: %c\n", test.mbr_partition_2.part_type); printf("Fit: %c\n", test.mbr_partition_2.part_fit); printf("Start: %d\n", test.mbr_partition_2.part_start); printf("Size: %d\n", test.mbr_partition_2.part_size); printf("Name: %s\n", test.mbr_partition_2.part_name); printf("///////////////////////////////////////////////////////////////\n"); /*STATUS*/ test.mbr_partition_2.part_status = 'A'; /*TYPE*/ test.mbr_partition_2.part_type = 'P'; /*FIT*/ test.mbr_partition_2.part_fit = fit; /*START*/ test.mbr_partition_2.part_start = test.mbr_partition_1.part_start + test.mbr_partition_1.part_size; /*SIZE*/ if(unit == 'B'){ test.mbr_partition_2.part_size = size; }else if(unit == 'K'){ test.mbr_partition_2.part_size = size*1024; }else if(unit == 'M'){ test.mbr_partition_2.part_size = size*1048576; } /*NAME*/ strncpy(test.mbr_partition_2.part_name, name, 16); printf("///////////////////////////////////////////////////////////////\n"); printf("Despues de la actualizacion:\n"); printf("Status: %c\n", test.mbr_partition_2.part_status); printf("Type: %c\n", test.mbr_partition_2.part_type); printf("Fit: %c\n", test.mbr_partition_2.part_fit); printf("Start: %d\n", test.mbr_partition_2.part_start); printf("Size: %d\n", test.mbr_partition_2.part_size); printf("Name: %s\n", test.mbr_partition_2.part_name); printf("///////////////////////////////////////////////////////////////\n"); /*Agrego los cambios al MBR*/ fseek(prueba, 0, SEEK_SET); fwrite(&test, sizeof(test), 1, prueba); fflush(prueba); fclose(prueba); printf("********************************************************************\n"); printf("Particion creada exitosamente!\n"); printf("********************************************************************\n"); }else if(test.mbr_partition_3.part_status != 'A'){ printf("///////////////////////////////////////////////////////////////\n"); printf("Antes de la actualizacion:\n"); printf("Status: %c\n", test.mbr_partition_3.part_status); printf("Type: %c\n", test.mbr_partition_3.part_type); printf("Fit: %c\n", test.mbr_partition_3.part_fit); printf("Start: %d\n", test.mbr_partition_3.part_start); printf("Size: %d\n", test.mbr_partition_3.part_size); printf("Name: %s\n", test.mbr_partition_3.part_name); printf("///////////////////////////////////////////////////////////////\n"); /*STATUS*/ test.mbr_partition_3.part_status = 'A'; /*TYPE*/ test.mbr_partition_3.part_type = 'P'; /*FIT*/ test.mbr_partition_3.part_fit = fit; /*START*/ test.mbr_partition_3.part_start = test.mbr_partition_2.part_start + test.mbr_partition_2.part_size; /*SIZE*/ if(unit == 'B'){ test.mbr_partition_3.part_size = size; }else if(unit == 'K'){ test.mbr_partition_3.part_size = size*1024; }else if(unit == 'M'){ test.mbr_partition_3.part_size = size*1048576; } /*NAME*/ strncpy(test.mbr_partition_3.part_name, name, 16); printf("///////////////////////////////////////////////////////////////\n"); printf("Despues de la actualizacion:\n"); printf("Status: %c\n", test.mbr_partition_3.part_status); printf("Type: %c\n", test.mbr_partition_3.part_type); printf("Fit: %c\n", test.mbr_partition_3.part_fit); printf("Start: %d\n", test.mbr_partition_3.part_start); printf("Size: %d\n", test.mbr_partition_3.part_size); printf("Name: %s\n", test.mbr_partition_3.part_name); printf("///////////////////////////////////////////////////////////////\n"); /*Agrego los cambios al MBR*/ fseek(prueba, 0, SEEK_SET); fwrite(&test, sizeof(test), 1, prueba); fflush(prueba); fclose(prueba); printf("********************************************************************\n"); printf("Particion creada exitosamente!\n"); printf("********************************************************************\n"); }else if(test.mbr_partition_4.part_status != 'A'){ printf("///////////////////////////////////////////////////////////////\n"); printf("Antes de la actualizacion:\n"); printf("Status: %c\n", test.mbr_partition_4.part_status); printf("Type: %c\n", test.mbr_partition_4.part_type); printf("Fit: %c\n", test.mbr_partition_4.part_fit); printf("Start: %d\n", test.mbr_partition_4.part_start); printf("Size: %d\n", test.mbr_partition_4.part_size); printf("Name: %s\n", test.mbr_partition_4.part_name); printf("///////////////////////////////////////////////////////////////\n"); /*STATUS*/ test.mbr_partition_4.part_status = 'A'; /*TYPE*/ test.mbr_partition_4.part_type = 'P'; /*FIT*/ test.mbr_partition_4.part_fit = fit; /*START*/ test.mbr_partition_4.part_start = test.mbr_partition_3.part_start + test.mbr_partition_3.part_size; /*SIZE*/ if(unit == 'B'){ test.mbr_partition_4.part_size = size; }else if(unit == 'K'){ test.mbr_partition_4.part_size = size*1024; }else if(unit == 'M'){ test.mbr_partition_4.part_size = size*1048576; } /*NAME*/ strncpy(test.mbr_partition_4.part_name, name, 16); printf("///////////////////////////////////////////////////////////////\n"); printf("Despues de la actualizacion:\n"); printf("Status: %c\n", test.mbr_partition_4.part_status); printf("Type: %c\n", test.mbr_partition_4.part_type); printf("Fit: %c\n", test.mbr_partition_4.part_fit); printf("Start: %d\n", test.mbr_partition_4.part_start); printf("Size: %d\n", test.mbr_partition_4.part_size); printf("Name: %s\n", test.mbr_partition_4.part_name); printf("///////////////////////////////////////////////////////////////\n"); /*Agrego los cambios al MBR*/ fseek(prueba, 0, SEEK_SET); fwrite(&test, sizeof(test), 1, prueba); fflush(prueba); fclose(prueba); printf("********************************************************************\n"); printf("Particion creada exitosamente!\n"); printf("********************************************************************\n"); } }
C
#include <stdio.h> #include <stdlib.h> #include <locale.h> int main() { setlocale(LC_ALL, "Portuguese"); int n; printf("Escreva um nmero e o programa responder se par ou mpar: "); scanf("%d",&n); if (n % 2 == 0) { printf("%d um nmero par!", n); } else { printf("%d um nmero mpar!", n); } return 0; }
C
/* ** EPITECH PROJECT, 2019 ** bsq_dlc1 ** File description: ** bsq_dlc1 */ #include "include/my.h" int get_nb_lines(int *fd, char *file) { int i = 0; char nb_lines[15]; *fd = open(file, O_RDONLY); while (read(*fd, &nb_lines[i], 1) > 0 && nb_lines[i] != '\n' && i < 15) i++; nb_lines[i] = 0; return (my_atoi(nb_lines)); } int get_nb_cols(char *file) { int fd = open(file, O_RDONLY); char tmp; int i = 0; while (read(fd, &tmp, 1) > 0 && tmp != '\n'); while (read(fd, &tmp, 1) > 0 && tmp != '\n') i++; close(fd); return (i); } int go_first_line(char *file, int *fd) { char tmp = 0; int i = 0; *fd = open(file, O_RDONLY); while (read(*fd, &tmp, 1) > 0 && tmp != '\n'); tmp = 0; while (read(*fd, &tmp, 1) > 0 && tmp != '\n') i++; close(*fd); *fd = open(file, O_RDONLY); tmp = 0; while (read(*fd, &tmp, 1) > 0 && tmp != '\n'); return (i); }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/socket.h> #include <arpa/inet.h> #include <netdb.h> #include <stdbool.h> #include <sys/types.h> #define MAXBUF 20 #define FALSE 0 #define TRUE 1 struct sockaddr_in sockme; int s; struct servent *pse; char * transport = "tcp"; int portnum; char *hostnum; char bufout[MAXBUF+1]; char bufin[MAXBUF+1]; char *cp; char c; int result; int n; int main(int argc, char *argv[]) { if (argc == 3) { hostnum = argv[1]; (void) sscanf(argv[2], "%d", &portnum); } else { (void) printf("usage: client <hostnum> <portnum>\n"); exit(-1); } sockme.sin_family = AF_INET; if ((sockme.sin_addr.s_addr = inet_addr(hostnum)) == INADDR_NONE) { (void) printf("Invalid dotted decimal address\n"); exit(-1); } sockme.sin_port = htons(portnum); if((s = socket(PF_INET, SOCK_STREAM, 0)) == 0) { /* if socket failed then display error and exit */ perror("Create socket"); exit(EXIT_FAILURE); } if ((result = connect (s, (struct sockaddr *) &sockme, sizeof(sockme)))) { perror("Connect failed\n"); close (s); exit(-1); }; (void) printf("Enter Message: \n"); cp = bufout; while ((c = getchar()) != '\n') { *cp++ = c; } *cp = '\0'; result = send (s, bufout, strlen(bufout), 0); if(result != strlen(bufout)){ perror("send"); exit(EXIT_FAILURE); } printf("Message Sent.\nWaiting for response.\n"); do{ n = read ( s, bufin, MAXBUF ); }while(n != 0); (void) printf("Recieved: %s\n", bufin); result = close(s); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include "sorting.h" static long PrintSorted(long * array,char * filename,long size); static int CheckArray(long * array, long size); static long * ImportNumbers(char * filename,long * size); int main(int argc, char ** argv){ if(argc!= 3){ return EXIT_FAILURE; } int a = 2; long * array; long size; array = ImportNumbers(argv[1],&size); if(array == NULL){ printf("Import failure.\n"); return EXIT_FAILURE; } if(a == 1){ MergeSort(array,size); } if(a == 2){ quicksort(array,size); } if(array == NULL){ printf("Sort failure\n"); return EXIT_FAILURE; } int b = CheckArray(array,size); printf("Array sorted:%d\n",b); if(b==0){ free(array); return EXIT_FAILURE; } PrintSorted(array,argv[2],size); free(array); return EXIT_SUCCESS; } static long PrintSorted(long * array,char * filename, long size){ FILE* fp = fopen(filename,"w"); if(fp == NULL){ return EXIT_FAILURE; } fwrite(array,sizeof(long),size,fp); fclose(fp); return EXIT_SUCCESS; } static int CheckArray(long * array,long size){ long i = 1; printf("len:%ld\n",size); while(i<size && array[i-1]<array[i]){ i++; } if(i < size){ printf("%ld\n",i); return(0); } return(i); } static long * ImportNumbers(char * filename,long * size){ FILE * fp = fopen(filename,"r"); if(fp == NULL){ printf("Bad import name.\n"); return NULL; } fseek(fp,0,SEEK_END); *size = ftell(fp); if((*size)%sizeof(long) != 0){ fclose(fp); printf("Improper format.\n"); return NULL; } *size = (*size)/sizeof(long); if(size == 0){ fclose(fp); printf("File is empty.\n"); return NULL; } printf("El:%ld\n",*size); long * array = malloc((*size)*(sizeof(long))); if(array == NULL){ fclose(fp); printf("Malloc failed."); return NULL; } fseek(fp,0,SEEK_SET); fread(array,(*size)*sizeof(long),1,fp); fclose(fp); return array; }
C
#include"head.h" void send_file(int newfd,char *name) { int size; data buf; buf.len = strlen(name); strcpy(buf.buf,name); printf("begin send file [%s]\n",buf.buf); size = send(newfd,&buf.len,4,0); if(-1 == size) err("send name_len") size = send(newfd,buf.buf,buf.len,0); if(-1 == size) err("send name") int fd = open(name,O_RDONLY); if(-1 == fd) err("open") int ret; while(bzero(&buf,sizeof(buf)),(buf.len = read(fd,buf.buf,sizeof(buf))) > 0) { size = send(newfd,&buf.len,4,0); if(-1 == size) err("send content_len") send_n(newfd,&buf); } bzero(&buf,sizeof(buf)); size = send(newfd,&buf.len,4,0); if(-1 == size) err("send end tag") } void send_n(int newfd,data *p) { int total = 0; int size; while(total < p->len) { size = send(newfd,&p->buf+total,p->len-total,0); total += size; } }
C
#include <stdio.h> #define N 100 void reversal(char array[], int n); int main() { char array[N]; char ch; int n = 0; printf("Enter the message: "); while ((ch = getchar()) != '\n') { if (n < N) { array[n] = ch; n++; } else { printf("out of range!!\n"); break; } } reversal(array, n); // 输出 for (char *p = array; p < array + n; p++) printf("%c", *p); printf("\n"); return 0; } void reversal(char array[], int n) { char *head = array, *tail = array + n - 1; char tmp; while (head < tail) { tmp = *head; *head++ = *tail; *tail-- = tmp; } } // test: Don't get mad, get even.
C
#include <stdlib.h> #include "heap.h" HEAP *makeheap(HEAPLT lessthan) { HEAP *heap = malloc(sizeof(HEAP)); heap->array = malloc(sizeof(void*) * HEAPINITSIZE); heap->cap = HEAPINITSIZE; heap->size = 0; heap->lessthan = lessthan; return heap; } void freeheap(HEAP *heap) { free(heap->array); free(heap); } /* double the size of the underlying array for a heap (free the old one) */ static void expand(HEAP *heap) { void **newarray = malloc(sizeof(void*) * heap->cap * 2); unsigned int i; for (i = 0; i < heap->size; i++) newarray[i] = heap->array[i]; free(heap->array); heap->array = newarray; heap->cap *= 2; } void *heappeek(HEAP *heap) { void *min = NULL; if (heap->size > 0) min = heap->array[0]; return min; } /* swap the elements in the heap's array at positions a and b */ static void swap(HEAP *heap, unsigned int a, unsigned int b) { void *tmp = heap->array[a]; heap->array[a] = heap->array[b]; heap->array[b] = tmp; } /* bubble up the heap from position a in the array */ static void bubbleup(HEAP *heap, unsigned int a) { HEAPLT lt = heap->lessthan; while (a > 0 && lt(heap->array[a], heap->array[HEAPPARENT(a)])) { swap(heap, a, HEAPPARENT(a)); a = HEAPPARENT(a); } } /* bubble down the heap from position a in the array */ static void bubbledown(HEAP *heap, unsigned int a) { HEAPLT lt = heap->lessthan; while (HEAPLEFT(a) < heap->size) { unsigned int b = HEAPLEFT(a); if (HEAPRIGHT(a) < heap->size && lt(heap->array[HEAPRIGHT(a)], heap->array[HEAPLEFT(a)])) b = HEAPRIGHT(a); if (lt(heap->array[b], heap->array[a])) { swap(heap, a, b); a = b; } else { return; } } } void heapinsert(HEAP *heap, void *element) { if (heap->size >= heap->cap) expand(heap); heap->array[heap->size] = element; heap->size += 1; bubbleup(heap, heap->size - 1); } void *heapdelete(HEAP *heap, unsigned int a) { if (a > heap->size - 1 || heap->size == 0) return NULL; swap(heap, a, heap->size - 1); heap->size -= 1; void *victim = heap->array[heap->size]; heap->array[heap->size] = NULL; if (heap->size > 1 && a < heap->size) { HEAPLT lt = heap->lessthan; if (lt(heap->array[a], heap->array[HEAPPARENT(a)])) bubbleup(heap, a); else bubbledown(heap, a); } return victim; } void *heappop(HEAP *heap) { return heapdelete(heap, 0); }
C
/* times -- system call emulation for 4.2BSD */ #include <sys/types.h> #include <sys/times.h> #include <sys/param.h> extern int _getrusage(); extern long time(); struct timeval { long tv_sec; long tv_usec; }; #define cvt(x) (HZ * x.tv_sec + ((HZ * x.tv_usec ) + 500000 ) / 1000000) long times( buffer ) register struct tms *buffer; /* where to put info */ { struct { struct timeval ru_utime; struct timeval ru_stime; int ru_stuff[14]; } rusage; struct timeval tt; if ( _getrusage( 0, &rusage ) != 0 ) /* self */ return -1L; buffer->tms_utime = cvt(rusage.ru_utime); buffer->tms_stime = cvt(rusage.ru_stime); if ( _getrusage( -1, &rusage ) != 0 ) /* children */ return -1L; buffer->tms_cutime = cvt(rusage.ru_utime); buffer->tms_cstime = cvt(rusage.ru_stime); if (_gettimeofday(&tt, (struct timezone *)0) < 0) return -1L; return cvt(tt); }
C
#include <stdio.h> #include <math.h> int main(){ double x1, x2, y1, y2; double soma; scanf("%lf %lf", &x1, &y1); scanf("%lf %lf", &x2, &y2); soma = ((x2 - x1)*(x2 - x1) + (y2 - y1)*(y2 - y1)); double distancia = sqrt (soma); printf("%.4lf\n", distancia); return 0; }
C
#include<stdio.h> void binary_Search(int *array, int len, int key) { int i = 0; int min_index = 0; int max_index = len-1; while(min_index <= max_index) { // calculate the mid index int mid = (min_index + max_index) / 2; printf("mid = %d\n",array[mid] ); // check if we get the key if(array[mid] == key) { printf("Key has been found\n"); return; } // traverse in the right side else if(array[mid] < key) { min_index = mid + 1; } // traverse in the left side else { max_index = mid - 1; } } printf("Not able to find key\n"); } int main() { int arr[5] = {10, 30, 45, 48, 78}; int arrayLen = 5; int key = 45; int key_2 = 34; //successful search // binary_Search(arr,arrayLen, key); //key not found case binary_Search(arr,arrayLen, key_2); return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* numbers2.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ohakola <ohakola@student.hive.fi> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/06/16 16:24:20 by ohakola #+# #+# */ /* Updated: 2020/06/16 17:18:22 by ohakola ### ########.fr */ /* */ /* ************************************************************************** */ #include "filler.h" void number_5(int letters[10][9][6]) { assign_ints(letters[5][0], (int[6]){1, 1, 1, 1, 1, 1}); assign_ints(letters[5][1], (int[6]){1, 0, 0, 0, 0, 0}); assign_ints(letters[5][2], (int[6]){1, 0, 0, 0, 0, 0}); assign_ints(letters[5][3], (int[6]){1, 0, 0, 0, 0, 0}); assign_ints(letters[5][4], (int[6]){0, 1, 1, 1, 0, 0}); assign_ints(letters[5][5], (int[6]){0, 0, 0, 0, 1, 0}); assign_ints(letters[5][6], (int[6]){0, 0, 0, 0, 0, 1}); assign_ints(letters[5][7], (int[6]){0, 0, 0, 0, 0, 1}); assign_ints(letters[5][8], (int[6]){1, 1, 1, 1, 1, 0}); } void number_6(int letters[10][9][6]) { assign_ints(letters[6][0], (int[6]){0, 1, 1, 1, 1, 1}); assign_ints(letters[6][1], (int[6]){1, 0, 0, 0, 0, 0}); assign_ints(letters[6][2], (int[6]){1, 0, 0, 0, 0, 0}); assign_ints(letters[6][3], (int[6]){1, 0, 0, 0, 0, 0}); assign_ints(letters[6][4], (int[6]){1, 1, 1, 1, 1, 0}); assign_ints(letters[6][5], (int[6]){1, 0, 0, 0, 0, 1}); assign_ints(letters[6][6], (int[6]){1, 0, 0, 0, 0, 1}); assign_ints(letters[6][7], (int[6]){1, 0, 0, 0, 0, 1}); assign_ints(letters[6][8], (int[6]){0, 1, 1, 1, 1, 0}); } void number_7(int letters[10][9][6]) { assign_ints(letters[7][0], (int[6]){1, 1, 1, 1, 1, 1}); assign_ints(letters[7][1], (int[6]){0, 0, 0, 0, 0, 1}); assign_ints(letters[7][2], (int[6]){0, 0, 0, 0, 0, 1}); assign_ints(letters[7][3], (int[6]){0, 0, 0, 0, 1, 0}); assign_ints(letters[7][4], (int[6]){0, 0, 0, 1, 0, 0}); assign_ints(letters[7][5], (int[6]){0, 0, 1, 0, 0, 0}); assign_ints(letters[7][6], (int[6]){0, 1, 0, 0, 0, 0}); assign_ints(letters[7][7], (int[6]){1, 0, 0, 0, 0, 0}); assign_ints(letters[7][8], (int[6]){1, 0, 0, 0, 0, 0}); } void number_8(int letters[10][9][6]) { assign_ints(letters[8][0], (int[6]){0, 1, 1, 1, 1, 0}); assign_ints(letters[8][1], (int[6]){1, 0, 0, 0, 0, 1}); assign_ints(letters[8][2], (int[6]){1, 0, 0, 0, 0, 1}); assign_ints(letters[8][3], (int[6]){1, 0, 0, 0, 0, 1}); assign_ints(letters[8][4], (int[6]){1, 1, 1, 1, 1, 0}); assign_ints(letters[8][5], (int[6]){1, 0, 0, 0, 0, 1}); assign_ints(letters[8][6], (int[6]){1, 0, 0, 0, 0, 1}); assign_ints(letters[8][7], (int[6]){1, 0, 0, 0, 0, 1}); assign_ints(letters[8][8], (int[6]){0, 1, 1, 1, 1, 0}); } void number_9(int letters[10][9][6]) { assign_ints(letters[9][0], (int[6]){0, 1, 1, 1, 1, 0}); assign_ints(letters[9][1], (int[6]){1, 0, 0, 0, 0, 1}); assign_ints(letters[9][2], (int[6]){1, 0, 0, 0, 0, 1}); assign_ints(letters[9][3], (int[6]){1, 0, 0, 0, 0, 1}); assign_ints(letters[9][4], (int[6]){0, 1, 1, 1, 1, 1}); assign_ints(letters[9][5], (int[6]){0, 0, 0, 0, 0, 1}); assign_ints(letters[9][6], (int[6]){0, 0, 0, 0, 0, 1}); assign_ints(letters[9][7], (int[6]){0, 0, 0, 0, 0, 1}); assign_ints(letters[9][8], (int[6]){1, 1, 1, 1, 1, 0}); }
C
#include "uls.h" static void sort_by_alphabet(t_names *names) { uint8_t offset = READ_FLAG(names->flags, flag_G) ? 4 : 0; uint8_t index = 0; index += READ_FLAG(names->flags, flag_l) ? 6 : 0; index += READ_FLAG(names->flags, flag_i); index += READ_FLAG(names->flags, flag_s); for(uint16_t j = 0; j < names->count.line; ++j) { for(uint16_t i = 0; i < names->count.line - 1; ++i) { if(READ_FLAG(names->flags, flag_r) ? mx_strcmp(&names->list[i][index][offset], &names->list[i + 1][index][offset]) < 0 : mx_strcmp(&names->list[i][index][offset], &names->list[i + 1][index][offset]) > 0) { char** temp = names->list[i]; names->list[i] = names->list[i + 1]; names->list[i + 1] = temp; } } } } static void size_sort(t_names *names) { for (uint32_t i = 0; i < names->count.line; i++) { for (uint32_t j = 0; j < names->count.line - 1; j++) { if (names->sort[j] < names->sort[j + 1]) { uint64_t temp_uint = names->sort[j]; char** temp = names->list[j]; names->sort[j] = names->sort[j + 1]; names->list[j] = names->list[j + 1]; names->sort[j + 1] = temp_uint; names->list[j + 1] = temp; } } } free(names->sort); names->sort = NULL; } void sort(t_names *names) { if(READ_FLAG(names->flags, flag_f)) { return; } else if(READ_FLAG(names->flags, flag_S | flag_t)) { size_sort(names); } else { sort_by_alphabet(names); } }
C
/* * The AVExec function will turn the Avenue source code * contained in source into an Avenue script, and execute * the script. If there are any errors, AVExec returns NULL. * Otherwise, AVExec turns the resultant object into a * string and returns it. Do NOT modify the resultant string. */ #if defined (__cplusplus) extern "C" { #endif char *AVExec(char* source); #if defined (__cplusplus) } #endif
C
/********************************************************************** * This code is representing my APP for WD RC1 * * Lab: OL-79 * * Author: Yonatan Vologdin * * Reviewer: Shaddad Gomid * * Date: 20.01.20 * **********************************************************************/ #include <stdio.h> /*printf*/ #include <signal.h> /* sigaction*/ #include <unistd.h> /*sleep*/ #include "watcher.h" /* #define TEST_DNR */ /* #define TEST_APP_CRASH */ #define DEAD_TIME (5) #define INTERVAL (1) #define UNUSE(x) (void)(x) int MMI(char **argv, int dead_time, int interval); int main(int argc, char **argv) { #ifdef TEST_DNR int i = 0; #endif #ifdef TEST_APP_CRASH int i = 0; #endif int k = 0; int dead_time = DEAD_TIME; int interval = INTERVAL; UNUSE(argc); if (0 != MMI(argv, dead_time, interval)) { printf("\n\nMMI failed\n\n"); return 1; } for(k = 0; k < 30; ++k) { printf("executing critial section\n"); #ifdef TEST_DNR printf("\t\t\tTHREAD: waiting for DNR to activate in %d/10\n", i); if (i == 10) { DNR(); } ++i; #endif #ifdef TEST_APP_CRASH printf("THREAD: Killing himself in %d/10 (TEST_APP_CRASH)\n", i); if (i == 10) { sleep(1); kill(getpid(), SIGKILL); printf("\t\t\tTHREAD: THREAD shoud be dead!\n"); } ++i; #endif sleep(1); } printf("\nAPP: APP terminated successfully!\n"); return 0; }
C
/** * \file Tester_Configurator.c * \brief Tester of Configurator functions * \author Morgan Chabaud \n */ #include "Configurator.h" #include "Type_Bool.h" // TextDesc extern int globs_occurThreshold; extern int globs_maxTerms; // SoundDesc extern int globs_windowSize; extern int globs_nbInterval; extern double globs_minFrequency; extern double globs_maxFrequency; extern double globs_minWindowMatch; extern double globs_minQuantifMatch; // PictureDesc extern int globs_nbWeightyBits; extern int globs_compTolerance; Bool tests_setGlobsVariables(Bool details); Bool tests_writeReadGlobs(Bool details); Bool tests_enterGlobsVariables(Bool details); Bool tests_initConfigurator(Bool details); //=================================================================================================== int main() { Bool hasPassed; printf("\n\n\n\n\tTester_Configurator:\n"); hasPassed = tests_setGlobsVariables(TRUE); if(hasPassed) printf("\n\t\tTests_setGlobsVariables: Success\n"); else printf("\n\t\tTests_setGlobsVariables: Failure\n"); hasPassed = tests_writeReadGlobs(TRUE); if(hasPassed) printf("\n\t\tTests_writeReadGlobs: Success\n"); else printf("\n\t\tTests_writeReadGlobs: Failure\n"); hasPassed = tests_enterGlobsVariables(TRUE); if(hasPassed) printf("\n\t\tTests_enterGlobsVariables: Success\n"); else printf("\n\t\tTests_enterGlobsVariables: Failure\n"); hasPassed = tests_initConfigurator(TRUE); if(hasPassed) printf("\n\t\tTests_initConfigurator: Success\n"); else printf("\n\t\tTests_initConfigurator: Failure\n"); printf("\tTester_End\n"); } //=================================================================================================== Bool tests_initConfigurator(Bool details) { Bool testPassed = TRUE; // Deleting the previous test file FILE* confFile = fopen(CONF_FILE_NAME, "wb+"); if(confFile == NULL) { perror("tests_writeReadGlobs fopen"); return FALSE; } fclose(confFile); if(initConfigurator()) { if(details) printf("\nThe configuration file is empty, first writing: Pass"); } else { if(details) printf("\nThe configuration file is empty, first writing: Fail"); testPassed = FALSE; } if(initConfigurator()) { if(details) printf("\nThe configuration file has already been set, we just import variables: Pass"); } else { if(details) printf("\nThe configuration file has already been set, we just import variables: Fail"); testPassed = FALSE; } printf("\nThose values have been imported:"); printf("\nglobs_maxPathLength: %d", globs_maxPathLength); printf("\nglobs_occurThreshold : %d", globs_occurThreshold); printf("\nglobs_maxTerms : %d", globs_maxTerms); printf("\nglobs_nbWeightyBits : %d", globs_nbWeightyBits); printf("\nglobs_compTolerance : %d", globs_compTolerance); printf("\nglobs_windowSize : %d", globs_windowSize); printf("\nglobs_nbInterval : %d", globs_nbInterval); printf("\nglobs_minFrequency : %f", globs_minFrequency); printf("\nglobs_maxFrequency : %f", globs_maxFrequency); printf("\nglobs_minWindowMatch: %f", globs_minWindowMatch); printf("\nglobs_minQuantifMatch: %f", globs_minQuantifMatch); return testPassed; } //=================================================================================================== Bool tests_enterGlobsVariables(Bool details) { Bool testPassed = TRUE; FILE* confFile = fopen("testConf.conf", "wb+"); if(confFile == NULL) { perror("tests_writeReadGlobs fopen"); return FALSE; } printf("\nIn order to test enterGlobsVariables, please compare your inputs and the stored variables:"); if(enterGlobsVariables(confFile)) { if(details) printf("\nVariables are stored in a configuration file named testConf.conf"); } else { if(details) printf("\nVariables are NOT stored in a configuration file"); testPassed = FALSE; } printf("\nThose values have been stored:"); printf("\nglobs_maxPathLength: %d", globs_maxPathLength); printf("\nglobs_occurThreshold : %d", globs_occurThreshold); printf("\nglobs_maxTerms : %d", globs_maxTerms); printf("\nglobs_nbWeightyBits : %d", globs_nbWeightyBits); printf("\nglobs_compTolerance : %d", globs_compTolerance); printf("\nglobs_windowSize : %d", globs_windowSize); printf("\nglobs_nbInterval : %d", globs_nbInterval); printf("\nglobs_minFrequency : %f", globs_minFrequency); printf("\nglobs_maxFrequency : %f", globs_maxFrequency); printf("\nglobs_minWindowMatch: %f", globs_minWindowMatch); printf("\nglobs_minQuantifMatch: %f", globs_minQuantifMatch); return testPassed; } //=================================================================================================== Bool tests_writeReadGlobs(Bool details) { Bool testPassed = TRUE; WritableGlobs globs = {10, 15, 20, 25, 0.35, -5.3, 90, 2}; FILE* file = fopen("testConf.conf", "wb+"); if(file == NULL) { perror("tests_writeReadGlobs fopen"); return FALSE; } if(!writeGlobs(&globs, file)) { perror("tests_writeReadGlobs writeGlobs"); return FALSE; } // Changing the global variables before reading the file just saved. globs_maxPathLength = 0; globs_occurThreshold = 0; globs_maxTerms = 0; globs_nbWeightyBits = 0; globs_compTolerance = 0; globs_windowSize = 0; globs_nbInterval = 0; globs_minFrequency = 0.0; globs_maxFrequency = 0.0; globs_minWindowMatch = 0.0; globs_minQuantifMatch = 0.0; rewind(file); if(!readGlobs(file)) { perror("tests_readGlobs readGlobs"); return FALSE; } // Let's test if the globals have been read correctly if(details) printf("\nglobs_maxPathLength: "); if(globs_maxPathLength != globs.listBaseDesc_maxPathLength) { if(details) printf("Fail"); testPassed = FALSE; } else { if(details) printf("Pass"); } if(details) printf("\nglobs_occurThreshold: "); if(globs_occurThreshold != globs.textDesc_occurThreshold) { if(details) printf("Fail"); testPassed = FALSE; } else { if(details) printf("Pass"); } if(details) printf("\nglobs_maxTerms: "); if(globs_maxTerms != globs.textDesc_maxTerms) { if(details) printf("Fail"); testPassed = FALSE; } else { if(details) printf("Pass"); } if(details) printf("\nglobs_nbWeightyBits: "); if(globs_nbWeightyBits != globs.pictureDesc_nbWeightyBits) { if(details) printf("Fail"); testPassed = FALSE; } else { if(details) printf("Pass"); } if(details) printf("\nglobs_compTolerance: "); if(globs_compTolerance != globs.pictureDesc_compTolerance) { if(details) printf("Fail"); testPassed = FALSE; } else { if(details) printf("Pass"); } if(details) printf("\nglobs_windowSize: "); if(globs_windowSize != globs.soundDesc_windowSize) { if(details) printf("Fail"); testPassed = FALSE; } else { if(details) printf("Pass"); } if(details) printf("\nglobs_nbInterval: "); if(globs_nbInterval != globs.soundDesc_nbInterval) { if(details) printf("Fail"); testPassed = FALSE; } else { if(details) printf("Pass"); } if(details) printf("\nglobs_minFrequency: "); if(fabs(globs_minFrequency - globs.soundDesc_minFrequency) > 0.00001) { if(details) printf("Fail"); testPassed = FALSE; } else { if(details) printf("Pass"); } if(details) printf("\nglobs_maxFrequency: "); if(fabs(globs_maxFrequency - globs.soundDesc_maxFrequency) > 0.00001) { if(details) printf("Fail"); testPassed = FALSE; } else { if(details) printf("Pass"); } if(details) printf("\nglobs_minWindowMatch: "); if(fabs(globs_minWindowMatch - globs.soundDesc_minWindowMatch) > 0.00001) { if(details) printf("Fail"); testPassed = FALSE; } else { if(details) printf("Pass"); } if(details) printf("\nglobs_minQuantifMatch: "); if(fabs(globs_minQuantifMatch - globs.soundDesc_minQuantifMatch) > 0.00001) { if(details) printf("Fail"); testPassed = FALSE; } else { if(details) printf("Pass"); } return testPassed; } //=================================================================================================== Bool tests_setGlobsVariables(Bool details) { Bool testPassed = TRUE; WritableGlobs globs = { 250, 10, 15, 20, 25, 0.35, -5.3, 90, 2, 2.3, 13.5}; setGlobsVariables(&globs); if(details) printf("\nInitialising globs_maxPathLength: "); if(globs_maxPathLength != globs.listBaseDesc_maxPathLength) { if(details) printf("Fail"); testPassed = FALSE; } else { if(details) printf("Pass"); } if(details) printf("\nInitialising globs_occurThreshold: "); if(globs_occurThreshold != globs.textDesc_occurThreshold) { if(details) printf("Fail"); testPassed = FALSE; } else { if(details) printf("Pass"); } if(details) printf("\nInitialising globs_maxTerms: "); if(globs_maxTerms != globs.textDesc_maxTerms) { if(details) printf("Fail"); testPassed = FALSE; } else { if(details) printf("Pass"); } if(details) printf("\nInitialising globs_windowSize: "); if(globs_windowSize != globs.soundDesc_windowSize) { if(details) printf("Fail"); testPassed = FALSE; } else { if(details) printf("Pass"); } if(details) printf("\nInitialising globs_nbInterval: "); if(globs_nbInterval != globs.soundDesc_nbInterval) { if(details) printf("Fail"); testPassed = FALSE; } else { if(details) printf("Pass"); } if(details) printf("\nInitialising globs_minFrequency: "); if(fabs(globs_minFrequency - globs.soundDesc_minFrequency) > 0.00001) { if(details) printf("Fail"); testPassed = FALSE; } else { if(details) printf("Pass"); } if(details) printf("\nInitialising globs_maxFrequency: "); if(fabs(globs_maxFrequency - globs.soundDesc_maxFrequency) > 0.00001) { if(details) printf("Fail"); testPassed = FALSE; } else { if(details) printf("Pass"); } if(details) printf("\nInitialising globs_nbWeightyBits: "); if(globs_nbWeightyBits != globs.pictureDesc_nbWeightyBits) { if(details) printf("Fail"); testPassed = FALSE; } else { if(details) printf("Pass"); } if(details) printf("\nInitialising globs_compTolerance: "); if(globs_compTolerance != globs.pictureDesc_compTolerance) { if(details) printf("Fail"); testPassed = FALSE; } else { if(details) printf("Pass"); } if(details) printf("\nInitialising globs_minWindowMatch: "); if(fabs(globs_minWindowMatch - globs.soundDesc_minWindowMatch) > 0.00001) { if(details) printf("Fail"); testPassed = FALSE; } else { if(details) printf("Pass"); } if(details) printf("\nInitialising globs_minQuantifMatch: "); if(fabs(globs_minQuantifMatch - globs.soundDesc_minQuantifMatch) > 0.00001) { if(details) printf("Fail"); testPassed = FALSE; } else { if(details) printf("Pass"); } return testPassed; }
C
#include "pthread.h" #include "sys/time.h" #include "myqueue.h" #include "myhandle.h" #include "myservice.h" #include "mysysenv.h" #include "myaux.h" static pthread_mutex_t test_mutex; static pthread_cond_t test_cond; #include<stdio.h> #include<stdlib.h> #include<signal.h> #include<string.h> #include<execinfo.h> void SystemErrorHandler(int signum) { const int len=1024; void *func[len]; size_t size; int i; char **funs; signal(signum,SIG_DFL); size=backtrace(func,len); funs=(char**)backtrace_symbols(func,size); fprintf(stderr,"System error, Stack trace:\n"); for(i=0;i<size;++i) fprintf(stderr,"%d %s \n",i,funs[i]); free(funs); //exit(1); } void Fun1() { char *p=NULL; *p = 'A'; } void Fun() { Fun1(); } void get_abstime_wait(int microseconds, struct timespec *abstime) { struct timeval tv; int absmsec; gettimeofday(&tv, NULL); absmsec = tv.tv_sec * 1000 + tv.tv_usec / 1000; absmsec += microseconds; abstime->tv_sec = absmsec / 1000; abstime->tv_nsec = absmsec % 1000 * 1000000; } void *thread_test(void* arg){ DBG_PRINT("%s\n",arg); int i = 0; while(1) { struct timeval now; struct timespec outtime; pthread_mutex_lock(&test_mutex); gettimeofday(&now,NULL); DBG_PRINT("now = %u\n", now.tv_sec); outtime.tv_sec = now.tv_sec + 1; outtime.tv_nsec = now.tv_usec*1000; //get_abstime_wait(1000,&outtime); pthread_cond_timedwait(&test_cond,&test_mutex,&outtime); pthread_mutex_unlock(&test_mutex); int source = outtime.tv_sec % 10; int handle = now.tv_usec % 30; int code = i++; int moduleIndex = now.tv_usec % 40; struct message_data *new_msg_data = malloc(sizeof(struct message_data)); new_msg_data->code = code; //send_msg(source,handle,new_msg_data); char name[MAX_NAME_LEN]; sprintf(name,"module-%d",moduleIndex); send_msg_byName(source,name,new_msg_data); } DBG_PRINT("%s-222\n",arg); } void send_test_msg(int source){ struct message_data *new_msg_data = msgQueue_create_msgData(); if(new_msg_data == NULL) return; new_msg_data->code = source; char name[MAX_NAME_LEN]; int target = (source + 1)%9+1; //int target = (source + 1)%10; sprintf(name,"module-%d",target); send_msg_byName(source,name,new_msg_data); } void send_test_msg0(int source){ struct message_data *new_msg_data = msgQueue_create_msgData(); if(new_msg_data == NULL) return; new_msg_data->code = source; char name[MAX_NAME_LEN]; int target = source; sprintf(name,"service-%d",target); send_msg_byName(source,name,new_msg_data); } int module_x_callback(int source,struct message_data* msg_d){ DBG_PRINT(L_RED"xxxxxmodule_x_callback,source= %d, msg_d->code = %d \n"NONE,source,msg_d->code); //send_test_msg(0); //send_test_msg(0); return 0; } int static idx = 100; int module_0_callback(int source,struct message_data* msg_d){ DBG_PRINT("00000module_0_callback,source= %d, msg_d->code = %d \n",source,msg_d->code); //send_test_msg(0); char name[MAX_NAME_LEN]; sprintf(name,"service-%d",idx++); service_create(name, module_x_callback, NULL, NULL, NULL,S_TYPE_ONCE); send_test_msg0(idx-1); //send_test_msg(0); return 0; } int module_1_callback(int source,struct message_data* msg_d){ //DBG_PRINT("11111module_1_callback,source= %d, msg_d->code = %d \n",source,msg_d->code); send_test_msg(1); send_test_msg0(0); //send_test_msg(0); return 0; } int module_2_callback(int source,struct message_data* msg_d){ //DBG_PRINT("22222module_2_callback,source= %d, msg_d->code = %d \n",source,msg_d->code); send_test_msg(2); send_test_msg0(0); //send_test_msg(5); return 0; } int module_3_callback(int source,struct message_data* msg_d){ //DBG_PRINT("33333module_3_callback,source= %d, msg_d->code = %d \n",source,msg_d->code); send_test_msg(3); send_test_msg0(0); //send_test_msg(1); return 0; } int module_4_callback(int source,struct message_data* msg_d){ //DBG_PRINT("44444module_4_callback,source= %d, msg_d->code = %d \n",source,msg_d->code); send_test_msg(4); send_test_msg0(0); //send_test_msg(2); return 0; } int module_5_callback(int source,struct message_data* msg_d){ //DBG_PRINT("55555module_5_callback,source= %d, msg_d->code = %d \n",source,msg_d->code); send_test_msg(5); send_test_msg0(0); //send_test_msg(9); return 0; } int module_6_callback(int source,struct message_data* msg_d){ //DBG_PRINT("66666module_6_callback,source= %d, msg_d->code = %d \n",source,msg_d->code); send_test_msg(6); send_test_msg0(0); //send_test_msg(7); return 0; } int module_7_callback(int source,struct message_data* msg_d){ //DBG_PRINT("77777module_7_callback,source= %d, msg_d->code = %d \n",source,msg_d->code); send_test_msg(7); send_test_msg0(0); //send_test_msg(5); return 0; } int module_8_callback(int source,struct message_data* msg_d){ //DBG_PRINT("88888module_8_callback,source= %d, msg_d->code = %d \n",source,msg_d->code); send_test_msg(8); send_test_msg0(0); //send_test_msg(2); return 0; } int module_9_callback(int source,struct message_data* msg_d){ //DBG_PRINT("99999module_9_callback,source= %d, msg_d->code = %d \n",source,msg_d->code); send_test_msg(9); send_test_msg0(0); //send_test_msg(3); return 0; } struct serviceInfo* module_x_init(callbackFunc cb,char* name){//name should short less than 20 struct serviceInfo* service = NULL; service = service_create(name, cb, NULL, NULL, NULL,S_TYPE_FOREVER); return service; } void modules_init(){ module_x_init(module_0_callback,"service-0"); module_x_init(module_1_callback,"module-1"); module_x_init(module_2_callback,"module-2"); module_x_init(module_3_callback,"module-3"); module_x_init(module_4_callback,"module-4"); module_x_init(module_5_callback,"module-5"); module_x_init(module_6_callback,"module-6"); module_x_init(module_7_callback,"module-7"); module_x_init(module_8_callback,"module-8"); module_x_init(module_9_callback,"module-9"); int i = 0; for (i=0;i<30;i++){ char name[MAX_NAME_LEN]; sprintf(name,"module-%d",i+10); module_x_init(module_x_callback,name); } } main(){ signal(SIGSEGV,SystemErrorHandler); //Invaild memory address signal(SIGABRT,SystemErrorHandler); // Abort signal //Fun(); //return 0; mysysenv_init(); modules_init(); send_test_msg(5); send_test_msg0(0); //pthread_mutex_init(&test_mutex,NULL); //pthread_cond_init(&test_cond,NULL); //pthread_t th_t; //pthread_create(&th_t,NULL,thread_test,"myTest");DBG_PRINT("th_t=%u\n",th_t); mysysenv_startwork(); //pthread_join(th_t,NULL); }
C
/* ** EPITECH PROJECT, 2019 ** engine_compartment.c ** File description: */ #include <stdio.h> #include "objdump.h" static void engine_compar_sub(char v[16], unsigned int uh, unsigned int i, unsigned char lm) { static const char *format = "%02x"; if (i % 16 == 0) engine_print_sub(v, &uh, 1, 16, i); else if (i % 4 == 0) printf(" "); (void)i; printf(format, lm); v[i % 16] = lm; } static void engine_compar_print(char v[16], unsigned int uh, unsigned int i) { if (i % 16 != 0) engine_print_sub(v, &uh, 0, i % 16, i); (void)i; if (i % 16 == 0) engine_print_sub(v, &uh, 0, 16, i); } void engine_compartment_32(data32_t *seed, int ne) { static const char *content = "Contents of section %s:\n"; char v[16]; unsigned int uh; unsigned int i; unsigned char lm; (void)seed; uh = (unsigned int)(seed->sh[ne].sh_addr); v[0] = 0; printf(content, &(seed->tab[seed->sh[ne].sh_name])); for (i = 0; i < seed->sh[ne].sh_size; i++) { lm = *(char *) (seed->dat + seed->sh[ne].sh_offset + i); (void)seed; engine_compar_sub(v, uh, i, lm); } engine_compar_print(v, uh, i); } void engine_compartment_64(data64_t *seed, int ne) { static const char *content = "Contents of section %s:\n"; char v[16]; unsigned int uh; unsigned int i; unsigned char lm; uh = (unsigned int)(seed->sh[ne].sh_addr); v[0] = 0; printf(content, &(seed->tab[seed->sh[ne].sh_name])); (void)seed; for (i = 0; i < seed->sh[ne].sh_size; i++) { lm = *(char *) (seed->dat + seed->sh[ne].sh_offset + i); (void)seed; engine_compar_sub(v, uh, i, lm); } engine_compar_print(v, uh, i); }
C
#include <inttypes.h> #include "console.h" #include "kstdlib.h" typedef enum { csDefault = 0, csSetColor, csSetForeground, csSetBackground, } ConsoleState; typedef struct { int foreground:4; int background:4; } ConsoleColor; typedef struct { char c; uint8_t color; } ConsoleChar; static int cursorX = 0; static int cursorY = 0; static ConsoleColor color = { COLOR_LIGHTGRAY, COLOR_BLACK }; static ConsoleState state = csDefault; static ConsoleChar *screen = (ConsoleChar*)0xB8000; static ConsoleChar *statusbar = (ConsoleChar*)(0xB8000 + 0x02 * CONSOLE_WIDTH * CONSOLE_HEIGHT); void console_setstate(const char *text) { for(size_t i = 0; i < CONSOLE_WIDTH; i++) { statusbar[i].c = ' '; statusbar[i].color = 0x70; } ConsoleChar *ptr = statusbar; while(*text) { (ptr++)->c = *text++; } } void ksetpos(int x, int y) { if((x >= 0) && (x < CONSOLE_WIDTH)) { cursorX = x; } if((y >= 0) && (y < CONSOLE_HEIGHT)) { cursorY = y; } } void kgetpos(int *x, int *y) { if(x != nullptr) *x = cursorX; if(y != nullptr) *y = cursorY; } void ksetcolor(int background, int foreground) { if(background >= 0) { background &= 0xF; color.background = background; } if(foreground >= 0) { foreground &= 0xF; color.foreground = foreground; } } void kgetcolor(int *background, int *foreground) { if(background != nullptr) *background = color.background; if(foreground != nullptr) *foreground = color.foreground; } void kclear(void) { cursorX = 0; cursorY = 0; for(size_t i = 0; i < (CONSOLE_WIDTH * CONSOLE_HEIGHT); i++) { screen[i].c = ' '; // Fill screen with spaces screen[i].color = *((uint8_t*)&color); // Set screen to current color } } static void newline() { cursorX = 0; cursorY += 1; if(cursorY == (CONSOLE_HEIGHT)) { // We need to scroll here: // Copy everything line on the screen to the previous line for(int line = 1; line < CONSOLE_HEIGHT; line++) { memcpy(&screen[CONSOLE_WIDTH * (line-1)], &screen[CONSOLE_WIDTH * line], CONSOLE_WIDTH * sizeof(ConsoleChar)); } // Fill the last line with blanks for(int i = 0; i < CONSOLE_WIDTH; i++) { screen[CONSOLE_WIDTH * (CONSOLE_HEIGHT-1)+i].c = ' '; screen[CONSOLE_WIDTH * (CONSOLE_HEIGHT-1)+i].color = *((uint8_t*)&color); } // Reset y cursor position to previous line (we don't want to write out of bounds) cursorY -= 1; } } void kputc(char c) { switch(state) { case csSetColor: { color = *((ConsoleColor*)&c); state = csDefault; return; } case csSetForeground: { color.foreground = c & 0xF; state = csDefault; return; } case csSetBackground: { color.background = c & 0xF; state = csDefault; return; } case csDefault: default: { int idx = CONSOLE_WIDTH * cursorY + cursorX; switch(c) { case '\x11': state = csSetColor; return; case '\x12': state = csSetForeground; return; case '\x13': state = csSetBackground; return; case '\r': // Ignore carriage return return; case '\n': newline(); return; default: screen[idx].color = *((uint8_t*)&color); // Set screen to current color screen[idx].c = c; cursorX += 1; if(cursorX >= CONSOLE_WIDTH) { newline(); } return; } break; } } } void kputs(const char *str) { while(*str) { kputc(*str); str++; } } void kprintf(const char *format, ...) { static char buffer[1024]; memset(buffer, 0, sizeof(buffer)); va_list vl; va_start(vl, format); vsprintf(buffer, format, vl); va_end(vl); kputs(buffer); }
C
#include "redis-c.h" #include <assert.h> /** * Commands operating on all the kind of values */ int redis_int_bulk_command(struct RedisHandle *h, const int argc, const struct Object argv[] ) { int ret = 0; struct Reply *r; if (redis_send_bulk(h, argc, argv)) return -1; while (ret == 0) { ret = redis_read(h); if (ret < 0) return -1; } r = redis_reply_pop(h); assert(r != NULL); /* r should be a int */ if (r->argc != 1 || r->argv[0].type != REDIS_TYPE_INT) { h->lastErr = "Error reading int reply, the reply does not have exactly one integer response."; redis_reply_free(r); return -1; } ret = (int)r->argv[0].ptr; redis_reply_free(r); return ret; } /** * EXISTS key test if a key exists * @param h * @param key * @param len * @return */ int redis_exists(struct RedisHandle *h, const char *key, size_t len) { const struct Object args[] = { REDIS_STR("EXISTS"), REDIS_RAW(key, len), }; return redis_int_bulk_command(h, sizeof(args) / sizeof(args[0]), args); } /** * DEL key delete a key */ /** * TYPE key return the type of the value stored at key */ /** * KEYS pattern return all the keys matching a given pattern */ /** * RANDOMKEY return a random key from the key space */ /* RENAME oldname newname rename the old key in the new one, destroing the newname key if it already exists RENAMENX oldname newname rename the old key in the new one, if the newname key does not already exist DBSIZE return the number of keys in the current db EXPIRE set a time to live in seconds on a key TTL get the time to live in seconds of a key SELECT index Select the DB having the specified index MOVE key dbindex Move the key from the currently selected DB to the DB having as index dbindex FLUSHDB Remove all the keys of the currently selected DB FLUSHALL Remove all the keys from all the databases */
C
#include <stdint.h> // Include guard for synth.h avoids redefinition of structs. #ifndef SYNTH_H #define SYNTH_H // typedefs to avoid having "struct foo" all around. typedef struct synth_note synth_note; typedef struct synth_part synth_part; typedef struct synth_song synth_song; typedef struct synth_song_playback synth_song_playback; typedef struct synth_part_playback synth_part_playback; // Macro definitions for testing purposes #define A 0 #define Ax 1 #define H 2 #define C 3 #define Cx 4 #define D 5 #define Dx 6 #define E 7 #define F 8 #define Fx 9 #define G 10 #define Gx 11 //----------------------------------------------------------------------------- // This struct defines several bitfields that are useful to pack a note into 16 // bits. This makes it possible to load several long sounds into the efm32gg. //----------------------------------------------------------------------------- struct __attribute__ ((__packed__)) synth_note { // The note pitch. // 0 = A // 1 = A# // 2 = H // 3 = C // 4 = C# // 5 = D // 6 = D# // 7 = E // 8 = F // 9 = F# // 10 = G // 11 = G# // // NOTE: Numbers above 11 are not supported. unsigned int pitch : 4; // The note octave. // // Using pitch and octave, the lowest note possible is A0 at 27.5 Hz, and the // highest is A10 at 28160 Hz. // // NOTE: Numbers above 10 are not supported. unsigned int octave : 4; // The note amplitude. // // The actual amplitude is calculated from this bitfield as 2^(amplitude + 5). unsigned int amplitude : 3; // The note duration. // // Five bits allow for 32 individual durations in an linear arrangement. The // actual duration of a note will depend on what duration unit is set in the // song or the playback structs. unsigned int duration : 5; }; // A part has a list of notes. struct synth_part { synth_note *start; uint32_t n_notes; uint32_t channel; }; // A song has two parts. struct synth_song { synth_part* part0; synth_part* part1; uint32_t default_duration_unit; }; // A "part playback" represents the playback of a single part. struct synth_part_playback { // The song playback using this part synth_song_playback *song_playback; synth_part *part; // The part being played uint32_t remaining_notes; // Remaining notes to play volatile uint32_t *dac_channel; // Output DAC channel synth_note *note; // The current note being played uint32_t remaining_samples; // Remaining samples to be fed to the DAC }; // A "song playback" represents the playback of a single song using two part playbacks. struct synth_song_playback { synth_song *song; // The song being played // The current duration unit and sample rate of the song. uint32_t duration_unit; uint32_t sampling_rate; // The two part playbacks of this song. synth_part_playback *part0_playback; synth_part_playback *part1_playback; }; // Create a note in the memory specified by "*note". void synth_create_note( uint32_t pitch, uint32_t octave, uint32_t amplitude, uint32_t duration, synth_note *note /* output */ ); // Create a part in the memory specified by "*part". void synth_create_part( synth_note *start, uint32_t n_notes, uint32_t channel, synth_part *part /* output */ ); // Create a song in the memory specified by 'song'. void synth_create_song( synth_part *part0, synth_part *part1, uint32_t duration_unit, synth_song *song /* output */ ); // Create a part playback in the memory specified by 'part_playback'. void synth_create_part_playback( synth_part *part, synth_song_playback *song_playback, synth_part_playback *part_playback /* output */ ); // Create a playback in the memory specified by "*playback". void synth_create_song_playback( synth_song *song, synth_part_playback *part0_playback, synth_part_playback *part1_playback, uint32_t sampling_rate, synth_song_playback *song_playback /* output */ ); // Play the next samples of the specified song playback. void synth_next_song_sample(synth_song_playback *song_playback); #endif /* SYNTH_H */
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* helper_swap.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: gmolin <gmolin@student.hive.fi> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/01/14 15:49:28 by gmolin #+# #+# */ /* Updated: 2020/01/21 16:21:35 by gmolin ### ########.fr */ /* */ /* ************************************************************************** */ #include "../includes/ft_printf.h" char *swap_plus_minus(char *joint, char c, int i) { while (joint[i] != '+' && joint[i] != '-' && joint[i]) i++; if (joint[i] == '+' || joint[i] == '-') { c = joint[i]; joint[i] = '0'; joint[0] = c; } return (joint); } char *swap_zero_x_l(char *joint, char c, int i) { while (joint[i] != 'x' && joint[i] != 'X' && joint[i]) i++; if (joint[i] == 'x' || joint[i] == 'X') { c = joint[i]; joint[i] = '0'; joint[1] = c; } return (joint); } char *swap_zero_x_r(char *joint, char c, int i) { while (joint[i] != 'x' && joint[i] != 'X' && joint[i]) i++; if (joint[i] == 'x' || joint[i] == 'X') { c = joint[i]; joint[i] = '0'; i = 0; while (joint[i] == ' ' || joint[i] == '\t' || joint[i] == '\n') i++; joint[i + 1] = c; } return (joint); } char *swap_space(char *joint, char c, int i) { while (joint[i] != ' ' && joint[i]) i++; if (joint[i] == ' ') { c = joint[i]; joint[i] = '0'; joint[0] = c; } return (joint); }
C
/* 'C' CALCULATOR */ /*This file contains all conversion functions */ /******************************************************************** Copyright (C) PRIYANKA D BENDARE priyankabendare@gmail.com * *This programme is free software; you can redistribute it and/or modify it *under the terms of the GNU lesser General Public Liscens as published by *the Free Software Foundation;either version 2.1 of the liscense , or *(at your option) any later version. * *This programme is distributed in the hope that it will be useful' *but WITHOUT ANY WARRANTY ;without even the implied warrenty of *MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *GNU Lesser General Public Liscense for more details. * *You should have reiceaved a copt of the GNU Lesser General Public License *along with this program; if not, write to the Free Software Foundation, *Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. *******************************************************************************/#include<stdio.h> /*This function convertbdecimal to binary*/ void dectobin() { int m, u = 1, v[25], e; printf("Enter the decimal number to convert it into binary\n"); scanf("%d", &e); while(e!=0) { v[u++] = e % 2; e = e / 2; } printf("The binary equivalent of decimal is :-\n"); for(m = u - 1; m > 0; m--) printf("%d", v[m]); printf("\n"); } /*This function convert decimal to hexadecimal*/ void dectohex() { int temp, n, i = 0, j, rem; char hex[20], hex1[20] = " "; printf("Enter the value of decimal to convert it into hexadecimal\n"); scanf("%d", &n); while(n != 0) { rem = n % 16; switch(rem) { case 10: hex[i] = 'A'; break; case 11: hex[i] = 'B'; break; case 12: hex[i] = 'C'; break; case 13: hex[i] = 'D'; break; case 14: hex[i] = 'E'; break; case 15: hex[i] = 'F'; break; default: hex[i] = rem + '0'; break; } i++; n = n / 16; } hex[i] = '\0'; int len = 0; for(i = 0; hex[i] != '\0'; i++) { len++; } for(i = 0, j = len; hex[i] != '\0'; i++,j--) { hex1[j] = hex[i]; } printf("%s", hex1); printf("\n"); } /*This function converts decimal to octal*/ void dectooct() { int num, i = 1, j, oct[50]; printf("Enter the decimal to convert it into octal\n"); scanf("%d", &num); while(num != 0) { oct[i++] = num % 8; num = num / 8; } printf("Octal conversion is:-\n"); for(j = i -1; j > 0; j--) { printf("%d", oct[j]); } printf("\n"); }
C
#include "setting.h" #include "game.h" #include "role.h" void producer(uint8_t turn) { uint8_t turn_counter = 0; while (turn_counter < 4) { // check for special card uint8_t well = 0, aqueduct = 0, library = 0; for (size_t i = 0; i < player_list[turn - 1]->builds; i++) { if (!strcmp(player_list[turn - 1]->board[i]->name, "Well")) well = 1; if (!strcmp(player_list[turn - 1]->board[i]->name, "Library")) library = 1; if (!strcmp(player_list[turn - 1]->board[i]->name, "Aqueduct")) aqueduct = 1; } // at most good uint8_t n = 1; if (turn_counter == 0) n += 1; if (aqueduct) n += 1; if (library) n = 3; printf("\nPlayer %d's turn\n", turn); if ((aqueduct || library || turn_counter == 0) && well) draw(player_list[turn - 1], 1, 1); produce_good(player_list[turn - 1], n); turn_counter++; turn++; if (turn == 5) turn = 1; sleep(1); } } void produce_good(Player *player, int8_t n) { int8_t deck_idx = rand() % 110; int8_t valid_produce = 0; int8_t real_produce = 0; int8_t take_count = 0; int8_t produce_count = 0; // check valid produce for (size_t i = 0; i < player->builds; i++) { if (player->board[i]->is_special_struct || player->board[i]->have_good) continue; valid_produce++; } // check at most produce if (valid_produce > n) real_produce = n; else real_produce = valid_produce; // discard card from deck & recycle while (take_count < real_produce) { if (deck[deck_idx]) take_count++; deck_idx = rand() % 110; } // produce good if (valid_produce <= n || (player->is_bot && level == 1)) // no need to choose scenario or level 1 bot { for (size_t i = 0; i < player->builds && produce_count < real_produce; i++) { if (player->board[i]->is_special_struct || player->board[i]->have_good) continue; player->board[i]->have_good = true; produce_count++; } } else if (player->is_bot && level == 2) // level 2 bot { int8_t card_color = 4; while (1) { for (size_t i = 0; i < player->builds && produce_count < real_produce; i++) { // choose structure with the most profit if (player->board[i]->color == card_color && !player->board[i]->have_good) { produce_count++; player->board[i]->have_good = true; } } if (card_color == 0) break; card_color--; } } else { int8_t idx = 0; int8_t choice = 0; printf("Please choose %d to produce good\n", real_produce); // show board for (size_t i = 0; i < player->builds; i++) { if (player->board[i]->have_good || player->board[i]->is_special_struct) continue; printf("(%ld)|| %s || ", i + 1, player->board[i]->name); } printf("\n"); // choose while (produce_count < real_produce) { printf("Your choice : "); if (scanf("%hhd", &choice) != 1 || choice < 0 || choice > player->builds) { CLEARBUF ERROR continue; } else if (!player->board[choice - 1] || player->board[choice - 1]->is_special_struct || player->board[choice - 1]->have_good) { CLEARBUF ERROR continue; } player->board[choice - 1]->have_good = true; produce_count++; } } printf("\033[1;34mPlayer %d produce %d goods\033[0m\n", player->id, produce_count); }
C
#include <stdio.h> #include <sys/socket.h> #include <stdlib.h> #include <netinet/in.h> #include <unistd.h> #include <sys/types.h> #include <string.h> #define _MAXLINE_ 80 #define _SERV_PORT_ 8000 int main() { struct sockaddr_in server_addr,client_addr; socklen_t cliaddr_len; int sockfd; char buf[_MAXLINE_]; char str[INET_ADDRSTRLEN]; int i, n; sockfd = socket(AF_INET, SOCK_DGRAM, 0); if(sockfd < 0){ printf("create socket error!...\n"); return -1; } bzero(&server_addr,sizeof(server_addr)); server_addr.sin_family = AF_INET; server_addr.sin_addr.s_addr = htonl(INADDR_ANY); server_addr.sin_port = htons(_SERV_PORT_); if(bind(sockfd,(struct sockaddr*)&server_addr,sizeof(server_addr)) < 0){ printf("bind error!..."); close(sockfd); return 1; } printf("Accepting connections ...\n"); while(1){ cliaddr_len = sizeof(client_addr); //n = recvfrom(sockfd, buf, _MAXLINE_, 0,(struct sockaddr *)&client_addr, &cliaddr_len); n = recvfrom(sockfd, buf, _MAXLINE_, 0,(struct sockaddr *)&client_addr, &cliaddr_len); if(n == -1){ printf("recvfrom error...\n"); exit(1); } printf("received from %s at PORT %d\n",inet_ntop(AF_INET, &client_addr.sin_addr, str,sizeof(str)),ntohs(client_addr.sin_port)); for(i = 0; i < n; i++){ buf[i] = toupper(buf[i]); } n = sendto(sockfd, buf, n, 0, (struct sockaddr *)&client_addr, sizeof(client_addr)); if(n == -1){ printf("sendto error...\n"); } } return 0; }
C
#include "query.h" #include "database.h" #include "eqp_core.h" #include "eqp_string.h" void query_init(Query* query) { memset(query, 0, sizeof(Query)); query->state = QUERY_NOT_YET_RUN; } void query_deinit(Query* query) { sqlite3_finalize(query->stmt); // Safe if m_stmt is null query->stmt = NULL; } void query_set_db_and_stmt(Query* query, Database* db, sqlite3_stmt* stmt, uint32_t queryId) { query->stmt = stmt; query->database = db; query->queryId = queryId; query->timestamp = clock_microseconds(); } void query_update_last_insert_id(Query* query) { sqlite3* sqlite = db_get_sqlite(query->database); query->lastInsertId = sqlite3_last_insert_rowid(sqlite); query->affectedRows = sqlite3_changes(sqlite); } int query_execute_background(Query* query) { int rc = sqlite3_step(query->stmt); switch (rc) { case SQLITE_BUSY: return false; case SQLITE_ROW: query_set_state(query, QUERY_HAS_RESULTS); break; case SQLITE_DONE: query_update_last_insert_id(query); break; default: exception_throw_format(B(db_get_core(query->database)), ErrorSql, "[query_execute_background] sqlite error %i: %s", rc, sqlite3_errstr(rc)); break; // Unreachable } // Logging is thread safe log_format(B(db_get_core(query->database)), LogSql, "Executed query %i against database '%s' in %lu microseconds", query->queryId, db_get_path_cstr(query->database), clock_microseconds() - query->timestamp); return true; } void query_execute_synchronus(Query* query) { for (;;) { if (query_execute_background(query)) break; } } void query_execute_synchronus_insert_update(Query* query) { query_execute_synchronus(query); query_reset(query); } void query_reset(Query* query) { sqlite3_reset(query->stmt); } int query_select(Query* query) { sqlite3_stmt* stmt; int rc; // The way we have things set up (to execute queries in the background) means that // when we call this the first time, we will already have the first row of results // queued up; need to special-case it if (query->state == QUERY_HAS_RESULTS) { query->state = SQLITE_OK; return true; } stmt = query->stmt; do { rc = sqlite3_step(stmt); } while (rc == SQLITE_BUSY); // Shouldn't happen now switch (rc) { case SQLITE_ROW: return true; case SQLITE_DONE: sqlite3_reset(stmt); break; default: exception_throw_format(B(db_get_core(query->database)), ErrorSql, "[query_select] %s", sqlite3_errstr(rc)); break; // Unreachable } return false; } void query_bind_int(Query* query, int col, int val) { int rc = sqlite3_bind_int(query->stmt, col, val); if (rc != SQLITE_OK) exception_throw_format(B(db_get_core(query->database)), ErrorSql, "[query_bind_int] %s", sqlite3_errstr(rc)); } void query_bind_int64(Query* query, int col, int64_t val) { int rc = sqlite3_bind_int64(query->stmt, col, val); if (rc != SQLITE_OK) exception_throw_format(B(db_get_core(query->database)), ErrorSql, "[query_bind_int64] %s", sqlite3_errstr(rc)); } void query_bind_double(Query* query, int col, double val) { int rc = sqlite3_bind_double(query->stmt, col, val); if (rc != SQLITE_OK) exception_throw_format(B(db_get_core(query->database)), ErrorSql, "[query_bind_double] %s", sqlite3_errstr(rc)); } static void query_do_bind_string(Query* query, int col, const char* str, int len, void (*type)(void*)) { int rc = sqlite3_bind_text(query->stmt, col, str, len, type); if (rc != SQLITE_OK) exception_throw_format(B(db_get_core(query->database)), ErrorSql, "[query_do_bind_string] %s", sqlite3_errstr(rc)); } void query_bind_string(Query* query, int col, const char* str, int len) { query_do_bind_string(query, col, str, len, SQLITE_TRANSIENT); } void query_bind_string_no_copy(Query* query, int col, const char* str, int len) { query_do_bind_string(query, col, str, len, SQLITE_STATIC); } static void query_do_bind_blob(Query* query, int col, const void* data, uint32_t len, void (*type)(void*)) { int rc = sqlite3_bind_blob(query->stmt, col, data, len, type); if (rc != SQLITE_OK) exception_throw_format(B(db_get_core(query->database)), ErrorSql, "[query_do_bind_blob] %s", sqlite3_errstr(rc)); } void query_bind_blob(Query* query, int col, const void* data, uint32_t len) { query_do_bind_blob(query, col, data, len, SQLITE_TRANSIENT); } void query_bind_blob_no_copy(Query* query, int col, const void* data, uint32_t len) { query_do_bind_blob(query, col, data, len, SQLITE_STATIC); } int query_get_int(Query* query, int col) { return sqlite3_column_int(query->stmt, col - 1); } int64_t query_get_int64(Query* query, int col) { return sqlite3_column_int64(query->stmt, col - 1); } double query_get_double(Query* query, int col) { return sqlite3_column_double(query->stmt, col - 1); } const char* query_get_string(Query* query, int col, uint32_t* len) { sqlite3_stmt* stmt = query->stmt; col--; if (len) *len = sqlite3_column_bytes(stmt, col); return (const char*)sqlite3_column_text(stmt, col); } const byte* query_get_blob(Query* query, int col, uint32_t* len) { sqlite3_stmt* stmt = query->stmt; col--; if (len) *len = sqlite3_column_bytes(stmt, col); return (const byte*)sqlite3_column_blob(stmt, col); } int query_is_null(Query* query, int col) { col--; return (sqlite3_column_type(query->stmt, col) == SQLITE_NULL); }
C
#include <stdio.h> void CriaMat (int M[ ][5]) { int i, j, a, b, c; a = 200; b = 20; while (a < 800) { if (b < 80) for (c=0;c < 8; c = c + 2) { M[i][j] = a+b+c; j++; if (j < 5) i++; j = 0; } else b = b + 200; } if (b > 80) a = a + 200; b = 20; } void MostraMat (int M1[ ][5]) { int i,j; printf ("\n\n ************** Matriz ************* \n\n"); for (i=0; i < 5; i++) { for (j=0; j < 5; j++) printf ("%3d", M1[i][j]); printf ("\n"); } } int main ( ) { int Mat[5][5]; CriaMat (Mat); MostraMat (Mat); }
C
#include <stdio.h> #include <stdlib.h> void Print(int *matrix, int n, int m) { int i,j; for(i=0;i<n;i++){ for(j=0;j<m;j++){ printf("%d ", *(matrix + j + i*m));} printf("\n");} return; } void Identity_Matrix(int *matrix, int n, int m) { int i,j; for(i=0;i<n;i++){ for(j=0;j<m;j++){ *(matrix + j + i*m) = 1;}} return; } void Identity_Diagonal_Matrix(int *matrix, int n, int m) { int i,j; for(i=0;i<n;i++){ for(j=0;j<m;j++){ if (i==j) *(matrix + j + i*m) = 1; else *(matrix + j + i*m) = 0;}} return; } void Plus(int *matrix1, int n, int m, int *matrix2,int *matrix3) { int i,j; for(i=0;i<n;i++){ for(j=0;j<m;j++){ *(matrix3 + j + i*m) = *(matrix1 + j + i*m) +*(matrix2 + j + i*m);}} return; } void Minus(int *matrix1, int n, int m, int *matrix2,int *matrix3) { int i,j; for(i=0;i<n;i++){ for(j=0;j<m;j++){ *(matrix3 + j + i*m) = *(matrix1 + j + i*m) - *(matrix2 + j + i*m);}} return; } void Composition(int *matrix1, int n1, int m1, int *matrix2,int n2, int m2,int *matrix3) { int i,j,k,sum=0; for(i=0;i<n1;i++){ for(j=0;j<m2;j++){ for(k=0;k<m1;k++){ sum=sum+*(matrix1 + k + i*m1)*(*(matrix2 + j + k*m2));} *(matrix3 + j + i*m2)=sum; sum=0;}} return; } void Random_Matrix(int *matrix, int n, int m, int minn, int maxx) { int i,j; for(i=0;i<n;i++){ for(j=0;j<m;j++){ *(matrix + j + i*m) =minn+rand()%maxx;}} return; } void Random_Symetrical_Matrix(int *matrix, int n, int m, int minn, int maxx) { int i,j,num; for(i=0;i<n;i++){ for(j=0;j<m;j++){ num = minn+rand()%maxx; *(matrix + j + i*m) = num; *(matrix + i + j*m) = num;}} return; } int main() { return 0; }
C
// gcc pwrite_benchmark.c -o pwrite_benchmark #define _GNU_SOURCE #include <unistd.h> #include <stdio.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <errno.h> #include <string.h> #include <fcntl.h> #include <stdlib.h> #include <stdint.h> #include <time.h> #include <sys/sendfile.h> //1MB //#define BUFSIZE 524288 //#define BUFSIZE 1048576 //#define BUFSIZE 67108864 #define BUFSIZE 1024 void append(char *s, char c) { int len = strlen(s); s[len] = c; s[len+1] = '\0'; } int main (int argc, char *argv[]) { char *buf = (char *) valloc (sizeof (char) * BUFSIZE + getpagesize ()); int tofd, fromfd, fileread = 1, filewrite = 1; int size; off_t offset = 0; struct stat fstat; stat (argv[2], &fstat); int blksize = (int) fstat.st_blksize; //4M blocksize int align = blksize - 1; long pwrite_start, pwrite_end, pwrite_time = 0; clock_t pwrite_clock_start, pwrite_clock_time; struct timeval timecheck; int msec, clock_time = 0; char alph = 'a'; //char *buf = (char *) malloc((int)blksize+align); //buf = (char *)(((uintptr_t)buf+align)&~((uintptr_t)align)); //char *buf = (char*) malloc((int)BLOCKSIZE+ALIGN); //printf("%d", getpagesize()); //printf("%ld", BUFSIZE); if ((fromfd = open (argv[1], O_RDONLY | O_ASYNC)) == -1) { fprintf (stderr, "OPEN ERROR with FROM FILE: %s\n", strerror (errno)); return 1; } if ((tofd = open (argv[2], O_CREAT | O_RDWR | O_DIRECT | O_ASYNC, 0666)) == -1) { fprintf (stderr, "OPEN ERROR with TO FILE: %s\n", strerror (errno)); return 1; } while (1) { /* if ((tofd = open (append(argv[2], alph++), O_CREAT | O_RDWR | O_DIRECT | O_ASYNC, 0666)) == -1) { fprintf (stderr, "OPEN ERROR with TO FILE: %s\n", strerror (errno)); return 1; } */ printf("offset:%ld\n", offset); fileread = sendfile (tofd, fromfd, &offset, BUFSIZE); if (fileread == -1) { fprintf (stderr, "Failed to read: %s\n", strerror (errno)); free (buf); return 1; } if (fileread == 0) { /*printf ("total pwrite time:%lds%ldms\n", pwrite_time / 1000, pwrite_time % 1000); printf ("total pwrite time_clock:%ds%dms\n", clock_time / 1000, clock_time % 1000);*/ close (fromfd); close (tofd); return 1; } /* gettimeofday (&timecheck, NULL); pwrite_start = (long) timecheck.tv_sec * 1000 + (long) timecheck.tv_usec / 1000; pwrite_clock_start = clock (); filewrite = pwrite (tofd, buf, fileread, offset); gettimeofday (&timecheck, NULL); pwrite_end = (long) timecheck.tv_sec * 1000 + (long) timecheck.tv_usec / 1000; pwrite_time += (pwrite_end - pwrite_start); pwrite_clock_time = clock () - pwrite_clock_start; msec = pwrite_clock_time * 1000 / CLOCKS_PER_SEC; clock_time += msec; if (filewrite == -1) { fprintf (stderr, "Failed to write: %s\n", strerror (errno)); free (buf); return 1; } printf("offset:%ld\n", offset); free (buf); buf = (char *) valloc (sizeof (char) * BUFSIZE + getpagesize ()); */ //buf = (char *) malloc((int)blksize+align); //buf = (char *)(((uintptr_t)buf+align)&~((uintptr_t)align)); //printf("offset:%ld\n", offset); //offset += BUFSIZE; } close (fromfd); close (tofd); return 0; }
C
#ifndef PARSEDEXPR_H #define PARSEDEXPR_H #include "containers/Vector.h" enum class TokenType; enum class Operator; //Sentence does not contain unary minus and unary plus. struct Sentence { Vector<TokenType> symbols; Vector<int> start_pos_in_original_expr; Vector<double> values; Vector<Operator> operators; void pb_alloc_operator (Operator op, int pos_in_expr); void pb_alloc_value (double value, int pos_in_expr); }; #endif // PARSEDEXPR_H
C
// // Created by Administrator on 2016/9/26 0026. // #include "SimpleClient.h" #include<stdio.h> #include<stdlib.h> #include<string.h> #include<errno.h> #include<sys/types.h> #include<sys/socket.h> #include<netinet/in.h> #include <android/log.h> #include<arpa/inet.h> #include<unistd.h> #include "../log/log.h" #include "string-uitls.h" #define MAXLINE 4096 int runFlag = 1; void *startClient(void *arg) { int sockfd, n, rec_len; char recvline[4096], sendline[4096]; char buf[MAXLINE]; struct sockaddr_in servaddr; if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) { LOGD("创建客户端套接字失败"); } LOGD("socket create success"); memset(&servaddr, 0, sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_port = htons(9998); if (inet_pton(AF_INET, "119.29.132.60", &servaddr.sin_addr) <= 0) { LOGD("inet_pton error for %s\n", "127.0.0.1"); return NULL; } if (connect(sockfd, (struct sockaddr *) &servaddr, sizeof(servaddr)) < 0) { LOGD("connect error: %s(errno: %d)\n", strerror(errno), errno); return NULL; } LOGD("socket connect success"); runFlag = 1; while (runFlag) { if (send(sockfd, "I connect server", 17, 0) < 0) { LOGD("发送失败"); runFlag = 0; close(sockfd); return NULL; } LOGD("socket send success"); if((rec_len = recv(sockfd, buf, MAXLINE,0)) == -1) { LOGD("接收失败"); runFlag = 0; close(sockfd); return NULL; } buf[rec_len] = '\0'; LOGD("server->client 收到数据:%s", buf); sleep(10); } close(sockfd); } void *stopClient(void *arg) { runFlag = 0; }
C
#include "hash.h" int insert_num(int num,numbers **hash_table) { numbers *new = malloc(sizeof(numbers)); if (new == NULL) { return FAILURE; } new->num = num; new->link = NULL; if (*hash_table == NULL) { // (*hash_table)->num = new->num; // (*hash_table)->link = NULL; *hash_table = new; return SUCCESS; } else { numbers *temp = *hash_table; while (temp->link) { temp = temp->link; } temp->link = new; } return SUCCESS; } void create_node(numbers **hash_table,int size) { for (int i = 0; i < size; i++) { hash_table[i] = (numbers *)NULL; } }
C
#include <stdio.h> #include <string.h> int main(int argc, char** argv){ if(argc > 3){ int i = 1; FILE* argumentyPlik = fopen("propertis.dat","wb"); if(argumentyPlik!= NULL){ int iloscLiter; int iloscArg = argc -1; fwrite((void*)&iloscArg,sizeof(int),1,argumentyPlik); while(i<argc){ iloscLiter = strlen(argv[i])+1; fwrite((void*)&iloscLiter,sizeof(int),1,argumentyPlik); fwrite((void*)argv[i],sizeof(char),iloscLiter,argumentyPlik); i++; } fclose(argumentyPlik); srand(time(NULL)); int iloscPomiarow = atoi(argv[1]); int iloscKategorii = argc -3; int tmpWynik; if(iloscKategorii > 0){ FILE* plikWyjsciowy =fopen(argv[2],"w"); while(iloscPomiarow){ i = iloscKategorii; while(i){ tmpWynik = (rand() % 200) - 100; fprintf(plikWyjsciowy,"%d",tmpWynik); if(i > 1) fputs(";",plikWyjsciowy); else if(i == 1)fputs("\n",plikWyjsciowy); i--; } iloscPomiarow--; } fclose(plikWyjsciowy); } } } else{ printf("generator <ilosc pomiarow> <nazwaPliku.csv> <kategoria> [<kategoria> ...]\n"); } return 0; }
C
#include "stdio.h" int main(int argc, char const *argv[]) { int a; printf("--Check odd or even--\n"); printf("Enter your input..\n"); scanf("%d",&a); if (a%2==0) printf("a=%d is even\n",a); else printf("a=%d is odd\n",a); return 0; }
C
#include "clik.h" #include "cosmosis/datablock/c_datablock.h" #include <math.h> // Hard-coded maximum number of likelihoods. // This is far more than have been released. // I'm just doing this to avoid some mallocs and stuff. #define MAX_NUMBER_LIKES 128 typedef struct configuration_data{ int ndata, nlensing; clik_object * clik_data[MAX_NUMBER_LIKES]; clik_lensing_object * clik_lensing_data[MAX_NUMBER_LIKES]; } configuration_data; typedef enum {clik_type_standard, clik_type_lensing} clik_type; static int read_requested_files(configuration_data * config, c_datablock * options, clik_type mode){ int status = 0; char param[512]; error * err = initError(); char * prefix; switch (mode) { case clik_type_standard: prefix = "data"; break; case clik_type_lensing: prefix = "lensing"; break; default: fprintf(stderr, "Unknown type of clik file - this is a coding error, please report it.\n"); exit(1); break; } int n=0; while (1){ if (n==127){ fprintf(stderr, "Somehow you have reached the hard-coded maximum number of clik files supported by cosmosis: %d.", MAX_NUMBER_LIKES); fprintf(stderr, "Probably you are just messing about trying to break things. Well done, then.\n"); fprintf(stderr, "If not (somehow) you will need to modify MAX_NUMBER_LIKES in cosmosis-stadard-library/likelihood/planck2014/planck_interface.c\n"); exit(1); } snprintf(param, 128, "%s_%d", prefix, n+1); char * value; status |= c_datablock_get_string_default(options, OPTION_SECTION, param, "", &value); if (strlen(value)==0) break; printf("Looking for clik Planck likelihood file %d: %s\n", n+1, value); switch (mode) { case clik_type_standard: config->clik_data[n] = clik_init(value, &err); break; case clik_type_lensing: config->clik_lensing_data[n] = clik_lensing_init(value, &err); break; default: fprintf(stderr, "Unknown type of clik file - this is a coding error, please report it.\n"); exit(1); break; } n++; if (isError(err)){ fprintf(stderr,"There was an error initializating one of the Planck likelihoods.\n"); fprintf(stderr,"Here is the error message:\n"); printError(stderr,err); fprintf(stderr,"\nIf it mentions \"stat\" then this probably means that a likelihood file was not found.\n\n"); fprintf(stderr,"If you are running demo two or demo four then it just means that you\n"); fprintf(stderr,"did not download the Planck likelihood when installing.\n"); fprintf(stderr,"You can either get it manually from:\n"); fprintf(stderr," http://pla.esac.esa.int/pla/aio/planckProducts.html\n"); fprintf(stderr,"and edit demos/demo2.ini, or just skip demos two and four for now.\n\n"); exit(1); } } endError(&err); return n; } configuration_data * setup(c_datablock * options){ configuration_data * config = malloc(sizeof(configuration_data)); int status = 0; config->ndata=read_requested_files(config, options, clik_type_standard); config->nlensing=read_requested_files(config, options, clik_type_lensing); if (config->ndata==0 + config->nlensing){ fprintf(stderr, "No data files were specified for Planck at all!\n"); fprintf(stderr, "In the options file (not the values.ini file) you need to set in the section for Planck at least the first of:\n"); fprintf(stderr, " data_1 = ...\n"); fprintf(stderr, " data_2 = ...\n"); fprintf(stderr, " data_3 = ...\n"); fprintf(stderr, " data_4 = ...\n"); fprintf(stderr, " etc. and/or\n"); fprintf(stderr, " lensing_1 = ...\n"); fprintf(stderr, " lensing_2 = ...\n"); fprintf(stderr, " etc.\n"); fprintf(stderr, "The Planck data files can be downloaded from:\n"); fprintf(stderr, "http://pla.esac.esa.int/pla/aio/planckProducts.html\n"); fprintf(stderr, "or some are packaged with the planck2015 cosmosis module.\n"); exit(1); } return config; } static int extract_c_ell(c_datablock * block, int n_cl, char * package_names[n_cl], int lmax_by_type[n_cl], int n_nuisance, parname nuisance_names[n_nuisance], double *p, double *cl) { int i; int status=0; for (i=0;i<n_cl;i++) { // Check lmax for this spectrum. If not needed, continue int lmax = lmax_by_type[i]; if (lmax<=0) continue; // Otherwise fill in first the trivial cl and then the rest, loaded fromt the package cl[0]=0.0; cl[1]=0.0; int nread=0; double * ell_squared_cl = NULL; status |= c_datablock_get_double_array_1d(block, CMB_CL_SECTION, package_names[i], &ell_squared_cl, &nread); if (status){ fprintf(stderr, "Could not get C_ell values for %s (status=%d)\n", package_names[i],status); status = 1; return status; } if (nread<lmax-1){ fprintf(stderr, "Could not get enough C_ell values for %s (read lmax=%d but needed lmax=%d). May need to adjust lmax.\n", package_names[i], nread+1, lmax_by_type[i]); status = 1; return status; } // Transform to raw cl from l**2 cl int ell; for (ell=2; ell<=lmax; ell++) { cl[ell] = ell_squared_cl[ell-2] / (ell*(ell+1.0)/2.0/M_PI); } free(ell_squared_cl); // Move the spectrum pointer forward ready for the next spectrum (e.g. TT->EE) cl+=lmax+1; } // ... and now get the nuisance parameters for (i=0; i<n_nuisance; i++){ int this_status=c_datablock_get_double(block, PLANCK_SECTION, nuisance_names[i], cl+i ); //ok // Report any missing parameters if (this_status) fprintf(stderr, "Could not get required Planck parameter %s in section %s\n",nuisance_names[i], PLANCK_SECTION); status |= this_status; } return status; } static int run_clik_cosmosis(c_datablock * block, clik_object * like_obj, double * output_like) { int i; const int N_CL = 6; int param_count=0; int status = 0; char * package_names[] = {"TT","EE","BB","TE","TB","EB"}; int lmax_by_type[N_CL]; // Planck internal error system error * err = initError(); // Get the lmax values for the different spectra and sum them clik_get_lmax(like_obj, lmax_by_type,&err); for (i=0;i<N_CL;i++) if (lmax_by_type[i]>0) param_count += lmax_by_type[i]+1; // Check for any errors from the Planck library if (isError(err)){ fprintf(stderr,"There was an error getting lmax from a Planck likelihood.\n"); endError(&err); return 1; } // Get the number and names of extra parameters and add to total int n_nuisance; parname * nuisance_names; n_nuisance = clik_get_extra_parameter_names(like_obj, &nuisance_names, &err); param_count += n_nuisance; // Check for any errors from the Planck library if (isError(err)){ fprintf(stderr,"There was an error getting nuisance params from a Planck likelihood.\n"); endError(&err); return 2; } // p is the overall space and cl is the space within it for each spectra. double * p = malloc(sizeof(double)*param_count); double * cl = p; // Get the c_ell we need, and the nuisance parameters (if any) status |= extract_c_ell(block, N_CL, package_names, lmax_by_type, n_nuisance, nuisance_names, p,cl); free(nuisance_names); // Check for any errors reading things in if (status){ free(p); return status; } // Compute the actual likelihood double like = clik_compute(like_obj, p, &err); free(p); // ... and check for errors if (isError(err)){ status = 1; fprintf(stderr,"Planck likelihood error\n"); } // Clean up Planck error system and // return required outputs endError(&err); *output_like = like; return 0; } static int run_clik_cosmosis_lensing(c_datablock * block, clik_object * like_obj, double * output_like) { int i; const int N_CL=7; int param_count=0; int status = 0; char * package_names[] = {"PP","TT","EE","BB","TE", "TB", "EB"}; error * err = initError(); int lmax_by_type[N_CL]; // Get the lmax values for the different spectra and sum them clik_lensing_get_lmaxs(like_obj, lmax_by_type,&err); for (i=0;i<N_CL;i++) if (lmax_by_type[i]>0) param_count += lmax_by_type[i]+1; // Check for any errors from the Planck library if (isError(err)){ fprintf(stderr,"There was an error getting lmax from a Planck lensing likelihood:\n"); printError(stderr,err); return 1; } // Get the number and names of extra parameters and add to total int n_nuisance; parname * nuisance_names; n_nuisance = clik_lensing_get_extra_parameter_names(like_obj, &nuisance_names, &err); param_count += n_nuisance; // Check for any errors from the Planck library if (isError(err)){ fprintf(stderr,"There was an error getting nuisance params from a Planck lensing likelihood.\n"); printError(stderr,err); return 2; } // p is the overall space and cl is the space within it for each spectra. double * p = malloc(sizeof(double)*param_count); double * cl = p; // Get the c_ell we need, and the nuisance parameters (if any) status |= extract_c_ell(block, N_CL, package_names, lmax_by_type, n_nuisance, nuisance_names, p,cl); free(nuisance_names); // Check for any errors reading things in and quit early if problem if (status){ free(p); return status; } // Compute the actual likelihood and check for errors double like = clik_lensing_compute(like_obj, p, &err); free(p); //Clean up if (isError(err)){ status = 1; fprintf(stderr, "Error running Planck lensing\n"); } // Clean up Planck error system and // return required outputs endError(&err); *output_like = like; return 0; return 0; } int execute(c_datablock * block, configuration_data * config){ double like = 0.0; int status = 0; for (int i=0; i<config->ndata; i++){ // Compute the likelihood for this file. double like_i = 0.0; status |= run_clik_cosmosis(block, config->clik_data[i], &like_i); // char name[64]; snprintf(name, 64, "PLANCK_LIKE_%d", i+1); status |= c_datablock_put_double(block, LIKELIHOODS_SECTION, name, like_i); like += like_i; } for (int i=0; i<config->nlensing; i++){ // Compute the likelihood for this file. double like_i = 0.0; status = run_clik_cosmosis_lensing(block, config->clik_lensing_data[i], &like_i); // char name[64]; snprintf(name, 64, "PLANCK_LENSING_LIKE_%d", i+1); status |= c_datablock_put_double(block, LIKELIHOODS_SECTION, name, like_i); like += like_i; } if (status) return status; // Save the total likelihood status |= c_datablock_put_double(block, LIKELIHOODS_SECTION, "PLANCK2015_LIKE", like); return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* env_list.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: cmehay <cmehay@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2014/01/17 17:19:07 by sbethoua #+# #+# */ /* Updated: 2014/03/05 00:28:46 by cmehay ### ########.fr */ /* */ /* ************************************************************************** */ #include "42sh.h" #include <stdlib.h> t_env *ms_env_lstadd(t_context *context, char *var) { t_env *elem; t_env *current; if ((elem = (t_env *) cool_malloc(sizeof(t_env))) == NULL) return ((t_env *) ms_function_failed("cool_malloc failed", NULL)); elem->name = ms_var_name_get(var); elem->value = ms_var_value_get(var); if (elem->name == NULL || elem->value == NULL) return (NULL); elem->prev = NULL; elem->next = NULL; if (context->env == NULL) { context->env = elem; return (elem); } current = context->env; while (current->next) current = current->next; elem->prev = current; current->next = elem; return (context->env); } void ms_env_lstdelone(t_env **current) { t_env *next; t_env *prev; if (*current) { next = (*current)->next; prev = (*current)->prev; if ((*current)->prev) (*current)->prev->next = next; if ((*current)->next) (*current)->next->prev = prev; cool_free((*current)->name); cool_free((*current)->value); cool_free(*current); *current = next; } } void ms_env_lstdel(t_env *env) { t_env *current; t_env *next; current = env; while (current) { next = current->next; cool_free(current->name); cool_free(current->value); cool_free(current); current = next; } } t_env *ms_env_copy(t_env *env, t_env *prev) { t_env *copy; if (env) { copy = (t_env*)cool_malloc(sizeof(t_env)); copy->name = cool_strdup(env->name); copy->value = cool_strdup(env->value); copy->prev = prev; copy->next = ms_env_copy(env->next, copy); } else return (NULL); return (copy); } t_env *ms_env_get(t_context *context) { int i; i = 0; while (context->environ[i]) { context->env = ms_env_lstadd(context, context->environ[i]); if (context->env == NULL) return (NULL); i++; } return (context->env); }
C
/* * main.c * Version vom 7.01.19 10:20 * Created on: Nov 13, 2018 * Author: David Dinse */ #include "control.h" int main(int argc, char *argv[]) { uint32_t prime_number, n_threads, i, wurzel, pre_calc; uint32_t mainResult; primeparam_t param; if(argc < 3 || argc > 4) { printf("USAGE: ./%s <MAX NUMBER> <THREAD COUNT>\n", argv[0]); return(-1); } else { prime_number = (uint32_t) strtol(argv[1], NULL, 10); n_threads = (uint32_t) strtol(argv[2], NULL, 10); if(n_threads > 32) { printf("Too many threads. max = 32\n"); return(-1); } } /****************************************/ if(pthread_barrier_init(&barrier, NULL, n_threads+1)) { printf("Could not create thread barrier."); return -1; } wurzel = sqrt(prime_number)+1; primesUntilSquare = calcWithMod(3, wurzel); //get prime number count til sqrt (without 2) printf("Sqrt=%i Primes until Square=%i\n", wurzel, primesUntilSquare); low_primes = (uint32_t*) malloc(32*primesUntilSquare); //create array //store Param structs param = (primeparam_t) malloc(n_threads*sizeof(struct _PARAMS)); mainResult = (prime_number-wurzel) / n_threads; //calculate Numbers per Thread pre_calc = (wurzel-3) / n_threads; param[0].start = wurzel+1; param[0].w_start = 3; param[0].w_sum = 0; for(i = 0; i < n_threads; i++) { if(i) param[i].start = param[i-1].end + 1; //set start if(i) param[i].w_start = param[i-1].w_end + 1; //set sqrt start param[i].end = param[i].start + mainResult; //set end param[i].w_end = param[i].w_start + pre_calc; //set sqrt end if(i == n_threads-1) { param[i].end = prime_number; //set real end for last thread param[i].w_end = wurzel; //set real sqrt end for last thread } //printf("Thread %i Start: %i End: %i\n",i+1,param[i].start,param[i].end); param[i].w_primecount = calcWithMod(param[i].w_start,param[i].w_end); if(i) param[i].w_sum += param[i-1].w_primecount + param[i-1].w_sum; param[i].id = i; //set ID param[i].primecount = 0; pthread_create(&param[i].tid, NULL, (void*)calcThread, (void*)&param[i]); } pthread_barrier_wait(&barrier); printf("Continue...\n"); mainResult = primesUntilSquare + 1; for(i = 0; i < n_threads; i++) { if(pthread_join(param[i].tid, NULL)) { printf("Could not join Thread %i\n", i); return -1; } mainResult += param[i].primecount; } printf("\nThere are %i Primenumbers from 0-%i\n", mainResult, prime_number); free(low_primes); free(param); return 0; } void printLong(uint64_t x) { uint64_t i; for(i = 0x8000000000000000; i; i = i >> 1) { if(i & x) printf("1"); else printf("0"); } printf("\n"); } void printLowPrimes() { int i; for(i = 0; i < primesUntilSquare; i++) printf("%i ",low_primes[i]); printf("\n"); }
C
#include<stdio.h> #include<stdlib.h> #define MAXSIZE 100 struct node { int data; struct node *next; }; typedef struct node NODE; #include"nodequeue.c" NODE *createnewnode(int data) { NODE *newnode; newnode=(NODE *)malloc(sizeof(NODE)); if(newnode==NULL) { printf("memory not allocated\n"); exit(0); } newnode->data=data; newnode->next=NULL; return newnode; } struct graph { int vertices; int edge; NODE **arr; }; typedef struct graph GRAPH; GRAPH *creategraph(int vertices) { GRAPH *graph; graph=(GRAPH *)malloc(sizeof(GRAPH)); if(graph==NULL) { printf("memory not allocated\n"); exit(0); } graph->vertices=vertices; graph->arr=(NODE **)malloc(graph->vertices*sizeof(NODE *)); if(graph->arr==NULL) { printf("memory not allocated\n"); exit(0); } graph->edge=0; return graph; } void edge(GRAPH *graph, int u,int v) { NODE *newnode; newnode=createnewnode(v); if(graph->arr[u]==NULL) { graph->arr[u]=newnode; } else { NODE *temp; temp=graph->arr[u]; while(temp->next!=NULL) { temp=temp->next; } temp->next=newnode; } } void display(GRAPH *graph) { int n; NODE *temp; int count=0; printf("enter the vertex to know its adjacent\n"); scanf("%d",&n); if(graph->arr[n]==NULL) { printf("vertex is isolated\n"); } else { temp=graph->arr[n]; printf("vertices adjacent to it is "); while(temp!=NULL) { count++; printf("%d\t",temp->data); temp=temp->next; } printf("vertices adjacent are %d\n",count); printf("total no of edges is %d\n",graph->edge); } } void breathfirstsearch(GRAPH *graph,int v,int *c,int n) { int i; if(graph->arr[v]==NULL) { printf("vertex is isolated\n"); } else { c[v]=1; NODE *temp; QUEUE *queue; queue=createqueue(); printf("vertices conected to v are\n"); temp=graph->arr[v]; enqueue(temp,queue); while(isempty(queue)==1) { temp=dequeue(queue); while(temp!=NULL) { if(c[temp->data]==0) { printf("%d\t",temp->data); enqueue(graph->arr[temp->data],queue); c[temp->data]=1; } temp=temp->next; } } int flag; flag=0; for(i=0;i<n;i++) { if(c[i]==1) { } else { flag=1; } } if(flag==1) { printf(" it is not conected\n"); } else { printf("it is conected\n"); } } } int main() { int n; GRAPH *graph; int v,u; int i; printf("enter the no of vertices\n"); scanf("%d",&n); graph=creategraph(n); int choice; printf("1)to make edge between verties\n2)to display\n3)to breath first search\n4)to exit the program\n"); int *c; c=(int *)malloc(n*sizeof(int)); if(c==NULL) { printf("memory not allocated\n"); exit(0); } for(i=0;i<n;i++) { c[i]=0; } do{ printf("enter the choice\n"); scanf("%d",&choice); switch(choice) { case 1: printf("enter the vertices in which edge is present\n"); scanf("%d %d",&u,&v); edge(graph,u,v); edge(graph,v,u); graph->edge++; break; case 2: display(graph); break; case 3: printf("enter the vertex\n"); scanf("%d",&v); breathfirstsearch(graph,v,c,n); for(i=0;i<n;i++) { c[i]=0; } break; case 4: break; } }while(choice!=4); return 0; }
C
/* Betriebssystem & Middleware * * Betriebssysteme I WS 2014/2015 * * Uebung 2.5 */ #include <stdio.h> #include <errno.h> #include <stdlib.h> #include <string.h> #include <pthread.h> #include <math.h> #define XSIZE 500 #define YSIZE 500 #include "algorithm.h" struct ThreadData { int startPos; int pixelCount; }; char colorArray[YSIZE][XSIZE][3]; void *threadRoutine (void *dataPointer) { struct ThreadData *td = (struct ThreadData *) dataPointer; int i, x, y; char* c; printf("new thread starting at offset %d, calculating %d values.\n", td->startPos, td->pixelCount); for (i = 0; i < td->pixelCount; ++i) { x = (td->startPos + i) % XSIZE; y = (td->startPos + i) / XSIZE; c = colorArray[y][x]; getColorValuesAt(x * (2.0 / XSIZE) - 1.5, y * (2.0 / YSIZE) - 1.0,&c[2],&c[1],&c[0]); } free(td); td = NULL; } int main(int argc, char *argv[]) { FILE *fd; int len,x,y,i; char *dsc; char bgr[3]; short svalue; int lvalue; unsigned char header[54],*ptr=&header[0]; int threadCount; int calculationsPerThread; pthread_t * threads; if(argc != 3) { perror("usage: bmp_fractal threadCount outputFilename.bmp"); exit(1); } if((threadCount = atoi(argv[1])) < 1) { perror("That is not a valid thread count."); exit(1); } calculationsPerThread = ceil( (float)XSIZE * (float)YSIZE / (float)threadCount); getDescription(NULL,&len); if(NULL==(dsc=(char*)malloc(sizeof(char)*len))) { perror("malloc"); exit(1); } getDescription(dsc,&len); printf("Calculate %s %d\n",dsc,getId()); fd=fopen(argv[2],"wb+"); if(NULL==fd) { perror("open"); exit(1); } svalue=0x4d42; memcpy(ptr,&svalue,2);//signatur ptr+=2; lvalue=XSIZE*YSIZE*3+54; memcpy(ptr,&lvalue,4); //filesize ptr+=4; lvalue=0; memcpy(ptr,&lvalue,4);//reserved ptr+=4; lvalue=54; memcpy(ptr,&lvalue,4);//image offset ptr+=4; lvalue=40; memcpy(ptr,&lvalue,4);//size of header follows ptr+=4; lvalue=XSIZE; memcpy(ptr,&lvalue,4);//with of image ptr+=4; lvalue=YSIZE; memcpy(ptr,&lvalue,4); //height of image ptr+=4; svalue=1; memcpy(ptr,&svalue,2); //number of planes ptr+=2; svalue=24; memcpy(ptr,&svalue,2); //number of pixel ptr+=2; lvalue=0; //compression memcpy(ptr,&lvalue,4); //compression ptr+=4; lvalue=XSIZE*YSIZE*3; memcpy(ptr,&lvalue,4); //size of image ptr+=4; lvalue=0; memcpy(ptr,&lvalue,4); //xres ptr+=4; lvalue=0; memcpy(ptr,&lvalue,4); //yres ptr+=4; lvalue=0; memcpy(ptr,&lvalue,4); //number of colortables ptr+=4; lvalue=0; memcpy(ptr,&lvalue,4); //number of important colors ptr+=4; len=fwrite(header,1,sizeof(header),fd); //write header if(-1==len || len!=sizeof(header)) { perror("write"); exit(2); } // allocate space for the threads threads = (pthread_t*) malloc(threadCount * sizeof(pthread_t)); if(threads == NULL) { perror("malloc for threads failed"); exit(2); } for(i=0; i<threadCount; i++) { // allocate space for the ThreadData structs struct ThreadData* td = (struct ThreadData*) malloc(sizeof(struct ThreadData)); if(td == NULL) { perror("malloc for ThreadData failed"); exit(2); } td->startPos = i * calculationsPerThread; td->pixelCount = calculationsPerThread; if(td->startPos + td->pixelCount > XSIZE * YSIZE) { printf("trimming %d to %d\n", td->pixelCount, ((XSIZE * YSIZE) - td->startPos)); td->pixelCount = (XSIZE * YSIZE) - td->startPos; } pthread_create(&threads[i], NULL, threadRoutine, (void*) td); } printf("waiting for threads...\n"); for(i=0; i<threadCount; i++) { pthread_join(threads[i], NULL); printf("thread %d joined.\n", i); } // free thread memory free(threads); // write precalculated values to the file for(y=YSIZE-1;y>=0;y--) { for(x=0;x<XSIZE;x++) { len=fwrite(&colorArray[y][x], 1, 3, fd); if(-1==len || len!=3) { perror("write"); exit(4); } } /*no padding required because 1500%4 =0*/ } fclose(fd); free(dsc); return 0; }
C
#include <stdio.h> #include <time.h> #include <stdlib.h> int main(){ int a; srand(time(NULL)); a=rand(); printf("random value: %d\n",a); if(a&1){ printf("nono~"); } else{ printf("Yes!"); } return 0; }
C
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <stdbool.h> #include <stdint.h> #include <errno.h> #include <regex.h> #include <unistd.h> #include <pthread.h> #include <sys/stat.h> #include "pipe.h" /* reads in barcodes */ char* substring (const char* in, int from, int size) { /* takes a const char array and returns a char* of size */ if (from+size <= strlen(in)) { char *out = malloc(size+1); sprintf(out, "%.*s", size ,&in[from]); return out; } else { return NULL; } } void gen_random(char *s, const int len) { static const char alphanum[] = "0123456789" "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz"; for (int i = 0; i < len; ++i) { s[i] = alphanum[rand() % (sizeof(alphanum) - 1)]; } s[len] = 0; } int write_year_to_file (int year) { FILE *f = fopen("year.txt", "w"); if (f == NULL) { printf("Error opening file!\n"); return 0; } /* print integers and floats */ fprintf(f, "%d\n", year); fclose(f); return 1; } int write_company_code_to_file (int company_code) { FILE *f = fopen("company_code.txt", "w"); if (f == NULL) { printf("Error opening file!\n"); return 0; } /* print integers and floats */ fprintf(f, "%d\n", company_code); fclose(f); return 1; } int read_year_from_file () { FILE *f = fopen("year.txt", "r"); if (f == NULL) { printf("Error opening file!\n"); return 2020; } int rv = 0; char buf[4 + 1]; size_t nread; if (f) { while ((nread = fread(buf, 1, sizeof buf, f)) > 0) sscanf(buf, "%d", &rv); } fclose(f); return rv; } int read_company_code_from_file () { FILE *f = fopen("company_code.txt", "r"); if (f == NULL) { printf("Error opening file!\n"); return 1000; } int rv = 0; char buf[4 + 1]; size_t nread; if (f) { while ((nread = fread(buf, 1, sizeof buf, f)) > 0) sscanf(buf, "%d", &rv); } fclose(f); return rv; } regex_t compile_regex (char * regex) { regex_t r; int regex_rv; regex_rv = regcomp(&r, regex, REG_EXTENDED); if (regex_rv) { fprintf(stderr, "Could not compile regex_single_number\n"); exit(1); } return r; } bool regex_matches (regex_t r, char * input) { int rv = regexec(&r, input, 0, NULL, 0); if (!rv) { return true; } else if (rv == REG_NOMATCH) { return false; } else { printf("Exiting because regex failed!"); exit(1); } return false; } struct Barcode { char * str; int company_code; int year; long long belnr; char * filename; int format_version; }; void create_barcode ( struct Barcode * bc) { printf("create_barcode() = %s\n", bc->str); #ifdef TEST return; #endif char barcode_cmd[200]; char convert_cmd[300]; if ( bc->format_version == 0 ) { // generate barcode sprintf(barcode_cmd, "barcode -b %s -o %s.ps -e \"i25\" -g \"590x300\";", bc->str, bc->filename); // convert .ps to .png with graphicsmagick sprintf(convert_cmd, "gm convert %s.ps -gravity south -resize 80%% -extent 696x271 -rotate 180 %s.png", bc->filename, bc->filename); } else { // generate barcode sprintf(barcode_cmd, "barcode -b %s -o %s.ps -e \"128b\" -E -g \"696x271\";", bc->str, bc->filename); // convert .ps to .png with graphicsmagick sprintf(convert_cmd, "gm convert %s.ps -gravity south -extent 696x271 -rotate 180 -fill white -draw 'rectangle 41,37,670,44' -fill none -stroke black -strokewidth 2 -draw 'rectangle 406,4,539,40' %s.png", bc->filename, bc->filename); } system(barcode_cmd); system(convert_cmd); } void print_label ( struct Barcode * bc ) { printf("print_label: %s\n", bc->str); #ifdef TEST return; #endif // print with label printer Brother QL-720NW char print_cmd[200]; sprintf(print_cmd, "brother_ql_create --model QL-720NW --label-size 62x29 -c 1 --no-cut %s.png > /dev/usb/lp0", bc->filename); if ( access( "/dev/usb/lp0", W_OK ) != -1 ) { //printf("/dev/usb/lp0 exists!\n"); system(print_cmd); } else { printf("/dev/usb/lp0 doesn't exist!\n"); } } /* 500020190000100999 */ void print_barcode (pipe_producer_t* pipe_creator_prod, int company_code, int year, long long belnr, int format_version) { if (belnr > 9999999999) { return; } char * barcode = malloc(20+1); char * filename = malloc(200); char rand[10+1]; gen_random(rand, 10); if ( format_version == 0 ) { sprintf(barcode, "%i%09lld", year, belnr); } else { sprintf(barcode, "%i%i%010lld", company_code, year, belnr); } sprintf(filename,"%s_%s",barcode, rand); printf("filename: %s\n",filename); struct Barcode bc = {barcode, company_code, year, belnr, filename, format_version}; pipe_push(pipe_creator_prod, &bc, 1); } struct Pipes { pipe_consumer_t *cons_pipe_creator; pipe_producer_t *prod_pipe_printer; }; void * creator_thread_func (void *arg) { printf("creator_thread_func\n"); struct Pipes * pipes = arg; pipe_consumer_t* pipe_creator_cons = pipes->cons_pipe_creator; while (true) { struct Barcode bc; (void) pipe_pop(pipe_creator_cons, &bc, 1); // blocking create_barcode(&bc); pipe_push(pipes->prod_pipe_printer, &bc, 1); } return NULL; } void * printer_thread_func (void *arg) { printf("printer_thread_func\n"); pipe_consumer_t* pipe_printer_cons = arg; while (true) { struct Barcode bc; (void) pipe_pop(pipe_printer_cons, &bc, 1); // blocking print_label(&bc); char sys_call [40]; #ifdef TEST continue; #endif sprintf(sys_call, "rm %s.*", bc.filename); system(sys_call); free(bc.str); free(bc.filename); } return NULL; } int run () { printf("This program allows you to print barcodes.\n"); chdir("barcodes"); // Creating pipes pipe_t* pipe_creator = pipe_new(sizeof(struct Barcode), 0); pipe_producer_t* pipe_creator_prod = pipe_producer_new(pipe_creator); pipe_consumer_t* pipe_creator_cons = pipe_consumer_new(pipe_creator); pipe_free(pipe_creator); pipe_t* pipe_printer = pipe_new(sizeof(struct Barcode), 0); pipe_producer_t* pipe_printer_prod = pipe_producer_new(pipe_printer); pipe_consumer_t* pipe_printer_cons = pipe_consumer_new(pipe_printer); pipe_free(pipe_printer); struct Pipes pipes; pipes.cons_pipe_creator = pipe_creator_cons; pipes.prod_pipe_printer = pipe_printer_prod; pthread_t creator_thread, printer_thread; if ( pthread_create(&creator_thread, NULL, creator_thread_func, &pipes) ) { fprintf(stderr, "Error creating thread\n"); return 1; } if ( pthread_create(&printer_thread, NULL, printer_thread_func, pipe_printer_cons) ) { fprintf(stderr, "Error creating thread\n"); return 1; } int format_version = 1; int company_code = read_company_code_from_file(); int year = read_year_from_file(); long long belnr = 5000; printf("year: %i\n", year); char * x = (char*)malloc(20); // Prepare regex regex_t regex_single_number = compile_regex("^[0-9]{1,10}$"); regex_t regex_range = compile_regex("^[0-9]{1,10}-[0-9]{1,10}$"); regex_t regex_plus = compile_regex("^\\+$"); // e.g. + regex_t regex_year = compile_regex("^\\/2[0-9]{3}$"); // e.g. /2021 regex_t regex_company_code = compile_regex("^\\*[0-9]{4}$"); // e.g. *1000 regex_t regex_format_version = compile_regex("^\\*\\*[0-9]\\*\\*$"); // e.g. **0** regex_t regex_restart = compile_regex("^\\.\\.\\.$"); // ... while (true) { scanf("%s", x); // blocking /* Execute regular expression */ if ( regex_matches(regex_single_number, x) ) { printf("regex_single_number match!\n"); char *end; belnr = strtoll(x, &end, 10); print_barcode(pipe_creator_prod, company_code, year, belnr, format_version); } else if ( regex_matches(regex_range, x) ) { printf("regex_range match!\n"); char * first_num = strtok(x, "-"); char * second_num = strtok(NULL, " "); char *end; long long from = strtoll( first_num, &end, 10); long long to = strtoll( second_num, &end, 10); if ( from > to ) { // flip from and to long long from_tmp = from; from = to; to = from_tmp; } // limit number of barcodes printed to 100 if ( (to - from) > 200 ) { continue; } long long belnr_i = 0; for ( belnr_i = from; belnr_i <= to; belnr_i++ ) { print_barcode(pipe_creator_prod, company_code, year, belnr_i, format_version); } belnr = to; } else if ( regex_matches(regex_year, x) ) { char *end; long in = strtol( substring(x, 1, 4), &end, 10); printf("year set to: %ld \n", in); year = (int) in; write_year_to_file(year); } else if ( regex_matches(regex_plus, x) ) { printf("Inkrement\n"); belnr++; print_barcode(pipe_creator_prod, company_code, year, belnr, format_version); } else if ( regex_matches(regex_company_code, x) ) { printf("Company code\n"); char *end; long cc = strtol( substring(x, 1, 4), &end, 10); printf("company_code set to: %ld \n", cc); company_code = (int) cc; write_company_code_to_file(company_code); } else if ( regex_matches(regex_format_version, x) ) { printf("format_version mode\n"); char *end; long in = strtol( substring(x, 2, 1), &end, 10); printf("format_version set to: %ld \n", in); format_version = (int) in; } else if ( regex_matches(regex_restart, x) ) { printf("restart app\n"); /* kill creator_thread */ void *res; int s; s = pthread_cancel(creator_thread); if (s != 0) { printf("pthread_cancel error: %d\n", s); } s = pthread_join(creator_thread, &res); if (s != 0) { printf("pthread_join error: %d\n", s); } if (res == PTHREAD_CANCELED) { printf("main(): thread was canceled\n"); } else { printf("main(): thread wasn't canceled (shouldn't happen!)\n"); } /* kill printer_thread */ s = pthread_cancel(printer_thread); if (s != 0) { printf("pthread_cancel error: %d\n", s); } s = pthread_join(printer_thread, &res); if (s != 0) { printf("pthread_join error: %d\n", s); } if (res == PTHREAD_CANCELED) { printf("main(): thread was canceled\n"); } else { printf("main(): thread wasn't canceled (shouldn't happen!)\n"); } /* Free memory allocated to the pattern buffer by regcomp() */ regfree(&regex_single_number); regfree(&regex_range); regfree(&regex_plus); regfree(&regex_year); regfree(&regex_company_code); regfree(&regex_format_version); regfree(&regex_restart); /* cleanup generated barcodes */ system("rm *.png"); system("rm *.ps"); // pipe_producer_free(pipe_creator_prod); // pipe_consumer_free(pipe_creator_cons); // pipe_producer_free(pipe_printer_prod); // pipe_consumer_free(pipe_printer_cons); free(x); return 0; } else { printf("---INVALID---\n"); } } return 0; } int main (void) { while( true ) { run(); } }
C
#include <stdio.h> #include <stdlib.h> #include <fcntl.h> #include <unistd.h> #define BUF_SIZE 100 void error_handling(char* message); int main(void){ int f_open = open("copy.txt", O_CREAT | O_WRONLY | O_TRUNC); int f_read = open("data.txt", O_RDONLY); if(f_open == -1){ error_handling("f_open open() error"); } else if(f_read == -1){ error_handling("f_read read() error"); } char buf[BUF_SIZE]; int f_size = -1; while((f_size = read(f_read, buf, sizeof(buf))) != 0){ //for(int i = 0; buf[i] != EOF; i++) write(f_open, buf+i, sizeof(buf[i])); write(f_open, buf, f_size); printf("1"); } } void error_handling(char* message){ fputs(message, stderr); fputc('\n', stderr); exit(1); }
C
#include<stdio.h> #include<math.h> typedef struct{ float r1,r2; }roots; typedef struct{ float real,imag; }complex; float findroots(float a,float b,float c); int main() { roots qd; float a,b,c; printf("enter the coefficients of x^2,x and the constants:"); scanf("%f %f %f",&a,&b,&c); findroots(a,b,c); printf("the roots of the quadratic equation are:%fand%f",qd.r1,qd.r2); return 0; } float findroots(float a,float b,float c) { roots qd; complex num; float d=b*b-4*a*c; if(d==0){ qd.r1=(-b/2*a); qd.r2=(-b/2*a); } else if(d>0){ qd.r1=(-b+sqrt(d))/(2*a); qd.r2=(-b-sqrt(d))/(2*a); } else if(d<0){ float i=sqrt(-1); num.real=(-b/2*a); num.imag=((sqrt(-d))/2*a); qd.r1=(num.real)+i*(num.imag); qd.r2=(num.real)-i*(num.imag); } return qd.r1; return qd.r2; }
C
#pragma once struct Point { short Row; short Coll; Point(); Point(int row, int coll); inline int GetSqrDistance(Point b) { int deltaRow = Row - b.Row; int deltaColl = Coll - b.Coll; return (deltaRow * deltaRow) + (deltaColl * deltaColl); } bool operator==(Point other) { return (Row == other.Row) && (Coll == other.Coll); } };
C
#include "checkPasswordFromFile.h" int checkPasswordFromFile (FILE *file , char inputPassword[], char passCheck[255]) { // fgets (passCheck, 255 , file) ; // printf ("\n%s\n", inputPassword) ; // printf ("%s\n", passCheck) ; // int x = strcmp (inputPassword, passCheck) ; // printf ("%d\n", x) ; while (1) { fscanf (file , "%[^\n]%*c", passCheck) ; if (strcmp (passCheck, inputPassword) == 0) { return 1 ; } else if (feof(file)) { fseek (file,0, SEEK_SET) ; return 0 ; } } }
C
/************************************************************************* > File Name: copy.c > Author: ma6174 > Mail: ma6174@163.com > Created Time: Tue 04 Sep 2018 06:41:21 PM PDT ************************************************************************/ #include "head.h" int main(int argc,char **argv) { int i; int clr; int file_flag; char *buf=null; printf("argc: %d\n",argc); printf("argv[3] is %s\n",argv[3]); // int file_flag=open("argv[1]",O_RDWR|O_CREAT,0777); if(argc!=3) { printf("Error!\n"); return -1; } int file_falg=open(argv[1],O_RDWR|O_CREAT,0777); if(file_flag==-1) { printf("open/creat file failed!"); } close(file_flag); file_flag=open("./test.txt",O_RDWR); int new_flag=open(argv[2],O_RDWR|O_CREAT,0777); if(new_flag==-1) {printf("new file_creat error!"); } //int read_flag= read(file_flag,buf,100); int read_flag=1; while(read_flag!=0) { *buf='0'; read_flag=read(file_flag,buf,1); if(read_flag!=0) write(new_flag,buf,1); } return 0; }
C
#include <stdio.h> #include <stdlib.h> typedef struct Bloco{ int data; struct Bloco* prox; } Bloquinho; typedef struct Node{ Bloquinho* topo; } No; No* aloca_no(){ No* n = (No*) malloc(sizeof(No)); n->topo = NULL; return n; } Bloquinho* aloca_bloquinho(int valor){ Bloquinho* b = (Bloquinho*) malloc(sizeof(Bloquinho)); b->data = valor; b->prox = NULL; return b; } int esta_vazia(No* Node){ return (Node->topo == NULL); } void push(char valor, No* Node){ Bloquinho* b = aloca_bloquinho(valor); b->prox = Node->topo; Node->topo = b; } void pop(No* Node){ if(esta_vazia(Node)){ printf("Ocorreu underflow\n"); } else{ Bloquinho* temp; temp = Node->topo; char aux = temp->data; Node->topo = Node->topo->prox; free(temp); } } int top(No* Node){ return Node->topo->data; } void print(No* Node){ Bloquinho* b = Node->topo; while(b != NULL){ printf("%d\n", b->data); b = b->prox; } } int main(){ No* Node = aloca_no(); push(7, Node); push(9, Node); push(10, Node); print(Node); printf("********\n"); pop(Node); print(Node); }
C
#include <hidef.h> /* common defines and macros */ #include "derivative.h" #include <mc9s12c128.h> #include <stdio.h> #include <termio.h> #include <terminal.h> #include "stdlib.h" char input[20]; unsigned int half_period; unsigned int frequency; unsigned int duration; unsigned int count; unsigned int duration1; unsigned int frequency1; unsigned int durFreq; unsigned int countTemp; unsigned int lowpin=0; void interrupt 7 keyP( ) { CRGFLG = 0x80; switch (lowpin) { case 0: PORTB = 0xE; break; case 1: PORTB = 0xD; break; case 2: PORTB = 0xB; break; default: PORTB = 0x7; break; } lowpin++; lowpin = lowpin % 4; } void interrupt 10 pt3INT( ){ TFLG1 |= 0x04; /*TC2 += half_period; count--; //printf("%d ", count); if (count <= 0){ TCTL2 = 0x00; //printf("COUNT=ZERO\n"); } */ } void main(void) { TERMIO_Init(); printf("REACHED First\n"); /* TERM_ReadString(input, 20); sscanf(input,"%d %d",&frequency, &duration); printf("Frequency %d, Duration %d\n", frequency, duration); half_period = 1000000/frequency; */ printf("REACHED\n"); EnableInterrupts; DDRB = 0x0F; PORTB = 0x0F; TFLG1 = 0x04; TSCR1 = 0x80; TIOS=0x04; TC2+= half_period; PTT=0x04; TCTL2 = 0x10; TIE=0x04; CRGINT |= 0x80; RTICTL = 0x40; while(1) { // printf("REACHED1\n"); if(PORTB == 0xEE) { putchar('1'); } if(PORTB == 0xDE) { putchar('2'); } if(PORTB == 0xBE) { putchar('3'); } if(PORTB == 0x7E) { putchar('A'); } if(PORTB == 0xED) { putchar('4'); } if(PORTB == 0xDD) { putchar('5'); } if(PORTB == 0xBD) { putchar('6'); } if(PORTB == 0x7D) { putchar('B'); } if(PORTB == 0xEB) { putchar('7'); } if(PORTB == 0xDB) { putchar('8'); } if(PORTB == 0xBB) { putchar('9'); } if(PORTB == 0x7B) { putchar('C'); } if(PORTB == 0xE7) { putchar('*'); } if(PORTB == 0xD7) { putchar('0'); } if(PORTB == 0xB7) { putchar('#'); } if(PORTB == 0x77) { putchar('D'); } /* TERM_ReadString(input, 20); sscanf(input,"%d %d",&frequency, &duration); printf("Frequency %d, Duration %d\n", frequency, duration); half_period = 1000000/frequency; duration1 = (duration/100); frequency1 = frequency/10; durFreq = (duration1 * frequency1); countTemp = (durFreq*2); count = countTemp; TCTL2 = 0x10; */ //printf("REACHED\n"); } }
C
// The elevator state machine. #include "elev_state_machine.h" static void drive(int current_floor, int motor_dir); // Defining the different states. typedef enum { S_IDLE, S_MOVING, S_AT_FLOOR, S_STOPBUTTON } ELState; // Initializing variables. static ELState el_state = S_IDLE; static int current_floor; static int motor_dir = DIRN_UP; #define OFF 0 #define ON 1 /* Initializing hardware and elevator. */ void evInitialize(){ // Initialize hardware if (!elev_init()) { printf("Unable to initialize hardware\n"); } //initialize elevator elev_set_motor_direction(motor_dir); while(TRUE){ if(elev_get_floor_sensor_signal() != -1){ elev_set_motor_direction(DIRN_STOP); current_floor = elev_get_floor_sensor_signal(); break; } } el_state = S_IDLE; } /* Event floor reached Check queue for the floor. Stop elevator and start timer if floor is in the queue for the current direction. */ void evFloor_reached(int floor){ elev_set_floor_indicator(floor); current_floor = floor; if (queue_check_floor(current_floor, motor_dir) == TRUE){ // Do if current floor is in the queue of the current direction. elev_set_motor_direction(DIRN_STOP); timer_start(); elev_set_door_open_lamp(ON); elev_turn_off_button_lamp(current_floor); queue_delete_floor(current_floor); el_state = S_AT_FLOOR; } else if (floor == FIRST || floor == FOURTH){ drive(current_floor, motor_dir); //Stops the elevator if the queue is empty when reaching 1st ot 4th floor } } /* Event button is pressed Updates the relevant queue. If the elevator is idle, it will start the motor in the direction the button indicates. */ void evButton_pressed(elev_button_type_t button, int floor){ //Check button type and set the relevant lamp. Ensures only valid buttons are passed as function calls. if(floor != -1 && !(floor == FIRST && button == BUTTON_CALL_DOWN) && !(floor == FOURTH && button == BUTTON_CALL_UP)){ elev_set_button_lamp(button, floor, ON); } //Check button type and set the relevant queue. if (button == BUTTON_CALL_UP && floor != FOURTH){ // Put order in UP queue. queue_set_up_queue(floor); } else if (button == BUTTON_CALL_DOWN && floor != FIRST){ // Put order in DOWN queue. queue_set_down_queue(floor); } else if (button == BUTTON_COMMAND){ // Put order in queue for internal commands. queue_set_queue(floor, current_floor); } //Start elevator in direction of button order if not already moving. switch(el_state){ case S_IDLE: if (floor - current_floor > 0){ queue_set_up_queue(floor); motor_dir = DIRN_UP; elev_set_motor_direction(motor_dir); el_state = S_MOVING; } else if (floor - current_floor < 0){ queue_set_down_queue(floor); motor_dir = DIRN_DOWN; elev_set_motor_direction(motor_dir); el_state = S_MOVING; } else{ timer_start(); elev_set_door_open_lamp(ON); elev_turn_off_button_lamp(current_floor); el_state = S_AT_FLOOR; //Remove floor from queue. queue_delete_floor(current_floor); } break; default: break; } } /* Event time is out When time is out, close door and start elevator if there are any orders. */ void evTime_out(){ elev_set_door_open_lamp(OFF); drive(current_floor, motor_dir); } /* Event for stop button If the button is pressed: Stop motor, light stop button lamp and erase queue. Open door if the elevator is at a floor. If the button is released: Turn off stop button lamp, close the door (regardless) and set the elevator to idle. */ void evStop_button_signal(int stop_signal, int floor_signal){ if (stop_signal == TRUE){ elev_set_motor_direction(DIRN_STOP); elev_set_stop_lamp(ON); queue_delete_queue(); elev_clear_all_button_lamps(); if (floor_signal > -1){ // TRUE if elevator is at a floor. Opens door. elev_set_door_open_lamp(ON); } el_state = S_STOPBUTTON; } else{ elev_set_stop_lamp(OFF); elev_set_door_open_lamp(OFF); el_state = S_IDLE; } } // Function for checking the queues and running the elevator. static void drive(int temp_floor, int temp_dir){ if (queue_get_queue(temp_floor, temp_dir) == TRUE){ // Check if there are any orders in the queue for the current direction. elev_set_motor_direction(motor_dir); el_state = S_MOVING; } else if (queue_get_queue(temp_floor, -temp_dir) == TRUE){ // Check if there are any orders in the opposite queue. motor_dir = -temp_dir; elev_set_motor_direction(motor_dir); el_state = S_MOVING; } else{ el_state = S_IDLE; } }
C
/* * project_utils.c * * Created on: 2020921 * Author: Alain */ #include "project_utils.h" //#include <stdio.h> //#include <string.h> //ָ u32 exponentiation(u32 base, int index){ u32 outnum = base; if (index == 0){ outnum = 1; }else{ for(int i = 0; i<(index-1); i++){ outnum = outnum * base; } } return outnum; } //ַת16֣ 0-f u32 StringToHex(char str[], int len) { u32 result = 0x0; uint8_t i; for (i = 0; i < len; i ++) //ѭжϵǰַֻСдַǴдĸ { if ((str[i] >= '0') && (str[i] <= '9')){ //ǰַΪ0~9ʱ result += (str[i] - '0' +0) * exponentiation(0x10, (len-i-1)); } if ((str[i] >= 'A') && (str[i] <= 'F')){ //ǰַΪдĸA~Zʱ result += (str[i] - 'A' +10) * exponentiation(0x10, (len-i-1)); } if ((str[i] >= 'a') && (str[i] <= 'f')){ //ǰַΪСдĸa~zʱ result += (str[i] - 'a' +10) * exponentiation(0x10, (len-i-1)); } } return result; } // ַͶת16 u32 StringBinToHex(char str[], int len) { u32 result = 0x0; uint8_t i; for (i = 0; i < len; i ++) //ѭжϵǰַֻСдַǴдĸ { if (str[i] == '1'){ //ǰַΪ0~9ʱ result += (str[i] - '0' +0) * exponentiation(0x2, (len-i-1)); } } return result; } //ַ16תʮ int StringHexToInt(char str[], int len){ int result = 0; int i; for (i=0; i<len; i++){ if ((str[i] >= '0') && (str[i] <= '9')){ //ǰַΪ0~9ʱ result += (str[i] - '0' +0) * exponentiation(0xA, (len-i-1)); } } return result; } //ַʮתʮ int StringIntToInt(char str[], int len){ int result = 0; int i; int base = 1; for(i = 0; i<len; i++){ result = result + base * (str[len-i-1] - '0'); base = base * 10; } return result; } //ߵ޷8λβ u8 re_uc_8(u8 a){ // xil_printf("original is : %x \r\n", a); u8 b=0; u8 temp; for(int i=0;i<8;i++){ temp=a&0x01; a=a>>1; b=b+temp; if(i != 7) b=b<<1; } return b; } //ߵ޷16λβ u16 re_uc_16(u16 a){ // xil_printf("original is : %x \r\n", a); u16 b=0; u16 temp; for(int i=0;i<16;i++){ temp=a&0x0001; a=a>>1; b=b+temp; if(i != 15) b=b<<1; } return b; } //ߵ޷32λβ u32 re_uc_32(u32 a){ // xil_printf("original is : %x \r\n", a); u32 b=0; u32 temp; for(int i=0;i<32;i++){ temp=a&0x00000001; a=a>>1; b=b+temp; if(i != 31) b=b<<1; } return b; } //8bitsתַͶ void tobin_8(u8 data_in, char *str){ u8 mask = 0x01; for(int i = 0; i < 8; i++){ str[(7-i)] = (data_in&(mask<<i))? '1' : '0'; } str[8] = '\0'; } //ת16λ޷ΪƱʾַ void tobin_16(u16 data_in, char *str){ u16 mask = 0x0001; for(int i = 0; i < 16; i++){ str[(15-i)] = (data_in&(mask<<i))? '1' : '0'; } str[16] = '\0'; } //ת32λ޷ΪƱʾַ void tobin_32(u32 data_in, char *str){ u32 mask = 0x00000001; for(int i = 0; i < 32; i++){ str[(31-i)] = (data_in&(mask<<i))? '1' : '0'; } str[32] = '\0'; } //ȡʼֹλַ֮ char* substring(char* str, int start, int end){ int i = 0; char* sub = NULL; char buff[256]; if(start < 0 || start >= end || strlen(str) < end){ return str; } for (i = start; i <= end; i++){ buff[i - start] = str[i]; } buff[end-start+1] = '\0'; sub = buff; return sub; } // ǷDzοֵλǣڲοƵĴ int check_value_shift_12b(u32 value, u32 value_ref){//ж12bitsvalue Ƿvalue_refѭλ int return_val = -1; u32 temp_val = value_ref & 0xFFF; int msb = 0; for(int i = 0; i < 12; i ++){ if(value == temp_val){ return_val = i; break; } msb = (temp_val >> 11) & 0x00000001; temp_val = temp_val << 1; temp_val = temp_val | (msb & 0x00000001); temp_val = temp_val & 0xFFF; } return return_val; }
C
/************************************************************************* > File Name: 3.c > Author: GWG > Mail: gaowenguang123@gmail.com > Created Time: 2014年11月24日 星期一 01时22分15秒 ************************************************************************/ #include<stdio.h> void len() { printf("%p\n", &x); } int main(void) { int x = 0; return 0; }
C
#ifndef OBJECTS_BOOL_H #define OBJECTS_BOOL_H #include <assert.h> #include <stdbool.h> #include "../object.h" #include "../type.h" extern const struct Type boolobj_type; typedef struct BoolObject { OBJECT_HEAD } BoolObject; extern BoolObject boolobj_true, boolobj_false; // yes, non-static inline functions are defined in header files in c // never fails, always returns a new reference inline BoolObject *boolobj_c2asda(bool cbool) { BoolObject *res = cbool ? &boolobj_true : &boolobj_false; OBJECT_INCREF(res); return res; } inline bool boolobj_asda2c(BoolObject *asdabool) { assert(asdabool == &boolobj_true || asdabool == &boolobj_false); return (asdabool == &boolobj_true); } #endif // OBJECTS_BOOL_H
C
#include <stdio.h> #include <stdlib.h> #include <errno.h> #include <pthread.h> #include <sys/types.h> #include <sys/shm.h> #include <sys/ipc.h> #include <sys/sem.h> #define NUM_ZONAS 8 /*Id para los recursos que serán compartidos entre diferentes procesos del sistema*/ int semid; //Id para el conjunto de semaforos int shmid; //Id para el bloque de memoria //Estructura que se guardará en la memoria compartida typedef struct{ int flag; //Campo que indica si la struct almacena un msj o llamada en ese instante char compania; //Caracter que indica la compañia emisora, el caracter será la primera letra del nombre char operacion[50]; //Contiene un telefono o un mensaje dependiendo del valor de flag char usuario[20]; //Nombre del usuario }Zona; //Apuntador con el que se accede a la zona de memoria compartida Zona *Memoria; //Union utilizada para borrar el semaforo union semun{ int val; /* value for SETVAL */ struct semid_ds *buf; /* buffer for IPC_STAT & IPC_SET */ ushort *array; /* array for GETALL & SETALL */ struct seminfo *__buf; /* buffer for IPC_INFO */ void *__pad; }; void *productor(void *); void waitS(int); void signalS(int); struct sembuf operacion; int numero_repeticiones=1, tecel = 0, movistar = 0, iusacell = 0; int main(int argc, char **argv){ key_t key; pthread_t productores[3]; /*Creacion e inicializacion de los recursos IPC*/ //Llave de acceso, se usará la misma tanto para semaforos como para sh_memory if((key = ftok("/bin/ls","A"))==-1){ printf("error key\n"); } //Creacion e inicializacion de los semaforos int num_semaphores = ((NUM_ZONAS*2)+2); if((semid = semget(key,num_semaphores,0666|IPC_CREAT|IPC_EXCL))==-1){ //El semaforo ya fue creado e inicializado, solo nos conectamos a este. if((semid = semget(key,num_semaphores,0666))==-1){ printf("error\n"); }else{ //Conexión con éxito a un semaforo existente printf("Productor ligando a un semaforo ya creado\n"); } }else{ //Inicialización //Semaforos externos semctl(semid,0,SETVAL,NUM_ZONAS); //semaforo externo productores semctl(semid,num_semaphores,SETVAL,0); //semaforo externo consumidores //Semáforos internos //productores - inician abiertos para que se pueda escribir for(int i=1;i <= NUM_ZONAS;i++){ semctl(semid,i,SETVAL,1); } //consumidores - inician cerrados esperando que se escriba for(int j = NUM_ZONAS+1; j <= NUM_ZONAS*2;j++){ semctl(semid,j,SETVAL,0); } printf("Productor cree e inicializo al semaforo\n"); /* Los productores no pueden eliminar los semaforos, esta tarea es delegada a los consumidores para evitar fallas. Las únicas opreaciones faltantes para semaforos se realizarán dentro de los threads que escriben en la memoria conpartida. */ } /*Creación de la memoria compartida*/ shmid = CreaLigaMemoria(key); //Creacion y llamada a los threads for(int k=0;k<3;k++){ //Productores pthread_create(&productores[k],NULL,productor,(void*)k); } //Esperando solo a los productores para hacer un deattached de la memoria compartida for(int m=0;m<3;m++){ pthread_join(productores[m],NULL); } /*Los productores no destruyen la memoria compartida pues no saben si los consumidores terminaron de leer, de esta forma despues de realizar todas la escrituras los productores solo de desconectan*/ shmdt (Memoria); } void *productor(void* args) { //viendo que thread productor soy int thread_id = (int)args; int semValue; char companiaId; //imprimiendo caracter n veces for(int n = 0; n < numero_repeticiones; n++){ if(thread_id == 0){ companiaId = 'T'; //TELCEL }else if(thread_id == 1){ companiaId = 'M'; //MOVISTAR }else{ companiaId = 'I'; //IUSACELL } /*sleeping process waitS(0); // 0 - Semaforo externo productor //Si ya entre es por que hay alguna zona abierta //Recorro las zonas hasta encontrar la que esta abierta for(int i=1; i <= NUM_ZONAS; i++){ //Obtener valor del semaforo en la posicion i semValue = semctl(semid, i, GETVAL, NULL); //Evaluamos para ver si el semaforo de la zona critica esta abierto if(semValue > 0){ //Semaforo abierto waitS(i); //Cerramos el semaforo que nos corresponde //Llenamos la zona critica con el valor del struct correspondiente al thread actual Memoria[i-1] = caracter; signalS(NUM_ZONAS+i);//Avisamos al semaforo del consumidor que estará en i+NUM_ZONAS que ya puede leer break; //Terminamos el ciclo pues ya encontramos un semaforo abierto } } signalS((NUM_ZONAS*2)+1); //Semaforo externo consumidor*/ } pthread_exit(0); } /*Función para la creación o attachment a una zona de memoria compartida*/ int CreaLigaMemoria(key_t key){ //Verifica si el segmento de memoria existe (IPC_CREAT|IPC_EXCL) if((shmid = shmget(key, sizeof(Zona) * NUM_ZONAS, IPC_CREAT|IPC_EXCL|0666)) == -1){ /* El segmento existe - abrir como cliente */ if((shmid = shmget(key, sizeof(Zona) * NUM_ZONAS , 0)) == -1){ perror("shmget"); exit(1); } else{ printf("\nProductor se ligo a una memoria ya existente\n"); } } else{ printf("\nProductor creo la memoria\n"); } //se attachment a la zona de memoria creada if((Memoria = (Zona*)shmat(shmid,(Zona*) 0,0)) == (void *)-1) { perror("shmat"); exit(1); } return shmid; //regresa el identificador de la memoria } void waitS(int posicion){ //printf("wait: %d \n", posicion); operacion.sem_num = posicion; operacion.sem_op = -1; operacion.sem_flg = SEM_UNDO; if(semop(semid,&operacion,1) == -1){ printf("error wait\n"); } } void signalS(int posicion){ //printf("signal: %d \n", posicion); operacion.sem_num = posicion; operacion.sem_op = 1; operacion.sem_flg = SEM_UNDO; if(semop(semid,&operacion,1)==-1){ printf("error signal\n"); } }
C
//AǷܱB֪Ϊʲôxhdо⣬ɡ #include <stdio.h> int main (void) { int n; int x,y; scanf("%d",&n); while(n){ n--; scanf("%d %d",&x,&y); if( x % y ) printf("NO"); else printf("YES"); } return 0; }
C
/* ============================================================================ Name : MDJ.c Author : Version : Copyright : Your copyright notice Description : Hello World in C, Ansi-style ============================================================================ */ #include <shared.h> #include "MDJ.h" int main() { logger = configurar_logger("MDJ.log","MDJ"); get_config(); int socket = definirSocket(logger); pthread_t consola; pthread_create(&consola, NULL, *abrirConsola, NULL); bindearSocketYEscuchar(socket, MDJ_CONF.IP, MDJ_CONF.PUERTO, logger); DAM_handler(socket); pthread_join(consola,NULL); exit_gracefully(0); } void *abrirConsola(){ char *linea; while(1){ linea = readline(">"); if(linea) add_history(linea); char **comando = string_split(linea, " "); char *directory = comando[1]; t_tipoComando c = convert(comando[0]); switch(c) { case cd: printf("Estas cambiando al directorio: %s\n",directory); chdir(directory); char cwd[PATH_MAX]; if (getcwd(cwd, sizeof(cwd)) != NULL){ printf("Current working dir: %s\n", cwd); } else { perror("getcwd() error"); } break; case ls: system(comando[0]); break; case cat: printf("ingresaste el comando %s\n", comando[0]); break; case md5: printf("ingresaste el comando %s\n", comando[0]); break; default: exit(EXIT_FAILURE); break; } free(linea); free(comando); } return 0; } void get_config(){ t_config *config = cargarConfiguracion("../MDJ.conf", logger); if(config_has_property(config,"IP")) { MDJ_CONF.IP= config_get_string_value(config, "IP"); remove_quotes(MDJ_CONF.IP); } if(config_has_property(config,"PUERTO")) { MDJ_CONF.PUERTO= config_get_int_value(config, "PUERTO"); } } t_tipoComando convert(char* str) { if(!strncmp(str,"ls",2)) return ls; else if(!strncmp(str,"cd",2)) return cd; else if(!strncmp(str,"cat",3))return cat; else if(!strncmp(str,"md5",3)) return md5; else return -1; } void exit_gracefully(int return_nr){ log_destroy(logger); config_destroy(config); close(clientSocket); loggear(logger, LOG_LEVEL_INFO, "Fin proceso MDJ."); exit(return_nr); } void DAM_handler(int socket){ clientSocket = aceptarConexiones(socket, logger); t_mensaje* msg = recibirMensaje(clientSocket, logger); loggear(logger,LOG_LEVEL_INFO, "Proceso: %d", msg->header.tipoProceso); loggear(logger,LOG_LEVEL_INFO,"Procesar mensaje: %d", msg->header.tipoMensaje); switch(msg->header.tipoProceso){ case diego: loggear(logger,LOG_LEVEL_INFO, "Proceso DAM Conectado"); enviarMensaje(mdj, handshake, 0, NULL, clientSocket, logger); break; default: exit_with_error(clientSocket, "El cliente conectado no es DAM", NULL); break; } destruirMensaje(msg); } void exit_with_error(int socket, char *error, void *buffer){ if(buffer!= NULL){ free(buffer); } log_error(logger, error); close(socket); exit_gracefully(1); }
C
#include <stdio.h> #include <stdlib.h> #define MAXN (5) int x,y,z; int xs[MAXN], ys[MAXN]; #define MAXH (2451671) #define MAXL (10) typedef struct _thash_{ char xs[MAXN],ys[MAXN]; double val; }thash; thash htab[MAXH]; void inithash(){ int i; for (i = 0; i < MAXH; i++) htab[i].val = -1.0; } int hash(){ int i; int sum = 1; for (i = 0; i < x; i++) sum = (13 * sum + xs[i]) % MAXH; for (i = 0; i < y; i++) sum = (13 * sum + ys[i]) % MAXH; return sum; } int equal(int hs){ int i; int ident = 1; for (i = 0; i < x && ident; i++) ident = htab[hs].xs[i] == xs[i]; for (i = 0; i < y && ident; i++) ident = htab[hs].ys[i] == ys[i]; return ident; } double fetch(){ int hs = hash(); int cur = MAXL; while (htab[hs].val>-1.0 && !equal(hs) && cur) { hs++; if (hs == MAXH) hs = 0; cur--;} if (htab[hs].val>-1.0 && equal(hs)) return htab[hs].val; else return -1.0; } void insert(double val){ int hs = hash(); int cur = MAXL; while (htab[hs].val != -1.0 && cur) { hs++; if (hs == MAXH) hs = 0; cur--;} if (htab[hs].val == -1.0) { int i; for (i = 0; i < x; i++) htab[hs].xs[i] = xs[i]; for (i = 0; i < y; i++) htab[hs].ys[i] = ys[i]; htab[hs].val = val; } } double explode(int cur, int sy){ int i; int nx = 0, ny = 0; double pr = fetch(); if (pr >= 0.0) return pr; pr = 0.0; for (i = 0; i < x; i++) nx += (xs[i] != 0); for (i = 0; i < y; i++) ny += (ys[i] != 0); if (!cur) return ny ? 0.0 : 1.0; if (!ny) return 1.0; if (sy > cur) return 0.0; for (i = 0; i < x; i++) if (xs[i] && (!i || xs[i-1] < xs[i])) { int j = i + 1; while (j < x && xs[j] == xs[i]) j++; xs[i]--; pr += (j - i) * explode(cur - 1, sy) / (nx + ny); xs[i]++; } for (i = 0; i < y; i++) if (ys[i] && (!i || ys[i-1] < ys[i])) { int j = i + 1; while (j < y && ys[j] == ys[i]) j++; ys[i]--; pr += (j - i) * explode(cur - 1, sy - 1) / (nx + ny); ys[i]++; } insert(pr); return pr; } int cmp(const void* a, const void* b){ return *((int*)a)-*((int*)b); } int main(){ int i, sy = 0; inithash(); scanf("%d %d %d",&x,&y,&z); for (i = 0; i < x; i++) scanf("%d",&xs[i]); qsort(xs, x, sizeof(int), cmp); for (i = 0; i < y; i++) { scanf("%d",&ys[i]); sy += ys[i];} qsort(ys, y, sizeof(int), cmp); printf("%1.8lf\n", explode(z, sy)); return 0; }
C
#include <stdio.h> #include <assert.h> #include <stdlib.h> enum list_error { NO_ERROR = 0, ///< The case of normal situation ALLOC_ERROR = 1, ///< The case of Allocation failure NULL_POINTER_ERROR = 2, ///< The case of NULL pointer COUNT_ERROR, WRONG_POINTER_ERROR, REMOVE_NUM_ERROR, F_OPEN_ERROR }; int LIST_ERROR = NO_ERROR; enum poison { COUNT_POISON = -1, POINTER_POISON = 0, VALUE_POISON = 666, }; int FIND_NUM_COUNT = 0; const int MAX_FIND_NUM_COUNT = 5; typedef char * list_val; typedef struct list_elem { list_val value; struct list_elem *next; struct list_elem *prev; } list_elem; typedef struct list_t { //list_elem **data; list_elem *head; list_elem *tail; int count; } list_t; int list_ctor (list_t *s); list_elem * list_elem_ctor (); int list_dtor (list_t *s); int list_elem_dtor (list_elem *s); int list_clean (list_t *s); list_elem * list_add_front (list_t *s, list_val value); list_elem * list_add_back (list_t *s, list_val value); list_val list_remove_front (list_t *s); list_val list_remove_back (list_t *s); list_elem * list_find_num (list_t *s, int num); list_elem * list_find_val (list_t *s, list_val val); list_val list_remove (list_t *s, list_elem * cur_elem); list_elem * list_add_after (list_t *s, list_elem *cur_elem, list_val val); list_elem * list_add_before (list_t *s, list_elem *cur_elem, list_val value); int is_list_elem_ok (list_elem *s_elem); void list_elem_dump (list_elem *s_elem); void list_print (list_t *s); int is_list_ok (list_t *s); int list_dot_print (list_t *s);
C
/* ** EPITECH PROJECT, 2019 ** CPE_corewar_2019 ** File description: ** my.h */ #ifndef CPE_COREWAR_2019_MY_H #define CPE_COREWAR_2019_MY_H #include <stddef.h> #include <stdbool.h> int my_atoi(char const *str); void *my_cmalloc(size_t size); int my_memcpy(void *src, void *dest, size_t size); void my_memset(void *ptr, size_t size, char set); int my_put_signed_long_base(long long nb, char const *base); int my_putchar(char c); int my_putstr(const char *str); void *my_sfree(void *ptr); int my_strcmp(char const *s1, char const *s2); char *my_strdup(char const *src); int my_strlen(const char *str); int my_strlen_until(const char *str, char c); int my_strncpy(char **dest, char const *src, int n); char *my_strndup(char const *src, int n); int my_swap_int_endian(int *value); void my_free_array(void **array, const int size); #endif //CPE_COREWAR_2019_MY_H
C
// // Created by Pavel on 07/11/2018. // #include <zconf.h> #include <fcntl.h> #include <stdio.h> #include <stdlib.h> int main(){ char* buffer = malloc(sizeof(char)*20); FILE *file = fopen("/Users/Pavel/programs/OSs/git/week12/ex1.txt", "w"); int fd = open("/dev/random", O_RDONLY); read(fd, buffer, sizeof(char)*20); fprintf(file, "%s", buffer); close(fd); fclose(file); return 0; }
C
#include "stdio.h" int a[1000],b[1000],c[1000],d[1000]; char s[1000]; int an,bn,cn,dn,i; int toBignum(int a[], char s[]){ int i,j; for(i = 0; s[i]; i++); for(i--,j=0; i>=0; i--,j++){ a[j] = s[i]-'0'; } return j; } void printN(int a[], int an){ int i; for(i = an-1; i>=0; i--){ putchar(a[i]+'0'); } putchar('\n'); } int muti(int a[], int an, int b[], int bn, int d[]){ int i,j,k,dn; for(i = 0; i < an+bn+20; i++) d[i] = 0; for(i=0; i<an; i++){ for(j=0; j<bn; j++){ d[i+j] += a[i]*b[j]; } } dn = an+bn-1; for(i=k=0; i<dn||k>0; i++){ //printf("%d ",d[i]); d[i] += k; k = d[i]/10; d[i] %= 10; if(i==dn) dn++; //printf("D[%d] = %d %d\n",i,d[i],k); } return dn; } int main(){ scanf(" %s", s); an = toBignum(a,s); scanf(" %s", s); bn = toBignum(b,s); scanf(" %s", s); cn = toBignum(c,s); dn = muti(a,an,b,bn,d); /*printN(a,an); printN(b,bn); printN(d,dn);*/ if(cn!=dn){ printf("dream\n"); }else{ for(i = 0; i < cn; i++){ if(c[i]!=d[i]) break; } if(i==cn){ printf("truth\n"); }else{ printf("dream\n"); } } }
C
/*--------------------------------------------------------- light_pd.c ---------------------------------------------------------*/ #include "light_pd.h" #include "light.h" #include "system.h" #include "keybrd.h" #define LIGHT_PORT GPIOA #define LIGHT_PIN GPIO_PIN_2 #define LIGHT_MASK GPIO_MASK_PIN_2 #define LIGHT_OUT GPIO_OUT_PIN_2 static NOINIT WORD LightContrastValueOn; static NOINIT WORD LightContrastValueOff; NOINIT BOOL LightState; //--------------------------------------------------------- void InitLight_pd(void) { WORD period = htim2.Instance->ARR; LightContrastValueOn = (WORD)(period*0.5f); LightContrastValueOff = (WORD)(period*0.05f); LightState = TRUE; } //--------------------------------------------------------- void SetupLight_pd(void) { HAL_TIM_OC_Start(&htim2, TIM_CHANNEL_2); } //--------------------------------------------------------- void DoLight_pd(void) { /* if(KeyDown == KB_F2) { if(LightState == TRUE) { LightState = FALSE; HAL_TIM_OC_Stop(&htim2, TIM_CHANNEL_2); } else { LightState = TRUE; HAL_TIM_OC_Start(&htim2, TIM_CHANNEL_2); } }*/ } //--------------------------------------------------------- void LightOn_pd(void) { htim2.Instance->CCR2 = LightContrastValueOn; } //--------------------------------------------------------- void LightOff_pd(void) { htim2.Instance->CCR2 = LightContrastValueOff; } //--------------------------------------------------------- void LightSetContrast_pd(BYTE contrast) { WORD period = htim2.Instance->ARR; FLOAT32 value = contrast/100.0f*period; LightContrastValueOn = value >= period ? period - 2U : (WORD)value; LightOn_pd(); }
C
#include <stdio.h> int at[10], bt[10], ct[10], tat[10], wt[10], id[10]; int processes; void sort () { for (int i = 0; i < processes - 1; i++) { for (int j = 0; j < processes- (i+1); j++) { if (at[j] > at[j+1]) { int temp = at[j]; at[j] = at[j+1]; at[j+1] = temp; temp = bt[j]; bt[j] = bt[j+1]; bt[j+1] = temp; } } } } void main() { printf ("enter number of processes :\t"); scanf ("%d",&processes); for (int i = 0; i < processes; i++) { printf ("\n\nprocess details :%d\n", i); printf ("enter the arrival time of process :%d\t", i); scanf ("%d", &at[i]); printf ("enter the bust time of process :%d\t", i); scanf ("%d", &bt[i]); } sort(); for (int i = 0; i < processes; i++) { if (i == 0) { ct[i] = bt[i]; tat[i] = ct[i] - at[i]; wt[i] = tat[i] - bt[i]; } else { ct[i] = ct[i-1] + bt[i]; tat[i] = ct[i] - at[i]; wt[i] = tat[i] - bt[i]; } } printf ("at\tbt\tct\ttat\twt\n"); for (int i = 0; i < processes; i++) printf ("%d\t%d\t%d\t%d\t%d\n", at[i], bt[i], ct[i], tat[i], wt[i]); }
C
#include "stdio.h" int main() { int n,i,c=0; scanf("%d",&n); int a[n],b[n]; for (i = 0;i < n;i++) { scanf("%d",&a[i]); } for (i = 0;i < n;i++) { scanf("%d",&b[i]); } for (i = 0;i < n;i++) { if(b[i]>=a[i]) { c++; } } printf("%d",c); return 0; }
C
#include<stdio.h> void print_arr(int arr[]); void print_reverse(int arr[], int n); int main() { int arr[] = { 10,20,30,40,50 }; print_arr(arr); printf("\n\n"); print_reverse(arr, 5); } void print_arr(int arr[]) { for (int i = 0; i < 5; i++) { printf("%d ", arr[i]); } } void print_reverse(int arr[], int n) { int* p = &arr[0] + 5 - 1; //int* p = &arr[0] + 5 - 1 = int* p = arr + 5 - 1 //********迭 ̸ 迭 ù° ּҸ Ÿ!!!!!!****** while (p >= arr) { printf("%d ", *p--); } }
C
#include <stdlib.h> #include "definitions.h" #include "helpers.h" #include "operators.h" #include <stdio.h> //Call one_point_crossover function solution* crossover_solutions(solution sol1, solution sol2, BEPinstance instance){ //Add random and one_point_cross when finished return one_point_crossover(sol1, sol2, instance); } //Select a cutting point for every bus, and mix the solution's routes, setting evacuees to 0 //after mixing all the buses, set the right amount of evacuees, satisfying shelter and bus capacity //constraints. solution* one_point_crossover(solution sol1, solution sol2, BEPinstance instance){ solution *sols; int max_cutpoint; int cut; int *cuts; int bus; int i; int evac; //Creating new solutions and cut point array sols = (solution*) malloc(sizeof(solution)*2); cuts = (int*) malloc(sizeof(int)*instance.buses); sols[0].bus_list = (bus_tour*) malloc(sizeof(bus_tour)*instance.buses); sols[0].people_remaining = (int*) malloc(sizeof(int)*instance.points); sols[0].capacity_remaining = (int*) malloc(sizeof(int)*instance.shelters); sols[1].bus_list = (bus_tour*) malloc(sizeof(bus_tour)*instance.buses); sols[1].people_remaining = (int*) malloc(sizeof(int)*instance.points); sols[1].capacity_remaining = (int*) malloc(sizeof(int)*instance.shelters); //Making a copy of parent solutions deep_copy_solution(&(sol1), &(sols[0]),instance); deep_copy_solution(&(sol2), &(sols[1]),instance); for(bus = 0; bus < instance.buses; bus++){ //Getting the smallest route_length if(sol1.bus_list[bus].route_length < sol2.bus_list[bus].route_length){ max_cutpoint = sol1.bus_list[bus].route_length; } else{ max_cutpoint = sol2.bus_list[bus].route_length; } //Generating cutting point and saving to the array cut = randint(max_cutpoint); cuts[bus] = cut; for(i = cut; i < MAX_TOURS; i++){ //Restoring Evacuees for new solution 1 sols[0].people_remaining[sol1.bus_list[bus].route[i].point] += sol1.bus_list[bus].route[i].evac; sols[0].capacity_remaining[sol1.bus_list[bus].route[i].shelter] += sol1.bus_list[bus].route[i].evac; //Swapping tours for new solution 2 sols[1].bus_list[bus].route[i].point = sol1.bus_list[bus].route[i].point; sols[1].bus_list[bus].route[i].shelter = sol1.bus_list[bus].route[i].shelter; sols[1].bus_list[bus].route[i].evac = 0; //Restoring Evacuees for new solution 2 sols[1].people_remaining[sol2.bus_list[bus].route[i].point] += sol2.bus_list[bus].route[i].evac; sols[1].capacity_remaining[sol2.bus_list[bus].route[i].shelter] += sol2.bus_list[bus].route[i].evac; //Swapping tours for new solution 1 sols[0].bus_list[bus].route[i].point = sol2.bus_list[bus].route[i].point; sols[0].bus_list[bus].route[i].shelter = sol2.bus_list[bus].route[i].shelter; sols[0].bus_list[bus].route[i].evac = 0; } //Changing route length sols[0].bus_list[bus].route_length = sol2.bus_list[bus].route_length; sols[1].bus_list[bus].route_length = sol1.bus_list[bus].route_length; } //Evacuating People to offspring solutions for(bus = 0; bus < instance.buses; bus++){ cut = cuts[bus]; for(i = cut; i < MAX_TOURS ; i++){ evac = get_evac(sols[0].bus_list[bus].route[i].point,sols[0].bus_list[bus].route[i].shelter, sols[0],instance); sols[0].bus_list[bus].route[i].evac = evac; sols[0].people_remaining[sols[0].bus_list[bus].route[i].point] -= evac; sols[0].capacity_remaining[sols[0].bus_list[bus].route[i].shelter] -= evac; evac = get_evac(sols[1].bus_list[bus].route[i].point,sols[1].bus_list[bus].route[i].shelter, sols[1],instance); sols[1].bus_list[bus].route[i].evac = evac; sols[1].people_remaining[sols[1].bus_list[bus].route[i].point] -= evac; sols[1].capacity_remaining[sols[1].bus_list[bus].route[i].shelter] -= evac; } } //Eliminating tours without evacuees eliminate_void(&sols[0],instance); eliminate_void(&sols[1],instance); //Updating fitness sols[0].fitness = calculate_fitness(sols[0],instance); sols[1].fitness = calculate_fitness(sols[1],instance); return sols; }
C
#include <stdio.h> #include <stdlib.h> #include "environment.h" #include "builtin.h" static SchemeObject* EnclosingEnvironment(SchemeObject* environ) { return Cdr(environ); } extern SchemeObject* FirstFrame(SchemeObject* environ) { return Car(environ); } static SchemeObject* MakeFrame(SchemeObject* variables, SchemeObject* values) { return Cons(variables, values); } extern SchemeObject* FrameVariables(SchemeObject* frame) { return Car(frame); } extern SchemeObject* FrameValues(SchemeObject* frame) { return Cdr(frame); } extern void AddBindingToFrame(SchemeObject* var, SchemeObject* val, SchemeObject* frame) { SetCar(frame, Cons(var, Car(frame))); SetCdr(frame, Cons(val, Cdr(frame))); } extern SchemeObject* ExtendEnvironment(SchemeObject* var, SchemeObject* val, SchemeObject* base_environ) { return Cons(MakeFrame(var, val), base_environ); } extern SchemeObject* LookupVariableValue(SchemeObject* var, SchemeObject* environ) { while (!IsTheEmptyList(environ)) { SchemeObject* frame = FirstFrame(environ); SchemeObject* vars = FrameVariables(frame); SchemeObject* vals = FrameValues(frame); while (!IsTheEmptyList(vars)) { if (var == Car(vars)) { return Car(vals); } vars = Cdr(vars); vals = Cdr(vals); } environ = EnclosingEnvironment(environ); } fprintf(stderr, "unbound variable, %s\n", var->data.symbol.value); exit(1); } extern void SetVariableValue(SchemeObject* var, SchemeObject* val, SchemeObject* environ) { while (!IsTheEmptyList(environ)) { SchemeObject* frame = FirstFrame(environ); SchemeObject* vars = FrameVariables(frame); SchemeObject* vals = FrameValues(frame); while (!IsTheEmptyList(frame)) { if (var == Car(vars)) { SetCar(vals, val); return; } vars = Cdr(vars); vals = Cdr(vals); } environ = EnclosingEnvironment(environ); } fprintf(stderr, "unbound variable, %s\n", var->data.symbol.value); exit(1); } extern SchemeObject* SetupEnvironment() { SchemeObject* initial_env = ExtendEnvironment(TheEmptyList, TheEmptyList, TheEmptyEnvironment); return initial_env; } extern SchemeObject* InteractionEnvironmentProc(SchemeObject* arguments) { return TheGlobalEnvironment; } extern SchemeObject* NullEnvironmentProc(SchemeObject* arguments) { return SetupEnvironment(); } extern SchemeObject* MakeEnvironment() { SchemeObject* env; env = SetupEnvironment(); PopulateEnvironment(env); return env; } extern SchemeObject* EnvironemntProc(SchemeObject* arguments) { return MakeEnvironment(); } extern SchemeObject* EvalProc(SchemeObject* arguments) { fprintf(stderr, "illagel state: The body of the eval primitive should not execute.\n"); exit(1); }
C
#include <stdio.h> int main() { int g; printf("Enter the grade: "); scanf("%d",&g); g/=10; switch(g){ case 10: break; case 4: break; default: switch(g<4 && g>0){ case 1: printf("F(FAIL)"); break; case 0: printf("INVALID"); break; } } return 0; }
C
/** * man fileno | col -b > fileno.man **/ #include <stdio.h> #include <stdlib.h> #include <unistd.h> int main (void) { FILE *fp; int fd; fp = fopen ("./fileno.man", "a+"); if (!fp) { perror ("fopen"); return (EXIT_FAILURE); } fd = fileno (fp); write (fd, "\nhello\n", 7); if (fflush (fp) == EOF) { perror ("fflush"); return (EXIT_FAILURE); } if (fclose (fp) == EOF) { perror ("fclose"); return (EXIT_FAILURE); } return (EXIT_SUCCESS); }
C
/** * @file * @brief ソケット処理(実行時ライブラリ) * * @author Kenta HATTORI * @date 2006/04/26 * $Id: sock.c,v 1.4 2006/08/07 09:07:51 hattori Exp $ */ #include <stdio.h> #include <stddef.h> #include <assert.h> #include <winsock2.h> #include "prcrt.h" #include "proc.h" #include "exec.h" #include "perr.h" #include "strerror.h" #include "sock.h" /* * WSAEVENT用のIO構造体(ioent_t互換) */ typedef struct ioevt_ { TAILQ_ENTRY(ioent_) link; /* リンク */ TAILQ_ENTRY(ioent_) mlink; /* 多重IO用リンク */ iotype_t iotype; /* IO種別 */ iof_t iof; /* IO処理関数へのポインタ */ chan_t *chan; /* チャネルへのリンク */ HANDLE handle; ioctlblk_t ctlblk; ioent_t *ioin; ioent_t *ioout; } ioevt_t; #define evtin ioin->ctlblk.hEvent #define evtout ioout->ctlblk.hEvent static void so_input(ioent_t *io, event_t *evt, int exec); static void so_output(ioent_t *io, event_t *evt, int exec); static void so_accept(ioent_t *io, event_t *evt, int exec); static void so_event(ioevt_t *io, event_t *evt, int exec); static void send_exec(ioent_t *io, event_t *evt); static ioevt_t *ioevt_create(SOCKET handle, ioent_t *ioin, ioent_t *ioout); static void ioevt_delete(ioevt_t *io); void prc_SockStart(void) { WORD version = MAKEWORD(2, 2); WSADATA wsadata; int status; if ((status = WSAStartup(version, &wsadata)) != 0) { perr(PERR_SYSTEM, "WSAStartup", StrError(status), __FILE__, __LINE__); } } void prc_SockFinish(void) { WSACleanup(); } /* * Udpクライアントソケットのハンドルを返す */ int prc_SockUdpClient(int ich, int och, char *host, int port) { struct hostent *hent; SOCKADDR_IN addr; SOCKET sock; if ((hent = gethostbyname(host)) == NULL) { perr(PERR_SYSTEM, "gethostbyname", StrError(WSAGetLastError()), __FILE__, __LINE__); return -1; } if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) == INVALID_SOCKET) { perr(PERR_SYSTEM, "socket", StrError(WSAGetLastError()), __FILE__, __LINE__); return -1; } memcpy(&addr.sin_addr, hent->h_addr, hent->h_length); addr.sin_port = htons(port); addr.sin_family = AF_INET; if (connect(sock, (LPSOCKADDR)&addr, sizeof(addr)) == SOCKET_ERROR) { perr(PERR_SYSTEM, "connect", StrError(WSAGetLastError()), __FILE__, __LINE__); closesocket(sock); return -1; } ioent_create((chan_t *)ich, (HANDLE)sock, IOT_INPUT, so_input, BUFSIZ); ioent_create((chan_t *)och, (HANDLE)sock, IOT_OUTPUT, so_output, BUFSIZ); return 0; } /* * Udpクライアントソケットのハンドルを返す */ int prc_SockUdpOpen(int ich, int och, char *host, int cport, int bport) { struct hostent *hent; SOCKADDR_IN addr; SOCKET sock; if ((hent = gethostbyname(host)) == NULL) { perr(PERR_SYSTEM, "gethostbyname", StrError(WSAGetLastError()), __FILE__, __LINE__); return -1; } if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) == INVALID_SOCKET) { perr(PERR_SYSTEM, "socket", StrError(WSAGetLastError()), __FILE__, __LINE__); return -1; } addr.sin_port = htons(bport); addr.sin_family = AF_INET; addr.sin_addr.s_addr = INADDR_ANY; if (bind(sock, (struct sockaddr *)&addr, sizeof(addr)) == SOCKET_ERROR) { perr(PERR_SYSTEM, "bind", StrError(WSAGetLastError()), __FILE__, __LINE__); closesocket(sock); return -1; } memcpy(&addr.sin_addr, hent->h_addr, hent->h_length); addr.sin_port = htons(cport); addr.sin_family = AF_INET; if (connect(sock, (struct sockaddr *)&addr, sizeof(addr)) == SOCKET_ERROR) { perr(PERR_SYSTEM, "connect", StrError(WSAGetLastError()), __FILE__, __LINE__); closesocket(sock); return -1; } ioent_create((chan_t *)ich, (HANDLE)sock, IOT_INPUT, so_input, BUFSIZ); ioent_create((chan_t *)och, (HANDLE)sock, IOT_OUTPUT, so_output, BUFSIZ); return 0; } /* * クライアントソケットのハンドルを返す */ int prc_SockTcpClient(int ich, int och, char *host, int port) { ioent_t *ioin, *ioout; struct hostent *hent; SOCKADDR_IN addr; SOCKET sock; if ((hent = gethostbyname(host)) == NULL) { perr(PERR_SYSTEM, "gethostbyname", StrError(WSAGetLastError()), __FILE__, __LINE__); return -1; } if ((sock = socket(AF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET) { perr(PERR_SYSTEM, "socket", StrError(WSAGetLastError()), __FILE__, __LINE__); return -1; } memcpy(&addr.sin_addr, hent->h_addr, hent->h_length); addr.sin_port = htons(port); addr.sin_family = AF_INET; if (connect(sock, (struct sockaddr *)&addr, sizeof(addr)) == SOCKET_ERROR) { perr(PERR_SYSTEM, "connect", StrError(WSAGetLastError()), __FILE__, __LINE__); closesocket(sock); return -1; } ioin = ioent_create((chan_t *)ich, (HANDLE)sock, IOT_INPUT, so_input, BUFSIZ); ioout = ioent_create((chan_t *)och, (HANDLE)sock, IOT_OUTPUT, so_output, BUFSIZ); ioevt_create(sock, ioin, ioout); return 0; } /* * サーバーソケットのハンドルを返す */ int prc_SockTcpServer(int ch, int port) { SOCKADDR_IN addr; SOCKET sock; BOOL option = TRUE; if ((sock = WSASocket(AF_INET, SOCK_STREAM, IPPROTO_IP, NULL, 0, WSA_FLAG_OVERLAPPED)) == INVALID_SOCKET) { perr(PERR_SYSTEM, "socket", StrError(WSAGetLastError()), __FILE__, __LINE__); return -1; } if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char *)&option, sizeof(option)) == SOCKET_ERROR) { perr(PERR_SYSTEM, "setsockopt", StrError(WSAGetLastError()), __FILE__, __LINE__); return -1; } /* TODO: fcntl()でO_NONBLOCKをセットする */ addr.sin_port = htons(port); addr.sin_family = AF_INET; addr.sin_addr.s_addr = INADDR_ANY; if (bind(sock, (struct sockaddr *)&addr, sizeof(addr)) == SOCKET_ERROR) { perr(PERR_SYSTEM, "bind", StrError(WSAGetLastError()), __FILE__, __LINE__); closesocket(sock); return -1; } if (listen(sock, SOMAXCONN) == SOCKET_ERROR) { perr(PERR_SYSTEM, "listen", StrError(WSAGetLastError()), __FILE__, __LINE__); closesocket(sock); return -1; } ioent_create((chan_t *)ch, (HANDLE)sock, IOT_INPUT, so_accept, 0); if (WSAEventSelect(sock, ((chan_t *)ch)->ioent->ctlblk.hEvent, FD_ACCEPT) == SOCKET_ERROR) { perr(PERR_SYSTEM, "WSAEventSelect", StrError(WSAGetLastError()), __FILE__, __LINE__); closesocket(sock); return -1; } return 0; } void prc_SockClose(int h) { perr(PERR_SYSTEM, "prc_SockClose", "not supported", __FILE__, __LINE__); } static void shutdown_recvsock(ioent_t *io) { ioevt_t *ioevt; // printf("shutdown_recvsock: enter\n"); // fflush(stdout); if (shutdown((SOCKET)io->handle, SD_RECEIVE) == SOCKET_ERROR) { perr(PERR_SYSTEM, "shutdown", StrError(WSAGetLastError()), __FILE__, __LINE__); return ; } /* * すでにSO_SENDされている場合 * ソケットクローズし,IOイベントも削除する */ ioevt = io->data; if (ioevt->ioout == NULL) { closesocket((SOCKET)io->handle); ioevt_delete(ioevt); } else { ioevt->ioin = NULL; } /* 入力IOチャネルを削除 */ ioent_delete(io); } static void shutdown_sendsock(ioent_t *io) { ioevt_t *ioevt; // printf("shutdown_sendsock: enter\n"); // fflush(stdout); if (shutdown((SOCKET)io->handle, SD_SEND) == SOCKET_ERROR) { perr(PERR_SYSTEM, "shutdown", StrError(WSAGetLastError()), __FILE__, __LINE__); return ; } /* * すでにSO_RECVされている場合 * ソケットクローズし,IOイベントも削除する */ ioevt = io->data; if (ioevt->ioin == NULL) { closesocket((SOCKET)io->handle); ioevt_delete(ioevt); } else { ioevt->ioout = NULL; } /* 出力IOチャネルを削除 */ ioent_delete(io); } static void CALLBACK recv_completion_handler(DWORD err, DWORD len, LPWSAOVERLAPPED ovl, DWORD flags) { event_t *evt; ioent_t *io = (ioent_t*)(((char*)ovl)-offsetof(ioent_t,ctlblk)); // printf("recv completed: err=%ld, len=%ld\n", err, len); // fflush(stdout); aio_count--; io_read_complete(io, len); if (len == 0) { shutdown_recvsock(io); return; } /* IO待ちプロセスが無ければ終了 */ if ((evt = chin_next(io->chan)) == NULL) { return; } io->iof(io, evt, 0); } /** * ソケットIOチャネル入力時の処理 */ static void so_input(ioent_t *io, event_t *evt, int exec) { WSABUF wsabuf; DWORD flags = 0; int result; int error; // printf("so_input: enter(exec=%d, trans=%d)\n", exec, evt->trans); // fflush(stdout); if (evt->trans == 0) { aio_count++; /* 新規に受信IO発行 */ wsabuf.len = io->bufsz; wsabuf.buf = io->buf; result = WSARecv((SOCKET)io->handle, &wsabuf, 1, (LPDWORD)&io->offset, &flags, &io->ctlblk, recv_completion_handler); if (result == 0) { // printf("so_input: WSARecv() result=0\n"); // fflush(stdout); return; } error = WSAGetLastError(); switch (error) { case WSA_IO_PENDING: // printf("so_input: WSARecv() WSA_IO_PENDING\n"); // fflush(stdout); break; case WSAECONNRESET: aio_count--; // printf("so_input: WSARecv() WSAECONNRESET\n"); // fflush(stdout); io_read_complete(io, 0); shutdown_recvsock(io); break; default: perr(PERR_SYSTEM, "WSARecv", StrError(error), __FILE__, __LINE__); break; } return; } else { ioevt_t *ioevt = (ioevt_t *)io->data; if (ioevt->mlink.tqe_prev == NULL) { TAILQ_INSERT_TAIL(&__prc__mioq, (ioent_t *)ioevt, mlink); } } TAILQ_INSERT_TAIL(&__prc__mioq, io, mlink); } static void CALLBACK send_completion_handler(DWORD err, DWORD len, LPWSAOVERLAPPED ovl, DWORD flags) { event_t *evt; ioent_t *io = (ioent_t*)(((char*)ovl)-offsetof(ioent_t,ctlblk)); // printf("send completed: err=%ld, len=%ld\n", err, len); // fflush(stdout); aio_count--; io->offset += len; evt = (event_t*)chout_next(io->chan); if (io->offset < STRLEN(evt->val)) { send_exec(io, evt); return; } io_write_complete(io, len); /* IO待ちプロセスが無ければ終了 */ if ((evt = chout_next(io->chan)) != NULL) { io->iof(io, evt, 0); } } static void send_exec(ioent_t *io, event_t *evt) { WSABUF wsabuf; DWORD flags = 0; int result; int error; int len; aio_count++; len = STRLEN(evt->val) - io->offset; if (len > io->bufsz) { len = io->bufsz; } /* 新規に送信IO発行 */ memcpy(io->buf, STRPTR(evt->val)+io->offset, len); wsabuf.len = len; wsabuf.buf = io->buf; result = WSASend((SOCKET)io->handle, &wsabuf, 1, (LPDWORD)&len, flags, &io->ctlblk, send_completion_handler); if (result == 0) { // printf("so_output: WSASend() result=0\n"); // fflush(stdout); return; } error = WSAGetLastError(); switch (error) { case WSA_IO_PENDING: // printf("so_output: WSASend() WSA_IO_PENDING\n"); // fflush(stdout); break; case WSAECONNRESET: aio_count--; // printf("so_output: WSASend() WSAECONNRESET\n"); // fflush(stdout); io_write_complete(io, 0); shutdown_sendsock(io); break; default: perr(PERR_SYSTEM, "WSASend", StrError(error), __FILE__, __LINE__); break; } } /** * ソケットIOチャネル出力時の処理 */ static void so_output(ioent_t *io, event_t *evt, int exec) { // printf("so_output: enter(exec=%d,trans=%d)\n", exec, evt->trans); // fflush(stdout); if (evt->trans == 0) { int len = STRLEN(evt->val); if (len == 0) { io_write_complete(io, 0); shutdown_sendsock(io); return; } io->offset = 0; send_exec(io, evt); return; } else { ioevt_t *ioevt = (ioevt_t *)io->data; if (ioevt->mlink.tqe_prev == NULL) { TAILQ_INSERT_TAIL(&__prc__mioq, (ioent_t *)ioevt, mlink); } } TAILQ_INSERT_TAIL(&__prc__mioq, io, mlink); } static void accept_exec(ioent_t *io) { ioent_t *ioin, *ioout; proc_t *prc; event_t *evt; SOCKET so; if ((so = accept((SOCKET)io->handle, NULL, NULL)) == INVALID_SOCKET) { perr(PERR_SYSTEM, "accept", StrError(WSAGetLastError()), __FILE__, __LINE__); return; } __prc__regs[0] = (int)__chan__(); __prc__regs[1] = (int)__chan__(); ioin = ioent_create((chan_t *)__prc__regs[0], (HANDLE)so, IOT_INPUT, so_input, BUFSIZ); ioout = ioent_create((chan_t *)__prc__regs[1], (HANDLE)so, IOT_OUTPUT, so_output, BUFSIZ); ioevt_create(so, ioin, ioout); __prc__regs[2] = __record__(2); ((int*)__prc__regs[2])[0] = __prc__regs[0]; ((int*)__prc__regs[2])[1] = __prc__regs[1]; /* 実行可能プロセスをセット */ prc = proc(); evt = chin_next(io->chan); prc->clos = evt->clos; prc->val = __prc__regs[2]; TAILQ_INSERT_TAIL(__prc__rdyq, prc, link); TAILQ_REMOVE(&io->chan->inq, evt, link); /* IO待ちプロセスが無ければ終了 */ if ((evt = chin_next(io->chan)) == NULL) { return; } io->iof(io, evt, 0); } /** * Listen IOチャネル入力時の処理 */ static void so_accept(ioent_t *io, event_t *evt, int exec) { if (exec) { accept_exec(io); return; } TAILQ_INSERT_TAIL(&__prc__mioq, io, mlink); } /** * IOイベントエントリの新規作成 */ static ioevt_t *ioevt_create(SOCKET handle, ioent_t *ioin, ioent_t *ioout) { WSAEVENT wsaevt; ioevt_t *io; io = malloc(sizeof(ioevt_t)); if (io == NULL) { perr(PERR_OUTOFMEM, __FILE__, __LINE__); return NULL; } io->iotype = IOT_EVENT; io->iof = (iof_t)so_event; io->chan = NULL; io->handle = (HANDLE)handle; io->ioin = ioin; io->ioout = ioout; ioin->data = io; ioout->data = io; if ((wsaevt = WSACreateEvent()) == WSA_INVALID_EVENT) { perr(PERR_SYSTEM, "CreateEvent", StrError(WSAGetLastError()), __FILE__, __LINE__); return NULL; } if (WSAEventSelect(handle, wsaevt, FD_READ|FD_WRITE|FD_CLOSE) == SOCKET_ERROR) { perr(PERR_SYSTEM, "WSAEventSelect", StrError(WSAGetLastError()), __FILE__, __LINE__); return NULL; } memset(&io->ctlblk, 0, sizeof(OVERLAPPED)); io->ctlblk.hEvent = wsaevt; TAILQ_INSERT_TAIL(&__prc__ioq, (ioent_t*)io, link); io->mlink.tqe_prev = NULL; // TAILQ_INSERT_TAIL(&__prc__mioq, (ioent_t*)io, mlink); return io; } /** * IOイベントエントリの削除 */ static void ioevt_delete(ioevt_t *io) { // printf("ioevt_delete: enter\n"); // fflush(stdout); TAILQ_REMOVE(&__prc__ioq, (ioent_t*)io, link); WSACloseEvent(io->ctlblk.hEvent); free(io); } /* * ソケットのイベント管理用 */ static void so_event(ioevt_t *io, event_t *evt, int exec) { WSANETWORKEVENTS wsaevts; int result; int error; // printf("so_event: enter\n"); // fflush(stdout); result = WSAEnumNetworkEvents((SOCKET)io->handle, io->ctlblk.hEvent, &wsaevts); if (result == SOCKET_ERROR) { error = WSAGetLastError(); perr(PERR_SYSTEM, "WSAEnumNetworkEvents", StrError(error), __FILE__, __LINE__); return; } if (wsaevts.lNetworkEvents & FD_READ) { // printf("so_event: FD_READ\n"); // fflush(stdout); if (!SetEvent(io->evtin)) { error = GetLastError(); perr(PERR_SYSTEM, "SetEvent", StrError(error), __FILE__, __LINE__); return; } } else if (wsaevts.lNetworkEvents & FD_WRITE) { // printf("so_event: FD_WRITE\n"); // fflush(stdout); if (!SetEvent(io->evtout)) { error = GetLastError(); perr(PERR_SYSTEM, "SetEvent", StrError(error), __FILE__, __LINE__); return; } } else if (wsaevts.lNetworkEvents & FD_CLOSE) { // printf("so_event: FD_CLOSE\n"); // fflush(stdout); if (!SetEvent(io->evtin)) { error = GetLastError(); perr(PERR_SYSTEM, "SetEvent", StrError(error), __FILE__, __LINE__); return; } return; } else { /* 想定外のイベント */ perr(PERR_INTERNAL, __FILE__, __LINE__); return; } if (((evt = chin_next(io->ioin->chan)) != NULL && evt->trans != 0) || ((evt = chout_next(io->ioout->chan)) != NULL && evt->trans != 0)) { TAILQ_INSERT_TAIL(&__prc__mioq, (ioent_t *)io, mlink); } }
C
#include <string.h> #include "UDPserver.h" #include <stdlib.h> #include <stdio.h> #include "minuit.h" #include "device.h" /*********************************************************/ /**************** Minuit parsing fonctions ***************/ /*********************************************************/ int size_bytes(int i) { if(i%4 == 0) return i; else return i + 4 - i%4; } char * string_to_float_ASCII(char * str){ char * s = malloc(sizeof(char)*5); int d = 0; for(int j = 0; j < 4 ; j++) { d <<= 8; d += str[j] & 0xFF; } float * f = (float * )&d; sprintf( s, "%f", *f); return s; } char * string_to_int_ASCII(char * str){ int d = 0; char * s = malloc(sizeof(char)*5); for(int i = 0 ; i < 4 ; i++){ d <<= 8; d += str[i] & 0xFF; } sprintf( s, "%d", d); return s; } char * data_cpy(DATA p, int debut, int fin){ char * tmp = malloc((fin - debut)*sizeof(char) + 1); int i = 0; while( i < fin - debut){ tmp[i] = ds_string(p)[debut+i]; i++; } tmp[i] = '\0'; return tmp; } Str_array OSC_to_str_array(DATA p){ int i = 0; while(i < ds_len(p) && ds_string(p)[i] != ',') i++; Str_array str = new_string_array(); char * path = data_cpy(p, 0, i); str = str_array_append(str, path); free(path); char * type = data_cpy(p, i, i+2); str = str_array_append(str, type); free(type); char * cpy = data_cpy(p, i+4, ds_len(p)); if(get_string(str, 1)[1] == 'i'){ char * val = string_to_int_ASCII(cpy); str = str_array_append(str, val); free(val); } if(get_string(str, 1)[1] == 'f'){ char * flo = string_to_float_ASCII(cpy); str = str_array_append(str, flo); free(flo); } free(cpy); return str; } Str_array minuit_to_str_array(DATA p){ if(ds_string(p)[0] == '/') return OSC_to_str_array(p); int i = 0; while(i < ds_len(p) && ds_string(p)[i] != '?' && ds_string(p)[i] != ':') i++; Str_array str = new_string_array(); char * device = data_cpy(p, 0, i); str = str_array_append(str, device); free(device); char * op = data_cpy(p, i, i+1); str = str_array_append(str, op); free(op); i++; int j; char * tmp = NULL; while(i <ds_len(p)){ j = 0; while(j < ds_len(p) - i && ds_string(p)[j+i] != '\0') j++; tmp = data_cpy(p, i, j + i); str = str_array_append(str, tmp); free(tmp); i += size_bytes(j+1); } return str; } DATA write_minuit_packet(Str_array str){ if(str != NULL){ int len = 0; for(int i = 0; i < 3 ; i++){ len += strlen(get_string(str, i)); } len = size_bytes(len + 1); for(int i = 3 ; i < get_size(str) ; i++){ len += size_bytes(strlen(get_string(str, i)) + 1); } char * buffer = malloc(len * sizeof(char)); int it = 0; for(int i = 0 ; i < 3 ; i++){ for(int j = 0 ; j < strlen(get_string(str, i)) ; j++){ buffer[it] = get_string(str,i)[j]; it++; } } while(it < size_bytes(strlen(get_string(str, 0)) + strlen(get_string(str, 1)) + strlen(get_string(str, 2)) + 1)){ buffer[it] = '\0'; it++; } for(int i = 3 ; i < get_size(str) ; i++){ for(int j = 0 ; j < strlen(get_string(str, i)) ; j++){ buffer[it] = get_string(str, i)[j]; it++; } for(int j = strlen(get_string(str, i)) ; j < size_bytes(strlen(get_string(str, i)) +1 ) ; j++){ buffer[it] = '\0'; it++; } } DATA d = init_data(buffer, len); free(buffer); return d; } else return NULL; } Attribute get_attribute(char * s){ int i = 0; while(i < strlen(s) && s[i] != ':'){ i++; } if(i >= strlen(s)) return unknown_attribute; else { char * attr = s + i + 1; if(strcmp(attr, "value") == 0) return value; if(strcmp(attr, "tags") == 0) return tags; if(strcmp(attr, "type") == 0) return type; if(strcmp(attr, "service") == 0) return service; if(strcmp(attr, "priority") == 0) return priority; if(strcmp(attr, "rangeBounds") == 0) return rangeBounds; if(strcmp(attr, "rangeClipmode") == 0) return rangeClipmode; if(strcmp(attr, "description") == 0) return description; else return unknown_attribute; } } Query get_query(Str_array str){ if(strcmp(get_string(str, 2), "namespace") == 0) return discover; if(strcmp(get_string(str, 2), "get" )== 0) return get; if(strcmp(get_string(str, 2), "set") == 0) return set; if(strcmp(get_string(str, 2), "listen") == 0) return listen; else return unknown_query; } Protocol protocol(Str_array str){ if(get_string(str, 0)[0] == '/') return OSC; if(get_string(str, 1)[0] == ':') return minuit_reply; if(get_string(str, 1)[0] == '?') return minuit_query; else return unknown_protocol; } //Réponse à une minuit_query Str_array namespace_answer(Device d, Str_array src){ char * path = get_string(src, 4); Str_array str = new_string_array(); str = str_array_append(str, node_name(get_root(d))); str = str_array_append(str, ":"); str = str_array_append(str, "namespace"); if(!strcmp(path, "/")){ //fabriquer namespace général char * type = malloc(sizeof(char)*(node_size(get_root(d)) + 6)); type[0] = ','; for(int i = 1 ; i < node_size(get_root(d))+5 ; i++) type[i] = 's'; type[node_size(get_root(d)) + 5] = '\0'; str = str_array_append(str, type); free(type); str = str_array_append(str, "/"); str = str_array_append(str, "Application"); str = str_array_append(str, "nodes={"); for(int i = 0 ; i < node_size(get_root(d)) ; i++) str = str_array_append(str, node_name(node_subnodes(get_root(d))[i])); str = str_array_append(str, "}"); } else{ //fabriquer namespace pour la node située à l'adresse path char * name = path_to_name(path); Node n = find_node(get_root(d), name); free(name); if(n == NULL){ printf("Couldn't find node\n"); return NULL; } char * type = NULL; if(strcmp(node_objectType(n), "Container")==0){ type = malloc(sizeof(char)*(node_size(n) + 6)); type[0] = ','; for(int i = 1 ; i < node_size(n)+5 ; i++) type[i] = 's'; type[node_size(n)+5] = '\0'; } else if (strcmp(node_objectType(n), "Data")==0){ type = malloc(sizeof(char)*5); type[0] = ','; for(int i = 1 ; i < 3 ; i++) type[i] = 's'; type[3] = '\0'; } if(type != NULL){ str = str_array_append(str, type); free(type); } str = str_array_append(str, path); str = str_array_append(str, node_objectType(n)); if(strcmp(node_objectType(n), "Container")==0){ str = str_array_append(str, "nodes={"); for(int i = 0 ; i < node_size(n) ; i++) str = str_array_append(str, node_name(node_subnodes(n)[i])); str = str_array_append(str, "}"); } } return str; } char * path_to_name(char * path){ int last_slash = 0; int i; for(i = 0 ; path[i] != '\0' && path[i] != ':' ; i++){ if(path[i] == '/') last_slash = i; } char * name = malloc((i - last_slash + 1 ) * sizeof(char)); name = strncpy(name, last_slash + 1 + path, i - last_slash - 1); name[i - last_slash -1] = '\0'; return name; } Str_array get_answer(Device d, Str_array str){ char * name = path_to_name(get_string(str, 4)); Node n = find_node(get_root(d), name); Str_array answer = new_string_array(); if( n == NULL ) printf("Node %s doesn't exist\n", name); else{ answer = str_array_append(answer, device_name(d)); answer = str_array_append(answer, ":"); answer = str_array_append(answer, "get"); switch(get_attribute(get_string(str, 4))){ case value: free_str_array(answer); answer = NULL; break; case type: answer = str_array_append(answer, ",ss"); answer = str_array_append(answer, get_string(str, 4)); answer = str_array_append(answer, node_type(n)); break; case tags: free_str_array(answer); answer = NULL; break; case rangeClipmode: free_str_array(answer); answer = NULL; break; case service: answer = str_array_append(answer, ",ss"); answer = str_array_append(answer, get_string(str, 4)); answer = str_array_append(answer, node_service(n)); break; case priority: ; char * p = malloc(sizeof(char)*5); sprintf(p,"%d", node_priority(n)); answer = str_array_append(answer, ",si"); answer = str_array_append(answer, get_string(str, 4)); answer = str_array_append(answer, p); free(p); break; case rangeBounds: free_str_array(answer); answer = NULL; break; case description: answer = str_array_append(answer, ",ss"); answer = str_array_append(answer, get_string(str, 4)); answer = str_array_append(answer, node_desc(n)); break; case unknown_attribute: free_str_array(answer); answer = NULL; break; } } free(name); return answer; } Str_array minuit_answer(Device d, Str_array str){ Str_array answer = NULL; switch(get_query(str)){ case discover: answer = namespace_answer(d, str); break; case get: answer = get_answer(d, str); break; case set: break; case listen: break; case unknown_query: break; } return answer; }
C
#include "calc_pn_mgx_no_pi_delay_sorted.h" #include "evalkit_constants.h" #include "pru.h" #include "fp_atan2.h" #include "calibration.h" #include "hysteresis.h" #include "adc_overflow.h" #include "saturation.h" #include "calculator.h" #include "iterator_mgx.h" #include <math.h> #include <stdlib.h> /// \addtogroup calculate /// @{ static uint16_t pixelData[MAX_NUM_PIX * 2]; /*! Does MGX mode PN modulation no Pi delay ( DCS0, DCS1) image acquisition and returns sorted distance/amplitude data array @param type calculation type: 0 - distance, 1-amplitude, 2 - distance and amplitude @param data pointer to data pointer array. This arrays contains image data @returns image size (number of pixels) */ int calcPNMGXNoPiDelayGetDataSorted(enum calculationType type, uint16_t **data) { int size = pruGetImage(data); uint16_t *pMem = *data; int nPixelPerDCS = size; int nCols = pruGetNCols(); uint16_t nHalves = pruGetNumberOfHalves(); calculatorInit(1); iteratorMGXInit(nPixelPerDCS, nCols, pruGetNRowsPerHalf() * pruGetNumberOfHalves()); while(iteratorMGXHasNext()){ struct Position p = iteratorMGXNext(); uint16_t pixelDCS0 = pMem[p.indexMemory]; uint16_t pixelDCS1 = pMem[p.indexMemory + nHalves * nCols]; calculatorSetArgs2DCS(pixelDCS0, pixelDCS1, p.indexMemory, p.indexCalibration); struct TofResult tofResult; switch(type){ case DIST: pixelData[p.indexSorted] = calculatorGetDistAndAmpPN().dist; break; case AMP: pixelData[p.indexSorted] = calculatorGetAmpPN(); break; case INFO: tofResult = calculatorGetDistAndAmpPN(); pixelData[p.indexSorted] = tofResult.dist; pixelData[p.indexSorted + nPixelPerDCS] = tofResult.amp; break; } } *data = pixelData; if (type == INFO){ return nPixelPerDCS; } return nPixelPerDCS / 2; } /// @}
C
#include <stdio.h> #include <string.h> #include "gameRules.h" /*Update the game*/ void update(card game1[], card game2[], int *N1, int *N2, card a, card b){ int i; *N1 += 1; *N2 -= 1; game1[*N1 - 1] = a; game1[*N1] = b; for (i = 0; i < *N1; i++){ game1[i] = game1[i + 1]; } for (i = 0; i < *N2; i++){ game2[i] = game2[i + 1]; } return; } /*Handle the result of a battle (1 shot)*/ void play(card game1[], card game2[], int *N1, int *N2){ card a, b; a = game1[0]; b = game2[0]; if ( game1[0].value > game2[0].value){ update(game1, game2, N1, N2, a, b); return; } if ( game1[0].value < game2[0].value){ update(game2, game1, N2, N1, b, a); return; } else { if (strcmp(game1[0].color, "heart") == 0 && strcmp(game2[0].color, "heart") != 0){ update(game1, game2, N1, N2, a, b); return; } if (strcmp(game2[0].color, "heart") == 0 && strcmp(game1[0].color, "heart") != 0){ update(game2, game1, N2, N1, b, a); return; } if (strcmp(game1[0].color, "spade") == 0 && strcmp(game2[0].color, "spade") != 0){ update(game1, game2, N1, N2, a, b); return; } if (strcmp(game2[0].color, "spade") == 0 && strcmp(game1[0].color, "spade") != 0){ update(game2, game1, N2, N1, b, a); return; } if (strcmp(game1[0].color, "diamond") == 0 && strcmp(game2[0].color, "diamond") != 0){ update(game1, game2, N1, N2, a, b); return; } if (strcmp(game2[0].color, "diamond") == 0 && strcmp(game1[0].color, "diamond") != 0){ update(game2, game1, N2, N1, b, a); return; } } return; }
C
/* Implementao do algoritmo do Crivo de Eratnestes para encontrar nmeros primos https://pt.wikipedia.org/wiki/Crivo_de_Erat%C3%B3stenes */ #include <stdio.h> #include <stdlib.h> #include <math.h> int main() { int i,j,N,raiz,counter=0; printf("Informe um numero:\n"); scanf("%d",&N); int elementos[N+1]; raiz = sqrt(N); for (i=0; i <=N+1; i++) { if(i == 0 || i == 1) elementos[i] = 0; else elementos[i] = 1; } for(j=2; j<=raiz; j++) for (i=0; i <=N+1; i++) if (i % j == 0 && i != j) elementos[i] = 0; printf("\nNumeros primos entre 0 e %d:\n", N); for (i=0; i <=N; i++) if (elementos[i] != 0) { printf("%d ", i); counter++; } printf("\nTotal: %d\n",counter); return 0; }
C
/** * Copyright: <David daijiwei41@gmail.com> * Created: 2015-04-22 * Modify: 2015-04-22 */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <signal.h> #include <errno.h> #include <unistd.h> #include <fcntl.h> #include <sys/types.h> #include <sys/socket.h> #include <sys/epoll.h> #include <netinet/in.h> #define BUF_SIZE 1024 #define LISTEN_BACKLOG 50 #define MAX_EVENTS 10 #define handle_error(msg) \ do{ \ perror(msg); \ exit(EXIT_FAILURE); \ }while(0) typedef int SOCKETFD; void str_echo(SOCKETFD socketfd) { char buf[BUF_SIZE]; int n; while((n = read(socketfd, buf, sizeof(buf))) > 0){ n = write(socketfd, buf, n); if (n < 0) { handle_error("write no message"); } } if (n < 0 ) { handle_error("read message failed"); } } void sig_chld(int signo){ pid_t pid; int stat; while((pid = waitpid(-1,&stat, WNOHANG)) > 0) printf("child %d terminated\n", pid); return; } void set_noblocking(int fd){ int ret; ret = fcntl(fd, F_GETFL); if(ret < 0){ handle_error("get flil ds filed\n"); exit(EXIT_FAILURE); } ret = ret | O_NONBLOCK; if(fcntl(fd, F_SETFL, ret) < 0){ handle_error("set nonblocking filed\n"); exit(EXIT_FAILURE); } } int main() { int listen_fd, connect_fd; int port = 8080; pid_t pid; socklen_t clientlen; struct sockaddr_in client_addr, server_addr; // epoll int epollfd, nfds, i; struct epoll_event ev, events[MAX_EVENTS]; listen_fd = socket(AF_INET, SOCK_STREAM, 0); if (-1 == listen_fd) { handle_error("create socket failed\n"); } memset(&server_addr, 0, sizeof(server_addr)); server_addr.sin_family = AF_INET; server_addr.sin_addr.s_addr = htonl(INADDR_ANY); server_addr.sin_port = htons(port); if(-1 == bind(listen_fd, (struct sockaddr *)&server_addr, sizeof(server_addr))){ handle_error("bind socket failed\n"); } if (-1 == listen(listen_fd, LISTEN_BACKLOG)){ handle_error("listen socket failed\n"); } epollfd = epoll_create(MAX_EVENTS); if(epollfd < 0) { handle_error("create epoll failed\n"); exit(EXIT_FAILURE); } ev.data.fd = listen_fd; ev.events = EPOLLIN; if(-1 == epoll_ctl(epollfd, EPOLL_CTL_ADD, listen_fd, &ev)){ handle_error("Epoll ctl add listen fd failed\n"); exit(EXIT_FAILURE); } for (; ;) { nfds = epoll_wait(epollfd, events, 20, 50); if(-1 == nfds){ handle_error("Epoll ctl add listen fd failed\n"); exit(EXIT_FAILURE); } for(i = 0; i < nfds; ++i){ if(events[i].data.fd == listen_fd) { clientlen = sizeof(client_addr); if ((connect_fd = accept(listen_fd, (struct sockaddr*)&client_addr, &clientlen)) < 0){ handle_error("accept message failed\n"); } ev.data.fd = connect_fd; set_noblocking(connect_fd); if(-1 == epoll_ctl(epollfd, EPOLL_CTL_ADD, listen_fd, &ev)){ handle_error("Epoll ctl add listen fd failed\n"); } } else if(events[i].events | EPOLLIN){ // read ev.events= EPOLLOUT | EPOLLET; if(-1 == epoll_ctl(epollfd, EPOLL_CTL_MOD, listen_fd, &ev)){ handle_error("Epoll ctl add listen fd failed\n"); } } else if(events[i].events | EPOLLOUT){ // send ev.events= EPOLLIN | EPOLLET; if(-1 == epoll_ctl(epollfd, EPOLL_CTL_MOD, listen_fd, &ev)){ handle_error("Epoll ctl add listen fd failed\n"); } } } } }
C
#include<stdio.h> int main() { /* 10 14 12 16 20 24 28 32 36 40 44 48 52 56 60 64 */ int matris1[4][4]; int a,b; for(a=0;a<4;a++){ for(b=0;b<4;b++){ scanf("%d\n",&matris1[a][b]); } } for(a=0;a<4;a++){ { for(b=0;b<4;b++) { printf("%d ",matris[a][b]); } printf("\n"); }
C
#include "holberton.h" /** * rev_string - reverse a string * @s: string of characters * */ void rev_string(char *s) { int a; int b = 0; int c = 0; int z[500]; for (a = 0; a < 500; a++) { if (s[a] == '\0') break; c++; } for (a = c - 1; a >= 0; a--) { z[b] = s[a]; b++; } for (a = 0; a < c; a++) { s[a] = z[a]; } }
C
/* This file is public domain; anyone may deal in it without restriction. screen.c: drawing */ #include "columns.h" #define DOUBLEWIDTH static int drawwidth; static int drawheight; static int drawleft; static int drawtop; static void drawhorizline(int row, int colstart, int colend) { int i; (void)move(row, colstart); for (i = colstart; i <= colend; i++) (void)addch('-'); } static void drawvertline(int rowstart, int rowend, int col) { int i; for (i = rowstart; i <= rowend; i++) (void)mvaddch(i, col, '|'); } int playsizeok(int width, int height) { #ifdef DOUBLEWIDTH width *= 2; #endif if (width + (2+PANEL_WIDTH)*2 > COLS) return 0; if (height + 2 > LINES) return 0; return 1; } void drawborders(int width, int height) { drawwidth = width; drawheight = height; #ifdef DOUBLEWIDTH drawwidth *= 2; #endif /* center the playfield */ drawleft = (COLS - drawwidth) / 2; drawtop = (LINES - drawheight) / 2; /* clear the screen */ (void)erase(); /* draw the horizontal borders */ drawhorizline(drawtop - 1, drawleft, drawleft + drawwidth - 1); drawhorizline(drawtop + drawheight, drawleft, drawleft + drawwidth - 1); /* draw the vertical borders */ drawvertline(drawtop, drawtop + drawheight - 1, drawleft - 1); drawvertline(drawtop, drawtop + drawheight - 1, drawleft + drawwidth); } void drawblock(int row, int col, chtype ch) { #ifdef DOUBLEWIDTH col *= 2; #endif (void)mvaddch(row + drawtop, col + drawleft, ch); #ifdef DOUBLEWIDTH (void)addch(ch); #endif } void drawlevel(int level) { char buf[200] = ""; int startcol; (void)snprintf(buf, 200, "Level %d", level); startcol = drawleft + drawwidth + 2; startcol += (PANEL_WIDTH - (int)strlen(buf)) / 2; (void)mvaddstr(drawtop + 1, startcol, buf); } void drawscore(int score) { char buf[200] = ""; int startcol; (void)snprintf(buf, 200, "%d", score); startcol = drawleft - 2 - PANEL_WIDTH; startcol += (PANEL_WIDTH - (int)strlen(buf)) / 2; (void)mvaddstr(drawtop + 1, startcol, buf); } void updatescreen(void) { (void)refresh(); }
C
#include "holberton.h" #include <stdlib.h> /** *_strdup - function that returns a pointer to a newly allocated space. *@str: char. *Return: Either NULL or a pointer. * * */ char *_strdup(char *str) { char *c; unsigned int s, i; s = 0; i = 0; if (str == 0) return (NULL); while (str[s] != '\0') { s++; } s++; c = malloc(sizeof(char) * s); if (c == 0) return (NULL); for (i = 0; i < s; i++) { c[i] = str[i]; } c[i] = '\0'; return (c); }
C
#ifndef OBUFFER_H #define OBUFFER_H #include <stdint.h> #define OBUFFER_MACRO 1 typedef struct { uint8_t *buf; uint8_t in; uint8_t out; uint8_t size; uint8_t maxSize; } obuffer_t; // standart variant (inoperable) #if OBUFFER_MACRO == 0 #error "OBUFFER_MACRO must be defined as 1!" void obuffer_init_(obuffer_t *obuf, uint8_t *buf, uint8_t maxSize); uint8_t obuffer_put_(obuffer_t *obuf, uint8_t value); uint8_t obuffer_get_(obuffer_t *obuf, uint8_t *value); #define obuffer_init(obuf, buffer, buffersize) obuffer_init_(&obuf, buffer, buffersize) #define obuffer_put(obuf, value) obuffer_put_(&obuf, value) #define obuffer_get(obuf, value) obuffer_get_(&obuf, &value) #endif // macro variant #if OBUFFER_MACRO != 0 #define obuffer_init(obuf, buffer, buffersize) \ (obuf.buf = buffer, obuf.in = obuf.out = obuf.size = 0, obuf.maxSize = buffersize) #define obuffer_put(obuf, value) \ ((obuf.size < obuf.maxSize) ? \ (obuf.buf[obuf.in] = value, ++obuf.size, (obuf.in = (++obuf.in >= obuf.maxSize) ? 0 : obuf.in), 1) : \ (0)) #define obuffer_get(obuf, value) \ ((obuf.size > 0) ? \ (value = obuf.buf[obuf.out], --obuf.size, (obuf.out = (++obuf.out >= obuf.maxSize) ? 0 : obuf.out), 1) : \ (0)) #endif #endif
C
// Exponential exp(x) #include<stdio.h> #include<math.h> int main() { int i,n,t0; float x,t1,R,sum; t0=1; //defining first term of series sum=t0; //first term is also first partial sum printf("Enter the value of x: "); scanf("%f",&x); printf("Enter the number of terms: "); scanf("%d",&n); // printing for n=0 printf("x\tn\tsum\n"); // loop for summing terms using ratio i=0; do { printf("%.2f\t%d\t%.2f\n",x,i+1,sum); i++; R=x/i; t1=R*t0; sum=sum+t1; t0=t1; } while (i<n); printf("\nFor x=%.2f and n=%d, exponential sum= %.2f",x,n,sum); }
C
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <netdb.h> #include <netinet/in.h> #include <sys/socket.h> #include <sys/types.h> #include <errno.h> void explode_bomb() { printf("Sorry, incorrect!\n"); printf("BOOOOM\n"); exit(0); } int string_length(char *s) { int result = 0; for (result = 0; s[result]; result++); return result; } int strings_not_equal(char *a, char *b) { int v2 = string_length(a); if (v2 != string_length(b)) return 1; int i; for (i = 0; a[i]; i++) { if (a[i] != b[i]) return 1; } return 0; } void phase_1(char *input) { int result = strings_not_equal(input, "Public speaking is very easy."); if (result) { explode_bomb(); } } void read_six_numbers(char *input, int *array) { int result; result = sscanf(input, "%d %d %d %d %d %d", &array[0], &array[1], &array[2], &array[3], &array[4], &array[5]); if (result <= 5) { explode_bomb(); } } void phase_2(char *input) { int array[6]; read_six_numbers(input, array); if (array[0] != 1) explode_bomb(); int f = 1; int i; for (i = 1; i < 6; i++) { f = array[i - 1] * (i + 1); if (array[i] != f) explode_bomb(); } } void phase_3(char *input) { int v3; char v4; int v5; char v2; if (sscanf(input, "%d %c %d", &v3, &v4, &v5) <= 2) explode_bomb(); switch(v3) { case 0: v2 = 113; if (v5 != 777) explode_bomb(); break; case 1: v2 = 98; if (v5 != 214) explode_bomb(); break; case 2: v2 = 98; if (v5 != 755) explode_bomb(); break; case 3: v2 = 107; if (v5 != 251) explode_bomb(); break; case 4: v2 = 111; if (v5 != 160) explode_bomb(); break; case 5: v2 = 116; if (v5 != 458) explode_bomb(); break; case 6: v2 = 118; if (v5 != 780) explode_bomb(); break; case 7: v2 = 98; if (v5 != 524) explode_bomb(); break; default: explode_bomb(); break; } if (v2 != v4) explode_bomb(); } int func(int inp) { int res; if (inp <= 1) { res = 1; } else { int v1 = func(inp - 1); res = v1 + func(inp - 2); } return res; } void phase_4(char *input) { int inp; if (sscanf(input, "%d", &inp) != 1) explode_bomb(); if (inp <= 0) explode_bomb(); int res = func(inp); if (res != 55) explode_bomb(); } char arr_123[16] = { 'i', 's', 'r', 'v', 'e', 'a', 'w', 'h', 'o', 'b', 'p', 'n', 'u', 't', 'f', 'g' }; void phase_5(char *input) { if (string_length(input) != 6) explode_bomb(); char data[7]; int i; for (i = 0; i < 6; i++) { data[i] = arr_123[(input[i] & 0xf)]; } data[6] = 0; if (strings_not_equal(data, "giants")) explode_bomb(); } struct node { int element; int unused; struct node *next; }; typedef struct node node; node node6 = { 0x1b0, 6, NULL }; node node5 = { 0x0d4, 5, &node6 }; node node4 = { 0x3e5, 4, &node5 }; node node3 = { 0x12d, 3, &node4 }; node node2 = { 0x2d5, 2, &node3 }; node node1 = { 0x0fd, 1, &node2 }; void phase_6(char *input) { int numbers[6]; read_six_numbers(input, numbers); int v2 = 0; for (v2 = 0; v2 < 6; v2++) { if ((unsigned int)(numbers[v2] - 1u) > 5u) explode_bomb(); int i; for (i = v2 + 1; i < 6; i++) { if (numbers[i] == numbers[v2]) explode_bomb(); } } node *nodes[6]; int v4 = 0; for (v4 = 0; v4 < 6; v4++) { node *tmp = &node1; int j; for (j = 1; j < numbers[v4]; j++) { tmp = tmp->next; } nodes[v4] = tmp; } node *v7; node *v13; v7 = v13 = nodes[0]; int v8; node *v9; for (v8 = 1; v8 < 6; v8++) { v9 = nodes[v8]; v7->next = v9; v7 = v9; } v9->next = NULL; node *v10 = v13; int v11 = 0; for (v11 = 0; v11 < 5; v11++) { if (v10->element < v10->next->element) explode_bomb(); v10 = v10->next; } } char input_string[1024]; char *read_line() { fgets(input_string, 80, stdin); input_string[strlen(input_string)-1] = '\0'; return &input_string[0]; } char username[1024]; void read_username() { fgets(username, 300, stdin); } int writen(int fd, char *buf, int count) { int so_far = 0; while (so_far < count) { int r = write(fd, buf, count); if (r < 0) { return r; } so_far += r; } } int writes(int fd, char *buf) { return writen(fd, buf, strlen(buf)); } int phases_defused = 0; void phase_defused() { phases_defused++; if (phases_defused == 6) { printf("Congratulations! You've defused the bomb! Submit your input!\n"); } printf("Automatically submitting flag...\n"); int clientfd; struct hostent *hp; struct sockaddr_in serveraddr; if ((clientfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) { printf("Could not submit the flag! Please submit it manually.\n"); return; } if ((hp = gethostbyname("picodemo.derig.org")) == NULL) { printf("Could not submit the flag! Please submit it manually.\n"); return; } bzero((char*)&serveraddr, sizeof(serveraddr)); serveraddr.sin_family = AF_INET; bcopy((char*)hp->h_addr_list[0], &serveraddr.sin_addr.s_addr, hp->h_length); serveraddr.sin_port = htons(8891); if (connect(clientfd, (const struct sockaddr *)&serveraddr, sizeof(serveraddr)) < 0) { printf("Could not submit the flag! Please submit it manually.\n"); return; } if (writes(clientfd, username) < 0) { printf("Could not submit the flag! Please submit it manually.\n"); return; } if (writes(clientfd, "1697c2e9c0a690a86737779923417cb5\n") < 0) { printf("Could not submit the flag! Please submit it manually.\n"); return; } int l = strlen(input_string); input_string[l] = '\n'; input_string[l+1] = '\0'; if (writes(clientfd, input_string) < 0) { printf("Could not submit the flag! Please submit it manually.\n"); return; } int res; read(clientfd, &res, sizeof(int)); close(clientfd); if (res != 0) printf("Flag accepted!\n"); else printf("Flag submitted but not accepted - maybe you have already solved this phase?\n"); } int main() { printf("Please enter your picoCTF account username, for automatic flag\n"); printf("submission.\n"); read_username(); printf("Welcome to my fiendish little bomb. You have 6 phases with\n"); printf("which to blow yourself up. Have a nice day!\n"); char *input = read_line(); phase_1(input); phase_defused(); printf("Phase 1 defused. How about the next one?\n"); input = read_line(); phase_2(input); phase_defused(); printf("That's number 2. Keep going!\n"); input = read_line(); phase_3(input); phase_defused(); printf("Halfway there!\n"); input = read_line(); phase_4(input); phase_defused(); printf("So you got that one. Try this one.\n"); input = read_line(); phase_5(input); phase_defused(); printf("Good work! On to the next...\n"); input = read_line(); phase_6(input); phase_defused(); }
C
#include<string.h> #include<limits.h> #include<pthread.h> extern char **environ; pthread_mutex_t env_mutex; static pthread_once_t init_done = PTHREAD_ONCE_INIT; static void thread_init(void){ pthread_mutexattr_t attr; pthread_mutexattr_init(&attr); pthread_mutexattr_settype(&attr,PTHREAD_MUTEX_RECURSIVE); pthread_mutex_init(&env_mutex,&attr); pthread_mytexattr_destroy(&attr); } int mygetenv_r(const char *name,char *buf,int buflen){ int len,oldlen; pthread_once(&init_done,thread_init); len=strlen(name); pthread_mutex_lock(&env_mutex); for(int i=0;environ[i]!=NULL;i++){ if((strncmp(name,environ[i],len)==0)&&(environ[i][len]=='=')){ oldlen = strlen(&environ[i][len+1]); if(oldlen >= buflen){ pthread_mutex_unlock(&env_mutex); return (ENOSPC); } strncpy(buf,&environ[i][len+1],oldlen); buf[oldlen]='\0'; pthread_mutex_unlock(&env_mutex); return (0); } } pthread_mutex_unlock(&env_mutex); return (ENOENT); }
C
#ifndef MALLOC_UTILS_H #define MALLOC_UTILS_H #define malloc_check_exit_on_error(m) \ { \ if(m == NULL) { \ perror("malloc"); \ exit(EXIT_FAILURE); \ } \ } #define malloc_free(m) \ { \ if(m) { \ free(m); \ m = NULL; \ } \ } #endif
C
#include <stdio.h> #include <math.h> int main(){ int i, k; for(i = 0; i < 1000000; i++){ for(k = 0;k < 1000000; k++){ if(k != i) if((pow(i, k) - pow(k,i)) == 0) printf("%d, %d\n", i, k); } } return 0; }
C
#include <stdio.h> #include <stdlib.h> #include "read_size.h" #include "ask_value.h" #include "copy_matrix_to_array.h" #include "calculate_percentile.h" //Read the size of a matrix(don't have to be squared matrix) from the console. //Allocate memory dynamically for the elements of the matrix, then read the elements. //Create a function which can calculate the n-th percentile of the elements. //Calculate the 80-th and the 90-th percentile. int main() { int matrix_size = read_size(); int line_size = read_size(); int** matrix = malloc(matrix_size * sizeof(int*)); for (int i = 0; i < matrix_size; ++i) { int* line = malloc(line_size * sizeof(int)); for (int j = 0; j < line_size; ++j) { line[j] = ask_value(i, j); } matrix[i] = line; } int* ordered_array = malloc(matrix_size * line_size * sizeof(int)); for (int i = 0; i < matrix_size; ++i) { for (int j = 0; j < line_size; ++j) { printf("%d ", matrix[i][j]); ordered_array[i * line_size + j] = matrix[i][j]; } printf("\n"); } for (int i = 0; i < matrix_size; ++i) { free(matrix[i]); } free(matrix); int swap; for (int i = 0 ; i < matrix_size * line_size - 1; i++) { for (int j = 0 ; j < matrix_size * line_size - i - 1; j++) { if (ordered_array[j] > ordered_array[j + 1]) { swap = ordered_array[j]; ordered_array[j] = ordered_array[j + 1]; ordered_array[j + 1] = swap; } } } for (int i = 0; i < matrix_size; ++i) { for (int j = 0; j < line_size; ++j) { printf("%d ", ordered_array[i * line_size + j]); } printf("\n"); } printf("The 90th percentile is: %d.", calculate_percentile(ordered_array, matrix_size * line_size, 90)); int percentile = 90; int element = (int)((float)matrix_size * line_size / 100.0 * (float)percentile) - 1; // printf("The 90th percentile is: %d.\n", ordered_array[element]); percentile = 80; element = (int)((float)matrix_size * line_size / 100.0 * (float)percentile) - 1; printf("The 80th percentile is: %d.\n", ordered_array[element]); free(ordered_array); return 0; }
C
#include <stdio.h> #include <string.h> #define MAX 100 void xstrcpy(char *, const char *); /* While passing values, keep your head cool.... because if you think we will pass something of the kind &'n' where n is anything, then you are wrong. REMEMBER: Whenever we are passing an array entirely, we are PASSING THE "ADDRESS OF THE ZEROTH ELEMENT", I.E here the address of the zeroth element of the char arrays. */ int main() { char yourString[MAX], myString[MAX], myString2[MAX]; printf("Enter Your String: "); gets(yourString); strcpy(myString, yourString); printf("ACCORDING TO C's FUNCTION ...."); printf("Your String is %s\n", yourString); printf("My String is %s\n", myString); printf("\n\n"); xstrcpy(myString2, yourString); printf("ACCORDING TO MY FUNCTION ...."); printf("Your String is %s\n", yourString); printf("My String is %s\n", myString2); return 0; } void xstrcpy(char *target, const char *source) { while (*source != '\0') { *target = *source; target++; source++; } *target = '\0'; }
C
#include <stdio.h> #include <stdlib.h> int main(void) { int n; double* score; double max = 0.0; double avg = 0.0; scanf_s("%d", &n); if (n > 1000) { return 0; } score = (double*)malloc(sizeof(double) * n); for (int i = 0; i < n; i++) { scanf_s("%lf", &score[i]); if (score[i] < 0.0 || score[i] > 100.0) { return 0; } if (score[i] > max) { max = score[i]; } } for (int i = 0; i < n; i++) { avg += score[i] / max * 100.0; } avg /= (double)n; printf("%.2lf", avg); free(score); return 0; }