language
large_string
text
string
C
#include "FilaComVetor.h" #include <stdio.h> #include <stdlib.h> #define TAM 10 struct fila { int ini; int n; Aluno* alunos[TAM]; }; Fila* InicFila(void){ Fila* f = (Fila*) malloc(sizeof (Fila)); f->ini = 0; f->n = 0; return f; } //insere fila (SEMPRE no final) void InsereFila(Fila* f, Aluno* al){ //testa se fila esta cheia if(!f || f->n >= TAM){ printf ("\nPilha invalida ou cheia!\n"); return; } //achando o final da fila circular int pos = (f->ini + f->n) % TAM; //inserindo no final f->alunos[pos] = al; //incrementando numero alunos f->n++; } //retirna fila (SEMPRE no inicio) Aluno* RetiraFila (Fila* f){ if(!f || f->n == 0){ printf ("\nPilha invalida ou cheia!\n"); return NULL; } Aluno* al = f->alunos[f->ini]; //faz incremento circular do indice do inicio f->ini = (f->ini+1)%TAM; f->n--; return al; } //Imprime fila (do inicio ao final) void ImprimeFila (Fila* f){ int i; int pos = 0; if(!f){ return; } for(i=0; i<f->n; i++){ ImprimeAluno(f->alunos[pos]); } } //libera memoria da fila (e nao dos alunos) void DestroiFila(Fila* f){ if(!f){ return; } free(f); //ver se precisa destruir aluno }
C
#include "hx711.h" // function prototype int *get_int(int *num); int main(int argc, char **argv) { int err = 0; if (argc < 3) { printf("\nRequired 3 args."); printf("\nFirst arg is CLK pin, second arg is DATA pin (BMC numbering)."); printf("\nThird arg is number of samples."); return 1; } int priority = 10; err = setPriority(priority); if (err) { printf("\n!!! Failed to set process priority to %d\n", priority); return 1; } HX711 hx; unsigned char clock_pin = (unsigned)atoi(argv[1]); unsigned char data_pin = (unsigned)atoi(argv[2]); unsigned int samples = 0; if (argc == 4) { samples = (unsigned)atoi(argv[3]); } err = initHX711(&hx, clock_pin, data_pin); if (err) { printf("\n!!! Failed to init HX711 struct !!!\n"); } setupGPIO(&hx); reset(&hx); if (!samples) { samples = 1; } // START doing work /* err = zeroScale(&hx); if (err) { printf("\n!!! Failed to zero the scale.\n"); return 1; } printf("\n Zero scale is done!"); */ double single_item_weight = getDataMean(&hx, samples); printf("%d", (int)single_item_weight); // STOP doing work cleanGPIO(&hx); return 0; }
C
/** * @mainpage * # Загальне завдання * **Створити** програму з використанням показчиків; * * # Індивідуальне завдання * **Підрахувати** кількість ділянок заданого масиву з N речовинних чисел, які утворюють безперервні послідовності чисел з незменшуваними значеннями. Максимальну ділянку переписати в інший масив. * * @author Belchynska K. * @date 23-feb-2021 * @version 1.0 */ /** * @file main.c * @brief Файл з викликом усіх функцій * використаних для заповнення результуючого масиву і підрахування кількості ділянок * @author Belchynska K. * @date 23-feb-2021 * @version 1.0 */ #include "lib.h" /** * Головна функція. * * Послідовність дій: * - виділення пам'яті для заданого масиву речовиних чисел * {@link arrayIn} * - виклик функції для заповнення заданого масиву псевдовипадковими числами * {@link fillArrayIn} * - виклик функції, що оприділяє кількість незменшуваних послідовностей * {@link countOfIncreasingSequences} * - виклик функції, що визначає максимальну довжину ділянки * {@link findMaxIncreasingSequence} * - виділення пам'яті під результуючий масив * {@link arrayOut} * - виклик функції, що заповнює результуючий масив * {@link fillArrayOut} * @return успішний код повернення з програми (0) */ int main() { printf("Лабораторна робота #12 \nБельчинська Катерина\n"); puts("Взаємодія з користувачем шляхом механізму введення-виведення"); fwrite("КІТ-320", sizeof(char), 9, stdout); int N; //long N3; //char N2; //char lenStr[2]; //lenStr[0] = N2; //lenStr[1] = '\0'; printf("\nВведіть довжину масиву: "); scanf("%d", &N); //N2 = getc(stdin); //N3 = strtol(lenStr, NULL, 10); float* arrayIn = (float*)malloc(N * sizeof(float)); fillArrOne(arrayIn, N); int countOfSequences = countOfIncreasingSequences(arrayIn, N); printf("\nКількість незменшуваних послідовностей: %d", countOfSequences); int startOfMaxIncreasingSequence = 0; int lenOut = findMaxIncreasingSequence(arrayIn, N, &startOfMaxIncreasingSequence); float * arrayOut1 = (float *)malloc(lenOut * sizeof(float )); fillArrayOut(arrayIn, startOfMaxIncreasingSequence, arrayOut1, lenOut); //fwrite(&countOfSequences, sizeof(countOfSequences), 1, stderr); //char sCountOfSequences[50]; //printf( "Кількість послідовностей: %d", countOfSequences); //puts("Результуючий масив: "); printArrayOut(arrayIn, startOfMaxIncreasingSequence, arrayOut1, lenOut); free(arrayIn); free(arrayOut1); return 0; }
C
#include "holberton.h" #include <stdlib.h> /** * alloc_grid - function that returns pointer to a 2-D array of integers * @width: number or row to print * @height: number of column to print * Return: pointer value of grid */ int **alloc_grid(int width, int height) { int **dimension; int alto, ancho; if (width <= 0 || height <= 0) return (NULL); dimension = malloc(sizeof(int *) * height); if (dimension == NULL) { free(dimension); return (NULL); } for (ancho = 0; ancho < height; ancho++) { dimension[ancho] = malloc(sizeof(int) * width); if (dimension[ancho] == NULL) { for (alto = ancho; alto >= 0; alto--) { free(dimension[alto]); } free(dimension); return (NULL); } } for (ancho = 0; ancho < height; ancho++) { for (alto = 0; alto < width; alto++) { dimension[ancho][alto] = 0; } } return (dimension); }
C
/*A Program To find The sum Of Digits Of A Number*/ #include <stdio.h> main() { int bit,sum=0; long temp,m; clrscr(); printf("\nEnter A Digit :\n"); scanf("%ld",&m); temp=m; while(temp>0) { bit=(temp%10); sum+=bit; temp/=10; } printf("\nThe Sum Of The Digits Is=\n%d",sum); getch(); } 
C
////By Maxim Johansson #include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <math.h> #include "functions.h" #include <crtdbg.h> #define HEIGHT 512 //Changable value #define WIDTH 1024 //Changable value int main () { _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF); //Flag to check for memory leaks // Memory allocation & color generation wizardry Image plain; plain.height = HEIGHT; plain.width = WIDTH; plain.pixels = (Pixel**) malloc(sizeof(Pixel*) * plain.height); for(unsigned int i = 0; i < plain.height; i++) { plain.pixels[i] = (Pixel*) malloc(sizeof(Pixel) * plain.width); for(unsigned int j = 0; j < plain.width; j++) { plain.pixels[i][j].r = 255-(i/2); plain.pixels[i][j].g = j/4; plain.pixels[i][j].b = 0; } } Image image; image.height = HEIGHT; image.width = WIDTH; // Variable declarations. bool filenamematch = false; // Boolean to loop the match. bool fileisloaded = false; // Boolean to loop the match. int choicereturn; // A returned choice from printMenu(). char readfilename[30]; // For scanning the flie name. char newfilename[30]; // For scanning the flie name. image.pixels = NULL; // Free the memory // Program menu. do { choicereturn = printMenu(); switch (choicereturn) { case 1: do { printf("\nType the name of the file: "); scanf("%s", &readfilename); getchar(); FILE *filepointer; // Extra feature to access file system. if ((filepointer = fopen(readfilename, "r")) == NULL) // This will check the file existance before importing. { filenamematch = false; printf("\nThe file wasn't found, please try again. "); } else if (image.pixels != NULL) // This will reimport the file (replace). { for (unsigned int i = 0; i < image.height; i++) //Will go though and empty { free(image.pixels[i]); } free(image.pixels); // Will just empty and import the file, fclose(filepointer); filenamematch = true; fileisloaded = true; readImage(readfilename, &image); printf("\nThe picture has been reimported! \nPress any key to continue..."); getchar(); } else // This will import the file. { fclose(filepointer); filenamematch = true; fileisloaded = true; readImage(readfilename, &image); printf("\nThe picture has been imported! \nPress any key to continue..."); getchar(); } } while (filenamematch != true); break; case 2: if (image.pixels != NULL) { printf("Note: name must have no spaces and .png extention must presist. \nUsing the same name with already existing file, will replace that file \nType the name: "); scanf("%s", &newfilename); getchar(); printf("\nSaving PNG...\n"); writeImage(newfilename, &image); printf("Save complete! \nPress any key to continue..."); getchar(); } else { printf("There is nothing to save! Load the file first!\n"); printf("Press any key to continue..."); getchar(); } break; case 3: if (image.pixels != NULL) { invertImg(&image); printf("The picture has been inverted! \nPress any key to continue..."); getchar(); } else { printf("Connot comply, load the file first!\n"); printf("Press any key to continue..."); getchar(); } break; case 4: if (image.pixels != NULL) { colorShift(&image); printf("The picture has been color corrected! \nPress any key to continue..."); getchar(); } else { printf("Connot comply, load the file first!\n"); printf("Press any key to continue..."); getchar(); } break; case 5: if (image.pixels != NULL) { rotateImg(&image); printf("The picture has been rotated! \nPress any key to continue..."); getchar(); } else { printf("Connot comply, load the file first!\n"); printf("Press any key to continue..."); getchar(); } break; case 6: if (image.pixels != NULL) { enlargeImg(&image); printf("The picture has been enlarged! \nPress any key to continue..."); getchar(); } else { printf("Connot comply, load the file first!\n"); printf("Press any key to continue..."); getchar(); } break; case 7: if (image.pixels != NULL) { zoomImg(&image); printf("The picture has been zoomed in! \nPress any key to continue..."); getchar(); } else { printf("Connot comply, load the file first!\n"); printf("Press any key to continue..."); getchar(); } break; case 8: // That will check if picture was loaded before and if yes, will free the memory and close the program, else just close the program. if (image.pixels != NULL) { for (unsigned int i = 0; i < image.height; i++) // Will go though and empty { free(image.pixels[i]); } free(image.pixels); for (unsigned int i = 0; i < plain.height; i++) // Will go though and empty { free(plain.pixels[i]); } free(plain.pixels); } else { for (unsigned int i = 0; i < plain.height; i++) // Will go though and empty { free(plain.pixels[i]); } free(plain.pixels); } break; } } while (choicereturn != 8); return 0; }
C
//TODO test this thoroughly int path_parse(char* pathspec, MAILPATH* path){ //See http://cr.yp.to/smtp/address.html for hints on address parsing bool quotes = false, done_parsing = false, comment = false; unsigned out_pos = 0, in_pos = 0; //skip leading spaces for(; isspace(pathspec[0]); pathspec++){ } logprintf(LOG_DEBUG, "Parsing path %s\n", pathspec); for(in_pos = 0; !done_parsing && out_pos < (SMTP_MAX_PATH_LENGTH - 1) && pathspec[in_pos]; in_pos++){ if(!comment){ switch(pathspec[in_pos]){ case '@': if(out_pos == 0){ //route syntax. skip until next colon. for(; pathspec[in_pos] && pathspec[in_pos] != ':'; in_pos++){ } if(pathspec[in_pos] != ':'){ //colon was somehow the last character. someone blew this. done_parsing = true; } } else{ if(quotes){ path->path[out_pos++] = pathspec[in_pos]; } else if(path->delimiter_position == 0 && path->path[path->delimiter_position] != '@'){ //copy to out buffer and update delimiter position path->delimiter_position = out_pos; path->path[out_pos++] = pathspec[in_pos]; } else{ logprintf(LOG_WARNING, "Multiple delimiters in path\n"); return -1; } } break; case '"': quotes = !quotes; break; case '\\': //escape character. add next char to out buffer //WARNING this can cause an issue when implemented incorrectly. //if the last character sent is a backslash escaping \0 the //loop potentially accesses memory out of bounds. //so, we check for that. //actually, in this implementation, there are at least //2 \0 bytes in that case, so this is a non-issue. //FIXME allow only printable/space characters here if(pathspec[in_pos + 1]){ in_pos++; if(isprint(pathspec[in_pos])){ path->path[out_pos++] = pathspec[in_pos]; } } else{ done_parsing = true; break; } break; case '(': //comment delimiter comment = true; break; case ')': //comment closed without active comment context logprintf(LOG_WARNING, "Path contained illegal parenthesis\n"); return -1; case '<': if(!quotes){ //start mark. ignore it. break; } //fall through case '>': //FIXME allow only printable nonspace(?) characters here if(!quotes){ done_parsing = true; break; } //fall through default: //copy to out buffer if(isprint(pathspec[in_pos])){ path->path[out_pos++] = pathspec[in_pos]; } } } else if(pathspec[in_pos] == ')'){ comment = false; } } path->path[out_pos] = 0; if(comment){ logprintf(LOG_WARNING, "Path contains unterminated comment\n"); return -1; } if(!path->delimiter_position){ path->delimiter_position = strlen(path->path); } logprintf(LOG_DEBUG, "Result is %s, delimiter is at %d\n", path->path, path->delimiter_position); return 0; } // If originating_user is set, this checks if the user may use the path outbound int path_resolve(MAILPATH* path, DATABASE* database, char* originating_user, bool is_reverse){ int status, rv = -1; //this early exit should never have to be taken if(path->route.router){ logprintf(LOG_WARNING, "Taking early exit for path %s, please notify the developers\n", path->path); return 0; } status = sqlite3_bind_text(database->query_address, 1, path->path, -1, SQLITE_STATIC); if(status == SQLITE_OK){ do{ status = sqlite3_step(database->query_address); if(status == SQLITE_ROW){ if(originating_user || is_reverse){ //Test whether the originating_user may user the supplied path outbound. //This implies traversing all entries and testing the following conditions // 1. Router must be 'store' // 2. Route must be the originating user // Else, try the next entry if(originating_user && (strcmp((char*)sqlite3_column_text(database->query_address, 0), "store") || strcmp(originating_user, (char*)sqlite3_column_text(database->query_address, 1)))){ // Falling through to SQLITE_DONE here implies a non-local origin while routers for this adress are set // (just not for this user). The defined router will then fail the address, the any router will accept it continue; } //Continuing here if no originating_user given or the current routing information //applies to the originating_user } //heap-copy the routing information path->route.router = common_strdup((char*)sqlite3_column_text(database->query_address, 0)); if(sqlite3_column_text(database->query_address, 1)){ path->route.argument = common_strdup((char*)sqlite3_column_text(database->query_address, 1)); } if(!path->route.router){ logprintf(LOG_ERROR, "Failed to allocate storage for routing data\n"); //fail temporarily rv = -1; break; } //check for reject if(!strcmp(path->route.router, "reject")){ rv = 1; break; } //all is well rv = 0; break; } } while(status == SQLITE_ROW); switch(status){ case SQLITE_ROW: //already handled during loop break; case SQLITE_DONE: logprintf(LOG_INFO, "No address match found\n"); //continue with this path marked as non-local rv = 0; break; default: logprintf(LOG_ERROR, "Failed to query wildcard: %s\n", sqlite3_errmsg(database->conn)); rv = -1; break; } } else{ logprintf(LOG_ERROR, "Failed to bind search parameter: %s\n", sqlite3_errmsg(database->conn)); rv = -1; } sqlite3_reset(database->query_address); sqlite3_clear_bindings(database->query_address); // Calling contract // 0 -> Accept path // 1 -> Reject path (500), if possible use router argument // * -> Reject path (400) return rv; } void path_reset(MAILPATH* path){ MAILPATH reset_path = { .delimiter_position = 0, .in_transaction = false, .path = "", .route = { .router = NULL, .argument = NULL } }; route_free(&(path->route)); *path = reset_path; }
C
#include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <errno.h> #include <string.h> #include <fcntl.h> #include <sys/dispatch.h> #include <sys/mman.h> #include <pthread.h> struct pid_data{ pthread_mutex_t pid_mutex; pid_t pid; }; int main(int argc, char *argv[]) { // Server int file_desc = shm_open("/sharedpid", O_RDWR | O_CREAT, S_IRWXU); ftruncate(file_desc, sizeof(struct pid_data)); struct pid_data* mem_pid_ptr; mem_pid_ptr = mmap(0, sizeof(struct pid_data), PROT_READ | PROT_WRITE, MAP_SHARED, file_desc, 0); pthread_mutexattr_t myattr; pthread_mutexattr_init(&myattr); pthread_mutexattr_setpshared(&myattr, PTHREAD_PROCESS_SHARED); pthread_mutex_init(&mem_pid_ptr->pid_mutex, &myattr); pid_t mypid = getpid(); mem_pid_ptr->pid = mypid; printf("%d\n", mypid); int channel = ChannelCreate(0); char buffer[10]; char reply[] = "Replying"; int msg_id = MsgReceive(channel, &buffer, sizeof(char)*10, NULL); printf("Received msg : %s\n", buffer); MsgReply(msg_id, 0, &reply, sizeof(char)*9); // Client /* int file_desc = shm_open("/sharedpid", O_RDWR, S_IRWXU); struct pid_data* mem_pid_ptr; mem_pid_ptr = mmap(0, sizeof(struct pid_data), PROT_READ | PROT_WRITE, MAP_SHARED, file_desc, 0); pthread_mutexattr_t myattr; pthread_mutexattr_init(&myattr); pthread_mutexattr_setpshared(&myattr, PTHREAD_PROCESS_SHARED); pthread_mutex_init(&mem_pid_ptr->pid_mutex, &myattr); pid_t pid = mem_pid_ptr->pid; printf("Found pid: %d\n", pid); char buffer[]="Got pid"; char received[10]; int channel = ConnectAttach(0, pid, 1, 0, 0); int status = MsgSend(channel, buffer, sizeof(char)*8, received, sizeof(char)*10); printf("Received: %s\n", received); ConnectDetach(channel); */ return EXIT_SUCCESS; }
C
#include "holberton.h" #include <stdlib.h> /** * str_concat - Entry point * @s1: wopa * @s2: ea * * Description: Show a message blablabla * Return: Always 0 (Success) */ char *str_concat(char *s1, char *s2) { unsigned int larg1 = 0, larg2 = 0, larg3, cont = 0; char *aux; if (!s1) s1 = ""; while (s1[larg1]) larg1++; if (!s2) s2 = ""; while (s2[larg2]) larg2++; larg3 = larg1 + larg2 + 1; aux = malloc(larg3 * sizeof(char)); if (!aux) return (NULL); while (cont < larg1) { aux[cont] = s1[cont]; cont++; } while (cont < larg3) { aux[cont] = s2[cont - larg1]; cont++; } aux[larg3 - 1] = '\0'; return (aux); }
C
#include <stdio.h> #include <time.h> int main() { time_t tempo_local; time(&tempo_local); printf("Tempo local = %s", ctime(&tempo_local)); return 0; } /* DESCRIÇÃO: - A função char *ctime(const time_t *timer) retorna um string que representa a hora local com base no argumento temporizador DECLARAÇÃO: char *ctime(const time_t *timer) PARAMETROS: timer -- É um ponteiro para um objeto do tipo time_t que contem um calendario. RETORNO: - Esta função retorna uma string C contendo a data e informações do tempo em um formato legível: WWW Mmm dd hh:mm:ss aaa - WWW é o dia da semana, - Mmm é o mês em letras, - dd é o dia do mês, - hh:mm:ss é a hora, minuto e segundo, - aaaa é o ano */
C
// // Shaun Chemplavil U08713628 // [email protected] // C / C++ Programming I : Fundamental Programming Concepts // 146359 Raymond L. Mitchell Jr. // 05 / 08 / 2020 // C1A7E2_main.c // Win10 // Visual C++ 19.0 // // This program prompts the user to enter nutritional information for // LUNCH_QTY number of food items contained in a 'lunch' Food structure array // 2 items within this structure array have been initialized // #include <stdio.h> #include <stdlib.h> #include <string.h> #define LUNCH_QTY 5 #define STR_LENGTH 129 #define PRE_INIT_STRUCT 2 int main(void) { struct Food { char *name; /* "name" attribute of food */ int weight, calories; /* "weight" and "calories" attributes of food */ }lunches[LUNCH_QTY] = {{"apple", 4, 100}, {"salad", 2, 80}}; // Populate uninitialized structure array elements for (int lunchCnt = PRE_INIT_STRUCT; lunchCnt < LUNCH_QTY; lunchCnt++) { char buffer[STR_LENGTH]; // get the users strings printf("Enter the whitespace separated name, weight, and calories: "); scanf("%128s%d%d", buffer, &lunches[lunchCnt].weight, &lunches[lunchCnt].calories); // find number of characters input by user size_t buffSize = strlen(buffer); // increment buffsize to account for null character buffSize++; // Allocate memory to place name within structure element if ((lunches[lunchCnt].name = (char *)malloc(buffSize)) == NULL) { fputs("Not enough memory for name\n", stderr); exit(EXIT_FAILURE); } memcpy(lunches[lunchCnt].name, buffer, buffSize); } // Display Results for (int lunchCnt = 0; lunchCnt < LUNCH_QTY; lunchCnt++) { printf("%-15s %5d %5d\n", lunches[lunchCnt].name, lunches[lunchCnt].weight, lunches[lunchCnt].calories); } // free dynamically allocated memory for (int lunchCnt = PRE_INIT_STRUCT; lunchCnt < LUNCH_QTY; lunchCnt++) { free(lunches[lunchCnt].name); } return 0; }
C
/* * Digital.h * * Created: 2/8/2014 2:58:32 PM * Author: Nathan Hernandez */ #ifndef DIGITAL_H_ #define DIGITAL_H_ //Pin Voltage #define LOW 0x0 #define HIGH 0x1 //Pin Mode #define INPUT 0x0 #define OUTPUT 0x1 #define INPUT_PULLUP 0x2 //Digital Pins #define D0 0 #define D1 1 #define D2 2 #define D3 3 #define D4 4 #define D5 5 #define D6 6 #define D7 7 #define D8 8 #define D9 9 #define D10 10 #define D11 11 #define D12 12 #define D13 13 //Analog Pins #define A0 14 #define A1 15 #define A2 16 #define A3 17 #define A4 18 #define A5 19 #include <avr/io.h> #include <inttypes.h> int8_t pinMode(uint8_t pin, uint8_t mode); int8_t digitalWrite(uint8_t pin, uint8_t value); int8_t digitalRead(uint8_t pin); #endif /* DIGITAL_H_ */
C
//#define LOG_DEBUG /** * Note: The returned array must be malloced, assume caller calls free(). */ void reverseArray(int* A, int ASize); int* addToArrayForm(int* A, int ASize, int K, int* returnSize); int* addToArrayForm(int* A, int ASize, int K, int* returnSize) { //check the max size of return array int KSize = 0; for (int i = K; i > 0; i /= 10) KSize++; int rSize = (KSize > ASize) ? (KSize+1) : (ASize+1); int *tmp = calloc(rSize, sizeof(int)); #ifdef LOG_DEBUG printf("rSize = %d \n", rSize); #endif //save values into temp array int idx = 0; for (int i = ASize-1; (i >= 0) || (K > 0); i--) { K += (i >= 0) ? A[i] : 0; tmp[idx] = K % 10; idx++; K /= 10; } #ifdef LOG_DEBUG for (int i = 0; i < rSize; i++) { printf("%d ", tmp[i]); } printf("\n"); #endif //save the temp array to ret int *ret; if (tmp[rSize-1] == 0) { ret = calloc(rSize-1, sizeof(int)); *returnSize = rSize-1; int j = 0; for (int i = rSize-2; i >= 0; i--) { ret[j++] = tmp[i]; } free(tmp); tmp = NULL; } else { ret = tmp; *returnSize = rSize; reverseArray(ret, rSize); } return ret; } void reverseArray(int* A, int ASize) { int l = 0, r = ASize-1; while (l <= r) { int tmp = A[l]; A[l] = A[r]; A[r] = tmp; l++; r--; } }
C
#include <stdio.h> #include <math.h> #define W 386 #define H 320 #define SZ (W*H) unsigned char image[SZ*3]; void d(int R,int G,int B,int x,int y,int r) { while (r) { float dp=1/(6.3*r); float p; for (p=0;p<6.3;p+=dp) { int xo=r*cos(p); int offset=x+xo+floor(y+r*sin(p))*W; if ((x+xo<W)&&offset>0&&offset<SZ) { image[offset*3]=R; image[offset*3+1]=G; image[offset*3+2]=B; } } r-=1; if (y-r>=H)return; } } int main(int argc, char * argv[]) { d(71,104,148,W/2,H/2,W); d(48,67,131,50,40,55); d(48,67,131,175,-240,300); d(162,162,162,130,171,25); d(129,143,120,28.,13,17); d(174,181,123,352,57,38); d(88,113,149,187,108,60); d(138,155,153,370,225,100); d(32,37,82,350,1400,1200); d(60,73,90,338,260,50); d(47,58,72,240,269,50); d(28,32,29,95,275,65); d(28,32,29,66,192,30); printf("P6\n386 320\n255\n"); fwrite(image, sizeof(image), 1, stdout); return 0; }
C
/* ** EPITECH PROJECT, 2019 ** my_compute_power_it ** File description: ** hello */ #include "../my.h" #include "../screen.h" void my_clear_buffer(framebuffer_t *buf) { int size = buf->width * buf->height*4/sizeof(long int); long unsigned int *bufy = (long int *)buf->pixels; long unsigned int lcolor = 0; for (int i = 0; i < size; i++) bufy[i] = lcolor; }
C
#include "../libft.h" #include <stdio.h> #include <string.h> int main(void) { char str1[] = "Hello world"; char str2[] = "42"; char str3[] = ""; char str4[] = "Found it!"; t_list *elem; t_list *elem_test; elem = ft_lstnew(str1); elem->next = ft_lstnew(str2); elem->next->next = ft_lstnew(str3); ft_lstadd_front(&elem, ft_lstnew(str4)); if (!strcmp(elem->content, str4) \ && !strcmp(elem->next->content, str1) \ && !strcmp(elem->next->next->content, str2) \ && !strcmp(elem->next->next->next->content, str3)) printf("\033[92mTest %2.i - OK \033[0m\n", 1); else printf("\033[91mTest %2.i - KO \033[0m\n", 1); free(elem->next->next->next); free(elem->next->next); free(elem->next); free(elem); elem = ft_lstnew(str1); elem->next = ft_lstnew(str2); elem->next->next = ft_lstnew(str3); ft_lstadd_front(&elem, NULL); if (!strcmp(elem->content, str1) \ && !strcmp(elem->next->content, str2) \ && !strcmp(elem->next->next->content, str3)) printf("\033[92mTest %2.i - OK \033[0m\n", 2); else printf("\033[91mTest %2.i - KO \033[0m\n", 2); free(elem->next->next); free(elem->next); free(elem); elem = ft_lstnew(str1); elem->next = ft_lstnew(str2); elem->next->next = ft_lstnew(str3); elem_test = ft_lstnew(str4); ft_lstadd_front(NULL, elem_test); if (!strcmp(elem->content, str1) \ && !strcmp(elem->next->content, str2) \ && !strcmp(elem->next->next->content, str3)) printf("\033[92mTest %2.i - OK \033[0m\n", 3); else printf("\033[91mTest %2.i - KO \033[0m\n", 3); free(elem->next->next); free(elem->next); free(elem); free(elem_test); elem = ft_lstnew(str1); elem->next = ft_lstnew(str2); elem->next->next = ft_lstnew(str3); ft_lstadd_front(NULL, NULL); if (!strcmp(elem->content, str1) \ && !strcmp(elem->next->content, str2) \ && !strcmp(elem->next->next->content, str3)) printf("\033[92mTest %2.i - OK \033[0m\n", 4); else printf("\033[91mTest %2.i - KO \033[0m\n", 4); free(elem->next->next); free(elem->next); free(elem); return (0); }
C
#include "bbs.h" /* Initialize the RNG NOTE: Only call this funtion once */ void bbs_init(uint32_t s, uint32_t p, uint32_t q, uint32_t l) { bbs_s = s; bbs_p = p; bbs_q = q; bbs_l = l; } /* Generate a new raw value */ uint32_t bbs_gen() { uint32_t n = bbs_p * bbs_q; uint32_t r = bbs_s % (n - 1); uint32_t rg, i, x_in, x_out; do { if(++r == n) { r = 1; } rg = gcd(r, n); } while(rg != 1); x_in = r; for(i = 0; i < bbs_l; i++) { x_in = (x_in * x_in) % n; x_out <<= 1; x_out |= x_in % 2; } bbs_s = x_out; return x_out; } /* Generate a new random value [0.0, 1.0) */ double bbs_rand() { return ((bbs_gen() & (((1 << 30) - 1) << 16)) >> 16) / (double) ((1 << 16) - 1); }
C
/* * autor..: EDUARDO DOS SANTOS SPAGNA * disc...: ESTRUTURA DE DADOS * * PILHA */ #include <stdio.h> #include <locale.h> #include <stdlib.h> typedef struct Idade{ int idade; struct Idade * prox; } Idade; typedef struct Pilha{ Idade * topo; } Pilha; Pilha* criar() { Pilha* q = (Pilha*) malloc(sizeof(Pilha)); q->topo = NULL; return q; } void inserir(Pilha* p, int idade) { Idade *new = (Idade*) malloc(sizeof(Idade)); new->idade = idade; new->prox = p->topo; p->topo = new; } int pilhaVazia(Pilha* p){ return(p->topo == NULL); } void imprimir(Pilha * p) { Idade * s; s = p->topo; if(pilhaVazia(p)){ printf("Esta fila est vazia!\n"); } else{ while(s != NULL){ printf("Idade.: %d\n", s->idade); s = s->prox; } } } Idade* buscar(Pilha* p, int idade) { Idade* s; for(s = p->topo; s != NULL; s = s->prox){ if(s->idade == idade) return s; } return NULL; } int remover(Pilha *p) { Idade * t; int v; if(pilhaVazia(p)){ printf("\nPilha j vazia!\n"); return 0; } t = p->topo; v = t->idade; p->topo = t->prox; free(t); return v; } void liberarPilha(Pilha *p) { Idade *s = p->topo; while(s != NULL){ Idade *t = s->prox; free(s); s = t; } free(s); printf("\nPilha liberada..."); } int PilhaOrdenada(Pilha* p) { Idade* s; s = p->topo; if(pilhaVazia(p)){ printf("Esta pilha est vazia!\n"); } else{ while(s->prox != NULL){ if(s->idade > s->prox->idade) return 0; s = s->prox; } } return 1; } int verifPrimo(int num) { int i; int valor; int vzs = 0; for (i = 1; i <= num && vzs <= 3; i++) { if (num % i == 0 || num == 2) vzs ++; } if(vzs == 2) return 1; else return 0; } int contaNumPrimos(Pilha* p) { Idade* s; int contPrimos = 0; int primo = 0; s = p->topo; if(pilhaVazia(p)){ printf("Esta pilha est vazia!\n"); } else{ while(s->prox != NULL){ primo = verifPrimo(s->idade); if(primo == 1) contPrimos++; s = s->prox; } } return contPrimos; } void comparaPilhas(Pilha* p1, Pilha* p2) { if(pilhaVazia(p1) && pilhaVazia(p2)){ printf("\n\nAs pilhas j estao vazias!\n"); return; } Idade* k1 = p1->topo; Idade* k2 = p2->topo; if(k1->idade == k2->idade){ if(k1->prox == NULL && k2->prox == NULL){ printf("\n\nAs filas sao iguais!\n\n"); return; } p1->topo = k1->prox; p2->topo = k2->prox; comparaPilhas(p1, p2); } else printf("\n\nAs pilhas no so iguais!\n\n"); } Pilha* imprimirInvertido(Pilha* p) { Pilha* aux = criar(); Idade* s = p->topo; while(!pilhaVazia(p)) inserir(aux, remover(p)); return aux; } int main() { setlocale(LC_ALL,"portuguese"); Pilha *p; Pilha *p2; Pilha *aux; Idade *k; p = criar(); p2 = criar(); aux = criar(); Idade *buscarIdade = NULL; printf("A pilha 1 est vazia (0,1) : %d\n", pilhaVazia(p)); printf("A pilha 2 est vazia (0,1) : %d\n", pilhaVazia(p2)); printf("\nInserindo elementos...\n"); inserir(p, 82); inserir(p, 71); inserir(p, 35); inserir(p, 5); inserir(p, 2); inserir(p2, 0); inserir(p2, 73); inserir(p2, 5); inserir(p2, 6); inserir(p2, 1); printf("\n===== Pilha 1 =====\n\n"); imprimir(p); printf("\n===== Pilha 2 =====\n\n"); imprimir(p2); printf("\n\nA pilha 1 est vazia (0,1) : %d\n", pilhaVazia(p)); printf("A pilha 2 est vazia (0,1) : %d\n", pilhaVazia(p2)); printf("\n\nBuscando elemento:\n"); buscarIdade = buscar(p, 35); if(buscarIdade != NULL){ printf("\tEncontrou o elemento: %d\n", buscarIdade->idade); } printf("\n\nA pilha 1 est ordenada (0,1) : %d\n", PilhaOrdenada(p)); printf("A pilha 2 est ordenada (0,1) : %d\n", PilhaOrdenada(p2)); printf("\n\nQuantidade de nmeros primos na pilha 1..: %d\n", contaNumPrimos(p)); printf("Quantidade de nmeros primos na pilha 2..: %d\n", contaNumPrimos(p2)); printf("\nRemovendo elemento: %d\n\n", remover(p)); imprimir(p); comparaPilhas(p, p2); printf("\n===== PILHA 1 INVERTIDA =====\n\n"); aux = imprimirInvertido(p); imprimir(aux); liberarPilha(aux); liberarPilha(p2); }
C
#include <stdio.h> #include <string.h> #include <stdlib.h> #include "AM.h" #include "bf.h" #include "defn.h" #include "myfunctions.h" #include <math.h>// ceil function //===================================================GLOBAL VARIABLES ================================================================ int leaf_header_size = sizeof(char) + sizeof(int) + sizeof(int);//leaf block header contains block type,no of entries,right neighbours number int index_header_size = sizeof(char) + sizeof(int); //index block header contains info on block type and no of entries int overflow_header_size = sizeof(char) + sizeof(int); //overflow block header contains info on block type and no of entries //==========================================FUNCTION FOR TYPE AND LENGTH CHECKING======================================================= int size_error(char type,int len){ /*checks the validity of the type and the corresponding length of a field*/ if(type == 'i' && len!=sizeof(int)){ //checking length matches type AM_errno = AM_INVALID_FIELD_SIZE; return -1; } if(type == 'f' && len!=sizeof(float)){ AM_errno = AM_INVALID_FIELD_SIZE; return -1; } if(len < 1){ //checking for valid length AM_errno = AM_INVALID_FIELD_SIZE; return -1; } if(type!= 'c' && type!='f' && type!='i'){//checking for valid type AM_errno = AM_INVALID_TYPE; return -1; } return 0; } //===========================================FUNCTION FOR DESCENDING TREE==================================================== int descend_tree(int fileDesc,void *value1,PATH *path){ /*stores a path of block numbers ,from root_block to the result data/leaf block, inside path array.Returns an empty path if the tree is empty.Returns -1 for error 0 for success.*/ BF_Block *block; char* block_data; char block_type; int keys_no,next_block_no,right,left,i; void *key; int len = Open_files[fileDesc]->f_len1; if(Open_files[fileDesc]->root_block == -1) //no tree blocks allocated yet ,tree is empty,insert leaf will create a root leaf return 0; key = malloc(len); BF_Block_Init(&block); next_block_no = Open_files[fileDesc]->root_block;//first block to be scanned will be root PATH_Push(path,next_block_no);//number of root is first element to be pushed in path AM_errno = BF_GetBlock(Open_files[fileDesc]->fileDesc,next_block_no,block); if(AM_errno != BF_OK) return -1; block_data = BF_Block_GetData(block); block_type = get_block_type(block_data);//retrieving block type while(block_type == 'i'){//descend through all index_blocks and stop when a leaf 'l' is reached keys_no = get_update_entries(block_data,0);//retrieving current number of entries of the block that is examined for(i = 0 ; i<= keys_no - 1 ; i++){//for all entries on the index_block ,searching for the first key greater than value1 get_key(fileDesc, block_data,i ,key); //retrieving the next key/entry at i position get_right(fileDesc,block_data,i,&right); //its right index get_left(fileDesc,block_data,i,&left); //and its left index if(compare_key(value1,key,Open_files[fileDesc]->f_type1) < 0)//comparing key and value1 break; } if(i <= keys_no-1){//found key (at i) greater than value1 next_block_no = left; //descending left index of i key } else{//value1 greater than all keys next_block_no = right;//descending right most index of the block(right index of the last key that was retrieved) } PATH_Push(path,next_block_no); // next block to be scanned pushed in the path AM_errno = BF_UnpinBlock(block);//current block no longer needed in memory if(AM_errno != BF_OK) return -1; AM_errno = BF_GetBlock(Open_files[fileDesc]->fileDesc,next_block_no,block);//retrieving next block to be scanned if(AM_errno != BF_OK) return -1; block_data = BF_Block_GetData(block);//retrieving data of the next block block_type = get_block_type(block_data);//retrieving type of the next block } AM_errno = BF_UnpinBlock(block);//last block was a leaf type,while stopped, we need to unpin it if(AM_errno != BF_OK) return -1; BF_Block_Destroy(&block); free(key); return 0; } //============================================BLOCK ALLOCATION AND FORMATTING FUNCTIONS======================================= int BlockCreate_Leaf(int fileDesc,BF_Block *block,int *block_no){ /*takes fileDesc,an initialized block struct, and a variable for returning the created blocks number descriptor.Allocates and initializes an empty new block of leaf type and returns its number descriptor in the variable block_no*/ char *block_data; int entriesno=0; AM_errno = BF_AllocateBlock(Open_files[fileDesc]->fileDesc,block); //allocating new block if(AM_errno != BF_OK) return -1; AM_errno = BF_GetBlockCounter(Open_files[fileDesc]->fileDesc,block_no);// retrieving total number of blocks in file if(AM_errno != BF_OK) return -1; *block_no -= 1; //number of this block is (number of blocks in file - 1) block_data = BF_Block_GetData(block);//data of the buffer to write into //=============== initializing header part of the block ==================== memcpy(block_data + sizeof(char),&entriesno,sizeof(int));//number of entries on the block initiallized to 0 write_block_type(block_data,'l');//type of the block update_neighbour(block_data,-1);//number of the current neighbour of the block ,-1 for none //============end of initialization============ BF_Block_SetDirty(block); return AME_OK; } int BlockCreate_Index(int fileDesc,BF_Block *block,int *block_no){ /*takes fileDesc,an initialized block struct, and a variable for returning the created blocks number descriptor.Allocates and initializes an empty new block of index type and returns its number descriptor in the variable block_no*/ char *block_data; int entriesno=0; AM_errno = BF_AllocateBlock(Open_files[fileDesc]->fileDesc,block); //allocating new block if(AM_errno != BF_OK) return -1; AM_errno = BF_GetBlockCounter(Open_files[fileDesc]->fileDesc,block_no);//checking number of blocks in file if(AM_errno != BF_OK) return -1; *block_no -= 1; //number descriptor of the block just created is the last block block_data = BF_Block_GetData(block);//data of the buffer to write into //=============== initializing header part of the block ==================== memcpy(block_data + sizeof(char),&entriesno,sizeof(int)); write_block_type(block_data,'i');//type of the block //============end of initialization============== BF_Block_SetDirty(block); return AME_OK; } int BlockCreate_Overflow(int fileDesc,BF_Block *block,int *block_no){ /*takes fileDesc,an initialized block struct, and a variable for returning the created blocks number descriptor.Allocates and initializes an empty new block of overflow type and returns its number descriptor in the variable block_no*/ char *block_data; int entriesno=0; AM_errno = BF_AllocateBlock(Open_files[fileDesc]->fileDesc,block); //allocating new block if(AM_errno != BF_OK) return -1; AM_errno = BF_GetBlockCounter(Open_files[fileDesc]->fileDesc,block_no);//checking number of blocks in file if(AM_errno != BF_OK) return -1; *block_no -= 1; //number descriptor of the block just created is the last block block_data = BF_Block_GetData(block);//data of the buffer to write into //=============== initializing header part of the block ==================== memcpy(block_data + sizeof(char),&entriesno,sizeof(int)); write_block_type(block_data,'o');//type of the block //============end of initialization============== BF_Block_SetDirty(block); return AME_OK; } //====================================COMPARE FUNCTION (char,int,float)============================================== float compare_key(void* value1,void* key,char type){ /*compares value1 of the record to be inserted with the key of the record that occupies the space on the block , returns 0 for equal values a positive integer if value1 is greater than key and a negative integer if value1 is less than key*/ //integer compare if(type == 'i') return (float)(*(int*)value1 - *(int*)key); //string compare else if(type == 'c') return (float)strcmp((char*)value1,(char*)key); //float compare else//(type == 'f') return *(float*)value1 - *(float*)key; } //===================================GENERAL BLOCK FUNCTIONS============================================= char get_block_type(char* data){ /*returns the type of the block*/ char type; memcpy(&type,data,sizeof(char)); return type; } void write_block_type(char* data ,char type){ /*stores the block type ,contained in type variable , in the header of the block*/ memcpy(data,&type,sizeof(char)); } int get_update_entries(char* data,int inc){ /*increments the number of entries on the block by inc amount(can be 0). The value is stored in the header.Returns the number of entries. Can be called with 0 inc to get the current number of entries on the block*/ int entriesno; memcpy(&entriesno,data + sizeof(char),sizeof(int)); entriesno += inc; memcpy(data + sizeof(char),&entriesno,sizeof(int)); return entriesno; } //==================================LEAF BLOCK SPECIFIC FUNCTIONS================================================= void update_neighbour(char* data,int neighbour){ /* updates the value corresponding to the number of the right neighbour*/ memcpy(data + sizeof(char)+sizeof(int),&neighbour,sizeof(int)); } int get_neighbour(char* data){ /*retrieves the number of the current right neighbour of the block*/ int neighbour; memcpy(&neighbour,data + sizeof(char) + sizeof(int),sizeof(int)); return neighbour; } void set_overflow_index(int fileDesc,char* data,int position,int overflowno){ /*sets the overflow index of a record stored sizeof(int) bytes left of it*/ int len1 = Open_files[fileDesc]->f_len1; int len2 = Open_files[fileDesc]->f_len2; memcpy(data + leaf_header_size + position * (len1 + len2 + sizeof(int)),&overflowno,sizeof(int)); } int get_overflow_index(int fileDesc,char* data,int position){ /*returns the overflow index of a record stored sizeof(int) bytes left of it*/ int index; int len1 = Open_files[fileDesc]->f_len1; int len2 = Open_files[fileDesc]->f_len2; memcpy(&index,data + leaf_header_size + position * (len1 + len2 + sizeof(int)),sizeof(int)); return index; } void set_record(int fileDesc,char* data,int position,void* value1,void* value2){ /*stores the record at position*/ int len1 = Open_files[fileDesc]->f_len1; int len2 = Open_files[fileDesc]->f_len2; memcpy(data + leaf_header_size + sizeof(int) + position * (len1 + len2 + sizeof(int)),value1,len1); memcpy(data + leaf_header_size + sizeof(int) + len1 + position * (len1 + len2 + sizeof(int)),value2,len2); } void get_record(int fileDesc,char* data,int position,void* value1,void* value2){ /*retrieves the record from position*/ int len1 = Open_files[fileDesc]->f_len1; int len2 = Open_files[fileDesc]->f_len2; memcpy(value1,data + leaf_header_size + sizeof(int) + position * (len1 + len2 + sizeof(int)),len1); memcpy(value2,data + leaf_header_size + sizeof(int) + len1 + position * (len1 + len2 + sizeof(int)),len2); } int leaf_insert(int fileDesc,void* value1,void* value2,PATH* path,int *new_block_no,void *index_value){ int all_entries,err,block_no,root_block_no,split,old_neighbour; char *old_data,*new_data,*root_data; void *carried_value,*carried_value2; int len1 = Open_files[fileDesc]->f_len1; int len2 = Open_files[fileDesc]->f_len2; int max_records = Open_files[fileDesc]->max_records; BF_Block *block,*newblock,*rootblock; BF_Block_Init(&block); BF_Block_Init(&newblock); carried_value = malloc(len1);//is the value carried until we find a greater value carried_value2 = malloc(len2);//is the value carried until we find a greater value split = 0; if(PATH_NotEmpty(path)==0){//tree is empty -> creating root BF_Block_Init(&rootblock); err = BlockCreate_Leaf(fileDesc,rootblock,&root_block_no);// creating leaf root if(err == -1) return -1; root_data = BF_Block_GetData(rootblock);//retrieve data of root block set_record(fileDesc,root_data,0,value1,value2);//first entry in root set_overflow_index(fileDesc,root_data,0,-1);//no overflow block yet update_neighbour(root_data,-1);//root has no neighbour get_update_entries(root_data,1); //accounting for first entry BF_Block_SetDirty(rootblock);//root block has been modified AM_errno = BF_UnpinBlock(rootblock); if(AM_errno != BF_OK) return -1; Open_files[fileDesc]->root_block = root_block_no;//updating metadata with first root number BF_Block_Destroy(&rootblock); } else{//path has at least one block number block_no = PATH_Pop(path); //retrieving leaf block number from path AM_errno = BF_GetBlock(Open_files[fileDesc]->fileDesc,block_no,block);//retrieving leaf block if(AM_errno != BF_OK) return -1; old_data = BF_Block_GetData(block);//data of the block retrieved all_entries = get_update_entries(old_data,0);//the number of all the entries in the block before any modification if(check_duplicate(fileDesc,old_data,value1 ,value2) == 0){//if value1 is not inserted already as duplicate continue insert memcpy(carried_value,value1,len1);//value1 and value2 are carried values , carried values are inserted when memcpy(carried_value2,value2,len2);//a key greater than carried_value is found if(all_entries == max_records){//block is full , split err = BlockCreate_Leaf(fileDesc,newblock,new_block_no);// creating block,this will be the right child of the if(err == -1) //parent index block return -1; new_data = BF_Block_GetData(newblock);//data of the block created from the split old_neighbour = get_neighbour(old_data); update_neighbour(new_data,old_neighbour);//new block's right neighbour was the neighbour of the original block update_neighbour(old_data,*new_block_no);//the new block is the new right neighbour of the original block split = 1;//split == true Leaf_split_push(fileDesc,old_data,new_data,carried_value,carried_value2,index_value);//split records and insert } else Leaf_push(fileDesc,old_data,carried_value,carried_value2);//insert if(split == 1){//if there was a split ,a newblock has been allocated and modified BF_Block_SetDirty(newblock); AM_errno = BF_UnpinBlock(newblock); if(AM_errno != BF_OK) return -1; } } BF_Block_SetDirty(block);//original block might have been modified(in check duplicate ,in overflow push if ov.index was -1) AM_errno = BF_UnpinBlock(block); if(AM_errno != BF_OK) return -1; } BF_Block_Destroy(&block); BF_Block_Destroy(&newblock); free(carried_value); free(carried_value2); return split; } int Leaf_push(int fileDesc,char* data,void* carried_value,void *carried_value2){ /*Used only if the block in not full and record is not duplicate.Inserts carried record in the right position of a block,and afterwards pushes the remaining records to the right ,if needed. returns -1 for error , else 0 for success */ int overflow,carried_overflow,t,all_entries,i,res; int len1 = Open_files[fileDesc]->f_len1; int len2 = Open_files[fileDesc]->f_len2; void *key,*temp,*value2,*temp2; all_entries = get_update_entries(data,0); key = malloc(len1); temp = malloc(len1); value2 = malloc(len2); temp2 = malloc(len2); carried_overflow = -1;//new entry has no overflow block for (i = 0; i<= all_entries - 1;i++){ //for all entries in the block,retrieving entry and storing the lesser of the two get_record(fileDesc,data,i,key,value2);//retrieve record from position(offset) i overflow = get_overflow_index(fileDesc,data,i);//retrieve respective overflow index res = compare_key(carried_value,key,Open_files[fileDesc]->f_type1); if(res < 0){ //key is greater than carried_value ,always swapping for lesser key (at i position)to keep the records sorted memcpy(temp,key,len1); memcpy(key,carried_value,len1); memcpy(carried_value,temp,len1); memcpy(temp2,value2,len2); //swapping secondary values of the records memcpy(value2,carried_value2,len2); memcpy(carried_value2,temp2,len2); t = overflow; //swapping overflow index values overflow = carried_overflow; carried_overflow = t; } set_record(fileDesc,data,i,key,value2); set_overflow_index(fileDesc,data,i,overflow); } set_record(fileDesc,data,i,carried_value,carried_value2);//max key in carried value , inserted last at the end of the block set_overflow_index(fileDesc,data,i,carried_overflow); get_update_entries(data,1); //accounting for the entry that was inserted free(key); free(temp); free(value2); free(temp2); return AME_OK; } int Leaf_split_push(int fileDesc,char* old_data,char* new_data,void* carried_value,void *carried_value2,void *index_value){ /*Used only if the original block is full and if the record is not duplicate. Inserts carried record in the right position of the apropriate block,and afterwards pushes the remaining records to the right ,meanwhile spliting all records of the original block. Returns -1 for error , else 0 for success.Stores a value in index_value thats going to be inserted in the parent index block */ int t,all_entries,i,k,old_entries_incr,new_entries_incr,overflow,carried_overflow,res; int len1 = Open_files[fileDesc]->f_len1; int len2 = Open_files[fileDesc]->f_len2; int max_records = Open_files[fileDesc]->max_records; float b = max_records; void *key,*temp,*value2,*temp2; all_entries = get_update_entries(old_data,0); key = malloc(len1); temp = malloc(len1); value2 = malloc(len2); temp2 = malloc(len2); carried_overflow = -1;//new entry has no overflow block k = 0; old_entries_incr = 0;//this keeps count of the entries removed from original block new_entries_incr = 0;//this keeps count of the entries added to new block added to the new block for (i = 0; i<= all_entries - 1;i++){ //for all entries in the block,the lesser between carried and key is stored get_record(fileDesc,old_data,i,key,value2); overflow = get_overflow_index(fileDesc,old_data,i); res = compare_key(carried_value,key,Open_files[fileDesc]->f_type1); if(res < 0){ //key > carried_value swap carried value and key memcpy(temp,key,len1); memcpy(key,carried_value,len1); memcpy(carried_value,temp,len1); memcpy(temp2,value2,len2); //swapping secondary values of the records memcpy(value2,carried_value2,len2); memcpy(carried_value2,temp2,len2); t = overflow; //swapping overflow index values overflow = carried_overflow; carried_overflow = t; } //Deciding which block to store the entry(below),while also searching for middle key to push up to parent block if(i == ceil(b/2.0)){//middle key pushed up within index_value memcpy(index_value,key,len1);//found index value(will be pushed up to parent block) old_entries_incr -=1; new_entries_incr +=1;//middle record is first entry to be removed from old block and added to new one set_record(fileDesc,new_data,k,key,value2); set_overflow_index(fileDesc,new_data,k,overflow); k++;//offset for entries in new block increased for the next entry } else if(i < ceil(b/2.0)){//place key in original block at i position , as long as the block is not half full set_record(fileDesc,old_data,i,key,value2); set_overflow_index(fileDesc,old_data,i,overflow); } else if(i > ceil(b/2.0)){//place key in new block at k position ,after the original block is half full old_entries_incr -= 1;//one entry removed from old block new_entries_incr +=1; //new block gets one entry from old set_record(fileDesc,new_data,k,key,value2); set_overflow_index(fileDesc,new_data,k,overflow); k++; } }//the max element is inserted at the end of the new block (after entries - 1 steps as the extra step from inserting a value) set_record(fileDesc,new_data,k,carried_value,carried_value2); set_overflow_index(fileDesc,new_data,k,carried_overflow); new_entries_incr += 1; // +1 entry for the last element get_update_entries(new_data,new_entries_incr);//updating number of entries get_update_entries(old_data,old_entries_incr);//for both blocks free(key); free(temp); free(value2); free(temp2); return AME_OK; } int check_duplicate(int fileDesc,char *data,void *value1 ,void *value2){ /*scans data buffer for a key that has value equal to value1 if it finds one ,the record is pushed in an overflow block*/ int i ,entries_no; void *key,*key_value2; key = malloc(Open_files[fileDesc]->f_len1); key_value2 = malloc(Open_files[fileDesc]->f_len2); entries_no = get_update_entries(data,0);//retrieving number of entries of the block for(i = 0; i <= entries_no - 1 ; i++){//scan all entries for a duplicate key get_record(fileDesc,data,i,key,key_value2);//get next record on data if(compare_key(value1,key,Open_files[fileDesc]->f_type1) == 0){//there is a duplicate key overflow_push(fileDesc,data,i,value1,value2);//insert value at the corresponding overlflow block free(key); free(key_value2); return 1;//1 indicates duplicate has been found and record has been inserted } } free(key); free(key_value2); return 0;//duplicate has not been found } void *find_next_leaf_entry(int scanDesc){ /*continuously scans blocks until there is a record match or until there are no more data blocks.If match is found sets info needed for next scan and returns the requested value,else returns NULL*/ int fileDesc = Open_scans[scanDesc]->fileDesc; int entries_no,i,flag,res; int op = Open_scans[scanDesc]->op; int len1 = Open_files[fileDesc]->f_len1; int len2 = Open_files[fileDesc]->f_len2; int next_block = Open_scans[scanDesc]->next_block; int next_record = Open_scans[scanDesc]->next_record; BF_Block *block; char* block_data; void *value,*v1,*v2; BF_Block_Init(&block); v1 = malloc(len1); v2 = malloc(len2); value = Open_scans[scanDesc]->value; flag = 0; while (next_block != -1){//block to be opened exists AM_errno = BF_GetBlock(Open_files[fileDesc]->fileDesc,next_block,block);//get the block if(AM_errno != BF_OK) return NULL; block_data = BF_Block_GetData(block); entries_no = get_update_entries(block_data,0);//get the number of total entries for(i = next_record ; i<= entries_no -1;i++){//scan through all of its entries or until match is found get_record(fileDesc,block_data,i,v1,v2);//retrieving record to check if it matches the op's requirements res = compare_key(v1,value,Open_files[fileDesc]->f_type1);//compare value with the key of the entry if(res == 0 && (op == 1 || op == 5 || op == 6)){// EQUAL , res fullfills requirements of the operator flag = 1;//return the corresponding value 2 break; } else if( res < 0 && (op == 2 || op == 3 || op == 5)){//LESS OR NOT EQUAL flag = 1; break; } else if(res > 0 && (op == 2 || op == 4 || op == 6)){ // GREATER OR NOT EQUAL flag = 1; break; } }//requirements fullfilled or there are no more entries in block if(i >= entries_no - 1){ //if all records are scanned jump to neighbouring block's first record(i reached last entry) next_block = get_neighbour(block_data);//neighbouring block will be scanned next,if -1 there is no next block,scan ends Open_scans[scanDesc]->next_block = next_block; next_record = 0; //position of the first record in neighbour block Open_scans[scanDesc]->next_record = next_record; } else if(i <entries_no - 1){//there are more records to be scanned after i,in the same block(i didn't reach last entry) next_record = i + 1; //then go to next record Open_scans[scanDesc]->next_record = i + 1; } AM_errno = BF_UnpinBlock(block); if(AM_errno != BF_OK) return NULL; if(flag == 1){//if op match found return v2 and exit function Open_scans[scanDesc]->overflow_block=get_overflow_index(fileDesc,block_data,i);//next call on overflow block if exists BF_Block_Destroy(&block); free(v1); return v2; } } free(v1); free(v2); BF_Block_Destroy(&block); AM_errno = AME_EOF; return NULL; } //========================================INDEX BLOCK SPECIFIC FUNCTIONS========================================= void get_key(int fileDesc, char* data,int position ,void* key){ /*returns the key value stored at position*/ int len = Open_files[fileDesc]->f_len1; memcpy(key,data + index_header_size + sizeof(int) + (len + sizeof(int)) * position,len); } void get_right(int fileDesc,char* data,int position,int *right){ /*returns the value of the right index of the key located at position*/ int key_len = Open_files[fileDesc]->f_len1; memcpy(right,data + index_header_size + (key_len + sizeof(int)) * (position + 1),sizeof(int)); } void get_left(int fileDesc,char* data,int position,int *left){ /*returns the value of the left index of the key located at position*/ int key_len = Open_files[fileDesc]->f_len1; memcpy(left,data + index_header_size + (key_len + sizeof(int)) * position,sizeof(int)); } void set_key(int fileDesc,char* data,int position ,void* key){ /*sets the key value at position*/ int len = Open_files[fileDesc]->f_len1; memcpy(data + index_header_size + sizeof(int) + (len + sizeof(int)) * position,key,len); } void set_right(int fileDesc,char* data,int position,int right){ /*sets the value of te right index of the key located at position*/ int key_len = Open_files[fileDesc]->f_len1; memcpy(data + index_header_size + (key_len + sizeof(int)) * (position + 1),&right,sizeof(int)); } void set_left(int fileDesc,char* data,int position,int left){ /*sets the value of the left index of the key located at position*/ int key_len = Open_files[fileDesc]->f_len1; memcpy(data + index_header_size + (key_len + sizeof(int)) * position,&left,sizeof(int)); } int Index_push(int fileDesc,char* data,void* carried_value,int carried_right){ /*Used only if the block in not full.Inserts carried value and carried right index in the right position of a block,and afterwards pushes the remaining records to the right ,if needed. returns -1 for error , else 0 for success */ int right,t,all_entries,i; int len = Open_files[fileDesc]->f_len1; void *key,*temp; all_entries = get_update_entries(data,0); key = malloc(len); temp = malloc(len); for (i = 0; i<= all_entries - 1;i++){ //for all entries in the block,retrieving entry and storing the lesser of the two get_key(fileDesc,data,i,key); get_right(fileDesc,data,i,&right); if(compare_key(carried_value,key,Open_files[fileDesc]->f_type1)<0){ //key > carried_value swap carried and key memcpy(temp,key,len); memcpy(key,carried_value,len); memcpy(carried_value,temp,len); t = right; //swapping right index values ,left indeces never change right = carried_right; carried_right = t; } set_key(fileDesc,data,i,key); //place key at i position set_right(fileDesc,data,i,right); } set_key(fileDesc,data,i ,carried_value);//max key in carried value , inserted last at the end of the block set_right(fileDesc,data,i,carried_right); get_update_entries(data,1); //accounting for the entry that was inserted free(key); free(temp); return AME_OK; } int Index_split_push(int fileDesc,char* old_data,char* new_data,void* carried_value,int carried_right,void *index_value){ /*Used only if the original block is full.Inserts carried value and carried right index in the right position of the apropriate block,and afterwards pushes the remaining records to the right ,if needed.Mean while moves half of the original entries to the new block. Returns -1 for error,else 0 for success.Stores a value in index_value that's going to be inserted on the parent index block */ int right,t,all_entries,i,k,old_entries_incr,new_entries_incr; int len = Open_files[fileDesc]->f_len1; int max_records = Open_files[fileDesc]->max_records; float b = max_records;//number of pointers per index block equals the number of max records per leaf block void *key,*temp; all_entries = get_update_entries(old_data,0); key = malloc(len); temp = malloc(len); k = 0; old_entries_incr = 0; new_entries_incr = 0; for (i = 0; i<= all_entries - 1;i++){ //for all entries in the block,the lesser between carried and key is stored get_key(fileDesc, old_data,i ,key); get_right(fileDesc,old_data,i,&right); if(compare_key(carried_value,key,Open_files[fileDesc]->f_type1)<0){ //key > carried_value swap values memcpy(temp,key,len); memcpy(key,carried_value,len); memcpy(carried_value,temp,len); t = right; //swapping right index values too right = carried_right; carried_right = t; } if(i == ceil(b/2.0) - 1){//middle key deleted and pushed up within index_value memcpy(index_value,key,len); old_entries_incr -=1; //middle key removed set_left(fileDesc,new_data,0,right);//first index of new block==right index of middle key } else if(i < ceil(b/2.0) - 1){//place key in original block at i position , as long as the block is not half full set_key(fileDesc,old_data,i ,key); set_right(fileDesc,old_data,i,right); } else if(i > ceil(b/2.0) - 1){//place key in new block at k position ,after the original block is half full old_entries_incr -= 1;//one entry removed from old block new_entries_incr +=1; //new block gets one entry from old set_key(fileDesc,new_data,k ,key); set_right(fileDesc,new_data,k,right); k++; } }//the max element is inserted at the end of the new block (after entries - 1 steps as the extra step from inserting a value) set_key(fileDesc,new_data,k ,carried_value); set_right(fileDesc,new_data,k,carried_right); new_entries_incr += 1; // +1 entry for the last element get_update_entries(new_data,new_entries_incr);//updating number of entries get_update_entries(old_data,old_entries_incr);//for both blocks free(key); free(temp); return AME_OK; } int Index_make_root(int fileDesc,void* index_value,int new_block_no){ /*creates an index block and makes it the root of the tree.Returns -1 for error, 0 for success*/ char* root_data; BF_Block *root_block; int root_block_no,err; BF_Block_Init(&root_block); err = BlockCreate_Index(fileDesc,root_block,&root_block_no); if(err == -1) return -1; root_data = BF_Block_GetData(root_block); set_left(fileDesc,root_data,0,Open_files[fileDesc]->root_block);//left index of root block is the previous root set_key(fileDesc,root_data,0,index_value);//first key of the block set_right(fileDesc,root_data,0,new_block_no);//right index is number of block created from last split get_update_entries(root_data,1);//increment number of entries by one , first entry Open_files[fileDesc]->root_block = root_block_no;//this is the new root block of the file BF_Block_SetDirty(root_block);//block modified AM_errno = BF_UnpinBlock(root_block); if(AM_errno != BF_OK) return -1; BF_Block_Destroy(&root_block); return AME_OK; } int index_insert(int fileDesc,void *index_value,PATH *path,int new_block_no){ /*Called only after a leaf block has been split. Inserts index value and new block no in the appropriate block.If a block is full ,a new one is made and the records are split between the two ,while the middle value becomes the index value for the higher level.If there is no index block in the tree or the index root has been split up it makes a new root.Returns -1 for error, 0 for success.*/ int all_entries,err,block_no,split,carried_right; char *old_data,*new_data; void *carried_value; int len = Open_files[fileDesc]->f_len1; int max_records = Open_files[fileDesc]->max_records; BF_Block *block,*newblock; BF_Block_Init(&block); BF_Block_Init(&newblock); carried_value = malloc(len);//is the value carried until we find a greater value split = 1;//leaf block was split //if a leaf root has been split ,while is not entered ,because there was no other element in path other than the poped leaf number while(PATH_NotEmpty(path) && split == 1){//if there is an index block in path and there has been a split in the level below block_no = PATH_Pop(path); //insert index_value and new_block_no in the new level memcpy(carried_value,index_value,len);//value to be inserted is carried carried_right = new_block_no; //right index of value to be inserted split = 0; //indicates whether a split has happened on a block AM_errno = BF_GetBlock(Open_files[fileDesc]->fileDesc,block_no,block);//this is the block before the split if(AM_errno != BF_OK) return -1; old_data = BF_Block_GetData(block);//data of the block before the split all_entries = get_update_entries(old_data,0);//the number of all the entries in the block before any modification if(all_entries == max_records - 1){//limit of stored keys reached(#pointers == max_records) err = BlockCreate_Index(fileDesc,newblock,&new_block_no);// creating new block,new_block_no will be pushed up for index if(err == -1) //in parent block return -1; new_data = BF_Block_GetData(newblock);//data of the block created from the split split = 1;//split == true Index_split_push(fileDesc,old_data,new_data,carried_value,carried_right,index_value);//inserting value,split == true } else Index_push(fileDesc,old_data,carried_value,carried_right);//inserting value in original block,split == false if(split == 1){//if there was a split newblock has been allocated and modified BF_Block_SetDirty(newblock); AM_errno = BF_UnpinBlock(newblock); if(AM_errno != BF_OK) return -1; } BF_Block_SetDirty(block);//original block has been modified AM_errno = BF_UnpinBlock(block); if(AM_errno != BF_OK) return -1; } if(split == 1){//either an index root(during the while loop) or a leaf root(meaning path was empty before the loop) has been split up err = Index_make_root(fileDesc,index_value,new_block_no); //make an index block that is root if(err == -1) return -1; } BF_Block_Destroy(&block); BF_Block_Destroy(&newblock); free(carried_value); return AME_OK; } //=======================================================OVERFLOW SPECIFIC FUNCTIONS============================================ void set_overflow_record(int fileDesc,char* data,int position,void* value1,void* value2){ /*stores the record at position*/ int len1 = Open_files[fileDesc]->f_len1; int len2 = Open_files[fileDesc]->f_len2; memcpy(data + overflow_header_size + position * (len1 + len2),value1,len1); memcpy(data + overflow_header_size + len1 + position * (len1 + len2),value2,len2); } void get_overflow_record(int fileDesc,char* data,int position,void* value1,void* value2){ /*retrieves the record from position*/ int len1 = Open_files[fileDesc]->f_len1; int len2 = Open_files[fileDesc]->f_len2; memcpy(value1,data + overflow_header_size + position * (len1 + len2),len1); memcpy(value2,data + overflow_header_size + len1 + position * (len1 + len2),len2); } int overflow_push(int fileDesc,char* leaf_data,int position,void* value1,void* value2){ /* inserts a duplicate record at the corresponding overflow block.If there isn't an overflow block (-1 overflow index) it gets created.Returns -1 for error , 0 for success*/ BF_Block *block; char* block_data; int entries,err,block_no; BF_Block_Init(&block); //initializing struct for block block_no = get_overflow_index(fileDesc,leaf_data,position); //retrieving overflow index from the buffer of the leaf block if(block_no == -1){ //if there is no overflow block pointed at err = BlockCreate_Overflow(fileDesc,block,&block_no); //create a new overflow block if(err == -1) return -1; set_overflow_index(fileDesc,leaf_data,position,block_no);//and set the index to point at this block //BF_Block_SetDirty(leaf_block);//leaf block's index to overflow block has been modified//ekswterika<========sthn insert leaf } else{ //else if there is an overflow block pointed at AM_errno = BF_GetBlock(Open_files[fileDesc]->fileDesc,block_no,block); //bring it to memory if(AM_errno != BF_OK) return -1; } block_data = BF_Block_GetData(block); entries = get_update_entries(block_data,0); //get the number of entries set_overflow_record(fileDesc,block_data,entries,value1,value2);//insert duplicate record(e.g. 0 entries -> 0 offset) get_update_entries(block_data,1); //update the number of entries BF_Block_SetDirty(block); //block has been modified AM_errno = BF_UnpinBlock(block); //done working on this block if(AM_errno != BF_OK) return -1; BF_Block_Destroy(&block); //destroy the struct return AME_OK; } void *find_next_overflow_entry(int scanDesc){ /*retrieves the second value of the next duplicate record stored in the overflow block , modifies overflow block and next overflow record accordingly(for the next scan) and returns the value*/ int next_overflow_record = Open_scans[scanDesc]->next_overflow_record; int entries_no; int fileDesc = Open_scans[scanDesc]->fileDesc; int len1 = Open_files[fileDesc]->f_len1; int len2 = Open_files[fileDesc]->f_len2; char* data; void *value1,*value2; BF_Block *block; BF_Block_Init(&block); value1 = malloc(len1); value2 = malloc(len2);//allocating space for storing the requested value AM_errno = BF_GetBlock(Open_files[fileDesc]->fileDesc,Open_scans[scanDesc]->overflow_block,block);//retrieve the overflow block if(AM_errno != BF_OK) return NULL; data = BF_Block_GetData(block); get_overflow_record(fileDesc,data,Open_scans[scanDesc]->next_overflow_record,value1,value2);//retrieve current records value2 entries_no = get_update_entries(data,0);//retrieve the number of total entries on this block if(next_overflow_record == entries_no - 1){//reached last entry for this block Open_scans[scanDesc]->overflow_block = -1;// next scan continues searching on leaf blocks Open_scans[scanDesc]->next_overflow_record = 0;//initiallizing record number for the next time an overflow block is found } else//haven't reached last entry yet (Open_scans[scanDesc]->next_overflow_record)++;//move to the next entry of this block(info needed for the next scan) AM_errno = BF_UnpinBlock(block);//block no longer needed in memory if(AM_errno != BF_OK) return NULL; free(value1); BF_Block_Destroy(&block); return value2;//returned retrieved value2 }
C
//旋转数组最小数字 #include <stdio.h> #include <malloc.h> int getMin(int *arr,int num) { int begin=0; int end=num-1; int mid=0; while(arr[begin]>=arr[end]) { mid=(begin+end)/2; if(arr[mid]>=arr[begin]) { begin=mid; } else if(arr[mid]<=arr[end]) { end=mid; } if(end-begin==1) { mid=end; return arr[mid]; } } } int main() { int num; printf("input size:"); scanf("%d",&num); int *arr=(int *)malloc(sizeof(int)*num); int i=0; printf("init arr:"); for(;i<num;i++) { scanf("%d",&arr[i]); } int ret=getMin(arr,num); printf("%d\n",ret); return 0; }
C
/*Calculating the square root of a number*/ //Function to calculte the absolute value of a number #include<stdio.h> float absoluteValue (float x) //function definition { if (x < 0) x = -x; return (x); } //Function to compute the square root of a number float squareRoot (double x) { const double epsilon = .000001; double guess = 1.0; float absoluteValue (float x); if (x<0) { printf("Negative argument to square root .\n"); return -1.0; } while( absoluteValue (guess * guess - x) >= epsilon) guess = (x /guess + guess) / 2.0; return guess; } int main (void ) { /* code */ printf("squareRoot (2.0) = %f\n",squareRoot (2.0)); printf("squareRoot (144.0) = %f\n",squareRoot (144.0)); printf("squareRoot (-2) = %f\n",squareRoot (-2)); return 0; }
C
/*-------------------------------------------------------------------------* * File: Potentiometer.c *-------------------------------------------------------------------------* * Description: * Potentiometer driver that uses the RX62N's S12AD A/D input. *-------------------------------------------------------------------------*/ /*-------------------------------------------------------------------------* * Includes: *-------------------------------------------------------------------------*/ #include <system/platform.h> #include <drv/ADC.h> #include "Potentiometer.h" /*-------------------------------------------------------------------------* * Constants: *-------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------* * Routine: Potentiometer_Init *---------------------------------------------------------------------------* * Description: * Initialize the potentiometer driver. * Inputs: * void * Outputs: * void *---------------------------------------------------------------------------*/ void Potentiometer_Init(void) { ADC_Start(); ADC_EnableChannel(POTENTIOMETER_CHANNEL); ADC_EnableChannel(MICROPHONE_CHANNEL); } /*---------------------------------------------------------------------------* * Routine: Potentiometer_Get *---------------------------------------------------------------------------* * Description: * Read the potentiometer and get the percent it is turned. * Inputs: * void * Outputs: * uint32_t -- value of 0 to 1000 for 0% to 100% *---------------------------------------------------------------------------*/ uint32_t Potentiometer_Get(void) { int32_t adc; // ADC sensor reading adc = ADC_GetReading(POTENTIOMETER_CHANNEL); // Get the temperature and show it on the LCD adc *= 1000; // scale it from 0 to 1000 adc /= (1 << 10); // 10-bit reading return adc; } uint32_t Microphone_Get(void) { int32_t adc; // ADC sensor reading adc = ADC_GetReading(MICROPHONE_CHANNEL); // Get the temperature and show it on the LCD adc *= 1000; // scale it from 0 to 1000 adc /= (1 << 10); // 10-bit reading return adc; } /*-------------------------------------------------------------------------* * End of File: Potentiometer.c *-------------------------------------------------------------------------*/
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 */ /* Variables and functions */ float dcn_bw_log(float a, float b) { int * const exp_ptr = (int *)(&a); int x = *exp_ptr; const int log_2 = ((x >> 23) & 255) - 128; x &= ~(255 << 23); x += 127 << 23; *exp_ptr = x; a = ((-1.0f / 3) * a + 2) * a - 2.0f / 3; if (b > 2.00001 || b < 1.99999) return (a + log_2) / dcn_bw_log(b, 2); else return (a + log_2); }
C
//2.0999֮Сˮɻ //ˮɻָһλλֵȷõڸ磻153153 ? 153һˮɻ // // //УˮɻNarcissistic numberҲΪķ˹׳ķ˹Armstrong numberָһNλ֮Nη͵ڸ //153370371407λˮɻ֮͵ڸ //153 = 1^3 + 5^3 + 3^3 //370 = 3^3 + 7^3 + 0^3 //371 = 3^3 + 7^3 + 1^3 //407 = 4^3 + 0^3 + 7^3 // #define _CRT_SECURE_NO_WARNINGS 1 #include <stdio.h> #include <stdlib.h> int main() { int num, a, b, c; printf("0~999ˮɻΪ"); for (num =100 ; num <= 999; num++) { a= num / 100; //λ b = (num -a* 100) / 10; //ʮλ c = num % 10; //λ if (num ==a*a*a+b*b*b+c*c*c) ///жnumǷλ { printf("%d ", num); } } printf("\n"); system("pause"); return 0; }
C
#include <stdio.h> int main() { // crash is possible here // char food[5]; // printf("Enter your favorite food: "); // scanf("%s", food); // printf("Your favorite food: %s\n", food); char food[5]; printf("Enter your favorite food: "); fgets(food, sizeof(food), stdin); printf("Your favorite food is %s\n", food); return 0; }
C
#include <stdio.h> /*(segundos) -> h:m:s 556 -> 0:9:16 1 -> 0:0:1 140153 -> 38:55:53 */ int myminuts(int sec) {int tmp = sec / 60; if((sec/60) > 60) { return tmp % 60; } return tmp; } int main(void) {int seconds; scanf("%d", &seconds); printf("%d:%d:%d\n",((seconds / 60)/ 60) ,(myminuts(seconds)),(seconds % 60)); int test = seconds / 60; int test2 = test % 60; printf("%d\n",test2); return 0; }
C
/* Run on OS X 10.8.4 */ /* $ gcc -O3 -o best_script best_script.c */ /* $ time ./best_script */ /* real 0m58.125 */ /* user 0m58.080s */ /* sys 0m0.042s */ #include <stdio.h> #include <stdlib.h> #include <string.h> struct list { char val[7]; int freq; struct list *next; }; struct list *append_list(struct list *, char *); struct list *search_list(struct list *, char *); int main(void) { struct list *l = NULL, *element, *old; char str[7]; FILE *numbers, *run_result; if ((numbers = fopen("numbers.txt", "r")) == NULL) return 1; if ((run_result = fopen("run_result.txt", "w")) == NULL) return 1; while (fscanf(numbers, "%s", str) == 1) if ((element = search_list(l, str)) == NULL) l = append_list(l, str); else (element->freq)++; while (l != NULL) { if (l->freq > 1) fprintf(run_result, "\"%s\", %d\n", l->val, l->freq); old = l; l = l->next; free(old); } fclose(run_result); fclose(numbers); return 0; } struct list *append_list(struct list *l, char *val) { struct list *new = (struct list *) malloc(sizeof (struct list)); if (new == NULL) exit(1); strncpy(new->val, val, 7); new->freq = 1; new->next = l; return new; } struct list *search_list(struct list *l, char *val) { while (l != NULL && strncmp(l->val, val, 7)) l = l->next; return l; }
C
/* print-prime.c By David Broman. Last modified: 2015-09-15 This file is in the public domain. max under 2s: 23920000 */ #include <stdio.h> #include <stdlib.h> #define COLUMNS 6 int check = 0; char * arr; void print_number(int p) { printf("%10d +", p); check++; if(check >= COLUMNS) { printf("\n"); check = 0; } } char * sieve(int n) { char * arr = (char*) malloc((n - 1) * sizeof(char)); for(int i = 2; i < n; i++) { arr[i] = 1; } for(int i = 2; i * i <= n; i++){ if(arr[i]) { for(int j = i * i; j < n; j = j + i) { arr[j] = 0; } } } return arr; } void print_mean(int N) { char * arr = sieve(N); int c = 0; int sum = 0; for(int i = 2; i < N; i++) { if(arr[i]){ c++; sum += i; } } double mean = ((double) sum / c); printf("Mean: %.6f", mean); free(arr); } void print_sieves(int n){ char * arr = sieve(n); int c = 0; for(int i = 0; i < n; i++) { if(arr[i]) { c++; print_number(i); } } printf("\ncount = %d\n", c); free(arr); } // 'argc' contains the number of program arguments, and // 'argv' is an array of char pointers, where each // char pointer points to a null-terminated string. int main(int argc, char *argv[]){ if(argc == 2) { print_sieves(atoi(argv[1])); print_mean(atoi(argv[1])); } else printf("Please state an interger number.\n"); return 0; }
C
/* * server FTP program * * NOTE: Starting homework #2, add more comments here describing the overall function * performed by server ftp program * This includes, the list of ftp commands processed by server ftp. * */ #include <sys/types.h> #include <netinet/in.h> #include <sys/socket.h> #include <netdb.h> #include <string.h> #define SERVER_FTP_PORT 9301 /* Error and OK codes */ #define OK 0 #define ER_INVALID_HOST_NAME -1 #define ER_CREATE_SOCKET_FAILED -2 #define ER_BIND_FAILED -3 #define ER_CONNECT_FAILED -4 #define ER_SEND_FAILED -5 #define ER_RECEIVE_FAILED -6 #define ER_ACCEPT_FAILED -7 /* Function prototypes */ int svcInitServer(int *s); int sendMessage (int s, char *msg, int msgSize); int receiveMessage(int s, char *buffer, int bufferSize, int *msgSize); /* List of all global variables */ char userCmd[1024]; /* user typed ftp command line received from client */ char cmd[1024]; /* ftp command (without argument) extracted from userCmd */ char argument[1024]; /* argument (without ftp command) extracted from userCmd */ char replyMsg[1024]; /* buffer to send reply message to client */ /* * main * * Function to listen for connection request from client * Receive ftp command one at a time from client * Process received command * Send a reply message to the client after processing the command with staus of * performing (completing) the command * On receiving QUIT ftp command, send reply to client and then close all sockets * * Parameters * argc - Count of number of arguments passed to main (input) * argv - Array of pointer to input parameters to main (input) * It is not required to pass any parameter to main * Can use it if needed. * * Return status * 0 - Successful execution until QUIT command from client * ER_ACCEPT_FAILED - Accepting client connection request failed * N - Failed stauts, value of N depends on the command processed */ int main( int argc, char *argv[] ) { /* List of local varibale */ int msgSize; /* Size of msg received in octets (bytes) */ int listenSocket; /* listening server ftp socket for client connect request */ int ccSocket; /* Control connection socket - to be used in all client communication */ int status; char* userList[7] = {"Jim", "Joe", "Mary", "John", "Tom", "Tim"}; char* passList[7] = {"1234", "abcd", "23mn", "4de2", "4rp3", "0987"}; int userMatchIndex = -1; /* * NOTE: without \n at the end of format string in printf, * UNIX will buffer (not flush) * output to display and you will not see it on monitor. */ printf("Started execution of server ftp\n"); /*initialize server ftp*/ printf("Initialize ftp server\n"); /* changed text */ status=svcInitServer(&listenSocket); if(status != 0) { printf("Exiting server ftp due to svcInitServer returned error\n"); exit(status); } printf("ftp server is waiting to accept connection\n"); /* wait until connection request comes from client ftp */ ccSocket = accept(listenSocket, NULL, NULL); printf("Came out of accept() function \n"); if(ccSocket < 0) { perror("cannot accept connection:"); printf("Server ftp is terminating after closing listen socket.\n"); close(listenSocket); /* close listen socket */ return (ER_ACCEPT_FAILED); // error exist } printf("Connected to client, calling receiveMsg to get ftp cmd from client \n"); /* Receive and process ftp commands from client until quit command. * On receiving quit command, send reply to client and * then close the control connection socket "ccSocket". */ do { /* Receive client ftp commands until */ status=receiveMessage(ccSocket, userCmd, sizeof(userCmd), &msgSize); if(status < 0) { printf("Receive message failed. Closing control connection \n"); printf("Server ftp is terminating.\n"); break; } char tempCmd[1024]; strcpy(tempCmd, userCmd); char* cmdpointer = strtok(tempCmd," "); char* argpointer = strtok(tempCmd,NULL); strcpy(cmd, cmdpointer); strcpy(argument, argpointer); /* * ftp server sends only one reply message to the client for * each command received in this implementation. */ if(strcmp(cmd,"user") == 0) { int userMatchedFlag = 0; for(int i = 0; i < 7; i++) { if(strcmp(argument, userList[i]) == 0) { userMatchIndex = i; userMatchedFlag = 1; break; } } if(userMatchedFlag == 1) { strcpy(replyMsg, "331 User name okay, need password."); } else { strcpy(replyMsg, "530 Not logged in. \n"); } } if(strcmp(cmd,"pass") == 0) { if(userMatchIndex == -1) { strcpy(replyMsg, "530 Not logged in. \n"); break; } if(strcmp(passList[userMatchIndex], argument) == 0) { strcpy(replyMsg, "User logged in, proceed."); } } if(strcmp(cmd,"mkdir") == 0) { if(userMatchIndex == -1) { strcpy(replyMsg, "530 Not logged in. \n"); break; } status = System(userCmd); if(status == 0) { strcpy(replyMsg, "200 command ok \n"); } else { strcpy(replyMsg, "500 command failed \n"); } } if(strcmp(cmd,"rmdir") == 0) { if(userMatchIndex == -1) { strcpy(replyMsg, "530 Not logged in. \n"); break; } status = System(userCmd); if(status == 0) { strcpy(replyMsg, "200 command ok \n"); } else { strcpy(replyMsg, "500 command failed \n"); } } if(strcmp(cmd, "cd") == 0) { if(userMatchIndex == -1) { strcpy(replyMsg, "530 Not logged in. \n"); break; } status = chdir(argument); if(status == 0) { strcpy(replyMsg, "200 command ok \n"); } else { strcpy(replyMsg, "500 command failed \n"); } } if(strcmp(cmd, "rm") == 0) { if(userMatchIndex == -1) { strcpy(replyMsg, "530 Not logged in. \n"); break; } status = system(userCmd); if(status == 0) { strcpy(replyMsg, "200 command ok \n"); } else { strcpy(replyMsg, "500 command failed \n"); } } if(strcmp(cmd, "pwd") == 0) { if(userMatchIndex == -1){ strcpy(replyMsg, "530 Not logged in. \n"); break; } status = system("pwd > output"); FILE* fptr = fopen("output", "r"); if(fptr != NULL){ char temp[1024]; int status = fread(temp, 1, 1024, fptr); if(status < 0){ strcpy(replyMsg, "450 Requested file action not taken. \n"); } else{ temp[status] = NULL; strcpy(replyMsg, "255 Requester file action okay, completed. \n"); strcat(replyMsg, temp); } } else{ strcpy(replyMsg, "450 Requested file action not taken. \n"); } } if(strcmp(cmd, "ls") == 0){ if(userMatchIndex == -1){ strcpy(replyMsg, "530 Not logged in. \n"); break; } status = system("ls > output"); FILE* fptr = fopen("output", "r"); if(fptr != NULL){ char temp[1024]; int status = fread(temp, 1, 1024, fptr); if(status < 0){ strcpy(replyMsg, "450 Requested file action not taken. \n"); } else{ temp[status] = NULL; strcpy(replyMsg, "255 Requested file action okay, completed. \n"); strcat(replyMsg, temp); } } else{ strcpy(replyMsg, "450 Requested file action not taken. \n"); } } if(strcmp(cmd, "help") == 0){ if(userMatchIndex == -1){ strcpy(replyMsg, "530 Not logged in. \n"); break; } strcpy(replyMsg, "214 Help message. \n"); strcpy(replyMsg, "Implemented ftp Commands: user, pass, mkdir, rmdir, cd, rm, pwd, ls, stat, help.\n"); } if(strcmp(cmd, "stat") == 0){ if(userMatchIndex == -1){ strcpy(replyMsg, "530 Not logged in. \n"); break; } strcpy(replyMsg, "200 command ok \n"); } status=sendMessage(ccSocket,replyMsg,strlen(replyMsg) + 1); /* Added 1 to include NULL character in */ /* the reply string strlen does not count NULL character */ if(status < 0) { break; /* exit while loop */ } } while(strcmp(cmd, "quit") != 0); printf("Closing control connection socket.\n"); close (ccSocket); /* Close client control connection socket */ printf("Closing listen socket.\n"); close(listenSocket); /*close listen socket */ printf("Existing from server ftp main \n"); return (status); } /* * svcInitServer * * Function to create a socket and to listen for connection request from client * using the created listen socket. * * Parameters * s - Socket to listen for connection request (output) * * Return status * OK - Successfully created listen socket and listening * ER_CREATE_SOCKET_FAILED - socket creation failed */ int svcInitServer ( int *s /*Listen socket number returned from this function */ ) { int sock; struct sockaddr_in svcAddr; int qlen; /*create a socket endpoint */ if( (sock=socket(AF_INET, SOCK_STREAM,0)) <0) { perror("cannot create socket"); return(ER_CREATE_SOCKET_FAILED); } /*initialize memory of svcAddr structure to zero. */ memset((char *)&svcAddr,0, sizeof(svcAddr)); /* initialize svcAddr to have server IP address and server listen port#. */ svcAddr.sin_family = AF_INET; svcAddr.sin_addr.s_addr=htonl(INADDR_ANY); /* server IP address */ svcAddr.sin_port=htons(SERVER_FTP_PORT); /* server listen port # */ /* bind (associate) the listen socket number with server IP and port#. * bind is a socket interface function */ if(bind(sock,(struct sockaddr *)&svcAddr,sizeof(svcAddr))<0) { perror("cannot bind"); close(sock); return(ER_BIND_FAILED); /* bind failed */ } /* * Set listen queue length to 1 outstanding connection request. * This allows 1 outstanding connect request from client to wait * while processing current connection request, which takes time. * It prevents connection request to fail and client to think server is down * when in fact server is running and busy processing connection request. */ qlen=1; /* * Listen for connection request to come from client ftp. * This is a non-blocking socket interface function call, * meaning, server ftp execution does not block by the 'listen' funcgtion call. * Call returns right away so that server can do whatever it wants. * The TCP transport layer will continuously listen for request and * accept it on behalf of server ftp when the connection requests comes. */ listen(sock,qlen); /* socket interface function call */ /* Store listen socket number to be returned in output parameter 's' */ *s=sock; return(OK); /*successful return */ } /* * sendMessage * * Function to send specified number of octet (bytes) to client ftp * * Parameters * s - Socket to be used to send msg to client (input) * msg - Pointer to character arrary containing msg to be sent (input) * msgSize - Number of bytes, including NULL, in the msg to be sent to client (input) * * Return status * OK - Msg successfully sent * ER_SEND_FAILED - Sending msg failed */ int sendMessage( int s, /* socket to be used to send msg to client */ char *msg, /* buffer having the message data */ int msgSize /* size of the message/data in bytes */ ) { int i; /* Print the message to be sent byte by byte as character */ for(i=0; i<msgSize; i++) { printf("%c",msg[i]); } printf("\n"); if((send(s, msg, msgSize, 0)) < 0) /* socket interface call to transmit */ { perror("unable to send "); return(ER_SEND_FAILED); } return(OK); /* successful send */ } /* * receiveMessage * * Function to receive message from client ftp * * Parameters * s - Socket to be used to receive msg from client (input) * buffer - Pointer to character arrary to store received msg (input/output) * bufferSize - Maximum size of the array, "buffer" in octent/byte (input) * This is the maximum number of bytes that will be stored in buffer * msgSize - Actual # of bytes received and stored in buffer in octet/byes (output) * * Return status * OK - Msg successfully received * R_RECEIVE_FAILED - Receiving msg failed */ int receiveMessage ( int s, /* socket */ char *buffer, /* buffer to store received msg */ int bufferSize, /* how large the buffer is in octet */ int *msgSize /* size of the received msg in octet */ ) { int i; *msgSize=recv(s,buffer,bufferSize,0); /* socket interface call to receive msg */ if(*msgSize<0) { perror("unable to receive"); return(ER_RECEIVE_FAILED); } /* Print the received msg byte by byte */ for(i=0;i<*msgSize;i++) { printf("%c", buffer[i]); } printf("\n"); return (OK); }
C
int main() { int n; scanf("%d",&n); getchar(); char a[50][10000]; int i; for(i=0;i<n;i++) { gets(a[i]); } for(i=0;i<n;i++) { int j; int len=strlen(a[i]); if(a[i][len-2]=='e' && a[i][len-1]=='r' || a[i][len-2]=='l' && a[i][len-1]=='y') { for(j=0;j<len-2;j++) putchar(a[i][j]); } if(a[i][len-3]=='i' && a[i][len-2]=='n' && a[i][len-1]=='g' ) { for(j=0;j<len-3;j++) putchar(a[i][j]); } printf("\n"); } return 0; }
C
#include <stdio.h> int main(){ int t,i; scanf("%d\n",&t); char curso[100]; for(i=0;i<t;i++){ scanf("%s",curso); } printf("Ciencia da Computacao\n"); return 0; }
C
// f(x) = x^2의 대한 정적분 구하는 프로그램 작성. #include <stdio.h> float integral(float a, float b, float n) { int i; float fx; float area; float dx=(b-a)/n; float integral = 0; float x=a; for(i=1; i<=n; i++) { fx = x*x; area = dx * fx; integral += area; x = x+dx; //printf("%.3f",dx); } return integral; } int main(void) { int a,b,n; float res; printf("시작 값 a를 적어 주세요 : "); scanf("%d", &a); printf("끝 값 b를 적어 주세요 : "); scanf("%d", &b); printf("적분 구간 [%d, %d]의 등분수 n을 적어 주세요 : ",a,b); scanf("%d", &n); res = integral(a,b,n); printf("f(x) = x^2의 적분 구간 [%d, %d]의 적분 근사치는 %.3f 입니다. \n",a,b,res); return 0; }
C
#include "types.h" #include "user.h" // int main(void){ int i=0; int j=0; if(shmget(12,(char *)0x7FFF0000,20480)<0){ printf(1,"error\n"); } char *test = (char*) 0x7FFF0000; char *temp = test; for(;i<4096; i++){ *test = 'A'; test++; } for(;i<8192; i++){ *test = 'B'; test++; } for(;i<20479;i++){ *test = 'C'; test++; } *test = '\0'; test = temp; if(fork()==0){ //child sleep(100); char *test1; if(shmget(12,(char *)0x20000000,0) < 0){ printf(1,"Child error"); exit(); } test1 =(char*) 0x20000000; for(;j<4096;j++){ if(*test1 != 'A'){ printf(1,"Fail on Page 1 %c\n", *test1); exit(); } test1++; } for(;j<8192;j++){ if(*test1 != 'B'){ printf(1,"Fail on page2\n"); exit(); } test1++; } for(;j<20479;j++){ if(*test1 != 'C'){ printf(1,"Fail on page 3 -> 5\n"); exit(); } test1++; } printf(1,"Child exiting with success!\n"); } wait(); /* int test1[15]; int * test = malloc(4096); printf(1,"test is %p, %x, %d\n",test,test,test); printf(1,"test1 is %p, %x, %d\n",test1,test1,test1);*/ exit(); }
C
/* 4.c */ #include <stdio.h> /* x $B$N(B y $B>h$r5a$a$k(B */ int pow(int x, int y) { int i,n=1; for(i=1;i<=y;i++) n *= x; return n; } /* $B#2>h$NOB!J7+$jJV$79=B$!K(B*/ int sum2_rep(int n) { int answer=0,i; for (i = 0; i <= n; i++) answer += i * i; return answer; } /* $B#2>h$NOB!J8x<0!K(B*/ int sum2_formula(int n) { return n * ( n + 1 ) * ( 2 * n + 1) / 6; } /* $B#3>h$NOB!J7+$jJV$79=B$!K(B*/ int sum3_rep(int n) { int answer=0,i; for (i = 0; i <= n; i++) answer += i * i * i; return answer; } /* $B#3>h$NOB!J8x<0!K(B*/ int sum3_formula(int n) { return (n * (n + 1) / 2) * (n * (n + 1) / 2) ; } /* r$B$N(Bi-1$B>h$NOB!J7+$jJV$79=B$!K(B*/ int sum4_rep(int n, int r) { int answer=0; int i,j; for (i = 1; i <= n ; i++) answer += pow(r,i-1); return answer; } /* r$B$N(Bi-1$B>h$NOB!J8x<0!K(B*/ int sum4_formula(int n, int r) { int answer=0; answer = ( 1 - pow(r ,n) ) / ( 1 - r ); return answer; } int main() { int n,r; printf("(a) n : "); scanf("%d",&n); printf("rep : %d, formula : %d\n",sum2_rep(n), sum2_formula(n)); printf("(b) n : "); scanf("%d",&n); printf("rep : %d, formula : %d\n",sum3_rep(n), sum3_formula(n)); printf("(c) n : "); scanf("%d",&n); printf("(c) r : "); scanf("%d",&r); if(r != 1) printf("rep : %d, formula : %d\n", sum4_rep(n,r), sum4_formula(n,r) ); else printf("Invalid number\n"); return 0; }
C
#ifndef CAMERAH_H #define CAMERAH_H #include <glm/vec3.hpp> #include <glm/mat4x4.hpp> struct Camera { glm::vec3 eye; glm::vec3 up; glm::vec3 target; glm::mat4 viewMatrix; glm::mat4 projMatrix; float zNear; float zFar; }; struct PerspectiveCamera : Camera { float fov; float aspect; }; struct OrthoCamera : Camera { float left; float right; float top; float bot; }; //void rotateCamera(OrthoCamera* cam, const glm::vec3& axis, float angle) //{ // cam->viewMatrix = rotate(cam->viewMatrix, angle, axis); // cam->up = cam->up * glm::rotate(glm::mat4(1.0f), angle, axis); // cam->target = rotate(cam->target, angle, axis); //} // //void translateCamera(OrthoCamera* cam, const glm::vec3& translationVector) //{ // cam->viewMatrix = translate(cam->viewMatrix, translationVector); // cam->eye = translate(cam->eye, translationVector); // cam->target = translate(cam->eye) //} // //void zoomCamera(OrthoCamera* cam, float value) //{ // float newWidth = (cam->right - cam->left) / value; // cam->left = //} void initOrtho(OrthoCamera* cam, const glm::vec3& eye, const glm::vec3& target, const glm::vec3& up, const glm::vec4& borders, float zNear, float zFar); void initPerspective(PerspectiveCamera* cam, const glm::vec3& eye, const glm::vec3& target, const glm::vec3& up, float fov, float aspect, float zNear, float zFar); void updateCameraViewMatrix(Camera* cam); void updateCameraProjectionMatrix(PerspectiveCamera* cam); void updateCameraProjectionMatrix(OrthoCamera* cam); static OrthoCamera gCam; static PerspectiveCamera gPerspectiveCam; #endif
C
#include <stdio.h> #include <unistd.h> //Used for UART #include <fcntl.h> //Used for UART #include <termios.h> //Used for UART static int init_serial(void) { int fd; fd = open("/dev/ttyS0", O_RDWR | O_NOCTTY | O_NDELAY); //Open in non blocking read/write mode if (fd == -1) { //ERROR - CAN'T OPEN SERIAL PORT printf("Error - Unable to open UART. Ensure it is not in use by another application\n"); } struct termios options; tcgetattr(fd, &options); options.c_cflag = B9600 | CS8 | CLOCAL | CREAD; //<Set baud rate options.c_iflag = IGNPAR; options.c_oflag = 0; options.c_lflag = 0; tcflush(fd, TCIFLUSH); tcsetattr(fd, TCSANOW, &options); return fd; } //use initserial() wherever you want in program
C
/* # Family Name: D'Aloia # Given Name: Philip # Section: E # Student Number: 213672431 # CSE Login: pdaloia */ #include <stdio.h> #include <string.h> #include <stdlib.h> #include <pthread.h> typedef struct{ char threadFileName[101]; int fileNumber; } fileInfoForThread; typedef struct { char word[101]; int freq; } wordStats; typedef struct { char word[101]; int distinct; int fileName; } fileStats; fileStats *fileArray; int word_information_compare(const void *firstInfo, const void *secondInfo){ int compute; int firstFreq = ((wordStats *)firstInfo)->freq; int secondFreq = ((wordStats *)secondInfo)->freq; char firstWord[101]; char secondWord[101]; strcpy(firstWord, ((wordStats *)firstInfo)->word); strcpy(secondWord, ((wordStats *)secondInfo)->word); compute = secondFreq - firstFreq; if(compute != 0) return compute; else { return strcmp(secondWord, firstWord); } } int file_information_compare(const void *firstInfo, const void *secondInfo){ int compute; int firstDistinct = ((fileStats *)firstInfo)->distinct; int secondDistinct = ((fileStats *)secondInfo)->distinct; compute = secondDistinct - firstDistinct; return compute; } void *find_file_stats(void *passedThreadFileInfo){ fileInfoForThread* threadFile = (fileInfoForThread*)passedThreadFileInfo; FILE *filePointer; wordStats wordArray[1000]; char currentWord[101]; char currentFileName[101]; strcpy(currentFileName, threadFile->threadFileName); //printf("%s\n", currentFileName); int i; int numberOfArrayElements = 0; //printf("%s\n", currentFileName); filePointer = fopen(currentFileName, "r"); fscanf(filePointer, "%s", currentWord); //printf("%s\n", currentWord); wordStats initialWord; initialWord.freq = 1; strcpy(initialWord.word, currentWord); //printf("%s", initialWord.word); wordArray[0] = initialWord; numberOfArrayElements = 1; fileStats fileToAnalyze; while(fscanf(filePointer, "%s", currentWord) != EOF){ int flag = 0; for(i = 0; i < sizeof(wordArray) / sizeof(wordStats); i++){ int wordFound = strcmp(wordArray[i].word, currentWord); if(wordFound == 0){ wordArray[i].freq++; flag = 1; break; } //end of if statement } //end of for loop if(flag == 0){ wordStats wordToAdd; wordToAdd.freq = 1; strcpy(wordToAdd.word, currentWord); wordArray[numberOfArrayElements] = wordToAdd; numberOfArrayElements++; } } //end of while loop qsort(wordArray, numberOfArrayElements, sizeof(wordStats), word_information_compare); char medianWord[101]; int medianFrequency; if(numberOfArrayElements % 2 == 0){ strcpy(medianWord, wordArray[(numberOfArrayElements / 2) - 1].word); medianFrequency = wordArray[(numberOfArrayElements / 2) - 1].freq; } else{ strcpy(medianWord, wordArray[(numberOfArrayElements / 2)].word); medianFrequency = wordArray[(numberOfArrayElements / 2)].freq; } strcpy(fileToAnalyze.word, medianWord); fileToAnalyze.distinct = numberOfArrayElements; fileToAnalyze.fileName = threadFile->fileNumber; memset(wordArray, 0, sizeof(wordArray)); fclose(filePointer); fileArray[threadFile->fileNumber - 1] = fileToAnalyze; //printf("%s %d %d\n",fileArray[threadFile->fileNumber].word, fileArray[threadFile->fileNumber].distinct, fileArray[threadFile->fileNumber].fileName); pthread_exit(0); } //end of find_median_word_and_freq int main (int argc, char *argv[]) { fileArray = malloc(argc * sizeof(fileStats)); pthread_t tid[argc - 1]; int i; fileInfoForThread arrayThreadArgs[argc - 1]; for(i = 0; i < argc - 1; i++){ arrayThreadArgs[i].fileNumber = i + 1; strcpy(arrayThreadArgs[i].threadFileName, argv[i + 1]); } for(i = 0; i < argc - 1; i++){ pthread_create(&tid[i], NULL, find_file_stats, &arrayThreadArgs[i]); } for(i = 0; i < argc - 1; i++){ pthread_join(tid[i], NULL); } /*printf("%s %d %d\n", fileArray[0].word, fileArray[0].fileName, fileArray[0].distinct); printf("%s %d %d\n", fileArray[1].word, fileArray[1].fileName, fileArray[1].distinct); printf("%s %d %d\n", fileArray[2].word, fileArray[2].fileName, fileArray[2].distinct); printf("%s %d %d\n", fileArray[3].word, fileArray[3].fileName, fileArray[3].distinct);*/ qsort(fileArray, argc - 1, sizeof(fileStats), file_information_compare); for(i = 0; i < argc - 1; i++){ printf("%s %d %s\n", argv[fileArray[i].fileName], fileArray[i].distinct, fileArray[i].word); } return 0; } //end of main
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* parser1.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: vneelix <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/10/27 15:37:01 by nsena #+# #+# */ /* Updated: 2020/10/27 21:41:03 by vneelix ### ########.fr */ /* */ /* ************************************************************************** */ #include "parser.h" char *find_and_parse_floor_texture(int *floor_texture, char *map_text) { while (1) { if (*map_text == '\0') return (NULL); if (is_line_floor_texture(map_text, '\n')) { map_text = ft_strchr(map_text, ' ') + 1; *floor_texture = ft_atoi(map_text); map_text = ft_strchr(map_text, '\n'); if (map_text != NULL) map_text++; break ; } map_text = ft_strchr(map_text, '\n'); if (map_text == NULL) return (NULL); map_text++; } return (map_text); } t_wall p_parse_wall_attribs(char *line) { t_wall wall; line = ft_strchr(line, ' ') + 1; wall.p1x = ft_atoi(line); line = ft_strchr(line, ' ') + 1; wall.p1y = ft_atoi(line); line = ft_strchr(line, ' ') + 1; wall.p2x = ft_atoi(line); line = ft_strchr(line, ' ') + 1; wall.p2y = ft_atoi(line); line = ft_strchr(line, ' ') + 1; wall.texture_index = ft_atoi(line); return (wall); } char *find_and_parse_walls(t_map *map, char *map_text) { int total_walls_red; total_walls_red = 0; while (1) { if (total_walls_red == map->wall_num) break ; if (*map_text == '\0') ft_assert(0, "Unexpected EOF."); if (is_line_wall(map_text, '\n')) { map->walls[total_walls_red] = p_parse_wall_attribs(map_text); total_walls_red++; } map_text = ft_strchr(map_text, '\n'); if (map_text == NULL) ft_assert(0, "Unexpected EOF."); map_text++; } return (map_text); } t_prsd_txr p_parse_texture_attribs(char *line) { t_prsd_txr texture; const char *line_end = ft_strchr(line, '\n'); int str_part_len; line = ft_strchr(line, ' ') + 1; ft_assert(ft_isdigit(*line), "Texture argument seq error."); texture.texture_index = ft_atoi(line); line = ft_strchr(line, ' ') + 1; str_part_len = (int)(line_end - line); texture.texture_name = malloc(sizeof(char) * (str_part_len + 1)); ft_strncpy(texture.texture_name, line, str_part_len); texture.texture_name[str_part_len] = '\0'; return (texture); } char *find_and_parse_textures(t_map *map, char *map_text) { int total_textures_red; int was_texture_block_found; total_textures_red = 0; was_texture_block_found = 0; while (1) { if (total_textures_red == map->texture_num) break ; ft_assert(*map_text != '\0', "Unexpected EOF."); if (is_line_texture(map_text, '\n')) { map->textures[total_textures_red] = p_parse_texture_attribs(map_text); total_textures_red++; was_texture_block_found = 1; } else if (was_texture_block_found) ft_assert(total_textures_red != map->texture_num, "Unexpected texture block end."); map_text = ft_strchr(map_text, '\n'); ft_assert(map_text != NULL, "Unexpected EOF."); map_text++; } return (map_text); }
C
/* fuction group about packet */ #include "packet.h" /* u_char* my_strncpy(u_char* d, const u_char* s, int len) { u_int i; d = malloc(sizeof(u_char) * (len + 1)); for (i = 0; i < len; ++i) d[i] = s[i]; d[len] = '\0'; return d; } //*/ ///* u_char* my_memcpy(u_char* d, const u_char* s, int len) { int i; //d = (u_char *)malloc(sizeof(u_char) * (len + 1)); for (i = 0; i < len; ++i) d[i] = s[i]; return d; } //*/ ///* void str_to_hex_print(u_char* str , int len) { int i; //printf("%d\n",sizeof(str)); for (i = 0; i < len ; i++) printf("%02x", str[i]); printf("\n"); } //*/
C
//Cameron Cobb //CS135 //lab9_problem1.c #include <stdio.h> #define SIZE 15 int swap(int *a, int *b){ int temp = 0; temp = *a; *a = *b; *b = temp; } int main(){ int arr[SIZE]; printf("Enter 15 integers:\n"); for(int i=0; i<SIZE; i++){ scanf("%d", &arr[i]); } swap(&arr[0],&arr[7]); swap(&arr[8],&arr[3]); swap(&arr[14],&arr[0]); printf("\n"); printf("Swapped array:\n"); for(int i=0; i<SIZE; i++){ printf("%d ", arr[i]); } printf("\n"); }
C
/* Set floating-point environment exception handling. Copyright (C) 2000-2017 Free Software Foundation, Inc. This file is part of the GNU C Library. Contributed by Denis Joseph Barrow ([email protected]). The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see <http://www.gnu.org/licenses/>. */ #include <fenv_libc.h> #include <math.h> #include <fpu_control.h> int fesetexceptflag (const fexcept_t *flagp, int excepts) { fexcept_t temp, newexcepts; /* Get the current environment. We have to do this since we cannot separately set the status word. */ _FPU_GETCW (temp); /* Install the new exception bits in the Accrued Exception Byte. */ excepts = excepts & FE_ALL_EXCEPT; newexcepts = excepts << FPC_FLAGS_SHIFT; temp &= ~newexcepts; if ((temp & FPC_NOT_FPU_EXCEPTION) == 0) /* Bits 6, 7 of dxc-byte are zero, thus bits 0-5 of dxc-byte correspond to the flag-bits. Clear given exceptions in dxc-field. */ temp &= ~(excepts << FPC_DXC_SHIFT); /* Integrate dxc-byte of flagp into flags. The dxc-byte of flagp contains either an ieee-exception or 0 (see fegetexceptflag). */ temp |= (*flagp | ((*flagp >> FPC_DXC_SHIFT) << FPC_FLAGS_SHIFT)) & newexcepts; /* Store the new status word (along with the rest of the environment. Possibly new exceptions are set but they won't get executed. */ _FPU_SETCW (temp); /* Success. */ return 0; }
C
#include <bits/stdc++.h> using namespace std; #define ll long long #define FOR(I,A,B) for(int I= (A); I<(B); ++I) #define REP(I,N) FOR(I,0,N) #define ALL(A) (A).begin(), (A).end() using namespace std; int main() { std::ios::sync_with_stdio(false); //I/O faster use'\n' in place of endl cin.tie(NULL); vector<int> fib( 36, 0 ); fib[1] = 1; fib[2] = 2; FOR( i, 3, 36 ) fib[i] = fib[i-1]+fib[i-2];//, cout << fib[i] << endl;; int N; vector<int>::iterator pos, prev; cin>>N; while(N!=0) { vector<int> ans( N, 0 ); int X; REP( i, N ) { cin>>X ; if( X >= 7465176 ) { ans[i] = 9227465; continue; } pos = lower_bound( fib.begin(), fib.end(), X ); if( *pos == X ) ans[i] = X; else { prev = pos-1; if( abs(*pos-X) > abs(*prev-X) ) ans[i] = *prev; else ans[i] = *pos; } } sort( ans.begin(), ans.end() ); cout<<ans[0]; FOR( i, 1, N ) cout<<" "<<ans[i]; cout<<'\n'; cin>>N; } }
C
#include<stdio.h> void fun(int n,int *mon,int *day) { int a[12]={31,28,31,30,31,30,31,31,30,31,30,31},i=0,h=0,sum=0; if(h+a[i]>n) { *mon=1; *day=n-a[0]; } while(h+a[i]<n) { h=h+a[i]; sum=sum+a[i]; i++; } *mon=i+1; *day=n-sum; } int main() { int n,month,day; scanf("%d",&n); fun(n,&month,&day) ; printf("%d%d\n",month, day) ; return 0; }
C
#include <unistd.h> int main(int argc, char *argv[]) { char n = '9'; while (n >= '0') { write(1, &n, 1); n--; } write(1, "\n", 1); return (0); }
C
#include <stdio.h> #include <timerms.h> #include <stdlib.h> #include <string.h> #include <stdlib.h> #include <arpa/inet.h> // Time htons etc etc #include "eth.h" #include "ipv4.h" #include "arp.h" /* Logitud máxmima del nombre de un interfaz de red */ #define IFACE_NAME_MAX_LENGTH 32 #define ARP_TABLE_SIZE 256 /* Número de entradas máximo de la tabla de rutas IPv4 */ ipv4_addr_t ip_addr; eth_iface_t *iface; typedef struct arp_table { arp_entry_t * entries[ARP_TABLE_SIZE]; } arp_table_t; typedef struct arp_entry{ mac_addr_t mac_addr; ipv4_addr_t ip_addr; }arp_entry_t; arp_entry_t * arp_create( ipv4_addr_t ip_addr, mac_addr_t mac_addr){ arp_entry_t * entry = (arp_entry_t *) malloc(sizeof(struct arp_entry)); if ((ip_addr != NULL) && (mac_addr != NULL) ) { memcpy(entry->ip_addr, ip_addr, IPv4_ADDR_SIZE); memcpy(entry->mac_addr, mac_addr, MAC_ADDR_SIZE); } return entry; } void arp_print ( arp_entry_t * entry ){ if (entry != NULL) { char ip_str[IPv4_STR_MAX_LENGTH]; ipv4_addr_str(entry->ip_addr,ip_str); char mac_str[MAC_STR_MAX_LENGTH]; mac_addr_str(entry->mac_addr,mac_str); printf("%s\t%s\n",ip_str,mac_str); } } void arp_free ( arp_entry_t * entry ) { if (entry != NULL) free(entry); } arp_entry_t* arp_read ( char* filename, int linenum, char * line ) { arp_entry_t* entry = NULL; char ip_addr_str[256]; char mac_addr_str[256]; /* Parse line: Format "<ip> <mask> <next_hop> <metric>\n" */ int params = sscanf(line, "%s %s\n",ip_addr_str, mac_addr_str); if (params != 2) { fprintf(stderr, "%s:%d: Invalid ARP Entry format: '%s' (%d params)\n",filename, linenum, line, params); fprintf(stderr,"%s:%d:Format <ip> <mac>\n",filename, linenum); return NULL; } /* Parse IPv4 route subnet address */ ipv4_addr_t ip_addr; int err = ipv4_str_addr(ip_addr_str, ip_addr); if (err == -1) { fprintf(stderr, "%s:%d: Invalid <addr> value: '%s'\n",filename, linenum, ip_addr_str); return NULL; } /* Parse MAC addr */ mac_addr_t mac_addr; err = mac_str_addr(mac_addr_str, mac_addr); if (err == -1) { fprintf(stderr, "%s:%d: Invalid <mac> value: '%s'\n", filename, linenum, mask_str); return NULL; } /* Create new route with parsed parameters */ entry = arp_create( ip_addr, mac_addr); if (route == NULL) { fprintf(stderr, "%s:%d: Error creating the new route\n",filename, linenum); } return route; } arp_table_t * arp_table_create(){ arp_table_t * table = (arp_table_t *) malloc(sizeof(struct arp_table)); if (table != NULL) { int i; for (i=0; i<arp_TABLE_SIZE; i++) { table->entries[i] = NULL; } } return table; } int arp_table_add ( arp_table_t * table, arp_entry_t * entry ) { int route_index = -1; if (table != NULL) { /* Find an empty place in the route table */ int i; for (i=0; i<ARP_TABLE_SIZE; i++) { if (table->entries[i] == NULL) { table->entries[i] = entry; route_index = i; break; } } } return route_index; } arp_entry_t * arp_table_remove ( arp_table_t * table, int index ) { arp_entry_t * removed_route = NULL; if ((table != NULL) && (index >= 0) && (index < ARP_TABLE_SIZE)) { removed_entry = table->entries[index]; table->entries[index] = NULL; } return removed_route; } arp_entry_t * arp_table_get ( arp_table_t * table, int index ) { arp_entry_t * route = NULL; if ((table != NULL) && (index >= 0) && (index < ARP_TABLE_SIZE)) { route = table->routes[index]; } return route; } int arp_table_find( arp_table_t * table, ipv4_addr_t ip_addr) { int route_index = -2; if (table != NULL) { route_index = -1; int i; for (i=0; i<ARP_TABLE_SIZE; i++) { arp_entry_t * route_i = table->entries[i]; if (route_i != NULL) { int same_addr = (memcmp(route_i->ip_addr, ip_addr, IPv4_ADDR_SIZE) == 0); if (same_addr && same_mask) { route_index = i; break; } } } } return route_index; } void arp_table_free ( arp_table_t * table ) { if (table != NULL) { int i; for (i=0; i<ARP_TABLE_SIZE; i++) { arp_entry_t * route_i = table->entries[i]; if (route_i != NULL) { table->entries[i] = NULL; arp_free(route_i); } } free(table); } } int arp_table_read ( char * filename, arp_table_t * table ) { int read_routes = 0; FILE * routes_file = fopen(filename, "r"); if (routes_file == NULL) { fprintf(stderr, "Error opening input IPv4 Routes file \"%s\": %s.\n",filename, strerror(errno)); return -1; } int linenum = 0; char line_buf[1024]; int err = 0; while ((! feof(routes_file)) && (err==0)) { linenum++; /* Read next line of file */ char* line = fgets(line_buf, 1024, routes_file); if (line == NULL) { break; } /* If this line is empty or a comment, just ignore it */ if ((line_buf[0] == '\n') || (line_buf[0] == '#')) { err = 0; continue; } /* Parse route from line */ arp_entry_t* new_route = arp_read(filename, linenum, line); if (new_route == NULL) { err = -1; break; } /* Add new route to Route Table */ if (table != NULL) { err = arp_table_add(table, new_route); if (err >= 0) { err = 0; read_routes++; } } } /* while() */ if (err == -1) { read_routes = -1; } /* Close IP Route Table file */ fclose(routes_file); return read_routes; } char mac_string[MAC_STR_LENGTH]; char ip_string[IPv4_STR_MAX_LENGTH]; int main(int argc,char *argv[]){ arp_table_t arp_table = arp_table_create(); // Si no hay suficientes argumentos if(argc != 4){ printf("Escriba %s [IF] [IP] [RIP_FILE]\n", argv[0]); return -1; } // Si la IP está mal iface = eth_open(argv[1]); if(ipv4_str_addr ( argv[2], ip_addr )){ printf("El argumento %s no es una IP válida\n",argv[1]); return -1; } int len = arp_table_read(argv[3],arp_table); if(len=0){ printf("No hay rutas en este fichero"); return -1; } while(1){ } eth_close(iface);//CErramos eth. return 0; }
C
#include <stdio.h> void swap_by_pointer(int* pvalue1, int* pvalue2) { if (NULL != pvalue1 && NULL != pvalue2) { int *temp = pvalue1; pvalue1 = pvalue2; pvalue2 = temp; printf("함수 내부(주소) : %p, %p\n",(void *) pvalue1,(void *) pvalue2); printf("함수 내부(가리키는 값) : %d, %d\n", *pvalue1,*pvalue2); } else { printf("swap() 내의 NULL 포인터 오류"); } } int main() { int value1 = 100, value2 = 200; int* pvalue1 = &value1; int* pvalue2 = &value2; printf("함수 호출 전(주소): %p, %p\n",(void *) pvalue1,(void *) pvalue2); printf("함수 호출 전(가리키는 값) : %d, %d\n", *pvalue1, *pvalue2); swap_by_pointer(pvalue1, pvalue2); printf("함수 호출 후(주소) : %p, %p\n",(void *)pvalue1,(void *) pvalue2); printf("함수 호출 후(가리키는 값) : %d, %d\n", *pvalue1, *pvalue2); return 0 ; }
C
#define NO_JNZ #include "skeleton.h" static void emit_c() { instruction *inst = insts; value *val = vals; puts("#include <stdio.h>\n#include <inttypes.h>\n\n#define DEFAULT_TAPE_SIZE 4*1024*1024\n\ntypedef uint8_t cell;\n\nstatic cell tapebuf[DEFAULT_TAPE_SIZE] = {0};\n\nint main(int argc, char *argv[])\n{\n\tcell *tape = tapebuf;\n"); #define def(n, v) case Op_##n: printf("\t" v ";\n"); break; #define defb(n, v) case Op_##n: printf("\t" v "\n"); val++; break; #define defv(n, v) case Op_##n: printf("\t" v ";\n", val->off); val++; break; #define defe(n, v) case Op_##n: printf("\t" v ";\n"); goto out; break; while (1) { switch (*inst++) { defv(PtrRight, "tape += %u") def(PtrRight1, "tape++") defv(PtrLeft, "tape -= %u") def(PtrLeft1, "tape--") defv(Inc, "(*tape) += %u") def(Inc1, "(*tape)++") defv(Dec, "(*tape) -= %u") def(Dec1, "(*tape)--") def(Putchar, "putchar_unlocked(*tape)") def(Getchar, "*tape = getchar_unlocked()") defb(Jz, "while (*tape) {") defb(Jmp, "}") def(Set0, "(*tape) = 0") def(Set1, "(*tape) = 1") defv(Set, "(*tape) = %u") defe(Return, "return 0") default: ; } } out: puts("}"); } int main(int argc, char *argv[]) { FILE *src; time_t time; if (argc < 2) return 1; src = fopen(argv[1], "r"); parse(src); fclose(src); emit_c(); return 0; }
C
#include<unistd.h> void ft_putchar(char c) { write(1,&c,1); } char *ft_strncpy(char *dest, char *src, unsigned int n) { if(dest == '\0') { return '\0'; } char *point; *point = dest; while(*src && n--) { *dest = *src; dest++; src++; } *dest = '\0' ; return point; }
C
#include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <string.h> static int job_id_count = 0; struct test_struct { int job_id; int job_pid; char job_name[256]; struct test_struct *next; }; //struct test_struct * ptr; struct test_struct *head = NULL; struct test_struct *curr = NULL; struct test_struct* create_list(int job_pid, char * job_name) { struct test_struct *ptr = (struct test_struct*)malloc(sizeof(struct test_struct)); if(NULL == ptr) { printf("\n Node creation failed \n"); return NULL; } ptr->job_id = job_id_count++; ptr->job_pid = job_pid; strcpy(ptr->job_name,job_name); ptr->next = NULL; head = curr = ptr; return ptr; } struct test_struct* add_to_list(int job_pid, char * job_name) { if(NULL == head) { return (create_list(job_pid,job_name)); } struct test_struct *ptr = (struct test_struct*)malloc(sizeof(struct test_struct)); if(NULL == ptr) { printf("\n Node creation failed \n"); return NULL; } ptr->job_id = job_id_count++; ptr->job_pid = job_pid; strcpy(ptr->job_name,job_name); ptr->next = NULL; curr->next = ptr; curr = ptr; return ptr; } struct test_struct* search_in_list(int job_pid, struct test_struct **prev) { struct test_struct *ptr = head; struct test_struct *tmp = NULL; bool found = false; //printf("\n Searching the list for value [%d] \n",job_pid); while(ptr != NULL) { if(ptr->job_pid == job_pid) { found = true; break; } else { tmp = ptr; ptr = ptr->next; } } if(true == found) { if(prev) *prev = tmp; return ptr; } else { return NULL; } } int search_by_job_id(int job_id) { struct test_struct *ptr = head; bool found = false; //printf("\n Searching the list for value [%d] \n",job_pid); while(ptr != NULL) { if(ptr->job_id == job_id) { found = true; break; } else { ptr = ptr->next; } } if(true == found) { return ptr->job_pid; } else { return 0; } } int delete_from_list(int job_pid) { struct test_struct *prev = NULL; struct test_struct *del = NULL; del = search_in_list(job_pid,&prev); if(del == NULL) { return -1; } else { printf("[%d] %d %s Finished!\n",del->job_id,del->job_pid,del->job_name); if(prev != NULL) prev->next = del->next; if(del == head) { head = del->next; } else if(del == curr) { curr = prev; } } free(del); del = NULL; return 0; } void print_list(void) { struct test_struct *ptr = head; while(ptr != NULL) { printf("[%d] %d %s\n",ptr->job_id,ptr->job_pid,ptr->job_name); ptr = ptr->next; } return; }
C
#ifndef FZRL_TILE_H #define FZRL_TILE_H #include "tile_types.h" /** * Public Tile Functions and Defines * * Tile Explanation: * - Tiles have a material type (e.g. dirt, grass, stone, wood, metal, water, fire, empty) * - Tiles have a form type (e.g. floor, path, paved, wall, empty) * - Material Types and Form Types have movement values (e.g. dirt floor < dirt path < paved stone) * - Material Types and Form Types have passability values (e.g. not passable, passable) */ typedef struct fzrl_tile { enum Tile_Material material; enum Tile_Form form; } Tile; enum Tile_Type { TILE_EMPTY, TILE_DIRT_FLOOR, TILE_GRASS_FLOOR, TILE_STONE_FLOOR, TILE_DIRT_WALL, TILE_STONE_WALL, TILE_GRASS_PAVED }; Tile *get_tile_by_type( enum Tile_Type type ); #endif
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* cylinder.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: vicmarti <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/02/03 12:04:04 by vicmarti #+# #+# */ /* Updated: 2021/03/07 19:36:35 by vicmarti ### ########.fr */ /* */ /* ************************************************************************** */ #include "minirt.h" #include "figures.h" #include <stdlib.h> static int in_bonds(long double d, t_cylinder c, t_coord r_orig, t_coord r_dir) { t_coord cyl_to_point; long double collision_height; vect_sub(&cyl_to_point, move_p(r_orig, r_dir, d), c.orig); collision_height = dot_prod(c.dir, cyl_to_point); if (0 > collision_height || collision_height > c.h) return (0); return (1); } long double cylinder_collision(void *cylinder, t_coord orig, t_coord dir) { t_cylinder c; t_coord term[2]; t_coord delta_cyl; long double coefficients[3]; long double sol[2]; c = *(t_cylinder*)cylinder; scalar_prod(&term[0], dot_prod(dir, c.dir), c.dir); vect_sub(&term[0], dir, term[0]); vect_sub(&delta_cyl, orig, c.orig); scalar_prod(&term[1], dot_prod(delta_cyl, c.dir), c.dir); vect_sub(&term[1], delta_cyl, term[1]); coefficients[0] = dot_prod(term[0], term[0]); coefficients[1] = 2 * dot_prod(term[0], term[1]); coefficients[2] = dot_prod(term[1], term[1]) - c.r * c.r; quad_solve(coefficients, &sol[0], &sol[1]); if (!isnan(sol[0]) && (sol[0] < 0.0L || equals_zero(sol[0]) || !in_bonds(sol[0], c, orig, dir))) sol[0] = NAN; if (!isnan(sol[1]) && (sol[1] < 0.0L || equals_zero(sol[1]) || !in_bonds(sol[1], c, orig, dir))) sol[1] = NAN; return (fminl(sol[0], sol[1])); } t_coord cylinder_normal(void *cylinder, t_coord at, t_coord facing) { t_coord normal; t_coord aux; t_cylinder c; c = *(t_cylinder*)cylinder; vect_sub(&aux, at, c.orig); scalar_prod(&aux, dot_prod(c.dir, aux), c.dir); vect_sum(&aux, aux, c.orig); vect_sub(&normal, at, aux); normalize(&(normal)); vect_sub(&facing, facing, at); if (dot_prod(normal, facing) < 0) scalar_prod(&normal, -1.0L, normal); return (normal); } void push_cylinder(t_figure **ppfig) { t_figure *aux; if (!(aux = malloc(sizeof(t_triangle)))) config_err("Could not allocate mem.\n"); aux->next = *ppfig; aux->collision = cylinder_collision; aux->normal_at = cylinder_normal; *ppfig = aux; }
C
#include "rtpersrc/pe_common.hh" /*********************************************************************** * * Routine name: pe_2sCompBinInt64 * * Description: This routine encompasses the rules to encode a * 2's complement binary integer as specified in * section 10.4 of the X.691 standard. * * Inputs: * * Name Type Description * ---- ---- ----------- * pctxt struct* Pointer to ASN.1 PER context structure * value uint Value to be encoded * * Outputs: * * Name Type Description * ---- ---- ----------- * status int Completion status of encode operation * * **********************************************************************/ EXTPERMETHOD int pe_2sCompBinInt64 (OSCTXT* pctxt, OSINT64 value) { /* 10.4.6 A minimum octet 2's-complement-binary-integer encoding */ /* of the whole number has a field width that is a multiple of 8 */ /* bits and also satisifies the condition that the leading 9 bits */ /* field shall not be all zeros and shall not be all ones. */ /* first encode integer value into a local buffer */ OSOCTET lbuf[8], lb; OSINT32 i = sizeof(lbuf); OSINT64 temp = value; memset (lbuf, 0, sizeof(lbuf)); do { lb = (OSOCTET) (temp % 256); temp /= 256; if (temp < 0 && lb != 0) temp--; /* two's complement adjustment */ lbuf[--i] = lb; } while (temp != 0 && temp != -1); /* If the value is positive and bit 8 of the leading byte is set, */ /* copy a zero byte to the contents to signal a positive number.. */ if (value > 0 && (lb & 0x80) != 0) { i--; } /* If the value is negative and bit 8 of the leading byte is clear, */ /* copy a -1 byte (0xFF) to the contents to signal a negative */ /* number.. */ else if (value < 0 && ((lb & 0x80) == 0)) { lbuf[--i] = 0xff; } /* Add the data to the encode buffer */ return pe_octets (pctxt, &lbuf[i], (sizeof(lbuf) - i) * 8); }
C
#include <stdio.h> #include <string.h> #include <stdlib.h> int SumRequiredSymbols(char *str) { int signs = 0, digits = 0, sum; char plus = 43, minus = 45, multiply = 42; for (int s = 0; str[s] != '\0'; s++) { if (str[s] == plus || str[s] == minus || str[s] == multiply) signs++; if (48 <= str[s] && str[s] <= 57) digits++; } sum = signs + digits; return sum; } int main(void) { char str[32]; char quantity; printf("Enter a string: "); fgets(str, 32, stdin); quantity = SumRequiredSymbols(str); printf("Quantity digits and signs '+', '-', '*': %d\n", quantity); }
C
#include <assert.h> #include <stdlib.h> #include <string.h> #include "cstring.h" #include "calloc.h" static const char* const EMPTY_STRING = ""; void chess_string_init(ChessString* string) { string->size = 0; string->data = EMPTY_STRING; } void chess_string_init_assign(ChessString* string, const char* s) { chess_string_init_assign_size(string, s, strlen(s)); } void chess_string_init_assign_size(ChessString* string, const char* s, size_t n) { char* buf; assert(s != NULL); if (n == 0) { string->size = 0; string->data = EMPTY_STRING; return; } string->size = n; buf = (char*)chess_alloc(n + 1); strncpy(buf, s, n); buf[n] = '\0'; string->data = buf; } void chess_string_cleanup(ChessString* string) { if (string->size > 0) chess_free((char*)string->data); } void chess_string_clear(ChessString* string) { chess_string_cleanup(string); chess_string_init(string); } void chess_string_assign(ChessString* string, const char* s) { chess_string_cleanup(string); chess_string_init_assign(string, s); } void chess_string_assign_size(ChessString* string, const char* s, size_t n) { chess_string_cleanup(string); chess_string_init_assign_size(string, s, n); }
C
/* SPDX-License-Identifier: BSD-2-Clause * * Job definition/interface * * Copyright (c) 2018-2021, Marek Koza ([email protected]) * All rights reserved. */ /* * Various long running tasks in plumCore, whether one shot or recurring, * share some common attributes: * - execution time in the range of several seconds to hours * - a steadily progressing state, stopping the job when reaching 100% * - ability to be paused without losing the execution state * - start/restart functionality for recurring jobs * * Tasks which never complete during runtime are considered daemons, not jobs. * They are implemented as services. * * As jobs are designed to be started and completed during runtime, managing * and discovering them using a service locator service is not optimal and * discouraged, although ossible if the service locator implements removing * interfaces from the list during runtime. Instead, a job manager service * exists for this purpose. */ #pragma once #include <stdint.h> typedef enum job_ret { JOB_RET_OK = 0, JOB_RET_FAILED, JOB_RET_NULL, } job_ret_t; typedef enum job_state { JOB_STATE_SCHEDULED = 0, JOB_STATE_RUNNING, JOB_STATE_COMPLETED, JOB_STATE_CANCELLED, JOB_STATE_SUSPENDED, } job_state_t; typedef struct job Job; struct job_vmt { /** * @brief Start a new job * * The job must be sufficiently prepared, it must know its parameters * before the start method is called. Either by setting them beforehand * or the job must discover them on start. * * The purpose of this function is to allow the job manager to start * scheduled job when there are enough resources available or when * it is defined as recurring. */ job_ret_t (*start)(Job *self); /** * @brief Cancal a running job * * A job cannot be stopped. It can be left runnng until it completes or * cancelled prematurely forgetting its state. */ job_ret_t (*cancel)(Job *self); /** * @brief Pause a running job */ job_ret_t (*pause)(Job *self); /** * @brief Resume a previously paused job */ job_ret_t (*resume)(Job *self); /** * @brief Get the current job progress * * A job progress is computed as @p done / @p total. The @p done and * @p total values must be provided by the job. */ job_ret_t (*progress)(Job *self, uint32_t *total, uint32_t *done); }; typedef struct job { const struct job_vmt *vmt; void *parent; } Job;
C
#include <stdio.h> #include <stdlib.h> int populate_array(int, int *); int check_sin(int *); int main(int argc, char **argv) { // TODO: Verify that command line arguments are valid. if(argc != 2){ return 1; } // TODO: Parse arguments and then call the two helpers in sin_helpers.c // to verify the SIN given as a command line argument. int arr[9]; int sin = strtol(argv[1], NULL, 10); populate_array(sin, arr); check_sin(arr); return 0; }
C
#include<stdio.h> int main(void) { int i, t, a[10], j; long n; scanf("%ld", &n); for(i = 0; i < n; i++) { scanf("%d", &a[i]); } i = 0; j = n - 1; while(j > i) { t = a[j], a[j] = a[i],a[i] = t; i++; j--; } for(i = 0; i < n; i++) { printf("%d%c", a[i], i == n - 1?'\n':' '); } return 0; }
C
#include<stdio.h> #include<stdlib.h> #define random(x) (rand()%x) #include<time.h> #include<conio.h> #include<string.h> //ҽṹ int count=0; char enter; struct player{ char Name[10]; int win; int lose; int tide; int score; }; struct player p,player[100]; // int main() { char Exit,choice,Choice; int x; int practice(); int newbie(); int rank(); int veteran(); int rule(); while(1) { system("cls"); printf(" ʯͷ\n"); printf("============================================\n"); printf("1-ϰģʽ 2-ģʽ 3-鿴а\n"); printf("4- 0-˳\n"); printf("============================================\n"); printf(" ѡ루1-30 ˳\n"); choice=getch(); switch(choice){ case '1': for(x=0;;x++){ practice(); system("PAUSE"); break; } break; case '2': while(1){ system("cls"); printf("ѡ\n"); printf("1- 2- 0-ز˵\n"); Choice=getch(); switch(Choice){ case '1': newbie(); system("PAUSE"); break; case '2': veteran(); system("PAUSE"); break; case '0':main(); default:; } } system("PAUSE"); break; case '3': rank(); system("PAUSE"); break; case '4': rule(); system("PAUSE"); break; case '0': exit(0); default:break; } } } //ϰģʽ int practice() { char a; int b,x,c,n=1; int win=0,lose=0,tide=0; for(c=1;c<=7;c++) { printf(" %d \n",n); printf("==========================\n"); printf("ѡ"); printf("1- 2-ʯͷ 3-\n"); scanf("%s",&a); printf("==========================\n"); switch(a) { case '1':printf(" 㣩VS");break; case '2':printf(" 㣩ʯͷVS");break; case '3':printf(" 㣩VS");break; default:printf("\n");break; } srand((int)time(0)); if(a=='3'||a=='1'||a=='2') { for(x=0;x<999;x++) { b=random(3);} if(b==0) printf("ԣ\n"); else if(b==1) printf("ʯͷԣ\n"); else if(b==2) printf("ԣ\n"); n++; } else printf(" \n"); if((a=='1'&&b==0)||(a=='2'&&b==1)||(a=='3'&&b==2)) {printf("\n ƽ\n\n\n"),tide++;} else if((a=='1'&&b==1)||(a=='2'&&b==2)||(a=='3'&&b==0)) printf("\n \n\n"),lose++; else if((a=='1'&&b==2)||(a=='2'&&b==0)||(a=='3'&&b==1)) printf("\n Ӯ\n\n"),win++; else{printf("\n");c--; } printf(" ĿǰӮ%d֣%d,ƽ%d\n\n\n",win,lose,tide); //Ӯ if(win>=4)break; if(lose>=4)break; } if(win>lose){ printf(" =========\n [ þʤ ]\n =========\n");} else if(lose>win){ printf(" =========\n [ þʧ ]\n =========\n");} else printf(" =========\n [ þƽ ]\n =========\n"); return 0; } //սģʽ- int newbie() { char a; int b,x,c,n=1,i,index=-1; int win=0,lose=0,tide=0; printf("û"); scanf("%s",player[count].Name); for (i=0;i<count;i++){ if (strcmp(player[i].Name,player[count].Name)==0){ index=i;break; } else index=-1; } if (index!=-1) printf("ûѴ!\n"); else { for(c=1;c<=7;c++){ printf(" %d \n",n); printf("==========================\n"); printf("ѡ"); printf("1- 2-ʯͷ 3-\n"); scanf("%s",&a); printf("==========================\n"); switch(a) { case '1':printf(" 㣩VS");break; case '2':printf(" 㣩ʯͷVS");break; case '3':printf(" 㣩 VS");break; default:printf("\n");break; } srand((int)time(0)); if(a=='3'||a=='1'||a=='2'){ for(x=0;x<999;x++) { b=random(3);} if(b==0) printf("ԣ\n"); else if(b==1) printf("ʯͷԣ\n"); else if(b==2) printf("ԣ\n"); n++; } else printf(" \n"); if((a=='1'&&b==0)||(a=='2'&&b==1)||(a=='3'&&b==2)){ printf("\n ƽ\n\n\n"),tide++;} else if((a=='1'&&b==1)||(a=='2'&&b==2)||(a=='3'&&b==0)) printf("\n \n\n"),lose++; else if((a=='1'&&b==2)||(a=='2'&&b==0)||(a=='3'&&b==1)) printf("\n Ӯ\n\n"),win++; else {printf("\n");c--;} printf(" ĿǰӮ%d֣%d,ƽ%d\n\n\n",win,lose,tide); if(win>=4)break; if(lose>=4)break; } if(win>lose){ printf(" =========\n [ þʤ ]\n =========\n"); player[count].win++;} else if(lose>win){ printf(" =========\n [ þʧ ]\n =========\n"); player[count].lose++;} else { printf(" =========\n [ þƽ ]\n =========\n"); player[count].tide++;} player[count].score=3*(player[count].win)+player[count].tide-2*player[count].lose; printf("Ӯ %d ֣ %d ֣ƽ %d ֣ %d \n", player[count].win,player[count].lose,player[count].tide,player[count].score); count++;} return 0; } //սģʽ- int veteran() { char name[10],a; int index; int b,x,c,n=1,i; int win=0,lose=0,tide=0; printf("û:"); scanf("%s",&name); for (i=0;i<count;i++){ if (strcmp(player[i].Name,name)==0){ index=i;break; } else index=-1; } if (index==-1) printf("ѧ!\n"); else { for(c=1;c<=7;c++) { printf(" %d \n",n); printf("==========================\n"); printf("ѡ"); printf("1- 2-ʯͷ 3-\n"); scanf("%s",&a); printf("==========================\n"); switch(a) { case '1':printf(" 㣩VS");break; case '2':printf(" 㣩ʯͷVS");break; case '3':printf(" 㣩 VS");break; default:printf("\n");break; } srand((int)time(0)); if(a=='3'||a=='1'||a=='2') { for(x=0;x<999;x++) { b=random(3);} if(b==0) printf("ԣ\n"); else if(b==1) printf("ʯͷԣ\n"); else if(b==2) printf("ԣ\n"); n++; } else printf(" \n"); if((a=='1'&&b==0)||(a=='2'&&b==1)||(a=='3'&&b==2)){ printf("\n ƽ\n\n\n"),tide++; } else if((a=='1'&&b==1)||(a=='2'&&b==2)||(a=='3'&&b==0)) printf("\n \n\n"),lose++; else if((a=='1'&&b==2)||(a=='2'&&b==0)||(a=='3'&&b==1)) printf("\n Ӯ\n\n"),win++; else { printf("\n");c--; } printf(" ĿǰӮ%d֣%d,ƽ%d\n\n\n",win,lose,tide); if(win>=4)break; if(lose>=4)break; } if(win>lose){ printf(" =========\n [ þʤ ]\n =========\n"); player[index].win++; } else if(lose>win){ printf(" =========\n [ þʧ ]\n =========\n"); player[index].lose++; } else { printf(" =========\n [ þƽ ]\n =========\n"); player[index].tide++; } player[index].score=3*(player[index].win)+player[index].tide-2*player[index].lose; printf("Ӯ %d ֣ %d ֣ƽ %d ֣ %d \n", player[index].win,player[index].lose,player[index].tide,player[index].score); } return 0; } //а int rank() { int i,j,k; for(i=0;i<count;i++){ for(j=i+1;j<=count;j++){ if(player[i].score<player[j].score){ p=player[i]; player[i]=player[j]; player[j]=p; } } } printf("*****************************************************************\n"); printf(" а\n\n"); printf(" ʤ ƽ ܷ\n"); for(k=0;k<count;k++){ printf("%d%12s%15d%16d%17d%18d\n",k+1,player[k].Name, player[k].win,player[k].tide,player[k].lose,player[k].score); } printf("*****************************************************************\n"); return 0; } //Ϸ int rule() { system("cls"); printf(" Ϸ\n\n"); printf("ʯͷӮӮӮʯͷļ򵥹ʤƣȡʤϷ\n\n"); printf("ϰģʽУһֱԡ\n\n"); printf("ڶսģʽУÿʤ3֣ƽֵ-2֣ʧܵ0\n\n"); printf("а񽫻¼սģʽʤ֡û\n\n"); return 0; }
C
#include <gb/gb.h> #include "ct/sprA.h" #include "ct/sprB.h" #include "ct/sprC.h" #include "ct/sprD.h" #include "ct/sprE.h" #include "ct/sprF.h" #include "ct/sprG.h" #include "ct/sprH.h" void drawImage(unsigned char *tile, unsigned char *map){ wait_vbl_done(); // Load up the tile data set_bkg_data(0, 255, tile); // Switch to VRAM VBK_REG = 1; // Switch out of VRAM VBK_REG = 0; // Set screen x,y pos to 0,0 and draw the map 20, 18 (size of the screen) set_bkg_tiles(0, 0, 20, 18, map); // Show the background SHOW_BKG; // Turn the display on DISPLAY_ON; // I wish these number were as exact as they look ;-; delay(125); } void main() { while (1) { drawImage(sprA_tile_data, sprA_map_data); // Additional first frame delay delay(98); drawImage(sprB_tile_data, sprB_map_data); drawImage(sprC_tile_data, sprC_map_data); drawImage(sprD_tile_data, sprD_map_data); drawImage(sprE_tile_data, sprE_map_data); drawImage(sprG_tile_data, sprG_map_data); drawImage(sprH_tile_data, sprH_map_data); } }
C
/*Programa que realizar el factorial de un número dado */ #include <stdio.h> int main(){ int n; int total = 1; printf("Indique el número del cual desea obtener el factorial: "); scanf("%d", &n); while(n>1){ total = total * n; n = n - 1; printf("%d\n", total); } printf("\n\n"); return 0; }
C
#include<stdio.h> int main(void) { char a; scanf("%c",&a); if((a>='a'&&a<='z')||(a>='A'&&a<='Z')) if(a=='a'||a=='e'||a=='i'||a=='o'||a=='u'||a=='A'||a=='E'||a=='I'||a=='O'||a=='U') printf("vowel"); else printf("consonant"); return 0; }
C
/* mesh_bi.c Copyright (C) 2012 Adapteva, Inc. Contributed by Wenlin Song <[email protected]> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program, see the file COPYING. If not, see <http://www.gnu.org/licenses/>. */ // This is the HOST side of the e_mesh bandwidth example // In this test, the left half section on the chip transfer // data to the right half section on the chip simultaneously. // Use CTIMER_0 register to measure the time on core (0,0). #include <stdlib.h> #include <stdio.h> #include <string.h> #include <unistd.h> #include <e-hal.h> int main(int argc, char *argv[]) { unsigned row, col, coreid, i, j, m, n, k; e_platform_t platform; e_epiphany_t dev; unsigned time; unsigned signal = 0xdeadbeef; unsigned clr = 0x00000000; float result1; srand(1); // initialize system, read platform params from // default HDF. Then, reset the platform and e_init(NULL); e_reset_system(); e_get_platform_info(&platform); // Open a workgroup e_open(&dev, 0, 0, platform.rows, platform.cols); // Load the device program onto core (0,0) e_load("e_mesh_bi00.elf", &dev, 0, 0, E_TRUE); usleep(1000); e_load_group("e_mesh_bi.elf", &dev, 1, 0, (platform.rows-1), 1, E_TRUE); e_load_group("e_mesh_bi1.elf", &dev, 0, 1, platform.rows, 1, E_TRUE); usleep(100000); // Sent the signal to start transfer e_write(&dev, 0, 0, 0x6100, &signal, sizeof(signal)); usleep(2000000); // Read message from shared buffer e_read(&dev, 0, 0, 0x5000, &time, sizeof(time)); // Calculate the bandwidth if (time == 0) result1 = 0; else result1 = (37500000)/time; // Print the message and close the workgroup fprintf(stderr, "0x%08x!\n", time); fprintf(stderr, "The bandwidth of bisection is %.2fMB/s!\n", result1); // Close the workgroup e_close(&dev); // Finalize the e-platform connection. e_finalize(); return 0; }
C
#include "nph.h" volatile sig_atomic_t is_sigstp = 0; volatile sig_atomic_t is_sigint = 0; extern char *back_ground[40]; extern int bp_id[40]; extern int bp_num[40]; extern int bp_count; extern int bpnum; void handler(int sig) { pid_t pid; int status; while ((pid = waitpid(-1, &status, WNOHANG)) != -1) { if (bp_count != 0 && pid == -1) { perror("waitpid "); return; } int i; for (i = 0; i < 40; i++) { if (bp_id[i] == pid) break; } if (pid > 0) { if (WIFEXITED(status)) { if (WEXITSTATUS(status) == 0) printf("\n%s with pid %d exited normally\n", back_ground[i], bp_id[i]); else printf("\n%s with pid %d exited abnormally with exit code %d\n", back_ground[i], bp_id[i], WEXITSTATUS(status)); for (int j = i; j < 39; j++) { bp_id[j] = bp_id[j + 1]; back_ground[j] = back_ground[j + 1]; bp_num[j] = bp_num[j + 1]; } free(back_ground[bp_count]); bp_count--; } } } } void child_stop(int sig) { if (sig == SIGINT && raise(SIGKILL) == -1) { perror("kill "); exit(1); } else { int fg_pgid = tcgetpgrp(STDERR_FILENO); if (getpgrp() == fg_pgid) { if (sig == SIGTSTP && setpgid(0, 0) == -1) { perror("setting processs group "); exit(1); } } if (raise(SIGSTOP) != 0) { perror("raise "); exit(1); } } } void parent_stop(int sig) { if (sig == SIGINT) is_sigint = 1; if (sig == SIGTSTP) is_sigstp = 1; } int nph(char *arguments[]) { int is_bg = 0, i = 0; while (arguments[i] != NULL) { if (strcmp(arguments[i], "&") == 0) { is_bg = 1; arguments[i] = NULL; } i++; } pid_t pid = fork(); if (pid == -1) { perror("fork error "); return 1; } else if (pid == 0) { struct sigaction stphandler; memset(&stphandler, 0, sizeof(stphandler)); stphandler.sa_handler = child_stop; if (sigaction(SIGTSTP, &stphandler, NULL) == -1) { perror("sigaction "); exit(1); } if (sigaction(SIGINT, &stphandler, NULL) == -1) { perror("sigaction "); exit(1); } if (is_bg && setpgid(0, 0) == -1) { perror("setting processs group "); exit(1); } if (execvp(arguments[0], arguments) == -1) { perror(arguments[0]); exit(1); } } else { tcsetpgrp(STDERR_FILENO, getpgrp()); if (is_bg) { setpgid(pid, pid); signal(SIGCHLD, handler); bp_id[bp_count] = pid; bp_num[bp_count] = bpnum; back_ground[bp_count] = (char *)malloc(100); strcpy(back_ground[bp_count], arguments[0]); bp_count++; bpnum++; printf("%s is being executed in background with pid %d\n", arguments[0], pid); } else { struct sigaction new_handler, old_handler; memset(&new_handler, 0, sizeof(new_handler)); new_handler.sa_handler = parent_stop; if (sigaction(SIGTSTP, &new_handler, &old_handler) == -1) { perror("sigaction "); return 1; } int status; pid_t ch_pid; do { ch_pid = waitpid(pid, &status, WUNTRACED); } while (!WIFEXITED(status) && !WIFSIGNALED(status) && ch_pid != pid); int ret = 0; if (is_sigstp == 1) { is_sigstp = 0; bp_id[bp_count] = pid; bp_num[bp_count] = bpnum; back_ground[bp_count] = (char *)malloc(100); strcpy(back_ground[bp_count], arguments[0]); bp_count++; bpnum++; ret = 1; } tcsetpgrp(STDERR_FILENO, getpgrp()); if (sigaction(SIGTSTP, &old_handler, NULL) == -1) { perror("sigaction "); return 1; } if (ret) return ret; return WEXITSTATUS(status); } tcsetpgrp(STDERR_FILENO, getpgrp()); } return 0; } int jobs() { char path[30]; pid_t pid; for (int i = 0; i < bp_count; i++) { pid = bp_id[i]; if (kill(pid, 0) == -1) { for (int j = i; j < 39; j++) { bp_id[j] = bp_id[j + 1]; back_ground[j] = back_ground[j + 1]; bp_num[j] = bp_num[j + 1]; } free(back_ground[bp_count]); bp_count--; i--; continue; } sprintf(path, "/proc/%d/stat", pid); FILE *o_file = fopen(path, "r"); if (o_file == NULL) { perror("proc opening error "); return 1; } char left[30], status; fscanf(o_file, "%d %s %c", &pid, left, &status); if (fclose(o_file) != 0) { perror("closing /proc/pid/stat "); return 1; } printf("[%d] ", bp_num[i]); switch (status) { case 'R': printf("Running"); break; case 'S': printf("Sleeping"); break; case 'D': printf("Waiting in uninterruptible disk sleep"); break; case 'Z': printf("Zombie"); break; case 'T': printf("Stopped"); break; case 'X': printf("Dead"); break; case 't': printf("Tracing stop"); break; default: break; } printf(" %s [%d]\n", back_ground[i], bp_id[i]); } } int kjob(char *arguments[]) { int arg_num = no_of_arg(arguments); if (arg_num < 3) { printf("shell: too less arguments"); return 1; } else if (arg_num > 3) { printf("shell: too many arguments"); return 1; } int num = 0; int len = strlen(arguments[1]); for (int i = 0; i < len; i++) num += (int)(arguments[1][i] - '0') * pow(10, len - 1 - i); int sig = 0; len = strlen(arguments[2]); for (int i = 0; i < len; i++) sig += (int)(arguments[2][i] - '0') * pow(10, len - 1 - i); for (int i = 0; i < bp_count; i++) { if (bp_num[i] == num) { if (kill(bp_id[i], sig) == -1) { perror("kill "); return 1; } return 0; } } printf("shell: No job with the given job number exists\n"); return 1; } int fg(char *arguments[]) { int arg_num = no_of_arg(arguments); if (arg_num < 2) { printf("shell: too less arguments"); return 1; } else if (arg_num > 2) { printf("shell: too many arguments"); return 1; } int num = 0; int len = strlen(arguments[1]); for (int i = 0; i < len; i++) num += (int)(arguments[1][i] - '0') * pow(10, len - 1 - i); pid_t pid = 0; int i; for (i = 0; i < bp_count; i++) { if (bp_num[i] == num) { pid = bp_id[i]; break; } } if (pid == 0) { printf("shell: No job with the given job number exists\n"); return 1; } setpgid(pid, getpgrp()); kill(pid, SIGCONT); tcsetpgrp(STDERR_FILENO, getpgrp()); struct sigaction new_handler, old_handler; memset(&new_handler, 0, sizeof(new_handler)); new_handler.sa_handler = parent_stop; if (sigaction(SIGTSTP, &new_handler, &old_handler) == -1) { perror("sigaction "); return 1; } if (sigaction(SIGINT, &new_handler, NULL) == -1) { perror("sigaction "); return 1; } tcsetpgrp(STDERR_FILENO, getpgrp()); int status; pid_t ch_pid; do { ch_pid = waitpid(pid, &status, WUNTRACED); } while (!WIFEXITED(status) && !WIFSIGNALED(status) && ch_pid != pid); if (is_sigstp == 0 || is_sigint == 1) { for (int j = i; j < 39; j++) { bp_id[j] = bp_id[j + 1]; back_ground[j] = back_ground[j + 1]; bp_num[j] = bp_num[j + 1]; } free(back_ground[bp_count]); bp_count--; } if (is_sigint == 1) { is_sigint = 0; if (kill(pid, SIGKILL) == -1) { perror("kill "); return 1; } } if (is_sigstp == 1) { is_sigstp = 0; if (kill(pid, SIGSTOP) != 0) { perror("kill "); exit(1); } } tcsetpgrp(STDERR_FILENO, getpgrp()); if (sigaction(SIGINT, &old_handler, NULL) == -1) { perror("sigaction "); return 1; } if (sigaction(SIGTSTP, &old_handler, NULL) == -1) { perror("sigaction "); return 1; } tcsetpgrp(STDERR_FILENO, getpgrp()); return 0; } int bg(char *arguments[]) { int arg_num = no_of_arg(arguments); if (arg_num < 2) { printf("shell: too less arguments"); return 1; } else if (arg_num > 2) { printf("shell: too many arguments"); return 1; } int num = 0; int len = strlen(arguments[1]); for (int i = 0; i < len; i++) num += (int)(arguments[1][i] - '0') * pow(10, len - 1 - i); for (int i = 0; i < bp_count; i++) { if (bp_num[i] == num) { kill(bp_id[i], SIGCONT); return 0; } } printf("shell: No job with the given job number exists\n"); return 1; } int overkill() { while (bp_count) { if (kill(bp_id[0], SIGKILL) == -1) { perror("kill "); return 1; } for (int j = 0; j < 39; j++) { bp_id[j] = bp_id[j + 1]; back_ground[j] = back_ground[j + 1]; bp_num[j] = bp_num[j + 1]; } free(back_ground[bp_count]); bp_count--; } return 0; }
C
#include <stdio.h> #include "gpu_fft.h" #include "mailbox.h" #define FFT_WINDOW_SIZE_LOG2N 11 #define FFT_WINDOW_SIZE (1 << FFT_WINDOW_SIZE_LOG2N) struct GPU_FFT_COMPLEX *data_in_ptr; struct GPU_FFT *fft; struct GPU_FFT_COMPLEX *fft_out; /* Generates and saves the complex conjugate sample at the mirror index of the FFT */ void generate_complex_conjugate (struct GPU_FFT_COMPLEX *ptr, unsigned int index) { ptr[FFT_WINDOW_SIZE - index].re = ptr[index].re; ptr[FFT_WINDOW_SIZE - index].im = -1 * ptr[index].im; } int main () { int i, ret, mb = mbox_open (); ret = gpu_fft_prepare(mb, FFT_WINDOW_SIZE_LOG2N, GPU_FFT_REV, 1, &fft); // call once printf ("Prepare FFT done\n"); data_in_ptr = fft->in; switch(ret) { case -1: printf("Unable to enable V3D. Please check your firmware is up to date.\n"); return -1; case -2: printf("log2_N=%d not supported. Try between 8 and 22.\n", FFT_WINDOW_SIZE_LOG2N); return -1; case -3: printf("Out of memory. Try a smaller batch or increase GPU memory.\n"); return -1; case -4: printf("Unable to map Videocore peripherals into ARM memory space.\n"); return -1; case -5: printf("Can't open libbcm_host.\n"); return -1; } for (i = 0; i < FFT_WINDOW_SIZE; i++) { data_in_ptr[i].re = 0; data_in_ptr[i].im = 0; } data_in_ptr[150].re = 60; data_in_ptr[150].im = 60; generate_complex_conjugate(data_in_ptr, 150); data_in_ptr[300].re = -60; data_in_ptr[300].im = 60; generate_complex_conjugate(data_in_ptr, 300); usleep(1); // Yield to OS gpu_fft_execute(fft); // call one or many times printf ("Execute FFT done\n"); fft_out = fft->out; for (i = 0; i < FFT_WINDOW_SIZE; i++) { printf ("%f,%f\n", data_in_ptr[i].re, data_in_ptr[i].im); } gpu_fft_release(fft); // Videocore memory lost if not freed ! return 0; }
C
#include <stdio.h> #include <openssl/rsa.h> #include <openssl/pem.h> #include <openssl/err.h> #include <openssl/rand.h> #include <string.h> #define RSAKEYLEN 2048 #define PUBLICXPONENT 3 unsigned char key[256/8], IV[16]; RSA *keypair; size_t priv_keylen; size_t pub_keylen; char *priv_key; char *pub_key; char *encryptedkey; char *decryptedkey; static void PrintinHex(const void* hexval , size_t length) { const unsigned char * hexnum = (const unsigned char*)hexval; if (NULL == hexval) { printf("NULL"); } else { size_t it = 0; for (; it<length; ++it) { printf("%02X ", *hexnum++); } } printf("\n"); } /*This function should not be generated by Bob. It is Alice's responsibilty. This is just for testing purposes.*/ void GenerateSymmetricKey() { if(!RAND_bytes(key, sizeof(key))) { printf("Could not generate the key\n"); } if(!RAND_bytes(IV, sizeof(IV))) { printf("Could not generate the IV\n"); } } void RSAKeyGenerator() { //printf("Size of RSA Key being generated is %d\n, RSAKEYLEN"); printf("\n.............Generating RSA KEY PAIR IA............\n"); keypair = RSA_generate_key(RSAKEYLEN, PUBLICXPONENT, NULL, NULL); BIO *priv = BIO_new(BIO_s_mem()); BIO *pub = BIO_new(BIO_s_mem()); PEM_write_bio_RSAPrivateKey(priv, keypair, NULL, NULL, 0, NULL, NULL); PEM_write_bio_RSAPublicKey(priv, keypair); priv_keylen = BIO_pending(priv); pub_keylen = BIO_pending(pub); priv_key = malloc(priv_keylen + 1); pub_key = malloc(pub_keylen + 1); BIO_read(priv, priv_key, priv_keylen); BIO_read(pub, pub_key, pub_keylen); priv_key[priv_keylen] = '\0'; pub_key[pub_keylen] = '\0'; printf("\n%s\n%s\n", priv_key, pub_key); key[sizeof(key)-1] = '\0'; encryptedkey = malloc(RSA_size(keypair)); int enc = RSA_public_encrypt(32, key, (unsigned char *)encryptedkey, keypair, RSA_PKCS1_OAEP_PADDING); if (enc == -1) { perror("Error in encryption\n"); RSA_free(keypair); BIO_free_all(pub); BIO_free_all(priv); free(priv_key); free(pub_key); free(encryptedkey); free(decryptedkey); } printf("The 256 bit AES key is \n"); PrintinHex(key, sizeof(key)); printf("size of encrypted text is %d\n", enc); printf("The encrypted text is \n"); PrintinHex(encryptedkey, enc); decryptedkey = malloc(enc); int dec = RSA_private_decrypt(enc, (unsigned char *)encryptedkey, (unsigned char *)decryptedkey, keypair, RSA_PKCS1_OAEP_PADDING); if(dec == -1) { perror("error in decryption\n"); RSA_free(keypair); BIO_free_all(pub); BIO_free_all(priv); free(priv_key); free(pub_key); free(encryptedkey); free(decryptedkey); } printf("size of decr is %d\n", dec); printf("The decrypted key is \n"); PrintinHex(decryptedkey, enc); //printf("the message is %#x\n", (unsigned char *)decryptedkey); } void main() { encryptedkey = NULL; decryptedkey = NULL; OpenSSL_add_all_algorithms(); ERR_load_crypto_strings(); GenerateSymmetricKey(); RSAKeyGenerator(); }
C
#include<stdio.h> //Print duplicate nums in array. int main(){ int n,count=1; printf("Enter the size: "); scanf("%d",&n); printf("Enter your number: "); int arr[n]; for(int i=0;i<n;i++){ scanf("%d",&arr[i]); } for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ if(i==j){ continue; } else if(arr[i]==arr[j] && arr[i]==0 && i<j){ count++; } else if(arr[i]==arr[j] && arr[i]!=0){ count++; arr[j]=0; continue; } } if(count!=1 && arr[i]!=0){ printf("%d",arr[i]); count=1; } } return 0; }
C
#include <stdio.h> #include <pcap.h> #include <time.h> #include <errno.h> #include <unistd.h> #include <stdlib.h> #include <string.h> #include "ieee802_11_radio.h" /** * 根据标准时间转化为指定的时间格式 */ void convert_format_time(time_t rawtime,char* buffer){ struct tm * timeinfo; time (&rawtime); timeinfo = localtime (&rawtime); strftime (buffer,80,"%Y-%m-%d %I:%M:%S",timeinfo); } void hex(void *ptr, int len) { int i = 0; uint8_t *pc = ptr; int val = -1; char str[20]; memset(str, 0, sizeof(str)); while(len > 0) { do { if(0 == i%16) { printf("%04x ", i); } val = len > 0 ? *pc : -1; if (val >= 0) { printf("%02x ", val ); } else { printf(" "); } str[i%16] = (val > 0x40 && val < 0x7f) ? val : '.'; pc++; i++; len--; if(0 == i%16) { printf(" %s\n", str); } } while (i%16); } }
C
#ifdef BLINKER_FRAMEWORK_PRESENT <% width = 2 #7 height = 2 #3 # up, right, down, left walls = (0...height).map { (0...width).map { [true, true, true, true] } } visited = (0...height).map { [false]*width } visited[0][0] = true stack = [[0,0]] until stack.empty? x, y = stack.pop choices = [[x,y-1,0],[x+1,y,1],[x,y+1,2],[x-1,y,3]].select { |nx, ny, _| visited[ny] && visited[ny][nx] == false && nx >= 0 && ny >= 0 && nx < width && ny < height }.shuffle unless choices.empty? stack.push [x,y] nx, ny, d = choices.first visited[ny][nx] = true walls[y][x][d] = false walls[ny][nx][(d+2)%4] = false stack.push [nx,ny] end end maze = (0..(height*2)).map { ['#']*(width*2+1) } (0...height).each { |y| (0...width).each { |x| lwalls = walls[y][x] row = 2*y + 1 col = 2*x + 1 maze[row][col] = ' ' maze[row-1][col] = ' ' unless lwalls[0] maze[row][col-1] = ' ' unless lwalls[3] } } maze[2*height-1][2*width] = ' ' %> #define W <%= 2*width+1 %> #define H <%= 2*height+1 %> char maze[H][W] = { <% maze.each { |row| %> { <%= row.map { |c| "'#{c}'" }.join(',') %> }, <% } %> }; #define BUFFER_SIZE <%= random_number (16..128) %> #else #define W 15 #define H 7 char maze[H][W] = { {1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}, {1,0,1,0,0,0,0,0,0,0,0,0,0,0,1}, {1,0,1,1,1,1,1,1,1,1,1,1,1,0,1}, {1,0,0,0,0,0,1,0,0,0,1,0,0,0,1}, {1,1,1,1,1,0,1,0,1,0,1,0,1,0,1}, {1,0,0,0,0,0,0,0,1,0,0,0,1,0,0}, {1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}, }; #define BUFFER_SIZE 32 #endif int x = 1, y = 1; int old_x = 1, old_y = 1; #include <stdio.h> #include <string.h> #include <unistd.h> #include <sys/ptrace.h> #include <sys/types.h> #include <sys/wait.h> void print_maze() { for (int j = 0; j < H; j++) { for (int i = 0; i < W; i++) printf("%c", (i==x && j==y) ? '.' : maze[j][i]); printf("\n"); } } void left() { old_x = x--; if (maze[y][x] == ' ') { puts("Going left."); return; } else { x = old_x; puts("Can't do that, sorry."); return; } } void right() { old_x = x++; if (maze[y][x] == ' ') { puts("Going right."); } else { x = old_x; puts("Can't do that, sorry."); } } void up() { old_y = y--; if (maze[y][x] == ' ') { puts("Going up."); } else { y = old_y; puts("Can't do that, sorry."); } } void down() { old_y = y++; if (maze[y][x] == ' ') { puts("Going down."); } else { y = old_y; puts("Can't do that, sorry."); } } int get_input() { char buf[BUFFER_SIZE]; printf("[l/r/u/d]? "); scanf("%s", buf); #ifdef ENABLE_NAVI if (buf[0]=='l') return 3; if (buf[0]=='r') return 1; if (buf[0]=='u') return 0; if (buf[0]=='d') return 2; #endif return -1; } int interact() { print_maze(); return get_input(); } int main(int argc, char **argv) { if (argc != 2) { puts("The first (and only) argument must be the flag."); return 1; } pid_t child = fork(); if (child == -1) { perror("fork"); return 1; } if (child == 0) { memset(argv[1], 0, strlen(argv[1])); while (1) { if (x == W - 1 || y == H - 1 || x == 0 || y == 0) { ptrace(PTRACE_TRACEME, 0, NULL, NULL); raise(SIGSTOP); break; } int dir = interact(); switch (dir) { case 0: up(); break; case 1: right(); break; case 2: down(); break; case 3: left(); break; default: puts("I don't understand, sorry."); } } } else { int wstatus; waitpid(child, &wstatus, 0); if (WIFSTOPPED(wstatus)) { int c_x = ptrace(PTRACE_PEEKDATA, child, &x, NULL); int c_y = ptrace(PTRACE_PEEKDATA, child, &y, NULL); puts("Game over."); if (c_x == W - 1 || c_y == H - 1 || c_x == 0 || c_y == 0) { printf("Good work! Here's your reward: %s\n", argv[1]); } else { puts("No luck there."); } } } return 0; }
C
#include <stdio.h> // iteration 144 // sample size 20 // Good tutorial on median filter: http://www.librow.com/articles/article-1 // window size 5 const int signal[20] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20}; const int output[16] = {3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18}; /*N - window_size - 1*/ int main () { //int counter = 0; int i, j, k; int min, temp; int N = 20; int window[5]; int result[20]; int main_result = 0; // Move window through all elements of input signal for (i = 2; i < N - 2; i++) { // Pick up the window elements for (j = 0; j < 5; j++) { window[j] = signal[i - 2 + j]; } // Sort the elements (only half of them) for (j = 0; j < 3; j++) { min = j; for (k = j + 1; k < 5; k++) { if (window[k] < window[min]) { min = k; } //counter = counter + 1; } // Put found minimum element in temp temp = window[j]; window[j] = window[min]; window[min] = temp; } // Get the result result[i - 2] = window[2]; } for (i = 0; i < 16 /*N - (window size -1)*/; i++){ main_result += (result[i] != output[i]); //printf("%i: %i\n", i, result[i]); } //printf("%d\n", counter); //printf("%i\n", main_result); return main_result; }
C
#include <linux/init.h> #include <linux/module.h> #include <linux/slab.h> #include <linux/sched.h> struct task_struct *task; void DFS(struct task_struct *task) { struct task_struct *child; struct list_head *list; printk(KERN_INFO "PID: [%5d] | Name: %s\n", task->pid, task->comm); list_for_each(list, &task->children) { child = list_entry(list, struct task_struct, sibling); DFS(child); } } int list_process_init(void) { printk (KERN_INFO "Loading Module\n"); // Linear printk (KERN_INFO "LINEAR:\n"); for_each_process(task) { printk(KERN_INFO "PID: [%5d] | Name: %s\n", task->pid, task->comm); } // DFS printk (KERN_INFO "DFS:\n"); DFS(task); return 0; } void list_process_exit(void) { printk(KERN_INFO "Removing Module\n"); } module_init(list_process_init); module_exit(list_process_exit);
C
#include "sum.h" #include "sub.h" void main(void) { printf("a + b = %d\n", sum(3, 4)); printf("a - b = %d\n", sub(3, 4)); }
C
/** * hellojni.c */ #include <string.h> #include <jni.h> #include <android/log.h> #define LOG_TAG "libhellojni" #define LOGI(...) __android_log_print(ANDROID_LOG_INFO,LOG_TAG,__VA_ARGS__) #define LOGE(...) __android_log_print(ANDROID_LOG_ERROR,LOG_TAG,__VA_ARGS__) jstring Java_com_example_appuidroid_JniCallerActivity_stringFromJNI(JNIEnv* env, jobject thiz) { jstring jstr; jclass clazz; jmethodID method; jmethodID method2; jobject result; const char *str; jstr = (*env)->NewStringUTF(env, "The string comes from jni."); clazz = (*env)->FindClass(env, "com/example/appuidroid/JniCallerActivity"); if (clazz == 0) { LOGE("find class failed"); return NULL; } method = (*env)->GetMethodID(env, clazz, "messageMe", "(Ljava/lang/String;)Ljava/lang/String;"); if (method == 0) { LOGE("find method failed"); return NULL; } result = (*env)->CallObjectMethod(env, thiz, method, jstr); if (result == 0) { LOGE("call method, but result is empty."); return NULL; } method2 = (*env)->GetMethodID(env, clazz, "messageMe2", "(Ljava/lang/String;)V"); if (method2 == 0) { LOGE("find method2 failed!!!"); return NULL; } (*env)->CallVoidMethod(env, thiz, method2, jstr); str = (*env)->GetStringUTFChars(env, (jstring)result, NULL); LOGI("call method result:%s\n", str); return (*env)->NewStringUTF(env, str); /** return (*env)->NewStringUTF(env, "hello world"); */ }
C
#ifndef _HASH_H #define _HASH_H #define BITS_PER_CHAR (2) // Number of bits used per nucleotide #define MAX_KMER_SIZE (((sizeof(unsigned int) * 8)/BITS_PER_CHAR) - 1) // Recommended max kmer size (15) #define A 0x0 // 0b00 #define C 0x1 // 0b01 #define G 0x2 // 0b10 #define T 0x3 // 0b11 // Hashes a kmer; h(x) = ((djb2(x) + binary(x)) ^ seed) unsigned int hash(const char *str, unsigned int seed); #endif
C
/*********************************************************** > File Name: exec_ps.c > Author: Kwong > Mail: [email protected] > Created Time: 2021年01月27日 星期三 13时51分44秒 > Modified Time:2021年01月27日 星期三 14时20分26秒 *******************************************************/ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <pthread.h> #include <stdio.h> #include <fcntl.h> int main(int argc,char* argv[]) { int fd; fd = open("ps.out", O_WRONLY | O_CREAT | O_TRUNC, 0644); if(fd < 0) { perror("open ps.out error"); exit(1); } dup2(fd, STDOUT_FILENO); execlp("ps", "ps", "ax", NULL); perror("execlp error"); return 0; }
C
//Created by Rahul Goel #include <stdio.h> int main() { int n; scanf("%d", &n); int arr[100005] = {0}; int ans[100005] = {0}; for(int i=1; i<=n; i++) scanf("%d", &arr[i]); for(int i=1; i<=n; i++) ans[arr[i]]=i; for(int i=1; i<=n; i++) printf("%d ", ans[i]); printf("\n"); return 0; }
C
/* envinit --- intialize the environment */ /* ** Initialize the environment a la Unix. ** Set up a bunch of strings of the form ** name=value ** sorted on name. The names and values ** are the user's shell variables. ** Make everything available through the ** variable environ and the getenv() routine. ** ** For use under bare primos, getenv returns NULL, and ** environ is set to NULL. This is conditionally compiled in, ** and handled by the build procedures. */ /* maximum length of the name and value of a variable */ /* maximum number of variables we'll allow */ #define MAXVAR 50 #define MAXVAL 250 #define MAXENV 256 #define MAXBUF 1024 char **environ = NULL; /* available for the outside world */ #ifndef STAND_ALONE /* to run under bare primos (shudder!) */ static char env[MAXBUF]; /* holds the strings */ static char *envptr[MAXENV+1]; /* points to them, sort this array */ static int no_vars; /* keep count */ /* The static functions must come first to avoid a bogus error form c1 */ #define swap(x,y) (temp = x, x = y, y = temp) static int compare(s1,s2) char *s1,*s2; { int i; for(i = 0; s1[i] == s2[i]; i++) if(s1[i] == '\0') return(0); /* strings are equal */ else if(s1[i] == '=' || s2[i] == '=') return((unsigned) s1[i-1] - (unsigned) s2[i-1]); /* loop broken. either chars equal or not */ return((unsigned) s1[i] - (unsigned) s2[i]); /* <0 if s1 < s2, >0 if s1 > s2 */ } static sort() { char *temp; int i,j; int incr; int n; /* shell sort */ n = no_vars; incr = n / 2; while(incr > 0) { for (i = incr + 1; i <= n; i++) { j = i - incr; while(j > 0) { if(compare(envptr[j-1], envptr[j+incr-1]) > 0) { swap(envptr[j-1], envptr[j+incr-1]); j -= incr; } else break; } /* end while */ } /* end for */ incr /= 2; } /* end while */ } #endif /* envinit --- initialize the environment */ envinit() { #ifndef STAND_ALONE int i, j, k, l; char value[MAXVAL+1]; int svscan(), svget(); /* get variables and values respectively */ static int first = TRUE; static int status[3] = { 0, 0, 0 }; if(first) first = FALSE; else return; /* initialize the environment only once */ /* string the name=value groups end to end */ for(i = j = 0; i < MAXBUF && j <= MAXENV && (k = svscan(&env[i], MAXVAR, status)) != EOF; j++) { l = svget(&env[i], &env[i+k+1], MAXVAL); env[i+k] = '='; envptr[j] = & env[i]; i += k + l + 1 + 1; /* leave room for the EOS */ } envptr[j] = NULL; no_vars = i; if(i >= MAXENV) { fprintf(stderr,"envinit(): too many variable in environment, "); fprintf(stderr,"using only the first %d variables\n",MAXENV); } if(j >= MAXBUF) { fprintf(stderr, "envinit(): too many characters in environment, "); fprintf(stderr, "using only the first %d characters\n", MAXBUF); } no_vars = j; sort(); /* sort the little devils */ environ = envptr; #endif } /* getenv --- return value of name=value pair from environment */ char *getenv (var) char *var; { #ifndef STAND_ALONE static int first = TRUE; int i,j; int low, mid, high, val; if(first) { first = FALSE; if(environ == NULL) envinit(); } /* use binary search */ i = val = 0; j = strlen(var); low = 0; high = no_vars - 1; mid = (high + low) / 2; while(low < high) { val = strncmp(var, environ[mid], j); if(val == 0) /* found */ break; else if(val < 0) /* var < environ[i] */ high = mid - 1; else /* var > environ[i] */ low = mid + 1; mid = (high + low) / 2; } if(strncmp(var, environ[mid], j) == 0) /* found */ i = mid; else /* not found */ return(NULL); if(environ[i] != NULL) /* got it */ { for(j = 0; environ[i][j] != '='; j++) ; /* skip over name */ j++; /* skip over '=' */ return(&environ[i][j]); } else return(NULL); #else return (NULL); #endif }
C
#include<stdio.h> #include<stdlib.h> #include<string.h> #include<unistd.h> char str[100]; static char *ptr; char *tokenize(char* string) { char *p; if(string != NULL) { ptr=string; p=string; } else { if(*ptr == '\0') return NULL; p=ptr; } while(*ptr != '\0') { while((*ptr==' ' || *ptr=='\t')) { if(ptr == p) { p++; ptr++; } else { *ptr='\0'; ptr++; return p; } } ptr++; } return p; } int main() { FILE *inputFile; FILE *outputFile; char c; int i; char *p_str,*token; char *tokens[100]; char input[100]; //char output[1024]; //char inFile[100]; char outFile[100]; while(1) { outputFile=NULL; inputFile=NULL; i=0; for(int i=0;i<99; i++)//make sure inputs are null { tokens[i]='\0'; input[i]='\0'; outFile[i]='\0'; //inFile[i]='\0'; } printf("\nTowns_Shell: "); scanf("%[^\n]",str); while((c = getchar()) != '\n' && c != EOF);//eat the \n at the end of scanf for (i=0, p_str=str; ; i++, p_str=NULL)//tokenize everything { token = tokenize(p_str); if (token == NULL) break; tokens[i]=token; } i=1; while(tokens[i]!='\0')//parse tokens into varius pieces { if(*tokens[i]=='<') { i++; inputFile=fopen(tokens[i],"r"); //fscanf(inputFile, "%c", input); fscanf(inputFile, "%[^\n]", input); fclose(inputFile); } else if(*tokens[i]=='>') { i++; outputFile=fopen(tokens[i], "w"); } else { for(int j=0;j<strlen(tokens[i]);j++) { input[(int)strlen(input)]=tokens[i][j]; } } i++; } //printf("\n%s\n", input); //printf("\ninFile: %s",inFile); //printf("\noutFile: %s",outFile); if(strcmp(tokens[0],"cd")==0) { if (chdir(input) != 0) perror("chdir() error()"); } else if(strcmp(tokens[0],"pwd")==0) { char cwd[1024]; if (chdir("./") != 0) perror("chdir() error()"); else { if (getcwd(cwd, sizeof(cwd)) == NULL) perror("getcwd() error"); else if(strcmp(outFile,"")!=0) fprintf(outputFile, "%s/\n", cwd); else printf("%s/\n", cwd); } } else if(strcmp(tokens[0],"exit")==0) { exit(0); } else//not built in { pid_t pid; // fork another process pid = fork(); if (pid < 0) //error { fprintf(stderr, "Fork Failed"); exit(-1); } else if (pid == 0) //child process started { char *cmd[]={tokens[0],input,(char *)0}; if(strcmp(input,"")==0)//0 if same { //printf("\n null input\n"); cmd[1]=NULL; } if(strcmp(outFile,"")!=0) outputFile=freopen(outFile, "w+", stdout); execvp(tokens[0], cmd); } else //parrent process { // parent will wait for the child to complete wait(NULL); //printf ("Child Complete"); //exit(0); } } } }
C
// Basic Console Output. #include <stdint.h> #include <string.h> #include <console.h> #define CONSOLE_HEIGHT 25 #define CONSOLE_WIDTH 80 #define MAX_PAGE_STORAGE 3 #define PAGE_SIZE CONSOLE_HEIGHT * CONSOLE_WIDTH #define CONSOLE_STORAGE PAGE_SIZE * MAX_PAGE_STORAGE #define DEFAULT_COLOUR 0x1F //Array of characters storing a buffer of characters. uint16_t _pageStored[CONSOLE_STORAGE] = { [0 ... CONSOLE_STORAGE - 1] = (DEFAULT_COLOUR << 8) }; uint16_t *_pageOffset = _pageStored + (PAGE_SIZE * 2); // Video memory uint16_t *_videoMemory = (uint16_t*) 0xB8000; // Current cursor position uint8_t _cursorX = 0; uint8_t _cursorY = 0; int _currPage = MAX_PAGE_STORAGE - 1; // Current color uint8_t _colour = DEFAULT_COLOUR; char stringBuffer[40]; char hexChars[] = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'}; // Write byte to device through port mapped io void OutputByteToVideoController(unsigned short portid, unsigned char value) { asm volatile("movb %1, %%al \n\t" "movw %0, %%dx \n\t" "out %%al, %%dx" : : "m" (portid), "m" (value)); } // Update hardware cursor position void UpdateCursorPosition(int x, int y) { uint16_t cursorLocation = y * 80 + x; // Send location to VGA controller to set cursor // Send the high byte OutputByteToVideoController(0x3D4, 14); OutputByteToVideoController(0x3D5, cursorLocation >> 8); // Send the low byte OutputByteToVideoController(0x3D4, 15); OutputByteToVideoController(0x3D5, cursorLocation); } // Display the Page. // @param the page to display. void DisplayPage(size_t pageToDisplay) { if (pageToDisplay > MAX_PAGE_STORAGE) { return; } uint16_t* offset = _pageStored + ((pageToDisplay * PAGE_SIZE)); for (int i = 0; i < PAGE_SIZE; i++) { _videoMemory[i] = offset[i]; } //Hide the cursor on non pages. if (pageToDisplay != MAX_PAGE_STORAGE - 1) { UpdateCursorPosition(0, CONSOLE_HEIGHT+1); } else { UpdateCursorPosition(_cursorX, _cursorY); } } // Scroll Page Up void ConsoleScrollPageDown() { if (_currPage > 0) { _currPage--; DisplayPage(_currPage); } } // Scroll Page Down void ConsoleScrollPageUp() { if (_currPage < MAX_PAGE_STORAGE - 1) { _currPage++; DisplayPage(_currPage); } } void Scroll() { if (_cursorY >= CONSOLE_HEIGHT) { uint16_t attribute = _colour << 8; // Move current display up one line int line25 = (CONSOLE_HEIGHT - 1) * CONSOLE_WIDTH; memcpy(_pageStored, _pageStored + CONSOLE_WIDTH, ((CONSOLE_HEIGHT * CONSOLE_WIDTH) * MAX_PAGE_STORAGE) * 2); for (int i = 0; i < line25; i++) { _videoMemory[i] = _videoMemory[i + CONSOLE_WIDTH]; _pageOffset[i] = _videoMemory[i]; } // Clear the bottom line for (int i = line25; i < line25 + 80; i++) { _videoMemory[i] = attribute | ' '; _pageOffset[i] = _videoMemory[i]; } _cursorY = 25; } } // Displays a character void ConsoleWriteCharacter(unsigned char c) { // Go down to the normal if we're print this.' if(_currPage != MAX_PAGE_STORAGE - 1) { _currPage = MAX_PAGE_STORAGE - 1; DisplayPage(MAX_PAGE_STORAGE - 1); } uint16_t attribute = _colour << 8; if (c == 0x08 && _cursorX) { // Backspace character _cursorX--; } else if (c == 0x09) { // Tab character _cursorX = (_cursorX + 8) & ~(8 - 1); } else if (c == '\r') { // Carriage return _cursorX = 0; } else if (c == '\n') { // New line _cursorX = 0; _cursorY++; } else if (c >= ' ') { // Printable characters // Display character on screen uint16_t* location = _videoMemory + (_cursorY * CONSOLE_WIDTH + _cursorX); uint16_t* storedLoc = _pageOffset + (_cursorY * CONSOLE_WIDTH + _cursorX); *location = c | attribute; *storedLoc = *location; _cursorX++; } // If we are at edge of row, go to new line if (_cursorX >= CONSOLE_WIDTH) { _cursorX = 0; _cursorY++; } // If we are at the last line, scroll up if (_cursorY >= CONSOLE_HEIGHT) { Scroll(); _cursorY = CONSOLE_HEIGHT - 1; } //! update hardware cursor UpdateCursorPosition (_cursorX, _cursorY); } void ConsoleWriteInt(unsigned int i, unsigned int base) { int pos = 0; if (i == 0 || base > 16) { ConsoleWriteCharacter('0'); } else { while (i != 0) { stringBuffer[pos] = hexChars[i % base]; pos++; i /= base; } while (--pos >= 0) { ConsoleWriteCharacter(stringBuffer[pos]); } } } // Sets new font colour and returns the old colour unsigned int ConsoleSetColour(const uint8_t c) { unsigned int t = (unsigned int)_colour; _colour = c; return t; } // Set new cursor position void ConsoleGotoXY(unsigned int x, unsigned int y) { // Go to the current page, first. DisplayPage(MAX_PAGE_STORAGE - 1); if (_cursorX <= CONSOLE_WIDTH - 1) { _cursorX = x; } if (_cursorY <= CONSOLE_HEIGHT - 1) { _cursorY = y; } // update hardware cursor to new position UpdateCursorPosition(_cursorX, _cursorY); } // Returns cursor position void ConsoleGetXY(unsigned* x, unsigned* y) { if (x == 0 || y == 0) { return; } *x = _cursorX; *y = _cursorY; } // Return horzontal width int ConsoleGetWidth() { return CONSOLE_WIDTH; } // Return vertical height int ConsoleGetHeight() { return CONSOLE_HEIGHT; } //! Clear screen void ConsoleClearScreen(const uint8_t c) { _colour = c; uint16_t blank = ' ' | (c << 8); size_t i = 0; for (; i < PAGE_SIZE; i++) { _pageStored[i] = blank; _videoMemory[i] = blank; } // then ensure we also clear the storage. for (; i < (MAX_PAGE_STORAGE * PAGE_SIZE); i++) { _pageStored[i] = blank; } ConsoleGotoXY(0, 0); } // Returns the current colour uint8_t ConsoleGetCurrentColour() { return _colour; } // Display specified string void ConsoleWriteString(const char* str) { if (!str) { return; } while (*str) { ConsoleWriteCharacter(*str++); } }
C
#include <stdio.h> #include <stdlib.h> int main() { char firstn[20],lastn[20]; float creditM,gradeM,creditE,gradeE; printf("Enter first name : "); scanf("%s",firstn); printf("Enter last name : "); scanf("%s",lastn); printf("Mathematic : #credit #grade(0-4) : "); scanf("%f %f",&creditM,&gradeM); printf("English : #credit #grade(0-4) : "); scanf("%f %f",&creditE,&gradeE); float GPA = ((creditM*gradeM)+(creditE*gradeE))/(creditM+creditE); printf("GPA of %s %s is %0.2f ",firstn,lastn,GPA); return 0; }
C
//MultiThreading #include<stdio.h> #include<pthread.h> #include <unistd.h> void* myturn(void * arg) { while(1) { sleep(1); printf("My Turn\n"); } return NULL; } void yourturn() { while(1) { printf("your Turn\n"); sleep(2); } } void main() { pthread_t newThread; pthread_create(&newThread,NULL,myturn,NULL); yourturn(); }
C
//һֻdzһΣֶΡ // //дһҳֻһε֡ #include<stdio.h> //#include<string.h> ////char *strtok(char *str, const char *delim){ //// ////} // int main() { int a[] = { 1, 4, 6, 8, 0, 6, 3, 1, 4, 3, 5, 7, 8, 7, 5, 9 }; for (int i = 0; i < (sizeof(a) / sizeof(a[0])-1); i++){ if (a[i]!=-1) for (int j = i+1; j < sizeof(a) / sizeof(a[0]); j++){ if (a[j] == a[i]){ a[j] = -1; a[i] = -1; break; } } } for (int i = 0; i < sizeof(a) / sizeof(a[0]); i++){ if (a[i] != -1){ printf("%d ", a[i]); } } return(0); }
C
#include <stdio.h> #include <stdlib.h> #include "employe.h" typedef struct employe { char LastName[20]; char FistName[20]; int ID; int Age; char gender; int ph_num; char email; }; int dimension(); int menu(); void ajouter_emp(employe *E) void modifier_emp(employe *E) void supprimer_emp(employe *E) int chercher_emp() void afficher_emp(employe *E) int main() { int choix; int N; employe E[50]; N=dimension() do{ choix=menu(); switch(choix) { case 1: ajouter_emp(E,&N); break; case 2: modifier_emp(E,&N); break; case 3: supprimer_emp(E,&N); break; case 4: chercher_emp(); break; case 5: Afficher_emp(E,N); break; } } while(choix!=0); }
C
#include<stdio.h> #include<string.h> struct Student{ int roll; char name[20]; }; void main(){ struct Student s1; s1.roll = 1997; strcpy(s1.name,"Pavan"); printf("\nRoll no.: %d\n",s1.roll); printf("\nname of student.: %s\n",s1.name); }
C
/************************************************************** Description : Implements an abstract data type representing a collection of Sale structs. Includes interface functions as well as functions to be used by the main. **************************************************************/ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "Sales.h" #include "Date.h" // creates new sales list by allocating memory SalesList *salesList_new() { // allocate memory SalesList *salesList = (SalesList*)malloc(sizeof(SalesList)); // check allocation was successful if (salesList == NULL) { fprintf(stderr, "Unable to allocate memory in salesList_new()\n"); exit(EXIT_FAILURE); } // set first and last node to null salesList->first = NULL; salesList->last = NULL; // return new list return salesList; } // add a stock item to the end of the list void salesList_add(SalesList *salesList, Sale *sale) { // allocate memory to the new node Node2* node =(Node2*)malloc(sizeof(Node2)); // check allocation was successful if (node == NULL) { fprintf(stderr, "Unable to allocate memory in salesList_add()\n"); exit(EXIT_FAILURE); } // store sale with node node->sale = sale; // set next node to null node->next = NULL; // check if last node of list is null if (salesList->last == NULL) { // if null, then store node in first/last node of list salesList->first = salesList->last = node; } else { // store node in last node of list salesList->last = salesList->last->next = node; } } // insert a sale at start of list void salesList_insert(SalesList *salesList, Sale *sale) { // allocate memory to new node Node2* node =(Node2*)malloc(sizeof(Node2)); // check allocation was successful if (node == NULL) { fprintf(stderr, "Error: Unable to allocate memory in salesList_add()\n"); exit(EXIT_FAILURE); } // store sale in new node node->sale = sale; // set next node to first node of list node->next = salesList->first; // if first node of list is null if(salesList->first == NULL) { // store new node in first/last node of list salesList->first = salesList->last = node; } else { // store new node at start of list salesList->first = node; } } // get length of list int SalesList_length(SalesList *salesList) { int length = 0; // loop over all nodes and count for (Node2* node = salesList->first; node != NULL; node = node->next) { // increment length length++; } return length; } // clear list from memory void salesList_clear(SalesList *salesList) { // loop until first node of list is empty while (salesList->first != NULL) { // store first node Node2* node = salesList->first; // store first node of list as next node salesList->first = node->next; // clear memory for node free(node); } // set last node to null salesList->last = NULL; } // print all sale items from list void salesList_print(SalesList *salesList) { // loop through every node until null for(Node2 *node = salesList->first; node != NULL; node = node->next){ // print sale sale_print(node->sale); } } // add sale to sales list void salesList_addFromFile(SalesList *salesList, InventoryList *inventoryList, char file[], SalesList *failList) { // open file FILE *readin = fopen(file, "r"); // check file opened if( readin == NULL) { printf("Unable to open %s.\n", file); exit(EXIT_FAILURE); } // create new sale Sale *complete; Sale *fail; // store each line char line[255]; // loop through file line by line while(fgets(line, sizeof(line), readin) != NULL){ // store each part of line seperated by comma and remove whitespace char* tempDate = removeWhitespace(strtok(line, ",")); char* tempCode = removeWhitespace(strtok(NULL, ",")); char* tempQuantity = removeWhitespace(strtok(NULL, ",")); // covert quantity into an int int quantity = atoi(tempQuantity); // seperate date string by / and convert to int int tempDay = atoi(strtok(tempDate, "/")); int tempMonth = atoi(strtok(NULL, "/")); int tempYear = atoi(strtok(NULL, "/")); // create new date Date *newDate; // make instance of date with temp ints newDate = date_new(tempDay, tempMonth, tempYear); int saleComplete; // reduce quantity of item based on sale saleComplete = inventoryList_reduceQuantity(inventoryList, tempCode, quantity); // if sale failed then output message if (saleComplete == 0){ fail = sale_new(newDate, tempCode, quantity); salesList_add(failList, fail); } else { // if sale was successful then make new sale instance complete = sale_new(newDate, tempCode, quantity); // add sale to list salesList_add(salesList, complete); } } } void salesList_printToFile(SalesList *salesList, char file[]) { FILE *f = fopen(file, "w"); if (f == NULL) { printf("Error opening file!\n"); exit(1); } for(Node2 *node = salesList->first; node != NULL; node = node->next){ int day = node->sale->date->day; int month = node->sale->date->month; int year = node->sale->date->year; char *code = node->sale->code; int quantity = node->sale->quantity; fprintf(f,"%d/%d/%d,%s,%d\n", day, month, year, code, quantity); } }
C
#include <stdio.h> int main() { int cnt; scanf("%d", &cnt); getchar(); int pairs[cnt]; int array[cnt]; int max = 0; for (int i = 0; i < cnt; i++) { //array[i]=getchar()-'0'; scanf("%d", array + i); if (i == 0) pairs[i] = 1; else if ( pairs[i-1] -1 < 0 || array[pairs[i - 1] - 1] == array[i]) { int not_pair = 1; int p; for (p = pairs[i - 1]; p < i; p++) { if (array[p] == array[i]) not_pair--; else not_pair++; if (not_pair == 0) break; } pairs[i] = p + 1; } else { if( pairs[i-1] - 2 < 0) pairs[i] = pairs[i-1] - 1; else pairs[i] = pairs[pairs[i - 1] - 2]; } int len = i - pairs[i] + 1; max = len > max ? len : max; } printf("%d",max); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include<string.h> #include <errno.h> #include <sys/types.h> #include <sys/ipc.h> #include <sys/msg.h> #define PERMISSIONS 0777 // Definition of Message Buffer struct messageBuffer { long mtype; char data[1024]; }; // Global Declaration of Message Buffer Object struct messageBuffer object; // Global Data for Variables int msqid; int string_status; key_t key; // Function to receive the data from message queue. void receiveMessages(){ while(1) { // Trying to retrieve the data from message queue by checking the condition. // If there is any error, while retrieving the data then // condition will throw an error and exits the function. if (msgrcv(msqid, &object, sizeof(object.data), 0, 0) == -1) { perror("msgrcv"); exit(1); } printf("received: \"%s\"\n", object.data); string_status = strcmp(object.data,"end"); if (string_status == 0) break; } } int main() { // Creating the unique Identifier for the message queue. if ((key = ftok("messagequeue.txt", 'B')) == -1) { perror("ftok"); exit(1); } // Connecting the Message Queue. if ((msqid = msgget(key, PERMISSIONS)) == -1) { // connect to the queue printf("Unable to Create the Message Queue.\n"); perror("msgget"); exit(1); } printf("Message Queue is ready to receive messages.\n"); // Calling the receive message function to reterive the data from message queue. receiveMessages(); printf("Message Queue is done with receiving messages.\n"); return 0; }
C
/** * socket server (connectionless) * * Copyright (C) 2016 Jinbum Park <[email protected]> */ #include "common.h" int main(int argc, char **argv) { char msg[MSG_SIZE_MAX]; struct sockaddr_un server_addr; int sock; ssize_t nread; struct sockaddr_storage sa; socklen_t sa_len; /* create socket */ if((sock = socket(AF_UNIX, SOCK_DGRAM, 0)) == -1) { printf("socket error : %s\n", strerror(errno)); return -1; } strncpy(server_addr.sun_path, SOCKET_SERVER_NAME, sizeof(SOCKET_SERVER_NAME)); server_addr.sun_family = AF_UNIX; unlink(SOCKET_SERVER_NAME); if(bind(sock, (struct sockaddr*)&server_addr, sizeof(server_addr)) == -1) { printf("bind error : %s\n", strerror(errno)); goto out; } while(1) { /* read msg */ sa_len = sizeof(sa); nread = recvfrom(sock, msg, sizeof(msg), 0, (struct sockaddr*)&sa, &sa_len); if(nread == 0 || (int)nread == -1) { printf("recvfrom error : %s\n", strerror(errno)); break; } else if(nread == sizeof(END_MSG)) { printf("end msg : %s\n", msg); break; } /* prepare msg */ strncpy(msg, REPLY_MSG, sizeof(REPLY_MSG)); /* send reply */ if(sendto(sock, msg, sizeof(REPLY_MSG), 0, (struct sockaddr*)&sa, sa_len) == -1) { printf("sendto error : %s\n", strerror(errno)); break; } } out: /* close socket */ close(sock); unlink(SOCKET_SERVER_NAME); return 0; }
C
#include<stdio.h> int sumd(int); int main() { int n,s; printf("\nEnter num:"); scanf("%d",&n); s=sumd(n); printf("\nSum of digits:%d \n",s); return 0; } int sumd(int num) { int s; if(num>0) s=(num%0)+sumd(num/10); return s; }
C
#define N_RAND 1000000000 #include "randomRSA.h" /** This program generates N_RAND random uniform numbers using the KISS RNG. * Expects a seed as an argument, otherwise runs with a default seed. */ int main(int argc, char * argv[]) { long seed; long i; double k; seed = 77777777777777; /*if (argc == 1) {*/ /*printf("Running with default seed: %ld\n", seed);*/ /*}*/ /*else {*/ /*seed = (long) argv[1];*/ /*}*/ /*Initialize the RNG using the seed*/ k = 0; randomRSA_init(); for (i=0; i<N_RAND; ++i) { k = randomRSA(); /*For generating the numbers to file. Ruins time benchmarks.*/ } printf("%2.8f\n", k); return 0; }
C
/* * Test Program for GA * This is to test GA_Create (is a collective operation) * * GA_Create -- used to create a global array using handles like 'g_A' * Here used GA_Inquire to verify that g_A hanle returns the right values of created_array */ #include<stdio.h> #include"mpi.h" #include"ga.h" #include"macdecls.h" #include"ga_unit.h" #define SIZE 10 #define MAX_DIM 7 int main(int argc, char **argv) { int rank, nprocs, i, j; int g_A, g_B; int dims[MAX_DIM], val=4, ndim, re; MPI_Init(&argc, &argv); MPI_Comm_rank(MPI_COMM_WORLD, &rank); MPI_Comm_size(MPI_COMM_WORLD, &nprocs); MA_init(C_INT, 1000, 1000); GA_Initialize(); for(i=1; i<=MAX_DIM; i++) { ndim=i; dims[i]=SIZE; // for(j=0; j<ndim; j++) g_A = NGA_Create(C_INT, ndim, dims, "array_A", NULL); g_B = NGA_Create(C_INT, ndim, dims, "array_B", NULL); if(!g_A) GA_Error("GA Error: no global array exists \n", ndim); if(!g_B) GA_Error("GA Error: no global array exists \n", ndim); } GA_Sync(); GA_Fill(g_A, &val); re=GA_Solve(g_A, g_B); if(re==0) printf("Cholesky Fact is Successful \n"); else if (re >0) printf("Cholesky Fact couldn't be completed \n"); else printf("An Error occured\n"); if(rank == 0) GA_PRINT_MSG(); GA_Destroy(g_A); GA_Destroy(g_B); GA_Terminate(); MPI_Finalize(); } /* * TO-DO : assign SIZE to a bigger value */
C
//HR easy challenge: insertion sort (part 2, the full sorting!) // Insertion sort: // Input line 1: number of elements to be sorted. // Input line 2: elements to be sorted. // Output: each step of insertion sort #include <stdio.h> #include <string.h> #include <math.h> #include <stdlib.h> #include <assert.h> void insertionSort(int ar_size, int * ar) { int V; V = ar[ar_size-1]; //last element (unsorted one) int curr_i; curr_i = ar_size - 2; //start from last but one element while(curr_i>=0 && ar[curr_i]>V){ //horrible errors arising from curr_i becoming negative. Invisible errors, as in, the sorting goes fine, but you see unnecessary #shifting operations===> more time lost ar[curr_i+1] = ar[curr_i]; curr_i--; } ar[curr_i+1] = V; return; } int main(void) { int _ar_size; scanf("%d", &_ar_size); int _ar[_ar_size], _ar_i; for(_ar_i = 0; _ar_i < _ar_size; _ar_i++) scanf("%d", &_ar[_ar_i]); int i, sub_ar_size, j; sub_ar_size = 1; for(i = 1; i < _ar_size; i++){ sub_ar_size++; insertionSort(sub_ar_size, _ar); for(j = 0; j < _ar_size; j++) printf("%d ", _ar[j]); printf("\n"); } return 0; }
C
/***************************************************************************** * * Copyright (c) 2011, CEA * 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. * * Neither the name of CEA, nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS AND 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 <ArrOfBit.h> #include <string.h> implemente_instanciable_sans_constructeur_ni_destructeur(ArrOfBit,"ArrOfBit",Objet_U) const unsigned int ArrOfBit::SIZE_OF_INT_BITS = 5; const unsigned int ArrOfBit::DRAPEAUX_INT = 31; // Description: Constructeur d'un tableau de taille n, non initialise ArrOfBit::ArrOfBit(entier n) { taille = 0; data = 0; resize_array(n); } // Description: Destructeur. ArrOfBit::~ArrOfBit() { if (data) delete[] data; data = 0; } // Description: Constructeur par copie (deep copy) ArrOfBit::ArrOfBit(const ArrOfBit & array) { taille = 0; data = 0; operator=(array); } // Description: // Taille en "int" du tableau requis pour stocker un tableau de bits // de taille donnees. entier ArrOfBit::calculer_int_size(entier taille) const { assert(taille >= 0); entier siz = taille >> SIZE_OF_INT_BITS; if (taille & DRAPEAUX_INT) siz++; return siz; } // Description: Change la taille du tableau et copie les donnees // existantes. Si la taille est plus petite, les donnees sont // tronquees, et si la taille est plus grande, les nouveaux elements // ne sont pas initialises. ArrOfBit & ArrOfBit::resize_array(entier n) { if (taille == n) return *this; assert(n >= 0); if (n > 0) { entier oldsize = calculer_int_size(taille); entier newsize = calculer_int_size(n); unsigned int * newdata = new unsigned int[newsize]; entier size_copy = (newsize > oldsize) ? oldsize : newsize; if (size_copy) { memcpy(newdata, data, size_copy); delete[] data; } data = newdata; taille = n; } else { delete[] data; // data!=0 sinon taille==n et on ne serait pas ici data = 0; taille = 0; } return *this; } // Description: Operateur copie (deep copy). ArrOfBit & ArrOfBit::operator=(const ArrOfBit & array) { entier newsize = calculer_int_size(array.taille); if (taille != array.taille) { if (data) { delete[] data; data = 0; } if (newsize > 0) data = new unsigned int[newsize]; } taille = array.taille; if (taille) memcpy(data, array.data, newsize * sizeof(unsigned int)); return *this; } // Description: Si la valeur est non nulle, met la valeur 1 dans // tous les elements du tableau, sinon met la valeur 0. ArrOfBit & ArrOfBit::operator=(entier val) { unsigned int valeur = val ? (~((unsigned int) 0)) : 0; entier size = calculer_int_size(taille); entier i; for (i = 0; i < size; i++) data[i] = valeur; return *this; } // Description: Ecriture du tableau. Format: // n // 0 1 0 0 1 0 ... (n valeurs) Sortie& ArrOfBit::printOn(Sortie& os) const { os << taille << finl; entier i; // Un retour a la ligne tous les 32 bits, // Une espace tous les 8 bits for (i = 0; i < taille; i++) { os << operator[](i); if ((i & 7) == 7) os << " "; if ((i & 31) == 31) os << finl; } // Un retour a la ligne si la derniere ligne n'etait pas terminee if (i & 31) os << finl; return os; } // Description: Lecture du tableau. Format: // n // 0 1 0 0 1 0 ... (n valeurs) Entree& ArrOfBit::readOn(Entree& is) { entier newsize; is >> newsize; resize_array(newsize); operator=(0); entier i; for (i = 0; i < taille; i++) { entier bit; is >> bit; if (bit) setbit(i); } return is; }
C
#include "linked_list.h" Node *concate(Node *, Node *); int main() { int n1, n2, i, data; Node *concatedList = NULL; Node *list1 = NULL; Node *list2 = NULL; printf("\nCreate 1st Linked List\n"); printf("\nEnter the no.of Nodes : "); scanf("%d", &n1); //list1 = (Node *)malloc(n1 * sizeof(Node)); for (i = 0; i < n1; i++) { printf("\nEnter the value of the Node : \n"); scanf("%d", &data); list1 = create(list1, data); } printf("\nCreate 2nd Linked List : "); printf("\nEnter the no.of Nodes : "); scanf("%d", &n2); //list2 = (Node *)malloc(n2 * sizeof(Node)); for (i = 0; i < n2; i++) { printf("\nEnter the value of the Node : "); scanf("%d", &data); list2 = create(list2, data); } display(list1); printf("\n"); display(list2); printf("\n"); concatedList = concate(list1, list2); display(concatedList); } Node *concate(Node *list1, Node *list2) { if (list1 == NULL) return list2; else if (list2 == NULL) return list1; else if (list1 == NULL && list2 == NULL) { printf("\nCouldn't found any Data...!!!"); exit(0); } else { Node *p; p = list1; while (p->next != NULL) p = p->next; p->next = list2; } return list1; } /* ================ OUTPUT ================ Create 1st Linked List Enter the no.of Nodes : 3 Enter the value of the Node : 20 Enter the value of the Node : 10 Enter the value of the Node : 30 Create 2nd Linked List : Enter the no.of Nodes : 2 Enter the value of the Node : 15 Enter the value of the Node : 25 ->(20) ->(10) ->(30) ->(15) ->(25) ->(20) ->(10) ->(30) ->(15) ->(25) */
C
#include <stdio.h> #include <stdlib.h> #include <string.h> /* run this program using the console pauser or add your own getch, system("pause") or input loop */ struct _Node; typedef struct _Node* Pos; typedef struct _Node { int el; Pos Next; }_NODE; Pos CreateNode(int); int ReadFromFile(Pos); int Unija(Pos,Pos,Pos); int Presjek(Pos,Pos,Pos); int Print(Pos); int main(int argc, char *argv[]) { Pos head1 = NULL; Pos head2 = NULL; Pos headU = NULL; Pos headP = NULL; char izbor; head1 = CreateNode(1); if(head1 == NULL) return -1; head1->Next = NULL; head2 = CreateNode(1); if(head2 == NULL) return -1; head2->Next = NULL; headU = CreateNode(1); if(headU == NULL) return -1; headU->Next = NULL; headP = CreateNode(1); if(headP == NULL) return -1; headP->Next = NULL; while(izbor != 'q' && izbor != 'Q'){ printf("IZBORNIK:\n"); printf("a) Unos i ispis listi iz datoteke;\n"); printf("b) Unija listi;\n"); printf("c) Presjek listi;\n"); printf("q) Izlaz;\n"); printf("++++++++++++++++++++++++++++++++++++++\n"); printf("Izbor: "); scanf(" %c", &izbor); printf("++++++++++++++++++++++++++++++++++++++\n"); switch(toupper(izbor)){ case 'A': ReadFromFile(head1); Print(head1->Next); ReadFromFile(head2); Print(head2->Next); break; case 'B': Unija(headU,head1->Next,head2->Next); Print(headU->Next); break; case 'Q': break; default: printf("Unesen je pogresan izbor!\n"); break; } } return 0; } Pos CreateNode(int n) { Pos q = NULL; q = (Pos)malloc(n*sizeof(_NODE)); return q; } int ReadFromFile(Pos p){ Pos q = NULL; Pos tmp = NULL; char* buffer = NULL; char* fName = NULL; FILE* fp = NULL; fName = (char *)malloc(40*sizeof(char)); if(fName == NULL) return -1; buffer = (char *)malloc(250*sizeof(char)); if(buffer == NULL) return -1; printf("Unesite ime datoteke(sa .txt): "); scanf(" %s", fName); fp = fopen(fName, "r"); if(fp == NULL) return -1; while(!feof(fp)){ memset(buffer, '\0', 250); tmp = p; fgets(buffer,250, fp); if(strlen(buffer)>0){ q = CreateNode(1); if(q == NULL) return -1; sscanf(buffer, "%d", &q->el); while(tmp->Next != NULL && tmp->Next->el > q->el) tmp = tmp->Next; if(tmp->el == q->el) free(q); q->Next = tmp->Next; tmp->Next = q; } } return 0; } int Print(Pos p) { Pos tmp = p; if(tmp == NULL) return -1; while(tmp != NULL){ printf("%d ", tmp->el); tmp = tmp->Next; } printf("\n"); return 0; } int Unija (Pos U, Pos p1, Pos p2) { Pos tmp1 = p1; Pos tmp2 = p2; Pos tmpU = U; Pos q = NULL; Pos tmp = NULL; if(tmp1 == NULL || tmp2 == NULL) return -1; while(tmp1 != NULL && tmp2 != NULL){ q = CreateNode(1); if(q == NULL) return -1; if(tmp1->el > tmp2->el){ q->el = tmp1->el; tmp1 = tmp1->Next; }else if(tmp1->el < tmp2->el){ q->el = tmp2->el; tmp2 = tmp2->Next; }else{ q->el = tmp1->el; tmp2 = tmp2->Next; tmp1 = tmp1->Next; } q->Next = tmpU->Next; tmpU->Next = q; } if(tmp1 == NULL) tmp = tmp2; else tmp = tmp1; while(tmp != NULL){ q = CreateNode(1); q->el = tmp->el; tmp = tmp->Next; q->Next = tmpU->Next; tmpU->Next = q; } return 0; }
C
/* ** display.c for dante in /home/jacqui_p/rendu/IA/dante/generateur/src/ ** ** Made by Pierre-Emmanuel Jacquier ** Login <[email protected]> ** ** Started on Thu May 19 17:05:19 2016 Pierre-Emmanuel Jacquier ** Last update Thu May 19 17:05:19 2016 Pierre-Emmanuel Jacquier */ #include "generator.h" #include "generator.h" #include <unistd.h> #include <stdlib.h> #include <time.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <stdio.h> void y_one_of_two(int live, short int *two) { if (*two == 0) { if (live) printf("\x1B[44m*\x1B[0m"); else putchar('*'); *two += 1; } else if (*two == 1) { if (live) printf("\x1B[37mX\x1B[0m"); else putchar('X'); *two = 0; } } void x_one_of_two(short int live, int width, int flag) { int i; i = 1; putchar('\n'); if (flag) putchar('X'); while (i < width) { if (live) printf("\x1B[37mX\x1B[0m"); else putchar('X'); i++; if (live) printf("\x1B[44m*\x1B[0m"); else putchar('*'); i++; } } void print_char(t_map *map, int i, int live) { if (live) { if (map[i].index == 0) putchar('X'); else if (map[i].index == 1) printf("\x1B[44m*\x1B[0m"); else if (map[i].index == 6) printf("\x1B[41m*\x1B[0m"); } else { if (map[i].index == 0) putchar('X'); else if (map[i].index == 1) putchar('*'); } } void display_map(t_map *map, short int y, short int live, t_x_y direct) { int i; int j; int line; short int two; two = 0; i = 0; j = 0; line = 0; while (line < direct.y) { while (j < direct.x) { print_char(map, i, live); j++; i++; } if (y) y_one_of_two(live, &two); if (line < direct.y - 1) putchar('\n'); j = 0; line++; } } void display_live(t_map *map, int coord, t_x_y direct) { map[coord].index = 6; system("clear"); display_map(map, 0, 1, direct); printf("\n\n\n"); map[coord].index = 1; usleep(50000); }
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 */ /* Variables and functions */ scalar_t__ str_is_ip6 (char*) ; __attribute__((used)) static void calc_num46(char** ifs, int num_ifs, int do_ip4, int do_ip6, int* num_ip4, int* num_ip6) { int i; *num_ip4 = 0; *num_ip6 = 0; if(num_ifs <= 0) { if(do_ip4) *num_ip4 = 1; if(do_ip6) *num_ip6 = 1; return; } for(i=0; i<num_ifs; i++) { if(str_is_ip6(ifs[i])) { if(do_ip6) (*num_ip6)++; } else { if(do_ip4) (*num_ip4)++; } } }
C
#include "kernel/types.h" #include "kernel/stat.h" #include "user/user.h" int main(int argc, char *argv[]){ int i; int j = 0; int k; int pid; sett(); tc1(); //system call for testing for (i = 0; i < 30; i++) { pid = fork(); if (pid == 0) { //child j = (getpid()) % 2; // ensures independence from the first son's pid when gathering the results in the second part of the program switch(j) { case 0: //CPU‐bound process (CPU): for (k = 0; k < 200; k++){ for (j = 0; j < 1000000; j++){} } break; case 1:// simulate I/O bound process (IO) for(k = 0; k < 800; k++){ sleep(1); } break; } fexit(); //system call to toggle firstexit exit(0); // children exit here } continue; // father continues to spawn the next child } setflag(); while((pid=wait(0))>=0) {} pfreset(); resetflag(); resett(); refexit(); exit(0); }
C
#include "holberton.h" #include <stdio.h> /** * _strspn - gets the length of a prefix substring * @s: the string that we use for searching * @accept: the substring that we search for. * Return: return the number of bytes in the initial segment of s which consist * only of bytes from accept. */ unsigned int _strspn(char *s, char *accept) { int i = 0, j, len = 0, prev_len = 0; while (s[i] != '\0') { for (j = 0; accept[j] != '\0'; j++) { if (s[i] == accept[j]) len++; } if (len == prev_len) return (len); prev_len = len; i++; } return (len); }
C
#ifndef LISTAREVISION_H_INCLUDED #define LISTAREVISION_H_INCLUDED #include "Revision.h" #include "Expediente.h" typedef struct nodoL{Revision revisiones; nodoL * sig; }nodoLista; typedef nodoLista * Lista; //Crea la lista void crearLista(Lista &l); //Verifica si la lista esta vacia boolean listaVacia(Lista l); //Devuelve la fecha del primer elemento de la lista Fecha fechaPrimerElementoListado(Lista l); //PRECONDICION: La lista no puede estar vacia //Agrega una revision al Principio listado void agregarRevisionFront(Lista &l, Revision rev); //Agrega una revision al Final listado void agregarRevisionBack(Lista &l, Revision rev); //Borra una revision en el listado void borrarRevision(Lista &l, long codigo); //PRECONDICION: La revision debe existir //Muesta todas las revisiones realizadas void listarRevisiones (Lista l); //Muestra las revisiones para el expediente void listarRevisionesPorExpediente (Lista l, long codigo); int cantidadRevPorExp(Lista l, long pCodigo); //Devuelvela cantidad de revisiones por fecha int cantidadRevisionesPorFecha(Lista l, Fecha fec1, Fecha fec2); void cantidadRevisionesPorTipo(Lista l, int &pSatisfactorias, int &pIncompletas, int &pPendientes); int mayorCantidadRevisiones(Lista vListaRevisiones); // Abre el archivo para escritura y agrega al archivo los datos de la lista void agregarListaAArchivo(Lista L, String pArchivo); //Abre el archivo para lectura y agrega en la lista los datos de las revisiones, //llamando al procedimiento agregarRevisionBack void leerListaDeArchivo(Lista &L, String pArchivo); //PRECONDICION: validar que exista el archivo #endif // LISTAREVISION_H_INCLUDED
C
/* * Config values, global constants, common functions. * * Copyright (C) 2018 Ben Burns. * * MIT License, see /LICENSE for details. */ #include <stdio.h> // recommended to include stdio before gmp #include <stdlib.h> #include <gmp.h> #include <assert.h> #include <stdarg.h> #include "console.h" #include "global.h" mpf_t g_one; mpf_t g_two; mpf_t g_zero; mpf_t g_epsilon; // internal variables use for calculation. static int _p_init = 0; static mpf_t _t1; static mpf_t _t2; /* * Set the precision of GMP. By default, this is called with PRECISION_BITS. * This only affects variables instantiated after this call. * Initializes some static variables. */ void global_init(mp_bitcnt_t precision, char* str_epsilon) { if (_p_init != 0) { return; } _p_init = 1; mpf_set_default_prec(precision); mpf_init(_t1); mpf_init(_t2); mpf_init_set_ui(g_zero, 0); mpf_init_set_ui(g_one, 1); mpf_init_set_ui(g_two, 2); mpf_init_set_str(g_epsilon, str_epsilon, 10); } /* * Frees any memory used by the global constants defined here. * Frees memory used by static variables. */ void global_free() { if (_p_init != 1) { return; } _p_init = 0; mpf_clear(_t1); mpf_clear(_t2); mpf_clear(g_zero); mpf_clear(g_one); mpf_clear(g_two); mpf_clear(g_epsilon); } /* * Check if a value is less than g_epsilon. * * @f: Value to compare. * * returns: 1 if the absolute value is less than g_epsilon, otherwise 0. */ int global_is_zero(mpf_t f) { mpf_abs(_t1, f); // Compare op1 and op2. Return a positive value if op1 > op2, zero if op1 = op2, and a negative value if op1 < op2. int result = mpf_cmp(_t1, g_epsilon); if (result > 0) { // absolute value is greater than g_epsilon, so it's not zero. return 0; } // absolute value is equal to or less than g_epsilon, so it's "zero" return 1; } /* * Compare a value to zero, within range of g_epsilon. * * @f: Value to compare. * * returns: 0 if the absolute value is less than g_epsilon, * -1 if the value is less than g_zero, * or 1 if the value is greater than g_zero. */ int global_compare_zero(mpf_t f) { mpf_abs(_t1, f); int result = mpf_cmp(_t1, g_epsilon); if (result < 1) { // absolute value is less than or equal to g_epsilon, so it's "zero" return 0; } return mpf_sgn(f); } /* * Compare two values, within range of g_epsilon. * * @f1: First value to compare. * @f2: Second value to compare. * * returns: 0 if the absolute value of the difference of * f1 and f2 is less than g_epsilon, * -1 if f1 is less than f2, * or 1 if f1 is greater than f2. */ int global_compare2(mpf_t f1, mpf_t f2) { mpf_sub(_t1, f1, f2); mpf_abs(_t2, _t1); int result = mpf_cmp(_t2, g_epsilon); if (result < 1) { // absolute value of difference is less than or equal to g_epsilon, so it's "zero" return 0; } return mpf_sgn(_t1); } /* * Prints an error message to stderr in red text. */ void global_error_printf(char *format, ...) { va_list args; va_start(args, format); fprintf(stderr, CONSOLE_RED); vfprintf(stderr, format, args); fprintf(stderr, CONSOLE_RESET); va_end(args); } /* * Checks if a pointer is null, and if so, prints * an error message to stderr in red text then exits. * * @p: pointer to compare to NULL. * @error_msg: message to print. */ void global_exit_if_null(void* p, char* error_msg) { if (p == NULL) { global_error_printf(error_msg); exit(1); } }