language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
/*--------------------------------------------------------------------- * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> *----------------------------------------------------------------------*/ #include "kidi.h" #include "io_utils.h" #include <stdio.h> #include <stdlib.h> #include <string.h> struct song* init_song_struct(int initial_capacity) { /* This method should allocate enough memory for the song struct AND for initial_capacity events. All fields of the newly allocated song struct should be appropriately initialized. */ struct song* new_song = (struct song*)malloc(sizeof(struct song)); new_song->tick_length = 0; new_song->num_events = 0; new_song->event_array = (struct event*)malloc(sizeof(struct event) * initial_capacity); new_song->event_capacity = initial_capacity; return new_song; } int resize_song_struct(struct song* song, uint16_t new_size) { song->event_capacity = new_size; song->event_array = realloc(song->event_array, sizeof(struct event) * song->event_capacity); if (song->event_array == NULL) { fprintf(stderr, "Not enough memory to resize the song!\n"); return -1; } return 0; } /* Writes the given song data to the given file in binary format. PARAMETERS: FILE* file_ptr The file to write to song* song The song data to write to the file RETURN: 0 if okay, -1 if an error occurs */ int write_kidi_binary(FILE* file_ptr, struct song* song) { char* heading = "KThd"; uint32_t zero = 0; // Write the header binary fwrite(heading, sizeof(char), 4, file_ptr); write_le_uint16(file_ptr, song->tick_length); fwrite(&zero, sizeof(char), 4, file_ptr); // Write the even binaries int i; for (i = 0 ; i < (song->event_capacity) ; i++) { struct event curr_event = (song->event_array)[i]; write_le_uint16(file_ptr, curr_event.delta_time); fwrite(&(curr_event.event_type), sizeof(char), 1, file_ptr); fwrite(&(curr_event.channel), sizeof(char), 1, file_ptr); write_le_uint16(file_ptr, curr_event.frequency); fwrite(&(curr_event.velocity), sizeof(char), 1, file_ptr); } // Write the "done" meta-event uint8_t meta_type = 0xFF; uint8_t meta_name = 0x2F; fwrite(&zero, sizeof(char), 2, file_ptr); fwrite(&meta_type, sizeof(char), 1, file_ptr); fwrite(&meta_name, sizeof(char), 1, file_ptr); return 0; } /* Writes the given song data to the given file. PARAMETERS: FILE* file_ptr The file to write to song* song The song data to write to the file RETURN: 0 if okay, -1 if an error occurs */ int write_kidi_ascii(FILE* file_ptr, struct song* song) { fprintf(file_ptr, "%d\n", song->tick_length); int a; for (a = 0; a < (song->num_events) ; a++) { struct event curr_event = (song->event_array)[a]; fprintf(file_ptr, "%d ", curr_event.delta_time); if (curr_event.event_type == ON_EVENT) { fprintf(file_ptr, "on "); } else { fprintf(file_ptr, "off "); } fprintf(file_ptr, "%d %d %d\n", curr_event.channel, curr_event.frequency, curr_event.velocity); } return 0; } /* Reads the given kidi binary file and creates the equivalent song. PARAMETERS: FILE* file_ptr The pointer to the file to read; RETURN: struct song* A pointer to the song that is represented by that file */ struct song* read_kidi_binary(FILE* file_ptr) { int init_capac = 0; struct song* curr_song = init_song_struct(init_capac); char header[4]; uint32_t zero; fread(header, sizeof(char), 4, file_ptr); read_uint16(file_ptr, &(curr_song->tick_length)); fread(&zero, sizeof(char), 4, file_ptr); int event_counter = 0; while(0 == 0) { if (feof(file_ptr)) { break; } struct event* evt = (struct event*)malloc(sizeof(struct event)); read_uint16(file_ptr, &(evt->delta_time)); read_uint8(file_ptr, &(evt->event_type)); read_uint8(file_ptr, &(evt->channel)); // Break if the "done" meta event is found if (evt->channel == 0x2F) { break; } read_uint16(file_ptr, &(evt->frequency)); read_uint8(file_ptr, &(evt->velocity)); int curr_size = curr_song->event_capacity; resize_song_struct(curr_song, (curr_size+1)); (curr_song->event_array)[curr_size] = *evt; event_counter++; } curr_song->num_events = event_counter; return curr_song; } /* Give a file, this method read the KIDI data and creates a song object. PARAMETERS: FILE* file_ptr A pointer to the file to read from RETURN: song* A pointer to the song object that was created from the file */ struct song* read_kidi_ascii(FILE* file_ptr) { int init_capac = 0; struct song* curr_song = init_song_struct(init_capac); char* line = (char*)malloc(100 * sizeof(char)); // Read the tick_length from the first line fgets(line, 100, file_ptr); int tic = strtol(line, NULL, 10); curr_song->tick_length = tic; int event_counter = 0; while(fgets(line, 100, file_ptr) != NULL) { if (feof(file_ptr)) { break; } struct event* evt = (struct event*)malloc(sizeof(struct event)); char* tokens = (char*)malloc(32 * sizeof(char)); tokens = strtok(line, " \t"); evt->delta_time = strtol(tokens, NULL, 10); tokens = strtok(NULL, " \t"); if (strcmp(tokens, "on") == 0) { evt->event_type = ON_EVENT; } else { evt->event_type = OFF_EVENT; } tokens = strtok(NULL, " \t"); evt->channel = strtol(tokens, NULL, 10); tokens = strtok(NULL, " \t"); evt->frequency = strtol(tokens, NULL, 10); tokens = strtok(NULL, " \t"); evt->velocity = strtol(tokens, NULL, 10); int curr_size = curr_song->event_capacity; resize_song_struct(curr_song, (curr_size+1)); (curr_song->event_array)[curr_size] = *evt; event_counter++; } curr_song->num_events = event_counter; return curr_song; }
C
/** *@brief Ejercicio9 *@author Lucia Rivas Molina *@author Daniel Santo-Tomas Lopez *@date 31/03/2018 *@file ejercicio9.c */ #include <unistd.h> #include <sys/wait.h> #include <signal.h> #include <time.h> #include "semaforos.h" /** *@brief numero de cajas del supermercado */ #define CAJAS 5 /** *@brief numero de semaforos necesarios *Necesitamos un semaforo para el archivo de cada * caja y uno más para el archivo info.txt que guarda * la señal mandada y la caja que la envía */ #define SEMAFOROS CAJAS+1 /** *@brief numero de corbos a clientes que realiza cada caja */ #define OPERAC 50 /** *@brief establece un numero aleatorio entre 0 y 300 * para la escritura de los archivos clientesCaja.txt */ #define ALEAT aleat_num(0, 300) /** *@brief establece un numero aleatorio entre 0 y 5 * para los segundos del sleep de cada caja */ #define SECS aleat_num(1,5) /** *@brief key para los semaforos */ #define SEMKEY 75798 /** *@brief Devuelve un numero aleatorio entre inf y sup * En caso de pasar un numero negativo se cambia de signo * En caso de que sup sea menor inf se permutan *@param inf minimo numero aleatorio que puede salir *@param sup maximo numero aleatorio que puede salir *@return el numero aleatorio */ int aleat_num(int inf, int sup); /** *@brief Lee el numero guardado en el fichero archivo y lo * devuelve. En caso de error devuelve ERROR *@param archivo nombre del fichero a leer *@return el numero leido o ERROR */ int leer(char *archivo); /** *@brief Escribe el numero cantidad en el fichero archivo y * devuelve, en caso de error ERROR y si sale bien OK *@param archivo nombre del fichero a escribir *@param cantidad a escribir *@return OK o ERROR */ int escribir(char *archivo, int cantidad); /** *@brief Funcion capturadora de la señal. Si la señal capturada * es SIGUSR1 el padre retira 900 euros. Si la señal es SIGUSR2 * el padre retira todo el dinero pues el hijo ha terminado *@param signal señal que captura *@return void */ void captura(int signal); /** *@brief Funcion que vacía un archivo abriendolo con "w" y cerrandolo *@param archivo array de char que contiene el fichero a vaciar *@return ERROR o OK */ int vaciar(char *archivo); /** * En primer lugar, el hijo abre clientesCaja.txt y va leyendo lo que paga cada cliente, * guardándolo en dinero. Luego, hace un down del semaforo de cajaTotal.txt para reescribir el total * y el up. Si el total es <=1000, hace un down del semaforo de info.txt para escribir SIGUSR1 hace * el up, un kill y un sleep. Cuando ha terminado, sale del while, cierra el fichero clientesCaja.txt * y hace un down de info.txt para mandarle al padre SIGUSR2 y hace un exit. * *@brief Función que contiene toda la estructura de lo que realiza cada hijo *@param clientesCaja contiene clientesCaja.txt del que caja hijo lee lo que paga el cliente *@param cajaTotal contiene cajaTotal.txt donde cada hijo guarda su total sumado *@param info contiene info.txt donde cada hijo escribe la señal que manda al padre y que hjo es *@param i int que indica que hijo/caja es *@param semid el semaforo *@return ERROR en caso de error, sino OK */ int caja(char *clientesCaja, char *cajaTotal, char *info, int i, int semid); /** *@brief Main del ejercicio 9 *@return EXIT_FAILURE o EXIT_SUCCESS */ int main(void) { int dinero = 0, total = 0, aleat, semid, status, i, j, cont = 0, sennal, hijo; char clientesCaja[CAJAS][50]; /*Nombres de los ficheros donde se almacena el pago de clientes*/ char cajaTotal[CAJAS][50]; /*Nombres de los ficheros donde se almacena el total de la caja*/ char info[9] = "info.txt"; /*Fichero donde se almacena la informacion que envia la caja*/ unsigned short *sem; FILE *clientes[CAJAS]; /*Tantos files como hijos haya, cada uno para su clientesCaja.txt*/ FILE *fich; /*file para info.txt y para generar los cajaTotal.txt*/ pid_t pid[CAJAS]; time(NULL); /*Vaciamos el fichero info por si acaso tuviera información*/ if(vaciar(info) == ERROR){ perror("Error vaciando fichero"); exit(EXIT_FAILURE); } /*Creamos el nombre de los ficheros y generamos los números aleatorios*/ for(i = 0; i < CAJAS; i++){ /*Creamos el nombre de los ficheros que vamos a usar*/ sprintf(clientesCaja[i], "clientesCaja%d.txt", i+1); sprintf(cajaTotal[i], "cajaTotal%d.txt", i+1); /*Abrimos el de los clientes y escribimos 50 numeros aleatorios*/ clientes[i] = fopen(clientesCaja[i], "w"); fich = fopen(cajaTotal[i], "w"); if (!clientes[i] || !fich){ return ERROR; } fprintf(fich, "%d\n", 0); for(j = 0; j < OPERAC; j++){ aleat = ALEAT; fprintf(clientes[i], "%d\n", aleat); } if (fclose(clientes[i]) != 0 || fclose(fich) != 0) { perror("Error en el cierre de ficheros"); exit(EXIT_FAILURE); } } /*Creamos las señales*/ if (signal(SIGUSR1, captura) == SIG_ERR){ perror("Error en las sennales"); exit(EXIT_FAILURE); } if (signal(SIGUSR2, captura) == SIG_ERR){ perror("Error en las sennales"); exit(EXIT_FAILURE); } /* *Creamos e inicializamos los semáforos, uno para cada caja * y el último para el fichero info.txt */ if (Crear_Semaforo(SEMKEY, SEMAFOROS, &semid) == ERROR){ perror("Error en el semaforo"); exit(EXIT_FAILURE); } sem = (unsigned short*)malloc(sizeof(short)*(SEMAFOROS)); if(!sem){ Borrar_Semaforo(semid); perror("Error en el semaforo"); exit(EXIT_FAILURE); } for(i = 0; i < SEMAFOROS; i++){ sem[i] = 1; } if (Inicializar_Semaforo(semid, sem) == ERROR){ Borrar_Semaforo(semid); free(sem); perror("Error en el semaforo"); exit(EXIT_FAILURE); } printf("Abriendo tienda...\n"); printf("Hay %d cajas operativas con %d clientes cada una\nEsperando respuesta...\n\n", CAJAS, OPERAC); /*El proceso padre genera las cajas hijas y cada una realiza su operación*/ for(i = 0; i < CAJAS; i++){ /*En caso de error en el fork*/ if((pid[i] = fork()) < 0){ Borrar_Semaforo(semid); free(sem); perror("Error en el fork"); exit(EXIT_FAILURE); } /*En caso del padre la variable 'dinero' es leida de cajaTotal y 'total' es la suma de todo lo leido */ else if(pid[i] > 0){ /*Primero genera todas las cajas con el continue*/ if (i < CAJAS-1) continue; /*Una vez estás todas las cajas realiza un pause() y almacena en cont el numero de hijos terminados*/ while(cont < CAJAS){ pause(); /*Down del semaforo de info.txt*/ if(Down_Semaforo(semid, CAJAS, SEM_UNDO) == ERROR){ perror("Error en los semaforos"); Borrar_Semaforo(semid); free(sem); exit(EXIT_FAILURE); } /*Lee de info.txt que señal recibe y que hijo la manda*/ if(!(fich = fopen(info, "r"))){ perror("Error leyenfo info.txt"); Borrar_Semaforo(semid); free(sem); exit(EXIT_FAILURE); } while(fscanf(fich, "%d %d\n", &sennal, &hijo) != EOF){ switch (sennal) { /*En caso de que sea SIGUSR1 restamos 900 euros al dinero*/ case SIGUSR1: if(Down_Semaforo(semid, hijo, SEM_UNDO) == ERROR){ perror("Error en los semaforos"); Borrar_Semaforo(semid); free(sem); exit(EXIT_FAILURE); } printf("CAJA %d : supervisor retirando 900 euros\n\n", hijo+1); /*Lee el total de la caja del hijo*/ dinero = leer(cajaTotal[hijo]); if(total == ERROR){ perror("Error en la lectura de ficheros"); Borrar_Semaforo(semid); free(sem); exit(EXIT_FAILURE); } /*Le resta 900 euros al dinero de la caja del hijo y los suma al total*/ dinero -= 900; total += 900; /*Volver a escribir el dinero en cajaTotal.txt*/ if(escribir(cajaTotal[hijo], dinero) == ERROR){ perror("Error en la escritura de ficheros"); Borrar_Semaforo(semid); free(sem); exit(EXIT_FAILURE); } /*Up del semaforo del hijo*/ if(Up_Semaforo(semid, hijo, SEM_UNDO)== ERROR){ perror("Error en los semaforos"); Borrar_Semaforo(semid); free(sem); exit(EXIT_FAILURE); } break; /*En caso de SIGUSR2 sacamos todo el dinero del fichero pues ha acabado*/ case SIGUSR2: if(Down_Semaforo(semid, hijo, SEM_UNDO) == ERROR){ perror("Error en los semaforos"); Borrar_Semaforo(semid); free(sem); exit(EXIT_FAILURE); } printf("CAJA %d : supervisor retirando dinero\n\n", hijo+1); /*Lee el dinero de la caja del hijo*/ dinero = leer(cajaTotal[hijo]); if(dinero == ERROR){ perror("Error en la lectura de ficheros"); Borrar_Semaforo(semid); free(sem); exit(EXIT_FAILURE); } /*Suma el dinero al total y aumenta el contador de hijos terminados*/ total += dinero; cont++; /*Up del semaforo del hijo*/ if(Up_Semaforo(semid, hijo, SEM_UNDO)== ERROR){ perror("Error en los semaforos"); Borrar_Semaforo(semid); free(sem); exit(EXIT_FAILURE); } break; } } /*Cerramos info.txt, lo vaciamos y hacemos un up de info.txt*/ fclose(fich); if(vaciar(info) == ERROR){ perror("Error vaciando fichero"); Borrar_Semaforo(semid); free(sem); exit(EXIT_FAILURE); } if(Up_Semaforo(semid, CAJAS, SEM_UNDO) == ERROR){ perror("Error en los semaforos"); Borrar_Semaforo(semid); free(sem); exit(EXIT_FAILURE); } } /*Una vez todos los hijos han acabado*/ printf("El total ganado hoy es %d\n", total); break; } /*Los hijos leen su correspondiente clientesCaja y van sumando el dinero en cajaTotal*/ else{ if(caja(clientesCaja[i], cajaTotal[i], info, i, semid) == ERROR){ perror("Error en la lectura de ficheros del hijo"); free(sem); exit(EXIT_FAILURE); } free(sem); exit(EXIT_SUCCESS); } } /*Esperamos a los hijos*/ for(i = 0; i < CAJAS; i++){ waitpid(pid[i], &status, WUNTRACED | WCONTINUED); } /*Borramos los semaforos y liberamos memoria*/ if(Borrar_Semaforo(semid) == ERROR) { perror("Error borrando semaforos"); free(sem); exit(EXIT_FAILURE); } free(sem); exit(EXIT_SUCCESS); } /*FUNCIONES AUXILIARES*/ int aleat_num(int inf, int sup){ int aux; /*En caso de que alguno sea negativo los cambia a positivo*/ if(sup < 0) sup = -sup; if(inf < 0) inf = -inf; /*En caso de que sup sea menor que inf los permuta*/ if( sup < inf ){ aux = sup; sup = inf; inf = aux; } return inf+(rand()%(sup-inf+1)); } void captura(int sig){ switch (sig) { /*SIGUSR1 avisa de que ha superado los 1000 euros*/ case SIGUSR1: printf("Caja llena, informando al supervisor\n"); break; /*SIGUSR2 avisa de que ha terminado la caja*/ case SIGUSR2: printf("Caja terminada, informando al supervisor\n"); break; } return; } int leer(char *archivo){ FILE *f; int leido; if(!archivo) return ERROR; /*Abre el fichero archivo en modo lectura*/ if(!(f = fopen(archivo, "r"))) return ERROR; /*Lee el valor, cierra y devuelve el valor leido*/ fscanf(f, "%d", &leido); if(fclose(f) != 0) return ERROR; return leido; } int escribir(char *archivo, int cantidad){ FILE *f; if(!archivo) return ERROR; /*Abre el fichero archivo en modo sobreescritura*/ if(!(f = fopen(archivo, "w"))) return ERROR; /*Escribe el valor cantidad y cierra*/ fprintf(f, "%d\n", cantidad); if(fclose(f) != 0) return ERROR; return OK; } int vaciar(char *archivo){ FILE *f; if(!(f = fopen(archivo, "w"))) return ERROR; if(fclose(f) != 0) return ERROR; return OK; } int caja(char *clientesCaja, char *cajaTotal, char *info, int i, int semid){ FILE *clientes, *fich; int dinero = 0, total = 0; /*Control de errores*/ if(!clientesCaja || !cajaTotal || !info || i < 0){ return ERROR; } /*Abrimos clientesCaja.txt y lo leemos hasta que se acabe en el while*/ if(!(clientes = fopen(clientesCaja, "r"))) return ERROR; while(!feof(clientes)){ /*Down del semaforo de cajaTotal.txt del hijo correspondiente*/ if(Down_Semaforo(semid, i, SEM_UNDO) == ERROR) return ERROR; /*Cobra al cliente leyendo de clientesTotal.txt y lo suma al total*/ fscanf(clientes, "%d\n", &dinero); total = leer(cajaTotal); if(total == ERROR){ return ERROR; } total += dinero; printf("\tOperando caja %d total : %d\n", i+1, total); /*Volver a escribir el total en cajaTotal.txt*/ if(escribir(cajaTotal, total) == ERROR){ return ERROR; } /*Up del semaforo de cajaTotal.txt para el padre*/ if(Up_Semaforo(semid, i, SEM_UNDO) == ERROR) return ERROR; /*Si el total de dinero supera los 1000 mandamos una señal al padre*/ if (1000 <= total){ /*Down del fichero info.txt*/ if(Down_Semaforo(semid, CAJAS, SEM_UNDO) == ERROR) return ERROR; if(!(fich = fopen(info, "a"))) return ERROR; /*Escribimos en info.txt la señal que enviamos y el hijo que somos*/ fprintf(fich, "%d %d\n", SIGUSR1, i); fclose(fich); /*Mandamos la señal al padre y hacemos un up de info.txt*/ kill(getppid(), SIGUSR1); if(Up_Semaforo(semid, CAJAS, SEM_UNDO) == ERROR) return ERROR; } /*Dormimos al proceso un valor aleatorio*/ sleep(SECS); } /*Cerramos el fichero de clientesTotal.txt y down de info.txt*/ fclose(clientes); if(Down_Semaforo(semid, CAJAS, SEM_UNDO) == ERROR) return ERROR; /*Escribimos en info.txt la señal y el hijo*/ if(!(fich = fopen(info, "a"))) return ERROR; fprintf(fich, "%d %d\n", SIGUSR2, i); fclose(fich); /*Mandamos la señal al padre, hacemos el up de info y hace un exit*/ kill(getppid(), SIGUSR2); if(Up_Semaforo(semid, CAJAS, SEM_UNDO) == ERROR) return ERROR; return OK; }
C
#include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <string.h> #define mf_printf printf #define mf_read read #define mf_fprintf fprintf #define mf_malloc malloc #define mf_free free #define STACK_SIZE 256 #define MEMORY_SIZE 65536 typedef long cell_t; cell_t *stack; void *memory, *here, *latest; unsigned int sp = 0; char word[256]; unsigned char word_len=0; unsigned int base = 10; enum {IMMEDIATE, COMPILE} state = IMMEDIATE; #define F_IMMED 0x80 #define F_HIDDEN 0x20 #define F_LENMASK 0x1f int is_sep(char c) { return c == ' ' || c == '\n' || c == '\r'; } static int get_next() { ssize_t result; char c; word_len = 0; while(1) { result = mf_read(STDIN_FILENO, &c, 1); if(result <= 0) return 0; if(is_sep(c) && word_len > 0) { word[word_len] = 0; return 1; } else word[word_len++] = c; if(word_len == 255) { mf_fprintf(stderr, "Error : word too long\n"); word_len = 0; return 1; } } } int push(cell_t c) { if(sp >= STACK_SIZE - 1) { mf_fprintf(stderr, "Error : stack overflow\n"); return 0; } stack[sp++] = c; return 0; } cell_t pop() { if(sp == 0) { mf_fprintf(stderr, "Error : stack underflow\n"); return 0; } return stack[--sp]; } void print_stack() { int i; mf_printf("<%d> ", sp); for(i = 0; i < sp; i++) mf_printf("%ld ", stack[i]); mf_printf("\n"); } void dot() { mf_printf("%ld ", pop()); } void add() { cell_t a, b; b = pop(); a = pop(); push(a + b); } void sub() { cell_t a, b; b = pop(); a = pop(); push(a - b); } void mul() { cell_t a, b; b = pop(); a = pop(); push(a * b); } void divide() { cell_t a, b; b = pop(); a = pop(); push(a / b); } void emit() { char c = pop(); write(STDOUT_FILENO, &c, 1); } void _here() { push((cell_t)here); } void lbrac() { state = IMMEDIATE; } void rbrac() { state = COMPILE; } void create() { unsigned char len = pop(); char* name = (char*)pop(); *((cell_t*)here) = (cell_t)latest; here += sizeof(cell_t); *((char*)here) = len; here += 1; memcpy(here, name, len); here += len; } void *find(char *name, int len) { if(!strcmp(name, ".s")) return print_stack; else if(!strcmp(name, ".")) return dot; else if(!strcmp(name, "+")) return add; else if(!strcmp(name, "-")) return sub; else if(!strcmp(name, "*")) return mul; else if(!strcmp(name, "/")) return divide; else if(!strcmp(name, "emit")) return emit; else if(!strcmp(name, "create")) return create; else if(!strcmp(name, "here")) return _here; return NULL; } int main(int argc, char *argv[]) { void *word_addr; char *end_ptr; long l; mf_printf("maxForth\n"); stack = (cell_t*)mf_malloc(sizeof(cell_t) * STACK_SIZE); if(stack == NULL) { mf_fprintf(stderr, "Not enough memory\n"); return 1; } mf_printf("cell_size : %ld bytes\n", sizeof(cell_t)); mf_printf("stack size : %d cells\n", STACK_SIZE); memory = mf_malloc(MEMORY_SIZE); here = memory; latest = NULL; if(memory == NULL) { mf_fprintf(stderr, "Not enough memory\n"); return 1; } mf_printf("memory : %d bytes\n", MEMORY_SIZE); while(get_next()) { word_addr = find(word, word_len); if(word_addr == NULL) { l = strtol(word, &end_ptr, base); if(end_ptr - word == word_len) push(l); else mf_fprintf(stderr, "Error : undefined word\n"); } else ((void (*)(void))word_addr)(); print_stack(); } return 0; }
C
// Reset j for next cycle. float j = 0.0; // Counter to know in which delta_time section we are on the xtdata // array. int arrcount = 0; // Temporal storage for the number of packets seen. int numpktseen = 0; // While the added time is less than the total time and we haven't // run out of packets, run this cycle to see how many packets we see // per delta_time section. while (arrcount < datapoints && timecnt < packets && j <= time_int ) { // Add the next timedata to j and pass to the next packet time // diff. j += timedata[timecnt++]; // We are seeing one new packet, so add it to our temporal // storage. numpktseen++; if (j >= (arrcount+1)*(delta_time)) { // If we've surpassed one of the delta_times, fill the // information for the delta_time section. xtdata[arrcount++] = numpktseen -1; // Boolean variables short int passed = 0; short int carry = 1; // Since we're not sure if the packet jumps through too // many sections, we check for it, filling each // sectioned passed with 0, except the first one which has // at least one. while (arrcount < datapoints && j > (arrcount)*(delta_time)) { if (passed == 0) { xtdata[arrcount++] = 1; passed = 1; carry = 0; } else { xtdata[arrcount++] = 0; } } // Finally we reset the temporal storage for the next cycle. if (carry == 1) { numpktseen = 1; } else { numpktseen = 0; } } }
C
/** * \file * * \brief Empty user application template * */ /* * Include header files for all drivers that have been imported from * Atmel Software Framework (ASF). */ /* * Support and FAQ: visit <a href="http://www.atmel.com/design-support/">Atmel Support</a> */ #include <asf.h> #include <util/delay.h> //this method makes a loop at port D void ledLoop(); void wait(int); int main (void) { /* Insert system clock initialization code here (sysclk_init()). */ board_init(); DDRD = 0b11111111; //set port D as output while(1){ ledLoop(); } } void ledLoop(){ for(int i = 0; i <9; i++) { PORTD = (1<<i); wait(500); } } void wait(int milliseconds){ int i = 0; for(; i < milliseconds; i++) _delay_ms(1); }
C
#include <stdio.h> #include <stdlib.h> #include <mpi.h> #include <time.h> #include <sys/time.h> #include <unistd.h> int main(int argc, char *argv[]){ int *sndbuf, *rcvbuf, N, i, rank, size, *res, temp; double start, finish; MPI_Status stat; struct timeval st, fn; MPI_Init(&argc, &argv); if(argc<2){ printf("Usage example :\n\te.g., mpirun -np 4 -hostfile hosts ./prefix_sum_scan 4\n"); return -1; } MPI_Comm_rank(MPI_COMM_WORLD, &rank); MPI_Comm_size(MPI_COMM_WORLD, &size); sscanf(argv[1], "%d", &N); sndbuf=(int*)calloc(N, sizeof(int)); rcvbuf=(int*)calloc(N, sizeof(int)); res=(int*)calloc(N, sizeof(int)); start=MPI_Wtime(); gettimeofday(&st, NULL); if(rank==0){ srand(time(NULL)); for(i=0; i<N; i++){ sndbuf[i]=rand()%10; printf("%d ", sndbuf[i]); } printf("\n"); } temp=0; for( i=0; i<=N/size; i++){ sndbuf[i*size]+=temp; MPI_Scatter(sndbuf+i*size, 1, MPI_INT, rcvbuf+i, 1, MPI_INT, 0, MPI_COMM_WORLD); MPI_Scan(rcvbuf+i, res+i, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD); if(rank==size-1) MPI_Send(res+i, 1, MPI_INT, 0, 0, MPI_COMM_WORLD); else if(rank==0){ MPI_Recv(&temp, 1, MPI_INT, size-1, 0, MPI_COMM_WORLD, &stat); } MPI_Barrier(MPI_COMM_WORLD); } finish=MPI_Wtime(); gettimeofday(&fn, NULL); for( i=0; i<N/size; i++){ printf("result[%3d]-%3d: %6d ( %ld.%06ld )\n", rank , i, res[i], fn.tv_sec-st.tv_sec, fn.tv_usec-st.tv_usec); // printf("%d %d\n", fn.tv_sec - st.tv_sec, fn.tv_usec - st.tv_usec); } if( rank < N%size ) printf("result[%3d]-%3d: %6d ( %ld.%06ld )\n", rank , i, res[i], fn.tv_sec-st.tv_sec, fn.tv_usec-st.tv_usec); // printf("result[%d]-%d: %d\n", rank, i, res[i]); // free(sndbuf); // free(rcvbuf); MPI_Finalize(); return 0; }
C
#include <stdio.h> #include <math.h> #include <stdlib.h> int main(int argc, char *argv[]) { int n = atoi(argv[1]); int m = n; int result = 0; int a; while(n!=0){ a = n%10; n = n/10; result = result + (a*a*a); } // printf("%d number %d result\n",m,result); if(result == m){ printf("Armstrong Number\n"); } else{ printf("Not Armstrong\n"); } return 0; }
C
#include "fatal.h" #define MaxDegree 100 #define Max(x, y) ((x) > (y) ? (x) : (y)) typedef struct { int CoeffArray[MaxDegree + 1]; int HighPower; } * Polynomial; // 初始化 void ZeroPolynomial(Polynomial Poly) { int i; for (i = 0; i <= MaxDegree; i++) Poly->CoeffArray[i] = 0; Poly->HighPower = 0; } //add void AddPolynomial(const Polynomial Poly1, const Polynomial Poly2, Polynomial PolySum) { ZeroPolynomial(PolySum); PolySum->HighPower = Max(Poly1->HighPower, Poly2->HighPower); for (int i = PolySum->HighPower; i >= 0; i--) PolySum->CoeffArray[i] = Poly1->CoeffArray[i] + Poly2->CoeffArray[i]; } //multiply void MultPolynomial(const Polynomial Poly1, const Polynomial Poly2, Polynomial PolyProd) { ZeroPolynomial(PolyProd); PolyProd->HighPower = Poly1->HighPower + Poly2->HighPower; if (PolyProd->HighPower > MaxDegree) Error("Exceeded array size"); else { for (int i = 0; i <= Poly1->HighPower; i++) for (int j = 0; j <= Poly2->HighPower; j++) PolyProd->CoeffArray[i + j] += Poly1->CoeffArray[i] * Poly2->CoeffArray[j]; } } void PrintPoly(const Polynomial Q) { int i; for (i = Q->HighPower; i > 0; i--) printf("%dx^%d + ", Q->CoeffArray[i], i); printf("%d\n", Q->CoeffArray[0]); } int main() { Polynomial P, Q; P = malloc(sizeof(*P)); Q = malloc(sizeof(*Q)); P->HighPower = 1; P->CoeffArray[0] = 1; P->CoeffArray[1] = 1; MultPolynomial(P, P, Q); PrintPoly(Q); // MultPolynomial( Q, Q, P ); AddPolynomial(P, P, Q); PrintPoly(Q); }
C
#include<stdio.h> int main() { int somme,i,nbr,test; printf("Voulez-vous tester la perfection d'un nombre ?(1=oui, 2=non)"); scanf("%d",&test); while(test != 2) { somme=0; printf("Entrez un entier : "); scanf("%d",&nbr); for(i=1;i<nbr;i++) { if(nbr%i==0) somme+=i; } if(somme==nbr) printf("C'est un nombre parfait\n"); else printf("Ce n'est pas un nombre parfait\n"); printf("Voulez-vous tester la perfection d'un autre nombre ?(1=oui, 2=non)"); scanf("%d",&test); } return 0; }
C
/*heading : Linear Search */ /*Details : Program to search for a record from a given list of records using linear search*/ #include <stdio.h> #include <conio.h> #include <string.h> typedef struct student { int rollno; char name[20]; int marks; }student; int search(student st[],int rollno,int n); void print(student st[],int n); void read(student st[],int n); void main() { student st[30]; int n,i,op,position,rollno; clrscr(); do{ flushall(); printf("\n\n1)create\n2)search\n3)print\n4)quit"); printf("\nEnter Your Choice:"); scanf("%d",&op); switch(op) { case 1: printf("\nEnter No. of student:"); scanf("%d",&n); read(st,n); break; case 2: printf("\nenter rollno:"); scanf("%d",&rollno); position=search(st,rollno,n); if(position==-1) printf("\nnot found"); else { printf("\n found at location=%d",position+1); printf("\n %s\t%d\t%d",st[position].name,st[position].rollno,st[position].marks); } break; case 3: print(st,n); break; } }while(op!=4); } int search(student st[],int rollno,int n) { int i; for(i=0;i<n;i++) if(rollno==st[i].rollno) return(i); return(-1); } void print(student st[],int n) { int i; for(i=0;i<n;i++) printf("\n%20s%5d%5d",st[i].name,st[i].rollno,st[i].marks); } void read(student st[],int n) { int i; for(i=0;i<n;i++) { printf("\n enter data(name(single word) rollno marks:"); scanf("%s%d%d",st[i].name,&st[i].rollno,&st[i].marks); } } /* *** OUTPUT *** 1)create 2)search 3)print 4)quit Enter Your Choice:1 Enter No. of student:2 enter data(name(single word) rollno marks: Abhi 1 80 enter data(name(single word) rollno marks:Rahul 2 85 1)create 2)search 3)print 4)quit Enter Your Choice:3 Abhi 1 80 Rahul 2 85 1)create 2)search 3)print 4)quit Enter Your Choice:2 enter rollno:1 found at location=1 Abhi 1 80 1)create 2)search 3)print 4)quit Enter Your Choice:2 enter rollno:3 not found 1)create 2)search 3)print 4)quit Enter Your Choice:4 */
C
#include<stdio.h> int main(){ int a =4,b=5; printf("Sum of %d and %d is %d\n" ,a,b,a+b); int g = 34,h=59; printf("Sum of %d and %d is %d",g,h,g+h); return 0; }
C
#include <stdlib.h> #include <string.h> #include <stdio.h> #include <ctype.h> #include <syslog.h> #include "stringlibs.h" int count_char_in_str(char *str, char find) { int count = 0; int i = 0; if (str == NULL) return count; for (i = 0; str[i]; i++) { if (str[i] == find) count++; } return count; } char *replace_char(char *str, char orig, char rep) { int i = 0; for (i = 0; str[i]; i++) { if (str[i] == orig) str[i] = rep; } return str; } char *replace_str(const char *str, const char *find, const char *rep) { int count = 0; const char *ins = str, *tmp = NULL; char *ret = NULL; const size_t len_find = strlen(find), len_rep = strlen(rep); for (count = 0; 0 != (tmp = strstr(ins, find)); ++count) ins = tmp + len_find; char *tmp2 = ret = (char*) malloc(strlen(str) + (len_rep - len_find) * count + 1); if (!ret) return NULL; while (count--) { ins = strstr(str, find); const size_t cp_size = ins - str; tmp2 = strncpy(tmp2, str, cp_size) + cp_size; tmp2 = strcpy(tmp2, rep) + len_rep; str += cp_size + len_rep; } strcpy(tmp2, str); return ret; } char *extract_str(char *str, const char start, const char end) { int len = 0; int write = -1; int i = 0; int j = 0; for (i = 0; str[i]; i++) { if (write == -1 && i > 0 && str[i-1] == start) write = 0; if (write == 0 && str[i] == end) write = 1; if (write == 0) len++; } char *newstr = (char *)malloc(len+1); write = -1; for (i = 0; str[i]; i++) { if (write == -1 && i > 0 && str[i-1] == start) write = 0; if (write == 0 && str[i] == end) write = 1; if (write == 0) newstr[j++] = str[i]; } newstr[j] = '\0'; return newstr; } char **split_str(char *str, const char delimiter) { int num_elems = count_char_in_str(str, delimiter); if (num_elems == 0) num_elems = 1; else num_elems += 2; char **tokenArray = (char **) malloc(sizeof(char *) * num_elems); int count = 1; int i = 0; tokenArray[0] = NULL; if (str == NULL) return tokenArray; tokenArray[0] = &str[0]; tokenArray[1] = NULL; for (i = 0; str[i]; i++) { if (str[i] == delimiter) { str[i] = '\0'; if (str[i+1]) { tokenArray[count] = &str[i+1]; tokenArray[count+1] = NULL; count++; } } } return tokenArray; }
C
/** * \file Thread.h * \brief Thread/Event queue functionality */ /** * @addtogroup Module Name * @{ */ #ifndef THREAD_H #define THREAD_H #include "Internal.h" /******************************************************************* * MACRO DEFINITIONS ******************************************************************/ #define Thread_send_event(thread, event, option ) \ (Thread_send_event_ex(thread, event, NULL, 0,option)) /******************************************************************* * TYPE DEFINITIONS ******************************************************************/ typedef struct { U32 bufferId; /**< Buffer to operate on */ } T_EVENT_BUFFER; typedef enum { CFG_SET_MODE=0, CFG_MAX } T_CFG; typedef struct { union { const t_base_cfg *P_MODE; const void * P_CFG; }cfg; T_CFG cfg_type; void (*completion_callback)(void *); void * p_completion_callback_data; } T_EVENT_CFG; typedef struct { void (*completion_callback)(void *p_data); void *p_data; } T_EVENT_COMPLETION; typedef struct { void *scheduler; U32 tag; } T_SCHEDULER_EVENT; /** * \brief A list of all possible thread events */ typedef enum { THREAD_EVENT_TIMEOUT, THREAD_EVENT_SET_CFG, THREAD_EVENT_SCHED_RUN, THREAD_EVENT_SCHED_GRANT, THREAD_CLOSE, THREAD_GET_STATE, THREAD_EVENT_MAX } T_THREAD_EVENT_TYPE; /** * \brief GET STATE */ typedef struct { void (*completion_callback)(U32); }T_GET_STATE_EVENT; /** * \brief A list of all possible thread event send options */ typedef enum { THREAD_EVENT_SEND_OPTION_DO_NOT_OR, /**< Always send */ THREAD_EVENT_SEND_OPTION_OR, /**< Send only if there is no event of same type queued already */ }T_THREAD_EVENT_SEND_OPTION; /** * \brief Thread event */ typedef struct { T_THREAD_EVENT_TYPE event; /**< event ID */ /** \brief Union of all possible thread events */ union { U32 data; /**< Data */ void *ptr; /**< data */ /* Buffer related information */ T_EVENT_BUFFER buffer_event; /* used by events which flush the export buffer */ T_EVENT_COMPLETION export_event; /* used by scheduler events */ T_SCHEDULER_EVENT scheduler_event; /* HW Configuration */ T_EVENT_CFG cfg_event; /* State info */ T_GET_STATE_EVENT state; } parameters; } T_THREAD_EVENT; /** * \brief Thread event information */ typedef struct { T_THREAD_EVENT event; /**< event structure */ BOOL processed; /**< Indicates that the event has been processed. */ } T_THREAD_EVENT_ENTRY; /** * \brief Thread event callback */ typedef BOOL (*T_THREAD_CB)(T_THREAD_EVENT *event); typedef T_THREAD_CB *T_THREAD_CB_LIST; typedef enum { THREAD_STATE_INIT = 0, /**< Thread is in init state */ THREAD_STATE_RUN, /**< Thread is running */ THREAD_STATE_SUSPEND /**< Thread is suspended */ } T_THREAD_STATE; typedef U16 T_THREAD_EVENT_INDEX; /** * \brief Application Service Thread */ typedef struct { /** Static information */ /** \brief thread_start function is executed in the thread context * (NULL if not available) before the thread enters it's main loop */ void (*thread_start)(void); /** \brief Event handler, NULL terminated array */ T_THREAD_CB_LIST event_handlers; const char *thread_name; const char *thread_event_name; /** Runtime Information */ T_THREAD_STATE state; /**< Thread execution state */ OsEvent event_id; /**< Event ID used for task */ OsThread event_thread_id; /**< Thread id for event task */ /**< Flag used for checking T_THREAD_EVENT_TYPE already queued or not */ BOOL thread_event_already_queued[THREAD_EVENT_MAX]; spinlock_t event_lock; /**< Spinlock for event queue */ /* circular thread event queue */ T_THREAD_EVENT_INDEX thread_event_wr; /**< Writer location */ T_THREAD_EVENT_INDEX thread_event_rd; /**< Reader location */ T_THREAD_EVENT_ENTRY thread_event[MAX_THREAD_EVENT_ENTRIES]; /**< thread event queue */ } T_THREAD; /******************************************************************* * FUNCTION PROTOTYPES ******************************************************************/ T_RESULT Thread_create(T_THREAD *thread); T_RESULT Thread_close(T_THREAD *thread); T_RESULT Thread_send_event_ex(T_THREAD *thread, T_THREAD_EVENT_TYPE event, void *data, U32 size, T_THREAD_EVENT_SEND_OPTION option); #endif /* THREAD_H */ /** @} */
C
#include "AVLArtigos.h" NodoAVL inserirArtigoAVL(NodoAVL av, int ano, int naut, int *ctr) { NodoAVL aux; if(!av) { aux = (NodoAVL)malloc(sizeof(NNodoAVL)); aux->data = ano; aux->nartigos = 1; aux->la = criaArtigoLL(NULL, naut); aux->balance = 0; aux->esq = NULL; aux->dir = NULL; *ctr=1; av=aux; } else { if(av->data == ano) { av->nartigos++; av->la = insereArtigoLL(av->la,naut); } else { if(av->data > ano) { av->esq = inserirArtigoAVL(av->esq, ano, naut, ctr); if(*ctr) { switch(av->balance) { case (-1) : av = balanceEsq(av,ctr); break; break; case (0) : av->balance = (-1); break; case (1) : av->balance = (0); *ctr=0; break; } } } else { av->dir = inserirArtigoAVL(av->dir, ano, naut, ctr); if(*ctr) { switch(av->balance) { case (-1) : av->balance = 0; *ctr=0; break; case (0) : av->balance = (1); break; case (1) : av = balanceDir(av,ctr); break; } } } } } return av; } NodoAVL balanceEsq (NodoAVL raiz, int* aum) { NodoAVL ls = raiz->esq ; NodoAVL rs ; switch (ls->balance) { case (-1) : raiz->balance = ls->balance = 0 ; raiz = roda_dir(raiz) ; break ; case (0) : break ; case (1) : rs = ls->dir ; switch (rs->balance) { case (1) : raiz->balance = 0 ; ls->balance = -1 ; break ; case (0) : raiz->balance = ls->balance = 0 ; break ; case (-1) : raiz->balance = 1 ; ls->balance = 0 ; break ; } rs->balance = 0 ; raiz->esq = roda_esq(ls) ; raiz = roda_dir(raiz) ; *aum = 0 ; } return raiz ; } NodoAVL balanceDir (NodoAVL raiz , int* aum) { NodoAVL rs = raiz->dir ; /** sub-árvore direita da raiz **/ NodoAVL ls ; switch (rs->balance) { case 1 : raiz->balance = rs->balance = 0 ; raiz = roda_esq(raiz) ; *aum = 0 ; break ; case 0 : break ; /** Já está balanceada **/ case (-1) : ls = rs->esq ; /** sub-árvore esquerda de rs **/ switch (ls->balance) { case 1 : raiz->balance = -1 ; rs->balance = 0 ; break ; case 0 : raiz->balance = rs->balance = 0 ; break ; case -1 : raiz->balance = 0 ; rs->balance = 1 ; break ; } ls->balance = 0 ; raiz->dir = roda_dir(rs) ; raiz = roda_esq(raiz) ; *aum = 0 ; } return raiz ; } NodoAVL roda_esq (NodoAVL raiz) { NodoAVL a = raiz ; if (raiz && raiz->dir) { a = raiz->dir ; raiz->dir = a->esq ; a->esq = raiz ; } return a ; } NodoAVL roda_dir (NodoAVL raiz) { NodoAVL a = raiz ; if (raiz && raiz->esq) { a = raiz->esq ; raiz->esq = a->dir ; a->dir = raiz ; } return a ; } /*void lista(NodoAVL a) { if(a) { lista(a->esq); printf("%d\n", a->data); printf("Numero de artigos: %d\n", a->nartigos); listarLL(a->la); lista(a->dir); } */
C
#include <stdio.h> #include <stdlib.h> int main(void){ int a, b, c, menor1, menor2; scanf("%d %d %d", &a, &b, &c); menor1 = (a < b && a < c)? a : b; menor2 = (b < c && b < a)? b : c; menor1 = (menor1 < menor2)? menor1 : menor2; printf("%d", menor1); return 0; }
C
#include <stdio.h> int main(void) { int a[20],num=0; double ave; imt i,j; for(i=0;a[i-1]!=-1;i++) scanf("%d",&a[i]); for(j=0;j<i;j++) num+=a[j]; ave=num/1.0/i; printf("%d %.2lf\n",num,ave); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* parse.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: mqian <mqian@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/03/28 17:32:39 by mqian #+# #+# */ /* Updated: 2019/04/16 20:14:40 by mqian ### ########.fr */ /* */ /* ************************************************************************** */ #include "../includes/fillit.h" /* ** piece parser has two parts, the actual parser which takes reads in the ** values and checks for bad input, and the second portion of the function ** which assesses the validity of each piece after its been stored into an ** array which holds all the pieces. */ int piece_reader(char **pieces, int fd, int *pc) //only reads and stores functions from input //27 lines { //it checks for bad line length, and incorrect number of lines in file int ret; int linecount; char *line; int totalcount; linecount = 0; totalcount = 0; while ((ret = get_next_line(fd, &line) > 0)) { if (linecount++ < 4) { piece_reader_helper(&*pieces, &*pc, &line); totalcount++; if (linecount == 4) *pc = *pc + 1; } else //linecount is "==" 5 its on 5th empty line, but value is still technically 4 { linecount = 0; //don't process empty line totalcount++; } } ft_memdel((void**)&line); return ((totalcount / 5 != (*pc - 1)) ? 0 : 1); } int is_valid_input(char **pieces, int *pc) { int i; int j; int dot_hash[2]; i = 0; while (i < *pc) { array_zero(dot_hash); j = 0; while (pieces[i][j] != '\0') { if (pieces[i][j] == '#') dot_hash[1]++; else if (pieces[i][j] == '.') dot_hash[0]++; j++; } if (dot_hash[0] != 12 || dot_hash[1] != 4) return (0); i++; } return (1); } int is_valid_piece(char **pieces, int *pc) { int i; int j; int borders; int len; i = 0; while (i < *pc) { borders = 0; j = 0; len = ft_strlen(pieces[i]); while (j < len) { check_adjacent(&*pieces, &i, &j, &borders); j++; } if ((borders / 2) < 3) //a piece aint valid, return 0 return (0); i++; } return (1); } void top_left_justify(char **pieces) //cycle through validated pieces, and mod index and subtract to 0 to get //GOOD // left justify, and add +4 to top justify //19 lines { int i; int j; int count; int values[4]; i = 0; while (pieces[i] != 0) { j = 0; count = 0; while (pieces[i][j]) { if (pieces[i][j] == '#') values[count++] = j; j++; } top_left_helper(values, pieces[i], i); i++; } } int parse_and_retrieve(char **pieces, int fd) { int ret; int piececount; piececount = 0; if (!(piece_reader(&*pieces, fd, &piececount))) { ft_putendl("error"); return (0); } if (!(ret = is_valid_input(&*pieces, &piececount))) { ft_putendl("error"); return (0); } if (!(ret = is_valid_piece(&*pieces, &piececount))) { ft_putendl("error"); return (0); } top_left_justify(&*pieces); return (1); }
C
/* * main.c * * Created on: 17 dec. 2020 * Author: Linus */ int main(){ int n = scanfs(); if (n % 2 == 0){ printf("%s", "Bob"); } else printf("%s", "Alice"); return 0; }
C
// Example C program for delay_until instruction. // Michael Zimmer (mzimmer@eecs.berkeley.edu) #include "flexpret_timing.h" #include "flexpret_io.h" int main(void) { int t1 = get_time(); debug_string(itoa_hex(t1)); debug_string("\n"); t1 += 10000; // 1000 cycles set_compare(t1); delay_until(); int t2 = get_time(); debug_string(itoa_hex(t2)); debug_string("\n"); return (t2 > t1); }
C
/* * DIO.c * * Created: 2/27/2021 8:55:16 AM */ #include "DIO.h" void DIO_SetDirection(Uint8t pin, Uint8t direction) { Uint8t port = pin / 8; Uint8t pins = pin % 8; switch(direction) { case DIO_PIN_INPUT: switch (port) { case DIO_PORTA: CLR_BIT(DDRA, pins); break; case DIO_PORTB: CLR_BIT(DDRB, pins); break; case DIO_PORTC: CLR_BIT(DDRC, pins); break; case DIO_PORTD: CLR_BIT(DDRD, pins); break; } break; case DIO_PIN_OUTPUT: switch (port) { case DIO_PORTA: SET_BIT(DDRA, pins); break; case DIO_PORTB: SET_BIT(DDRB, pins); break; case DIO_PORTC: SET_BIT(DDRC, pins); break; case DIO_PORTD: SET_BIT(DDRD, pins); break; } break; } } void DIO_SetValue(Uint8t pin, Uint8t state) { Uint8t port = pin / 8; Uint8t pins = pin % 8; switch(state) { case DIO_PIN_LOW: switch (port) { case DIO_PORTA: CLR_BIT(PORTA, pins); break; case DIO_PORTB: CLR_BIT(PORTB, pins); break; case DIO_PORTC: CLR_BIT(PORTC, pins); break; case DIO_PORTD: CLR_BIT(PORTD, pins); break; } break; case DIO_PIN_HIGH: switch (port) { case DIO_PORTA: SET_BIT(PORTA, pins); break; case DIO_PORTB: SET_BIT(PORTB, pins); break; case DIO_PORTC: SET_BIT(PORTC, pins); break; case DIO_PORTD: SET_BIT(PORTD, pins); break; } break; } } Uint8t DIO_ReadValue(Uint8t pin) { Uint8t port = pin / 8; Uint8t pins = pin % 8; Uint8t val = 0; switch(port) { case DIO_PORTA: val = GET_BIT(PINA, pins); break; case DIO_PORTB: val = GET_BIT(PINB, pins); break; case DIO_PORTC: val = GET_BIT(PINC, pins); break; case DIO_PORTD: val = GET_BIT(PIND, pins); break; } return val; } void DIO_SetPin_Direction(Uint8t port, Uint8t pin, Uint8t direction) { switch(direction) { case DIO_PIN_INPUT: switch (port) { case DIO_PORTA: CLR_BIT(DDRA, pin); break; case DIO_PORTB: CLR_BIT(DDRB, pin); break; case DIO_PORTC: CLR_BIT(DDRC, pin); break; case DIO_PORTD: CLR_BIT(DDRD, pin); break; } break; case DIO_PIN_OUTPUT: switch (port) { case DIO_PORTA: SET_BIT(DDRA, pin); break; case DIO_PORTB: SET_BIT(DDRB, pin); break; case DIO_PORTC: SET_BIT(DDRC, pin); break; case DIO_PORTD: SET_BIT(DDRD, pin); break; } break; } } void DIO_SetPin_Value(Uint8t port, Uint8t pin, Uint8t state) { switch(state) { case DIO_PIN_LOW: switch (port) { case DIO_PORTA: CLR_BIT(PORTA, pin); break; case DIO_PORTB: CLR_BIT(PORTB, pin); break; case DIO_PORTC: CLR_BIT(PORTC, pin); break; case DIO_PORTD: CLR_BIT(PORTD, pin); break; } break; case DIO_PIN_HIGH: switch (port) { case DIO_PORTA: SET_BIT(PORTA, pin); break; case DIO_PORTB: SET_BIT(PORTB, pin); break; case DIO_PORTC: SET_BIT(PORTC, pin); break; case DIO_PORTD: SET_BIT(PORTD, pin); break; } break; } } void DIO_TogglePin_Value(Uint8t port, Uint8t pin) { switch(port) { case DIO_PORTA: TGL_BIT(PORTA, pin); break; case DIO_PORTB: TGL_BIT(PORTB, pin); break; case DIO_PORTC: TGL_BIT(PORTC, pin); break; case DIO_PORTD: TGL_BIT(PORTD, pin); break; } } Uint8t DIO_ReadPin_Value(Uint8t port, Uint8t pin) { Uint8t val = 0; switch(port) { case DIO_PORTA: val = GET_BIT(PINA, pin); break; case DIO_PORTB: val = GET_BIT(PINB, pin); break; case DIO_PORTC: val = GET_BIT(PINC, pin); break; case DIO_PORTD: val = GET_BIT(PIND, pin); break; } return val; } void DIO_SetPort_Direction(Uint8t port, Uint8t direction) { switch(direction) { case DIO_PORT_INPUT: switch (port) { case DIO_PORTA: DDRA = 0x00; break; case DIO_PORTB: DDRB = 0x00; break; case DIO_PORTC: DDRC = 0x00; break; case DIO_PORTD: DDRD = 0x00; break; } break; case DIO_PORT_OUTPUT: switch (port) { case DIO_PORTA: DDRA = 0xFF; break; case DIO_PORTB: DDRB = 0xFF; break; case DIO_PORTC: DDRC = 0xFF; break; case DIO_PORTD: DDRD = 0xFF; break; } break; } } void DIO_SetPort_Value(Uint8t port, Uint8t state) { } void DIO_TogglePort_Value(Uint8t port, Uint8t pin) { } Uint8t DIO_ReadPort_Value(Uint8t port) { return 0; }
C
/* #include<stdio.h> #include<stdlib.h> int n=2; long long Factorial(int n) //1-nȻзʽ { int i; long long product = 1; for (i = 1; i <= n; i++) product = product * i; return product; } long Evaluate_determinant(int input[], int c_subscript[]) { long sum = 0, SUM = 0; int column = 0; for (int i = 1; i <= Factorial(n); i++) { int product = 1, symbol = 1; for (int count = 0; count < n; count++) { column = c_subscript[(i - 1) * n + count + 1]; printf("c%d=%d\n", column,input[column-1]); product = product * input[count*n+column-1]; for (int c = count+1; c < n; c++) { int nextcolumn = c_subscript[(i - 1) * n + count + 2]; printf("next column =%d\n", nextcolumn); if (column > nextcolumn) symbol *= -1; } } product *= symbol; printf("product=%d", product); SUM += product; printf("SUM=%d", SUM); } return SUM; } int main(void) { int input[4] = { 1,2,2,1 }; int c_subscript[5] = { 0,1,2,2,1 }; printf("%d", Evaluate_determinant(input, c_subscript)); return 0; } */
C
#include <stdio.h> //void swap(int *a, int *b); void swapVoid(void *av, void *bv); int main(){ int a = 10, b = 20; printf("innan byte:\na: %d b: %d\n", a, b); swapVoid(&a, &b); char s[30]; sprintf(s, "efter byte: \na: %d b: %d", a, b); puts(s); return 0; } /* void swap(int *a, int *b){ int temp; temp = *a; *a = *b; *b = temp; } */ void swapVoid(void *av, void *bv){ int temp; int *a = av, *b = bv; temp = *a; *a = *b; *b = temp; return; }
C
#include <stdlib.h> #include "stack.h" /* * Creates an empty stack and sets * the size equal to 0 */ stack* create_stack() { stack* newstack = malloc(sizeof(stack)); newstack->size = 0; newstack->stack = NULL; return newstack; } /* * pushes the value into the top of the stack */ void push(stack *s, int val) { node *n = malloc(sizeof(node)); n->data = val; n->next = s->stack; s->stack = n; s->size++; } /* * pops the head of the stack * the value is not returned */ void pop(stack *s) { //if stack is empty, return if(s->size == 0) return; node* current = s->stack; s->stack = current->next; free(current); --s->size; } /* * returns the value at the top of the stack * the stack remains unchanged */ int top(stack *s) { if(s->size == 0) return 0; node* current = s->stack; return current->data; } /* * returns 1 if the stack is empty * 0 otherwise */ int isEmpty(stack *s) { if (s->size == 0) return 1; else return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* init_matrices.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: zyuan <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/06/30 12:01:52 by zyuan #+# #+# */ /* Updated: 2018/06/30 12:05:56 by zyuan ### ########.fr */ /* */ /* ************************************************************************** */ #include "mlx.h" #include "fdf.h" #include "../libft/libft.h" #include <stdlib.h> #include <string.h> t_matrix rotation_x_matrix(t_mlx *map) { t_matrix m; ft_bzero(m.value, sizeof(m.value)); m.value[0][0] = 1.0; m.value[1][1] = cos(DEGTORAD(map->fac.rotation_x)); m.value[1][2] = -sin(DEGTORAD(map->fac.rotation_x)); m.value[2][1] = sin(DEGTORAD(map->fac.rotation_x)); m.value[2][2] = cos(DEGTORAD(map->fac.rotation_x)); m.value[2][3] = 1.0; m.value[3][3] = 1.0; return (m); } t_matrix rotation_y_matrix(t_mlx *map) { t_matrix m; ft_bzero(m.value, sizeof(m.value)); m.value[0][0] = cos(DEGTORAD(map->fac.rotation_y)); m.value[0][2] = sin(DEGTORAD(map->fac.rotation_y)); m.value[1][1] = 1.0; m.value[2][0] = -sin(DEGTORAD(map->fac.rotation_y)); m.value[2][2] = cos(DEGTORAD(map->fac.rotation_y)); m.value[2][3] = 1.0; m.value[3][3] = 1.0; return (m); } t_matrix rotation_z_matrix(t_mlx *map) { t_matrix m; ft_bzero(m.value, sizeof(m.value)); m.value[0][0] = cos(DEGTORAD(map->fac.rotation_z)); m.value[0][1] = -sin(DEGTORAD(map->fac.rotation_z)); m.value[1][0] = sin(DEGTORAD(map->fac.rotation_z)); m.value[1][1] = cos(DEGTORAD(map->fac.rotation_z)); m.value[2][3] = 1.0; m.value[3][3] = 1.0; return (m); } t_matrix translation_matrix(t_mlx *map) { t_matrix m; ft_bzero(m.value, sizeof(m.value)); m.value[0][0] = 1.0; m.value[0][3] = map->fac.translation_x; m.value[1][1] = 1.0; m.value[1][3] = map->fac.translation_y; m.value[2][2] = 1.0; m.value[2][3] = map->fac.translation_z; m.value[3][3] = 1; return (m); }
C
#include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/mman.h> #include <sys/stat.h> #include <sys/sysinfo.h> #include <sys/types.h> #include <unistd.h> #define MAX_ORDER 11 #define PAGE_SIZE 4096 #define SZ_GB (1UL << 30) #define max(a,b) \ ({ \ __typeof__ (a) _a = (a); \ __typeof__ (b) _b = (b); \ _a > _b ? _a : _b; \ }) #define min(a,b) \ ({ \ __typeof__ (a) _a = (a); \ __typeof__ (b) _b = (b); \ _a < _b ? _a : _b; \ }) static int print_buddyinfo(void) { char buf[4 * PAGE_SIZE] = {0}; int ret, off, fd, i; ssize_t len; unsigned long nr[MAX_ORDER] = {0}; unsigned long total = 0, cumulative = 0; fd = open("/proc/buddyinfo", O_RDONLY); if (fd < 0) { perror("open"); return -1; } len = read(fd, buf, sizeof(buf)); if (len <= 0) { perror("read"); close(fd); return -1; } off = 0; while (off < len) { int node; char __node[64], __zone[64], zone[64]; unsigned long n[MAX_ORDER]; int parsed; ret = sscanf(buf + off, "%s %d, %s %s %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu\n%n", __node, &node, __zone, zone, &n[0], &n[1], &n[2], &n[3], &n[4], &n[5], &n[6], &n[7], &n[8], &n[9], &n[10], &parsed); //printf("%d %s %lu %lu %lu\n", node, zone, n[0], n[1], n[10]); if (ret < 15) break; off += parsed; for (i = 0; i < MAX_ORDER; i++) nr[i] += n[i]; } for (i = 0; i < MAX_ORDER; i++) total += (PAGE_SIZE << i) * nr[i]; printf("%-4s%10s%10s%10s%10s\n", "Order", "Pages", "Total", "%Free", "%Higher"); for (i = 0; i < MAX_ORDER; i++) { unsigned long bytes = (PAGE_SIZE << i) * nr[i]; cumulative += bytes; printf("%-4d %10lu %7.2lfGB %8.1lf%% %8.1lf%%\n", i, nr[i], (double) bytes / SZ_GB, (double) bytes / total * 100, (double) (total - cumulative) / total * 100); } close(fd); return 0; } static int fragment_memory(int order, int dentries) { struct sysinfo info; size_t off = 0, size, mmap_size, i; char *area; int ret, iter = 0; ret = sysinfo(&info); if (ret) { perror("sysinfo"); return -1; } print_buddyinfo(); printf("total %.1lf GB, free %.1lf GB\n", (double)info.totalram / SZ_GB, (double)info.freeram / SZ_GB); mmap_size = info.totalram; area = mmap(NULL, mmap_size, PROT_WRITE | PROT_READ, MAP_ANONYMOUS | MAP_PRIVATE, 0, 0); if (area == MAP_FAILED) { perror("mmap"); return -1; } off = 0; while (1) { ret = sysinfo(&info); if (ret) { perror("sysinfo"); break; } size = info.freeram; printf("%.1lf GB..\n", (double)size / SZ_GB); /* Populate region */ for (i = off; i < min(off + size, mmap_size); i += PAGE_SIZE) area[i] = 'f'; /* Make holes */ for (i = off; i < min(off + size, mmap_size - (PAGE_SIZE << order) - PAGE_SIZE); i += (PAGE_SIZE << order)) { ret = madvise(area + i + PAGE_SIZE, (PAGE_SIZE << order) - PAGE_SIZE, MADV_DONTNEED); if (ret) { perror("madvise"); return -1; } } if (dentries) { unsigned long count; ret = sysinfo(&info); if (ret) { perror("sysinfo"); break; } count = info.freeram * (PAGE_SIZE << (order - PAGE_SIZE)) / (PAGE_SIZE << order); /* struct dentry is ~192 bytes large*/ count /= 192; printf("creating %lu dentries (%.1lfGB)\n", count, (double)count * 192 / SZ_GB); for (i = 0; i < count; i++) { struct stat st; char buf[32]; snprintf(buf, sizeof(buf), "/%ld%d%lu", info.uptime, iter, i); stat(buf, &st); } } off += size; if (off >= mmap_size) break; iter++; } printf("done\n"); print_buddyinfo(); if (!dentries) { while(1) { sleep(10); printf("\n"); print_buddyinfo(); } } munmap(area, mmap_size); return 0; } int main(int argc, char **argv) { int dentries = 0, order, i; if (argc < 2) goto bad_args; if (strcmp(argv[1], "stat") == 0) { print_buddyinfo(); return EXIT_SUCCESS; } else if (strcmp(argv[1], "fragment") == 0) { for (i = 2; i < argc - 1; i++) { if (strcmp(argv[i], "--dentries") == 0) dentries = 1; } order = atoi(argv[argc - 1]); if (order < 1 || order > 18) { fprintf(stderr, "Order must be in [1; 18] range\n"); return EXIT_FAILURE; } fragment_memory(order, dentries); } else { goto bad_args; } return EXIT_SUCCESS; bad_args: fprintf(stderr, "Usage:\n" " Fragment memory: fragment [--dentries] <order>\n" " Show stats: stat\n"); return EXIT_FAILURE; }
C
// Finds amplitude in the bandpass filter #include <stdio.h> #include <math.h> int bpf(if1,if2,if3,if4,omega,bpfilt) int if1,if2,if3,if4; float omega; float *bpfilt; { double dummy; float w1,w2,w3,w4; float PI, TPI; PI = 4.*atan(1.); TPI = 2.*PI; w1 = if1*TPI/1000.; w2 = if2*TPI/1000.; w3 = if3*TPI/1000.; w4 = if4*TPI/1000.; if( w1 == 0. && w4 == 0.) { *bpfilt = 1.; return(1); } // fprintf(stdout,"in bfp() omega = %f\n", omega); // fprintf(stdout,"w1 w2 w3 w4= %f %f %f %f\n",w1,w2,w3,w4); if( omega>w4 || omega<w1 ) *bpfilt = 0.; else if( omega<=w4 && omega>=w3 ) { dummy = cos( (omega-w3)/(w4-w3)*PI/2. ); *bpfilt = dummy*dummy; } else if( omega<w3 && omega>w2 ) *bpfilt = 1.; else if( omega<=w2 && omega>=w1 ) { dummy = cos( (omega-w2)/(w1-w2)*PI/2. ); *bpfilt = dummy*dummy; } else *bpfilt = 0.; // fprintf(stdout,"in bfp() freq = %f bpfilt = %f\n", omega/PI/2., *bpfilt); return(1); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* precifloat.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: mascorpi <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/02/01 12:49:19 by mascorpi #+# #+# */ /* Updated: 2019/02/12 15:46:46 by mascorpi ### ########.fr */ /* */ /* ************************************************************************** */ #include "ft_printf.h" char *ft_approx(char *deci) { unsigned int i; i = ft_strlen(deci); i--; if (deci[i] >= '5') { while (deci[i - 1] == '9') { deci[i - 1] = '0'; i--; } deci[i - 1] = deci[i - 1] + 1; } i = ft_strlen(deci); i--; deci[i] = '\0'; return (deci); } static char *ft_float_pre(float f, size_t prec) { long tmp; char *rtn; char *deci; char *temp; tmp = f; rtn = ft_itoalong(tmp); temp = rtn; rtn = ft_strjoin(rtn, "."); f = f - tmp; deci = ft_fill_zero_pre(tmp, deci, f, prec); free(temp); temp = rtn; if (f < 0) rtn = ft_strjoin(rtn, deci + 1); else rtn = ft_strjoin(rtn, deci); free(deci); free(temp); return (rtn); } static char *ft_float_d_pre(double f, size_t prec) { long tmp; char *rtn; char *deci; char *temp; tmp = f; rtn = ft_itoalong(tmp); temp = rtn; rtn = ft_strjoin(rtn, "."); f = f - tmp; deci = ft_fill_zero_pre(tmp, deci, f, prec); free(temp); temp = rtn; if (f < 0) rtn = ft_strjoin(rtn, deci + 1); else rtn = ft_strjoin(rtn, deci); free(deci); free(temp); return (rtn); } static char *ft_float_long_d_pre(long double f, size_t prec) { long tmp; char *rtn; char *deci; char *temp; tmp = f; rtn = ft_itoalong(tmp); temp = rtn; rtn = ft_strjoin(rtn, "."); f = f - tmp; deci = ft_fill_zero_pre(tmp, deci, f, prec); free(temp); temp = rtn; if (f < 0) rtn = ft_strjoin(rtn, deci + 1); else rtn = ft_strjoin(rtn, deci); free(deci); free(temp); return (rtn); } int ft_precifloat(va_list ap, t_struct *all, size_t prec) { char *rtn; float f; double d; long double ld; if (all->flag == 28) { f = va_arg(ap, double); rtn = ft_float_pre(f, prec); } if (all->flag == 29) { d = va_arg(ap, double); rtn = ft_float_d_pre(d, prec); } if (all->flag == 30) { ld = va_arg(ap, long double); rtn = ft_float_long_d_pre(ld, prec); } ft_putstr(rtn); all->ret += ft_strlen(rtn); free(rtn); return (all->ret); }
C
#ifndef _WORM_H #define _WORM_H /************************************************************************* * This file contains: * * Total update: * void nworms(int nw) * * Worm update for constrained variables: * void move0() * void move1() * void move() * void get_current_segments_and_links( int rho, int sseg, int *xf ) * * Update of unconstrained variables: * void sweep_l( ) * *------------------------------------------------------------------------------ * * Directions: * nu,rho = 0,1,2 spatial directions * nu,rho = 3 temporal direction * * Link ordering in the plaquettes: * __2__ * | | * ^ 3 1 * nu1| |__0__| * ---> * nu0 nu0<nu1 always * * vlink[i][j]: i=site and j=0,1,2,3 * vplaq[i][j]: i=site and j=nu+rho-1 if spatial plaquette * i=site and j=nu+rho if temporal plaquette * * xx = site of open_link_init * nu = direction of open_link_init : nu>0 always * rho = other direction of plaquette: rho>0 moving towards positive direction of axis * rho<0 moving towards negative direction of axis * * open_link_init: (x) ---> (x+nu) * open_link_end: choose randomly among the other 3 links * * Regarding variables: * ivar = index of var(=segment or link) * vvar = value of var(=segment or link) * **************************************************************************/ #define NWORMS nsite #define ERROR_WORM(x) \ if ((x)>=LENGTH_FLUX) \ { cout << "FATAL ERROR WORM: flux>max_length" << endl; exit(-1); } #define ERROR_PLAQ(x) \ if (abs((x))>=LENGTH) { cout << "FATAL ERROR plaq: plaq>max_length" << endl; exit(-1); } // STRUCT VARS struct tlink { /* Link variable */ int lidx;// position in the segment [0,3] int lval; // occupation number int lx; // lattice site [0,nsites-1] int lnu; // link direction [0,3] }; struct segment { /* Segment variable for worm updates */ tlink slink[4]; // 4 link variables: link[0] and link[1] = links to be modified // link[2] = current worm's head // link[3] = new worm's head int svplaq; // occupation number of plaquette variable int sxplaq; // site of the lower-left corner of the plaquette int sdirmove; // if the segment will be inserted in positive or negative direction int ssignseg; // if a positve or negative segment will be inserted }; // Global variables int insert_next_segment; int oldsignseg,oldrho,real_world,oldlidx2; int delta_seg[5] = {-1,-1,1,1,1}; // link_0,link_1,link_2,link_3,pp = -1,-1,+1,+1,+1 tlink link0; segment seg; // Subroutines //_________________________________________________________________________ inline void a_eq_b(int *a, int*b ) { a[0] = b[0]; a[1] = b[1]; a[2] = b[2]; a[3] = b[3]; } //________________________________________________________________________ inline void a_eq_mb(int *a, int*b ) { a[0] = -b[0]; a[1] = -b[1]; a[2] = -b[2]; a[3] = -b[3]; } //________________________________________________________________________ void get_current_segments_and_links( int rho, int sseg, int *xf ) { // get 4 links and plaquette and set // open_link_init and open_link_end if (seg.slink[2].lnu<rho) { if (seg.sdirmove > 0) { seg.slink[2].lidx = 0; seg.slink[3].lidx++; switch (seg.slink[3].lidx) { case 1: seg.ssignseg = 0; seg.slink[0].lx = neib[seg.slink[2].lx][rho]; seg.slink[0].lnu = seg.slink[2].lnu; seg.slink[0].lidx = 2; seg.slink[1].lx = seg.slink[2].lx; seg.slink[1].lnu = rho; seg.slink[1].lidx = 3; seg.slink[3].lx = neib[seg.slink[2].lx][seg.slink[2].lnu]; seg.slink[3].lnu = rho; xf[0] = seg.slink[0].lx; xf[1] = neib[seg.slink[0].lx][seg.slink[0].lnu]; xf[2] = seg.slink[1].lx; xf[3] = -1; break; case 2: seg.ssignseg = 0; seg.slink[0].lx = neib[seg.slink[2].lx][seg.slink[2].lnu]; seg.slink[0].lnu = rho; seg.slink[0].lidx = 1; seg.slink[1].lx = seg.slink[2].lx; seg.slink[1].lnu = rho; seg.slink[1].lidx = 3; seg.slink[3].lx = neib[seg.slink[2].lx][rho]; seg.slink[3].lnu = seg.slink[2].lnu; xf[0] = seg.slink[0].lx; xf[1] = neib[seg.slink[0].lx][seg.slink[0].lnu]; xf[2] = seg.slink[1].lx; xf[3] = neib[seg.slink[1].lx][seg.slink[1].lnu]; break; case 3: seg.ssignseg = 1; seg.slink[0].lx = neib[seg.slink[2].lx][seg.slink[2].lnu]; seg.slink[0].lnu = rho; seg.slink[0].lidx = 1; seg.slink[1].lx = neib[seg.slink[2].lx][rho]; seg.slink[1].lnu = seg.slink[2].lnu; seg.slink[1].lidx = 2; seg.slink[3].lx = seg.slink[2].lx; seg.slink[3].lnu = rho; xf[0] = neib[seg.slink[1].lx][seg.slink[1].lnu]; xf[1] = seg.slink[0].lx; xf[2] = seg.slink[1].lx; xf[3] = -1; break; } seg.sxplaq = seg.slink[2].lx; } else { seg.slink[2].lidx = 2; seg.slink[3].lidx = seg.slink[2].lidx - seg.slink[3].lidx + (seg.slink[3].lidx==0); switch (seg.slink[3].lidx) { case 0: seg.ssignseg = 1; seg.slink[3].lx = neib[seg.slink[2].lx][rho+4]; seg.slink[3].lnu = seg.slink[2].lnu; seg.sxplaq = seg.slink[3].lx; seg.slink[0].lx = neib[seg.slink[3].lx][seg.slink[2].lnu]; seg.slink[0].lnu = rho; seg.slink[0].lidx = 1; seg.slink[1].lx = seg.slink[3].lx; seg.slink[1].lnu = rho; seg.slink[1].lidx = 3; xf[0] = seg.slink[0].lx; xf[1] = neib[seg.slink[0].lx][seg.slink[0].lnu]; xf[2] = seg.slink[1].lx; xf[3] = neib[seg.slink[1].lx][seg.slink[1].lnu]; break; case 1: seg.ssignseg = 0; seg.slink[0].lx = neib[seg.slink[2].lx][rho+4]; seg.slink[0].lnu = seg.slink[2].lnu; seg.slink[0].lidx = 0; seg.sxplaq = seg.slink[0].lx; seg.slink[1].lx = seg.slink[0].lx; seg.slink[1].lnu = rho; seg.slink[1].lidx = 3; seg.slink[3].lx = neib[seg.slink[0].lx][seg.slink[2].lnu]; seg.slink[3].lnu = rho; xf[0] = seg.slink[0].lx; xf[1] = neib[seg.slink[0].lx][seg.slink[0].lnu]; xf[2] = neib[seg.slink[1].lx][seg.slink[1].lnu]; xf[3] = -1; break; case 3: seg.ssignseg = 1; seg.slink[3].lx = neib[seg.slink[2].lx][rho+4]; seg.slink[3].lnu = rho; seg.slink[0].lx = seg.slink[3].lx; seg.slink[0].lnu = seg.slink[2].lnu; seg.slink[0].lidx = 0; seg.sxplaq = seg.slink[0].lx; seg.slink[1].lx = neib[seg.slink[3].lx][seg.slink[2].lnu]; seg.slink[1].lnu = rho; seg.slink[1].lidx = 1; xf[0] = seg.slink[1].lx; xf[1] = seg.slink[0].lx; xf[2] = neib[seg.slink[1].lx][seg.slink[1].lnu]; xf[3] = -1; break; } } } else { if (seg.sdirmove > 0) { seg.slink[2].lidx = 3; switch (seg.slink[3].lidx) { case 0: seg.ssignseg = 1; seg.slink[3].lx = seg.slink[2].lx; seg.slink[3].lnu = rho; seg.slink[0].lx = neib[seg.slink[2].lx][rho]; seg.slink[0].lnu = seg.slink[2].lnu; seg.slink[0].lidx = 1; seg.slink[1].lx = neib[seg.slink[2].lx][seg.slink[2].lnu]; seg.slink[1].lnu = rho; seg.slink[1].lidx = 2; xf[0] = neib[seg.slink[1].lx][seg.slink[1].lnu]; xf[1] = seg.slink[0].lx; xf[2] = seg.slink[1].lx; xf[3] = -1; break; case 1: seg.ssignseg = 0; seg.slink[0].lx = seg.slink[2].lx; seg.slink[0].lnu = rho; seg.slink[0].lidx = 0; seg.slink[1].lx = neib[seg.slink[2].lx][seg.slink[2].lnu]; seg.slink[1].lnu = rho; seg.slink[1].lidx = 2; seg.slink[3].lx = neib[seg.slink[2].lx][rho]; seg.slink[3].lnu = seg.slink[2].lnu; xf[0] = seg.slink[0].lx; xf[1] = neib[seg.slink[0].lx][seg.slink[0].lnu]; xf[2] = seg.slink[1].lx; xf[3] = neib[seg.slink[1].lx][seg.slink[1].lnu]; break; case 2: seg.ssignseg = 0; seg.slink[0].lx = seg.slink[2].lx; seg.slink[0].lnu = rho; seg.slink[0].lidx = 0; seg.slink[1].lx = neib[seg.slink[2].lx][rho]; seg.slink[1].lnu = seg.slink[2].lnu; seg.slink[1].lidx = 1; seg.slink[3].lx = neib[seg.slink[2].lx][seg.slink[2].lnu]; seg.slink[3].lnu = rho; xf[0] = seg.slink[1].lx; xf[1] = seg.slink[0].lx; xf[2] = neib[seg.slink[1].lx][seg.slink[1].lnu]; xf[3] = -1; break; } seg.sxplaq = seg.slink[2].lx; } else { seg.slink[2].lidx = 1; seg.slink[3].lidx += (seg.slink[3].lidx!=0); switch (seg.slink[3].lidx) { case 0: seg.ssignseg = 1; seg.slink[3].lx = neib[seg.slink[2].lx][rho+4]; seg.slink[3].lnu = rho; seg.sxplaq = seg.slink[3].lx; seg.slink[0].lx = neib[seg.slink[3].lx][seg.slink[2].lnu]; seg.slink[0].lnu = rho; seg.slink[0].lidx = 2; seg.slink[1].lx = seg.slink[3].lx; seg.slink[1].lnu = seg.slink[2].lnu; seg.slink[1].lidx = 3; xf[0] = seg.slink[0].lx; xf[1] = neib[seg.slink[0].lx][seg.slink[0].lnu]; xf[2] = seg.slink[1].lx; xf[3] = -1; break; case 2: seg.ssignseg = 0; seg.slink[0].lx = neib[seg.slink[2].lx][rho+4]; seg.slink[0].lnu = rho; seg.slink[0].lidx = 0; seg.sxplaq = seg.slink[0].lx; seg.slink[1].lx = seg.slink[0].lx; seg.slink[1].lnu = seg.slink[2].lnu; seg.slink[1].lidx = 3; seg.slink[3].lx = neib[seg.slink[0].lx][seg.slink[2].lnu]; seg.slink[3].lnu = rho; xf[0] = seg.slink[0].lx; xf[1] = neib[seg.slink[0].lx][seg.slink[0].lnu]; xf[2] = neib[seg.slink[1].lx][seg.slink[1].lnu]; xf[3] = -1; break; case 3: seg.ssignseg = 1; seg.slink[0].lx = neib[seg.slink[2].lx][rho+4]; seg.slink[0].lnu = rho; seg.slink[0].lidx = 0; seg.sxplaq = seg.slink[0].lx; seg.slink[1].lx = neib[seg.slink[0].lx][seg.slink[2].lnu]; seg.slink[1].lnu = rho; seg.slink[1].lidx = 2; seg.slink[3].lx = seg.slink[0].lx; seg.slink[3].lnu = seg.slink[2].lnu; xf[0] = seg.slink[0].lx; xf[1] = neib[seg.slink[0].lx][seg.slink[0].lnu]; xf[2] = seg.slink[1].lx; xf[3] = neib[seg.slink[1].lx][seg.slink[1].lnu]; break; } } } seg.slink[0].lval = vlink[seg.slink[0].lx][seg.slink[0].lnu]; seg.slink[1].lval = vlink[seg.slink[1].lx][seg.slink[1].lnu]; seg.slink[3].lval = vlink[seg.slink[3].lx][seg.slink[3].lnu]; seg.svplaq = vplaq[seg.sxplaq][seg.slink[2].lnu+rho-sseg]; } //_________________________________________________________________________ void move0() { // // Insert first link // double ran[4]; ranlxd( ran, 4 ); seg.slink[2].lx = int(ran[0]*nsite); seg.slink[2].lnu = int(ran[1]*4); seg.slink[2].lval = vlink[seg.slink[2].lx][seg.slink[2].lnu]; // calculate probability link0.lval = 1-2*(ran[2]<0.5); int newvalseg = seg.slink[2].lval + link0.lval; int ll = vllink[seg.slink[2].lx][seg.slink[2].lnu]; int ff[2], ffnew[2]; ff[0] = vflux[seg.slink[2].lx]; ff[1] = vflux[ neib[seg.slink[2].lx][seg.slink[2].lnu] ]; ffnew[0] = ff[0] + abs(newvalseg) - abs(seg.slink[2].lval); ffnew[1] = ff[1] + abs(newvalseg) - abs(seg.slink[2].lval); // Check if fluxes > maximum ERROR_WORM(ffnew[0]); ERROR_WORM(ffnew[1]); double weig = Pn[ffnew[0]] - Pn[ff[0]] + Pn[ffnew[1]] - Pn[ff[1]] + fac[ abs(seg.slink[2].lval) + ll ] - fac[ abs(newvalseg) + ll ]; weig = exp( weig ); if ( ran[3] <= weig ) { insert_next_segment = 1; vlink[seg.slink[2].lx][seg.slink[2].lnu] = newvalseg; vflux[seg.slink[2].lx] = ffnew[0]; vflux[neib[seg.slink[2].lx][seg.slink[2].lnu]] = ffnew[1]; nflux[ff[0]]--; nflux[ff[1]]--; nflux[ffnew[0]]++; nflux[ffnew[1]]++; nlink[abs(seg.slink[2].lval)]--; nlink[abs(newvalseg)]++; } } //_________________________________________________________________________ void move1() { // // The worm tries to insert the first segment // double ran[2]; ranlxd(ran,2); int rho = int(ran[0]*4); if ( rho == 3 ) // try to close the worm { seg.slink[2].lval = vlink[seg.slink[2].lx][seg.slink[2].lnu]; int newvalseg = seg.slink[2].lval - link0.lval; int ll = vllink[seg.slink[2].lx][seg.slink[2].lnu]; int ff[2], ffnew[2]; ff[0] = vflux[seg.slink[2].lx]; ff[1] = vflux[ neib[seg.slink[2].lx][seg.slink[2].lnu] ]; ffnew[0] = ff[0] + abs(newvalseg) - abs(seg.slink[2].lval); ffnew[1] = ff[1] + abs(newvalseg) - abs(seg.slink[2].lval); // Check if fluxes > maximum ERROR_WORM(ffnew[0]); ERROR_WORM(ffnew[1]); double weig = Pn[ffnew[0]] - Pn[ff[0]] + Pn[ffnew[1]] - Pn[ff[1]] + fac[ abs(seg.slink[2].lval) + ll ] - fac[ abs(newvalseg) + ll ]; weig = exp( weig ); if ( ran[1] <= weig ) { vlink[seg.slink[2].lx][seg.slink[2].lnu] = newvalseg; vflux[seg.slink[2].lx] = ffnew[0]; vflux[neib[seg.slink[2].lx][seg.slink[2].lnu] ] = ffnew[1]; nlink[ abs(seg.slink[2].lval) ]--; nlink[ abs(newvalseg) ]++; nflux[ff[0]]--; nflux[ff[1]]--; nflux[ffnew[0]]++; nflux[ffnew[1]]++; insert_next_segment = 0; } } else // Insert segment { seg.sdirmove = ran[1]<0.5; // 1=positive and 0=negative direction switch(seg.slink[2].lnu){ case 0: rho++; break; case 1: rho += (rho!=0); break; case 2: rho = seg.slink[2].lnu - rho + (rho==0); break; } ranlxd(ran,2); seg.slink[3].lidx = int(ran[0]*3); int sseg = (seg.slink[2].lnu!=3)&(rho!=3); int xf[4]; get_current_segments_and_links( rho, sseg, xf ); // select sign: int delta[5]; if ( link0.lval != delta_seg[seg.slink[2].lidx] ) a_eq_mb( delta, delta_seg ); else a_eq_b( delta, delta_seg ); int newvalseg[3]; newvalseg[0] = seg.slink[0].lval + delta[seg.slink[0].lidx]; newvalseg[1] = seg.slink[1].lval + delta[seg.slink[1].lidx]; newvalseg[2] = seg.svplaq + delta[4]; int ll[2], ff[4], ffnew[4]; ll[0] = vllink[seg.slink[0].lx][seg.slink[0].lnu]; ll[1] = vllink[seg.slink[1].lx][seg.slink[1].lnu]; if ( xf[3]<0 ) { ff[0] = vflux[xf[0]]; ff[1] = vflux[xf[1]]; ff[2] = vflux[xf[2]]; ff[3] = 0; ffnew[0] = ff[0] + abs(newvalseg[0]) - abs(seg.slink[0].lval) + abs(newvalseg[1]) - abs(seg.slink[1].lval); ffnew[1] = ff[1] + abs(newvalseg[0]) - abs(seg.slink[0].lval); ffnew[2] = ff[2] + abs(newvalseg[1]) - abs(seg.slink[1].lval); ffnew[3] = 0; } else { ff[0] = vflux[xf[0]]; ff[1] = vflux[xf[1]]; ff[2] = vflux[xf[2]]; ff[3] = vflux[xf[3]]; ffnew[0] = ff[0] + abs(newvalseg[0]) - abs(seg.slink[0].lval); ffnew[1] = ff[1] + abs(newvalseg[0]) - abs(seg.slink[0].lval); ffnew[2] = ff[2] + abs(newvalseg[1]) - abs(seg.slink[1].lval); ffnew[3] = ff[3] + abs(newvalseg[1]) - abs(seg.slink[1].lval); } // Check if fluxes > maximum ERROR_PLAQ(newvalseg[2]); ERROR_WORM(ffnew[0]); ERROR_WORM(ffnew[1]); ERROR_WORM(ffnew[2]); ERROR_WORM(ffnew[3]); // calculate probability double weig = In[abs(newvalseg[2])] - In[abs(seg.svplaq)] + Pn[ffnew[0]] - Pn[ff[0]] + Pn[ffnew[1]] - Pn[ff[1]] + Pn[ffnew[2]] - Pn[ff[2]] + Pn[ffnew[3]] - Pn[ff[3]] + fac[abs(seg.slink[0].lval)+ll[0]] - fac[abs(newvalseg[0])+ll[0]] + fac[abs(seg.slink[1].lval)+ll[1]] - fac[abs(newvalseg[1])+ll[1]]; weig = exp( weig ); if ( ran[1] <= weig ) { insert_next_segment = 2; vlink[seg.slink[0].lx][seg.slink[0].lnu] = newvalseg[0]; vlink[seg.slink[1].lx][seg.slink[1].lnu] = newvalseg[1]; vplaq[seg.sxplaq][seg.slink[2].lnu+rho-sseg] = newvalseg[2]; vflux[xf[0]] = ffnew[0]; vflux[xf[1]] = ffnew[1]; vflux[xf[2]] = ffnew[2]; nlink[abs(seg.slink[0].lval)]--; nlink[abs(seg.slink[1].lval)]--; nplaq[abs(seg.svplaq)]--; nlink[abs(newvalseg[0])]++; nlink[abs(newvalseg[1])]++; nplaq[abs(newvalseg[2])]++; nflux[ff[0]]--; nflux[ff[1]]--; nflux[ff[2]]--; nflux[ffnew[0]]++; nflux[ffnew[1]]++; nflux[ffnew[2]]++; if ( xf[3]>=0 ) { vflux[xf[3]] = ffnew[3]; nflux[ff[3]]--; nflux[ffnew[3]]++; } oldsignseg = seg.ssignseg; if (seg.slink[3].lnu == rho){ oldrho = seg.slink[2].lnu; }else{ oldrho = rho; } // open_end --> open_init of next move seg.slink[2].lx = seg.slink[3].lx; seg.slink[2].lnu = seg.slink[3].lnu; seg.slink[2].lval = seg.slink[3].lval; oldlidx2 = seg.slink[3].lidx; a_eq_b( delta_seg, delta ); }// accepted update } } //_________________________________________________________________________ void move( ) { double ran[2]; ranlxd(ran,2); int rho = int(ran[0]*4); if ( rho == 3 ) // try to close worm { int newvalseg = seg.slink[2].lval + delta_seg[oldlidx2]; int ll = vllink[seg.slink[2].lx][seg.slink[2].lnu]; int ff[2], ffnew[2]; ff[0] = vflux[seg.slink[2].lx]; ff[1] = vflux[ neib[seg.slink[2].lx][seg.slink[2].lnu] ]; ffnew[0] = ff[0] + abs(newvalseg) - abs(seg.slink[2].lval); ffnew[1] = ff[1] + abs(newvalseg) - abs(seg.slink[2].lval); ERROR_WORM(ffnew[0]); ERROR_WORM(ffnew[1]); double weig = Pn[ffnew[0]] - Pn[ff[0]] + Pn[ffnew[1]] - Pn[ff[1]] + fac[ abs(seg.slink[2].lval) + ll ] - fac[ abs(newvalseg) + ll ]; weig = exp( weig ); if ( ran[1] <= weig ) { vlink[seg.slink[2].lx][seg.slink[2].lnu] = newvalseg; vflux[seg.slink[2].lx] = ffnew[0]; vflux[ neib[seg.slink[2].lx][seg.slink[2].lnu] ] = ffnew[1]; nlink[ abs(seg.slink[2].lval) ]--; nlink[ abs(newvalseg) ]++; nflux[ff[0]]--; nflux[ff[1]]--; nflux[ffnew[0]]++; nflux[ffnew[1]]++; insert_next_segment = 0; } } else // Insert next segment { seg.sdirmove = ran[1]<0.5; // 1=positive and 0=negative direction switch(seg.slink[2].lnu){ case 0: rho++; break; case 1: rho += (rho!=0); break; case 2: rho = seg.slink[2].lnu - rho + (rho==0); break; } ranlxd(ran,2); seg.slink[3].lidx = int(ran[0]*3); int sseg = (seg.slink[2].lnu!=3)&(rho!=3); int xf[4]; get_current_segments_and_links( rho, sseg, xf ); // change sign of delta according to direction of move: int delta[5]; if (rho==oldrho) { if (seg.sdirmove==oldsignseg) // go back a_eq_mb( delta, delta_seg ); else a_eq_b( delta, delta_seg ); } else { int var = (seg.slink[2].lnu<rho) + (seg.slink[2].lnu<oldrho); if (var==1) { if (seg.sdirmove!=oldsignseg) a_eq_mb( delta, delta_seg ); else a_eq_b( delta, delta_seg ); } else { if (seg.sdirmove==oldsignseg) a_eq_mb( delta, delta_seg ); else a_eq_b( delta, delta_seg ); } } int newvalseg[3]; newvalseg[0] = seg.slink[0].lval + delta[seg.slink[0].lidx]; newvalseg[1] = seg.slink[1].lval + delta[seg.slink[1].lidx]; newvalseg[2] = seg.svplaq + delta[4]; int ll[2], ff[4], ffnew[4]; ll[0] = vllink[seg.slink[0].lx][seg.slink[0].lnu]; ll[1] = vllink[seg.slink[1].lx][seg.slink[1].lnu]; if ( xf[3]<0 ) { ff[0] = vflux[xf[0]]; ff[1] = vflux[xf[1]]; ff[2] = vflux[xf[2]]; ff[3] = 0; ffnew[0] = ff[0] + abs(newvalseg[0]) - abs(seg.slink[0].lval) + abs(newvalseg[1]) - abs(seg.slink[1].lval); ffnew[1] = ff[1] + abs(newvalseg[0]) - abs(seg.slink[0].lval); ffnew[2] = ff[2] + abs(newvalseg[1]) - abs(seg.slink[1].lval); ffnew[3] = 0; } else { ff[0] = vflux[xf[0]]; ff[1] = vflux[xf[1]]; ff[2] = vflux[xf[2]]; ff[3] = vflux[xf[3]]; ffnew[0] = ff[0] + abs(newvalseg[0]) - abs(seg.slink[0].lval); ffnew[1] = ff[1] + abs(newvalseg[0]) - abs(seg.slink[0].lval); ffnew[2] = ff[2] + abs(newvalseg[1]) - abs(seg.slink[1].lval); ffnew[3] = ff[3] + abs(newvalseg[1]) - abs(seg.slink[1].lval); } // Check if fluxes > maximum ERROR_PLAQ(newvalseg[2]); ERROR_WORM(ffnew[0]); ERROR_WORM(ffnew[1]); ERROR_WORM(ffnew[2]); ERROR_WORM(ffnew[3]); // calculate probability double weig = In[abs(newvalseg[2])] - In[abs(seg.svplaq)] + Pn[ffnew[0]] - Pn[ff[0]] + Pn[ffnew[1]] - Pn[ff[1]] + Pn[ffnew[2]] - Pn[ff[2]] + Pn[ffnew[3]] - Pn[ff[3]] + fac[abs(seg.slink[0].lval)+ll[0]] - fac[abs(newvalseg[0])+ll[0]] + fac[abs(seg.slink[1].lval)+ll[1]] - fac[abs(newvalseg[1])+ll[1]]; weig = exp( weig ); if ( ran[1] <= weig ) { vlink[seg.slink[0].lx][seg.slink[0].lnu] = newvalseg[0]; vlink[seg.slink[1].lx][seg.slink[1].lnu] = newvalseg[1]; vplaq[seg.sxplaq][seg.slink[2].lnu+rho-sseg] = newvalseg[2]; vflux[xf[0]] = ffnew[0]; vflux[xf[1]] = ffnew[1]; vflux[xf[2]] = ffnew[2]; nlink[abs(seg.slink[0].lval)]--; nlink[abs(seg.slink[1].lval)]--; nplaq[abs(seg.svplaq)]--; nlink[abs(newvalseg[0])]++; nlink[abs(newvalseg[1])]++; nplaq[abs(newvalseg[2])]++; nflux[ff[0]]--; nflux[ff[1]]--; nflux[ff[2]]--; nflux[ffnew[0]]++; nflux[ffnew[1]]++; nflux[ffnew[2]]++; if ( xf[3]>=0 ) { vflux[xf[3]] = ffnew[3]; nflux[ff[3]]--; nflux[ffnew[3]]++; } oldsignseg = seg.ssignseg; if (seg.slink[3].lnu == rho){ oldrho = seg.slink[2].lnu; }else{ oldrho = rho; } // open_end --> open_init of next move seg.slink[2].lx = seg.slink[3].lx; seg.slink[2].lnu = seg.slink[3].lnu; seg.slink[2].lval = seg.slink[3].lval; oldlidx2 = seg.slink[3].lidx; a_eq_b( delta_seg, delta ); }// accepted update } } //___________________________________________________________________________ void nworms(int nw) { for(int iw=1; iw<=nw; iw++) { int inw = 0; while ( inw < NWORMS ) { bool unsuccessful_worm = true; do{ double ran; ranlxd( &ran, 1 ); delta_seg[0] = 1-2*(ran<0.5); delta_seg[1] = delta_seg[0]; delta_seg[2] = -delta_seg[1]; delta_seg[3] = delta_seg[2]; delta_seg[4] = delta_seg[3]; insert_next_segment = 0; move0(); while ( insert_next_segment == 1) { unsuccessful_worm = false; move1(); }; while ( insert_next_segment == 2 ) { unsuccessful_worm = false; move(); }; }while(unsuccessful_worm); inw++; }; // sweep of unscontrained variables sweep_l( ); } } #endif
C
// Działanie funkcji fork() #include <stdio.h> //#include <process.h> #include <unistd.h> #include <sys/wait.h> #include <sys/types.h> #include <stdlib.h> void main(int argc, char* argv[]){ int pid,status,i,j; //Deklaracja zmiennych for(i=0;i<argc-1 ;i++){ if((pid = fork()) == 0) { //Proces potomny pot ------- printf("Potomny PID = %d \n",getpid()); for(j=i;j <= atoi(argv[i+2]);++j){ printf("Potomny = %d , krok: %d \n",i+1, j); sleep(1); } exit(i); //Zakonczenie procesu } } // Proces macierzysty ---------------- for(j=0;j<atoi(argv[1]);++j){ printf("Macierzysty, krok: %d \n",j); sleep(1); } for(i=0;i<argc-1 ;++i){ pid = wait(&status); //Czekanie na zakonczenie procesu printf("Proces %d zakończony status: %d\n",pid,WEXITSTATUS(status)); } }
C
// a function to calculate a to the power of b #include <math.h> double power(double a, double b){ double result; result = pow(a, b); return result; }
C
#include <x86 32 bit.h> //#include <windows.h> //#include <system/devices/mouse/mouse.h> #include "graphics.h" typedef struct { N_32 x; N_32 y; N_32 width; N_32 height; } Rectangle; procedure draw_rectangle(Rectangle *rectangle, Canvas *canvas) { N_32 x; N_32 y; Byte *pixel; for(y=rectangle->y; y<rectangle->y + rectangle->height; ++y) { for(x=rectangle->x; x<rectangle->x + rectangle->width; ++x) { pixel = get_canvas_pixel(canvas, x, y); fill_canvas_pixel(canvas, pixel); } } } procedure draw_scene(Canvas *canvas) { Rectangle rect; static N_32 x = 0; static N_32 y = 0; rect.x = 10 + x;//get_mouse_coord_x(); rect.y = 10;//get_mouse_coord_y(); rect.width = 100; rect.height = 100; ++x; clear_canvas(canvas); set_canvas_color(canvas, 255, 0, 0, 255); draw_rectangle(&rect, canvas); } N_32 main() { initialize_graphics(1440, 900, 120, &draw_scene); return 0; }
C
/* Equipo: Angel Avila, Giovanni Mazzolo */ #define _GNU_SOURCE #include <stdio.h> #include <sys/time.h> #include <stdlib.h> #include <unistd.h> #include <malloc.h> #include <pthread.h> #include <sys/types.h> #include <wait.h> #include <signal.h> #include <sched.h> #define NTHREADS 4 // Procesos #define FIBER_STACK 1024*64 // 64kB stack (tamaño de stack por proceso) long long num_steps = 1000000000; double step, sum = 0.0; // Variables globales pthread_mutex_t candado; void *clone_pi(void *args){ int i, tnum, counter_init, counter_end; double x, lsum = 0.0; tnum = *((int *) args); // Se recibe el numero del proceso o índice counter_init = (num_steps/NTHREADS)*tnum; counter_end = (num_steps/NTHREADS)*(tnum+1); for (i=counter_init; i<counter_end; i++) { x = (i + .5)*step; lsum = lsum + 4.0/(1.+ x*x); } pthread_mutex_lock(&candado); sum += lsum; pthread_mutex_unlock(&candado); return(NULL); } int main(int argc, char* argv[]) { long long start_ts; long long stop_ts; float elapsed_time; // long lElapsedTime; struct timeval ts; double pi; int i, status; int args[NTHREADS]; void * stack; gettimeofday(&ts, NULL); start_ts = ts.tv_sec * 1000000 + ts.tv_usec; // Tiempo inicial step = 1./(double)num_steps; stack = malloc( FIBER_STACK * NTHREADS); // Se asigna el tamaño de memoria total pthread_mutex_init(&candado,NULL); for(i=0;i<NTHREADS;i++) // Se crean los procesos { args[i]=i; clone( (void*)&clone_pi, (char*) stack + (FIBER_STACK*(i+1)), SIGCHLD | CLONE_FS | CLONE_FILES | CLONE_SIGHAND | CLONE_VM, (void*)&args[i]); } for(i=0;i<NTHREADS;i++) // Se espera a los procesos { wait(&status); } pi = sum*step; free(stack); gettimeofday(&ts, NULL); stop_ts = ts.tv_sec * 1000000 + ts.tv_usec; // Tiempo final elapsed_time = (float) (stop_ts - start_ts)/1000000.0; printf("El valor de PI es %1.12f\n",pi); printf("Tiempo = %2.2f segundos\n",elapsed_time); return 0; }
C
#include "keySpace2.h" #include <stdio.h> #include <stdlib.h> typedef enum ans { KEY_NF = -1, TABLE_FULL = 1, ST_OK = 0, EL_NOTFOUND = 2, VERS_NOTFOUND = 3, KEY_AE = 4 }ans; KeySpace2** ks2_Init(int size){ // Выделение памяти под таблицу return (KeySpace2**)calloc(size, sizeof(KeySpace2*)); } int hash_f(unsigned int key, int max){ // Хэш-функция return ((int)key % max); } KeySpace2* ks2_Find(unsigned int requiredKey, KeySpace2** ks, int max){ // Поиск по ks2 // Входные данные: искомый ключ, ks, размер таблицы // Выходные данные: указатель на эл-т int pos = hash_f(requiredKey, max); if (!ks[pos]) return NULL; KeySpace2* buf = ks[pos]; while (buf){ if (buf->key == requiredKey){ return buf; } buf = buf->next; } return NULL; } KeySpace2* getKS(Item* item, unsigned int key){ // Создание элемента ks и запись в него данных // Входные данные: данные, ключ // Выходные данные: указатель на эл-т ks2 KeySpace2 * bufKS = (KeySpace2*)calloc(1, sizeof(KeySpace2)); bufKS->info = item; bufKS->info->key2 = key; bufKS->key = key; return bufKS; } int ks2_Add(unsigned int key, Item* item, KeySpace2** ks, int max){ // Добавление элемента // Входные данные: ключ, данные, ks, размер таблицы // Выходные данные: код ошибки if (ks2_Find(key, ks, max)) return KEY_AE; int pos = hash_f(key, max); KeySpace2* bufKS = getKS(item, key); bufKS->next = ks[pos]; ks[pos] = bufKS; return ST_OK; } void freeKS(KeySpace2* el, int flag){ // Очистка памяти элемента KeySpace2 // Входные данные: элемент, флаг(0 - очищать данные, 1 - нет) // Выходные данные: if (el){ if (el->info && !flag){ if (el->info->info){ if (el->info->info->second) free(el->info->info->second); if (el->info->info->first) free(el->info->info->first); free(el->info->info); } free(el->info); } free(el); } } int ks2_Delete(unsigned int deletedKey, KeySpace2** ks, int max, int flag){ // Удаление эл-та ks2 // Входные данные: ключ, ks, размер таблицы, флаг(0 - очищать данные, 1 - нет) // Выходные данные: код ошибки KeySpace2* element = ks2_Find(deletedKey, ks, max); if (!element) return EL_NOTFOUND; int pos = hash_f(deletedKey, max); KeySpace2* par = NULL; KeySpace2* buf = ks[pos]; while (buf) { if (buf->key == deletedKey){ if (par){ par->next = buf->next; } else { ks[pos] = buf->next; } break; } par = buf; buf = buf->next; } freeKS(buf, flag); return ST_OK; } void ks2_Free(KeySpace2** ks, int max){ // Очистка памяти KeySpace2** bufKS = ks; for (int i = 0; i < max; i++, ks++){ if (*ks){ KeySpace2* buf = *ks; KeySpace2* del = NULL; while (buf){ del = buf; buf = buf->next; freeKS(del, 1); } } } free(bufKS); } void ks2_Print(KeySpace2** ks, int max){ for (int i = 0; i < max; i++, ks++){ if (*ks){ KeySpace2 *buf = *ks; while (buf){ printf("%3u ", buf->key); buf = buf->next; } printf("\n"); } else { printf("NULL\n"); } } }
C
/* * Controller.h * * Lonnie L. Souder II * 04/13/2018 * * This file defines a data structure which contains all the necessary * data for a PID controller including gain constants and rolling * sums for error, integral of error, and derivative of error. * In addition, this file will include methods used to derive and manipulate * all of data collected by the PID controller */ struct Controller { // Gain Constants const int Kp; const int Ki; const int Kd; // Error Signals int e; // Current error signal int int_e; // Integral of previous error signal int de; // Instantaneous derivative of error signal //Inputs int target; // Desired output int driver; // Current input to the system const int driverMax;// If the system is using a PWM signal to control something // the duty cycle will be a percentage of driverMax. // driverMax could be the value up to which the Timer // Module counts, for instance. // Otherwise, driverMax can be set to 2^16 // Output Signal int y; // Saves the ***previous*** output signal for error calculations }; int calcError(struct &Controller controller, int outputReading); int calcIntError(struct &Controller controller, int outputReading, int timeStep); int calcIntError(struct &Controller controller, int outputReading, int timeStep, int error); int calcdError(struct &Controller controller, int outputReading, int timeStep); int calcdError(struct &Controller controller, int outputReading, int timeStep, int error); void calcPID(struct &Controller controller int outputReading, int timeStep); void updateDriver(struct &Controller controller, int outputReading, int timeStep); /************************************** * Helper Functions for PWM Controller ***************************************/ int Clamp(&int subject, int min, int max); // Use this function instead of `updateDriver()` if the plant is controlled using a PWM signal void updatePWMDriver(struct &Controller controller, int outputReading, int timeStep);
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* width.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: lvan-bei <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/02/17 10:29:39 by lvan-bei #+# #+# */ /* Updated: 2020/02/17 10:29:40 by lvan-bei ### ########.fr */ /* */ /* ************************************************************************** */ #include "../ft_printf.h" void zero_numb(t_flag *f) { f->i = -1; f->len = ft_strlen(f->final_arg); f->len_zero = f->flag[1] - f->len; if (f->flag[3] == 1 && f->flag[0] <= 0) { if (f->check_prec == 1) { precision_numb(f, f->len_zero, 0); space_plus_sharp(f); } else { space_plus_sharp(f); precision_numb(f, f->len_zero, 1); } } else { precision_numb(f, f->len_zero, 1); space_plus_sharp(f); } while (f->flag[0] > f->len++) buf('0', f); while (f->final_arg[++f->i] != '\0') buf(f->final_arg[f->i], f); } void minus_numb(t_flag *f) { int i; int len; int len_zero; i = -1; len_zero = f->flag[1] - (int)ft_strlen(f->final_arg); len = (int)ft_strlen(f->final_arg); f->flag[3] = 0; space_plus_sharp(f); while (f->flag[0] > len++) buf('0', f); while (f->final_arg[++i] != '\0') buf(f->final_arg[i], f); precision_numb(f, len_zero, 1); } void width_numb(t_flag *f) { int i; int len; i = -1; len = (int)ft_strlen(f->final_arg); if (len < f->flag[1]) { if (f->flag[4] == 1) minus_numb(f); else zero_numb(f); } else { space_plus_sharp(f); while (f->flag[0] > len++) buf('0', f); while (f->final_arg[++i] != '\0') buf(f->final_arg[i], f); } }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "graph.h" #include "util.h" #include "dlist.h" #include "array_1d.h" /* * Name: graph.c * * Description: This program is and implementation of a graph using an array as * a directed list. * * Authors: Viktoria Nordkvist (id19vnt@cs.umu.se) * Tobias Bergström (id19tbm@cs.umu.se) * * Version information: * 2018-03-18: v1.0, first public version. */ // ====================== PUBLIC DATA TYPES ========================== // Anonymous declarations of node and graph. struct node { bool seen; char name[41]; dlist *neighbours; }; struct graph { array_1d *entries; int size; }; // =================== NODE COMPARISON FUNCTION ====================== /** * nodes_are_equal() - Check whether two nodes are equal. * @n1: Pointer to node 1. * @n2: Pointer to node 2. * * Returns: true if the nodes are considered equal, otherwise false. * */ bool nodes_are_equal(const node *n1,const node *n2){ return (n1 == n2); } // =================== GRAPH STRUCTURE INTERFACE ====================== /** * graph_empty() - Create an empty graph. * @max_nodes: The maximum number of nodes the graph can hold. * * Returns: A pointer to the new graph. */ graph *graph_empty(int max_nodes){ // Allocate memory graph *g = calloc(1, sizeof(graph)); g->size = max_nodes + 1; // Create the array to hold the table_entries. g-> entries = array_1d_create(0,g->size, NULL); return g; } /** * graph_is_empty() - Check if a graph is empty, i.e. has no nodes. * @g: Graph to check. * * Returns: True if graph is empty, otherwise false. */ bool graph_is_empty(const graph *g){ //If the array is empty then we return true return !array_1d_has_value(g->entries, array_1d_low(g->entries)); } /** * graph_has_edges() - Check if a graph has any edges. * @g: Graph to check. * * Returns: True if graph has any edges, otherwise false. */ bool graph_has_edges(const graph *g){ //If the array is empty then we return true return !array_1d_has_value(g->entries, array_1d_low(g->entries)); } /** * graph_insert_node() - Inserts a node with the given name into the graph. * @g: Graph to manipulate. * @s: Node name. * * Creates a new node with a copy of the given name and puts it into * the graph. * * Returns: The modified graph. */ graph *graph_insert_node(graph *g, const char* s){ int pos = array_1d_low(g->entries); struct node *n = malloc(sizeof(struct node)); strcpy(n->name, s); n->neighbours = dlist_empty(NULL); n->seen = false; while(array_1d_has_value(g->entries, pos)){ pos++; } array_1d_set_value(g->entries, n, pos); return g; } /** * graph_find_node() - Find a node stored in the graph. * @g: Graph to manipulate. * @s: Node identifier, e.g. a char *. * * Returns: A pointer to the found node, or NULL. */ node *graph_find_node(const graph *g, const char *s){ int i = array_1d_low(g->entries); char name[41]; node *n; strcpy(name, s); while(array_1d_has_value(g->entries, i)) { //node *temp = array_1d_inspect_value(g->entries, i); n = array_1d_inspect_value(g->entries ,i); if ( strcmp(n->name, name) == 0){ return n; } i++; } return NULL; } //ska leta upp listan som börjar på "char s" /** * graph_node_is_seen() - Return the seen status for a node. * @g: Graph storing the node. * @n: Node in the graph to return seen status for. * * Returns: The seen status for the node. */ bool graph_node_is_seen(const graph *g, const node *n){ int pos = array_1d_low(g->entries); node *current_node = NULL; while(array_1d_has_value(g->entries, pos)){ current_node = array_1d_inspect_value(g->entries, pos); if(current_node->name == n->name){ return current_node->seen; } pos++; } return false; } /** * graph_node_set_seen() - Set the seen status for a node. * @g: Graph storing the node. * @n: Node in the graph to set seen status for. * @s: Status to set. * * Returns: The modified graph. */ graph *graph_node_set_seen(graph *g, node *n, bool seen) { int pos = array_1d_low(g->entries); node *current_node = NULL; while(array_1d_has_value(g->entries, pos)){ current_node = array_1d_inspect_value(g->entries, pos); if(current_node->name == n->name){ current_node->seen = seen; return g; } pos++; } return g; } /** * graph_reset_seen() - Reset the seen status on all nodes in the graph. * @g: Graph to modify. * * Returns: The modified graph. */ graph *graph_reset_seen(graph *g){ int pos = array_1d_low(g->entries); node *current_node = NULL; while(array_1d_has_value(g->entries, pos)){ current_node = array_1d_inspect_value(g->entries, pos); current_node->seen = false; return g; pos++; } return g; } /** * graph_insert_edge() - Insert an edge into the graph. * @g: Graph to manipulate. * @n1: Source node (pointer) for the edge. * @n2: Destination node (pointer) for the edge. * * NOTE: Undefined unless both nodes are already in the graph. * * Returns: The modified graph. */ graph *graph_insert_edge(graph *g, node *n1, node *n2){ node *node_cmp = NULL; bool first_found = false; bool second_found = false; int pos = array_1d_low(g->entries); while(array_1d_has_value(g->entries, pos)){ node_cmp = array_1d_inspect_value(g->entries ,pos); if(strcmp(node_cmp->name, n1->name) == 0){ first_found = true; } if(strcmp(node_cmp->name, n2->name) == 0){ second_found = true; } if(first_found == true && second_found == true){ dlist_insert(n1->neighbours, n2->name, dlist_first(n1->neighbours)); } pos++; } return g; } /** * graph_choose_node() - Return an arbitrary node from the graph. * @g: Graph to inspect. * * Returns: A pointer to an arbitrayry node. * * NOTE: The return value is undefined for an empty graph. */ node *graph_choose_node(const graph *g){ node *arbt_node = NULL; arbt_node = array_1d_inspect_value(g->entries, array_1d_low(g->entries)); return arbt_node; } /** * graph_neighbours() - Return a list of neighbour nodes. * @g: Graph to inspect. * @n: Node to get neighbours for. * * Returns: A pointer to a list of nodes. Note: The list must be * dlist_kill()-ed after use. */ dlist *graph_neighbours(const graph *g,const node *n){ int pos = array_1d_low(g->entries); node *current_node = NULL; while(array_1d_has_value(g->entries, pos)){ current_node = array_1d_inspect_value(g->entries, pos); if(current_node->name == n->name){ return current_node->neighbours; } pos++; } return NULL; } /** * graph_kill() - Destroy a given graph. * @g: Graph to destroy. * * Return all dynamic memory used by the graph. * * Returns: Nothing. */ void graph_kill(graph *g){ int pos = array_1d_low(g->entries); node *current_node = NULL; while(array_1d_has_value(g->entries, pos)){ current_node = array_1d_inspect_value(g->entries, pos); dlist_kill(current_node->neighbours); free(current_node); pos++; } array_1d_kill(g->entries); free(g); }
C
#include "wrMeters.h" #include <stdlib.h> // malloc #include <stdio.h> // printf #include <math.h> VU_meter_t* VU_init( void ) { VU_meter_t* self = malloc( sizeof( VU_meter_t ) ); if( !self ){ printf("VU malloc failed\n"); return NULL; } self->smooth = lp1_init(); lp1_set_coeff( self->smooth, 0.018 ); return self; } void VU_deinit( VU_meter_t* self) { lp1_deinit( self->smooth ); free(self); self = NULL; } void VU_time( VU_meter_t* self, float slew) { lp1_set_coeff( self->smooth, slew ); } float VU_step( VU_meter_t* self, float in ) { // RMS return sqrtf( lp1_step( self->smooth , in * in ) ); }
C
#include <stdio.h> #include <stdlib.h> #include <conio.h> #include <unistd.h> #include "dask.h" int main(int argc, char **argv) { I16 card, err; U16 card_num; U16 acq_value; F64 v_acq_value; printf("Please input a card number: "); scanf(" %hd", &card_num); if((card=Register_Card (PCI_9221, card_num)) < 0) { printf("Register_Card error=%d", card); exit(1); } do{ clrscr(); usleep(100000); //err = AI_ReadChannel(card, 0, AD_B_5_V, &acq_value); err = AI_VReadChannel(card, 0, AD_B_5_V, &v_acq_value); if(err < 0){ printf("AI Read Ch0 Error: %d\n", err); exit(1); } //printf("\nAI CH0 ACQ Value: 0x%x\n", acq_value); printf("\nAI CH0 ACQ Value: %f\n", (F32)v_acq_value); printf("\n\n Press any key to exit...\n"); }while(!kb_hit()); err = Release_Card(card); if(err < 0){ printf("Release_Card error=%d", err); exit(1); } return 0; }
C
#include <string.h> #include <stdio.h> int main(int argc, char* argv[]) { char *world = "world"; printf("%ld\n", strcspn("hello", world)); // should be 2 printf("%ld\n", strcspn("banana", world)); // should be 6 return 0; }
C
#include<stdio.h> #include<math.h> void main() { int n,num,num1=0,num2,c=0; scanf("%d",&n); num=n; num2=n; while(num2!=0) { num2=num2/10; ++c; } while(num!=0) { int r=num%10; num1=num1+pow(r,c); num=num/10; } if(num1==n) printf("yes"); else printf("no"); }
C
#include"header.h" double** produit_vecteurv_vecteurh(double x[n],double y[n]) { double ** r; int i,j; r = (double**)malloc((n)*sizeof(double*)); for (i=0;i<n;i++) { r[i]=(double*)malloc((n)*sizeof(double)); } for(i=0;i<n;i++) { for(j=0;j<n;j++) { r[i][j]=x[i]*y[j]; } } return(r); }
C
/* * uart.c * * Created: 2013-12-17 22:19:36 * Author: Max */ #include <asf.h> #include <board.h> #include "uart.h" /** * \def BUFFER_SIZE * \brief The size of the UART buffer */ #define BUFFER_SIZE 128 // set the correct BAUD and F_CPU defines before including setbaud.h #include "conf_clock.h" #include "conf_uart.h" /** * \name avr_libc_inc avr libc include files * @{ */ #include <util/setbaud.h> #include <avr/interrupt.h> //! @} #include "ring_buffer.h" // buffers for use with the ring buffer (belong to the UART) uint8_t out_buffer[BUFFER_SIZE]; uint8_t in_buffer[BUFFER_SIZE]; //! ring buffer to use for the UART transmission struct ring_buffer ring_buffer_out; //! ring buffer to use for the UART reception struct ring_buffer ring_buffer_in; /** * \brief UART data register empty interrupt handler * * This handler is called each time the UART data register is available for * sending data. */ ISR(UART0_DATA_EMPTY_IRQ) { // if there is data in the ring buffer, fetch it and send it if (!ring_buffer_is_empty(&ring_buffer_out)) { UDR0 = ring_buffer_get(&ring_buffer_out); } else { // no more data to send, turn off data ready interrupt UCSR0B &= ~(1 << UDRIE0); } } /** * \brief Data RX interrupt handler * * This is the handler for UART receive data */ ISR(UART0_RX_IRQ) { ring_buffer_put(&ring_buffer_in, UDR0); } /** * \brief Initialize the UART with correct baud rate settings * * This function will initialize the UART baud rate registers with the correct * values using the AVR libc setbaud utility. In addition set the UART to * 8-bit, 1 stop and no parity. */ void uart_init(void) { // Enable the UART clock sysclk_enable_peripheral_clock(&UCSR0A); #if defined UBRR0H // get the values from the setbaud tool UBRR0H = UBRRH_VALUE; UBRR0L = UBRRL_VALUE; #else #error "Device is not supported by the driver" #endif #if USE_2X UCSR0A |= (1 << U2X0); #endif // enable RX and TX and set interrupts on rx complete UCSR0B = (1 << RXEN0) | (1 << TXEN0) | (1 << RXCIE0); // 8-bit, 1 stop bit, no parity, asynchronous UART UCSR0C = (1 << UCSZ01) | (1 << UCSZ00) | (0 << USBS0) | (0 << UPM01) | (0 << UPM00) | (0 << UMSEL01) | (0 << UMSEL00); // initialize the in and out buffer for the UART ring_buffer_out = ring_buffer_init(out_buffer, BUFFER_SIZE); ring_buffer_in = ring_buffer_init(in_buffer, BUFFER_SIZE); } /** * \brief Function for putting a char in the UART buffer * * \param data the data to add to the UART buffer and send * */ inline void uart_putchar(uint8_t data) { // Disable interrupts to get exclusive access to ring_buffer_out. cli(); if (ring_buffer_is_empty(&ring_buffer_out)) { // First data in buffer, enable data ready interrupt UCSR0B |= (1 << UDRIE0); } // Put data in buffer ring_buffer_put(&ring_buffer_out, data); // Re-enable interrupts sei(); } /** * \brief Function for getting a char from the UART receive buffer * * \retval Next data byte in receive buffer */ inline uint8_t uart_getchar(void) { return ring_buffer_get(&ring_buffer_in); } /** * \brief Function to check if we have a char waiting in the UART receive buffer * * \retval true if data is waiting * \retval false if no data is waiting */ inline bool uart_char_waiting(void) { return !ring_buffer_is_empty(&ring_buffer_in); }
C
#include <stdio.h> #include <stdlib.h> int main(){ int reslutado,a=2,b=3,c=4,d=5,cont=1; reslutado= a+b*c/d; printf("resultado %d\t %d\n",cont,reslutado); cont++; reslutado=a% 5%2+c; printf("resultado %d\t %d\n",cont,reslutado); cont++; reslutado=(a+b)*c %d; printf("resultado %d\t %d\n",cont,reslutado); cont++; reslutado= (d<65)&&(2-14==c+1); printf("resultado %d\t %d\n",cont,reslutado); cont++; reslutado=a<=b || (3>a); printf("resultado %d\t %d\n",cont,reslutado); cont++; reslutado=(c<=7+d) || (7>c); printf("resultado %d\t %d\n",cont,reslutado); cont++; reslutado=(a>d) && (2-14==c+1); printf("resultado %d\t %d\n",cont,reslutado); cont++; reslutado=a%d%c; printf("resultado %d\t %d\n",cont,reslutado); cont++; reslutado=3+5*d % 10; printf("resultado %d\t %d\n",cont,reslutado); cont++; reslutado=a/b %2; printf("resultado %d\t %d\n",cont,reslutado); cont++; reslutado=-a*7; printf("resultado %d\t %d\n",cont,reslutado); cont++; reslutado= (a>d ) && (b<c) || (d>5); printf("resultado %d\t %d\n",cont,reslutado); cont++; reslutado= ((a>b) || (a<c)) && ((a=c) ||(a>=b)); printf("resultado %d\t %d\n",cont,reslutado); cont++; cont++; reslutado = ((a>b) || (a<d)) && 16; printf("resultado %d\t %d\n",cont,reslutado); cont++; reslutado= ((a>=d) && (c>d)); printf("resultado %d\t %d\n",cont,reslutado); cont++; reslutado= !(a<=c) || (c>d); printf("resultado %d\t %d\n",cont,reslutado); cont++; return 0; }
C
#include<glib.h> GMainLoop* loop; int main(int argc, char* argv[]) { //g_thread_init是必需的,GMainLoop需要gthread库的支持。 if(g_thread_supported() == 0) g_thread_init(NULL); //创建一个循环体,先不管参数的意思。 g_print("g_main_loop_new\n"); loop = g_main_loop_new(NULL, FALSE); //让这个循环体跑起来 g_print("g_main_loop_run\n"); g_main_loop_run(loop); //循环运行完成后,计数器减一 //glib的很多结构类型和c++的智能指针相似,拥有一个计数器 //当计数器为0时,自动释放资源。 g_print("g_main_loop_unref\n"); g_main_loop_unref(loop); return 0; }
C
#include <stdio.h> #define SIZE 4 int sum[SIZE][SIZE] = {0}; int matrix[SIZE][SIZE] = { -1, -1, -3, -4, 1, 1, -4, -2, 1, 1, -3, -4, 1, 1, -2, -1, }; int sumBetween(int leftCol, int rightCol, int row) { int sum, i; sum = 0; for(i=leftCol;i<=rightCol;i++) sum = matrix[row][i] + sum; return sum; } int main() { int i, j, t_s, c_b, c_b_s; int x, y, z; int totalBestSum = -10000000; int row, col, leftCol, rightCol, rowSum; for (row = 0; row < SIZE; row++) { for (col = 0; col < SIZE; col++) { printf("%5d ", matrix[row][col]); } printf("\n"); } for (leftCol = 0; leftCol < SIZE; leftCol++) for (rightCol = leftCol; rightCol < SIZE; rightCol++) { int curSum = 0, curBestSum = -10000000; for (row = 0; row < SIZE; row++) { int rowSum = sumBetween(leftCol, rightCol, row); curSum += rowSum; if (curSum > curBestSum) { curBestSum = curSum; x = row; } if (curSum < 0) curSum = 0; } if (curBestSum > totalBestSum) { totalBestSum = curBestSum; y = leftCol; z = rightCol; } } printf("%d x %d y %d z %d\n", totalBestSum, x, y, z); return 0; }
C
#include <stdio.h> #include <string.h> /* Write a function setbits(x,p,n,y) that returns x with the n bits that begin at position p set to the rightmost n bits of y, leaving the other bits unchanged. */ unsigned int setbits(int x, int p, int n, int y) { for (int i = p; i < y; ++i) { x = x | (2<<i); } return x; } int main() { int x,p,n,y; scanf("%d%d%d%d", &x,&p,&n,&y); printf("%d\n", setbits(x,p,n,y)); return 0; }
C
#include <stdio.h> #define SET 2 #define ROW 3 #define COL 4 int main() { int i,j,k; int *a; int *fun1(); a = fun1(); for(i=0;i<SET;i++) { for(j=0;j<ROW;j++) { for(k=0;k<COL;k++) { printf("%d ",*(a+i*ROW + j*COL +k)); } printf("\n"); } } return 0; } int *fun1() { static int arr[SET][ROW][COL] = { {23,45,46,78, 89,90,65,32, 63,32,45,88 }, {20,34,67,90, 77,54,67,89, 92,56,75,32} }; return (int *)arr; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* show_alloc_mem.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ebouther <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/06/12 12:06:56 by ebouther #+# #+# */ /* Updated: 2017/06/12 15:09:17 by ebouther ### ########.fr */ /* */ /* ************************************************************************** */ #include "malloc.h" static unsigned int parse_blocks(t_block **blocks, char is_large) { t_block *block; unsigned int total; block = *blocks; total = 0; while (block) { if (block->freed == FALSE) { if (is_large) { disp_large_zone(block->addr); is_large = 0; } disp_blk(block->addr, block->size, 0); total += block->size; } else if (DEBUG) disp_blk(block->addr, block->size, 1); block = block->next; } return (total); } static unsigned int parse_zone(const char *zone_type, t_zone *zone) { unsigned int total; total = 0; while (zone) { ft_putstr((char *)zone_type); ft_putstr("0x"); ft_putstr(ft_lltoa_base((long long)zone->memory, HEX)); ft_putstr("\n"); total += parse_blocks(&zone->blocks, 0); zone = zone->next; } return (total); } void show_alloc_mem(void) { static pthread_mutex_t mutex; unsigned int total; mutex = (pthread_mutex_t)PTHREAD_MUTEX_INITIALIZER; pthread_mutex_lock(&mutex); total = 0; total += parse_zone("TINY : ", g_zones.tiny); total += parse_zone("SMALL : ", g_zones.small); total += parse_blocks(&g_zones.large, 1); ft_putstr("Total : "); ft_putstr(ft_lltoa_base(total, DEC)); ft_putstr(" octets\n"); pthread_mutex_unlock(&mutex); }
C
#include<stdio.h> #include<stdlib.h> #include<math.h> /* Define o tipo de dado no */ typedef struct NoTag { char info; struct NoTag *link; }no; void inicializa_Pilha(no **L) { /* atribui NULL ao ponteiro L */ *L = NULL; } void imprime_Pilha(no **L) { no *P; P = *L; // P recebe o endereco do primeiro no da lista printf("\n Itens da Pilha (lista LIFO):"); while(P != NULL) { printf("\n %d", P->info); P = P->link; } } void PUSH(no **L, char x) { /* declara um ponteiro denominado N */ no *N; /* aloca memria para armazenar o novo n e atribui o endereo da rea reservada para N */ N = (no *) malloc (sizeof(no)); /* armazena a informao no novo n */ N->info = x; /* o link do novo n recebe o endereo do n apontado por L ou seja , o link do novo n aponta para o antigo primeiro n da lista*/ N->link = *L; /* L recebe o endereo de N */ *L = N; } void POP(no **L, char *n) { no *AUX; /* verifica se existe dados na pilha */ if (*L != NULL) { /* faz a chamada recursiva da pilha */ *n = (*L)->info; /* o ponteiro AUX recebe o prximo da pilha*/ AUX = *L; /* aux recebe o prximo dado*/ *L = (*L)->link; /* o valor excluido (pop)*/ free(AUX); } } int main(void){ no *L; char aux[10]; int x, c; char choice[10]; inicializa_Pilha(&L); do{ printf("\n"); printf("PILHA \n"); printf("1 - PUSH\n"); printf("2 - POP\n"); printf("3 - Imprime Itens da PILHA\n"); printf("4 - Sair\n"); printf("\n Escolha: "); gets(choice); c = atoi(choice); switch(c){ case 1: printf(" \nEntre com o item a ser inserido na PILHA: "); gets(aux); x = atoi(aux); PUSH(&L,x); break; case 2: POP(&L,&x); printf(" \nItem retirado da PILHA: %d", x); break; case 3: imprime_Pilha(&L); break; case 4: exit(0); break; }; }while (c != 4); return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* rpn_calc.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ibotnaru <ibotnaru@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/05/17 21:37:41 by ibotnaru #+# #+# */ /* Updated: 2019/05/17 21:38:23 by ibotnaru ### ########.fr */ /* */ /* ************************************************************************** */ /* ** Assignment name : rpn_calc ** Expected files : *.c, *.h ** Allowed functions: atoi, printf, write, malloc, free ** -------------------------------------------------------------------------------- ** ** Write a program that takes a string which contains an equation written in ** Reverse Polish notation (RPN) as its first argument, evaluates the equation, and ** prints the result on the standard output followed by a newline. ** ** Reverse Polish Notation is a mathematical notation in which every operator ** follows all of its operands. In RPN, every operator encountered evaluates the ** previous 2 operands, and the result of this operation then becomes the first of ** the two operands for the subsequent operator. Operands and operators must be ** spaced by at least one space. ** ** You must implement the following operators : "+", "-", "*", "/", and "%". ** ** If the string isn't valid or there isn't exactly one argument, you must print ** "Error" on the standard output followed by a newline. ** ** All the given operands must fit in a "int". ** ** Examples of formulas converted in RPN: ** ** 3 + 4 >> 3 4 + ** ((1 * 2) * 3) - 4 >> 1 2 * 3 * 4 - ou 3 1 2 * * 4 - ** 50 * (5 - (10 / 9)) >> 5 10 9 / - 50 * ** ** Here's how to evaluate a formula in RPN: ** ** 1 2 * 3 * 4 - ** 2 3 * 4 - ** 6 4 - ** 2 ** ** Or: ** ** 3 1 2 * * 4 - ** 3 2 * 4 - ** 6 4 - ** 2 ** ** Examples: ** ** $> ./rpn_calc "1 2 * 3 * 4 +" | cat -e ** 10$ ** $> ./rpn_calc "1 2 3 4 +" | cat -e ** Error$ ** $> ./rpn_calc |cat -e ** Error$ */
C
/* This program demos sendrecv that will help to prevent deadlocks * It does the same random add as mpi2 */ #include <mpi.h> #include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]) { int my_rank; int nproc; MPI_Init(&argc, &argv); MPI_Comm_size(MPI_COMM_WORLD, &nproc); MPI_Comm_rank(MPI_COMM_WORLD, &my_rank); int r = rand()%10; printf("Rank: %d My number: %d \n", my_rank, r); int other; /* *int MPI_Sendrecv(void* sbuffer, int scount, MPI_Datatype stype, int dest, int stag, * void* rbuff, int rcount, MPI_Datatype, int source, int rtag, * MPI_COMM, MPI_STATUS); */ MPI_Status status; MPI_Sendrecv((void*) &r, 1, MPI_INT, (my_rank+1)%nproc, 1, (void*) &other, 1, MPI_INT, (my_rank-1+nproc)%nproc, 1, MPI_COMM_WORLD, &status); r += other; printf("Rank: %d sum: %d \n", my_rank, r); MPI_Finalize(); return 0; }
C
// Thyago Arthur Higgins Domingues BP 3008657 // Gabriel da Silva Camargo BP 3007642 #include <stdio.h> #include <stdio.h> #include <string.h> #include <locale.h> #include <stdlib.h> #include "funcao.h" int main () { setlocale (LC_CTYPE, "ptb"); // Permite a visualizao de informaes em portugues// int opcaoMenu1, opcaoMenu2, i,cont; candidato dados; vaga vet[10]; carregadadosarquivo (vet); do{ printf("\n0 - Iniciar o programa\n1 - Finalizar o programa\n"); scanf("%d", &opcaoMenu1); verificaopcao1(opcaoMenu1); if (opcaoMenu1 == 0){ do{ printf("\n0 - Entrar com idade"); printf("\n1 - Entrar com o sexo"); printf("\n2 - Entrar com a pretenso salarial"); printf("\n3 - Entrar com o nvel de escolaridade;"); printf("\n4 - Buscar vaga"); printf("\n5 - Quantidade de vagas disponveis"); printf("\n6 - Voltar ao menu anterior\n"); scanf("%d", &opcaoMenu2); verificaopcao2(opcaoMenu2); system ("cls"); switch (opcaoMenu2) { case 0: dados = carregadados(0); exibedadosdocand(dados); break; case 1: dados = carregadados(1); exibedadosdocand(dados); break; case 2: dados = carregadados(2); exibedadosdocand(dados); break; case 3: dados = carregadados(3); exibedadosdocand(dados); break; case 4: buscar_vaga (dados,vet); break; case 5: printf("\n\n VEJA AS VAGAS DISPONVEL:\n\n"); for(i = 0; i < 5; i++){ printf("%s\n%s\n%c\n%d\n%d\n%f\n%d\n\n", vet[i].cargo, vet[i].nivel, vet[i].sexo, vet[i].idadeMin, vet[i].idadeMax, vet[i].salario, vet[i].nvagas); } } }while (opcaoMenu2 != 6); } }while(opcaoMenu1 != 1); printf ("VOC OPTOU POR TERMINAR O PROGRAMA"); }
C
#include <sys/types.h> #include <errno.h> #include <string.h> #include <fcntl.h> #include <sys/stat.h> #include <stdio.h> #include <unistd.h> #include <stdlib.h> int main() { char filename[] = "data"; struct stat statbuf; if (stat(filename, &statbuf) == -1) { return EXIT_FAILURE; } // printf("st_dev: %lu\n", statbuf.st_dev); // printf("st_ino: %lu\n", statbuf.st_ino); // printf("st_mode: %d\n", statbuf.st_mode); // printf("st_nlink: %lu\n", statbuf.st_nlink); // printf("st_uid: %d\n", statbuf.st_uid); // printf("st_gid: %d\n", statbuf.st_gid); // printf("st_rdev: %lu\n", statbuf.st_rdev); //printf("st_size: %lu\n", statbuf.st_size); // printf("st_blksize: %lu\n", statbuf.st_blksize); // printf("st_blocks: %lu\n", statbuf.st_blocks); int fd; if ((fd = open(filename, O_RDWR|O_TRUNC)) == -1) { fprintf(stderr, "Error: Cannot open '%s'. %s\n", filename, strerror(errno)); } int n; off_t off; if ((n = write(fd, "asdf", 5)) != 5) { fprintf(stderr, "Error: Failed to write to file. %s\n", strerror(errno)); } off = lseek(fd, 3, 0); if ((n = write(fd, "asdf", 5)) != 5) { fprintf(stderr, "Error: Failed to write to file. %s\n", strerror(errno)); } if (stat(filename, &statbuf) == -1) { return EXIT_FAILURE; } printf("st_size: %lu\n", statbuf.st_size); printf("st_blksize: %lu\n", statbuf.st_blksize); printf("st_blocks: %lu\n", statbuf.st_blocks); if ((fd = close(fd)) == -1) { fprintf(stderr, "Error: Couldn't close '%s'. %s\n", filename, strerror(errno)); } }
C
/* ** EPITECH PROJECT, 2019 ** my_strcmp ** File description: ** return 1 if s1 is different and/or longer, 0 if same, -1 if shorter */ int my_strlen(char const *str); int my_strcmp(char const *s1, char const *s2) { int i = 0; for (i = 0; s1[i] != '\0' && s2[i] != '\0'; i++) { if (s1[i] > s2[i]) return 1; if (s1[i] < s2[i]) return -1; } if (s2[i] == '\0' && s1[i] != '\0') return 1; if (s1[i] == '\0' && s2[i] != '\0') return -1; return 0; }
C
#include "schedule.h" void schedule_initialization() { active_schedule.current_running_process_count = 0; active_schedule.next_terminal_in_schedule = 2; active_schedule.schedule_activated = 1; } //MP3.5 Scheduling //utilize the kernel stack (HALT) //again you will be using assembly to the context switch //switch esp/ebp to next process' kernel stack //restore the next process TSS //FLUSH TLB on process switch void schedule_handling() { cli(); int last_running_process; if(active_schedule.schedule_activated) { if(active_schedule.current_running_process_count < MAX_TERMINALS) // total # of terminals not max but not 0 { // can active_schedule another task // need to put current esp, ebp to the terminal struct before switching tasks if(active_schedule.current_running_process_count != 0) { asm volatile ( "movl %%esp, %0;" "movl %%ebp, %1;" : : "m"(terminal[active_terminal].current_esp), "m"(terminal[active_terminal].current_ebp) ); //m for memory address of this to be used } last_running_process = active_schedule.current_running_process_count; save_and_switch_term(last_running_process); // decrement because we want the previous terminal, not the incremented one active_terminal = last_running_process; active_schedule.current_running_process_count++; sti(); execute((uint8_t*)"shell"); } else if(active_schedule.current_running_process_count == MAX_TERMINALS) // all terminals just got instantiated { //already running max number of tasks asm volatile ( "movl %%esp, %0;" "movl %%ebp, %1;" : "=r"(terminal[2].current_esp), "=r"(terminal[2].current_ebp) //we can have 2 ); active_schedule.current_running_process_count++; save_and_switch_term(0); } else //need to round robin between existing tasks { asm volatile ( "movl %%esp, %0;" "movl %%ebp, %1;" : "=r"(terminal[active_schedule.next_terminal_in_schedule].current_esp), "=r"(terminal[active_schedule.next_terminal_in_schedule].current_ebp) //we can have 2 ); active_schedule.next_terminal_in_schedule++; active_schedule.next_terminal_in_schedule = active_schedule.next_terminal_in_schedule % 3; if(active_schedule.next_terminal_in_schedule != active_terminal){ //keeps keyboard from interrupting a different term than active disable_irq(0x01); //if pit is not looking at current term, keep keyboard from interrupting } else { enable_irq(0x01); //have to be able to type on current term } //set up paging int pid = terminal[active_schedule.next_terminal_in_schedule].process_num; pDirectory[32]=(EIGHTMB+(FOURMB*pid))|0x87; //0x87 permissions for program loading //tlb flush- change cr3 asm volatile ( "movl %%cr3, %%ebx;" "movl %%ebx, %%cr3;" : : :"%ebx" ); tss.esp0 = EIGHTMB - (EIGHTKB)*pid - 4; //gotten from piazza - (-4 for the spacing) asm volatile ( "movl %0, %%esp;" "movl %1, %%ebp;" : : "r"(terminal[active_schedule.next_terminal_in_schedule].current_esp), "r"(terminal[active_schedule.next_terminal_in_schedule].current_ebp) ); } sti(); } else { printf("schedule not yet activated for this OS"); } }
C
#include <stdio.h> int main() { int a = 3; printf("%d %d %d", a, ++a, a++); // in print arguments are passed from right to left // it depends upon compiler to compiler return 0; }
C
/********************************************************************************************** Snake game program. The game can be played on MZ_APO board. snake.c - Consists of fuctions necessary for initializing game board with snakes and borders, controlling movements of snakes, performing moves, generating food pieces, processing eating, and keeping the state of the game. Developed by: Silvia Goldasova Date: May 2020 ***********************************************************************************************/ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <strings.h> #include <stdint.h> #include <time.h> #include <unistd.h> #include <stdbool.h> #include <unistd.h> #include "mzapo_parlcd.h" #include "mzapo_phys.h" #include "mzapo_regs.h" #include "font_functions.h" #include "leds_interaction.h" #include "snake.h" #ifndef LCD_WIDTH #define LCD_WIDTH 480 #endif #ifndef LCD_HEIGHT #define LCD_HEIGHT 320 #endif #ifndef CELL_SIZE #define CELL_SIZE 20 #endif #ifndef BORDER_SIZE #define BORDER_SIZE 10 #endif #define APPLE_COLOR 0xE061 //0xC841 //red color #define SNAKE_COLOR 0xFFFF #define BORDER_COLOR 0xFFFE #define BORDER_SIZE 10 void printBoardToLcd(uint16_t * content, unsigned char * parlcd_mem_base) { parlcd_write_cmd(parlcd_mem_base, 0x2c); for (int i = 0; i < 320 * 480 ; i++) { parlcd_write_data(parlcd_mem_base, content[i]); } } void blackLcd(unsigned char * parlcd_mem_base) { parlcd_write_cmd(parlcd_mem_base, 0x2c); for (int i = 0; i < 320 * 480; i++) { parlcd_write_data(parlcd_mem_base, 0x0); } } bool isInRange(int currentRow, int currentCol, int pointX, int pointY, int range) { if ( (abs(currentRow-pointX) < range) && (abs(currentCol-pointY) < range) ) { return true; } return false; } void initializeSnakeAndDirection(int initX, int initY, int snakeLength, uint16_t * snakeArr, Cell ** directionArr) { int distance = CELL_SIZE / 2; int upperLeftCornerX = initX-distance; int upperLeftCornerY = initY-distance; int bottomRightCornerX = upperLeftCornerX + snakeLength * CELL_SIZE; int bottomRightCornerY = upperLeftCornerY + CELL_SIZE; //printf("pos initial (upper left point): [%d, %d]\r\n", upperLeftCornerX, upperLeftCornerY); //printf("pos initial (bottom right point): [%d, %d]\r\n", bottomRightCornerX, bottomRightCornerY); for(int row = upperLeftCornerY; row < bottomRightCornerY; row++) { for (int col = upperLeftCornerX; col < bottomRightCornerX; col++) { snakeArr[row * 480 + col] = 0xFFFF; //direction[row * 480 + col] = 'R'; } } for (int i = 0; i < snakeLength; i++) { directionArr[i] = (Cell *) malloc(sizeof(Cell)); directionArr[i] -> posX = initX; directionArr[i] -> posY = initY; directionArr[i] -> direction = 'R'; //printf("cell: pos [%d, %d], dir: %c; ", directionArr[i] ->posX, directionArr[i] -> posY, directionArr[i] -> direction); initX += CELL_SIZE; } } void initializeBorders(uint16_t * snakeArr) { int offsetToLastLine = (LCD_HEIGHT-1) * LCD_WIDTH; int offset = 0; for (int j = 0; j < BORDER_SIZE; j++) { for (int i = 0; i < LCD_WIDTH; i++) { snakeArr[offset+i] = BORDER_COLOR; snakeArr[i+offsetToLastLine-offset] = BORDER_COLOR; } offset += LCD_WIDTH; } int offsetToLastCol = LCD_WIDTH-1; for (int i = 0; i < LCD_HEIGHT * LCD_WIDTH; i += LCD_WIDTH) { for (int j = 0; j < BORDER_SIZE; j++) { snakeArr[j + i] = BORDER_COLOR; snakeArr[i+offsetToLastCol-j] = BORDER_COLOR; } } } void redrawSnakeCell(uint16_t * snakeArr, int posX, int posY, uint16_t color) { int distance = CELL_SIZE / 2; int upperLeftCornerX = posX - distance; int upperLeftCornerY = posY - distance; int bottomRightCornerX = upperLeftCornerX + CELL_SIZE; int bottomRightCornerY = upperLeftCornerY + CELL_SIZE; for(int row = upperLeftCornerY; row < bottomRightCornerY; row++) { for (int col = upperLeftCornerX; col < bottomRightCornerX; col++) { snakeArr[row * 480 + col] = color; } } } int addApple(uint16_t * snakeArr) { bool wasSuccess = false; int randomPosX, randomPosY, posInArr; int horizontalRange = (LCD_WIDTH - 6 * BORDER_SIZE) / CELL_SIZE; int verticalRange = (LCD_HEIGHT - 6 * BORDER_SIZE) / CELL_SIZE; while(!(wasSuccess)) { randomPosX = (rand() % horizontalRange) * CELL_SIZE + 2 * BORDER_SIZE; randomPosY = (rand() % verticalRange) * CELL_SIZE + 3 * BORDER_SIZE; posInArr = randomPosY * LCD_WIDTH + randomPosX; if (snakeArr[posInArr] == 0) { //printf("[%d, %d]; ", randomPosX, randomPosY); redrawSnakeCell(snakeArr, randomPosX, randomPosY, APPLE_COLOR); wasSuccess = true; } } return posInArr; } void distributeApples(uint16_t * snakeArr, int * applesArr, int applesCount){ for (int i = 0; i < applesCount; i++) { applesArr[i] = addApple(snakeArr); } } void shiftDirCell(Cell * cell, unsigned char prevCellDir) { switch (cell -> direction){ case 'U': cell -> posY = cell -> posY - CELL_SIZE; break; case 'D': cell -> posY = cell -> posY + CELL_SIZE; break; case 'L': cell -> posX = cell -> posX - CELL_SIZE; break; case 'R': cell -> posX = cell -> posX + CELL_SIZE; break; } cell -> direction = prevCellDir; // now direction of updated position (held in the cell closer to the head) } bool isWithinLCD(int posX, int posY){ if (posX < BORDER_SIZE || posX > LCD_WIDTH-BORDER_SIZE || posY < BORDER_SIZE || posY > LCD_HEIGHT-BORDER_SIZE) { return false; } return true; } bool isCellOccupied(uint16_t * snakeArr, Cell * head){ int posInSnakeArr = (head->posY) * 480 + head->posX; //printf("pos of head: [%d, %d], color: %hu\r\n", head->posX, head->posY, snakeArr[posInSnakeArr]); if (snakeArr[posInSnakeArr] == SNAKE_COLOR) { return true; } return false; } bool isApple(uint16_t * snakeArr, Cell * head) { int posInSnakeArr = (head->posY) * 480 + head->posX; if (snakeArr[posInSnakeArr] == (uint16_t) APPLE_COLOR) { return true; } return false; } bool snakeMakeMove(uint16_t * snakeArr, Cell ** directionArr, int * length, unsigned char * mem_base, bool * isEaten) { Cell * head = directionArr[*length-1]; int headPosX = head->posX; int headPosY = head->posY; shiftDirCell(head, head->direction); // shift head cell, direction stays if (!(isWithinLCD(head->posX, head->posY))) { return false; } if (isApple(snakeArr, head)){ *isEaten = true; redrawSnakeCell(snakeArr, head->posX, head->posY, 0xFFFF); directionArr[*length] = directionArr[*length-1]; directionArr[*length-1] = (Cell *) malloc(sizeof(Cell)); directionArr[*length-1] -> posX = headPosX; directionArr[*length-1] -> posY = headPosY; directionArr[*length-1] -> direction = directionArr[*length]->direction; *length = *length + 1; //printf("Apple eaten -> updated length: %d\r\n", *length); return true; } // changes in snake array: one to make disappear last cell and draw new head cell to the new position redrawSnakeCell(snakeArr, directionArr[0]->posX, directionArr[0]->posY, 0x0); // for all cells except head for (int i = 0; i < *length-1; i++) { shiftDirCell(directionArr[i], directionArr[i+1] -> direction); // shift a cell } if (isCellOccupied(snakeArr, head)) { // check if in snake array is blank position for the pos to which head is moved return false; } redrawSnakeCell(snakeArr, head->posX, head->posY, 0xFFFF); return true; } void updateDirection(Cell * cell, unsigned char newDirection) { cell -> direction = newDirection; } unsigned char getRandomDirection(unsigned char currentDir) { unsigned char verticalDirs[] = {'U', 'D'}; unsigned char horizontalDirs[] = {'L', 'R'}; int randomIndex = rand() % 2; //printf("random index: %d, ", randomIndex); if (currentDir == 'U' || currentDir == 'D') { return horizontalDirs[randomIndex]; } else { return verticalDirs[randomIndex]; } } unsigned char mapKeyToDirection(unsigned char lastDirection, char pressedKey) { // press 'a' for left, 'd' for right switch(lastDirection) { case 'R': if (pressedKey == 'a') // left return 'U'; else // right return 'D'; break; case 'L': if (pressedKey == 'a') // left return 'D'; else // right return 'U'; break; case 'U': if (pressedKey == 'a') // left return 'L'; else // right return 'R'; break; case 'D': if (pressedKey == 'a') // left return 'R'; else // right return 'L'; break; } //printf("pressedKey not identified"); return 'X'; } unsigned char getKeyboardInput(unsigned char lastDirection){ char keyPressed; int ret = read(0, &keyPressed, 1); if (ret != 1) return lastDirection; //printf("ret: %d, %c\r\n", ret, keyPressed); if (!(keyPressed == 'a' || keyPressed == 'd')) { if (keyPressed == 'e') return 'e'; return lastDirection; } unsigned char newDir = mapKeyToDirection(lastDirection, keyPressed); //printf("Updating cell head direction: from %c to %c\r\n", lastDirection, newDir); return newDir; } int isDirPossible(char lastDir, char desiredDir) { switch (lastDir) { case 'U': if (desiredDir != 'D') { return 1; } return -2; break; case 'R': if (desiredDir != 'L') { return 1; } return -2; break; case 'D': if (desiredDir != 'U') { return 1; } return -2; break; case 'L': if (desiredDir != 'R') { return 1; } return -2; break; default: printf("Nonexistent direction in isDirPossible"); break; } return 0; } char generateComputerMoveDir(uint16_t * board, int * chosenAppleIndex, int * applesArr, Cell * head, int applesCount){ while (*chosenAppleIndex == -1 || applesArr[*chosenAppleIndex] == -1) { *chosenAppleIndex = rand() % applesCount; } int applePosX = applesArr[*chosenAppleIndex] % LCD_WIDTH; int applePosY = (applesArr[*chosenAppleIndex] - applePosX) / LCD_WIDTH; //printf("going to [%d, %d] - ", applePosX, applePosY); int possibleDirs[4] = {'U', 'R', 'D', 'L'}; int possibleDirsVals[4] = {0, 0, 0, 0}; // is turn possible? for (int i = 0; i < 4; i++) { possibleDirsVals[i] = isDirPossible(head->direction, possibleDirs[i]); } // does it get snake head closer to the apple? if ((applePosX - head->posX) > 0) { possibleDirsVals[1] += 1; } else if ((applePosX - head->posX) < 0) { possibleDirsVals[3] += 1; } if (applePosY - head->posY > 0) { possibleDirsVals[2] += 1; } else if ((applePosY - head->posY) < 0) { possibleDirsVals[0] += 1; } int score = 2; while (1) { for (int i = 0; i < 4; i++) { if (possibleDirsVals[i] == score) return possibleDirs[i]; } score--; } } bool isAnyAppleLeft(int * applesArr, int len) { for (int i = 0; i < len; i++) { if (applesArr[i] != -1) { return true; } } return false; } void playRandomVsSSH(unsigned char *mem_base, unsigned char *parlcd_mem_base, int * snakeLengthS1, int * snakeLengthS2, uint16_t * board, Cell ** directionArrS1, Cell ** directionArrS2, int applesCount){ int applesArr[applesCount]; distributeApples(board, applesArr, applesCount); int chosenAppleIndex = -1; unsigned char currentDirS1 = 'R'; unsigned char currentDirS2 = 'R'; bool isGameOverS1 = false; bool isGameOverS2 = false; bool isEaten = false; while (!(isGameOverS1) || !(isGameOverS2)) { printBoardToLcd(board, parlcd_mem_base); sleep(0.5); // PLAYER MOVE //currentDir = getRandomDirection(currentDirS2); if (!(isGameOverS2)) { currentDirS2 = getKeyboardInput(currentDirS2); if (currentDirS2 == 'e') { isGameOverS2 = true; continue; } lightGreenLED(mem_base, 2); updateDirection(directionArrS2[*snakeLengthS2-1], currentDirS2); if (!(snakeMakeMove(board, directionArrS2, snakeLengthS2, mem_base, &isEaten))) { isGameOverS2 = true; lightRedLED(mem_base, 2); } if (isEaten) { lightBlueLED(mem_base, 2); for (int i = 0; i < applesCount; i++) { if (directionArrS2[*snakeLengthS2-1]->posY * LCD_WIDTH + directionArrS2[*snakeLengthS2-1]->posX == applesArr[i]) { applesArr[i] = -1; break; } } isEaten = false; if (!(isAnyAppleLeft(applesArr, applesCount))){ isGameOverS1 = true; isGameOverS2 = true; } } } // COMPUTER MOVE if (!(isGameOverS1)) { lightGreenLED(mem_base, 1); currentDirS1 = generateComputerMoveDir(board, &chosenAppleIndex, applesArr, directionArrS1[*snakeLengthS1-1], applesCount); //printf("current: %c - ", currentDirS1); updateDirection(directionArrS1[*snakeLengthS1-1], currentDirS1); if (!(snakeMakeMove(board, directionArrS1, snakeLengthS1, mem_base, &isEaten))) { isGameOverS1 = true; lightRedLED(mem_base, 1); //printf("Gameover for S1"); } if (isEaten) { applesArr[chosenAppleIndex] = -1; isEaten = false; lightBlueLED(mem_base, 1); if (!(isAnyAppleLeft(applesArr, applesCount))){ isGameOverS1 = true; isGameOverS2 = true; } } } } } void playRandomVsRandom(unsigned char *mem_base, unsigned char *parlcd_mem_base, int * snakeLengthS1, int * snakeLengthS2, uint16_t * board, Cell ** directionArrS1, Cell ** directionArrS2, int applesCount){ int applesArr[applesCount]; distributeApples(board, applesArr, applesCount); int chosenAppleIndexS1 = -1; int chosenAppleIndexS2 = -1; unsigned char currentDirS1 = 'R'; unsigned char currentDirS2 = 'R'; bool isGameOverS1 = false; bool isGameOverS2 = false; bool isEaten = false; while (!(isGameOverS1) || !(isGameOverS2)) { printBoardToLcd(board, parlcd_mem_base); sleep(0.8); // COMPUTER PLAYER MOVE if (!(isGameOverS2)) { lightGreenLED(mem_base, 2); currentDirS2 = generateComputerMoveDir(board, &chosenAppleIndexS2, applesArr, directionArrS2[*snakeLengthS2-1], applesCount); //printf("current: %c", currentDirS2); updateDirection(directionArrS2[*snakeLengthS2-1], currentDirS2); if (!(snakeMakeMove(board, directionArrS2, snakeLengthS2, mem_base, &isEaten))) { isGameOverS2 = true; lightRedLED(mem_base, 2); //printf("Gameover for S2"); } if (isEaten) { applesArr[chosenAppleIndexS2] = -1; isEaten = false; lightBlueLED(mem_base, 2); if (!(isAnyAppleLeft(applesArr, applesCount))){ isGameOverS1 = true; isGameOverS2 = true; } } } // COMPUTER MOVE if (!(isGameOverS1)) { lightGreenLED(mem_base, 1); currentDirS1 = generateComputerMoveDir(board, &chosenAppleIndexS1, applesArr, directionArrS1[*snakeLengthS1-1], applesCount); //printf("current: %c", currentDirS1); updateDirection(directionArrS1[*snakeLengthS1-1], currentDirS1); if (!(snakeMakeMove(board, directionArrS1, snakeLengthS1, mem_base, &isEaten))) { isGameOverS1 = true; lightRedLED(mem_base, 1); //printf("Gameover for S1"); } if (isEaten) { applesArr[chosenAppleIndexS1] = -1; isEaten = false; lightBlueLED(mem_base, 1); if (!(isAnyAppleLeft(applesArr, applesCount))){ isGameOverS1 = true; isGameOverS2 = true; } } } //printf("\r\napples left: "); for (int i = 0; i < applesCount; i++) { if (applesArr[i] != -1) { //printf("."); } } } }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_base64_output.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: omakovsk <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/02/16 18:53:11 by omakovsk #+# #+# */ /* Updated: 2019/02/16 18:53:13 by omakovsk ### ########.fr */ /* */ /* ************************************************************************** */ #include "ft_base64.h" void base64_result_output(unsigned char *result, t_crypt_info *crypt_info, unsigned int len) { unsigned int i; i = 1; if (result) { if (crypt_info->flags.output_file) write_to_file(result, len, crypt_info->flags.output_file, crypt_info->flags.d); else { while (i <= len) { write(1, result, 1); if ((i % 64) == 0 && i + 1 <= len && !crypt_info->flags.d) write(1, "\n", 1); i++; result++; } if (!crypt_info->flags.d) write(1, "\n", 1); } } } void write_to_file(unsigned char *result, unsigned int len, char *filename, uint8_t is_decode) { int fd; unsigned int i; i = 1; fd = open(filename, O_WRONLY | O_CREAT, 0644); if (fd == -1) ft_printf("unable to open file %s\n", filename); while (i <= len) { if (write(fd, result, 1) == -1) { ft_printf("unable to write to file %s\n", filename); return ; } if ((i % 64) == 0) write(fd, "\n", 1); i++; result++; } if (!is_decode && write(fd, "\n", 1) == -1) ft_printf("unable to write to file %s\n", filename); }
C
#include <unistd.h> void ft_putchar(char c) { write(1, &c, 1); } void ft_maff_alphabet() { char first; char second; int i; first = 'A'; second = 'b'; i = 0; while (i <= 12) { ft_putchar(first); ft_putchar(second); first = first + 2; second = second + 2; i++; } ft_putchar('\n'); } int main() { ft_maff_alphabet(); return (0); }
C
//Implements LRU cache #include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct Node{ struct Node *last, *next; char* fileName; char* fileContents; } Node; typedef struct Queue{ Node *first, *last; int size; int currentNum; } Queue; Node* createNode(char* fileName, char* fileContents); Queue* queueInit(int size); int isQueueEmpty(Queue *queue); int isQueueFull(Queue *queue); void deQueue(Queue *queue); void enQueue(Queue *queue, char* fileName, char* fileContents); Node* isInQueue(Queue *queue, char* fileName); Node* createNode(char* fileName, char* fileContents) { Node *newNode = (Node *)malloc(sizeof(Node)); newNode->fileName = fileName; newNode->fileContents = fileContents; newNode->last = newNode->next = NULL; return newNode; } Queue* queueInit(int size) { Queue *newQueue = (Queue *)malloc(sizeof(Queue)); newQueue->size = size; newQueue->currentNum = 0; newQueue->first = newQueue->last = NULL; return newQueue; } int isQueueEmpty(Queue *queue) { if(queue->currentNum == 0) return 1; else return 0; } int isQueueFull(Queue *queue) { if(queue->currentNum == queue->size) return 1; else return 0; } void deQueue(Queue *queue) { printf("Dequeuing...\n"); Node *temp = queue->last; queue->last->last->next = NULL; queue->last = queue->last->last; queue->currentNum -= 1; free(temp); } void enQueue(Queue *queue, char* fileName, char* fileContents) { if(isQueueFull(queue)) { deQueue(queue); } Node *newNode = createNode(fileName, fileContents); Node *temp = queue->first; if(temp == NULL) { queue->first = newNode; queue->last = newNode; } else { temp->last = newNode; newNode->next = queue->first; queue->first->last = newNode; queue->first = newNode; } queue->currentNum += 1; } Node* isInQueue(Queue *queue, char* fileName) { Node *temp = queue->first; while(temp != NULL) { if(strcmp(temp->fileName,fileName)==0) return temp; temp = temp->next; } return NULL; } int main(int argc, char** argv) { Queue *queue = queueInit(3); enQueue(queue, "1", "firstOne"); enQueue(queue, "2", "secondOne"); enQueue(queue, "3", "thirdOne"); enQueue(queue, "4", "fourthOne"); Node *temp = isInQueue(queue, "3"); if(temp == NULL) { printf("uh oh, couldn't find the node!"); return 1; } printf("Found node: %s\n", temp->fileName); return 0; }
C
#include <stdio.h> #define MAX 4 struct part { short number; char name[10]; } data[MAX] = {1, "Smith", 2, "Jones", 3, "Adams", 4, "Wilson", }; struct part *p_part; int count; int main (void) { p_part=data; for (count = 0 ; count < MAX ; count++) { printf("At address %p: %d %s\n", p_part, p_part->number, p_part->name); p_part++; } return 0; }
C
#ifndef JZ_STRING_H #define JZ_STRING_H #include <unicode/ustring.h> #include "jazz.h" #include "value.h" #include "gc.h" typedef struct { jz_gc_header gc; UChar str[1]; } jz_str_value; struct jz_str { jz_gc_header gc; int start; int length; unsigned int hash; /* TODO: uint32 */ union { const UChar* ext; jz_str_value* val; } value; }; #define JZ_STR_EXT_BIT 2 #define JZ_STR_HASHED_BIT 3 #define JZ_STR_IS_EXT(str) JZ_BIT(str->gc.tag, JZ_STR_EXT_BIT) #define JZ_STR_IS_INT(str) (!JZ_STR_IS_EXT(str)) #define JZ_STR_IS_HASHED(str) JZ_BIT(str->gc.tag, JZ_STR_HASHED_BIT) #define JZ_STR_PTR(string) \ ((JZ_STR_IS_EXT(string) ? (string)->value.ext : \ (string)->value.val->str) + (string)->start) #define JZ_STR_INT_PTR(string) \ (assert(!JZ_STR_IS_EXT(string)), (string)->value.val->str + (string)->start) /* Creates a new jz_str* from external string data. This is shallow, so the 'value' member is the same as the 'value' argument. */ jz_str* jz_str_external(JZ_STATE, int length, const UChar* value); /* Creates a new jz_str*. This is deep, so the character data is copied out of the 'value' argument into a newly allocated 'value' member. */ jz_str* jz_str_deep_new(JZ_STATE, int length, const UChar* value); /* Allocates space a new jz_str*, but sets the length to 0. The UChar* buffer can be accessed with JZ_STR_INT_PTR. */ jz_str* jz_str_alloc(JZ_STATE, int space); /* Returns a null jz_str*. This means that 'length' is 0 and 'value' is NULL. The string itself isn't null, though, and must be freed when no longer in use. */ jz_str* jz_str_null(JZ_STATE); /* Creates a shallow duplicate of 'this'. This means that both 'this' and the return value point to the same character string. */ jz_str* jz_str_dup(JZ_STATE, const jz_str* this); /* Creates a deep duplicate of 'this'. This means that the data of the 'value' member of 'this' is copied to a newly allocated 'value' member of the return value. */ jz_str* jz_str_deep_dup(JZ_STATE, const jz_str* this); jz_str* jz_str_substr(JZ_STATE, const jz_str* this, int start); /* Returns a shallow substring of 'this', beginning at the index 'start' and going through the index 'end'. This is shallow, so the new string is pointing to the same character array as 'this'. */ jz_str* jz_str_substr2(JZ_STATE, const jz_str* this, int start, int end); /* Shallow */ jz_str* jz_str_strip(JZ_STATE, const jz_str* this); /* Deep */ jz_str* jz_str_concat(JZ_STATE, const jz_str* s1, const jz_str* s2); /* Returns whether or not s1 and s2 are equivalent strings. */ jz_bool jz_str_equal(JZ_STATE, const jz_str* s1, const jz_str* s2); /* Returns an integer indicating how s1 and s2 are ordered relative to each other. The return value is > 0 if s1 > s2, < 0 if s1 < s2, and 0 if s1 == s2. The ordering is defined by the ECMAscript spec. */ int jz_str_comp(JZ_STATE, const jz_str* s1, const jz_str* s2); double jz_str_to_num(JZ_STATE, const jz_str* this); unsigned int jz_str_hash(JZ_STATE, jz_str* this); /* Returns a newly allocated character array containing 'this' transcoded into UTF-8. */ char* jz_str_to_chars(JZ_STATE, const jz_str* this); #define jz_str_from_literal(jz, value) \ jz_str_from_chars(jz, value, sizeof(value) - 1) jz_str* jz_str_from_chars(JZ_STATE, const char* value, int length); #endif
C
/** @author @file main.c @brief ENTER discription */ /******************************************************************************/ /* INCLUDED FILES */ /******************************************************************************/ #include <avr/io.h> // newly added #include <util/delay.h> #include <stdio.h> #include "lcd.h" /******************************************************************************/ /* FUNCTIONS */ /******************************************************************************/ /** @brief Init the microcontroller */ void init(void){ // Digital I/O init---------------------------------------------------- DDRB &= ~(1 << DDB0); // PB0 as Input (key 1) PORTB |= ( 1 << PB0); // Pullup PB0 DDRB |= (1 << DDB1); // PB1 as Output (LED red) DDRB |= (1 << DDB2); // PB1 as Output (LED yellow) DDRB |= (1 << DDB3); // PB1 as Output (LED green) } /******************************************************************************/ /** @brief Main function @return only a dummy to avoid a compiler warning, not used */ int main(void){ init(); // Loop forever while (1){ if (~PINB & (1<<PB0)){ PORTB |= (1<<PB1); _delay_ms(20); PORTB &= ~(1<<PB1); _delay_ms(50); } else { PORTB |= (1<<PB1); } } return 0; } /******************************************************************************/
C
#include "complexe.h" #include "mnblas.h" //VECTEUR typedef float* vfloat ; typedef double* vdouble ; typedef complexe_float_t* vcfloat ; typedef complexe_double_t* vcdouble ; //Initialise toutes les composantes d'un vecteur avec une unique valeur vfloat vector_init_float (int size, float x) ; vdouble vector_init_double (int size, double x) ; vcfloat vector_init_float_complexe (int size, complexe_float_t x) ; vcdouble vector_init_double_complexe (int size, complexe_double_t x) ; //Affiche toutes les composantes d'un vecteur void vector_print_float (int size, vfloat V) ; void vector_print_double (int size, vdouble V) ; void vector_print_float_complexe (int size, vcfloat V) ; void vector_print_double_complexe (int size, vcdouble V) ; //MATRICE typedef float* mfloat ; typedef double* mdouble ; typedef complexe_float_t* mcfloat ; typedef complexe_double_t* mcdouble ; //Initialise toutes les composantes d'un vecteur avec une unique valeur mfloat matrix_init_float (int row, int col, float x) ; mdouble matrix_init_double (int row, int col, double x) ; mcfloat matrix_init_float_complexe (int row, int col, complexe_float_t x) ; mcdouble matrix_init_double_complexe (int row, int col, complexe_double_t x) ; //Affiche toutes les composantes d'un vecteur void matrix_print_float (MNCBLAS_LAYOUT Layout, int row, int col, mfloat M) ; void matrix_print_double (MNCBLAS_LAYOUT Layout, int row, int col, mdouble M) ; void matrix_print_float_complexe (MNCBLAS_LAYOUT Layout, int row, int col, mcfloat M) ; void matrix_print_double_complexe (MNCBLAS_LAYOUT Layout, int row, int col, mcdouble M) ;
C
/* Matthew Kim PP6 4/27/18 Roller Coaster Problem coaster.h */ #include <stdio.h> #include <stdlib.h> #include <pthread.h> #include <stdbool.h> #include <unistd.h> int CarCapacity, Passengers,carcount,state; int PassengersInCar; bool isWaiting = false; pthread_cond_t carunload; pthread_cond_t carload; pthread_cond_t fullcar; pthread_cond_t carfirst; pthread_mutex_t rollerCoaster; void takeRide(int* x); void load(); void unload(); void carThread(); int main(int argc, char *argv[]){ if (argc != 3){ puts("Please enter (Number of Passengers) and (Car Capacity).\n"); exit(0); } else { Passengers = atoi(argv[1]); CarCapacity = atoi(argv[2]); } PassengersInCar = 0; pthread_t rider[Passengers]; printf("Number of passengers: %d\n", Passengers); printf("Capacity of cars: %d\n", CarCapacity); carcount = 0; state = 0; pthread_mutex_init(&rollerCoaster, NULL); pthread_cond_init(&carload, NULL); pthread_cond_init(&carunload, NULL); pthread_cond_init(&fullcar, NULL); pthread_cond_init(&carfirst,NULL); pthread_t Car; pthread_create(&Car,NULL,(void*) carThread,NULL); sleep(1); for (int i = 1; i != Passengers+1; i++){ int *x; x = (int *)malloc(sizeof(int)); *x = i; pthread_create(&(rider[i]),NULL, (void *) takeRide, x); } pthread_join(Car, NULL); for (int i = 0; i < Passengers; i++){ pthread_join(rider[Passengers],NULL); } return 0; }
C
/* * ===================================================================================== * * Filename: 1880.c * * Description: Psych Up's Eigenvalues * * ===================================================================================== */ #include <stdio.h> #include <stdlib.h> #define NUM 3 int binSearch(int *arr, int len, int to_be_find) { int low = 0; int high = len - 1; while(low <= high) { int mid = (low + high) / 2; if(arr[mid] > to_be_find) high = mid - 1; else if(arr[mid] < to_be_find) low = mid + 1; else return 1; } return 0; } int main(void) { int i,j; int *a[NUM]; int len[NUM]; int count = 0; for(i = 0; i < NUM; i++) { scanf("%d", &len[i]); a[i] = malloc(len[i] * sizeof(int)); if(a[i] == NULL) return -1; for(j = 0; j < len[i]; j++) scanf("%d", &a[i][j]); } for(j = 0; j < len[0]; j++) { if(binSearch(a[1], len[1], a[0][j]) && binSearch(a[2], len[2], a[0][j])) ++count; } printf("%d\n", count); return 0; }
C
#include <std.h> #include "/d/dagger/marsh/tower/short.h" inherit TROOM; int FLAG; void init() { ::init(); add_action("insert_fun","insert"); } void create() { ::create(); set_property("light",0); set_property("indoors",1); set_property("no teleport",1); set_long("%^RED%^" "The small and cramped chamber is made of the same %^BOLD%^" "blood-red%^RESET%^%^RED%^ stone as seen in other parts of the tower. " "The stone calls out to you as though it is alive and held captive in " "an endless state of torment. Old rusted torch brackets hang broken " "from the walls. Cobwebs fill the chamber, as though nothing has entered " "this area of the tower for years. A %^BLUE%^pedestal%^RED%^ sits " "in the center of the room. No dust or cobwebs gather upon the %^BLUE%^pedestal%^RED%^. " "A small %^GREEN%^depression%^RED%^ is located on the top side of the %^BLUE%^pedastal%^RED%^." "%^RESET%^" ); set_short("%^RED%^Cramped Chamber%^RESET%^"); set_listen("default", "It is silent, yet the silence is filled with cosmic sounds." ); set_smell("default", "The smell of ancient decay surrounds you." ); set_items(([ "stone":"%^RED%^The stone used to form the chamber is made from an unknown " "material and seems to glow in it's blood-red colour. As you gaze upon it, " "you hear the distant laughter of Grazzt.%^RESET%^", "brackets":"%^ORANGE%^The brackets hang broken from the walls.", "cobwebs":"The cobwebs cover the ceiling and the walls of the chamber.", "pedestal":"The pedestal is small and plain looking. A small depression is located " "within the top side of it.", "depression":"The depression looks as though a gem or a jewel or a stone could be inserted into it.", ])); set_exits(([ "east": RPATH "e3", ])); } int insert_fun(string str) { object GEM; if(!str) { notify_fail("Insert what into what?\n"); return 0; } if(str != "gem into depression") { notify_fail("Insert what into what?\n"); return 0; } if(!present("gem",TP)) { notify_fail("You don't have a gem to insert!\n"); return 0; } if(!(GEM = present("demongem2",TP))) { notify_fail("That gem does not fit into the depression!\n"); return 0; } if(FLAG == 1) { notify_fail("The portal is already open!\n"); return 0; } write( "%^RED%^You insert the demongem into the depression!\nA slow rumble fills the chamber!\n" "%^BLUE%^A portal appears!%^RESET%^" ); say( "%^RED%^"+TPQCN+" inserts a gem into the depression!\nA slow rumble fills the chamber!\n" "%^BLUE%^A portal appears!%^RESET%^" ,TP); GEM->remove(); TO->add_exit( RPATH "e14","portal"); FLAG = 1; return 1; } void reset() { if(FLAG == 1) { FLAG = 0; set_exits(([ "east": RPATH "e3", ])); } }
C
#include<stdio.h> #include<string.h> #define max(a,b) ((a)>(b)?(a):(b)) int main() { char s[100001]; scanf("%s",s); int o1[26]={0}; int o2[26][26]={0}; int length=strlen(s); for(int i=0; i<length; i++) { for(int j=0; j<i; j++) o2[j][s[i]-'a']+=o1[s[i]-'a']; o1[s[i]-'a']++; } int max1=0; for(int i=0; i<26; i++) max1=max(max1,o1[i]); int max2=0; for(int i=0; i<26; i++) for(int j=0; j<26; j++) max2=max(max2,o2[i][j]); printf("%d\n",max(max1, max2)); }
C
#include <stdio.h> #include <stdbool.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <fcntl.h> #include <sys/mman.h> #include <sys/stat.h> #include <semaphore.h> #include <pthread.h> #include <unistd.h> #include "c_queue.h" typedef struct ans ans; struct ans { int cmd; int val; char path[32]; }; typedef struct node node,*pnode; struct node { pnode s; pnode b; int val; bool is_root; }; pnode node_create(int val) { pnode new_node = (pnode)malloc(sizeof(node)); if (new_node) { new_node -> val = val; new_node -> s = NULL; new_node -> b = NULL; new_node -> is_root = false; } return new_node; } pnode* search(pnode* t, queue *path) { if (!(*t) && !q_is_empty(path)) { return NULL; } if (!q_is_empty(path)) { char c = q_front(path); pop(path); if (c == 's') { return search(&(*t) -> s, path); } else if (c == 'b') { return search(&(*t) -> b, path); } return NULL; } return t; } bool add(pnode* t, int val, queue *path) { if (!(*t) && q_is_empty(path)) { (*t) = node_create(val); return true; } pnode* pr = search(t, path); if (!pr) { return false; } pnode new_node = node_create(val); if (!new_node) { return false; } new_node -> b = (*pr); (*pr) = new_node; return true; } void rmv(pnode* t) { while((*t) -> s != NULL){ rmv(&((*t) -> s)); } pnode tmp = *t; *t = (*t) -> b; free(tmp); } bool valid_numb(char* numb) { if (numb == NULL) { return false; } bool flag = true; int i = 0; if (numb[i] != '-' && !(numb[i] >= '0' && numb[i] <= '9')) { flag = false; } i++; while (i < 11) { if (numb[i] == '\0') { break; } if (!(numb[i] >= '0' && numb[i] <= '9')) { flag = false; break; } i++; } return flag; } bool valid_path(char* path) { if (path == NULL) { return false; } if (path[0] == '@' && path[1] == '\0') { return true; } for (int i = 0; i < 32; i++) { if (path[i] == '\0') { break; } else if (path[i] != 's' && path[i] != 'b') { return false; } } return true; } ans* parser(char* cmd) { ans* parsed = (ans*)malloc(sizeof(ans)); char* pch = strtok(cmd," \n"); while (pch != NULL) { if (strcmp(pch, "prt") == 0) { parsed->cmd = 0; break; } else if (strcmp(pch, "rmv") == 0) { pch = strtok(NULL, " \n"); if (valid_path(pch)) { parsed->cmd = 1; strcpy(parsed->path, pch); if (parsed->path[0] == 'b') { parsed->cmd = -1; } break; } else { parsed->cmd = -1; break; } } else if (strcmp(pch, "add") == 0) { pch = strtok(NULL, " \n"); if (valid_path(pch)) { strcpy(parsed->path, pch); pch = strtok(NULL, " \n"); if (parsed->path[0] == 'b') { parsed->cmd = -1; break; } if (valid_numb(pch)) { parsed->cmd = 2; parsed->val = atoi(pch); break; } else { parsed->cmd = -2; break; } } else { parsed->cmd = -1; break; } } else if (strcmp(pch, "ext") == 0) { parsed->cmd = 3; break; } else { parsed->cmd = -777; break; } } return parsed; } void tree_print(pnode t, int depth) { if (t) { for (int i = 0; i < depth; i++) { write(1, "\t", 1); } char numb[11] = {'\0'}; sprintf(numb, "%d", t->val); int i = 0; while (numb[i] != '\0') { i++; } write(1, numb, i); write(1,"\n", 1); tree_print(t -> s, depth + 1); tree_print(t -> b, depth); } } int create_tmp() { char *fn = strdup("/tmp/tmpf.XXXXXX"); int fd = mkstemp(fn); unlink(fn); free(fn); write(fd, " ", 100); return fd; } int main(int argc, char* argv[]) { setvbuf(stdout, (char *) NULL, _IONBF, 0); pnode test = NULL; char cmd[100] = {'\0'}; ans *parsed = (ans *) malloc(sizeof(ans)); int fd = create_tmp(); lseek(fd, 100, SEEK_END); write(fd, "", 1); struct stat sb; if (fstat(fd, &sb) == -1) { perror("can't get file size\n"); } int fsize = sb.st_size; char* f_in_m = mmap(NULL, fsize, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); sem_t* sem_calc = sem_open("/calc", O_CREAT, 777, 0); if (sem_calc == SEM_FAILED) { perror("Semaphores doesn't create"); exit(1); } sem_unlink("/calc"); pid_t pr = -1; pr = fork(); if (pr < 0) { write(1, "Can't create process\n", 22); } else if (pr > 0) { while (read(0, cmd, 100)) { parsed = parser(cmd); sprintf(f_in_m, "%d %d %s", parsed->cmd, parsed->val, parsed->path); if (parsed->cmd == 3) { return 0; } for (int i = 0; i < 100; i++) { cmd[i] = '\0'; } sem_post(sem_calc); } sem_post(sem_calc); close(fd); } else { while (1) { sem_wait(sem_calc); queue *q = q_create(); sscanf(f_in_m, "%d %d %32s", &parsed->cmd, &parsed->val, parsed->path); int k = 0; while (parsed->path[k] != '\0') { push(q, parsed->path[k]); k++; } if (q_size(q) == 0) { push(q, '\0'); } if (parsed->cmd == 3) { return 0; } else if (parsed->cmd == 2) { if (test == NULL) { while (q_size(q) != 0) { pop(q); } test = node_create(parsed->val); test->is_root = true; } else { add(&test, parsed->val, q); } } else if (parsed->cmd == 1) { pnode* f = search(&test, q); if (test == NULL) { write(1, "empty tree\n", 11); } else if ((*f) == NULL) { write(1, "its root\n", 9); rmv(&test); } else { rmv(f); } } else if (parsed->cmd == 0) { if (test == NULL) { write(1, "empty tree\n", 11); } else { tree_print(test, 0); } } else if (parsed->cmd == -2){ write(1, "invalid value\n", 14); } else if (parsed->cmd == -1) { write(1, "invalid path\n", 13); } else if (parsed->cmd == -777) { write(1, "invalid command\n", 16); } q_destroy(q); lseek(fd, 0, SEEK_SET); write(fd, "", 100); } sem_close(sem_calc); munmap(f_in_m, 100); lseek(fd, 0, SEEK_SET); write(fd, "", 100); close(fd); } return 0; }
C
//https://www.interviewbit.com/problems/partition-list/ listnode* partition(listnode* A, int B) { if(A==NULL || A->next ==NULL)return A; listnode *prev = NULL; listnode *temp = A; listnode *store = NULL; listnode *next = NULL; while(temp->next!=NULL) { if(temp->val>=B) { store = prev; break; } prev = temp; temp = temp->next; } while(temp->next!=NULL) { if(temp->next->val<B) { prev = temp->next; temp->next = temp->next->next; if(store ==NULL) { next = A; A = prev; prev->next = next; store = A; continue; } next = store->next; store->next = prev; prev->next = next; store = store->next; continue; } temp = temp->next; } return A; }
C
/* mulTTY -> make an identity for a program * * From: Rick van Rein <rick@openfortress.nl> */ #include <arpa2/multty.h> /* Construct a standard identity structure from an identity string * (up to 32 chars) with an optionally appended <US> when it will * carry along a description. * * Return true on success, or else false. */ bool mtyp_mkid (const char *id, bool with_descr, MULTTY_PROGID prgid) { int idlen = strlen (id); if ((idlen > 32) || (!mtyescapefree (MULTTY_ESC_BINARY, id, idlen))) { return false; } memcpy (prgid, id, idlen); memset (prgid+idlen, 0, sizeof (MULTTY_PROGID) - idlen); if (with_descr) { prgid [idlen] = c_US; } return true; }
C
#include "private/ff_common.h" #include "private/ff_fiber.h" #include "private/ff_event.h" #include "private/ff_core.h" #include "private/arch/ff_arch_fiber.h" #define DEFAULT_FIBER_STACK_SIZE 0x10000 struct ff_fiber { /* context, which will be passed to the func */ void *ctx; /* the function, which will be executed in the fiber */ ff_fiber_func func; /* the event, which is used by ff_fiber_join() */ struct ff_event *stop_event; /* platform-specific fiber */ struct ff_arch_fiber *arch_fiber; }; static struct ff_fiber main_fiber; static struct ff_fiber *current_fiber = NULL; /** * @private * The entry point for arch_fiber */ static void generic_arch_fiber_func(void *ctx) { struct ff_fiber *fiber; fiber = (struct ff_fiber *) ctx; fiber->func(fiber->ctx); ff_event_set(fiber->stop_event); ff_core_yield_fiber(); ff_assert(0); } void ff_fiber_initialize() { ff_assert(current_fiber == NULL); main_fiber.ctx = NULL; main_fiber.func = NULL; main_fiber.stop_event = NULL; main_fiber.arch_fiber = ff_arch_fiber_initialize(); current_fiber = &main_fiber; } void ff_fiber_shutdown() { ff_assert(current_fiber == &main_fiber); ff_arch_fiber_shutdown(main_fiber.arch_fiber); current_fiber = NULL; } void ff_fiber_switch(struct ff_fiber *fiber) { if (fiber != current_fiber) { current_fiber = fiber; ff_arch_fiber_switch(fiber->arch_fiber); } } struct ff_fiber *ff_fiber_create(ff_fiber_func fiber_func, int stack_size) { struct ff_fiber *fiber; ff_assert(stack_size >= 0); if (stack_size == 0) { stack_size = DEFAULT_FIBER_STACK_SIZE; } fiber = (struct ff_fiber *) ff_malloc(sizeof(*fiber)); fiber->ctx = NULL; fiber->func = fiber_func; fiber->stop_event = ff_event_create(FF_EVENT_MANUAL); fiber->arch_fiber = ff_arch_fiber_create(generic_arch_fiber_func, fiber, stack_size); return fiber; } void ff_fiber_delete(struct ff_fiber *fiber) { ff_assert(fiber != current_fiber); ff_assert(fiber != &main_fiber); ff_arch_fiber_delete(fiber->arch_fiber); ff_event_delete(fiber->stop_event); ff_free(fiber); } void ff_fiber_start(struct ff_fiber *fiber, void *ctx) { ff_assert(fiber != current_fiber); ff_assert(fiber != &main_fiber); fiber->ctx = ctx; ff_core_schedule_fiber(fiber); } void ff_fiber_join(struct ff_fiber *fiber) { ff_assert(fiber != current_fiber); ff_assert(fiber != &main_fiber); ff_event_wait(fiber->stop_event); } struct ff_fiber *ff_fiber_get_current() { return current_fiber; }
C
#include<stdio.h> void num(int a[n],int n,int *max,int *min) { int i; *min=*max=a[0]; for(i=1;i<n;i++) { if(a[i]>*max) { *max=a[i]; } else if(a[i]<*min) { *min=a[i]; } } } int main() { int i,n,j,min,max; printf("enter the length of an array: "); scanf("%d",&n); int a[n]; printf("enter the array elements one by one :\n"); for(i=0;i<n;i++) { scanf("%d",&a[i]); } num(a[n],n,&max,&min); printf("largest element is: %d ",max); printf("\nsmallest element is: %d ",min); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <stdarg.h> void show_array(const double ar[], int n); double *new_d_array(int n, ...); int main(void) { double *p1; double *p2; p1 = new_d_array(5, 1.2, 2.3, 3.4, 4.5, 5.6); p2 = new_d_array(4, 100.0, 20.00, 8.08, -1890.0); show_array(p1, 5); show_array(p2, 4); free(p1); free(p2); return 0; } double *new_d_array(int n, ...) { double * ptd; va_list ap; ptd = (double *) malloc(n * sizeof(double)); int i; va_start(ap, n); for (i = 0; i < n; i++) ptd[i] = va_arg(ap, double); va_end(ap); return ptd; } void show_array(const double ar[], int n) { int index; for (index = 0; index < n; index++) printf("%10.2f ", ar[index]); putchar('\n'); }
C
/* Name: Sharan Rathnakumar Date: 17th October 2022 Description: WAP to generate AP, GP, HP series Input: Enter the First Number 'A': 2 Enter the Common Difference / Ratio 'R': 3 Enter the number of terms 'N': 5 Output: AP = 2, 5, 8, 11, 14 GP = 2, 6, 18, 54, 162 HP = 0.500000, 0.200000, 0.125000, 0.090909, 0.071428 */ #include<stdio.h> int main() { int i,FirstNum,Ap,Gp,ratio,num; //Initialising Variables as integer float Hp; //Initialising Hp variable as float // printf("Enter the First Number 'A':"); //Asks user to enter first number scanf("%d",&FirstNum); //Take input from user and store in FirstNum variable // printf("Enter the Common Difference / Ratio 'R':"); //Asks user to enter common difference/ratio scanf("%d",&ratio); //Take input from user and store it to ratio variable // printf("Enter the number of terms 'N':"); //Asks user to enter number of terms scanf("%d",&num); if(num>0) //Checks if input num is greater than 0 { Ap=FirstNum; //Store FirstNum value to Ap Gp=FirstNum; //Store FirstNum value to Gp printf("\nAp = "); for(i=0;i<num;i++) //Iterating num times { printf("%d, ",Ap); //Prints Value of Ap Ap+=ratio; //Increments Ap by difference value given by user } printf("\nGp = "); for(i=0;i<num;i++) //Iterating loop num times { printf("%d, ",Gp); //Prints the Gp in sequence Gp*=ratio; //Gp = Gp*ratio } Ap=FirstNum; //Initialising Ap as First term printf("\nHp = "); for(i=0;i<num;i++) //Iterating num times { Hp=(float)1/Ap; //Storing Inverse of Ap term as Hp printf("%f, ",Hp); //Printing Hp term in sequence Ap+=ratio; //Calculating next Ap term } printf("\n"); } else { printf("Invalid input\n"); //Printing error message } return 0; }
C
#include <stdio.h> int main(){ printf("Witaj .NET\n"); printf("Witaj Swiecie\n"); printf("5 + 5 = %f", add(5,5)); return 0; } float add(int a, int b){ return a+b; } float multiply(int a, int b){ return a*b; }
C
#include "uart.h" //Inicializa UART, nesse caso apenas UART0 (conectada na interface usb) void UART_Init(void) { //Ativar o clock para porta SYSCTL_RCGCUART_R |= UART_ALL_PORTS; //Esperar porta ficar pronta while(SYSCTL_PRUART_R != UART_ALL_PORTS); //Desabilita UART para configurar UART0_CTL_R = 0x0; //Escrever Baud-Rate para 19200 bps UART0_IBRD_R = 260; UART0_FBRD_R = 27; //Configurando UARTLCRH UART0_LCRH_R |= 0x70; // 8bits, Ativa FIFO, 1 stop bit, sem paridade //Garantir mesmo clock para UART e sistema UART0_CC_R = 0x0; //Habilitar RXE, TXE e UARTEN UART0_CTL_R |= 0x301; } unsigned char UART0_RxChar(void) { while((UART0_FR_R & 0x10) > 0); // FIFO vazia return (unsigned char)(UART0_DR_R & 0xFF); } void UART0_TxChar(unsigned char data) { while((UART0_FR_R & 0X20) > 0); // FIFO cheia UART0_DR_R = data; } void UART0_TxString(unsigned char* data) { size_t size = strlen((char*)data); int i = 0; for(i = 0; i < size; i++) { UART0_TxChar(data[i]); } }
C
//uva prblm 11777 #include<stdio.h> int main() { int t1,t2,f,at,ct1,ct2,ct3,c,d,n,i; while(scanf("%d",&n)==1) { for(i=1;i<=n;i++) { scanf("%d%d%d%d%d%d%d",&t1,&t2,&f,&at,&ct1,&ct2,&ct3); if(ct1<=ct2 && ct1<=ct3) c=(ct2+ct3)/2; else if(ct2<=ct1 && ct2<=ct3) c=(ct1+ct3)/2; else if(ct3<=ct1 && ct3<=ct2) c=(ct1+ct2)/2; d=t1+t2+f+at+c; if(d>=90) printf("Case %d: An",i); else if(d>=80) printf("Case %d: Bn",i); else if(d>=70) printf("Case %d: Cn",i); else if(d>=60) printf("Case %d: Dn",i); else if(d<60) printf("Case %d: Fn",i); } } return 0; }
C
#include<stdio.h> #include<stdlib.h> int n; int Top = -1, postIndex; void push(int value, int s[]){ if(Top==n-1){ printf("\nOverflow!!"); } else{ Top=Top+1; s[Top]=value; } } void pop(int s[]){ if(Top==-1){ printf("\nUnderflow!!"); } else{ printf("\nPopped element: %d",s[Top]); Top=Top-1; } } // A utility function to search data in in[] int search (int in[], int data, int n){ int i = 0; for (i = 0; i < n; i++) if (in[i] == data) return i; return i; } // Fills preorder traversal of tree with given // inorder and postorder traversals in a stack void fillPre (int in[], int post[], int inStrt, int inEnd, int s[], int n, int postIndex, int Top){ if (inStrt > inEnd) return; // Find index of next item in postorder traversal in // inorder. int val = post[postIndex]; int inIndex = search (in, val, n); postIndex--; // traverse right tree fillPre (in, post, inIndex + 1, inEnd, s, n, postIndex, Top); // traverse left tree fillPre (in, post, inStrt, inIndex - 1, s, n, postIndex, Top); push(val,s); } // This function basically initializes postIndex // as last element index, then fills stack with // reverse preorder traversal using printPre void printPreMain (int in[], int post[], int n, int s[]){ int len = n; postIndex = len - 1; fillPre (in, post, 0, len - 1, s, n, postIndex, Top); int sLength = sizeof(s) / sizeof(s[0]); while (sLength > 0){ printf("%d",s[Top]); pop(s,Top); } } int main (){ int n; int Top=-1; int postIndex = 0; int value; printf ("Enter the no. of element : "); scanf ("%d", &n); int post[n], in[n], s[n]; printf ("Enter the Inorder :"); for (int i = 0; i < n; i++) { scanf ("%d", &value); in[i] = value; } printf ("Enter the Postorder :"); for (int i = 0; i < n; i++) { scanf ("%d", &value); post[i] = value; } printPreMain (in, post, n, s); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <locale.h> #define FILA 5 struct tatividades { int RA; char nome_arquivo[50]; char extensao_arquivo[10]; int matricula_responsavel; }; struct tfila { struct tatividades dados[FILA]; int ini; int fim; }; struct tfila fila; menu(){ printf("******************************************\n"); printf("* *\n"); printf("* *\n"); printf("* GERENCIAMENTO DE ATIVIDADES *\n"); printf("* *\n"); printf("* *\n"); printf("******************************************\n"); } opcoes(){ printf("\n1 - Matricular\n"); printf("2 - Remover Atividade\n"); printf("3 - Remover todas as Atividades Registradas\n"); printf("4 - Encerrar o Programa\n"); } void fila_matricular(){ if(fila.fim == FILA){ printf("\n Numero total de atividades registradas atingidas!\n\n"); system("pause"); } else{ printf("Digite o RA: "); scanf("%d", &fila.dados[fila.fim].RA); printf("Escreva o nome do Arquivo: "); scanf("%s", fila.dados[fila.fim].nome_arquivo); printf("Escreva a extenso do arquivo: "); scanf("%s", fila.dados[fila.fim].extensao_arquivo); printf("Digite a Matricula do professor reponsvel pela correo: "); scanf("%d", &fila.dados[fila.fim].matricula_responsavel); fila.fim++; system("cls"); } } void imprimir(){ int i; if(fila.ini == fila.fim || fila.ini == 0){ printf("No h atividades para mostrar!\n"); } else{ for(i = 0; i < fila.fim; i++){ printf("%d \n", fila.dados[i].RA); printf("%s \n", fila.dados[i].nome_arquivo); printf("%s \n", fila.dados[i].extensao_arquivo); printf("%d \n", fila.dados[i].matricula_responsavel); printf("-----------------\n"); } } } remover(){ int i; if(fila.ini == fila.fim){ printf("No existe atividades para remover!\n\n"); system("pause"); system("cls"); } else{ for(i = 0; i < fila.fim; i++) { fila.dados[i] = fila.dados[i + 1]; strcpy(fila.dados[i].nome_arquivo, fila.dados[i + 1].nome_arquivo); strcpy(fila.dados[i].extensao_arquivo, fila.dados[i + 1].extensao_arquivo); } fila.dados[fila.fim].RA = 0; strcpy(fila.dados[fila.fim].nome_arquivo, ""); strcpy(fila.dados[fila.fim].extensao_arquivo, ""); fila.dados[fila.fim].matricula_responsavel = 0; fila.fim--; system("cls"); } } remove_tudo(){ int i; if(fila.ini == fila.fim){ printf("No existe atividades para remover!\n\n"); system("pause"); system("cls"); } else{ for(i = 0; i < fila.fim; i++) { fila.dados[i] = fila.dados[i + fila.fim]; strcpy(fila.dados[i].nome_arquivo, fila.dados[i + fila.ini].nome_arquivo); strcpy(fila.dados[i].extensao_arquivo, fila.dados[i + fila.ini].extensao_arquivo); } fila.dados[fila.fim].RA = 0; strcpy(fila.dados[fila.fim].nome_arquivo, ""); strcpy(fila.dados[fila.fim].extensao_arquivo, ""); fila.dados[fila.fim].matricula_responsavel = 0; fila.fim--; system("cls"); } } main(){ int opcao; setlocale(LC_ALL, "Portuguese"); do{ menu(); imprimir(); opcoes(); printf("Escolha uma opo: "); scanf("%d", &opcao); switch(opcao){ case 1: fila_matricular(); break; case 2: remover(); break; case 3: remove_tudo(); break; case 4: break; } }while(opcao != 4); }
C
#include <math.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "fit.h" /* This file contains a bunch of function for allocating */ /* vectors and matrices. */ extern int debug; extern int wiflag; void myerror(char *); double **dmatrix(nr,nc) int nr,nc; { int i; double **m; char s[80]; m=(double **) malloc((unsigned) (nr)*sizeof(double*)); if (!m) myerror("allocation failure 1 in dmatrix()"); for(i=0;i<nr;i++) { m[i]=(double *) malloc((unsigned) (nc)*sizeof(double)); sprintf(s,"allocation failure 2 in dmatrix() on column %d",i); if (!m[i]) myerror(s); } return m; } int **imatrix(nr,nc) int nr,nc; { int i,**m; m=(int **)malloc((unsigned) (nr)*sizeof(int*)); if (!m) myerror("allocation failure 1 in imatrix()"); for(i=0;i<nr;i++) { m[i]=(int *)malloc((unsigned) (nc)*sizeof(int)); if (!m[i]) myerror("allocation failure 2 in imatrix()"); } return m; } void free_dmatrix(m,nr,nc) double **m; int nr,nc; { int i; for(i=nr-1;i>=0;i--) free((char*) (m[i])); free((char*) (m)); } void free_imatrix(m,nr,nc) int **m; int nr,nc; { int i; for(i=nr-1;i>=0;i--) free((char*) m[i]); free((char*) (m)); } void myerror(s) char s[80]; { printf("%s\n", s); } double *dvector(int n){ return (double *)malloc((unsigned) (n)*sizeof(double)); } int *ivector(int n){ return (int *)malloc((unsigned) (n)*sizeof(int)); } /* parse parses command line arguments */ int parse(command, cmdarg) char *command, cmdarg[NUM_ARGS][30]; { int i=0, j=0, k, toomany=0; while( command[i] != '\x0' ){ if(j >= NUM_ARGS){ toomany = 1; break; } if( command[i] == ' ' ){ i++; k = 0; while(command[i] == ' ') i++; while( command[i] != ' ' && k < 30 && command[i] != '\x0'){ if(command[i] != ' '){ cmdarg[j][k] = command[i]; k++; } i++; } cmdarg[j][k] = '\x0'; j++; } if(j==0)i++; } if(toomany){ printf("Warning: there is a maximum of %d command arguments\n",NUM_ARGS); printf("Change NUM_ARGS in fit.h and recompile\n"); } if(k == 0) j--; if(debug){ printf("#args: %d\n",j); for( i = 0; i < j; i++) printf("%s\n", cmdarg[i]); } return j; } /* calc_yfit calculates the value of the */ /* fitting function for all the values of */ /* the independent variable */ int calc_yfit(func, data, order, num_indep, a, ndata, ma, chisqr) int (*func)(); double **data; struct data_order order; int num_indep; double a[]; int ndata, ma; double *chisqr; { int i, j; int failed; double *dyda; double *dydx; int *fita; double *y; double *x; int *dydx_flag; double sig2i; y = data[order.yfit]; dyda = dvector(ma); fita = ivector(ma); x = dvector(num_indep); dydx = dvector(num_indep); dydx_flag = ivector(num_indep); for(j = 0; j < num_indep; j++) dydx_flag[j] = 0; for(j = 0; j < ma; j++) fita[j] = 0; *chisqr = 0; for(i=0; i < ndata; i++){ for(j = 0; j < num_indep; j++){ x[j] = data[order.x[j]][i]; if(debug > 1) printf("i: %d order.x[%d]: %d x[%d]: %g\n", i, j, order.x[j], j, x[j]); } if(debug > 1) printf("about to call (*func)()\n"); failed = (*func)(x,a,&y[i],dyda,ma,0,fita,dydx_flag,dydx,data[order.y][i]); if(failed) break; sig2i = data[order.sig][i]*data[order.sig][i]; if(sig2i > 1e-30 && (wiflag == 0 || window(x, num_indep))) *chisqr += (y[i] - data[order.y][i])*(y[i] - data[order.y][i])/sig2i; } free(dyda); free(fita); free(x); free(dydx); free(dydx_flag); return failed; } /* help lists comands */ int help(char topic[12], int maxlines){ char inbuf[80]; FILE *stream; int i; char buf[20]; if(strcmp(topic,"") == 0)strcpy(topic,"COMMANDS"); stream = NULL; if(getenv("FITHELP") == NULL && (stream = fopen("fit.hlp","r")) == NULL){ printf("help file not found, set environment variable FITHELP to point to fit.hlp\n"); return 1; } if( (stream == NULL) && (stream = fopen(getenv("FITHELP"),"r")) == NULL){ printf("help file not found, set environment variable FITHELP to point to fit.hlp\n"); return 1; } while(fgets(inbuf,80,stream) != NULL){ if( strncmp(inbuf, topic, strlen(topic)) == 0){ i = 0; printf("%s",inbuf); while( strncmp( fgets(inbuf,80,stream), "END",3) ){ printf("%s",inbuf); i++; if(i == 20){ i = 0; gets(buf); } if( i == maxlines) return 0; } } } fclose(stream); return 0; } int nonzero(double *array, int ndata){ int i; for(i = 0; i < ndata; i++) if(array[i] < 1e-60) return 0; return 1; } 
C
// letter.c #include "switch.h" #include <stdio.h> #ifdef MAC #include <GLUT/glut.h> #else #include <GL/glut.h> #endif #include "letter.h" #include "global.h" #include "shot.h" int width; int height; int score; int used_shots; // Q[\ void disp_info(void) { char str[64]; void *font = GLUT_BITMAP_HELVETICA_18; // QlTCg: http://wiki.livedoor.jp/mikk_ni3_92/d/%b4%f0%cb%dc%ca%d417%3a%3abitmap%a5%d5%a5%a9%a5%f3%a5%c8 glPushMatrix(); glLoadIdentity(); glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); gluOrtho2D(0, width, 0, height); //` glPushAttrib(GL_CURRENT_BIT | GL_DEPTH_BUFFER_BIT); glDisable(GL_DEPTH_TEST); glColor3d(0.0, 0.0, 0.0); sprintf(str, "SCORE: %d", score); draw_string(str ,font, 4.0, 8.0); // XRA\ sprintf(str, "REMAININGS: %d", NUM_OF_SHOTS - used_shots); draw_string(str, font, 4.0, 28.0); // c̃^}\ glPopAttrib(); glPopMatrix(); glMatrixMode(GL_MODELVIEW); glPopMatrix(); } void disp_result(void) { char str[64]; void *font = GLUT_BITMAP_HELVETICA_18; // QlTCg: http://wiki.livedoor.jp/mikk_ni3_92/d/%b4%f0%cb%dc%ca%d417%3a%3abitmap%a5%d5%a5%a9%a5%f3%a5%c8 glPushMatrix(); glLoadIdentity(); glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); gluOrtho2D(0, width, 0, height); //` glPushAttrib(GL_CURRENT_BIT | GL_DEPTH_BUFFER_BIT); glDisable(GL_DEPTH_TEST); glColor3d(0.0, 0.0, 0.0); sprintf(str, "YOUR SCORE: %d", score); draw_string(str ,font, width * 0.5 - 70, height * 0.5); // XRA\ glPopAttrib(); glPopMatrix(); glMatrixMode(GL_MODELVIEW); glPopMatrix(); } void draw_string(const char *str, void *font, double x, double y) { //printf("debug\n"); //glRasterPos3d(x, y, z); glRasterPos2d(x, y); //_ for (;*str != '\0'; str++) { glutBitmapCharacter(font, *str); } }
C
/* C port of Adafruit_SleepyDog, AVR component. see WatchdogAVR.h for explanation. functions other than sleep() were made static and seem unnecessary. nspring Jan 2017 */ #include <avr/interrupt.h> #include <avr/power.h> #include <avr/sleep.h> #include <avr/wdt.h> #include "sleep.h" static int _wdto; static void _setPeriod(int maxMS, int *wdto, int *actualMS); /* must be avoided if watchdog library included. // Define watchdog timer interrupt. ISR(WDT_vect) { // Nothing needs to be done, however interrupt handler must be defined to // prevent a reset. } */ static int sleeper_enable(int maxPeriodMS) __attribute__((unused)); static void sleeper_reset(void) __attribute__((unused)); static void sleeper_disable(void) __attribute__((unused)); static int sleeper_enable(int maxPeriodMS) { // Pick the closest appropriate watchdog timer value. int actualMS; _setPeriod(maxPeriodMS, &_wdto, &actualMS); // Enable the watchdog and return the actual countdown value. wdt_enable(_wdto); return actualMS; } static void sleeper_reset(void) { // Reset the watchdog. wdt_reset(); } static void sleeper_disable(void) { // Disable the watchdog and clear any saved watchdog timer value. wdt_disable(); _wdto = -1; } int sleep_ms(int maxPeriodMS) { // Pick the closest appropriate watchdog timer value. int sleepWDTO, actualMS; _setPeriod(maxPeriodMS, &sleepWDTO, &actualMS); // Build watchdog prescaler register value before timing critical code. uint8_t wdps = ((sleepWDTO & 0x08 ? 1 : 0) << WDP3) | ((sleepWDTO & 0x04 ? 1 : 0) << WDP2) | ((sleepWDTO & 0x02 ? 1 : 0) << WDP1) | ((sleepWDTO & 0x01 ? 1 : 0) << WDP0); // The next section is timing critical so interrupts are disabled. cli(); // First clear any previous watchdog reset. MCUSR &= ~(1<<WDRF); // Now change the watchdog prescaler and interrupt enable bit so the watchdog // reset only triggers the interrupt (and wakes from deep sleep) and not a // full device reset. This is a timing critical section of code that must // happen in 4 cycles. WDTCSR |= (1<<WDCE) | (1<<WDE); // Set WDCE and WDE to enable changes. WDTCSR = wdps; // Set the prescaler bit values. WDTCSR |= (1<<WDIE); // Enable only watchdog interrupts. // Critical section finished, re-enable interrupts. sei(); // Disable USB if it exists #ifdef USBCON USBCON |= _BV(FRZCLK); //freeze USB clock PLLCSR &= ~_BV(PLLE); // turn off USB PLL USBCON &= ~_BV(USBE); // disable USB #endif // Set full power-down sleep mode and go to sleep. set_sleep_mode(SLEEP_MODE_PWR_DOWN); sleep_mode(); // Chip is now asleep! // Once awakened by the watchdog execution resumes here. Start by disabling // sleep. sleep_disable(); // Check if the user had the watchdog enabled before sleep and re-enable it. if (_wdto != -1) { wdt_enable(_wdto); } // Return how many actual milliseconds were spent sleeping. return actualMS; } static void _setPeriod(int maxMS, int *wdto, int *actualMS) { // Note the order of these if statements from highest to lowest is // important so that control flow cascades down to the right value based // on its position in the range of discrete timeouts. if ((maxMS >= 8000) || (maxMS == 0)) { *wdto = WDTO_8S; *actualMS = 8000; } else if (maxMS >= 4000) { *wdto = WDTO_4S; *actualMS = 4000; } else if (maxMS >= 2000) { *wdto = WDTO_2S; *actualMS = 2000; } else if (maxMS >= 1000) { *wdto = WDTO_1S; *actualMS = 1000; } else if (maxMS >= 500) { *wdto = WDTO_500MS; *actualMS = 500; } else if (maxMS >= 250) { *wdto = WDTO_250MS; *actualMS = 250; } else if (maxMS >= 120) { *wdto = WDTO_120MS; *actualMS = 120; } else if (maxMS >= 60) { *wdto = WDTO_60MS; *actualMS = 60; } else if (maxMS >= 30) { *wdto = WDTO_30MS; *actualMS = 30; } else { *wdto = WDTO_15MS; *actualMS = 15; } }
C
#include<stdio.h> #include<stdlib.h> #include<math.h> #include<string.h> #include<ctype.h> int main() { //puts and gets functions // function reads out spaces i.e the problem with scanf function is replaced by function //whenever a string is scanned with a space the program breaks and the part after space is not read. char catsName[50]; char catsFood[25]; char sentence[75] = ""; puts("Whats the cats name ? "); //acts like printf ; doesn't need a \n i.e. it automatically adds a new line gets(catsName); //acts like scnaf puts("What does he eat?"); gets(catsFood); strcat(sentence , catsName); strcat(sentence, " loves to eat "); strcat(sentence,catsFood); puts(sentence); return 0; }
C
#include <stdio.h> #include <unistd.h> #include <stdlib.h> int sys() { int i,j; for(i=0;i<2;i++) { for(j=0;j<52;j++) { printf("-"); } printf("\n"); if(i==0) {printf("| 1.Food | 2.Play | 3.Light | 4.Medicine | 5.Clean |\n");} } } int poring_normal(num) { if(num%2==0) { printf(" aa\n"); printf(" aa\n"); printf(" aaaaaa\n"); printf(" aaaaaaaa\n"); printf(" aaaaaaaaaa\n"); printf(" aaaOaa|aaOaaa\n"); printf(" aaaaaaWaaaaaaaa\n"); printf(" aaaaaaaaaaaaaa\n"); printf(" aaaaaaaaaaaa\n"); } else if(num%2==1) { printf(" aa\n"); printf(" aa\n"); printf(" aaaaaa\n"); printf(" aaaaaaaa\n"); printf(" aaaaaaaaaa\n"); printf(" aaa=aa|aa=aaa\n"); printf(" aaaaaaWaaaaaaaa\n"); printf(" aaaaaaaaaaaaaa\n"); printf(" aaaaaaaaaaaa\n"); } } int command_line(command) { switch(command) { case 1: printf("Eating..."); break; case 2: printf("Playing..."); break; case 3: printf("Sleeping..."); break; case 4: printf("Curing..."); break; case 5: printf("Cleaning..."); break; default: printf("Nothing"); break; } } /*function check status input 5 variable return status*/ int main() { int num,status=99; num=0; while(1) { sys(); switch(status) { case 1: { /*call function*/ status=99; break; } case 2: { /*call function*/ status=99; break; } case 3: { /*call function*/ status=99; break; } case 4: { /*call function*/ break; } case 5: { /*call function*/ break; } case 91: { /*printf tamagot want food*/ break; } case 92: { /*printf tamagot want play*/ break; } case 93: { /*printf tamagot want light*/ break; } case 94: { /*printf tamagot want Medicine*/ break; } case 95: { /*printf tamagot want clean*/ break; } default: { /*command print tamagot normal*/ } /* if check for change status*/ system("cmd /c cls"); } /* poring_normal(num); num++; sleep(600); system("cls"); /*printf("Your command :"); scanf("%d",&command); */ } }
C
#include <stdio.h> #include <stdlib.h> #include <time.h> #include <omp.h> #include <math.h> #include <string.h> #include "dataTypes.h" #include "basicEvaluation.h" #include "prefixSumEvaluation.h" #include "hornerEvaluation.h" #include "estrinEvaluation.h" #include "parallelHornerEvaluation.h" #define MAX_STRING 256 double * read_constants(int * degree) { int i; double * polynomial; scanf("%d", degree); polynomial = (double *) malloc(sizeof(double) * ((*degree) + 1)); for (i = *degree; i >= 0; i--) scanf("%lf", &polynomial[i]); return polynomial; } double * read_instances(int * num) { int i; double * instances; scanf("%d", num); instances = (double *) malloc(sizeof(double) * (*num)); for (i = 0; i < *num; i++) scanf("%lf", &instances[i]); return instances; } void print_polynomial(double * polynomial, int degree) { int i = 0, firsttime = 1; for (i = degree; i >= 0; i--) { char str[MAX_STRING] = ""; double factor = polynomial[i]; if (factor != 0) { if (firsttime) sprintf(str, "%.1lf", factor); else if (factor < 0) sprintf(str, " - %.1lf", -factor); else sprintf(str, " + %.1lf", factor); if (str[0] != '\0') { if (i > 0) { printf("%s x^%d", str, i); } else printf("%s", str); str[0] = '\0'; firsttime = 0; } } } } void evaluate(double * polynomial, int degree, double * inputlist, int num_inputs, double (evaluate_function)(double *, int, double)) { int i; //printf("p(x) = "); //print_polynomial(polynomial, degree); //printf("\n"); for (i = 0; i < num_inputs; i++) { double input = inputlist[i]; double output = evaluate_function(polynomial, degree, input); //printf("p(%.1lf) = %lf\n", input, output); } } /* NOTA: esta função não está de acordo com os requisitos do enunciado. Leia cuidadosamente as instruções relativamente ao formato da saída. */ int main(void) { int degree, num_instances; double * polynomial = read_constants(&degree); double * instances = read_instances(&num_instances); clock_t ticks1, ticks2; // Basic evaluation printf("Basic evaluation optmimized\n"); ticks1 = clock(); evaluate(polynomial, degree, instances, num_instances, basicEvaluation); ticks2 = clock(); printf("seconds basic = %lf\n", 1.0 * (ticks2 - ticks1) / CLOCKS_PER_SEC); // Basic evaluation dumb printf("Basic evaluation dumb\n"); ticks1 = clock(); evaluate(polynomial, degree, instances, num_instances, basicEvaluationDumb); ticks2 = clock(); printf("seconds basic = %lf\n", 1.0 * (ticks2 - ticks1) / CLOCKS_PER_SEC); //Horner Evaluation printf("Horner evaluation\n"); ticks1 = clock(); evaluate(polynomial, degree, instances, num_instances, hornerEvaluation); ticks2 = clock(); printf("seconds horner = %lf\n", 1.0 * (ticks2 - ticks1) / CLOCKS_PER_SEC); // // Prefix 1 evaluation printf("Prefix evaluation V1\n"); ticks1 = clock(); evaluate(polynomial, degree, instances, num_instances, calculatePolynomPrefixSumV1); ticks2 = clock(); printf("seconds prefix V1 = %lf\n", 1.0 * (ticks2 - ticks1) / CLOCKS_PER_SEC); // // Prefix 2 evaluation printf("Prefix evaluation V2\n"); ticks1 = clock(); evaluate(polynomial, degree, instances, num_instances, calculatePolynomPrefixSumV2); ticks2 = clock(); printf("seconds prefix V2 = %lf\n", 1.0 * (ticks2 - ticks1) / CLOCKS_PER_SEC); // Estrin evaluation printf("Estrin evaluation V1\n"); ticks1 = clock(); evaluate(polynomial, degree, instances, num_instances, estrinEvaluation); ticks2 = clock(); printf("seconds estrin V1 = %lf\n", 1.0 * (ticks2 - ticks1) / CLOCKS_PER_SEC); // Horner parallel evaluation printf("Horner Parallel evaluation V1\n"); ticks1 = clock(); evaluate(polynomial, degree, instances, num_instances, parallelHornerEvaluation); ticks2 = clock(); printf("seconds Horner Parallel V1 = %lf\n", 1.0 * (ticks2 - ticks1) / CLOCKS_PER_SEC); free(polynomial); free(instances); return 0; }
C
#include <pthread.h> #include <stdio.h> #include <stdlib.h> #define NUM_THREADS 3 #include "crest.h" #include "../assert.h" int x, y; void *thread_1(void *threadid) { x = 0; y = 0; assert(x == y); pthread_exit(NULL); } void *thread_2(void *threadid) { x = 1; y = 1; pthread_exit(NULL); } int main(int argc, char* argv[]) { pthread_t t1, t2; CREST_shared_int(x); CREST_shared_int(y); pthread_create(&t1, NULL, thread_1, (void *)NULL); pthread_create(&t2, NULL, thread_2, (void *)NULL); /* Last thing that main() should do */ pthread_exit(NULL); }
C
#include<stdio.h> #include<stdlib.h> int main() { int a, b, q, r; scanf("%d%d", &a, &b); for(r = 0; r < abs(b); ++r) { if((a-r)%b == 0){ q = (a-r)/b; break; } } printf("%d %d\n", q, r); return 0; }
C
#include <stdio.h> void main() { int num,temp,rev; printf("Enter the 3 digit number: "); scanf("%d",&num); temp = num%10; rev=temp*100; temp = num/10; temp = temp%10; rev=rev+temp*10; temp = num/10; temp = temp/10; rev=rev+temp; if(rev==num) { printf("Palindrome"); } else { printf("Not palindrome"); } }
C
#include<stdio.h> int main() { int n,x,i,flag=0,first,last,mid; printf("number od elements u need\n"); scanf("%d",&n); int number[n]; printf("enter the elements in assending order\n"); for(i=0;i<n;i++) scanf("%d",&number[i]); printf("entre the number to search\n"); scanf("%d",&x); first=0; last=n-1; while(first<=last) { mid=(first+last)/2; if(x==number[mid]) { flag=1; break; } else if(x>number[mid]) first=mid+1; else last=mid-1; } if(flag==1) printf("element found at position::%d\n",mid+1); else printf("\nelement not found\n"); }
C
//////////////////////////////////////////////////////////////////////////////// // // PPS4 ROM Reader // // Reads A05 type PPS4/2 ROMs. These are -17V supply ROMs // with data clocked out by a two phse clock arrangement. ROM and // RAM memory spaces exist and the ROM can be mask programmed to respond // to either memory space. It can also respond to any of the AS select lines // which are effectively extra address lines. So, dump the entire space // and work out where the data is later. // ROM data is 8 bits and RAM data is 4 bits. RAM data can be addressed // using the A11X signal as an upper/lower nibble select, so RAM data // needs a slightly different addressing mode. // // // A startup option allows configuration data to be set up. // At the top of flash memory we have two areas. One holds config // data and one holds slots for ROM dumps. The tool only works with up to // 16K ROMs so we have 16K slots. Slots are only ever filled by the dump code // once full the slot have to be deleted with a flash sector erase. // //////////////////////////////////////////////////////////////////////////////// #include <ctype.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <time.h> #include "pico/stdlib.h" //##include "hardware/pio.h" //##include "hardware/clocks.h" #include "hardware/flash.h" // Use this if breakpoints don't work #define DEBUG_STOP {volatile int x = 1; while(x) {} } //////////////////////////////////////////////////////////////////////////////// // // // Only scan once, if multiple dumps needed then use a loop around the entire tool // This makes the post processing easier. #define NUM_SCANS 1 // 16 AS areas or 1024 bytes, A11X 2 areas and RAM and ROM data #define SLOT_SIZE (16*1024*2*2) // How many slots there are. We could have very many slots, why not? #define NUM_SLOTS 4 //----------------------------------------------------------------------------- // Config sector #define FLASH_CONFIG_OFFSET (1024 * 1024) uint8_t *flash_config_contents = (uint8_t *) (XIP_BASE + FLASH_CONFIG_OFFSET); // ROM image slots #define FLASH_SLOT_OFFSET (1028 * 1024) uint8_t *flash_slot_contents = (uint8_t *) (XIP_BASE + FLASH_SLOT_OFFSET); //-------------------------------------------------------------------------------- typedef enum { USB_DUMP = 0, SLOT_DUMP, NUM_SETUP_MODES, } SETUP_MODE; char *setup_mode_name[NUM_SETUP_MODES] = { "USB DUMP", "SLOT_DUMP", }; typedef struct { int valid_a; // magic number and an int valid_b; // inverterted magic number int mode; // Mode we are in int usb_dump_count; // Incremented after every dump int slot_dump_count; // Incremented after every slot dump } CONFIG_RECORD; CONFIG_RECORD *config_record = (CONFIG_RECORD *) (XIP_BASE + FLASH_CONFIG_OFFSET); CONFIG_RECORD copy_config_record; #define CONFIG_MAGIC_A 0xCFAA0134 #define CONFIG_MAGIC_B 0xCFBB5623 // RAM slot which we copy to flash once filled uint8_t slot_data[SLOT_SIZE]; //-------------------------------------------------------------------------------- void dump_slot(int slotnum); void display_slot_map(void); void clear_slot_data(void); //------------------------------------------------------------------------------ const int LED_PIN = 25; // This pin layout gives a rotation to the data // rather than do more dumps, I'll live with it and post process const int ID1_PIN = 0; const int ID2_PIN = 1; const int ID3_PIN = 2; const int ID4_PIN = 3; const int ID5_PIN = 4; const int ID6_PIN = 5; const int ID7_PIN = 6; const int ID8_PIN = 7; // // The address lines (always inputs) // const int AB1_PIN = 8; const int AB2_PIN = 9; const int AB3_PIN = 10; const int AB4_PIN = 11; const int AB5_PIN = 12; const int AB6_PIN = 13; const int AB7_PIN = 14; const int AB8_PIN = 15; const int AB9_PIN = 16; const int AB10_PIN = 17; const int AB11X_PIN = 18; const int CLKA_PIN = 19; const int CLKB_PIN = 20; const int AS0_PIN = 21; const int AS1_PIN = 22; const int AS2_PIN = 26; const int AS3_PIN = 27; // Arrays for setting GPIOs up #define NUM_ADDR 11 #define NUM_AS 4 #define NUM_DATA 8 const int address_pins[NUM_ADDR] = { AB1_PIN, AB2_PIN, AB3_PIN, AB4_PIN, AB5_PIN, AB6_PIN, AB7_PIN, AB8_PIN, AB9_PIN, AB10_PIN, AB11X_PIN, }; const int as_pins[NUM_ADDR] = { AS0_PIN, AS1_PIN, AS2_PIN, AS3_PIN, }; const int data_pins[NUM_DATA] = { ID1_PIN, ID2_PIN, ID3_PIN, ID4_PIN, ID5_PIN, ID6_PIN, ID7_PIN, ID8_PIN, }; //////////////////////////////////////////////////////////////////////////////// // // Set the address lines to a value // //////////////////////////////////////////////////////////////////////////////// void set_address(int addr) { for(int i=0; i<NUM_ADDR; i++) { if( addr & (1<<i) ) { gpio_put(address_pins[i], 1); } else { gpio_put(address_pins[i], 0); } } } void set_as(int as) { for(int i=0; i<NUM_AS; i++) { if( as & (1<<i) ) { gpio_put(as_pins[i], 1); } else { gpio_put(as_pins[i], 0); } } } int read_data(void) { int result = 0; for(int i=0; i<NUM_DATA; i++) { if( gpio_get(data_pins[i]) ) { result |= (1 << i); } } return(result); } //////////////////////////////////////////////////////////////////////////////// void print_hex(uint8_t *buf, int len) { for (size_t i = 0; i < len; ++i) { if((i % 16) == 0) { printf("\n"); } printf("%02x ", buf[i]); } } //////////////////////////////////////////////////////////////////////////////// void prompt(void) { printf("\n>"); } void setup_menu(void) { printf("\nSetup"); printf("\n====="); printf("\n"); printf("\n?: Display menu"); printf("\nq: Quit"); printf("\nc: Clear config settings"); printf("\nC: Clear slot data"); printf("\nd: Display config settings"); printf("\np: Print information"); printf("\nP: Dump config sector"); printf("\nU: Set USB dump mode"); printf("\nS: Set slot dump mode"); printf("\nM: Display slot map"); printf("\nr: Display slot"); printf("\nz: Zero USB dump count"); printf("\nZ: Zero Slot dump count"); } void erase_config_sector(void) { flash_range_erase(FLASH_CONFIG_OFFSET, FLASH_SECTOR_SIZE); } void erase_slot_data(void) { flash_range_erase(FLASH_SLOT_OFFSET, SLOT_SIZE*NUM_SLOTS); } void program_config_record(CONFIG_RECORD *data) { flash_range_program(FLASH_CONFIG_OFFSET,(uint8_t *) data, sizeof(CONFIG_RECORD)); } void write_config_record(CONFIG_RECORD *cfg_rec) { // Make record valid cfg_rec->valid_a = CONFIG_MAGIC_A; cfg_rec->valid_b = CONFIG_MAGIC_B; erase_config_sector(); program_config_record(cfg_rec); } void zero_usb_dump_count(void) { copy_config_record = *config_record; copy_config_record.usb_dump_count = 0; write_config_record(&copy_config_record); } void zero_slot_dump_count(void) { copy_config_record = *config_record; copy_config_record.slot_dump_count = 0; write_config_record(&copy_config_record); } void increment_usb_dump_count(void) { copy_config_record = *config_record; (copy_config_record.usb_dump_count)++; write_config_record(&copy_config_record); } void increment_slot_dump_count(void) { copy_config_record = *config_record; (copy_config_record.slot_dump_count)++; write_config_record(&copy_config_record); } //-------------------------------------------------------------------------------- void write_data_to_slot(uint8_t *data, int slotnum) { printf("\nWriting data to slot %d", slotnum); flash_range_program(FLASH_SLOT_OFFSET + (SLOT_SIZE * slotnum), (uint8_t *) data, SLOT_SIZE); printf("\nData written"); } //-------------------------------------------------------------------------------- // int slot_is_blank(int slotnum) { int blank = 0; // See if all bytes in this slot are 0xff // Assume blank blank = 1; for(int j=0; j<SLOT_SIZE;j++) { if( *(flash_slot_contents+slotnum*SLOT_SIZE+j) !=0xFF ) { // Not blank blank = 0; break; } } if( blank ) { // We found a slot, return its index return(1); } return(0); } //-------------------------------------------------------------------------------- // // Find a slot that has no data in it, i.e. is full of 0xFF // returns either the slot number or -1 if none are blank int find_blank_slot(void) { int slotnum = -1; for(slotnum=0; slotnum<NUM_SLOTS; slotnum++) { if( slot_is_blank(slotnum) ) { return(slotnum); } } return(-1); } char *get_mode_name(int mode) { switch(mode) { case USB_DUMP: case SLOT_DUMP: return(setup_mode_name[mode]); break; default: return("Unknown"); break; } } //////////////////////////////////////////////////////////////////////////////// // // Check for entry into the setup code // //////////////////////////////////////////////////////////////////////////////// void check_config_entry(void) { int c; int key_pressed = 0; printf("\nPress any key to enter setup...\n"); // Wait for a while and see if a keypress occurred for(int i=0; i<5; i++) { printf(" %d...", i); sleep_ms(1000); if( (c = getchar_timeout_us(1000)) != PICO_ERROR_TIMEOUT ) { if( (c != 0) && (c != 255) ) { key_pressed = 1; break; } } } if( key_pressed ) { printf("\nkey %d pressed", c); // Key was pressed, enter setup loop int done = 0; setup_menu(); prompt(); while(!done) { if( (c = getchar_timeout_us(1000)) != PICO_ERROR_TIMEOUT ) { // handle command switch(c) { case '?': setup_menu(); break; case 'q': done = 1; break; case 'd': printf("\nConfiguration data:"); printf("\n"); break; case 'c': // Erase config sector erase_config_sector(); break; case 'C': clear_slot_data(); break; case 'U': // Set USB mode // Read config into RAM copy_config_record = *config_record; copy_config_record.mode = USB_DUMP; write_config_record(&copy_config_record); break; case 'S': // Set SLOT mode // Read config into RAM copy_config_record = *config_record; copy_config_record.mode = SLOT_DUMP; write_config_record(&copy_config_record); break; case 'r': { int slot_number; printf("\nSlot number:"); scanf("%d", &slot_number); dump_slot(slot_number); } break; case 'M': display_slot_map(); break; case 'z': zero_usb_dump_count(); break; case 'Z': zero_slot_dump_count(); break; case 'P': // Print flash config data sector print_hex(flash_config_contents, FLASH_SECTOR_SIZE); break; case 'p': // print information printf("\nFlash sector size: %d", FLASH_SECTOR_SIZE); printf("\nFlash page size : %d", FLASH_PAGE_SIZE); printf("\nConfiguration data"); printf("\n"); print_hex(flash_config_contents, sizeof(CONFIG_RECORD)); printf("\n"); if( (config_record->valid_a == CONFIG_MAGIC_A) && (config_record->valid_b == CONFIG_MAGIC_B )) { printf("\nConfiguration valid"); printf("\nMode : %s", get_mode_name(config_record->mode)); printf("\nUSB dump count : %d", config_record->usb_dump_count); printf("\nSlot dump count: %d", config_record->slot_dump_count); printf("\n"); } else { printf("\nConfiguration NOT valid"); } break; default: printf("\nKey press unknown: %d", c); break; } prompt(); } } } } //////////////////////////////////////////////////////////////////////////////// // // USB Dump mode // //////////////////////////////////////////////////////////////////////////////// void usb_dump(void) { // We scan the device with all permutations of AS and AB signals and also with // A11X in both states. This should result in data being returned however the // device has been mask programmed. int scan = 0; int addr = 0; int as = 0; int byte = 0; int ascii_i = 0; int sloti = 0; #define LINELEN 32 char ascii[LINELEN+1] = ""; // Dump over the entire address range, with every permutation of AS signals as well // Set the clock to the initial states gpio_put(CLKA_PIN, 1); gpio_put(CLKB_PIN, 0); for(as=0; as<16; as++) { set_as(as); for(addr=0; addr < (1<<NUM_ADDR); addr++) { ascii_i = addr % LINELEN; if( (addr % LINELEN) == 0 ) { printf("\n%04X: ", addr); } // Set the address lines up // We use the same address for RAM and ROM spaces set_address(addr); sleep_us(100); // We have to clock the data out with the two phase clock // We interleave the RAM and ROM data for ease of dumping // Move to clear bus clock cycle gpio_put(CLKA_PIN, 0); sleep_us(10); gpio_put(CLKB_PIN, 1); sleep_us(10); // Move to RAM readout cycle gpio_put(CLKB_PIN, 0); sleep_us(10); // read RAM data byte = read_data(); slot_data[sloti++] = byte; if( sloti > SLOT_SIZE ) { printf("\nSlot size inconsistent"); } if( isprint(byte)) { ascii[ascii_i] = byte & 0xFF; } else { ascii[ascii_i] = '.'; } printf("%02X ", byte); if( ascii_i == (LINELEN-1) ) { ascii[LINELEN] = '\0'; printf(" %s", ascii); } // Move to clear bus clock cycle gpio_put(CLKA_PIN, 1); sleep_us(10); gpio_put(CLKB_PIN, 1); sleep_us(10); // Move to ROM readout cycle gpio_put(CLKB_PIN, 0); sleep_us(10); // read ROM data byte = read_data(); slot_data[sloti++] = byte; if( sloti > SLOT_SIZE ) { printf("\nSlot size inconsistent"); } if( isprint(byte)) { ascii[ascii_i] = byte & 0xFF; } else { ascii[ascii_i] = '.'; } printf("%02X ", byte); if( ascii_i == (LINELEN-1) ) { ascii[LINELEN] = '\0'; printf(" %s", ascii); } } } // Sucessful dump, increment the count increment_usb_dump_count(); } //////////////////////////////////////////////////////////////////////////////// // // Slot Dump mode // //////////////////////////////////////////////////////////////////////////////// // We dump the ROM to a RAM slot then copy the data into a blank slot. If no blank // slots then we don't copy any data. // The ROM is dumped to RAM and displayed on USB as well, so if the slots are full // then a USB dump still occurs void slot_dump(void) { int slotnum = -1; // Do a USB dump, which will save the data for us in slot_data[] and also // has done a 'backup' USB dump for us. // this will increment the USB dump counter usb_dump(); // We have the data in RAM, now try to find somewhere in flash to store it slotnum = find_blank_slot(); if( slotnum == -1 ) { printf("\nNo free slots available"); // No slots, we can do no more // Slot dump counter not incremented return; } // We have a slot to store the data in, so write it write_data_to_slot(slot_data, slotnum); increment_slot_dump_count(); } void display_slot_map(void) { printf("\nSlot Map\n"); printf("\n\nSlot size:%d bytes\n", SLOT_SIZE); for(int s=0; s<NUM_SLOTS; s++) { printf("\n%02d: %s", s, slot_is_blank(s)?"Blank":"Used "); } printf("\n"); } void dump_slot(int slotnum) { printf("\nSlot %d\n", slotnum); print_hex(flash_slot_contents+slotnum*SLOT_SIZE, SLOT_SIZE); printf("\n"); } void clear_slot_data(void) { char answer[100]; printf("\n*** CLEAR SLOT DATA ***\n"); printf("\n\nAre you sure? (Yes/No):"); scanf("%s", answer); srand(time_us_32()); if( strcmp(answer, "Yes") == 0 ) { int code = rand(); int code_answer = code+1; printf("\n\nEnter code:%d:", code); scanf("%d", &code_answer); if( code==code_answer ) { printf("\nDeleting slot data in 10 seconds..."); for(int ct=1; ct<=10; ct++) { sleep_ms(1000); printf("\n%d...", ct); } printf("\nDeleting..."); erase_slot_data(); printf("\nDone"); } } } //////////////////////////////////////////////////////////////////////////////// // // // //////////////////////////////////////////////////////////////////////////////// int main() { char line[80]; stdio_init_all(); sleep_ms(3000); printf("\nPPS4 ROM Reader V1.0\n"); sleep_ms(1000); check_config_entry(); #if TEST_STDIO { int count; while (true) { count++; if( (count % 1000000) == 0 ) { sprintf(line, "\nRP2040: %d", count); printf(line); } } } #endif // LED ON solid gpio_init(LED_PIN); gpio_set_dir(LED_PIN, GPIO_OUT); gpio_put(LED_PIN, 1); printf("\nSetting GPIOs..."); sleep_ms(1000); // Address lines are driven for (int i=0; i<NUM_ADDR; i++) { // Set up directions for the control lines gpio_init(address_pins[i]); gpio_set_dir(address_pins[i], GPIO_OUT); } for (int i=0; i<NUM_AS; i++) { // Set up directions for the control lines gpio_init(as_pins[i]); gpio_set_dir(as_pins[i], GPIO_OUT); } // Data lines are inputs for (int i=0; i<NUM_DATA; i++) { // Set up directions for the control lines gpio_init(data_pins[i]); gpio_set_dir(data_pins[i], GPIO_IN); } // Clock lines are outputs gpio_init(CLKA_PIN); gpio_set_dir(CLKA_PIN, GPIO_OUT); gpio_init(CLKB_PIN); gpio_set_dir(CLKB_PIN, GPIO_OUT); // Perform the mode that was requested switch(config_record->mode) { case USB_DUMP: printf("\nUSB Dump\n"); sleep_ms(1000); usb_dump(); break; case SLOT_DUMP: printf("\nSlot Dump\n"); sleep_ms(1000); slot_dump(); break; default: printf("\nUnknown mode."); break; } // All done, flash the LED printf("\nDone."); printf("\n"); while(1) { sleep_ms(250); gpio_put(LED_PIN, 0); sleep_ms(250); gpio_put(LED_PIN, 1); } }
C
#include "holberton.h" /** * print_triangle - Prototype * Description: Print a triangle * @size: size of triangle * Return: void */ void print_triangle(int size) { int colm; int row; /* If size is 0 or less, print new line per project request */ if (size < 1) _putchar('\n'); /* create the column using size as size of triangle */ for (colm = 1; colm <= size; colm++) { for (row = 1; row <= size - colm; row++) _putchar(' '); /* Create the row with also using size as triangle size */ for (; row <= size; row++) _putchar('#'); _putchar('\n'); } }
C
#include <stdio.h> /* NULL Pointer */ int main() { int *ptr = NULL; printf("Pointer degeri : %x\n", ptr); return 0; }
C
/******************************************************************************/ /* INCLUDE FILES */ /******************************************************************************/ #include "Serial.h" /******************************************************************************/ /* DEFINITIONS */ /******************************************************************************/ #define Serial_MAX_TX_SIZE 32 #define Serial_MAX_RC_SIZE 32 /******************************************************************************/ /* GLOBAL VARIABLES */ /******************************************************************************/ unsigned char Serial_TX_BUFFER[Serial_MAX_TX_SIZE], Serial_RC_BUFFER[Serial_MAX_RC_SIZE]; unsigned char Serial_TX_HEAD, Serial_TX_TAIL, Serial_RC_HEAD, Serial_RC_TAIL; /******************************************************************************/ /* FUNCTIONS */ /******************************************************************************/ /******************************************************************************/ /* General Functions Part 1 */ /******************************************************************************/ /***************************************************************************//** * @brief Initializes the EUSART communication. * * @param None. * * @return None. *******************************************************************************/ unsigned char Serial_Initialize() { unsigned long baud_rate = 34; //416; unsigned char i; /* Set the pins for the RC pin */ Serial_RC_DIR = 1; Serial_RC_ANSEL = 0; /* Set the pins for the TX pin */ Serial_TX_DIR = 1; Serial_TX_ANSEL = 0; /* Set the bits for controlling the baud rate */ Serial_BAUDRATE_HB = (baud_rate >> 8); // value needs to be 34 Serial_BAUDRATE_LB = (baud_rate >> 0); /* Set the bits for the TxSTA1 register */ Serial_TX_ENABLE = 1; // Transmit enabled Serial_TX_MODE = 0; // Asynchronous mode Serial_TX_HIGHRATE = 1; // High speed /* Set the bits for the RCSTA1 register */ Serial_RC_SERIAL = 1; // Serial port enabled (configures RXx and TXx pins as serial port pins) Serial_RC_CONT = 1; // Enables receiver /* Set the bits for the BAUDCON register for the baud rate generator */ Serial_BAUD_RCPOL = 0; // Receive data (RXx) is not inverted (active-high) Serial_BAUD_TXPOL = 0; // Idle state for transmit (TXx) is low Serial_BAUD_BITSIZE = 1; // 16-bit Baud Rate Generator is used Serial_BAUD_AUTO = 0; // Auto-Baud Detect mode is disabled /* Activate the interrupts */ INTERRUPT_PRIORITY = 1; // Enable priority levels on interrupts INTERRUPT_GLOBAL = 0; // Enable all high priority interrupts INTERRUPT_PERIPHERAL = 0; // Enable all low priority interrupts /* Enable interrupts on the PIE1 register */ Serial_RCINT_ENABLE = 1; // Enables the EUSART1 receive interrupt Serial_TXINT_ENABLE = 1; // Enables the EUSART1 transmit interrupt /* Clear the interrupt flags on the PIR1 register */ Serial_RC_FULL = 0; // EUSART1 Receive Interrupt Flag bit Serial_TX_EMPTY = 0; // EUSART1 Transmit Interrupt Flag bit /* Set the interrupt priority on the IPR1 register */ Serial_RCINT_PRIORITY = 1; // High priority Serial_TXINT_PRIORITY = 1; // High priority /* Initialize the RC and TX buffers */ Serial_RC_HEAD = Serial_RC_TAIL = Serial_TX_HEAD = Serial_TX_TAIL = 0; for (i = 0; i < Serial_MAX_RC_SIZE; i = i + 1) { Serial_RC_BUFFER[i] = 0; } return 1; } /***************************************************************************//** * @brief Increment the specified index and check if the end of the buffer has * been reached. If the end has been reached, the index is wrapped back * around to the beginning of the buffer. * * @param None. * * @return Incremented index value. *******************************************************************************/ unsigned char Serial_IncrementIndex(unsigned char idx, unsigned char max) { if (++idx == max) { idx = 0; } // increment index; and if buffer end reached, start from beginning return idx; // return the index } /******************************************************************************/ /* Receive Functions */ /******************************************************************************/ /***************************************************************************//** * @brief Stores the new character that is received on the serial communication * into the input buffer. * * @param None. * * @return None. *******************************************************************************/ void Serial_RC_WriteBuffer(unsigned char data) { /* Write the data to the current head of the buffer */ Serial_RC_BUFFER[Serial_RC_HEAD] = data; /* Increment the head of the buffer */ Serial_RC_HEAD = Serial_IncrementIndex(Serial_RC_HEAD, Serial_MAX_RC_SIZE); /* If you have reached the tail, increment the tail of the buffer */ if (Serial_RC_HEAD == Serial_RC_TAIL) { Serial_RC_TAIL = Serial_IncrementIndex(Serial_RC_TAIL, Serial_MAX_RC_SIZE); } } /***************************************************************************//** * @brief Retrieves a received value from the RC buffer * * @param None. * * @return Oldest character in the RC buffer. *******************************************************************************/ unsigned char Serial_RC_ReadBuffer() { unsigned char data; /* Temporarily disable the interrupts */ INTERRUPT_GLOBAL = 0; /* Read the data from the end of the buffer */ data = Serial_RC_BUFFER[Serial_RC_TAIL]; /* Increment the tail of the buffer */ Serial_RC_TAIL = Serial_IncrementIndex(Serial_RC_TAIL, Serial_MAX_RC_SIZE); /* Re-enable the interrupt */ INTERRUPT_GLOBAL = 1; return data; } /***************************************************************************//** * @brief Reads a byte off the RC register and writes it to the RC buffer. * * @param None. * * @return None. *******************************************************************************/ void Serial_RC_ReadByte() { /* Read the data from the RC register */ Serial_RC_WriteBuffer(Serial_RC_REGISTER); /* REMOVE THIS LINE OF CODE. Testing used to send characters to the transmit buffer */ Serial_TX_WriteBuffer(Serial_RC_ReadBuffer()); } /***************************************************************************//** * @brief Checks if there is received data available to be read. * * @param None. * * @return 1 - data is available to be read, 0 - data is not available. *******************************************************************************/ unsigned char Serial_RC_isDataAvailable() { return (Serial_RC_HEAD != Serial_RC_TAIL); } /***************************************************************************//** * @brief Resets the RC buffer. * * @param None. * * @return None. *******************************************************************************/ void Serial_RC_Clear() { Serial_RC_HEAD = Serial_RC_TAIL = 0; // reset the head and the tail to the beginning of the buffer } /******************************************************************************/ /* Transmit Functions */ /******************************************************************************/ /***************************************************************************//** * @brief Stores a character that needs to be transmitted on the TX buffer. * * @param Byte of data to write to the transmit buffer. * * @return None. *******************************************************************************/ void Serial_TX_WriteBuffer(unsigned char data) { /* Temporarily disable interrupts */ INTERRUPT_GLOBAL = 0; /* Write the data to the current head of the buffer */ Serial_TX_BUFFER[Serial_TX_HEAD] = data; /* Increment the head of the buffer */ Serial_TX_HEAD = Serial_IncrementIndex(Serial_TX_HEAD, Serial_MAX_TX_SIZE); /* If you have reached the tail, increment the tail of the buffer */ if (Serial_TX_HEAD == Serial_TX_TAIL) { Serial_TX_TAIL = Serial_IncrementIndex(Serial_TX_TAIL, Serial_MAX_RC_SIZE); } /* Re-enable the interrupts */ Serial_TXINT_ENABLE = 1; INTERRUPT_GLOBAL = 1; } /***************************************************************************//** * @brief Puts multiple bytes of data into the transmit buffer. * * @param None. * * @return 1 - transfer of data successful, 0 - transfer of data unsuccessful. *******************************************************************************/ void Serial_TX_WriteBufferMultiple(unsigned char* data) { /* Iterate through the data */ while (*data != 0x00) { // while there is still data in the vector /* Write the data to the buffer */ Serial_TX_WriteBuffer(*data); /* Increment the data address */ data = data + 1; } } /***************************************************************************//** * @brief Outputs a signal byte to the Serial communication line. * * @param None. * * @return None. *******************************************************************************/ void Serial_TX_SendByte() { /* Temporarily disable interrupts */ INTERRUPT_GLOBAL = 0; /* Write the data at the end of the transmit buffer to the transmit register */ Serial_TX_REGISTER = Serial_TX_BUFFER[Serial_TX_TAIL]; /* Increment the tail of the buffer */ Serial_TX_TAIL = Serial_IncrementIndex(Serial_TX_TAIL, Serial_MAX_TX_SIZE); /* Re-enable interrupts */ INTERRUPT_GLOBAL = 1; } /***************************************************************************//** * @brief Checks if there is data available to be transmitted on the TX buffer. * * @param None. * * @return 1 - data is available to be transmitted, 0 - data is not available.. *******************************************************************************/ unsigned char Serial_TX_isDataAvailable() { /* If data is available, enable the TX interrupts */ if (Serial_TX_HEAD != Serial_TX_TAIL) { Serial_TXINT_ENABLE = 1; } /* If data is not available, disable the TX interrupt */ else { Serial_TXINT_ENABLE = 0; } return Serial_TXINT_ENABLE; } /***************************************************************************//** * @brief Resets the TX buffer. * * @param None. * * @return None. *******************************************************************************/ void Serial_TX_Clear() { Serial_TX_HEAD = Serial_TX_TAIL = 0; // reset the head and the tail to the beginning of the buffer } /******************************************************************************/ /* General Functions Part 2 */ /******************************************************************************/ /***************************************************************************//** * @brief Clears both the receive and transmit buffers. * * @param None. * * @return None. *******************************************************************************/ void Serial_ClearAll() { Serial_TX_Clear(); Serial_RC_Clear(); } /***************************************************************************//** * @brief Interrupt service routing for EUSART communication. * * @param None. * * @return None. *******************************************************************************/ void Serial_ISR() { /* If there is data in the RC register and the RC interrupts are enabled */ if (Serial_RC_FULL && Serial_RCINT_ENABLE) { /* Read the byte on the RC register and write it to the RC buffer */ Serial_RC_ReadByte(); if (Serial_RC_FULL) { Serial_RC_ReadByte(); } } /* If the TX register is available and the TX interrupts are enabled */ if (Serial_TX_EMPTY && Serial_TXINT_ENABLE) { /* If data is available to be transmitted */ if (Serial_TX_isDataAvailable()) { /* Write data from the TX buffer to the TX register*/ Serial_TX_SendByte(); if (Serial_TX_EMPTY) { Serial_TX_SendByte(); } } } /* Clear the interrupt flags */ Serial_RC_FULL = 0; Serial_TX_EMPTY = 0; } void Serial_ISR_SimpleResponse() { unsigned char data; /* If the RC register is full and we have RC interrupts enabled */ if (Serial_RC_FULL && Serial_RCINT_ENABLE) { /* Read data from the RC register */ data = Serial_RC_REGISTER; /* If the TX register is empty and we have TX interrupts enabled, send out the received data */ if (Serial_TX_EMPTY && Serial_TXINT_ENABLE) { Serial_TX_REGISTER = data; } } /* Clear the interrupt flags */ Serial_RC_FULL = 0; Serial_TX_EMPTY = 0; }
C
#include "holberton.h" /** * get_bit - returns the value of a bit at a given index. * @n: integer input. * @index: index to retrieve value at. * Return: int, binary value at index. * -1, on failure. */ int get_bit(unsigned long int n, unsigned int index) { unsigned int i; if (index > sizeof(long) * 8) return (-1); i = (n & (1 << index) ? 1 : 0); if (i <= 1) return (i); return (-1); }
C
#define _CRT_SECURE_NO_WARNINGS #include<stdio.h> #include<stdlib.h> #include<string.h> char *change(char *str) { char *tempstr = malloc(strlen(str) + 1); //strlen //memset(tempstr, 0, sizeof(str) + 1); int x = 0, y = 0; char assii_1, assii_2; while (tempstr[x]) { if ((tempstr[x] = str[y]) == '%') { //y+1,y+2 if (str[y + 1] >= 'A') { assii_1 = str[y + 1] - 55; } else { assii_1 = str[y + 1] - 48; } if (str[y + 2] >= 'A') { assii_2 = str[y + 2] - 55; } else { assii_2 = str[y + 2] - 48; } tempstr[x] = assii_1 * 16 + assii_2; y += 2; } x++; y++; } tempstr[x] = '\0'; return tempstr; } void search(char *path, char *searchstr) { FILE *pf = fopen(path, "r"); if (pf == NULL) { printf("<br>ʧ"); } else { while (!feof(pf)) { char str[512] = { 0 }; fgets(str, 512, pf); char *p = strstr(str, searchstr); if (p != NULL) { puts(str); puts("<br>"); } } fclose(pf); } } void main() { printf("Content-type:text/html\n\n"); // char szpost[256] = { 0 }; gets_s(szpost, sizeof(szpost)); printf("%s", szpost); char *p1 = strchr(szpost, '&'); if (p1 != NULL) { *p1 = '\0'; } printf("<br>%s", szpost + 5); printf("<br>%s", change(szpost + 5)); char *p2 = strchr(p1 + 1, '&'); if (p2 != NULL) { *p2 = '\0'; } printf("<br>%s", p1 + 6); printf("<br>%s", change(p1 + 6)); char path[256] = "G:\\BigData.txt"; search(path, change(szpost + 5)); //֮ } void main123() { printf("Content-type:text/html\n\n"); // char path[256] = "G:\\BigData.txt"; search(path, "1424543"); }
C
#include <stdio.h> int main() { int n; scanf("%d",&n); while (n--) { char s[10]; scanf("%s",s); char temp[] = "Vino\0"; if ( strcmp(s,temp) == 0 ) { printf("Vino is exist"); break; } } if (!++n) printf("The Entered Name is not in the Directory"); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <sys/types.h> #include <sys/socket.h> #include <arpa/inet.h> #include <netinet/in.h> int main() { int client_socket; char buffer[256]; char msg[50]; struct sockaddr_in server_address, client_address; if ( (client_socket = socket(AF_INET, SOCK_DGRAM, 0)) < 0 ) { printf("error: socket creation failed\n"); return -1; } server_address.sin_family = AF_INET; server_address.sin_port = htons(6000); server_address.sin_addr.s_addr=inet_addr("127.0.0.1"); sprintf(msg, "12 53"); sendto(client_socket, (const char *)msg, strlen(msg), MSG_CONFIRM,(const struct sockaddr *) &server_address, sizeof(server_address)); printf("Sending was successfull!\n"); int n, server_address_len; n = recvfrom(client_socket, (char *)buffer, 255, MSG_WAITALL, (struct sockaddr*) &server_address, &server_address_len); buffer[n] = '\0'; printf("SUM is: %s\n", buffer); close(client_socket); return 0; }
C
/* ** ex_02.c for ex_02.c in /home/jerome/rendu/pool_c_d04/ex_02 ** ** Made by demourgues ** Login <jerome> ** ** Started on Thu Oct 5 12:09:30 2017 demourgues ** Last update Thu Oct 5 15:23:18 2017 demourgues */ #include <stdio.h> #include <unistd.h> void my_putchar(char a) { write(1, &a, 1); } void my_putstr(char *str) { int i; i = 0; while (str[i] != '\0') { my_putchar(str[i]); ++i; } } /* int main() { char *str; str = ""; my_putstr(str); return(0); } */
C
//2019117865 質 #define _CRT_SECURE_NO_WARNINGS #include <stdio.h> int main(void) { int num; do { int fac = 1; printf(" 1 Էϼ (: ) : "); scanf("%d", &num); for (int i = 1; i < num + 1; i++) { fac *= i; } if (num >= 0) { printf("%d! = %d\n\n", num, fac); } } while (num >= 0); return 0; }