language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
#include <stdio.h> #include <sys/socket.h> #include <netinet/in.h> #include <string.h> #include <stdlib.h> #include<math.h> #include<errno.h> #include<signal.h> #define SERV_PORT 5051 void sig_chld(int signo) { pid_t pid; int stat; while ( (pid = waitpid(-1, &stat, WNOHANG)) > 0) printf("child %d terminated\n", pid); return; } int main(int argc, char **argv) { int listenfd, connfd; pid_t childpid; socklen_t clilen; struct sockaddr_in cliaddr, servaddr; void sig_chld(int); listenfd = socket (AF_INET, SOCK_STREAM, 0); bzero (&servaddr, sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_addr.s_addr = htonl(INADDR_ANY); servaddr.sin_port = htons(SERV_PORT); bind(listenfd, (struct sockaddr *) &servaddr, sizeof(servaddr)); listen(listenfd,5); signal (SIGCHLD, sig_chld); /* must call waitpid() */ for ( ; ; ) { clilen = sizeof(cliaddr); if ( (connfd = accept (listenfd, (struct sockaddr *) &cliaddr, &clilen)) < 0) { if (errno == EINTR) continue; /* back to for() */ else printf("accept error"); } if ( (childpid = fork()) == 0) { /* child process */ close(listenfd); /* close listening socket */ exit(0); } close (connfd); /* parent closes connected socket */ } }
C
//Sat Feb 27 10:16:59 UTC 2021 //Write a program to convert decimal to binary //ll #include <stdio.h> #include <stdlib.h> #include <math.h> typedef struct { char *stack_item; //pointer to array of stack values for dynamic allocation by malloc int top; int size; }Stack; void printBinary(unsigned int n); void stackInitMalloc(Stack *, int ); void freeMallocMem(Stack *); void push(Stack *, char); char pop(Stack *); int getSize(Stack *); int isOverflow(Stack *); int isUnderflow(Stack *); int reverseIt(char[], char[]); int main(){ // printBinary(128); int f = reverseIt("/home/slanjo/Programming/C/dta_str/input_text.txt", "/home/slanjo/Programming/C/dta_str/output_text.txt"); if (f) printf("File copied successfully\n"); else printf("Error -- copy failed\n"); return 0; } void push(Stack *s, char value){ // if ( s->top == s->size - 1 ){ // printf("Stack Overflow \n"); // return; if (isOverflow(s)){ char *temp; temp = (char *)malloc(sizeof(char) * s->size * 2); if ( temp == NULL ){ printf("Stack Overflow\n"); return; } int i; for(i=0; i <= s->top; i++){ temp[i] = s->stack_item[i]; } free(s->stack_item); s->stack_item = temp; s->size = s->size * 2; } s->top++; s->stack_item[s->top] = value; } char pop(Stack *s ){ // if (s->top == -1){ if (isUnderflow(s)){ printf("Stack Underflow\n"); return '\0'; } char v = s->stack_item[s->top]; s->top--; return v; } void stackInitMalloc(Stack *s, int size){ s->top = -1; s->stack_item = (char *)malloc(sizeof(char) * size); if ( s->stack_item == NULL ){ printf("Failed to alocate memory\n"); exit(1); } s->size = size; // return; } void freeMallocMem(Stack *s){ if ( s->stack_item != NULL ){ free(s->stack_item); s->top = -1; s->size = 0; } printf("Freed freeMallocMem \n"); return; } int getSize(Stack *s){ return s->size; } int isOverflow(Stack *s){ return s->top == s->size - 1; } int isUnderflow(Stack *s){ return s->top == -1; } int reverseIt(char source[], char dest[]){ FILE *fps, *fpd; const int SIZE = 50; fps = fopen(source, "r"); if(fps == NULL){ printf("Error opening the file %s\n", source); return 0; } fpd = fopen(dest, "w"); if(fpd == NULL){ printf("Errof opening the file %s\n", dest); return 0; } Stack s; stackInitMalloc(&s, SIZE); char buff; buff = fgetc(fps); while(!feof(fps)){ push(&s, buff); buff = fgetc(fps); } while(!isUnderflow(&s)){ fputc(pop(&s), fpd); } fclose(fps); fclose(fpd); freeMallocMem(&s); return 1; }
C
/* * File: Main.c * Author: Armstrong Subero * PIC: 18F4553 w/Ext OSC @ 16MHz ; PLL to 48MHz, 5v * Program: 00_Blink * Compiler: XC8 (v1.38, MPLAX X v5.05) * Program Version: 1.0 * * * Program Description: This Program Allows PIC18F4553 to blink an LED at * 50% duty cycle * * Hardware Description: An LED is connected via a 1k resistor to PIN D0 * * Created September 7th, 2018, 1:28 PM */ /******************************************************************************* * Includes and Defines ******************************************************************************/ #include "18F4553_STD.h" /******************************************************************************* * Function: Main * * Returns: Nothing * * Description: Program entry point ******************************************************************************/ void main(void) { // Configure pin D0 as output TRISDbits.TRISD0 = 0; while(1) { // Toggle PIND0 LATDbits.LATD0 = !LATDbits.LATD0; // Delay 500 ms delay_ms(500); } return; }
C
#include "../inc/getstring.h" uchar* get_string(uint16_t *len) { *len=0; uint16_t capacity=1; uchar* s=(uchar*)malloc(10*sizeof(uchar)); uchar c=getchar(); while(c!='\n') { s[(*len)++]=c; if(*len>=10) { capacity*=2; s=(uchar*)realloc(s, capacity*sizeof(uchar)); } c=getchar(); } s[*len]='\0'; return s; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "util.h" #include "abb.h" #include "avl.h" #define LIMITE 3 int min(int a, int b) { return (a < b ? a : b); } int min3(int a, int b, int c) { return min(a, min(b, c)); } void listarPalavras (No *raizArvore, char *palavra) { if (raizArvore != NULL) { if (distanciaEdicao(getPalavra(raizArvore), palavra) < LIMITE) { printf("\033[1;32m%s\033[00m, ", getPalavra(raizArvore)); } listarPalavras(raizArvore->esq, palavra); listarPalavras(raizArvore->dir, palavra); } } int distanciaEdicao(char *a, char *b) { int m = strlen(a), n = strlen(b); int dp[m+1][n+1]; for (int i=0; i <= m; i++) { dp[i][0] = i; } for (int j=0; j <= n; j++) { dp[0][j] = j; } for (int i=1; i <= m; i++) { for (int j=1; j <= n; j++) { if (a[i-1] != b[j-1]) { dp[i][j] = min3( 1 + dp[i-1][j], 1 + dp[i][j-1], 1 + dp[i-1][j-1]); } else { dp[i][j] = dp[i-1][j-1]; } } } return dp[m][n]; } void *mallocSafe(size_t nbytes) { void *ptr; ptr = malloc(nbytes); if (ptr == NULL) { ERRO(Malloc devolveu NULL!); exit(EXIT_FAILURE); } return ptr; }
C
#include <fcntl.h> #include <unistd.h> #include<sys/stat.h> #include<semaphore.h> #include<stdlib.h> #include <string.h> #include<stdio.h> int main(int argc, char const *argv[]) { char * semname1 = "/SemFile"; char * semname2 = "/SemFile1"; char * fileName = "abc.txt"; sem_t *s1 ,*s2; pid_t p ; int count = 3,retVal; int fd = open(fileName,O_CREAT|O_APPEND|O_WRONLY,0777); printf("%d \n",fd); if(fd < 0) { perror("File Opening Error"); exit(EXIT_FAILURE); } s1 = sem_open(semname1,O_CREAT,0644,1); if(s1 == SEM_FAILED) { perror("Semaphore not created:"); exit(0); } s2 = sem_open(semname2,O_CREAT,0644,0); if(s2 == SEM_FAILED) { perror("Semaphore not created:"); exit(0); } sem_wait(s1); retVal = write(fd,"Child\n",strlen("Child\n")); if(retVal < 0) perror("write:"); sem_post(s2); sem_close(s1); sem_close(s2); /*sem_unlink(semname1); sem_unlink(semname2);*/ return 0; }
C
/* Write a function to multiply all the numbers in a list. */ #include <stdio.h> /* Multiply the elements of a list*/ int multiply(int *list, int elements); int main() { /*--------------------------------------------------- Put the numbers you want to multiply inside the {} ---------------------------------------------------*/ int list[] = {3,4,1,3}; printf("Multilpliaction is is: %i\n",multiply(list,sizeof(list)/4)); return 0; } int multiply(int *list, int elements) { int result = list[0]; for (int i = 1; i < elements; i++) { result = result * list[i]; } return result; }
C
/* ************************************************************************ * file: listrent.c Part of CircleMUD * * Usage: list player rent files * * Written by Jeremy Elson * * All Rights Reserved * * Copyright (C) 1993 The Trustees of The Johns Hopkins University * ************************************************************************* */ #include "conf.h" #include "sysdep.h" #include "structs.h" void Crash_listrent(char *fname); int main(int argc, char **argv) { int x; for (x = 1; x < argc; x++) Crash_listrent(argv[x]); return (0); } void Crash_listrent(char *fname) { FILE *fl; char buf[MAX_STRING_LENGTH]={'\0'}; struct obj_file_elem object; struct rent_info rent; if (!(fl = fopen(fname, "rb"))) { sprintf(buf, "%s has no rent file.\r\n", fname); printf("%s", buf); return; } sprintf(buf, "%s\r\n", fname); if (!feof(fl)) fread(&rent, sizeof(struct rent_info), 1, fl); switch (rent.rentcode) { case RENT_RENTED: strcat(buf, "Rent\r\n"); break; case RENT_CRASH: strcat(buf, "Crash\r\n"); break; case RENT_CRYO: strcat(buf, "Cryo\r\n"); break; case RENT_TIMEDOUT: case RENT_FORCED: strcat(buf, "TimedOut\r\n"); break; default: strcat(buf, "Undef\r\n"); break; } while (!feof(fl)) { fread(&object, sizeof(struct obj_file_elem), 1, fl); if (ferror(fl)) { fclose(fl); return; } if (!feof(fl)) sprintf(buf, "%s[%5d] %s\n", buf, object.item_number, fname); } printf("%s", buf); fclose(fl); }
C
/* ** EPITECH PROJECT, 2021 ** main ** File description: ** main sokoban */ #include "my.h" int move_player(int *x, int *y, int result) { switch (result) { case 66: *y += 1; break; case 65: *y -= 1; break; case 67: *x += 1; break; case 68: *x -= 1; break; } return (result); }
C
//2 tipologie di thread: cons, prod. //5 istanze che fanno codice prod, 1 cons //compito 7.7.11 #include "header.h" #include <stdio.h> #include <stdlib.h> #include <unistd.h> #define NUM_PRODUTTORI 5 #define NUM_CONSUMATORI 1 #define TOTAL NUM_PRODUTTORI+NUM_CONSUMATORI #define DIM 5 #define NUM_PROD 4 #define NUM_CONS 10 //ogni produttore deve fare 4 inserimenti intervallati da tot secondi void*Produttore(void*arg){ //casting Stack*s; s=(Stack*) arg; int i; Elem e; i=0; while(i<NUM_PROD){ e=(Elem) (rand()%11);//si potrebbe anche omettere questo casting StackPush(s,e); printf("[PRODUTTORE] valore prodoto %d\n", e); sleep(1);//generiamo elemento dopo sleep i++; } pthread_exit(NULL); } void*Consumatore(void*arg){ //casting Stack*s; s=(Stack*) arg; int i; i=0; Elem e1, e2; while(i<NUM_CONS){ printf("[CONSUMATORE] Consumo n* %d\n",i+1); e1= StackPop(s); e2= StackPop(s); printf("[CONSUMATORE] HO consmato %d e %d e la somma è %d\n", e1,e2,e1+e2); i++; } pthread_exit(NULL); } int main(){ pthread_t threads[TOTAL]; pthread_attr_t attr; //creiamo puntatore stack Stack* s; Elem e; int i; i=0; srand(time(NULL)); pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_JOINABLE); s=(Stack*) malloc(sizeof(Stack)); StackInit(s, DIM); for(i=0;i<TOTAL; i++){ if(i==0){ pthread_create(&threads[i], &attr, Consumatore, (void*)s); }else{ pthread_create(&threads[i], &attr, Produttore, (void*)s); } } for(i=0;i<TOTAL;i++){ pthread_join(threads[i],NULL); } StackRemove(s); return 0; }
C
#include <stdio.h> int main(){ printf("2. Find the sum of the even-valued terms (under 4.000.000) \ of the Fibonacci sequence.\n"); int u1, u2, u3, count=0; u1=u2=1; do{ u3 = u1+u2; u1 = u2; u2 = u3; if(!(u3 % 2)) count+=u3; } while(u3<4000000); printf("Sum = %d\n", count); return 0; }
C
/* Desenvolva um programa em C que leia 99 números do tipo inteiro do usuário. Separe esses números em pares e ímpares e os armazenem em dois outros vetores chamados vet_par e vet_impar. Em seguida, o programa dever apresentar os resultados na tela. */ #include <stdio.h> #define TAM_VET 99 int main() { printf("\tIntituto Federal da Bahia - IFBA - Campus Barreiras.\n"); printf("\tDisciplina: Estrutura de Dados - Turma 732.\n"); printf("\tProfessor: Djalma A. Lima Filho\n"); printf("\tAluno(a): Lucas Alves Rego \n\n\n"); //Vetores int nums[TAM_VET], vet_par[TAM_VET], vet_impar[TAM_VET]; //Contadores int cont_par = 0, cont_impar = 0; //Leitura dos números for (int cont = 0; cont < TAM_VET; cont++) { printf("Digite um número:\n>>> "); scanf("%i", &nums[cont]); if (nums[cont] % 2 == 0) { vet_par[cont_par] = nums[cont]; cont_par++; } else { vet_impar[cont_impar] = nums[cont]; cont_impar++; } } printf("\nNúmeros pares > "); for (int cont = 0; cont < cont_par; cont++) { printf("%i > ", vet_par[cont]); } printf("\nNúmeros impares > "); for (int cont = 0; cont < cont_impar; cont++) { printf("%i > ", vet_impar[cont]); } return (0); }
C
// toolfunc.c, 159 #include "spede.h" #include "typedef.h" #include "extern.h" void MyBzero(char *p, int byte_size) { int i; for(i=0; i<byte_size; i++){ *p=0; p++; } } void EnQ(int pid, q_t *p) { if(p->len == Q_LEN){ cons_printf("Queue is full.\n"); return; } p->len++; p->q[p->tail] = pid; p->tail = (p->tail+1)%(Q_LEN); } int DeQ(q_t *p) { // return -1 if q is empty int pid; if(p->len == 0) { return -1; } pid = p->q[p->head]; p->head = (p->head+1)%(Q_LEN); p->len--; return pid; } void checkWait() { int temp_pid; q_t temp_q; temp_pid = DeQ(&sleep_q); MyBzero((char *) &temp_q, sizeof (q_t) ); while (temp_pid !=-1){ if (OS_clock == pcb[temp_pid].wake_time) { EnQ(temp_pid, &ready_q); pcb[temp_pid].state = READY; temp_pid = DeQ(&sleep_q); }else { EnQ(temp_pid, &temp_q); temp_pid = DeQ(&sleep_q); } } temp_pid = DeQ(&temp_q); while (temp_pid != -1) { EnQ(temp_pid, &sleep_q); temp_pid = DeQ(&temp_q); } } void MsgEnQ(msg_t *msg_ptr, msg_q_t *msg_q_ptr) { if (msg_q_ptr->len == Q_LEN) { cons_printf("Queue is full.\n"); return; } msg_q_ptr->msg[msg_q_ptr->tail] = *msg_ptr; msg_q_ptr->tail = (msg_q_ptr->tail+1)%(Q_LEN); msg_q_ptr->len++; } msg_t *MsgDeQ(msg_q_t *msg_q_ptr) { msg_t *returnvalue; if (msg_q_ptr->len <1) { cons_printf("Queue is empty!"); return 0; } returnvalue = &(msg_q_ptr->msg[msg_q_ptr->head]); msg_q_ptr->head = (msg_q_ptr->head+1)%(Q_LEN); msg_q_ptr->len--; return returnvalue; } void MyStrcpy(char * dest, char *src) { while (*src != '\0') *dest++ = *src++; *dest = '\0'; }
C
/*====================================================================* * * void syslogd_close_sockets (struct socket *sockets); * * close open sockets; this stops incoming messages from external * sources but syslogd can still post outgoing messages until all * syslogs are closed; * * visit sockets having valid descriptors and address structures; * create an alias pointer for the correct address structure type * then close the socket; for simplicity, alias pointers have the * same name as the structures they point to; * * think of it as having a cat named 'cat' and a dog name 'dog'; * *. Motley Tools by Charles Maier *: Published 1982-2005 by Charles Maier for personal use *; Licensed under the Internet Software Consortium License * *--------------------------------------------------------------------*/ #ifndef SYSLOGD_CLOSE_SOCKETS_SOURCE #define SYSLOGD_CLOSE_SOCKETS_SOURCE #include <unistd.h> #include <sys/un.h> #include <errno.h> #include "../linux/syslog.h" #include "../sysklogd/syslogd.h" #include "../tools/sizes.h" void syslogd_close_sockets (struct socket * sockets) { struct socket * socket = sockets; char buffer [HOSTADDR_MAX]; #if SYSLOGD_TRACE trace_enter ("syslogd_close_sockets"); #endif do { socket = socket->next; if (socket->desc < 0) { continue; } if (socket->sockaddr == (struct sockaddr *) (0)) { syslogd_error (EINVAL, "Invalid socket address structure"); continue; } #ifdef SYSLOGD_UNIXAF if (socket->sockaddr->sa_family == AF_UNIX) { struct sockaddr_un * sockaddr_un = (struct sockaddr_un *) (socket->sockaddr); syslogd_print (SYSLOG_SYSLOG | SYSLOG_NOTICE, "Closing host connection on %s", sockaddr_un->sun_path); close (socket->desc); if (unlink (sockaddr_un->sun_path)) { syslogd_error (errno, "Can't remove socket %s", sockaddr_un->sun_path); } socket->desc = - 1; continue; } #endif #ifdef SYSLOGD_INETAF if (socket->sockaddr->sa_family == AF_INET) { struct sockaddr_in * sockaddr_in = (struct sockaddr_in *) (socket->sockaddr); getsocketname (buffer, sizeof (buffer), sockaddr_in); syslogd_print (SYSLOG_SYSLOG | SYSLOG_NOTICE, "Closing inet connection on %s", buffer); close (socket->desc); socket->desc = - 1; continue; } #endif } while (socket != sockets); #if SYSLOGD_TRACE trace_leave ("syslogd_close_sockets"); #endif return; } /*====================================================================* * *--------------------------------------------------------------------*/ #endif
C
#include "pomocnicze2.h" #include "pomocnicze3.h" void readName(char *ch, Customer *current, FILE *dataBase) { int i = 0; while(*ch != '#'){ current -> name[i] = *ch; *ch = getc(dataBase); i++; } } void readSurname(char *ch, Customer *current, FILE *dataBase) { int i = 0; while (*ch != '#') { current -> surname[i] = *ch; *ch = getc(dataBase); i++; } } void readTools(char *ch, Customer **current, FILE *dataBase, Customer **previous) { if(*ch == '$'){ Licence *this = NULL; Licence *former = NULL; while (*ch != '!') { *ch = getc(dataBase); this = malloc(sizeof(Licence)); if(!this){ exit(-1); } if(former == NULL){ (*current) -> headL = this; } else{ former -> next = this; } readTool(ch, &this); *ch = getc(dataBase); readLicenceNum(ch, dataBase, &this); *ch = getc(dataBase); readStartDate(ch, dataBase, &this); *ch = getc(dataBase); readEndDate(ch, dataBase, &this); former = this; } *ch = getc(dataBase); *ch = getc(dataBase); *previous = *current; } } void chChosenCount(Customer* headC, char chs){ Customer *current = headC; Licence *this = NULL; time_t date = time(NULL); int userNum = 0; int licNum = 0; while (current != NULL) { this = current -> headL; while (this != NULL) { if (this -> tool == chs && (long)date < (long)this -> dateEnd) { userNum += 1; licNum += this -> licenceNum; } this = this -> next; } current = current -> next; } printf("\nZ WYBRANEGO NARZEDZIA KORZYSTA %d UZYTKOWNIKOW", userNum); printf("\n%d LICENCJI WYBRANEGO NARZEDZIA JEST W UZYTKU\n\n", licNum); } void chChosenTool(Customer* headC, char chs){ Customer *current = headC; Licence *this = NULL; time_t date = time(NULL); puts("\nZ WYBRANEGO NARDZEDZIA KORZYSTAJA:\n"); while (current != NULL) { this = current -> headL; while (this != NULL) { if (this -> tool == chs && (long)date < (long)this -> dateEnd) { printf("IMIE: %s\n", current -> name); printf("NAZWISKO: %s\n", current -> surname); printf("START: %s", ctime(&this -> dateStart)); printf("KONIEC: %s\n", ctime(&this -> dateEnd)); } this = this -> next; } current = current -> next; } } void chChosenExp(Customer* headC, char chs){ Customer *current = headC; Licence *this = NULL; time_t date = time(NULL); puts("\nLICENCJA NA WYBRANE NARZEDZIE WYGASA NASTEPUJACYM UZYTKOWNIKOM:\n"); while (current != NULL) { this = current -> headL; while (this != NULL) { if ((long)date <= (long)this -> dateEnd && (long)this -> dateEnd <= (long)date + TWOWEEKS && this -> tool == chs) { printf("IMIE: %s\n", current -> name); printf("NAZWISKO: %s\n", current -> surname); printf("START: %s", ctime(&this -> dateStart)); printf("KONIEC: %s\n", ctime(&this -> dateEnd)); } this = this -> next; } current = current -> next; } }
C
//Ŷ //1.жരڷKṩй˿ͰʱŶӣдڿʱһλ˿ͼȥôڴ //жരڷģж typedef struct People ElementType; struct People{ //˿ int T; //˿͵ʱ int P; //˿ﱻʱ }; typedef int Position; struct QNode{ //н ElementType *Data; //˿ Position Front, Rear; //еͷβָ int MaxSize; // }; typedef struct QNode *Queue; Queue CreateQueue(int MaxSize){ Queue Q = (Queue)malloc(sizeof(struct QNode)); Q->Data = (ElementType *)malloc(MaxSize*sizeof(ElementType)); Q->Front = Q->Rear = 0; Q->MaxSize = MaxSize; return Q; } bool IsFull(Queue Q){ return((Q->Rear+1)%Q->MaxSize==Q->Front); } bool AddQ(Queue Q, ElementType X){ if(IsFull(Q)){ printf(""); return false; } else{ Q->Rear = (Q->Rear+1)%Q->MaxSize; Q->Data[Q->Rear] = X; return true; } } bool IsEmpty(Queue Q){ return(Q->Front == Q->Rear); } ElementType DeleteQ(Queue Q){ if(IsEmpty(Q)){ printf("пա"); return ERROR; } else{ Q->Front = (Q->Front+1)%Q->MaxSize; return Q->Data[Q->Front]; } } //жരڷģ int main(){ int N; //˿ Queue Q; //˿Ͷ int i; ElementType X; scanf("%d", &N); //ȡ˿ Q = CreateQueue(N); //յĹ˿Ͷ for(i=0; i<N; i++){ //˿ scanf("%d%d", &X.T, &X.P); AddQ(Q, X); } //ӡNλ˿͵ƽȴʱ printf("Average waiting time = %.If minute(s). \n", QueueingAtBank(Q, N)); DestroyQueue(Q); return 0; } //жരڷģĴ double QueueAtBank(Queue Q, int N){ //ݹ˿ͶQNع˿ƽȴʱ struct People Next; //һλ˿ int K; //Ӫҵڸ int TotalTime; //ȫ˿͵ȴʱ int CurrentTime; //ǰʱ䣬ӪҵʱΪ0 int Window[MaxWindow]; //ӪҵҪʱ䳤 int WaitTime; //δڿ֮Ҫȴʱ int WinAvail; //дڵλ int i, j; scanf("%d", &K); //Ӫҵڸ if(N<K) return 0; //ڱȴ //ʼ for(i=0; i<K; i++){ Window[i] = 0; } TotalTime = 0; // while(!IsEmpty(Q)){ //зǿգ //һǰ̵񣬵õһд WinAvail = FindNextWindow(Window, K, &WaitTime); CurrentTime += WaitTime; //ڶһλ˿ͳ Next = DeleteQ(Q); if(CurrentTime >= Next.T){ //˿Ѿȴ TotalTime += CurrentTime - Next.T; //ۼƵȴʱ } else{ //˿ͻû WaitTime = Next.T - CurrentTime; //дڵȴ˿͵ʱ for(j=0; j<K; j++){ //ˢд˿͵״̬ Window[j] -= WaitTime; if(Window[j]<0){ Window[j] = 0; } } CurrentTime = Next.T; //µǰʱΪ˿͵ʱ } //˿NextWinAvailڽҵ Window[WinAvail] = Next.P; } //ÿλ˿͵ƽȴʱ return((double)TotalTime/(double)N); } //жരڷģFindNextWindow int FindNextWindow(int W[], int K, int *WaitTime){ //KW[]״̬һдڵλ //Լδڿ֮ȴʱWaitTime int WinAvail; //һдڵλ int MinW = MaxProc+1; //ʱ䣬ʼΪֵ int i; for(i=0; i<K; i++){ //ɨÿڣҵ if(W[i]<MinW){ MinW = W[i]; WinAvail = i; } } *WaitTime = MinW; //ʱοմĵȴʱ for(i=0; i<k; i++){ W[i] - MinW; //ˢдڵ״̬ } return WinAvail; //һմλ } //2.жര+VIP񣺵ûVIPͻʱVIPΪͨ˿ͷ񣻵VIPڿҶVIPͻȴʱǰVIPͻܸôڵķ //ͬʱֵijVIPڳʱVIPڷǿգÿͻѡеͨ //жര+VIPģж typedef struct People ElementType; struct People{ //˿ int T; //˿͵ʱ int P; //˿ﱻʱ int VIP; //VIP־1VIP0ͨ-1ɾ }; typedef int Position; struct QNode{ //н ElementType *Data; //˿ Position Front, Rear; //еͷβָ int MaxSize; // //VIPжӦԪ Position VIPFront, VIPRear; int *VIPCustomer; int *VIPSize; //VIP }; typedef struct QueueRecord *Queue; bool VIPIsFull(Queue Q); bool AddVIP(Queue Q); bool VIPIsEmpty(Queue Q); ElementType DeleteVIP(Queue Q); Queue CreateQueue(int MaxSize); bool IsFull(Queue Q); bool AddQ(Queue Q); bool IsEmpty(Queue Q); ElementType DeleteQ(Queue Q); //жര+VIPģĴ double QueueAtBank(Queue Q, int N){ //ݹ˿ͶQNع˿ƽȴʱ struct People Next; //һλ˿ int K; //Ӫҵڸ int TotalTime; //ȫ˿͵ȴʱ int CurrentTime; //ǰʱ䣬ӪҵʱΪ0 int Window[MaxWindow]; //ӪҵҪʱ䳤 int WaitTime; //δڿ֮Ҫȴʱ int WinAvail; //дڵλ int i, j; int VIPWindow; //VIPڱ scanf("%d%d", &K, &VIPWindow); //ӪҵڸVIPڱ if(N<K) return 0; //ڱȴ //ʼ for(i=0; i<K; i++){ Window[i] = 0; } TotalTime = 0; // while(!IsEmpty(Q)){ //зǿգ //һǰ̵񣬵õһд WinAvail = FindNextWindow(Window, K, &WaitTime); CurrentTime += WaitTime; //ڶһλ˿ͳ if((WinAvail==VIPWindow)&&(IsVipHere(Q, CurrentTime))){ Next = DeleteVIP(Q); //VIPڿVIPڶ } else{ Next = DeleteQ(Q); } if(Next.T==EmptyQ){ break; //յѿյźţ˳ѭ } if(CurrentTime >= Next.T){ //˿Ѿȴ TotalTime += CurrentTime - Next.T; //ۼƵȴʱ } else{ //˿ͻû WaitTime = Next.T - CurrentTime; //дڵȴ˿͵ʱ for(j=0; j<K; j++){ //ˢд˿͵״̬ Window[j] -= WaitTime; if(Window[j]<0){ Window[j] = 0; } } CurrentTime = Next.T; //µǰʱΪ˿͵ʱ } //˿NextWinAvailڽҵ Window[WinAvail] = Next.P; } //ÿλ˿͵ƽȴʱ return((double)TotalTime/(double)N); } //жരڷģFindNextWindow int FindNextWindow(int W[], int K, int *WaitTime){ //KW[]״̬һдڵλ //Լδڿ֮ȴʱWaitTime int WinAvail; //һдڵλ int MinW = MaxProc+1; //ʱ䣬ʼΪֵ int i; for(i=0; i<K; i++){ //ɨÿڣҵ if(W[i]<MinW){ MinW = W[i]; WinAvail = i; } } *WaitTime = MinW; //ʱοմĵȴʱ for(i=0; i<k; i++){ W[i] - MinW; //ˢдڵ״̬ } return WinAvail; //һմλ } //жര+VIPģDeleteQ bool VIPIsEmpty(Queue Q){ return(Q->VIPSize==0); } ElementType DeleteVIP(Queue Q){ //VIPж׵Ŀͻ ElementType X; Position P; if(!VIPIsEmpty(Q)){ //VIPͻ //ö׿ͻڹ˿Ͷеλ P = Q->VIPCustomer[Q->VIPFront]; //λôVIPɾ Q->VIPFront++; Q->VIPSize--; Q->Data[P].VIP = -1; //ɾ˿ͶеVIP X.T = Q->Data[P].T; X.P = Q->Data[P].P; } else{ //ûVIPͻͨ X = DeleteQ(Q); } return X; } #define EmptyQ -1 //пյź ElementType DeleteQ(Queue Q){ //Q׵Ĺ˿ͳ ElementType X; //λڶǰ˵ıɾĹ˿ɾ while(Q->Data[Q->Front].VIP = -1){ Q->Front++; } if(IsEmpty(Q)){ //ֶѿգؿź X.T = EmptyQ; return X; } if(Q->Data[Q->Front].VIP = 1){ X.DeleteVIP(Q); //׵VIPͻ } else{ //ͨ˿ͳ X.T = Q->Data[Q->Front].T; X.P = Q->Data[Q->Front].P; } //ɾ׵Ĺ˿ Q->Front++; return X; }
C
#include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <netinet/tcp.h> #include <arpa/inet.h> #include <unistd.h> #include <strings.h> #include <string.h> #include <errno.h> #include <time.h> #include <fcntl.h> #include <linux/sockios.h> #include "session.h" #include "transport_l.h" /* Sends a packet to the transport layer by invoking sendto() system call */ void transport_send_packet(int socket_t, char *packet, int packet_len, int *error, struct sockaddr_in *address, int address_len) { int result; result = sendto(socket_t, packet, packet_len, 0, (struct sockaddr *)address, (socklen_t)address_len); if (result == -1) { printf("Packet not sent. %s %d \n", packet, packet_len); } } /* Receives a packet from the transport layer by invoking recvfrom() system call */ void transport_recv_packet(int socket_t, char *packet, int *packet_len, int *error, struct sockaddr_in *address, int *address_len) { *packet_len = recvfrom(socket_t, packet, PKT_SIZE_MAX, 0, (struct sockaddr *)address, (socklen_t *)address_len); if (*packet_len == -1) { printf("Received a NUll packet \n"); } }
C
/* * Banker's Algorithm for SOFE 3950U / CSCI 3020U: Operating Systems * * Copyright (C) 2015, Muhammad Ahmad, Timothy MacDougall, Devin Westbye * All rights reserved. * */ #include <stdlib.h> #include <stdio.h> #include <stdbool.h> #include <pthread.h> #include <semaphore.h> #include "banker.h" // Put any other macros or constants here using #define // May be any values >= 0 #define NUM_CUSTOMERS 5 #define NUM_RESOURCES 3 // Put global environment variables here // Available amount of each resource int available[NUM_RESOURCES]; // Maximum demand of each customer int maximum[NUM_CUSTOMERS][NUM_RESOURCES]; // Amount currently allocated to each customer int allocation[NUM_CUSTOMERS][NUM_RESOURCES]; // Remaining need of each customer int need[NUM_CUSTOMERS][NUM_RESOURCES]; pthread_mutex_t mutex; pthread_mutex_t console; void print_resources(){ pthread_mutex_lock(&console); printf("Available: "); for(int i = 0; i < NUM_RESOURCES; i++){ printf("%d ", available[i]); } printf("\n"); pthread_mutex_unlock(&console); } void print_need(int customer){ pthread_mutex_lock(&console); printf("Need for %d: ", customer); for(int i = 0; i < NUM_RESOURCES; i++){ printf("%d ", need[customer][i]); } printf("\n"); pthread_mutex_unlock(&console); } void print_result(int num, int request[], bool safe){ pthread_mutex_lock(&console); printf("Request from %d: ", num); for(int j = 0; j < NUM_RESOURCES; j++){ printf("%d ", request[j]); } if(!safe){ printf("State Unsafe; Request denied\n"); } else { printf("State Safe; Request accepted\n"); } pthread_mutex_unlock(&console); } void* requestReleaseRepeat (void* arg) { int customerNumber = (int) arg; //int count = 10; bool finished = false; while(!finished) { int request[NUM_RESOURCES]; finished = true; for (int i = 0; i < NUM_RESOURCES; i++) { if(need[customerNumber][i] != 0){ finished = false; request[i] = rand() % (need[customerNumber][i]+1); } else { request[i] = 0; } //printf("%d ", request[i]); } //printf("\n"); //print_resources(); bool success; //do { //print_need(customerNumber); pthread_mutex_lock(&mutex); success = request_res(customerNumber, request); pthread_mutex_unlock(&mutex); //printf("success: %d\n", success); //} while(!success); //while(!request_res(customerNumber, request)); //print_resources(); if(success){ pthread_mutex_lock(&mutex); release_res(customerNumber, request); pthread_mutex_unlock(&mutex); } //print_resources(); //count--; sleep(1); } printf("Process %d completed\n", customerNumber); return NULL; } // Define functions declared in banker.h here bool request_res(int n_customer, int request[]) { for(int j = 0; j < NUM_RESOURCES; j++){ if(request[j] > need[n_customer][j]){ puts("Error: requesting more than you need"); return false; } } for(int j = 0; j < NUM_RESOURCES; j++){ if(request[j] > available[j]){ puts("ERROR: resources not available"); return false; } } for(int j = 0; j < NUM_RESOURCES; j++){ available[j] -= request[j]; allocation[n_customer][j] += request[j]; } bool safe = is_safe(); print_result(n_customer, request, safe); if(!safe){ release_res(n_customer, request); } else { for(int j = 0; j < NUM_RESOURCES; j++){ need[n_customer][j] -= request[j]; } } return safe; } // Release resources, returns true if successful bool release_res (int n_customer, int amount[]) { pthread_mutex_lock(&console); printf("Released "); for(int j = 0; j < NUM_RESOURCES; j++){ available[j] += amount[j]; allocation[n_customer][j] -= amount[j]; //need[n_customer][j] += amount[j]; printf("%d ", amount[j]); } printf("from %d\n", n_customer); pthread_mutex_unlock(&console); return true; } bool lessthan_equalto(int array1[], int array2[], int length){ for(int i = 0; i < length; i++){ if(array1[i] > array2[i]){ return false; } } return true; } // Check if state is safe bool is_safe() { int work[NUM_RESOURCES]; for(int i = 0; i < NUM_RESOURCES; i++){ work[i] = available[i]; } bool finish[NUM_CUSTOMERS] = {false}; bool found; do { found = false; for (int i = 0; i < NUM_CUSTOMERS; i++){ if(finish[i] == false){ //for(int j = 0; j < NUM_RESOURCES; j++){ // need[i][j] = maximum[i][j] - allocation[i][j]; //} if(lessthan_equalto(need[i], work, NUM_RESOURCES)){ found = true; for(int j = 0; j < NUM_RESOURCES; j++){ work[j] += allocation[i][j]; } finish[i] = true; } } } } while(found); for(int i = 0; i < NUM_CUSTOMERS; i++){ if(finish[i] == false){ return false; } } return true; } int main(int argc, char *argv[]) { // define local variables pthread_t customer[NUM_CUSTOMERS]; if (argc != NUM_RESOURCES+1) { printf("Error: Incorrect amount of arguments supplied. Requires: %d Received: %d\n", NUM_RESOURCES, argc-1); exit(0); } // initialize available resources for (int i = 0; i < NUM_RESOURCES; i++) { available[i] = atoi(argv[i+1]); for(int j = 0; j < NUM_CUSTOMERS; j++){ maximum[j][i] = rand() % available[i]; need[j][i] = maximum[j][i]; } } for(int i = 0; i < NUM_CUSTOMERS; i++){ pthread_create(&customer[i], 0, requestReleaseRepeat, (void*) i); } // ==================== YOUR CODE HERE ==================== // // Initialize the pthreads, locks, mutexes, etc. // Run the threads and continually loop // The threads will request and then release random numbers of resources // If your program hangs you may have a deadlock, otherwise you *may* have // implemented the banker's algorithm correctly // If you are having issues try and limit the number of threads (NUM_CUSTOMERS) // to just 2 and focus on getting the multithreading working for just two threads for(int i = 0; i < NUM_CUSTOMERS; i++){ pthread_join(customer[i], NULL); } return EXIT_SUCCESS; }
C
#include <stdio.h> int i, n, f, a, b; int main() { scanf("%d", &n); if (n<3) { f=1; } else { a=1; b=1; } for (i=3; i<=n; i++) { f=a+b; a=b; b=f; } printf("%d", f); }
C
#include <stdio.h> #include <stdint.h> #include <string.h> #include <time.h> #include <math.h> #define TEXT_LENGTH 1000000 double run_naive_implementation(){ printf(" ----------TEST 1-------------- \n"); // Time measurements according to: // https://www.tutorialspoint.com/how-to-measure-time-taken-by-a-function-in-c uint8_t source[TEXT_LENGTH]; uint8_t dest[TEXT_LENGTH]; size_t plaintextlen = TEXT_LENGTH; clock_t timestamp_start; clock_t timestamp_end; timestamp_start = clock(); for (size_t i=0; i<plaintextlen; i++){ dest[i] = source[i]; } timestamp_end = clock(); printf(" Test ran for %ld steps \n", timestamp_end - timestamp_start); printf(" Test ran for %f miliseconds \n", ((double) (timestamp_end - timestamp_start)*1000)/CLOCKS_PER_SEC); printf(" ------------------------------ \n"); return ((double) (timestamp_end - timestamp_start)*1000)/CLOCKS_PER_SEC; } double run_improved_implementation(){ printf(" ----------TEST 2-------------- \n"); // Time measurements according to: // https://www.tutorialspoint.com/how-to-measure-time-taken-by-a-function-in-c uint8_t source[TEXT_LENGTH]; uint8_t dest[TEXT_LENGTH]; size_t plaintextlen = TEXT_LENGTH; clock_t timestamp_start; clock_t timestamp_end; timestamp_start = clock(); memmove(dest, source, TEXT_LENGTH); timestamp_end = clock(); printf(" Test ran for %ld steps \n", timestamp_end - timestamp_start); printf(" Test ran for %f miliseconds \n", ((double) (timestamp_end - timestamp_start)*1000)/CLOCKS_PER_SEC); printf(" ------------------------------ \n"); return ((double) (timestamp_end - timestamp_start)*1000)/CLOCKS_PER_SEC; } int main() { printf("Running comparison tests\n"); // for (size_t i=0; i<taglen; i++){ // printf("dest[%lu] = %d\n", plaintextlen+i, dest[plaintextlen+i]); // } int number_of_experiments = 100; double list_miliseconds_to_complete_naive[number_of_experiments]; double list_miliseconds_to_complete_improved[number_of_experiments]; // 1. Run experiments for (int i=0; i<number_of_experiments; i++){ list_miliseconds_to_complete_naive[i] = run_naive_implementation(); } for (int i=0; i<number_of_experiments; i++){ list_miliseconds_to_complete_improved[i] = run_improved_implementation(); } // 2. Report results double avg_milisecond_to_complete_naive = 0.0; for (int i=0; i<number_of_experiments; i++){ avg_milisecond_to_complete_naive+=list_miliseconds_to_complete_naive[i]; } avg_milisecond_to_complete_naive = avg_milisecond_to_complete_naive/number_of_experiments; double avg_squared_distance_naive = 0.0; for (int i=0; i<number_of_experiments; i++){ double distance = avg_milisecond_to_complete_naive - list_miliseconds_to_complete_naive[i]; avg_squared_distance_naive += distance*distance; } double standard_deviation_naive = sqrt(avg_squared_distance_naive/(number_of_experiments-1)); double avg_milisecond_to_complete_improved = 0; for (int i=0; i<number_of_experiments; i++){ avg_milisecond_to_complete_improved+=list_miliseconds_to_complete_improved[i]; } avg_milisecond_to_complete_improved = avg_milisecond_to_complete_improved/number_of_experiments; double avg_squared_distance_improved = 0.0; for (int i=0; i<number_of_experiments; i++){ double distance = avg_milisecond_to_complete_improved - list_miliseconds_to_complete_improved[i]; avg_squared_distance_improved += distance*distance; } double standard_deviation_improved = sqrt(avg_squared_distance_improved/(number_of_experiments-1)); printf("Naive implementation took: %f miliseconds on average (stdev: %f) \n", avg_milisecond_to_complete_naive, standard_deviation_naive); printf("Improved implementation took: %f miliseconds on average (stdev: %f) \n", avg_milisecond_to_complete_improved, standard_deviation_improved); // for (size_t i=0; i<taglen; i++){ // printf("dest[%lu] = %d\n", plaintextlen+i, dest[plaintextlen+i]); // } return 0; }
C
/* The structure of the tree is struct tree_node { int data; struct tree_node* left_child; struct tree_node* right_child; }; */ struct tree_node* insert(struct tree_node* root, int key) { if (root == NULL) { struct tree_node *temp = (struct tree_node *)malloc(sizeof(struct tree_node)); temp->data = key; temp->left_child = temp->right_child = NULL; printf("%d element is inserted in BST.\n",key); return temp; } if (key < root->data) root->left_child = insert(root->left_child, key); else if (key > root->data) root->right_child = insert(root->right_child, key); return root; } struct tree_node* minValueNode(struct tree_node* node) { struct tree_node* current = node; while (current->left_child != NULL) // go deep in left, as inorder successor will be minimum of right subtree & // leftmost node of right subtree will be the inorder successor. current = current->left_child; return current; } struct tree_node* deleteNode(struct tree_node* root, int key) { if (root == NULL) { printf("Node not found\n"); // Node not present in the tree so return NULL. return NULL; } // If the key to be deleted is smaller than the root's key if (key < root->data) root->left_child = deleteNode(root->left_child, key); // If the key to be deleted is greater than the root's key else if (key > root->data) root->right_child = deleteNode(root->right_child, key); // if key is same as root's key, then This is the node to be deleted else { struct tree_node *temp = NULL; // node with no child if (root->left_child == NULL && root->right_child == NULL) { free(root); return NULL; } else if(root->left_child == NULL) { temp = root->right_child; free(root); return temp; } else if (root->right_child == NULL) { temp = root->left_child; free(root); return temp; } // if none of above case execute then, // node is having with two children So, // Get the inorder successor or inorder predecessor temp = minValueNode(root->right_child); // inorder successor is taken here. // Copy the inorder successor's content to this node root->data = temp->data; // Delete the inorder successor root->right_child = deleteNode(root->right_child, temp->data); // Delete the inorder predecessor if it is taken above. // root->left_child = deleteNode(root->left_child, temp->data); } return root; } int main() { // create the root tree_node struct tree_node *root = NULL; struct tree_node *temp; int key; root = insert(root, 25); insert(root, 15); insert(root, 50); insert(root, 10); insert(root, 22); insert(root, 35); insert(root, 70); printf("\nInorder traversal of binary search tree is \n"); printInorder(root); key = 22; printf("\nDelete node with key = %d\n",key); root = deleteNode(root, key); printf("\nInorder traversal of binary search tree is \n"); printInorder(root); key = 28; printf("\nDelete node with key = %d\n",key); root = deleteNode(root, key); printf("\nInorder traversal of binary search tree is \n"); printInorder(root); key = 25; printf("\nDelete node with key = %d\n",key); root = deleteNode(root, key); printf("\nInorder traversal of binary search tree is \n"); printInorder(root); return 0; }
C
#define DIM_TABLOU 10 #define LUNGIME_N 5 #define LUNGIME_PP 3 #define LUNGIME_NPP 4 #define LUNGIME_NN 3 static int numarPrim(int numar) { int i; int ret = 0; if(numar < 2) ret = 0; if(numar == 2) ret = 1; for(i = 2; i <=( numar / 2); i++) if((numar % i) == 0) ret = 0; return ret; } void fill_arrays(long tab_numere[LUNGIME_N], unsigned long tab_nrPrimePozitive[LUNGIME_PP], unsigned long tab_nrNonPrimePozitive[LUNGIME_NPP], long tab_nrNegative[LUNGIME_NN]) { int i; int contorneg = 0, contorprim = 0, contorpoz = 0; for(i=0;i<LUNGIME_N;i++) { if( tab_numere[i] < 0) { tab_nrNegative[contorneg++] = tab_numere[i]; } else { if(numarPrim(tab_numere[i]) == 1) { tab_nrPrimePozitive[contorprim++] = tab_numere[i]; } else { tab_nrNonPrimePozitive[contorpoz++] = tab_numere[i]; } } if(i == LUNGIME_N || contorneg == LUNGIME_NN || contorprim == LUNGIME_PP || contorpoz == LUNGIME_NPP) { break; } } } void main() { int i=0; long tab_numere[LUNGIME_N]={2,-15,35,4,12}; unsigned long tab_nrPrimePozitive[LUNGIME_PP] = {0}; unsigned long tab_nrNonPrimePozitive[LUNGIME_NPP] = {0}; long tab_nrNegative[LUNGIME_NN] = {0}; fill_arrays(tab_numere, tab_nrPrimePozitive, tab_nrNonPrimePozitive, tab_nrNegative); printf("Tab Numere \n"); for(i = 0; i<LUNGIME_N ; i++) { printf("%ld ",tab_numere[i]); } printf("\n"); printf("Tab Numere Prime pozitive \n"); for(i = 0; i<LUNGIME_PP ; i++) { printf("%ld ",tab_nrPrimePozitive[i]); } printf("\n"); printf("Tab Numere NonPrime pozitive \n"); for(i = 0; i<LUNGIME_NPP ; i++) { printf("%ld ",tab_nrNonPrimePozitive[i]); } printf("\n"); printf("Tab Numere Negative \n"); for(i = 0; i<LUNGIME_N ; i++) { printf("%ld ",tab_nrNegative[i]); } printf("\n"); }
C
// Compile this assignment with: gcc main.c -o main // // Include parts of the C Standard Library // These have been written by some other really // smart engineers. #include <stdio.h> // For IO operations #include <stdlib.h> // for malloc// Our library that we have written. // Also, by a really smart engineer! #include "myqueue.h" // Note that we are locating this file // within the same directory, so we use quotations // and provide the path to this file which is within // our current directory. //First unit test case // A sample test of your program // You need to add sufficient testing. void unitTest1(){ queue_t* test1 = create_queue(1); if (queue_full(test1)){ printf("This queue is full.\n"); } printf("Add: %d\n", 1); printf("Status: %d\n", queue_enqueue(test1, 1)); printf("Size: %d\n", queue_size(test1)); if (queue_full(test1)){ printf("This queue is full.\n"); } printf("Add: %d\n", 2); printf("Status: %d\n", queue_enqueue(test1, 2)); printf("Size: %d\n", queue_size(test1)); if (queue_empty(test1)){ printf("This queue is empty.\n"); } printf("Removing: %d\n",queue_dequeue(test1)); printf("Size: %d\n", queue_size(test1)); printf("Removing: %d\n",queue_dequeue(test1)); printf("Size: %d\n", queue_size(test1)); free_queue(test1); } //Second unit test case //Following the same format as the first unit test, but using an even number queue void unitTest2(){ queue_t* test2 = create_queue(4); if (queue_full(test2)){ printf("This is a full queue.\n");} printf("Add: %d\n", 1); printf("Status: %d\n", queue_enqueue(test2, 1)); printf("Size: %d\n", queue_size(test2)); if (queue_full(test2)){ printf("This is a full queue.\n");} printf("Add: %d\n", 2); printf("Status: %d\n", queue_enqueue(test2, 2)); printf("Size: %d\n", queue_size(test2)); if (queue_full(test2)){ printf("This is a full queue.\n");} printf("Add: %d\n", 3); printf("Status: %d\n", queue_enqueue(test2, 3)); printf("Size: %d\n", queue_size(test2)); if (queue_full(test2)){ printf("This is a full queue.\n");} printf("Add: %d\n", 4); printf("Status: %d\n", queue_enqueue(test2, 4)); printf("Size: %d\n", queue_size(test2)); if (queue_empty(test2)){ printf("This is an empty queue.\n");} printf("Removing: %d\n",queue_dequeue(test2)); printf("The size is %d.\n", queue_size(test2)); printf("Removing: %d\n",queue_dequeue(test2)); printf("The size is %d.\n", queue_size(test2)); printf("Removing: %d\n",queue_dequeue(test2)); printf("The size is %d.\n", queue_size(test2)); printf("Removing: %d\n",queue_dequeue(test2)); printf("The size is %d.\n", queue_size(test2)); printf("Removing: %d\n",queue_dequeue(test2)); printf("The size is %d.\n", queue_size(test2)); free_queue(test2); } //Third unit test case //Similar format, but more focus on empty queue and the dequeue of an empty queue void unitTest3(){ queue_t* test3 = create_queue(0); //Empty queue if (queue_empty(test3)){ printf("This queue is empty.\n"); } free_queue(test3); } // ==================================================== // ================== Program Entry =================== // ==================================================== int main(){ // List of Unit Tests to test your data structure unitTest1(); printf("============================================\n"); unitTest2(); printf("============================================\n"); unitTest3(); printf("============================================\n"); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> struct etudiant{ char nom[100]; char prenom [100]; unsigned int age; unsigned int annee; }; typedef struct etudiant etudiant; void lire_ligne(char * ch){ int i = 0; char c; c = getchar(); while(c != '\n'){ ch[i] = c; i++; c = getchar(); } ch[i] = '\0'; } void saisie1(etudiant *e){ printf("Saisir nom : "); scanf("%s", e->nom); printf("Saisir prénom : "); scanf("%s", e->prenom); printf("Saisir age : "); scanf("%d", &e->age); printf("Saisir année d'étude : "); scanf("%d", &e->annee); } etudiant saisie2(){ etudiant e; printf("Saisir nom : "); scanf("%s", e.nom); printf("Saisir prenom : "); scanf("%s", e.prenom); printf("Saisir age : "); scanf("%d", &e.age); printf("Saisir annee d'etude : "); scanf("%d", &e.annee); return e; } etudiant * saisie3(){ etudiant * e = (etudiant *) malloc(sizeof(etudiant)); printf("Saisir nom : "); scanf("%s", e->nom); printf("Saisir prenom : "); scanf("%s", e->prenom); printf("Saisir age : "); scanf("%d", &e->age); printf("Saisir annee d'etude : "); scanf("%d", &e->annee); return e; } void affichage(const etudiant *e){ printf("Etudiant %s %s, de %d ans en annee %d \n", e->prenom, e->nom, e->age, e->annee); } struct duree{ int heure; int minute; int seconde; }; typedef struct duree duree; duree convert(int ss){ duree d; d.heure = ss / 3600; d.seconde = ss % 60; d.minute = (ss - d.heure * 3600) / 60; return d; } int convertSeconde(int h, int m, int s){ return h * 3600 + m * 60 + s; } int convertSeconde2(const duree * d){ return d->heure * 3600 + d->minute * 60 + d->seconde; } int convertSeconde3(duree d){ return d.heure * 3600 + d.minute * 60 + d.seconde; } void ceasar(char * ch, int k){ int i; for(i = 0; i < strlen(ch); i++){ if(ch[i] >= 'a' && ch[i] <= 'z') ch[i] = (ch[i] - 'a' + k) % 26 + 'a'; else if(ch[i] >= 'A' && ch[i] <= 'Z') ch[i] = (ch[i] - 'A' + k) % 26 + 'A'; } } int main() { char ch[100] = "Bonjour tout le monde !"; ceasar(ch, 3); printf("ch = '%s' \n", ch); ceasar(ch, -3); printf("ch = '%s' \n", ch); return 0; }
C
#include <stdio.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> #include <time.h> #define MAX_SPECIAL_CHARS 20 struct pair { int val1; char val2; }; #define TITLELEN 1024 static char title[TITLELEN]; static char exp_title[TITLELEN]; #define MAX_LINE_LEN 4096 static char line[MAX_LINE_LEN]; static char usage[] = "\ usage: fgrep (-c) (-nl) (-nt) (-nd) (-special_charhhc) (-file_maxn) (-anchor)\n" " string filename\n"; static char couldnt_open[] = "couldn't open %s\n"; static char couldnt_get_status[] = "couldn't get status of %s\n"; void GetLine(FILE *fptr,char *line,int *line_len,int maxllen); int main(int argc,char **argv) { int curr_arg; FILE *fptr0; FILE *fptr; struct stat statbuf; char *cpt; int chara; int linelen; int searchlen; int line_no; int put_title; int tries; int m; int n; int p; int case_sens; int line_numbers; bool bTitle; bool bDate; bool bAnchor; int string_arg; int put_search_string; int put_line; int file_max; int file_count; int num_special_chars; struct pair special_chars[MAX_SPECIAL_CHARS]; char buf[3]; if (argc < 2) { printf(usage); return 1; } case_sens = 0; line_numbers = 1; bTitle = true; bDate = true; num_special_chars = 0; file_max = -1; bAnchor = false; for (curr_arg = 1; ; curr_arg++) { if (!strcmp(argv[curr_arg],"-c")) case_sens = 1; else if (!strcmp(argv[curr_arg],"-nl")) line_numbers = 0; else if (!strcmp(argv[curr_arg],"-nt")) bTitle = false; else if (!strcmp(argv[curr_arg],"-nd")) bDate = false; else if (!strncmp(argv[curr_arg],"-special_char",13)) { if (num_special_chars == MAX_SPECIAL_CHARS) { printf("num_special_chars may not exceed %d\n",MAX_SPECIAL_CHARS); return 2; } buf[0] = argv[curr_arg][13]; buf[1] = argv[curr_arg][14]; buf[2] = 0; sscanf(buf,"%x",&special_chars[num_special_chars].val1); sscanf(&argv[curr_arg][15],"%c",&special_chars[num_special_chars++].val2); } else if (!strncmp(argv[curr_arg],"-file_max",9)) sscanf(&argv[curr_arg][9],"%d",&file_max); else if (!strcmp(argv[curr_arg],"-anchor")) bAnchor = true; else break; } if (argc - curr_arg < 1) { printf(usage); return 3; } if (argc - curr_arg == 1) fptr0 = stdin; else if ((fptr0 = fopen(argv[argc - 1],"r")) == NULL) { printf(couldnt_open,argv[argc - 1]); return 4; } string_arg = curr_arg; if (num_special_chars || !case_sens) { for (n = 0; (chara = argv[string_arg][n]); n++) { for (p = 0; p < num_special_chars; p++) { if (chara == special_chars[p].val2) { argv[string_arg][n] = (char)special_chars[p].val1; break; } } if (!case_sens) { if ((chara >= 'A') && (chara <= 'Z')) argv[string_arg][n] = (char)(chara - 'A' + 'a'); } } } searchlen = strlen(argv[string_arg]); put_search_string = 0; if (file_max != -1) file_count = 0; for ( ; ; ) { fscanf(fptr0,"%s",title); if (feof(fptr0)) { if (fptr0 != stdin) fclose(fptr0); break; } if (file_max != -1) { file_count++; if (file_count > file_max) break; } if ((fptr = fopen(title,"r")) == NULL) { printf(couldnt_open,title); continue; } if (stat(title,&statbuf)) { printf(couldnt_get_status,title); continue; } if (bDate) { cpt = ctime(&statbuf.st_mtime); if (cpt[8] == ' ') cpt[8] = '0'; cpt[strlen(cpt) - 1] = 0; sprintf(exp_title,"%s %s",cpt,title); } else strcpy(exp_title,title); if (bTitle) put_title = 0; for (line_no = 1; ; line_no++) { GetLine(fptr,line,&linelen,MAX_LINE_LEN); if (feof(fptr)) { if (bTitle && put_title) putchar(0x0a); fclose(fptr); break; } put_line = 0; if (linelen >= searchlen) { if (!bAnchor) tries = linelen - searchlen + 1; else tries = 1; for (m = 0; m < tries; m++) { for (n = 0; n < searchlen; n++) { chara = line[m+n]; if (!case_sens) if ((chara >= 'A') && (chara <= 'Z')) chara -= 'A' - 'a'; if (chara != argv[string_arg][n]) break; } if (n == searchlen) break; } if (n == searchlen) put_line = 1; } if (put_line) { if (!put_search_string) { printf("search string: %s\n\n",argv[string_arg]); put_search_string = 1; } if (bTitle && !put_title) { printf("%s\n",exp_title); for (n = strlen(exp_title); (n); n--) putchar('='); putchar(0x0a); put_title = 1; } if (line_numbers) printf("%03d:%s\n",line_no,line); else printf("%s\n",line); } } } return 0; } void GetLine(FILE *fptr,char *line,int *line_len,int maxllen) { int chara; int local_line_len; local_line_len = 0; for ( ; ; ) { chara = fgetc(fptr); if (feof(fptr)) break; if (chara == '\n') break; if (local_line_len < maxllen - 1) line[local_line_len++] = (char)chara; } line[local_line_len] = 0; *line_len = local_line_len; }
C
/** * IFJ20 Compiler * @file postfix.c * @authors Martin Bednář (xbedna77) */ #include <stdlib.h> #include <stdbool.h> #include "postfix.h" #include "vargen.h" #include "utils.h" #include "../error.h" #include "../memory.h" typedef struct tstack_t { int length; token_t** memory; } tstack_t; tstack_t* tstack_ctor(int size) { tstack_t* stack = safe_alloc(sizeof(tstack_t)); stack->memory = safe_alloc(size * sizeof(token_t*)); stack->length = 0; return stack; } void tstack_dtor(tstack_t* stack) { guard(stack != NULL); guard(stack->memory != NULL); free(stack->memory); free(stack); } void tstack_push(tstack_t* stack, token_t* token) { guard(stack != NULL); stack->memory[stack->length] = token; stack->length++; } token_t* tstack_pop(tstack_t* stack) { guard(stack != NULL); guard(stack->length != 0); stack->length--; return stack->memory[stack->length]; } token_t* tstack_peek(tstack_t* stack) { guard(stack != NULL); guard(stack->length != 0); return stack->memory[stack->length - 1]; } bool tstack_isempty(tstack_t* stack) { return stack->length == 0; } bool is_operand(token_t* token) { return token->id == TOKENID_IDENTIFIER || token->id == TOKENID_STRING_LITERAL || token->id == TOKENID_NUM || token->id == TOKENID_NUM_DECIMAL || token->id == TOKENID_BOOL_LITERAL; } /** * Returns operator priority as int. * Higher value means higher operator priority. */ int op_precedence(token_t* token) { switch (token->id) { case TOKENID_LEFT_PARENTHESES: return 0; case TOKENID_OPERATOR_OR: return 1; case TOKENID_OPERATOR_AND: return 2; case TOKENID_OPERATOR_EQUALS: case TOKENID_OPERATOR_NOT_EQUAL: return 3; case TOKENID_OPERATOR_LESS: case TOKENID_OPERATOR_LESS_OR_EQUAL: case TOKENID_OPERATOR_GREATER: case TOKENID_OPERATOR_GREATER_OR_EQUAL: return 4; case TOKENID_OPERATOR_ADD: case TOKENID_OPERATOR_SUB: return 5; case TOKENID_OPERATOR_MUL: case TOKENID_OPERATOR_DIV: return 6; case TOKENID_OPERATOR_NOT: return 7; default: error("Invalid operator."); } } bool are_operand_equal(token_t* operand1, token_t* operand2) { switch (operand1->id) { case TOKENID_BOOL_LITERAL: return operand1->value.bool_value == operand2->value.bool_value; break; case TOKENID_STRING_LITERAL: return strcpy(operand1->value.string_value, operand2->value.string_value) == 0; break; case TOKENID_NUM_DECIMAL: return operand1->value.decimal_value == operand2->value.decimal_value; break; case TOKENID_NUM: return operand1->value.int_value == operand2->value.int_value; break; default: error("First operand had unexpected type"); } } /** * Evaluates operation on given operands. */ token_t* eval_operation(token_t* operand1, token_t* operand2, token_t* operator) { switch (operator->id) { case TOKENID_OPERATOR_AND: operand1->value.bool_value = operand1->value.bool_value && operand2->value.bool_value; break; case TOKENID_OPERATOR_OR: operand1->value.bool_value = operand1->value.bool_value || operand2->value.bool_value; break; case TOKENID_OPERATOR_EQUALS: operand1->value.bool_value = are_operand_equal(operand1, operand2); operand1->id = TOKENID_BOOL_LITERAL; break; case TOKENID_OPERATOR_NOT_EQUAL: operand1->value.bool_value = !are_operand_equal(operand1, operand2); operand1->id = TOKENID_BOOL_LITERAL; break; case TOKENID_OPERATOR_LESS: if (operand1->id == TOKENID_NUM) { operand1->value.bool_value = operand1->value.int_value < operand2->value.int_value; } else { operand1->value.bool_value = operand1->value.decimal_value < operand2->value.decimal_value; } operand1->id = TOKENID_BOOL_LITERAL; break; case TOKENID_OPERATOR_LESS_OR_EQUAL: if (operand1->id == TOKENID_NUM) { operand1->value.bool_value = operand1->value.int_value <= operand2->value.int_value; } else { operand1->value.bool_value = operand1->value.decimal_value <= operand2->value.decimal_value; } operand1->id = TOKENID_BOOL_LITERAL; break; case TOKENID_OPERATOR_GREATER: if (operand1->id == TOKENID_NUM) { operand1->value.bool_value = operand1->value.int_value > operand2->value.int_value; } else { operand1->value.bool_value = operand1->value.decimal_value > operand2->value.decimal_value; } operand1->id = TOKENID_BOOL_LITERAL; break; case TOKENID_OPERATOR_GREATER_OR_EQUAL: if (operand1->id == TOKENID_NUM) { operand1->value.bool_value = operand1->value.int_value >= operand2->value.int_value; } else { operand1->value.bool_value = operand1->value.decimal_value >= operand2->value.decimal_value; } operand1->id = TOKENID_BOOL_LITERAL; break; case TOKENID_OPERATOR_ADD: if (operand1->id == TOKENID_NUM) { operand1->value.int_value = operand1->value.int_value + operand2->value.int_value; } else if (operand1->id == TOKENID_NUM_DECIMAL) { operand1->value.decimal_value = operand1->value.decimal_value + operand2->value.decimal_value; } else if (operand1->id == TOKENID_STRING_LITERAL) { // String concatenation int len = strlen(operand1->value.string_value) + strlen(operand2->value.string_value) + 1; operand1->value.string_value = safe_realloc(operand1->value.string_value, sizeof(char) * len); strcat(operand1->value.string_value, operand2->value.string_value); } break; case TOKENID_OPERATOR_SUB: if (operand1->id == TOKENID_NUM) { operand1->value.int_value = operand1->value.int_value - operand2->value.int_value; } else { operand1->value.decimal_value = operand1->value.decimal_value - operand2->value.decimal_value; } break; case TOKENID_OPERATOR_DIV: if (operand1->id == TOKENID_NUM) { operand1->value.int_value = operand1->value.int_value / operand2->value.int_value; } else { operand1->value.decimal_value = operand1->value.decimal_value / operand2->value.decimal_value; } break; case TOKENID_OPERATOR_MUL: if (operand1->id == TOKENID_NUM) { operand1->value.int_value = operand1->value.int_value * operand2->value.int_value; } else { operand1->value.decimal_value = operand1->value.decimal_value * operand2->value.decimal_value; } break; default: error("Given token is not operator"); } return operand1; } /** * Replaces three tokens from expression (at indexes: i, i+1, i+2) with * given token and shifts rest of the expression accordingly. */ void replace_three_tokens(astnode_exp_t* exp, token_t* token, int i) { token_t* new = token_copy(token); token_dtor(exp->tokens[i]); token_dtor(exp->tokens[i + 1]); token_dtor(exp->tokens[i + 2]); exp->tokens[i] = new; for (int j = i + 3; j < exp->tokens_count; j++) { exp->tokens[j - 2] = exp->tokens[j]; } exp->tokens_count -= 2; } /** * Optimizes expression by evaluating constant operands. * Returns true, if optimization was performed. */ bool optimize_by_evaluation(astnode_exp_t* exp) { bool flag = false; bool optimized; do { optimized = false; for (int i = 0; i < exp->tokens_count - 2 && !optimized; i++) { token_t* t1 = exp->tokens[i]; token_t* t2 = exp->tokens[i + 1]; token_t* t3 = exp->tokens[i + 2]; if (is_const_tokenid(t1->id) && is_const_tokenid(t2->id) && !is_operand(t3)) { replace_three_tokens(exp, eval_operation(t1, t2, t3), i); optimized = true; } } if (optimized) { flag = true; } } while (optimized); return flag; } bool is_zero_value(token_t* t) { return (t->id == TOKENID_NUM && t->value.int_value == 0) || (t->id == TOKENID_NUM_DECIMAL && t->value.decimal_value == 0.0); } bool is_unary_value(token_t* t) { return (t->id == TOKENID_NUM && t->value.int_value == 1) || (t->id == TOKENID_NUM_DECIMAL && t->value.decimal_value == 1.0); } /** * Optimizes expression by set of arithmetic rules. * Returns true, if optimization was performed. */ bool optimize_by_arithmetics(astnode_exp_t* exp) { bool flag = false; bool optimized; do { optimized = false; for (int i = 0; i < exp->tokens_count - 2 && !optimized; i++) { token_t* t1 = exp->tokens[i]; token_t* t2 = exp->tokens[i + 1]; token_t* t3 = exp->tokens[i + 2]; if (is_operand(t1) && is_operand(t2) && !is_operand(t3)) { switch (t3->id) { case TOKENID_OPERATOR_MUL: if (is_zero_value(t1)) { replace_three_tokens(exp, t1, i); optimized = true; } else if (is_zero_value(t2)) { replace_three_tokens(exp, t2, i); optimized = true; } else if (is_unary_value(t1)) { replace_three_tokens(exp, t2, i); optimized = true; } else if (is_unary_value(t2)) { replace_three_tokens(exp, t1, i); optimized = true; } break; case TOKENID_OPERATOR_DIV: if (is_zero_value(t1)) { replace_three_tokens(exp, t1, i); optimized = true; } else if (is_zero_value(t2)) { exit(ERRCODE_ZERO_DIVISION_ERROR); } else if (is_unary_value(t2)) { replace_three_tokens(exp, t1, i); optimized = true; } break; case TOKENID_OPERATOR_ADD: if (is_zero_value(t1)) { replace_three_tokens(exp, t2, i); optimized = true; } else if (is_zero_value(t2)) { replace_three_tokens(exp, t1, i); optimized = true; } break; case TOKENID_OPERATOR_SUB: if (is_zero_value(t2)) { replace_three_tokens(exp, t1, i); optimized = true; } break; default: break; } } } if (optimized) { flag = true; } } while (optimized); return flag; } void optimize_postfix(astnode_exp_t* exp) { while (optimize_by_arithmetics(exp) || optimize_by_evaluation(exp)); } void infix_to_postfix(astnode_exp_t* exp) { tstack_t* stack = tstack_ctor(exp->tokens_count); int j = 0; for (int i = 0; i < exp->tokens_count; i++) { if (is_operand(exp->tokens[i])) { exp->tokens[j++] = exp->tokens[i]; } else if (exp->tokens[i]->id == TOKENID_LEFT_PARENTHESES) { tstack_push(stack, exp->tokens[i]); } else if (exp->tokens[i]->id == TOKENID_RIGHT_PARENTHESES) { while (!tstack_isempty(stack) && tstack_peek(stack)->id != TOKENID_LEFT_PARENTHESES) { exp->tokens[j++] = tstack_pop(stack); } token_dtor(tstack_pop(stack)); } else { // Operator is encountered while (!tstack_isempty(stack) && op_precedence(exp->tokens[i]) <= op_precedence(tstack_peek(stack))) { exp->tokens[j++] = tstack_pop(stack); } tstack_push(stack, exp->tokens[i]); } } // Pop rest of the operators on stack while (!tstack_isempty(stack)) { exp->tokens[j++] = tstack_pop(stack); } exp->tokens_count = j; // Realloc space for the expression, which will be smaller, if included brackets exp->tokens = safe_realloc(exp->tokens, j * sizeof(token_t*)); tstack_dtor(stack); }
C
// // BEEPoo - Standalone AY-3-8912 player with ATMEGA32U4 with Arduino bootloader // // Copyright (c) 2014 SmallRoomLabs / Mats Engstrom - [email protected] // // Hardware and Firmware released under the MIT License (MIT) than can be // found in full in the file named LICENCE in the git repository. // // https://github.com/SmallRoomLabs/BEEPoo // #include "Arduino.h" #include <stdint.h> #include "nokia1202.h" #include "rotary.h" #include "pff.h" #include "buttons.h" #include "selectFile.h" #define DEBUGLED_ON PORTB |= B10000000 #define DEBUGLED_OFF PORTB &= B01111111 // // // static void scan_files_header(char* path, uint16_t startNo) { LcdClear(); LcdXY(0,0); LcdCharacter('['); if (strlen(path)) { LcdString(path); } else { LcdCharacter('/'); } LcdCharacter(']'); } // // // static uint16_t scan_files(char* path, uint16_t startNo) { FRESULT res; FILINFO fno; DIR dir; int i; int line; uint8_t headerprinted; uint16_t holdStartNo; headerprinted=0; holdStartNo=startNo; line=1; res=pf_opendir(&dir, path); if (res!=FR_OK) return -1; DEBUGLED_ON; for (;;) { res=pf_readdir(&dir, &fno); if (res!=FR_OK || fno.fname[0]==0) break; // Ignore hidden or system files if (fno.fattrib&(AM_HID|AM_SYS)) continue; if (startNo>0) { startNo--; } else { if (!headerprinted) { headerprinted=1; scan_files_header(path, holdStartNo); if (path[0] && holdStartNo==0) { LcdXY(8,line++); LcdString(".."); } } LcdXY(8,line++); if (!(fno.fattrib&AM_DIR)) { LcdString(fno.fname); } else { LcdCharacter('['); LcdString(fno.fname); LcdCharacter(']'); } } if (line==8) break; } DEBUGLED_OFF; return line; } // // // static void get_filename(char* path, uint16_t startNo, char *filename) { FRESULT res; FILINFO fno; DIR dir; if (path[0]) { if (startNo==0) { strcpy(filename,".."); return; } startNo--; } filename[0]=0; res=pf_opendir(&dir, path); if (res!=FR_OK) return; for (;;) { res=pf_readdir(&dir, &fno); if (res!=FR_OK || fno.fname[0]==0) break; // Ignore hidden or system files if (fno.fattrib&(AM_HID|AM_SYS)) continue; if (startNo>0) { startNo--; } else { strcpy(filename,fno.fname); return; } } } // // // void SelectFile(char *selectedFile) { uint8_t i; int16_t lastRotaryValue; int16_t myRotary; int16_t scrollValue; char filename[16]; char path[16]; selectedFile[0]=0; path[0]=0; scrollValue=0; rotaryValue=0; lastRotaryValue=-1; scan_files(path,0); for (;;) { myRotary=rotaryValue; // files start at 0, negative values is not allowed if (myRotary<0) { rotaryValue=0; myRotary=0; } if (BUTTONS&(BUTTON_ROTARY|BUTTON_OK)) { delay(25); while (BUTTONS&(BUTTON_ROTARY|BUTTON_OK)) delay(25); get_filename(path, myRotary, filename); if (strcmp(filename,"..")==0) { path[0]=0; } else { if (!path[0]) { strcpy(path,filename); } else { strcpy(selectedFile,path); strcat(selectedFile,"/"); strcat(selectedFile,filename); return; } } scrollValue=0; rotaryValue=0; myRotary=0; lastRotaryValue=-1; scan_files(path,0); delay(25); } // If same value as before we don't need to update screen if (myRotary==lastRotaryValue) continue; lastRotaryValue=myRotary; // Clear the cursor column for (i=1; i<8; i++) { LcdXY(0,i); LcdCharacter(' '); } // If we're still inside the window just move the cursor, // when going outside update the scroll position i=myRotary-scrollValue; if (i<0) { // Reached top of screen scrollValue=myRotary; scan_files(path,scrollValue); } else if ((i>=0) && (i<7)) { // Still inside the window } else if (i>=7) { // Reached to bottom of screen scrollValue=myRotary-6; scan_files(path,scrollValue); } LcdXY(0,1+myRotary-scrollValue); LcdCharacter(127); } }
C
#include<stdio.h> int main() { int arr[5]; arr[0] = 10; arr[1] = 20; arr[2] = 30; arr[3] = 40; arr[4] = 50; int arr2[] = { 10,20,30,40,50 }; int arr3[5] = {10,20,30,40,50 }; printf("%d\n",&arr[0]); printf("%d\n",&arr[1]); printf("%d\n",&arr[2]); printf("%d\n",&arr[3]); printf("%d\n",&arr[4]); return 0; }
C
/* wq@ function (W check) U expression ھ expression XT "True" "False" */ #include <stdio.h> ??? check(???) { ??? } int main(void) { int x = 5; int y = 3; check(x > 2 && y == 3); check( !(x < 2 || y == 3) ); check(x != 0 && y); check(x == 0 || !y); check(x != y && (20/x) < y); check( !(y>5 || y<2) && !(x%5) ); check(!x && x); return 0; }
C
#include <stdio.h> int main() { float valor= 900.25; int tamanho; tamanho = sizeof(valor); printf("Um float : %f\n",valor); printf("espaco de memoria ocupado: %d bytes\n", tamanho); return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* print_err.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: sdiego <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/10/15 17:18:57 by sdiego #+# #+# */ /* Updated: 2020/11/04 15:50:39 by sdiego ### ########.fr */ /* */ /* ************************************************************************** */ #include "../include/push_swap.h" void ft_putstr(char const *s) { int i; i = 0; if (s) { while (s[i]) { write(1, &s[i++], 1); } } } void ft_putendl(char const *s) { if (s) { ft_putstr(s); write(2, "\n", 1); } } void str_free(char **str) { int i; i = 0; while (str[i] != NULL) { free(str[i]); i++; } free(str); } void exit_print_err_and_free_str(char *s, int error, char **str) { str_free(str); ft_putendl(s); del_memory(); exit(error); } void exit_print_err(char *s, int error) { ft_putendl(s); del_memory(); exit(error); } void exit_err(int error) { del_memory(); exit(error); }
C
/* Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution. For example, given array S = {-1 2 1 -4}, and target = 1. The sum that is closest to the target is 2. (-1 + 2 + 1 = 2). */ #include <stdlib.h> static int mycmp(const void* p1, const void* p2) { return (*((int*)p1) - *((int*)p2)); } void myqsort(void* base, size_t nel, size_t width, int (*compar)(const void*, const void*)) { if (nel > 2) { void *p, *q, *r, *end; char tmp[width]; p = base; q = p + (nel >> 1) * width; end = base + (nel - 1) * width; for (r = end; p < r; r -= width) { if (r == q) { continue; } if (compar(r, q) < 0) { while ((p < r) && ((p == q) || (compar(p, q) < 0))) { p += width; } if (p >= r) { break; } memcpy(tmp, r, width); memcpy(r, p, width); memcpy(p, tmp, width); p += width; if (p == q) { p += width; } } } int cmp = compar(p, q); if (cmp != 0) { if (cmp < 0) { if (p < q) { p += width; } } else { if (p > q) { p -= width; } } if (p != q) { memcpy(tmp, p, width); memcpy(p, q, width); memcpy(q, tmp, width); } } if (p > base + width) { myqsort(base, ((p - base) / width), width, compar); } if (p < end - width) { myqsort(p + width, nel - 1 - ((p - base) / width), width, compar); } } else if (nel == 2) { if (compar(base, base + width) > 0) { char tmp[width]; memcpy(tmp, base, width); memcpy(base, base + width, width); memcpy(base + width, tmp, width); } } } //4ms version if using qsort, 8ms if using myqsort int threeSumClosest(int* nums, int numsSize, int target) { int minDelta = INT_MAX; int result = INT_MAX; int *p, *q, *r; int vp, vq, vr; int vtarget; if (!nums || (numsSize < 3)) { return result; } myqsort(nums, numsSize, sizeof(nums[0]), mycmp); for (r = nums + numsSize - 1; r > nums + 1; r--) { vr = *r; vtarget = vr - target; p = nums; q = r - 1; vp = *p; vq = *q; while (p < q) { int delta = vtarget + vp + vq; int absDelta = abs(delta); if (absDelta < minDelta) { minDelta = absDelta; result = target + delta; } if (delta < 0) { vp = *(++p); } else if (delta > 0) { vq = *(--q); } else { return target; } } } return result; }
C
#include <stdio.h> #include <stdlib.h> #include <conio.h> #include <windows.h> char M[3][3]={{' ',' ',' '},{' ',' ',' '},{' ',' ',' '}},id_1[100],id_2[100]; int tour=1,score_id_1=0,score_id_2=0; int GameLoop(){ clrscr(); printf("Morpion Tour : %d | Score: %s : %d /!/ %s : %d \n",tour, id_1,score_id_1,id_2,score_id_2); printf("______________\n"); printf("| %c | %c | %c |\n",M[0][0],M[0][1],M[0][2]); printf("______________\n"); printf("| %c | %c | %c |\n",M[1][0],M[1][1],M[1][2]); printf("______________\n"); printf("| %c | %c | %c |\n",M[2][0],M[2][1],M[2][2]); printf("______________\n"); if(GameTest()=='X') return 1; else {if (GameTest()=='O') return 2; else {if (tour==9) return 3;}} return 4; } void Control(){ int k=0,l=0,p=1; if (tour%2==0) p=2; else p=1; do{ if(p==1) printf("Player %s : i and j: \n",id_1); else printf("Player %s : i and j: \n",id_2); scanf("%d%d",&k,&l); }while(M[k][l]!=' '); if (tour%2==0) M[k][l]='O'; else M[k][l]='X'; } int GameTest(){ if(M[0][0]==M[1][1] && M[0][0]==M[2][2]) return M[0][0]; if(M[2][0]==M[1][1] && M[2][0]==M[0][2]) return M[2][0]; if(M[0][0]==M[0][1] && M[0][0]==M[0][2]) return M[0][0]; if(M[1][0]==M[1][1] && M[1][0]==M[1][2]) return M[1][0]; if(M[2][0]==M[2][1] && M[2][0]==M[2][2]) return M[2][0]; if(M[0][0]==M[1][0] && M[0][0]==M[2][0]) return M[0][0]; if(M[0][1]==M[1][1] && M[0][1]==M[2][1]) return M[0][1]; if(M[0][2]==M[1][2] && M[0][2]==M[2][2]) return M[0][2]; } void main(){ int i,j,game=0,ingame=0; do{ printf("Welcome to Morpion by Hamza Ahmouny\n"); printf("Entrer le nom du joueur 1:\n");scanf("%s",&id_1); printf("Entrer le nom du joueur 2:\n");scanf("%s",&id_2); score_id_1=0;score_id_2=0; for(i=0;i<3;i++){ for(j=0;j<3;j++){ M[i][j]=' '; }} do{ for(i=0;i<3;i++){ for(j=0;j<3;j++){ M[i][j]=' '; }} while(tour<10){ Control(); GameLoop(); if(GameLoop()==1) {printf("PLAYER %s WIN !\n",id_1);score_id_1++;break;} if(GameLoop()==2) {printf("PLAYER %s WIN !\n",id_2);score_id_2++;break;} if(GameLoop()==3) {printf("GAME NULL\n");break;} tour++;Sleep(1); } printf("Entrer 0 pour continuer 1 pour reset le score");scanf("%d",&ingame); clrscr(); }while(ingame==0); printf("Entrer 0 pour recommencer une partie et 1 pour quitter le jeu");scanf("%d",&game); clrscr(); }while(game==0); }
C
/* ** token_funct.c for token_funct.h in /home/ozouf_h//42sh/include ** ** Made by harold ozouf ** Login <[email protected]> ** ** Started on Mon Apr 9 15:44:05 2012 harold ozouf ** Last update Fri May 18 22:26:05 2012 kevin platel */ #include <stdlib.h> #include "token.h" #include "token_funct.h" t_bool is_a_dollar(t_token **tok, char **str) { if (str && *str && **str == '$') { *str += 1; if (add_token(tok, DOLLARS, "$", NONE) == EXIT_FAILURE) return (ERROR); return (TRUE); } return (FALSE); } t_bool is_a_pv(t_token **tok, char **str) { if (str && *str && **str == ';') { *str += 1; if (add_token(tok, PV, ";", NONE) == EXIT_FAILURE) return (ERROR); return (TRUE); } return (FALSE); } t_bool is_an_excla(t_token **tok, char **str) { if (str && *str && **str == '!') { if (add_token(tok, EXCLA, "!", NONE) == EXIT_FAILURE) return (ERROR); *str += 1; return (TRUE); } return (FALSE); } t_bool is_a_esp(t_token **tok, char **str) { if (str && *str && **str == '&') { *str += 1; if (add_token(tok, ESP, "&", NONE) == EXIT_FAILURE) return (ERROR); return (TRUE); } return (FALSE); }
C
#pragma once #include<dirent.h> #include<sys/stat.h> #include<sys/types.h> //struct dirent //{ // long d_ino; /* inode number 索引节点号 */ // off_t d_off; /* offset to this dirent 在目录文件中的偏移 */ // unsigned short d_reclen; /* length of this d_name 文件名长 */ // unsigned char d_type; /* the type of d_name 文件类型 */ // char d_name[NAME_MAX + 1]; /* file name (null-terminated) 文件名,最长255字符 */ //} //struct __dirstream //{ // void *__fd; /* `struct hurd_fd' pointer for descriptor.   */ // char *__data; /* Directory block.   */ // int __entry_data; /* Entry number `__data' corresponds to.   */ // char *__ptr; /* Current pointer into the block.   */ // int __entry_ptr; /* Entry number `__ptr' corresponds to.   */ // size_t __allocation; /* Space allocated for the block.   */ // size_t __size; /* Total valid data in the block.   */ // __libc_lock_define(, __lock) /* Mutex lock for this structure.   */ //}; //typedef struct __dirstream DIR; //DIR* opendir(const char * path); //struct dirent* readdir(DIR* dir_handle); //void closedir(DIR* dir_handle); void Copy(const char *dst, const char *src)//仅仅只是拷贝文件 { FILE *f1 = fopen(src, "rb"); FILE *f2 = fopen(dst, "wb"); fseek(f1, 0L, SEEK_END); int lens = ftell(f1);//取出原文件大小 rewind(f1); fread(buf, lens, 1, f1); fwrite(buf, lens, 1, f2); fclose(f1); fclose(f2); } void travel_dir(char *dir) { DIR *dir_point; //DIR是directory的缩写,是目录的意思 struct dirent *entry; if ((dir_point = opendir(dir)) == NULL) return;//打开文件夹失败,直接退出 while (!(entry = readdir(dir_point))){ printf("%s\n", entry->d_name); } } void test() { travel_dir("../../."); }
C
/* ** my_put_nbr.c for putnbr in /home/sauvau_m/rendu/Piscine_C_J07/lib/my ** ** Made by Mathieu Sauvau ** Login <[email protected]> ** ** Started on Tue Oct 6 17:44:34 2015 Mathieu Sauvau ** Last update Mon Feb 1 21:16:23 2016 Mathieu Sauvau */ #include "function.h" int my_put_nbr(int nb) { int div; if (nb < 0) { my_putchar(1, '-'); nb = -nb; } if (nb >= 10) { div = nb % 10; nb = (nb - div) / 10; my_put_nbr(nb); my_putchar(1, div + '0'); } else my_putchar(1, nb % 10 + '0'); return (nb); }
C
#include<stdio.h> int main() { char x = 15; char y = 10; int *ptr = NULL; ptr = (int *)&x; *ptr = 50; printf("%d\n",*ptr); return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* main.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ahrytsen <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/11/12 16:01:11 by ahrytsen #+# #+# */ /* Updated: 2017/11/24 21:36:35 by ahrytsen ### ########.fr */ /* */ /* ************************************************************************** */ #include "fillit.h" void ft_error(void) { ft_putendl("error"); exit(1); } static void ft_usage(void) { ft_putendl("usage: ./fillit [source_file]"); exit(0); } static int ft_minsqr(int amount) { int minsqr; minsqr = 2; while ((minsqr * minsqr) < (amount * 4)) minsqr++; return (minsqr); } int main(int ac, char **av) { int fd; int amount; t_etr *figures; int sqr_size; t_16bit *map; if (ac != 2) ft_usage(); fd = open(av[1], O_RDONLY); figures = (t_etr*)ft_memalloc(sizeof(t_etr) * 27); map = (t_16bit*)ft_memalloc(sizeof(t_16bit) * 16); if (fd == -1 || !figures || !map) ft_error(); amount = ft_reader(fd, figures); sqr_size = ft_minsqr(amount); while (!ft_solve(figures, map, sqr_size) && sqr_size++ < 14) ft_bzero(map, sizeof(t_16bit) * 16); if (sqr_size == 14) ft_error(); ft_output(figures, sqr_size); return (0); }
C
#include <pthread.h> #include <stdio.h> #include <unistd.h> #include <stdlib.h> #define MAX_THREAD_NUM 100 pthread_mutex_t m_lock = PTHREAD_MUTEX_INITIALIZER; int total = 0; void *factorial(void *param){ int *n = (int*)param; int n_fac = 1; for(int i = *n; i > 0; i--) n_fac *= i; printf("n = %d : %d! = %d\n", *n,*n, n_fac); pthread_mutex_lock(&m_lock); total += n_fac; pthread_mutex_unlock(&m_lock); } int main(int argc, char *argv[]){ int num = 0; int *arr; if(argc != 2) { printf("argument must have one\n"); return 0; } num = atoi(argv[1]); arr = (int*)malloc(num*sizeof(int)); pthread_t thread_id[num]; for(int i = 0; i < num ; i++) arr[i] = i + 1; for(int i = 0; i < num; i++) pthread_create(&thread_id[i], NULL, factorial, (void*)&arr[i]); for(int i = 0; i < num; i++) pthread_join(thread_id[i], NULL); pthread_mutex_destroy(&m_lock); printf("total : %d\n", total); return 0; }
C
#include <stdio.h> int main() { //printf("Tutorijal 4, Zadatak 2"); int i,j,a,b; printf("Unesite stranice pravougaonika a,b: "); scanf("%d,%d",&a,&b); for(i=1;i<=b;i++){ if(i==1 || i==b){ for(j=1;j<=a;j++){ { if(j==1 || j==a){ printf("+"); } else printf("-"); } } } else{ for(j=1;j<=a;j++){ if(j==1 || j==a){ printf("|"); } else printf(" "); } } printf("\n"); } return 0; }
C
#include<stdio.h> #include<math.h> int main() { int a, r; float result; printf_s("Enter a and r:\n"); scanf_s("%d %d", &a, &r); result = a * sqrt(4 * pow(r, 2) - pow(a, 2)) + pow(r, 2)*(3.1415926535 - 4 * asin(sqrt(1 - (pow(a, 2) / (4 * pow(r, 2)))))); printf_s("%.3f\n", result); system("pause"); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <errno.h> #include <unistd.h> #include <fcntl.h> #include <string.h> #include <math.h> #include <sys/wait.h> #include <ctype.h> #define ARTICLE "classique" #define SERVEUR "sw1" #define ACHETEUR "Philippe" #define TRANSPORTEUR "Xavier" #define QteRouleauStock 100 #define SURFACE 25 #define PrixRouleau 10 #define PALETTE 63 #define MSGSIZE 256 void acheteur(int pSEcriture[], int pSLecture[], int pTEcriture[], int pTLecture[]); void serveur(int pAEcriture[], int pALecture[], int pTEcriture[]); void transporteur(int pAEcriture[], int pALecture[], int pSLecture[]); char* concat(const char *s1, const char *s2); char* getMontantFacture(); char* getNombrePalettes(); void boucleLecture (int p[], const char* ROLE, const char* signature); int getNombreDigit(char s[], int longueurVoulue); int main(int argc, char **argv){ pid_t pidAcheteur; pid_t pidServeurWeb; pid_t pidTransporteur; int tabAcheteurServeur[2]; int tabServeurAcheteur[2]; int tabTransporteurAcheteur[2]; int tabAcheteurTransporteur[2]; int tabServeurTransporteur[2]; int pipeAcheteurServeur = pipe(tabAcheteurServeur); //creation du pipe: c'est un tableau de 2 cases ou chaque case est un identifient fichier if (pipeAcheteurServeur < 0) { printf("ACHETEUR. Tube non support\u00e9. Fin\n"); exit(1); // si pipe() est executee avec succes alors la fonction renvoie 0, -1 sinon } printf("ACHETEUR. Activation du mode non bloquant.\n"); if (fcntl(tabAcheteurServeur[0], F_SETFL, O_NONBLOCK) < 0) { /* Fonction qui rend la lecture du pipe non bloquante (asynchrone) Dans ce cas read() dans un tube vide ne bloque pas et renvoie -1. Ce n'est pas considere comme fin de fichier, mais une erreur */ printf("ACHETEUR. Mode non bloquant indisponible. Fin\n"); exit(2); } int pipeServeurAcheteur = pipe(tabServeurAcheteur); if (pipeServeurAcheteur < 0){ printf("SERVEUR. Tube non support\u00e9. Fin\n"); exit(3); } printf("SERVEUR. Activation du mode non bloquant.\n"); if (fcntl(tabServeurAcheteur[0], F_SETFL, O_NONBLOCK) < 0) { printf("SERVEUR. Mode non bloquant indisponible. Fin\n"); exit(4); } int pipeTransporteurAcheteur = pipe(tabTransporteurAcheteur); if (pipeTransporteurAcheteur < 0){ printf("TRANSPORTEUR. Tube non support\u00e9. Fin\n"); exit(5); } printf("TRANSPORTEUR. Activation du mode non bloquant.\n"); if (fcntl(tabTransporteurAcheteur[0], F_SETFL, O_NONBLOCK) < 0) { printf("TRANSPORTEUR. Mode non bloquant indisponible. Fin\n"); exit(6); } int pipeAcheteurTransporteur = pipe(tabAcheteurTransporteur); if (pipeAcheteurTransporteur < 0){ printf("ACHETEUR. Tube non support\u00e9. Fin\n"); exit(7); } printf("ACHETEUR. Activation du mode non bloquant.\n"); if (fcntl(tabAcheteurTransporteur[0], F_SETFL, O_NONBLOCK) < 0) { printf("ACHETEUR. Mode non bloquant indisponible. Fin\n"); exit(8); } int pipeServeurTransporteur = pipe(tabServeurTransporteur); if (pipeServeurTransporteur < 0){ printf("SERVEUR. Tube non support\u00e9. Fin\n"); exit(9); } printf("SERVEUR. Activation du mode non bloquant.\n"); if (fcntl(tabServeurTransporteur[0], F_SETFL, O_NONBLOCK) < 0) { printf("SERVEUR. Mode non bloquant indisponible. Fin\n"); exit(10); } printf("\n------------------------------\n"); printf("\nD\u00e9but des communications.\n\n"); pidAcheteur = fork(); // creation du processus fils if (pidAcheteur < 0){ // on teste s'il y a eu un pb printf("ACHETEUR. Fork impossible.\n"); exit(11); } else if (pidAcheteur == 0) { // on rentre dans le processus fils acheteur(tabAcheteurServeur, tabServeurAcheteur, tabAcheteurTransporteur, tabTransporteurAcheteur); } else { pidServeurWeb = fork(); if (pidServeurWeb == -1){ printf("SERVEUR. Fork impossible.\n"); exit(12); } else if (pidServeurWeb == 0) { serveur(tabServeurAcheteur, tabAcheteurServeur, tabServeurTransporteur); } else { pidTransporteur = fork(); if (pidTransporteur == -1){ printf("TRANSPORTEUR. Fork impossible.\n"); exit(13); } else if (pidTransporteur == 0){ transporteur(tabTransporteurAcheteur, tabAcheteurTransporteur, tabServeurTransporteur); } } } waitpid(pidAcheteur, 0, 0); waitpid(pidServeurWeb, 0, 0); waitpid(pidTransporteur, 0, 0); return 0; } void acheteur(int pSEcriture[], int pSLecture[], int pTEcriture[], int pTLecture[]){ close(pSEcriture[0]); close(pSLecture[1]); close(pTEcriture[0]); close(pTLecture[1]); int nread; char buf[MSGSIZE]; const char* signature = "ACHETEUR"; char* msg1 = "Je souhaiterais avoir l'article "; // Q1 char* msg3 = "Je souhaite passer une commande pour une surface de "; // Q3 char* msg9 = "Merci. Je vous rends un bon sign\u00e9"; // Q9 write(pSEcriture[1], concat(msg1, ARTICLE), MSGSIZE); // Question 1: l'acheteur saisit le nom d'un article boucleLecture(pSLecture, SERVEUR, signature); char str1[MSGSIZE]; // pour utiliser la fonction sprintf() sprintf(str1, "%d", SURFACE); // on convertit la surface en string write(pSEcriture[1], concat(msg3, str1), MSGSIZE); // Question 3: l'acheteur saisit la surface souhaitee boucleLecture(pSLecture, SERVEUR, signature); // On lit la question 4 boucleLecture(pSLecture, SERVEUR, signature); // Question 5: l'acheteur paie en saisissant son numero de carte bancaire et son cryptogramme char numCarte[16]; printf("Veuillez saisir votre num\u00e9ro de carte bancaire (16 chiffres au total): "); int x = getNombreDigit(numCarte, 17); while (x != 16){ // On boucle jusqu'a ce que l'utilisateur rentre bien 16 chiffres printf("Vous n'avez pas saisi 16 chiffres... Veuillez r\u00e9essayer: "); x = getNombreDigit(numCarte, 17); } // pareil pour le cryptogramme: char crypto[3]; printf("Veuillez saisir votre cryptogramme (3 chiffres): "); int c = getNombreDigit(crypto, 4); while (c != 3){ printf("Vous n'avez pas saisi 3 chiffres... Veuillez r\u00e9essayer: "); c = getNombreDigit(crypto, 4); } write(pSEcriture[1], numCarte, MSGSIZE); write(pSEcriture[1], crypto, MSGSIZE); boucleLecture(pSLecture, SERVEUR, signature); // On lit la question 6 boucleLecture(pTLecture, TRANSPORTEUR, signature); // Q8 on lit le msg du transporteur write(pTEcriture[1], msg9, MSGSIZE); // Q9: l'acheteur signe un des bons qu'il remet au livreur } void serveur(int pAEcriture[], int pALecture[], int pTEcriture[]){ close(pAEcriture[0]); close(pALecture[1]); close(pTEcriture[0]); const char* signature = "SERVEUR"; char* msg2 = "Le nombre de rouleaux en stock disponible pour cet article est "; // Q2 char msg4[MSGSIZE] = "Commande recue. Nombre total de palette(s): "; // Q4 char msg4Bis[MSGSIZE] = "Montant total de la facture: "; // Q4 char* msg6 = "J'accuse r\u00e9ception de votre paiement. Le montant de la transaction \u00e9tait de: "; // Q6 char* msg7 = "Voici un bon de livraison. Pour rappel, le nombre de palettes de l'article choisi est: "; // Q7 char* msg7Bis = "Voici un autre bon de livraison pour cette meme commande"; // Q7 boucleLecture(pALecture, ACHETEUR, signature); // On lit la question 1 char str2[MSGSIZE]; // pour utiliser la fonction sprintf() et convertir un int en str sprintf(str2, "%d", QteRouleauStock); write(pAEcriture[1], concat(msg2, str2), MSGSIZE); // Question 2: le serveur web transmet la quantite disponible en stock boucleLecture(pALecture, ACHETEUR, signature); // On lit la question 3 printf("%s. Calcul du nombre de palettes...\n", SERVEUR); printf("%s. Calcul du montant de la facture...\n", SERVEUR); write(pAEcriture[1], concat(msg4, getNombrePalettes()), MSGSIZE); // Question 4: le serveur transmet le nombre de palettes a l'acheteur write(pAEcriture[1], concat(msg4Bis, getMontantFacture()), MSGSIZE); // Question 4: le serveur transmet le montant de la facture a l'acheteur boucleLecture(pALecture, ACHETEUR, signature); // On lit la question 5 boucleLecture(pALecture, ACHETEUR, signature); write(pAEcriture[1], concat(msg6, getMontantFacture()), MSGSIZE); // Question 6: le serveur web envoie un accuse de reception du paiement a l'acheteur, rappelant le montant total de la transaction write(pTEcriture[1], concat(msg7, getNombrePalettes()), MSGSIZE); // Question 7: le serveur web transmet un bon de livraison comprenant le nombre de palettes de l'article choisi write(pTEcriture[1], msg7Bis, MSGSIZE); // Q7: en double exemplaire au transporteur } void transporteur(int pAEcriture[], int pALecture[], int pSLecture[]){ close(pAEcriture[0]); close(pALecture[1]); close(pSLecture[1]); int nread; char buf[MSGSIZE]; const char* signature = "TRANSPORTEUR"; char* msg8 = "Bonjour, je suis votre livreur. Voici les 2 bons de livraison"; // Q8 boucleLecture(pSLecture, SERVEUR, signature); // On lit la question 7 boucleLecture(pSLecture, SERVEUR, signature); write(pAEcriture[1], msg8, MSGSIZE); // Question 8: le transporteur livre à l'acheteur en lui remettant les 2 bons boucleLecture(pALecture, ACHETEUR, signature); } char* getNombrePalettes(){ int compteur = 1; int n = SURFACE; char *nbPalettes = (char*) malloc((10*sizeof(char))); if (n <= PALETTE){ sprintf(nbPalettes, "%d", compteur); return nbPalettes; } else { while (n > PALETTE){ n = n-PALETTE; compteur ++; } sprintf(nbPalettes, "%d", compteur); return nbPalettes; } } char* getMontantFacture(){ int prixTotal; char* prixFacture = NULL; prixFacture= (char*) malloc((10*sizeof(char))); prixTotal = (SURFACE * PrixRouleau); sprintf(prixFacture, "%d", prixTotal); return prixFacture; } char* concat(const char *s1, const char *s2){ char *result = malloc(strlen(s1) + strlen(s2) + 1); // +1 for the null-terminator strcpy(result, s1); strcat(result, s2); return result; } void boucleLecture (int p[], const char* ROLE, const char* signature){ int nread; char buf[MSGSIZE]; int dummy = 1; while (dummy) { // on fait une boucle infinie nread = read(p[0], buf, MSGSIZE); switch (nread) { case -1: if (errno == EAGAIN){ // Tube Vide sleep(1); break; } else { perror("read"); exit(100); } case 0: // Si nread == 0, ca veut dire qu'on est arrivés à la fin du buffer close(p[0]); // on ferme le pipe printf("\n[%s]. FERMETURE DU PIPE.\n", signature); exit(0); default: printf("[%s][%s]. Message recu de %s. Contenu = \"%s\".\n", signature, ACHETEUR, ROLE, buf); dummy = 0; break; } } } int getNombreDigit(char s[], int longueurVoulue){ int compteur=0; while(compteur<longueurVoulue){ //au plus longueurVoulue digits s[compteur]=getchar(); if(!isdigit(s[compteur])){ //break if non digit entered s[compteur]='\0';//end string with a null. break; } compteur++; } s[compteur]='\0'; return compteur; }
C
/****************************************************************************************** Функции работы с сокетами Copyright (с) Stanislav V. Tretyakov, [email protected] ******************************************************************************************/ #include "sys_socket.h" /*---------------------------------------------------------------- Общие функции ----------------------------------------------------------------*/ extern bool ss_valid_sock(socket_t sock_fd){ return (((sock_fd) >= 0) && ((sock_fd) < FD_SETSIZE) ? 1 : 0); } /* Функция закрывает ранее открытый сокет */ extern void ss_close(socket_t sock_fd){ if(ss_valid_sock(sock_fd)){ ss_nonblock(sock_fd, 0); shutdown(sock_fd, 0); shutdown(sock_fd, 1); close(sock_fd); } return; } /* Закрытие сокета на чтение */ extern void ss_close_read(socket_t sock_fd){ if(ss_valid_sock(sock_fd)) shutdown(sock_fd, 0); return; } /* Закрытие сокета на запись */ extern void ss_close_write(socket_t sock_fd){ if(ss_valid_sock(sock_fd)) shutdown(sock_fd, 1); return; } /* Установка сокета в блокируемое (не блокируемое) состояние возвращает 0 в случае успеха либо -1 в случае ошибки */ extern int ss_nonblock(socket_t sock_fd, int as_nonblock){ int flags; if(!ss_valid_sock(sock_fd)) return -1; if((flags = fcntl(sock_fd, F_GETFL, 0)) == -1) return -1; if(as_nonblock) return (fcntl(sock_fd, F_SETFL, flags | O_NONBLOCK) == -1 ? -1 : 0); else return (fcntl(sock_fd, F_SETFL, flags & (~O_NONBLOCK)) == -1 ? -1 : 0); } /* Ожидание соединения для начала записи / чтения timeout - время ожидания наступлени события в миллисекундах (1000 миллисекунд = 1 секунде), если событие не наступило по истечении заданного времени - возвращается 0 ev - события, которые должны произойти для успешного завершения функции ev = POLLWRNORM - ждет начала доступности сокета на запись ev = POLLRDNORM - ждет начала доступности сокета на чтение */ /* Ожидание соединения */ extern int ss_connwait(socket_t sock_fd, long timeout, bool for_read){ if(!ss_valid_sock(sock_fd)) return -1; int srv; fd_set fdset; fd_set fderr; struct timeval tv; struct timeval init_tv; struct timeval now_tv; gettimeofday(&init_tv, NULL); timeout = (timeout>0 ? timeout : _VSOCKET_CONNECT_WAIT); int wait_ms = timeout; FD_ZERO(&fdset); FD_ZERO(&fderr); FD_SET(sock_fd, &fdset); FD_SET(sock_fd, &fderr); do{ tv.tv_sec = floor(wait_ms / 1000); tv.tv_usec = (wait_ms % 1000) * 1000; srv = select(sock_fd + 1, (for_read ? &fdset : NULL), (for_read ? NULL : &fdset), &fderr, &tv); if(srv != -1) break; if (errno && errno != EINTR) break; gettimeofday(&now_tv, NULL); wait_ms = timeout - floor((now_tv.tv_sec-init_tv.tv_sec)*1000+(now_tv.tv_usec-init_tv.tv_usec)/1000); if(wait_ms <= 0) break; }while(srv == -1); if(srv < 0) return -1; if(srv == 0) return 0; if(FD_ISSET(sock_fd, &fderr)) return -1; if(FD_ISSET(sock_fd, &fdset)) return 1; return 0; } /* extern int ss_connwait(socket_t sock_fd, long timeout, bool for_read){ struct pollfd fds[1]; int pp = 0; short ev = (for_read ? POLLIN : POLLOUT); time_t start_time = time(NULL); fds[0].fd = sock_fd; fds[0].events = ev; timeout = (!timeout ? _VSOCKET_CONNECT_WAIT : timeout); do{ //Очень большой таймаут... if(time(NULL) - start_time > 10) return 0; pp = poll(fds, 1, timeout); }while (pp == -1 && errno == EINTR); if (pp == 0) return 0; //если таймаут if (pp < 0) return -1; //если ошибка return ((fds[0].revents & ev) ? 1 : 0); //успешно } */ /* Функция проводит операции по уcтановлению соединения с удаленным сервером по протоколу TCP В случае ошибки, если соединение установить не удалось, возвращается INVALID_SOCKET. В случае успешного соединения - его идентификатор. */ typedef struct{ pthread_t thread_id; bool completed; struct addrinfo hints; struct addrinfo * servinfo; const char * hostname; const char * port; int rv; }_gai_thr; static void * ss_gai_thr_funct(void * data){ _gai_thr * thr = (_gai_thr *)data; if(!thr) return NULL; thr->thread_id = pthread_self(); (void) pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL); thr->rv = getaddrinfo(thr->hostname, thr->port, &(thr->hints), &(thr->servinfo)); (void) pthread_setcanceltype (PTHREAD_CANCEL_DEFERRED, NULL); thr->completed = true; return NULL; } extern socket_t ss_connect(const char * hostname, const char * port, long timeout){ socket_t sock_fd; _gai_thr gthr; unsigned int iter = 0; struct addrinfo * p; int rv; //const int on = 1; if(!hostname || !port) return INVALID_SOCKET; if(!timeout) timeout = _VSOCKET_CONNECT_WAIT; memset(&gthr, 0, sizeof(gthr)); gthr.hints.ai_family = AF_INET; gthr.hints.ai_socktype = SOCK_STREAM; gthr.hints.ai_protocol = IPPROTO_TCP; gthr.hostname = hostname; gthr.port = port; //Создание потока получения информации от GetAddrInfo if (pthread_create(&gthr.thread_id, NULL, ss_gai_thr_funct, (void *) &gthr) != 0) return INVALID_SOCKET; while(!gthr.completed && iter < 50){ ++iter; su_msleep(100); } if(!gthr.completed){ (void) pthread_cancel(gthr.thread_id); } pthread_join( gthr.thread_id, NULL ); if (gthr.rv != 0){ if(gthr.servinfo) freeaddrinfo(gthr.servinfo); return INVALID_SOCKET; } if(!gthr.servinfo){ return INVALID_SOCKET; } //Просмотр всех полученных результатов адресов //в попытке установить соединение for(p = gthr.servinfo; p != NULL; p = p->ai_next){ //Открытие сокета //if((sock_fd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) continue; if((sock_fd = socket(AF_INET, SOCK_STREAM, 0)) == -1) continue; //Установка сокета в неблокируемое состояние if( ss_nonblock(sock_fd, 1) == -1){ ss_close(sock_fd); continue; } //Попытка установки соединения //rv = connect(sock_fd, p->ai_addr, p->ai_addrlen); rv = connect(sock_fd, (struct sockaddr *)p->ai_addr, sizeof(struct sockaddr)); //Обработка ошибки устаноки соединения //Это стандартное явление для неблокируемых сокетов if( rv == -1 ){ if( errno == EINPROGRESS || #if defined(EAGAIN) #if (EAGAIN) != (EWOULDBLOCK) errno == EAGAIN || #endif #endif errno == EALREADY ){ //Ожидание готовности соединения на запись данных rv = ss_connwait(sock_fd, timeout, false); //Соединение установлено if(rv == 1){ break; }else{ ss_nonblock(sock_fd, 0); ss_close(sock_fd); continue; } } else{ ss_nonblock(sock_fd, 0); ss_close(sock_fd); continue; } }//Обработка ошибки устаноки соединения //Соединение установлено //Далее нет смысла просматривать адреса break; } freeaddrinfo(gthr.servinfo); //Если были просмотрены все доступные адреса и //соединение не удалось установить - выход if(!p){ #if _VSOCKET_DEBUG_ERROR != 0 printf("_connect: getaddrinfo error: no records for: [%s] : [%s]\n", hostname, port); #endif return INVALID_SOCKET; } return sock_fd; } /* Чтение блока данных из сокета, функция пытается прочесть nleft байт из сокета sock_fd в буффер buf, возвращает количество прочитанных байт. в переменную status записывается результат работы функции -1 в случае ошибки 0 - если таймаут либо все данные были прочитаны 1 - если выполнено успешно На заметку: если прочитаны не все nleft байт, а меньшее количество, то с большой степенью вероятности, больше данных на чтение не будет, поэтому повторно вызывать _sread нет смысла. Разумеется, могут быть задержки при получении данных от удаленного сервера, но, поскольку функция будет ожидать новые данные еще как минимум интервал времени равный _VSOCKET_CONNECT_WAIT до момента своего завершения, то можно предположить, что следующий вызов _sread вернет ноль байт и статус завершения то таймауту. */ extern size_t ss_read(socket_t sock_fd, void * buf, size_t nleft, int * status, long timeout){ if(!ss_valid_sock(sock_fd)){ *status = -1; return 0; } void * ptr = buf; int ss,n; int nlefttoread = nleft; int flags = MSG_DONTWAIT; struct timeval init_tv; struct timeval now_tv; gettimeofday(&init_tv, NULL); timeout = (timeout > 0 ? timeout : _VSOCKET_READ_WAIT); int wait_ms = timeout; //Ожидание сокета на чтение ss = ss_connwait(sock_fd, wait_ms, true); if( ss < 1 ){ *status = ss; return 0; } for(;;){ //читаем данные do{ n = recv(sock_fd, ptr, nlefttoread, flags); } while (n == -1 && errno == EINTR); if( n < 0 ){ if(errno != EWOULDBLOCK && errno != EAGAIN){ *status = -1; return (size_t)(ptr-buf); } } //если данные получены else if( n > 0 ){ ptr += n; nlefttoread -= n; if(nlefttoread <= 0){ *status = 1; return (size_t)(ptr-buf); } } //все данные получены else if( n == 0 && nlefttoread < nleft) break; gettimeofday(&now_tv, NULL); wait_ms = timeout - floor((now_tv.tv_sec-init_tv.tv_sec)*1000+(now_tv.tv_usec-init_tv.tv_usec)/1000); if(wait_ms <= 0) break; //Ожидание сокета на чтение ss = ss_connwait(sock_fd, 1500, true); //если ошибка select if( ss < 1 ){ *status = ss; return (size_t)(ptr-buf); } } *status = 0; return (size_t)(ptr-buf); } /* Функция создает буфер для чтения данных, читает данные из сокета и возвращает указатель на начало данных Также записывает количество прочтенных данных в переменную len В переменную status записывается результат чтения данных 1 - все данные прочитаны 0 - таймаут -1 - ошибка чтения данных Примечание: функция возвращает указатель на выделенный блок памяти для буффера чтения, поэтому вызавающая функция сама должна заботиться об ее освобождении. Также иногда возвращается NULL */ extern char * ss_get(socket_t sock_fd, size_t * len, int * status, long timeout){ char * buf = NULL; char * ptr = NULL; size_t buf_size = 0; size_t need_size = 0; int to_read = 0; size_t readed = 0; size_t n = 0; *status = 1; /* //Ожидение готовности сокета на чтение //Если сокет не готов на чтение, выход по таймауту if ( ss_connwait(sock_fd, timeout, true) != 1){ *len = 0; *status = 0; printf("_vsock_get: timeout\n"); return NULL; } */ //Чтение данных из сокета for(;;){ //Рассчет размера буфера need_size += _VSOCKET_BLOCK_SIZE; //Если размер буффера более допустимого лимита if(need_size > _VSOCKET_SCONTENT_LIMIT){ need_size = _VSOCKET_SCONTENT_LIMIT; } //Выделение либо увеличение памяти под буффер чтения if(buf_size < need_size){ buf = (char *)sm_realloc(buf, need_size); //Если не удалось выделить / увеличить объем памяти //немедленно завершение функции if(!buf){ *len = readed; *status = -1; printf("_vsock_get: can not allocated memory for buffer\n"); return NULL; } buf_size = need_size; //Ставим указатель для начала записи на последнюю позицию ptr = (char *)(buf + readed); //Количество байт, которые надо прочитать //-1 байт для символа 0x00 to_read = buf_size - readed - 1; //Если to_read = 0 - выход if(to_read < 1) break; } //Если текуший размер буфера равен либо больше требуемого //то для избежания переполнения буфера - прерываем чтение else{ break; } //Чтение данных в буфер n = ss_read(sock_fd, ptr, to_read, status, timeout); //+n прочитанных байт readed += n; buf[readed] = 0x00; //статус не 1 (выполнено успешно) //завершаем чтение if(n < to_read || *status != 1) break; }//Чтение данных из сокета *len = readed; buf[readed] = 0x00; return buf; } /* Отправка данных функция пытается отправить nleft байт из буффера buf, возвращает количество прочитанных байт. Возвращает в результате -1 в случае ошибки 0 - если таймаут 1 - выполнено успешно */ extern int ss_write(socket_t sock_fd, const void * buf, size_t n){ if(!ss_valid_sock(sock_fd)) return -1; int nleft = n; ssize_t nwritten; const void * ptr = buf; int ss; struct timeval init_tv; struct timeval now_tv; gettimeofday(&init_tv, NULL); int wait_ms = _VSOCKET_WRITE_WAIT; //Ожидание сокета на запись ss = ss_connwait(sock_fd, wait_ms, false); if( ss < 1 ){ return ss; } for(;;){ do{ nwritten = write(sock_fd, ptr, nleft); } while (nwritten == -1 && errno == EINTR); if(nwritten < 1){ if(nwritten == -1 && errno != EWOULDBLOCK && errno != EAGAIN) return -1;// error } else{ nleft -= nwritten; ptr += nwritten; } if(nleft <= 0) return 1; gettimeofday(&now_tv, NULL); wait_ms = _VSOCKET_WRITE_WAIT - floor((now_tv.tv_sec-init_tv.tv_sec)*1000+(now_tv.tv_usec-init_tv.tv_usec)/1000); if(wait_ms <= 0) break; //Ожидание сокета на чтение ss = ss_connwait(sock_fd, wait_ms, false); //если ошибка либо таймаут if( ss < 1 ) return ss; }//for return 1; } /*---------------------------------------------------------------- Функции сервера ----------------------------------------------------------------*/ /* Принять входящее соединение] */ extern socket_t ss_accept(socket_t sock_fd, struct sockaddr *saptr, socklen_t *salenptr){ socket_t n; again: if ( (n = accept(sock_fd, saptr, salenptr)) < 0) { #ifdef EPROTO if (errno == EPROTO || errno == ECONNABORTED) #else if (errno == ECONNABORTED) #endif goto again; else return INVALID_SOCKET; } return n; } /* Инициализация TCP прослушивающего сокета, возвращает идентификатор прослушивающего сокета в случае успеха либо INVALID_SOCKET, если не удалось инициализировать прослушивающий сокет */ extern socket_t ss_listen(const char *host, const char *port, socklen_t * addrlenp){ socket_t listen_fd; int rv; const int on = 1; struct addrinfo hints; struct addrinfo * res; struct addrinfo * ressave; //Получение информации о хосте memset(&hints, 0, sizeof(struct addrinfo)); hints.ai_flags = AI_PASSIVE; hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; if ( (rv = getaddrinfo(host, port, &hints, &res)) != 0){ #if _VSOCKET_DEBUG_ERROR != 0 printf("_stcp_listen: getaddrinfo error: %s\n", gai_strerror(rv)); #endif return INVALID_SOCKET; } ressave = res; do { listen_fd = socket(res->ai_family, res->ai_socktype, res->ai_protocol); if (listen_fd < 0) continue; setsockopt(listen_fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)); setsockopt(listen_fd, SOL_SOCKET, SO_KEEPALIVE, &on, sizeof(on)); if (bind(listen_fd, res->ai_addr, res->ai_addrlen) == 0) break; ss_close(listen_fd); } while ( (res = res->ai_next) != NULL); if(!res) return INVALID_SOCKET; listen(listen_fd, _VSOCKET_LISTENQ); if (addrlenp) *addrlenp = res->ai_addrlen; freeaddrinfo(ressave); return listen_fd; }
C
/* * main.c * * Created on: Aug 31, 2021 * Author: shrouk */ #include "stdio.h" void main () { int n1,i; float average=0,sum=0; printf("Enter the numbers of data:"); fflush(stdout); fflush(stdin); scanf("%d",&n1); float arr[n1]; for(i=0;i<n1;i++){ printf("%d.Enter number:",++i); --i; fflush(stdout); fflush(stdin); scanf("%f",&arr[i]); sum+=arr[i]; if(i==n1-1){ average=sum/n1; printf("Average:%.2f",average); } } }
C
#include <stdio.h> #include <stdlib.h> int x[] = {1,2,3,-1,-2,0,184,340057058}; int y[] = {0,0,0,0,0,0,0,0}; int f(int a) { int i = 0; while(a != 0) { if ((a & 0x80000000) != 0) i++; a = a << 1; } return i; } int main (int argc, char* argv[]) { for (int i = 7; i>=0; i--){ y[i] = f(x[i]); } for(int i = 0; i < 8; i++){ printf("%d\n", x[i]); } for(int i = 0; i < 8; i++){ printf("%d\n", y[i]); } }
C
/* * File: usart.c * Author: YH31 * * Created on May 8, 2020, 9:26 AM */ #include "usart.h" #include "lcd.h" void UsartInit() { // 1.SPBRGò // //貨ΪK,SPBRGֵΪx //TXSTA<2>ֵΪ1 //ôͬ첽ʹùʽ£ //x=Fosc/(K*16)-1 //TXSTA<2>ֵΪ0 //ͬģʽ£x=Fosc/(K*4)-1 //첽ģʽ£x=Fosc/(K*64)-1 //ǰK=20000000,ҪK=9600,TXSTA<2>=1 //x=20000000/(9600*16)-1 SPBRG = 0x82; // 2÷ //ƼĴ,첽ģʽ //ڲʱ|8λ|ʹ|첽ģʽ|Ͳ // TXSTA=_TXSTA_TXEN_MASK|_TXSTA_BRGH_MASK; TXSTAbits.TX9 = 0; //8λ TXSTAbits.TXEN = 1; //ʹ TXSTAbits.SYNC = 0; //ʹ첽ģʽ TXSTAbits.BRGH = 1; //ʹģʽ㲨 // Ҫʹжϣôжʹ // INTCONbits.GIE=1; // INTCONbits.PEIE=1; // PIE1bits.TXIE=1; //3ý //տƼĴ //ʹܣὫRC6/RC7óɴţ|8λ|첽ʹ,ûżУ // RCSTA = _RCSTA_SPEN_MASK | _RCSTA_CREN_MASK; RCSTAbits.SPEN = 1; //ʹ RCSTAbits.RX9 = 0; //8λ RCSTAbits.CREN = 1; //첽 // Ҫʹжϣôжʹ // INTCONbits.GIE=1; // INTCONbits.PEIE=1; // PIE1bits.RCIE=1; } //͵ void serial_tx(unsigned char val) { TXREG = val; //TSRΪգ˵ûд,TXREGĴǴTSR while (!TXSTAbits.TRMT); } //ַ void serial_tx_str(const char* val) { unsigned char i = 0; while (val[i]) { serial_tx(val[i]); i++; } } // //ʱʱtimeount40usı unsigned char serial_rx() { unsigned int to = 0; //֡󣬻 ͨCRENý if (RCSTAbits.FERR || RCSTAbits.OERR)//trata erro { RCSTAbits.CREN = 0; RCSTAbits.CREN = 1; } //жRCIF״̬1,ôʾRCREGĴеֵǽյ if (PIR1bits.RCIF) return RCREG; else return 0xA5; }
C
#include <stdio.h> /*6. Tipos estruturados. Exercício 6.2 */ //Define a estrutura de vetor typedef struct vetor{ float x, y, z; } Vetor; /*Função que retorna o produto de dois vetores */ float dot ( Vetor* v1, Vetor* v2 ) { float prod; prod = ( v1->x * v2->x ) + ( v1->y * v2->y ) + ( v1->z * v2->z ); return prod; } /*Função principal */ int main( void ) { Vetor a, b; float produto; printf( "Dê um vetor a = (x, y, z): " ); scanf( " %f %f %f", &a.x, &a.y, &a.z ); printf( "Dê outro vetor b = (x, y, z): " ); scanf( " %f %f %f", &b.x, &b.y, &b.z ); produto = dot( &a, &b ); printf( "O produto de a(%.1f, %.1f, %.1f) x b(%.1f, %.1f, %.1f) = %.1f\n", a.x, a.y, a.z, b.x, b.y, b.z, produto ); return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* get_next_line.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ialvarez <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/04/26 16:12:56 by ialvarez #+# #+# */ /* Updated: 2021/05/07 15:05:01 by ialvarez ### ########.fr */ /* */ /* ************************************************************************** */ #include "get_next_line.h" static void norris(char **reader, char *rest, int fd, int i) { char *aux; while (i > 0) { rest[i] = '\0'; if (!reader[fd]) reader[fd] = ft_strdup(rest); else { aux = ft_strjoin(reader[fd], rest); free(reader[fd]); reader[fd] = aux; } if (ft_strchr(rest, '\n')) break ; i = read(fd, rest, BUFFER_SIZE); } } static int floki(int i, int fd, char **line, char **reader) { char *tempor; char *aux; if (!reader[fd] && !i) { *line = ft_strdup(""); return (0); } tempor = ft_strchr(reader[fd], '\n'); if (tempor) { *tempor = '\0'; *line = ft_strdup(reader[fd]); aux = ft_strdup(++tempor); free(reader[fd]); reader[fd] = aux; return (1); } else { *line = reader[fd]; reader[fd] = NULL; } return (0); } int get_next_line(int fd, char **line) { static char *reader[4096]; char rest[BUFFER_SIZE + 1]; int i; if (BUFFER_SIZE < 1 || !line || fd < 0 || read(fd, rest, 0) < 0) return (-1); if (reader[fd] && ft_strchr(reader[fd], '\n')) return (floki(1, fd, line, reader)); i = read(fd, rest, BUFFER_SIZE); norris(reader, rest, fd, i); return (floki(i, fd, line, reader)); } /* int main(void) { char *line; int fd; int stat; fd = open("lotr.txt", O_RDONLY); stat = get_next_line(fd, &line); while (stat >= 0) { printf("%s\n", line); free(line); line = NULL; if (stat == 0) break ; stat = get_next_line(fd, &line); } free(line); line = NULL; close(fd); system("leaks a.out"); return (0); } */
C
/*6 length of a string using pointers*/ #include <stdio.h> int main() { char str1[50],*p; printf("\nEnter a string: "); scanf("%s",str1); p=str1; int count=0; while (*p !='\0') { count++; p++; } printf("the length of the string is %d",count); }
C
// Evan Smedley 101148695 // Trong Nguyen 100848232 #include <sys/shm.h> #include <stdlib.h> #include <stdio.h> // Create shared memory int shm_create(key_t key, int size) { int shmid = shmget(key, size, IPC_CREAT | 0666); if (shmid == -1) { fprintf(stderr, "shmget failed\n"); exit(EXIT_FAILURE); } return shmid; } // Access shared memory void *shm_access(int shmid) { void *shared_memory = shmat(shmid, (void *)0, 0); if (shared_memory == (void *)-1) { fprintf(stderr, "shmat failed\n"); exit(EXIT_FAILURE); } return shared_memory; } // Detach shared memory void shm_detach(void *shared_memory) { if (shmdt(shared_memory) == -1) { fprintf(stderr, "shmdt failed \n"); exit(EXIT_FAILURE); } } // Delete shared memory void shm_delete(int shmid) { if (shmctl(shmid, IPC_RMID, 0) == -1) { fprintf(stderr, "shmctl(IPC_RMID) failed \n"); exit(EXIT_FAILURE); } }
C
#include<math.h> #include<stdio.h> int main(){ prime_test_sqrt(99999991); // prime_test_half(99999991); } //------------------------------------------- prime_test_half(int num){ printf("Half Trick Function \n"); int tnum=0; tnum = num / 2; int count = 0; for(int i=1; i <= tnum; i++){ printf("count_half\n"); if( !(num%i) ){ count = count + 1; } } if(count == 1){ // return 1; printf("prime"); }else{ // return 0; printf("composite"); } } //----------------------------------------- prime_test_sqrt(int num){ printf("sqrt Trick Function \n"); int tnum=0; tnum = sqrt(num); int count = 0; for(int i=1; i <= tnum; i++){ printf("count_sqrt\n"); if( !(num%i) ){ count = count + 1; } } if(count == 1){ // return 1; printf("prime"); }else{ // return 0; printf("composite"); } }
C
#define _CRT_SECURE_NO_WARNINGS 1 #include<stdio.h> #include<stdlib.h> int main() { int sn = 0; int a = 2; sn = a * 5 + a * 4 * 10 + a * 3 * 100 + a * 2 * 1000 + a * 10000; printf("%d", sn); system("pause"); return 0; }
C
#include<stdio.h> int stack[20]; int top=-1; void push(char data){ top++; stack[top]=data; } void pop(){ if(top==-1){ printf("Nothing to be removed"); } else top--; } int empty(){ if(top==-1) return 1; //1-> stack empty else return 0; //0-> stack is not empty//(a+b)*(c+d) } int main() { char str[20]; scanf("%s",str); for(int ind=0;str[ind]!='\0';ind++) { if(str[ind]=='['||str[ind]=='{'||str[ind]=='(') push(str[ind]); else if((stack[top]=='('&&str[ind]==')')||(stack[top]=='{'&&str[ind]=='}')||(stack[top]=='['&&str[ind]==']')) pop(); else if(('a'<=str[ind]&&str[ind]<='z')||('A'<=str[ind]&&str[ind]<='Z')||str[ind]=='+'||'-'||'*'||'/') continue; else { printf("Invalid"); return 0; } } if(empty()) printf("VALID"); else printf("INVALID"); } //Alternate Program /*#include<stdio.h> #define N 100 char stack[N]; int indx=-1; void push(char data){ indx++; stack[indx]=data; } void pop(){ if(indx==-1){ printf("Nothing to be removed"); } else indx--; } char top(){ return stack[indx]; } int empty(){ if(indx==-1) return 1; //1-> stack empty else return 0; //0-> stack is not empty } int main(){ char s[100]; scanf("%s",&s); for(int i=0;s[i]!='\0';i++){ if(s[i]=='(' || s[i]=='{' || s[i]=='[') push(s[i]); else{ if(empty()){ printf("INVALID"); return 0; }else{ char t=top(); if(t=='(' && s[i]==')' || t=='['&&s[i]==']' || t=='{'&&s[i]=='}') pop(); else{ printf("INVALID"); return 0; } } } } if(empty()) printf("VALID"); else printf("INVALID"); }*/
C
/*************************************************************************** VCS-80 12/05/2009 Skeleton driver. http://hc-ddr.hucki.net/entwicklungssysteme.htm#VCS_80_von_Eckhard_Schiller This system is heavily based on the tk80. The display and keyboard matrix are very similar, while the operation is easier in the vcs80. The hardware is completely different however. Pasting: 0-F : as is A+ : ^ A- : V MA : - GO : X When booted, the system begins at 0000 which is ROM. You need to change the address to 0400 before entering a program. Here is a test to paste in: 0400-11^22^33^44^55^66^77^88^99^0400- Press the up-arrow to confirm data has been entered. Operation: 4 digits at left is the address; 2 digits at right is the data. As you increment addresses, the middle 2 digits show the previous byte. You can enter 4 digits, and pressing 'MA' will transfer this info to the left, thus setting the address to this value. Press 'A+' to store new data and increment the address. ****************************************************************************/ #include "includes/vcs80.h" #include "vcs80.lh" /* Read/Write Handlers */ READ8_MEMBER( vcs80_state::pio_r ) { switch (offset) { case 0: return z80pio_c_r(m_pio, 1); case 1: return z80pio_c_r(m_pio, 0); case 2: return z80pio_d_r(m_pio, 1); case 3: return z80pio_d_r(m_pio, 0); } return 0; } WRITE8_MEMBER( vcs80_state::pio_w ) { switch (offset) { case 0: z80pio_c_w(m_pio, 1, data); break; case 1: z80pio_c_w(m_pio, 0, data); break; case 2: z80pio_d_w(m_pio, 1, data); break; case 3: z80pio_d_w(m_pio, 0, data); break; } } /* Memory Maps */ static ADDRESS_MAP_START( vcs80_mem, AS_PROGRAM, 8, vcs80_state ) AM_RANGE(0x0000, 0x01ff) AM_ROM AM_RANGE(0x0400, 0x07ff) AM_RAM ADDRESS_MAP_END static ADDRESS_MAP_START( vcs80_io, AS_IO, 8, vcs80_state ) ADDRESS_MAP_GLOBAL_MASK(0xff) AM_RANGE(0x04, 0x07) AM_READWRITE(pio_r, pio_w) ADDRESS_MAP_END /* Input Ports */ static INPUT_PORTS_START( vcs80 ) PORT_START("ROW0") PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_0) PORT_CHAR('0') PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_1) PORT_CHAR('1') PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_2) PORT_CHAR('2') PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_3) PORT_CHAR('3') PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_4) PORT_CHAR('4') PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_5) PORT_CHAR('5') PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_6) PORT_CHAR('6') PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_7) PORT_CHAR('7') PORT_START("ROW1") PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_8) PORT_CHAR('8') PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_9) PORT_CHAR('9') PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_A) PORT_CHAR('A') PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_B) PORT_CHAR('B') PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_C) PORT_CHAR('C') PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_D) PORT_CHAR('D') PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_E) PORT_CHAR('E') PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_F) PORT_CHAR('F') PORT_START("ROW2") PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_NAME("A+") PORT_CODE(KEYCODE_UP) PORT_CHAR('^') PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_NAME("A-") PORT_CODE(KEYCODE_DOWN) PORT_CHAR('V') PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_NAME("MA") PORT_CODE(KEYCODE_M) PORT_CHAR('-') PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_NAME("RE") PORT_CODE(KEYCODE_R) PORT_CHAR('R') PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_NAME("GO") PORT_CODE(KEYCODE_G) PORT_CODE(KEYCODE_X) PORT_CHAR('X') PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_NAME("TR") PORT_CODE(KEYCODE_T) PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_NAME("ST") PORT_CODE(KEYCODE_S) PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_NAME("PE") PORT_CODE(KEYCODE_P) INPUT_PORTS_END /* Z80-PIO Interface */ static TIMER_DEVICE_CALLBACK( vcs80_keyboard_tick ) { vcs80_state *state = timer.machine().driver_data<vcs80_state>(); if (state->m_keyclk) { state->m_keylatch++; state->m_keylatch &= 7; } z80pio_pa_w(state->m_pio, 0, state->m_keyclk << 7); state->m_keyclk = !state->m_keyclk; } READ8_MEMBER( vcs80_state::pio_pa_r ) { /* bit description PA0 keyboard and led latch bit 0 PA1 keyboard and led latch bit 1 PA2 keyboard and led latch bit 2 PA3 GND PA4 keyboard row input 0 PA5 keyboard row input 1 PA6 keyboard row input 2 PA7 demultiplexer clock input */ UINT8 data = 0; /* keyboard and led latch */ data |= m_keylatch; /* keyboard rows */ data |= BIT(input_port_read(machine(), "ROW0"), m_keylatch) << 4; data |= BIT(input_port_read(machine(), "ROW1"), m_keylatch) << 5; data |= BIT(input_port_read(machine(), "ROW2"), m_keylatch) << 6; /* demultiplexer clock */ data |= (m_keyclk << 7); return data; } WRITE8_MEMBER( vcs80_state::pio_pb_w ) { /* bit description PB0 VQD30 segment A PB1 VQD30 segment B PB2 VQD30 segment C PB3 VQD30 segment D PB4 VQD30 segment E PB5 VQD30 segment G PB6 VQD30 segment F PB7 _A0 */ UINT8 led_data = BITSWAP8(data & 0x7f, 7, 5, 6, 4, 3, 2, 1, 0); int digit = m_keylatch; /* skip middle digit */ if (digit > 3) digit++; output_set_digit_value(8 - digit, led_data); } static Z80PIO_INTERFACE( pio_intf ) { DEVCB_CPU_INPUT_LINE(Z80_TAG, INPUT_LINE_IRQ0), /* callback when change interrupt status */ DEVCB_DRIVER_MEMBER(vcs80_state, pio_pa_r), /* port A read callback */ DEVCB_NULL, /* port A write callback */ DEVCB_NULL, /* portA ready active callback */ DEVCB_NULL, /* port B read callback */ DEVCB_DRIVER_MEMBER(vcs80_state, pio_pb_w), /* port B write callback */ DEVCB_NULL /* portB ready active callback */ }; /* Z80 Daisy Chain */ static const z80_daisy_config vcs80_daisy_chain[] = { { Z80PIO_TAG }, { NULL } }; /* Machine Initialization */ void vcs80_state::machine_start() { z80pio_astb_w(m_pio, 1); z80pio_bstb_w(m_pio, 1); /* register for state saving */ save_item(NAME(m_keylatch)); save_item(NAME(m_keyclk)); } /* Machine Driver */ static MACHINE_CONFIG_START( vcs80, vcs80_state ) /* basic machine hardware */ MCFG_CPU_ADD(Z80_TAG, Z80, XTAL_5MHz/2) /* U880D */ MCFG_CPU_PROGRAM_MAP(vcs80_mem) MCFG_CPU_IO_MAP(vcs80_io) MCFG_CPU_CONFIG(vcs80_daisy_chain) /* keyboard timer */ MCFG_TIMER_ADD_PERIODIC("keyboard", vcs80_keyboard_tick, attotime::from_hz(1000)) /* video hardware */ MCFG_DEFAULT_LAYOUT( layout_vcs80 ) /* devices */ MCFG_Z80PIO_ADD(Z80PIO_TAG, XTAL_5MHz/2, pio_intf) /* internal ram */ MCFG_RAM_ADD(RAM_TAG) MCFG_RAM_DEFAULT_SIZE("1K") MACHINE_CONFIG_END /* ROMs */ ROM_START( vcs80 ) ROM_REGION( 0x10000, Z80_TAG, 0 ) ROM_LOAD( "monitor.rom", 0x0000, 0x0200, CRC(44aff4e9) SHA1(3472e5a9357eaba3ed6de65dee2b1c6b29349dd2) ) ROM_END /* Driver Initialization */ DIRECT_UPDATE_HANDLER( vcs80_direct_update_handler ) { vcs80_state *state = machine.driver_data<vcs80_state>(); /* _A0 is connected to PIO PB7 */ z80pio_pb_w(state->m_pio, 0, (!BIT(address, 0)) << 7); return address; } static DRIVER_INIT( vcs80 ) { machine.device(Z80_TAG)->memory().space(AS_PROGRAM)->set_direct_update_handler(direct_update_delegate(FUNC(vcs80_direct_update_handler), &machine)); machine.device(Z80_TAG)->memory().space(AS_IO)->set_direct_update_handler(direct_update_delegate(FUNC(vcs80_direct_update_handler), &machine)); } /* System Drivers */ /* YEAR NAME PARENT COMPAT MACHINE INPUT INIT COMPANY FULLNAME FLAGS */ COMP( 1983, vcs80, 0, 0, vcs80, vcs80, vcs80, "Eckhard Schiller", "VCS-80", GAME_SUPPORTS_SAVE | GAME_NO_SOUND)
C
//test code from // https://www.geeksforgeeks.org/multithreading-c-2/ /*compile gcc -Wall thrvar.c -o thrvar -l pthread test code from https://www.geeksforgeeks.org/multithreading-c-2/ */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <pthread.h> // Let us create a global variable to change it in threads int g = 0; // The function to be executed by all threads void *myThreadFun(void *vargp) { // Store the value argument passed to this thread int *myid = (int *)vargp; // Let us create a static variable to observe its changes static int s = 0; // Change static and global variables ++s; ++g; // Print the argument, static and global variables printf("Thread ID: %d, Static: %d, Global: %d\n", *myid, ++s, ++g); } int main() { int i; pthread_t tid; // Let us create three threads for (i = 0; i < 3; i++) pthread_create(&tid, NULL, myThreadFun, (void *)&tid); pthread_exit(NULL); return 0; }
C
#include <stdio.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <inttypes.h> enum { STRUCT_SIZE = 12, BUF_SIZE = 3 }; int dfs(int fd, int idx) { off_t offset = idx * STRUCT_SIZE; if (lseek(fd, offset, SEEK_SET) == -1) { fprintf(stderr, "Invalid input\n"); return 1; } int32_t buf[BUF_SIZE]; int32_t key, left_idx, right_idx; if (read(fd, buf, sizeof(buf)) != sizeof(buf)) { fprintf(stderr, "Invalid input\n"); return 1; } key = buf[0]; left_idx = buf[1]; right_idx = buf[2]; if (right_idx) { int dfs_ret = dfs(fd, right_idx); if (dfs_ret) { return dfs_ret; } } printf("%" PRId32 " ", key); if (left_idx) { int dfs_ret = dfs(fd, left_idx); if (dfs_ret) { return dfs_ret; } } return 0; } int main(int argc, char *argv[]) { int fd = open(argv[1], O_RDONLY); if (fd == -1) { fprintf(stderr, "Can't open file\n"); return 1; } int dfs_ret = dfs(fd, 0); if (dfs_ret) { return dfs_ret; } putchar('\n'); close(fd); return 0; }
C
int reverse(int x) { int temp = x; int sol = 0; for (; temp != 0; ) { sol = sol * 10 + temp % 10; temp = temp / 10; } }
C
#include <stdlib.h> #include <string.h> #include <stdio.h> #include "document_create.h" document_create_t *document_create_create( long dispatchJobId, char *notes, char *documentTypeUuid, list_t *fields ) { document_create_t *document_create = malloc(sizeof(document_create_t)); document_create->dispatchJobId = dispatchJobId; document_create->notes = notes; document_create->documentTypeUuid = documentTypeUuid; document_create->fields = fields; return document_create; } void document_create_free(document_create_t *document_create) { listEntry_t *listEntry; free(document_create->notes); free(document_create->documentTypeUuid); list_ForEach(listEntry, document_create->fields) { document_field_free(listEntry->data); } list_free(document_create->fields); free(document_create); } cJSON *document_create_convertToJSON(document_create_t *document_create) { cJSON *item = cJSON_CreateObject(); // document_create->dispatchJobId if(cJSON_AddNumberToObject(item, "dispatchJobId", document_create->dispatchJobId) == NULL) { goto fail; //Numeric } // document_create->notes if(cJSON_AddStringToObject(item, "notes", document_create->notes) == NULL) { goto fail; //String } // document_create->documentTypeUuid if(cJSON_AddStringToObject(item, "documentTypeUuid", document_create->documentTypeUuid) == NULL) { goto fail; //String } // document_create->fields cJSON *fields = cJSON_AddArrayToObject(item, "fields"); if(fields == NULL) { goto fail; //nonprimitive container } listEntry_t *fieldsListEntry; list_ForEach(fieldsListEntry, document_create->fields) { cJSON *item = document_field_convertToJSON(fieldsListEntry->data); if(item == NULL) { goto fail; } cJSON_AddItemToArray(fields, item); } return item; fail: cJSON_Delete(item); return NULL; } document_create_t *document_create_parseFromJSON(char *jsonString){ document_create_t *document_create = NULL; cJSON *document_createJSON = cJSON_Parse(jsonString); if(document_createJSON == NULL){ const char *error_ptr = cJSON_GetErrorPtr(); if (error_ptr != NULL) { fprintf(stderr, "Error Before: %s\n", error_ptr); goto end; } } // document_create->dispatchJobId cJSON *dispatchJobId = cJSON_GetObjectItemCaseSensitive(document_createJSON, "dispatchJobId"); if(!cJSON_IsNumber(dispatchJobId)) { goto end; //Numeric } // document_create->notes cJSON *notes = cJSON_GetObjectItemCaseSensitive(document_createJSON, "notes"); if(!cJSON_IsString(notes) || (notes->valuestring == NULL)){ goto end; //String } // document_create->documentTypeUuid cJSON *documentTypeUuid = cJSON_GetObjectItemCaseSensitive(document_createJSON, "documentTypeUuid"); if(!cJSON_IsString(documentTypeUuid) || (documentTypeUuid->valuestring == NULL)){ goto end; //String } // document_create->fields cJSON *fields; cJSON *fieldsJSON = cJSON_GetObjectItemCaseSensitive(document_createJSON,"fields"); if(!cJSON_IsArray(fieldsJSON)){ goto end; //nonprimitive container } list_t *fieldsList = list_create(); cJSON_ArrayForEach(fields,fieldsJSON ) { if(!cJSON_IsObject(fields)){ goto end; } char *JSONData = cJSON_Print(fields); document_field_t *fieldsItem = document_field_parseFromJSON(JSONData); list_addElement(fieldsList, fieldsItem); free(JSONData); } document_create = document_create_create ( dispatchJobId->valuedouble, strdup(notes->valuestring), strdup(documentTypeUuid->valuestring), fieldsList ); cJSON_Delete(document_createJSON); return document_create; end: cJSON_Delete(document_createJSON); return NULL; }
C
#include <petscsys.h> /*I "petscsys.h" I*/ /*@C PetscGatherNumberOfMessages - Computes the number of messages a node expects to receive Collective Input Parameters: + comm - Communicator . iflags - an array of integers of length sizeof(comm). A '1' in ilengths[i] represent a message from current node to ith node. Optionally NULL - ilengths - Non zero ilengths[i] represent a message to i of length ilengths[i]. Optionally NULL. Output Parameters: . nrecvs - number of messages received Level: developer Notes: With this info, the correct message lengths can be determined using PetscGatherMessageLengths() Either iflags or ilengths should be provided. If iflags is not provided (NULL) it can be computed from ilengths. If iflags is provided, ilengths is not required. .seealso: PetscGatherMessageLengths() @*/ PetscErrorCode PetscGatherNumberOfMessages(MPI_Comm comm,const PetscMPIInt iflags[],const PetscMPIInt ilengths[],PetscMPIInt *nrecvs) { PetscMPIInt size,rank,*recv_buf,i,*iflags_local = NULL,*iflags_localm = NULL; PetscErrorCode ierr; PetscFunctionBegin; ierr = MPI_Comm_size(comm,&size);CHKERRQ(ierr); ierr = MPI_Comm_rank(comm,&rank);CHKERRQ(ierr); ierr = PetscMalloc2(size,&recv_buf,size,&iflags_localm);CHKERRQ(ierr); /* If iflags not provided, compute iflags from ilengths */ if (!iflags) { if (!ilengths) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Either iflags or ilengths should be provided"); iflags_local = iflags_localm; for (i=0; i<size; i++) { if (ilengths[i]) iflags_local[i] = 1; else iflags_local[i] = 0; } } else iflags_local = (PetscMPIInt*) iflags; /* Post an allreduce to determine the numer of messages the current node will receive */ ierr = MPIU_Allreduce(iflags_local,recv_buf,size,MPI_INT,MPI_SUM,comm);CHKERRQ(ierr); *nrecvs = recv_buf[rank]; ierr = PetscFree2(recv_buf,iflags_localm);CHKERRQ(ierr); PetscFunctionReturn(0); } /*@C PetscGatherMessageLengths - Computes info about messages that a MPI-node will receive, including (from-id,length) pairs for each message. Collective Input Parameters: + comm - Communicator . nsends - number of messages that are to be sent. . nrecvs - number of messages being received - ilengths - an array of integers of length sizeof(comm) a non zero ilengths[i] represent a message to i of length ilengths[i] Output Parameters: + onodes - list of node-ids from which messages are expected - olengths - corresponding message lengths Level: developer Notes: With this info, the correct MPI_Irecv() can be posted with the correct from-id, with a buffer with the right amount of memory required. The calling function deallocates the memory in onodes and olengths To determine nrecevs, one can use PetscGatherNumberOfMessages() .seealso: PetscGatherNumberOfMessages() @*/ PetscErrorCode PetscGatherMessageLengths(MPI_Comm comm,PetscMPIInt nsends,PetscMPIInt nrecvs,const PetscMPIInt ilengths[],PetscMPIInt **onodes,PetscMPIInt **olengths) { PetscErrorCode ierr; PetscMPIInt size,rank,tag,i,j; MPI_Request *s_waits = NULL,*r_waits = NULL; MPI_Status *w_status = NULL; PetscFunctionBegin; ierr = MPI_Comm_size(comm,&size);CHKERRQ(ierr); ierr = MPI_Comm_rank(comm,&rank);CHKERRQ(ierr); ierr = PetscCommGetNewTag(comm,&tag);CHKERRQ(ierr); /* cannot use PetscMalloc3() here because in the call to MPI_Waitall() they MUST be contiguous */ ierr = PetscMalloc2(nrecvs+nsends,&r_waits,nrecvs+nsends,&w_status);CHKERRQ(ierr); s_waits = r_waits+nrecvs; /* Post the Irecv to get the message length-info */ ierr = PetscMalloc1(nrecvs,olengths);CHKERRQ(ierr); for (i=0; i<nrecvs; i++) { ierr = MPI_Irecv((*olengths)+i,1,MPI_INT,MPI_ANY_SOURCE,tag,comm,r_waits+i);CHKERRQ(ierr); } /* Post the Isends with the message length-info */ for (i=0,j=0; i<size; ++i) { if (ilengths[i]) { ierr = MPI_Isend((void*)(ilengths+i),1,MPI_INT,i,tag,comm,s_waits+j);CHKERRQ(ierr); j++; } } /* Post waits on sends and receivs */ if (nrecvs+nsends) {ierr = MPI_Waitall(nrecvs+nsends,r_waits,w_status);CHKERRQ(ierr);} /* Pack up the received data */ ierr = PetscMalloc1(nrecvs,onodes);CHKERRQ(ierr); for (i=0; i<nrecvs; ++i) { (*onodes)[i] = w_status[i].MPI_SOURCE; #if defined(PETSC_HAVE_OMPI_MAJOR_VERSION) /* This line is a workaround for a bug in OpenMPI-2.1.1 distributed by Ubuntu-18.04.2 LTS. It happens in self-to-self MPI_Send/Recv using MPI_ANY_SOURCE for message matching. OpenMPI does not put correct value in recv buffer. See also https://lists.mcs.anl.gov/pipermail/petsc-dev/2019-July/024803.html https://www.mail-archive.com/[email protected]//msg33383.html */ if (w_status[i].MPI_SOURCE == rank) (*olengths)[i] = ilengths[rank]; #endif } ierr = PetscFree2(r_waits,w_status);CHKERRQ(ierr); PetscFunctionReturn(0); } /*@C PetscGatherMessageLengths2 - Computes info about messages that a MPI-node will receive, including (from-id,length) pairs for each message. Same functionality as PetscGatherMessageLengths() except it takes TWO ilenths and output TWO olengths. Collective Input Parameters: + comm - Communicator . nsends - number of messages that are to be sent. . nrecvs - number of messages being received - ilengths1, ilengths2 - array of integers of length sizeof(comm) a non zero ilengths[i] represent a message to i of length ilengths[i] Output Parameters: + onodes - list of node-ids from which messages are expected - olengths1, olengths2 - corresponding message lengths Level: developer Notes: With this info, the correct MPI_Irecv() can be posted with the correct from-id, with a buffer with the right amount of memory required. The calling function deallocates the memory in onodes and olengths To determine nrecevs, one can use PetscGatherNumberOfMessages() .seealso: PetscGatherMessageLengths() and PetscGatherNumberOfMessages() @*/ PetscErrorCode PetscGatherMessageLengths2(MPI_Comm comm,PetscMPIInt nsends,PetscMPIInt nrecvs,const PetscMPIInt ilengths1[],const PetscMPIInt ilengths2[],PetscMPIInt **onodes,PetscMPIInt **olengths1,PetscMPIInt **olengths2) { PetscErrorCode ierr; PetscMPIInt size,tag,i,j,*buf_s = NULL,*buf_r = NULL,*buf_j = NULL; MPI_Request *s_waits = NULL,*r_waits = NULL; MPI_Status *w_status = NULL; PetscFunctionBegin; ierr = MPI_Comm_size(comm,&size);CHKERRQ(ierr); ierr = PetscCommGetNewTag(comm,&tag);CHKERRQ(ierr); /* cannot use PetscMalloc5() because r_waits and s_waits must be contiguous for the call to MPI_Waitall() */ ierr = PetscMalloc4(nrecvs+nsends,&r_waits,2*nrecvs,&buf_r,2*nsends,&buf_s,nrecvs+nsends,&w_status);CHKERRQ(ierr); s_waits = r_waits + nrecvs; /* Post the Irecv to get the message length-info */ ierr = PetscMalloc1(nrecvs+1,olengths1);CHKERRQ(ierr); ierr = PetscMalloc1(nrecvs+1,olengths2);CHKERRQ(ierr); for (i=0; i<nrecvs; i++) { buf_j = buf_r + (2*i); ierr = MPI_Irecv(buf_j,2,MPI_INT,MPI_ANY_SOURCE,tag,comm,r_waits+i);CHKERRQ(ierr); } /* Post the Isends with the message length-info */ for (i=0,j=0; i<size; ++i) { if (ilengths1[i]) { buf_j = buf_s + (2*j); buf_j[0] = *(ilengths1+i); buf_j[1] = *(ilengths2+i); ierr = MPI_Isend(buf_j,2,MPI_INT,i,tag,comm,s_waits+j);CHKERRQ(ierr); j++; } } if (j != nsends) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_PLIB,"j %d not equal to expected number of sends %d\n",j,nsends); /* Post waits on sends and receivs */ if (nrecvs+nsends) {ierr = MPI_Waitall(nrecvs+nsends,r_waits,w_status);CHKERRQ(ierr);} /* Pack up the received data */ ierr = PetscMalloc1(nrecvs+1,onodes);CHKERRQ(ierr); for (i=0; i<nrecvs; ++i) { (*onodes)[i] = w_status[i].MPI_SOURCE; buf_j = buf_r + (2*i); (*olengths1)[i] = buf_j[0]; (*olengths2)[i] = buf_j[1]; } ierr = PetscFree4(r_waits,buf_r,buf_s,w_status);CHKERRQ(ierr); PetscFunctionReturn(0); } /* Allocate a bufffer sufficient to hold messages of size specified in olengths. And post Irecvs on these buffers using node info from onodes */ PetscErrorCode PetscPostIrecvInt(MPI_Comm comm,PetscMPIInt tag,PetscMPIInt nrecvs,const PetscMPIInt onodes[],const PetscMPIInt olengths[],PetscInt ***rbuf,MPI_Request **r_waits) { PetscErrorCode ierr; PetscInt **rbuf_t,i,len = 0; MPI_Request *r_waits_t; PetscFunctionBegin; /* compute memory required for recv buffers */ for (i=0; i<nrecvs; i++) len += olengths[i]; /* each message length */ /* allocate memory for recv buffers */ ierr = PetscMalloc1(nrecvs+1,&rbuf_t);CHKERRQ(ierr); ierr = PetscMalloc1(len,&rbuf_t[0]);CHKERRQ(ierr); for (i=1; i<nrecvs; ++i) rbuf_t[i] = rbuf_t[i-1] + olengths[i-1]; /* Post the receives */ ierr = PetscMalloc1(nrecvs,&r_waits_t);CHKERRQ(ierr); for (i=0; i<nrecvs; ++i) { ierr = MPI_Irecv(rbuf_t[i],olengths[i],MPIU_INT,onodes[i],tag,comm,r_waits_t+i);CHKERRQ(ierr); } *rbuf = rbuf_t; *r_waits = r_waits_t; PetscFunctionReturn(0); } PetscErrorCode PetscPostIrecvScalar(MPI_Comm comm,PetscMPIInt tag,PetscMPIInt nrecvs,const PetscMPIInt onodes[],const PetscMPIInt olengths[],PetscScalar ***rbuf,MPI_Request **r_waits) { PetscErrorCode ierr; PetscMPIInt i; PetscScalar **rbuf_t; MPI_Request *r_waits_t; PetscInt len = 0; PetscFunctionBegin; /* compute memory required for recv buffers */ for (i=0; i<nrecvs; i++) len += olengths[i]; /* each message length */ /* allocate memory for recv buffers */ ierr = PetscMalloc1(nrecvs+1,&rbuf_t);CHKERRQ(ierr); ierr = PetscMalloc1(len,&rbuf_t[0]);CHKERRQ(ierr); for (i=1; i<nrecvs; ++i) rbuf_t[i] = rbuf_t[i-1] + olengths[i-1]; /* Post the receives */ ierr = PetscMalloc1(nrecvs,&r_waits_t);CHKERRQ(ierr); for (i=0; i<nrecvs; ++i) { ierr = MPI_Irecv(rbuf_t[i],olengths[i],MPIU_SCALAR,onodes[i],tag,comm,r_waits_t+i);CHKERRQ(ierr); } *rbuf = rbuf_t; *r_waits = r_waits_t; PetscFunctionReturn(0); }
C
#include <stdio.h> #define MAX_EXPRESSION 100 int isParenthesisBalanced(char *); int main() { char expr[MAX_EXPRESSION]; printf("Enter expression: "); scanf("%s", &expr); if(isParenthesisBalanced(expr) == 0) printf("Balanced parenthesis. \n"); else printf("Unbalanced\n"); return 0; } //returns 0 if the parenthesis are balanced int isParenthesisBalanced(char *expr) { int bf = 0; int i; i = 0; while(expr[i] != '\0') { if(expr[i] == '(') bf++; else if(expr[i] == ')') { bf--; if(bf < 0) break; } i++; } return bf; }
C
#include <limits.h> #include <stdbool.h> #include <stdio.h> #include<stdlib.h> typedef struct graph{ int **mat; int nodes; }graph; graph *createGraph(int N) { int i; graph *new = malloc(sizeof(graph)); new->nodes = N; new->mat = malloc((N + 1) * sizeof(int*)); for(i = 1; i <= N; i++) new->mat[i] = calloc(N + 1, sizeof(int)); return new; } void addEdge(graph *g, int v1, int v2, int cost) { g->mat[v1][v2] = g->mat[v2][v1] = cost; } void destroyGraph(graph *g) { int i; for(i = 1; i <= g->nodes; i++) free(g->mat[i]);\ free(g->mat); free(g); } int minKey(int N, int key[], int visited[]) { int i; int min = INT_MAX, minIndex; for (i = 1; i <= N; i++) if (visited[i] == 0 && key[i] < min) min = key[i], minIndex = i; return minIndex; } void primMST(graph *g, FILE *fout) { int i, j, s = 0; int key[g->nodes], visited[g->nodes], parent[g->nodes]; for (i = 1; i <= g->nodes; i++) key[i] = INT_MAX, visited[i] = 0; key[1] = 0; parent[1] = -1; int count; for (count = 0; count < g->nodes; count++) { int u = minKey(g->nodes, key, visited); visited[u] = 1; s = s + key[u]; for (j = 1; j <= g->nodes; j++) if (g->mat[u][j] && visited[j] == 0 && g->mat[u][j] < key[j]) parent[j] = u, key[j] = g->mat[u][j]; } fprintf(fout, "%d\n", s); for(i = 1; i <= g->nodes; i++) fprintf(fout, "%d ", parent[i] == -1 ? 0 : parent[i]); } int main() { FILE *fin = fopen("prim.in", "r"); FILE *fout = fopen("prim.out", "w"); int N, M, i, v1, v2, cost; fscanf(fin, "%d%d", &N, &M); graph *g = createGraph(N); for(i = 1; i <= M; i++) { fscanf(fin, "%d%d%d", &v1, &v2, &cost); addEdge(g, v1, v2, cost); } primMST(g, fout); destroyGraph(g); fclose(fin); fclose(fout); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> typedef struct _Endereco Endereco; struct _Endereco { char logradouro[72]; char bairro[72]; char cidade[72]; char uf[72]; char sigla[2]; char cep[8]; char lixo[2]; }; int compara(const void *e1, const void *e2) { return strncmp(((Endereco*)e1)->cep,((Endereco*)e2)->cep,8); } int main (int argc, char**argv) { FILE *f, *a, *b, *saida; Endereco *e, ea, eb; long posicao, qtd, tamanhoBloco; char buffer[30]; char novoNome[]= "cep_ordenado_final.dat"; int inicio= 0, final=16; // variável "final" controla a quantidade de blocos a ser dividido e intercalado. f= fopen("cep.dat","r"); fseek(f,0,SEEK_END); posicao= ftell(f); qtd= posicao/sizeof(Endereco); tamanhoBloco= qtd/final; printf("Quantidade de bytes registro: %ld\n\n", sizeof(Endereco)); printf("Quantidade Registros: %ld\n\n", qtd); printf("Tamanho de cada Bloco: %ld\n\n", tamanhoBloco); printf("Tamanho do ultimo Bloco: %ld\n\n",(tamanhoBloco+(qtd%final))); rewind(f); // Divide o cep.dat em 16 blocos // for (int i=0; i<final; i++) { if(i==final-1) tamanhoBloco=tamanhoBloco+(qtd%final); e= (Endereco*) malloc(tamanhoBloco*sizeof(Endereco)); if(fread(e,sizeof(Endereco),tamanhoBloco,f) == tamanhoBloco) { printf("Bloco %d Lido = OK\n", i); } qsort(e,tamanhoBloco,sizeof(Endereco),compara); printf("Bloco %d Ordenado = OK\n", i); sprintf(buffer, "cep_%d.dat", i); //atribui o nome do arquivo referindo a posição do bloco saida = fopen(buffer,"w"); fwrite(e,sizeof(Endereco),tamanhoBloco,saida); fclose(saida); printf("Bloco %d Escrito = OK\n\n", i); free(e); } fclose(f); // Intercala // while( inicio<final-1) { sprintf(buffer, "cep_%d.dat", inicio); a = fopen(buffer,"r"); sprintf(buffer, "cep_%d.dat", inicio+1); b = fopen(buffer,"r"); sprintf(buffer, "cep_%d.dat", final); saida = fopen(buffer,"w"); fread(&ea,sizeof(Endereco),1,a); fread(&eb,sizeof(Endereco),1,b); while(!feof(a) && !feof(b)) { if(compara(&ea,&eb)<0) // ea.cep < eb.cep { fwrite(&ea,sizeof(Endereco),1,saida); fread(&ea,sizeof(Endereco),1,a); } else { fwrite(&eb,sizeof(Endereco),1,saida); fread(&eb,sizeof(Endereco),1,b); } } while(!feof(a)) { fwrite(&ea,sizeof(Endereco),1,saida); fread(&ea,sizeof(Endereco),1,a); } while(!feof(b)) { fwrite(&eb,sizeof(Endereco),1,saida); fread(&eb,sizeof(Endereco),1,b); } printf("bloco %d + bloco %d = bloco %d intercalado com sucesso\n", inicio, inicio+1, final); fclose(a); fclose(b); fclose(saida); final=final+1; inicio=inicio+2; } sprintf(buffer, "cep_%d.dat", final-1); if(rename(buffer, novoNome) == 0) // renomeia ultimo cep_*.dat renomeado { printf("Arquivo renomeado com sucesso"); } else { printf("Erro: falha ao renomear o arquivo"); } return 0; }
C
#include<stdio.h> void merge(int a[], int p, int q, int r){ int n1 = q-p+1; int n2 = r-q; int l1[n1],l2[n2]; for(int i=0; i<n1; i++) l1[i]=a[p+i]; for(int i=0; i<n2; i++) l2[i]=a[q+i+1]; int i=0,j=0,k=p; while(i<n1 && j<n2){ if(l1[i]<=l2[j]){ a[k] = l1[i]; i++; } else{ a[k] = l2[j]; j++; } k++; } while(i<n1){ a[k] = l1[i]; i++; k++; } while(j<n2){ a[k] = l2[j]; j++; k++; } } void mergesort(int a[],int p,int r){ if(p<r){ int q = p+(r-p)/2; mergesort(a,p,q); mergesort(a,q+1,r); merge(a,p,q,r); } } int main(){ int t,i; scanf("%d",&t); int a[t]; for(i=0; i<t; i++){ scanf("%d",&a[i]); } int p = 0; mergesort(a,p,t-1); for(i=0; i<t; i++) printf("%d\n",a[i]); return 0; }
C
#include "reef.h" #include "_mdf.h" #define _FORCE_HASH_AT 10 void _mdf_drop_child_node(MDF *pnode, MDF *cnode) { if (cnode->parent != pnode) return; MDF *prev = cnode->prev, *next = cnode->next; if (prev == NULL) { pnode->child = next; if (next) next->prev = NULL; else pnode->last_child = NULL; } else { prev->next = next; if (next) next->prev = prev; else pnode->last_child = prev; } mhash_remove(pnode->table, cnode->name); cnode->next = NULL; mdf_destroy(&cnode); } void _mdf_append_child_node(MDF *pnode, MDF *newnode, int current_childnum) { if (current_childnum < 0) { if (pnode->table) current_childnum = mhash_length(pnode->table); else { current_childnum = 0; for (MDF *cnode = pnode->child; cnode; cnode = cnode->next) current_childnum++; } } if (current_childnum >= _FORCE_HASH_AT && pnode->table == NULL) { /* new hash table */ mhash_init(&pnode->table, mhash_str_hash, mhash_str_comp, NULL); MDF *cnode = pnode->child; while (cnode) { mhash_insert(pnode->table, cnode->name, cnode); cnode = cnode->next; } } if (pnode->table) { /* insert to table */ mhash_insert(pnode->table, newnode->name, newnode); } /* append to list */ newnode->parent = pnode; newnode->prev = pnode->last_child; if (!pnode->child) pnode->child = newnode; if (pnode->last_child) pnode->last_child->next = newnode; pnode->last_child = newnode; } void _mdf_insert_child_node(MDF *pnode, MDF *newnode, int current_childnum, int position) { if (current_childnum < 0) { if (pnode->table) current_childnum = mhash_length(pnode->table); else { current_childnum = 0; for (MDF *cnode = pnode->child; cnode; cnode = cnode->next) current_childnum++; } } if (current_childnum >= _FORCE_HASH_AT && pnode->table == NULL) { /* new hash table */ mhash_init(&pnode->table, mhash_str_hash, mhash_str_comp, NULL); MDF *cnode = pnode->child; while (cnode) { mhash_insert(pnode->table, cnode->name, cnode); cnode = cnode->next; } } if (pnode->table) { /* insert to table */ mhash_insert(pnode->table, newnode->name, newnode); } /* * insert to list * 节点编号为 0, 1, 2, 3... * position 为插入位置,如:2 为查入到第三位,即原来索引为2的元素之前 */ newnode->parent = pnode; newnode->prev = newnode->next = NULL; if (position > current_childnum) position = current_childnum; else if (position < current_childnum * -1) position = 0; else if (position < 0) position = current_childnum + position + 1; int ahead_count = 0; MDF *nextnode = pnode->child; while (nextnode && ahead_count < position) { ahead_count++; nextnode = nextnode->next; } if (ahead_count == current_childnum) { /* 插到最后一个 */ newnode->prev = pnode->last_child; if (!pnode->child) pnode->child = newnode; if (pnode->last_child) pnode->last_child->next = newnode; pnode->last_child = newnode; } else if (nextnode) { newnode->prev = nextnode->prev; newnode->next = nextnode; if (nextnode->prev == NULL) { pnode->child = newnode; } else { nextnode->prev->next = newnode; } nextnode->prev = newnode; } else { /* TODO unpossible */ fprintf(stderr, "unbelieve, %d %d %d\n", current_childnum, position, ahead_count); } }
C
#include <stdio.h> #include <string.h> #include <stdlib.h> #include "bstr.h" int main(int argc, char *argv[]) { unsigned long p = 0xAA0000AA; char q = 0x10; char r = 'a'; char buf[0x1000]; char *pre1, *pre2, *pre3, *pre4; int cpos; /*Test 1:convert other type variable to bitstring*/ printf( "/*Test 1:convert other type variable to bitstring*/\n" ); cp_bstr *a = cp_bstr_create(7, (unsigned char *) &p); cp_bstr *b = cp_bstr_create(8, (unsigned char *) &q); cp_bstr *c = cp_bstr_create(8, (unsigned char *) &r); pre1 = cp_bstr_to_string(a); pre2 = cp_bstr_to_string(b); pre3 = cp_bstr_to_string(c); cp_bstr_dump(a); cp_bstr_dump(b); cp_bstr_dump(c); printf( "pre1 is %s\n", pre1 ); printf( "pre2 is %s\n", pre2 ); printf( "pre3 is %s\n", pre3 ); /*Test 2:convert "010100"like string to cp_bstr bitstring*/ printf( "/*Test 2:convert 010100like string to cp_bstr bitstring*/\n" ); cp_bstr *d = cstr_to_bstr("100"); pre4 = cp_bstr_to_string(d); cp_bstr_dump(d); printf( "pre4 is %s\n", pre4 ); /*Test 3: test concatenate function*/ printf( "/*Test 3: test concatenate function*/\n" ); cp_bstr_cat(d, d); cp_bstr_dump(d); /*Test 4: test compare function*/ printf( "/*Test 4: test compare function*/\n" ); int res2 = cp_bstr_cmp( b, c, &cpos ); printf( "res is %d cpos is %d\n", res2, cpos ); res2 = cp_bstr_cmp( b, b, &cpos ); printf( "res is %d cpos is %d\n", res2, cpos ); /*Test 5: test bit shift left function*/ printf( "/*Test 5: test bit shift left function*/\n" ); cp_bstr_dump(a); cp_bstr_shift_left( a, 1 ); cp_bstr_dump(a); free(pre1); free(pre2); free(pre3); free(pre4); cp_bstr_destroy(a); cp_bstr_destroy(b); cp_bstr_destroy(c); cp_bstr_destroy(d); return 0; } #if 0 /*Test 1:convert other type variable to bitstring*/ bit sequence: 7 bits 1010101 bit sequence: 8 bits 00010000 bit sequence: 8 bits 01100001 pre1 is 1010101 pre2 is 00010000 pre3 is 01100001 /*Test 2:convert 010100like string to cp_bstr bitstring*/ bit sequence: 3 bits 100 pre4 is 100 /*Test 3: test concatenate function*/ bit sequence: 6 bits 100100 /*Test 4: test compare function*/ res is -81 cpos is 1 res is 0 cpos is 8 /*Test 5: test bit shift left function*/ bit sequence: 7 bits 1010101 bit sequence: 6 bits 010101 #endif
C
#include<stdio.h> /* int main() { int i = 0 , j = 0, num = 0 ; char arr[]="Piyush" ; char *ptr = NULL ; //printf("%s\n",arr); while(arr[i]!='\0') { for(j=0 ; j<=i ; j++) { printf("%c ",arr[j]); } i++ ; printf("\n"); } return 0 ; } */ ////////////////////////////////////////////////////////////////// /* int main() { int i = 0 , j = 0, num = 0 ; char arr[]="PIYUSH" ; char *ptr = NULL ; ptr = arr ; while(*ptr!='\0') { i++ ; ptr++ ; } ptr=arr ; while(i) { j=0; while(j<i) { if(j%2==0) printf("%c ",ptr[j]); else printf("%c ",ptr[j]+32); j++; } printf("\n"); i--; } return 0 ; } */ ///////////////////////////////////////////////////////////////////// int main() { int i = 0 , j = 0, num = 0,temp = 0,temp2=0,temp3=0 ; char arr[]=/*"VIJAY NARSING CHAKOLE VIJAY NARSING CHAKOLE";*/"UNIX WIN32 SDK" ; char *ptr = NULL ; //printf("%s\n",arr); int flag = 0 ; while(arr[i]!='\0') { if(arr[i]==' ') { if(flag==0) { flag = 1 ; temp2 = num; } else { temp2 = --num; } temp = ++i ; temp3=temp2; //temp2 = temp2 - 2; while(temp2--) { printf(" "); } temp2 = temp3 ; } if(i!=0) printf("\n"); while(temp2-->1) { printf(" "); } temp2 = temp3 ; for(j=temp ; j<=i ; j++ ) { printf("%c ",arr[j]); } i++ ; num++ ; } return 0 ; }
C
#include<stdio.h> #include<stdlib.h> #include<string.h> #include<sys/types.h> #include<sys/ipc.h> #include<sys/msg.h> int main(void) { key_t key; int proj_id = 1; int msqid; char message1[] = {"hello microsoft"}; char message2[] = {"goodbye"}; struct msgbuf /* you need to define your own msgbufs */ { long msgtype; char msgtext[1024]; }snd, rcv; key = ftok("/home/seven", proj_id); if(key == -1) { perror("create key error!\n"); return 1; } if((msqid = msgget(key, IPC_CREAT|0666)) == -1) { printf("msgget error!\n"); exit(1); } snd.msgtype = 1; //just like the fprintf, for catenation. sprintf(snd.msgtext, "%s", message1); // +1 is for the end character '\0'. if(msgsnd(msqid, (struct msgbuf*)&snd, sizeof(message1)+1, 0) == -1) { printf("msgsnd 1 error!\n"); exit(1); } snd.msgtype = 2; sprintf(snd.msgtext, "%s", message2); if(msgsnd(msqid, (struct msgbuf*)&snd, sizeof(message2)+1, 0) == -1) { printf("msgsnd 2 error!\n"); exit(1); } if(msgrcv(msqid, (struct msgbuf*)&rcv, 80, 1, IPC_NOWAIT) == -1) { printf("msgrcv 1 error!\n"); exit(1); } printf("the received message1: %s.\n", rcv.msgtext); if(msgrcv(msqid, (struct msgbuf*)&rcv, 80, 2, IPC_NOWAIT) == -1) { printf("msgrcv 2 error!\n"); exit(1); } printf("the received message2: %s.\n", rcv.msgtext); /* if you do not have caches in the msg queue, there will be not bytes after all msgs being received. */ system("ipcs -q"); msgctl(msqid, IPC_RMID, 0); // delete the msg queue. system("ipcs -q"); exit(0); }
C
#include "standard.h" int main(int argc, char **argv) { int opt; int num_levels = DEFAULT_NUM_LEVELS; int num_children = DEFAULT_NUM_CHILDREN; int s; bool pflag = false; bool sflag = false; opt = getopt(argc, argv, OPT_STRING); while (opt != -1) { switch (opt) { case 'u': usage(); return EXIT_SUCCESS; break; case 'N': if (parseStr(optarg, &num_levels)) { fprintf(stderr, "Error: %s cannot be coverted to an integer\n", optarg); return EXIT_FAILURE; } if (num_levels > MAX_NUM_LEVELS) { fprintf(stderr, "Error: number of levels cannot be <= %i\n", MAX_NUM_LEVELS); return EXIT_FAILURE; } else if (num_levels == 0) { num_levels = 1; } break; case 'M': if (parseStr(optarg, &num_children)) { fprintf(stderr, "Error: %s cannot be coverted to an integer\n", optarg); return EXIT_FAILURE; } if (num_children > MAX_NUM_CHILDREN) { fprintf(stderr, "Error: number of children cannot be <= %i\n", MAX_NUM_CHILDREN); return EXIT_FAILURE; } break; case 'p': pflag = true; break; case 's': if (parseStr(optarg, &s)) { fprintf(stderr, "Error: %s cannot be coverted to an integer\n", optarg); return EXIT_FAILURE; } sflag = true; break; case ':': missingArg(optopt); return EXIT_FAILURE; break; case '?': unknownArg(optopt); return EXIT_FAILURE; break; default: fprintf(stderr, "Something happened\n"); return EXIT_FAILURE; break; } opt = getopt(argc, argv, OPT_STRING); } if (pflag && sflag) { fprintf(stderr, "Error: cannot both sleep and pause"); return EXIT_FAILURE; } else if (!pflag && !sflag) { sflag = true; s = 1; } pid_t self = getpid(); pid_t parent = getppid(); pid_t child; fprintf(stdout, "ALIVE: Level %i process with pid=%i, child of ppid=%i.\n", num_levels - 1, self, parent); if (num_levels > 1) { char sbuff[BUFF_SIZE]; char nbuff[BUFF_SIZE]; char mbuff[BUFF_SIZE]; if (snprintf(nbuff, BUFF_SIZE, "%i", (num_levels - 1)) < 0) { fprintf(stderr, "Error: problem with snprintf, %s\n", strerror(errno)); return EXIT_FAILURE; } if (snprintf(mbuff, BUFF_SIZE, "%i", num_children) < 0) { fprintf(stderr, "Error: problem with snprintf, %s\n", strerror(errno)); return EXIT_FAILURE; } if (sflag && snprintf(sbuff, BUFF_SIZE, "%i", s) < 0) { fprintf(stderr, "Error: problem with snprintf, %s\n", strerror(errno)); return EXIT_FAILURE; } for (int i = 0; i < num_children; ++i) { child = fork(); if (child < 0) { fprintf(stderr, "Error: problem with fork, %s\n", strerror(errno)); return EXIT_FAILURE; } else if (child == 0 && sflag) { execl(argv[0], argv[0], "-M", mbuff, "-N", nbuff, "-s", sbuff, NULL); } else if (child == 0) { execl(argv[0], argv[0], "-M", mbuff, "-N", nbuff, "-p", NULL); } } for (int i = 0; i < num_children; ++i) { wait(NULL); } } else if (sflag) { sleep(s); } else { pause(); } fprintf(stdout, "EXITING: Level %i process with pid=%i, child of ppid=%i.\n", num_levels - 1, self, parent); return EXIT_SUCCESS; } static void usage(void) { fprintf(stderr, "%s", USAGE_STRING); } static void missingArg(int arg) { fprintf(stderr, "Error: missing argument, -%c expects a value\n", arg); usage(); } static void unknownArg(int arg) { fprintf(stderr, "Error: unknown argument, -%c\n", arg); usage(); } static int parseStr(char *str, int *val) { int p = strtoul(str, NULL, 10); if (p || isdigit(str[0])) { *val = p; return 0; } else { return -1; } }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <rtthread.h> #include "webclient.h" #define WEBCLIENT_READ_BUFFER (1024 * 4) int webclient_test(int argc, char **argv) { struct webclient_session* session = RT_NULL; unsigned char *buffer = RT_NULL; int ret = 0; if(argc != 2) { rt_kprintf("input argc is err!\n"); ret = -RT_ERROR; goto _exit; } buffer = rt_malloc(WEBCLIENT_READ_BUFFER); if(!buffer) { rt_kprintf("have no memory for buffer\n"); ret = -RT_ERROR; goto _exit; } session = webclient_open(argv[1]); if(!session) { rt_kprintf("open failed, url:%s\n", argv[1]); ret = -RT_ERROR; goto _exit; } rt_kprintf("response : %d, content_length : %d\n",session->response, session->content_length); int rc = 0; int nw = WEBCLIENT_READ_BUFFER; int content_pos = 0; int len = 0, i = 0; int content_length = session->content_length; do { int page_pos = 0; do { memset(buffer + page_pos, 0x00, nw - page_pos); rc = webclient_read(session, buffer + page_pos, nw - page_pos); if(rc < 0) { rt_kprintf("webclient read err ret : %d\n", rc); break; } if(rc == 0) break; page_pos += rc; }while(page_pos < nw); len = page_pos; for(i = 0; i<len; i++) rt_kprintf("%c", buffer[i]); content_pos += page_pos; }while(content_pos < content_length); rt_kprintf("content pos : %d, content_length : %d\n", content_pos, session->content_length); if(session) webclient_close(session); _exit: if(buffer) rt_free(buffer); return ret; } MSH_CMD_EXPORT(webclient_test,webclient open URI test);
C
#include <stdio.h> #include <stdlib.h> #include <math.h> /* ax^2 + bx + c entradas: 2 4 -1 2 9 5 */ int main() { float a, b, c, x1, x2, delta; printf("Digite o valor de a: "); scanf("%f", &a); printf("Digite o valor de b: "); scanf("%f", &b); printf("Digite o valor de c: "); scanf("%f", &c); delta = b*b -(4*a*c); x1 = (-b + sqrt(delta))/(2*a); x2 = (-b - sqrt(delta))/(2*a); printf("\nx1 = %.2f\nx2 = %.2f\n", x1, x2); return 0; }
C
#ifndef _TYPES_H_ #define _TYPES_H_ /* ڹܽ ѯ*/ typedef uint8_t PinName; /* InPut and OutPut mode */ typedef enum Mode { In=0, Out }Mode; /* used as OutPut Pins Low or High */ typedef enum Station { Low=0, High, Tristate }Station; #endif
C
#include <stdio.h> #include <stdlib.h> struct Node { int data; struct Node *next; }; void display(struct Node *ptr) { int size = 0; while (ptr != NULL) { printf("%d\t", ptr->data); ptr = ptr->next; size++; } printf("size=%d", size); } struct Node *rearend(struct Node *ptr) { struct Node *backend; while (ptr->next != NULL) { ptr = ptr->next; } backend = ptr; return backend; } int isEmpty(struct Node *ptr, struct Node *head, struct Node *back) { if (ptr == NULL || head == back) { return 1; } else { return 0; } } int isFull(struct Node *ptr) { struct Node *ptr1 = (struct Node *)malloc(sizeof(struct Node)); if (ptr1 == NULL) { return 1; } else { return 0; } } struct Node *enqueue(struct Node *back, int data) { struct Node *temp = (struct Node *)malloc(sizeof(struct Node)); temp->data = data; back->next = temp; back = temp; return back; } int dequeue(struct Node* temp,struct Node* head,struct Node* back) { if(isEmpty(temp,head,back)) { return 1; } else { temp=temp->next; head=temp; return head; } } int main() { //creating nodes struct Node *head; struct Node *second; struct Node *third; struct Node *fourth; struct Node *fifth; //allocating memory to the nodes head = (struct Node *)malloc(sizeof(struct Node)); second = (struct Node *)malloc(sizeof(struct Node)); third = (struct Node *)malloc(sizeof(struct Node)); fourth = (struct Node *)malloc(sizeof(struct Node)); fifth = (struct Node *)malloc(sizeof(struct Node)); //feeding data in the nodes head->data = 10; second->data = 20; third->data = 30; fourth->data = 40; fifth->data = 50; //connecting nodes head->next = second; second->next = third; third->next = fourth; fourth->next = fifth; fifth->next = NULL; struct Node *back = fourth->next; display(head); back = enqueue(back, 2100); back = enqueue(back, 1900); back = enqueue(back, 800); printf("\n\nafter enqueue\n"); display(head); head=dequeue(head,head,back); printf("\n\nafter dequeue\n\n"); display(head); return 0; }
C
#include <stdio.h> #include <time.h> int main() { int x, fatorial, i; printf("Digite o valor do x:(entre 0 e 12) \n"); scanf("%d",&x); fatorial = x; if (x==0) { fatorial = 1; printf("%d",fatorial); } else { for (i = x-1; i != 1; i--) fatorial = fatorial * i; printf("%d",fatorial); } return 0; }
C
#define _GNU_SOURCE // Obtain O_DIRECT definition from <fcntl.h> #include <fcntl.h> // #include <malloc.h> #include "../tlpi.h" int main(int argc, char *argv[]) { int fd; ssize_t nread; size_t length, alignment; off_t offset; char *buffer; if (argc < 3 || strcmp(argv[1], "--hlep") == 0) { usage_error("%s file length [offset [alignment]]\n", argv[0]); } length = get_long(argv[2], GN_ANY_BASE, "length"); offset = (argc > 3) ? get_long(argv[3], GN_ANY_BASE, "offset") : 0; alignment = (argc > 4) ? get_long(argv[4], GN_ANY_BASE, "alignment") : 4096; fd = open(argv[1], O_RDONLY | O_DIRECT); if (fd == -1) { error_exit("open"); } if (posix_memalign(&buffer, alignment * 2, length + alignment) != 0) { error_exit("posix_memalign"); } // buffer = memalign(alignment * 2, length + alignment); // if (buffer == NULL) { // error_exit("memalign"); // } buffer += alignment; if (lseek(fd, offset, SEK_SET) == -1) { error_exit("lseek"); } nread = read(fd, buffer, length); if (nread == -1) { error_exit("read"); } printf("Read %ld bytes\n", (long)nread); return 0; }
C
#include <stdio.h> #include <string.h> #include <smi.h> int main(int argc, char *argv[]) { SmiNode *smiNode; int oidlen, first = 1; if (argc != 2) { fprintf(stderr, "Usage: smisubtree oid\n"); exit(1); } smiInit(NULL); for((smiNode = smiGetNode(NULL, argv[1])) && (oidlen = smiNode->oidlen); smiNode && (first || smiNode->oidlen > oidlen); smiNode = smiGetNextNode(smiNode, SMI_NODEKIND_ANY), first = 0) { printf("%*s%-32s\n", (smiNode->oidlen - oidlen + 1) * 2, " ", smiNode->name); }; exit(0); }
C
/* * blevel.c * * Created by Alejandro Santiago on 12/09/20. * [email protected] * */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include "types.h" double *calcula_blevel() { int i,nodo; double *blevel; blevel=reserva_vector_double(T); nodo=0; //el nodo de entrada for(i=0;i<T;i++) { blevel[i]=recursivo_blevel(i,promedios[i]); } return blevel; } double recursivo_blevel(int nodo, double sum) { int i; double max,temp; max=sum; for(i=0;i<T;i++) { if(graph[nodo][i]) { temp=recursivo_blevel(i,sum+graph[nodo][i]+promedios[i]); if(max<temp) max=temp; } } return max; }
C
#include "image.h" #include "ppmIO.h" #include <stdlib.h> #include <stdio.h> #include <math.h> /* * Allocates an Image structure and initializes * the top level fields to appropriate values. Allocates space for an image of the specified size, unless * either rows or cols is 0. Returns a pointer to the allocated Image structure. Returns a NULL pointer if * the operation fails. */ Image *image_create(int rows, int cols){ //malloc an image Image *image = (Image*)malloc(sizeof(Image)); image -> rows = rows; image -> cols = cols; //check to see rows or cols are valid if (rows == 0 || cols == 0){ return image; } image -> data = (FPixel**)malloc(sizeof(FPixel*)*rows); if(image -> data == NULL){ free(image); return NULL; } image -> data[0] = (FPixel*)malloc(sizeof(FPixel) * rows * cols); if(image -> data[0] == NULL){ free(image); return NULL; } //set all of my outer aray int i; for(i = 1; i < rows; i++){ image -> data[i] = &image -> data[0][i * cols]; } image_fillz(image, 1.0); return image; } /* * de-allocates image data and frees the Image structure. */ void image_free(Image *src){ if(src -> data != NULL){ if(src -> data[0] != NULL){ free(src -> data[0]); } free(src -> data); } free(src); } /* * given an uninitialized Image structure, sets the rows and cols * fields to zero and the data field to NULL. */ void image_init(Image *src){ src -> rows = 0; src -> cols = 0; src -> data = NULL; image_fillz(src, 1.0); } /* */ int image_alloc(Image *src, int rows, int cols){ //just always free the memory to be safe since checks are in there anyway if(src -> data != NULL){ if(src -> data[0] != NULL){ free(src -> data[0]); } free(src -> data); } printf("reset fields of image\n"); src -> rows = rows; src -> cols = cols; src -> data = (FPixel**)malloc(sizeof(FPixel*)*rows); if(src -> data == NULL){ return -1; } src -> data[0] = (FPixel*)malloc(sizeof(FPixel) * rows * cols); if(src -> data[0] == NULL){ return -1; } //set all of my outer aray int i; for(i = 1; i < rows; i++){ src -> data[i] = &src -> data[0][i * cols]; } int j; for(i = 0; i < rows; i++){ for(j = 0; j < cols; j++){ SET_ARGBZ(src->data[i][j], 0.0, 0.0, 0.0, 1.0, 1.0); } } return 0; } /* * de-allocates image data and resets the Image structure * fields. The function does not free the Image structure. */ void image_dealloc(Image *src){ //I'm not sure how this is different from my init so I will just call it here?? if(src -> data != NULL){ if(src -> data[0] != NULL){ free(src -> data[0]); } free(src -> data); src -> data = NULL; } image_init(src); } /* * reads a PPM image from the given filename. An optional * extension is to determine the image type from the filename and permit the use of different file * types. Initializes the alpha channel to 1.0 and the z channel to 1.0. Returns a NULL pointer if the * operation fails. */ Image *image_read(char *filename){ int rows; int cols; int colors; Pixel* src = readPPM(&rows, &cols, &colors, filename); if(src == NULL){ return NULL; } Image* image = image_create(rows, cols); int i; for(i = 0; i < rows * cols; i++){ SET_ARGBZ((image -> data[0][i]), src[i].r/255.0, src[i].g/255.0, src[i].b/255.0, 1.0, 1.0); } free(src); return image; } /* * writes a PPM image to the given filename. Returns 0 on success. */ int image_write(Image *src, char *filename){ if(src == NULL){ return -1; } if(src -> data == NULL){ return -1; } Pixel* image = (Pixel*)malloc(sizeof(Pixel) * src -> rows * src -> cols); int i; //for now do nothing with the alpha or Z channels for(i = 0; i < src -> rows * src -> cols; i++){ //I choose to make a ROUND macro image[i].r = ROUND(src -> data[0][i].rgb[RED] * 255); image[i].g = ROUND(src -> data[0][i].rgb[GREEN] * 255); image[i].b = ROUND(src -> data[0][i].rgb[BLUE] * 255); } writePPM(image, src -> rows, src -> cols, 255, filename); free(image); return 0; } /* * returns the FPixel at (r, c). */ FPixel image_getf(Image *src, int r, int c){ return src -> data[r][c]; } /* * returns the value of band b at pixel (r, c) */ float image_getc(Image *src, int r, int c, int b){ return src -> data[r][c].rgb[b]; } /* * returns the alpha value at pixel(r,c) */ float image_geta(Image *src, int r, int c){ return src -> data[r][c].a; } /* * returns the depth value at pixel(r,c) */ float image_getz(Image *src, int r, int c){ return src -> data[r][c].z; } /* * sets the values of the pixel (r,c) to the FPixel val */ void image_setf(Image *src, int r, int c, FPixel val){ //I'm not sure if we can directly set src[r][c] to val so I'm just gonna be safe and copy SET_ARGBZ(src -> data[r][c], val.rgb[RED], val.rgb[GREEN], val.rgb[BLUE], val.a, val.z); } /* * sets the value of pixel (r, c) band b to val. */ void image_setc(Image *src, int r, int c, int b, float val){ src -> data[r][c].rgb[b] = val; } /* * sets the alpha value of pixel (r,c) to val */ void image_seta(Image *src, int r, int c, float val){ src -> data[r][c].a = val; } /* * sets the depth value of pixel (r,c) to val */ void image_setz(Image *src, int r, int c, float val){ src -> data[r][c].z = val; } /* * resets every pixel to a default value (e.g. Black, alpha value of 1.0, z value of 1.0). */ void image_reset(Image *src){ int i; for(i = 0; i < src -> rows * src -> cols; i++){ SET_ARGBZ(src->data[0][i], 0.0, 0.0, 0.0, 1.0, 1.0); } } /* * sets every FPixel to the given value. */ void image_fill(Image *src, FPixel val){ int i; for(i = 0; i < src -> rows * src -> cols; i++){ SET_ARGBZ(src -> data[0][i], val.rgb[RED], val.rgb[GREEN], val.rgb[BLUE], val.a, val.z); } } /* * sets the (r, g, b) values of each pixel to the given color. */ void image_fillrgb(Image *src, float r, float g, float b){ int i; for(i = 0; i < src -> rows * src -> cols; i++){ SET_RGB(src -> data[0][i], r, g, b); } } /* * sets the alpha value of each pixel to the given value. */ void image_filla(Image *src, float a){ int i; for(i = 0; i < src -> rows * src -> cols; i++){ src -> data[0][i].a = a; } } /* * sets the z value of each pixel to the given value. */ void image_fillz(Image *src, float z){ int i; for(i = 0; i < src -> rows * src -> cols; i++){ src -> data[0][i].z = z; } }
C
#include <stdio.h> struct human; struct human { int id; char name[64]; //struct human lover; struct human *lover; }; int main() { struct human stlk = {1,"sinzzang",NULL}; struct human naru = {2,"narci", &naru}; struct human *lover1; struct human *lover2; char* l2name; stlk.lover = &naru; lover1 = stlk.lover; lover2 = lover1->lover; l2name = lover2->name; printf("%s\n", l2name); }
C
#include <stdio.h> int main(void) { char char_A = 'A'; char char_B = 'B'; const char * myPtr1 = &char_A; char * const myPtr2 = &char_A; const char * const myPtr3 = &char_A; *myPtr1 = char_B; // not allowed myPtr2 = &char_B; // not allowed return 0; }
C
#include "lexer.h" #include "parserDef.h" #include "symbolTable.h" #include <stdlib.h> int ht_size=91; int last_offset=0; matSize getOffset(astNode s,matSize m){ astNode temp=s,tempChil; int a=0,row,prev; while(temp!=NULL){ tempChil=temp->children; row=0; while(tempChil!=NULL){ row+=2; tempChil=tempChil->next; } if(a!=0 && row!=prev){ return NULL; } m->x = row/2; prev=row; a+=row; temp=temp->next; } if(m->x!=0){ m->y = a/(m->x*2); } return m; } symbolTable insertToHT(symbolTable st,astNode root,int* offset){ symbolTable tempSt=st; int a= *offset; int h,c=0; char* type= (char*)malloc(sizeof(char)*7); strcpy(type,root->children->name); astNode temp=root->children->next; astNode par=root->next; if(temp==NULL){ *offset=-1; st->last_offset=-1; return NULL; } if(strcmp(type,"INT")==0 || strcmp(type,"REAL")==0){ while(temp!=NULL){ h=hash(temp->p->tk->value,st->ht->size); if(st->ht->s[h]==NULL){ st->ht->s[h]=(stNode)malloc(sizeof(stnode)); st->ht->s[h]->var_name=temp->p->tk->value; st->ht->s[h]->type=type; st->ht->s[h]->offset=a; st->ht->s[h]->next=NULL; temp->st=st; if(strcmp(type,"INT")==0){ a+=2; } else{ a+=4; } *offset=a; } else{ stNode tempNode=st->ht->s[h]; while(tempNode->next!=NULL){ if(strcmp(temp->p->tk->value,tempNode->var_name)==0){ fprintf(errorFile,"Multiple Declarations of the variable %s at line %d \n",temp->p->tk->value,temp->p->tk->line_no); break; // return st; // *offset=-1; // return NULL; } tempNode=tempNode->next; } if(strcmp(temp->p->tk->value,tempNode->var_name)==0){ // *offset=-1; // return NULL; fprintf(errorFile,"Multiple Declarations of the variable %s at line %d.\n",temp->p->tk->value,temp->p->tk->line_no); break; // return st; } tempNode->next=(stNode)malloc(sizeof(stnode)); tempNode=tempNode->next; tempNode->var_name=temp->p->tk->value; temp->st=st; tempNode->type=type; tempNode->offset=a; tempNode->next=NULL; if(strcmp(type,"INT")==0){ a+=2; } else { a+=4; } *offset=a; } temp=temp->next; } st->last_offset=*offset; return st; } while(temp!=NULL){ astNode tempPar=par; while(tempPar!=NULL){ if((strcmp(tempPar->name,"ASSIGNMENTSTMT")==0) && (strcmp(tempPar->children->p->tk->value,temp->p->tk->value)==0) ){ if(strcmp(tempPar->children->next->name,"FUNCTIONCALL")==0){ // *offset=-1; fprintf(errorFile,"STRING or MATRIX %s initialized with a function Call at line %d - Not supported\n",temp->p->tk->value,tempPar->children->p->tk->line_no); break; // return st; } else if(strcmp(tempPar->children->next->name,"PLUS")==0 || strcmp(tempPar->children->next->name,"MINUS")==0 || strcmp(tempPar->children->next->name,"MUL")==0 || strcmp(tempPar->children->next->name,"DIV")==0){ fprintf(errorFile,"Variable %s used at line number %d before assigned\n",temp->p->tk->value,tempPar->children->p->tk->line_no); tempPar=tempPar->next; continue; } else{ h=hash(temp->p->tk->value,st->ht->size); if(st->ht->s[h]==NULL){ if(strcmp(type,"MATRIX")==0){ st->ht->s[h]=(stNode)malloc(sizeof(stnode)); st->ht->s[h]->var_name=temp->p->tk->value; st->ht->s[h]->mat = (matSize)calloc(1,sizeof(matsize)); st->ht->s[h]->mat=getOffset(tempPar->children->next,st->ht->s[h]->mat); if(NULL==st->ht->s[h]->mat){ fprintf(errorFile,"Inconsistent Matrix declaration for variable %s at line %d\n",temp->p->tk->value,tempPar->children->p->tk->line_no); break; } st->ht->s[h]->type=type; st->ht->s[h]->offset=a; st->ht->s[h]->next=NULL; a+=(2*st->ht->s[h]->mat->x*st->ht->s[h]->mat->y); } else{ st->ht->s[h]=(stNode)malloc(sizeof(stnode)); st->ht->s[h]->var_name=temp->p->tk->value; st->ht->s[h]->type=type; st->ht->s[h]->offset=a; st->ht->s[h]->next=NULL; a+=strlen(tempPar->children->next->p->tk->value)-2; } temp->st=st; *offset=a; break; } else{ stNode tempNode=st->ht->s[h]; while(tempNode->next!=NULL){ if(strcmp(tempPar->children->next->p->tk->value,tempNode->var_name)==0){ fprintf(errorFile,"Multiple Declarations of the variable %s at line %d\n",temp->p->tk->value,temp->p->tk->line_no); break; } tempNode=tempNode->next; } if(strcmp(tempPar->children->next->p->tk->value,tempNode->var_name)==0){ fprintf(errorFile,"Multiple Declarations of the variable %s at line %d \n",temp->p->tk->value,temp->p->tk->line_no); break; } if(strcmp(type,"MATRIX")==0){ tempNode->next=(stNode)malloc(sizeof(stnode)); tempNode=tempNode->next; tempNode->var_name=temp->p->tk->value; tempNode->type=type; tempNode->mat = (matSize)calloc(1,sizeof(matsize)); tempNode->mat=getOffset(tempPar->children->next,tempNode->mat); if(tempNode->mat == NULL){ fprintf(errorFile,"Inconsistent Matrix declaration for variable %s at line %d\n",temp->p->tk->value,temp->p->tk->line_no); break; } tempNode->offset=(2*tempNode->mat->x*tempNode->mat->y); tempNode->next=NULL; a+=c; } else{ tempNode->next=(stNode)malloc(sizeof(stnode)); tempNode=tempNode->next; tempNode->var_name=temp->p->tk->value; tempNode->type=type; tempNode->offset=a; a+=strlen(tempPar->children->next->p->tk->value); tempNode->next=NULL; } temp->st=st; *offset=a; break; } } break; } tempPar=tempPar->next; } if(tempPar==NULL){ fprintf(errorFile,"Uninitialized variable %s at line %d\n",temp->p->tk->value,temp->p->tk->line_no); } temp=temp->next; } st->last_offset=*offset; return st; } int checkinHash(symbolTable st,char* name){ int h=hash(name,st->ht->size); stNode temp=st->ht->s[h]; while(temp!=NULL){ if(strcmp(temp->var_name,name)==0){ return 1; } temp=temp->next; } return 0; } symbolTable buildST(astNode root){ // last_offset=0; int begin_offset=0,flag=0; astNode temp=root,temp2; astNode par=root; symbolTable st=NULL,stChil=NULL; symbolTable stAns=NULL; st = (symbolTable)malloc(sizeof(symboltable)); st->par=NULL; st->next=NULL; st->children=NULL; st->ht = (st_hashTable)malloc(sizeof(st_hashtable)); stAns=st; if(strcmp(temp->name,"MAIN")==0){ st->ht->scope=(char*)malloc(sizeof(char)*6); strcpy(st->ht->scope,"_main"); } else{ temp=temp->children; while(temp!=NULL){ if(strcmp(temp->name,"FUNID")==0){ st->ht->scope=temp->p->tk->value; break; } temp=temp->next; } } if(temp==NULL){ fprintf(errorFile,"Name of the function is not defined at line %d\n",root->children->children->p->tk->line_no); return NULL; } temp=root; st->ht->size= ht_size; st->ht->s=(stNode*)calloc(st->ht->size,sizeof(stNode)); par=temp; temp=temp->children; while(temp!=NULL){ if(strcmp(temp->name,"FUNCTIONDEF")==0){ if(st->children!=NULL){ stChil=st->children; temp2=temp->children; while(temp2!=NULL){ if(strcmp(temp2->name,"FUNID")==0){ break; } temp2=temp2->next; } while(stChil->next!=NULL){ if(temp2!=NULL && strcmp(stChil->ht->scope,temp2->p->tk->value)==0){ fprintf(errorFile,"Multiple Declarations of function %s at line %d\n",temp2->p->tk->value,temp2->p->tk->line_no); break; } stChil=stChil->next; } if(temp2!=NULL && strcmp(stChil->ht->scope,temp2->p->tk->value)==0){ fprintf(errorFile,"Multiple Declarations of function %s at line %d\n",temp2->p->tk->value,temp2->p->tk->line_no); } else if(stChil->next==NULL){ stChil->next=buildST(temp); stChil->next->par=stChil->par; } } else{ st->children=buildST(temp); st->children->par=st; } } else if(strcmp(temp->name,"ASSIGNMENTSTMT")==0){ if(checkinHash(st,temp->children->p->tk->value)==0){ fprintf(errorFile,"Undeclared Variable %s at line %d\n",temp->children->p->tk->value,temp->children->p->tk->line_no); } } else if(strcmp(temp->name,"DECLARATIONSTMT")==0){ st=insertToHT(st,temp,&begin_offset); } temp=temp->next; } return stAns; } int inHt(char* var_name,symbolTable st){ st_hashTable ht = st->ht; int i=0; stNode temp; for(i=0;i<ht->size;i++){ if(ht->s[i]){ temp=ht->s[i]; while(temp!=NULL){ if(strcmp(temp->var_name,var_name)==0){ return 1; } temp=temp->next; } } } return 0; } char* staticParent(symbolTable st,char* varname){ symbolTable temp=st; while(temp!=NULL){ if(inHt(varname,temp)){ return temp->ht->scope; } temp=temp->par; } return NULL; } int compare(const void* s1,const void* s2){ return ((stNode*)s1)[0]->offset - ((stNode*)s2)[0]->offset; } int level =1; void printHash(symbolTable st){ st_hashTable ht = st->ht; int i=0; stNode temp; stNode* res=NULL; int s=0; for(i=0;i<ht->size;i++){ if(ht->s[i]){ if(res){ res=(stNode*)realloc(res,(s+1)*sizeof(stNode));s++; } else{ res=(stNode*)malloc(sizeof(stNode)); s=1; } temp=ht->s[i]; while(temp!=NULL){ res[s-1]=temp; if(temp->next!=NULL){ res=(stNode*)realloc(res,(s+1)*sizeof(stNode));s++; } temp=temp->next; } } } qsort(res,s,sizeof(stNode),compare); for(i=0;i<s;i++){ if(strcmp(res[i]->type,"MATRIX")==0){ if(i!=s-1){ if(st->par==NULL){ printf("%-20s %-20s %-13d %-20s %-8s [%d , %d] %-10d %-10d\n",res[i]->var_name,ht->scope,level,"NULL",res[i]->type,res[i]->mat->x,res[i]->mat->y,res[i+1]->offset-res[i]->offset,res[i]->offset); } else{ printf("%-20s %-20s %-13d %-20s %-8s [%d , %d] %-10d %-10d\n",res[i]->var_name,ht->scope,level,st->par->ht->scope,res[i]->type,res[i]->mat->x,res[i]->mat->y,res[i+1]->offset-res[i]->offset,res[i]->offset); } } else{ if(st->par){ printf("%-20s %-20s %-13d %-20s %-8s [%d , %d] %-10d %-10d\n",res[i]->var_name,ht->scope,level,st->par->ht->scope,res[i]->type,res[i]->mat->x,res[i]->mat->y,st->last_offset-res[i]->offset,res[i]->offset); } else{ printf("%-20s %-20s %-13d %-20s %-8s [%d , %d] %-10d %-10d\n",res[i]->var_name,ht->scope,level,"NULL",res[i]->type,res[i]->mat->x,res[i]->mat->y,st->last_offset-res[i]->offset,res[i]->offset); } } } else{ if(i!=s-1){ if(st->par){ printf("%-20s %-20s %-13d %-20s %-20s %-10d %-10d\n",res[i]->var_name,ht->scope,level,st->par->ht->scope,res[i]->type,res[i+1]->offset-res[i]->offset,res[i]->offset); } else{ printf("%-20s %-20s %-13d %-20s %-20s %-10d %-10d\n",res[i]->var_name,ht->scope,level,"NULL",res[i]->type,res[i+1]->offset-res[i]->offset,res[i]->offset); } } else{ if(st->par) { printf("%-20s %-20s %-13d %-20s %-20s %-10d %-10d\n",res[i]->var_name,ht->scope,level,st->par->ht->scope,res[i]->type,st->last_offset-res[i]->offset,res[i]->offset); } else{ printf("%-20s %-20s %-13d %-20s %-20s %-10d %-10d\n",res[i]->var_name,ht->scope,level,"NULL",res[i]->type,st->last_offset-res[i]->offset,res[i]->offset); } } } } } void printST1(symbolTable st){ symbolTable temp=st; while(temp!=NULL){ printHash(temp); level++; printST1(temp->children); level--; temp=temp->next; } } void printST(symbolTable st){ printf("-----------------------------------------------------------------------------------------------------------------------\n"); printf("%-20s %-20s %-10s %-20s %-20s %-10s %-10s\n","Identifier Name","SCOPE","NestingLevel","Static Parent","TYPE","WIDTH","OFFSET"); printf("-----------------------------------------------------------------------------------------------------------------------\n"); printST1(st); } astNode typeChecker(astNode ast,symbolTable root){ }
C
#include<stdio.h> #include<stdlib.h> #include<unistd.h> #include<sys/select.h> #include<string.h> int main(){ fd_set readfds, writefds; char msg[100]; int activity, max; FILE *fdw = popen("./reader", "w"), *fdr1 = popen("./writer1", "r"), *fdr2 = popen("./writer2", "r"), *fdr3 = popen("./writer3", "r"); int fdwn = fileno(fdw), fdr1n = fileno(fdr1), fdr2n = fileno(fdr2), fdr3n = fileno(fdr3); if(fdr1n>fdr2n) max = fdr1n; else max = fdr2n; if(fdr3n>max) max = fdr3n; for(int i=0; i<3; i++){ FD_ZERO(&readfds); FD_ZERO(&writefds); FD_SET(fdwn, &writefds); FD_SET(fdr1n, &readfds); FD_SET(fdr2n, &readfds); FD_SET(fdr3n, &readfds); printf("i: %d\n", i); activity = select(max+1, &readfds, NULL, NULL, NULL); if(activity<0){ printf("select error\n"); return 1; } else printf("activity: %d\n", activity); if(FD_ISSET(fdr1n, &readfds)){ printf("read detected on 1\n"); read(fdr1n, msg, sizeof(msg)); printf("read from 1\n"); int len = strlen(msg); //msg[len] = '\n'; if(len>2) printf("%s\n", msg); } else if(FD_ISSET(fdr2n, &readfds)){ printf("read detected on 2\n"); read(fdr2n, msg, sizeof(msg)); int len = strlen(msg); //msg[len] = '\n'; if(len>2) printf("%s\n", msg); } else if(FD_ISSET(fdr3n, &readfds)){ printf("read detected on 3\n"); read(fdr3n, msg, sizeof(msg)); int len = strlen(msg); //msg[len] = '\n'; if(len>2) printf("%s\n", msg); } } pclose(fdw); pclose(fdr1); pclose(fdr2); pclose(fdr3); return 0; }
C
#include <poll.h> #include <termios.h> void _shrink(int alink, char *result, int x) { *result=x; } void _extend(int alink, int *result, char x) { *result=x; } void _strlen(int alink, int* result, char *s) { char *t=s; for (;*s;s++) {} *result=(int)(s-t); } void _strcmp(int alink, int *result, char *s2, char *s1) { while (*s1 != 0 && *s2 != 0 && *s1 == *s2) { s1++; s2++; } if (*s1 == 0 && *s2 == 0) *result=0; else if (*s1 > *s2) *result=1; else *result=-1; } void _strcpy(int alink, int *result, char *src, char *trg) { while (*src) { *trg=*src; trg++; src++; }; *trg=0; } void _strcat(int alink, int *result, char *src, char *trg) { while (*trg) { trg++; } _strcpy(0, 0, src, trg); } void _writeString(int alink, int result, char *s){ int len; _strlen(0, &len, s); asm("int $0x80" : /* No output registers */ : "a" (4), /* eax = system call number (write) */ "b" (1), /* ebx = stdout */ "c" (s), /* ecx = pointer to buffer */ "d" (len)); /* edx = buffer length */ } void _writeInteger(int alink, int result, int x) { char buf[12]; int minus=(x<0),i=11; if (!minus) x=-x; buf[i--]=0; if (x==0) buf[i--]='0'; while (x<0) { buf[i--]='0'-x%10; x/=10; } if (minus) buf[i--]='-'; _writeString(0,0,&buf[i+1]); } void _writeByte(int alink, int result, char x) { _writeInteger(0, 0, x); } void _writeChar(int alink, int result, char x) { char buf[2]={x,0}; _writeString(0, 0, buf); } static void readSingleChar(char *buf) { int unused; asm volatile("int $0x80" : "=a" (unused) : "a" (3), /* eax = system call number (read) */ "b" (0), /* ebx = stdin */ "c" (buf), /* ecx = pointer to buffer */ "d" (1)); /* edx = buffer length */ } void _readString(int *alink, int result, char *s, int size) { while (1) { readSingleChar(s); if (size <= 1 || *s == '\n') break; s++; size--; } if (*s != '\n') s++; *s = 0; } static inline int isDigit(char s) { return s >= '0' && s <= '9'; } /* FIXME: handle overflow */ static int parseInteger(char *s) { int res=0,minus; if (!*s) return res; minus=(*s == '-'); if (minus) s++; while (isDigit(*s)) { res*=10; res+=*s-'0'; s++; } return minus ? -res : res; } static inline int isWhite(char s) { return s == ' ' || s == '\t' || s == '\n' || s == '\r'; } void _readInteger(int *alink, int *result) { char buf[64]; int i=0,state=0; while (1) { readSingleChar(&buf[i]); if (state == 0) { if (buf[i] == '-') state = 1; else if (isDigit(buf[i])) state = 2; else if (!isWhite(buf[i])) break; else i--; } else if (state == 1) { if (isDigit(buf[i])) state = 2; else break; } else if (state == 2) { if (!isDigit(buf[i])) { state = 3; break; } } i++; } buf[state == 3 ? i+1 : 0] = 0; *result = parseInteger(buf); } void _readByte(int *alink, char *result) { int res; _readInteger(0, &res); *result = res; } void _readChar(int *alink, char *result) { volatile struct termios s; asm volatile("int $0x80" : : "a" (54), /* eax = system call number (ioctl) */ "b" (0), /* ebx = stdin */ "c" (0x5401), /* ecx = ioctl request (TCGETS) */ "d" (&s)); /* edx = buffer */ s.c_lflag &= ~ICANON; asm volatile("int $0x80" : : "a" (54), /* eax = system call number (ioctl) */ "b" (0), /* ebx = stdin */ "c" (0x5403), /* ecx = ioctl request (TCSETSW) */ "d" (&s)); /* edx = buffer */ readSingleChar(result); s.c_lflag |= ICANON; asm volatile("int $0x80" : : "a" (54), /* eax = system call number (ioctl) */ "b" (0), /* ebx = stdin */ "c" (0x5403), /* ecx = ioctl request (TCSETSW) */ "d" (&s)); /* edx = buffer */ }
C
/* -*- coding: iso-latin-1-unix; -*- */ /* DECLARO QUE SOU O UNICO AUTOR E RESPONSAVEL POR ESTE PROGRAMA. // TODAS AS PARTES DO PROGRAMA, EXCETO AS QUE FORAM FORNECIDAS // PELO PROFESSOR OU COPIADAS DO LIVRO OU DAS BIBLIOTECAS DE // SEDGEWICK OU ROBERTS, FORAM DESENVOLVIDAS POR MIM. DECLARO // TAMBEM QUE SOU RESPONSAVEL POR TODAS AS COPIAS DESTE PROGRAMA // E QUE NAO DISTRIBUI NEM FACILITEI A DISTRIBUICAO DE COPIAS. // // Autor: Gabriel de Russo e Carmo // Numero USP: 9298041 // Sigla: GABRIELD // Data: 2015-11-15 // // Este arquivo faz parte da tarefa I // da disciplina MAC0121. // ////////////////////////////////////////////////////////////// */ #ifndef _PALAVRAS_H #define _PALAVRAS_H #include <string.h> #include <stdlib.h> #include <ctype.h> #include <stdio.h> typedef char *string; struct pacote { string pal; int linha; }; typedef struct pacote pct; /* Devolve um ponteiro para um struct que contem uma 'palavra boa' de entrada // e a linha que aparece em entrada. // Uma palavra uma sequncia maximal no vazia de caracteres alfanumricos e // dita boa se comea com uma letra.*/ pct *proximaPalavra (FILE *entrada); #endif
C
#include<stdio.h> #include<unistd.h> #include<sys/types.h> #include<sys/wait.h> #include<stdlib.h> int main(int argc,char *argv[]) { for(int i=1;i<=4 ;i++) { fork(); printf("\n %d : my PID = %d \n ",i,(int)getpid()); } sleep(1); printf("--> my PID = %d \n",(int)getpid()); return 0; }
C
#include <stdio.h> #include <string.h> /**********Begin**********/ char* fun(char *a) { int num = strlen(a); char* p = &a[num-1]; while (*p == '*') { a[num-1] = ' \0'; p--; num--; } return a; } /**********End**********/ int main() { char s[81]; fgets(s,81,stdin); fun( s ); printf("The string after deleted:\n"); puts(s); strcpy(s, "****A*BC*DE*F*G*********"); fun(s); printf("%s", s); return 0; }
C
#include "lists.h" /** * insert_dnodeint_at_index - insert a new node at a given position * @h: pointer to the head of the list * @idx: index of where the new node should be inserted, starting from 0 * @n: data of the new node * * Return: pointer to the new node or NULL on failure */ dlistint_t *insert_dnodeint_at_index(dlistint_t **h, unsigned int idx, int n) { dlistint_t *node, *looper; unsigned int i = 0; if (!h) return (NULL); if (idx == 0) return (add_dnodeint(h, n)); looper = *h; while (looper && i < idx) { looper = looper->next; i++; } if (i != idx) return (NULL); if (!looper) return (add_dnodeint_end(h, n)); node = malloc(sizeof(dlistint_t)); if (!node) return (NULL); node->n = n; node->next = looper; node->prev = looper->prev; (looper->prev)->next = node; looper->prev = node; return (node); }
C
#include<stdio.h> int main() { int i; for(i=0;i<100;i++) { if(((i%10)%3)==0) { printf("%d \t",i); } } }
C
#include <msp430.h> /** * main.c */ int main(void) { WDTCTL = WDTPW | WDTHOLD; // stop watchdog timer P1DIR &= ~BIT1; //configures as input P9OUT |= BIT7; // pull-up resistor P9REN |= BIT7; //enable resistor on P2.1 P9DIR |= BIT7; //configures as output while(1) { int value = P5IN & BIT6; // set button as an int value if(value == 0) P9OUT |= BIT7; // if value is 0 turn on LED else P9OUT &= ~BIT7; // if not keep it off } }
C
// // // ParameterDatabase.h // #ifndef PARAMETERDATABASE_H #define PARAMETERDATABASE_H #include "../GeneralInclude/ForwardDeclarations.h" #include "../GeneralInclude/BasicTypes.h" #include "../Base/CC_RootObject.h" #include "../Qom/object.h" /* * Base class from which all parameter database classes are derived. * A parameter database object encapsulates a set of parameter values. * Each parameter can have two values: the <i>default value</i> and the * <i>current value</i>. * The default value is the value of the parameters immediately after the * database object is created or reset. * The current values are initialized with the default values at the time the * database object is created or * reset and they can subsequently be modified. * <p> * Parameters are identified by a <i>parameter identifier</i>. * Syntactically, this is a positive integer. * Each application instantiated from the framework would have its own set of * parameter identifiers. * <p> * In order to properly use the parameter database abstraction, it is * necessary to understand the conceptual implementation model that is * behind the interface defined in this class. * Parameter database information is stored in two tables: the <i>Default Table</i> * and the <i>Operational Table</i>. Each table stores a sequence of pairs. * The pairs have the form: (parameter value, parameter identifier). * Each entry in the table, in other words, contains the value of a parameter * and its identifier. * The two tables store values for the same set of parameters. * They differ only because the values stored in the default table are * intended to remain fixed whereas the values stored in the operational table * can be dynamically updated. * The operational table is initialized with a copy of the default table(this * is done using the <code>reset</code> operation). * <p> * In many implementations, the default table will be stored in ROM and the * operational table will be stored in RAM. * <p> * No methods are defined to set the default parameter values. This is because, * in most cases, these are defined outside the parameter database class * (they may, for instance, be burnt in PROM). * <p> * A parameter database is a low-level data structure whose implementation will * usually require use of pointers. Most implementations of this class * will therefore violate project specific coding rule PR3.1. * <p> * Client components can access the parameters in two ways. They can either * get their values using the getter methods defined in this interface. Or * they can <i>link</i> to the parameters using the <code>getParameterPointer</code> * method. This method returns a pointer to a specific parameter(as identified * by its identifier) which the client component can then store internally and * use to directly access the parameter value. * <p> * Parameters have a type. * The type of the parameter defines how the raw parameter value is * interpreted and how it is returned to the * external user of the database. * The possible types for the parameters are: unsigned int, int, unsigned short, * unsigned char, char, float, double. * For each paramete type, there is a dedicated parameter getter method. * Note that this interface does not mandate any protection against attempts to * access parameters with the wrong type. * Thus, for instance, if the parameter identified by identifier ID is * intended to represent an integer, * attempts to retrieve it as if it were of float type(using method * <CODE>getFloatParameter(ID)</CODE>) will not necessarily result * in an error and may produce a meaningless result. * Avoiding this type of errors is the responsibility of the user. * Subclasses, however, are free to introduce some run-time check to catch * this kind of error. * <p> * For similar reasons, the interface defined by this class does not mandate * any checks on the legality of the value of the parameter identifier in the * method calls. Such checks can again be added by subclasses. * <p> * The methods declared by this class allow an application component to * establish a link between their internal variables and the database parameters. * The process whereby this link is established is called <i>database linking</i>. * Two types of database linking are allowed by this class: <i>copy link</i> * and <i>pointer link</i>. * <p> * In a <i>copy link</i>, the application component holds a reference to * the parameter database and to the identifier of the target parameter * and periodically updates the value of its internal variable by copying * the value of the target database parameter. * <p> * In a <i>pointer link</i>, the application component internally defines * a pointer which is then initialized to point to the target database * parameter. The application component effectively uses the target database * parameter as its internal variable. * <p> * This is an abstract class because the internal organization of the * parameter database is application-dependent. * All the class methods are declared abstract. * In particular, the data structure used to represent the parameter tables * and the way parameters and their identifiers are associated is * application dependent. * <p> * @todo This class defines the setter and getter methods to be virtual. This * is expensive in CPU time. Given that database implementations will often * be generated automatically by XSL programs, and given that an application * would normally only have one database component, it may be wiser to * have the XSL program generate an implementation for class ParameterDatabase that * is defined to have only non-virtual methods. The problem with this approach * is that it is not possible to have multiple implementations of a database * in a single delivery and that therefore it is not possible to have several * database test cases in the same delivery(this could be alleviated by * generating the test case for the database as well as the database * implementation). * @author Alessandro Pasetti(P&P Software GmbH) * @version 1.0 * @ingroup Data */ #define TYPE_PARAMETERDATABASE "parameterdatabase" void ParameterDatabase_register(void); /////////////////////////////////////////////////////////////////////////////// // // class and struct // /////////////////////////////////////////////////////////////////////////////// struct ParameterDatabase { CC_RootObject parent; }; struct ParameterDatabaseClass { CC_RootObjectClass parent_class; void (*reset)(void *obj); void (*setParameterUnsignedInt)(void *obj, TD_DatabaseId parId, unsigned int newValue); void (*setParameterInt)(void *obj, TD_DatabaseId parId, int newValue); void (*setParameterUnsignedShort)(void *obj, TD_DatabaseId parId, unsigned short newValue); void (*setParameterShort)(void *obj, TD_DatabaseId parId, short newValue); void (*setParameterBool)(void *obj, TD_DatabaseId parId, bool newValue); void (*setParameterChar)(void *obj, TD_DatabaseId parId, char newValue); void (*setParameterUnsignedChar)(void *obj, TD_DatabaseId parId, unsigned char newValue); void (*setParameterFloat)(void *obj, TD_DatabaseId parId, float newValue); void (*setParameterDouble)(void *obj, TD_DatabaseId parId, double newValue); unsigned int (*getParameterUnsignedInt)(void *obj, TD_DatabaseId parId); int (*getParameterInt)(void *obj, TD_DatabaseId parId); unsigned short (*getParameterUnsignedShort)(void *obj, TD_DatabaseId parId); short (*getParameterShort)(void *obj, TD_DatabaseId parId); bool (*getParameterBool)(void *obj, TD_DatabaseId parId); unsigned char (*getParameterUnsignedChar)(void *obj, TD_DatabaseId parId); char (*getParameterChar)(void *obj, TD_DatabaseId parId); float (*getParameterFloat)(void *obj, TD_DatabaseId parId); double (*getParameterDouble)(void *obj, TD_DatabaseId parId); unsigned int* (*getParameterPointerUnsignedInt)(void *obj, TD_DatabaseId parId); int* (*getParameterPointerInt)(void *obj, TD_DatabaseId parId); unsigned short* (*getParameterPointerUnsignedShort)(void *obj, TD_DatabaseId parId); short* (*getParameterPointerShort)(void *obj, TD_DatabaseId parId); unsigned char* (*getParameterPointerUnsignedChar)(void *obj, TD_DatabaseId parId); char* (*getParameterPointerChar)(void *obj, TD_DatabaseId parId); bool* (*getParameterPointerBool)(void *obj, TD_DatabaseId parId); float* (*getParameterPointerFloat)(void *obj, TD_DatabaseId parId); double* (*getParameterPointerDouble)(void *obj, TD_DatabaseId parId); }; #define PARAMETERDATABASE_GET_CLASS(obj) \ OBJECT_GET_CLASS(ParameterDatabaseClass, obj, TYPE_PARAMETERDATABASE) #define PARAMETERDATABASE_CLASS(klass) \ OBJECT_CLASS_CHECK(ParameterDatabaseClass, klass, TYPE_PARAMETERDATABASE) #define PARAMETERDATABASE(obj) \ OBJECT_CHECK(ParameterDatabase, obj, TYPE_PARAMETERDATABASE) ParameterDatabase* ParameterDatabase_new(void); #endif
C
#include "myLib.h" #include "furtherTrees.h" #include "trees.h" // TODO 2.0 // TODO 4.0 // Prototypes void initialize(); void game(); // Button Variables unsigned short buttons; unsigned short oldButtons; // Horizontal Offset unsigned short hOff; int main() { initialize(); while(1) { game(); oldButtons = buttons; buttons = BUTTONS; } } // Initialize the game on first launch void initialize() { // TODO 2.1 - set up display control register REG_DISPCTL = MODE0 | BG0_ENABLE | BG1_ENABLE; // TODO 4.1 - edit display control register to enable bg 0 // TODO 2.2 - load tile palette DMANow(3, furtherTreesPal, PALETTE, furtherTreesPalLen/2); // TODO 2.3 - set up bg 1 control register REG_BG1CNT = BG_SIZE_SMALL | BG_CHARBLOCK(0) | BG_SCREENBLOCK(28); // TODO 2.4 - load furtherTrees tiles to charblock DMANow(3, furtherTreesTiles, &CHARBLOCK[0], furtherTreesTilesLen/2); // TODO 2.5 - load furtherTrees map to screenblock DMANow(3, furtherTreesMap, &SCREENBLOCK[28], furtherTreesMapLen/2); // TODO 4.2 - set up bg 0 control register REG_BG0CNT = BG_SIZE_WIDE | BG_CHARBLOCK(1) | BG_SCREENBLOCK(26); // TODO 4.3 - load trees tiles to charblock DMANow(3, treesTiles, &CHARBLOCK[1], treesTilesLen/2); // TODO 4.4 - load trees map to screenblock DMANow(3, treesMap, &SCREENBLOCK[26], treesMapLen/2); hOff = 0; buttons = BUTTONS; } // Update game each frame void game() { // Scroll the background if(BUTTON_HELD(BUTTON_LEFT)) { hOff--; } if(BUTTON_HELD(BUTTON_RIGHT)) { hOff++; } waitForVBlank(); // Update the offset registers with the actual offsets // TODO 5.0 - change to implement parallax REG_BG0HOFF = hOff; //REG_BG1HOFF = hOff; if (hOff % 2 == 0) { REG_BG1HOFF = hOff; } }
C
#include "head.h" #include <string.h> unsigned long long tick(void) { unsigned long long tmp; __asm__ __volatile__ ("rdtsc" : "=A" (tmp) ); return tmp; } int Plus_R(int n, int m, float *A1, float *A2, int *JA1, int *JA2, struct IA *IA1, struct IA *IA2, int lenA1, int lenA2, float *A3, int *JA3, struct IA *IA3, int *lenA3) { float *T = calloc(m, sizeof(float)); struct IA *tmp1 = IA1->next, *tmp2, *tmp3 = IA3; int l3 = 0, al, t; while (tmp1->next != NULL) { tmp2 = IA2->next; while (tmp2->next != NULL) { if (tmp1->i == tmp2->i) break; tmp2 = tmp2->next; } if (tmp2->next == NULL) { tmp3 = add(tmp3, tmp1->i, l3); al = abs(tmp1->next->Nk - tmp1->Nk); for (int k=0; k<al; k++) { A3[k+l3] = A1[tmp1->Nk+k]; JA3[k+l3] = JA1[tmp1->Nk+k]; } l3 += al; } else { // if (IA1[tmp1->Nk] < IA2[tmp2->Nk]) tmp3 = add(tmp3, tmp1->i, l3); // else // tmp3 = add(tmp3, tmp2->j, tmp2->Nk); al = abs(tmp1->next->Nk - tmp1->Nk); for (int k=0; k<al; k++) T[JA1[tmp1->Nk+k]] += A1[tmp1->Nk+k]; t = JA1[tmp1->Nk+al-1]; al = abs(tmp2->next->Nk - tmp2->Nk); for (int k=0; k<al; k++) T[JA2[tmp2->Nk+k]] += A2[tmp2->Nk+k]; if (t < JA2[tmp2->Nk+al-1]) t = JA2[tmp2->Nk+al-1]; for (int k=0; k<=t; k++) if (T[k] != 0) { A3[l3] = T[k]; JA3[l3] = k; l3++; } memset(T, 0, m*sizeof(T)); } tmp1 = tmp1->next; } tmp2 = IA2->next; while (tmp2->next != NULL) { tmp1 = IA1->next; while (tmp1->next != NULL) { if (tmp1->i == tmp2->i) break; tmp1 = tmp1->next; } if (tmp1->next == NULL) { tmp3 = add(tmp3, tmp2->i, l3); al = abs(tmp2->next->Nk - tmp2->Nk); for (int k=0; k<al; k++) { A3[k+l3] = A2[tmp2->Nk+k]; JA3[k+l3] = JA2[tmp2->Nk+k]; } l3 += al; } tmp2 = tmp2->next; } *lenA3 = l3; add(tmp3, n, l3); return 0; } /* int matrTolist(float *matr, int n, int m, struct IA *IA) { for(int i = 0; i < n; i++) for(int j = 0; j < m; j++) { if (matr[i*n+j] != 0) { if (IA == NULL) { IA = create(i, matr[i*n+j]); } else { IA = add(IA, i, matr[i*n+j]); } } } } */ int summtrix(float *matr1, float *matr2, float *matr3,int n,int m) { for (int i=0; i<n; i++) for (int j=0; j<m; j++) matr3[i*m+j] = matr1[i*m+j] + matr2[i*m+j]; return 0; } int time_test(int fill) { srand(time(0)); int n1, m1, n2, m2, lenA1 = 0, lenA2 = 0, lenA3 = 0; float *Matr1, *Matr2, *Matr3, *A1, *A2, *A3; int *JA1, *JA2, *JA3; struct IA *IA1 = NULL, *IA2 = NULL, *IA3 = create(-1, -1); int count1 = 0, count2 = 0; // количество ненулевых элементов //int fill = 2; // то, что заполнится 5 % unsigned long long time_beg, time_end; unsigned long long time_beg2, time_end2; // Сложение методом единичек n1 = m1 = 1000; IA1 = create(-1, -1); Matr1 = calloc(n1*m1, sizeof(float)); create_matrix(Matr1, n1, m1, fill, &count1); A1 = malloc(n1*m1*sizeof(float)); JA1 = malloc(n1*m1*sizeof(int)); matrDefault(Matr1, n1, m1,A1,JA1,IA1, &lenA1); //print(n1,m1, Matr1, A1, JA1, IA1, lenA1); printf("Time test for summing arrays of 10000 elements with fill of %d procents", fill); n2 = m2 = 1000; IA2 = create(-1, -1); Matr2 = calloc(n2*m2, sizeof(float)); create_matrix(Matr2, n2, m2, fill, &count2); printf("\n"); A2 = malloc(n2*m2*sizeof(float)); JA2 = malloc(n2*m2*sizeof(int)); matrDefault(Matr2, n2, m2,A2,JA2,IA2, &lenA2); //print(n2,m2, Matr2, A2, JA2, IA2, lenA2); //Matr3 = calloc(, sizeof(float)); // Сложение Matr3 = calloc(n2*m2, sizeof(float)); A3 = malloc(n2*m2*sizeof(float)); JA3 = malloc(n2*m2*sizeof(int)); time_beg = tick(); Plus_R(n1, m1, A1, A2, JA1, JA2, IA1, IA2, lenA1, lenA2, A3, JA3, IA3, &lenA3); time_end = tick(); printf("Time taken %lu milliseconds for method \n", time_end - time_beg); time_beg2 = tick(); summtrix(Matr1, Matr2, Matr3, n1, m1);; time_end2 = tick(); printf("Time taken %lu milliseconds for simple metod\n", time_end2 - time_beg2); return 0; //print(n1,m1, Matr3, A3, JA3, IA3, lenA1); } /* int time_test2(int fill) { srand(time(0)); int var, n1, m1, n2, m2, lenA1 = 0, lenA2 = 0, lenA3 = 0; float *Matr1, *Matr2, *Matr3, *A1, *A2, *A3; int *JA1, *JA2, *JA3; struct IA *IA1 = NULL, *IA2 = NULL, *IA3 = create(-1, -1); int count1 = 0, count2 = 0; // количество ненулевых элементов // то, что заполнится 5 % clock_t time_beg, time_end; // Сложение методом единичек n1 = m1 = 500; IA1 = create(-1, -1); Matr1 = calloc(n1*m1, sizeof(float)); create_matrix(Matr1, n1, m1, fill, &count1); A1 = malloc(n1*m1*sizeof(float)); JA1 = malloc(n1*m1*sizeof(int)); matrDefault(Matr1, n1, m1,A1,JA1,IA1, &lenA1); //print(n1,m1, Matr1, A1, JA1, IA1, lenA1); n2 = m2 = 500; IA2 = create(-1, -1); Matr2 = calloc(n2*m2, sizeof(float)); create_matrix(Matr2, n2, m2, fill, &count2); printf("\n"); A2 = malloc(n2*m2*sizeof(float)); JA2 = malloc(n2*m2*sizeof(int)); matrDefault(Matr2, n2, m2,A2,JA2,IA2, &lenA2); //print(n2,m2, Matr2, A2, JA2, IA2, lenA2); Matr3 = calloc(10*10, sizeof(float)); // Сложение Matr3 = calloc(n2*m2, sizeof(float)); A3 = malloc(n2*m2*sizeof(float)); JA3 = malloc(n2*m2*sizeof(int)); //time_beg = clock(); Plus_R(n1, m1, A1, A2, JA1, JA2, IA1, IA2, lenA1, lenA2, A3, JA3, IA3, &lenA3); //time_end = clock() - time_beg; printf("Time taken %d seconds %d milliseconds", (time_end * 1000 / CLOCKS_PER_SEC)/1000, (time_end * 1000 / CLOCKS_PER_SEC)%1000); //print(n1,m1, Matr3, A3, JA3, IA3, lenA1); }*/ // Функция выделения памяти под элемент и его создания struct IA* create(int i, int num) { struct IA *node = malloc(sizeof(struct IA)); if (node) { node->Nk = num; node->i = i; node->next = NULL; } return node; } // Функция добавления элемента в стек struct IA* add(struct IA *node, int i, int num) { struct IA *curr; curr = create(i, num); if (curr == NULL) return NULL; node->next = curr; return curr; } // Освобождение всех эл-тов стека void free_all(struct IA *head) { struct IA *nxt; for (; head; head = nxt) { nxt = head->next; free(head); } }
C
#include <stdio.h> #include <netdb.h> #include <arpa/inet.h> int main(int argc, char *argv[]){ char *host; host = argv[1]; if (argc < 2){ printf("Modo de uso: ./resolver www.businesscorp.com.br\n"); return 0; } else { struct hostent *alvo = gethostbyname(host); if (alvo == NULL) { printf ("Ocorreu um erro :( \n"); } else { printf("IP: %s\n",inet_ntoa(*((struct in_addr *)alvo->h_addr))); } } return 0; }
C
/* Tier 3 : Part 5 : Question 3 */ #include<stdio.h> #include<stdlib.h> #include<stdarg.h> int number_input(); int add_some_numbers(); double add(int number_count,...); int number_input()//simple function for getting a number { int user_number; while( scanf("%d",&user_number)!=1) { printf("Pleaes enter an integer\r\n"); fflush(stdin); } return user_number; } int add_some_numbers()//function to run the addition { int answer=0; int number_of_arguements; printf("Please enter the number of summations from 0 you want\r\n"); printf("Maximum is 20\r\n"); number_of_arguements = number_input(); if(number_of_arguements>20) { fprintf(stderr,"%s","Sorry number wasn't in the range of 0-20\r\n"); exit(EXIT_FAILURE); } else { answer = add(number_of_arguements,0,1.1,2,3.3,4,5.5,6, 7.7,8,9.9,10,11.11,12,13.13,14,15.15,16,17.17,18,19.19); printf("The added numbers upto %d are = %d\r\n",number_of_arguements,answer); return 0; } } double add(int number_count,...)//function to add variable numbers { int loop_counter=0; int added_integers=0; double added_floats=0.0; double added_numbers=0; va_list ap;//create a variable called ap from va_list va_start(ap, number_count);//start by taking the first arguement which //will tell the loop how many times to add while(loop_counter < number_count) { added_integers += va_arg(ap,int);//add the next arguement of type integer added_floats += va_arg(ap,double);//add the next arguement of type double //the second arguement is a safety net where the arguement will only be caught if its //of the type specified , in other words if you have only integers , and its looking for a //double , the program wont add the double at all loop_counter++; } va_end(ap); // end the use of va_list variable ap printf("%d is the added integers \r\n",added_integers); printf("%f is the added floats \r\n",added_floats); added_numbers = (double)added_integers + added_floats; return added_numbers; } int main() { add_some_numbers(); return 0; }
C
/************************************************************************* > File Name: userprogram.c > Author: tiany > Mail: [email protected] > Description: 先打印出当前进程的pid,使得程序睡眠一段时间,然后根据pid > 挂载内核进程,此时程序睡眠结束,执行chdir()函数切换工作目录,陷入 > 内核,调用挂载的内核模块中的chdir()处理函数,在该自定义函数中写 > 进程地址空间; > chdir()函数返回,用户程序while(1);循环等待,保持进程不退出,使用gdb > 验证成功覆写进程地址空间。 ************************************************************************/ #include<stdio.h> #include<stdlib.h> #include<string.h> #include<unistd.h> #include<sys/types.h> void main(void) { int ret; char str[] = "hello world hello world hello world hello world hello world"; printf("my pid is %d\n",getpid()); sleep(20); /* 睡眠是为了获得pid后,插入内核模块 */ printf("printf str is %s, sizeof is %ld\n",str,sizeof(str)); ret = chdir("/tmp"); printf("chdir return ret = %d\n", ret); printf("uid is %d\n",geteuid()); while(1); }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include "WaveLib.h" #include "../Gnuplot/Gnuplot.h" int comp( const void *a, const void *b ) { if( (*(double*)a - *(double*)b) > 0.00001 ) return 1; else if( (*(double*)a - *(double*)b) < -0.00001 ) return -1; else return 0; } void Wavelet( double *inp, int N, int J ) { wave_object obj; wt_object wt; double *out; int i; obj = wave_init("haar"); out = (double*)malloc(sizeof(double)* N); wt = wt_init(obj, "dwt", N, J); setDWTExtension(wt, "sym"); setWTConv(wt, "direct"); dwt(wt, inp); double *dtmp = (double*)malloc(sizeof(double)* wt->outlength); double thr = sqrt(2*log(wt->outlength*1.0)); memcpy( dtmp, wt->output, sizeof(double)*wt->outlength ); int start = wt->length[0]; for( int i=1; i<=wt->J; i++ ) { int len = wt->length[i]; for( int j=0; j<len; j++ ) { *(dtmp+start+j) = fabs(*(dtmp+start+j)); } qsort( dtmp + start, len, sizeof(double), comp ); double fuck = 0; int len2 = len/2; if( len2*2 == len ) { fuck = (dtmp+start)[len2]/0.6745; } else { fuck = ((dtmp+start)[len2] + (dtmp+start)[len2+1])/2/0.6745; } double fuck2 = thr*fuck; // printf( "start:%d, len:%d, thr:%f, fuck:%f, %f\n", start, len, thr, fuck, fuck2 ); for( int j=0; j<len; j++ ) { if( wt->output[start+j] <= fuck2 && wt->output[start+j] >= -fuck2 ) wt->output[start+j] = 0.0; } start += len; } free( dtmp ); idwt(wt, out); wave_free(obj); wt_free(wt); memcpy( inp, out, N*sizeof(double) ); free(out); return; }
C
/* * --------------------------------- * Ʈ Ž * * --------------------------------- */ #include <stdio.h> #include <malloc.h> #include <string.h> struct tfield { char name[20]; /* ̸ */ char tel[20]; /* ȭȣ */ struct tfield *pointer; /* 带 Ű */ } *head; struct tfield *talloc(void); int main(void) { struct tfield *head,*p, sentinel; /* */ char key[20]; head=&sentinel; /* Ű */ while (p=talloc(),scanf("%s %s",p->name,p->tel)!=EOF) { p->pointer=head; head=p; } rewind(stdin); /* Ž */ while (printf("\nkey name : "),scanf("%s",key)!=EOF) { strcpy(sentinel.name,key); /* 忡 Ű Ѵ. */ p=head; while (strcmp(p->name,key)!=0) p=p->pointer; if (p!=&sentinel) printf("%s %s\n",p->name,p->tel); else printf("ã ϴ.\n"); } return 0; } struct tfield *talloc(void) /* ޸ Ҵ */ { return (struct tfield *)malloc(sizeof(struct tfield)); }
C
//Aluno: Anderson Reis dos Santos //Matricula : 03098292 //Turma : CIN04S1 #include <stdio.h> #include <stdlib.h> void sort(int *arr, int size){ int x, y, value; for (x = 1 ; x < size ; x++){ value = arr [x]; for (y = x - 1 ; y >= 0 && arr[y] > value ; y--){ arr[y+1] = arr[y]; } arr[y+1] = value; } } int main() { int a[] = {5,7,1,3,9}; int i; sort (a, 5); for ( i = 0; i < 5 ; i++) printf("%i\n", a[i]); return 0; }
C
#include "all.h" tagRng_t lastTagRng; int updateTagRng(char *str, char *bgnPtn, char *endPtn, int ignoreCase) // mbs_ { tagRng_t *i = &lastTagRng; char *p = mbs_strstrCase(str, bgnPtn, ignoreCase); if(!p) return 0; i->bgn = p; i->innerBgn = p + strlen(bgnPtn); p = mbs_strstrCase(i->innerBgn, endPtn, ignoreCase); #if 1 if(!p) return 0; i->innerEnd = p; i->end = p + strlen(endPtn); #else // v if(p) { i->innerEnd = p; i->end = p + strlen(endPtn); } else { p = strchr(i->innerBgn, 0x00); i->innerEnd = p; i->end = p; } #endif return 1; } int updateAsciiTagRng(char *str, char *bgnPtn, char *endPtn) { tagRng_t *i = &lastTagRng; char *p = strstr(str, bgnPtn); if(!p) return 0; i->bgn = p; i->innerBgn = p + strlen(bgnPtn); p = strstr(i->innerBgn, endPtn); if(!p) return 0; i->innerEnd = p; i->end = p + strlen(endPtn); return 1; }
C
/* CREMENESCU RAUL-VALENTIN 333CB */ #include "utils.h" double* my_solver(int N, double *A, double* B) { int i, j, k; double *D = malloc(N * N * sizeof(double)); double *final = malloc(N * N * sizeof(double)); double *A_tr = malloc(N * N * sizeof(double)); double *B_tr = malloc(N * N * sizeof(double)); for (i = 0; i < N; ++i) { for ( j = 0; j < N; ++j) { A_tr[j * N + i] = A[i * N + j]; B_tr[j * N + i] = B[i * N + j]; D[i * N + j] = 0; } } for (i = 0; i < N; i++) { for (j = 0; j < N; j++) { double suma = 0.0; double suma1 = 0.0; if(i <= j) { for (k = 0; k < N; k++) { suma += A_tr[i * N + k] * B[k * N + j]; suma1 += B_tr[i * N + k] * A[k * N + j]; } D[i * N + j] = suma + suma1; } } } for (i = 0; i < N; i++) { for (j = 0; j < N; j++) { double sum = 0.0; for (k = 0; k < j + 1; k++) { sum += D[i * N + k] * D[k * N + j]; } final[i * N + j] = sum; } } free(D); free(A_tr); free(B_tr); return final; }
C
#include <stdio.h> #include <string.h> #include "../wumanber.h" #include "test.c" void test_wumanber_init(void); void test_wumanber_search(void); #define HBITS 4 #define TABLE_SIZE 32768 #define NPAT 2 /* #define NPAT 3 */ uint8_t *patterns[NPAT] = { "jour", "hui", /* "h", */ }; const char *text = "hello, bonjour, hola... aujourd’hui"; int main(void) { test_wumanber_init(); test_wumanber_search(); printf("wumanber_test success\n"); return 0; } void test_wumanber_init(void) { uint8_t *patterns_[3] = { "jour", "bon", "llo" }; size_t len_patterns[3] = { 4, 3, 3 }; struct wumanber wm; struct wumamber_patterns pat; pat.n_pat = 3; pat.patterns = patterns_; pat.len_patterns = len_patterns; int ret = wumanber_init(&wm, &pat, HBITS, TABLE_SIZE); if (ret) { fail("wumanber_init() failed\n"); } if (wm.hbits != HBITS || wm.table_size != TABLE_SIZE) { fail("wumanber_init() did not set the right values for struct members\n"); } if (strcmp(*((char**) vector_get(&wm.other_patterns, 0)), patterns_[0])) { fail("wumanber_init() failed\n"); } else if (strcmp(*((char**) vector_get(&wm.other_patterns, 1)), patterns_[1])) { fail("wumanber_init() failed\n"); } else if (strcmp(*((char**) vector_get(&wm.other_patterns, 2)), patterns_[2])) { fail("wumanber_init() failed\n"); } wumanber_free(&wm); } void test_wumanber_search (void) { uint8_t *patterns_[3] = { "jour", "bon", "llo" }; size_t len_patterns[3] = { 4, 3, 3 }; struct wumanber wm; struct wumamber_patterns pat; pat.n_pat = 3; pat.patterns = patterns_; pat.len_patterns = len_patterns; int ret = wumanber_init(&wm, &pat, HBITS, TABLE_SIZE); if (ret) { fail("wumanber_init() failed\n"); } struct wumanber_matches *matches = wumanber_scan(&wm, text, strlen(text)); printf("%lu matches\n", matches->size); size_t i; for (i = 0; i < matches->size; ++i) { struct wumanber_match *match = matches->matches + i; printf("(match \n"); printf(" (pattern \"%s\")\n", match->pattern); printf(" (start \"%lu\")\n", match->start); printf(")\n"); } wumanber_matches_free(matches); wumanber_free(&wm); }