language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
#include <stdio.h> #include <stdlib.h> int main() { int year; printf("Enter the year :\n"); scanf("%d", &year); if ((year%4==0 && year%100!=0) || (year%100==0 && year%400==0)) { printf("Yes %d is a leap year :)",year); } else { printf("No You doofus %d is not a leap year, what were you thinking :(", year); } return 0; }
C
#include "graphics.h" /* * Author: Amartya Vadlamani * Notes: Not much really */ void drawIncreasingCircles(int x, int y, int radius, int numOvals, int padding, int growthFac){ for (int i = 0; i <= numOvals; i++){ drawOval(x, y, radius, radius); x += radius + padding; y -= growthFac / 2; radius += growthFac; } } int main(void){ drawIncreasingCircles(10, 100, 20, 7, 1, 10); }
C
/* Escribir un programa ISO C MULTIPLATAFORMA que procese el archivo “bigEndian.dat” sobre sí mismo, leyendo nros. de 4 bytes Big-Endian y triplicando los impares. */ #include <inttypes.h> #include <stdio.h> #include <unistd.h> #include <arpa/inet.h> int main(){ const char* file = "bigEndian.dat"; FILE* read = fopen(file,"r"); FILE* write = fopen(file,"r+"); int elementos = 0; uint32_t aux,num; //leo contenido total while (!feof(read)){ elementos += fread(&num,sizeof(uint32_t),1,read); } //copio al final para expandir //solo escribo una vez porque pide duplicar int elemEscritos = 0; rewind(read); fseek(write,0,SEEK_END); while (elemEscritos < elementos){ fread(&num,sizeof(uint32_t),1,read); elemEscritos += fwrite(&num,sizeof(uint32_t),1,write); } elemEscritos = 0; rewind(read); fseek(write,0,SEEK_END);//creo que no hace falta while (elemEscritos < elementos){ fread(&num,sizeof(uint32_t),1,read); elemEscritos += fwrite(&num,sizeof(uint32_t),1,write); } //resuelvo el problema int bytes = 0; rewind(write); fseek(read,-elementos * sizeof(uint32_t),SEEK_END); fread(&num,sizeof(uint32_t),1,read); while (!feof(read)){ aux = ntohl(num); fwrite(&num,sizeof(uint32_t),1,write); bytes += sizeof(uint32_t); if (aux % 2 == 1){ fwrite(&num,sizeof(uint32_t),1,write); bytes += sizeof(uint32_t); fwrite(&num,sizeof(uint32_t),1,write); bytes += sizeof(uint32_t); } fread(&num,sizeof(uint32_t),1,read); } ftruncate(fileno(write),bytes); fclose(write); fclose(read); return 0; }
C
#include <stdio.h> #include <stdlib.h> int main(void) { int i, n, max, *pArr = NULL; do { printf("Input n: "); scanf("%d", &n); } while (n <= 0); pArr = (int *)malloc(sizeof(int) * n); for (i = 0; i < n; i++) { printf("a[%d] = ", i); scanf("%d", &pArr[i]); } max = pArr[0]; for (int i = 1; i < n; i++) if (pArr[i] > max) max = pArr[i]; free(pArr); printf("Maximum = %d\n", max); return 0; }
C
#include <stdio.h> #include <math.h> float DIS (int , int , int , int); int main(){ int V; float D1,D2; int I; int X[6]; for(I=0,V=1;I<6;I++,printf("\n") ){ if(I==0||I==2||I==4){ printf("in X%d :",V); scanf("%d",&X[I]); } if(I==1||I==3||I==5){ printf("in Y%d :",V); scanf("%d",&X[I]); V++; } } D1=DIS(X[0],X[1],X[2],X[3]); D2=DIS(X[2],X[3],X[4],X[5]); printf("la distancia es %2.2f", D1+D2); return 0;} float DIS(int X1, int Y1 , int X2, int Y2){ int R1,R2,RT; float V; R1=X1-X2; R2=Y1-Y2; RT=R1*R1+R2*R2; V=sqrt(RT); return V; }
C
#include <stdio.h> #include <string.h> void printChars(int size, char c ); /* provided, DO NOT IMPLEMENT */ void printCheckerLine(int checkerWidth, int checkerCount, char c1, char c2); void printCheckerBoard(int checkerWidth, int checkerCount, char c1, char c2); int main(void) { char command[80]; int checkerWidth = 0; int checkerHeight = 0; char c1, c2; /* read commands from file */ /* <command> <width> <count> <c1> <c2> */ while (scanf("%s %d %d %c %c", command, &checkerWidth, &checkerHeight, &c1, &c2) == 5) { if (strcmp(command, "printCheckerLine") == 0) { printCheckerLine(checkerWidth, checkerHeight, c1, c2); } else if (strcmp(command, "printCheckerBoard") == 0) { printCheckerBoard(checkerWidth, checkerHeight, c1, c2); } } return 0; } /* * Prints the given character the given number of times on the screen. * Parameter: size - the number of characters to print * Parameter: c - the character to print */ void printChars(int size, char c ) { int i; /* print character size times */ for (i=0; i<size; i++) { printf( "%c", c ); } }
C
#include "led.h" #include "delay.h" #include "sys.h" #include "usart.h" #include <math.h> #include "lcd.h" #include "my_exit.h" extern volatile int move_left; extern volatile int move_right; void simulate ( void ) { int score_num = 0; /* */ const int r = 20; /* С뾶 */ const int l = 320; /* Ļij */ double x_ball = 160, y_ball = 330; /* Сʵʱλ */ double vx = 0, vy = 0; /* xyϵٶȷ */ double x_rect = 160, y_rect = 360; /* þ */ const int w_rect = 80; /* þĿ */ const int h_rect = 20; /* þĸ߶ */ const int move_step = 20; /* þƶIJ */ double left = r; /* ߽ */ double right = l - r; /* ߽Ҳ */ double bottom = y_rect - h_rect / 2 - r; /* ߽ײ */ double top = r; /* ߽ϲ */ LCD_DrawRectangle ( x_rect - w_rect / 2, y_rect - h_rect / 2, x_rect + w_rect / 2, y_rect + h_rect / 2 ); /* */ LCD_Fill ( x_rect - w_rect / 2, y_rect - h_rect / 2, x_rect + w_rect / 2, y_rect + h_rect / 2, RED ); LCD_ShowString ( 0, 450, 50, 50, 16, "score:" ); LCD_ShowNum ( 50, 450, score_num, 1, 16 ); vy = sin ( 45 * 3.14 / 180 ) * 5; /* xٶȷ */ vx = cos ( 45 * 3.14 / 180 ) * 5; /* yٶȷ */ while ( 1 ) { x_ball += vx; /* xķ */ y_ball -= vy; /* yķ */ while ( ( x_ball < left ) || ( x_ball > right ) || ( y_ball > bottom ) || ( y_ball < top ) ) { if ( x_ball < left ) { /* */ x_ball = 2 * r - x_ball, vx = -vx; } if ( x_ball > right ) { /* Ҳ */ x_ball = 2 * l - 2 * r - x_ball, vx = -vx; } if ( ( y_ball > bottom ) && ( ( x_ball > x_rect - w_rect / 2 - r / 1.41 ) && ( x_ball < x_rect + w_rect / 2 + r / 1.41 ) ) ) { /* С򴥵 */ y_ball = 2 * ( bottom + r ) - 2 * r - y_ball, vy = -vy; score_num++; if ( ( score_num >= 0 ) && ( score_num <= 9 ) ) { LCD_ShowNum ( 50, 450, score_num, 1, 16 ); } else if ( ( score_num >= 10 ) && ( score_num <= 99 ) ) { LCD_ShowNum ( 50, 450, score_num, 2, 16 ); } } else if ( ( y_ball > bottom ) && ( ( x_ball < x_rect - w_rect / 2 - r / 1.41 ) || ( x_ball > x_rect + w_rect / 2 + - r / 1.41 ) ) ) { /* Сδ */ LCD_Clear ( GREEN ); POINT_COLOR = RED; LCD_ShowString ( 0, 450, 50, 50, 16, "score:" ); if ( ( score_num >= 0 ) && ( score_num <= 9 ) ) { LCD_ShowNum ( 50, 450, score_num, 1, 16 ); } else if ( ( score_num >= 10 ) && ( score_num <= 99 ) ) { LCD_ShowNum ( 50, 450, score_num, 2, 16 ); } } if ( y_ball < top ) { /* */ y_ball = 2 * r - y_ball, vy = -vy; } } Draw_Circle ( x_ball, y_ball, r ); delay_ms ( 10 ); LCD_Fill ( x_ball - r, y_ball - r, x_ball + r, y_ball + r, WHITE ); if ( move_left == 1 ) { /* ƶ */ move_left = 0; /* ƶ־иλ */ if ( x_rect > w_rect / 2 ) { /* δƶԵ */ LCD_Fill ( x_rect - w_rect / 2, y_rect - h_rect / 2, x_rect + w_rect / 2, y_rect + h_rect / 2, WHITE ); x_rect -= move_step; LCD_Fill ( x_rect - w_rect / 2, y_rect - h_rect / 2, x_rect + w_rect / 2, y_rect + h_rect / 2, RED ); } } if ( move_right == 1 ) { /* ƶ */ move_right = 0; /* ƶ־иλ */ if ( x_rect < l - w_rect / 2 ) { /* δƶұԵ */ LCD_Fill ( x_rect - w_rect / 2, y_rect - h_rect / 2, x_rect + w_rect / 2, y_rect + h_rect / 2, WHITE ); x_rect += move_step; LCD_Fill ( x_rect - w_rect / 2, y_rect - h_rect / 2, x_rect + w_rect / 2, y_rect + h_rect / 2, RED ); } } } } #define DISABLE_JTAG do \ { \ RCC->APB2ENR |= 0x00000001; /* afioʱ */ \ AFIO->MAPR = ( 0x00FFFFFF & AFIO->MAPR ) | 0x04000000; /* رJTAG */ \ }while(0); int main ( void ) { DISABLE_JTAG; /* رJTAG */ SystemInit(); delay_init ( 72 ); NVIC_Configuration(); uart_init ( 9600 ); LED_Init(); key_init(); LCD_Init(); LCD_Clear ( WHITE ); POINT_COLOR = RED; simulate(); while ( 1 ); }
C
// Copyright (c) 2014 Parker Harris Emerson // Lab 1-1 Assignment for New Beginnings Fall 2014, Assigned by Bryant York. // Write a C program to sequentially search a list of positive integers read from a file named “data1.txt” for a positive integer read from the terminal. Your program should print the index or indexes of the position(s) in the list of positive integers at which the desired integer has been found. Use 0-origin indexing. If the desired integer cannot be found in the list, your program should print the string “NOT FOUND” // Simon says: A complete list of includes. #include <float.h> #include <limits.h> #include <math.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> int main(int argc, char* argv[]) { // Get user integer. int userInt = 0; printf("Please enter a positive integer: "); scanf("%d", &userInt); printf("You entered positive integer: %d\n", userInt); // Initialize and declare search variables. int* intData = NULL; int intSize = 0; int foundUserInt = 0; // Open file, assign to fileHandle FILE* fileHandle = fopen("./Data1.txt", "r"); { // Grab first value, which declares number of integers in file. fscanf(fileHandle, "%d", &intSize); // Establish array intData, setting to size of first value. intData = (int*) (malloc(sizeof(int) * intSize)); // Fill array with values, reading over file. for (int intFor1 = 0; intFor1 < intSize; intFor1++) { fscanf(fileHandle, "%d", &intData[intFor1]); } } // Super important - close the file. fclose(fileHandle); // Run through the array, comparing to intScan (initially declared at 0), and tracking largest. for (int intFor1 = 0; intFor1 < intSize; intFor1++) { if (userInt == intData[intFor1]) { printf("Number %d found at index %d.\n", userInt, intFor1); foundUserInt++; } } // If userInt not found, announce as such. if (!foundUserInt) { printf("Integer NOT FOUND.\n"); } }
C
/* This is a test of the isGameOver() function. The game ends when the last Province is bought, or when three supply piles are depleted. */ #include <stdbool.h> #include "dominion.h" #include "dominion_helpers.h" #include <stdio.h> #include <math.h> #include <stdlib.h> #include <string.h> #include <time.h> #include "rngs.h" #define RESET "\033[0m" #define KRED "\x1B[31m" void restoreSupply(struct gameState *G); int main() { int i; int total_test = 30; int failed_test = 0; srand(time(NULL)); int status = 0; int numPlayer = 2; int handCount = 5; int p = 0; int k[10] = {adventurer, council_room, feast, gardens, mine, remodel, smithy, village, baron, great_hall }; int testHand[3] = {copper, copper, village}; struct gameState G; int gameSeed = rand() % 1000 + 1; memset(&G, 23, sizeof(struct gameState)); initializeGame(numPlayer, k, gameSeed, &G); memcpy(G.hand[p], testHand, sizeof(int)*handCount); /* Test */ printf("Test 1: Province count = 0 && No supply piles depleted \n"); restoreSupply(&G); G.supplyCount[province] = 0; status = isGameOver(&G); if(status == 1) //game is over { printf(" >> PASSED: "); } else { printf(KRED " >> FAILED: " RESET); failed_test++; } printf("Expected = %d | Actual = %d \n", 1, status); printf("Test 2: Province count > 0 && No supply piles depleted \n"); restoreSupply(&G); G.supplyCount[province] = 1; status = isGameOver(&G); if(status == 0) { printf(" >> PASSED: "); } else { printf(KRED " >> FAILED: " RESET); failed_test++; } printf("Expected = %d | Actual = %d \n", 0, status); printf("Test 3: Province count > 0 && One Supply pile depleted \n"); restoreSupply(&G); G.supplyCount[province] = 1; G.supplyCount[adventurer] = 0; status = isGameOver(&G); if(status == 0) { printf(" >> PASSED: "); } else { printf(KRED " >> FAILED: " RESET); failed_test++; } printf("Expected = %d | Actual = %d \n", 0, status); printf("Test 4: Province count > 0 && Three Supply pile depleted \n"); restoreSupply(&G); G.supplyCount[province] = 1; G.supplyCount[adventurer] = 0; G.supplyCount[council_room] = 0; G.supplyCount[feast] = 0; status = isGameOver(&G); if(status == 1) { printf(" >> PASSED: "); } else { printf(KRED " >> FAILED: " RESET); failed_test++; } printf("Expected = %d | Actual = %d \n", 1, status); //=================================================== enum CARD card1; enum CARD card2; enum CARD card3; int j = total_test - 4; for(i = 0; i < j; i++) { //reset memset(&G, 23, sizeof(struct gameState)); initializeGame(numPlayer, k, gameSeed, &G); //pick a random card except province do { card1 = (enum CARD)(rand() % 27); card2 = (enum CARD)(rand() % 27); card3 = (enum CARD)(rand() % 27); } while( card1 == province || card2 == province || card3 == province || card1 == card2 || card2 == card3 || card1 == card3); //deplete the three random supplies restoreSupply(&G); G.supplyCount[card1] = 0; G.supplyCount[card2] = 0; G.supplyCount[card3] = 0; //check status status = isGameOver(&G); printf("Test %d: Province count > 0 && [%d] [%d] [%d] depleted \n", i+5, (int)card1, (int)card2, (int)card3); if(status == 1) { printf(" >> PASSED: "); } else { printf(KRED " >> FAILED: " RESET); failed_test++; } printf("Expected = %d | Actual = %d \n", 1, status); } printf("----------------------------------------------------\n"); printf("FAILED = %d | PASSED = %d | TOTAL = %d \n", failed_test, total_test-failed_test, total_test); return 0; } void restoreSupply(struct gameState *G) { int i; for(i = 0; i < 27; i++) { G->supplyCount[i] = 1; } }
C
/* *@function obtenir permet d'obtenir le choix de l'usager pour une option du menu *@param char* *@return void */ void obtenirss(char *pt){ char c; printf("Tapez : \n"); printf(" - Q pour Quitter \n"); printf(" - V pour Visualiser \n"); printf(" - C pour Chercher\n"); printf(" - A pour Ajouter un nouvel emprunt\n"); printf(" - M pour Modifier les informations d'un emprunt\n"); printf(" - S pour Supprimer un emprunt de la liste\n"); printf(" - I pour visualiser la liste Inverse \n"); printf(" - R pour retourner au menu principal\n"); printf(" - N pour Nettoyer l'ecran \n"); do{ printf("\n\n"); printf("Entrez votre choix >>"); fflush(stdin); c = toupper(getchar()); }while(strchr("QVCAMSIRN", c) == NULL); *pt = c; } /* *@function affiche permet d'afficher les informations sur l'emprunts *@param char* *@return void */ void afficherss(Emprunt emprunt){ printf("\n\nindex: %6d\n",emprunt.index); printf("l'identifiant de l'adherent: %d\n",emprunt.id); printf("nom adherent: %s\n",emprunt.nom); printf("Titre de l'ouvrage: %s\n",emprunt.Titre); printf("Auteur de l'ouvrage: %s\n",emprunt.Auteur); printf("Date d'emprunt: %d/%d/%d %d:%d \n",emprunt.date.annee,emprunt.date.mois,emprunt.date.jour,emprunt.date.heure,emprunt.date.minute); printf("Date retour: %d/%d/%d %d:%d \n",emprunt.retour.annee,emprunt.retour.mois,emprunt.retour.jour,emprunt.retour.heure,emprunt.retour.minute); } /* *@function demander permet de recuperer les informations sur l'emprunt *@param Emprunt* *@return void */ void demanderss(Emprunt *emp){ Emprunt perso; printf("Entrez les informations de l'emprunt : \n"); printf(" - index : "); scanf("%d",&(perso.index)); fflush(stdin); viderBuffer(); printf(" - identifiant adherent: "); scanf("%d",&(perso.id)); fflush(stdin); viderBuffer(); printf(" - nom adherent: "); scanf("%s",perso.nom); viderBuffer(); printf(" - Titre de l'ouvrage : "); scanf("%s",perso.Titre); viderBuffer(); printf(" - Auteur de l'ouvrage : "); scanf("%s",perso.Auteur); printf(" - date d'emprunt : \n"); printf("\t - jour :"); scanf("%d",&(perso.date.jour)); printf("\t - mois :"); scanf("%d",&(perso.date.mois)); printf("\t - année :"); scanf("%d",&(perso.date.annee)); printf("\t - heure :"); scanf("%d",&(perso.date.heure)); printf("\t - minute :"); scanf("%d",&(perso.date.minute)); printf(" - date de retour : \n"); printf("\t - jour :"); scanf("%d",&(perso.retour.jour)); printf("\t - mois :"); scanf("%d",&(perso.retour.mois)); printf("\t - année :"); scanf("%d",&(perso.retour.annee)); printf("\t - heure :"); scanf("%d",&(perso.retour.heure)); printf("\t - minute :"); scanf("%d",&(perso.retour.minute)); *emp = perso; } /* *@function visualiser permet de visualiser les informations d'un emprunt dans la liste chainée *@param liste type pointeur *@return void */ void visualiserss(pointeurs liste){ const int parEcran = 20 ; /* 20 personnes par écran */ int n ; char unCar ; n = 0 ; unCar = ' ' ; printf("Dans l'ordre : \n"); while ( unCar != 'T' && liste ){ n++; printf("%3d) %d %d %s %s %s %d/%d/%d %d:%d %d/%d/%d %d:%d \n",n,(liste->emp).index,(liste->emp).id,(liste->emp).nom, (liste->emp).Titre,(liste->emp).Auteur, (liste->emp).date.annee,(liste->emp).date.mois,(liste->emp).date.jour,(liste->emp).date.heure,(liste->emp).date.minute, (liste->emp).retour.annee,(liste->emp).retour.mois,(liste->emp).retour.jour,(liste->emp).retour.heure,(liste->emp).retour.minute); liste = liste->suivant; if ( n % parEcran == 0 || liste == NULL){ printf("\n\n"); printf("Appuyez sur Entrée pour continuer ou T pour terminer "); fflush(stdin); unCar = toupper(getchar()); if ( unCar != 'T' && liste != NULL){ printf("Dans l'ordre : \n"); } } } } /* *@function lire permet de lire les informations d'un emprunt dans un fichier elle lit une ligne dans le fichier *@param FILE *donnees , Adherent *p *@return void */ void liress (FILE * donnees, Emprunt *P){ Date date; Date retour; fscanf(donnees,"%d%d%s%s%s %d%d%d%d%d %d%d%d%d%d\n", &(P->index), &(P->id), P->nom, P->Titre, P->Auteur,&(date.annee),&(date.mois), &(date.jour),&(date.heure),&(date.minute),&(retour.annee),&(retour.mois),&(retour.jour),&(retour.heure),&(retour.minute)); P->date = date; P->retour = retour; } /* *@function creerFIFO permet de créer la liste chainée First In First Out *@param pointeur *L *@return void */ void creerFIFOss (pointeurs *L){ /* dans l'ordre FIFO */ /* comme le fichier de données a été trié selon le numéro de personnes, cette façon de création permet d'obtenir une liste triée. */ FILE *donnees ; Emprunt unePers ; pointeurs tempo, Laliste, present ; int tailleOctets = sizeof(Elements) ; donnees = fopen("Emprunt.txt","r+"); if (feof(donnees)) Laliste = NULL ; else{ Laliste = (pointeurs) malloc (tailleOctets); liress(donnees, &unePers); Laliste->emp = unePers; present = Laliste; while (!feof(donnees)){ tempo = (pointeurs) malloc (tailleOctets); liress(donnees, &unePers); tempo->emp = unePers ; present->suivant = tempo; present = tempo; } fclose(donnees); present->suivant = NULL; /* mettre la fin de la liste, ici en dehors de la boucle */ } *L = Laliste; } /* *@function inverser *@param pointeur * *@return void */ void inverserss(pointeurs *L){ pointeurs aContourner, leSuivant , liste = * L ; aContourner = liste ; liste = NULL ; while (aContourner){ leSuivant = aContourner->suivant ; aContourner->suivant = liste ; liste = aContourner ; aContourner = leSuivant; } *L = liste ; } /* *@function find permet d'effectuer une recherche dans la liste chainée *la recherche se fait en fonction des index du plus petit au plus grand *@param int, pointeur, pointeur *, pointeur * *@return void */ void findss(int aChercher, pointeurs liste, pointeurs *av, pointeurs *cl){ pointeurs avant, cestLui ; avant = NULL ; cestLui = liste ; while ( cestLui && (cestLui->emp).index < aChercher ){ avant = cestLui; cestLui = cestLui->suivant ; } /* si on ne le trouve pas, on met le cestLui à NULL */ if (cestLui && (cestLui->emp).index != aChercher) cestLui = NULL; *av = avant ; *cl = cestLui ; } /* *@function chercher permet d'appliquer la function find afin de chercher un index dans la liste *@param pointeur *@return void */ void chercherss(pointeurs liste){ pointeurs cestLui, avant ; int aChercher; do{ viderBuffer(); printf("Entrez le numéro de la personne à chercher "); scanf("%d", &aChercher); findss (aChercher,liste, &avant, &cestLui); if (cestLui != NULL){ /* on le trouve */ printf("\nYOUPI! on l'a trouvé : \n"); afficherss(cestLui->emp); }else{ printf("Désolé! on ne trouve pas cet emprunt\n"); } if (avant == NULL){ printf("\navant vaut NULL\n"); }else{ printf("\nvaleur avant : %5d\n", avant->emp.index); } viderBuffer(); printf("avez-vous un autre emprunt à chercher (O/N) ? "); //fflush(stdin); //viderBuffer(); }while (toupper(getchar()) != 'N'); viderBuffer(); } /* *@function eliminer permet la suppression dans la liste chainée *@param pointeur *,Adherent ,pointeur *@return void */ void eliminerss(pointeurs *P, pointeurs avant, pointeurs cestLui){ if(avant == NULL){ /* au début de la liste */ *P = (*P)->suivant ; /* on fait avancer la liste */ }else{ avant->suivant = cestLui->suivant; } } /* *@function supprimer permet d'appliquer la function eliminer pour *supprimer une element en fonction de l'index de cette element *@param pointeur * *@return void */ void supprimerss(pointeurs *P){ pointeurs liste, cestLui, avant, tempo ; int aSupprimer; char reponse ; do{ viderBuffer(); printf("\n\nEntrez le numéro à supprimer "); scanf("%d", &aSupprimer); findss(aSupprimer,*P, &avant, &cestLui); reponse = 'N'; if (cestLui != NULL){ printf("On l'a trouvé : \n"); afficherss(cestLui->emp); viderBuffer(); printf("\nConfirmez-vous la suppression ?(O/N) "); fflush(stdin); reponse = toupper(getchar()); if (reponse == 'O'){ eliminerss( P, avant, cestLui);} }else{ printf("Désolé! on ne trouve pas cet emprunt\n"); viderBuffer(); printf("avez-vous autre emprunt à supprimer (O/N) ? "); fflush(stdin); } }while (toupper(getchar()) != 'N'); } /* *@function inserer permet l'insertion dans la liste chainée *@param pointeur *,Adherent ,pointeur *@return void */ void insererss(pointeurs *P, Emprunt unePers, pointeurs avant){ pointeurs tempo; tempo = (pointeurs) malloc(sizeof(Elements)); tempo->emp = unePers ; if(avant == NULL){ tempo->suivant = *P ; (*P) = tempo; }else{ tempo->suivant = avant->suivant ; avant->suivant= tempo; } } /* *@function ajouter applique la function inserer pour inserer des informations sur l'emprunt * et insere les informations de la liste chainée dans le fichier emprunt.txt *@param pointeur * *@return void */ void ajouterss(pointeurs * P){ pointeurs liste,cestLui, avant, tempo ; FILE *donnees = NULL; donnees = fopen("Emprunt.txt","a"); int aAjouter; char reponse ; Emprunt unePers ; viderBuffer(); printf("Entrez le nouveau numéro de l'emprunt afin de faire une vérification d'existance: "); scanf("%d", &aAjouter); findss(aAjouter, *P, &avant, &cestLui ); reponse = 'N'; if (cestLui != NULL){ printf("Cet identifiant ou emprunt existe déjà en: \n"); afficherss(cestLui->emp); printf("\n\n"); viderBuffer(); printf("Désirez-vous ajouter les informations de cet emprunt avec un autre identifiant ?(O/N) "); fflush(stdin); reponse = toupper(getchar()); if (reponse == 'O' || cestLui == NULL){ viderBuffer(); demanderss(&unePers); insererss(P, unePers, avant); fprintf(donnees,"%d %d %s %s %s %d %d %d %d %d %d %d %d %d %d",unePers.index,unePers.id,unePers.nom,unePers.Titre,unePers.Auteur, unePers.date.annee,unePers.date.mois,unePers.date.jour,unePers.date.heure,unePers.date.minute, unePers.retour.annee,unePers.retour.mois,unePers.retour.jour,unePers.retour.heure,unePers.retour.minute); } }else{ printf("Cet identifiant n'existe pas\n"); printf("Tapez O pour l'ajout des informations de cet emprunt"); fflush(stdin); reponse = toupper(getchar()); if (reponse == 'O' || cestLui == NULL){ viderBuffer(); demanderss(&unePers); insererss(P, unePers, avant); fprintf(donnees,"%d %d %s %s %s %d %d %d %d %d %d %d %d %d %d",unePers.index,unePers.id,unePers.nom,unePers.Titre,unePers.Auteur, unePers.date.annee,unePers.date.mois,unePers.date.jour,unePers.date.heure,unePers.date.minute, unePers.retour.annee,unePers.retour.mois,unePers.retour.jour,unePers.retour.heure,unePers.retour.minute); } } } /* *@function modifier permet de modifier une information dans la liste chainée *et modifie le contenu du fichier emprunt.txt *@param pointeur * *@return void */ void modifierss(pointeurs * P){ pointeurs cestLui, avant, tempo ; int aModifier; char reponse ; Emprunt nouvPers ; FILE *donnees = NULL; donnees = fopen("Emprunt.txt","r+"); do{ viderBuffer(); printf("Entrez l'identifiant de l'emprunt à modifier ses informations "); scanf("%d", &aModifier); findss(aModifier, *P, &avant, &cestLui ); reponse = 'N'; if (cestLui != NULL){ printf("On l'a trouvé : \n"); afficherss(cestLui->emp); printf("\n\n"); viderBuffer(); printf("Désirez-vous modifier les informations de cet emprunt ?(O/N) "); fflush(stdin); reponse = toupper(getchar()); if (reponse == 'O'){ demanderss( &nouvPers); if ( nouvPers.index == (cestLui->emp).index ){ cestLui->emp = nouvPers; }else{ eliminerss( P, avant, cestLui); findss( nouvPers.index, *P, &avant, &cestLui); insererss(P, nouvPers, avant); fprintf(donnees,"%d %d %s %s %s %d %d %d %d %d %d %d %d %d %d",nouvPers.index,nouvPers.id,nouvPers.nom,nouvPers.Titre, nouvPers.Auteur,nouvPers.date.annee,nouvPers.date.mois,nouvPers.date.jour,nouvPers.date.heure,nouvPers.date.minute, nouvPers.retour.annee,nouvPers.retour.mois,nouvPers.retour.jour,nouvPers.retour.heure,nouvPers.retour.minute); } } }else{ printf("Désolé! on ne trouve pas cet emprunt\n"); viderBuffer(); printf("avez-vous autre emprunt à modifier (O/N) ? "); fflush(stdin); } }while (toupper(getchar()) != 'N'); } /* *@function traiter permet de traiter le choix de l'utilisateur *@param char,pointeur * *@return void */ void traiterss( char choix, pointeurs *L){ switch(choix){ case 'V' : visualiserss( *L ); break; case 'C' : chercherss( *L ); break ; case 'S' : supprimerss(L); break; case 'A' : ajouterss(L); break; case 'M' : modifierss(L); break; case 'I' : inverserss(L); /* inverser la liste */ visualiserss(*L); inverserss(L); /* remettre dans l'ordre FIFO */ break; case 'R' : menu(); break; case 'N' : system("clear"); break; } }
C
#include <stdio.h> #include <math.h> #include <stdlib.h> #include <string.h> char * sttr; char * sfrac_simplify(char * n); double sfrac_todouble(char * x); void my_reverse(char str[], int len); char * sfrac_fromdouble(double x); char * sfrac_add(char * n1, char * n2); char * sfrac_sub(char * n1, char * n2); char * sfrac_negate(char * n); char * sfrac_mult(char * n1, char * n2); char * sfrac_div(char * n1, char * n2); double sfrac_todouble(char * str){ int value, sign; int i = 0; value = 0; if(str[0] == '-') sign = 1; else sign = 0; for(i = sign; str[i] != '/' && str[i] != '\0'; i++){ value *= 10; value += str[i] - '0'; } if(sign == 1) value *= -1; value = round(value); return value; } char * sfrac_simplify(char * n){ int i,k,j,y = 0; int c = 1; double sayi1,sayi2 = 0; char * s_sayi1[30]; char * s_sayi2; char s_sayi3; for(i = 0;(n[i] != '/') && (n[i] != '\0') ;++i){ } y = i; j = i+1; sayi1 = sfrac_todouble(&n[0]); sayi2 =sfrac_todouble(&n[j]); while(c){ if (((sayi1/2)-(int)sayi1/2)==0 &&((sayi2/2)-(int)sayi2/2)==0){ sayi1 = (sayi1/2); sayi2 = (sayi2/2); } else if (((sayi1/3)-(int)sayi1/3)==0 &&((sayi2/3)-(int)sayi2/3)==0){ sayi1 = (sayi1/3); sayi2 = (sayi2/3); } else if (((sayi1/4)-(int)sayi1/4)==0 &&((sayi2/4)-(int)sayi2/4)==0){ sayi1 = (sayi1/4); sayi2 = (sayi2/4); } else if (((sayi1/5)-(int)sayi1/5)==0 &&((sayi2/5)-(int)sayi2/5)==0){ sayi1 = (sayi1/5); sayi2 = (sayi2/5); } else if (((sayi1/6)-(int)sayi1/6)==0 &&((sayi2/6)-(int)sayi2/6)==0){ sayi1 = (sayi1/6); sayi2 = (sayi2/6); } else if (((sayi1/7)-(int)sayi1/7)==0 &&((sayi2/7)-(int)sayi2/7)==0){ sayi1 = (sayi1/7); sayi2 = (sayi2/7); } else if (((sayi1/8)-(int)sayi1/8)==0 &&((sayi2/8)-(int)sayi2/8)==0){ sayi1 = (sayi1/8); sayi2 = (sayi2/8); } else if (((sayi1/9)-(int)sayi1/9)==0 &&((sayi2/9)-(int)sayi2/9)==0){ sayi1 = (sayi1/9); sayi2 = (sayi2/9); } else{ c = 0; } } // *s_sayi2=("%s",((char)(sayi1+48))); //printf("%s\n\n",s_sayi2); //return s_sayi2; } char * sfrac_add(char * n1, char * n2){ int i,k,j,j2,yer1,yer2= 0; int c = 1; double sayi1a,sayi1b,sayi2a,sayi2b,sayi3a,sayi3b = 0; int temp; for(i = 0;(n1[i] != '/') && (n1[i] != '\0') ;++i){ } yer1 = i; j = i+1; for(i = 0;(n2[i] != '/') && (n2[i] != '\0') ;++i){ } yer2 = i; j2 = i+1; sayi1a = sfrac_todouble(&n1[0]); sayi1b =sfrac_todouble(&n1[j]); sayi2a = sfrac_todouble(&n2[0]); sayi2b =sfrac_todouble(&n2[j2]); if(sayi1b==sayi2b){ } else{ temp = sayi1b; sayi1a = sayi1a*sayi2b; sayi1b = sayi1b*sayi2b; sayi2a = sayi2a*temp; sayi2b = sayi2b*temp; } sayi3a = sayi1a+sayi2a; sayi3b = sayi1b; printf("%1.2f/",sayi3a); printf("%1.2f\n",sayi3b); } char * sfrac_sub(char * n1, char * n2){ int i,k,j,j2,yer1,yer2= 0; int c = 1; double sayi1a,sayi1b,sayi2a,sayi2b,sayi3a,sayi3b = 0; int temp; for(i = 0;(n1[i] != '/') && (n1[i] != '\0') ;++i){ } yer1 = i; j = i+1; for(i = 0;(n2[i] != '/') && (n2[i] != '\0') ;++i){ } yer2 = i; j2 = i+1; sayi1a = sfrac_todouble(&n1[0]); sayi1b =sfrac_todouble(&n1[j]); sayi2a = sfrac_todouble(&n2[0]); sayi2b =sfrac_todouble(&n2[j2]); if(sayi1b==sayi2b){ } else{ temp = sayi1b; sayi1a = sayi1a*sayi2b; sayi1b = sayi1b*sayi2b; sayi2a = sayi2a*temp; sayi2b = sayi2b*temp; } sayi3a = sayi1a-sayi2a; sayi3b = sayi1b; printf("%1.2f/",sayi3a); printf("%1.2f\n",sayi3b); } char * sfrac_negate(char * n){ int i,k,j,y = 0; int c = 1; double sayi1,sayi2 = 0; char s_sayi1[30]; char s_sayi2[30]; for(i = 0;(n[i] != '/') && (n[i] != '\0') ;++i){ } y = i; j = i+1; sayi1 = sfrac_todouble(&n[0]); sayi2 =sfrac_todouble(&n[j]); sayi1 = -sayi1; printf("%1.2f/",sayi1); printf("%1.2f\n",sayi2); } char * sfrac_mult(char * n1, char * n2){ int i,k,j,j2,yer1,yer2= 0; int c = 1; double sayi1a,sayi1b,sayi2a,sayi2b,sayi3a,sayi3b = 0; int temp; for(i = 0;(n1[i] != '/') && (n1[i] != '\0') ;++i){ } yer1 = i; j = i+1; for(i = 0;(n2[i] != '/') && (n2[i] != '\0') ;++i){ } yer2 = i; j2 = i+1; sayi1a = sfrac_todouble(&n1[0]); sayi1b =sfrac_todouble(&n1[j]); sayi2a = sfrac_todouble(&n2[0]); sayi2b =sfrac_todouble(&n2[j2]); sayi3a = sayi1a*sayi2a; sayi3b = sayi1b*sayi2b; printf("%1.2f/",sayi3a); printf("%1.2f\n",sayi3b); } char * sfrac_div(char * n1, char * n2){ int i,k,j,j2,yer1,yer2= 0; int c = 1; double sayi1a,sayi1b,sayi2a,sayi2b,sayi3a,sayi3b = 0; int temp; for(i = 0;(n1[i] != '/') && (n1[i] != '\0') ;++i){ } yer1 = i; j = i+1; for(i = 0;(n2[i] != '/') && (n2[i] != '\0') ;++i){ } yer2 = i; j2 = i+1; sayi1a = sfrac_todouble(&n1[0]); sayi1b =sfrac_todouble(&n1[j]); sayi2a = sfrac_todouble(&n2[0]); sayi2b =sfrac_todouble(&n2[j2]); sayi3a = sayi1a*sayi2b; sayi3b = sayi1b*sayi2a; printf("%1.2f/",sayi3a); printf("%1.2f\n",sayi3b); } void my_reverse(char str[], int len) { int start, end; char temp; for(start=0, end=len-1; start < end; start++, end--) { temp = *(str+start); *(str+start) = *(str+end); *(str+end) = temp; } } char * sfrac_fromdouble(double x){ int i = 0; int isNegative = 0; if (x == 0) { sttr[i] = '0'; sttr[i + 1] = '\0'; } if (x < 0 && 10 == 10) { isNegative = 1; x = -x; } while (x != 0) { int rem = (int)x % 10; sttr[i++] = (rem > 9)? (rem-10) + 'A' : rem + '0'; x = x/10; } if (isNegative){ sttr[i++] = '-'; } sttr[i] = '\0'; my_reverse(sttr, i); }
C
#include<stdio.h> #include<conio.h> #include<stdlib.h> #include<windows.h> char square[10] = {'0','1','2','3','4','5','6','7','8','9'}; int checkWin(); void drawBoard(); void main() { int player = 1,i,choice; char mark; // X,O do{ drawBoard(); player = (player % 2)? 1 : 2 ; printf("Player %d , enter the choice : ",player); scanf("%d",&choice); mark = (player == 1)? 'X' : 'O' ; if(choice == 1 && square[1] == '1') square[1] = mark; else if(choice == 2 && square[2] =='2') square[2] = mark; else if(choice == 3 && square[3] == '3') square[3] = mark; else if(choice == 4 && square[4] == '4') square[4] = mark; else if(choice == 5 && square[5] == '5') square[5] = mark; else if(choice == 6 && square[6] == '6') square[6] = mark; else if(choice == 7 && square[7] == '7') square[7] = mark; else if(choice == 8 && square[8] == '8') square[8] = mark; else if(choice == 9 && square[9] == '9') square[9] = mark; else { printf("INVALID OPTION !"); player--; // decrement the player because if the player input invalid option he/she get another chance getch(); } i = checkWin(); player++; // increment the player because player 2 gets its turns after the first player }while(i == -1); void drawBoard(); // because if the do while() loop ends the board will disappear so to play new game we have to call the drawBoard() again if(i==1) { printf("==> Player %d won",--player); // to declare the winner } else { printf("==> Game Draw"); // if the game will be drawn } getch(); return 0; } int checkWin(){ // if these conditions are true then we have the winner if(square[1] == square[2] && square[2] == square[3]) return 1; else if(square[4] == square[5] && square[5] == square[6]) return 1; else if(square[7] == square[8] && square[8] == square[9]) return 1; else if(square[1] == square[4] && square[4] == square[7]) return 1; else if(square[2] == square[5] && square[5] == square[8]) return 1; else if(square[3] == square[6] && square[6] == square[9]) return 1; else if(square[1] == square[5] && square[5] == square[9]) return 1; else if(square[3] == square[5] && square[5] == square[7]) return 1; // draw condition else if(square[1] != '1' && square[2] != '2' && square[3] != '3' && square[4] != '4' && square[5] != '5' && square[6] != '6' && square[7]!= '7' && square[8] != '8' && square[9] != '9') return 0; else return -1; // the game is still in the promise } void drawBoard() { system("cls"); printf("\n\n\t\t\t\t\t TIC TAC TOE \n\n"); printf("\n\n\t\t\t\t Player1 (X) - Player2 (O)\n\n\n"); printf(" | | \n"); printf(" %c %c %c \n",square[1],square[2],square[3]); printf("____|____|____\n"); printf(" | | \n"); printf(" %c %c %c \n",square[4],square[5],square[6]); printf("____|____|____\n"); printf(" | | \n"); printf(" %c %c %c \n",square[7],square[8],square[9]); printf(" | | \n"); }
C
#define _CRT_SECURE_NO_WARNINGS 1 #include <stdio.h> #include <string.h> //int main() //{ // struct S // { // int num; // char name[20]; // char sex; // int age; // float score; // char addr[30]; // }; // struct S s1; // printf("%d\n", sizeof(s1)); // return 0; //} //int main() //{ // struct S // { // int num; // char name[20]; // int score; // }; // struct S s1 = { 1001,"",85 }; // struct S s2 = { 1002,"",95 }; // if (s1.score > s2.score) // printf("%d %s %d\n", s1.num, s1.name, s1.score); // else // printf("%d %s %d\n", s2.num, s2.name, s2.score); // return 0; //} //struct S //{ // char name[20]; // int age; //}; //int main() //{ // struct S s1 = { "",20 }; // printf("%s% d\n", s1.name, s1.age); // struct S s2 = s1; // printf("%s% d\n", s2.name, s2.age); // return 0; //} //struct S //{ // char name[20]; // int age; //}; //int main() //{ // struct S s1 = { "", 20 }; // printf("%s %d\n", s1.name, s1.age); // strcpy(s1.name, ""); // //scanf("%s", s1.name); // printf("%s %d\n", s1.name, s1.age); // return 0; //} //int main() //{ // int a = 5, b = 4, c = 3; // if (a > b) // { // a = b + c, // b = 2 * c; // } // else // { // a = b - c, // b = 3 * c; // // } // a = b + c; // printf("%d %d", a, b); // return 0; //} //struct S //{ // char name[20]; // char sex; // int age; //}; //int main() //{ // struct S s; // struct S* p; // p = &s; // /*strcpy(p -> name, ""); // p -> sex = 'M'; // p -> age = 18; // printf("%s %c %d\n", p->name, p->sex, p->age);*/ // // //(*p).name = "";//arr // // strcpy((*p).name, ""); // (*p).sex = 'M'; // (*p).age = 18; // printf("%s %c %d\n", (*p).name, (*p).sex, (*p).age); // return 0; //} struct S { char name[20]; char sex; int age; }; int main() { struct S arr[3] = { {"",'M',18},{"",'F',19},{"",'M',20} }; struct S* p = arr; int i; for (p = arr;p < arr + 3;p++) { printf("name: %s\nsex: %c\nage: %d\n\n", p->name, p->sex, p->age); } for (i = 0;i < 3;i++) { printf("name: %s\nsex: %c\nage: %d\n\n", (*(p + i)).name, (*(p + i)).sex, (*(p + i)).age); } return 0; }
C
//Program to find the shortest sequence of paths taken by a knight from source to destination vertex #include<stdio.h> #include<ctype.h> #include<string.h> #include<stdlib.h> #define N 8 typedef struct Node { int x; int y; int distance; }Node; //valid movement of the knight int row[] = {-2, -1, 1, 2, -2, -1, 1, 2}; int col[] = {-1, -2, -2, -1, 1, 2, 2, 1}; int visit[N+1][N+1] = {{0}}; Node q[1000]; int front = -1; int rear = -1; int top = -1; int mapCoordsToIndex(int x, int y) //hash code conversion { return y*8 + x; } int isValid(int x, int y) { //checking if the coordinate given doesnt go out of the chess board if(x >= 1 && x <= N && y >= 1 && y <= N) return 1; return 0; } void enqueue(int x, int y, int distance) { if(front==-1) front=0; rear++; q[rear].x=x; q[rear].y=y; q[rear].distance=distance; } void dequeue() { if(front == rear) front = rear = -1; else front++; } int qisempty() { if(rear==-1 && front ==-1) return 1; return 0; } void push(int index, int *stack) { top++; stack[top] = index; } void pop() { top--; } int getX(int index) //extracts and returns the X coordinate { return (index % 8) + 1; } int getY(int index) //extracts and returns the Y coordinate { return (index / 8) + 1; } void bfs(int sx, int sy, int dx, int dy) { Node t; int x, y; enqueue(sx, sy, 0); //adding starting position of knight to the queue with 0 distance travelled //visited starting position visit[sx][sy] = 1; int map[64] = {0}; //using array of size 64 to simulate map, using the encoding i*8+j to store the respective pairs //looping until queue is empty while(!qisempty()) { t = q[front]; dequeue(); if(t.x == dx && t.y == dy) { // to do when the index is found printf("Total moves needed to be taken : %d \n", t.distance); int stack[1000]; push(mapCoordsToIndex(t.x-1, t.y-1),stack); if(t.distance != 0) //when source and destination are not the same { for(int i = mapCoordsToIndex(t.x-1, t.y-1); ; i = mapCoordsToIndex(t.x-1, t.y-1)) //moving to the parent { if(!(getX(map[i]) == sx && getY(map[i]) == sy)) //if not equal to source , then continue { t.x = getX(map[i]); t.y = getY(map[i]); push(mapCoordsToIndex(t.x-1, t.y-1),stack); } else break; } } printf("path : (%d,%d) ",sx,sy); for (; top != -1; pop()) printf("-> (%d,%d) ",getX(stack[top]) ,getY(stack[top])); printf("\n\n"); return; } for(int i=0;i<8;i++) //knights movements { x = t.x + row[i]; y = t.y + col[i]; if(isValid(x,y) && !visit[x][y]) { visit[x][y] = 1; enqueue(x, y, t.distance + 1); map[mapCoordsToIndex(x-1, y-1)] = mapCoordsToIndex(t.x-1, t.y-1); //maps each next coordinate with next coordinate } } } } int main() { //Destination coordinates int dx,dy; //Source coordinates int sx,sy; printf("Enter the Source Coordinates (x,y), where x and y are numbers between 1 and 8: \n"); scanf("%d%d",&sx,&sy); printf("Enter the Destiation Coordinates (x,y), where x and y are numbers between 1 and 8: \n"); scanf("%d%d",&dx,&dy); if((isValid(sx,sy) && isValid(dx,dy))) bfs(sx,sy,dx,dy); else printf("Wrong input!\n"); return 0; }
C
/* ** EPITECH PROJECT, 2018 ** myftp ** File description: ** dir_command.c */ #include "server.h" static int change_dir(char **tab) { char *path = realpath(tab[1], NULL); if ((tab[1] && tab[2] != NULL) || (path == NULL) || (chdir(tab[1]) == -1)) { return (1); } return (0); } void cwd(char **tab, t_client *clt) { if (clt->log <= 0) { dprintf(clt->fd, "530 Please login with USER and PASS.\n"); } else if (tab[1] == NULL || change_dir(tab) == 1) { dprintf(clt->fd, "550 Failed to change directory.\n"); } else { dprintf(clt->fd, "250 Directory successfully changed.\n"); } } static int change_dir_cdup(char *path, char **tab) { (void)tab; if (chdir(path) == -1) { return (1); } return (0); } void cdup(char **tab, t_client *clt) { if (clt->log <= 0) { dprintf(clt->fd, "530 Please login with USER and PASS.\n"); } else if (change_dir_cdup("../", tab) == 1) { dprintf(clt->fd, "550 Failed to change directory.\n"); } else { dprintf(clt->fd, "250 Directory successfully changed.\n"); } }
C
/* jisSem1.c : JIS C 5.1.2.3 Program execution pp.8-9 */ #include <stdio.h> char line[4] = {'1', '2', '3', '\0'}; char buff[100]; int column; char getchar1(); int main() { char c1='a', c2=1; float f1, f2=3.14f; double d=2.0; short a1, a2, x11, x12, x13, x21, x22, x23, x24, b1, b2; int sum; char *p; int i; c1 = c1 + c2; printf("c1=\'a\'+1 : %c\n", c1); f1 = f2 * d; printf("f1 = f2 * d : %f %f \n", f1, f2); a1 = -32754; b1 = -15; x11 = a1 + 32760 + b1 + 5; x12 = (((a1 + 32760) + b1) + 5); x13 = ((a1 + b1) + 32765); a2 = -17; b2 = 12; x21 = a2 + 32760 + b2 + 5; x22 = ((a2 + 32765) + b2); x23 = (a2 + (b2 + 32765)); printf("x11 = a1 + 32760 + b1 + 5 : %d\n", x11); printf("x12 = (((a1 + 32760) + b1) + 5) : %d\n", x12); printf("x13 = ((a1 + b1) + 32765) : %d\n", x13); printf("x21 = a2 + 32760 + b2 + 5 : %d\n", x21); printf("x22 = ((a2 + 32765) + b2) : %d\n", x22); printf("x23 = (a2 + (b2 + 32765)) : %d\n", x23); p = &buff[0]; column = 0; sum = 0; for (i = 0; i < 3; i++) { sum = sum * 10 - '0' + (*p++ = getchar1()); } printf("sum %d\n", sum); p = &buff[0]; column = 0; sum = 0; for (i = 0; i < 3; i++) { sum = (((sum * 10) - '0') + ((*(p++)) = (getchar1()))); } printf("sum %d\n", sum); return 0; } char getchar1() { char c = line[column]; column++; return c; }
C
#include <stdio.h> int main(void) { int arr[2]={1,2}; int *ptr = arr; for(int i=0 ; i<2; i++){ ptr[i]++; } printf("%d, %d\n",*(arr+0),*(arr+1)); }
C
#include<stdio.h> #define ANSI_COLOR_RED "\x1b[31m" #define ANSI_COLOR_GREEN "\x1b[32m" #define ANSI_COLOR_RESET "\x1b[0m" #define ANSI_COLOR_CYAN "\x1b[36m" int arr[4][11]; void display() { printf("\n\n"); printf(ANSI_COLOR_CYAN" <버스 좌석표> \n"ANSI_COLOR_RESET); printf(" "); for(int i=0;i<58;i++) printf("-"); printf("\n"); printf("|"); for(int i=0;i<58;i++) printf(" "); printf("|\n"); printf("|"); for(int i=0;i<11;i++) { if(arr[0][i]==0) { printf(ANSI_COLOR_GREEN "[A%d] "ANSI_COLOR_RESET,i+1); } else { printf(ANSI_COLOR_RED "[A%d] "ANSI_COLOR_RESET,i+1); } } printf(" |\n"); printf("|"); for(int i=0;i<11;i++) { if(arr[1][i]==0) { printf(ANSI_COLOR_GREEN"[B%d] "ANSI_COLOR_RESET,i+1); } else { printf(ANSI_COLOR_RED"[B%d] "ANSI_COLOR_RESET,i+1); } } printf(" |\n"); printf("|"); for(int i=0;i<58;i++) printf(" "); printf("|\n"); printf("|"); for(int i=0;i<58;i++) printf(" "); printf("|\n"); printf("|"); for(int i=0;i<11;i++) { if(arr[2][i]==0) { printf(ANSI_COLOR_GREEN"[C%d] "ANSI_COLOR_RESET,i+1); } else { printf(ANSI_COLOR_RED"[C%d] "ANSI_COLOR_RESET,i+1); } } printf(" |"); printf("\n"); printf("|"); for(int i=0;i<11;i++) { if(arr[3][i]==0) { printf(ANSI_COLOR_GREEN"[D%d] "ANSI_COLOR_RESET,i+1); } else printf(ANSI_COLOR_RED"[D%d] "ANSI_COLOR_RESET,i+1); } printf(" |"); printf("\n"); printf("|"); for(int i=0;i<58;i++) printf(" "); printf("|\n"); for(int i=0;i<58;i++) printf("-"); printf("\n"); } int main() { arr[2][1]=1; arr[3][6]=1; display(); return 0; }
C
/// A sample C extension. // Demonstrates using ldoc's C/C++ support. Can either use /// or /*** */ etc. // @module mylib #include <string.h> #include <math.h> // includes for Lua #include <lua.h> #include <lauxlib.h> #include <lualib.h> /*** Create a table with given array and hash slots. @function createtable @param narr initial array slots, default 0 @param nrec initial hash slots, default 0 */ static int l_createtable (lua_State *L) { int narr = luaL_optint(L,1,0); int nrec = luaL_optint(L,2,0); lua_createtable(L,narr,nrec); return 1; } /*** Solve a quadratic equation. @function solve @tparam num a coefficient of x^2 @tparam num b coefficient of x @tparam num c constant @treturn num first root @treturn num second root */ static int l_solve (lua_State *L) { double a = lua_tonumber(L,1); // coeff of x*x double b = lua_tonumber(L,2); // coef of x double c = lua_tonumber(L,3); // constant double abc = b*b - 4*a*c; if (abc < 0.0) { lua_pushnil(L); lua_pushstring(L,"imaginary roots!"); return 2; } else { abc = sqrt(abc); a = 2*a; lua_pushnumber(L,(-b + abc)/a); lua_pushnumber(L,(+b - abc)/a); return 2; } } static const luaL_reg mylib[] = { {"createtable",l_createtable}, {"solve",l_solve}, {NULL,NULL} }; int luaopen_mylib(lua_State *L) { luaL_register (L, "mylib", mylib); return 1; }
C
/* zapbig.c 8-22-00 LTH Write the hex bytes [B0 47 05 80 00 01 00] to an EEPROM at address 1. This is handy for over-writing an EEPROM that was previously loaded with 'B2' code for boot-load testing. By writing the seven bytes above we create an EEPROM that acts like the 24LC00 supplied on the stock development board. To use it: 1. Rocker Switch 7 [EEPROM A0=1] must be in the down (OFF) position PERMANENTLY. 2. Flip Rocker Switch 8 [A1] to the down (OFF) position. This sets the EEPROM address to 3. 3. Press the RESET button. The AN2131 finds 'missing' EEPROM (nothing at address 0 or 1), and enumerates as generic, using internal VID/PID/DID. 4. Flip Rocker Switch 8 back to the up (ON) position. The EEPROM is now at address 1. 5. Start the control panel. It binds to the board because of internal VID/PID/DID. The green MONITOR light should come on. You're in the debug environment. 6. At any later time re-program the EEPROM by selecting the 'EEPROM' button and choosing an 'iic' file. 7. When you're finished testing the EEPROM download of code, go back to step 1. */ xdata char I2CS _at_ 0x7FA5; // I2C port Control/Status xdata char I2DAT _at_ 0x7fA6; // I2C data #define bSTOPBIT 0x40 // I2CS.6 is i2c STOP bit void display_hex (char val); // display 'val' as hex in 7-seg readout main() { display_hex(0xFE); // Light up the top segment to show we're running // while (I2CS & bSTOPBIT); // wait for STOP bit LOW--last operation complete I2CS = 0x80; // set the START bit I2DAT = 0xA2; // EEPROM address 1, b0=0 means 'write' while ((I2CS&0x01)!=0x01); // wait for DONE=1 (i2c transmit complete) I2DAT = 0; // send Addr-H while ((I2CS&0x01)!=0x01); // wait for DONE=1 I2DAT = 0; // send Addr-L while ((I2CS&0x01)!=0x01); // wait for DONE=1 I2DAT = 0xB0; // byte 1 while ((I2CS&0x01)!=0x01); // wait for DONE=1 I2DAT = 0x47; // byte 2 while ((I2CS&0x01)!=0x01); // wait for DONE=1 I2DAT = 0x05; // byte 3 while ((I2CS&0x01)!=0x01); // wait for DONE=1 I2DAT = 0x80; // byte 4 while ((I2CS&0x01)!=0x01); // wait for DONE=1 I2DAT = 0x00; // byte 5 while ((I2CS&0x01)!=0x01); // wait for DONE=1 I2DAT = 0x01; // byte 6 while ((I2CS&0x01)!=0x01); // wait for DONE=1 I2DAT = 0x00; // byte 7 while ((I2CS&0x01)!=0x01); // wait for DONE=1 I2CS = 0x40; // set the STOP bit display_hex(0xF7); // Light up bottom segment } void display_hex (char val) { while (I2CS & bSTOPBIT); // wait for STOP bit LOW--last operation complete I2CS = 0x80; // set the START bit I2DAT = 0x42; // IO expander address=42, LSB=0 for write while ((I2CS&0x01)!=0x01); // wait for DONE=1 (i2c transmit complete) I2DAT = val; // send the data byte while ((I2CS&0x01)!=0x01); // wait for DONE=1 I2CS = 0x40; // set the STOP bit }
C
#include <stdio.h> #include <stdlib.h> #include <time.h> #include <malloc.h> typedef struct LNode { int data; struct LNode *next; }LNode; int initLink(LNode *L) { LNode *head=L->next, *p; while (head) { p = head; head = head->next; free(p); } L->next = NULL; printf("initiate success.\n"); return 1; } int insertElem(LNode *L, int ps, int e) { if(L->next != NULL) { int i, count = 0; LNode *pre, *p, *s; s = (LNode *)malloc(sizeof(LNode)); s->data = e; s->next = NULL; for(pre = L, p = L->next; p!=NULL; pre = p, p = p->next) if(count++ == ps) { s->next = p; pre->next = s; // free(s); // 此处释放内存导致,插入值被释放,得不到被插入值。 return 1; } } return 0; } int deleteElem(LNode *L, int ps,int *e) { if (L->next != NULL) { int i, count = 0; LNode *p, *pre; for(pre = L, p = L->next; p!=NULL;pre = p, p= p->next) { if (count++ == ps ) { *e = p->data; pre->next = p->next; return 1; } } if (count -1<ps) { printf("length of the link is %d shorter than your expect\n", count); return 0; } } return 0; } int createLink(LNode *L) { int i, mathod, length; LNode *head = L; LNode *p; printf("input mathod to create link(0:for random/1:manual input):\n"); scanf("%d", &mathod); printf("input lenght of the link:\n"); scanf("%d", &length); if (mathod == 0) { time_t t; if (head) { srand((unsigned)time(&t)); for ( i = 0; i < length; i++) { p = (LNode *)malloc(sizeof(LNode)); p->data = rand()%100; p ->next = head->next; head->next = p; } // L = head; return 1; } } if (mathod == 1) { if (head) { // head->next = NULL; LNode *q = L; int data; for(i = 0; i<length; i++) { p = (LNode *)malloc(sizeof(LNode)); p->next =NULL; printf("Please input the %d element:\n ", i); scanf("%d", &data); p->data = data; q ->next =p; q = q->next; } // L = head; return 1; } } } int mergeLink(LNode *La, LNode *Lb, LNode *Lc) { int i; LNode *p, *q, *r; // free(Lc); // Lc = La; // r = Lc; p = La->next; r = Lc; r->next = NULL; q = Lb->next; while ((p!=NULL)&&(q!=NULL)) { if(p->data < q->data) { r->next = p; p = p->next; // r = r->next; // r->next = NULL; } else { r->next = q; q = q->next; // r = r->next; // r->next = NULL; } r= r->next; // printf("%d\t", r->data); r->next = NULL; } if (p !=NULL) { r->next = p; // printf("%d", r->next->data); } else { r->next = q; // printf("%d", r->next->data); } return 1; } int ascending(LNode *L) { if(L->next) { LNode *head, *p, *s, *pre; head = L-> next; L->next = NULL; for (; head != NULL; ) { s = head; head = head->next; s->next = NULL; // printf("%d\t", s->data); for ( pre = L, p = L->next; p !=NULL;) { if (s->data < p->data) //结点插入位置总是在pre后面,符合插入条件则插入,否则执行选择语句外面的语句 { pre->next = s; pre = pre->next; pre->next = p; break; } pre = p; //如果没有跳出,则总是执行指针的向后移动; p = p->next; } if (p == NULL) { pre->next = s; p = s; } } return 1; } return 0; } int main() { int ln, de, *elem=&de; LNode *L1,*L2, *L3=NULL, *p; int result; // result = initLink(L); // printf("%d",result); // printf("\n") ; L1 = (LNode *)malloc(sizeof(LNode)); L1->next = NULL; /* if (!L) { printf("apply memory failed"); return 0; } */ L2 = (LNode *)malloc(sizeof(LNode)); L2->next = NULL; createLink(L1); createLink(L2); L3 = (LNode *)malloc(sizeof(LNode)); L3->next = NULL; p = L1->next; while (p!=NULL) { printf("%d\t", p->data); p = p->next; } printf("\n"); // initLink(L); // ascending(L); p = L2->next; while (p!=NULL) { printf("%d\t", p->data); p = p->next; } printf("\n"); /* insertElem(L, 3, 10); p = L->next; while (p!=NULL) { printf("%d\t", p->data); p = p->next; } printf("\n"); deleteElem(L, 6, elem); */ ascending(L1); ascending(L2); p = L1->next; while (p!=NULL) { printf("%d\t", p->data); p = p->next; } printf("\n"); p = L2->next; while (p!=NULL) { printf("%d\t", p->data); p = p->next; } printf("\n"); mergeLink(L1, L2, L3); p = L3->next; while (p!=NULL) { printf("%d\t", p->data); p = p->next; } printf("\n"); return 1; }
C
/* CUDA speed test without the memory overhead gcc-mp-4.8 -O3 cudadgemmtest.c common.c -o cudadgemmtest -I../../../../netlib/CBLAS -I/usr/local/cuda/include/ -L/usr/local/cuda/lib -lcublas export DYLD_LIBRARY_PATH=/usr/local/cuda/lib ./cudadgemmtest > ../../../results/mac_os_x-x86_64-dgemm-cuda_nooh.csv */ #include <stdlib.h> #include <stdio.h> #include <math.h> #include <cblas.h> #include "common.h" #include <cublas.h> // does AB == C ? If not, complain on stderr void test(int m, double* a, double *b, double *c) { int i, j, k, exact = 0, wrong = 0; double diff; double* d = calloc(m * m, sizeof(double)); for (i = 0 ; i < m ; i++) { for (j = 0 ; j < m ; j++) { for (k = 0 ; k < m ; k++) { d[i + j * m] += a[i + k * m] * b[j * m + k]; } } } for (i = 0 ; i < m ; i++) { for (j = 0 ; j < m ; j++) { diff = c[i * m + j] - d[i * m + j]; if (diff != 0.0) { exact++; } if (abs(diff) > 0.000001) { wrong++; } } } free(d); if (wrong > 0) { fprintf(stderr, "not exact = %d, wrong = %d\n", exact, wrong); } } void checkStatus(char* message, cublasStatus status) { if (status != CUBLAS_STATUS_SUCCESS) { fprintf (stderr, "!!!! %s fail %d\n", message, status); exit(EXIT_FAILURE); } } long benchmark(int size) { int m = sqrt(size); long requestStart, requestEnd; double* a = random_array(m * m); double* b = random_array(m * m); double* c = calloc(m * m, sizeof(double)); double *cuA, *cuB, *cuC; cublasStatus status; status = cublasAlloc(m * m, sizeof(double),(void**)&cuA); checkStatus("A", status); status = cublasAlloc(m * m, sizeof(double),(void**)&cuB); checkStatus("B", status); status = cublasAlloc(m * m, sizeof(double),(void**)&cuC); checkStatus("C", status); status = cublasSetMatrix(m, m, sizeof(double), a, m, cuA, m); checkStatus("setA", status); status = cublasSetMatrix(m, m, sizeof(double), b, m, cuB, m); checkStatus("setB", status); requestStart = currentTimeNanos(); cublasDgemm('N', 'N', m, m, m, 1, cuA, m, cuB, m, 0, cuC, m); requestEnd = currentTimeNanos(); status = cublasGetMatrix(m, m, sizeof(double), cuC, m, c, m); checkStatus("setB", status); status = cublasFree(cuA); checkStatus("freeA", status); status = cublasFree(cuB); checkStatus("freeB", status); status = cublasFree(cuC); checkStatus("freeC", status); #ifdef __TEST__ test(m, a, b, c); #endif free(a); free(b); free(c); return (requestEnd - requestStart); } main() { cublasStatus status; srand(time(NULL)); status = cublasInit(); checkStatus("init", status); double factor = 6.0 / 100.0; int i, j; for (i = 0 ; i < 10 ; i++) { for (j = 1 ; j <= 100 ; j++) { int size = (int) pow(10.0, factor * j); if (size < 10) continue; long took = benchmark(size); printf("\"%d\",\"%lu\"\n", size, took); fflush(stdout); } } }
C
#include <string.h> #include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <ctype.h> /* This file contains special methods to dealing with cummon string operations when reading a mathematical expression and parsing it to a expression stack. */ void resize_assing(char *str, char* new_str){ str = (char*) realloc(str, sizeof(char)*(strlen(new_str)+2)); strcpy(str, new_str); } void append(char* str, char c){ if (strlen(str) >= 1){ int length = strlen(str); str = (char*) realloc(str, sizeof(char*)*(length+2)); str[length] = c; str[length+1] = '\0'; } else { str[0] = c; str[1] = '\0'; } } char* get_substring(char* exp, int lookahead, int length){ char* str = (char*) malloc(sizeof(char)*(length+1)); if (length == 0){ strcpy(str, ""); return str; } for (int i = lookahead;i < (lookahead+length);i++){ str[i] = exp[i]; } str[length+1] = '\0'; return str; } bool is_substring_function(char* exp, int lookahead){ int n = lookahead; while (!isdigit(exp[n]) && exp[n] != ' ') n++; while(exp[n] == ' ') n++; if (exp[n] == '(') return true; else return false; } void get_spaces(char* exp, int* lookahead){ while(exp[(*lookahead)] == ' ' || exp[(*lookahead)] == '\t'){ (*lookahead)++; } }
C
/* parse.c - parser ** ** Syntax: ** <expression> ::= <apply> ** | <expression> ";" <identifier> <atomic> ** <apply> ::= <atomic> ** | <apply> <atomic> ** <atomic> ::= "\" <identifier> <atomic> ** | "(" <expression> ")" ** | <identifier> ** | <literal> ** ** The backslash ('\') starts a lambda expression (similar to Haskell). ** The semicolon (';') is a recursive let operator, but with reversed notation ** (the definitions come last; like 'where' in Haskell). ** ** Example: f 10 20 ; f \x \y (g x y) ; g \x \y (f x y) ** ** This should apply function f on two numeric arguments (literals), ** in a context where f and g are defined as mutually recursive functions. ** Syntactically sound, semantically an infinite loop. */ #include <stdlib.h> #include <stdio.h> #include <string.h> #define AST_NODE_ID #ifndef AST_NAMES #define AST_NAMES #endif #include "ast.h" #include "token.h" #include "errmsg.h" #define STARTS_ATOMIC(token) \ ((token) > TOKEN_ERROR && (token) != TOKEN_CLOSE && (token) != TOKEN_WHERE) static NODE *parse_expression(TOKEN expected); static NODE *parse_atomic(TOKEN token) { NODE *ast = NULL; switch (token) { case TOKEN_LAMBDA: token = token_get(); if (token == TOKEN_IDENT) { const char *name = strdup(token_buffer); ast = create_lambda(parse_atomic(token_get()), name); } else { error_message(stderr, TOKEN_IDENT, token, TOKEN_LAMBDA); } break; case TOKEN_PRIM: ast = create_prim(strdup(token_buffer + 1)); break; case TOKEN_IDENT: ast = create_ident(strdup(token_buffer)); break; case TOKEN_CHAR: ast = create_int((long)token_char); break; case TOKEN_INT: ast = create_int(token_int); break; case TOKEN_DOUBLE: ast = create_double(token_double); break; case TOKEN_STRING: ast = create_string(token_buffer); break; case TOKEN_OPEN: ast = parse_expression(TOKEN_CLOSE); break; default: error_message(stderr, TOKEN_OPEN, token, TOKEN_EOF); break; } return ast; } static DEFINE *parse_defines(TOKEN token, TOKEN expected) { DEFINE *defines = NULL; while (token == TOKEN_WHERE) { token = token_get(); if (token == TOKEN_IDENT) { const char *name = strdup(token_buffer); defines = create_define(defines, parse_atomic(token_get()), name); } else { error_message(stderr, TOKEN_IDENT, token, TOKEN_WHERE); } token = token_get(); } if (token != expected) { error_message(stderr, expected, token, TOKEN_EOF); } return defines; } static NODE *parse_expression(TOKEN expected) { NODE *ast = NULL; int token = token_get(); if (!STARTS_ATOMIC(token)) { error_message(stderr, TOKEN_WHERE, token, TOKEN_EOF); } else { ast = parse_atomic(token); token = token_get(); while (STARTS_ATOMIC(token)) { ast = create_apply(ast, parse_atomic(token)); token = token_get(); } ast = create_rlet(ast, parse_defines(token, expected)); } return ast; } DEFINE *parse_module(void) { return parse_defines(token_get(), TOKEN_EOF); } NODE *parse_root(void) { return parse_expression(TOKEN_EOF); }
C
#include<stdio.h> main() { getvalues(); perimeter(); area(); } getvalues() { int x; printf("Enter radius of the circle:"); scanf("%d",&x); } perimeter() { float c,x; c=2*3.14*x; printf("\nPerimeter is %f",c); } area() { float a,x; a=3.14*(x*x); printf("\nArea is %f",a); }
C
#include <string.h> #include <stdio.h> #include <stdlib.h> #include "structure.h" int main(){ char val[10]; int n=0; memset(val, 0, 10); struct GBN_Receiver_Queue *q = create_queue(); while(1){ printf("Enter the value to store: "); scanf("%d", &n); printf("\n"); memcpy(val, &n, sizeof(int)); memcpy(val+sizeof(int), &n, sizeof(int)); printf("Value copied\n"); enQueue(q, val, 8); display(q); } }
C
#include<stdio.h> void main() { int x,y,t; printf("enter the number is"); scanf("%d%d",&x,&y); t=x; y=x; y=t; printf("the swapping number is%d%d",x,y); }
C
#include<stdio.h> void main() { char ch; printf("enter the alphabet:"); scanf("%c",&ch); switch(ch) { case'a': printf("vowels"); break; case'e': printf("vowels"); break; case'i': printf("vowels"); break; case'o': printf("vowels"); break; case'u': printf("vowels"); break; default: printf("consonant"); break; } }
C
////*Using a mutex to protect access to global variable*////// /* This program is a modified version of the previous program. It uses a mutex to protect access to the global variable glob. When we run this program with a similar command line to that used earlier, we see the glob is always reliably incremented*/ #include <pthread.h> static int glob = 0; static pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER; static void* threadFunc(void *arg) { int loops = *((int *)arg); int loc, j, s; for(j=0;j<loops;j++) { s = pthread_mutex_lock(&mtx); if(s!=0) { printf("pthread_mutex_lock 1 ERROR\n"); return; } loc = glob; loc++; glob = loc; s = pthread_mutex_unlock(&mtx); if(s!=0) { printf("pthread_mutex_lock 2 ERROR\n"); return; } } return NULL; } int main(int argc, char *argv[]) { pthread_t t1, t2; int loops, s; //loops = (argc > 1) ? (getInt(argv[1],GN_GT_0,"num-loops") : 10000000; loops = 700000; s = pthread_create(&t1, NULL, threadFunc, &loops); if(s != 0) { printf("pthread_create 1 ERROR\n"); return; } s = pthread_create(&t2, NULL, threadFunc, &loops); if(s != 0) { printf("pthread_create 2 ERROR\n"); return; } s=pthread_join(t1,NULL); if(s!=0) { printf("pthread_join 1 ERROR\n"); return; } s=pthread_join(t2,NULL); if(s!=0) { printf("pthread_join 2 ERROR\n"); return; } printf("glob = %d\n", glob); return 0; }
C
// // Vector3.c // GroupDevelopTutorial // // Created by 岡本 直樹 on 2016/12/21. // Copyright © 2016年 Naoki Okamoto. All rights reserved. // #include "Vector3.h" Vector3 Vector3_init(double x, double y, double z) { Vector3 vec; vec.vec[0] = x; vec.vec[1] = y; vec.vec[2] = z; vec.plusWith = __Vector3_plusWith; vec.multiWith = __Vector3_multiWith; vec.copy = __Vector3_copy; vec.rotate = __Vector3_rotate; return vec; } void __Vector3_plusWith(Vector3 *this_, Vector3 vec) { for(int i = 0; i < 3; i++) this_->vec[i] += vec.vec[i]; } void __Vector3_multiWith(Vector3 *this_, Vector3 vec) { for(int i = 0; i < 3; i++) this_->vec[i] *= vec.vec[i]; } void __Vector3_copy(Vector3 *this_, Vector3 vec) { for(int i = 0; i < 3; i++) this_->vec[i] = vec.vec[i]; } void __Vector3_rotate(Vector3 *this_, double r) { int i, j; double rotate[3][3]; rotate[0][0] = cos(r); rotate[1][0] = 0; rotate[2][0] = sin(r); rotate[0][1] = 0; rotate[1][1] = 1; rotate[2][1] = 0; rotate[0][2] = -sin(r); rotate[1][2] = 0; rotate[2][2] = cos(r); Vector3 ans = Vector3_init(0.0, 0.0, 0.0); for(i = 0; i < 3; i++) { double buff = 0.0; for(j = 0; j < 3; j++) { buff += rotate[j][i] * this_->vec[j]; } ans.vec[i] = buff; } this_->copy(this_, ans); } void __Vector3_getAsGLdouble(Vector3 *this_, GLdouble *gldouble) { for(int i = 0; i < 3; i++) *(gldouble+i) = this_->vec[i]; }
C
// File containing User defined definitions such as configuring the si114x_init file for an indoors or general mode #ifndef INDOORS #ifndef GENERAL // If either INDOORS or GENERAL is defined, it must have been defined via a command-line switch. In this case, // this code is never reached and the command line switch takes precedence. // // However, if neither INDOORS nor GENERAL is defined, then we need to define it here. // // Use #define GENERAL to configure slider for general use mode // Use #define INDOORS to configure slider for indoors and long range use // // Do not set both GENERAL and INDDORS at the same time. // #define INDOORS #endif #endif
C
#include <fcntl.h> #include <errno.h> #include <string.h> #include <stdlib.h> #include <assert.h> #include <arpa/inet.h> #include <sys/socket.h> #include "bmp_log.h" #include "bmp_recv.h" #include "bgp_router.h" #include "bmp_session.h" #include "bmp_process.h" int bmp_session_compare(void *a, void *b, void *c) { bmp_session *A = (bmp_session*)a; bmp_session *B = (bmp_session*)b; return (A->fd - B->fd); } static void bmp_session_cleanup(bmp_session *session) { free(session); } int bmp_protocol_error(bmp_session *session, int error) { /* * TODO: do some book-keeping here */ bmp_session_close(session, BMP_SESSION_PROTOCOL_ERROR); return 0; } int bmp_session_close(bmp_session *session, int reason) { char port[16]; int multiport; bgp_router *router = session->router; assert(router != NULL); assert(session != NULL); assert(session->fd != 0); avl_remove(session->server->sessions, session, NULL); close(session->fd); // this will also remove the fd from the epoll queue snprintf(port, 16, ":%d", session->port); multiport = (router->flags & BGP_ROUTER_MULTIPORT); bmp_log("BMP-ADJCHANGE: Router %s%s DOWN (%s)", session->router->name, multiport ? port : "", BMP_SESSION_CLOSE_REASON(reason)); bgp_router_session_remove(session); bmp_session_cleanup(session); return 0; } /* * Create a bmp_session entry in the server->session avl tree * Queue the accepted fd to the same epoll queue as the server socket */ int bmp_session_create(bmp_server *server, int fd, struct sockaddr *addr, socklen_t slen) { int rc, multiport; char port[16]; bmp_session *session; bgp_router *router; rc = fd_nonblock(fd); if (rc < 0) { return rc; } if (fd > BMP_SESSION_MAX - 1) { bmp_log("new session dropped. fd '%d' > BMP_SESSION_MAX", fd); close(fd); return -1; } session = calloc(1, sizeof(bmp_session)); if (session == NULL) { return -1; } session->server = server; session->fd = fd; session->rdbuf = calloc(1, BMP_RDBUF_MAX); session->rdptr = session->rdbuf; if (session->rdptr == NULL) { bmp_log("session rdbuffer alloc failed"); free(session); return -1; } memcpy(&session->addr, addr, slen); session->port = bmp_sockaddr_port(&session->addr); gettimeofday(&session->time, NULL); avl_insert(server->sessions, session, NULL); /* * Queue the session fd into the server's epoll queue */ MONITOR_FD(server->eq, fd, rc); if (rc < 0) { bmp_log("epoll add %d failed: %s", fd, strerror(errno)); close(fd); return -1; } router = bgp_router_session_add(session); if (router == NULL) { return -1; } snprintf(port, 16, ":%d", session->port); multiport = (router->flags & BGP_ROUTER_MULTIPORT); bmp_log("BMP-ADJCHANGE: Router %s%s UP", session->router->name, multiport ? port : ""); return rc; } static int bmp_session_read(bmp_session *session) { int rc = 1, error = 0, space; uint64_t msgs; char *pread; assert(session->fd != 0); assert(session->router != NULL); msgs = session->router->msgs; while (rc > 0) { while ((space = BMP_RDBUF_SPACE(session)) > 0) { rc = read(session->fd, session->rdptr, space); if (rc <= 0) { error = errno; break; } session->server->bytes += rc; session->bytes += rc; session->rdptr += rc; } if (session->rdptr - session->rdbuf > 0) { /* * Whatever we read, feed it to the protocol machinery. This will * consume the read buffer upto the last full PDU, leaving behind a * partial PDU if any bytes should remain */ pread = bmp_recv(session, session->rdbuf, session->rdptr); /* * If the protocol parsing detects an error, it will return NULL */ if (pread == NULL) return rc; /* * Protocol should *not* read past the end of the read buffer */ assert(pread <= session->rdptr); /* * If pread == client->rdbuf for too many iterations, we have an issue */ /* * Copy the fragment PDU to the head of the read buffer. The protocol * read always happens from the head of the read buffer */ if (pread < session->rdptr && pread != session->rdbuf) { memcpy(session->rdbuf, pread, session->rdptr - pread); } session->rdptr = session->rdbuf + (session->rdptr - pread); } } /* * If we read at least one full PDU from this session we have to signal the * processing task to "process" this session now. Note: at this point, the * session COULD be in inactive state (session torn down, etc) */ if (session->router->msgs - msgs) { bmp_process_message_signal(session->router); } if (rc == 0) { bmp_session_close(session, BMP_SESSION_REMOTE_CLOSE); } if (rc < 0 && error != EAGAIN) { bmp_session_close(session, BMP_SESSION_READ_ERROR); } return rc; } int bmp_session_process(bmp_server *server, int fd, int events) { int rc = 0; bmp_session *session, search; search.fd = fd; session = (bmp_session*)avl_lookup(server->sessions, &search, NULL); assert(session != NULL); assert(session->router != NULL); rc = bmp_session_read(session); return rc; }
C
#ifndef _OBJ_H_A #define _OBJ_H_A #include <stdlib.h> int* findDisappearedNumbers(int* nums, int numsSize, int* returnSize) { int *arr = (int*)malloc((numsSize + 1) * sizeof(int)); int i, j, count = 0; for (i = 0; i <= numsSize; i++) arr[i] = 0; for (i = 0; i < numsSize; i++) { arr[nums[i]]++; } arr[0] = 1; for (i = 1; i <= numsSize; i++) { if (arr[i] == 0) count++; } *returnSize = count; int* re = (int*)malloc(count * sizeof(int)); for (i = 0; i < count; i++) { re[i] = 0; } for (i = 1; i <= numsSize; i++) { if (arr[i] == 0) { for (j = 0; j < count; j++) { if (re[j] == 0) { re[j] = i; break; } } } } free(arr); arr = NULL; return re; } #endif
C
#pragma once #include "stdbool.h" /* STRUCTS */ typedef struct merge_sort_array { int* data; int size; }MergeSortArray; /* FUNCTIONS */ //Reads the file with numbers, put numbers in an array, sorts the array and returns it int* quick_sort_from_file(const char* fName, bool print); //Main quicksort function void quick_sort(int* A, int p, int r); //Partition function int partition(int* A, int p, int r); /* UTILITY FUNCTIONS */ //Swaps A[j] and A[i] void exchange(int* A, int j, int i);
C
#include <stdio.h> #include <stdlib.h> #include <pthread.h> #include <string.h> #include <sys/time.h> #define HASHTABLE_SIZE 1000099 #define LOCALBUFFER_SIZE 100 /* node structure for heap */ typedef struct node { /* square orientation */ char str[17]; /* stores the distance from the expected orientation */ int dist; /* if this node is used in a linked list, it points to the next node in the list */ struct node * next; /* pointer to the moves after which this orientation is obtained */ char * moves; /* maximum number of moves that can fit in moves string */ int max_moves; } node; /* stores heap for the work queue */ node heap[1000000]; /* it shores the hash table of orientation in chained format */ node * hash_table[HASHTABLE_SIZE]; /* the number of nodes currently in work queue */ int heap_size = 0; /* the number of threads running our algorithm */ int nthreads; /* mutex lock for accessing the working queue */ pthread_mutex_t working_queue_lock; /* flag that will be set if any of the threads find the solution */ int found_solution; /** * @param a orientation of the 15 square in string format. * finds the manhattan distance from the expected orientation */ int get_manhattan_distance(char *a) { int dist = 0, i; for(i = 0; i < strlen(a); i++) { int exp_r; int exp_c; if(a[i] == 'a') { exp_r = 3; exp_c = 3; } else { exp_r = (a[i] - 'a' - 1) / 4; exp_c = (a[i] - 'a' - 1) % 4; } int tmp = abs(exp_c - (i % 4)) + abs(exp_r - i / 4); dist += tmp; } return dist; } /** * @param s string representation of the square * makes a new node with the fields populated accordingly */ node get_heap_node(char * s, char * moves, int max_moves) { node new; strcpy(new.str, s); new.dist = get_manhattan_distance(s); new.moves = moves; new.max_moves = max_moves; return new; } /** * @param s The orientation of the square in string format that needs to be inserted in the heap * Inserts a node corresponding to s in the heap */ void insert_heap_node(node new, node heap[], int * heap_size) { int idx; if(*heap_size >= 1000000) idx = 999999; else idx = *heap_size; *heap_size = idx + 1; heap[idx] = new; while(1) { if(idx == 0) break; int pid = (idx - 1) / 2; if(heap[pid].dist > new.dist) { heap[idx] = heap[pid]; heap[pid] = new; idx = pid; } else break; } } /** * returns the node corresponding to minimum distance orientation in the heap */ node extract_heap_min(node heap[], int * heap_size) { node tmp = heap[0]; heap[0] = heap[*heap_size - 1]; heap[*heap_size - 1] = tmp; *heap_size = *heap_size - 1; int idx = 0; while(1) { int lid = idx * 2 + 1; int rid = idx * 2 + 2; if(lid >= *heap_size && rid >= *heap_size) break; node left = heap[lid]; node right = heap[rid]; if(lid < *heap_size && (left.dist < right.dist || rid >= *heap_size)) { if(heap[idx].dist > left.dist) { node tmp = heap[idx]; heap[idx] = left; heap[lid] = tmp; idx = lid; } else break; } else if(rid < *heap_size) { if(heap[idx].dist > right.dist) { node tmp = heap[idx]; heap[idx] = right; heap[rid] = tmp; idx = rid; } else break; } } return heap[*heap_size]; } /** * @param s string for which hash is to be calculated * returns the hashed value for the string */ long long int compute_hash(char *s, long long int sz) { const int p = 31; const int m = sz; long long int hash_value = 0; long long int p_pow = 1; for (int i = 0; i < strlen(s); i++) { char c = s[i]; hash_value = (hash_value + (c - 'a' + 1) * p_pow) % m; p_pow = (p_pow * p) % m; } return hash_value; } /** * @param s The orientation in string format that we want to hash * inserts a node structure corresponding to s into the hash table */ void insert_in_ht(node * hash_table[], char * s, long long int sz) { int idx = compute_hash(s, sz); node * new = (node *)malloc(sizeof(node)); strcpy(new -> str, s); new -> dist = get_manhattan_distance(s); new -> next = NULL; node * tmp = hash_table[idx]; if(tmp == NULL) { hash_table[idx] = new; return; } node * prev = NULL; while(tmp != NULL) { prev = tmp; tmp = tmp -> next; } prev -> next = new; new -> next = tmp; } /** * @param s The orientation in string format that we want to hash * finds a node structure corresponding to s into the hash table * 0: not found 1: found */ int find_in_ht(node * hash_table[], char * s, long long int sz) { int idx = compute_hash(s, sz); node * tmp = hash_table[idx]; while(tmp != NULL) { if(strcmp(tmp -> str, s) == 0) return 1; tmp = tmp -> next; } return 0; } /** * s starting orientation of the puzzle in string format * checks whether the given start orientation is solvable * 0: unsolvable 1: solvable */ int is_solvable(char * s) { int inv = 0; int row; for(int i = 0; i < strlen(s); i++) { if(s[i] == 'a') { row = i / 4; continue; } for(int j = i + 1; j < strlen(s); j++) { if(s[i] > s[j] && s[j] != 'a') inv++; } } if(row % 2 == 0 && inv % 2) return 1; if(row % 2 == 1 && inv % 2 == 0) return 1; return 0; } /* reads the input state of the puzzle and returns its string equivalent */ char * read_input() { FILE * fp = fopen("input.txt", "r"); int i, j; char * ret = (char *)malloc(20); ret[16] = '\0'; for(i = 0; i < 4; i++) for(j = 0; j < 4; j++) { int tmp; fscanf(fp, "%d", &tmp); ret[i*4 + j] = (char)('a' + tmp); } return ret; } /* the tree search function where each thread begins its execution */ void * tree_search(void * i) { int * id = (int *) i; node local_heap[LOCALBUFFER_SIZE]; node * local_ht[LOCALBUFFER_SIZE]; for(int i = 0; i < LOCALBUFFER_SIZE; i++) local_ht[i] = NULL; int local_heap_size = 0; node min_dist_node; while(1) { /* getting lock on working queue and after taking he minimum distance orientation, instantaneously release the lock */ if(local_heap_size == 0) { /* no local heap, so we have to get the lock and get the minimum element */ pthread_mutex_lock(&working_queue_lock); if(heap_size == 0) { if(found_solution) { pthread_mutex_unlock(&working_queue_lock); break; } pthread_mutex_unlock(&working_queue_lock); // printf("Thread: %d continued\n", *id); continue; } min_dist_node = extract_heap_min(heap, &heap_size); pthread_mutex_unlock(&working_queue_lock); } else if(local_heap_size == LOCALBUFFER_SIZE) { pthread_mutex_lock(&working_queue_lock); if(found_solution) { pthread_mutex_unlock(&working_queue_lock); break; } for(int i = 0; i < LOCALBUFFER_SIZE; i++) { if(!find_in_ht(hash_table, local_heap[i].str, HASHTABLE_SIZE)) { insert_heap_node(local_heap[i], heap, &heap_size); insert_in_ht(hash_table, local_heap[i].str, HASHTABLE_SIZE); } } min_dist_node = extract_heap_min(heap, &heap_size); pthread_mutex_unlock(&working_queue_lock); local_heap_size = 0; } else { int lock_status = pthread_mutex_trylock(&working_queue_lock); if(lock_status != 0) { min_dist_node = extract_heap_min(local_heap, &local_heap_size); } else { if(found_solution) { pthread_mutex_unlock(&working_queue_lock); break; } for(int i = 0; i < local_heap_size; i++) { if(!find_in_ht(hash_table, local_heap[i].str, HASHTABLE_SIZE)) { insert_heap_node(local_heap[i], heap, &heap_size); insert_in_ht(hash_table, local_heap[i].str, HASHTABLE_SIZE); } } min_dist_node = extract_heap_min(heap, &heap_size); pthread_mutex_unlock(&working_queue_lock); local_heap_size = 0; } } printf("Thread: %d, orientation: %s, dist: %d\n", *id, min_dist_node.str, min_dist_node.dist); if(found_solution) break; if(min_dist_node.dist == 0) { found_solution = 1; printf("The solution is: %s\n", min_dist_node.moves); break; } /* spotting the blank position */ char pos[17]; strcpy(pos, min_dist_node.str); insert_in_ht(local_ht, pos, LOCALBUFFER_SIZE); int i; for(i = 0; i < 16; i++) if(pos[i] == 'a') break; int row, col; row = i / 4; col = i % 4; /* reallocating memory if moves are greater than memory given */ int moves_done = strlen(min_dist_node.moves); if(moves_done + 1 > min_dist_node.max_moves) { min_dist_node.max_moves *= 2; // min_dist_node.moves = (char *)realloc(min_dist_node.moves_done, min_dist_node.max_moves); } /* moving appropriately */ if(row > 0) { char tmp[17]; strcpy(tmp, pos); tmp[(row - 1) * 4 + col] = 'a'; tmp[row * 4 + col] = pos[(row - 1) * 4 + col]; char * moves = (char *)malloc(min_dist_node.max_moves); strcpy(moves, min_dist_node.moves); moves[strlen(min_dist_node.moves) + 1] = '\0'; moves[strlen(min_dist_node.moves)] = 'U'; node new = get_heap_node(tmp, moves, min_dist_node.max_moves); if(local_heap_size < LOCALBUFFER_SIZE - 1 && !find_in_ht(local_ht, new.str, LOCALBUFFER_SIZE)) { insert_heap_node(new, local_heap, &local_heap_size); insert_in_ht(local_ht, new.str, LOCALBUFFER_SIZE); } } if(row < 3) { char tmp[17]; strcpy(tmp, pos); tmp[(row + 1) * 4 + col] = 'a'; tmp[row * 4 + col] = pos[(row + 1) * 4 + col]; char * moves = (char *)malloc(min_dist_node.max_moves); strcpy(moves, min_dist_node.moves); moves[strlen(min_dist_node.moves) + 1] = '\0'; moves[strlen(min_dist_node.moves)] = 'D'; node new = get_heap_node(tmp, moves, min_dist_node.max_moves); if(local_heap_size < LOCALBUFFER_SIZE - 1 && !find_in_ht(local_ht, new.str, LOCALBUFFER_SIZE)) { insert_heap_node(new, local_heap, &local_heap_size); insert_in_ht(local_ht, new.str, LOCALBUFFER_SIZE); } } if(col > 0) { char tmp[17]; strcpy(tmp, pos); tmp[row * 4 + col - 1] = 'a'; tmp[row * 4 + col] = pos[row * 4 + col - 1]; char * moves = (char *)malloc(min_dist_node.max_moves); strcpy(moves, min_dist_node.moves); moves[strlen(min_dist_node.moves) + 1] = '\0'; moves[strlen(min_dist_node.moves)] = 'L'; node new = get_heap_node(tmp, moves, min_dist_node.max_moves); if(local_heap_size < LOCALBUFFER_SIZE - 1 && !find_in_ht(local_ht, new.str, LOCALBUFFER_SIZE)) { insert_heap_node(new, local_heap, &local_heap_size); insert_in_ht(local_ht, new.str, LOCALBUFFER_SIZE); } } if(col < 3) { char tmp[17]; strcpy(tmp, pos); tmp[row * 4 + col + 1] = 'a'; tmp[row * 4 + col] = pos[row * 4 + col + 1]; char * moves = (char *)malloc(min_dist_node.max_moves); strcpy(moves, min_dist_node.moves); moves[strlen(min_dist_node.moves) + 1] = '\0'; moves[strlen(min_dist_node.moves)] = 'R'; node new = get_heap_node(tmp, moves, min_dist_node.max_moves); if(local_heap_size < LOCALBUFFER_SIZE - 1 && !find_in_ht(local_ht, new.str, LOCALBUFFER_SIZE)) { insert_heap_node(new, local_heap, &local_heap_size); insert_in_ht(local_ht, new.str, LOCALBUFFER_SIZE); } } } printf("%d\n", *id); } int main(int argc, char ** argv) { /* initializing the number of threads to be spawned */ nthreads = atoi(argv[1]); found_solution = 0; struct timeval t1, t2; gettimeofday(&t1, 0); /* taking the input orientation of the puzzle and inserting it into the work queue and hash table */ char start[17]; strcpy(start, read_input()); // printf("%s\n", start); if(!is_solvable(start)) { printf("The given puzzle is unsolvable\n"); return 0; } insert_in_ht(hash_table, start, HASHTABLE_SIZE); node new = get_heap_node(start, "", 256); insert_heap_node(new, heap, &heap_size); pthread_mutex_init(&working_queue_lock, NULL); /* creating the threads */ pthread_t thread_id[nthreads]; int i; for(i = 0; i < nthreads; i++) { pthread_create(&thread_id[i], NULL, tree_search, (void *) &i); } /* waiting for the threads to join */ for(i = 0; i < nthreads; i++) { pthread_join(thread_id[i], NULL); } gettimeofday(&t2, 0); double time_taken = t2.tv_sec+t2.tv_usec/1e6-(t1.tv_sec+t1.tv_usec/1e6); // in seconds printf("Program took %lf seconds to execute \n", time_taken); return 0; }
C
/*Write a program to draw a point of width 10 pixel*/ #include<GL/glut.h> #include<stdio.h> #include<math.h> struct scanLine { int y; int x[20]; }; struct Edge { int x1,y1; float m; }e[20]; void MyInit ( void ) { glClearColor ( 0.0, 0.0, 0.0, 0.0 ); //white background glColor3f(0.0f, 1.0f,0.0f); // green drawing colour glPointSize(1.0); // 5 pixel dot! glMatrixMode ( GL_PROJECTION ); glLoadIdentity ( ); gluOrtho2D ( 0.0, (GLdouble)500, 0.0, (GLdouble)500 ); //Display area } int main(int argc, char **argv) { glutInit(&argc,argv); glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB); int n; printf("Enter the no. of vertices in the polygon!\n"); scanf("%d",&n); float xt[n],yt[n]; //int x[2*n],y[2*n]; printf("Enter x,y for each vertex!\n"); int i=0; for(i=0;i<n;i++) { printf("%d\t",i); scanf("%f%f",&xt[i],&yt[i]); } int index=0; for(i=0;i<n;i++) { e[index].x1=xt[i]; e[index].y1=yt[i]; e[index].x2=xt[(i+1)%n]; e[index].y2=yt[(i+1)%n]; index++; } /* glutInitWindowPosition(50,25); glutInitWindowSize(500,500); glutCreateWindow("Green window"); MyInit ( ); glClear ( GL_COLOR_BUFFER_BIT ); //clear pixel buffer glBegin(GL_POINTS); // render with points */ i=0; int cur=0,pre=n-1,nex=1; float m=0; for(cur=0;cur<n;cur++) { if(yt[pre]<yt[cur]&&yt[cur]<yt[nex]) { m=(yt[pre]-yt[cur])/(xt[pre]-xt[cur]); //printf("%f\t",m); e[i].m=m; e[i].x1=round(xt[pre]+(1/m)*(yt[cur]-yt[pre]-1)); e[i].y1=yt[cur]-1; //i++; //x[i]=xt[cur]; //y[i]=yt[cur]; e[i].x2=xt[cur]; e[i].x2=yt[cur]; } else if(yt[pre]>yt[cur]&&yt[cur]>yt[nex]) { m=(yt[nex]-yt[cur])/(xt[nex]-xt[cur]); //printf("%f\t",m); x[i]=xt[cur]; y[i]=yt[cur]; i++; x[i]=round(xt[nex]+(1/m)*(yt[cur]-yt[nex]-1)); y[i]=yt[cur]-1; nv[nvi].index=i; nv[nvi].up=1; nvi++; } else { x[i]=xt[cur]; y[i]=yt[cur]; } pre=(pre+1)%n; nex=(nex+1)%n; i++; } int end=i; for(i=0;i<end;i++) printf("%d , %d\n",x[i],y[i]); int ymin,xmin,ymax; for(i=0;i<end;i++) { if(i==nv[nvi] } //glVertex2i(x8,y8); /* glEnd(); glFlush(); glutMainLoop(); */ return 0; }
C
/* ITS240-01 Lab 10 ch11p546pe1 04/17/2017 Daniel Kuckuck Write a C program that stores the following numbers in an array named ‘miles’: 15, 22, 16, 18, 27, 23, 20. Have your program copy the data stored in miles to another array named ‘dist’ and then display the values in the dist array. */ #include <stdio.h> int main() { int miles[] = {15, 22, 16, 18, 27, 23, 20}, dist[7]; //strncpy(dist, miles, 8); for (int j = 0; j < 7; ++j) { dist[j] = miles[j]; } for (int i = 0; i < 7; ++i) { printf("%d ", dist[i]); } printf("\n"); return 0; }
C
#include "libs/Header.h" #pragma warning(disable : 4996) #define SectionSize sizeof(IMAGE_SECTION_HEADER) #define PExoortDirecotry64 &Image_Nt_Header64.OptionalHeader.DataDirectory[0] #define PExoortDirecotry32 &Image_Nt_Header32.OptionalHeader.DataDirectory[0] #define PImportDirectory64 &Image_Nt_Header64.OptionalHeader.DataDirectory[1] #define PImportDirectory32 &Image_Nt_Header32.OptionalHeader.DataDirectory[1] #define PRelocationDirectory64 &Image_Nt_Header64.OptionalHeader.DataDirectory[5] #define PRelocationDirectory32 &Image_Nt_Header32.OptionalHeader.DataDirectory[5] int Machine64(); int Machine32(); int main() { if ((fp = fopen("TEST2.exe","rb")) == NULL) { fprintf(stderr, "File open error\n"); return 1; } WORDSIZE = sizeof(WORD); DWORDSIZE = sizeof(DWORD); printf("%8s\t%8s\t%-16s\n", "OFFSET", "VALUE", "DESCRIPTION"); Offset = Dos_Header(fp); fseek(fp, Offset + DWORDSIZE, SEEK_SET); fread(&Machine, WORDSIZE, 1, fp); fseek(fp, Offset, SEEK_SET); // 64bit if (Machine == 0x8664) Machine64(); // 32bit else if (Machine == 0x014c) Machine32(); fclose(fp); return 0; } int Machine64() { PIMAGE_SECTION_HEADER PSECTION_HEADER; IMAGE_NT_HEADERS64 Image_Nt_Header64; unsigned int SectionNumber = 0; SectionNumber = NT_Header64(&Image_Nt_Header64); PSECTION_HEADER = (PIMAGE_SECTION_HEADER)malloc(SectionSize * SectionNumber); Section_Header(PSECTION_HEADER, SectionNumber, Image_Nt_Header64.OptionalHeader.FileAlignment); ExportDirectory(PSECTION_HEADER, PExoortDirecotry64, SectionNumber,Image_Nt_Header64.OptionalHeader.FileAlignment); ImportDirectory(PSECTION_HEADER, PImportDirectory64, SectionNumber,Image_Nt_Header64.OptionalHeader.FileAlignment); // RelocationDirectory(PSECTION_HEADER, PRelocationDirectory64, SectionNumber); free(PSECTION_HEADER); return 0; } int Machine32() { PIMAGE_SECTION_HEADER PSECTION_HEADER; IMAGE_NT_HEADERS32 Image_Nt_Header32; unsigned int SectionNumber = 0; SectionNumber = NT_Header32(&Image_Nt_Header32); PSECTION_HEADER = (PIMAGE_SECTION_HEADER)malloc(SectionSize * SectionNumber); Section_Header(PSECTION_HEADER, SectionNumber, Image_Nt_Header32.OptionalHeader.FileAlignment); // ExportDirectory(PSECTION_HEADER, PExoortDirecotry32, SectionNumber,Image_Nt_Header32.OptionalHeader.FileAlignment); // ImportDirectory(PSECTION_HEADER, PImportDirectory32, SectionNumber,Image_Nt_Header32.OptionalHeader.FileAlignment); RelocationDirectory(PSECTION_HEADER, PRelocationDirectory32, SectionNumber); free(PSECTION_HEADER); return 0; }
C
#include <GL/glut.h> #include <GL/glu.h> typedef enum { FALSE = 0, TRUE = 1 } bool; void init(void) { glClearColor(0.0f, 0.0f, 0.0f, 0.0f); glShadeModel(GL_FLAT); } void drawFractal(int level, bool isRoot) { if (level < 0) return; glutWireCube(1.0); glPushMatrix(); glTranslatef(0.0, 0.75, 0.0); glScalef(0.75, 0.75, 0.75); glRotatef(10.0, 0.0, 0.0, -1.0); drawFractal(level - 1, FALSE); glPopMatrix(); if (!isRoot) return; glPushMatrix(); glTranslatef(0.75, 0.0, 0.0); glScalef(0.75, 0.75, 0.75); glRotatef(90, 0.0, 0.0, -1.0); glRotatef(10.0, 0.0, 0.0, -1.0); drawFractal(level - 1, FALSE); glPopMatrix(); glPushMatrix(); glTranslatef(0.0, -0.75, 0.0); glScalef(0.75, 0.75, 0.75); glRotatef(180, 0.0, 0.0, -1.0); glRotatef(10.0, 0.0, 0.0, -1.0); drawFractal(level - 1, FALSE); glPopMatrix(); glPushMatrix(); glTranslatef(-0.75, 0.0, 0.0); glScalef(0.75, 0.75, 0.75); glRotatef(270, 0.0, 0.0, -1.0); glRotatef(10.0, 0.0, 0.0, -1.0); drawFractal(level - 1, FALSE); glPopMatrix(); } void display(void) { glClear(GL_COLOR_BUFFER_BIT); glColor3f(1.0, 1.0, 1.0); glLoadIdentity(); gluLookAt(0.0, 0.0, 5.0, // Eye position 0.0, 0.0, 0.0, // Looking at 0.0, 1.0, 0.0); // With normal vector glRotatef(30.0, 0.0, 0.0, -1.0); drawFractal(15, TRUE); glFlush(); } void reshape(int w, int h) { glViewport(0.0f, 0.0f, (GLsizei) w, (GLsizei) h); glMatrixMode(GL_PROJECTION); glLoadIdentity(); float ratio = ((float) w) / h; glFrustum(-ratio, ratio, -1.0, 1.0, 1.5, 20.0); glMatrixMode(GL_MODELVIEW); } int main(int argc, char **argv) { glutInit(&argc, argv); glutInitDisplayMode (GLUT_SINGLE | GLUT_RGB); glutInitWindowSize(500, 500); glutInitWindowPosition(100, 100); glutCreateWindow (argv[0]); init(); glutDisplayFunc(display); glutReshapeFunc(reshape); glutMainLoop(); return 0; }
C
#include <stdio.h> #include <cs50.h> // Collatz Conjecture // Program that calculates how many steps it takes to get back to 1. int collatz(int n); int collatz(int n) { if(n == 1) { return 0; } else if((n % 2) == 0) { return 1 + collatz(n/2); } else { return 1 + collatz(3*n + 1); } } int main(void) { }
C
#include <stdio.h> #include <unistd.h> #include <stdlib.h> #include "../my.h" #include "../my_list.h" void *xmalloc(int size) { void *ptr; if ((ptr = malloc(size)) == NULL) { printf("CANT MALLOC SRY\n"); my_exit(); } return (ptr); } int xfork() { pid_t pid; int i; if ((pid = fork()) == -1) { printf("CANT FORK SRY"); my_exit(); } return (pid); } int xread(int place, void *buffer, int nbbyte) { int nb; nb = read(place, buffer, nbbyte); if (nb == -1) { printf("CANT READ SRY\n"); my_exit(); } return (nb); } int xwrite(int place, void *buffer, int nbbyte) { int nb; nb = write(place, buffer, nbbyte); if (nb == -1) { printf("CANT WRITE SRY\n"); my_exit(); } return (nb); }
C
#pragma once #include "Prototypes.h" /****************************************************************************************** * Function Name: get_valid_string(char *string) * * Funtion Description: * This function allows a user to give a description to an item * * * User-interface variables:- * *OUT (Return values): * - NONE * *IN (Value Parameters): * - NONE * *IN and OUT (Reference Parameters): * - char *string * * History [Date (Author): Description)]:- * 2019-17-01 (Maxwell Gyamfi): get valid string ******************************************************************************************/ void get_valid_string(char *string) { char buffer[MAX_LENGHT_DESCRIPTION]; int success = 0; do { fgets(buffer, sizeof(buffer), stdin);//request user input int lenght = strlen(buffer); buffer[lenght - 1] = '\0'; if (strlen(buffer) < 1)//checks if too short { printf("Decription too short, try again: "); } else if (strlen(buffer) > MAX_LENGHT_DESCRIPTION)//checks if too long { printf("Decription too long, try again: "); } else { strcpy(string, buffer);//copy string into string array success = 1; } } while (success == 0); } /*************************************************************************************** * Function Name: void get_valid_password(char *password) * * Funtion Description: * -This function request a user to input a password. * -Will repeat and display specific error message if provided inuput does not meet * requirements. * * User-interface variables:- * *OUT (Return values): * - NONE * *IN (Value Parameters): * - NONE * *IN and OUT (Reference Parameters): * - char *password * * History [Date (Author): Description)]:- * 2019-17-01 (Maxwell Gyamfi): gets valid password ******************************************************************************************/ void get_valid_password(char *password) { //local variables int i = 0; int k = 0; int lenght = 0; char ch = '\0'; char buffer[PASSWORD_LENGHT]; int success = 0; do { k = 0; i = 0; memset(buffer, 0, sizeof(buffer));//sets array values to 0 while (k < PASSWORD_LENGHT) { ch = getch(); if (ch == '\r')//breaks if new line charater is inputted { break; } else if (ch == '\b') { if (i > 0) { i--;//removes backspace character from array k--; printf("\b \b"); } } else { //masks password displaying '*' character buffer[i++] = ch; ch = '*'; printf("%c", ch); k++; } } lenght = get_string_length(buffer); if (lenght > PASSWORD_LENGHT)//checks password length { printf("\nPassword is too long,try again: "); } else if (lenght < 8) { printf("\nPassword too short,try again: "); } else if (!hasdigit(buffer, lenght))//checks if integer present { printf("\nYour password should contain at least an integer,try again: "); } else if (!has_upper_case(buffer, lenght))//checks for uppercase { printf("\nYour password should contain at least an upper-case character,try again: "); } else { copy_string(buffer, password); success = 1; } } while (success == 0); } /*************************************************************************************** * Function Name: cipher_password(char *password,char *key,char *pswd,int value) * * Funtion Description: * -This function encrypts and decrypts a password provided by user. * -It first generate a key which is then summed or subracted to password * based on switch value. * * User-interface variables:- * *OUT (Return values): * - NONE * *IN (Value Parameters): * - char *password,char *key,int value * *IN and OUT (Reference Parameters): * - char *pswd * * History [Date (Author): Description)]:- * 2019-17-01 (Maxwell Gyamfi): encrypts and decrypts password ******************************************************************************************/ void cipher_password(char *password, char *key, char *pswd, int value) { //local variables int i, j = 0; //calculates password and key length int len_password = strlen(password); int len_key = strlen(key); //dynamically allocates memory char *new_key = (char*)malloc(len_password * sizeof(char)); char *encrypted_msg = (char*)malloc(len_password * sizeof(char)); char *decrypted_msg = (char*)malloc(len_password * sizeof(char)); //loops and generate new key for (i = 0, j = 0; i < len_password; i++, j++) { if (j == len_key) { j = 0; } new_key[i] = key[j]; } new_key[i] = '\0'; //action selection menu switch (value) { case 0: //encrypts password by summing password to key and 'A' character for (i = 0; i < len_password; i++) { encrypted_msg[i] = ((password[i] + new_key[i])) + 'A'; } encrypted_msg[i] = '\0'; strcpy(pswd, encrypted_msg); break; case 1: //decrypts password by subracting password from key and 'A' character for (i = 0; i < len_password; i++) { decrypted_msg[i] = ((password[i] - new_key[i])) - 'A'; } decrypted_msg[i] = '\0'; strcpy(pswd, decrypted_msg); break; default: break; } } /*************************************************************************************** * Function Name: hasdigit(char *string,int lenght) * * Funtion Description: * -This function checks if a string contains a numberic value. * * User-interface variables:- * *OUT (Return values): * - bool(1:True,0:False) * *IN (Value Parameters): * - char *string,int lenght * *IN and OUT (Reference Parameters): * - NONE * * History [Date (Author): Description)]:- * 2019-17-01 (Maxwell Gyamfi): checks for integer value ******************************************************************************************/ int hasdigit(char *string, int lenght) { //local variable int i = 0; //loops and check for integer value for (i = 0; i < lenght; i++) { if (string[i] >= '0' && string[i] <= '9') { return 1; } } return 0; } /*************************************************************************************** * Function Name: has_upper_case(char *string, int lenght) * * Funtion Description: * -This function checks if a string contains at least one upper-case alphabet value . * * User-interface variables:- * *OUT (Return values): * - bool(1:True,0:False) * *IN (Value Parameters): * - char *string,int lenght * *IN and OUT (Reference Parameters): * - NONE * * History [Date (Author): Description)]:- * 2019-17-01 (Maxwell Gyamfi): checks for upper-case alphabet value ******************************************************************************************/ int has_upper_case(char *string, int lenght) { //local variable int i = 0; //loops and checks for upper-case alphabet for (i = 0; i < lenght; i++) { if (string[i] >= 'A' && string[i] <= 'Z') { return 1; } } return 0; } /*************************************************************************************** * Function Name: get_valid_email(int number_of_accounts, struct User *users,int login,char *email) * * Funtion Description: * -This function prompts a user to input a valid email address.It will display a speci- * fic error message and request input if wrong input is provided. * -Based on login value it will either copy correct email-value to char email or struct *users * * User-interface variables:- * *OUT (Return values): * - NONE * *IN (Value Parameters): * - int number_of_accounts,struct User *users,int login * *IN and OUT (Reference Parameters): * - struct User *users,char *email * * History [Date (Author): Description)]:- * 2019-17-01 (Maxwell Gyamfi): requests and check for valid email address ******************************************************************************************/ void get_valid_email(int number_of_accounts, struct User *users, int login, char *email) { //local varaibles char buffer[EMAIL_LENGHT]; int success = 0; int lenght = 0; do { //requests input fgets(buffer, sizeof(buffer), stdin); lenght = get_string_length(buffer); buffer[lenght - 1] = '\0'; lenght = lenght - 1; if (lenght > EMAIL_LENGHT)//checks string length { printf("\nEmail is too long,try again: "); } else if (!has_at_email(buffer, lenght))//checks for '@character' { printf("\nAn email has at least one '@' character,try again: "); } else if (!has_domain(buffer, lenght))//checks for correct domain { printf("\nYou inputted a wrong domain,try again: "); } else if (email_exist(users, number_of_accounts, buffer))//checks for email existence { if (login == 1) { copy_string(buffer, email); success = 1; break; } printf("\nYour inputted email exists already, try again: "); } else { copy_string(buffer, users[number_of_accounts].user_email); success = 1; } } while (success == 0); } /*************************************************************************************** * Function Name: email_exist(struct User *users, int number_of_accounts,char *string) * * Funtion Description: * -This function checks if user provided email input exists already in the system * * User-interface variables:- * *OUT (Return values): * - bool(1:True,0:False) * *IN (Value Parameters): * - struct User *users, int number_of_accounts,char *string * *IN and OUT (Reference Parameters): * - NONE * * History [Date (Author): Description)]:- * 2019-17-01 (Maxwell Gyamfi): checks for email presence in system ******************************************************************************************/ int email_exist(struct User *users, int number_of_accounts, char *string) { //local variable int i = 0; //loops and compare provided email to system emails for (i = 0; i < number_of_accounts; i++) { if (strcmp(string, users[i].user_email) == 0) { return 1; } } return 0; } /*************************************************************************************** * Function Name: has_at_email(char *string, int lenght) * * Funtion Description: * -This function checks if a string a has an '@' character * * User-interface variables:- * *OUT (Return values): * - bool(1:True,0:False) * *IN (Value Parameters): * - char *string, int lenght * *IN and OUT (Reference Parameters): * - NONE * * History [Date (Author): Description)]:- * 2019-17-01 (Maxwell Gyamfi): checks for '@ ' character in string ******************************************************************************************/ int has_at_email(char *string, int lenght) { //local variable int i = 0; //loops and checks for '@' character for (i = 0; i < lenght; i++) { if (string[i] == '@') { return 1; } } return 0; } /*************************************************************************************** * Function Name: has_domain(char *string, int lenght) * * Funtion Description: * -This function checks if a string has a correct email domain * * User-interface variables:- * *OUT (Return values): * - bool(1:True,0:False) * *IN (Value Parameters): * - char *string, int lenght * *IN and OUT (Reference Parameters): * - NONE * * History [Date (Author): Description)]:- * 2019-17-01 (Maxwell Gyamfi): checks for correct email domain ******************************************************************************************/ int has_domain(char *string, int lenght) { //local variables int i = 0; int j = 0; char temp[20]; char string_domain[25]; //sets array values to 0; memset(temp, 0, sizeof(temp)); memset(string_domain, 0, sizeof(string_domain)); //email domains char domains[][25] = { "aol.com","att.net","comcast.net","facebook.com","gmail.com", "gmx.com","googlemail.com","google.com","hotmail.com","hotmail.co.uk", "mac.com","me.com", "mail.com","msn.com","live.com","sbcglobal.net", "verizon.net","yahoo.com","yahoo.co.uk","email.com","fastmail.fm", "games.com","gmx.net","hush.com", "hushmail.com","icloud.com", "iname.com","inbox.com","lavabit.com","love.com","outlook.com", "pobox.com","protonmail.com","rocketmail.com","safe-mail.net","wow.com", "ygm.com","ymail.com","zoho.com","yandex.com","hotmail.it","btinternet.com", "virginmedia.com","blueyonder.co.uk","freeserve.co.uk","live.co.uk", "ntlworld.com","o2.co.uk","orange.net","sky.com","talktalk.co.uk", "tiscali.co.uk","virgin.net","wanadoo.co.uk","bt.com","uwe.ac.uk" }; //copy domain starting from '@' character while (string[i] != '\0') { //advance array until character found if (string[i] == '@') { i++; while (string[i] != '\0') { //copy domain to array string_domain[j++] = string[i++]; } break; } i++; } //loops and compare domain to systems domains for (i = 0; i < 56; i++) { strcpy(temp, domains[i]); if (strcmp(string_domain, temp) == 0) { return 1; } } return 0; } /******************************************************************************* * Function Name: get_valid_integer(int minimum, int maximum) * * Funtion Description: * -This function requests a user to input an integer value between a mini- * mum and a maximum. It will prompt the user to re-input integer value and * display a specific error message if wrong input provided. It returns * correct integer value if provided. * * User-interface variables:- * *OUT (Return values): * - int value * *IN (Value Parameters): * - int minimum, int maximum * *IN and OUT (Reference Parameters): * - NONE * * History [Date (Author): Description)]:- * 2019-17-01 (Maxwell Gyamfi): gets valid integer input *******************************************************************************/ int get_valid_integer(int minimum, int maximum) { //local variables int sum = 0; int lenght = 0; int value = 0; int success = 0; char buffer[10]; do { fgets(buffer, sizeof(buffer), stdin);//request string input lenght = get_string_length(buffer);//calculate string lenght buffer[lenght - 1] = '\0'; lenght = lenght - 1; if (isfloat(buffer, lenght))//checks if float value { printf("\nYou entered a float value, please try again(%d-%d): ", minimum, maximum); } else if (!is_integer(buffer, lenght))//checks if special character inputted { printf("\nYou didnt enter an integer, please try again(%d-%d): ", minimum, maximum); } else { value = convert_string_to_integer(buffer, 0, lenght, sum);//convert value to integer if (value< minimum || value > maximum)//changes integer range { printf("\nThe value is out of range, try again(%d-%d): ", minimum, maximum); } else { success = 1; return value; } } } while (success == 0); } /******************************************************************** * Function Name: char get_valid_yes_or_no() * * Funtion Description: * -This function requests a user to input a character 'Y'or 'N' * -Display specific error message and request to re-input correct * input until provided. It will returns the correct character * * User-interface variables:- * *OUT (Return values): * - char input * *IN (Value Parameters): * - NONE * *IN and OUT (Reference Parameters): * - NONE * * History [Date (Author): Description)]:- * 2019-17-01 (Maxwell Gyamfi): gets valid yes or no ***********************************************************************/ char get_valid_yes_or_no() { //local variables char input = 0; int success = 0; do { scanf("%c%*c", &input);//request character and discards scanf buffer if (isalpha(input)) { input = toupper(input);//convert character to upper-case if (input == 'Y' || input == 'N') { success = 1; } else { printf("Wrong input, please input (Y/N): "); } } } while (success == 0); return input; } /******************************************************************** * Function Name: isfloat(char *string,int length) * * Funtion Description: * -This function checks if a '.' character is present in an array * of characters. * * User-interface variables:- * *OUT (Return values): * bool(1:True,0:False) * *IN (Value Parameters): * - char *string,int length * *IN and OUT (Reference Parameters): * - NONE * * History [Date (Author): Description)]:- * 2019-17-01 (Maxwell Gyamfi): checks if string has '.' value ***********************************************************************/ int isfloat(char *string, int length) { //local variable int i = 0; //loops and look for '.' character for (i = 0; i < length; i++) { if (string[i] == '.') { return 1; } } return 0; } /******************************************************************** * Function Name: int is_integer(char *string,int length) * * Funtion Description: * -This function checks if an array of characters contains only * numeric values. * * User-interface variables:- * *OUT (Return values): * bool(1:True,0:False) * *IN (Value Parameters): * - char *string,int length * *IN and OUT (Reference Parameters): * - NONE * * History [Date (Author): Description)]:- * 2019-17-01 (Maxwell Gyamfi): checks if string has '.' value ***********************************************************************/ int is_integer(char *string, int length) { //local variable int i = 0; //loops and checks if all characters in array are numeric for (i = 0; i < length; i++) { if (string[i] >= '0' && string[i] <= '9') {} else { return 0; } } return 1; } /******************************************************************** * Function Name: get_string_length(char *string) * * Funtion Description: * -This function calculates and returns the length of string * * User-interface variables:- * *OUT (Return values): * - int count * *IN (Value Parameters): * - char *string * *IN and OUT (Reference Parameters): * - NONE * * History [Date (Author): Description)]:- * 2019-17-01 (Maxwell Gyamfi): calculates string length ***********************************************************************/ int get_string_length(char *string) { //local variables int count = 0; int i = 0; //increment counts and i until reaches null character while (string[i] != '\0') { count++; i++; } return count; } /************************************************************************************* * Function Name: convert_string_to_integer(char *string,int count,int lenght,int sum) * * Funtion Description: * -This function converts a string of integers into an integer value. It calls the * appropriate switch case based on the lenght and it sums the character with a * power of 10. * * User-interface variables:- * *OUT (Return values): * - int sum * *IN (Value Parameters): * - char *string,int count,int lenght,int sum * *IN and OUT (Reference Parameters): * - NONE * * History [Date (Author): Description)]:- * 2019-17-01 (Maxwell Gyamfi): converts string to integer ***************************************************************************************/ int convert_string_to_integer(char *string, int count, int lenght, int sum) { char arr_value = '\0'; //action selection based on string length switch (lenght) { case 1: //sums array character with case power of 10 value sum = convert_character_to_integer(arr_value, string, sum, 1, count); return sum; break; case 2: sum = convert_character_to_integer(arr_value, string, sum, 10, count); //recursively call function with different array index and reduce string length convert_string_to_integer(string, count + 1, lenght - 1, sum); break; case 3: sum = convert_character_to_integer(arr_value, string, sum, 100, count); convert_string_to_integer(string, count + 1, lenght - 1, sum); break; case 4: sum = convert_character_to_integer(arr_value, string, sum, 1000, count); convert_string_to_integer(string, count + 1, lenght - 1, sum); break; case 5: sum = convert_character_to_integer(arr_value, string, sum, 10000, count); convert_string_to_integer(string, count + 1, lenght - 1, sum); break; case 6: sum = convert_character_to_integer(arr_value, string, sum, 100000, count); convert_string_to_integer(string, count + 1, lenght - 1, sum); break; default: sum = atoi(string);//converts character to integer return sum; break; } } /************************************************************************************* * Function Name: convert_character_to_integer(char character, char *string, int sum, int value,int count) * * Funtion Description: * -This function converts a single character based of array index to integer * -It then multiplys converted value to the power of 10 value based * on case selection and sums to sum variable * User-interface variables:- * *OUT (Return values): * - int sum * *IN (Value Parameters): * - char character, char *string, int sum, int value,int count * *IN and OUT (Reference Parameters): * - NONE * * History [Date (Author): Description)]:- * 2019-17-01 (Maxwell Gyamfi): converts character to integer ***************************************************************************************/ int convert_character_to_integer(char character, char *string, int sum, int value, int count) { int number = 0; character = string[count];//gets character at array index number = character - '0';//converts character to integer sum += (number * value);//multiply number with power of 10 value and add to sum return sum; } /*************************************************************************************** * Function Name: copy_string(char *source, char*destination) * * Funtion Description: * -This function copys one array of characters to another array * * User-interface variables:- * *OUT (Return values): * - NONE * *IN (Value Parameters): * - char *source * *IN and OUT (Reference Parameters): * - char*destination * * History [Date (Author): Description)]:- * 2019-17-01 (Maxwell Gyamfi): copys characters to array ******************************************************************************************/ void copy_string(char *source, char*destination) { //local variable int i = 0; int lenght = get_string_length(source);//calculate string length for (i = 0; i < lenght; i++) { destination[i] = source[i]; } destination[lenght] = '\0'; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* sha.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: uhand <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/10/29 13:53:03 by uhand #+# #+# */ /* Updated: 2020/11/30 12:18:00 by uhand ### ########.fr */ /* */ /* ************************************************************************** */ #include "../includes/sha.h" int ft_sha224(char const *message, t_prc_file *prc, int print, char **digest) { t_block_32 sha; t_read rd; if (digest == NULL) return (-1); ft_bzero(&rd, sizeof(rd)); rd.str_msg = message; rd.prc = prc; rd.print = print; sha224_init(&sha, &rd); sha256_alg(&sha, &rd); sha224_output(&sha, digest); return (1); } int ft_sha256(char const *message, t_prc_file *prc, int print, \ char **digest) { t_block_32 sha; t_read rd; if (digest == NULL) return (-1); ft_bzero(&rd, sizeof(rd)); rd.str_msg = message; rd.prc = prc; rd.print = print; sha256_init(&sha, &rd); sha256_alg(&sha, &rd); sha256_output(&sha, digest); return (1); } int ft_sha384(char const *message, t_prc_file *prc, int print, \ char **digest) { t_block_64 sha; t_read rd; if (digest == NULL) return (-1); ft_bzero(&rd, sizeof(rd)); rd.str_msg = message; rd.prc = prc; rd.print = print; sha384_init(&sha, &rd); sha512_alg(&sha, &rd); sha384_output(&sha, digest); return (1); } int ft_sha512(char const *message, t_prc_file *prc, int print, \ char **digest) { t_block_64 sha; t_read rd; if (digest == NULL) return (-1); ft_bzero(&rd, sizeof(rd)); rd.str_msg = message; rd.prc = prc; rd.print = print; sha512_init(&sha, &rd); sha512_alg(&sha, &rd); sha512_output(&sha, digest); return (1); }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "myhtml.h" int main(){ char buf[256],uid[80],age,male; int len; char* query; // char* method; char* ptr; // char* env; putContentType(); ptr = getenv("REQUEST_METHOD"); if(strcmp(ptr,"GET") == 0){ putHTMLheader("GET Value"); ptr = getenv("QUERY_STRING"); len = strlen(ptr); query = (char*)malloc(len+1); strncpy(query,ptr,len+1); //strncpy(buf,env,sizeof(buf)); }else{ putHTMLheader("POST Value"); ptr = getenv("CONTENT_LENGTH"); len = atoi(ptr); query=(char*)malloc(len+1); fgets(query,len+1,stdin); //fgets(buf,sizeof(buf),stdin); } //strncpy(buf,query,sizeof(buf)); //strncpy(uid,ptr,sizeof(buf)); ptr = strtok(query,"="); ptr = strtok(NULL,"&"); strncpy(uid,ptr,sizeof(uid)); ptr =strtok(NULL, "="); ptr = strtok(NULL,"&"); male = atoi(ptr); ptr = strtok(NULL, "="); ptr = strtok(NULL,"&"); age = atoi(ptr); printf("Your Name: %s <br>", uid); puts("Gender: "); if(male==0){ printf("fe"); } puts("male<br>"); puts("Age: "); switch(age){ case 1: puts("1019"); break; case 2: puts("2029"); break; case 3: puts("30"); break; default: break; } puts("<br>"); putHTMLfooter(); // free (query); return 0; }
C
// һ // 1.5ַ/ // ׼ṩһ/дһַĺ򵥵getcharputchar // ÿεʱgetcharıжһַ뽫Ϊֵء // ÿεputcharʱӡһַ
C
#include "../src/internal.h" #include "test.h" #include "util.h" #include <passwand/passwand.h> #include <stdlib.h> #include <string.h> TEST("encode: encode(\"\")") { const char *empty = ""; char *r; int err = encode((const uint8_t *)empty, strlen(empty), &r); ASSERT_EQ(err, PW_OK); ASSERT_NOT_NULL(r); ASSERT_STREQ(empty, r); free(r); } TEST("encode: basic functionality") { const char *basic = "hello world"; char *r; int err = encode((const uint8_t *)basic, strlen(basic), &r); ASSERT_EQ(err, PW_OK); ASSERT_NOT_NULL(r); ASSERT_STREQ(r, "aGVsbG8gd29ybGQ="); free(r); } TEST("encode: == base64") { char *output; int r = run("printf \"hello world\" | base64", &output); ASSERT_EQ(r, 0); ASSERT_STREQ(output, "aGVsbG8gd29ybGQ=\n"); free(output); }
C
// ユークリッド互除法 # include <stdio.h> int main(){ int a,b,c; a = 3136; b = 126; do{ c = a % b; printf("%4d %% %4d = %4d\n",a,b,c); a = b; b = c; }while(c!=0); // LMC = 最大公約数 printf("LMC=%2d.\n",a); }
C
#include <stdio.h> //avoid putting function inside functions cause compile error void sayHello() { printf("this is a procedure not function cus it returns nothing"); } int main() { //declaring variable int age = 32; const int a; //this is a constrant printf(" hello from c !!! \n "); printf("same thing here \r "); printf(""); //char type printf("char size = %d byte\n", sizeof(char)); printf("char size = %d byte\n", sizeof(unsigned char)); printf("char size = %d byte\n", sizeof(char)); //int type printf("int size = %d byte\n", sizeof(int)); printf("int size = %d byte\n", sizeof(unsigned int)); printf("int size = %d byte\n", sizeof(long int)); //long long //fload double //by default all floating point number are double const float pi = 3.14l; const float pi2= 3.14f; //Enum, this is used to define name constants ie give names to interger constants //enum <name> {enumeration_list}[variable_name]; enum Days { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday } //you can defined it here also ; enum Days Mydays; //defining the data structure Mydays = Sunday; printf("Sunday = %d\n", Mydays); float f = (float)3 / 5; // typecasting sayHello(); getch(); return 0; }
C
#include "test-common.h" static int req_closed; static int write_cb_called; static int shutdown_cb_called; static uv_http_req_t req; static void req_write_client(int fd) { client_send_str("GET /path HTTP/1.1\r\n\r\n"); client_expect_str("HTTP/1.1 200 OK\r\n" "ABC: DEF\r\n" "X-Something: some-value\r\n" "Transfer-Encoding: chunked\r\n\r\n" "9\r\nsome body\r\n" "0\r\n\r\n"); } static void req_close_cb(uv_link_t* req) { req_closed++; } static int req_on_complete(uv_http_req_t* req) { uv_link_close((uv_link_t*) req, req_close_cb); return 0; } static void req_write_cb(uv_link_t* link, int status, void* arg) { CHECK_EQ(status, 0, "status should be zero"); write_cb_called++; } static void req_shutdown_cb(uv_link_t* link, int status, void* arg) { CHECK_EQ(status, 0, "status should be zero"); shutdown_cb_called++; } static void req_on_active(uv_http_req_t* req, int status) { uv_buf_t fields[2]; uv_buf_t values[2]; uv_buf_t msg; uv_buf_t body; CHECK_EQ(status, 0, "status should be zero"); fields[0] = uv_buf_init("ABC", 3); values[0] = uv_buf_init("DEF", 3); fields[1] = uv_buf_init("X-Something", 11); values[1] = uv_buf_init("some-value", 10); msg = uv_buf_init("OK", 2); CHECK_EQ(uv_http_req_respond(req, 200, &msg, fields, values, 2), 0, "uv_http_req_write"); body = uv_buf_init("some body", 9); CHECK_EQ(uv_link_write((uv_link_t*) req, &body, 1, NULL, req_write_cb, NULL), 0, "uv_link_write()"); CHECK_EQ(uv_link_shutdown((uv_link_t*) req, req_shutdown_cb, NULL), 0, "uv_link_shutdown()"); CHECK_EQ(uv_link_read_stop((uv_link_t*) server.http), 0, "uv_read_stop(server)"); } static void req_write_server(uv_http_t* http, const char* url, size_t url_len) { CHECK_EQ(uv_http_accept(http, &req), 0, "uv_http_accept()"); uv_http_req_on_active(&req, req_on_active); req.on_headers_complete = req_on_complete; } TEST_IMPL(req_write) { http_client_server_test(req_write_client, req_write_server); CHECK_EQ(req_closed, 1, "req_closed == 1"); CHECK_EQ(write_cb_called, 1, "write_cb_called == 1"); CHECK_EQ(shutdown_cb_called, 1, "shutdown_cb_called == 1"); }
C
#include "encryptor.h" #include <stdio.h> #include <string.h> #include <stdlib.h> #define S_SIZE 256 void encryptor_ksa(encryptor_t * self); void encryptor_prga(encryptor_t * self, int len); void encryptor_swap_S(encryptor_t * self, int i, int j); void stderr_keystream_hexa_uppercase(encryptor_t *self , int len); void stdin_input_hexa_lowercase(char * input, int len); //key-scheduling void encryptor_ksa(encryptor_t * self){ for (int i=0; i < S_SIZE; i++){ self->S[i] = i; } int keyLen = strlen(self->key); int j = 0; for (int i=0; i < S_SIZE; i++){ j = (j+ self->S[i] + self->key[i % keyLen]) %S_SIZE; encryptor_swap_S(self,i,j); } } //programacion pseudo-aleatoria void encryptor_prga(encryptor_t * self, int len){ int k; for (int index =0; index <len; index++){ self->i = (self->i +1) % S_SIZE; self->j = (self->j +self->S[self->i]) % S_SIZE; encryptor_swap_S(self, self->i, self->j); k = self->S[(self->S[self->i]+self->S[self->j]) % S_SIZE]; self->keystream[index] = k; } } void encryptor_swap_S(encryptor_t * self, int i, int j){ int aux = self->S[i]; self->S[i]= self->S[j]; self->S[j] = aux; } void stderr_keystream_hexa_upperrcase(encryptor_t *self , int len){ for (int i=0; i < len; i++){ fprintf(stderr, "%02hhX", self->keystream[i]); } } void stdin_input_hexa_lowercase(char * input, int len){ for (int i=0; i < len; i++){ printf("%02hhx", input[i]); } } void encryptor_encrypt(encryptor_t * self, char * input, int len){ self-> keystream = (char *)malloc(sizeof(char)*len); encryptor_prga(self, len); for (int i = 0; i < len; i++){ input[i] = input[i] ^ self->keystream[i]; } stdin_input_hexa_lowercase(input, len); stderr_keystream_hexa_upperrcase(self,len); free(self->keystream); } void encryptor_create(encryptor_t * self, const char * key){ self->key = key; self-> i = 0; self-> j = 0; encryptor_ksa(self); } void encryptor_destroy(encryptor_t * self){ }
C
#include<stdio.h> #include<stdlib.h> int main() { int a=0, b=1, c=0; printf("Ingrese el numero del que quiere sacar su factorial\n"); scanf("%d", &a); for (int i = 1; i <= a; i++) { c=b*i; b=c; } printf("El factorial de %d es %d\n", a, c); return 0; }
C
#include "lib.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <limits.h> unsigned long long potencia(int n, int potencia){ unsigned long long resultado = 1; for(int i = 0 ; i < potencia ; i++){ resultado *=n; } return resultado; } bool pilhaVazia(Celula * pilha){ if(pilha == NULL){ return true; }else{ return false; } } void inserirNaPilha(Celula **pilha, char c){ Celula *novo; if(pilhaVazia(*pilha) == true){ novo = malloc(sizeof(Celula)); *pilha = novo; novo->digito = c; novo->prox = NULL; }else{ novo = malloc(sizeof(Celula)); novo->digito = c; novo->prox = *pilha; *pilha = novo; } } void printPilha(Celula *pilha,bool negativo){ bool diferente_zero = false; if(negativo == true){ printf("-"); } while(pilha != NULL){ if(pilha->digito == '0' && diferente_zero ==false){ pilha = pilha->prox; continue; }else{ diferente_zero = true; } printf("%c",pilha->digito); pilha = pilha->prox; } printf("\n"); } bool * validarEntrada(char numero[],char base_entrada[], char base_saida[]){ bool *resposta = malloc(sizeof(bool)*2); resposta[0] = false; resposta[1] = false; bool numero_tem_letra = false; int num_maior_maiusculo = 0; int num_maior_minusculo = 0; int index_alfabeto; int len_numero = strlen(numero); for(int i = 0 ; i < len_numero; i++){ int temp = (int) numero[i]; if(i == 0){ if (!(temp == 45 || (temp>=48 && temp<=57) || (temp>=65 && temp<=90) || (temp>=97 && temp<=122))){ //printf("Numero invalido!\n"); return resposta; } }else{ if (!((temp>=48 && temp<=57) || (temp>=65 && temp<=90) || (temp>=97 && temp<=122))){ //printf("Numero invalido!\n"); return resposta; } } if((temp>=65 && temp<=90) || (temp>=97 && temp<=122)){ numero_tem_letra = true; resposta[1] = true; } if(temp>=65 && temp<=90){ if(temp > num_maior_maiusculo) num_maior_maiusculo = temp; } else if(temp>=97 && temp<=122){ if(temp > num_maior_minusculo) num_maior_minusculo = temp; } } if(numero_tem_letra == true) { num_maior_minusculo -= 32; if (num_maior_minusculo > num_maior_maiusculo) { num_maior_maiusculo = num_maior_minusculo; } index_alfabeto = num_maior_maiusculo - 64; } int len_bEntrada = strlen(base_entrada); for(int i = 0 ; i < len_bEntrada; i++){ int temp = (int) base_entrada[i]; if (!((temp>=48 && temp<=57) )){ //printf("Base entrada invalida!\n"); return resposta; } } int base_entrada_convertida = atoi(base_entrada); if(base_entrada_convertida<2 || base_entrada_convertida>36){ //printf("Base de entrada fora do intervalo 0<BASE<37\n"); return resposta; } int len_bSaida = strlen(base_saida); for(int i = 0 ; i < len_bSaida ; i++){ int temp = (int) base_saida[i]; if (!((temp>=48 && temp<=57))){ //printf("Base saida invalida!\n"); return resposta; } } int base_saida_convertida = atoi(base_saida); if(base_saida_convertida<2 || base_saida_convertida>36){ //printf("Base de saida fora do intervalo 0<BASE<37\n"); return resposta; } if(numero_tem_letra == true){ if(!(index_alfabeto <= (atoi(base_entrada)-10))){ //printf("(Acima de 10) Numero e base de entrada incompativeis!\n"); return resposta; } }else{ int tamanho_numero = strlen(numero); int temp; int base = atoi(base_entrada); for(int i = 0 ; i < tamanho_numero ; i++){ temp = numero[i] -48; if(temp >= base){ //printf("(Abaixo ou igual a 10) Numero e base de entrada incompativeis!\n"); return resposta; } } } resposta[0] = true; return resposta; } int verificarNumero(char c){ if(c >= '0' && c <= '9'){ return (int)c - '0'; }else{ if(c >=97 && c <= 122) { c -= 32; //deixa maiusculo, caso seja minusculo; } return (int)c - 'A' +10; } } unsigned long long converterParaBase10(char numero[],int base_entrada){ unsigned long long numero_convertido = 0; int expoente; int tamanho_string = strlen(numero); if(numero[0] == 45){ expoente = tamanho_string - 2 ; for(int i = 1 ; i < tamanho_string ; i++){ numero_convertido += verificarNumero(numero[i]) * potencia(base_entrada,expoente); expoente--; } }else{ expoente = tamanho_string -1 ; for(int i = 0 ; i < tamanho_string ; i++){ numero_convertido += verificarNumero(numero[i]) * potencia(base_entrada,expoente); expoente--; } } return numero_convertido; } char verificarNumero2(int n){ if(n >= 0 && n <=9){ return (char)n + '0'; }else{ return (char)(n - 10 + 'A'); } } void converterParaBaseM(unsigned long long numero, int base_saida,bool negativo){ Celula *pilha = NULL; int quociente, resto; do{ quociente = numero/base_saida; resto = numero % base_saida; inserirNaPilha(&pilha,verificarNumero2(resto)); numero = quociente; if(numero <(unsigned long)base_saida) inserirNaPilha(&pilha,verificarNumero2(numero)); } while(base_saida <= quociente); printPilha(pilha,negativo); }
C
/* Задача 13. Направете обединение с членове unsigned short и char. Ограничете използваните битове до 6. Инициализирайте и изведете на конзолата. union <tagUnion> { Ctype m_bitField : N; }; */ #include <stdio.h> #include <stdint.h> union myunion { unsigned short Var1:6; int8_t Var2:6; char var3:6; } Shorty; int main(){ Shorty.Var1 = 255; Shorty.Var2 = 126; Shorty.var3 = 'c'; printf("The union limited to 6 bits consists of:\n%d, %d and %c", Shorty.Var1, Shorty.Var2, Shorty.var3); }
C
/** * recover.c * */ #include <stdio.h> #include <stdlib.h> #include <string.h> // prototypes int isjpeg(); int main(int argc, char* argv[]) { // ensure proper usage if (argc != 1) { printf("Usage: ./recover\n"); return 1; } // filename for input file char* infile = "card.raw"; // allocate pointer for output file char* outfile = malloc(strlen("000.jpg") + 1); // open input file FILE* inptr = fopen(infile, "r"); if (inptr == NULL) { printf("Could not open %s.\n", infile); return 2; } FILE* outptr; int BytesToRead = 4; int FAT = 512; unsigned char* byte = malloc(BytesToRead); unsigned char signature[BytesToRead + 1]; int njpeg = 0; unsigned char* jpegbuffer = malloc(FAT - BytesToRead); signature[0] = 0xff; signature[1] = 0xd8; signature[2] = 0xff; signature[3] = 0xe0; signature[4] = 0xef; fread(byte, BytesToRead, 1, inptr); while (njpeg < 1) // Find the first jpeg { // check for first part of signature if (isjpeg(byte, signature)) { // this is a jpeg - do something sprintf(outfile, "%03d.jpg", njpeg); njpeg++; // read the rest of the block fread(jpegbuffer, FAT - BytesToRead, 1, inptr); // open first jpeg file and write first block to it including the first four bytes // open new Jpeg file outptr = fopen(outfile, "w+"); if (outptr == NULL) { fclose(inptr); fprintf(stderr, "Could not create %s.\n", outfile); return 3; } // write the buffer and bytes to the jpeg fwrite(byte, BytesToRead, 1, outptr); fwrite(jpegbuffer, FAT - BytesToRead, 1, outptr); fread(byte, BytesToRead, 1, inptr); // read first four bytes of next block } else { // move back three bytes fseek(inptr, -3, SEEK_CUR); // check the next sequence for signature fread(byte, BytesToRead, 1, inptr); } } while(!feof(inptr)) // now read to end of file { if (isjpeg(byte, signature)) { // close previous jpeg file fclose(outptr); sprintf(outfile, "%03d.jpg", njpeg); njpeg++; // read the rest of the block fread(jpegbuffer, FAT - BytesToRead, 1, inptr); // open first jpeg file and write first block to it including the first four bytes // open new Jpeg file outptr = fopen(outfile, "w+"); if (outptr == NULL) { fclose(inptr); fprintf(stderr, "Could not create %s.\n", outfile); return 3; } // write the buffer and bytes to the jpeg fwrite(byte, BytesToRead, 1, outptr); fwrite(jpegbuffer, FAT - BytesToRead, 1, outptr); fread(byte, BytesToRead, 1, inptr); // read first four bytes of next block } else { // read remainder of block fread(jpegbuffer, FAT - BytesToRead, 1, inptr); // write to existing jpeg including first four bytes fwrite(byte, BytesToRead, 1, outptr); fwrite(jpegbuffer, FAT - BytesToRead, 1, outptr); // read first four bytes of next block fread(byte, BytesToRead, 1, inptr); } } // free allocated memory free(byte); free(jpegbuffer); free(outfile); // close infile fclose(inptr); fclose(outptr); // the end! return 0; } int isjpeg(unsigned char* byte, unsigned char* signature) // must use unsigned as signed takes up more bytes { if ((byte[0] == signature[0]) && (byte[1] == signature[1]) && (byte[2] == signature[2]) && (byte[3] >= signature[3] && byte[3] <= signature[4])) { return 1; } else { return 0; } }
C
#include<stdlib.h> #include<stdio.h> #define SqStackInitSIZE 20 typedef struct { int* data; int top; int capacity; }SqStack; #pragma region SqStackFunctions SqStack* initSqStack(); SqStack* createSqStack(int size); int isEmptySqStack(SqStack* S); int isFullSqStack(SqStack* S); int push(SqStack* S, int value); int pop(SqStack* S, int* get); int* peek(SqStack* S); int clearSqStack(SqStack* S); int destroySqStack(SqStack** S); #pragma endregion SqStack* initSqStack() { SqStack* stack = (SqStack*)malloc(sizeof(SqStack)); stack->data = (int*)malloc(sizeof(int) * SqStackInitSIZE); stack->capacity = SqStackInitSIZE; stack->top = -1; return stack; } SqStack* createSqStack(int size) { SqStack* stack = (SqStack*)malloc(sizeof(SqStack)); stack->data = (int*)malloc(sizeof(int)* size); stack->capacity = size; stack->top = -1; return stack; } int isEmptySqStack(SqStack* S) { if (S == NULL || S->top == -1) return 1; else return 0; } int isFullSqStack(SqStack* S) { if (S == NULL) return 0; else if (S->top + 1 >= S->capacity) return 1; else return 0; } int push(SqStack* S, int value) { if (isFullSqStack(S)) return 0; S->data[++S->top] = value; return 1; } int pop(SqStack* S, int* get) { if(isEmptySqStack(S)) return 0; *get = S->data[S->top--]; return 1; } int* peek(SqStack* S) { if (isEmptySqStack(S)) return NULL; return &(S->data[S->top]); } int clearSqStack(SqStack* S) { if (isEmptySqStack(S)) return 0; S->top = -1; return 1; } int destroySqStack(SqStack** S) { if (!clearSqStack(*S)) return 0; free((*S)->data); (*S)->data = NULL; free(*S); *S = NULL; return 1; }
C
#ifndef LISTA_H_INCLUDED #define LISTA_H_INCLUDED #include"sqlite3.h" typedef struct osoba { char imie[100]; char nazwisko[100]; struct zespoly *ulubione; struct osoba*next; }osoba; typedef struct zespoly { char nazwa[100]; struct zespoly *next; }zespoly; //Funkcja przygotowuje plik "Uzytkownicy.db" do odczytu danych, a nastpnie wywouje funkcj wczytajOsoba, //jej argumentem jest wskanik na pierwszy element listy osoba void wczytaj(osoba ** glowa); //Funkcja wczytuje dane uytkownikw i zapisuje je do list, //jej argumentami s wskanik na otwarty plik "Uzytkownicy.db", liczba kolumn pliku, wskanik na pierwszy element listy osoba void wczytajOsobe(sqlite3_stmt *stmt,int kol, osoba**glowa); //Funkcja wstawia nowo utworzony elemnt listy zespoly na pocztek listy, //jej argumentami s wskanik na pierwszy element listy oraz wskanik na nowo utworzony element void dodajwezelzespoly(struct osoba* nowa, zespoly *nowy); //Funkcja wstawia nowo utworzony elemnt listy osoba na pocztek listy, //jej argumentami s wskanik na pierwszy element listy oraz wskanik na nowo utworzony element void dodajwezelosoby(osoba** glowa, osoba* nowa); //Funkcja dodaje nowy element do listy zespoly, //jej argumentami s pierwszy elemnt listy osoba oraz nazwa zespolu void dodajzespol(osoba** nowa, char nazwa[100]); //Funkcja wywietla list uytkownikw("osoba"), //jej argumentem jest wskanik na pierwszy element listy osoba void wyswietl(struct osoba *glowa); //Funckja wywietla ulubione zespoy danego uytkownika, //jej argumentem jest wskanik na pierwszy element listy zespoly void wyswietlUlub(struct zespoly*glowa); //Funckja usuwa list ulubionych zespow danego uytkownika, //jej argumentem jest wskanik na pierwszy element listy zespoy void usunZespoly(struct zespoly* glowa); //Funkcja usuwa list uytkownikw("osoba"), //jej argumentem jest wskanik na pierwszy element listy void usun(struct osoba* glowa); #endif // LISTA_H_INCLUDED
C
/***************************************** * *A simplest shell written in c lang. * * Basic lifetime of a shell * - Initialize: A typical shell would read and execute its configuration * and execute its configuration files. These change aspects of the shell's behavior. * - Interpret: Next, the shell reads commands from stdin (which could be interactive, or a file) and * executes them. * - Terminate: After its commands are executed, the shell executes any shutdown commands, frees up any * memory, and terminates. * *author: rovo98 *date: 2018.9.3 **********************************************/ #include "simple-shell-in-c.h" #include "func-impl.c" #include <stdio.h> /** @brief Main entry point. @param argc Argument count. @param argv Argument vector. @return status code */ int main() { // Load config files, if any. // Run command loop. lsh_loop(); // Perform any shutdown/cleanup. return 0; }
C
#include<stdlib.h> #include<stdio.h> #include<mysql/mysql.h> MYSQL *conn_ptr; unsigned int timeout = 7; //超时时间7秒 int main(){ //初始化 int ret = 0; //错误返回null conn_ptr = mysql_init(NULL); if(!conn_ptr){ printf("mysql_init failed! line %d\n",__LINE__); return -1; } //设置超时选项,正常返回0 ret = mysql_options(conn_ptr,MYSQL_OPT_CONNECT_TIMEOUT,(const char*)&timeout); if(ret){ printf("Options Set ERRO!\n"); } //连接MySQL testdb数据库,正常返回指针 conn_ptr = mysql_real_connect(conn_ptr,"localhost","root","1245215743","study",0,NULL,0); if(conn_ptr){ printf("Connection Succeed!\n"); //执行sql语句,在数据库表中添加内容,正常返回0 //int mysql_real_query(MYSQL *mysql, const char *q, unsigned long length); ret = mysql_query(conn_ptr,"insert into children(fname,age)values('ann',3)"); /*变量插入示例: int id =11; char name[10]="哈哈"; char sex[3] = "女"; char password[15]="1234456"; char str[200]; sprintf(str,"insert into User values(%d,'%s','%s','%s',%d)",id,name,sex,password,0); rc = mysql_real_query(&mysql,str,strlen(str));*/ if(!ret){ //返回上一次update更改行数 printf("inserted %lu rows\n",(unsigned long)mysql_affected_rows(conn_ptr)); }else{ //返回错误代码,错误消息 printf("Connect Error: %d %s\n",mysql_errno(conn_ptr),mysql_error(conn_ptr)); } //关闭连接 mysql_close(conn_ptr); printf("Connection closed!\n"); }else{ //错误处理 printf("Connection Failed!\n"); if(mysql_errno(conn_ptr)){ printf("Connect Erro:%d %s\n",mysql_errno(conn_ptr),mysql_error(conn_ptr));//返回错误代码、错误消息 } return -2; } return 0; }
C
#include<unistd.h> #include<time.h> #include<stdio.h> #include<malloc.h> #include<stdlib.h> /* Main Function Starts here */ int my_xtime(struct timespec *ktime){ //printf("\n Call to system to display time:"); int ret_value= syscall(326,ktime); if(ret_value != 0){ printf("\nSyscall not executed.\n"); } printf("\nGot time from kernel :%s", ctime(&ktime->tv_sec) ); printf("\n%lld : %lld\n",ktime->tv_nsec, ktime->tv_sec); return 0; } int main(void){ /* timespec *ptr to pass to kernel. give a syscall print the results returned by kernel in the timespec pointer. */ struct timespec *ktime = malloc(sizeof(struct timespec)); int retval= my_xtime(ktime); if(retval != 0){ printf("\napplication level: program showed time.\n"); free(ktime); exit(1); } free(ktime); ktime=NULL; int choice=0; do{ printf("\nSelect a method :\n0. Divide by zero\n1.Pointer Dereference\n2.Infinite recursion\n3.Infinite loop.\n4.Wrong Return Value\n5.kmalloc\n6.Crash\n7.Exit\n.Enter Choice:\t"); scanf("%d",&choice); syscall(327,choice); }while(choice != 7); /* give a call to kernel. it wont retun. */ //syscall(327,0); // divide by zero. killed. //syscall(327,1); // pointer dereference. killed. //syscall(327,2); // stack overflow by infinite recursion. soft lockup. crashed. //syscall(327,3); // system infinite loop. //syscall(327,4); // wrong return value. didnt not panic because of wrong return value. //syscall(327,5); // kmalloc. crash. //syscall(327,6); //crash. return 0; }
C
#include <stdlib.h> #include <limits.h> #ifndef LAPTOP #include <msp430.h> #include "temp_bins.h" #include "temp_thresholds.h" #include "adc_sensor.h" #else #include <stdio.h> #include <assert.h> #include <time.h> #endif #define NUM_BINS 10 /*total number of bins*/ #define USE_LEDS #define FLASH_ON_BOOT /*Need to calibrate to get real values for this*/ const unsigned thresholds[NUM_BINS] = { 10, 20, 30, 40, 50, 60, 70, 80, 90, 0xffff /*last bin is for everything else*/ }; /* These "pinned" variables are fixed at these addresses. */ /*currTemp is a pointer to the current entry in the temp log*/ #ifndef LAPTOP volatile __attribute__((section("FRAMVARS"))) unsigned int __NV_totalSamples; volatile __attribute__((section("FRAMVARS"))) unsigned int inErrorState; volatile __attribute__((section("FRAMVARS"))) unsigned int uninitialized; #else volatile unsigned int __NV_totalSamples; volatile unsigned int inErrorState; static unsigned tempBins[NUM_BINS]; static unsigned tempThresh[NUM_BINS]; unsigned __dino_read__NV_tempBin(unsigned i){ return tempBins[i]; } void __dino_write__NV_tempBin(unsigned i, unsigned v){ tempBins[i] = v; } unsigned __dino_read__NV_tempThresh(unsigned i){ return tempThresh[i]; } void __dino_write__NV_tempThresh(unsigned i, unsigned v){ tempThresh[i] = v; } #endif /*tempLog is a buffer of TEMP_WINDOW NV data entries*/ /*defined in temp_array.h, generated by dinoArrayGen.pl... ugh*/ #ifndef LAPTOP unsigned getOneSample(){ //Read thermometer here unsigned ret = adc12_sample(); return ret; } #endif void abortWithError(){ inErrorState = 1; while(1){ #ifndef LAPTOP #if defined(WISP5) P4OUT |= BIT0; PJOUT |= BIT6; #elif defined(BREADBOARD) P1OUT |= BIT0; #endif //BREADBOARD int i; for (i = 0; i < 0xfff; i++) ; #if defined(WISP5) P4OUT &= ~BIT0; // Toggle P4.4 using exclusive-OR PJOUT &= ~BIT6; // Toggle P4.5 using exclusive-OR #elif defined(BREADBOARD) P1OUT &= ~BIT0; #endif //BREADBOARD #endif //Laptop } } #ifdef LAPTOP void printHisto(){ int q; fprintf(stderr,"<"); for( q = 0; q < NUM_BINS; q++ ){ fprintf(stderr,"(%u, %u)",__dino_read__NV_tempThresh(q),__dino_read__NV_tempBin(q)); } fprintf(stderr,">\n"); } #endif /*We will use __NV_tempBin[] as a list of bins, each of which corresponds to a temperature range. We will use __NV_tempThresh[] as a list of thresholds, each of which is the upper bound of the data value in the corresponding tempBin bin NUM_BINS = 3 thresholds [ 10 | 20 | 30 ] tempthresh [ 0 | 1 | 2 ] tempbins [ 0 | 0 | 0 ] addToBin(15) thresholds [ 10 | 20 | 30 ] tempthresh [ 0 | 1 | 2 ] tempbins [ 0 | 1 | 0 ] swapBins(0,1) thresholds [ 10 | 20 | 30 ] tempthresh [ 1 | 0 | 2 ] <--entry 0 contains "1", a pointer to "20" tempbins [ 1 | 0 | 0 ] <--entry 0 contains "1", the count for "20" and so on. Invariant: temps that contribute to the value in __NV_tempBin[i] were less than __NV_tempBin[i] when they were recorded. each entry in thresholds occurs in exactly one location in __NV_tempThresh[]. the sum of values in __NV_tempBin[] is exactly equal to __NV_totalSamples */ void addToBin(unsigned temp){ /*Fill this out so we pass a value in and get a bin back*/ unsigned i; unsigned thresh = 0xffff; #ifdef LAPTOP fprintf(stderr,"Adding %u\n",temp); #endif for( i = 0; i < NUM_BINS; i++){ /*Look through the sorted list of histogram thresholds...*/ if( temp < thresholds[i] ){ /*thresholds[i] is the threshold for this measurment*/ thresh = thresholds[i]; #ifdef LAPTOP fprintf(stderr,"temp %u is less than %u\n",temp,thresh); #endif break; } } unsigned j; /*Find this threshold in the unsorted list of histogram keys*/ for( j = 0; j < NUM_BINS; j++ ){ unsigned tInd = __dino_read__NV_tempThresh(j);//the index for this key unsigned t = thresholds[tInd];//the key itself /*This key (t) matches the threshold for this measurement (thresholds[i]).*/ if( t == thresh ){ #ifdef LAPTOP fprintf(stderr,"key %u is %u, matching %u, binning %u \n",j,t,thresh,temp); #endif /*Increment the found key's bin's value*/ unsigned binVal = __dino_read__NV_tempBin(j); __dino_write__NV_tempBin(j, binVal+1); return; } } /*If we get here, the measurement has no bin in the histogram, which is an error*/ #ifndef LAPTOP abortWithError(); #else assert(0 && "NO BIN FOR MEASUREMENT"); #endif } void swapBins(int binI, int binJ){ if(binI >= NUM_BINS || binJ >= NUM_BINS ){ return; } unsigned tmpBinVal = __dino_read__NV_tempBin(binI); unsigned tmpThrVal = __dino_read__NV_tempThresh(binI); __dino_write__NV_tempBin(binI, __dino_read__NV_tempBin(binJ)); __dino_write__NV_tempThresh(binI, __dino_read__NV_tempThresh(binJ)); /*A failure here leaves the data structure corrupted!*/ __dino_write__NV_tempBin(binJ, tmpBinVal); __dino_write__NV_tempThresh(binJ, tmpThrVal); } void sortBinsByFrequency(void){ /*InsertionSort: http://en.wikipedia.org/wiki/Insertion_sort*/ unsigned i = 0; for( i = 1; i < NUM_BINS; i++ ){ unsigned j = i; while( j > 0 && __dino_read__NV_tempBin(j-1) > __dino_read__NV_tempBin(j) ){ swapBins(j,j-1); } } } void checkInvariants(void){ unsigned i; unsigned total = 0; unsigned numKeysFound = 0; unsigned keysFound[NUM_BINS]; for( i = 0; i < NUM_BINS; i++ ){ keysFound[i] = 0; } for( i = 0; i < NUM_BINS; i++ ){ total += __dino_read__NV_tempBin(i); unsigned key = __dino_read__NV_tempThresh(i); if( keysFound[key] == 0 ){ keysFound[key] = 1; numKeysFound++; }else{ #ifndef LAPTOP abortWithError(); #else assert(0 && "Duplicate Key Found!"); #endif } } #ifndef LAPTOP if( total != __NV_totalSamples || numKeysFound < NUM_BINS ){ abortWithError(); } #else assert(total == __NV_totalSamples); assert(numKeysFound == NUM_BINS); #endif } void initializeHardware(){ #ifndef LAPTOP #ifdef WISP setupDflt_IO(); PRXEOUT |= PIN_RX_EN; /** TODO: enable PIN_RX_EN only when needed in the future */ // set clock speed to 4 MHz CSCTL0_H = 0xA5; CSCTL1 = DCOFSEL0 | DCOFSEL1; CSCTL2 = SELA_0 | SELS_3 | SELM_3; CSCTL3 = DIVA_0 | DIVS_0 | DIVM_0; /*Before anything else, do the device hardware configuration*/ P4DIR |= BIT0; PJDIR |= BIT6; #if defined(USE_LEDS) && defined(FLASH_ON_BOOT) P4OUT |= BIT0; PJOUT |= BIT6; int i; for (i = 0; i < 0xffff; i++) ; P4OUT &= ~BIT0; // Toggle P4.4 using exclusive-OR PJOUT &= ~BIT6; // Toggle P4.5 using exclusive-OR #endif #ifdef BREADBOARD P1DIR |= BIT0; P1OUT |= BIT0; #if defined(USE_LEDS) && defined(FLASH_ON_BOOT) P1OUT |= BIT0; int i; for (i = 0; i < 0xffff; i++) ; P1OUT &= ~BIT0; #endif #endif #endif #else fprintf(stderr,"Starting Histogram Test\n"); #endif//LAPTOP } void initializeNVData() { #ifndef LAPTOP if( uninitialized == 0 ){ #endif for(int i = 0; i < NUM_BINS; i++){ __dino_write__NV_tempBin(i,0x0); /*The bin corresponding to the ith threshold is in the ith position to start*/ __dino_write__NV_tempThresh(i,i); } __NV_totalSamples = 0; uninitialized = 1; #ifndef LAPTOP } #endif } #ifndef LAPTOP __attribute__((section(".init9"), aligned(2))) #endif int main(void){ #ifndef LAPTOP WDTCTL = WDTPW | WDTHOLD; // Stop watchdog timer PM5CTL0 &= ~LOCKLPM5; #endif initializeHardware(); initializeNVData(); if( inErrorState == 1 ){ abortWithError(); } #ifdef LAPTOP srand(time(NULL)); #endif while(1){ addToBin((rand() % 100)); #ifdef LAPTOP printHisto(); #endif __NV_totalSamples++; sortBinsByFrequency(); #ifdef LAPTOP fprintf(stderr,"sorted:\n"); printHisto(); #endif checkInvariants(); } }
C
/* Small S3M player written as AICA firmware * * (c)2000 Dan Potter * * Notes on using: * * To use this player, you just need to load your S3M into sound RAM * at 0x10000, and then load this program into the ARM CPU. This program * will then parse the S3M into samples and tracks, etc, and start * playing it. To stop the playback, use dc_snd_stop_arm() in libdream. */ /****************** Timer *******************************************/ extern volatile int timer; void timer_wait(int jiffies) { int fin = timer + jiffies; while (timer <= fin) ; } /****************** Main Program ************************************/ volatile unsigned long *s3mwait = (unsigned long*)0x1002c; volatile unsigned long *debug = (unsigned long*)0xffc0; int arm_main() { *debug = 1; /* Check to see that there's an S3M waiting */ /*while (*s3mwait != 0x77826783) { int i; volatile unsigned long *tmp = (unsigned long *)0; for (i=0; i<5000; i++) { *tmp; } } */ *debug = 2; /* Initialize the AICA part of the SPU */ aica_init(); *debug = 3; /* Load the S3M */ s3m_load(); *debug = 4; /* Start playback */ s3m_start_playback(); }
C
#include<reg51.h> //sbit pin1=P2^0; //sbit pin2=P2^1; void uart_ins() { TMOD = 0x20; // use timer 1 8-bit auto reload moad TH1 = 0xfd; // 9600 bord rate SCON = 0x50; // use 8-bit 1 start bit 1 stop bit TR1 = 1; // start timer 1 } void uart_send(unsigned char uart_data) { SBUF = uart_data; while(TI == 0); TI = 0; } char uart_receive() { unsigned char uart_data; while(RI == 0); uart_data = SBUF; RI = 0; return(uart_data); } void uart_sends(unsigned char *string) { while(*string) { uart_send(*string++); } } void name(unsigned char n) { char a[]={0xfe,0xfd,0xfb,0xf7,0xef},b[5]; // char a[]={0x01,0x02,0x04,0x08,0x10},b[5]; int i,j,k; // while(*n!='\0') // { switch(n) { case 'A': { b[0]=0x10; b[1]=0x76; b[2]=0x76; b[3]=0x76 ; b[4]=0x01; break; } case 'B': { b[0]=0x00; b[1]=0x36; b[2]=0x36; b[3]=0x36 ; b[4]=0x41; break; } case 'C': { b[0]=0x00; b[1]=0x3e; b[2]=0x3e; b[3]=0x3e ; b[4]=0x3e; break; } case 'D': { b[0]=0x00; b[1]=0x3e; b[2]=0x3e; b[3]=0x3e ; b[4]=0x41; break; } case 'E': { b[0]=0x00; b[1]=0x36; b[2]=0x36; b[3]=0x36 ; b[4]=0x36; break; } case 'F': { b[0]=0x00; b[1]=0x76; b[2]=0x76; b[3]=0x76 ; b[4]=0x76; break; } case 'G': { b[0]=0x40; b[1]=0x5a; b[2]=0x5a; b[3]=0x42 ; b[4]=0x7b; break; } case 'H': { b[0]=0x00; b[1]=0x77; b[2]=0x77; b[3]=0x77 ; b[4]=0x00; break; } case 'I': { b[0]=0x3e; b[1]=0x3e; b[2]=0x00; b[3]=0x3e ; b[4]=0x3e; break; } case 'J': { b[0]=0x3e; b[1]=0x3e; b[2]=0x00; b[3]=0x7e ; b[4]=0x7e; break; } case 'K': { b[0]=0x00; b[1]=0x77; b[2]=0x6b; b[3]=0x5d ; b[4]=0x3e; break; } case 'L': { b[0]=0x00; b[1]=0x3f; b[2]=0x3f; b[3]=0x3f ; b[4]=0x3f; break; } case 'M': { b[0]=0x00; b[1]=0x7d; b[2]=0x7b; b[3]=0x7d ; b[4]=0x00; break; } case 'N': { b[0]=0x00; b[1]=0x7d; b[2]=0xe3; b[3]=0x5f ; b[4]=0x00; break; } case 'O': { b[0]=0x00; b[1]=0x3e; b[2]=0x3e; b[3]=0x3e ; b[4]=0x00; break; } case 'P': { b[0]=0x80; b[1]=0xf6; b[2]=0xf6; b[3]=0xf6 ; b[4]=0xf9; break; } case 'Q': { b[0]=0xf1; b[1]=0xee; b[2]=0xe6; b[3]=0x86 ; b[4]=0xb1; break; } case 'R': { b[0]=0x00; b[1]=0xee; b[2]=0xce; b[3]=0xbe ; b[4]=0x39; break; } case 'S': { b[0]=0x30; b[1]=0x36; b[2]=0x36; b[3]=0x36 ; b[4]=0x06; break; } case 'T': { b[0]=0xfe; b[1]=0xfe; b[2]=0x00; b[3]=0xfe ; b[4]=0xfe; break; } case 'U': { b[0]=0xc0; b[1]=0x3f; b[2]=0x3f; b[3]=0x3f ; b[4]=0xc0; break; } case 'V': { b[0]=0x60; b[1]=0x5f; b[2]=0x3f; b[3]=0x5f ; b[4]=0x60; break; } case 'W': { b[0]=0x00; b[1]=0x5f; b[2]=0x6f; b[3]=0x5f ; b[4]=0x00; break; } case 'X': { b[0]=0x1c; b[1]=0x6b; b[2]=0x77; b[3]=0x6b ; b[4]=0x1c; break; } case 'Y': { b[0]=0x7e; b[1]=0x7d; b[2]=0x03; b[3]=0x7d ; b[4]=0x7e; break; } case 'z': { b[0]=0x1e; b[1]=0x2e; b[2]=0x36; b[3]=0x3a ; b[4]=0x3c; break; } case ' ': { b[0]=0x00; b[1]=0x00; b[2]=0x00; b[3]=0x00 ; b[4]=0x00; } } for(i=0;i<5;i++) { for(j=0;j<5;j++) { P0=b[j]; P1=a[j]; for(k=0;k<5;k++); P0=0xff ; P1=0x00; } } n++ ; } //} /* void display(unsigned char str_dis[]) { unsigned char k; for(k=str_dis[k];k>0;k--) { pin1=1; pin2=1; name(str_dis[k]) ; pin1=0; pin2=1; name(str_dis[k]) ; pin1=1; pin2=0; name(str_dis[k]) ; pin1=0; pin2=0; name(str_dis[k]) ; } } */ void main() { unsigned char d[10],i,a ; P0=0xff; P1=0x00; P2=0X00; uart_ins(); while(1) { d[i]=uart_receive(); i++; if(i>=9) { while(1) { for(i=0 ; i<5 ;i++) { P2=i; a=d[i]; // display(s[i]); name(a); } } } } }
C
/* readdir.c */ #include <stdio.h> #include <errno.h> #include <sys/types.h> #include <dirent.h> #include <unistd.h> #include <fcntl.h> #include <sys/stat.h> int main(int argc, char **argv) { DIR *dirp; // open directory descriptor struct dirent *dp; // directory entry pointer FILE *outfile; // html file to be rendered char *t; if ( argc < 2 ) { fputs("A pathname argument is required.\n", stderr); return 1; } dirp = opendir(argv[1]); // open the dir if ( !dirp ) { perror("opendir(3)"); return 1;; } errno = 0; // open output file if ( (outfile = fopen ("list.html", "w")) == NULL) { printf("<!> Error creating %s\n", "out.txt"); // Client unable to create output file return 1; } fprintf (outfile,"<html>\n"); // write to file while( (dp = readdir(dirp)) != NULL) { fprintf (outfile,"<br><a href=%s>%s</a>", dp->d_name,dp->d_name); errno = 0; } if ( errno != 0) perror("readdir(3)"); fprintf (outfile,"<br><p>This page is being served by kern_httpd 0.1 (2004)</p>"); fprintf (outfile,"</html>\n"); // tidy up fclose(outfile); if( closedir(dirp) == -1 ) perror("closedir(3)"); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> void main(int argc, char *argv[]) { FILE *fp; int c; fp = fopen(argv[1], "w"); c = fgetc(stdin); while(c!=EOF){ fputc(c, fp); c = fgetc(stdin); } fclose(fp); }
C
#include <stdio.h> #include <stdlib.h> struct Node { int data; struct Node* next; }; typedef struct Node Myn; typedef Myn * P; struct Node* head; //global void insert(int x) { // using type def P tmp =(p)malloc(sizeof(Myn)); // add 1st elemen insert at begining .t // no using typedef // struct Node* tmp =(struct Node*)malloc(sizeof(struct Node)); tmp ->data = x; tmp->next = NULL; // head = tmp; // when it is empty // add emel when not emptybuild Need to set the next of new node to preous's next if(head !=NULL) tmp->next = head;// let new node point to the node where old head point to // for null head, no need do previous step head = tmp; // only need put head at tmp } void print() { struct Node* p= head; while ( p !=NULL) // for (int j=0; j<n ; j++) { printf("%d", p->data); p = p->next; } printf("/n"); } int main() { // create head node head = NULL; int n, i, x; scanf("%d:", &n); for(i =0; i <n; i++) { printf("enter the number \n"); scanf("%d:", &x); insert(x); print(); } }
C
#include<stdio.h> int main(){ int n, i, j, dem, count=0; int a[100]; int b[100]; scanf("%d", &n); for(i=0;i<n;i++) scanf("%d", &a[i]); for(i=0;i<n;i++){ dem=0; for(j=0;j<n;j++){ if(a[i]==a[j]&&i!=j) dem=1; } if(dem==0){ printf("%d ", a[i]); count++; } } if(count==0) printf("0"); return 0; }
C
/* * @Descripttion: exec查看网络配置 * @Author: Altair * @Date: 2020-04-22 14:47:19 */ #include <stdio.h> #include <unistd.h> #include <errno.h> #include <string.h> int main(int argc, char *argv[]) { if (execl("/sbin/ifconfig", "/sbin/ifconfig", NULL) == -1) //如果execl()返回-1,就表明它执行失 if (execlp("ipconfig", "ipconfig", NULL) == -1) { fprintf(stderr, "Cannot run ipconfig: %s", strerror(errno)); return 1; } return 0; }
C
// Unit test for the discardCard() method. // Business requirements: // discardCard() gets called whenever there is a need to remove a card to the player's hand. // The card should be sent to the trash pile if (and only if) that is specified. // Only the hand should be affected. // Discarding from the front, middle, and end of the hand should work. // No other player's hand should be affected. // The players discard and deck piles should not be affected. #include <stdlib.h> #include <stdio.h> #include <assert.h> #include "dominion.h" #include "dominion_helpers.h" void discardCardTest(int totalHandCount, int handPos, int player, int trashFlag){ struct gameState state; // Initialize the played card count if not trashing if (trashFlag < 1) state.playedCardCount = 0; state.handCount[player] = totalHandCount; state.deckCount[player] = 0; state.discardCount[player] = 0; state.handCount[player + 1] = 0; // Set all hards in hand to smithy to initialize them int c = 0; for (; c < totalHandCount; c++){ // Set to following ard so we can later check that it was pushed back state.hand[player][c] = smithy; } // Set the card in question to sea_hag so we can later check and ensure it // was discarded (set to -1) or set to smithy if it wasn't the last card in the hand. state.hand[player][handPos] = sea_hag; discardCard(handPos, player, &state, trashFlag); // The card should be sent to the trash pile if (and only if) that is specified. if (trashFlag < 1) assert(state.playedCardCount == 1); assert(state.hand[player][handPos] != sea_hag); // If we are discarding the one and only hard in the hand, it should be reset to -1. // If we are discarding the last card, it should also be reset to -1. // Otherwise it should be the smithy card if (totalHandCount == 1 || handPos == totalHandCount - 1){ // Only the hand should be affected. assert(state.hand[player][handPos] == -1); } else { // Only the hand should be affected. assert(state.hand[player][handPos] == smithy); } // The players discard and deck piles should not be affected. assert(state.deckCount[player] == 0); assert(state.discardCount[player] == 0); // No other player's hand should be affected. assert(state.handCount[player + 1] == 0); } int main(int argc, char *argv[]){ // Discarding from the front, middle, and end of the hand should work. // Start with the case where there is only one card in the hand. discardCardTest(1, 0, 0, 0); discardCardTest(1, 1, 0, 0); discardCardTest(1, 0, 1, 0); discardCardTest(1, 0, 0, 1); // Now do cases where there are 3 cards in the hand and we want to remove the first discardCardTest(3, 0, 0, 0); discardCardTest(3, 0, 1, 0); discardCardTest(3, 0, 0, 1); // Now do cases where there are 3 cards in the hand and we want to remove the middle discardCardTest(3, 1, 0, 0); discardCardTest(3, 1, 0, 1); discardCardTest(3, 1, 1, 0); discardCardTest(3, 1, 0, 1); // Now do cases where there are 3 cards in the hand and we want to remove the last discardCardTest(3, 2, 0, 0); discardCardTest(3, 2, 0, 1); discardCardTest(3, 2, 1, 0); discardCardTest(3, 2, 0, 1); printf("\tunittest3: PASS\r\n"); return 0; }
C
/* xparsecfg * tool to parse configuration file. * current tool have static predefined parameter. * this tool is a layered one. * gcc xparsecfg.c -Wall -ggdb3 -o xparsecfg */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "parserclass.h" #include "filecfgparser.h" #include "stduserparser.h" int cleanup () { FILE *fnull = fopen ("/dev/null", "w"); int c = 0; while ((c = fgetc (stdin)) != 0x0a) ; ungetc(c, stdin); fclose (fnull); return 0; } int printlistname(PLIST plist) { PL_ITEM pl_item; if (!plist) return 0; fprintf (stdout, "print list member of [%s]\n", plist->l_item.class.name); while ((pl_item = plist->take(plist)) != NULL) { fprintf (stdout, "l_item [%s]", pl_item->class.name); pl_item->class.preparedelete(&pl_item->class); free (pl_item); pl_item = NULL; } fprintf (stdout, "\n"); return 0; } int main (int argc , char **argv) { FILE *fp = NULL; char tokenlist [] ="[]#\n="; PLIST root = 0; PMINIPARSER pfile, pstdio; if (argc < 2) { fprintf (stderr, "usage %s filename\n", argv[0]); exit (-1); } fp = fopen (argv[1], "r"); if (!fp) { fprintf (stderr,"err file %s\n", argv[1]); exit (-1); } pfile = newminiparser (fp, tokenlist, infile_parse); if (root ) { fprintf (stdout, "num_root_elmt : %d \n", root->count); } pfile->parse (pfile,&root); fclose (fp); pstdio = newminiparser (stdin, " \n", stdin_parse); pstdio->parse (pstdio,&root); /* root->l_item.class.preparedelete(&root->l_item.class); */ free(root); exit (0); }
C
#include "lexer.h" /* * TODO Implement escaping */ // maybe TODO maybe rollout homemade strlen /* * An array of keywords */ char* theKeywords[] = { "int", "char", "long", "void", "short", "for", "if", "while", "else", "switch", "case", "default", "break", "continue" }; /* * Find if a string buf begins with a string candid * Return 0 on false, length of candid on true * TODO: care for \0 */ int beginsWith(char buf[], char candid[]){ int x; if(buf == 0 || candid == 0) return 0; if(strlen(buf) < strlen(candid)) return 0; for (x = 0; x < strlen(buf) && x < strlen(candid); x++){ if(buf[x] == candid[x]) continue; return 0; } return strlen(candid); } int bufFail(char buf[]){ return buf == 0 || strlen(buf) < 1; } /* * matches a keyword from the array above * return length of matched keyword * TODO: set return type * TODO: maybe deglobalize and parameterize theKeywords * probably not if we want to maintain the match func(buf) interface */ match matchKeyword(char buf[]){ match theMatch; theMatch.type = 0; theMatch.length = 0; int i; for (i=0; i < sizeof(theKeywords)/sizeof(theKeywords[0]); i++){ if(!beginsWith(buf, theKeywords[i])){ continue; } theMatch.length = strlen(theKeywords[i]); theMatch.type = 1; return theMatch; } return theMatch; } int isAlphaOrUnderscore(char x){ return (x >= 'A' && x <= 'Z') || (x >= 'a' && x <= 'z') || x == '_'; } int isDigit(char x){ return x <= '9' && x >= '0'; } match matchComment(char buf[]){ match theMatch; theMatch.type = 0; theMatch.length = 0; if (bufFail(buf)) return theMatch; if(!beginsWith(buf, "/*")) return theMatch; int i; for(i=1; i < strlen(buf); i++){ if(buf[i-1] == '*' && buf[i] == '/'){ // shouldn't require a type for this // just eat it theMatch.length = i+1; return theMatch; } } return theMatch; } /* matchString and matchLiteral are mergable*/ match matchString(char buf[]){ match theMatch; theMatch.type = 0; theMatch.length = 0; if (bufFail(buf)) return theMatch; if(!beginsWith(buf, "\"")) return theMatch; int i; for(i=1; i < strlen(buf); i++){ if(buf[i] == '"'){ theMatch.length = i+1; return theMatch; } } return theMatch; } /* matchString and matchLiteral are mergable*/ match matchLiteral(char buf[]){ match theMatch; theMatch.type = 0; theMatch.length = 0; if (bufFail(buf)) return theMatch; if(!beginsWith(buf, "'")) return theMatch; int i; for(i=1; i < strlen(buf); i++){ if(buf[i] == '\''){ theMatch.length = i+1; return theMatch; } } return theMatch; } match matchSymbol(char buf[]){ match theMatch; theMatch.type = 0; theMatch.length = 0; if (bufFail(buf)) return theMatch; if(!isAlphaOrUnderscore(buf[0])) return theMatch; int i; for (i=0; i < strlen(buf); i++){ if(!(isAlphaOrUnderscore(buf[i]) || isDigit(buf[i]))) break; } theMatch.length = i; // TODO set type return theMatch; } match matchwhiteSpace(char buf[]){ match theMatch; theMatch.type = 0; theMatch.length = 0; if (bufFail(buf)) return theMatch; int i; for(i = 0; i < strlen(buf); i++){ if(buf[i] != '\n' && buf[i] != '\t' && buf[i] != ' ' && buf[i] != '\r') break; } theMatch.length = i; return theMatch; } typedef struct{ char punct; int type; }TcharIntEl; match matchSinglePunctuation(char buf[]){ match theMatch; theMatch.type = 0; theMatch.length = 0; TcharIntEl puncmap[] = { {'{', KURLYOPEN}, {'}', KURLYCLOSE}, {'(', PARENOPEN}, {')', PARENCLOSE}, {'[', SQUAREOPEN}, {']', SQUARECLOSE}, {',', COMMA}, {'-', MINUS}, {'+', PLUS}, {'/', DIV}, {'*', MULT}, {'~', TILDE}, {'!', EXC}, {'%', PERC}, {'^', XOR}, {'&', AMP}, {'|', OR}, {'=', EQ}, {'?', BM} }; if (bufFail(buf)) return theMatch; theMatch.length = 1; /* TODO: we'de ideally be using a map here */ for(int i = 0; i < sizeof(puncmap)/sizeof(puncmap[0]); i++){ if(buf[0] == puncmap[i].punct){ theMatch.type = puncmap[i].type; return theMatch; } } theMatch.length = 0; return theMatch; } /* * TODO: the idea is to go through all the matcher functions * that `implement` the matcher interface */ int lex(char buf[]){ match (*func[1])(char buf[]) = { &matchKeyword }; match zz = func[0](buf); printf("%d", zz.length); }
C
#include <stdio.h> #include <libxml/parser.h> #include <libxml/tree.h> int main(int argc, char **argv) { xmlDocPtr doc = NULL; //ļָ xmlNodePtr root_node = NULL; xmlNodePtr sk_node = NULL, ipport_node = NULL;//ڵָ xmlNodePtr dm_node = NULL, name_node = NULL;//ڵָ // һļԼһڵ doc = xmlNewDoc(BAD_CAST "1.0"); root_node = xmlNewNode(NULL, BAD_CAST "socket"); xmlDocSetRootElement(doc, root_node); //һڸڵӽڵ sk_node = xmlNewNode(NULL, BAD_CAST "socket_type"); xmlNewProp(sk_node, BAD_CAST "type", BAD_CAST "common"); xmlAddChild(root_node, sk_node); ipport_node = xmlNewChild(sk_node, NULL, BAD_CAST "IP_port", BAD_CAST"192.168.15.22:1234"); ipport_node = xmlNewChild(sk_node, NULL, BAD_CAST "IP_port", BAD_CAST"192.168.15.22:2345"); //ͨxmlNewProp()һڵ dm_node = xmlNewNode(NULL, BAD_CAST "socket_type"); xmlNewProp(dm_node, BAD_CAST "type", BAD_CAST "domain"); xmlAddChild(root_node, dm_node); //ڵһַ name_node = xmlNewChild(dm_node, NULL, BAD_CAST "name", BAD_CAST"cl_domain_socket"); name_node = xmlNewChild(dm_node, NULL, BAD_CAST "name", BAD_CAST"co_domain_socket"); //save the xml file xmlSaveFormatFileEnc("w.xml", doc, "UTF-8", 1); /*free the document */ xmlFreeDoc(doc); xmlCleanupParser(); xmlMemoryDump();//debug memory for regression tests return(0); }
C
#include <stdio.h> #include <stdlib.h> #include <time.h> #include "dijkstra.h" #include "floyd.h" #define ANSI_COLOR_CYAN "\x1b[36m" #define ANSI_COLOR_RESET "\x1b[0m" int G[][5] = { {0, 10, 0, 30, 100,}, {10, 0, 50, 0, 0, }, {0, 50, 0, 20, 10, }, {30, 0, 20, 0, 60, }, {100, 0, 10, 60, 0, }, }; int H[28][28] = {{0}}; void test_1(); void test_2(); void test_3(); void test_4(); void initGraph(); void initGraph(){ //58 H[1][0] = 10;// H[1][2] = 5;// H[2][1] = 5;// H[0][3] = 5;// H[3][2] = 10;// H[3][4] = 2;// H[2][5] = 2;// H[5][2] = 2;// H[5][4] = 10;// H[4][7] = 1;// H[4][6] = 2;// H[6][12] = 4;// H[5][8] = 3;// H[8][5] = 3;// H[8][7] = 9;// H[8][10] = 2;// H[10][8] = 2;// H[7][11] = 2;// H[11][10] = 9;// H[10][16] = 2;// H[16][10] = 2;// H[11][13] = 1;// H[13][16] = 8;// H[16][15] = 4;// H[12][13] = 2;// H[13][12] = 2;// H[13][14] = 1;// H[15][13] = 3;// H[15][14] = 2;// H[16][19] = 2;// H[19][16] = 2;// H[14][20] = 1;// H[20][19] = 6;// H[19][22] = 2;// H[22][19] = 2;// H[20][21] = 2;// H[22][21] = 5;// H[22][26] = 2;// H[26][22] = 2;// H[26][27] = 6;// H[27][26] = 6;// H[21][27] = 2;// H[10][9] = 6;// H[9][17] = 2;// H[17][9] = 2;// H[16][17] = 6;// H[17][16] = 6;// H[17][18] = 2;// H[18][17] = 2;// H[19][18] = 6;// H[18][23] = 2;// H[23][18] = 2;// H[23][22] = 6;// H[23][24] = 2;// H[24][23] = 2;// H[24][26] = 6;// H[26][24] = 6;// H[25][26] = 4;// H[26][25] = 4;// } int* getMeta(int half){ static int a[3]; a[0] = sizeof(H)/sizeof(H[0]); if(half == 0){ printf("\nStarting station no. >>"); scanf("%d", &a[1]); printf("\nEnding station no. >>"); scanf("%d", &a[2]); } return a; } void test_1(){ clock_t start; double timeTaken = 0; int *a = getMeta(0); start = clock(); printf("\n\n** Dijkstra's Algorithm **\n"); dijkstra(&H[0][0], *a, *(a + 1), *(a + 2), 0); timeTaken = (double) clock() - start / CLOCKS_PER_SEC; printf(ANSI_COLOR_CYAN "Time taken: %f\n\n" ANSI_COLOR_RESET, timeTaken); start = clock(); printf("\n\n** Floyd Warshall's Algorithm **\n"); floydWarshall(&H[0][0], *a, *(a + 1), *(a + 2), 0); timeTaken = (double) clock() - start / CLOCKS_PER_SEC; printf(ANSI_COLOR_CYAN "Time taken: %f\n\n" ANSI_COLOR_RESET, timeTaken); } void test_2(){ int n, num; clock_t start; double timeTaken = 0; int *a = getMeta(1); n = *a; printf("Enter number of tests to run >>"); scanf("%d", &num); start = clock(); printf("\n\n** Dijkstra's Algorithm **\n"); for(int i = 0; i < num; i++){ dijkstra(&H[0][0], n, (rand() % (n-1)) + 1, (rand() % (n-1)) + 1, 1); } timeTaken = (double) clock() - start / CLOCKS_PER_SEC; printf(ANSI_COLOR_CYAN "Time taken: %f\n\n" ANSI_COLOR_RESET, timeTaken); start = clock(); printf("\n\n** Floyd Warshall's Algorithm **\n"); for(int i = 0; i < num; i++){ floydWarshall(&H[0][0], n, (rand() % (n-1)) + 1, (rand() % (n-1)) + 1, 1); } timeTaken = (double) clock() - start / CLOCKS_PER_SEC; printf(ANSI_COLOR_CYAN "Time taken: %f\n\n" ANSI_COLOR_RESET, timeTaken); } void test_3(){ int n, num; clock_t start1, start2; double timeTaken = 0; int *a = getMeta(1); n = *a; printf("Enter number of tests to run >>"); scanf("%d", &num); start1 = clock(); printf("\n\n** Dijkstra's Algorithm **\n"); for(int i = 0; i < num; i++){ dijkstra(&H[0][0], n, (rand() % (n-1)) + 1, (rand() % (n-1)) + 1, 1); } timeTaken = (double) clock() - start1 / CLOCKS_PER_SEC; printf(ANSI_COLOR_CYAN "Time taken: %f\n\n" ANSI_COLOR_RESET, timeTaken); start2 = clock(); printf("\n\n** Floyd Warshall's Algorithm **\n"); floydWarshallM(&H[0][0], n); for(int i = 0; i < num; i++){ getPaths(n, (rand() % (n-1)) + 1, (rand() % (n-1)) + 1, 1); } timeTaken = (double) clock() - start2 / CLOCKS_PER_SEC; printf(ANSI_COLOR_CYAN "Time taken: %f\n\n" ANSI_COLOR_RESET, timeTaken); } void test_4(){ int ch = 0; Chckpt2: printf("\n\tEnter one of the following - \n\t( 1 ) Dijkstra's Algorithm\n\t( 2 ) Floyd Warshall's algorithm\n\t"); scanf("%d", &ch); int *a = getMeta(0); switch(ch){ case 1: dijkstra(&H[0][0], *a, *(a + 1), *(a + 2), 0); break; case 2: floydWarshall(&H[0][0], *a, *(a + 1), *(a + 2), 0); break; default: printf("Not a valid option. Try again ..."); goto Chckpt2; break; } } int main(){ initGraph(); int ch = 0; Chckpt: printf("\n\tEnter one of the following - \n\t( 1 ) Single test\n\t( 2 ) Multiple tests\n\t( 3 ) Multiple tests with Optimisation\n\t( 4 ) Test with individual algorithms\n\t"); scanf("%d", &ch); switch(ch){ case 1: test_1(); break; case 2: test_2(); break; case 3: test_3(); break; case 4: test_4(); break; default: printf("Not a valid option. Try again ..."); goto Chckpt; break; } return 0; }
C
// Luis Ivan // Hill Cipher // This program converts plain text in to encrypted text // when provided with a cipher key of "n" length. // "n" can not be any larger than 9 or smaller than 2 /* matrix multiplaction and hill key cipher math encrypt |d|e|f| |a| (d*a + e*b + f*c)%26 |m| |g|h|i| * |b| = (g*a + h*b + i*c)%26 = |n| |j|k|l| |c| (j*a + k*b + l*c)%26 |o| */ #include <stdio.h> #include <stdlib.h> #include <string.h> int main(int argc, char *argv[]) { FILE *eKeyFile = NULL; FILE *ptextFile = NULL; int *keyBuffer=NULL; char *ptextBuffer=NULL; char *etextBuffer=NULL; char *etext=NULL; char temp; int e=0; int index,key,count,row,col,ecount; int i=0,j=0,k; int charCap = 10000; int capacity = 82; int size = 0; keyBuffer=malloc(sizeof(int)*capacity); ptextBuffer=malloc(sizeof(char)*charCap); // encryption key file will store a single positive integer, // n (1 < n < 10), number of rows and columns in matrix // "r" = open for reading if ((eKeyFile = fopen(argv[1], "r")) == NULL) { fprintf(stderr, "Could not open %s in main()!\n", argv[1]); exit(0); } // character array of size 10000, // the text files no more than 9991 letters if ((ptextFile = fopen(argv[2], "r")) == NULL) { fprintf(stderr, "Could not open %s in main()!\n", argv[2]); exit(0); } // stores the key while (fscanf(eKeyFile, "%d" , keyBuffer+size)!=EOF) { key=keyBuffer[0]; size++; } for(j=size; j<capacity; j++ ) { keyBuffer[j]=-1; } i=0; // takes in every character and determines if letter // if letter is capital it is converted to lower case while (fscanf(ptextFile, "%c" , ptextBuffer+i)!=EOF) { temp=ptextBuffer[i]; // 65 - 90 A - Z // 97 - 122 a - z if(temp>=65&&temp<=90) { ptextBuffer[i]=temp+32; i++; } if(temp>=97&&temp<=123) i++; } index=i; // we have to make sure that the index is a factor // of key[0] if not we need to padd with x's ptextBuffer // index is how many letters taken in while(index%key!=0) { ptextBuffer[index]=0; ptextBuffer[index]='x'; index++; } // creating the encrypted text buffer etext=malloc(sizeof(char)*index); // size of key array count=0; ecount=1; // this is supposed to do matrix multiplication Hill style while(count<index) { // rows of the matrix for(row=0;row< key;row++) { // columns of the matrix k=count; for(col=0;col< key;col++) { if(ecount==(key*key+1)) ecount=1; e=(int)e+((int)ptextBuffer[k++]-97)*(keyBuffer[ecount]); ecount++; if(ecount==(key*key+1)) ecount=1; } // mod26 makes sure the text is from 0 to 25 // which correlates to the letters of the alphabet etext[row+count]=e%26+'a'; e=0; } ecount=1; count=key+count; } // prints out the key printf("\nKey matrix:\n\n"); for(i=1;i<size;i++) { printf("%d ", keyBuffer[i]); if(i%key==0) printf("\n"); } printf("\n"); printf("\nPlaintext:\n\n"); // this one prints out the text for (i=0;i<index;i++) { printf("%c", ptextBuffer[i]); if(i%80==79) printf("\n"); } printf("\n\n"); printf("\nCiphertext:\n\n"); // this one prints out encrypted text for (i=0;i<index;i++) { printf("%c", etext[i]); if(i%80==79) printf("\n"); } printf("\n\n"); fclose(eKeyFile); fclose(ptextFile); free(keyBuffer); free(ptextBuffer); free(etext); return 0; }
C
#include<stdio.h> #include<string.h> int i=0,j=0,k=0,z=0,length=0; char stk[15], input[50]; char left[50][50], right[50][50], temp[5], str[50]; int rule, stk_idx, inp_idx; int is_operator(char ch){ if(ch=='+' || ch=='-' || ch=='*' || ch=='/' || ch=='^' || ch=='(' || ch==')') return 1; return 0; } int main() { freopen("input.txt", "r", stdin); int i,j,k; //printf("How many production: "); scanf("%d", &rule); //printf("Enter the grammar:\n"); for(i=0;i<rule;i++){ scanf("%s%s%s", left[i], temp, right[i]); } //printf("Input: "); scanf("%s", str); int len = strlen(str); strcpy(input, str); printf("Stack\t\tInput\t\tAction\n"); printf("======= =============== =============\n"); printf("$\t\t%s$\n",str); stk[0] = '\0'; while(1){ if(inp_idx==len) break; char cur[50]; int c = 0; if(is_operator(str[inp_idx])){ cur[c++] = str[inp_idx]; cur[c] = '\0'; inp_idx++; } else{ while(inp_idx<len && !is_operator(str[inp_idx])){ cur[c++] = str[inp_idx]; inp_idx++; } cur[c] = '\0'; } printf("$%s%s\t\t",stk, cur); for(i=inp_idx;i<len;i++) printf("%c", input[i]); printf("$\t\tShift %s\n",cur); if(strcmp(cur,")")==0){ char temp[50]; for(i=strlen(stk)-1;i>=0;i--){ if(stk[i]=='(') break; } j = i; int t = 0; for(;i<strlen(stk);i++){ temp[t++] = stk[i]; } temp[t] = ')'; temp[t+1] = '\0'; strcpy(cur, temp); stk[j] = '\0'; //printf("%s!!\n", cur); } while(1){ int reduce = 0; for(i=0;i<rule;i++){ if(strcmp(cur, right[i])==0){ printf("$%s%s\t\t",stk,left[i]); for(j=inp_idx;j<len;j++) printf("%c", input[j]); printf("$\t\tReduce %s\n", cur); strcpy(cur, left[i]); reduce = 1; break; } } if(reduce==0) break; } strcat(stk,cur); while(1){ int reduce = 0; for(i=0;i<rule;i++){ if(strcmp(stk, right[i])==0){ printf("$%s\t\t",left[i]); for(j=inp_idx;j<len;j++) printf("%c", input[j]); printf("$\t\tReduce %s\n", stk); strcpy(stk, left[i]); reduce = 1; break; } } if(reduce==0) break; strcpy(cur, stk); } } if(strlen(stk)==1) printf("The given string is accepted\n"); else printf("The given string is not accepted\n"); return 0; }
C
#include <stdio.h> #include <unistd.h> #include <sys/types.h> #include <sys/wait.h> int main() { int ret = fork(); int childID = getpid(); int parentID = getppid(); if(ret == 0 ) { printf("Child \n"); exit(0); } else { wait(NULL); printf("Child ID : %d \n", childID); } }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <assert.h> #include <ctype.h> #include <time.h> #include "mspms2.h" /** * Check if any dihedral, angle, bond share the same ending pairs. */ int InitCheckUniques() { int mm, ii, jj; PSAMPLE_MOLECULE pSampleMole; int iFirst_Dih, iLast_Dih, iFirst_Agl, iLast_Agl, iFirst_Bnd, iLast_Bnd; // Check unique for dihedrals. // This is for possible ring structures where 1,4 atoms can form multiple dihedrals. // e.g. 1-2-3-4 // \5-6/ // 1234 and 1564 // The 14 pair should only be calculated once for energy/force. // That is what the unique check is for. for (mm=0;mm<nspecie;mm++) { pSampleMole = sample_mole + mm; for (ii=0;ii<pSampleMole->ndih;ii++) { pSampleMole->isDih_unique[ii] = true; } for (ii=0; ii<pSampleMole->ndih-1; ii++) // ii diehdral { if (pSampleMole->isDih_unique[ii]) { for (jj=ii+1; jj<pSampleMole->ndih; jj++) // jj dihedral { if (pSampleMole->isDih_unique[jj]) { if ((pSampleMole->dih_idx[ii][0]==pSampleMole->dih_idx[jj][0] && pSampleMole->dih_idx[ii][3]==pSampleMole->dih_idx[jj][3]) || (pSampleMole->dih_idx[ii][0]==pSampleMole->dih_idx[jj][3] && pSampleMole->dih_idx[ii][3]==pSampleMole->dih_idx[jj][0])) { pSampleMole->isDih_unique[jj] = false; fprintf( fpouts, "Sample molecule %d: Dihedral %d and dihedral %d have the same ending pairs.\n", mm, ii, jj); } // Check uniqueness } // End if dihedral jj is unique } // End of dihedral jj } // End if dihedral ii is unique } // End of Dihedral ii // following codes make sure 14 and 13 do not share same ending pairs // this is also for ring kind structures for (ii=0; ii<pSampleMole->ndih; ii++) { if (pSampleMole->isDih_unique[ii]) { for (jj=0; jj<pSampleMole->nangle; jj++) { if ((pSampleMole->dih_idx[ii][0]==pSampleMole->agl_idx[jj][0] && pSampleMole->dih_idx[ii][3]==pSampleMole->agl_idx[jj][2]) || (pSampleMole->dih_idx[ii][0]==pSampleMole->agl_idx[jj][2] && pSampleMole->dih_idx[ii][3]==pSampleMole->agl_idx[jj][0])) { pSampleMole->isDih_unique[jj] = false; fprintf( fpouts, "Sample molecule %d: Dihedral %d and angle %d have the same ending pairs.\n", mm, ii, jj); } // Check uniqueness } // End of Angle loop } // If dihedral is unique } // End of Dihedral loop // following codes make sure 14 and 12 do not share the same ending pairs for (ii=0; ii<pSampleMole->ndih; ii++) { if (pSampleMole->isDih_unique[ii]) { for (jj=0; jj<pSampleMole->nbond; jj++) { if ((pSampleMole->dih_idx[ii][0]==pSampleMole->bnd_idx[jj][0] && pSampleMole->dih_idx[ii][3]==pSampleMole->bnd_idx[jj][1]) || (pSampleMole->dih_idx[ii][0]==pSampleMole->bnd_idx[jj][1] && pSampleMole->dih_idx[ii][3]==pSampleMole->bnd_idx[jj][0])) { pSampleMole->isDih_unique[jj] = false; fprintf( fpouts, "Sample molecule %d: Dihedral %d and bond %d have the same ending pairs.\n", mm, ii, jj); } // End of check of uniqueness } // End of Bond loop } // End if dihedral unique } // End of dihedral loop // check unique for angles // see above comments for dihedrals for (ii=0; ii<pSampleMole->nangle; ii++) { pSampleMole->isAngle_unique[ii] = true; } for (ii=0; ii<pSampleMole->nangle-1; ii++) { if (pSampleMole->isAngle_unique[ii]) { for (jj=ii+1; jj<pSampleMole->nangle; jj++) { if (pSampleMole->isAngle_unique[jj]) { if ((pSampleMole->agl_idx[ii][0]==pSampleMole->agl_idx[jj][0] && pSampleMole->agl_idx[ii][2]==pSampleMole->agl_idx[jj][2]) || (pSampleMole->agl_idx[ii][0]==pSampleMole->agl_idx[jj][2] && pSampleMole->agl_idx[ii][2]==pSampleMole->agl_idx[jj][0])) { pSampleMole->isAngle_unique[jj] = false; fprintf( fpouts, "Sample molecule %d: Angle %d and angle %d have the same ending pairs.\n", mm, ii, jj); } // Check the angle uniqueness } // End angle jj uniqueness } // End of angle jj loop } // End angle ii uniqueness } // End of angle ii loop // following codes make sure 13 and 12 do not share the same ending pairs for (ii=0; ii<pSampleMole->nangle; ii++) { if (pSampleMole->isAngle_unique[ii]) { for (jj=0; jj<pSampleMole->nbond; jj++) { if ((pSampleMole->agl_idx[ii][0]==pSampleMole->bnd_idx[jj][0] && pSampleMole->agl_idx[ii][2]==pSampleMole->bnd_idx[jj][1]) || (pSampleMole->agl_idx[ii][0]==pSampleMole->bnd_idx[jj][1] && pSampleMole->agl_idx[ii][2]==pSampleMole->bnd_idx[jj][0])) { pSampleMole->isAngle_unique[jj] = false; fprintf( fpouts, "Sample molecule %d: Angle %d and bond %d have the same ending pairs.\n", mm, ii, jj); } // End of angle uniqueness check } // End of bond loop } // End of Angle uniqueness } // End of Angle loop } return 0; } /** * Initialize velocities */ int velinit() { int ii; double px, py, pz; double stdvtmp, stdv; int specie_id, sample_atom_id; px = py = pz = 0.0; // mv^2=kT, So, p = sqrt(kTm), v = sqrt(kT/m) // Use reduced units, v* = sqrt(T*/m*) stdvtmp = sqrt(treq); for (ii=0; ii<natom; ii++) { // From index ii, we calculate which specie this atom belongs to and // its position within a molecule get_specie_and_relative_atom_id(ii, &specie_id, &sample_atom_id); stdv = stdvtmp/sqrt(sample_mole[specie_id].aw[sample_atom_id]); vx[ii] = stdv*gaussran(); vy[ii] = stdv*gaussran(); vz[ii] = stdv*gaussran(); px += vx[ii]*sample_mole[specie_id].aw[sample_atom_id]; py += vy[ii]*sample_mole[specie_id].aw[sample_atom_id]; pz += vz[ii]*sample_mole[specie_id].aw[sample_atom_id]; } // zero the momentum px /= system_mass; py /= system_mass; pz /= system_mass; for (ii=0; ii<natom; ii++) { get_specie_and_relative_atom_id(ii, &specie_id, &sample_atom_id); vx[ii] -= px; vy[ii] -= py; vz[ii] -= pz; } px = 0.0; py = 0.0; pz = 0.0; for (ii=0; ii<natom; ii++) { // From index ii, we calculate which specie this atom belongs to and // its position within a molecule get_specie_and_relative_atom_id(ii, &specie_id, &sample_atom_id); px += vx[ii]*sample_mole[specie_id].aw[sample_atom_id]; py += vy[ii]*sample_mole[specie_id].aw[sample_atom_id]; pz += vz[ii]*sample_mole[specie_id].aw[sample_atom_id]; } // Calculate the energy and instantaneous temperature ukin = 0.0; for (ii=0; ii<natom; ii++) { get_specie_and_relative_atom_id(ii, &specie_id, &sample_atom_id); ukin += sample_mole[specie_id].aw[sample_atom_id]*(vx[ii]*vx[ii]+vy[ii]*vy[ii]+vz[ii]*vz[ii]); } ukin = 0.5*ukin; tinst = 2.0*ukin/nfree; // Rescale velocity for required temperature double scaling; scaling = sqrt(treq/tinst); for (ii=0; ii<natom; ii++) { vx[ii] *= scaling; vy[ii] *= scaling; vz[ii] *= scaling; } // recalculate the kinetic energy and instantaneous temperature // should be exactly the set tempature ukin = 0.0; for (ii=0; ii<natom; ii++) { get_specie_and_relative_atom_id(ii, &specie_id, &sample_atom_id); ukin += sample_mole[specie_id].aw[sample_atom_id]*(vx[ii]*vx[ii]+vy[ii]*vy[ii]+vz[ii]*vz[ii]); } ukin = 0.5*ukin; tinst = 2.0*ukin/nfree; return 0; } // Read and initialize the necessary variables for HMC int init_hmc() { int ii; char buffer[LONG_STRING_LENGTH]; char keyword[100]; int position_counter; fprintf(stderr,"Reading input data for HMC simulation...\n"); fprintf(fpouts, "Reading input data for HMC simulation...\n"); // re-open input file to read extra data section fpins = fopen(INPUT,"r"); while (fgets(buffer, LONG_STRING_LENGTH, fpins)!=NULL) { sscanf(buffer, "%s", keyword); for (ii=0; ii<strlen(keyword); ii++) { keyword[ii] = toupper(keyword[ii]); } if (!strcmp(keyword, "HMC")) { fprintf(stderr,"Data section for HMC simulation found...\n"); fprintf(fpouts, "Data section for HMC simulation found...\n"); sscanf(fgets(buffer, LONG_STRING_LENGTH, fpins), "%d", &nstep_md_per_hmc); sscanf(fgets(buffer, LONG_STRING_LENGTH, fpins), "%lf", &pdisp); sscanf(fgets(buffer, LONG_STRING_LENGTH, fpins), "%lf", &pvolm); sscanf(fgets(buffer, LONG_STRING_LENGTH, fpins), "%lf", &pmake); sscanf(fgets(buffer, LONG_STRING_LENGTH, fpins), "%lf", &pkill); sscanf(fgets(buffer, LONG_STRING_LENGTH, fpins), "%lf", &rreq_disp); sscanf(fgets(buffer, LONG_STRING_LENGTH, fpins), "%lf", &rreq_volm); sscanf(fgets(buffer, LONG_STRING_LENGTH, fpins), "%lf", &delv); sscanf(fgets(buffer, LONG_STRING_LENGTH, fpins), "%d", &nstep_delt_adj_cycle); sscanf(fgets(buffer, LONG_STRING_LENGTH, fpins), "%d", &nstep_delv_adj_cycle); // Read insertion/deletion input data if required if (pmake+pkill > 0.0) { for (ii=0; ii<nspecie; ii++) { sscanf(fgets(buffer, LONG_STRING_LENGTH, fpins), "%lf %lf", &cpt[ii], &pcomp[ii]); // initialize zact zact[ii] = exp(cpt[ii]/treq)*boxv; } } // Allocate memory for saving positions _safealloc(xx_old,natom,sizeof(double)) ; _safealloc(yy_old,natom,sizeof(double)) ; _safealloc(zz_old,natom,sizeof(double)) ; fclose(fpins); return 0; } // if keyword found } // read through the lines fprintf(stderr,"Error: Data for HMC simulation not found.\n"); fprintf(fpouts, "Error: Data for HMC simulation not found.\n"); fclose(fpins); exit(1); } /// Read parameters from the input file for MDNVT and initialize the variables needed for NVT simulation int init_nvt() { int ii; char buffer[LONG_STRING_LENGTH]; char keyword[100]; fprintf(stderr,"Reading input data for MD NVT simulation...\n"); fprintf(fpouts, "Reading input data for MD NVT simulation...\n"); // re-open input file to read extra data section fpins = fopen(INPUT,"r"); while (fgets(buffer, LONG_STRING_LENGTH, fpins)!=NULL) { sscanf(buffer, "%s", keyword); for (ii=0; ii<strlen(keyword); ii++) { keyword[ii] = toupper(keyword[ii]); } if (!strcmp(keyword, "MDNVT")) { fprintf(stderr,"Data section for MD NVT simulation found...\n"); fprintf(fpouts, "Data section for MD NVT simulation found...\n"); sscanf(fgets(buffer, LONG_STRING_LENGTH, fpins), "%lf %lf", &qq, &qqs); /** * Qts = RGAS*treq*nfree/Omega * where Omega is a parameter related to the mass of the thermostat * for this program, we read in the Qts directly. */ // variables for nose-hoover NVT, see frenkel and smit delt_sqby2 = delt*delt/2.0; delts_sqby2 = delts*delts/2.0; unhts = 0.0; gg = nfree; // need double check ss = 0.0; ps = 0.0; ggs = nfree; sss = 0.0; pss = 0.0; unhtss = 0.0; fclose(fpins); return 0; } // if keyword found } // read through lines fprintf(stderr,"Error: data for MD NVT not found.\n"); fprintf(fpouts, "Error: data for MD NVT not found.\n"); fclose(fpins); exit(1); } // Read and initialize NPT related variables int init_npt_respa() { int ii; char buffer[LONG_STRING_LENGTH]; char keyword[100]; fprintf(stderr,"Reading input data for MD NPT simulation...\n"); fprintf(fpouts, "Reading input data for MD NPT simulation...\n"); // re-open input file to read extra data section fpins = fopen(INPUT,"r"); while (fgets(buffer, LONG_STRING_LENGTH, fpins)!=NULL) { sscanf(buffer, "%s", keyword); for (ii=0; ii<strlen(keyword); ii++) { keyword[ii] = toupper(keyword[ii]); } if (!strcmp(keyword, "MDNPT")) { fprintf(stderr,"Data section for MD NPT simulation found...\n"); fprintf(fpouts, "Data section for MD NPT simulation found...\n"); sscanf(fgets(buffer, LONG_STRING_LENGTH, fpins), "%lf %lf", &Qts, &Qbs); // thermo/barostat utsbs = 0.0; vts = sqrt((nfree+1.0)/Qts); vbs = sqrt((nfree+1.0)/Qbs); rts = 0.0; utsbs = 0.5*Qbs*vbs*vbs + 0.5*Qts*vts*vts + (nfree+1)*treq*rts + preq*boxv; fclose(fpins); return 0; } // if keyword found } // read through lines fprintf(stderr,"Error: data for MD NPT not found.\n"); fprintf(fpouts, "Error: data for MD NPT not found.\n"); fclose(fpins); exit(1); } /// Read in electrostatic parametes and initialize related variables int init_charge() { int ii; char buffer[LONG_STRING_LENGTH]; char keyword[100]; fprintf(stderr,"Reading input data for Electrostatic interactions...\n"); fprintf(fpouts, "Reading input data for Electrostatic interactions...\n"); // re-open input file to read extra data section fpins = fopen(INPUT,"r"); while (fgets(buffer, LONG_STRING_LENGTH, fpins)!=NULL) { sscanf(buffer, "%s", keyword); for (ii=0; ii<strlen(keyword); ii++) { keyword[ii] = toupper(keyword[ii]); } if (!strcmp(keyword, "ELECTROSTATIC")) { fprintf(stderr,"Data section for electrostatics found...\n"); fprintf(fpouts, "Data section for electrostatics found...\n"); if (iChargeType == ELECTROSTATIC_EWALD) { sscanf(fgets(buffer, LONG_STRING_LENGTH, fpins), "%lf", &kappa); sscanf(fgets(buffer, LONG_STRING_LENGTH, fpins), "%d", &KMAXX); sscanf(fgets(buffer, LONG_STRING_LENGTH, fpins), "%d", &KMAXY); sscanf(fgets(buffer, LONG_STRING_LENGTH, fpins), "%d", &KMAXZ); sscanf(fgets(buffer, LONG_STRING_LENGTH, fpins), "%d", &KSQMAX); sscanf(fgets(buffer, LONG_STRING_LENGTH, fpins), "%d", &fEwald_BC); sscanf(fgets(buffer, LONG_STRING_LENGTH, fpins), "%d", &fEwald_Dim); // Initialization // set ewald parameters kappa = kappa*sigma_base; // Reduce the kappa kappasq = kappa*kappa; Bfactor_ewald = 1.0/(4.0*kappa*kappa); Vfactor_ewald = 2.0*pi/(boxlx*boxly*boxlz); TWOPI_LX = 2.0*pi/boxlx; TWOPI_LY = 2.0*pi/boxly; TWOPI_LZ = 2.0*pi/boxlz; // 1D ewald constant twopi_over_3v = 2.0*pi/3.0/boxlx/boxly/boxlz; } else if (iChargeType == ELECTROSTATIC_WOLF) { sscanf(fgets(buffer, LONG_STRING_LENGTH, fpins), "%lf", &kappa); // set wolf parameters kappa = kappa*sigma_base; // Reduce the kappa wolfvcon1 = -erfc(kappa*rcutoffelec)/rcutoffelec; wolfvcon2 = erfc(kappa*rcutoffelec)/rcutoffelecsq + 2.0*kappa *exp(-(kappa *rcutoffelec)*(kappa*rcutoffelec)) /(sqrt(pi) *rcutoffelec); wolfvcon3 = kappa/sqrt(pi)+erfc(kappa*rcutoffelec)/(2.0*rcutoffelec); wolffcon1 = 2.0*kappa/sqrt(pi); wolffcon2 = -wolfvcon2; } else if (iChargeType == ELECTROSTATIC_SIMPLE_COULOMB) { } // calculate the reduced coulomb constant coulomb_prefactor = COULOMB_PREFACTOR/epsilon_base/sigma_base; fclose(fpins); return 0; } // if keyword found } // read through lines fprintf(stderr,"Error: data for electrostatics not found.\n"); fprintf(fpouts, "Error: data for electrostatics not found.\n"); fclose(fpins); exit(1); } int InitLJlrcCommonTerms() { // Calculate the common terms for LJ lrc int ii, jj; int mm, nn; double uljlrc_term1, uljlrc_term2; double pljlrc_term1, pljlrc_term2; int atomid_1, atomid_2; double sigmaij, epsilonij; double temp1, temp2, temp3; // set lrc to zero even long range correction is not needed just in case uljlrc = 0.0; pljlrc = 0.0; uljlrc_term1 = (8.0/9.0)*pi*pow(rcutoff, -9.0); uljlrc_term2 = -(8.0/3.0)*pi*pow(rcutoff, -3.0); pljlrc_term1 = (32.0/9.0)*pi*pow(rcutoff, -9.0); pljlrc_term2 = -(16.0/3.0)*pi*pow(rcutoff, -3.0); // calculate long range correction terms for single molecules for (mm=0; mm<nspecie; mm++) { for (nn=0; nn<nspecie; nn++) { uljlrc_term[mm][nn] = 0.0; pljlrc_term[mm][nn] = 0.0; // loop through the atoms in one molecule of specie mm for (ii=0; ii<sample_mole[mm].natom; ii++) { // use the first molecule of one specie to do the calculation atomid_1 = ii; // loop through all the atoms in one molecule of specie nn for (jj=0; jj<sample_mole[nn].natom; jj++) { atomid_2 = jj; sigmaij = 0.5*(sample_mole[mm].sigma[atomid_1]+sample_mole[nn].sigma[atomid_2]); epsilonij = sqrt(sample_mole[mm].epsilon[atomid_1]*sample_mole[nn].epsilon[atomid_2]); temp1 = pow(sigmaij, 9.0)*uljlrc_term1 + pow(sigmaij, 3.0)*uljlrc_term2; temp2 = epsilonij*pow(sigmaij, 3.0); temp3 = pow(sigmaij, 9.0)*pljlrc_term1 + pow(sigmaij, 3.0)*pljlrc_term2; uljlrc_term[mm][nn] += temp1*temp2; pljlrc_term[mm][nn] += temp3*temp2; } // through all atom in one molecule of specie 2 } // through all atom in one molecule of specie 1 } // loop through specie 2 } // loop through speice 1 return 0; } /// Initiate variables /** * Initialize the real atom, bond, angle, dihedral, improper, non-bonded list * using Samples. * Initialize the readin variables. * Readin additional data section according to the simulation and ensemble * type. * Check the uniqueness for dihedrals and angles. * Calculate the long range corrections. */ int init_vars() { int ii, jj, kk; fprintf(stderr,"Initializing variables...\n"); fprintf(fpouts, "Initializing variables...\n"); for (ii=0;ii<natom;ii++) { fxl[ii] = fyl[ii] = fzl[ii] = 0.0; fxs[ii] = fys[ii] = fzs[ii] = 0.0; } uvdw = 0.0; ushift = 0.0; uelec = 0.0; ureal = 0.0; uexcl = 0.0; ucoulomb = 0.0; virial_inter = 0.0; uinter = 0.0; ubond = 0.0; uangle = 0.0; udih = 0.0; uimp = 0.0; virial_intra = 0.0; uintra = 0.0; /// Initiate file variables, LOG, TRAJECTORY\n /// Output file is initialized already at the very beginning of the run. fplog = fopen(LOG,"w"); fptrj = fopen(TRAJECTORY,"wb"); /// Calculate molecule weight for the real list. system_mass = 0.0; for (ii=0; ii<nspecie; ii++) { system_mass += sample_mole[ii].mw*nmole_per_specie[ii]; } /// Zero the number of frames in trajectory file. nframe = 0; /// Set the starting step to 1, will be changed by load it if it is continue run. /// istep is used for printit, the first print should be at step zero. istep = 0; nstep_start = 1; // Set the proper end step to eq steps or data taking steps nstep_end = (nstep_eq>0) ? nstep_eq : nstep; // Zero the counts and accums rezero(); /// initialize random number generator rmarin(ij, jk); /// calculate the degree of freedom nfree = 3*natom - nconstraint; // cutoff related rcutoffsq = rcutoff*rcutoff; rcutoffelecsq = rcutoffelec*rcutoffelec; rcutonsq = rcuton*rcuton; roff2_minus_ron2_cube = (rcutoffsq-rcutonsq)*(rcutoffsq-rcutonsq) *(rcutoffsq-rcutonsq); // shift energies, use rcutoff shift1 = pow((1/rcutoff), 6.0); shift4 = 4.0*shift1; // volume calculation boxv = boxlx*boxly*boxlz; // delt related deltby2 = delt/2.0; delts = delt/nstep_inner; deltsby2 = delts/2.0; dt_outer2 = deltby2; dt_outer4 = delt/4.0; dt_outer8 = delt/8.0; // Check if any bond, angle, dihedral share the same ending pairs. InitCheckUniques(); if (what_simulation == MOLECULAR_DYNAMICS) { } else if (what_simulation == HYBRID_MONTE_CARLO) // initialize HMC input data { init_hmc(); } else if (what_simulation == SIMULATED_ANNEALING) { init_siman(); } // initialize velocities for needed simulations fprintf(stderr, "initializing velocities...\n"); fprintf(fpouts, "initializing velocities...\n"); velinit(); // initialize thermostat/baron stat input data if (what_ensemble == NVT) { init_nvt(); } else if (what_ensemble == NPT) { init_npt_respa(); } // If Solid-fluid interaction is required, initiliaze the related variables. if (iSF_type==SF_NANOTUBE_HYPERGEO) { init_sf_hypergeo(); } else if (iSF_type==SF_NANOTUBE_ATOM_EXPLICIT) { init_sf_atom_explicit(); } else if (iSF_type==SF_NANOTUBE_TASOS) { init_tasos_grid(); } else if (iSF_type==SF_NANOTUBE_MY_INTERP) { init_my_interp(); } // Read in electrostatic parametes and initialize if needed if (iChargeType != ELECTROSTATIC_NONE) { init_charge(); } // Initialize the common terms and calculate LJ lrc if it is requested. if (isLJlrcOn) { fprintf(stderr,"calculating LJ long range corrections...\n"); fprintf(fpouts, "calculating LJ long range corrections...\n"); // Initialize common terms InitLJlrcCommonTerms(); // calculate the total lj lrc calculate_ljlrc(); } // if not new run, load from old file if (iStart_option!=NEW) { loadit(); } return 0; }
C
#include "TPO.h" int AgregarNodoUsuario(USU *usuario, NodeUser *root) { NodeUser *current=root; int id=1; if(current==NULL){ root = (NodeUser*)malloc(sizeof(NodeUser)); root->user=*usuario; root->user.id=id; return id; } while(current->nxt!=NULL){ current=current->nxt; } current->nxt=(NodeUser*)malloc(sizeof(NodeUser)); current->nxt->user=*usuario; id=(current->user.id)++; current->nxt->user.id=id; return id; } //Revisar!!
C
//switch~case ޴ #include <stdio.h> void one(int x) { puts("\n 1.one \n"); } void two(int x) { puts("\n 2.two \n"); } void three(int x) { puts("\n 3.three \n"); } void four(int x) { puts("\n 4.four \n"); } int main(void) { int number; puts("\n *޴ * \n"); while (1) { printf(" ȣ ϼ[0 to quit]:"); scanf_s("%d", &number); if (number == 0) return; switch (number) { case 1: one(number); break; case 2: two(number); break; case 3: three(number); break; case 4: four(number); break; default: printf("%d ȣ Դϴ \n", number); } } return 0; }
C
#include "newi2c.h" void I2C_WriteByte(I2C_TypeDef * I2Cx,uint8_t slave_addr,uint8_t reg_addr, uint8_t data) { while (I2C_GetFlagStatus(I2Cx, I2C_FLAG_BUSY)) ; I2C_GenerateSTART(I2Cx, ENABLE); //开启I2Cx while (!I2C_CheckEvent(I2Cx, I2C_EVENT_MASTER_MODE_SELECT)) ; /*EV5,主模式*/ I2C_Send7bitAddress(I2Cx, slave_addr, I2C_Direction_Transmitter); //器件地址 while (!I2C_CheckEvent(I2Cx, I2C_EVENT_MASTER_TRANSMITTER_MODE_SELECTED)) ; I2C_SendData(I2Cx, reg_addr); //寄存器地址 while (!I2C_CheckEvent(I2Cx, I2C_EVENT_MASTER_BYTE_TRANSMITTED)) ; I2C_SendData(I2Cx, data); //发送数据 while (!I2C_CheckEvent(I2Cx, I2C_EVENT_MASTER_BYTE_TRANSMITTED)) ; I2C_GenerateSTOP(I2Cx, ENABLE); //关闭I2Cx总线 } void I2C_ReadData(I2C_TypeDef * I2Cx, uint8_t slave_addr, uint8_t reg_addr, uint8_t *pBuffer, uint16_t NumByteToRead) { // I2C读取数据串(器件地址,寄存器,内部地址,数量) while (I2C_GetFlagStatus(I2Cx, I2C_FLAG_BUSY)) ; I2C_GenerateSTART(I2Cx, ENABLE); //开启信号 while (!I2C_CheckEvent(I2Cx, I2C_EVENT_MASTER_MODE_SELECT)) ; //清除 EV5 I2C_Send7bitAddress(I2Cx, slave_addr, I2C_Direction_Transmitter); //写入器件地址 while (!I2C_CheckEvent(I2Cx, I2C_EVENT_MASTER_TRANSMITTER_MODE_SELECTED)) ; //清除 EV6 I2C_Cmd(I2Cx, ENABLE); I2C_SendData(I2Cx, reg_addr); //发送读的地址 while (!I2C_CheckEvent(I2Cx, I2C_EVENT_MASTER_BYTE_TRANSMITTED)) ; //清除 EV8 I2C_GenerateSTART(I2Cx, ENABLE); //开启信号 while (!I2C_CheckEvent(I2Cx, I2C_EVENT_MASTER_MODE_SELECT)) ; //清除 EV5 I2C_Send7bitAddress(I2Cx, slave_addr, I2C_Direction_Receiver); //将器件地址传出,主机为读 while (!I2C_CheckEvent(I2Cx, I2C_EVENT_MASTER_RECEIVER_MODE_SELECTED)) ; //清除EV6 while (NumByteToRead) { if (NumByteToRead == 1) { //只剩下最后一个数据时进入 if 语句 I2C_AcknowledgeConfig(I2Cx, DISABLE); //最后有一个数据时关闭应答位 I2C_GenerateSTOP(I2Cx, ENABLE); //最后一个数据时使能停止位 } if (I2C_CheckEvent(I2Cx, I2C_EVENT_MASTER_BYTE_RECEIVED)) { //读取数据 *pBuffer = I2C_ReceiveData(I2Cx); //调用库函数将数据取出到 pBuffer pBuffer++; //指针移位 NumByteToRead--; //字节数减 1 } } I2C_AcknowledgeConfig(I2Cx, ENABLE); }
C
#include <cs50.h> #include <ctype.h> #include <stdio.h> #include <string.h> // could int main(void) { // store string to name string name = GetString(); // takes the first letter and puts to upper case printf("%c", toupper(name[0])); // increments through string places, use 'n' to keep tidy for ( int i = 0, n = strlen(name); i < n; i++) { // if a value in the string has a space...and not end of text if ( name[i] == ' ' && name[i + 1] != '\0') { // make the next one a capital printf("%c",toupper(name[i + 1])); i++; } } // after end print out new line printf("\n"); }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> struct cadastro { char nome[50]; int codigo; float sal; }; int main() { FILE *fp; FILE *new; struct cadastro func[3]; char ch; int x; fp = fopen("exerc3.txt", "r+b"); new = fopen("exerc4.txt", "w+b"); for (x = 0; x < 3; x++) { fread(&func[x], sizeof(struct cadastro), 1, fp); } for (x = 0; x < 3; x++) { fwrite(&func[x], sizeof(struct cadastro), 1, new); } fclose(fp); fclose(new); }
C
#include<stdio.h> #include<assert.h> #include<stdlib.h> #include<string.h> struct Person { char *name; int age; int height; int weight; }; struct Person *Person_create(char *name, int age, int height, int weight) { struct Person *who = malloc(sizeof(struct Person)); assert(who != NULL); who->name = strdup(name); who->age = age; who->height = height; who->weight = weight; return who; } void Person_destroy(struct Person *who) { assert(who != NULL); free(who->name); free(who); } void Person_print(struct Person *who) { printf("Name: %s\n", who->name); printf("\tAge: %d\n", who->age); printf("\tHeight: %d\n", who->height); printf("\tWeight: %d\n", who->weight); } void Person_print_byvalue(struct Person who) { printf("Name: %s\n", who.name); printf("\tAge: %d\n", who.age); printf("\tHeight: %d\n", who.height); printf("\tWeight: %d\n", who.weight); } int main(int argc, char *argv[]) { struct Person subho = {"Subho", 27, 170, 160}; struct Person *basu = Person_create("Basu", 28, 180, 180); printf("Subho is at memory location: %p\n", &subho); Person_print_byvalue(subho); printf("Basu is at memory location: %p\n", basu); Person_print(basu); subho.age += 20; subho.height += 2; subho.weight -=20; Person_print_byvalue(subho); //destroy the objects and clean up //Person_destroy(subho); Person_destroy(basu); return 0; }
C
// This file is part of the Corinthia project (http://corinthia.io). // // See the COPYRIGHT.txt file distributed with this work for // information regarding copyright ownership. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "Common.h" #include "Parser.h" #include "Util.h" #include <stdlib.h> #include <string.h> #include <stdio.h> #include <assert.h> typedef struct Parser Parser; struct Parser { Grammar *gram; const char *input; int start; int end; int pos; }; static Term *parseExpr(Parser *p, Expression *expr) { int startPos = p->pos; switch (ExpressionKind(expr)) { case ChoiceExpr: for (int i = 0; i < ExprChoiceCount(expr); i++) { Term *term = parseExpr(p,ExprChoiceChildAt(expr,i)); // If parsing of a choice succeeds, we return immediately. if (term != NULL) return TermNew(expr,startPos,p->pos,TermListNew(term,NULL)); // Success // If parsing of a choice fails, we reset the current position, and continue on with // the next choice (if any). If there are no more choices, the loop complets and // we return NULL. p->pos = startPos; } // If we get here, none of the choices have matched, so evaluation of the // choice expression as a whole fails. return NULL; // Failure case SequenceExpr: { TermList *list = NULL; TermList **listEnd = &list; for (int i = 0; i < ExprSequenceCount(expr); i++) { Term *term = parseExpr(p,ExprSequenceChildAt(expr,i)); // If parsing of a sequence item fails, the sequence as a whole fails. We reset // the current position to the start. if (term == NULL) { p->pos = startPos; return NULL; // Failure } // If parsing of a sequence item succeeds, we append it to the list of // accumulated child terms, and continue with the next item. TermListPtrAppend(&listEnd,term); } // If we get here, all items in the sequence have matched, and evaluation succeeds, // returning a term with children comprising the parse results of all items. return TermNew(expr,startPos,p->pos,list); // Success } case AndExpr: { // Evaluate the child expression to see if it succeeds, but reset the position since // this is a predicate which is not supposed to consume any input. AndExpr is a // positive lookahead assertion, which means it succeeds if and only if the child // evaluation succeeds. Term *term = parseExpr(p,ExprAndChild(expr)); p->pos = startPos; if (term != NULL) return TermNew(expr,startPos,startPos,NULL); // Success else return NULL; // Failure } case NotExpr: { // Evaluate the child expression to see if it succeeds, but reset the position since // this is a predicate which is not supposed to consume any input. NotExpr is a // *negative* lookahead assertion, which is the opposite of the above; it succeeds // if and only if the child evaluation *fails*. Term *term = parseExpr(p,ExprNotChild(expr)); p->pos = startPos; if (term != NULL) return NULL; // Failure else return TermNew(expr,startPos,startPos,NULL); // Success } case OptExpr: { // An optional expression (? operator) succeeds regardless of whether or not the child // expression succeeds. If the child did succeed, we return its result as a child of the // OptExpr result. Term *term = parseExpr(p,ExprOptChild(expr)); TermList *children; if (term != NULL) children = TermListNew(term,NULL); else children = NULL; return TermNew(expr,startPos,p->pos,children); // Success } case StarExpr: { // A zero-or-more expression (* operator) repeatedly matches is child as many times // as possible, suceeding regardless of the number of matches. TermList *list = NULL; TermList **listEnd = &list; for (;;) { Term *term = parseExpr(p,ExprStarChild(expr)); if (term == NULL) break; TermListPtrAppend(&listEnd,term); } return TermNew(expr,startPos,p->pos,list); } case PlusExpr: { // A one-or-more expression (+ operator) operates like a zero-or-match, but fails if // there is not at least one match TermList *list = NULL; TermList **listEnd = &list; // First make sure we have at least one match. If this parse fails then we have zero // matches, and thus the plus expression as a whole fails. Term *term = parseExpr(p,ExprPlusChild(expr)); if (term == NULL) return NULL; // Failure TermListPtrAppend(&listEnd,term); // Now parse any following matches for (;;) { Term *term = parseExpr(p,ExprPlusChild(expr)); if (term == NULL) break; TermListPtrAppend(&listEnd,term); } return TermNew(expr,startPos,p->pos,list); // Success } case IdentExpr: { Term *term = parseExpr(p,ExprIdentTarget(expr)); if (term != NULL) return TermNew(expr,startPos,p->pos,TermListNew(term,NULL)); else return NULL; } case LitExpr: { const char *value = ExprLitValue(expr); int len = (int)strlen(value); if ((p->pos + len <= p->end) && !memcmp(&p->input[p->pos],value,len)) { p->pos += len; return TermNew(expr,startPos,p->pos,NULL); } else { return NULL; } } case ClassExpr: // Actually identical to ChoiceExpr; we should really merge the two for (int i = 0; i < ExprClassCount(expr); i++) { Term *term = parseExpr(p,ExprClassChildAt(expr,i)); // If parsing of a choice succeeds, we return immediately. if (term != NULL) return TermNew(expr,startPos,p->pos,TermListNew(term,NULL)); // Success // If parsing of a choice fails, we reset the current position, and continue on with // the next choice (if any). If there are no more choices, the loop complets and // we return NULL. p->pos = startPos; } // If we get here, none of the choices have matched, so evaluation of the // choice expression as a whole fails. return NULL; // Failure case DotExpr: { size_t offset = p->pos; int c = UTF8NextChar(p->input,&offset); // FIXME: Should use uint32_t here if (c == 0) return NULL; p->pos = offset; return TermNew(expr,startPos,p->pos,NULL); } case RangeExpr: { size_t offset = p->pos; int c = UTF8NextChar(p->input,&offset); // FIXME: Should use uint32_t here if (c == 0) return NULL; if ((c >= ExprRangeStart(expr)) && (c < ExprRangeEnd(expr))) { p->pos = offset; return TermNew(expr,startPos,p->pos,NULL); } else { return NULL; } } case StringExpr: { Term *term = parseExpr(p,ExprStringChild(expr)); if (term == NULL) return NULL; // We ignore the parsed term here, since we're only interested in the string content // (which can be recovered from the input, and the start and end fields of the term). return TermNew(expr,startPos,p->pos,NULL); } case LabelExpr: { Term *term = parseExpr(p,ExprLabelChild(expr)); if (term == NULL) return NULL; return TermNew(expr,startPos,p->pos,TermListNew(term,NULL)); } } assert(!"unknown expression type"); return NULL; } Term *parse(Grammar *gram, const char *rule, const char *input, int start, int end) { Expression *rootExpr = GrammarLookup(gram,rule); if (rootExpr == NULL) { fprintf(stderr,"%s: No such rule\n",rule); exit(1); } Parser *p = (Parser *)calloc(1,sizeof(Parser)); p->gram = gram; p->input = input; p->start = start; p->end = end; p->pos = start; Term *result = parseExpr(p,rootExpr); free(p); return result; }
C
#include "arthimetic.h" void main(){ int number1,number2; //get input from keyboard printf("Enter The First Number: \n"); scanf("%d",&number1); printf("Enter The Second Number: \n"); scanf("%d",&number2); //display the result printf("The sum is:%d\n",Add(number1,number2) ); printf("The diffrence is:%d\n",Subtract(number1,number2) ); printf("The nultiple is:%d\n",Multiply(number1,number2) ); printf("The ratio is:%lf\n",Devide(number1,number2) ); } int Add(int number1, int number2){ return number1+number2; } int Subtract(int number1,int number2){ return number1-number2; } int Multiply(int number1,int number2){ return number1*number2; } double Devide(int number1,int number2){ return number1/number2; }
C
/* ** redirection.c for redirection in /home/abollo_h/minishell1/pipe ** ** Made by ** Login <[email protected]> ** ** Started on Fri Jan 31 15:05:13 2014 ** Last update Sun May 25 19:49:06 2014 TAWFIK */ #include <stdlib.h> #include <sys/types.h> #include <sys/wait.h> #include <unistd.h> #include <sys/stat.h> #include <fcntl.h> #include "pipe_and_red.h" #include "parser.h" #include "basic_funct.h" static const t_op g_operator[] = { {"<<", &double_left_c}, {"<", &left_c}, {"2>&1", &err_and_no_right_c}, {"2>>", &err_double_right_c}, {">>", &double_right_c}, {"2>", &err_right_c}, {">", &right_c} }; t_btree *execution(t_tab *tab, t_btree **tree) { int j; j = -1; while (++j != sizeof(g_operator) / sizeof(g_operator[0])) { if (my_strcmp(g_operator[j].str, (*tree)->stock[0]) == 0) { if (g_operator[j].ptr(tab, tree)) return (NULL); if (save_arg(&(tab->save), &((*tree)->right->stock[1]), NOT)) return (NULL); relink_tree(tree); return (*tree); } } return (NULL); } int my_separator(t_tab *tab, t_btree **tree, int n, t_pid **pid) { if (send_to_arg(tab, tree)) return (-1); exec_command(tab, tree, pid); init_to_zero(tab); if (n == 0) return (execute(tab, tree, pid)); else if (n == 1) { if (tab->status != 0) while (*tree && (*tree)->stock && (find_sep((*tree)->stock[0], 0) != 2) && (find_sep((*tree)->stock[0], 0) != 0)) relink_tree(tree); return (execute(tab, tree, pid)); } if (tab->status == 0) while ((*tree)->stock && (find_sep((*tree)->stock[0], 0) != 1) && (find_sep((*tree)->stock[0], 0) != 0)) relink_tree(tree); return (execute(tab, tree, pid)); } int send_to_arg(t_tab *tab, t_btree **tree) { if ((*tree)->right == NULL) { if (((*tree)->right = malloc(sizeof(t_btree))) == NULL) return (-1); (*tree)->right->stock = NULL; (*tree)->right->par = (*tree)->par; } if (save_arg(&((*tree)->right->stock), tab->save, CLEAN)) return (-1); tab->save = NULL; return (0); } int other_execute(t_tab *tab, t_btree **tree, t_pid **pid) { int n; if (find_op((*tree)->left->stock[0], 0) == 0) { if (((*tree)->left = execution(tab, &((*tree)->left))) == NULL) return (-1); return (execute(tab, tree, pid)); } if ((n = find_sep((*tree)->left->stock[0], 0)) >= 0) return (my_separator(tab, tree, n, pid)); return (0); } int execute(t_tab *tab, t_btree **tree, t_pid **pid) { if (!(*tree) || !(*tree)->left || !(*tree)->stock || (tab->exit_flag)) return (0); if (!(*tree)->left->stock || my_strcmp((*tree)->left->stock[0], "&") == 0 || (my_strcmp((*tree)->left->stock[0], ";") == 0)) { if (send_to_arg(tab, tree)) return (-1); exec_command(tab, tree, pid); tab->last_status = tab->status; init_to_zero(tab); return (execute(tab, tree, pid)); } if (my_strcmp((*tree)->left->stock[0], "|") == 0) { if ((send_to_arg(tab, tree)) || ((exec_pipe(tab, tree, 0, pid)) == -1)) return (-1); return (execute(tab, tree, pid)); } return (other_execute(tab, tree, pid)); }
C
/* * utils.h * * Created on: Jul 7, 2013 * Author: alessandro */ #ifndef UTILS_H_ #define UTILS_H_ /** * Given one of the resolution unit used in the EXIF Tags ( ResolutionUnit and FocalPlaneResolutionUnit ) * this methods will return the resolution value associated ( in millimeters ) * @param resolutionUnit * @return */ double computeResolutionUnit( int resolutionUnit ) { double result = 0; switch( resolutionUnit) { case 1: result = 25.4; break; // inch case 2: // According to the information I was using, 2 means meters. // But looking at the Cannon powershot's files, inches is the only // sensible value. result = 25.4; break; case 3: result = 10; break; // centimeter case 4: result = 1; break; // millimeter case 5: result = .001; break; // micrometer default: result = 25.4; break; } return result; } #endif /* UTILS_H_ */
C
#include<stdio.h> void main() { char yesno='y'; while(yesno=='Y'||yesno=='y') { int num1,num2,ans; char ch; printf("enter your first number"); scanf("%d",&num1); printf("enter your second number"); scanf("%d",&num2); printf("choose operation (+,-,*,/)"); fflush(stdin); scanf("%c",&ch); if(ch=='+') { ans = num1+num2; printf("Addition is %d",ans); } else if(ch=='-') { printf("Subtraction is %d",(num1-num2)); } else if(ch=='*') { printf("multiplication is %d",(num1*num2)); } else if(ch=='/') { printf("division is %d",(num1/num2)); } else { printf("Invalid"); } printf("press y to continue"); fflush(stdin); scanf("%c",&yesno); } }
C
#include<stdio.h> #include<stdlib.h> #include<string.h> #include<assert.h> char * my_strtok(char *input,char t){ static unsigned int token=0; static char **part_token = NULL; static unsigned int current_returned_tokens=0; if(input){ unsigned int i=0,j=0; /*Count the tokens and create the part_token array*/ token=0; while(input[i]){ if(input[i]==t){ token++; } i++; } part_token = (char **) malloc(sizeof(char *)*(token+1)); token = 0; i=0;j=0; while(input[i]){ if(input[i] == t){ part_token[token++] = malloc(sizeof(char)*(i-j+1)); assert(part_token[token-1]); assert(strncpy(part_token[token-1],&input[j],i-j) == part_token[token-1]); part_token[token-1][i-j] = '\0'; j = i+1; } i++; } part_token[token++] = malloc(sizeof(char)*(i-j+1)); strncpy(part_token[token-1],&input[j],i-j); part_token[token-1][i-j+1] = '\0'; }else if(current_returned_tokens < token){ return part_token[current_returned_tokens++]; }else{ current_returned_tokens = 0; return NULL; } } int main(){ //char *test_string = "ababbbbaaaaaba"; char test_string[256]; char *out=NULL; while(scanf("%s",test_string)){ my_strtok(test_string,'a'); out = my_strtok(NULL,'a'); while(out){ printf("%s\n",((out[0])?out:"(NULL)")); free(out); out = my_strtok(NULL,'a'); } } }
C
#include <stdio.h> int main() { int score; printf(" Էϱ : "); scanf("%d", &score); // ùٸ if if (score <= 70) printf(""); else if (score <= 90) printf(""); else printf(""); // ߸ if if (score <= 70) printf(""); if (score <= 90) printf(""); if (score <= 100) printf(""); /* if - else if - else ϳ Ʈ ռ Ǵ ؼ Ѵ. ٸ if Ź ٸ Ȯϱ⿡ ߺ ִ. */ return 0; }
C
#include<stdio.h> #include<unistd.h> #include<linux/unistd.h> #include<linux/time.h> int main() { struct timespec time; int ret = syscall(326, &time); if(ret==0) { printf("Successfully returned the System call\n"); printf("Time in nanoseconds: %ld\n", time.tv_nsec); } else { printf("System call failed to return\n"); } return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_db.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: apineda <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/04/20 13:25:10 by qho #+# #+# */ /* Updated: 2017/05/05 18:25:53 by apineda ### ########.fr */ /* */ /* ************************************************************************** */ #include "ft_db.h" int ft_array_len(char **args) { int len; char **tmp; len = 0; tmp = args; while (*tmp) { tmp++; len++; } return (len); } void ft_cleanup(t_table *t) { int c_idx; int r_idx; c_idx = 0; r_idx = 0; while (c_idx < COL_SIZE) { while (r_idx < ROW_SIZE && t->row_id[r_idx] != 0) { free(t->columns[c_idx].content_array[r_idx].data); r_idx++; } free(t->columns[c_idx].content_array); c_idx++; } free(t->columns); } void ft_exit(t_table *t) { ft_save_handler(t); ft_cleanup(t); } int ft_dbms(char *command, char **rec, t_table *t) { int ac; ac = ft_array_len(rec); (void)t; if (ac == 1 && !strncmp(command, "help", 4)) ft_print_help_all(); else if (ac == 1 && !strncmp(command, "exit", 4)) { ft_exit(t); return (0); } else if (ac == 1 && !strncmp(command, "save", 4)) ft_save_handler(t); else if (!strncmp(command, "insert", 6)) ft_insert_handler(rec, t); else if (!strncmp(command, "update", 6)) ft_update_handler(rec, t); else if (!strncmp(command, "print", 5)) ft_print_handler(rec, t); else if (!strncmp(command, "delete", 6)) ft_delete_handler(rec, t); else printf("Invalid command. Use \"help\" to see usage.\n"); return (1); }
C
struct{ double circle_t,circle_r; double dot_r; double speed; //pixels per second }player={0,100,5,50*M_PI}; double player_get_x(){ return cos(player.circle_t)*player.circle_r; } double player_get_y(){ return sin(player.circle_t)*player.circle_r; } void player_rotate(double direction){ player.circle_t += direction*player.speed/FPS/player.circle_r; if (player.circle_t < 0) player.circle_t+=2*M_PI; if (player.circle_t > 2*M_PI) player.circle_t-=2*M_PI; } void player_move_radial(double direction){ player.circle_r += direction*player.speed/FPS; if (player.circle_r<0.1) player.circle_r=0.1; }
C
#include <stdio.h> #include <cs50.h> void question(void); void printMario(int); int height = 0; int main(void){ question(); } void question(void){ printf("Height : "); height = get_int(); if (height > 0 && height < 24){ printMario(height); } else if (height == 0){ height=0; } else question(); } void printMario(int n){ int i = 0; for (i = 1 ; i <= n ; i++){ printf("%.*s",n-i," "); printf("%.*s",n-(n-i),"########################"); printf(" "); printf("%.*s\n",n-(n-i),"########################"); } }
C
#include <stdio.h> int main (){ //Declarando variáveis int num1; //Dado printf("Informe um número: "); scanf("%d", &num1); //Processamento if (num1 > 100){ printf("%d", num1); }else{ num1 = 0; printf("%d", num1); } }
C
#include <stdio.h> int main(){ int a,b; while (1) { /* code */ printf("Ctrl+Cで終了\n" ); printf("計算する値を入力してください\n"); printf("例:5%%8\n" ); scanf("%d %d",&a,&b ); printf("答えは:%d\n",a%b ); } return 0; }
C
/**************************************************************** * Autor: José Manuel C. Noronha * Autor: Noé Godinho * Turma: PL2 * Grupo: 5 * Ano Lectivo: 2016 - 2017 ***************************************************************/ /* Includes, Definições e Notas */ #include "../lib/ex8.h" /* * função que atribui os valores necessários * para tornar a thread i periódica */ void new_rt_task_make_periodic(int i, int priority, struct timespec start_time, struct timespec periodo, int end_time){ thread_info[i].priority = priority; thread_info[i].start = start_time; /* aplica o tempo de início mais o tempo que a thread decorre */ thread_info[i].end.tv_sec = thread_info[i].start.tv_sec + end_time; thread_info[i].end.tv_nsec = thread_info[i].start.tv_nsec; thread_info[i].period = periodo; } /* * igual à função anterior, no entanto aplica um delay de início */ void new_rt_task_make_periodic_relative_ns(int i, int priority, struct timespec start_delay, struct timespec periodo, int end_time){ struct timespec actual_time; /* estrutura para obter o tempo actual */ clock_gettime(CLOCK_MONOTONIC, &actual_time); thread_info[i].priority = priority; /* como a thread inicia com um delay, é-lhe atribuído o tempo obtido mais o delay para início da thread */ thread_info[i].start.tv_sec = actual_time.tv_sec + start_delay.tv_sec; thread_info[i].start.tv_nsec = actual_time.tv_nsec + start_delay.tv_nsec; /* condição para evitar overflow na variável de nanosegundos */ if(thread_info[i].start.tv_nsec > BILLION){ thread_info[i].start.tv_nsec -= BILLION; ++thread_info[i].start.tv_sec; } /* aplica o tempo de início mais o tempo que a thread decorre */ thread_info[i].end.tv_sec = thread_info[i].start.tv_sec + end_time; thread_info[i].end.tv_nsec = thread_info[i].start.tv_nsec; thread_info[i].period = periodo; } /* * função que faz parar a thread durante um determinado período */ void new_rt_task_wait_period(int i){ /* faz sleep à thread até voltar a ser chamada novamente */ clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &thread_info[i].start, NULL); /* adiciona o periodo à thread */ thread_info[i].start.tv_sec += thread_info[i].period.tv_sec; thread_info[i].start.tv_nsec += thread_info[i].period.tv_nsec; /* condição para evitar overflow na variável de nanosegundos */ if(thread_info[i].start.tv_nsec > BILLION){ thread_info[i].start.tv_nsec -= BILLION; ++thread_info[i].start.tv_sec; } }
C
/* * Cyclone V HPS Interrupt Controller * ------------------------------------ * Description: * Driver for enabling and using the General Interrupt * Controller (GIC). The driver includes code to create * a vector table, and register interrupts. * * The code makes use of function pointers to register * interrupt handlers for specific interrupt IDs. * * Company: University of Leeds * Author: T Carpenter * * Change Log: * * Date | Changes * -----------+---------------------------------- * 12/03/2018 | Creation of driver * */ #ifndef HPS_IRQ_H_ #define HPS_IRQ_H_ #include <stdbool.h> #include <stdlib.h> #define HPS_IRQ_SUCCESS 0 #define HPS_IRQ_ERRORNOINIT -1 #define HPS_IRQ_NOTFOUND -2 #define HPS_IRQ_NONENOUGHMEM -4 //Include a list of IRQ IDs that can be used while registering interrupts #include "HPS_IRQ_IDs.h" //Function Pointer Type for Interrupt Handlers // - interruptID is the ID of the interrupt that called the handler. // - When IRQ handler is called by interrupt, 'isInit' is false and 'initParams' // can be ignored. // - If variables need to be shared with the handler, the user can call the irq // handler manually with 'isInit' set to true, and 'initParams' a pointer to // the variables that need to be shared. typedef void (*isr_handler_func)(HPSIRQSource interruptID, bool isInit, void* initParams); // Two examples of IRQ handlers are as follows: /* ---Start Examples--- //Handler not needing parameters void exampleIRQHandlerWithNoParams(HPSIRQSource interruptID, bool isInit, void* initParams) { if (!isInit) { //IRQ handler stuff... } } //Handler needing parameters void exampleIRQHandlerUsingParams(HPSIRQSource interruptID, bool isInit, void* initParams) { static someVarType* params = NULL; if (isInit) { //Initialise the params variable. params = (someVarType*)initParams; } else if (params != NULL) { //IRQ handler stuff... } //Optionally, else { //Do something if interrupted before initialised } } // ---End Examples--- */ //Initialise HPS IRQ Driver // - userUnhandledIRQCallback is either a function pointer to an isr_handler to // be called in the event of an unhandled IRQ occurring. If this parameter is // passed as NULL (0x0), a default handler which causes crash by watchdog will // be used. // - Returns HPS_IRQ_SUCCESS if successful. signed int HPS_IRQ_initialise(isr_handler_func userUnhandledIRQCallback ); //Check if driver initialised // - Returns true if driver previously initialised bool HPS_IRQ_isInitialised(void); //Register a new interrupt ID handler // - interruptID is the number between 0 and 255 of the interrupt being configured // - handlerFunction is a function pointer to the function that will be called when IRQ with ID occurs // - if a handler already exists for the specified ID, it will be replaced by the new one. // - the interrupt ID will be enabled in the GIC // - returns HPS_IRQ_SUCCESS on success. // - returns HPS_IRQ_NONENOUGHMEM if failed to reallocated handler array. signed int HPS_IRQ_registerHandler(HPSIRQSource interruptID, isr_handler_func handlerFunction); //Unregister interrupt ID handler // - interruptID is the number between 0 and 255 of the interrupt being configured // - the interrupt will be disabled also in the GIC // - returns HPS_IRQ_SUCCESS on success. // - returns HPS_IRQ_NOTFOUND if handler not found signed int HPS_IRQ_unregisterHandler(HPSIRQSource interruptID); #endif /* HPS_IRQ_H_ */
C
/************************************************************************* > File Name: src/2010.c > Author: JS > Created Time: 2016年03月12日 星期六 19时14分14秒 ************************************************************************/ #include <stdio.h> #include <math.h> int main() { int m, n; while (scanf("%d%d", &m, &n) != EOF){ if (m < 100 || n < 100 || m > 999 || n > 999 || m > n){ continue; } int num[100] = {0}, j = 0; for (int i = m; i <= n; i++){ int a , b, c; a = i / 100; c = i % 10; b = (i - a * 100 - c) / 10; if (i == (pow(a, 3) + pow(b, 3) + pow(c, 3))){ num[j++] = i; } } if (num[0] == 0){ printf("no"); } for (int i = 0; num[i] != 0; i++){ printf("%d", num[i]); if (num[i+1] != 0){ printf(" "); } } printf("\n"); } return 0; }
C
#include <stdio.h> #include <stdlib.h> void copy(int *A, int *B, int low, int high) { int i; for (i = low; i <= high; i++) { A[i] = B[i]; } } int merge_and_count(int *A, int *B, int low, int mid, int high) { int left, right, i, count; left = i = low; right = mid + 1; count = 0; while (left <= mid && right <= high) { if (A[left] < A[right]) { B[i] = A[left++]; } else { B[i] = A[right++]; count = count + (mid - left + 1); } i++; } while (left <= mid) { B[i] = A[left++]; i++; } while (right <= high) { B[i] = A[right++]; i++; } return count; } int sort_and_count(int *A, int *B, int low, int high) { int r, mid, left, right; r = left = right = 0; if ( (high - low + 1) == 1 ) { return 0; } else { mid = low + ((high - low) / 2); left = sort_and_count(A, B, low, mid); right = sort_and_count(A, B, mid + 1, high); r = merge_and_count(A, B, low, mid, high); return (r + left + right); } } int main(int argc, char* argv[]) { int i, n, result; int *array, *temp; scanf("%i", &n); array = (int*) malloc(sizeof(int) * n); temp = (int*) malloc(sizeof(int) * n); for (i = 0; i < n; i++) { scanf("%i", &array[i]); } printf("result = %i\n", sort_and_count(array, temp, 0, n - 1)); free(temp); free(array); return 0; }
C
#include<stdio.h> #include<stdlib.h> #include<sys/types.h> #include<sys/socket.h> #include<sys/uio.h> #include<netinet/in.h> #include<arpa/inet.h> #include<unistd.h> #include<string.h> void main(int argc,char* argv[]) { int sockid,rval; char a1[50],a2[50],b1[50],b2[50]; sockid=socket(AF_INET,SOCK_STREAM,0); if(sockid==-1) { perror("SOCK-CRE-ERR"); exit(1); } struct sockaddr_in s; struct iovec iov[2]; system("clear"); if(argc<3) { printf("\nUSAGE : %s IP_ADDR PORT#\n",argv[0]); exit(0); } s.sin_family=AF_INET; s.sin_port=htons(atoi(argv[2])); s.sin_addr.s_addr=inet_addr(argv[1]); rval=connect(sockid,(struct sockaddr*)&s, sizeof(s)); if(rval==-1) { perror("CONN-ERR:"); close(sockid); exit(1); } printf("\nEnter the first message : "); scanf("%s",a1); printf("\nEnter the second message : "); scanf("%s",a2); iov[0].iov_base=a1; iov[0].iov_len=50; iov[1].iov_base=a2; iov[1].iov_len=50; writev(sockid,&iov[0],2); printf("Message sent successfully\n"); iov[0].iov_base=b1; iov[0].iov_len=50; iov[1].iov_base=b2; iov[1].iov_len=50; readv(sockid,&iov[0],2); printf("Server response is : %s \n %s\n",b1,b2); close(sockid); }