language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
#include <stdio.h> #include "../src/linkedlist.h" int test_linkedlist_is_empty(void) { s_linkedlist *linked_list = NULL; int test_one = 0; int test_two = 0; unsigned int error = 0; // Test linked_list = linkedlist_create(); linkedlist_add_front(linked_list, NULL); test_one = linkedlist_is_empty(linked_list); linkedlist_remove(linked_list, 0); test_two = linkedlist_is_empty(linked_list); // Assert if (test_one) { error += 1; } if (!test_two) { error += 1; } // Free allocated memory linkedlist_destroy(linked_list, NULL); return (error == 0); }
C
// Palette uploader. // // When a request to change palette arrives, 'requested_palette' is set to the requested palette number. // Then, palette is uploaded to multiple boards when I2C bus becomes free, this is time-consuming. // There is no queue for palette change commands, // it is assumed that they are issued extremely rarely, when the device is initialized. // --------------------------------------------------------------------------------------------------------------------------------- #ifndef __BLM_BOARDS__COMM__LEDS__PALETTE__UPLOADER #define __BLM_BOARDS__COMM__LEDS__PALETTE__UPLOADER #include <stdint.h> #include <Arduino.h> #include <Wire.h> #include "seq__blm_bridge__config.h" #include "blm_boards__comm__leds__palette__buffer.h" int8_t blm_boards__comm__leds__palette__uploader__requested_palette; static TwoWire *blm_boards__comm__leds__palette__uploader__wire; static uint8_t blm_boards__comm__leds__palette__uploader__base_address; void blm_boards__comm__leds__palette__uploader__init(TwoWire *wire, uint8_t base_address) { blm_boards__comm__leds__palette__uploader__wire = wire; blm_boards__comm__leds__palette__uploader__base_address = base_address; blm_boards__comm__leds__palette__uploader__requested_palette = -1; } void blm_boards__comm__leds__palette__uploader__request(uint8_t palette) { blm_boards__comm__leds__palette__uploader__requested_palette = palette; } /** * Upload the specified palette to the specified board. * Because I2C payload size is limited by Wire library, do multiple (16) uploads, each carrying data for 8 entries. */ void blm_boards__comm__leds__palette__uploader__upload(uint8_t board, uint8_t palette) { for (int entry = 0; entry < 128; entry += 8) { blm_boards__comm__leds__palette__uploader__wire->beginTransmission(blm_boards__comm__leds__palette__uploader__base_address + board); blm_boards__comm__leds__palette__uploader__wire->write(0x80 + entry); // WRITE_PALETTE_MEMORY command blm_boards__comm__leds__palette__uploader__wire->write(&blm_boards__comm__leds__palette__buffer__palettes[palette][entry * 3], 8 * 3); blm_boards__comm__leds__palette__uploader__wire->endTransmission(); } } bool blm_boards__comm__leds__palette__uploader__is_runnable() { return blm_boards__comm__leds__palette__uploader__requested_palette >= 0; } void blm_boards__comm__leds__palette__uploader__run() { for (uint8_t board = 0; board < NUM_BOARDS; board++) { blm_boards__comm__leds__palette__uploader__upload(board, blm_boards__comm__leds__palette__uploader__requested_palette); } blm_boards__comm__leds__palette__uploader__requested_palette = -1; } #endif
C
#include<stdio.h> int main() { int x,y,z,i,j,k; i = 1;j=2;k=3; z = i-1 && j++ < k; x = y = z -= 1; ++x && ++y && ++z; printf("x=%d,y=%d,z=%d\n",x,y,z); }
C
// // main.c // hw2test // // Created by Elizabeth Han on 10/17/17. // Copyright © 2017 Elizabeth Han. All rights reserved. // #include <stdio.h> long cread(long*xp) { return (xp? *xp : 0); } /*int main(void) { long x = 3; long *y = &x; long z = cread(y); printf("%li \n", z); return 0; } */
C
#include<stdio.h> void main() { int a[] = {2,4,6,8,10},i,s = 0; for(i=0;i<3;i++) s += a[i+1]; printf("%d\n",s); }
C
#include<stdio.h> #include<stdlib.h> #include<string.h> char tmap[64][64]; char flag[64][64][4]; char step[][2] = { {0, 1}, {1, 0}, {0, -1}, {-1, 0}, }; int main() { int tc, ti, n, r, i, x, y; int nx, ny, d; scanf("%d", &tc); for (ti=0; ti<tc; ti++) { memset(tmap, 0, sizeof(tmap)); scanf("%d %d", &n, &r); for (i=0; i<r; i++) { scanf("%d %d", &x, &y); tmap[x][y]=1; } scanf("%d %d", &x, &y); if (y==0) d=0; else if (x==0)d=1; else if (y==n+1) d=2; else d=3; memset(flag, 0, sizeof(flag)); flag[x][y][d]=1; while(1) { nx = step[d][0]+x; ny = step[d][1]+y; if (nx==0||nx==n+1||ny==0||ny==n+1) { printf("%d %d\n", nx, ny); break; } if (tmap[nx][ny]) d=(d+1)%4; if (flag[nx][ny][d]==1) { printf("0 0\n"); break; } flag[nx][ny][d]==1; x = nx; y=ny; } } return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <strings.h> #include "jeu.h" t_jeu* creer_jeu(char *nom, genre_jeu genre, int nbJoueurMin, int nbJoueurMax, int duree) { t_jeu *jeu; jeu = (t_jeu*)malloc(sizeof(t_jeu)); if (jeu == NULL) return NULL; jeu->nom = nom; jeu->genre = genre; jeu->nbJoueurMin = nbJoueurMin; jeu->nbJoueurMax = nbJoueurMax; jeu->duree = duree; return jeu; } t_jeu* saisir_jeu() { char *nom = (char*)malloc((sizeof(char))*50); char genre_str[10]; int nbMin, nbMax, duree; printf("Veuillez saisir dans l'ordre : nom, genre, nombre de joueurs minimum, nombre de joueurs maximum, la duree.\n"); scanf("%s",nom); scanf("%s",genre_str); scanf("%d%d%d",&nbMin,&nbMax,&duree); while (getchar()!='\n'); // clear input return creer_jeu(nom,genreFromString(genre_str),nbMin,nbMax,duree); } char *stringFromGenre(enum genre g) { if (g == -1) return "-1"; static char *strings[] = { "PLATEAU", "RPG", "COOPERATIF", "AMBIANCE", "HASARD" }; return strings[g]; } genre_jeu genreFromString(char *str) { if (strcasecmp(str,"AMBIANCE") == 0) // si strcasecmp() n'existe pas sur votre OS utilisez strcmp() return AMBIANCE; else if (strcasecmp(str,"COOPERATIF") == 0) // si strcasecmp() n'existe pas sur votre OS utilisez strcmp() return COOPERATIF; else if (strcasecmp(str,"RPG") == 0) // si strcasecmp() n'existe pas sur votre OS utilisez strcmp() return RPG; else if (strcasecmp(str,"PLATEAU") == 0) // si strcasecmp() n'existe pas sur votre OS utilisez strcmp() return PLATEAU; else if (strcasecmp(str,"HASARD") == 0) // si strcasecmp() n'existe pas sur votre OS utilisez strcmp() return HASARD; return HASARD; }
C
#include "u.h" #include "libc.h" /* * first argument (l) is in r3 at entry. * r3 contains return value upon return. */ int tas(int *x) { int v; /* * this __asm__ works with gcc 2.95.2 (mac os x 10.1). * this assembly language destroys r0 (0), some other register (v), * r4 (x) and r5 (temp). */ __asm__("\n sync\n" " li r0,0\n" " mr r4,%1 /* &l->val */\n" " lis r5,0xdead /* assemble constant 0xdeaddead */\n" " ori r5,r5,0xdead /* \" */\n" "tas1:\n" " dcbf r4,r0 /* cache flush; \"fix for 603x bug\" */\n" " lwarx %0,r4,r0 /* v = l->val with reservation */\n" " cmp cr0,0,%0,r0 /* v == 0 */\n" " bne tas0\n" " stwcx. r5,r4,r0 /* if (l->val same) l->val = 0xdeaddead */\n" " bne tas1\n" "tas0:\n" " sync\n" " isync\n" : "=r" (v) : "r" (x) : "cc", "memory", "r0", "r4", "r5" ); switch(v) { case 0: return 0; case 0xdeaddead: return 1; default: print("tas: corrupted 0x%lux\n", v); } return 0; }
C
//************************************// /*NAME: VARA ASHISH H. TITLE: GENERATE FOLLOWING TASK USING INTERRUPT: 1) CREATING SQUARE WAVE ON P2.5 2) SENDING LATTER 'A' TO SERIAL PORT 3) GET SINGLE BIT FROM P1.7 AND SEND IT TO P1.0 DATE: 07/01/2014 */ //***********************************// //***********START****************// #include<reg51.h> sbit wave = P2^5; sbit LED = P1^0; sbit SW = P1^7; //***********INTERRUPT FOR TIMER 0****************// void timer0() interrupt 1 { wave = ~wave; TH0 = 0xFC; TL0 = 0x66; } //***********INTERRUPT FOR SERIAL COMUNICATION****************// void serial0() interrupt 4 { if(TI == 1) { TI = 0; SBUF = 'A'; } else { RI = 0; } } //**************MAIN PROGRAM****************// void main() { SW = 1; IE = 0x92; //enable timer0 and seial communication interrupt; SCON = 0x50; //for serial communication; TMOD = 0x21; //configure timer0 in mode 1 and timer1 in mode 2; TH1 = 0xFD; //load value of 9600 baudrate for timer1; TH0 = 0xFC; //load value for 1ms pulse TL0 = 0x66; TR1 = 1; //timer1 start; TR0 = 1; //timer0 start; SBUF = 'A'; //transmit latter 'A'; while(1) { LED = SW; //ger data from p1.7 and send it to p1.0; } } //**************STOP****************//
C
/* Writing/reading struct to disk */ #include <stdio.h> #include <stdlib.h> #include <ctype.h> #include <string.h> #include <errno.h> #define FALSE 0 #define TRUE 1 struct account { int number; char firstname[30]; char lastname[30]; float balance; struct account *next; }; struct account *first_ac = NULL; struct account *current_ac = NULL; struct account *new_ac = NULL; int acc_num = 0; /* this automatically gives ac. no. to new accounts */ void flush_input(void); void add_new_account(void); void list_all_accounts(void); void delete_account(void); void modify_account(void); void print_a_record(struct account *acc_ptr); void save_records(const char *filename); void read_records(const char *filename); void prompt(void); int main(int argc, const char *argv[]) { char user_choice; int done = FALSE; /* check for the filename argument */ if (argc != 2) { prompt(); return EXIT_FAILURE; } /* initialize database */ read_records( argv[1] ); /* display the menu */ do { /* clear the screen */ system("clear"); puts("\nManage Bank Account\n"); puts("A - Add a new account"); puts("D - Delete an account"); puts("L - List all the accounts"); puts("M - Modify an account"); puts("Q - Quit this program"); printf("\nYour choice --> "); user_choice = toupper( getchar() ); flush_input(); /* clear the stdin */ switch (user_choice) { case 'A': puts("\nAdd new account"); puts("****************************"); add_new_account(); break; case 'L': puts("\nList all the accounts"); puts("****************************"); list_all_accounts(); break; case 'D': puts("\nDelete an account"); puts("****************************"); delete_account(); break; case 'M': puts("\nModify an account"); puts("****************************"); modify_account(); break; case 'Q': done = TRUE; puts("\nQuitting...\n"); save_records( argv[1] ); break; default: puts("\nWHAT?"); printf("Press any key to continue..."); getchar(); } } while ( !done ); return EXIT_SUCCESS; } /* eat all the chars in stdin untill '\n' */ void flush_input(void) { while ( getc(stdin) != '\n' ) ; } void add_new_account(void) { /* create a new account */ new_ac = (struct account *) malloc( sizeof(struct account) ); new_ac->next = NULL; /* check if it is the first record */ if ( first_ac == NULL ) { first_ac = current_ac = new_ac; } else /* link the record with the list */ { current_ac->next = new_ac; current_ac = new_ac; } /* get the user inputs */ /* get the account number */ acc_num++; printf("Account Number: %i\n", acc_num); current_ac->number = acc_num; printf("Enter customer’s last name: "); fgets(current_ac->lastname, 30, stdin); printf("Enter customer’s first name: "); fgets(current_ac->firstname, 30, stdin); printf("Enter account balance: $"); scanf("%f", &current_ac->balance); flush_input(); printf("Account #%d has been created successfully\n", current_ac->number); printf("\nPress any key to continue..."); getchar(); } void list_all_accounts(void) { int ac_counter; struct account *travers; if (first_ac == NULL) { puts("There are no records to display"); } else { /* rewind the list */ travers = first_ac; ac_counter = 1; /* Display the list */ while (travers) { printf("\n#%d Account = %i:\n", ac_counter++, travers->number); printf("Last name: %s", travers->lastname); printf("First name: %s", travers->firstname); printf("Account balance = $%.2f\n", travers->balance); /* go to the next record */ travers = travers->next; } } printf("\nPress any key to continue..."); getchar(); } void delete_account(void) { int ac_no; struct account *travers = first_ac; struct account *prev = NULL; if (first_ac == NULL) { puts("There are no records to delete"); } else { list_all_accounts(); /* show all records first */ printf("Enter account number to delete: "); scanf("%i", &ac_no); flush_input(); /* scan the list */ while (travers) { if (travers->number == ac_no) { if (prev == NULL) { first_ac = travers->next; /* it's the first record */ } else { /* it it's the last account then upadte current_ac */ if (travers->next == NULL) current_ac = prev; prev->next = travers->next; } free(travers); printf("Account #%d has been deleted successfully\n", ac_no); break; } prev = travers; travers = travers->next; } if (travers == NULL) { printf("No records found for account #%d\n", ac_no); puts("Nothing deleted."); } } printf("\nPress any key to continue..."); getchar(); } void modify_account(void) { int ac_no; struct account *travers = first_ac; if (first_ac == NULL) { puts("There are no records to modify"); } else { printf("Enter account number to modify: "); scanf("%i", &ac_no); flush_input(); /* scan the list */ while (travers) { if (travers->number == ac_no) { /* display the record first */ puts("Record found!"); print_a_record(travers); printf("Enter customer’s last name: "); fgets(travers->lastname, 30, stdin); printf("Enter customer’s first name: "); fgets(travers->firstname, 30, stdin); printf("Enter account balance: $"); scanf("%f", &travers->balance); flush_input(); printf("Account #%d has been modified successfully", ac_no); break; } travers = travers->next; } if (travers == NULL) { printf("No records found for account #%d\n", ac_no); puts("Nothing modified."); } } printf("\nPress any key to continue..."); getchar(); } void print_a_record(struct account *acc_ptr) { if (acc_ptr == NULL) { puts("Don't give me garbage to print"); } else { printf("\nAccount = %i:\n", acc_ptr->number); printf("Last name: %s", acc_ptr->lastname); printf("First name: %s", acc_ptr->firstname); printf("Account balance = $%.2f\n", acc_ptr->balance); } putchar('\n'); } void save_records(const char *filename) { FILE *pfile; /* check if the list is empty */ if (first_ac == NULL) return; pfile = fopen(filename, "w"); if (pfile == NULL) { printf("Error writing to %s\n", filename); perror("fopen()"); exit(EXIT_FAILURE); } /*traverse the list end save each record to disk */ while (first_ac) { fwrite(first_ac, sizeof(struct account), 1, pfile); first_ac = first_ac->next; } fclose(pfile); puts("Records have been written to disk successfuly"); } void read_records(const char *filename) { FILE *pfile = NULL; struct account *temp_ptr; long int bytes; pfile = fopen(filename, "r"); if (pfile == NULL) { printf("Error writing to %s\n", filename); perror("fopen()"); exit(EXIT_FAILURE); } /* read all the records off of the file */ while (1) { /* allocate memory for every record */ temp_ptr = (struct account *) malloc( sizeof(struct account) ); bytes = fread(temp_ptr, sizeof(struct account), 1, pfile); if (bytes == 0) { break; } temp_ptr->next = NULL; if ( temp_ptr->number > acc_num ) { acc_num = temp_ptr->number; /* get the last higest assigned acc no */ } if (first_ac == NULL) { first_ac = current_ac = temp_ptr; } else { current_ac->next = temp_ptr; current_ac = temp_ptr; } } fclose(pfile); puts("Records have been initialized successfuly"); puts("Press any key to start the program..."); getchar(); } void prompt(void) { puts("Database name argument is missing"); puts("Try ./bank_ac <database_name>"); }
C
#include "MapsParse.h" #include "ThreadControl.h" /* * 입력받은 메모리 영역에 값을 추출 합니다. */ void getValue(int mem_fd,long staMemAddr,long endMemAddr,void *buf){ //printf("getValue Function! - Start\n"); //printf("staMemAddr : %#lx, endMemAddr : %#lx\n",staMemAddr,endMemAddr); for (; staMemAddr < endMemAddr; staMemAddr += 4096) { //printf("fd : %d, staMemAddr : %#lx, endMemAddr : %#lx\n",mem_fd,staMemAddr,endMemAddr); lseek(mem_fd, staMemAddr, SEEK_SET); read(mem_fd, buf, MEMREADSIZE); for (int j = 0; j < MEMREADSIZE / 4; j++) { memInfoStruct.address = (void*) (staMemAddr + (j * 4)); memInfoStruct.value = ((long**) buf)[j]; memDataList.push_back(memInfoStruct); } } //printf("getValue Function! - End\n"); } void reMemRead(){ //printf("reMemRead Function! - Start\n"); char memFileName[30]; int mem_fd; void *buf = malloc(MEMREADSIZE); sprintf(memFileName, "/proc/%d/mem", privatePid); long staMemAddr = 0,endMemAddr = 0; if(0 < (mem_fd = open(memFileName, O_RDONLY | O_LARGEFILE))){ for (int i = 0; i < findDataList.size(); i++) { findInfoStruct = findDataList.at(i); long cmp = (long)findInfoStruct.address; if((staMemAddr >= cmp) || (cmp >= endMemAddr)){ staMemAddr = (long)findInfoStruct.address; endMemAddr = staMemAddr+MEMREADSIZE; getValue(mem_fd, staMemAddr, endMemAddr,buf); } //printf("staMemAddr : %ld, (long)findInfoStruct.address : %ld, endMemAddr : %ld\n",staMemAddr,(long)findInfoStruct.address,endMemAddr); } }else{ printf("%s\n", errorMsgPid); } free(buf); close(mem_fd); //printf("reMemRead memDataList size : %u \n",memDataList.size()); //printf("reMemRead Function! - End\n"); } void renewal(){ //printf("renewal Function! - Start\n"); if(findDataList.size()){ reMemRead(); long listSize = memDataList.size(); for(int i = 0;i < findDataList.size();i++) { findInfoStruct = findDataList.at(i); for (int j = 0; j < listSize; j++) { memInfoStruct = memDataList.at(j); if ((long) findInfoStruct.address == (long) memInfoStruct.address) { //printf("Find Value : %ld\n",(long) memInfoStruct.value); tempDataList.push_back(memInfoStruct); } } } findDataList.clear(); findDataList = tempDataList; tempDataList.clear(); memDataList.clear(); } //printf("renewal Function! - End\n"); } void ShowDataList(){ //printf("ShowDataList Function! - Start\n"); //printf("List Size : %d\n",findDataList.size()); if(findDataList.size()){ renewal(); } //검색된 값을 출력합니다. for (int i = 0; i < findDataList.size(); i++) { findInfoStruct = findDataList.at(i); printf("address : %#lx, Value : %ld\n",(long)findInfoStruct.address,(long)findInfoStruct.value); } //printf("ShowDataList Function! - End\n"); } void MemRead() { //printf("MemRead Function! - Start\n"); char memFileName[30]; int mem_fd; void *buf = malloc(MEMREADSIZE); //printf("pid : %d \n",privatePid); sprintf(memFileName, "/proc/%d/mem", privatePid); if(0 < (mem_fd = open(memFileName, O_RDONLY | O_LARGEFILE))){ for (int i = 0; i < memReadAreaList.size(); i++) { maps = memReadAreaList.at(i); long staMemAddr = maps.staMemAddr; long endMemAddr = maps.endMemAddr; getValue(mem_fd,staMemAddr,endMemAddr,buf); } }else{ printf("%s\n", errorMsgPid); } free(buf); close(mem_fd); //printf("MemRead Function! - End\n"); }
C
/* Copyright 2017 IBM Corp. * * 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 <stdlib.h> #include <string.h> #include <stdio.h> #include <stdarg.h> #include <stdint.h> #include <ctype.h> #include <errno.h> #include <time.h> #include "utils.h" /* messages are traced here All messages, even error messages, are traced only if verbose is set. There messages are 'techie' and should not be returned unless the user asks for them. */ extern FILE* messageFile; extern int verbose; #define COPY_BLOCK_SIZE 1024 /* File_Copy() copies the source file to the destination file. */ int File_Copy(const char *destinationFilename, const char *sourceFilename) { int rc = 0; char buffer[COPY_BLOCK_SIZE]; size_t bytesRead; size_t bytesWritten; FILE *destination = NULL; /* freed @1 */ FILE *source = NULL; /* freed @2 */ /* open the destination for write */ if (rc == 0) { rc = File_Open(&destination, destinationFilename, "w"); /* closed @1 */ } /* open the source for read */ if (rc == 0) { rc = File_Open(&source, sourceFilename, "r"); /* closed @2 */ } /* copy the source to the destination */ while (rc == 0) { bytesRead = fread(buffer, 1, COPY_BLOCK_SIZE, source); if (bytesRead == 0) { if (feof(source)) { break; } else { if (verbose) fprintf(messageFile, "File_Copy: Error reading from %s\n", sourceFilename); rc = ERROR_CODE; } } bytesWritten = fwrite(buffer, 1, bytesRead, destination); if (bytesWritten != bytesRead) { if (verbose) fprintf(messageFile, "File_Copy: Error writing to %s\n", destinationFilename); } } /* close the destination */ if (destination != NULL) { fclose(destination); /* @1 */ } /* close the source */ if (source != NULL) { fclose(source); /* @2 */ } return rc; } /* File_Open() opens the 'filename' for 'mode' */ int File_Open(FILE **file, const char *filename, const char* mode) { int rc = 0; if (rc == 0) { *file = fopen(filename, mode); if (*file == NULL) { if (verbose) { // Check to make sure we aren't attempting to reroute the message file if (file != &messageFile) { fprintf(messageFile, "File_Open: Error opening %s for %s, %s\n", filename, mode, strerror(errno)); } else { fprintf(stderr, "File_Open: Error opening %s for %s, %s\n", filename, mode, strerror(errno)); } } rc = ERROR_CODE; } } return rc; } /* File_OpenMessageFile() opens the global messageFile. messageFile is used to fprintf messages to the returned output email body. For each new email, the framework first opens for write. Then the signer program can open it for append. Finally, the framework can then open for append to add any final messages. Returns responseType */ int File_OpenMessageFile(const char *outputBodyFilename, const char* mode) { int rc = 0; /* Switch messageFile error and trace printing from stdout to the output body. The design sends framework initialization to stdout so the person initiating the program can see errors. Once it's running, everything else goes to the output body and (usually) back to the user. */ if (rc == 0) { rc = File_Open(&messageFile, outputBodyFilename, mode); } /* if the open succeeded */ if (rc == 0) { /* turn off buffering as a debug aid, so the file gets updated while stepping with a debugger */ setvbuf(messageFile , 0, _IONBF, 0); } /* if the open failed */ else { messageFile = stdout; fprintf(messageFile, "File_OpenMessageFile: Error cannot open %s\n", outputBodyFilename); /* Since the configuration is validated at startup, this should never fail. The only possibilty is that something happened to the platform while the framework was running. No email can be returned and messages go to stdout. */ rc = RESPONSE_NO_EMAIL; } return rc; } /* File_CloseMessageFile() flushes and then closes the global messageFile and them sets it to stdout. If messageFile is already stdout (or NULL), the function does nothing. */ int File_CloseMessageFile(void) { int rc = 0; if ((messageFile != NULL) && /* should never happen after start up */ (messageFile != stdout)) { fflush(messageFile); fclose(messageFile); messageFile = stdout; /* should never print after this, but the messages should go somewhere */ } return rc; } /* File_Readline() returns the next non-comment, non-whitespace line from the file. It replaces the white space at the end of a line with a NUL terminator. */ int File_ReadLine(int *haveLine, /* TRUE is line returned, otherwise FALSE */ char *line, /* returned line */ size_t *lineLength, /* returned actual length */ size_t lineSize, /* max size of line buffer */ FILE *file) /* opened file to read */ { int rc = 0; char *prc = NULL; /* pointer return code */ *haveLine = FALSE; do { /* read the line */ if (rc == 0) { prc = fgets(line, lineSize, file); } /* skip comment lines */ if ((rc == 0) && (prc != NULL)) { if (line[0] == '#') { continue; } } /* skip lines beginning with whitespace */ if ((rc == 0) && (prc != NULL)) { if (isspace(line[0])) { continue; } } if ((rc == 0) && (prc != NULL)) { /* found a line with text */ *haveLine = TRUE; /* check for line overflow */ *lineLength = strlen(line); if (line[*lineLength -1] != '\n') { /* last character before NUL should be newline */ if (verbose) fprintf(messageFile, "File_ReadLine: Error, Line %s is longer that %u bytes\n", line, (unsigned int)lineSize); rc = ERROR_CODE; } } /* strip off white space at the end of the line */ if ((rc == 0) && (prc != NULL)) { while (*lineLength > 0) { if (isspace(line[(*lineLength) - 1])) { line[(*lineLength) - 1] = '\0'; (*lineLength)--; } else { break; } } } break; } while ((rc == 0) && (prc != NULL)); return rc; } /* File_ReadBinaryFile() reads 'filename'. The results are put into 'data', which must be freed by the caller. 'length' indicates the number of bytes read. 'length_max' is the maximum allowed length. If 'length_max' is zero, the caller trusts the file length. */ int File_ReadBinaryFile(unsigned char **data, /* must be freed by caller */ size_t *length, size_t length_max, const char *filename) { int rc = 0; long lrc; size_t src; int irc; FILE *file = NULL; *data = NULL; *length = 0; /* open the file */ if (rc == 0) { rc = File_Open(&file, filename, "rb"); /* closed @1 */ } /* determine the file length */ if (rc == 0) { irc = fseek(file, 0L, SEEK_END); /* seek to end of file */ if (irc == -1L) { if (verbose) fprintf(messageFile, "File_ReadBinaryFile: Error seeking to end of %s\n", filename); rc = ERROR_CODE; } } if (rc == 0) { lrc = ftell(file); /* get position in the stream */ if (lrc == -1L) { if (verbose) fprintf(messageFile, "File_ReadBinaryFile: Error ftell'ing %s\n", filename); rc = ERROR_CODE; } else { *length = (size_t)lrc; /* save the length */ } } if (rc == 0) { irc = fseek(file, 0L, SEEK_SET); /* seek back to the beginning of the file */ if (irc == -1L) { if (verbose) fprintf(messageFile, "File_ReadBinaryFile: Error seeking to beginning of %s\n", filename); rc = ERROR_CODE; } } /* allocate a buffer for the actual data */ if ((rc == 0) && *length != 0) { /* if length_max is zero, the caller trusts the file length */ if (length_max == 0) { length_max = *length; } rc = Malloc_Safe(data, *length, length_max); } /* read the contents of the file into the data buffer */ if ((rc == 0) && *length != 0) { src = fread(*data, 1, *length, file); if (src != *length) { if (verbose) fprintf(messageFile, "File_ReadBinaryFile: Error reading %s, %u bytes\n", filename, (unsigned int)*length); rc = ERROR_CODE; } } if (file != NULL) { irc = fclose(file); /* @1 */ if (irc != 0) { if (verbose) fprintf(messageFile, "File_ReadBinaryFile: Error closing %s\n", filename); rc = ERROR_CODE; } } if (rc != 0) { if (verbose) fprintf(messageFile, "File_ReadBinaryFile: Error reading %s\n", filename); free(*data); data = NULL; } return rc; } /* File_ReadTextFile() reads 'filename'. The results are put into 'text', which must be freed by the caller. 'length' indicates the number of bytes read. A NUL terminator is added to 'text', but the bytes are not scanned for e.g., printable characters. */ int File_ReadTextFile(char **text, /* must be freed by caller */ size_t *length, size_t length_max, const char *filename) { int rc = 0; /* read the file as raw binary data */ if (rc == 0) { rc = File_ReadBinaryFile((unsigned char **)text, length, length_max, filename); } /* realloc one more byte for the NULL terminator */ if (rc == 0) { rc = Realloc_Safe((unsigned char **)text, (*length) + 1); } /* NUL terminate the string */ if (rc == 0) { (*text)[*length] = '\0'; } return rc; } /* File_GetSize() opens a file for read and returns its length */ int File_GetSize(size_t *fileLength, const char *filename) { int rc = 0; FILE *file = NULL; /* freed @1 */ int irc; long lrc; if (rc == 0) { if (filename == NULL) { if (verbose) fprintf(messageFile, "File_GetSize: Error, filename is null\n"); rc = ERROR_CODE; } } if (rc == 0) { rc = File_Open(&file, filename, "rb"); /* freed @1 */ } /* determine the file length */ if (rc == 0) { irc = fseek(file, 0L, SEEK_END); /* seek to end of file */ if (irc == -1L) { if (verbose) fprintf(messageFile, "File_GetSize: Error fseek'ing %s, %s\n", filename, strerror(errno)); rc = ERROR_CODE; } } if (rc == 0) { lrc = ftell(file); /* get position in the stream */ if (lrc == -1L) { if (verbose) fprintf(messageFile, "File_GetSize: Error (fatal) ftell'ing %s, %s\n", filename, strerror(errno)); rc = ERROR_CODE; } else { *fileLength = lrc; /* save the length */ } } if (file != NULL) { fclose(file); /* @1 */ } return rc; } /* File_ValidateOpen() validates that a file can be opened for 'mode'. It then closes the file. */ int File_ValidateOpen(const char *filename, const char *mode) { int rc = 0; FILE *file = NULL; /* freed @1 */ if (rc == 0) { if (filename == NULL) { if (verbose) fprintf(messageFile, "File_ValidateOpen: Error, filename is null\n"); rc = ERROR_CODE; } } if (rc == 0) { rc = File_Open(&file, filename, mode); /* freed @1 */ } /* immediately close */ if (file != NULL) { fclose(file); /* @1 */ } return rc; } /* File_WriteBinaryFile() writes 'length' bytes of data to filename */ int File_WriteBinaryFile(const unsigned char *data, size_t length, const char *filename) { long rc = 0; size_t src; int irc; FILE *file = NULL; /* open the file */ if (rc == 0) { rc = File_Open(&file, filename, "wb"); /* closed @1 */ } /* write the contents of the data buffer into the file */ if (rc == 0) { src = fwrite(data, 1, length, file); if (src != length) { if (verbose) fprintf(messageFile, "File_WriteBinaryFile: Error writing %s\n", filename); rc = ERROR_CODE; } } if (file != NULL) { irc = fclose(file); /* @1 */ if (irc != 0) { if (verbose) fprintf(messageFile, "File_WriteBinaryFile: Error closing %s\n", filename); rc = ERROR_CODE; } } return rc; } /* File_WriteBinaryFileVa() writes filename with a varargs list of length / buffer pairs. A zero length terminates the loop */ int File_WriteBinaryFileVa(const char *filename, ...) { long rc = 0; FILE *file = NULL; /* closed @1 */ va_list ap; uint32_t length; unsigned char *buffer; size_t src; int irc; int done = FALSE; /* open the file */ if (rc == 0) { rc = File_Open(&file, filename, "wb"); /* closed @1 */ } if (rc == 0) { va_start(ap, filename); } while ((rc == 0) && !done) { length = va_arg(ap, size_t); /* first vararg is the length */ if (length != 0) { /* loop until a zero length argument terminates */ buffer = va_arg(ap, unsigned char *); /* second vararg is the array */ src = fwrite(buffer , 1, length, file); /* write the buffer */ if (src != length) { if (verbose) fprintf(messageFile, "File_WriteBinaryFileVa: Error writing %s\n", filename); rc = ERROR_CODE; } } else { done = TRUE; } } if (file != NULL) { irc = fclose(file); /* @1 */ if (irc != 0) { if (verbose) fprintf(messageFile, "File_WriteBinaryFileVa: Error closing %s\n", filename); rc = ERROR_CODE; } } return rc; } /* File_GetNameValue() reads the next non-comment, non-whitespace line from the file. If a line is found, it allocates memory and returns the 'name' and 'value'. name and value are separated by a '=' character. */ int File_GetNameValue(int *haveLine, char **name, /* freed by caller */ char **value, /* freed by caller */ char *lineBuffer, size_t lineBufferLength, FILE *file) { int rc = 0; size_t lineLength; char *token; if (rc == 0) { rc = File_ReadLine(haveLine, lineBuffer, &lineLength, lineBufferLength, file); } /* get first token */ if ((rc == 0) && *haveLine) { token = strtok(lineBuffer, "="); /* get first token */ if (token == NULL) { /* malformed line */ if (verbose) fprintf(messageFile, "File_GetNameValue: Error, bad format, missing =\n"); if (verbose) fprintf(messageFile, "File_GetNameValue: Line: %s\n", lineBuffer); rc = ERROR_CODE; } } if ((rc == 0) && *haveLine) { rc = Malloc_Strcpy(name, token); } if ((rc == 0) && *haveLine) { token = strtok(NULL,"" ); /* get next token, rest of string */ if (token == NULL) { /* malformed line */ if (verbose) fprintf(messageFile, "File_GetNameValue: Error, bad format, missing =\n"); if (verbose) fprintf(messageFile, "File_GetNameValue: Line: %s\n", lineBuffer); rc = ERROR_CODE; } } if ((rc == 0) && *haveLine) { rc = Malloc_Strcpy(value, token); } return rc; } /* File_MapNameToValue() scans lines from file of the form name=value if found, memory is malloc'ed for the value and the value is copied if not found, an error is returned */ int File_MapNameToValue(char **value, /* freed by caller */ const char *name, /* name to search for */ char *lineBuffer, /* supplied buffer for lines */ size_t lineBufferLength, /* size of the line buffer */ FILE *file) /* input file stream */ { int rc = 0; int irc = 0; int haveLine; /* true if more lines in the file stream */ size_t lineLength; /* length of the current line */ char *token; /* tokenizing the line */ do { if (rc == 0) { rc = File_ReadLine(&haveLine, lineBuffer, &lineLength, lineBufferLength, file); } /* out of lines and no match is error */ if (rc == 0) { if (!haveLine) { if (verbose) fprintf(messageFile, "File_MapNameToValue: Error, missing value for %s\n", name); rc = ERROR_CODE; } } /* get subject, first token */ if (rc == 0) { token = strtok(lineBuffer, "="); /* get first token */ if (token == NULL) { /* malformed line */ if (verbose) fprintf(messageFile, "File_MapNameToValue: Error, bad format, missing =\n"); rc = ERROR_CODE; } } /* compare name */ if (rc == 0) { irc = strcmp(name, token); if (irc == 0) { /* match, done */ break; } } } while (rc == 0); if (rc == 0) { token = strtok(NULL,"" ); /* get next token, rest of string */ if (token == NULL) { /* malformed line */ if (verbose) fprintf(messageFile, "File_MapNameToValue: Error, bad format, missing value for %s\n", name); rc = ERROR_CODE; } } /* copy token to project file name */ if (rc == 0) { rc = Malloc_Strcpy(value, token); } return rc; } /* File_MapNameToBool() scans lines from file of the form name=value if found, the value is checked for 'true' or 'false' and the boolean is returned. if not found, or the value is not true or false, an error is returned */ int File_MapNameToBool(int *booln, const char *name, char *lineBuffer, size_t lineBufferLength, FILE *file) { int rc = 0; char *booleanString = NULL; /* freed @1 */ if (rc == 0) { rc = File_MapNameToValue(&booleanString, /* freed by caller */ name, lineBuffer, lineBufferLength, file); } /* look for true or false, no other string */ if (rc == 0) { if (strcmp(booleanString, "true") == 0) { *booln = TRUE; } else if (strcmp(booleanString, "false") == 0) { *booln = FALSE; } else { if (verbose) fprintf(messageFile, "File_MapNameToBool: Error mapping %s, value is %s\n", name, booleanString); rc = ERROR_CODE; } } free(booleanString); /* @1 */ return rc; } /* File_MapNameToUint() scans lines from file of the form name=value if found, the value is checked for an unsigned integer and the integer is returned. if not found, or the value is not an unsigned integer, an error is returned */ int File_MapNameToUint(unsigned int *value, const char *name, char *lineBuffer, size_t lineBufferLength, FILE *file) { int rc = 0; int irc; char *intString = NULL; /* freed @1 */ char dummy; /* extra characters at the end of the line */ if (rc == 0) { rc = File_MapNameToValue(&intString, /* freed by caller */ name, lineBuffer, lineBufferLength, file); } /* look for unsigned int, no other string */ if (rc == 0) { irc = sscanf(intString, "%u%c", value, &dummy); if (irc != 1) { /* when this function returns an error, set the value to 0 so that the later delete doesn't think there are items to free */ *value = 0; if (verbose) fprintf(messageFile, "File_MapNameToUint: Error mapping %s, value is %s\n", name, intString); rc = ERROR_CODE; } } free(intString); /* @1 */ return rc; } /* File_GetNameValueArray() parses the rest of 'file' for name=value pairs. It allocates the 'names' and 'values' arrays and fills in the elements lineBuffer is a temporary, to hold lines. */ int File_GetNameValueArray(char ***names, /* freed by caller */ char ***values, /* freed by caller */ size_t *length, /* final length of the array */ char *lineBuffer, size_t lineBufferLength, FILE *file) { int rc = 0; int haveLine = TRUE; char *name = NULL; char *value = NULL; char *tmp; /* used by realloc */ *length = 0; /* check that names and values are NULL at entry, sanity check for memory leak */ if (rc == 0) { if (names == NULL || values == NULL) { if (verbose) fprintf(messageFile, "File_GetNameValueArray: names %p or values %p are NULL\n", names, values); rc = 1; } else if ((*names != NULL) || (*values != NULL)) { if (verbose) fprintf(messageFile, "File_GetNameValueArray: names %p or values %p not NULL\n", *names, *values); rc = 1; } } while ((rc == 0) && haveLine) { name = NULL; value = NULL; /* get a name - value pair */ if (rc == 0) { rc = File_GetNameValue(&haveLine, &name, /* freed by caller */ &value, /* freed by caller */ lineBuffer, lineBufferLength, file); } /* if found a pair */ if ((rc == 0) && haveLine) { /* increase the array size */ (*length)++; /* grow the names array */ tmp = realloc(*names, *length * sizeof(char *)); if (tmp != NULL) { *names = (char **)tmp; } else { if (verbose) fprintf(messageFile, "File_GetNameValueArray: " "Error allocating memory for %u names\n", (unsigned int)*length); rc = ERROR_CODE; } } if ((rc == 0) && haveLine) { /* grow the values array */ tmp = realloc(*values, *length * sizeof(char *)); if (tmp != NULL) { *values = (char **)tmp; } else { if (verbose) fprintf(messageFile, "File_GetNameValueArray: " "Error allocating memory for %u values\n", (unsigned int)*length); rc = ERROR_CODE; } } if ((rc == 0) && haveLine) { /* assign name and value to array */ (*names)[(*length) - 1] = name; (*values)[(*length) - 1] = value; } } return rc; } /* File_GetValueArray() parses 'file' for values. The number of values is determined by the first line, which is of the form 'name'=integer It allocates the 'values' array and fills in the elements. */ int File_GetValueArray(char ***values, /* freed by caller */ size_t *length, /* items in the array */ const char *name, char *lineBuffer, size_t lineBufferLength, FILE *file) { int rc = 0; size_t i; int haveLine = TRUE; size_t lineLength; *length = 0; /* check that values is NULL at entry, sanity check for memory leak */ if (rc == 0) { if (*values != NULL) { if (verbose) fprintf(messageFile, "File_GetValueArray: values %p not NULL\n", *values); } } /* get the count of values in the array */ if (rc == 0) { rc = File_MapNameToUint((unsigned int *)length, name, lineBuffer, lineBufferLength, file); } /* allocate the array for the values */ if (rc == 0) { rc = Malloc_Safe((unsigned char **)values, /* freed by caller */ *length * sizeof(char *), *length * sizeof(char *)); /* trust the configuration file */ } /* immediately NULL the array so it can be freed */ for (i = 0 ; (rc == 0) && (i < *length) ; i++) { (*values)[i] = NULL; } /* for each expected value in the array */ for (i = 0 ; (rc == 0) && (i < *length) ; i++) { /* each line is a value */ if (rc == 0) { rc = File_ReadLine(&haveLine, lineBuffer, &lineLength, lineBufferLength, file); } /* insufficient lines is an error */ if (rc == 0) { if (!haveLine) { if (verbose) fprintf(messageFile, "File_GetValueArray: Error, not %u entries for %s\n", (unsigned int)*length, name); rc = ERROR_CODE; } } /* allocate memory for the value and copy into the array entry */ if (rc == 0) { rc = Malloc_Strcpy(&((*values)[i]), lineBuffer); /* freed by caller */ } } return rc; } /* File_LogTime() adds the current date and time to 'logFile' */ void File_LogTime(FILE *logFile) { time_t log_time; log_time = time(NULL); fprintf(logFile, "\n%s", ctime(&log_time)); return; } /* File_Printf() does an fprintf of the same parameters to both lFile (typically a log file) and mfile (typically the messageFile, the output body). lFile is prefixed by a tab character. If either is NULL, that file is skipped. */ void File_Printf(FILE *lFile, FILE *mFile, const char *format, ...) { va_list va; va_start(va, format); /* print to the log file if it's not NULL */ if (lFile != NULL) { fprintf(lFile,"\t"); va_start(va, format); vfprintf(lFile, format, va); va_end(va); } /* print to the messages file if it's not NULL */ if (mFile != NULL) { va_start(va, format); vfprintf(mFile, format, va); va_end(va); } return; } /* Arguments_Init() sets all elements of the argv array to NULL. This permits the free() to be safe. */ void Arguments_Init(Arguments *arguments) { size_t i; arguments->argvBytes = 0; for (i = 0 ; i < MAX_ARGV_BODY ; i++) { arguments->argv[i] = NULL; } return; } /* Argvuments_Delete() frees all elements of argv and sets them back to NULL. Secret values are cleared before the memory is freed. These are currently: -pwd */ void Arguments_Delete(Arguments *arguments) { size_t i; /* clear the plaintext password */ Arguments_ClearSecret("-pwd", arguments); /* free allocated memory */ for (i = 0 ; i < MAX_ARGV_BODY ; i++) { free(arguments->argv[i]); arguments->argv[i] = NULL; } return; } /* Arguments_ClearSecret() looks for 'flag' and zeros the value associated with the flag */ void Arguments_ClearSecret(const char *flag, Arguments *arguments) { size_t i; size_t length; int irc; /* start at 1, argvBody[0] is the name of the program, not a flag */ for (i = 1 ; i < (size_t)arguments->argc ; i++) { irc = strcmp(arguments->argv[i], flag); if (irc == 0) { /* found a flag match */ i++; /* advance past the flag to the value */ /* In some error cases the -pwd arg may exist but the companion doesn't */ if (NULL != arguments->argv[i]) { length = strlen(arguments->argv[i]); memset(arguments->argv[i], '\0', length); } } } return; } /* Arguments_AddPairTo() adds the C strings 'flag' and 'value' pair to argv. argc and argvBytes are updated accordingly. */ int Arguments_AddPairTo(Arguments *arguments, const char *flag, const char *value) { int rc = 0; /* check flag format */ if (rc == 0) { } /* add flag */ if (rc == 0) { rc = Arguments_AddTo(arguments, flag, FALSE); } /* add value */ if (rc == 0) { rc = Arguments_AddTo(arguments, value, FALSE); } return rc; } /* Arguments_AddTo() adds the C string 'data' to argvBody. argvBytes is updated accordingly. If zero is TRUE, the item is added at argv[0]. If FALSE, the item is added at the end and argc is updated accordingly. 'zero' handles the speccial case of the program name. */ int Arguments_AddTo(Arguments *arguments, const char *data, int zero) { int rc = 0; size_t i; size_t length; /* check for NULL argument */ if (rc == 0) { if (data == NULL) { if (verbose) fprintf(messageFile, "Arguments_AddTo: Error, adding NULL argument\n"); rc = ERROR_CODE; } } /* check for array overflow */ if (rc == 0) { length = strlen(data); } /* check data for illegal characters */ for (i = 0 ; (rc == 0) && (i < length) ; i++) { if (!isprint(data[i])) { if (verbose) fprintf(messageFile, "Arguments_AddTo: Error, argument not printable at index %u\n", (unsigned int)i); rc = ERROR_CODE; } } /* check for array overflow. This is a framwork compile time limitation. The -1 reserves the last entry as a NULL, needed by exec() */ if ((rc == 0) && !zero) { if (arguments->argc > (MAX_ARGV_BODY-1)) { if (verbose) fprintf(messageFile, "Arguments_AddTo: Error, overflows array of %u entries\n", MAX_ARGV_BODY); rc = ERROR_CODE; } } /* check for total bytes overflow. This is a platform OS limitation */ if (rc == 0) { if ((arguments->argvBytes + length) > ARG_MAX) { if (verbose) fprintf(messageFile, "Arguments_AddTo: Error, %s overflows argument list length\n", data); rc = ERROR_CODE; } } /* malloc and copy */ if (rc == 0) { if (!zero) { rc = Malloc_Strcpy(&(arguments->argv[arguments->argc]), data); } else { rc = Malloc_Strcpy(&(arguments->argv[0]), data); } } if (rc == 0) { if (!zero) { arguments->argc++; /* adjust the argument count */ } arguments->argvBytes += length; /* adjust the total number of bytes */ } return rc; } /* Arguments_GetFrom() iterates through arguments->argv, searching for flag. If found, the value is returned. The value is a pointer into arguments->argv. It is not allocated and should not be freed. If not found, an error is returned. */ int Arguments_GetFrom(const char **value, const char *flag, Arguments *arguments) { int rc = 0; int irc; int i; int found = FALSE; /* start with [1], [0] is the program name, not a command line argument */ for (i = 1 ; !found && (i < arguments->argc) ; i++) { irc = strcmp(flag, arguments->argv[i]); if ((irc == 0) && ((i+1) < arguments->argc)) { /* if a flag match */ *value = arguments->argv[i+1]; /* return the value */ found = TRUE; } } if (!found) { if (verbose) fprintf(messageFile, "Arguments_GetFrom: %s not found\n", flag); rc = ERROR_CODE; } return rc; } /* character array handling */ /* Array_GetLine() acts on a character array. It returns the next non-comment, non-whitespace line from the array. It replaces the white space at the end of a line with NUL. It also returns a pointer to the next line. Returns error if the line is too long or contains non-printable characters. */ int Array_GetLine(int *haveLine, /* TRUE if line returned, otherwise FALSE */ char *outLine, /* returned line */ const char **nextLine, /* returned pointer to next line */ size_t lineSize, /* max size of line buffer */ const char *inLines, /* input character array */ FILE *logFile) /* audit log file */ { int rc = 0; size_t i = 0; /* index into outLine */ const char *ptr; *haveLine = FALSE; ptr = inLines; /* starting point */ /* skip comment lines or lines beginning with whitespace */ if (rc == 0) { /* skip comment lines or lines beginning with whitespace */ while ((*ptr == '#') || (isspace(*ptr))) { /* if the line should be ignored, search for next newline, then increment past it */ for ( ; *ptr != '\0' ; ptr++) { if (*ptr == '\n') { ptr++; /* point to next line and loop back to check for skip */ break; } } } /* found another line (or at the end of the buffer) */ /* scan to the end of the current line or the end of the buffer */ while ((*ptr != '\0') && (*ptr != '\n')) { *haveLine = TRUE; /* check for overflow, leave space for NUL */ if (i == (lineSize-1)) { outLine[lineSize-1] = '\0'; /* terminate the line for error message */ File_Printf(logFile, messageFile, "Error, Line is longer than %u bytes: %s\n", lineSize, outLine); if (verbose) fprintf(messageFile, "Array_GetLine: Error, Line is longer than %u bytes: %s\n", (unsigned int)lineSize, outLine); rc = ERROR_CODE; break; } /* scan for non-printable characters */ if (!isprint(*ptr)) { outLine[i] = '\0'; /* terminate the line for error message */ File_Printf(logFile, messageFile, "Error, Line %s has non-printable character at index %u\n", outLine, i); if (verbose) fprintf(messageFile, "Array_GetLine: " "Error, Line %s has non-printable character at index %u\n", outLine, (unsigned int)i); rc = ERROR_CODE; break; } /* character valid, copy from input array to output line */ outLine[i] = *ptr; ptr++; /* next input character */ i++; /* next output character */ } } /* set next line */ if (rc == 0) { if (*ptr == '\0') { /* if finished, just point to NUL terminator for input array */ *nextLine = ptr; } else { *nextLine = ptr+1; /* if more lines, point past newline */ } } if ((rc == 0) && *haveLine) { outLine[i] = '\0'; /* terminate the line */ i--; /* search back from last character */ /* strip off white space at the end of the line */ for ( ; (i > 0) && isspace(outLine[i]) ; i--) { outLine[i] = '\0'; } if (outLine[0] == '\0') { if (verbose) fprintf(messageFile, "Array_GetLine: Error: Line has only whitespace\n"); rc = ERROR_CODE; /* this should never occur, line with all whitespace should be ignored */ } } return rc; } /* Malloc_Strcpy() malloc's an array for the 'in' string and then copies the string and the terminating NUL */ int Malloc_Strcpy(char **out, /* freed by caller */ const char *in) { int rc = 0; /* malloc for the data */ if (rc == 0) { rc = Malloc_Safe((unsigned char **)out, strlen(in) + 1, strlen(in) + 1); /* trust configuration files */ } /* copy the data */ if (rc == 0) { strcpy(*out, in); } return rc; } /* Malloc_Safe() is a wrapper around malloc that detects memory leaks, uninitialized pointers, or an unreasonably large request */ int Malloc_Safe(unsigned char **ptr, size_t len, size_t max_length) { int rc = 0; if (rc == 0) { if (len > max_length) { if (verbose) fprintf(messageFile, "Malloc_Safe: Error, length %u too large\n", (unsigned int)len); rc = ERROR_CODE; } } if (rc == 0) { if (*ptr != NULL) { if (verbose) fprintf(messageFile, "Malloc_Safe: Error, pointer is not NULL : %p\n", *ptr); rc = ERROR_CODE; } } if (rc == 0) { *ptr = malloc(len); if (*ptr == NULL) { if (verbose) fprintf(messageFile, "Malloc_Safe: Error, could not allocate %u bytes : %p\n", (unsigned int)len, *ptr); rc = ERROR_CODE; } } return rc; } /* Realloc_Safe() is a general purpose wrapper around realloc() The caller is responsible for validating that 'size' is reasonable. */ int Realloc_Safe(unsigned char **buffer, size_t size) { int rc = 0; unsigned char *tmpptr = NULL; if (rc == 0) { tmpptr = realloc(*buffer, size); if (tmpptr == NULL) { if (verbose) fprintf(messageFile, "Realloc_Safe: Error reallocating %u bytes\n", (unsigned int)size); rc = ERROR_CODE; } } if (rc == 0) { *buffer = tmpptr; } return rc; } /* Format Conversion */ /* Format_ToHexascii() converts binary to hex ascii and appends a NUL terminator */ void Format_ToHexascii(char *string, unsigned char *binary, size_t length) { size_t i; for (i = 0 ; i < length ; i++, binary++, string += 2) { sprintf(string, "%02x", *binary); } return; } /* Format_FromHexAscii() converts 'string' in hex ascii to 'binary' of 'length' It assumes that the string has enough bytes to accommodate the length. */ int Format_FromHexascii(unsigned char *binary, const char *string, size_t length) { int rc = 0; size_t i; for (i = 0 ; (rc == 0) && (i < length) ; i++) { rc = Format_ByteFromHexascii(binary + i, string + (i * 2)); } return rc; } /* Format_ByteFromHexAscii() converts two bytes of hex ascii to one byte of binary */ int Format_ByteFromHexascii(unsigned char *byte, const char *string) { int rc = 0; size_t i; char c; *byte = 0; for (i = 0 ; (rc == 0) && (i < 2) ; i++) { (*byte) <<= 4; /* big endian, shift up the nibble */ c = *(string + i); /* extract the next character from the string */ if ((c >= '0') && (c <= '9')) { *byte += c - '0'; } else if ((c >= 'a') && (c <= 'f')) { *byte += c + 10 - 'a'; } else if ((c >= 'A') && (c <= 'F')) { *byte += c + 10 - 'A'; } else { if (verbose) fprintf(messageFile, "Format_ByteFromHexascii: " "Error: Line has non hex ascii character: %c\n", c); rc = ERROR_CODE; } } return rc; }
C
/************************************************************************* > File Name: seqtest.c > Author: suziteng > Mail: [email protected] > Created Time: 2019年05月04日 星期六 10时11分16秒 ************************************************************************/ #include <stdio.h> #include <stdlib.h> #include <time.h> typedef struct Vector { int *data; int size, length; } Vector; Vector *init(int n) { Vector *p = (Vector *)malloc(sizeof(Vector)); p->data = (int *)malloc(sizeof(int) * n); p->size = n; p->length = 0; return p; } int insert(Vector *v, int ind, int val) { if (v->length == v->size) return 0; if (ind < 0 || ind > v->length) return 0; for (int i = v->length - 1; i >= ind; i--) { v->data[i + 1] = v->data[i]; } v->data[ind] = val; v->length += 1; return 1; } int erase(Vector *v, int ind) { if (ind < 0 || ind >= v->length) return 0; for (int i = ind + 1; i < v->length; i++) { v->data[i - 1] = v->data[i]; } v->length -= 1; return 1; } void clear(Vector *v) { if (v == NULL) return ; free(v->data); free(v); return ; } void output(Vector *v) { printf("arr = ["); for (int i = 0; i < v->length; i++) { printf(" %d", v->data[i]); } printf(" ]\n"); return ; } int main() { #define MAX_OP 20 int op, ind, val; Vector *v = init(MAX_OP); for (int i = 0; i < MAX_OP; i++) { op = rand() % 2; ind = rand() % (v->length + 3) - 1; val = rand() % 100; switch (op) { case 0: { printf("insert %d to vector at %d = %d\n", val, ind, insert(v, ind, val)); output(v); } break; case 1: { printf("erase element at %d from vector = %d\n", ind, erase(v, ind)); output(v); } break; default: fprintf(stderr , "wrong op %d\n", op); break; } } clear(v); return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* lst_dir.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: vjovanov <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/01/11 08:42:38 by vjovanov #+# #+# */ /* Updated: 2019/01/20 19:54:54 by vjovanov ### ########.fr */ /* */ /* ************************************************************************** */ #include "ft_ls.h" t_dir *new_dir(void) { return (NULL); } t_dir *insert_child_dir(t_dir *lst_dir, t_dir *new_dirs) { t_dir *tmp; if (new_dirs == NULL) return (lst_dir); tmp = new_dirs; while (tmp->next != NULL) tmp = tmp->next; tmp->next = lst_dir->next; lst_dir->next = new_dirs; return (lst_dir); } t_dir *fill_lst_dir(t_file *lst_file, t_dir *lst_dir) { t_file *tmp; t_dir *new_dirs; char *parent; tmp = lst_file; new_dirs = new_dir(); parent = NULL; while (tmp != NULL) { if ((parent = (LST_DIR->parent == NULL) ? ft_strdup(LST_DIR->pathname) : ft_strjoin(LST_DIR->parent, LST_DIR->pathname)) == NULL) return (NULL); if (tmp->file_type == 'd' && !(ft_strequ(tmp->pathname, ".") || ft_strequ(tmp->pathname, ".."))) new_dirs = insert_back_dir(new_dirs, tmp->pathname, parent); ft_memdel((void**)&(parent)); tmp = tmp->next; } lst_dir = insert_child_dir(lst_dir, new_dirs); new_dirs = NULL; return (lst_dir); } t_dir *insert_front_dir(t_dir *dir, char *path, char *parent) { t_dir *new; if (path == NULL || (new = malloc(sizeof(*new))) == NULL) return (NULL); if (parent == NULL) { new->parent = ft_strdup(""); new->pathname = ft_strdup(path); } else { new->parent = ft_strdup(path); new->pathname = ft_strjoin("/", path); } if (new->parent == NULL || new->pathname == NULL) return (NULL); if (is_empty_dir(dir)) new->next = NULL; else new->next = dir; return (new); } t_dir *insert_back_dir(t_dir *dir, char *path, char *parent) { t_dir *new; t_dir *tmp; if (path == NULL || (new = malloc(sizeof(*new))) == NULL) return (NULL); if (parent == NULL) new->parent = ft_strdup(""); if (parent == NULL) new->pathname = ft_strdup(path); if (parent != NULL) new->parent = ft_strdup(parent); if (parent != NULL) new->pathname = (ft_strequ(parent, "/")) ? ft_strdup(path) : ft_strjoin("/", path); new->next = NULL; if (new->parent == NULL || new->pathname == NULL) return (del_front_dir(new)); if (is_empty_dir(dir)) return (new); tmp = dir; while (tmp->next != NULL) tmp = tmp->next; tmp->next = new; return (dir); } /* ** void display_lst_dir(t_dir *dir) ** { ** t_dir *tmp; ** ** tmp = dir; ** if (is_empty_dir(dir)) ** { ** ft_printf("--\n"); ** ft_printf("(null)\n"); ** ft_printf("--\n"); ** } ** while (dir != NULL) ** { ** ft_printf("--\n"); ** ft_printf("path: %s\n", dir->pathname); ** ft_printf("parent: %s\n", dir->parent); ** ft_printf("--\n"); ** dir = dir->next; ** } ** dir = tmp; ** } */
C
#include <stdio.h> #include <stdlib.h> #include "genericlist.h" LIST slist; int main() { int arr[10] = {11, 12, 13, 20, 30, 111, 987, 567, 876, 8796}; int i, *aa; GLITER iter; int *x = malloc(sizeof(int)); *x = 55; gListInit(&slist, "G-SLIST"); for (i = 0; i < sizeof(arr)/sizeof(arr[0]); i++) { gListAddElem(&slist, &arr[i]); } gListShow(&slist); gListAddElem(&slist, x); gListRemoveElem(&slist, &arr[0]); gListRemoveElem(&slist, &arr[5]); gListShow(&slist); i = 0; for(aa = gLiistIterInit(&slist, &iter); aa; aa = gLiistIterNext(&slist, &iter)) { printf("Elem(%d) = %d\n", i++, *aa); } printf("\n"); i = 0; for(aa = gLiistIterInit(&slist, &iter); aa; aa = gLiistIterNext(&slist, &iter)) { if (*aa == 30) { gLiistIterRemove(&slist, &iter); continue; } printf("Elem(%d) = %d\n", i++, *aa); } printf("\n"); i = 0; for(aa = gLiistIterInit(&slist, &iter); aa; aa = gLiistIterNext(&slist, &iter)) { printf("Elem(%d) = %d\n", i++, *aa); } gListShow(&slist); return 1; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include <omp.h> #define I(i, j) ((N) * (i) + (j)) #define NUM_ITERATIONS 1000 #define N 2000 void stencil2D(double* G1, double* G2) { for (size_t it = 0; it < NUM_ITERATIONS; it++) { for (size_t i = 1; i < N - 1; i++) { for (size_t j = 1; j < N - 1; j++) { G1[I(i, j)] = 0.2 * (G2[I(i - 1, j)] + G2[I(i + 1, j)] + G2[I(i, j - 1)] + G2[I(i, j + 1)] + G2[I(i, j)]); } } memcpy(G1, G2, sizeof(long) * N * N); } } void stencil2D_nocopy(double* G1, double* G2) { for (size_t it = 0; it < NUM_ITERATIONS; it++) { for (size_t i = 1; i < N - 1; i++) { for (size_t j = 1; j < N - 1; j++) { G1[I(i, j)] = 0.2 * (G2[I(i - 1, j)] + G2[I(i + 1, j)] + G2[I(i, j - 1)] + G2[I(i, j + 1)] + G2[I(i, j)]); } } double* tmp = G1; G1 = G2; G2 = tmp; } } void stencil2D_parallel_nocopy(double* G1, double* G2) { #pragma omp parallel { for (size_t it = 0; it < NUM_ITERATIONS; it++) { #pragma omp for for (size_t i = 1; i < N - 1; i++) { for (size_t j = 1; j < N - 1; j++) { G1[I(i, j)] = 0.2 * (G2[I(i - 1, j)] + G2[I(i + 1, j)] + G2[I(i, j - 1)] + G2[I(i, j + 1)] + G2[I(i, j)]); } } double* tmp = G1; G1 = G2; G2 = tmp; } } } void test(const char* func_name, void f(double*, double*)) { double* G1 = malloc(sizeof(double) * N * N); double* G2 = malloc(sizeof(double) * N * N); // populate matrix with random numbers for (size_t i = 0; i < N - 1; i++) { for (size_t j = 0; j < N - 1; j++) { G1[I(i, j)] = G2[I(i, j)] = rand(); } } double time = omp_get_wtime(); f(G1, G2); printf("%s: %fs\n", func_name, omp_get_wtime()-time); free(G1); free(G2); } int main(void) { time_t t; srand((unsigned) time(&t)); test("stencil2D", stencil2D); test("stencil2D_nocopy", stencil2D_nocopy); test("stencil2D_parallel_nocopy", stencil2D_parallel_nocopy); return 0; }
C
#include <unistd.h> #include <stdio.h> #include <stdlib.h> void hacerTarea() { fprintf(stdout,"Mi PID es %d y el de mi padre %d\n", getpid(), getppid()); exit(0); } void main() { int i,pid; fprintf(stdout,"Mi PID es el %d\n", getpid()); for (i = 0; i < 3; i++) { pid = fork(); if (pid == 0) hacerTarea(); } fprintf(stdout, "Entrando en bucle infinito... \n"); while (1); }
C
#include<stdio.h> int main() { int arr[]={10,20,30,40,50}; int i=0,n=5,item=60,k=2; printf("Original Array: \n"); for(i=0;i<n;i++) { printf("arr[%d]=%d \n", i, arr[i]); } arr[2]=item; printf("Updated Array: \n"); for(i=0;i<n;i++) { printf("arr[%d]=%d \n", i, arr[i]); } return 0; }
C
#include <math.h> #include "dft.h" #define M_PI 3.14159265358979323846264338327950288 /* @brief original dft process per mathmatical formula * * Y[m] = sum { X[n] (cos(2 * PI * n * m / N) - jsin(2 * PI * n * m / N)) } * X[n] = Real[2 * n] + jImag[2 * n]] * * Real(Y[m]) = y[2 * m] = x[2 * n] * cosf() + x[2 * n + 1] * sinf() * Imag(Y[m]) = y[2 * m + 1] = x[2 * n + 1] * cosf() - x[2 * n] * sinf() * * @param[in] x pointer of complex input smaples(2 * n is real part, 2 * n +1 is image) in time domain * @param[out] y pointer of dft output sequences in frequency domain * @papra[in] N size or points of dft performed * * return none * */ //O(N^2) void dftProcess(const float *x, float *y, size_t N) { size_t m, n; for (m = 0; m < N; m++) { y[2 * m] = 0.0f; y[2 * m +1] = 0.0f; for (n = 0; n < N; n++) { const float c = cosf(2 * M_PI * m * n / N); const float s = sinf(2 * M_PI * m * n / N); y[2 * m] += x[2 * n] * c + x[2 * n + 1] * s; y[2 * m + 1] += x[2 * n + 1] * c - x[2 * n] * s; } } } // inverse dft void idftProcess(const float *x, float *y, size_t N) { size_t m, n; for (m = 0; m < N; m++) { y[2 * m] = 0.0f; y[2 * m +1] = 0.0f; for (n = 0; n < N; n++) { const float c = cosf(2 * M_PI * m * n / N); const float s = sinf(2 * M_PI * m * n / N); y[2 * m] += x[2 * n] * c - x[2 * n + 1] * s; y[2 * m + 1] += x[2 * n + 1] * c + x[2 * n] * s; } y[2 * m] = y[2 * m] / N; y[2 * m +1] = y[2 * m + 1] / N; } }
C
void controllo(int pipein) { pos astronave, missile_left, missile_right, valore_letto; astronave.x = -1; missile_left.x = -1; missile_right.x = -1; do { read(pipein, &valore_letto, sizeof(valore_letto)); /* leggo dalla pipe */ if (valore_letto.c == NAVICELLA) { if (astronave.x >= 0) { /* cancello la 'vecchia' posizione dell'astronave*/ mvaddch(astronave.y, astronave.x, ' '); } astronave = valore_letto; } if (valore_letto.c == MISSILE_SX) { if (missile_left.x >= 0) { /* cancello la 'vecchia' posizione della */ mvaddch(missile_left.y, missile_left.x, ' '); } missile_left = valore_letto; } if (valore_letto.c == MISSILE_DX) { if (missile_right.x <= MAXX) { mvaddch(missile_right.y, missile_right.x, ' '); } missile_right = valore_letto; } mvaddch(valore_letto.y, valore_letto.x, valore_letto.c); curs_set(0); refresh(); } while (1); }
C
#define _GNU_SOURCE #include <sys/types.h> #include <sys/syscall.h> #include <unistd.h> #include <stdio.h> #include <errno.h> #ifndef __NR_pidfd_open #define __NR_pidfd_open 434 /* System call # on most architectures */ #endif int main(void) { pid_t self = getpid(); int pidfd = syscall(__NR_pidfd_open, self, 0); if (pidfd < 0) { if (errno == ENOSYS) { printf("%d %d\n", -1, -1); } perror("pidfd_open"); return 1; } printf("%d %d\n\n\n", self, pidfd); fclose (stdout); pause(); return 0; }
C
#include <stdlib.h> #include "ef_fd.h" static PetscErrorCode set_second_order(ef_fd *fd) { PetscErrorCode ierr; ierr = ef_stencil_create(&fd->first[-1], 3, 0);CHKERRQ(ierr); ierr = ef_stencil_create(&fd->second[-1], 4, 0);CHKERRQ(ierr); ierr = ef_stencil_create(&fd->first[0], 3, 1);CHKERRQ(ierr); ierr = ef_stencil_create(&fd->second[0], 3, 1);CHKERRQ(ierr); ierr = ef_stencil_create(&fd->first[1], 3, 2);CHKERRQ(ierr); ierr = ef_stencil_create(&fd->second[1], 4, 3);CHKERRQ(ierr); fd->first[0]->v[-1] = -0.5; fd->first[0]->v[0] = 0; fd->first[0]->v[1] = 0.5; fd->first[-1]->v[0] = -3*.5; fd->first[-1]->v[1] = 4*.5; fd->first[-1]->v[2] = -.5; fd->first[1]->v[0] = 3*.5; fd->first[1]->v[-1] = -4*.5; fd->first[1]->v[-2] = .5; fd->second[0]->v[-1] = 1; fd->second[0]->v[0] = -2; fd->second[0]->v[1] = 1; fd->second[-1]->v[0] = 2; fd->second[-1]->v[1] = -5; fd->second[-1]->v[2] = 4; fd->second[-1]->v[3] = -1; fd->second[1]->v[0] = 2; fd->second[1]->v[-1] = -5; fd->second[1]->v[-2] = 4; fd->second[1]->v[-3] = -1; return 0; } PetscErrorCode ef_fd_create(ef_fd **effd, ef_fd_type type) { PetscErrorCode ierr; ef_fd *fd = (ef_fd*) malloc(sizeof(ef_fd)); fd->first = (ef_stencil**) malloc(3*sizeof(ef_stencil*)); fd->second = (ef_stencil**) malloc(3*sizeof(ef_stencil*)); fd->first++; fd->second++; if (strcmp(type, EF_FD_STANDARD_O2) == 0) { ierr = set_second_order(fd);CHKERRQ(ierr); } *effd = fd; return 0; } PetscErrorCode ef_fd_destroy(ef_fd *fd) { PetscErrorCode ierr; int i; fd->first--; fd->second--; for(i = 0; i < 3; i++) { ierr = ef_stencil_destroy(fd->first[i]);CHKERRQ(ierr); free(fd->first[i]); ierr = ef_stencil_destroy(fd->second[i]);CHKERRQ(ierr); free(fd->second[i]); } free(fd->first); free(fd->second); return 0; }
C
#define BUFFERSIZE 10 #include <stdio.h> #include <string.h> #include <stdlib.h> int main(int argc, char *argv[]) { char buffer[BUFFERSIZE]; printf("Path is :%s", getenv("PATH")); strcpy(buffer, getenv("USERNAME")); printf("USERNAME is:%s\n", buffer); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* jyakdi.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: jyakdi <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/04/19 14:34:11 by jyakdi #+# #+# */ /* Updated: 2017/04/26 15:23:11 by jyakdi ### ########.fr */ /* */ /* ************************************************************************** */ #include "jyakdi.h" int main() { char *line; t_elem board; t_elem piece; ft_get_player(&board); ft_get_size(&board.size); get_next_line(0, &line); board.tab = ft_get_array(board.size, 4); /* int i; int j = 0; ft_putendl_fd("tab enregistree = ", 2); while (j < board.size.y) { i= 0; while (i < board.size.x) { ft_putchar_fd(board.tab[j][i], 2); i++; } ft_putendl_fd("", 2); j++; } */ ft_get_size(&piece.size); piece.tab = ft_get_array(piece.size, 0); /* j = 0; ft_putendl_fd("piece enregistree = ", 2); while (j < piece.size.y) { i= 0; while (i < piece.size.x) { ft_putchar_fd(piece.tab[j][i], 2); i++; } j++; }*/ ft_place(board, piece); while (get_next_line(0, &line)) { get_next_line(0, &line); board.tab = ft_get_array(board.size, 4); ft_get_size(&piece.size); piece.tab = ft_get_array(piece.size, 0); /* ft_putendl_fd("piece enregistree = ", 2); while (j < piece.size.y) { i= 0; while (i < piece.size.x) { ft_putchar_fd(piece.tab[j][i], 2); i++; } j++; }*/ ft_place(board, piece); } return (0); }
C
// // Created by 浩然 on 2021/3/7. // #ifndef ALG_HEAP_H #define ALG_HEAP_H struct HeapStruct; //堆的定义 typedef struct HeapStruct *PriorityQueue;//优先级队列的定义 PriorityQueue Initialize(int MaxElements);//初始化 void Destroy(PriorityQueue H);//销毁 void MakeEmpty(PriorityQueue H);//清空 void Insert(ElememtType X, PriorityQueue H);//插入 ElementType DeleteMin(PriorityQueue H);//取最小值并在队列中删除 ElementType FindMin(PriorityQueue);//查找最小值 int IsEmpty(PriorityQueue H);//判空 int IsFull(PriorityQueue H);//判满 #endif //ALG_HEAP_H
C
#include "BST.h" int main(){ tree root,tmp; root = (nodeType*)malloc(sizeof(nodeType)); root=NULL; tmp = (nodeType*)malloc(sizeof(nodeType)); insertNode(3, &root); insertNode(6, &root); insertNode(2, &root); insertNode(9, &root); insertNode(1, &root); insertNode(5, &root); insertNode(7, &root); print2D(root); printInOrder(root); printf("\n"); findGreater(3, root); printf("\n"); deleteNode(9, &root); //printInOrder(root); print2D(root); //printf("\n"); int n= numberNode(&root); printf("Number of Node: %d\n", n); tmp=findMin(root); printf("Min value: %d\n", tmp->key); tmp=findMax(root); printf("Max value: %d\n", tmp->key); return 0; }
C
//#define _CRT_SECURE_NO_WARNINGS 1 //#include <stdio.h> // ////%2/2size_tܲĶƲͳ //int number_one_bit1(size_t n) //{ // int count = 0; // while (n) // { // if (n % 2 == 1) // count++; // n /= 2; // } // return count; //} // // ////>>& //int number_one_bit2(int n) //{ // int i = 0; // int count = 0; // for (i = 0; i < 32; i++) // { // if (((n >> i) & 1) == 1) // count++; // } // return count; //} // ////6ķ //int number_one_bit3(int n) //{ // int count = 0; // // while (n) // { // n = n & (n - 1);//ʽӵ:ÿμnλһ1 // count++; // } // return count; //} // ////1ĸ //int main() //{ // int n; // scanf("%d", &n); // // int num = number_one_bit3(n); // printf("%d\n", num); // return 0; //}
C
/** \file * \brief get/set callback * * See Copyright Notice in "iup.h" */ #include <stdlib.h> #include <stdarg.h> #include "iup.h" #include "iup_object.h" #include "iup_assert.h" char* iupGetCallbackName(Ihandle *ih, const char *name) { void* value; Icallback func = (Icallback)iupTableGetFunc(ih->attrib, name, &value); if (!func && value) { /* if not a IUPTABLE_FUNCPOINTER then it is an old fashion name */ func = IupGetFunction((const char*)value); if (func) return value; } return NULL; } Icallback IupGetCallback(Ihandle *ih, const char *name) { Icallback func = NULL; void* value; iupASSERT(iupObjectCheck(ih)); if (!iupObjectCheck(ih)) return NULL; iupASSERT(name!=NULL); if (!name) return NULL; func = (Icallback)iupTableGetFunc(ih->attrib, name, &value); if (!func && value) { /* if not a IUPTABLE_FUNCPOINTER then it is an old fashion name */ func = IupGetFunction((const char*)value); } return func; } Icallback IupSetCallback(Ihandle *ih, const char *name, Icallback func) { Icallback old_func = NULL; iupASSERT(iupObjectCheck(ih)); if (!iupObjectCheck(ih)) return NULL; iupASSERT(name!=NULL); if (!name) return NULL; if (!func) iupTableRemove(ih->attrib, name); else { void* value; old_func = (Icallback)iupTableGetFunc(ih->attrib, name, &value); if (!old_func && value) old_func = IupGetFunction((const char*)value); iupTableSetFunc(ih->attrib, name, (Ifunc)func); } return old_func; } Ihandle* IupSetCallbacks(Ihandle* ih, const char *name, Icallback func, ...) { va_list arglist; iupASSERT(iupObjectCheck(ih)); if (!iupObjectCheck(ih)) return NULL; IupSetCallback(ih, name, func); va_start(arglist, func); name=va_arg(arglist, const char*); while (name) { func=va_arg(arglist, Icallback); IupSetCallback(ih, name, func); name=va_arg(arglist, const char*); } va_end (arglist); return ih; }
C
/* main.c */ /* Esempio d'uso di una lista concatenata */ #include <stdio.h> #include "list.h" int main(void) { List l; list_init(&l); /* head ---> NULL */ printf("IsEmpty? %d\n", list_isEmpty(&l)); printf("Size: %d\n", list_size(&l)); list_print(&l); putchar('\n'); /* aggiunta di un nuovo nodo */ list_insert(&l, 1); /* head ---> 1 ---> NULL */ printf("IsEmpty? %d\n", list_isEmpty(&l)); printf("Size: %d\n", list_size(&l)); list_print(&l); putchar('\n'); /* aggiunta di un nodo in coda */ list_insert(&l, 3); /* head ---> 1 ---> 3 ---> NULL */ printf("IsEmpty? %d\n", list_isEmpty(&l)); printf("Size: %d\n", list_size(&l)); list_print(&l); putchar('\n'); /* aggiunta di un nodo intermedio */ list_insert(&l, 2); /* head ---> 1 ---> 2 ---> 3 ---> NULL */ printf("IsEmpty? %d\n", list_isEmpty(&l)); printf("Size: %d\n", list_size(&l)); list_print(&l); putchar('\n'); /* aggiunta di un nodo in testa */ list_insert(&l, 0); /* head ---> 0 ---> 1 ---> 2 ---> 3 ---> NULL */ printf("IsEmpty? %d\n", list_isEmpty(&l)); printf("Size: %d\n", list_size(&l)); list_print(&l); putchar('\n'); /* un altro nodo ancora */ list_insert(&l, 4); /* head ---> 0 ---> 1 ---> 2 ---> 3 ---> 4 ---> NULL */ printf("IsEmpty? %d\n", list_isEmpty(&l)); printf("Size: %d\n", list_size(&l)); list_print(&l); putchar('\n'); /* rimozione di un nodo non esistente */ list_remove(&l, 42); /* head ---> 0 ---> 1 ---> 2 ---> 3 ---> NULL */ printf("IsEmpty? %d\n", list_isEmpty(&l)); printf("Size: %d\n", list_size(&l)); list_print(&l); putchar('\n'); /* rimozione di un nodo in coda */ list_remove(&l, 4); /* head ---> 0 ---> 1 ---> 2 ---> 3 ---> NULL */ printf("IsEmpty? %d\n", list_isEmpty(&l)); printf("Size: %d\n", list_size(&l)); list_print(&l); putchar('\n'); /* rimozione di un nodo in testa */ list_remove(&l, 0); /* head ---> 1 ---> 2 ---> 3 ---> NULL */ printf("IsEmpty? %d\n", list_isEmpty(&l)); printf("Size: %d\n", list_size(&l)); list_print(&l); putchar('\n'); /* rimozione di un nodo intermedio */ list_remove(&l, 2); /* head ---> 1 ---> 3 ---> NULL */ printf("IsEmpty? %d\n", list_isEmpty(&l)); printf("Size: %d\n", list_size(&l)); list_print(&l); putchar('\n'); list_clear(&l); putchar('\n'); /* head ---> NULL */ printf("IsEmpty? %d\n", list_isEmpty(&l)); printf("Size: %d\n", list_size(&l)); list_print(&l); putchar('\n'); return 0; }
C
/* getpid.c - getpid */ #include <conf.h> #include <kernel.h> #include <proc.h> #include <lab0.h> /*------------------------------------------------------------------------ * getpid -- get the process id of currently executing process *------------------------------------------------------------------------ */ SYSCALL getpid() { long start, totalTime; if(tracking==1){ start=ctr1000; //start holds the time at which this function starts } if(tracking==1){ totalTime=ctr1000-start; //totalTime holds the time from start to end of this func execTime[currpid][2] = execTime[currpid][2] + totalTime; freq[currpid][2]++; } return(currpid); }
C
//by Shashank Heda //Calculation of an integral using Trapezoidal Rule using Parallel Programming #include<stdio.h> #include<math.h> // To incorporate usage of functions like sin, log etc. #include<stdlib.h> // For the function exit(1) #include "mpi.h" // To incorporate MPI Library #include "mpe.h" #define x(y) sqrt((1-(y*y))/2) // This is equation of plane where both 3d curves intersect #define z1(x,y) (5*((x*x)+(y*y))) // First surface curve #define z2(x,y) (6-7*(x*x)-(y*y)) // Second Surface curve int main(int argc, char* argv[]) { int my_rank, np, process; long int n=100,l=100; // Total number of parts (in which y is divided) long int local_ay,local_y,local_x,width,local_local_volume,i,j; double ay1=-1.0 , ay2=1.0; double h, local_l1, local_l2,x,local_volume=0.0, total_volume; double time1,time2; //int *sendbuf, *recvbuf; //MPI Starts MPI_Init(&argc,&argv); MPI_Comm_rank(MPI_COMM_WORLD,&my_rank); MPI_Comm_size(MPI_COMM_WORLD,&np); time1=MPI_Wtime(); h = (ay1 - ay2) / n; // number of strips in which y axis is divided local_ay = n / np; // Number of strips given to each process local_l1 = ay1 + my_rank * local_ay * h; // To determine starting point of integration for each process on the axis y local_l2 = local_l1 + local_ay * h; // To determine the end point of integration for each process on the axis y ********************************************************************************************************* for(j=0;j<l;j++) { local_volume=(z1(local_x*j/l, local_l1)+z1(local_x*j/l, local_l2)+z2(local_x*j/l, local_l1)+z2(local_x*j/l, local_l2); } for(i=1;i<local_ay;i++) // To calculate the value of all f(x) inside the local interval of the function { local_y=local_l1+i*h; local_x=x(local_y); width=local_x/l; for(j=0;j<l;j++) { local_local_volume+=2*z1((local_x*j)/l, local_y); local_local_volume+=2*z2((local_x*j)/l, local_y); } local_volume+=local_local_volume*h*width; // Value of integral = (Value of all f's * width h) //x=local_a+i*h; //local_integral+=f(x); } /* Add up the volumes calculated by each process */ if (my_rank!=0) { MPI_Send(&local_volume, 1, MPI_DOUBLE,0,0, MPI_COMM_WORLD); } else { total_volume = local_volume; for (process=1; process<np; process++) { MPI_Recv(&local_volume, 1, MPI_DOUBLE,process,0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); total_volume+=local_volume; } } /*Using MPI_Reduce sendbuf = (int *)malloc( 3 * sizeof(int) ); recvbuf = (int *)malloc( 3 * sizeof(int) ); MPI_Barrier(MPI_COMM_WORLD); MPI_Reduce( sendbuf, recvbuf, 3, MPI_INT, MPI_SUM,0,MPI_COMM_WORLD); */ time2=MPI_Wtime(); if(my_rank==0) { printf("\n\tValue of integration by the Trapezoidal Rule is : %1.10f",total_volume); printf("\n\tTotal number of processes used in parallel is : %d",np); printf("\n\tTime taken for calculation in Parallel Processing is : %f\n",time2-time1); } MPI_Finalize(); return 0; }
C
/* * Author: Lorenzo Tabasso, mat: 812499 * Author: Andrea Malgaroli, mat: 823429 */ #include "sums.h" #include "sorts.h" #include "tests.h" // COMPARE FUNCTIONS ----------------------------------------------------------- int compare_insertionsort(void* r1_p,void* r2_p){ long long first = (long long) r1_p; long long second = (long long) r2_p; if(first < second){ return(1); } return(0); } int compare_mergesort(void* r1_p,void* r2_p){ long long first = (long long) r1_p; long long second = (long long) r2_p; if(first <= second){ return(1); } return(0); } int compare_sums(void* r1_p, void* r2_p){ long long first = (long long) r1_p; long long second = (long long) r2_p; if(first < second){ return(1); } return(0); } // UTILITY FUNCTIONS ----------------------------------------------------------- int is_sorted(void ** array, int size, int (* compare)(void *, void *)) { int test = 1; for (int i = 0; i < size-1; i++) { test = compare(array[i], array[i+1]); } if (test == 1) return (1); else return (0); } void load_array(void ** array, int size, char * path){ clock_t start = clock(); // for timing printf("\nLoading data from file...\n"); FILE * dataset_p = fopen(path, "r"); if(dataset_p == NULL){ fprintf(stderr,"Load: unable to open the file"); exit(EXIT_FAILURE); } char * read_line_p; char buffer[1024]; int buf_size = 1024; long long number_in_read_line = 0; void * number_in_read_line_p; int i = 0; while(fgets(buffer, buf_size, dataset_p) != NULL && i < size){ read_line_p = malloc((strlen(buffer) + 1) * sizeof(char)); strcpy(read_line_p, buffer); char *field_in_read_line_p = strtok(read_line_p, "\n"); number_in_read_line = strtoull(field_in_read_line_p, (char **) NULL, 10); number_in_read_line_p = (void *) number_in_read_line; array[i] = number_in_read_line_p; free(read_line_p); i++; } clock_t stop = clock(); double seconds = (double)(stop - start) / CLOCKS_PER_SEC; fclose(dataset_p); printf("Data loaded. Read %d lines in %f seconds.\n", i, seconds); } void print_array(void ** array, int size){ long long * to_print_p = NULL; long long to_print = 0; printf("Array: ["); for(int i = 0; i < size; i++){ to_print_p = (long long *) array[i]; to_print = (long long) to_print_p; if (i == size-1) { printf("%lld", to_print); } else { printf("%lld, ", to_print); } } printf("]\n"); } // TESTS FUNCTIONS ------------------------------------------------------------- static void test_insertion_sort(void){ /* Begin Setup */ void ** array0 = malloc(sizeof(int *)); // empty array void ** array1 = malloc(10 * sizeof(int *)); void ** array2 = malloc(10 * sizeof(int *)); void ** array3 = malloc(10 * sizeof(int *)); void ** array_integers = malloc(10 * sizeof(void *)); long long a1[10] = {1,2,3,4,5,6,7,8,9,10}; long long a2[10] = {6,1,2,7,9,8,3,5,10,4}; long long a3[10] = {10,9,8,7,6,5,4,3,2,1}; void * a1_ptr; void * a2_ptr; void * a3_ptr; for (int i = 0; i < 10; ++i) { a1_ptr = (void *) a1[i]; array1[i] = a1_ptr; a2_ptr = (void *) a2[i]; array2[i] = a2_ptr; a3_ptr = (void *) a3[i]; array3[i] = a3_ptr; } load_array(array_integers, 10, INTEGERS_PATH); /* End Setup */ clock_t start = clock(); printf("\nBefore insertionSort\n"); print_array(array0, 0); print_array(array1,10); print_array(array2,10); print_array(array3,10); print_array(array_integers, 10); printf("\nStarting insertionSort, timer set to 0 seconds.\n"); insertion_sort(array0, 0, compare_insertionsort); insertion_sort(array1, 10, compare_insertionsort); insertion_sort(array2, 10, compare_insertionsort); insertion_sort(array3, 10, compare_insertionsort); insertion_sort(array_integers, 10, compare_insertionsort); clock_t stop = clock(); double seconds = (double)(stop - start) / CLOCKS_PER_SEC; printf("InsertionSort finished, time elapsed: %f seconds\n", seconds); printf("\nAfter insertionSort:\n"); print_array(array0,0); print_array(array1,10); print_array(array2,10); print_array(array3,10); print_array(array_integers, 10); TEST_ASSERT_TRUE(is_sorted(array0, 0, compare_insertionsort)); TEST_ASSERT_TRUE(is_sorted(array1, 10, compare_insertionsort)); TEST_ASSERT_TRUE(is_sorted(array2, 10, compare_insertionsort)); TEST_ASSERT_TRUE(is_sorted(array3, 10, compare_insertionsort)); TEST_ASSERT_TRUE(is_sorted(array_integers, 10, compare_insertionsort)); /* Begin Teardown */ free(array0); free(array1); free(array2); free(array3); free(array_integers); /* End Teardown */ } /* End test_insertion_sort */ static void test_merge_sort(void){ /* Begin Setup */ void ** array0 = malloc(sizeof(int *)); void ** array1 = malloc(10 * sizeof(int *)); void ** array2 = malloc(10 * sizeof(int *)); void ** array3 = malloc(10 * sizeof(int *)); void ** array_integers = malloc(20000000 * sizeof(void *)); long long a1[10] = {1,2,3,4,5,6,7,8,9,10}; long long a2[10] = {6,1,2,7,9,8,3,5,10,4}; long long a3[10] = {10,9,8,7,6,5,4,3,2,1}; void * a1_ptr; void * a2_ptr; void * a3_ptr; for (int i = 0; i < 10; ++i) { a1_ptr = (void *) a1[i]; array1[i] = a1_ptr; a2_ptr = (void *) a2[i]; array2[i] = a2_ptr; a3_ptr = (void *) a3[i]; array3[i] = a3_ptr; } load_array(array_integers, 20000000, INTEGERS_PATH); /* End Setup */ clock_t start1 = clock(); printf("\nBefore mergeSort:\n"); print_array(array1,0); print_array(array1,10); print_array(array2,10); print_array(array3,10); printf("\nStarting mergeSort, timer set to 0 seconds.\n"); merge_sort(array0, 0, 0, compare_mergesort); merge_sort(array1, 0, 10-1, compare_mergesort); merge_sort(array2, 0, 10-1, compare_mergesort); merge_sort(array3, 0, 10-1, compare_mergesort); clock_t stop1 = clock(); double seconds1 = (double)(stop1 - start1) / CLOCKS_PER_SEC; printf("MergeSort finished, time elapsed: %f seconds\n", seconds1); printf("\nAfter mergeSort:\n"); print_array(array0,0); print_array(array1,10); print_array(array2,10); print_array(array3,10); printf("\nRestarting mergeSort on array_integers. Timer reset to 0 " "seconds.\n"); clock_t start2 = clock(); merge_sort(array_integers, 0, 20000000-1, compare_mergesort); clock_t stop2 = clock(); double seconds2 = (double)(stop2 - start2) / CLOCKS_PER_SEC; printf("MergeSort of array_integers finished, time elapsed: %f seconds\n", seconds2); TEST_ASSERT_TRUE(is_sorted(array0, 0, compare_mergesort)); TEST_ASSERT_TRUE(is_sorted(array1, 10, compare_mergesort)); TEST_ASSERT_TRUE(is_sorted(array2, 10, compare_mergesort)); TEST_ASSERT_TRUE(is_sorted(array3, 10, compare_mergesort)); TEST_ASSERT_TRUE(is_sorted(array_integers, 20000000, compare_mergesort)); /* Begin Teardown */ free(array1); free(array2); free(array3); free(array_integers); /* End Teardown */ } /* End test_merge_sort */ static void test_sums_in_array(void){ /* Begin Setup */ void ** array0 = malloc(sizeof(int *)); void ** array1 = malloc(10 * sizeof(int *)); void ** array2 = malloc(5 * sizeof(int *)); void ** array_integers = malloc(20000000 * sizeof(void *)); void ** array_sums = malloc(11 * sizeof(void *)); long long a1[10] = {10,9,8,7,6,5,4,3,2,1}; long long a2[5] = {4,7,6,1,10}; void * a1_ptr; void * a2_ptr; for (int i = 0; i < 10; ++i) { a1_ptr = (void *) a1[i]; array1[i] = a1_ptr; } for (int j = 0; j < 5; ++j) { a2_ptr = (void *) a2[j]; array2[j] = a2_ptr; } load_array(array_integers, 20000000, INTEGERS_PATH); load_array(array_sums, 11, SUMS_PATH); /* End Setup */ clock_t start1 = clock(); printf("\nBefore mergeSort\n"); print_array(array0, 0); print_array(array1, 10); print_array(array2, 5); printf("\t(array of sums)\n"); printf("\nStarting mergeSort, timer set to 0 seconds.\n"); merge_sort(array0, 0, 0, compare_mergesort); merge_sort(array1, 0, 10-1, compare_mergesort); clock_t stop1 = clock(); double seconds1 = (double)(stop1 - start1) / CLOCKS_PER_SEC; printf("MergeSort finished, time elapsed: %f seconds\n", seconds1); printf("\nAfter mergeSort\n"); print_array(array0, 0); print_array(array1, 10); printf("Applying sums_in_array function. "); int result1 = sums_in_array(array1, array2, 10, 5, compare_sums); printf("Result: %d\n", result1); TEST_ASSERT_TRUE(is_sorted(array0, 0, compare_mergesort)); TEST_ASSERT_TRUE(is_sorted(array1, 10, compare_mergesort)); TEST_ASSERT_TRUE(result1 == 1); /* Restart with array_integers of 20000000 elements */ printf("\nRestarting mergeSort on array_integers. Timer reset to 0 " "seconds.\n"); clock_t start2 = clock(); merge_sort(array_integers, 0, 20000000-1, compare_mergesort); clock_t stop2 = clock(); double seconds2 = (double)(stop2 - start2) / CLOCKS_PER_SEC; printf("MergeSort finished, time elapsed: %f seconds\n", seconds2); printf("Applying sums_in_array function. "); int result2 = sums_in_array(array_integers, array_sums, 20000000, 11, compare_sums); printf("Result: %d\n", result2); TEST_ASSERT_TRUE(is_sorted(array_integers, 20000000, compare_mergesort)); TEST_ASSERT_TRUE(result2 == 1); /* Begin Teardown*/ free(array0); free(array1); free(array2); free(array_integers); free(array_sums); /* End Teardown */ } /* End test_sums_in_array */ // MAIN FUNCTION --------------------------------------------------------------- int main(void) { UNITY_BEGIN(); RUN_TEST(test_insertion_sort); RUN_TEST(test_merge_sort); RUN_TEST(test_sums_in_array); return UNITY_END(); }
C
#include<stdio.h> #include<stdlib.h> #include<string.h> #include<unistd.h> #include<sys/stat.h> #include<sys/types.h> #include<sys/socket.h> #include<sys/wait.h> #include<errno.h> #include<fcntl.h> #include<netinet/in.h> #include<arpa/inet.h> #define SUCCESS 1 #define FAILURE 0 int my_read(int, char **buffer); int process(char **buffer,int ret); int my_write(int confd,char **buffer,int ret); #include"header.h" char vowel[10]={'a','e','i','o','u','A','E','I','O','U'}; int process(char ** buffer,int ret) { char *token[20]; char buff[10] memset(buff,0,10); memset(token,0,20*sizeof(char*)); int i=0; token[i]=strtok(*buffer," "); while(NULL!=token[i]) { i++; token[i]=strtok(NULL," "); } free(*buffer); int l,vow=0,total=0; char vowe[2]; for(j=0;j<i;j++) { strcpy(buff,token[j],strlen(token[j])); for(k=0;k<strlen(buff);k++) { for(l=0;l<10;i++) { if(buff[k]==vowel[l]) vow++; } } sprintf(vowe,"%d",vow); buffer=(char*)realloc(*buffer,len+strlen(token[j])+2); memcpy(*buffer+total,token[j],strlen(token[j])); memcpy(*buffer+total+1,vowe,2); total=strlen(*buffer); vow=0; } } int my_write(int sd,char **buffer,int len) { int totalbytes=0; int pointer=0; while(1) { ret=write(sd,buffer+pointer,len-totalbytes); if(0>ret) { perror("error in writing"); return FAILURE; } pointer+=ret; totalbytes+=ret; if(totalbytes==len) { return totalbytes; } } } int my_read(int sd,char **buffer) { int total=0; int pointer=0; char buff[10]; memset(buff,0,10); while(1) { ret=read(sd,buff,10); if(0>ret) { } total+=ret; buffer=(char)realloc(buffer,total); memcpy(buffer+pointer,buff,ret); pointer+=ret; if(strstr(*buffer,"$",1)) { return totalbytes; } } }
C
/** * Module: tools.c * Author(s): Kristofer Hansson Aspman * * Description: Contains the functions to make * the life of a motor control * programmer easier. * */ #define INT_TO_BITFIELD(a) *(msg_pointer)a #define BITFIELD_TO_CHAR(a) *(unsigned char*)a //NOTE: The following two (commented) functions have // been changed to macros instead. /* unsigned char bitfieldToChar(msg_pointer mp){ */ /* return *(unsigned char*)mp; */ /* } */ /* msg intToBitfield(unsigned int* ip){ */ /* return *(msg_pointer)ip; */ /* } */ /** * Functions: void scanDecMsgSTDIN() * void scanHexMsgSTDIN() * Author(s): Kristofer Hansson Aspman * * Description: Scans for a hex or decimal number * using scanf. * * */ msg scanDecMsgSTDIN(){ unsigned int input; printf("Enter the message in Decimal: "); scanf("%d", &input); return INT_TO_BITFIELD(&input); } msg scanHexMsgSTDIN(){ unsigned int input; printf("Enter the message in hexadecimal: "); scanf("%x", &input); return INT_TO_BITFIELD(&input); } void printMsg(msg_pointer mp){ printf("***********************************\n"); printf(" Message Informatin\n"); printf("\nBits are:\n-ID: %d\n-Incr: %d\n-Panic: %d\n", mp->ID, mp->increase, mp->panic); printf("-Left: %d\n-Right: %d\n-Front: %d\n-Rear: %d\n", mp->left, mp->right, mp->front, mp->rear); printf("\nSize of bitfield: %ld\n", sizeof(*mp)); printf("Hexadecimal representation: %x\n", BITFIELD_TO_CHAR(mp)); printf("Decimal representation: %d\n", BITFIELD_TO_CHAR(mp)); printf("***********************************\n"); }
C
/** * Definition for a binary tree node. * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * }; */ /** * Return an array of arrays of size *returnSize. * The sizes of the arrays are returned as *returnColumnSizes array. * Note: Both returned array and *columnSizes array must be malloced, assume caller calls free(). */ int** levelOrderBottom(struct TreeNode* root, int* returnSize, int** returnColumnSizes){ if(!root) { *returnSize = 0; return NULL; } int **retValue, queueLength = 1, i = 0, j, nextEndDepth = 0, prevEndDepth = -1, maxDepth = 5000, maxQueueSize = 5000; struct TreeNode *queue[maxQueueSize], *curTree; *returnColumnSizes = (int *) malloc(maxDepth * sizeof(int *)); retValue = (int **) malloc(maxDepth * sizeof(int *)); *returnSize = 0; memset(queue, '\0', 100 * sizeof(struct TreeNode *)); queue[0] = curTree = root; while(curTree) { if(curTree->left) queue[queueLength++] = curTree->left; if(curTree->right) queue[queueLength++] = curTree->right; if(i++ == nextEndDepth) { (*returnColumnSizes)[maxDepth-1-*returnSize] = nextEndDepth - prevEndDepth; retValue[maxDepth-1-*returnSize] = (int *) malloc((nextEndDepth - prevEndDepth) * sizeof(int)); for(j = 0; j < nextEndDepth - prevEndDepth; j++) retValue[maxDepth-1-*returnSize][j] = queue[prevEndDepth + 1 + j]->val; *returnSize += 1; prevEndDepth = nextEndDepth; nextEndDepth = queueLength - 1; } curTree = queue[i]; } // NOTE: these steps are technically unsafe, because they leave some remaining // allocated space (i.e., memory leak) from the beginning of the original // *returnColumnSizes and retValue values. This can be fixed with realloc/ // memmove (e.g., see https://stackoverflow.com/questions/1304771/) but left // out for simplicity *returnColumnSizes = *returnColumnSizes + (maxDepth - *returnSize); retValue = retValue + (maxDepth - *returnSize); return retValue; }
C
#include <stdio.h> #include <string.h> int main() { int n, i, j, k; char a[50]; scanf("%d", &n); int x[n], y; for(i = 1; i <= n; i++) { y = 0; gets(a); k = strlen(a); for(j = 0; j < k; j++) { y = y + a[j]; } x[i] = y; } for(i = 0; i < n; i++) { printf("%d\n", x[i]); } }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> int main() { char *tmp = malloc(4); int start = 20, lnum = 998765; tmp[0] |= start; tmp[1] |= lnum % (1 << 8); tmp[2] |= lnum % (1 << 16) / (1 << 8); tmp[3] |= lnum / (1 << 16); for(int i = 0; i < 4; i++) printf("%d ",tmp[i]); printf("\n"); }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> #include "lib/encoding.h" int ctoi(char c){ // 0-9 if ( c >= 48 && c <= 57) return c - 48; // A-F if (c >= 65 && c <= 70) return c - 55; } int main(int argc, char * argv[]) { if ( argc != 4 ) { printf("Usage: %s [issuer] [accountName] [secretHex]\n", argv[0]); return(-1); } char * issuer = argv[1]; char * accountName = argv[2]; char * secret_hex = argv[3]; assert (strlen(secret_hex) <= 20); printf("\nIssuer: %s\nAccount Name: %s\nSecret (Hex): %s\n\n", issuer, accountName, secret_hex); // Create an otpauth:// URI and display a QR code that's compatible // with Google Authenticator // Encode AccountName, Issuer & create encoding ptr for the secret char * accountName_encoded = urlEncode(accountName); char * issuer_encoded = urlEncode(issuer); char secret_encoded[16]; // Convert secret_hex to uint8_t data uint8_t data[10]; int i; for ( i = 0; i < 19; i += 2 ) { data[i / 2] = ctoi(secret_hex[i + 1]) + 16 * ctoi(secret_hex[i]); } int numBytesEncoded = 0; numBytesEncoded = base32_encode(data, 10, secret_encoded, 17); char URI[512]; snprintf((const char *)URI, 512, "otpauth://totp/%s?issuer=%s&secret=%s&period=30", accountName_encoded, issuer_encoded, secret_encoded); displayQRcode(URI); return (0); }
C
#include "parse.h" #include "wrap.h" extern char *cwd; FILE *configfp=NULL; static FILE *getfp(char *path) { configfp=Fopen(path,"r"); return configfp; } static char* getconfig(char* name) { /* pointer meaning: ...port...=...8000... | | | | | *fs | | | *be f->forward b-> back *fe | *bs s->start e-> end *equal */ static char info[64]; int find=0; char tmp[256],fore[64],back[64],tmpcwd[MAXLINE]; char *fs,*fe,*equal,*bs,*be,*start; strcpy(tmpcwd,cwd); strcat(tmpcwd,"/"); FILE *fp=getfp(strcat(tmpcwd,"config.ini")); while(fgets(tmp,255,fp)!=NULL) { start=tmp; equal=strchr(tmp,'='); while(isblank(*start)) ++start; fs=start; if(*fs=='#') continue; while(isalpha(*start)) ++start; fe=start-1; strncpy(fore,fs,fe-fs+1); fore[fe-fs+1]='\0'; if(strcmp(fore,name)!=0) continue; find=1; start=equal+1; while(isblank(*start)) ++start; bs=start; while(!isblank(*start)&&*start!='\n') ++start; be=start-1; strncpy(back,bs,be-bs+1); back[be-bs+1]='\0'; strcpy(info,back); break; } if(find) return info; else return NULL; } char* Getconfig(char* name) { char *p=getconfig(name); if(p==NULL) { syslog(LOG_ERR,"there is no %s in the configure",name); exit(0); } else return p; } /* parse_config test int main() { char *s=getconfig("port"); printf("%s\n",s); s=getconfig("root"); printf("%s\n",s); } */
C
#include<stdio.h> #include<stdlib.h> #include<time.h> //#include"league_inter.c" /*void swap(int a,int b) { int temp; temp=a; a=b; b=temp; }*/ int run(int *count) { int a[11],i,m=0,f=0,c=0,c1=0,f1=0,f2=0,choice; int n,s[11]={0},balls,overs,over=0,total=0,b[20]={0}; float str,rrt; printf("\n Enter the number of overs"); scanf("%d",&overs); balls=overs*6; srand(time(NULL)); for(i=1;i<=balls;i++) { n=rand()%8; switch(n) { //(n%2)?(s[m]+=n):(s[m+1]+=n); case 1:s[m]+=n;over+=n;total+=n; printf("\n The score is 1"); printf("\nBatsman two on strike"); //swap(s[m],s[m+1]); break; case 2:s[m]+=n;over+=n;total+=n; printf("\n The score is 2"); printf("\nStrike remains the same"); break; case 3:s[m]+=n;over+=n;total+=n; printf("\nThe score is 3"); printf("\nBatsman two on strike"); //swap(s[m],s[m+1]); break; case 4:s[m]+=n;over+=n;total+=n; printf("\nThe score is 4"); printf("\nStrike remains the same"); break; case 5:s[m]+=n;over+=n;total+=n; printf("\nThe score is 5"); printf("\nBatsman two on strike"); //swap(s[m],s[m+1]); break; case 6:s[m]+=n;over+=n;total+=n; printf("\n The score is 6"); printf("\nStrike remains the same"); break; case 7:printf("\n OOOPS!!!Its wicket"); printf("\n YOU CAN USE THIRD UMPIRE ONLY ONCE"); if(f2==0) { printf("\n DO YOU WANT TO GO FOR THIRD UMPIRE"); printf("\n 1.Yes\n2.No"); scanf("%d",&choice); if(choice==1) { int x; x=rand(); if(x%2==0) { printf("\n WICKET"); f=1; c++; } else { printf("\n YOU CAN PLAY!!!!"); break; } } f2=1; } f=1; c++; break; } rrt=(s[m]/(i))*6.0; prif(choice==1) { int x; x=rand(); if(x%2==0) { printf("\n WICKET"); f=1; c++; } else { printf("\n YOU CAN PLAY!!!!"); break; } } f2=1; }ntf("\nRunrate is %f\n",rrt); if(f==1) { m++; printf("\n The total score of the batsman %d is %d",m,s[m-1]); str=(100.0/(i))*s[m-1]; printf("\n-----------------\n"); printf("\nStrike rate of the batsman %d is %f\n",m,str); printf("-----------------\n"); f=0; } if(i%6==0) { printf("\n OVER UP!!!"); printf("\n NEXT BOWLER ON GROUND"); printf("\n The total in this over is %d",over); b[c1]=over; printf("\n The bowler %d has given %d runs",c1+1,over); //printf("\n The runrate of this over is %d",over); over=0; c1++; } if(m==10) { printf("\n FIRST INNINGS OVER!!!"); printf("\n YOUR TATGET IS %d ",(total+1)); break; } } printf("\nThe total score of batsman %d is %d",m+1,s[m]); str=(100.0/(i))*s[m]; printf("\n-----------------\n"); printf("\nStrike rate of the batsman %d is %f\n",m+1,str); printf("-----------------\n"); printf("\n The total score of the match is %d",total); printf("\n YOUR TARGET IS %d",(++total)); *count=c; return total; } int run1(int t,int *w) { int a[11],i,m=0,f=0,c=0,c1=0,f1=0; int n,s[11]={0},balls,overs,over=0,total=0,b[20]={0}; float str,rrt; printf("\n Enter the number of overs"); scanf("%d",&overs); balls=overs*6; srand(time(NULL)); for(i=1;i<=balls;i++) { n=rand()%8; switch(n) { case 0:printf("\nThe score is 0"); printf("\n\nIts a Dot ball"); break; case 1:s[m]+=n;over+=n;total+=n; printf("\n The score is 1"); printf("\n\n A single on the mid...."); printf("\nBatsman two on strike"); //swap(s[m],s[m+1]); break; case 2:s[m]+=n;over+=n;total+=n; printf("\n The score is 2"); printf("\n\n Nice shot....two runs"); printf("\nStrike remains the same"); break; case 3:s[m]+=n;over+=n;total+=n; printf("\nThe score is 3"); printf("\n\n Long deep...nice running between the wickets...three runs"); printf("\nBatsman two on strike"); //swap(s[m],s[m+1]); break; case 4:s[m]+=n;over+=n;total+=n; printf("\nThe score is 4"); printf("\n\n One pitch over the rope....four runs..."); printf("\nStrike remains the same"); break; case 5:s[m]+=n;over+=n;total+=n; printf("\nThe score is 5"); printf("\n\n A wide plus FOUR...gives five runs"); printf("\nBatsman two on strike"); //swap(s[m],s[m+1]); break; case 6:s[m]+=n;over+=n;total+=n; printf("\n The score is 6"); printf("\n\nHUGE shot....out of the stadium...SIX runs..."); printf("\nStrike remains the same"); break; case 7:printf("\n OOOPS!!!Its wicket"); #include<stdio.h> #include<stdlib.h> #include<time.h> #include"league_inter.c" /*void swap(int a,int b) { int temp; temp=a; a=b; b=temp; }*/ int run(int *count) { int a[11],i,m=0,f=0,c=0,c1=0,f1=0; int n,s[11]={0},balls,overs,over=0,total=0,b[20]={0}; float str,rrt; printf("\n Enter the number of overs"); scanf("%d",&overs); balls=overs*6; srand(time(NULL)); for(i=1;i<=balls;i++) { n=rand()%8; switch(n) { //(n%2)?(s[m]+=n):(s[m+1]+=n); case 1:s[m]+=n;over+=n;total+=n; printf("\n The score is 1"); printf("\nBatsman two on strike"); //swap(s[m],s[m+1]); break; case 2:s[m]+=n;over+=n;total+=n; printf("\n The score is 2"); printf("\nStrike remains the same"); break; case 3:s[m]+=n;over+=n;total+=n; printf("\nThe score is 3"); printf("\nBatsman two on strike"); //swap(s[m],s[m+1]); break; case 4:s[m]+=n;over+=n;total+=n; printf("\nThe score is 4"); printf("\nStrike remains the same"); break; case 5:s[m]+=n;over+=n;total+=n; printf("\nThe score is 5"); printf("\nBatsman two on strike"); //swap(s[m],s[m+1]); break; case 6:s[m]+=n;over+=n;total+=n; printf("\n The score is 6"); printf("\nStrike remains the same"); break; case 7:printf("\n OOOPS!!!Its wicket"); f=1; c++; break; } rrt=(s[m]/(i))*6.0; printf("\nRunrate is %f\n",rrt); if(f==1) { m++; printf("\n The total score of the batsman %d is %d",m,s[m-1]); str=(100.0/(i))*s[m-1]; printf("\n-----------------\n"); printf("\nStrike rate of the batsman %d is %f\n",m,str); printf("-----------------\n"); f=0; } if(i%6==0) { printf("\n OVER UP!!!"); printf("\n NEXT BOWLER ON GROUND"); printf("\n The total in this over is %d",over); b[c1]=over; printf("\n The bowler %d has given %d runs",c1+1,over); //printf("\n The runrate of this over is %d",over); over=0; c1++; } if(m==10) { printf("\n FIRST INNINGS OVER!!!"); printf("\n YOUR TATGET IS %d ",(total+1)); break; } } printf("\nThe total score of batsman %d is %d",m+1,s[m]); str=(100.0/(i))*s[m]; printf("\n-----------------\n"); printf("\nStrike rate of the batsman %d is %f\n",m+1,str); printf("-----------------\n"); printf("\n The total score of the match is %d",total); printf("\n YOUR TARGET IS %d",(++total)); *count=c; return total; } int run1(int t,int *w) { int a[11],i,m=0,f=0,c=0,c1=0,f1=0; int n,s[11]={0},balls,overs,over=0,total=0,b[20]={0}; float str,rrt; printf("\n Enter the number of overs"); scanf("%d",&overs); balls=overs*6; srand(time(NULL)); for(i=1;i<=balls;i++) { n=rand()%8; switch(n) { case 0:printf("\nThe score is 0"); printf("\n\nIts a Dot ball"); break; case 1:s[m]+=n;over+=n;total+=n; printf("\n The score is 1"); printf("\n\n A single on the mid...."); printf("\nBatsman two on strike"); //swap(s[m],s[m+1]); break; case 2:s[m]+=n;over+=n;total+=n; printf("\n The score is 2"); printf("\n\n Nice shot....two runs"); printf("\nStrike remains the same"); break; case 3:s[m]+=n;over+=n;total+=n; printf("\nThe score is 3"); printf("\n\n Long deep...nice running between the wickets...three runs"); printf("\nBatsman two on strike"); //swap(s[m],s[m+1]); break; case 4:s[m]+=n;over+=n;total+=n; printf("\nThe score is 4"); printf("\n\n One pitch over the rope....four runs..."); printf("\nStrike remains the same"); break; case 5:s[m]+=n;over+=n;total+=n; printf("\nThe score is 5"); printf("\n\n A wide plus FOUR...gives five runs"); printf("\nBatsman two on strike"); //swap(s[m],s[m+1]); break; case 6:s[m]+=n;over+=n;total+=n; printf("\n The score is 6"); printf("\n\nHUGE shot....out of the stadium...SIX runs..."); printf("\nStrike remains the same"); break; case 7:printf("\n OOOPS!!!Its wicket"); f=1; c++; break; } rrt=(s[m]/(i))*6.0; printf("\nRunrate is %f\n",rrt); if(f==1) { m++; printf("\n The total score of the batsman %d is %d",m,s[m-1]); str=(100.0/(i))*s[m-1]; printf("\n-----------------\n"); printf("\nStrike rate of the batsman %d is %f\n",m,str); printf("-----------------\n"); f=0; } if(i%6==0) { printf("\n OVER UP!!!"); printf("\n NEXT BOWLER ON GROUND"); printf("\n The total in this over is %d",over); b[c1]=over; printf("\n The bowler %d has given %d runs",c1+1,over); printf("\n The runrate of this over is %d",over); over=0; c1++; } if(m==10) { printf("\n FIRST INNINGS OVER!!!"); printf("\n YOUR TATGET IS %d ",(total+1)); break; } if(total>t) { printf("\nThe score of the batsman is %d is %d",m+1,s[m]); return total; } } printf("\nThe total score of batsman %d is %d",m+1,s[m]); str=(100.0/(i))*s[m]; printf("\n-----------------\n"); printf("\nStrike rate of the batsman %d is %f\n",m+1,str); printf("-----------------\n"); printf("\n The total score is %d",total); printf("\n%d",c); *w=c; return total; } void main() { int t[2]={0}; int a,b; teams(); printf("\n=========================================================================================================="); printf("\n FIRST INNINGS STARTS!!!! "); printf("\n==========================================================================================================\n"); t[0]=run(&a); printf("\n%d",a); printf("\n=========================================================================================================="); printf("\n SECOND INNINGS STARTS!!!! "); printf("\n==========================================================================================================\n"); t[1]=run1(t[0],&b); printf("\n%d",b); printf("\n Total of team two is %d",t[1]); if(t[1]>t[0]) printf("\n team two won by %d wickets",(11-b)); else if(t[0]>t[1]) printf("\n team one won by %d runs",t[0]-t[1]); else printf("\n its a draw match"); } f=1; c++; break; } rrt=(s[m]/(i))*6.0; printf("\nRunrate is %f\n",rrt); if(f==1) { m++; printf("\n The total score of the batsman %d is %d",m,s[m-1]); str=(100.0/(i))*s[m-1]; printf("\n-----------------\n"); printf("\nStrike rate of the batsman %d is %f\n",m,str); printf("-----------------\n"); f=0; } if(i%6==0) { printf("\n OVER UP!!!"); printf("\n NEXT BOWLER ON GROUND"); printf("\n The total in this over is %d",over); b[c1]=over; printf("\n The bowler %d has given %d runs",c1+1,over); printf("\n The runrate of this over is %d",over); over=0; c1++; } if(m==10) { printf("\n FIRST INNINGS OVER!!!"); printf("\n YOUR TATGET IS %d ",(total+1)); break; } if(total>t) { printf("\nThe score of the batsman is %d is %d",m+1,s[m]); return total; } } printf("\nThe total score of batsman %d is %d",m+1,s[m]); str=(100.0/(i))*s[m]; printf("\n-----------------\n"); printf("\nStrike rate of the batsman %d is %f\n",m+1,str); printf("-----------------\n"); printf("\n The total score is %d",total); printf("\n%d",c); *w=c; return total; } void main() { int t[2]={0}; int a,b; //teams(); printf("\n=========================================================================================================="); printf("\n FIRST INNINGS STARTS!!!! "); printf("\n==========================================================================================================\n"); t[0]=run(&a); printf("\n%d",a); printf("\n=========================================================================================================="); printf("\n SECOND INNINGS STARTS!!!! "); printf("\n==========================================================================================================\n"); t[1]=run1(t[0],&b); printf("\n%d",b); printf("\n Total of team two is %d",t[1]); if(t[1]>t[0]) printf("\n team two won by %d wickets",(10-b)); else if(t[0]>t[1]) printf("\n team one won by %d runs",t[0]-t[1]); else printf("\n its a draw match"); }
C
#include <stdio.h> #include <stdlib.h> #include <time.h> #include <unistd.h> #include <termios.h> #include <string.h> struct Node { char name[100]; char nickName[100]; char id[100]; char password[100]; double point; int rank; int state; struct Node* next; }; struct Words { char eng[15]; char kor[30]; struct Words *next; }; struct Node* nodeHead = NULL; struct Words* head = NULL; struct Words* last = NULL; #define W 4 #define H 4 int count = 0; // global val int ground[W][H]; int c1, c2; int isLogined; int moveCount; double playTime; char loginedId[100]; //func origin int getch(void); //linked list FILE *openFile_R(int); FILE *openFile_W(void); void updateFile(void); void setNodeUser(FILE*); void setNodeGame(FILE*); void freeNode(void); void freeNode_Game(void); void freeNode_User(void); int deleteNode(char*); int findNode(char*); void updateNode(char *, int); void insertNode(struct Node*); void sortNodes(void); void showAllPlayer(void); void loginPage(void); int getLoginState(char*, char*); int isValidId(char*); int isValidPassword(char*, int); void signupPage(); int isIdUnique(char*); int isNickNameUnique(char*); //sliding puzzle void menuGame(void); int game(void); void quizStart(void); //game void menu(void); void programInit(void); //page void signupPage(void); void signinPage(void); void signoutPage(void); void withdrawalPage(void); void puzzleGamePage(void); void playerPage(void); void playerPageForSerach(); void playerPageForShowAll(); void exitPage(void); int main() { programInit(); while (1) { menu(); int page; printf(":"); scanf("%d", &page); getch(); switch (page) { case 1: signupPage(); break; case 2: signinPage(); break; case 3: puzzleGamePage(); break; case 4: playerPage(); break; case 5: signoutPage(); break; case 6: withdrawalPage(); break; case 7: exitPage(); return 0; default: printf("not found page.\n"); } system("clear"); } return 0; } void signupPage() { system("clear"); printf("Sign up Page\n"); char _id[100]; char _password[100]; char _name[100]; char _nickName[100]; while (1) { printf("id: "); scanf("%s", _id); if (isIdUnique(_id) != 0) { printf("already exist id.\n"); continue; } else { printf("good id!\n"); } printf("password: "); scanf("%s", _password); break; } while (1) { printf("nickname: "); scanf("%s", _nickName); if (isNickNameUnique(_nickName) != 0) { printf("already exist nickname\n"); continue; } else { printf("good nickname!\n"); } printf("name: "); scanf("%s", _name); break; } struct Node* node = (struct Node*)malloc(sizeof(struct Node)); strcpy(node -> id, _id); strcpy(node -> password, _password); strcpy(node -> nickName, _nickName); strcpy( node -> name, _name); node -> point = 0; node -> rank = 0; node -> state = 0; node -> next = NULL; insertNode(node); printf("complete sign up! hello!\n"); getch(); } void signinPage() { if (isLogined == 0) { system("clear"); printf("Sign in Page\n"); int loginState; struct Node* cur = nodeHead; char tempId[100]; char tempPassword[100]; while (1) { printf("id : "); scanf("%s", tempId); printf("password : "); scanf("%s", tempPassword); loginState = getLoginState(tempId, tempPassword); if (loginState == -99999) { printf("error id or password. please again.\n"); continue; } else { printf("success!\n"); break; } } while (loginState--) { cur = cur -> next; } cur -> state = 1; isLogined = 1; strcpy(loginedId, cur -> id); printf("welcom! %s\n", cur -> nickName); } else { printf("already logined! back to menu\n"); } getch(); } void signoutPage() { char ans; if (isLogined == 1) { printf("Do you want to sign out? [y/n]: "); scanf("%c", &ans); getch(); if (ans == 'y') { isLogined = 0; struct Node* cur = nodeHead; while (1) { if (strcmp(loginedId, cur -> id)) { cur -> state = 0; break; } else { cur = cur -> next; } } printf("bye %s\n", cur -> name); } else if (ans == 'n') { printf("back to menu.\n"); } else { printf("wrong answer.\n "); } } else { printf("Not logined. Please login first.\n"); } getch(); } void withdrawalPage() { if (isLogined != 0) { struct Node* cur = nodeHead; while (1) { if (strcmp(loginedId, cur -> id)) { break; } else { cur = cur -> next; } } char c; printf("정말 회원을 탈퇴하시겠습니까? [y/n]: "); scanf("%c", &c); if (c == 'y') { if (isLogined == 1) { isLogined = 0; strcpy(loginedId, " "); } deleteNode(loginedId); printf("회원 탈퇴가 완료되었습니다."); } else if (c == 'n') { printf("회원 탈퇴를 취소합니다. 메뉴화면으로 돌아갑니다."); } else { printf("잘못된 입력입니다. 메뉴화면으로 돌아갑니다."); } } else { printf("로그인 상태가 아닙니다.\n"); } getch(); } void menuGame(){ printf(">> 영어 단어 맞추기 프로그램 <<"); printf("\n1. 영어 단어 맞추기 2. 프로그램 종료\n\n번호를 선택하세요: "); }; void puzzleGamePage() { system("clear"); sleep(1); system("clear"); if (isLogined != 0) { printf("환영합니다! %s\n", loginedId); sleep(1); system("clear"); game(); } else { char _ans; printf("로그인 상태가 아닙니다.\n게임 결과는 저장되지 않습니다.\n계속하시겠습니까?[y/n]:" ); scanf("%c", &_ans); getch(); if (_ans == 'y') { printf("게임을 시작합니다.\n"); sleep(1); system("clear"); game(); } else if (_ans == 'n'){ printf("메뉴로 돌아갑니다.\n"); sleep(1); } else { printf("잘못된 입력입니다. 메뉴로 돌아갑니다.\n"); sleep(1); } } } int game() { int n; setNodeGame(openFile_R(2)); while (1) { menuGame(); scanf("%d",&n); switch (n){ case 1: quizStart(); system("clear"); break; case 2: system("clear"); return 0; default: break; } }; }; void quizStart() { struct Words* tmp = head; char eng_a[30], q[30] = ".quit"; double cor = 0, incor = 0; while (1) { printf("%s -> ", tmp->kor); scanf("%s", eng_a); getchar(); if (!strcmp(q,eng_a)) break; if (!strcmp( tmp->eng, eng_a )) { printf("correct!\n"); cor++; } else { printf("incorrect!\n"); incor++; } if(tmp->next == NULL) break; else tmp = tmp->next; }; printf("당신의 점수는 %.2f점입니다.", (cor+incor) == 0 ? 0 : (cor)/(cor+incor)*100); getchar(); }; void playerPage() { system("clear"); int select; printf("============= PLAYER =============\n"); printf("==================================\n"); printf("= 1. search player 2. all player =\n"); printf("==================================\n"); scanf("%d", &select); while (1) { if (select == 1) { playerPageForSerach(); break; } else if (select == 2) { playerPageForShowAll(); break; } else { printf("잘못된 입력입니다. 다시입력해주세요\n"); break; } } } void playerPageForSerach() { char inputForserach[100]; system("clear"); while (1) { system("clear"); printf("search(exit: 0):"); scanf("%s", inputForserach); if (strcmp(inputForserach, "0") == 0) { printf("exit\n"); break; } else { struct Node* cur = nodeHead; int isExist = 0; while (cur != NULL) { if (strstr(cur -> nickName, inputForserach) != NULL) { isExist = 1; } cur = cur -> next; } if (isExist != 0) { printf("| Rank | NickName | Point |\n"); while (cur != NULL) { if (strstr(cur -> nickName, inputForserach) != NULL) { printf(" %d %.2lf %s \n", cur -> rank, cur -> point, cur -> nickName); } cur = cur -> next; } } else { printf("찾으시는 플레이어가 없습니다.\n"); } } getch(); getch(); } getch(); } void playerPageForShowAll() { system("clear"); printf("| Rank | NickName | Point |\n"); showAllPlayer(); getch(); } void programInit() { isLogined = 0; system("clear"); setNodeUser(openFile_R(1)); } void exitPage() { system("clear"); printf("see you next time!!\n"); freeNode(); } void showAllPlayerPage() { showAllPlayer(); } void menu() { printf("==================================\n"); printf("========== SLIDING GAME ==========\n"); isLogined == 0 ? printf("======================== not login\n") : printf("======================== %s\n", loginedId); printf("==================================\n"); printf("= menu =\n"); printf("==================================\n"); printf("= 1. sign up =\n"); printf("= 2. sign in =\n"); printf("= 3. start =\n"); printf("= 4. players =\n"); printf("= 5. sign out =\n"); printf("= 6. delete player =\n"); printf("= 7. exit =\n"); printf("==================================\n"); } int isNickNameUnique(char* nickName) { struct Node* cur = nodeHead; int result = 0; while (cur != NULL) { if (strcmp(nickName, cur -> nickName) == 0) { result = 1; break; } cur = cur -> next; } return result; } int isIdUnique(char* id) { struct Node* cur = nodeHead; int result = 0; while (cur != NULL) { if (strcmp(id, cur -> id) == 0) { result = 1; break; } cur = cur -> next; } return result; } int isValidId(char* id) { struct Node* cur = nodeHead; int result = findNode(id); return result; } int isValidPassword(char* password, int index) { struct Node* cur = nodeHead; int tempIndex = index; int result = 0; while (tempIndex--) { cur = cur -> next; } if (!strcmp(password, cur -> password)) { result = 1; } return result; } int getLoginState(char* tempId, char* tempPassword) { int result = -99999; int checkId = isValidId(tempId); if (checkId == -99999) { return result; } else { result = checkId; } int checkPassword = isValidPassword(tempPassword, checkId); if (!checkPassword) { result = -99999; } return result; } void showAllPlayer() { struct Node* cur = nodeHead; while (1) { printf(" %d %.2lf %s \n", cur -> rank, cur -> point, cur -> nickName); if(cur -> next == NULL) break; else cur = cur -> next; }; getch(); } void setNodeUser(FILE* f) { struct Node* cur; while(1) { struct Node* tempNode = (struct Node*)malloc(sizeof(struct Node)); if (EOF == (fscanf(f,"%s %s %s %s %lf %d %d", tempNode -> nickName, tempNode -> name, tempNode -> id, tempNode -> password, &tempNode -> point, &tempNode -> rank, &tempNode -> state))) { break; } if (nodeHead == NULL){ nodeHead = tempNode; tempNode -> next = NULL; cur = nodeHead; } else { cur -> next = tempNode; tempNode -> next = NULL; cur = cur -> next; } } fclose(f); } void setNodeGame(FILE* f) { struct Words* cur = NULL; struct Words* pre = NULL; while (1) { struct Words* node = (struct Words*)malloc(sizeof(struct Words)); if(EOF == (fscanf(f,"%s %s",node->eng, node->kor))) break; if (head == NULL) { head = node; node->next = last; } else { if (strcmp( node-> eng, head-> eng ) < 0 ) { struct Words* tmp = NULL; tmp = head; head = node; head->next = tmp; } else { pre = head; cur = pre->next; while (1) { if (cur == NULL && strcmp( node->eng, pre->eng ) > 0) { pre->next = node; pre->next->next = cur; break; } else if (strcmp( node->eng, cur->eng ) < 0) { struct Words* tmp = NULL; tmp = cur; pre->next = node; pre->next->next = tmp; break; } else { pre = cur; cur = cur->next; } }; }; }; count++; }; fclose(f); }; void freeNode() { freeNode_User(); freeNode_Game(); } void freeNode_User() { struct Node* node = nodeHead; struct Node* tmp = nodeHead; while(tmp){ node = tmp -> next; free(tmp); tmp = node; }; } void freeNode_Game() { struct Words* node = head; struct Words* tmp = head; while(tmp){ node = tmp->next; free(tmp); tmp = node; }; } int deleteNode(char* id) { struct Node* cur = nodeHead; int result = findNode(id); if(result == -99999) { printf("no data for delete.\n"); } else { struct Node* tempNode = (struct Node*)malloc(sizeof(struct Node)); struct Node* prevNode = (struct Node*)malloc(sizeof(struct Node)); int tempIndex = result; while (tempIndex--) { if (tempIndex == 0) { prevNode = cur; } cur = cur -> next; } tempNode = cur -> next; prevNode -> next = tempNode; free(cur); } return result; } int findNode(char* id) { struct Node* cur = nodeHead; int result = -99999; int index = 0; while (cur != NULL) { if (strcmp(id, cur -> id) == 0) { result = index; return result; } else { cur = cur -> next; } index++; } return result; } void updateNode(char *id, int action) { struct Node* cur = nodeHead; while (cur != NULL) { if (strcmp(id, cur -> id)) { if (action == 1) { //name } else if (action == 2) { //nickname } else if (action == 3) { cur -> point = playTime + moveCount; playTime = 0; moveCount = 0; } break; } cur = cur -> next; } if (cur == NULL) { printf("유효하지 않은 id입니다.\n"); } } void updateFile() { struct Node* cur = nodeHead; FILE* f = openFile_W(); while (cur != NULL) { if (cur -> next == NULL) { fprintf(f, "%s %s %s %s %lf %d %d", cur -> nickName, cur -> name, cur -> id, cur -> password, cur -> point, cur -> rank, cur -> state); } else { fprintf(f, "%s %s %s %s %lf %d %d\n", cur -> nickName,cur -> name, cur -> id, cur -> password, cur -> point, cur -> rank, cur -> state); } cur = cur -> next; } fclose(f); } void insertNode(struct Node* data) { struct Node* cur = nodeHead; while (cur -> next != NULL) { cur = cur -> next; } cur -> next = data; } FILE* openFile_W() { FILE *f; if((f = fopen("client.txt", "w")) == NULL){ printf("Error : Can not open file.\n"); exit(0); } else { return f; } return 0; } FILE* openFile_R(int fileNumber) { FILE *f; switch (fileNumber) { case 1: if((f = fopen("client.txt", "r")) == NULL){ printf("Error : Can not open file.\n"); exit(0); } else return f; break; case 2: if((f = fopen("dict.txt", "r")) == NULL){ printf("파일을 열 수가 없습니다.\n"); exit(0); } else return f; default: break; } return 0; } int getch(void){ int ch; struct termios buf; struct termios save; tcgetattr(0,&save); buf = save; buf.c_lflag &= ~(ICANON | ECHO); buf.c_cc[VMIN] = 1; buf.c_cc[VTIME] = 0; tcsetattr(0,TCSAFLUSH,&buf); ch = getchar(); tcsetattr(0,TCSAFLUSH,&save); return ch; }
C
#define _CRT_SECURE_NO_WARNINGS // scanf #include <stdio.h> int main() { int count; scanf("%d", &count); // Է¹ for (; count > 0; count--) // ʱ갪 scanf ҽѼ ݺ { printf("Hello, world! %d\n", count); } return 0; }
C
#ifndef SUPPORT_H #define SUPPORT_H #define PI 3.14159265358979323846 #include <cmath> // return radians - same way as asin() of <cmath> double myAsin(double sinAlpha, double cosAlpha) { if (sinAlpha > 0.) { if (cosAlpha > 0.) { return asin(sinAlpha); } else { return PI - asin(sinAlpha); } } else { if (cosAlpha > 0.) { return 2.*PI + asin(sinAlpha); } else { return PI - asin(sinAlpha); } } } #endif // SUPPORT_H
C
#include <stdio.h> char *secret = "password"; void shell() { char *shell = "/bin/sh"; char *cmd[] = { "/bin/sh", 0 }; printf("The Force Is Strong With You\n"); //setreuid(0); execve(shell,cmd,0); } int authorization() { char password[64]; printf("Enter Password: "); gets(password); if (!strcmp(password,secret)) return 1; else return 0; } int main() { if (authorization()) { printf("ACCESS GRANTED! \n"); shell(); } else { printf("Do or Do Not, There Is No Try . . . . \n"); } return 0; }
C
#include<stdio.h> #include<stdlib.h> #include<time.h> /*this is for stack */ typedef struct st{ int data; struct st *next; }stack; /*these are for queue*/ typedef struct qu{ int data; struct qu *next; }node_t; typedef struct{ node_t *frontp; node_t *rearp; int size; }queue; /*this is for binary tree*/ typedef struct b_tree{ int data; struct b_tree *leftp,*rightp; }bst; void fill_structures(stack ** stack_, queue ** queue_, bst ** bst_, int data[20]); void ordered_print(stack * stack_, queue * queue_, bst * bst_); void search(stack * stack_, queue * queue_, bst * bst_, int val_to_search); void special_traverse(stack * stack_, queue * queue_, bst * bst_); /*My Helper Functions*/ bst *fill_bst( bst * bst_,int data); void bubble_sort(stack *roots,queue *rootq,int flag); void print_bst(bst * bst_,int *min,int flag); void tree_search(bst *rootp,int searc_key,int step); stack *create_temp_s(stack *root); queue *create_temp_q( queue *root); int find_max_s(stack *root); int find_min_s(stack *root); stack *pop(stack *root,int key); int find_max_q(queue *root); int find_min_q(queue *root); queue *pop_q(queue *root,int key); void print_bst_min(bst * bst_,int flag,int *min); void print_bst_traverse(bst * bst_,bst *bst2,int flag,int *min); int main(){ int data[20]={5, 2, 7, 8, 11, 3, 21, 7, 6, 15, 19, 35, 24, 1, 8, 12, 17,8, 23, 4}; bst * bst_; queue * queue_; stack *stack_; fill_structures(&stack_, &queue_, &bst_, data); ordered_print(stack_, queue_, bst_); search(stack_, queue_, bst_, 5); special_traverse(stack_, queue_, bst_); return 0; } void fill_structures(stack ** stack_, queue ** queue_, bst ** bst_, int data[20]){ int i; /*fill the stack*/ double time_s,time_q,time_b,mili; mili=(double)1000; clock_t s,e; *stack_ =NULL; s=clock(); for (i = 0; i < 20; i++) { stack *newp; newp=(stack *)malloc(sizeof(stack)); newp->data=data[i]; newp->next=*stack_; *stack_=newp; } e=clock(); time_s = ((double) (e - s)/CLOCKS_PER_SEC)*mili; /*fill the queue*/ *queue_ =(queue*)malloc(sizeof(queue)); (*queue_)->size=0; s=clock(); for (i = 0; i < 20; i++) { if ((*queue_)->size ==0) { (*queue_)->rearp=(node_t*)malloc(sizeof(node_t)); (*queue_)->frontp= (*queue_)->rearp; } else { (*queue_)->rearp->next=(node_t*)malloc(sizeof(node_t)); (*queue_)->rearp= (*queue_)->rearp->next; } (*queue_)->rearp->data=data[i]; (*queue_)->rearp->next=NULL; (*queue_)->size=(*queue_)->size+1; } e=clock(); time_q = ((double) (e - s)/CLOCKS_PER_SEC)*mili; /*fill the bst*/ s=clock(); for (i = 0; i < 20; i++) { *bst_=fill_bst((*bst_),data[i]); } e=clock(); time_b = ((double) (e - s)/CLOCKS_PER_SEC)*mili; printf("-------------------FILL--------------------------------\n"); printf("Structures\tStack\tQueue\tBST\n"); printf("Exec. Time\t%.3f\t%.3f\t%.3f\n",time_s,time_q,time_b); printf("\n"); } bst *fill_bst( bst * bst_,int data){ if (bst_ == NULL) { bst_ = (bst*)malloc(sizeof(bst)); bst_->data = data; bst_->leftp = NULL; bst_->rightp = NULL; } else if (data == bst_->data) { //same data //don't insert } else if (data < bst_->data) { bst_->leftp = fill_bst(bst_->leftp, data); } else { bst_->rightp =fill_bst(bst_->rightp,data); } return bst_; } void ordered_print(stack * stack_, queue * queue_, bst * bst_){ printf("-------------------ORDERED PRINT-----------------------\n"); double time_s,time_q,time_b,mili; mili=(double)1000; clock_t s,e; int max,min; stack *temp_s,*head; queue *temp_q; /*order and print temp stack*/ s=clock(); temp_s=create_temp_s(stack_); //create a temp stack bubble_sort(temp_s,temp_q,0); //sort the temp stack printf("Stack: "); while (temp_s!=NULL) //print sorted temp stack { printf("%d ",temp_s->data); temp_s=temp_s->next; } printf("\n"); e=clock(); time_s = ((double)(e - s)/CLOCKS_PER_SEC)*mili; /*order and print temp queue*/ s=clock(); temp_q=create_temp_q(queue_);//create a temp queue bubble_sort(temp_s,temp_q,1); //sort the temp queue printf("Queue: "); while (temp_q->frontp!=NULL) //print sorted temp queue { printf("%d ",temp_q->frontp->data); temp_q->frontp=temp_q->frontp->next; } printf("\n"); e=clock(); time_q = ((double)(e - s)/CLOCKS_PER_SEC)*mili; /*print bst*/ printf("Bst: "); s=clock(); print_bst(bst_,&min,1); //print bst with recursively e=clock(); time_b = ((double)(e - s)/CLOCKS_PER_SEC)*mili; printf("\n"); /*Print time*/ printf("Structures\tStack\tQueue\tBST\n"); printf("Exec. Time\t%.3f\t%.3f\t%.3f\n",time_s,time_q,time_b); /*free the temps variable*/ free(temp_s); free(temp_q); printf("\n"); } stack *create_temp_s(stack *root){ /*İn order to not break the orijinal stack create a temp stack*/ stack *temp,*head; stack *iter=root; temp=(stack*)malloc(sizeof(temp)); head=temp; while (iter!=NULL) { temp->data=iter->data; if (iter->next!=NULL) { temp->next=(stack*)malloc(sizeof(temp)); temp=temp->next; } else temp->next=NULL; iter=iter->next; } return head; } queue *create_temp_q( queue *root){ /*İn order to not break the orijinal queue create a temp queue*/ queue *temp,*head; queue *iter; iter=(queue*)malloc(sizeof(queue)); iter->frontp=root->frontp; temp =(queue*)malloc(sizeof(queue)); temp->rearp=(node_t*)malloc(sizeof(node_t)); temp->frontp=temp->rearp; head=temp; while (iter->frontp!=NULL) { temp->rearp->data=iter->frontp->data; if (iter->frontp->next!=NULL) { temp->rearp->next=(node_t*)malloc(sizeof(node_t)); temp->rearp= temp->rearp->next; temp->size=temp->size+1; temp->rearp->next=NULL; } else// { temp->rearp->next=NULL; } iter->frontp=iter->frontp->next; } return head; } void bubble_sort(stack *roots,queue *rootq,int flag){ if (flag==0) /*sort stack*/ { stack *iter,*iter2,tmp; iter=roots; /*bubble sort with while loops*/ while(iter!=NULL){ iter2=iter->next; while (iter2!=NULL) { if (iter2->data > iter->data){ /*swap them*/ tmp=*iter2; iter2->data=iter->data; iter->data=tmp.data; } iter2=iter2->next; } iter=iter->next; if (iter->next==NULL) iter=iter->next; } } else{ /*sort queue*/ node_t *iter,*iter2,tmp; iter=rootq->frontp; /*bubble sort with while loops*/ while(iter!=NULL){ iter2=iter->next; while (iter2!=NULL) { if (iter2->data > iter->data){ /*swap them*/ tmp=*iter2; iter2->data=iter->data; iter->data=tmp.data; } iter2=iter2->next; } iter=iter->next; if (iter->next==NULL) iter=iter->next; } } } void print_bst(bst * bst_,int *min,int flag){ if (bst_==NULL) // base case { return;//stop; } else { print_bst(bst_->rightp,min,flag); if (flag==1) { printf("%d ",bst_->data); } else { *min=bst_->data; } print_bst(bst_->leftp,min,flag); } } void search(stack * stack_, queue * queue_, bst * bst_, int val_to_search){ printf("-------------------SEARCHING---------------------------\n"); double time_s,time_q,time_b,mili; int i=1; mili=(double)1000; clock_t s,e; stack * iter=stack_; s=clock(); //search in the stack while (iter!=NULL) { if (iter->data==val_to_search) { printf("1 result founded on %d. step.(in Stack)\n",i); } iter=iter->next; i++; } e=clock(); time_s = ((double)(e - s)/CLOCKS_PER_SEC)*mili; i=1; node_t * iter1=queue_->frontp; s=clock(); //search in the queue while (iter1!=NULL) { if (iter1->data==val_to_search) { printf("1 result founded on %d. step.(in Queue)\n",i); } iter1=iter1->next; i++; } e=clock(); time_q = ((double) (e - s)/CLOCKS_PER_SEC)*mili; i=0; s=clock(); tree_search(bst_,val_to_search,i); //search in the bst e=clock(); time_b = ((double) (e - s)/CLOCKS_PER_SEC)*mili; printf("Structures\tStack\tQueue\tBST\n"); printf("Exec. Time\t%.3f\t%.3f\t%.3f\n",time_s,time_q,time_b); printf("\n"); } void tree_search(bst *rootp,int searc_key,int step){ /*search tree with recursively*/ if (rootp==NULL) { return; } else if (rootp->data==searc_key) { step++; printf("1 Result founded on %d. step.(in Bst)\n",step); } else if (searc_key<rootp->data) { step++; tree_search(rootp->leftp,searc_key,step); } else { step++; tree_search(rootp->rightp,searc_key,step); } } void special_traverse(stack * stack_, queue * queue_, bst * bst_){ printf("-------------------SPEACIAL TRAVERSE-------------------\n"); double time_s,time_q,time_b,mili; int max,min; mili=(double)1000; clock_t s,e; stack *temp_s; queue *temp_q; /*print stack*/ s=clock(); temp_s=create_temp_s(stack_);//create a temp stackk printf("Stack: "); while (temp_s!=NULL) { max=find_max_s(temp_s);//find max in the temp stack printf("%d ",max); //print it temp_s=pop(temp_s,max); //delete it from temp stack min=find_min_s(temp_s); //find min in the temp stack printf("%d ",min); //print it temp_s=pop(temp_s,min); //delete it from temp stack } printf("\n"); e=clock(); time_s = ((double) (e - s)/CLOCKS_PER_SEC)*mili; /*print queue*/ s=clock(); printf("Queue: "); temp_q=create_temp_q(queue_);//create a temp stack while (temp_q->frontp!=NULL) { max=find_max_q(temp_q);//find max in the temp queue printf("%d ",max); //print it temp_q=pop_q(temp_q,max);//delete it from temp queue min=find_min_q(temp_q);//find min in the temp queue printf("%d ",min);//print it temp_q=pop_q(temp_q,min);//delete it from temp queue } printf("\n"); e=clock(); time_q = ((double) (e - s)/CLOCKS_PER_SEC)*mili; /*print bst*/ printf("Bst: "); print_bst(bst_,&min,0);//find the min value of bst min--; s=clock(); print_bst_traverse(bst_,bst_,min,&min); //print traverse e=clock(); time_b = ((double)(e - s)/CLOCKS_PER_SEC)*mili; printf("\n"); printf("Structures\tStack\tQueue\tBST\n"); printf("Exec. Time\t%.3f\t%.3f\t%.3f\n",time_s,time_q,time_b); printf("------------------------------------------------------\n"); free(temp_s); free(temp_q); } int find_max_s(stack *root){ //find the max value of stack int max; stack *iter; iter=root; max=iter->data; while(iter!=NULL){ if (iter->data > max){ max=iter->data; } iter=iter->next; } return max; } int find_min_s(stack *root){ //find the min value of stack int min; stack *iter; iter=root; min=iter->data; while(iter!=NULL){ if (iter->data < min){ min=iter->data; } iter=iter->next; } return min; } stack *pop(stack *root,int key){ //delete given key from stack stack *iter=root; stack *temp; if (iter->next==NULL) { temp=iter; root=NULL; free(temp); return root; } else if (iter->data==key) { temp=iter; iter=iter->next; root=iter; free(temp); return root; } else { while (iter->next!=NULL) { if (iter->next->data==key) { temp=iter->next; iter->next=iter->next->next; free(temp); break; } iter=iter->next; } } return root; } int find_max_q(queue *root){ //find the max value of queue int max; node_t *iter; iter=root->frontp; max=iter->data; while(iter!=NULL){ if (iter->data > max){ max=iter->data; } iter=iter->next; } return max; } int find_min_q(queue *root){ //find the min value of queue int min; node_t *iter; iter=root->frontp; min=iter->data; while(iter!=NULL){ if (iter->data < min){ min=iter->data; } iter=iter->next; } return min; } queue *pop_q(queue *root,int key){ //delete given key from queue queue *iter; node_t *temp; iter=(queue*)malloc(sizeof(queue)); iter->frontp=root->frontp; if (iter->frontp->next==NULL) { temp=iter->frontp; root->frontp=NULL; free(temp); return root; } else if (iter->frontp->data==key) { temp=iter->frontp; iter->frontp=iter->frontp->next; root->frontp=iter->frontp; free(temp); return root; } else { while (iter->frontp->next!=NULL) { if (iter->frontp->next->data==key) { temp=iter->frontp->next; iter->frontp->next=iter->frontp->next->next; free(temp); break; } iter->frontp=iter->frontp->next; } } return root; } void print_bst_min(bst * bst_,int flag,int *min){ /*return min value of bst in order*/ if (bst_==NULL) // base case { return;//stop; } else { print_bst_min(bst_->leftp,flag,min); if (bst_->data > (*min) && flag==(*min)) { *min=bst_->data; } print_bst_min(bst_->rightp,flag,min); } } void print_bst_traverse(bst * bst_,bst *bst2,int flag,int *min){ if (bst_==NULL) // base case { return;//stop; } else// { print_bst_traverse(bst_->rightp,bst2,flag,min); if (!(*min>=bst_->data)) { printf("%d ",bst_->data); //print max value if (flag!= (*min)) flag=(*min); print_bst_min(bst2,flag,min); //find min value of bst flag=(*min); if ((*min)!=bst_->data) { printf("%d ",flag); //print min value } } print_bst_traverse(bst_->leftp,bst2,flag,min); } }
C
#define NULL ((void*)0) typedef unsigned long size_t; // Customize by platform. typedef long intptr_t; typedef unsigned long uintptr_t; typedef long scalar_t__; // Either arithmetic or pointer type. /* By default, we understand bool (as a convenience). */ typedef int bool; #define false 0 #define true 1 /* Forward declarations */ /* Type definitions */ /* Variables and functions */ int /*<<< orphan*/ GIT_FILELOCK_EXTENSION ; int /*<<< orphan*/ is_valid_ref_char (char const) ; int /*<<< orphan*/ memcmp (char const*,int /*<<< orphan*/ ,int const) ; scalar_t__ strlen (int /*<<< orphan*/ ) ; __attribute__((used)) static int ensure_segment_validity(const char *name, char may_contain_glob) { const char *current = name; char prev = '\0'; const int lock_len = (int)strlen(GIT_FILELOCK_EXTENSION); int segment_len; if (*current == '.') return -1; /* Refname starts with "." */ for (current = name; ; current++) { if (*current == '\0' || *current == '/') break; if (!is_valid_ref_char(*current)) return -1; /* Illegal character in refname */ if (prev == '.' && *current == '.') return -1; /* Refname contains ".." */ if (prev == '@' && *current == '{') return -1; /* Refname contains "@{" */ if (*current == '*') { if (!may_contain_glob) return -1; may_contain_glob = 0; } prev = *current; } segment_len = (int)(current - name); /* A refname component can not end with ".lock" */ if (segment_len >= lock_len && !memcmp(current - lock_len, GIT_FILELOCK_EXTENSION, lock_len)) return -1; return segment_len; }
C
#include <common.h> static queue_st q; static queue_item_st items[100]; void test_queue() { int i; for (i = 0; i < 100; ++i) { items[i].p = (void *)(intptr_t)i; } queue_init(&q, "test"); queue_push(&q, &items[0]); assert(queue_pop(&q) == &items[0]); assert(queue_pop(&q) == NULL); for (i = 0; i < 100; ++i) { queue_push(&q, &items[i]); } for (i = 0; i < 100; ++i) { assert(queue_pop(&q) == &items[i]); } assert(queue_pop(&q) == NULL); }
C
<<<<<<< HEAD #include <stdio.h> int main() { int A,B,C,maior; scanf(" %i", &A); scanf(" %i", &B); scanf(" %i", &C); if(A > B && A > C) { maior = A; } else { if(B > A && B > C) { maior = B; } else { maior = C; } } printf("%i eh o maior\n", maior); ======= #include <stdio.h> int main() { int A,B,C,maior; scanf(" %i", &A); scanf(" %i", &B); scanf(" %i", &C); if(A > B && A > C) { maior = A; } else { if(B > A && B > C) { maior = B; } else { maior = C; } } printf("%i eh o maior\n", maior); >>>>>>> b40020655e623470d8694fef4dab9e11f5ddbd76 }
C
// Simulado para a prova p1. #include<stdio.h> #include<stdlib.h> #include<string.h> //funcoes void push(); void mostrar(); void pop(); //variaveis globais int topo=0; int pilha[31]; int entrada; int i=0, c, qtd=0; //main int main(){ for(i=0; i<5;i++){ scanf("%d", &entrada); if(entrada%2==0){ push(); }else{ pop(); } } mostrar(); } //funcoes void push(){ pilha[topo]=entrada; topo++; qtd++; } void pop(){ if(topo!=0){ pilha[topo-1]= 0; topo--; } } void mostrar(){ if(topo!=0){ for(c=0; c<qtd;c++){ printf("\n%d\n", pilha[c]); } }else{ printf("Nao existem numeros armazenados\n"); } }
C
// UTMSPACE_2018-2019-sem2_SCSJ1013_Programming_Techniques_I // SX180357CSJS04 // Randy Tan Shaoxian // Algorithm for the program: total_cost_of_apples // 1. Begin. // 2. Read in the value for the amount in kg of the apples, store it in amount. // 3. Read in the value for the cost per kg of the apples in RM, store it in cost_per_kg. // 4. Calculate the total cost of apples in RM by multiplying amount by cost_per_kg, store it in total. // 5. Write the value of total to the output. // 6. End. // Input & Output 1 // // Input // How many kg of apples? 10 // Cost per kg? RM5 // // Output // Total cost of apples is RM50.00. // Input & Output 2 // // Input // How many kg of apples? 5.99 // Cost per kg? RM12.3 // // Output // Total cost of apples is RM73.68. // Input & Output 3 // // Input // How many kg of apples? 13 // Cost per kg? RM999 // // Output // Total cost of apples is RM12987.00. #include <stdio.h> int main (void) { float amount, cost_per_kg, total; printf("How many kg of apples? "); scanf("%f", &amount); printf ("Cost per kg? RM"); scanf("%f", &cost_per_kg); total = amount * cost_per_kg; printf("Total cost of apples is RM%0.2f.\n", total); return 0; }
C
#include <core/shader.h> #include <string.h> #include <memory.h> struct Shader_s { GLuint _program; GLuint _handles[MAX_SHADERS]; char* _srcs[MAX_SHADERS]; }; CENGINE_API SHADER* CENGINE_CALL new_shader_f(const char* vs_path, const char* fs_path) { SHADER* shader = new_shader(); if (MAX_SHADERS >= 2) { shader->_srcs[VERTEX_SHADER] = shader_load_vs(shader, vs_path); shader->_srcs[FRAGMENT_SHADER] = shader_load_fs(shader, fs_path); int* comp_result = shader_compile(shader); return shader; } else { free(shader); } return NULL; } CENGINE_API SHADER* CENGINE_CALL new_shader() { SHADER* shader = (SHADER*) malloc(sizeof(SHADER)); return shader; } CENGINE_API void CENGINE_CALL free_shader(SHADER* shader) { glDeleteProgram(shader->_program); shader = NULL; free(shader); } CENGINE_API void CENGINE_CALL shader_use_p(SHADER* shader) { glUseProgram(shader->_program); } CENGINE_API char* CENGINE_CALL shader_load_vs(SHADER* shader, const char* file_path) { return shader_load_file(shader, file_path, GL_VERTEX_SHADER); } CENGINE_API char* CENGINE_CALL shader_load_fs(SHADER* shader, const char* file_path) { return shader_load_file(shader, file_path, GL_FRAGMENT_SHADER); } CENGINE_API char* CENGINE_CALL shader_load_file(SHADER* shader, const char* file_path, GLenum type) { FILE* file_p; char* buffer = NULL; size_t size; file_p = fopen(file_path, "rb"); if (file_p != NULL) { fseek(file_p, 0, SEEK_END); size = ftell(file_p); fseek(file_p, 0, SEEK_SET); buffer = (char*) malloc(sizeof(char) * (size)); fread(buffer, 1, size, file_p); // Make sure that we don't have any trailing garbage in the buffer // because apparently we were getting some for some reason memset(&buffer[size], '\0', 1); } else { fprintf(stderr, "Error opening %s for reading", file_path); } fclose(file_p); return buffer; } CENGINE_API int* CENGINE_CALL shader_compile(SHADER* shader) { shader->_handles[VERTEX_SHADER] = glCreateShader(GL_VERTEX_SHADER); shader->_handles[FRAGMENT_SHADER] = glCreateShader(GL_FRAGMENT_SHADER); bool results[MAX_SHADERS]; int infoLogLength = 0; GLint result = GL_FALSE; bool shouldLinkProgram = true; int i; for (i = 0; i < MAX_SHADERS; i++) { results[i] = true; char const* src = shader->_srcs[i]; glShaderSource(shader->_handles[i], 1, &src, NULL); glCompileShader(shader->_handles[i]); glGetShaderiv(shader->_handles[i], GL_COMPILE_STATUS, &result); glGetShaderiv(shader->_handles[i], GL_INFO_LOG_LENGTH, &infoLogLength); if (infoLogLength > 0) { results[i] = false; shouldLinkProgram = false; char* error_buffer = (char*) malloc(sizeof(char) * infoLogLength); glGetShaderInfoLog(shader->_handles[i], infoLogLength, NULL, error_buffer); printf("%s\n", error_buffer); free(error_buffer); } } if (shouldLinkProgram == true) { shader->_program = glCreateProgram(); for (i = 0; i < MAX_SHADERS; i++) { glAttachShader(shader->_program, shader->_handles[i]); } glLinkProgram(shader->_program); for (i = 0; i < MAX_SHADERS; i++) { glDetachShader(shader->_program, shader->_handles[i]); glDeleteShader(shader->_handles[i]); free(shader->_srcs[i]); } glGetProgramiv(shader->_program, GL_LINK_STATUS, &result); glGetProgramiv(shader->_program, GL_INFO_LOG_LENGTH, &infoLogLength); if (infoLogLength > 0) { char* error_buffer = (char*) malloc(sizeof(char) * infoLogLength); glGetProgramInfoLog(shader->_program, infoLogLength, NULL, error_buffer); printf("%s\n", error_buffer); free(error_buffer); } } return results; } CENGINE_API void CENGINE_CALL shader_set_matrix4f(SHADER* shader, const char* name, const Matrix_4f* m) { } CENGINE_API void CENGINE_CALL shader_set_vec2f(SHADER* shader, const char* name, const vec2_f* v) { } CENGINE_API void CENGINE_CALL shader_set_vec3f(SHADER* shader, const char* name, const vec3_f* v) { } CENGINE_API void CENGINE_CALL shader_set_vec4f(SHADER* shader, const char* name, const vec4_f* v) { } CENGINE_API void CENGINE_CALL shader_set_float(SHADER* shader, const char* name, float val) { } CENGINE_API void CENGINE_CALL shader_set_bool(SHADER* shader, const char* name, bool val) { } CENGINE_API void CENGINE_CALL shader_set_int(SHADER* shader, const char* name, int val) { } CENGINE_API void CENGINE_CALL shader_set_uint(SHADER* shader, const char* name, unsigned int val) { }
C
#ifndef __STM8S_ENCODER_C #define __STM8S_ENCODER_C #include "inc/stm8s_encoder.h" void EncoderInit(encoder_t* encod, GPIO_TypeDef* GPIOx_A, GPIO_Pin_TypeDef GPIO_PIN_A, GPIO_TypeDef* GPIOx_B, GPIO_Pin_TypeDef GPIO_PIN_B, int32_t cnt,int32_t boost_max,uint16_t period_max ) { /* encod->p1_gpio=p1_Gpio; encod->p1_pin=p1_Pin; encod->p2_gpio=p2_Gpio; encod->p2_pin=p2_Pin; */ encod->cnt=cnt; encod->boost_max=boost_max; encod->period=1; if (period_max>0) { encod->period_max=period_max; encod->period=period_max; } else { encod->period_max=1; } GPIO_Init(GPIOx_A, GPIO_PIN_A, GPIO_MODE_IN_FL_NO_IT); GPIO_Init(GPIOx_B, GPIO_PIN_B, GPIO_MODE_IN_FL_NO_IT); encod->p1_last=GPIO_ReadInputPin(GPIOx_A, GPIO_PIN_B); encod->p2_last=GPIO_ReadInputPin(GPIOx_B, GPIO_PIN_B); } int32_t EncoderRead(encoder_t* encod, GPIO_TypeDef* GPIOx_A, GPIO_Pin_TypeDef GPIO_PIN_A, GPIO_TypeDef* GPIOx_B, GPIO_Pin_TypeDef GPIO_PIN_B) { int8_t dir; // int32_t dc; // if (encod->period<encod->period_max) { encod->period++; } // encod->p1_now=GPIO_ReadInputPin(GPIOx_A, GPIO_PIN_A); encod->p2_now=GPIO_ReadInputPin(GPIOx_B, GPIO_PIN_B); // 1 if (encod->p1_last!=encod->p1_now) { encod->p1_last=encod->p1_now; encod->p1_front=1; dir=1; } // 1 if (encod->p2_last!=encod->p2_now) { encod->p2_last=encod->p2_now; encod->p2_front=1; dir=-1; } // if ((encod->p1_now==encod->p2_now)&&(encod->p1_front)&&(encod->p2_front) ) { encod->p1_front=0; encod->p2_front=0; dc=dir*encod->boost_max/encod->period; encod->period=0; if ((dc>0) && (encod->cnt>0)) { encod->cnt+=dc; if (encod->cnt<0) { encod->cnt=S32_MAX; } return encod->cnt; } if ((dc<0) && (encod->cnt<0)) { encod->cnt+=dc; if (encod->cnt>0) { encod->cnt=S32_MIN; } return encod->cnt; } } else { dc=0; } encod->cnt+=dc; return encod->cnt; } void EncoderSetCount(encoder_t* encod,int32_t cnt) { encod->cnt=cnt; } #endif
C
#include "dataplane/iface.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <signal.h> #include <string.h> #include <sys/time.h> #include <sys/types.h> interface *iface_h1_sw, *iface_h2_sw; interface * initialize_interface(char *name) { interface *iface = malloc(sizeof(interface)); iface->name = strdup(name); iface->iface_socket = -1; iface->state = 0; return iface; } interface * get_out_port(char *buf, int buf_size, interface *in_port) { // TODO printf("DST MAC: %X:%X:%X:%X:%X:%X\n", buf[0], buf[1], buf[2], buf[3], buf[4], buf[5]); printf("SRC MAC: %X:%X:%X:%X:%X:%X\n", buf[6], buf[7], buf[8], buf[9], buf[10], buf[11]); if (in_port == NULL) { return NULL; } if (in_port->name == "h1-sw") { return iface_h2_sw; } else if (in_port->name == "h2-sw") { return iface_h1_sw; } printf("no matching interface for out_port.\n"); return NULL; } int main(int argc, char *argv[]) { interface *iface_h1_sw = initialize_interface("h1-sw"); interface *iface_h2_sw = initialize_interface("h2-sw"); int retCode; retCode = up(iface_h1_sw); printf("\nresult of interface h1-sw up is %d\n", retCode); retCode = up(iface_h2_sw); printf("\nresult of interface h2-sw up is %d\n", retCode); fd_set read_fds; struct timeval tv; tv.tv_sec = 10; tv.tv_usec = 500000; __time_t delay = 60; __time_t start_time = time(NULL); while (time(NULL) - start_time < delay) { FD_ZERO(&read_fds); FD_SET(iface_h1_sw->iface_socket, &read_fds); FD_SET(iface_h2_sw->iface_socket, &read_fds); retCode = select(FD_SETSIZE, &read_fds, NULL, NULL, &tv); if (retCode <= 0) { printf("Failed to select socket descriptor"); goto end; } printf("select is ok\n"); ssize_t recv_size = -1; ssize_t send_size = -1; if (FD_ISSET(iface_h1_sw->iface_socket, &read_fds)) { // h1-sw forward to h2-sw printf("recieve from h1-sw is ready. receiving now..."); char buf[1500]; memset(&buf, 0, sizeof(buf)); recv_size = iface_recv(iface_h1_sw, &buf, sizeof(buf)); if (recv_size == -1) { perror("error in Socket receive\n"); exit(0); } printf("recieved %d bytes\n", recv_size); get_out_port(buf, recv_size, NULL); send_size = iface_send(iface_h2_sw, &buf, recv_size); if (send_size == -1) { perror("error in Socket send\n"); exit(0); } printf("sent %d bytes\n", sizeof(buf)); } else { printf("h1-sw is not ready for recieve.\n"); } if (FD_ISSET(iface_h2_sw->iface_socket, &read_fds)) { // h2-sw forward to h1-sw printf("recieve from h2-sw is ready. receiving now..."); char buf[1500]; memset(&buf, 0, sizeof(buf)); recv_size = iface_recv(iface_h2_sw, &buf, recv_size); if (recv_size == -1) { perror("error in Socket receive\n"); exit(0); } printf("recieved %d bytes\n", recv_size); get_out_port(buf, recv_size, NULL); send_size = iface_send(iface_h1_sw, &buf, sizeof(buf)); if (send_size == -1) { perror("error in Socket send\n"); exit(0); } printf("sent %d bytes\n", sizeof(buf)); } else { printf("h2-sw is not ready for recieve.\n"); } } end: retCode = down(iface_h1_sw); retCode = down(iface_h2_sw); printf("\nresult of interface down is %d\n", retCode); return 0; }
C
#define _POSIX_C_SOURCE 200809 #include <stdio.h> #include <sys/ioctl.h> #include <linux/fb.h> #include <fcntl.h> #include <sys/stat.h> #include <sys/types.h> int main(void) { int fd = open("/dev/dri/card0", O_RDONLY); if (!fd) { perror("open(\"/dev/dri/card0\")"); return 1; } struct fb_fix_screeninfo si; int ret = ioctl(fd, FBIOGET_FSCREENINFO, &si); if (ret) { perror("ioctl(FBIOGET_FSCREENINFO)"); return 1; } printf("Ioctl succeded\n"); printf("%u\n", si.smem_len); printf("%u\n", si.line_length); printf("%lx\n", si.mmio_start); // on my computer this shows si.mmio_start = 0 certainly because I'm using // Nvidia proprietary drivers, thus calling the DRM is not the way to do it. return 0; }
C
#include <stdio.h> #include <stdlib.h> int main() { int n,i,j,y,t[100],tab[100]; do{ printf("Donner la Taille du tableau : \n"); scanf("%d",&n); }while (((n%2)!=0)|| (n<1)); for(i=0;i<n;i++){ printf("Case[%d] : ",i); scanf("%d",&t[i]); t[i+1]=t[i]; i++; } printf("\n \nTABLEAU INITIAL : \n"); for (i=0;i<n;i++){ printf ("%d|",t[i]); } y=0; for(i=0;i<n;i=i+2){ tab[y]=t[i]; y++; } for(j=n-1;j>=0;j=j-2){ tab[y]=t[j]; y++; } printf("\n \nTABLEAU FINAL : \n"); for(y=0;y<n;y++){ printf("%d|",tab[y]); } return 0; }
C
#include <stdio.h> int main() { int n, cnt = 0; char s[101]; scanf("%d", &n); scanf("%s", s); for(int i = 0; i < n; ++i) { cnt += s[i] == '8'; } int ans = cnt; if(ans > n / 11) { ans = n / 11; } printf("%d\n", ans); return 0; }
C
/* to compile: gcc -o CPacking CPacking.c * to run: ./CPacking */ #include <stdio.h> int main() { int a; short b; short c; printf("%x int a\n", &a); printf("%x short b\n", &b); printf("%x short c\n", &c); }
C
/* * Sort01.c * sorting an array of 0's and 1's * Created on: May 4, 2014 * Author: Venkata */ void sort01(int *arr, int n) { int left=0, right=n-1, temp; while(left < right) { //see the problem if you leave it with arr[left] below ? //say if there are only 0's in the arr! while(arr[left] == 0 && left < right) left++; while(arr[right] == 1 && left < right) right--; if(left < right) { temp = arr[left]; arr[left] = arr[right]; arr[right] = temp; left++; right--; } } } void _sort01() { int arr[14] = {0, 1, 0, 0, 0, 1, 1, 1, 0, 1, 1, 1, 0, 0}, i; sort01(arr, sizeof(arr)/sizeof(int)); for(i=0; i<sizeof(arr)/sizeof(int); i++) printf("%d|", arr[i]); }
C
/* * PWMControl.c * * Created on: Jul 9, 2020 * Author: raing */ #include "main.h" uint32_t IC_Value1 = 0; uint32_t IC_Value2 = 0; uint32_t Difference = 0; uint32_t Frequency = 0; uint8_t Is_First_Captured = 0; // 0- not captured, 1- captured bool NewDiffAvailable = false; void start_pwm1(int onTimemSec) { TIM2->CCR1 = onTimemSec * 4 / 10; HAL_TIM_PWM_Start(&htim2, TIM_CHANNEL_1); } void set_pwm1(int onTimemSec) { TIM2->CCR1 = onTimemSec * 4 / 10; } void stop_pwm1(void) { HAL_TIM_PWM_Stop(&htim2, TIM_CHANNEL_1); } void start_pwm2(int PercentOn) { TIM1->CCR4 = PercentOn; HAL_TIM_PWM_Start(&htim1, TIM_CHANNEL_4); } void set_pwm2(int PercentOn) { TIM1->CCR4 = PercentOn; } void stop_pwm2(void) { HAL_TIM_PWM_Stop(&htim1, TIM_CHANNEL_4); } void start_pwm3(void) { HAL_TIM_IC_Start_IT(&htim1, TIM_CHANNEL_1); } void stop_pwm3(void) { HAL_TIM_IC_Stop_IT(&htim1, TIM_CHANNEL_1); } void start_pwm4(int onTimemSec) { TIM1->CCR3 = onTimemSec * 4 / 10; HAL_TIM_PWM_Start(&htim1, TIM_CHANNEL_3); } void stop_pwm4(void) { HAL_TIM_PWM_Stop(&htim1, TIM_CHANNEL_3); } void HAL_TIM_IC_CaptureCallback(TIM_HandleTypeDef *htim) { if (htim->Channel == HAL_TIM_ACTIVE_CHANNEL_1) // if interrput source is channel 1 { if (Is_First_Captured==0) // is the first value captured ? { IC_Value1 = HAL_TIM_ReadCapturedValue(htim, TIM_CHANNEL_1); // capture the first value Is_First_Captured =1; // set the first value captured as true } else if (Is_First_Captured) // if the first is captured { IC_Value2 = HAL_TIM_ReadCapturedValue(htim, TIM_CHANNEL_1);//HAL_TIM_ReadCapturedValue(htim, TIM_CHANNEL_1); // capture second value if (IC_Value2 > IC_Value1) { Difference = IC_Value1; // calculate the difference } else if (IC_Value2 < IC_Value1) { Difference = IC_Value2; } else { Error_Handler(); } Frequency = HAL_RCC_GetSysClockFreq()/(htim->Instance->ARR * (htim->Instance->PSC + 1)); // calculate frequency Is_First_Captured = 0; // reset the first captured } } }
C
#include <stdio.h> #include <string.h> #include <stdlib.h> #include "../utils/getline_debug.c" #include "../utils/strlist.c" typedef struct nlist { struct nlist *next; char *name; char *defn; } nlist; #define HASHSIZE 101 static nlist *hashtab[HASHSIZE]; nlist *install(char *, char *); unsigned hash(char *); int undef(char *); nlist *lookup(char *); int main(void) { install("foo", "bar"); install("lol", "bar"); undef("lol"); } int undef(char *name) { nlist *last = NULL; nlist *current = NULL; unsigned int hashed = hash(name); for (current = hashtab[hashed]; current != NULL; current = current->next) { if (strcmp(current->name, name) == 0) { nlist *next = current->next; free((void *)current->name); free((void *)current->defn); free((void *)current); if (last == NULL) hashtab[hashed] = next; else last->next = next; return 1; } last = current; } return 0; } unsigned hash(char *s) { unsigned hashval; for (hashval = 0; *s != '\0'; s++) hashval = *s + 31 * hashval; return hashval % HASHSIZE; } nlist *lookup(char *s) { nlist *np; for (np = hashtab[hash(s)]; np != NULL; np = np->next) if (strcmp(s, np->name) == 0) return np; return NULL; } nlist *install(char *name, char *defn) { nlist *np; unsigned hashval; if ((np = lookup(name)) == NULL) { np = (nlist *)malloc(sizeof(*np)); if (np == NULL || (np->name = strdup(name)) == NULL) return NULL; hashval = hash(name); np->next = hashtab[hashval]; hashtab[hashval] = np; } else free((void *)np->defn); if ((np->defn = strdup(defn)) == NULL) return NULL; return np; }
C
#define M_SIZE 0x8000 #define P 6 char f1(int i) { return i % 26 + 'A'; } char f2(int i) { return i%26 + 'a'; } char f0(int i) { return i*0; } void fill(char *arr, char (*func)(int)) { int i; for (i = 0; i < M_SIZE; i++) { arr[i] = func(i); } //verify(arr,func); return; } int handle; int verify(char *arr, char (*func)(int)) { int i; for (i = 0; i < M_SIZE; i++) { if (arr[i] != func(i)) { crt_printf(handle,"ERROR: Got (%c = %d) but was expecting (%c = %d) at index %d\n",arr[i],arr[i],func(i),func(i),i); return 0; } } return 1; }
C
/**Vincenzo Petrolo s256499*/ #include <ctype.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #define __NOMEFILE__ "corse.txt" #define __LOGFILE__ "log.txt" #define __N_COMANDI__ 7 #define __MAX_S__ 31 #define __MAX_DATI__ 1000 typedef enum{r_date,r_tratte,r_partenza,r_capolinea,r_ricerca,r_stampa,r_fine}comando; typedef struct { char codice_tratta[__MAX_S__]; char partenza[__MAX_S__]; char data_part[__MAX_S__]; char destinazione[__MAX_S__]; char orario_partenza[__MAX_S__]; char orario_arrivo[__MAX_S__]; int ritardo; }dati; typedef enum{VIDEO,FILE_TESTO} stampa; typedef enum{FALSE,TRUE} boolean; typedef struct { int giorno; int mese; int anno; }data; typedef struct { dati *ord_date[__MAX_DATI__]; boolean date_ordinate; dati *ord_codice[__MAX_DATI__]; boolean codice_ordinato; dati *ord_partenza[__MAX_DATI__]; boolean partenza_ordinato; dati *ord_arrivo[__MAX_DATI__]; boolean arrivo_ordinato; }set_vettori; int leggiFile(dati tabella[]); int leggiComando(stampa tipo_stampa); void esegui_comandi(dati tabella[],int lunghezza_tabella,set_vettori *vettori,int comando); void ordinamento(dati tabella[],set_vettori *vettori,int lunghezza,comando richiesta_campo_ordinamento); void stampa_log(stampa tipo,comando comando,set_vettori vettori,int lunghezza); void string2low(char stringa[__MAX_S__]); stampa leggi_tipo_stampa(); void ricerca_dicotomica(set_vettori vettori,int lunghezza,char chiave[__MAX_S__],int l,int r); void ricerca_lineare(set_vettori vettori,int lunghezza); int main() { int comando,lunghezza_effettiva; dati tabella[__MAX_DATI__]; set_vettori vettori; vettori.arrivo_ordinato=FALSE; vettori.partenza_ordinato=FALSE; vettori.codice_ordinato = FALSE; vettori.date_ordinate = FALSE; stampa tipo_stampa; lunghezza_effettiva=leggiFile(tabella); tipo_stampa = leggi_tipo_stampa(); while ((comando=leggiComando(tipo_stampa)) != r_fine) { esegui_comandi(tabella, lunghezza_effettiva,&vettori, comando); stampa_log(tipo_stampa,comando,vettori,lunghezza_effettiva); tipo_stampa = leggi_tipo_stampa(); } return 0; } stampa leggi_tipo_stampa() { stampa decisione=VIDEO; char stringa[__MAX_S__]; printf("\nVuoi stampare su file anzichè video?[S/n]"); scanf("%s",stringa); string2low(stringa); if (strstr(stringa,"s") != NULL) { decisione = FILE_TESTO; } return decisione; } int leggiComando(stampa tipo_stampa){ char comandi[][50] = {"data","codice","partenza", "arrivo","ricerca","Stampa attuale: ","fine"}; char comando_utente[20]; int result = -1; for (int i = 0; i <__N_COMANDI__ ; i++) { printf("\n>"); printf("%s",comandi[i]); if (i == __N_COMANDI__ -2) { if (tipo_stampa == FILE_TESTO) printf(" File di testo"); else printf(" Video"); } } printf("\nInserire il comando:\n> "); scanf("%s",comando_utente); string2low(comando_utente); for (int j = 0; j < __N_COMANDI__; j++) { if (strcmp(comandi[j],comando_utente) == 0) result = j; } return result; } int leggiFile(dati tabella[]) { int righe; FILE* fp; char data_part[__MAX_S__]; char ora_part[__MAX_S__]; char ora_arr[__MAX_S__]; fp = fopen(__NOMEFILE__,"r"); if (fp == NULL) { exit(EXIT_FAILURE); } fscanf(fp,"%d",&righe); for (int i = 0; i < righe; i++) { fscanf(fp,"%s%s%s%s%s%s%d",tabella[i].codice_tratta,tabella[i].partenza,tabella[i].destinazione,tabella[i].data_part, tabella[i].orario_partenza,tabella[i].orario_arrivo,&tabella[i].ritardo); string2low(tabella[i].codice_tratta); string2low(tabella[i].partenza); string2low(tabella[i].destinazione); // ho normalizzato la stringa tutto al minimo } return righe; } void esegui_comandi(dati tabella[],int lunghezza_tabella,set_vettori *vettori,int comando){ char stringa1[__MAX_S__],stringa2[__MAX_S__]; switch (comando) { case r_date: { /**0 Ordinamento per date**/ ordinamento(tabella,vettori,lunghezza_tabella,comando); break; } case r_tratte:{ /**1 Ordinamento per codice tratta*/ ordinamento(tabella,vettori,lunghezza_tabella,comando); break; } case r_partenza:{ /**2 Ordinamento per stazione di partenza*/ ordinamento(tabella,vettori,lunghezza_tabella,comando); break; } case r_capolinea:{ /**3 Ordinamento per stazione di arrivo*/ ordinamento(tabella,vettori,lunghezza_tabella,comando); break; } case r_ricerca: { if (vettori->partenza_ordinato == TRUE) { char chiave[__MAX_S__]; scanf("%s",chiave); ricerca_dicotomica(*vettori, lunghezza_tabella,chiave, 0, lunghezza_tabella); } else{ for (int k = 0; k < lunghezza_tabella; k++) { vettori->ord_partenza[k] = &tabella[k]; } //sposto i puntatori nel vettore da ordinare ricerca_lineare(*vettori,lunghezza_tabella);} break; } default: printf("\nComando errato!"); } } int compara_date(char data_l[__MAX_S__],char data_m[__MAX_S__],char orario1[__MAX_S__],char orario2[__MAX_S__]){ /**Ritorna 1 se il primo argomento è maggiore del secondo * Ritorna -1 se il primo argomento è minore del secondo * Ritorna 0 se entrambi gli argomenti sono uguali*/ /**Comparo anni mesi e giorni trasformandoli in intero*/ char giorno[3]; char mese[3]; char anno[5]; data date_da_comparare[3]; //0 data_l 1 data_m 2 data_r int risultato=0; /**Salvo i giorni*/ strncpy(giorno,data_l,2); date_da_comparare[0].giorno = atoi(giorno); strncpy(giorno,data_m,2); date_da_comparare[1].giorno = atoi(giorno); /**Salvo i mesi*/ strncpy(mese,data_l+3,2); //sposto il puntatore di 3 poichè ricevo i dati in forma gg/mm/aaaa allora mi muovo di 3 posizioni fino all'inizio del mese date_da_comparare[0].mese = atoi(mese); strncpy(mese,data_m+3,2); date_da_comparare[1].mese = atoi(mese); /**Salvo gli anni*/ strncpy(anno,data_l+6,4); //sposto il puntatore di 6 poichè ricevo i dati in forma gg/mm/aaaa allora mi muovo di 6 posizioni fino all'inizio del mese date_da_comparare[0].anno = atoi(anno); strncpy(anno,data_m+6,4); date_da_comparare[1].anno = atoi(anno); if (date_da_comparare[0].anno > date_da_comparare[1].anno) risultato= 1; else if (date_da_comparare[0].anno < date_da_comparare[1].anno) risultato= -1; else if (date_da_comparare[0].anno == date_da_comparare[1].anno) if (date_da_comparare[0].mese > date_da_comparare[1].mese) risultato= 1; else if (date_da_comparare[0].mese < date_da_comparare[1].mese) risultato= -1; else if (date_da_comparare[0].mese == date_da_comparare[1].mese) if (date_da_comparare[0].giorno > date_da_comparare[1].giorno) risultato= 1; else if (date_da_comparare[0].giorno < date_da_comparare[1].giorno) risultato= -1; else if (date_da_comparare[0].giorno == date_da_comparare[1].giorno) if (strcmp(orario1,orario2) > 0) risultato= 1; else if (strcmp(orario1,orario2) < 0) risultato= -1; else risultato= 0; return risultato; } void string2low(char stringa[__MAX_S__]){ for (int i = 0; i < strlen(stringa); i++) { stringa[i]=tolower(stringa[i]); } } void ordinamento(dati tabella[],set_vettori *vettori,int lunghezza,comando richiesta_campo_ordinamento) { /*Applico il Selection Sort*/ switch (richiesta_campo_ordinamento) { case r_date: { /**0 Ordinamento per date**/ if (vettori->date_ordinate != TRUE){ for (int k = 0; k < lunghezza; k++) { vettori->ord_date[k] = &tabella[k]; } //sposto i puntatori nel vettore da ordinare //siccome lo sto ordinando setto la variabile che si riferisce al fatto se ha ordinato o meno gia il vettore vettori->date_ordinate = TRUE; /*Selection sort ha inizio*/ int i, j, l = 0, r = lunghezza - 1; int posizione; int minimo; dati *tmp; for (i = l; i < r; i++) { //associo il minimo all'elemento i-esimo della struttura minimo = i; for (j = i + 1; j <= r; j++) if (compara_date((vettori->ord_date[j])->data_part,(vettori->ord_date[minimo])->data_part,(vettori->ord_date[j])->orario_partenza,(vettori->ord_date[minimo])->data_part) == -1) //se è minore del minimo {minimo = j;} //ordino il vettore di puntatori anzichè quello effettivo if (minimo != i) { tmp = vettori->ord_date[i]; vettori->ord_date[i] = vettori->ord_date[minimo]; vettori->ord_date[minimo] = tmp; } } } break; } case r_tratte: { /**1 Ordinamento per codice tratta*/ if (vettori->codice_ordinato != TRUE) { for (int k = 0; k < lunghezza ; k++) { vettori->ord_codice[k] = &tabella[k]; } //sposto i puntatori nel vettore da ordinare //siccome lo sto ordinando setto la variabile che si riferisce al fatto se ha ordinato o meno gia il vettore vettori->codice_ordinato = TRUE; /**Per questo tipo di dato preferisco usare l'insertion sort, sempre stabile,in loco*/ int i, j, l=0, r=lunghezza-1; dati *x; for(i = l+1; i <= r; i++) { x = vettori->ord_codice[i]; j = i - 1; while (j >= l && strcmp(x->codice_tratta,(vettori->ord_codice[j])->codice_tratta) < 0) { vettori->ord_codice[j+1] = vettori->ord_codice[j]; j--; } vettori->ord_codice[j+1] = x; } } break; } case r_partenza: { /**2 Ordinamento per stazione di partenza*/ if (vettori->partenza_ordinato != TRUE) { for (int k = 0; k < lunghezza; k++) { vettori->ord_partenza[k] = &tabella[k]; } //sposto i puntatori nel vettore da ordinare //siccome lo sto ordinando setto la variabile che si riferisce al fatto se ha ordinato o meno gia il vettore vettori->partenza_ordinato = TRUE; /**Per questo tipo di dato preferisco usare l'insertion sort, sempre stabile,in loco*/ int i, j, l = 0, r = lunghezza - 1; dati *x; for (i = l + 1; i <= r; i++) { x = vettori->ord_partenza[i]; j = i - 1; while (j >= l && strcmp(x->partenza, (vettori->ord_partenza[j])->partenza) < 0) { vettori->ord_partenza[j + 1] = vettori->ord_partenza[j]; j--; } vettori->ord_partenza[j + 1] = x; } } break; } case r_capolinea: { /**3 Ordinamento per stazione di arrivo*/ if (vettori->arrivo_ordinato != TRUE ) { for (int k = 0; k < lunghezza; k++) { vettori->ord_arrivo[k] = &tabella[k]; } //sposto i puntatori nel vettore da ordinare //siccome lo sto ordinando setto la variabile che si riferisce al fatto se ha ordinato o meno gia il vettore vettori->arrivo_ordinato = TRUE; /**Per questo tipo di dato preferisco usare l'insertion sort, sempre stabile,in loco*/ int i, j, l = 0, r = lunghezza - 1; dati *x; for (i = l + 1; i <= r; i++) { x = vettori->ord_arrivo[i]; j = i - 1; while (j >= l && strcmp(x->destinazione, (vettori->ord_arrivo[j])->destinazione) < 0) { vettori->ord_arrivo[j + 1] = vettori->ord_arrivo[j]; j--; } vettori->ord_arrivo[j + 1] = x; } } break; } default: break; } } void stampa_log(stampa tipo,comando comando,set_vettori vettori,int lunghezza) { FILE * fp; if (tipo == FILE_TESTO) { fp = fopen(__LOGFILE__, "a"); } else { fp = stdout; } switch (comando) { case r_date: { fprintf(fp,"ORDINAMENTO DATE"); for (int i = 0; i < lunghezza; i++) { fprintf(fp,"\nCodice Tratta: %s || Partenza: %s || Capolinea: %s || Data: %s || Ora partenza: %s ||" "Ora arrivo: %s ", (*(vettori.ord_date[i])).codice_tratta, (*(vettori.ord_date[i])).partenza, (*(vettori.ord_date[i])).destinazione, (*(vettori.ord_date[i])).data_part,(*(vettori.ord_date[i])).orario_partenza, (*(vettori.ord_date[i])).orario_arrivo); } break; } case r_tratte: { fprintf(fp,"\nORDINAMENTO CODICI"); for (int i = 0; i < lunghezza; i++) { fprintf(fp,"\nCodice Tratta: %s || Partenza: %s || Capolinea: %s || Data: %s || Ora partenza: %s ||" "Ora arrivo: %s ", (*(vettori.ord_codice[i])).codice_tratta, (*(vettori.ord_codice[i])).partenza, (*(vettori.ord_codice[i])).destinazione, (*(vettori.ord_codice[i])).data_part,(*(vettori.ord_codice[i])).orario_partenza, (*(vettori.ord_codice[i])).orario_arrivo); } break; } case r_partenza: { fprintf(fp,"\nORDINAMENTO PER STAZIONI DI PARTENZA"); for (int i = 0; i < lunghezza; i++) { fprintf(fp,"\nCodice Tratta: %s || Partenza: %s || Capolinea: %s || Data: %s || Ora partenza: %s ||" "Ora arrivo: %s ", (*(vettori.ord_partenza[i])).codice_tratta, (*(vettori.ord_partenza[i])).partenza, (*(vettori.ord_partenza[i])).destinazione, (*(vettori.ord_partenza[i])).data_part,(*(vettori.ord_partenza[i])).orario_partenza, (*(vettori.ord_partenza[i])).orario_arrivo); } break; } case r_capolinea: { fprintf(fp,"ORDINAMENTO PER STAZIONI DI ARRIVO"); for (int i = 0; i < lunghezza; i++) { fprintf(fp,"\nCodice Tratta: %s || Partenza: %s || Capolinea: %s || Data: %s || Ora partenza: %s ||" "Ora arrivo: %s ", (*(vettori.ord_arrivo[i])).codice_tratta, (*(vettori.ord_arrivo[i])).partenza, (*(vettori.ord_arrivo[i])).destinazione, (*(vettori.ord_arrivo[i])).data_part,(*(vettori.ord_arrivo[i])).orario_partenza, (*(vettori.ord_arrivo[i])).orario_arrivo); } break; } default: break; } if (fp != stdout) fclose(fp); } void ricerca_lineare(set_vettori vettori,int lunghezza) { char chiave[__MAX_S__]; scanf("%s",chiave); printf("\nRISULTATI RICERCA: "); for (int i = 0; i < lunghezza; i++) { if (strncmp(vettori.ord_partenza[i]->partenza,chiave,2) == 0) fprintf(stdout,"\nCodice Tratta: %s || Partenza: %s || Capolinea: %s || Data: %s || Ora partenza: %s ||" "Ora arrivo: %s ", (*(vettori.ord_partenza[i])).codice_tratta, (*(vettori.ord_partenza[i])).partenza, (*(vettori.ord_partenza[i])).destinazione, (*(vettori.ord_partenza[i])).data_part,(*(vettori.ord_partenza[i])).orario_partenza, (*(vettori.ord_partenza[i])).orario_arrivo); } } void ricerca_dicotomica(set_vettori vettori,int lunghezza,char chiave[__MAX_S__],int l,int r) { if (l>r) return; int m = (r+l)/2; int risultato = strncmp(chiave,vettori.ord_partenza[m]->partenza,strlen(chiave)); if ( risultato > 0) return ricerca_dicotomica(vettori,lunghezza,chiave,m+1,r); else if (risultato < 0) return ricerca_dicotomica(vettori,lunghezza,chiave,l,m-1); else if (risultato == 0) { printf("\nRISULTATI RICERCA: "); fprintf(stdout, "\nCodice Tratta: %s || Partenza: %s || Capolinea: %s || Data: %s || Ora partenza: %s ||" "Ora arrivo: %s ", (*(vettori.ord_partenza[m])).codice_tratta, (*(vettori.ord_partenza[m])).partenza, (*(vettori.ord_partenza[m])).destinazione, (*(vettori.ord_partenza[m])).data_part, (*(vettori.ord_partenza[m])).orario_partenza, (*(vettori.ord_partenza[m])).orario_arrivo); int tmp = m; while ( ++m<lunghezza && strncmp(chiave, vettori.ord_partenza[m]->partenza, strlen(chiave)) == 0 && m<lunghezza) { fprintf(stdout, "\nCodice Tratta: %s || Partenza: %s || Capolinea: %s || Data: %s || Ora partenza: %s ||" "Ora arrivo: %s ", (*(vettori.ord_partenza[m])).codice_tratta, (*(vettori.ord_partenza[m])).partenza, (*(vettori.ord_partenza[m])).destinazione, (*(vettori.ord_partenza[m])).data_part, (*(vettori.ord_partenza[m])).orario_partenza, (*(vettori.ord_partenza[m])).orario_arrivo); } m = tmp; while ( --m>=0 && strncmp(chiave, vettori.ord_partenza[m]->partenza, strlen(chiave)) == 0 ) { fprintf(stdout, "\nCodice Tratta: %s || Partenza: %s || Capolinea: %s || Data: %s || Ora partenza: %s ||" "Ora arrivo: %s ", (*(vettori.ord_partenza[m])).codice_tratta, (*(vettori.ord_partenza[m])).partenza, (*(vettori.ord_partenza[m])).destinazione, (*(vettori.ord_partenza[m])).data_part, (*(vettori.ord_partenza[m])).orario_partenza, (*(vettori.ord_partenza[m])).orario_arrivo); } return; } }
C
/* See LICENSE file for copyright and license details. */ #include <stdio.h> #include <stdlib.h> #include <xcb/xcb.h> #include <err.h> #include <string.h> #include "util.h" static xcb_connection_t *conn; static xcb_screen_t *scrn; static xcb_atom_t atom; static void usage(char *name) { fprintf(stderr, "usage: %s <group>\n", name); exit(1); } xcb_atom_t atom_get(char *grp) { xcb_intern_atom_cookie_t cookie; xcb_intern_atom_reply_t *reply; xcb_atom_t atom; cookie = xcb_intern_atom(conn, 1, strlen(grp), grp); reply = xcb_intern_atom_reply(conn, cookie, NULL); atom = reply->atom; free(reply); return atom; } void group_list(char *grp) { xcb_window_t *wc; xcb_get_property_cookie_t prop_c; xcb_get_property_reply_t *prop_r; int wn; wn = get_windows(conn, scrn->root, &wc); for (int i = 0; i < wn; i++) { prop_c = xcb_get_property(conn, 0, wc[i], atom, XCB_ATOM_STRING, 0L, 32L); if ((prop_r = xcb_get_property_reply(conn, prop_c, NULL))) { if (strcmp(grp, (char *) xcb_get_property_value(prop_r)) == 0) { printf("0x%08x\n", wc[i]); } free(prop_r); } } } int main(int argc, char **argv) { init_xcb(&conn); get_screen(conn, &scrn); if (argc != 2) { usage(argv[0]); } atom = atom_get("_WM_GROUP"); if (atom == XCB_ATOM_NONE) { return 0; } group_list(argv[1]); kill_xcb(&conn); return 0; }
C
/****************************************************************************** FILENAME: Cordic.c ***************************************************************************** Public domain module Adaption: Gerard Gauthier Author: J. Pitts Jarvis III (+), 3Com Corporation, October 1990 Target Device: Portable (+) very sadly, J. Pitts Jarvis III born in Fayetteville, Arkansas on November 3, 1946 died suddenly of a heart attack on October 10, 2003, in Palo Alto, California. * cordic.c computes CORDIC (COordinate, Rotation DIgital Computer) * constants and exercises the basic algorithms * Represents all numbers in fixed point notation, as a 32-bit long integer: * 1 bit sign, (31-n) bits for integral part, and n bits for fractional part * for example, n=29 lets us represent numbers in the interval [-4, 4[ in 32 bit * Two's complement arithmetic is operative here Usage: fast sine, cosine, arctg, sinh, cosh, ln, sqrt, etc * *** cordic algorithm identities *** * * for circular functions, starting with [x, y, z] and then * driving z to 0 gives: [P*(x*cos(z)-y*sin(z)), P*(y*cos(z)+x*sin(z)), 0]: Circular (C) * driving y to 0 gives: [P*sqrt(x^2+y^2), 0, z+atan(y/x)]: Reciprocal Circular (rC) * where K = 1/P = sqrt(1+1)* . . . *sqrt(1+(2^(-2*i))) * special cases which compute interesting functions * sin, cos C[K*r, 0, a] -> [r*cos(a), r*sin(a), 0] * atan rC[1, a, 0] -> [sqrt(1+a^2)/K, 0, atan(a)] * rC[x, y, 0] -> [sqrt(x^2+y^2)/K, 0, atan(y/x)] * * for hyperbolic functions, starting with [x, y, z] and then * driving z to 0 gives: [P*(x*cosh(z)+y*sinh(z)), P*(y*cosh(z)+x*sinh(z)), 0]: Hyperbolic (H) * driving y to 0 gives: [P*sqrt(x^2-y^2), 0, z+atanh(y/x)]: Reciprocal Hyperbolic (rH) * where K = 1/P = sqrt(1-(1/2)^2)* . . . *sqrt(1-(2^(-2*i))) * special cases which compute interesting functions * sinh, cosh H[K, 0, a] -> [cosh(a), sinh(a), 0] * exponential H[K, K, a] -> [e^a, e^a, 0] * atanh rH[1, a, 0] -> [sqrt(1-a^2)/K, 0, atanh(a)] * rH[x, y, 0] -> [sqrt(x^2-y^2)/K, 0, atanh(y/x)] * ln rH[a+1, a-1, 0] -> [2*sqrt(a)/K, 0, ln(a)/2] * sqrt rH[a+(K/2)^2, a-(K/2)^2, 0] -> [sqrt(a), 0, ln(a*(2/K)^2)/2] * sqrt, ln rH[a+(K/2)^2, a-(K/2)^2, -ln(K/2)] -> [sqrt(a), 0, ln(a)/2] * * for linear functions, starting with [x, y, z] and then * driving z to 0 gives: [x, y+x*z, 0]: Linear * driving y to 0 gives: [x, 0, z+y/x]: Reciprocal Linear Example: compute 2-D coordinates from rectangular (x, y) to polar (r, th) long x, y, r, th; x = 110; // init x, unscaled integer value (not yet a cordic value) y = -96; // init y, unscaled integer value (not yet a cordic value) // here multiplies by cordic_X0C will both counterbalance 1/K and scale x and y cordic_InvertCircular(x*cordic_X0C, y*cordic_X0C, 0); // sqrt(x*2+y^2)/K, 0, atan(y/x) r = cordic_X; // module, scaled cordic 32-bit decimal value th = cordic_Z; // angle, scaled cordic 32-bit decimal value And from this, calculate back from polar to rectangular cordic_Circular(cordic_X0C, 0, th); // cos(th), sin(th), 0 // now, calculate x and y as scaled cordic 32-bit decimal values // right shifts to ensure it's a 16x16 multiply // shifts biased to save sine/cosine significant fractional digits x = (r>>(cordic_fractionBits-3)) * (cordic_X>>3); y = (r>>(cordic_fractionBits-3)) * (cordic_Y>>3); // results of this round-trip (for cordic_fractionBits=16): // x = 109.99902, y = -96.00854 Change Log is at end of file *******************************************************************************/ //**************************************** // include files //**************************************** #include "Cordic.h" /******************************************************************************************* * local defines that remove the "cordic_" prefix to alleviate implementation in this module *******************************************************************************************/ #define X cordic_X #define Y cordic_Y #define Z cordic_Z #define X0C cordic_X0C #define X0H cordic_X0H #define X0R cordic_X0R #define OneOverE cordic_OneOverE #define E cordic_E #define HalfLnX0R cordic_HalfLnX0R #define fractionBits cordic_fractionBits #define longBits cordic_longBits #define One cordic_One #define HalfPi cordic_HalfPi /*******************************************************************************************/ /* misc local defines */ /* Delta is inefficient but pedagogical */ #define Delta(n, Z) (Z >= 0) ? (n) : -(n) #define abs(n) (n >= 0) ? (n) : -(n) /******************************************************************************************* * exported variables - BEWARE: their external names are prefixed with cordic_ *******************************************************************************************/ /* X, Y, Z result registers of cordic functions */ long X, Y, Z; /*************************************** * seeds for circular and hyperbolic ***************************************/ /* 'K' prescaling constant for circular functions */ /* cordic_Circular(X0C, 0, a) -> cos(a), sin(a), 0 */ long X0C; /* 'K' prescaling constant for hyperbolic functions */ /* cordic_Hyperbolic(X0H, 0, a) -> cosh(a), sinh(a), 0 */ long X0H; /* constant useful for reciprocal hyperbolic function: (X0H/2)^2 */ /* cordic_InvertHyperbolic(a+1, a-1, 0) -> 2*sqrt(a)/X0R, 0, ln(a)/2 */ long X0R; /* 'K' prescaling constant for reciprocal hyperbolic functions */ /* e: base of natural logarithms */ long E; /* 1/e */ long OneOverE; /* constant used in simultaneous sqrt and ln computations: -ln(X0H/2) */ /* cordic_InvertHyperbolic(x+X0R, x-X0R, cordic_HalfLnX0R) -> sqrt(a), 0, ln(a)/2 */ long HalfLnX0R; /* constant used in simultaneous sqrt, ln computation */ /***************************************** * Local variables *****************************************/ /* compute atan(x) and atanh(x) using infinite series * atan(x) = x - x^3/3 + x^5/5 - x^7/7 + . . . for x^2 < 1 * atanh(x) = x + x^3/3 + x^5/5 + x^7/7 + . . . for x^2 < 1 * To calculate these functions to 32 bits of precision, pick * terms[i] s.t. ((2^-i)^(terms[i]))/(terms[i]) < 2^-32 * For x <= 2^(-11), atan(x) = atanh(x) = x with 32 bits of accuracy */ static unsigned terms[11] = { 0, 27, 14, 9, 7, 5, 4, 4, 3, 3, 3 }; static long a[28], atan[fractionBits + 1], atanh[fractionBits + 1]; /***************************************************************************** FUNCTION cordic_Reciprocal Description: calculate reciprocal of n to k bits of precision a and r form integer and fractional parts of the dividend respectively Entrance Conditions: Exit Conditions: args: n: computed number k: number of bits returns: reciprocal *****************************************************************************/ long cordic_Reciprocal(unsigned n, unsigned k) { unsigned i, a = 1; long r = 0; for (i = 0; i <= k; ++i) { r += r; if (a >= n) { r += 1; a -= n; } a += a; } return a >= n ? r + 1 : r; /* round result */ } /***************************************************************************** FUNCTION cordic_ScaledReciprocal Description: calculate scaled reciprocal (1/n) of n to k bits of precision beware: internal routine, does not deal correctly with n<=0 Entrance Conditions: Exit Conditions: args: n: computed number k: number of bits returns: scaled reciprocal *****************************************************************************/ long cordic_ScaledReciprocal(long n, unsigned k) { long a, r = 0; unsigned i; a = 1L << k; for (i = 0; i <= k; ++i) { r += r; if (a >= n) { r += 1; a -= n; } a += a; } return a >= n ? r + 1 : r; /* round result */ } /***************************************************************************** FUNCTION cordic_Poly2 Description: calculates polynomial where the variable is an integral power of 2 coefficients are in the array a[] Entrance Conditions: Exit Conditions: args: log is the power of 2 of the variable n is the order of the polynomial returns: polynomial *****************************************************************************/ long cordic_Poly2(int log, unsigned n) { long r = 0; int i; for (i = n; i >= 0; --i) { r = (log<0 ? r> > -log : r << log) + a[i]; } return r; } /***************************************************************************** FUNCTION cordic_Circular Description: First Cordic generic function For more see Cordic identities at the beginning of this file Entrance Conditions: Cordic Module Initialized Exit Conditions: X, Y, Z updated as result of computation (Z -> 0) args: x, y, z: entry variables returns: nothing *****************************************************************************/ void cordic_Circular(long x, long y, long z) { int i; X = x; Y = y; Z = z; for (i = 0; i <= fractionBits; ++i) { x = X >> i; y = Y >> i; z = atan[i]; X -= Delta(y, Z); Y += Delta(x, Z); Z -= Delta(z, Z); } } /***************************************************************************** FUNCTION cordic_InvertCircular Description: Reciprocal of first Cordic generic function For more see Cordic identities at the beginning of this file Entrance Conditions: Cordic Module Initialized Exit Conditions: X, Y, Z updated as result of computation (Y -> 0) args: x, y, z: entry variables returns: nothing *****************************************************************************/ void cordic_InvertCircular(long x, long y, long z) { int i; X = x; Y = y; Z = z; for (i = 0; i <= fractionBits; ++i) { x = X >> i; y = Y >> i; z = atan[i]; X -= Delta(y, -Y); Z -= Delta(z, -Y); Y += Delta(x, -Y); } } /***************************************************************************** FUNCTION cordic_Hyperbolic Description: Second Cordic generic function For more see Cordic identities at the beginning of this file Entrance Conditions: Cordic Module Initialized Exit Conditions: X, Y, Z updated as result of computation (Z -> 0) args: x, y, z: entry variables returns: nothing *****************************************************************************/ void cordic_Hyperbolic(long x, long y, long z) { int i; X = x; Y = y; Z = z; for (i = 1; i <= fractionBits; ++i) { x = X >> i; y = Y >> i; z = atanh[i]; X += Delta(y, Z); Y += Delta(x, Z); Z -= Delta(z, Z); if ((i == 4) || (i == 13)) { x = X >> i; y = Y >> i; z = atanh[i]; X += Delta(y, Z); Y += Delta(x, Z); Z -= Delta(z, Z); } } } /***************************************************************************** FUNCTION cordic_InvertHyperbolic Description: Reciprocal of second Cordic generic function For more see Cordic identities at the beginning of this file Entrance Conditions: Cordic Module Initialized Exit Conditions: X, Y, Z updated as result of computation (Y -> 0) args: x, y, z: entry variables returns: nothing *****************************************************************************/ void cordic_InvertHyperbolic(long x, long y, long z) { int i; X = x; Y = y; Z = z; for (i = 1; i <= fractionBits; ++i) { x = X >> i; y = Y >> i; z = atanh[i]; X += Delta(y, -Y); Z -= Delta(z, -Y); Y += Delta(x, -Y); if ((i == 4) || (i == 13)) { x = X >> i; y = Y >> i; z = atanh[i]; X += Delta(y, -Y); Z -= Delta(z, -Y); Y += Delta(x, -Y); } } } /***************************************************************************** FUNCTION cordic_Linear Description: Third Cordic generic function For more see Cordic identities at the beginning of this file Entrance Conditions: Cordic Module Initialized Exit Conditions: X, Y, Z updated as result of computation (Z -> 0) args: x, y, z: entry variables returns: nothing *****************************************************************************/ void cordic_Linear(long x, long y, long z) { int i; X = x; Y = y; Z = z; z = One; for (i = 1; i <= fractionBits; ++i) { x >>= 1; z >>= 1; Y += Delta(x, Z); Z -= Delta(z, Z); } } /***************************************************************************** FUNCTION cordic_InvertLinear Description: Reciprocal of third Cordic generic function For more see Cordic identities at the beginning of this file Entrance Conditions: Cordic Module Initialized Exit Conditions: X, Y, Z updated as result of computation (Y -> 0) args: x, y, z: entry variables returns: nothing *****************************************************************************/ void cordic_InvertLinear(long x, long y, long z) { int i; X = x; Y = y; Z = z; z = One; for (i = 1; i <= fractionBits; ++i) { Z -= Delta(z >>= 1, -Y); Y += Delta(x >>= 1, -Y); } } /***************************************************************************** FUNCTION cordic_Init Description: Cordic Initialization. To be called once prior to Coridc function (Circular, Hyperbolic...) Entrance Conditions: Exit Conditions: Circular, Hyperbolic, and Linear Cordic function can be safely called args: returns: nothing *****************************************************************************/ void cordic_Init(void) { int i; for (i = 0; i <= 13; ++i) { a[2 * i] = 0; a[2 * i + 1] = cordic_Reciprocal(2 * i + 1, fractionBits); } for (i = 0; i <= 10; ++i) { atanh[i] = cordic_Poly2(-i, terms[i]); } atan[0] = HalfPi / 2; /* atan(2^0)= pi/4 */ for (i = 1; i <= 7; ++i) { a[4 * i - 1] = -a[4 * i - 1]; } for (i = 1; i <= 10; ++i) { atan[i] = cordic_Poly2(-i, terms[i]); } for (i = 11; i <= fractionBits; ++i) { atan[i] = atanh[i] = 1L << (fractionBits - i); } cordic_Circular(One, 0L, 0L); X0C = cordic_ScaledReciprocal(X, fractionBits); cordic_Hyperbolic(One, 0L, 0L); X0H = cordic_ScaledReciprocal(X, fractionBits); X0R = X0H >> 1; cordic_Linear(X0R, 0L, X0R); X0R = Y; cordic_Hyperbolic(X0H, X0H, -One); OneOverE = X; cordic_Hyperbolic(X0H, X0H, One); E = X; cordic_InvertHyperbolic(One + X0R, One - X0R, 0L); HalfLnX0R = Z; } #ifdef CORDIC_TEST_FCT /***************************************************************************** FUNCTION cordic_WriteFraction Description: test function: print n as NET.FRACT to fp integer and fractional parts separated by a dot Entrance Conditions: Exit Conditions: args: n value fp file where to print n to returns: nothing *****************************************************************************/ void cordic_fWriteFraction(long n, FILE* fp) { unsigned short i, low, digit; unsigned long k; putchar(n < 0 ? '-' : ' '); n = abs(n); fprintf(fp, "%li", n >> fractionBits); fputc('.', fp); k = n << (longBits - fractionBits); /* align octal point at left */ low = (unsigned short)k; k >>= 4; /* shift to make room for a decimal digit */ for (i = 1; i <= 8; ++i) { digit = (k *= 10L) >> (longBits - 4); low = (low & 0xf) * 10; k += ((unsigned long)(low >> 4)) - ((unsigned long)digit << (longBits - 4)); fputc(digit + '0', fp); } } /***************************************************************************** FUNCTION cordic_WriteRegisters Description: test function: prints main registers X, Y, Z of this Cordic implementation to fp Entrance Conditions: Exit Conditions: args: fp file where to print n to returns: nothing *****************************************************************************/ void cordic_fWriteRegisters(FILE* fp) { fprintf(fp, " X: "); cordic_WriteVar(X); fprintf(fp, " Y: "); cordic_WriteVar(Y); fprintf(fp, " Z: "); cordic_WriteVar(Z); } /***************************************************************************** FUNCTION cordic_WriteVar Description: test function: sends data about a variable to stdout (decimal value, hexa raw value, etc) Entrance Conditions: Exit Conditions: args: n value to print returns: nothing *****************************************************************************/ void cordic_fWriteVar(long n, FILE* fp) { cordic_fWriteFraction(n, fp); fprintf(fp, " %li 0x%08lx\n", n, n); } /***************************************************************************** FUNCTION cordic_Test Description: Generic test functions together with their expected results in some cases Entrance Conditions: Exit Conditions: args: returns: nothing *****************************************************************************/ void cordic_Test(void) { int i; long r; cordic_Init(); printf("\natanh(2^-n)\n"); for (i = 1; i <= 10; ++i) { printf("%2d ", i); cordic_WriteVar(atanh[i]); } r = 0; for (i = 1; i <= fractionBits; ++i) { r += atanh[i]; } r += atanh[4] + atanh[13]; printf("radius of convergence"); cordic_WriteFraction(r); printf("\n\natan(2^-n)\n"); for (i = 0; i <= 10; ++i) { printf("%2d ", i); cordic_WriteVar(atan[i]); } r = 0; for (i = 0; i <= fractionBits; ++i) { r += atan[i]; } printf("radius of convergence"); cordic_WriteFraction(r); /* all the results reported in the printfs are calculated with an HP-41C */ printf("\n\n--------------------circular functions--------------------\n"); printf("Grinding on [1, 0, 0]\n"); cordic_Circular(One, 0L, 0L); cordic_WriteRegisters; printf("\n K: "); cordic_WriteVar(cordic_ScaledReciprocal(X, fractionBits)); printf("\nGrinding on [K, 0, 0]\n"); cordic_Circular(X0C, 0L, 0L); cordic_WriteRegisters; printf("\nGrinding on [K, 0, pi/6] -> [0.86602540, 0.50000000, 0]\n"); cordic_Circular(X0C, 0L, HalfPi / 3L); cordic_WriteRegisters; printf("\nGrinding on [K, 0, pi/4] -> [0.70710678, 0.70710678, 0]\n"); cordic_Circular(X0C, 0L, HalfPi / 2L); cordic_WriteRegisters; printf("\nGrinding on [K, 0, pi/3] -> [0.50000000, 0.86602540, 0]\n"); cordic_Circular(X0C, 0L, 2L * (HalfPi / 3L)); cordic_WriteRegisters; printf("\n------Inverse functions------\n"); printf("Grinding on [1, 0, 0]\n"); cordic_InvertCircular(One, 0L, 0L); cordic_WriteRegisters; printf("\nGrinding on [1, 1/2, 0] -> [1.84113394, 0, 0.46364761]\n"); cordic_InvertCircular(One, One / 2L, 0L); cordic_WriteRegisters; printf("\nGrinding on [2, 1, 0] -> [3.68226788, 0, 0.46364761]\n"); cordic_InvertCircular(One * 2L, One, 0L); cordic_WriteRegisters; printf("\nGrinding on [1, 5/8, 0] -> [1.94193815, 0, 0.55859932]\n"); cordic_InvertCircular(One, 5L * (One / 8L), 0L); cordic_WriteRegisters; printf("\nGrinding on [1, 1, 0] -> [2.32887069, 0, 0.78539816]\n"); cordic_InvertCircular(One, One, 0L); cordic_WriteRegisters; printf("\n--------------------hyperbolic functions--------------------\n"); printf("Grinding on [1, 0, 0]\n"); cordic_Hyperbolic(One, 0L, 0L); cordic_WriteRegisters; printf("\n K: "); cordic_WriteVar(cordic_ScaledReciprocal(X, fractionBits)); printf(" R: "); cordic_Linear(X0R, 0L, X0R); cordic_WriteVar(Y); printf("\nGrinding on [K, 0, 0]\n"); cordic_Hyperbolic(X0H, 0L, 0L); cordic_WriteRegisters; printf("\nGrinding on [K, 0, 1] -> [1.54308064, 1.17520119, 0]\n"); cordic_Hyperbolic(X0H, 0L, One); cordic_WriteRegisters; printf("\nGrinding on [K, K, -1] -> [0.36787944, 0.36787944, 0]\n"); cordic_Hyperbolic(X0H, X0H, -One); cordic_WriteRegisters; printf("\nGrinding on [K, K, 1] -> [2.71828183, 2.71828183, 0]\n"); cordic_Hyperbolic(X0H, X0H, One); cordic_WriteRegisters; printf("\n------Inverse functions------\n"); printf("Grinding on [1, 0, 0]\n"); cordic_InvertHyperbolic(One, 0L, 0L); cordic_WriteRegisters; printf("\nGrinding on [1/e + 1, 1/e - 1, 0] -> [1.00460806, 0, -0.50000000]\n"); cordic_InvertHyperbolic(OneOverE + One, OneOverE - One, 0L); cordic_WriteRegisters; printf("\nGrinding on [e + 1, e - 1, 0] -> [2.73080784, 0, 0.50000000]\n"); cordic_InvertHyperbolic(E + One, E - One, 0L); cordic_WriteRegisters; printf("\nGrinding on (1/2)*ln(3) -> [0.71720703, 0, 0.54930614]\n"); cordic_InvertHyperbolic(One, One / 2L, 0L); cordic_WriteRegisters; printf("\nGrinding on [3/2, -1/2, 0] -> [1.17119417, 0, -0.34657359]\n"); cordic_InvertHyperbolic(One + (One / 2L), -(One / 2L), 0L); cordic_WriteRegisters; printf("\nGrinding on sqrt(1/2) -> [0.70710678, 0, 0.15802389]\n"); cordic_InvertHyperbolic(One / 2L + X0R, One / 2L - X0R, 0L); cordic_WriteRegisters; printf("\nGrinding on sqrt(1) -> [1.00000000, 0, 0.50449748]\n"); cordic_InvertHyperbolic(One + X0R, One - X0R, 0L); cordic_WriteRegisters; printf("\nGrinding on sqrt(2) -> [1.41421356, 0, 0.85117107]\n"); cordic_InvertHyperbolic(One * 2L + X0R, One * 2L - X0R, 0L); cordic_WriteRegisters; printf("\nGrinding on sqrt(1/2), ln(1/2)/2 -> [0.70710678, 0, -0.34657359]\n"); cordic_InvertHyperbolic(One / 2L + X0R, One / 2L - X0R, -HalfLnX0R); cordic_WriteRegisters; printf("\nGrinding on sqrt(3)/2, ln(3/4)/2 -> [0.86602540, 0, -0.14384104]\n"); cordic_InvertHyperbolic((3L * One / 4L) + X0R, (3L * One / 4L) - X0R, -HalfLnX0R); cordic_WriteRegisters; printf("\nGrinding on sqrt(2), ln(2)/2 -> [1.41421356, 0, 0.34657359]\n"); cordic_InvertHyperbolic(One * 2L + X0R, One * 2L - X0R, -HalfLnX0R); cordic_WriteRegisters; } #endif /* CORDIC_TEST_FCT */ /****************************************************************************** End of file *******************************************************************************/
C
#include<stdio.h> int main() { int i; int num = 6; int product = 1; for(i=1 ; i<=num ; i++) product += i; printf("Factorial of %d is %d\n", num, product); }
C
/** * Student.C * CS 3505 * Authors: Landon Gilbert-Bland and Alex Clemmer * Date: Spring 2011 * * Defines member functions of Student.h */ #include <stdlib.h> #include <iostream> #include "Student.h" #include "Helpers.h" using namespace std; string Student::toString() { string result = name + "," + level + ": "; for(unsigned i=0;i<times.size();i++) { result += IntToString(times[i]) + ", "; } return result; } void Student::parseLine(string line) { size_t start = 0; size_t end = line.find(" ", start); // name is line[0] to the index of the first space name = line.substr(start, end); // Check for the optional prefered students while(true) { start = end + 1; end = line.find(" ", start); string tmp = line.substr(start, end - start); if(tmp == "excellent" || tmp == "good" || tmp == "average" || tmp == "poor" || tmp == "not_saying") { level = tmp; break; } else { preferedTeammates.push_back(tmp); } } // Move forward to start parsing out the times someone can meet start = end + 1; end = line.find(" ", start); string current_number; // parse out each meeting time, put in vector times while(end != string::npos) { current_number = line.substr(start, end-start); int time = StringToInt(current_number); addTime(time); start = end + 1; end = line.find(" ", start); } // Get the last number current_number = line.substr(start, end-start); int time = StringToInt(current_number); addTime(time); } void Student::addTime(int time) { // Insert the item so it is in sorted location. times.push_back(time); for(unsigned i=times.size() - 1; i>0; i--) { if(times.at(i) < times.at(i - 1)) { int tmp = times.at(i); times.at(i) = times.at(i-1); times.at(i-1) = tmp; } else { break; } } } void Student::isAvaliable(bool b) { avaliable = b; } bool Student::isAvaliable() { return avaliable; } std::vector<int> Student::getHours() { return times; } Student::Student(const Student& p) { name = p.name; level = p.level; times = p.times; preferedTeammates = p.preferedTeammates; avaliable = p.avaliable; }
C
#ifndef LZ4_H_ #define LZ4_H_ //****************************************************************************** // //! \addtogroup lz4_api //! @{ // //****************************************************************************** //***************************************************************************** // // If building with a C++ compiler, make all of the definitions in this header // have a C binding. // //***************************************************************************** #ifdef __cplusplus extern "C" { #endif #include <stdint.h> #include <stdbool.h> //****************************************************************************** // //! \brief Maximum size of a compressed file, one percent plus 27 bytes larger //! than uncompressed data. // //****************************************************************************** #define LZ4_COMPRESS_MAX_SIZE(n) ((size_t)((n * 101) / 100) + 27) //****************************************************************************** // //! \brief LZ4 status return types. // //****************************************************************************** typedef enum { //! Successful operation. LZ4_SUCCESS, //! Data was partially decompressed due to insufficient space. LZ4_PARTIAL_SUCCESS, //! Content size is not present in LZ4 frame header. LZ4_NO_CONTENT_SIZE, //! Error in frame header. LZ4_FRAMING_ERROR, //! Incorrect block checksum. LZ4_BLOCK_CHECKSUM_ERROR, //! Incorrect content checksum. LZ4_CONTENT_CHECKSUM_ERROR } LZ4_status; //****************************************************************************** // //! \brief Compression parameters for a LZ4 frame. // //****************************************************************************** typedef struct LZ4_compressParams { //! Pointer to the source data buffer to compress. const void *src; //! Pointer to the destination data buffer to store compressed data. void *dst; //! Length of source data buffer. uint32_t length; //! Pointer to memory block with pow2(hashLog2Size) bytes allocated. void *hashTable; //! Power of two used to determine the hash table size. uint16_t hashLog2Size; //! Add checksum to each compressed block. Decreases compression //! performance. Valid values are: //! - false //! - true bool addBlockChecksum; //! Add checksum of original source data buffer. Decreases compression //! performance. Valid values are: //! - false //! - true bool addContentChecksum; //! Add total content size to LZ4 frame. Increases total frame size by 8 //! bytes. Valid values are: //! - false //! - true bool addContentSize; } LZ4_compressParams; //****************************************************************************** // //! \brief Compression parameters for a single LZ4 block. // //****************************************************************************** typedef struct LZ4_compressBlockParams { //! Pointer to the source data buffer to compress. const void *src; //! Pointer to the destination data buffer to store compressed data. void *dst; //! Length of source data buffer. uint32_t length; //! Pointer to memory block with pow2(hashLog2Size) bytes allocated. void *hashTable; //! Power of two used to determine the hash table size. uint16_t hashLog2Size; //! Add checksum to each compressed block. Decreases compression //! performance. Valid values are: //! - false //! - true bool addBlockChecksum; } LZ4_compressBlockParams; //****************************************************************************** // //! \brief Decompression parameters for a LZ4 frame. // //****************************************************************************** typedef struct LZ4_decompressParams { //! Pointer to the source data buffer to decompress. const void *src; //! Pointer to the destination data buffer to store compressed data. void *dst; //! Length of the destination data buffer. uint32_t dstLength; //! Enable verification of block checksum if present. Valid values are: //! - false //! - true bool verifyBlockChecksum; //! Enable verification of content checksum if present. Valid values are: //! - false //! - true bool verifyContentChecksum; } LZ4_decompressParams; //****************************************************************************** // //! \brief Decompression parameters for a single LZ4 block. // //****************************************************************************** typedef struct LZ4_decompressBlockParams { //! Pointer to the source data buffer to decompress. const void *src; //! Pointer to the destination data buffer to store compressed data. void *dst; //! Length of the destination data buffer. uint32_t dstLength; //! Enable verification of block checksum if present. Valid values are: //! - false //! - true bool verifyBlockChecksum; } LZ4_decompressBlockParams; //****************************************************************************** // //! \brief Compress a block of data to a LZ4 frame. //! //! Compress a block of data using LZ4 compression and add LZ4 framing. This //! API will compress data to a valid LZ4 file and contains several parameters //! to enable or disable features of the LZ4 framing specification such as //! content and block checksum using the xxHash algorithm or block size. See //! the LZ4_compressParams structure documentation for more details about the //! available parameters. //! //! A block compressed with this method can be saved as a binary .lz4 file and //! extracted using the LZ4 command line utility. //! //! \param params Pointer to the LZ4 compression parameter structure. //! \param status Pointer to a LZ4 status that will contain the result status. //! \return The total compressed frame size. // //****************************************************************************** extern uint32_t LZ4_compress(const LZ4_compressParams *params, LZ4_status *status); //****************************************************************************** // //! \brief Compress a block of data to a single LZ4 block without framing. //! //! Compress a block of data using only LZ4 compression and block format. This //! API can be used to compress data and create a custom framing scheme using an //! alternative checksum method. The LZ4 block format has a single parameter //! for enabling block checksum computation with the xxHash algorithm. The //! block checksum is computed on the compressed data block. See the //! LZ4_compressBlockParams structure documentation for more details about the //! available parameters. //! //! \param params Pointer to the LZ4 compression block parameter structure. //! \param status Pointer to a LZ4 status that will contain the result status. //! \return The total compressed block size. // //****************************************************************************** extern uint32_t LZ4_compressBlock(const LZ4_compressBlockParams *params, LZ4_status *status); //****************************************************************************** // //! \brief Decompress a LZ4 frame to a block of data. //! //! Decompress a LZ4 frame to an uncompressed data block. This API contains //! parameters to enable checking of content and block checksum. When enabled //! the xxHash algorithm is used to verify the checksum. While not required it //! is the application programmers responsibility to determine if validating //! the checksum is necessary. See the LZ4_decompressParams structure //! documentation for more details about the available parameters. //! //! A .lz4 file compressed with the LZ4 command line utility can be //! decompressed using this API. //! //! \param params Pointer to the LZ4 decompression parameter structure. //! \param status Pointer to a LZ4 status that will contain the result status. //! \return The total decompressed data block size. // //****************************************************************************** extern uint32_t LZ4_decompress(const LZ4_decompressParams *params, LZ4_status *status); //****************************************************************************** // //! \brief Decompress a single LZ4 block without framing to a block of data. //! //! Decompress a LZ4 block to an uncompressed data block. This API contains //! a single parameter to enable checking of the block checksum. When enabled //! the xxHash algorithm is used to verify the checksum. While not required it //! is the application programmers responsibility to determine if validating //! the checksum is necessary. See the LZ4_decompressBlockParams structure //! documentation for more details about the available parameters. //! //! \param params Pointer to the LZ4 decompression block parameter structure. //! \param status Pointer to a LZ4 status that will contain the result status. //! \return The total decompressed data block size. // //****************************************************************************** extern uint32_t LZ4_decompressBlock(const LZ4_decompressBlockParams *params, LZ4_status *status); //****************************************************************************** // //! \brief Get the content size of a compressed LZ4 frame. //! //! Get the size of the original uncompressed data block if it is present. The //! content size is an optional parameter when compressing but it is recommended //! to enable it and verify the uncompressed data block fits in the allocated //! buffer before decompressing. //! //! \param src Pointer to the LZ4 frame. //! \param status Pointer to a LZ4 status that will contain the result status. //! \return The total decompressed content size. The content size is stored as //! 64-bit but will be truncated to 32-bit. // //****************************************************************************** extern uint32_t LZ4_getContentSize(const uint8_t *src, LZ4_status *status); //***************************************************************************** // // Mark the end of the C bindings section for C++ compilers. // //***************************************************************************** #ifdef __cplusplus } #endif //****************************************************************************** // // Close the Doxygen group. //! @} // //****************************************************************************** #endif /* LZ4_H_ */
C
#include <stdio.h> int get_sum_of_array(int rows,int array[rows]){ int i,sum=0; for (i=0;i < rows;i++){ sum += array[i]; } return sum; } int main (void){ int numbers[10] = {0,1,2,3,4,5,6,7,8,9}; printf("The sum of the array is %i.",get_sum_of_array((sizeof(numbers)/sizeof(numbers[0])),numbers)); }
C
#include <png.h> #include <stdio.h> #include <stdlib.h> #include <math.h> #include <float.h> #define QUIET char *color_type_string(int color_type) { switch (color_type) { case PNG_COLOR_TYPE_GRAY: return "PNG_COLOR_TYPE_GRAY"; case PNG_COLOR_TYPE_GRAY_ALPHA: return "PNG_COLOR_TYPE_GRAY_ALPHA"; case PNG_COLOR_TYPE_PALETTE: return "PNG_COLOR_TYPE_PALETTE"; case PNG_COLOR_TYPE_RGB: return "PNG_COLOR_TYPE_RGB"; case PNG_COLOR_TYPE_RGB_ALPHA: return "PNG_COLOR_TYPE_RGB_ALPHA"; default: return "UNKNOWN_COLOR_TYPE"; } } double find_nearest(int value, int from_column, int from_row, png_bytepp rows, int width, int height) { // We do a brute-force search of the entire bitmask for now, checking every // pixel. No need to optimize when we can run this overnight. double nearest = 1E6; int row; for (row = 0; row < height; ++row) { int column; for (column = 0; column < width; ++column) { if (((rows[row][column/8] >> (7-column%8)) & 0x01) == value) { double distance = sqrt((column - from_column)*(column - from_column) + (row - from_row)*(row - from_row)); if (distance < nearest) { nearest = distance; // printf("Found new nearest distance %f\n", nearest); } } } } #ifndef QUIET printf("Found nearest distance %f\n", nearest); #endif return nearest; } int main(int argc, char **argv) { if (argc != 6) { printf("Need 5 arguments\n"); return 1; } const char *input_file = argv[1]; const char *output_file = argv[2]; int output_width = atoi(argv[3]); int output_height = atoi(argv[4]); double spread = atof(argv[5]); FILE *fp = fopen(input_file, "rb"); if (!fp) { return 1; } png_structp png_ptr = png_create_read_struct( PNG_LIBPNG_VER_STRING, (png_voidp)NULL, NULL, NULL); if (!png_ptr) { png_destroy_read_struct(&png_ptr, (png_infopp)NULL, (png_infopp)NULL); return 1; } png_infop info_ptr = png_create_info_struct(png_ptr); if (!info_ptr) { png_destroy_read_struct(&png_ptr, (png_infopp)NULL, (png_infopp)NULL); return 1; } png_infop end_ptr = png_create_info_struct(png_ptr); if (!end_ptr) { png_destroy_read_struct(&png_ptr, (png_infopp)NULL, (png_infopp)NULL); return 1; } png_init_io(png_ptr, fp); png_read_png(png_ptr, info_ptr, PNG_TRANSFORM_IDENTITY, NULL); png_bytepp row_pointers = png_get_rows(png_ptr, info_ptr); int input_width, input_height, bit_depth, color_type; input_width = png_get_image_width(png_ptr, info_ptr); input_height = png_get_image_height(png_ptr, info_ptr); bit_depth = png_get_bit_depth(png_ptr, info_ptr); color_type = png_get_color_type(png_ptr, info_ptr); // Max distance used in conjunction with the spread double max_distance = sqrt(input_width*input_width + input_height*input_height); printf("input_width: %d\ninput_height: %d\nbit_depth: %d\ncolor_type: %s\n", input_width, input_height, bit_depth, color_type_string(color_type)); if (bit_depth != 1 || color_type != PNG_COLOR_TYPE_GRAY) { printf("Only bitmaps supported."); return 1; } // Print out the bits as ascii, for debugging /* { int y; for (y = 0; y < input_height; ++y) { int x; for (x = 0; x < input_width; ++x) { if ((row_pointers[y][x/8] >> (7-x%8)) & 0x01) { printf(" "); } else { printf("#"); } } printf("\n"); } } */ // Allocate memory for the SDF we are generating unsigned int *sdf = malloc(4 * output_width * output_height); if (!sdf) { printf("Could not allocate memory for SDF!\n"); return 1; } // Loop through the signed distance field values we want generated int sdf_row; for (sdf_row = 0; sdf_row < output_height; ++sdf_row) { int sdf_column; for (sdf_column = 0; sdf_column < output_width; ++sdf_column) { // Distribute the sampled pixels evenly; not very sophisticated int input_row = sdf_row * (input_height/output_height); int input_column = sdf_column * (input_width/output_width); int sampledValue = (row_pointers[input_row][input_column/8] >> (7-input_column%8)) & 0x01; // Look for the nearest pixel of opposite value double nearest_distance = find_nearest(!sampledValue, input_column, input_row, row_pointers, input_width, input_height); // Map the nearest distance between 0 and 255 and put it in the alpha // channel (and all the other channels) double normalized = nearest_distance / (spread*max_distance); normalized = (normalized > 1.0) ? 1.0 : normalized; unsigned char result; if (sampledValue) { // Interpolate between 128 and 255 for values inside the figure result = 255 - ((1.0 - normalized) * 127); } else { // Interpolate between 0 and 127 for values outside the figure result = (1.0 - normalized) * 127; } unsigned int result_int = 0; int i; for (i = 0; i < 4; ++i) { result_int |= (unsigned int)result << 8*i; } sdf[sdf_column%output_width + sdf_row*output_width] = result_int; #ifndef QUIET printf("normalized: %f pixel [%i][%i] value: %02x\n", normalized, sdf_column, sdf_row, result); #endif } } // Free the png read resources fclose(fp); png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1); png_destroy_read_struct(&png_ptr, (png_infopp)NULL, (png_infopp)NULL); // Write our results into the output png FILE *out_fp = fopen(output_file, "wb"); if (!out_fp) { return 1; } png_structp write_ptr = png_create_write_struct (PNG_LIBPNG_VER_STRING, (png_voidp)NULL, NULL, NULL); if (!write_ptr) { return 1; } info_ptr = png_create_info_struct(write_ptr); if (!info_ptr) { png_destroy_write_struct(&write_ptr, (png_infopp)NULL); return 1; } png_init_io(write_ptr, out_fp); png_set_IHDR(write_ptr, info_ptr, output_width, output_height, 8, PNG_COLOR_TYPE_RGB_ALPHA, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT); png_write_info(write_ptr, info_ptr); // TODO: Write the generated sdf data to the output png one row at a time int row; for (row = 0; row < output_height; ++row) { png_write_row(write_ptr, (png_const_bytep)(&(sdf[row*output_width]))); } png_write_end(write_ptr, NULL); fclose(out_fp); png_free_data(write_ptr, info_ptr, PNG_FREE_ALL, -1); png_destroy_write_struct(&write_ptr, (png_infopp)NULL); free(sdf); }
C
#include <wchar.h> wchar_t * wcspbrk(s, set) const wchar_t *s; const wchar_t *set; { const wchar_t *p; const wchar_t *q; p = s; while (*p) { q = set; while (*q) { if (*p == *q) { /* LINTED interface specification */ return (wchar_t *)p; } q++; } p++; } return NULL; }
C
/* program to print all the even numbers except those which are multiple of either 3 or 5 */ #include<stdio.h> int main() { for(int i=1;i<100;i++) { if((i%2==0)&&(i%3!=0)&&(i%5!=0)) printf("%d\n",i);}}
C
/* Name: Paul Talaga Date: March 6, 2018 Desc: Shapes assignment */ #include <stdio.h> int main(){ srand(time(0)); printf("1. Filled-in rectangle\n"); printf("2. Rectangle frame\n"); printf("3. Rectangle frame with alternating interior\n"); printf("4. Square with alternating interior\n"); printf("5. Rectangle frame with random inside\n"); printf("6. Right triangle\n"); printf("7. Pyramid\n"); printf("8. Circle\n"); printf("9. EC - Death Star\n"); printf("Enter your choice.\n"); int choice = 0; scanf("%d", &choice); while(choice < 1 || choice > 9){ printf("Enter a value from 1 to 8!\n"); scanf("%d", &choice); } // Now do it! if(choice == 1){ // Filled rectangle int width = 0; int height = 0; printf("Height?\n"); scanf("%d", &height); while(height < 0){ printf("Height should be non-negative! Re-enter!\n"); scanf("%d", &height); } printf("Width?\n"); scanf("%d", &width); while(width < 0){ printf("Width should be non-negative! Re-enter!\n"); scanf("%d", &width); } int x = 0; int y = 0; for(y = 0; y < height; y++){ for(x = 0; x < width; x++){ printf("*"); } printf("\n"); } }else if(choice == 2){ // rectangle frame int width = 0; int height = 0; printf("Height?\n"); scanf("%d", &height); while(height < 0){ printf("Height should be non-negative! Re-enter!\n"); scanf("%d", &height); } printf("Width?\n"); scanf("%d", &width); while(width < 0){ printf("Width should be non-negative! Re-enter!\n"); scanf("%d", &width); } int x = 0; int y = 0; for(y = 0; y < height; y++){ for(x = 0; x < width; x++){ if(y == 0 || y == height - 1 || x == 0 || x == width - 1){ // border printf("*"); }else{ // inside printf(" "); } } printf("\n"); } }else if(choice == 3){ // rectangle frame with period and space inside int width = 0; int height = 0; printf("Height?\n"); scanf("%d", &height); while(height < 0){ printf("Height should be non-negative! Re-enter!\n"); scanf("%d", &height); } printf("Width?\n"); scanf("%d", &width); while(width < 0){ printf("Width should be non-negative! Re-enter!\n"); scanf("%d", &width); } int x = 0; int y = 0; for(y = 0; y < height; y++){ for(x = 0; x < width; x++){ if(y == 0 || y == height - 1 || x == 0 || x == width - 1){ // border printf("*"); }else if(x % 2 == 0){ printf("."); }else{ printf(" "); } } printf("\n"); } }else if(choice == 4){ // square frame with period and comma int height = 0; printf("Height?\n"); scanf("%d", &height); while(height < 0){ printf("Height should be non-negative! Re-enter!\n"); scanf("%d", &height); } int x = 0; int y = 0; for(y = 0; y < height; y++){ for(x = 0; x < height; x++){ if(y == 0 || y == height - 1 || x == 0 || x == height - 1){ // border printf("*"); }else if(x % 2 == 0){ printf("."); }else{ printf(","); } } printf("\n"); } }else if(choice == 5){ // rectangle frame with random period int width = 0; int height = 0; printf("Height?\n"); scanf("%d", &height); while(height < 0){ printf("Height should be non-negative! Re-enter!\n"); scanf("%d", &height); } printf("Width?\n"); scanf("%d", &width); while(width < 0){ printf("Width should be non-negative! Re-enter!\n"); scanf("%d", &width); } int x = 0; int y = 0; for(y = 0; y < height; y++){ for(x = 0; x < width; x++){ if(y == 0 || y == height - 1 || x == 0 || x == width - 1){ // border printf("*"); }else if(rand() % 4 == 0){ printf("."); }else{ printf(" "); } } printf("\n"); } }else if(choice == 6){ // triangle int width = 0; printf("Width?\n"); scanf("%d", &width); while(width < 0){ printf("Width should be non-negative! Re-enter!\n"); scanf("%d", &width); } int x = 0; int y = 0; for(y = 1; y <= width; y++){ for(x = 1; x <= width; x++){ if(x <= y){ // inside the triangle! printf("*"); }else{ printf(" "); } } printf("\n"); } }else if(choice == 7){ // pyramid int width = 0; printf("Width?\n"); scanf("%d", &width); while(width < 0){ printf("Width should be non-negative! Re-enter!\n"); scanf("%d", &width); } int x = 0; int y = 0; for(y = 1; y <= width/2; y++){ for(x = 1; x <= width; x++){ if(x > width/2 - y && x < width/2 + y){ // inside the triangle! printf("*"); }else{ printf(" "); } } printf("\n"); } }else if(choice == 8){ // circle int radius = 0; printf("Radius?\n"); scanf("%d", &radius); while(radius < 0){ printf("Radius should be non-negative! Re-enter!\n"); scanf("%d", &radius); } int x = 0; int y = 0; for(y = 0; y <= radius * 2; y++){ for(x = 0; x <= radius * 2; x++){ if((x - radius)*(x-radius) + (y - radius)*(y - radius) <= radius * radius){ // inside the circle printf("* "); }else{ printf(" "); } } printf("\n"); } }else if(choice == 9){ // death star int radius = 0; printf("Radius?\n"); scanf("%d", &radius); while(radius < 0){ printf("Radius should be non-negative! Re-enter!\n"); scanf("%d", &radius); } int x = 0; int y = 0; for(y = 0; y <= radius * 2; y++){ for(x = 0; x <= radius * 2; x++){ if((x - radius)*(x-radius) + (y - radius)*(y - radius) <= radius * radius){ // inside the circle if((x - radius *1.4)*(x-radius*1.4) + (y - radius*0.6)*(y - radius*0.6) <= radius/4 * radius/4){ // inside the triangle! printf(". "); }else{ printf("* "); } }else{ printf(" "); } } printf("\n"); } } }
C
/* ** matrix.c for doom in /home/petren_l/rendu/tek1/semestre_01/doom/src ** ** Made by Ludovic Petrenko ** Login <[email protected]> ** ** Started on Mon Jan 11 17:43:32 2016 Ludovic Petrenko ** Last update Wed Jan 27 08:20:27 2016 Luka Boulagnon */ #include "tekdoom.h" void mtx_clear(double *m) { m[0] = 1; m[1] = 0; m[2] = 0; m[3] = 0; m[4] = 0; m[5] = 1; m[6] = 0; m[7] = 0; m[8] = 0; m[9] = 0; m[10] = 1; m[11] = 0; m[12] = 0; m[13] = 0; m[14] = 0; m[15] = 1; } void mtx_cpy(double *src, double *dest) { dest[0] = src[0]; dest[1] = src[1]; dest[2] = src[2]; dest[3] = src[3]; dest[4] = src[4]; dest[5] = src[5]; dest[6] = src[6]; dest[7] = src[7]; dest[8] = src[8]; dest[9] = src[9]; dest[10] = src[10]; dest[11] = src[11]; dest[12] = src[12]; dest[13] = src[13]; dest[14] = src[14]; dest[15] = src[15]; } void mtx_mult_mult(double *m, double *n) { double tmp[16]; mtx_cpy(m, tmp); m[0] = tmp[0] * n[0] + tmp[1] * n[4] + tmp[2] * n[8] + tmp[3] * n[12]; m[1] = tmp[0] * n[1] + tmp[1] * n[5] + tmp[2] * n[9] + tmp[3] * n[13]; m[2] = tmp[0] * n[2] + tmp[1] * n[6] + tmp[2] * n[10] + tmp[3] * n[14]; m[3] = tmp[0] * n[3] + tmp[1] * n[7] + tmp[2] * n[11] + tmp[3] * n[15]; m[4] = tmp[4] * n[0] + tmp[5] * n[4] + tmp[6] * n[8] + tmp[7] * n[12]; m[5] = tmp[4] * n[1] + tmp[5] * n[5] + tmp[6] * n[9] + tmp[7] * n[13]; m[6] = tmp[4] * n[2] + tmp[5] * n[6] + tmp[6] * n[10] + tmp[7] * n[14]; m[7] = tmp[4] * n[3] + tmp[5] * n[7] + tmp[6] * n[11] + tmp[7] * n[15]; m[8] = tmp[8] * n[0] + tmp[9] * n[4] + tmp[10] * n[8] + tmp[11] * n[12]; m[9] = tmp[8] * n[1] + tmp[9] * n[5] + tmp[10] * n[9] + tmp[11] * n[13]; m[10] = tmp[8] * n[2] + tmp[9] * n[6] + tmp[10] * n[10] + tmp[11] * n[14]; m[11] = tmp[8] * n[3] + tmp[9] * n[7] + tmp[10] * n[11] + tmp[11] * n[15]; m[12] = tmp[12] * n[0] + tmp[13] * n[4] + tmp[14] * n[8] + tmp[15] * n[12]; m[13] = tmp[12] * n[1] + tmp[13] * n[5] + tmp[14] * n[9] + tmp[15] * n[13]; m[14] = tmp[12] * n[2] + tmp[13] * n[6] + tmp[14] * n[10] + tmp[15] * n[14]; m[15] = tmp[12] * n[3] + tmp[13] * n[7] + tmp[14] * n[11] + tmp[15] * n[15]; } void mtx_mult_mtx_dest(double *m, double *n, double *res) { res[0] = m[0] * n[0] + m[1] * n[4] + m[2] * n[8] + m[3] * n[12]; res[1] = m[0] * n[1] + m[1] * n[5] + m[2] * n[9] + m[3] * n[13]; res[2] = m[0] * n[2] + m[1] * n[6] + m[2] * n[10] + m[3] * n[14]; res[3] = m[0] * n[3] + m[1] * n[7] + m[2] * n[11] + m[3] * n[15]; res[4] = m[4] * n[0] + m[5] * n[4] + m[6] * n[8] + m[7] * n[12]; res[5] = m[4] * n[1] + m[5] * n[5] + m[6] * n[9] + m[7] * n[13]; res[6] = m[4] * n[2] + m[5] * n[6] + m[6] * n[10] + m[7] * n[14]; res[7] = m[4] * n[3] + m[5] * n[7] + m[6] * n[11] + m[7] * n[15]; res[8] = m[8] * n[0] + m[9] * n[4] + m[10] * n[8] + m[11] * n[12]; res[9] = m[8] * n[1] + m[9] * n[5] + m[10] * n[9] + m[11] * n[13]; res[10] = m[8] * n[2] + m[9] * n[6] + m[10] * n[10] + m[11] * n[14]; res[11] = m[8] * n[3] + m[9] * n[7] + m[10] * n[11] + m[11] * n[15]; res[12] = m[12] * n[0] + m[13] * n[4] + m[14] * n[8] + m[15] * n[12]; res[13] = m[12] * n[1] + m[13] * n[5] + m[14] * n[9] + m[15] * n[13]; res[14] = m[12] * n[2] + m[13] * n[6] + m[14] * n[10] + m[15] * n[14]; res[15] = m[12] * n[3] + m[13] * n[7] + m[14] * n[11] + m[15] * n[15]; }
C
#pragma warning(disable:4996) #include <stdio.h> #include <string.h> void read_file(char *n, struct Sales x[], int *s); void print_biggest_sale(struct Sales k[], int numrecords); int compare(struct Sales k[], char *buffer, int numrecords, int *s); void get_file_name(char *n); void save_records(struct Sales k[], int numrecords); void read_files(); typedef struct Sales { char name[20]; int sold; int money; }sales; int main() { int s = 0; char n[20]; sales m[20]; get_file_name(n); read_file(n, m, &s); print_biggest_sale(m, s); read_files(s); getch(); return 0; } void get_file_name(char *n) { printf("Input the name of the file: "); scanf("%s", n); } void read_file(char *n,struct Sales x[],int *s) { int flag = 0; FILE *file; int sold = 0;int money = 0;int count = 0; int i = 0;char k = 0;char name[20];char temp[20]; memset(temp, 0, sizeof(temp)); memset(name, 0, sizeof(name)); int numrecords = 0; file = fopen(n, "r"); if (file == NULL) { perror("Error"); exit(0); } while (!feof(file)) { k = fgetc(file); if (k == EOF) { break; } while (k != '\n') { if (count == 1) { if (flag ==0) { strcpy(temp, name); i = 0; memset(name, 0, sizeof(name)); flag++; } } if (count == 2) { if (flag == 1) { sscanf(name, "%d", &sold); i = 0; memset(name, 0, sizeof(name)); flag++; } } if (k == ' ') { count++; } else { name[i] = k; i++; } k = fgetc(file); } flag = 0; sscanf(name, "%d", &money); i = 0; count = 0; memset(name, 0, sizeof(name)); if (compare(x, temp, numrecords,s)) { x[*s].money += money; x[*s].sold += sold; } else { strcpy(x[numrecords].name, temp); x[numrecords].money = money; x[numrecords].sold = sold; numrecords++; } } *s = numrecords; save_records(x, numrecords); } int compare(struct Sales k[], char *buffer, int numrecords,int *s) { int i = 0; for (i = 0; i < numrecords; i++) { if (strcmp(buffer, k[i].name) == 0) { *s = i; return 1; } } return 0; } void print_biggest_sale(struct Sales k[], int numrecords) { int money = 0; int i = 0; int biggest = 0; for (i = 0; i < numrecords; i++) { if (k[i].money > money) { money = k[i].money; biggest = i; } } printf("Out of all the person who made money was %s", k[biggest].name); printf("\n%s made %d", k[biggest].name, k[biggest].money); } void save_records(struct Sales k[], int numrecords) { int i = 0; FILE*file; file = fopen("sales.txt", "wb"); if (file == NULL) { perror("Error"); exit(0); } for (i = 0; i < numrecords; i++) { fwrite(&k[i], sizeof(struct Sales), 1, file); } fclose(file); } void read_files() { sales temp; sales s[20]; int i = 0; FILE*file; file = fopen("sales.txt", "rb"); if (file == NULL) { perror("Error"); exit(0); } while (!feof(file)) { fread(&s[i], sizeof(struct Sales), 1, file); i++; } fclose(file); printf("\n%s", s[2].name); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_util.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: mcossu <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/11/11 19:40:26 by mcossu #+# #+# */ /* Updated: 2020/11/11 19:40:36 by mcossu ### ########.fr */ /* */ /* ************************************************************************** */ #include "ft_util.h" int is_numeric(char c) { return (c >= '0' && c <= '9'); } int ft_atoi(char *str) { int result; result = 0; while (*str == '0') str++; while (is_numeric(*str)) { result = (result * 10) + (*str - '0'); str++; } if (*str) return (0); return (result); } int ft_ctoi(char c, t_validator *valid) { if (c == valid->empty) return (1); if (c == valid->obs) return (0); return (-2); } int is_valid(char c, t_validator *valid) { if (c == valid->empty || c == valid->obs) return (1); return (0); } char ft_itoc(int nbr, t_validator *valid) { if (nbr == 0) return (valid->obs); if (nbr == -1) return (valid->full); return (valid->empty); }
C
#define _CRT_SECURE_NO_WARNINGS 1 #include<stdio.h> int fib(int m) { int f3 = 0; if( 1 == m || 2 == m) return 1; else { int f1 = 1; int f2 = 1; int i = 0; for(i = 3; i<=m; i++) { f3 = f2 + f1; f1 = f2; f2 = f3; } } return f3; }
C
/* Program acts as a system GPIB controller using USB. This is binary version. Command syntax: IB<CR> Powers on. Returns: <ACK> IBC<cmd><CR> or IBc<cmd><CR> Sends <cmd> byte as bus command. C: Releases ATN, c: does not release ATN. Returns: <ACK>, 1, 2, 8 IB<DLE><STX><data bytes><DLE><ETX> Sends data. EOI is set with the last byte if Write Mode is 0-3. <DLE> in data bytes should be replaced with <DLE><DLE>. <DLE><ACK> can be sent in data sequence (but not before first byte). The controller will answer with ACK. Returns: <ACK>, 1, 2, 8 IB?<CR> Receives data. Format: <DLE><STX><data bytes><DLE><ETX> <DLE> in data bytes is replaced with <DLE><DLE>. Operation can be interrupted by sending <ESC>. In this case transfer will be normally ended with <DLE><ETX>. Returns: <ACK>, 3, 9 IBB<CR> Receives 1 byte. (Useful for seriall polling). IBZ<CR> Performs interface clear. Returns: <ACK> IBO<CR> Switches the controller to off state. Sets timeouts and Write Mode to deafult state. Returns: / New commands in V2.3: IBe<Write Mode><CR> Sets Write Mode (decimal value). Default: 0. 0-3 - EOI will be asserted with the last byte send. 4-7 - EOI will not be asserted with the last byte send. Returns: <ACK> or <NAK> if the number is invalid. IBt<TimeOut><CR> Sets Handshake timeout (decimal value) in increments of 32.768 ms. Handshake timeout is disabled when Total Timeout is specified. Valid range is 2-255 (32-8323 ms). Use 0 to disable. Default: 30 (1 sec) Returns: <ACK> IBT<TimeOutTot><CR> Sets total timeout for write and read (decimal value) in increments of 32.768 ms. Transfer will not be interrupted during handshake, i.e. no bytes will be lost. Total timeout is disabled for read until specified. Valid range is 2-65535 (32-2,147 s). Use 0 to disable. Default: 0 (disabled) Returns: <ACK> IBm<ren><CR> Valid values of ren: 0, 1. Default: 1 1 asserts REN, 0 leaves REN unasserted. New commands in V2.4: IBf<TimeOutFirst><CR> Sets timeout for transfer of first byte for write and read (decimal value) in increments of 32.768 ms. Valid range is 2-65535 (32-2,147 s). Use 0 to disable. Default: 30 (1 sec) Returns: <ACK> IBS<CR> Returns state of GPIB control lines as a byte (without ACK). Bits order: 7 6 5 4 3 2 1 0 SRQ ATN EOI DAV NRFD NDAC IFC REN Note that lines are active zero. IBQx<CR> Enable (x=1) or disable (x=0) SRQ interrupt. If the interrupt is enable, the controller will send ENQ each time SRQ is asserted. ENQ will also be sent, if SRQ is asserted when the interrupt enable command is received. ENQ can only be sent while the controller is idle (not during data transfer). Returns: <ACK> Note: At least one timeout should always be enabled. Debug commands; used to directly acces lines on the bus. All data send and received are in binary format. Debug mode should be first enabled, otherwise commands are not recognized. IBDE\AA<CR> Enables debug mode. Returns: <ACK> IBDTx<CR> Sets talk/listen to listen (x=0) or talk (x=1). Returns: <ACK> IBDCx<CR> Puts x on control bus. Bits order: 7 6 5 4 3 2 1 0 SRQ ATN EOI DAV NRFD NDAC IFC REN Returns: <ACK> IBDMx<CR> Puts inverted x on a data (D7-D0) bus. Returns: <ACK> IBD?x<CR> Reads control (x=C), data (M) or both buses (x=?). Return: one or two bytes only (without ACK). Returns: Interface will return 1 byte after each command. <ACK> Normal execution <NAK> Command syntax error 0x01 Not Ready Timeout occured before NRFD become false. 0x02 Not Accepted Timeout occured before byte was accepted. 0x03 Not DAV Released Timeout occured before DAV was released. 0x08 No Listeners Timeout occured before NRFD or NDAC become true. 0x09 No Data Timeout occured before reception (DAV edge) of a byte. Note: All timeouts applies to byte-byte basis. Hardware: ATmega8515 8 MHz, FT245, SN75160/161, Rev V1.0 & Rev V1.1 V2.4.1 Bostjan Glazar, LPVO, FE, November 2006 Code: 1607 W, Const.: 53 W /******** Updates in V2.4.1 version Nov. 2006: - T1 delay updated to standard. For 8 MHz only for commands. /******** Updates in V2.4.0b version Sep. 2005: - Each timeout can now be disabled. - IBf, IBQ and IBS commands added. - Handshake timeout not used any more for write while waiting for listener. - Reading of one byte (IBB) corrected to return null in case of timeout. /******** Updates in V2.3.0b (Beta) version Mar. 2005: - Interruption of data received corrected. - Corrected bug with releasing REN on timeout. - Added total timeout. - Added option for Write Mode (disabling EOI). - Added ACK during write. - Compacted code in SendBinData function. - Debug commands are now standard repertory. - Operation with variable flags corrected. /******** Updates in V2.2.1b (Beta) version Oct. 2004: - Powering ON will now assert REN line. Because of problems with some devices. Code: 1086 W, Const.: 50 W /******** Updates in V2.0.1a version Dec. 2003: - Previous version released. /******** Updates in V0.8.1b (Beta) version Aug. 2003: - Added receiving of 1 byte (for seriall pulling). - Added escape option on receive. /******** Updates in V0.8a (Alpha) version: - Binary mode introduced. Any byte can be sent or received. ASCII mode is no longer provided. - Commands are send as codes and not as mnemonics. - All responses are 1 byte long what simplifies driver. /******** Updates in V0.7.2 Alpha version: - USB suspend added (will power off) - IBIDN, IBIFC, IBL, IBUNL, IBGET, IBSDC, IBDCL commands added - REN line is no longer used - On Data read, OK response is added. CR preceeds ERROR on no data to prevent missinterpreting ERROR response as data. Normally LF or CR from device will be sent before OK string. /******** Updates in V0.7.1 Alpha version: - Receiving capability added. - SetTalk and SetListen routins does not controll DC any more. (It is always 0.) - SendCmd wait for NRFD or NDAC to go low after ATN=0 instead of waiting for a while. They can also set NoListener. - Repaired a bug in receiving a command. - SendDataCR renamed to SendData. Another routine with parameter (number of bytes) can be added with the same name. - Command and error branching changed. /******** FTDI Info: Product description: GPIB Controller Consumption: 320 mA */ #include <mega8515.h> #include <stdlib.h> #include <ctype.h> #include <delay.h> #include <sleep.h> #include <string.h> // ASCII characters #define NUL 0 #define SOH 1 #define STX 2 #define ETX 3 #define EOT 4 #define ENQ 5 #define ACK 6 #define BEL 7 #define DLE 16 #define NAK 21 #define ETB 23 #define CAN 24 #define ESC 27 // Port connection #define PORTUSB PORTB #define DDRUSB DDRB #define PINUSB PINB #define PORTIB PORTA #define PINIB PINA #define PORTIBctrl PORTC #define PINIBctrl PINC #define DDRIB DDRA #define DDRIBctrl DDRC // PORTD lines (used to control hardware) #define TE PORTD.7 // Talk Enable, O #define DC PORTD.6 // Direction control, O #define PWR PORTD.5 // Power, inverted O #define TXE PIND.4 // Transmitt FIFO empty, inverted I #define RXF PIND.3 // Receive FIFO empty, inverted I #define PWREN PIND.2 // Power enable from USB, inverted I #define WR PORTD.1 // Write to USB, O #define RD PORTD.0 // Read to USB, inverted O // GPIB controll lines #define SRQout PORTC.7 // Service Request #define SRQin PINC.7 #define ATNout PORTC.6 // Attention #define ATNin PINC.6 #define EOIout PORTC.5 // End Or Identity #define EOIin PINC.5 #define DAVout PORTC.4 // Data Valid #define DAVin PINC.4 #define NRFDout PORTC.3 // Not Ready For Data #define NRFDin PINC.3 #define NDACout PORTC.2 // Not Data Accepted #define NDACin PINC.2 #define IFCout PORTC.1 // Interface Clear #define IFCin PINC.1 #define RENout PORTC.0 // Remote Enable #define RENin PINC.0 // Error and sleep bits; variable brk #define NotAccBrk 0x01 // Not Accepted Break; Listener(s) didn't release NDAC. #define NotRdyBrk 0x02 // Not Ready Break; Listener(s) were not ready in time. (NRFD pulled low) #define NoLstn 0x03 // No Listener; NRFD and NDAC were sensed high #define NoData 0x04 // No Data received: Timer expired while waiting for data #define NotDAVrel 0x05 // DAV line not released: Timer expired while waiting for DAV line to be released during data reception #define DataFrmtErr 0x06 // DLE not followed by DLE or ETX #define TimOutBrk 0x40 // Timout Break; Timer expired #define SleepBrk 0x80 // Sleep Break; USB went into suspend mode // Variable flags #define PCByteRdy 0x01 // Byte in PCDat is valid #define XmtBlkBrk 0x02 // Transmitting data; Used to wait for DLE ETX on error #define RenState 0x04 // REN state; new in V2.3 #define UseFirst 0x08 // Use TMaxFirst instead of TMax for timeout #define DDRtalk 0x73 // 01110011 #define DDRlstn 0x4f // 01001111 #define DDRcomm 0x43 // 01000011 #define DDR_EOI DDRIBctrl.5 // SRQst bits - SRQ status variable - used for SRQ interrupt #define SRQstate 0x01 // Current state of SRQ line, 1 means active #define SRQen 0x02 // SRQ interrupt enable flag #define TMax_def 30 // Number of timer interrupts for timeout between bytes, 30x32.768ms= 1 s #define TMaxTot_def 0 // Number of timer interrupts for total timeout, Nx32.768ms // New code V2.3, Total timeout disabled by default #define TMaxFirst_def 30 // Number of timer interrupts for timeout before the first byte, 30x32.768ms= 1 s // New V2.4 #define InstrMax 10 // Maximum length of command (incl. CR) #define Receive 1 const unsigned char StrIDN0[]="USB GPIB Controller\r\n"; const unsigned char StrIDN1[]="B.G., LSD, FE, Slovenia\r\n"; const unsigned char StrIDN2[]="HW V1.0, August 2003, FW V2.4.1, November 2006\r\n"; const unsigned char StrDataSend[]={DLE, STX}; unsigned char timer=0, brk=0, flags, PCDat; unsigned int timer_tot=0; // timer is incremented on every TOV0 (ca. 4 ms) // brk (break) - status variable for interrupts // Current timeouts; unit: number if timer interrupt unsigned char TMax; // Byte timeout unsigned int TMaxTot; // Total timeout unsigned int TMaxFirst; // First byte timeout //Routine increments timer and sets brk if reaches TMax or TMaxFirst, depending on UseFirst flag. //The flag is reset when timer is detected zero (first byte transfered). //timer_tot is similarly incremented and compared to TMaxTot interrupt [TIM0_OVF] void timer0_ovf(void){ // if(++timer==TMax) brk|=TimOutBrk; // if(++timer_tot==TMaxTot) brkT|=TimOutBrk; // New code V2.3; Total timeout if(!timer) flags&=~UseFirst; if((~flags&UseFirst) && TMax) if(++timer==TMax) brk|=TimOutBrk; // Modified code V2.4 if((flags&UseFirst) && TMaxFirst) if(++timer==TMaxFirst) brk|=TimOutBrk; // Modified code V2.4 if(TMaxTot) if(++timer_tot==TMaxTot) brk|=TimOutBrk; } //Routine sets brk when USB goes to suspend state. interrupt [EXT_INT0] void ext_int0(void){ brk|=SleepBrk; // brkT|=SleepBrk; // New code V2.3; Total timeout } //Routine is called on first received byte after power-down. interrupt [EXT_INT1] void ext_int1(void){ TIMSK=0x02; // Enable timer interrupts GICR=0x40; // Disable ext. int. TCNT0=0; timer=0; } //Routine sets DDRs and 75160/161 to talk mode. void SetTalk(void){ DDRIBctrl=DDRcomm; TE=1; DDRIBctrl=DDRtalk; DDRIB=0xff; } //Routine sets DDRs and 75160/161 to listen mode. void SetListen(void){ DDRIB=0; DDRIBctrl=DDRcomm; TE=0; DDRIBctrl=DDRlstn; } /* Routine send command to GPIB It can be interrupted with variable brk. If brk is set it is ORed with bit according to state (NRFD or DAV wait). Talk mode should be set prior to call. ATN is not relesed at normal operation. If brk is set, routine releases ATN. */ unsigned char SendCmd(unsigned char cmd){ ATNout=0; PORTIB=~cmd; while(NDACin&&NRFDin) if(brk) {brk|=NoLstn; goto Ret;} timer=0; while(!NRFDin) if(brk) {brk|=NotRdyBrk; goto Ret;} DAVout=0; while(!NDACin) if(brk) {brk|=NotAccBrk; goto Ret;} DAVout=1; return brk; Ret: ATNout=1; return brk; } /* This routine send a byte to PC through USB. It returns if brk is set. */ unsigned char SendPCChr(char byte){ DDRUSB=0xff; PORTUSB=byte; while(TXE) {timer=0; if(brk) goto Brk;} timer=0; WR=1; WR=0; Brk: DDRUSB=0; return brk; } /* Routine send string terminated with null to the PC If brk is set during transfer, the later is interrupted and brk returned. */ unsigned char SendPCStr(char flash str[]){ unsigned char i; DDRUSB=0xff; for(i=0;str[i];i++){ PORTUSB=str[i]; while(TXE) {timer=0; if(brk) goto Brk;} timer=0; WR=1; WR=0; } Brk: DDRUSB=0; return brk; } /* This routine sends binary data from PC (USB) to GPIB bus. Data should begin without header. DLE should be followed by another DLE. Transfer is ended with DLE STX. eoi different from 0 signals to send EOI with the last byte. Returns global variable brk which can also be set to NoLstn, DataFrmtErr, NotRdyBrk, NotAccBrk. Transfer will also be interrupted by setting brk (timeout). Routine resets timer variable for each byte after first. Initially timer is set to 1 and UseFirst flag is set to enable usage of TimeOutFirst. GPIB and USB direction should be set before calling. */ unsigned char SendBinData(int eoi){ unsigned char PCDat; timer_tot=0; // BrkT deleted in V2.4 timer=1; flags|=UseFirst; TMax++; // Use timeout for first byte initially while(NDACin&&NRFDin) if(brk) {brk|=NoLstn; return brk;} // Wait for listener SendBinData1: while(RXF) {timer=1; if(brk) return brk;} // Wait for data from PC RD=0; timer=1; // Changed to 1 in V2.4 PCDat=PINUSB; RD=1; if(PCDat==DLE){ while(RXF) {timer=1; if(brk) return brk;} // Changed to 1 in V2.4 RD=0; timer=1; // Changed to 1 in V2.4 PCDat=PINUSB; RD=1; if(PCDat==DLE) PORTIB=~PCDat; else if(PCDat==ETX){ flags&=~XmtBlkBrk; return brk; } else if(PCDat==ACK){ if(brk=SendPCChr(ACK)) return brk; goto SendBinData1; } else{ brk|=DataFrmtErr; return brk; } } else PORTIB=~PCDat; while(1){ while(RXF) {timer=!!(flags&UseFirst); if(brk) return brk;} RD=0; #asm("nop"); // PCDat=PINUSB; RD=1; if(PCDat!=DLE){ while(!NRFDin) if(brk) {brk|=NotRdyBrk; return brk;} DAVout=0; while(!NDACin) if(brk) {brk|=NotAccBrk; return brk;} DAVout=1; PORTIB=~PCDat; } else{ while(RXF) {timer=!!(flags&UseFirst); if(brk) return brk;} RD=0; #asm("nop"); // timer=0; // moved to end of loop in order to use different timeout after first byte PCDat=PINUSB; RD=1; // Modified and new code V2.3: compacted, ACK if(PCDat==ETX) if(eoi) EOIout=0; while(!NRFDin) if(brk) {brk|=NotRdyBrk; return brk;} DAVout=0; while(!NDACin) if(brk) {brk|=NotAccBrk; return brk;} DAVout=1; if(PCDat==DLE) PORTIB=~PCDat; else if(PCDat==ETX){ flags&=~XmtBlkBrk; break; } else if(PCDat==ACK){ if(brk=SendPCChr(ACK)) return brk; goto SendBinData1; } else{ // ERROR brk|=DataFrmtErr; flags&=~XmtBlkBrk; break; } } // else DLE timer=0; // Moved V2.4 } // while(1) EOIout=1; return brk; } // SendBinData /* This routine receives data from GPIB bus. Data is send is BSC protocol as above, however the routine send DLE STX at the beginning. As SendBinData this routine also uses two timeouts between bytes. Routine normally return 0. On error it returns the value of brk variable. Data transfer can be interrupted by sending ESC from the PC. Reception of this character is only monitored when the routine has nothing to do. */ unsigned char RcvBinData(){ unsigned char eoi; NDACout=0; ATNout=1; DDRUSB=0xff; // USB port is output PORTUSB=DLE; // Send DLE, STX while(TXE) {timer=0; if(brk) goto Brk1;} // wait for not full FIFO WR=1; WR=0; PORTUSB=STX; while(TXE) {timer=0; if(brk) goto Brk1;} // wait for not full FIFO WR=1; WR=0; timer=1; flags|=UseFirst; TMax++; // Use timeout for first byte initially timer_tot=0; // BrkT deleted in V2.4 do{ while(TXE) { timer=!!(flags&UseFirst); if(brk) goto Brk; // wait for not full FIFO if(brk) goto Brk; // wait for not full FIFO if(!RXF) if(~flags&PCByteRdy){ // Check for escape code DDRUSB=0x00; // USB port is input // Corrected V2.3 RD=0; #asm("nop"); PCDat=PINUSB; RD=1; DDRUSB=0xff; // if(PCDat==ESC) goto Brk; else flags|=PCByteRdy; } } NRFDout=1; // Ready for data while(DAVin){ if(brk) {brk|=NoData; goto Brk;} // Wait for data if(!RXF) if(~flags&PCByteRdy){ // Check for escape code DDRUSB=0x00; // USB port is input // Corrected V2.3 RD=0; #asm("nop"); PCDat=PINUSB; RD=1; DDRUSB=0xff; // if(PCDat==ESC) goto Brk; else flags|=PCByteRdy; } } PORTUSB=~PINIB; WR=1; WR=0; // Accept and send data eoi=PINIBctrl&0x20; // Save EOI NRFDout=0; // Not ready for more data NDACout=1; // Data received if(PORTUSB==DLE){ // send another DLE after DLE while(TXE) {timer=0; if(brk) goto Brk;} // wait for not full FIFO WR=1; WR=0; } timer=0; while(!DAVin) if(brk) {brk|=NotDAVrel; goto Brk;} // Wait for DAV rel. NDACout=0; // Data not accepted (no data on bus) }while(eoi); // Finish when EOI is active Brk: if(!(brk&SleepBrk)){ // Send DLE, ETX PORTUSB=DLE; while(TXE) {timer=0; if(brk) goto Brk1;} // wait for not full FIFO WR=1; WR=0; while(TXE) {timer=0; if(brk) goto Brk1;} // wait for not full FIFO PORTUSB=ETX; WR=1; WR=0; } Brk1: DDRUSB=0; return brk; } // RcvBinData /* This routine reads only 1 byte from the GPIB bus and sends it to the PC in binary form. The routine returns brk, which is normally zero. */ unsigned char RcvBinByte(){ NDACout=0; ATNout=1; DDRUSB=0xff; // USB port is output while(TXE) {timer=0; if(brk) goto Brk;} // wait for not full FIFO timer=0; NRFDout=1; // Ready for data while(DAVin) if(brk) {brk|=NoData; goto Brk;} // Wait for data PORTUSB=~PINIB; WR=1; WR=0; // Accept and send data NRFDout=0; // Not ready for more data NDACout=1; // Data received Brk: if(brk&~SleepBrk){ // NULL in case of no data PORTUSB=0; WR=1; WR=0; } Brk1: NRFDout=1; DDRUSB=0; return brk; } // RcvBinByte void main(){ unsigned char PCstr[InstrMax+1]; // This string holds received command, excluding IB header unsigned char i; //,state; unsigned char debug; // Debug flag unsigned char WMode; // New code V2.3; GPIB write mode; 0-3 send EOI, 4-7 do not send EOI // Currently set timeouts. These variables are copied to alike named without _set at start of a command. unsigned char TMax_set; // Byte timeout unsigned int TMaxTot_set; // Total timeout unsigned char SRQst; // Flags for SRQ operation. Definition at the beginning TMax_set=TMax_def; // Set timeouts to default state TMaxTot_set=TMaxTot_def; TMaxFirst=TMaxFirst_def; WMode=0; // Default write mode flags=0; // REN asserted by default debug=0; // We are not in debug mode (yet) SRQst=0; // SRQ interrupt is disabled DDRIB=0; // GPIB interface is in listen mode DDRIBctrl=0; PORTD=0x2d; DDRD=0xe3; // Configure external interrupts MCUCR=0x13; // INT0 (RXF) on low level, INT1 (PWREN) sleep_enable(); brk=0; #asm("sei"); //enable interrupts if(RXF){ GICR=0x80; // Enable wake-up on RXF powerdown(); } // Timer0 initialisation TCCR0=0x05; // CK/1024/256= 32.768 ms interrupt TIMSK=0x02; // enable TOV0 GICR=0x40; // Enable PWREN int. while(1){ Start: TMax=0; // Disable timeouts, V2.4 TMaxTot=0; //timer=0; timer_tot=0; for(i=0;i<3;){ // wait for "IB" if(!(flags&PCByteRdy)){ // Skip waiting for a byte if it was read before (during previous read command). while(RXF){ if(brk) goto Brk; // wait for byte from USB if(SRQin) SRQst&=~SRQstate; // Check SRQ state and send ENQ if newly set to the PC else{ if(SRQst==0x02) if(SendPCChr(ENQ)) goto Brk; SRQst|=SRQstate; } } RD=0; #asm("nop"); PCDat=PINUSB; RD=1; // read byte } flags&=~PCByteRdy; // Clear the "byte waiting" flag switch(i){ case 0: if(PCDat=='I') i++; // check for letter I else if(PCDat=='\r'||PCDat=='\n'||PCDat==ETX||PCDat==ESC) i=0; else i=2; break; case 1: if(PCDat=='B') i=3; // check for letter B else if(PCDat=='\r'||PCDat=='\n'||PCDat==ETX) i=0; else i=2; break; default: if(PCDat=='\r'||PCDat=='\n'||PCDat==ETX) i=0; // wait for CR (or LF) after errored beginning } } for(i=0;i<InstrMax;i++){ // get cmd w/o param. while(RXF) if(brk) goto Brk; // wait for byte from USB RD=0; #asm("nop"); PCDat=PINUSB; RD=1; // read byte if(PCDat=='\n') PCDat='\r'; //replace LF /w CR PCstr[i]=PCDat; // if((PCDat=='\r'||PCDat==STX)&& (i!=1 || PCstr[0]!='c' && PCstr[0]!='C')){ // The condition after && allows any character after first C to be send thus enabling any bus command. if((PCDat=='\r'||PCDat==STX)&& (i!=1 || PCstr[0]!='c' && PCstr[0]!='C') || (i==3 && PCstr[0]=='D')){ // Aditional ORed condition allows any character in debug mode. String is 3 characters long incl. CR. PCstr[i+1]=0; break; } } if(i>=InstrMax){ // Check that command is not too long if(SendPCChr(NAK)) goto Brk; } else if(PCstr[0]=='O'){ // Power OFF DDRUSB=0; DDRIB=0; DDRIBctrl=0; PORTIB=0; // disables pull-ups on GPIB PORTIBctrl=0; DC=0; TE=0; PWR=1; // power off GICR=0x80; // Enable wake-up on RXF TIMSK=0; powerdown(); brk=0; TMax_set=TMax_def; // New code V2.3 TMaxTot_set=TMaxTot_def; WMode=0; // Default write mode // ntotr=1; flags&=~RenState; goto Start; } // New code V2.3 set timeouts else if(PCstr[0]=='t'){ // byte timeout TMax_set=atoi(PCstr+1); if(SendPCChr(ACK)) goto Brk; goto Start; } else if(PCstr[0]=='T'){ // Total timeout TMaxTot_set=atoi(PCstr+1); if(SendPCChr(ACK)) goto Brk; // ntotr=0; goto Start; } // Special timeout for first byte V2.4 else if(PCstr[0]=='f'){ TMaxFirst=atoi(PCstr+1); if(SendPCChr(ACK)) goto Brk; goto Start; } else if(PCstr[0]=='e'){ // Set write mode i=atoi(PCstr+1); if(i<=7){ if(SendPCChr(ACK)) goto Brk; WMode=i; } else if(SendPCChr(NAK)) goto Brk; goto Start; } else if(PCstr[0]=='m'){ // Set REN state if(PCstr[1]=='0'){ flags|=RenState; if(SendPCChr(ACK)) goto Brk; } else if(PCstr[1]=='1'){ flags&=~RenState; if(SendPCChr(ACK)) goto Brk; } else if(SendPCChr(NAK)) goto Brk; goto Start; } // End of new code else if(PCstr[0]=='Q'){ // Enable/disable SRQ interrupt if(PCstr[1]=='0'){ SRQst=0; if(SendPCChr(ACK)) goto Brk; } else if(PCstr[1]=='1'){ SRQst=SRQen; if(SendPCChr(ACK)) goto Brk; } else if(SendPCChr(NAK)) goto Brk; goto Start; } else if(PCstr[0]=='I'){ // Read a controller's identification string switch(PCstr[1]){ case '0': if(SendPCStr(StrIDN0)) goto Brk; break; case '1': if(SendPCStr(StrIDN1)) goto Brk; break; case '2': if(SendPCStr(StrIDN2)) goto Brk; } goto Start; } else if(PWR){ // Power on if powered off PWR=0; // power on PORTIBctrl=0xfe+!!(flags&RenState); // Set REN; V2.3 modified DDRIBctrl=DDRlstn; //Set listen mode IFCout=0; // Clear interface PORTIB=0xff; delay_us(100); IFCout=1; SRQst=0; // New in V2.4 } if(PCstr[0]=='S'){ // Return state of control lines, new V2.4 if(brk=SendPCChr(PINIBctrl)) goto Brk; goto Start; } if(PCstr[0]=='\r'){ // null command (power on and return ACK) if(SendPCChr(ACK)) goto Brk; goto Start; } timer=0; timer_tot=0; TMax=TMax_set; // Enable timeouts TMaxTot=TMaxTot_set; if(!strncmpf(PCstr,StrDataSend,2)){ // SendData SetTalk(); flags|=XmtBlkBrk; if(SendBinData(WMode<4)) goto BrkIB; else SendPCChr(ACK); flags&=~XmtBlkBrk; SetListen(); } else if(PCstr[0]=='?'){ // Read data NRFDout=0; // Set Not Ready For Data before releasing ATN to prevent No listener condition SetListen(); if(RcvBinData()) goto BrkIB; NDACout=1; SendPCChr(ACK); } else if(PCstr[0]=='B'){ // Read one byte from the bus NRFDout=0; // Set Not Ready For Data before releasing ATN to prevent No listener condition SetListen(); if(RcvBinByte()) goto BrkIB; NDACout=1; SendPCChr(ACK); } else if(PCstr[0]=='C'||PCstr[0]=='c'){ // Send bus command SetTalk(); if(SendCmd(PCstr[1])) goto BrkIB; SetListen(); if(PCstr[0]=='C') ATNout=1; SendPCChr(ACK); } else if(PCstr[0]=='Z'){ // Interface Clear TE=0; IFCout=0; // Clear interface delay_us(100); IFCout=1; PORTIB=0xff; PORTIBctrl=0xfe+!!(flags&RenState);// Assert REN DDRIBctrl=DDRlstn; //Set listen mode DDRIB=0; SendPCChr(ACK); } //******** Debug (low-level) commands else if(PCstr[0]=='D'){ // Was a debug command received if(debug){ if(PCstr[1]=='T'){ // Talk command if(PCstr[2]=='0') {SetListen(); brk=SendPCChr(ACK);} else if(PCstr[2]=='1') {SetTalk(); brk=SendPCChr(ACK);} } else if(PCstr[1]=='M'){ // Write data (D7-D0) PORTIB=~PCstr[2]; brk=SendPCChr(ACK); } else if(PCstr[1]=='C'){ // Write control PORTIBctrl=PCstr[2]; brk=SendPCChr(ACK); } else if(PCstr[1]=='?'){ // Read if(PCstr[2]=='C' || PCstr[2]=='?') brk=SendPCChr(PINIBctrl); // control if(PCstr[2]=='M' || PCstr[2]=='?') brk=SendPCChr(~PINIB); // data } } if(!strncmpf(PCstr,"DE\xAA",3)){ debug=1; // Enable debug mode. brk=SendPCChr(ACK); } } // End of debug commands else{ SendPCChr(NAK); // The command was not recognised, return NAK } BrkIB: TMax=0; // Disable timeouts, V2.4 TMaxTot=0; flags&=~UseFirst; // Don't use timeout before first byte if(brk&TimOutBrk){ // Time Out Occured SetListen(); if(!(brk&NoData)){ // Do not reset GPIB if no data were received (support for serial poll) PORTIBctrl=0xfe+!!(flags&RenState); IFCout=0; delay_us(100); IFCout=1; // Clear interface } switch(brk&0x0f){ // Send ERROR character case NotRdyBrk: SendPCChr(1); break; case NotAccBrk: SendPCChr(2); break; case NoLstn: SendPCChr(8); break; case NoData: SendPCChr(9); break; case NotDAVrel: SendPCChr(3); case DataFrmtErr: SendPCChr(NAK); break; } } if(flags&XmtBlkBrk){ // This loop waits for binary data block to end (DLE ETX). flags&=~XmtBlkBrk; i=0; do{ switch(i){ case 0: if(PCDat==DLE) i=1; break; default: if(PCDat==DLE) i=0; else {i=0x80; if(PCDat!=ETX) brk|=DataFrmtErr;} } if(i!=0x80){ while(RXF) {timer=0; if(brk&SleepBrk) break;} RD=0; timer=0; PCDat=PINUSB; RD=1; } }while(!(i&0x80)); } Brk: if(brk&SleepBrk||PWREN){ // USB went sleep DDRUSB=0; DDRIB=0; DDRIBctrl=0; PORTIB=0; // disables pull-ups on GPIB PORTIBctrl=0; DC=0; TE=0; PWR=1; // power off while(!RXF){ // Empty receiver FIFO RD=0; RD=1; } GICR=0x80; // Enable wake-up on RXF // #asm("sleep"); // Go sleep TIMSK=0; // Disable timer interrupts powerdown(); } brk=0; //state=0; timer=0; } //while(1) } //main
C
#include <stdio.h> #if 0 main() { FILE *fp; char ch, filename[50]; printf("Please input filename:\n"); scanf("%s",filename); if((fp = fopen(filename,"w"))==NULL) { printf("cannot open file\n"); exit(0); } printf("Please input paragarm(#end):\n"); ch = getchar(); while(ch!='#') { fputc(ch,fp);//һַд뵽ȥ ch = getchar(); } fclose(fp); } #endif
C
#include <stdio.h> int main(void) { int base = 0; int count = 0; printf("pls input a base_number:\n"); scanf("%d",&base); while(base) { base /= 10; count++; } printf("count = %d\n",count); return 0; }
C
#include <stdlib.h> #include <stdio.h> void lerElementos(int *arr, int n); int main(){ int n; do{ printf("Digite o tamanho de n: "); scanf("%d", &n); }while(n <= 0); int *arr = (int*)calloc(n, sizeof(int)); if(arr == NULL){ printf("Mmoria insuficiente"); exit(0); } lerElementos(arr, n); printf("\n"); int i; for(i = 0; i < n; i++){ printf(" %d", arr[i]); } free(arr); } void lerElementos(int *arr, int n){ int i; for(i = 0; i < n; i++){ scanf("%d", &arr[i]); } }
C
#include "imei.h" void yapiciFonksiyon2(struct IMEI * Imei) { Imei->imei=malloc(sizeof(int)*15); } void ImeiOlustur(struct IMEI * Imei) { int i,r ; for (i = 0; i < 14; i++) //14 haneye random rakam atarız { r=rand()%10; Imei->imei[i]=r; } int tekTop=0,ciftler=0; for (i = 0; i < 14; i++) { if(i%2==0) tekTop+=Imei->imei[i]; //Tek hane kontrolu if(i%2==1) ciftler+= (Imei->imei[i]*2)%10 + (Imei->imei[i]*2)/10; //Cift hanelerin kontrol islemi } if(((tekTop+ciftler)%10)==0) { Imei->imei[14]=0; } else { Imei->imei[14]=10-(tekTop+ciftler)%10; //15.haneyi bulup diziye atama yaptık } } void yikiciFonksiyon2(struct IMEI * Imei) //Ayirdigimiz bellegi serbest biraktik { free(Imei->imei); }
C
#include "shell.h" int (*builtin_f[]) (char **) = { &help, &cd}; /* char *builtin[] = { "help", "cd"}; */ /** *Fork - wrapper function for fork. *Return: process created. */ pid_t Fork(void) { pid_t pid = fork(); if (pid < 0) perror("Fork error"); return (pid); } /** * num - Calculates the number of builtin functions * * Return: the number of builtin functions */ int num(char *built[]) { return(sizeof(built) / sizeof(char *)); } /** * help - Writes simple_shell instructions to stdout * @tokens: command * * Return: 1 */ int help(char __attribute__((unused)) **tokens) { write(STDOUT_FILENO, "simple shell\n", 17); return (1); } /** * exit_1 - Compares command with exit * @tokens: command * * Return: zero on success and 1 on failure */ int exit_1(char **tokens) { if (!_strcmp(tokens[0], "exit")) return (0); return (1); } /** * cd - executes cd command * @tokens: command * * Return: zero on success */ int cd(char **tokens) { int x, count; char **dirs = NULL, *delims = "/"; char __attribute__((unused)) *dir; char *buf = NULL, *new_wd, home[] = "/home/", *home2; size_t size = 0; if (tokens[1] == NULL) { new_wd = getcwd(buf, size); count = ntokens(new_wd, delims); dirs = tokenise(count, new_wd, delims); home2 = malloc(sizeof(home) + sizeof(dirs[1])); if(home2 == NULL) { free(home2); free_dptr(tokens); free_dptr(dirs); } _strcpy(home2, home); _strcat(home2, dirs[1]); chdir(home2), free(home2), free_dptr(dirs); return(0); } else { dir = getcwd(buf, size); x = (chdir(tokens[1])); if (x == -1) { perror("Error"); return(0); free_dptr(tokens); } } return (0); free_dptr(tokens), free(home2); } /** * compare - compares user input with the existing builtin commands * @tokens: user command * * Return: zero on success */ int compare(char **tokens) { int i; char *builtin[] = { "help", "cd"}; int size = num(builtin); if (tokens == NULL) return(-1); for (i = 0; i <= size; i++) { if (_strcmp(tokens[0], builtin[i]) == 0) { (*builtin_f[i])(tokens); return 1; } } return (0); } /** * def_prompt - write $ on a new line. * * Return: void. */ void def_prompt(void) { write(1, "$ ", 2); } /** * def_prompt2 - Write > on a new line * * Return: void */ void def_prompt2(void) { write(STDOUT_FILENO, "> ", 2); }
C
/*Substitui ocorrncia*/ #include <stdio.h> #include <stdlib.h> #include <ctype.h> #include <string.h> #define TAM 1000 struct list { char ch; struct list *P; }; typedef struct list Lista; Lista *insere (Lista *,char *); void imprime (Lista *); Lista *clona (Lista *); unsigned int tamanho (Lista *); Lista *substitui (Lista *,Lista *,Lista *,unsigned int); int main(){ Lista *L1 = NULL, *L2 = NULL, *L3 = NULL; char str1[TAM], str2[TAM], str3[TAM]; printf("String Principal: "); gets(str1); strrev(str1); L1 = insere(L1,str1); printf("String Secundaria: "); gets(str2); strrev(str2); L2 = insere(L2,str2); printf("String para substituicao: "); gets(str3); strrev(str3); L3 = insere(L3,str3); putchar('\n'); printf("String Resultante: "); imprime(substitui(L1,L2,L3,tamanho(L2))); free(L1); free(L2); free(L3); return 0; } Lista *insere (Lista *L,char *ch){ Lista *novo; while (*ch){ novo = (Lista *) malloc(sizeof(Lista)); if (novo == NULL) exit(0); novo->ch = *ch; novo->P = L; L = novo; ch++; } return novo; } void imprime (Lista *L){ Lista *aux = L; while (aux != NULL){ printf("%c", aux->ch); aux = aux->P; } } unsigned int tamanho (Lista *L){ unsigned int n = 0; Lista *aux = L; while (aux){ if (tolower(aux->ch) >= 'a' && tolower(aux->ch) <= 'z') n++; aux = aux->P; } return n; } Lista *clona (Lista *L1){ Lista *novo = NULL,*aux = L1; char ch[TAM]; int i = 0; while (aux){ ch[i] = aux->ch; aux = aux->P; i++; } ch[i] = '\0'; strrev(ch); novo = insere(novo,ch); return novo; } Lista *substitui (Lista *L1,Lista *L2,Lista *L3,unsigned int n){ Lista *aux1 = L1, *aux2 = NULL, *aux3 = NULL,*novo = NULL,*prox1 = NULL, *ant1 = NULL, *aant1 = NULL; unsigned int conta,i = 0,fez = 0; char str[TAM]; while (aux1){ ant1 = aux1; aux2 = clona(L2); while (aux2->ch == ' ') {aux2 = aux2->P;if(!aux2) break;} if (!aux2) break; prox1 = aux1->P; if (tolower(aux1->ch) == tolower(aux2->ch)){ conta = 0; while (aux1 && aux2){ while (aux1->ch == ' ') {aux1 = aux1->P;if(!aux1) break;} while (aux2->ch == ' ') {aux2 = aux2->P;if(!aux2) break;} if (!aux1 || !aux2) break; if (tolower(aux1->ch) == tolower(aux2->ch)) conta++; aant1 = aux1; aux1 = aux1->P; aux2 = aux2->P; } if (conta == n){ aux3 = clona(L3); while (aux3){ str[i++] = aux3->ch; aux3 = aux3->P; } fez = 1; aux1 = aant1; continue; } else { if (fez == 0) str[i++] = ant1->ch; fez = 0; } } else { if (fez == 0) str[i++] = ant1->ch; fez = 0; } aux1 = prox1; } str[i] = '\0'; strrev(str); novo = insere(novo,str); return novo; }
C
/* Tickle class library Copyright (c) 2003,2004 Alessandro Scotti */ #ifndef EMU_BLITTER_H_ #define EMU_BLITTER_H_ struct TBitBlitter { virtual ~TBitBlitter () { } virtual void blit( unsigned char * dst, unsigned char * src, int len ) = 0; }; struct TBltCopy : public TBitBlitter { virtual void blit( unsigned char * dst, unsigned char * src, int len ) { memcpy( dst, src, (size_t)len ); } }; struct TBltCopyReverse : public TBitBlitter { virtual void blit( unsigned char * dst, unsigned char * src, int len ) { for( ; len > 0; len-- ) { *dst++ = *--src; } } }; struct TBltAdd : public TBitBlitter { TBltAdd( unsigned char color ) : color_(color) { } virtual void blit( unsigned char * dst, unsigned char * src, int len ) { for( ; len > 0; len-- ) { *dst++ = color_ + *src++; } } TBltAdd * color( unsigned char c ) { color_ = c; return this; } protected: unsigned char color_; }; struct TBltAddReverse : public TBltAdd { TBltAddReverse( unsigned char color ) : TBltAdd(color) { } virtual void blit( unsigned char * dst, unsigned char * src, int len ) { for( ; len > 0; len-- ) { *dst++ = color_ + *--src; } } }; struct TBltAddSrcTrans : public TBltAdd { TBltAddSrcTrans( unsigned char color, unsigned char trans ) : TBltAdd(color), trans_(trans) { } virtual void blit( unsigned char * dst, unsigned char * src, int len ) { for( ; len > 0; len-- ) { unsigned char c = *src++; if( c != trans_ ) *dst = color_ + c; dst++; } } protected: unsigned char trans_; }; struct TBltAddSrcTransReverse : public TBltAddSrcTrans { TBltAddSrcTransReverse( unsigned char color, unsigned char trans ) : TBltAddSrcTrans(color,trans) { } virtual void blit( unsigned char * dst, unsigned char * src, int len ) { for( ; len > 0; len-- ) { unsigned char c = *--src; if( c != trans_ ) *dst = color_ + c; dst++; } } }; struct TBltAddSrcZeroTransBlackAndWhite : public TBltAdd { TBltAddSrcZeroTransBlackAndWhite( unsigned char color ) : TBltAdd(color) { } virtual void blit( unsigned char * dst, unsigned char * src, int len ) { for( ; len > 0; len-- ) { unsigned char c = *src++; if( c ) *dst = color_; dst++; } } }; struct TBltAddSrcZeroTrans : public TBltAdd { TBltAddSrcZeroTrans( unsigned char color ) : TBltAdd(color) { } virtual void blit( unsigned char * dst, unsigned char * src, int len ) { for( ; len > 0; len-- ) { unsigned char c = *src++; if( c ) *dst = color_ + c; dst++; } } }; struct TBltAddSrcZeroTransReverse : public TBltAddSrcZeroTrans { TBltAddSrcZeroTransReverse( unsigned char color ) : TBltAddSrcZeroTrans(color) { } virtual void blit( unsigned char * dst, unsigned char * src, int len ) { for( ; len > 0; len-- ) { unsigned char c = *--src; if( c ) *dst = color_ + c; dst++; } } }; struct TBltAddXlat : public TBltAdd { TBltAddXlat( unsigned char color, unsigned char * xlat ) : TBltAdd(color), xlat_(xlat) { } virtual void blit( unsigned char * dst, unsigned char * src, int len ) { for( ; len > 0; len-- ) { *dst++ = xlat_[ (unsigned char)(color_ + *src++) ]; } } protected: unsigned char * xlat_; }; struct TBltAddXlatReverse : public TBltAddXlat { TBltAddXlatReverse( unsigned char color, unsigned char * xlat ) : TBltAddXlat(color,xlat) { } virtual void blit( unsigned char * dst, unsigned char * src, int len ) { for( ; len > 0; len-- ) { *dst++ = xlat_[ (unsigned char)( color_ + *--src) ]; } } }; struct TBltAddXlatSrcTrans : public TBltAddSrcTrans { TBltAddXlatSrcTrans( unsigned char color, unsigned char trans, unsigned char * xlat ) : TBltAddSrcTrans(color,trans), xlat_(xlat) { } virtual void blit( unsigned char * dst, unsigned char * src, int len ) { for( ; len > 0; len-- ) { unsigned char c = *src++; if( c != trans_ ) *dst = xlat_[ (unsigned char)( color_ + c) ]; dst++; } } protected: unsigned char * xlat_; }; struct TBltAddXlatSrcTransReverse : public TBltAddSrcTrans { TBltAddXlatSrcTransReverse( unsigned char color, unsigned char trans, unsigned char * xlat ) : TBltAddSrcTrans(color,trans), xlat_(xlat) { } virtual void blit( unsigned char * dst, unsigned char * src, int len ) { for( ; len > 0; len-- ) { unsigned char c = *--src; if( c != trans_ ) *dst = xlat_[ (unsigned char)( color_ + c) ]; dst++; } } protected: unsigned char * xlat_; }; struct TBltAddXlatDstTrans : public TBltAddXlatSrcTrans { TBltAddXlatDstTrans( unsigned char color, unsigned char trans, unsigned char * xlat ) : TBltAddXlatSrcTrans(color,trans,xlat) { } virtual void blit( unsigned char * dst, unsigned char * src, int len ) { for( ; len > 0; len-- ) { unsigned char c = xlat_[ (unsigned char)( color_ + *src++) ]; if( c != trans_ ) *dst = c; dst++; } } }; struct TBltAddXlatDstTransReverse : public TBltAddXlatDstTrans { TBltAddXlatDstTransReverse( unsigned char color, unsigned char trans, unsigned char * xlat ) : TBltAddXlatDstTrans(color,trans,xlat) { } virtual void blit( unsigned char * dst, unsigned char * src, int len ) { for( ; len > 0; len-- ) { unsigned char c = xlat_[ (unsigned char)( color_ + *--src) ]; if( c != trans_ ) *dst = c; dst++; } } }; #endif // EMU_BLITTER_H_
C
/* apl compiler build new parse tree nodes timothy a. budd */ /* The APL Compiler is Public Domain It may be freely redistributed as long as this notice of authorship is retained with the sources. Tim Budd Oregon State University Department of Computer Science Corvallis, Oregon 97331 USA No guarantees are given as to the suitablity of this code for any purposes whatsoever */ # include "parse.h" # include "y.tab.h" # include <stdio.h> extern char *sconsts; /* current string constants */ /* strllen - string length without escape characters */ int slen(c) char *c; { int i; char *p; i = 0; for (p = c; *p ; p++) if (*p != '\\') i++; return(i); } /* newid - create a new id string */ char *newid(name) char *name; { char *x; x = (char *) malloc((unsigned) strlen(name)+1); if (x == NILCHAR) yyerror("out of space"); strcpy(x, name); return(x); } /* newhead - make a new function header node */ struct headnode *newhead(name, parm1, parm2) char *name, *parm1, *parm2; { struct headnode *x; struct symnode *enterid(); x = structalloc(headnode); if (x == NILHEAD) yyerror("out of space"); enterid(name, FUNCTION, UKTYPE, NORANK); x->fname = name; x->asvar = NILCHAR; x->parm1 = parm1; x->parm2 = parm2; if (parm1 != NILCHAR) enterid(parm1, PARAM, UKTYPE, NORANK); if (parm2 != NILCHAR) enterid(parm2, PARAM, UKTYPE, NORANK); return(x); } /* direct - direct defintion declaration */ direct(label, expr) char *label; struct node *expr; { struct node *x, *pt2(), *ptvar(); struct symnode *s; struct headnode *h; struct statenode *newstate(); enum classes idclass(); h = newhead(label, "_alpha", "_omega"); h->asvar = "_zeta"; idclass("_zeta", &s); x = pt2(ASSIGN, ptvar(s), expr); prog(h, newstate(NILCHAR, x)); resetconsts(); reinitsymtab(); } /* newstate - produce a new statement node */ struct statenode *newstate(label, code) char *label; struct node *code; { struct statenode *x; if (code->nodetype == COMMENT && label == NILCHAR) return(NILSTATE); x = structalloc(statenode); if (x == NILSTATE) yyerror("out of space"); x->label = label; x->code = code; x->nextstate = NILSTATE; x->list = NILSYM; return(x); } /* addstmt - add a statement to statement list */ struct statenode *addstmt(first, new) struct statenode *first, *new; { struct statenode *i; if (new == NILSTATE) return(first); else if (first == NILSTATE) return(new); else { for (i = first; i->nextstate != NILSTATE; i = i->nextstate) ; i->nextstate = new; return(first); } } /* newnode - produce a new parse tree node */ struct node *newnode(type) int type; { struct node *x; x = structalloc(node); if (x == (struct node *)0) yyerror("out of space"); x->nodetype = type; x->info = 0; x->left = x->right = x->a.axis = NILP; x->type.n = x->rank.n = x->shape.n = x->values.n = 0; x->optype = NOT; x->index = 0; return(x); } /* pt1 - simple 1 child node */ struct node *pt1(type, child) int type; struct node *child; { struct node *x; x = newnode(type); x->right = child; return(x); } /* ptaxis - process an axis specifier */ ptaxis(x, axis, ainfo) struct node *axis, *x; int ainfo; { if (axis != NILP) { x->a.axis = pt1(CSCALAR, axis); } else { x->a.axis = NILP; x->info |= ainfo; } } /* pt1a - 1 child node with axis */ struct node *pt1a(type, axis, ainfo, child) int type, ainfo; struct node *child, *axis; { struct node *x; x = pt1(type, child); ptaxis(x, axis, ainfo); return(x); } /* pt1o - 1 child node with operator */ struct node *pt1o(type, op, child) int type; enum sops op; struct node *child; { struct node *x; x = pt1(type, child); x->optype = op; return(x); } /* pt1ao - one child node with both axis and operator */ struct node *pt1ao(type, op, axis, child, ainfo) int type, ainfo; enum sops op; struct node *axis, *child; { struct node *x; x = pt1a(type, axis, ainfo, child); x->optype = op; return(x); } /* pt2 - simple 2 child node */ struct node *pt2(type, child1, child2) int type; struct node *child1, *child2; { struct node *x; x = newnode(type); x->left = child1; x->right = child2; return(x); } /* pt2a - 2 child node with axis */ struct node *pt2a(type, axis, ainfo, child1, child2) int type, ainfo; struct node *child1, *child2, *axis; { struct node *x; x = pt2(type, child1, child2); ptaxis(x, axis, ainfo); return(x); } /* pt2o - two child node with operator */ struct node *pt2o(type, op, child1, child2) int type; enum sops op; struct node *child1, *child2; { struct node *x; x = pt2(type, child1, child2); x->optype = op; return(x); } /* pt2ao - two child node with both operator and axis */ struct node *pt2ao(type, op, axis, ainfo, child1, child2) int type, ainfo; enum sops op; struct node *axis, *child1, *child2; { struct node *x; x = pt2a(type, axis, ainfo, child1, child2); x->optype = op; return(x); } /* ptsort - sort function */ struct node *ptsort(direction, child) int direction; struct node *child; { struct node *x; x = pt1(SORT, child); x->a.ptr0 = direction; return(x); } /* ptsvec - string constant (vector) */ struct node *ptsvec(chars) char *chars; { struct node *x; int slen(); x = newnode(SCON); x->type.n = (int) CHAR; x->rank.n = 1; x->shape.n = addicon(slen(chars)); x->values.n = slen(sconsts); x->info |= (TYPEDECL | TYPEKNOWN | RANKDECL | RANKKNOWN | SHAPEKNOWN | VALUESKNOWN); if (strlen(chars) + strlen(sconsts) > MAXCONSTS) yyerror("too many string constants"); strcat(sconsts, chars); return(x); } /* ptval - scalar value */ struct node *ptval(type, val) int type; int val; { struct node *x; x = newnode(type); x->rank.n = 0; x->shape.n = 1; x->values.n = val; x->info |= (TYPEDECL | TYPEKNOWN | RANKDECL | RANKKNOWN | SHAPEKNOWN | VALUESKNOWN); return(x); } /* aptval - add a scalar value, forming an array */ struct node *aptval(node) struct node *node; { node->rank.n = 1; node->shape.n++; return(node); } /* ptvec - constant vector */ struct node *ptvec(x, type, rtype) struct node *x; int type; int rtype; { x->nodetype = type; x->type.n = (int) rtype; x->info |= (TYPEDECL | TYPEKNOWN); if (x->rank.n) x->shape.n = addicon(x->shape.n); return(x); } struct node *sysparm(name) char *name; { struct symnode *x, *enterid(); struct node *ptvar(); idclass(name, &x); if (x == NILSYM) { /* declare system generated variables */ enterid(newid("_alpha"), PARAM, UKTYPE, NORANK); enterid(newid("_omega"), PARAM, UKTYPE, NORANK); enterid(newid("_zeta"), LOCAL, UKTYPE, NORANK); /* try it again */ idclass(name, &x); if (x == NILSYM) yyerror("sysparm error"); } return(ptvar(x)); } /* ptvar - variable node */ struct node *ptvar(var) struct symnode *var; { struct node *x; x = newnode(IDENT); x->a.namep = var->name; if ((var->type != UKTYPE) & (var->type != ANY)) x->info |= ( TYPEDECL | TYPEKNOWN ); x->type.n = var->type; if (var->vrank != NORANK) x->info |= ( RANKDECL | RANKKNOWN ); x->rank.n = var->vrank; return(x); } /* ptfun - functions */ struct node *ptfun(fun, child1, child2) struct symnode *fun; struct node *child1, *child2; { struct node *x; x = pt2(FIDENT, child1, child2); x->a.namep = fun->name; x->type.n = fun->type; if ((fun->type != UKTYPE) & (fun->type != ANY)) x->info |= ( TYPEDECL | TYPEKNOWN ); x->rank.n = fun->vrank; if (fun->vrank != NORANK) x->info |= ( RANKDECL | RANKKNOWN ); return(x); } /* ptmrho - monadic rho (shape) */ struct node *ptmrho(child) struct node *child; { struct node *x; if (child->nodetype == RHO) { x = child; x->nodetype = RHORHO; } else { x = newnode(RHO); x->right = child; } return(x); } /* ptsub - subscripted assignment */ struct node *ptsub(child1, child2) struct node *child1, *child2; { child1->a.axis = child1->right; /* child1->left = child1->left */ child1->right = child2; child1->nodetype = SUBASSIGN; return(child1); } /* pttop - top of expression */ struct node *pttop(child) struct node *child; { struct node *x; int type; type = child->nodetype; /* if not assignment or function call, print out expression */ if (type == ASSIGN || type == BOXASSIGN || type == FIDENT || type == DBOXAS || type == QBOXAS || type == DQBOXAS) x = child; else if (type == SYSVAR && child->right != NILP) x = child; else x = pt1(BOXASSIGN, child); return(x); } /* ptsemi - semicolon */ struct node *ptsemi(child1, child2) struct node *child1, *child2; { struct node *x; x = pt2(SM, child1, child2); if (child1 == NILP) x->ptr1 = 0; else x->ptr1 = child1->ptr1 + 1; return(x); }
C
// Generate a power-on reset pulse using an attiny84. #include <avr/interrupt.h> #define F_CPU 800000UL #include <util/delay.h> #include <stdint.h> // GPIOs on port A // Pin 0 is the reset output. // Pin 1 is the momentary normally open manual reset button: // when the button is pressed, pin 1 is connected to ground. // Pin 2 is a LED that is lit when the firmware starts running. // This is useful becaues you can see the duration of the reset // pulse (500 ms). #define RST (1 << 0) #define SW (1 << 1) #define PWR (1 << 2) int main(){ DDRA = RST|PWR; // enable output on A0 and A2 PORTA |= SW; // enable pullup on A1, for reset switch // Light the LED on A2 just so we can see // when the reset pulse is being generated PORTA |= PWR; // Generate a 500 ms reset pulse PORTA &= ~RST; _delay_ms(500); PORTA |= RST; // Monitor switch: when pressed, input will go low, and // we'll re-assert reset. Use a counter to debounce // the signal. uint8_t btn_last = PINA & SW; uint8_t count = 0; while (1) { uint8_t btn_now = PINA & SW; if (btn_now != btn_last) { count = 0; } else if (count < 255) { count++; } if (count > 10) { if (btn_now == 0) { // pressed, generate manual reset PORTA &= ~RST; } else { // not pressed PORTA |= RST; } } btn_last = btn_now; _delay_us(100); // delay .1ms } }
C
/**---------------------------------------------------------- Base64 Encoder-Decoder Main file -------------------------------------------------------------*/ #include "base64.h" /**---------------- Main function. It just handle the file management and the memory allocation part, creating the strings that the encode/decode functions work with. -------------------*/ int main(int argc, const char *argv[]){ int fds, fdd; unsigned char o_flag=1, encode_flag; char dest_f[256], lf[1]; char *d_string; void *s_string; size_t s_size, d_size; if((argc<3) | (argc>4)){ printf("Use: %s [E/D] ascii_source_file destination_file\n",argv[0]); exit(EXIT_FAILURE); } //Encode or decode flag if(*argv[1]=='E') encode_flag = 1; else if(*argv[1]=='D') encode_flag = 0; else{ printf("Use: %s [E/D] ascii_source_file destination_file\n",argv[0]); exit(EXIT_FAILURE); } //Source file if((fds=open(argv[2],O_RDONLY))<0){ perror("Couldnt open the source file."); exit(EXIT_FAILURE); } //Destination file if(argc==4){ if((fdd=open(argv[3],O_RDWR|O_CREAT|O_TRUNC, 0644))<0) perror("Couldnt open the given destination file. Trying with the default one."); else o_flag=0; } if((argc==3) | (o_flag)){ if(encode_flag) sprintf(dest_f, "cod_%s", argv[2]); else sprintf(dest_f, "decod_%s", argv[2]); if((fdd=open(dest_f,O_RDWR|O_CREAT|O_TRUNC, 0644))<0){ perror("Couldnt open the default destination file."); exit(EXIT_FAILURE); } } //Source file size if((s_size=lseek(fds,-1,SEEK_END))<=0){ perror("Couldnt calculate dest file size or EMPTY SOURCE FILE."); exit(EXIT_FAILURE); } else{ //text editors like gedit add Line Feed at the end when you save the file. This fakes the //s_size, thats the reason we stop lseek before the last character and check it read(fds, lf, 1); if(lf[0]!=10) s_size++; } //Destination file size calculation if(encode_flag){ if(s_size%3) d_size = ((s_size/3)+1)*4; else d_size = (s_size/3)*4; } else{ if((s_size%4)!=0){ perror("Incorrect Base64 ascii file (number of characters doesnt fix). Couldnt decode."); printf("%li %li\n",s_size, (s_size%4)); exit(EXIT_FAILURE); } else d_size = (s_size/4)*3; } //Destination string memory allocation if((d_string=(char*)malloc(d_size))==NULL){ perror("Couldnt allocate destination string."); exit(EXIT_FAILURE); } //Source string memory allocation s_string=mmap(0, s_size, PROT_READ|PROT_WRITE, MAP_PRIVATE, fds, 0); if(s_string==MAP_FAILED){ perror("Couldnt achieve memory mapping of the source file."); free(d_string); exit(EXIT_FAILURE); } //Enocding-decoding operation if(encode_flag) encode((char*)s_string, s_size, d_string, d_size); else decode((char*)s_string, s_size, d_string, d_size); //Destination file updating if((write(fdd, d_string, d_size))<d_size) perror("Error al guardar la decodificacion"); //Memory freeing if(munmap(s_string,s_size)<0) perror("Couldnt unmap the source file"); free(d_string); close(fds); close(fdd); return 0; }
C
#include <stdio.h> #include <math.h> #include <stdlib.h> #include "prac2funs_1.h" #include "prac2funs_2.h" /* AUTOR: Astor Prieto, niUB: 16445586, DNI: 39427935R */ double f(double x) { double f; f = pow(sin(y), 2); return f; } double F(double x) { int N, nMax; double T_n = 0; double T_aux = 0; double tol = pow(10, -8); int cont = 1; for (N = 2; N < pow(2, nMax); N = pow(2, cont)) { T_n = trapezis(N, -x, x); if (fabs(T_n - T_aux) < tol) { printf("Integral Aproximada: %f\n", T_n); return T_n; } T_aux = T_n; cont++; } printf("Error al calcular la integral aproximada.\n"); return 1.0; } double dF(double x) { double dF; dF = f(x) + f(-x); return dF; } int main(void) { int N, nMax; int cont = 1; double C, T_n; double T_aux = 0; printf("Indica el valor 'C': \n"); scanf("%lf", &C); return -1; }
C
// ʵֺ ToLowerCase()úһַ strַеĴдĸתСдĸ֮󷵻µַ // ʾ 1 // : "Hello" // : "hello" // ʾ 2 // : "here" // : "here" // ʾ?3 // : "LOVELY" // : "lovely" char * toLowerCase(char * str){ char* ret = str; while (*str != '\0') { if (*str <= 'Z' && *str >= 'A') *str += 32; str++; } return ret; }
C
#include<stdio.h> #include<stdlib.h> #include<string.h> typedef char element[100]; typedef struct ListNode{ element data; struct ListNode *link; } ListNode; typedef struct CListType{ ListNode *head; }CListType; //Ʈ ׸ void print_list(CListType *L){ ListNode *p; if(L->head ==NULL) return; p = L->head->link; do{ printf("%s -> ", p->data); p = p->link; } while(p!=L->head); printf("%s -> ", p->data); // } void insert_first(CListType* L, element data){ ListNode *node = (ListNode *)malloc(sizeof(ListNode)); strcpy(node->data, data); if(L->head==NULL){ L->head=node; node->link = L->head; } else{ node->link = L->head->link; L->head->link = node; } } //ḮƮ ׽Ʈ α׷ int main(void){ CListType list= {NULL}; insert_first(&list,"KIM"); insert_first(&list,"PARK"); insert_first(&list,"CHOI"); ListNode* p = list.head; int i; for(i=0;i<10;i++){ printf(" : %s\n", p->data); p= p->link; } }
C
// // Created by greg on 2021-07-30. // #include "lang.h" #include <assert.h> // region ------------------- SHADING --------------- // todo: spot light is done by comparing the angle (dot prod) between light dir an vec from light to fragment // https://www.lighthouse3d.com/tutorials/glsl-tutorial/spotlights/ public float luminosity(const float distance, const Light light) { return 1.0f / (light.attenConstant + light.attenLinear * distance + light.attenQuadratic * distance * distance); } public vec3 diffuseContrib(const vec3 lightDir, const vec3 fragNormal, const PhongMaterial material) { float diffuseTerm = dotv3(fragNormal, lightDir); return diffuseTerm > 0.0f ? mulv3f(material.diffuse, diffuseTerm) : v3zero(); } public vec3 halfVector(const vec3 left, const vec3 right) { return normv3(addv3(left, right)); } public vec3 specularContrib(const vec3 viewDir, const vec3 lightDir, const vec3 fragNormal, const PhongMaterial material) { vec3 hv = halfVector(viewDir, lightDir); float specularTerm = dotv3(hv, fragNormal); return specularTerm > 0.0f ? mulv3f(material.specular, powf(specularTerm, material.shine)) : v3zero(); } public vec3 lightContrib(const vec3 viewDir, const vec3 lightDir, const vec3 fragNormal, const float attenuation, const Light light, const PhongMaterial material) { vec3 lighting = v3zero(); lighting = addv3(lighting, diffuseContrib(lightDir, fragNormal, material)); lighting = addv3(lighting, specularContrib(viewDir, lightDir, fragNormal, material)); return mulv3(mulv3f(light.color, attenuation), lighting); } public vec3 pointLightContrib(const vec3 viewDir, const vec3 fragPosition, const vec3 fragNormal, const Light light, const PhongMaterial material) { vec3 direction = subv3(light.vector, fragPosition); vec3 lightDir = normv3(direction); if (dotv3(lightDir, fragNormal) < 0.0f) { return v3zero(); } float distance = lenv3(direction); float lum = luminosity(distance, light); return lightContrib(viewDir, lightDir, fragNormal, lum, light, material); } public vec3 dirLightContrib(const vec3 viewDir, const vec3 fragNormal, const Light light, const PhongMaterial material) { vec3 lightDir = negv3(normv3(light.vector)); return lightContrib(viewDir, lightDir, fragNormal, 1.0f, light, material); } public vec4 shadingFlat(vec4 color) { return color; } public vec4 shadingPhong(const vec3 fragPosition, const vec3 eye, const vec3 fragNormal, const vec3 fragAlbedo, const PhongMaterial material) { vec3 viewDir = normv3(subv3(eye, fragPosition)); vec3 color = material.ambient; for (int i = 0; i < uLightsPointCnt; ++i) { color = addv3(color, pointLightContrib(viewDir, fragPosition, fragNormal, uLights[i], material)); } for (int i = uLightsPointCnt; i < uLightsPointCnt + uLightsDirCnt; ++i) { color = addv3(color, dirLightContrib(viewDir, fragNormal, uLights[i], material)); } color = mulv3(color, fragAlbedo); return v3tov4(color, material.transparency); } custom vec3 getNormalFromMap(const vec3 normal, const vec3 worldPos, const vec2 texCoord, const vec3 vnormal) { const vec3 result = addv3(addv3(addv3(normal, worldPos), vnormal), v2tov3(texCoord, 1)); assert(dotv3(result, worldPos) && "Some chicken shit happens here.."); /*vec3 tangentNormal = fromMap * 2.0 - 1.0; vec3 Q1 = dFdx(vWorldPos); vec3 Q2 = dFdy(vWorldPos); vec2 st1 = dFdx(vTexCoord); vec2 st2 = dFdy(vTexCoord); vec3 N = normalize(vNormal); vec3 T = normalize(Q1*st2.t - Q2*st1.t); vec3 B = -normalize(cross(N, T)); mat3 TBN = mat3(T, B, N); return normalize(TBN * tangentNormal);*/ return result; } public float distributionGGX(const vec3 N, const vec3 H, const float a) { float a2 = a * a; float NdotH = maxf(dotv3(N, H), 0.0f); float NdotH2 = NdotH*NdotH; float nom = a2; float denom = (NdotH2 * (a2 - 1.0f) + 1.0f); denom = PI * denom * denom; return nom / denom; } public float geometrySchlickGGX(const float NdotV, const float roughness) { float r = (roughness + 1.0f); float k = (r*r) / 8.0f; float nom = NdotV; float denom = NdotV * (1.0f - k) + k; return nom / denom; } public float geometrySmith(const vec3 N, const vec3 V, const vec3 L, const float roughness) { float NdotV = maxf(dotv3(N, V), 0.0f); float NdotL = maxf(dotv3(N, L), 0.0f); float ggx2 = geometrySchlickGGX(NdotV, roughness); float ggx1 = geometrySchlickGGX(NdotL, roughness); return ggx1 * ggx2; } public vec3 fresnelSchlick(const float cosTheta, const vec3 F0) { return addv3(F0, mulv3(subv3(ftov3(1.0f), F0), ftov3(powf(1.0f - cosTheta, 5.0f)))); } public vec4 shadingPbr(const vec3 eye, const vec3 worldPos, const vec3 albedo, const vec3 N, const float metallic, const float roughness, const float ao) { const vec3 alb = powv3(albedo, ftov3(2.2f)); const vec3 V = normv3(subv3(eye, worldPos)); vec3 F0 = ftov3(0.04f); F0 = mixv3(F0, alb, metallic); vec3 Lo = v3zero(); for(int i = 0; i < uLightsPointCnt; ++i) { const vec3 toLight = subv3(uLights[i].vector, worldPos); const vec3 L = normv3(toLight); const vec3 H = normv3(addv3(V, L)); const float distance = lenv3(toLight); const float lum = luminosity(distance, uLights[i]); const vec3 radiance = mulv3(uLights[i].color, ftov3(lum)); const float NDF = distributionGGX(N, H, roughness); const float G = geometrySmith(N, V, L, roughness); const vec3 F = fresnelSchlick(maxf(dotv3(H, V), 0.0f), F0); const vec3 nominator = mulv3(F, ftov3(NDF * G)); const float denominator = 4.0f * maxf(dotv3(N, V), 0.0f) * maxf(dotv3(N, L), 0.0f) + 0.001f; const vec3 specular = divv3f(nominator, denominator); vec3 kD = subv3(ftov3(1.0f), F); kD = mulv3(kD, ftov3(1.0f - metallic)); const float NdotL = maxf(dotv3(N, L), 0.0f); Lo = addv3(Lo, mulv3(mulv3(addv3(divv3(mulv3(kD, alb), ftov3(PI)), specular), radiance), ftov3(NdotL))); } const vec3 ambient = mulv3(ftov3(0.1f * ao), alb); vec3 color = addv3(ambient, Lo); color = divv3(color, addv3(color, ftov3(1.0f))); color = powv3(color, ftov3(1.0f/2.2f)); return v3tov4(color, 1.0f); } // endregion ------------------- SHADING ---------------
C
#include <stdio.h> int main(void) { int n = 0, min = 0, max = 0, sub = 0; int a[1001] = { 0, }; scanf("%d", &n); for (int i = 0; i < n; i++) { scanf("%d", &a[i]); } min = max = a[0]; for (int j = 0; j < n; j++) { if (a[j] > max) max = a[j]; else if (a[j] < min) min = a[j]; } sub = max - min; printf("%d", sub); return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* draw.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: khakala <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/01/14 16:59:51 by khakala #+# #+# */ /* Updated: 2020/01/28 15:35:38 by khakala ### ########.fr */ /* */ /* ************************************************************************** */ #include "fdf.h" void isometric(float *x, float *y, int z, t_fdf *data) { *x = (*x - *y) * cos(data->cos_angle); *y = (*x + *y) * sin(data->sin_angle) - z; } void get_color(t_fdf *data) { if (data->z || data->z1) { if (data->z < 0 || data->z1 < 0) data->color = 0x00ffff; else if (data->z > 50 || data->z1 > 50) data->color = 0xffff05; else data->color = 15207436; } else data->color = 16777215; } void bresenham(float x, float y, t_fdf *data) { data->z = data->z_matrix[(int)y][(int)x]; data->z1 = data->z_matrix[(int)data->y1][(int)data->x1]; if (data->z != 0) data->z = data->z_matrix[(int)y][(int)x] * (data->z_alt); if (data->z1 != 0) data->z1 = data->z_matrix[(int)data->y1][(int)data->x1] * (data->z_alt); x *= data->zoom; y *= data->zoom; data->x1 *= data->zoom; data->y1 *= data->zoom; get_color(data); if (data->camera == 1) { isometric(&x, &y, data->z, data); isometric(&data->x1, &data->y1, data->z1, data); } draw_lines(x, y, data); } void draw_lines(float x, float y, t_fdf *data) { float x_step; float y_step; int max; x += data->shift_x; y += data->shift_y; data->x1 += data->shift_x; data->y1 += data->shift_y; x_step = data->x1 - x; y_step = data->y1 - y; max = MAX1(MOD(x_step), MOD(y_step)); x_step /= max; y_step /= max; while ((int)(x - data->x1) || (int)(y - data->y1)) { mlx_pixel_put(data->mlx_ptr, data->win_ptr, x, y, data->color); x += x_step; y += y_step; } } void draw(t_fdf *data) { int x; int y; y = 0; while (y < data->height) { x = 0; while (x < data->width) { if (x < data->width - 1) { data->x1 = x + 1; data->y1 = y; bresenham(x, y, data); } if (y < data->height - 1) { data->y1 = y + 1; data->x1 = x; bresenham(x, y, data); } x++; } y++; } }
C
#include <stdio.h> int main() { double KRW, exchange_rate; printf("KRW : "); scanf_s("%lf", &KRW); printf("원/달러 환율 : "); scanf_s("%lf", &exchange_rate); printf("KRW %.2lf = USD %.2lf", KRW, KRW / exchange_rate); return 0; }
C
#include <stdio.h> #include <stdlib.h> // rand #include <time.h> // time #include <assert.h> // assert #define SUIT_NUM 2 // F6 #define NUMBER_NUM 10 // F10 #define MAX_CARD (SUIT_NUM * NUMBER_NUM) #define MAX_LINE 9 // line̐ #define MAX_MEMBER 3 // 1C̏l #define MAX_HAND 7 // D #define PLAYER1 0 // #define PLAYER2 1 // #define PLAYER_NUM 2 #define STRAIGHT_FIN_NUM 3 #define MULTI_FIN_NUM 5 #define MAX_COMMAND_LINE 10 /*--< >--*/ typedef enum { Buta, Straight, Flash, ThreeCard, StraightFlush } LineScore; typedef struct { int suit; // 0`5 int num; // 0`9 int id; // for shuffle } card_t; card_t card[MAX_CARD]; card_t *card_ptr[MAX_CARD]; card_t blank = { 6, 10, 0}; // w`̏̍ۂɒu󔒂\J[h card_t *lines[PLAYER_NUM][MAX_LINE][MAX_MEMBER]; // wƓGw̏ int lines_count[PLAYER_NUM][MAX_LINE]; // eɉ‚̃J[huĂ邩L^ card_t *hands[PLAYER_NUM][MAX_HAND]; int next_card = 0; // ̃J[hdeck牽Ԗڂ int lines_v_d[MAX_LINE]; //eł̏sL^ 0:ΐ 1:PLAYER1 2:PLAYER2 /* J[h\̒suitϐɑΉ镶o */ char suit_to_mark(int suit){ char mark[7] = "!#$%&?-"; // suit ̐ɑΉ return mark[suit]; } /* J[h\̒numϐɑΉ镶o */ char num_to_char(int num){ char c_num[11] = "0123456789-"; // num ̐ɑΉ return c_num[num]; } /* ȅs\ */ char print_v_d(int k){ char ox[4]=" 12"; return ox[k]; } /* ̏Ԃ\ */ void print_field(void){ int i, j; /* Gw̕\ */ for(j=0; j<MAX_MEMBER; j++){ for(i=0; i<MAX_LINE; i++){ printf("%c%c ", suit_to_mark( lines[PLAYER2][i][j]-> suit ), num_to_char( lines[PLAYER2][i][j]-> num) ); } printf("\n"); } for (i=0; i<MAX_LINE; i++){ printf("%c ", print_v_d( lines_v_d[i] )); } printf("\n"); /* w̕\ */ for(j=0; j<MAX_MEMBER; j++){ for(i=0; i<MAX_LINE; i++){ printf("%c%c ", suit_to_mark( lines[PLAYER1][i][j]-> suit ), num_to_char( lines[PLAYER1][i][j]-> num ) ); } printf("\n"); } /* eɔԍ\(FUP) */ for(i=0; i<MAX_LINE; i++){ printf("%d ", i); } printf("\n\n"); } /* fbN̒gׂĕ\ */ void print_deck(void){ int i; for (i=0; i<MAX_CARD; i++){ printf("%d: %d\n", card_ptr[i]-> suit, card_ptr[i]-> num); } } /* player̎D\ */ void print_hand(int player){ int i; for(i=0; i<MAX_HAND; i++){ printf("%c%c ", suit_to_mark( hands[player][i]-> suit ), num_to_char( hands[player][i]-> num ) ); } printf("\n"); } /* card̓ւ */ void swap_card(card_t **c1, card_t **c2){ card_t *tmp; tmp = *c1; *c1 = *c2; *c2 = tmp; } /* J[h̑召r */ /* 1:1 0:2 */ int is_card_greater(card_t *c1, card_t * c2){ if (c1->suit > c2->suit){ return 1; } else if( c1->suit == c2->suit){ if( c1->num > c2->num){ return 1; } else{ return 0; } } else{ return 0; } } /* J[h\[g */ void babble_sort(card_t *cards_ptr[], int size){ int i, j; for (i=0; i<size-1; i++){ for (j=i+1; j<size; j++){ if (is_card_greater(cards_ptr[i], cards_ptr[j])){ swap_card(&cards_ptr[i], &cards_ptr[j]); } } } } /* dJ[hȂ̌ */ /* 0:Ȃ 1: */ int is_repeat_card(card_t *deck[]){ int i, j; for (i=0; i<MAX_CARD-1; i++){ for (j=i+1; j<MAX_CARD; j++){ if (deck[i]-> suit == deck[j]-> suit){ if (deck[i]-> num == deck[j]-> num){ return 1; } } } } return 0; } /* 𔻒 */ /* Xg[gtbV->3J[h */ /* ->tbV->Xg[g->u^ */ LineScore line_score(card_t *line_ptr[MAX_MEMBER]){ int i; int first_suit; int first_num; first_suit = line_ptr[0]-> suit; first_num = line_ptr[0]-> num; /* Xg[gtbV */ if (line_ptr[1]-> suit == first_suit && line_ptr[1]-> num == (first_num + 1) ){ if (line_ptr[2]-> suit == first_suit && line_ptr[2]-> num == (first_num + 2) ){ return StraightFlush; } } /* 3J[h */ if (line_ptr[1]-> num == first_num ){ if (line_ptr[2]-> num == first_num ){ return ThreeCard; } } /* tbV */ if (line_ptr[1]-> suit == first_suit ){ if (line_ptr[2]-> suit == first_suit ){ return Flash; } } /* Xg[g */ if (line_ptr[1]-> num == (first_num + 1) ){ if (line_ptr[2]-> num == (first_num + 2) ){ return Straight; } } if (line_ptr[1]-> num == (first_num + 2) ){ if (line_ptr[2]-> num == (first_num + 1) ){ return Straight; } } if (line_ptr[1]-> num == (first_num - 1) ){ if (line_ptr[2]-> num == (first_num + 1) ){ return Straight; } } if (line_ptr[1]-> num == (first_num + 1) ){ if (line_ptr[2]-> num == (first_num - 1) ){ return Straight; } } if (line_ptr[1]-> num == (first_num - 2) ){ if (line_ptr[2]-> num == (first_num - 1) ){ return Straight; } } if (line_ptr[1]-> num == (first_num - 1) ){ if (line_ptr[2]-> num == (first_num - 2) ){ return Straight; } } /* Ȃ */ return Buta; } /* ǂ̐̔̕ */ /* 12苭ǂ */ /* 1:1 0:2 */ int is_line_greater(card_t *line_ptr1[MAX_MEMBER], card_t *line_ptr2[MAX_MEMBER], int player){ LineScore score[PLAYER_NUM]; int sum[PLAYER_NUM]; int i; score[0] = line_score(line_ptr1); score[1] = line_score(line_ptr2); for (i=0; i<PLAYER_NUM; i++){ sum[i] = 0; } if (score[0] > score[1]){ return 1; } else if (score[0] == score[1]){ for (i=0; i<MAX_MEMBER; i++){ sum[0] += line_ptr1[i]-> num; sum[1] += line_ptr2[i]-> num; } if (sum[0] > sum[1]){ return 1; } else if(sum[0] == sum[1]){ return player; // ŌɏovC[ } else{ return 0; } } else { return 0; } } /* z left right ̗vf̃}[W\[gs */ void m_sort(card_t *deck[], int left, int right) { int mid, i; int left_end, right_head; int tmp_pos = 0; card_t *temp[MAX_CARD]; if (left >= right) /* z̗vfЂƂ‚Ȃ */ return; mid = (left + right) / 2; m_sort(deck, left, mid); m_sort(deck, mid + 1, right); left_end = mid; right_head = mid + 1; while ( (left <= left_end) && (right_head <=right) ){ if ( deck[left]-> id < deck[right_head]-> id){ temp[tmp_pos] = deck[left]; left++; } else { temp[tmp_pos] = deck[right_head]; right_head++; } tmp_pos++; } /* Е̗vfȂȂ΁Cc͌ɂ‚ */ while (left <= left_end){ temp[tmp_pos] = deck[left]; left++; tmp_pos++; } while (right_head <=right){ temp[tmp_pos] = deck[right_head]; right_head++; tmp_pos++; } /* temp {̊i[ꏊփRs[ */ for (i = tmp_pos-1; 0<=i; i--){ deck[right] = temp[i]; right--; } } /* J[h̏ւ */ void MergeSort(card_t *deck[], int size){ m_sort(deck, 0, size-1); } /* gpJ[hɐ蓖Ă */ void init_card(card_t *deck[]){ int i, j, k; k = 0; for (i=0; i<SUIT_NUM; i++){ for (j=0; j<NUMBER_NUM; j++){ deck[k]-> suit = i; deck[k]-> num = j; k++; } } } /* eJ[hɗUCɏ]ă\[g */ void shuffle(card_t *deck[]){ int i; srand( (unsigned)time(NULL) ); for(i=0; i < MAX_CARD; i++){ deck[i]-> id = rand(); } MergeSort(deck, MAX_CARD); } /* eJ[h̍\̂ւ̃|C^[z쐬 */ void make_card_shadow(card_t deck[], card_t *shadow[], int size){ int i; for( i=0; i < size; i++){ shadow[i] = &deck[i]; } } /* iJ[h̐ݒƃVbtj */ void init_deck(card_t deck[]){ make_card_shadow(deck, card_ptr, MAX_CARD); init_card(card_ptr); shuffle(card_ptr); if ( is_repeat_card(card_ptr) ){ printf("J[hdĂ܂\n"); // for debug } } /* ̏Ԃ̏ */ void init_field(void){ int i,j; for(i=0; i<MAX_LINE; i++){ for(j=0; j<MAX_MEMBER; j++){ lines[PLAYER1][i][j] = &blank; lines[PLAYER2][i][j] = &blank; } lines_count[PLAYER1][i] = 0; lines_count[PLAYER2][i] = 0; lines_v_d[i] = 0; } } /* evC[ɏDzz */ void init_hands(void){ int i; for(i=0; i<MAX_HAND; i++){ hands[PLAYER1][i] = card_ptr[next_card]; next_card++; } for(i=0; i<MAX_HAND; i++){ hands[PLAYER2][i] = card_ptr[next_card]; next_card++; } /* e̎D̃\[g */ babble_sort(hands[PLAYER1], MAX_HAND); babble_sort(hands[PLAYER2], MAX_HAND); } /* str sep ̕؂ɕ */ /* ͍̕ő max ‚܂ */ /* ꂽe̐擪 ret ֊i[ */ /* Ԃl͕ */ int split_str(char *str, char *ret[], char sep, int max){ int col = 0; // ret[col++] = str; while (*str && col< max){ if (*str == sep){ ret[col++] = str + 1; } ++str; } return col; } /* vC[̓͂߂ */ /* ͂IꂽJ[hƗǂݎ */ /* ُ͎sele_cd, sele_ln -1 */ void get_command(int *sele_cd, int *sele_ln){ char line[MAX_COMMAND_LINE]; char *ret[2]; if (fgets(line, MAX_COMMAND_LINE, stdin) != NULL){ if (split_str(line, ret, ':', 2) == 2){ *sele_cd = atoi(ret[0]); *sele_ln = atoi(ret[1]); } else{ /* error */ *sele_cd = -1; *sele_ln = -1; } } else{ /* error */ *sele_cd = -1; *sele_ln = -1; } } /* sele_cd sele_ln ɓĂl͗LȂ̂ */ /* LF1 F0 */ int is_valid_command(int sele_cd, int sele_ln){ if (sele_cd < 0 || MAX_HAND <= sele_cd) return 0; // error if (sele_ln < 0 || MAX_LINE <= sele_ln) return 0; // error return 1; } /* linẽJ[h\[g */ void sort_line(card_t *line_ptr[MAX_MEMBER], int size){ if (size < 2) return; babble_sort(line_ptr, size); } /* IꂽJ[h card \̂ւ̎QƂĂ邩 */ /* ‚܂AJ[hQƂĂ邩̔ */ /* F1 قȂF0 */ int is_the_card(int player, int sele_cd, card_t *card){ if (hands[player][sele_cd] == card){ return 1; } return 0; } /* D̃J[hIɏo */ /* ԂlFIJ[hԍ */ int play_card(int player){ int selected_card = -1; int selected_line = -1; int i; print_hand(player); do{ printf("input [select_card : select_line]\n"); get_command(&selected_card, &selected_line); } while ( !(is_valid_command(selected_card, selected_line)) || is_the_card(player, selected_card, &blank) ); for (i=0; i<MAX_MEMBER; i++){ /* Iɋ󂫂Α} */ if ( (lines[player][selected_line][i]-> suit == 6) && (lines[player][selected_line][i]-> num == 10) ){ lines[player][selected_line][i] = hands[player][selected_card]; ++lines_count[player][selected_line]; sort_line(lines[player][selected_line], lines_count[player][selected_line]); return selected_card; } } /* 󔒂Ȃꍇ */ printf("ERROR:This line is full\n"); return play_card(player); } /* eCɂď܂ǂ */ void v_d_card_line(int player){ int i; int line; int w_l; // s(1: 0:) for (i=0; i<MAX_LINE; i++){ if ( lines_count[PLAYER1][i] == MAX_MEMBER && lines_count[PLAYER2][i] == MAX_MEMBER){ if (lines_v_d[i] == 0){ w_l = is_line_greater(lines[PLAYER1][i], lines[PLAYER2][i], player); if (w_l){ // PLAYER1Ȃ lines_v_d[i] = 1; } else { lines_v_d[i] = 2; } } } } } /* AƂ菟𔻒 */ int is_straight_win(int player){ int i; int count = 0; for (i=0; i<MAX_LINE; i++){ if (lines_v_d[i] == player+1){ count++; if (count == STRAIGHT_FIN_NUM){ return 1; } } else{ count = 0; } } return 0; } /* Q[̏s܂ǂ𔻒 */ /* eCŏK萔̏sꂽ */ int win_lose(void){ int i; int flag_finish = 0; int win_count[PLAYER_NUM] = {0, 0}; int s_fin[PLAYER_NUM] = {0, 0}; for (i=0; i<MAX_LINE; i++){ if (lines_v_d[i]==1){ win_count[PLAYER1]++; } else if(lines_v_d[i]==2){ win_count[PLAYER2]++; } } for (i=0; i<PLAYER_NUM; i++){ s_fin[i] = is_straight_win(i); } if ( (win_count[PLAYER1] == MULTI_FIN_NUM) || s_fin[PLAYER1]){ printf("\n----PLAYER1 WIN!!-------\n"); flag_finish = 1; } else if ( (win_count[PLAYER2] == MULTI_FIN_NUM) || s_fin[PLAYER2]){ printf("\n----PLAYER2 WIN!!-------\n"); flag_finish = 1; } return flag_finish; } /* ɂ鏟sƃQ[̏s̏ */ int victory_or_defeat(int player){ int flag_finish = 0; v_d_card_line(player); // eCɂď܂ǂ flag_finish = win_lose(); // Q[̏s܂ return flag_finish; // fix me } /* J[h1 */ void draw_a_card(int player, int selected_card){ if (next_card < MAX_CARD){ hands[player][selected_card] = card_ptr[next_card]; next_card++; } else { hands[player][selected_card] = &blank; } babble_sort( hands[player], MAX_HAND); } /* ԂlɎ̃vC[̐Ԃ */ int turn_chenge(int player){ return 1-player; } /* CƂȂQ[̒g */ void play_game(void){ int selected_card = 0; int player = PLAYER1; int flag_finish = 0; // gemȅs‚Ȃ 1 ɂȂ char player_name[PLAYER_NUM][10] = {"PLAYER1", "PLAYER2"}; while(!flag_finish){ printf("y%s's turnz\n", player_name[player]); print_field(); selected_card = play_card(player); // J[hvC flag_finish = victory_or_defeat(player); // 킢ŏs̊mFƏ draw_a_card(player, selected_card); // D̕[ player = turn_chenge(player); // Ԃ̌ } print_field(); } /* NCAgƂ̐ڑ */ /* wl̃vC[ڑ܂őҋ@ */ void begin_program(void){ // fix me } /* ڑĂNCAgɏI郁bZ[W */ /* \Pbg̏Is֐ */ void end_program(void){ // fix me } void test(void){ assert( is_valid_command(-1,-1) == 0 ); assert( is_valid_command(0,8) == 1 ); assert( is_valid_command(6,0) == 1 ); assert( is_valid_command(6,8) == 1 ); assert( is_valid_command(0,9) == 0 ); assert( is_valid_command(7,0) == 0 ); assert( is_valid_command(7,9) == 0 ); } int main2(void){ test(); printf("DEBUG SUCCESS\n"); } int main(void) { //begin_program(); // 쐬 init_deck(card); init_field(); init_hands(); play_game(); //end_program(); // 쐬 return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <unistd.h> #define EXT ".rle" char* getNewFilename(char *filename) { int ext_len = strlen(EXT); int fin_len = strlen(filename); char *fout_name = malloc((fin_len + ext_len + 1) * sizeof(char)); //add ".rle" plus null terminator strncpy(fout_name, filename, fin_len); strncpy(fout_name + fin_len, EXT, ext_len); fout_name[(fin_len + ext_len) * sizeof(char)] = '\0'; return fout_name; } int main(int argc, char **argv) { // argument check if (argc != 2) { fprintf(stderr, "Usage: compress_file original-file"); } // parse file char *filename = argv[1]; printf("filename: %s\n", filename); FILE *file_in; FILE *file_out; file_in = fopen(filename, "rb"); if (file_in == NULL) { perror("Failed to open file"); exit(1); } else { // we're in business char *fout_name = getNewFilename(filename); file_out = fopen(fout_name, "wb"); // TODO: use proper filename free(fout_name); // start reading file byte by byte char *buffer = malloc(sizeof(char)); char current; char next; int seq_count; // TODO: empty file case fread(buffer, sizeof(char), 1, file_in); current = *buffer; seq_count = 1; while(fread(buffer, sizeof(char), 1, file_in)) { printf("seq_count: %d | buffer: %d\n", seq_count, current); printf("buffer: %d\n", *buffer); next = *buffer; if (next == current) { seq_count++; current = next; continue; } else { // write the value printf("Writing seq_count: %d\n", seq_count); fwrite(&seq_count, 1, 1, file_out); printf("Writing current byte: %d\n", current); fwrite(&current, 1, 1, file_out); current = next; seq_count = 1; // reset seq_count } } // TODO: take care of last item printf("Writing seq_count: %d\n", seq_count); fwrite(&seq_count, 1, 1, file_out); printf("Writing current byte: %d\n", current); fwrite(&current, 1, 1, file_out); free(buffer); } fclose(file_in); fclose(file_out); return 0; }
C
#ifndef __VECTOR2_H #define __VECTOR2_H /** @defgroup vector2 vector2 * @{ * 2 Dimensional vector struct and functions * Notes: * -the funcs v2_equal and normalizeRef use epsilon. be careful. * -every vector2 func starts as "v2" * */ /** * 2 dimensional vector */ typedef struct vector2d{ float x;///<x component float y;///<y component }vector2; extern const vector2 v2_zero; extern const vector2 v2_unitX; extern const vector2 v2_unitY; extern const vector2 v2_One; //"construtors" //vector2 Vector2(float xy); vector2 Vector2(float x,float y);///<creates a vector (x,y) vector2 Vector2Copy(vector2 v);///<copies a vector //operations /**@brief check if to vector are equal. * @return 0 if different, 1 if equal */ char v2_equal(vector2 vec1,vector2 vec2); vector2 v2add (vector2 a,vector2 b);///<(a+b) add 2 vectors vector2 v2sub (vector2 a,vector2 b);///<(a-b) subtract 2 vectors void v2mulRef(vector2 *aRef,float f);///<a=(a*f) multiply given vector by f vector2 v2mul(vector2 a,float f);///<(a*f) multiply a vector by f and return result float v2_lenght_squared(vector2 v);///<find vector length squared float v2_lenght(vector2 v);///<find vector length char normalizeRef(vector2 *v);///<snaps vector length to size one /**@brief find rotated vector anti-clockwise * @param vector original vector * @param angle to rotate in degrees * @return rotated vector */ vector2 v2_rotateACW(vector2 v, float rotAng); /**@brief rotates given vector anti-clockwise * @param vector to rotate * @param angle to rotate in degrees * @return rotated vector */ void v2_rotateACWref(vector2 *v, float rotAng); /** @} end of vector2 */ #endif //__VECTOR2_H
C
#include <stdio.h> #include <math.h> #include <stdlib.h> // generate the polinomial void generatePolinomial(int *a, int k, int s, int nbits) { // a0 = secret a[0] = s; int i, max = (int)pow(2, nbits); // find the other k-1 random numbers for(i = 1; i < k; i++) { a[i] = rand() % max; } } void generatePoints(int *a, int *points, int p, int n, int k) { int i, j; int soma; // for to generate each point for(i = 0; i < n; i++) { soma = 0; // generate the point using the polinomial for(j = 0; j < k; j++) { soma += ((int)pow(i+1,j)%p * (a[j]%p)); } points[i] = soma % p; } } int lagrangeInterpolation(int *pointsX, int *pointsY, int k, int p) { double sum = 0.0; int i, j, m, n; double f; long int aux, l; l = 0; for (j = 0; j < k; j++) { aux = 1; for (m = 0; m < k; m++) { if (m != j) { // sub = xm - xj int sub = pointsX[m]-pointsX[j]; if(sub < 0) { sub += p; } // use the inverse of (xm - xj) * xm to get the interpolation in finite field aux *= pointsX[m]*euclides(sub, p); aux = aux % p; printf("%d * %d | euclides de %d - %d\n", pointsX[m], euclides(sub, p), pointsX[m], pointsX[j]); } } l += aux*pointsY[j]; printf("l = %d * %d = %d\n", aux, pointsY[j], l); l = l % p; printf("l = %d\n", l); } if(l < 0) return (int)l+p; return (int)l; } // extended euclides to get the multiplicative modular inverse int euclides(int x, int p) { int r = x, r1 = p, u = 1, u1 = 0; int rs, us, q; while(r1 != 0) { q = r/r1; rs = r; us = u; r = r1; u = u1; r1 = rs - q * r1; u1 = us - q * u; } return u; } void restoreSecret() { /* k = number of parts necessary to restore the secret p = prime used to create the finite field secret = secret to be restored pointsX, pointsY = tuple of values that represents the point (part of the secret) (pointsX, pointsY) = (x, f(x) mod p) */ int *pointsX, *pointsY; int k, i, p; int secret; printf("informe a quantidade de partes necessárias para restaurar o segredo\n"); scanf("%d", &k); pointsX = malloc(k*sizeof(int)); pointsY = malloc(k*sizeof(int)); printf("informe o primo\n"); scanf("%d", &p); printf("informe as tuplas no formato n n\n"); for(i = 0; i < k; i++) { scanf("%d %d", &pointsX[i], &pointsY[i]); } secret = lagrangeInterpolation(pointsX, pointsY, k, p); printf("%d\n", secret); } int createSecret() { /* n = parts that the secret is shared k = subset sufficient to reconstruct the secret s = secret nbits = number of bits to generate the random numbers p = prime number to make the finite field */ int n, k, s, nbits, p; // array to put random numbers to generate the polinomial int *a; int *points; printf("Informe a quantidade de partes\n"); scanf("%d", &n); printf("Informe a quantidade de partes suficientes para reconstruir o segredo\n"); scanf("%d", &k); printf("Informe o segredo\n"); scanf("%d", &s); printf("Informe o número primo\n"); scanf("%d", &p); printf("Informe a quantidade de bits para gerar o polinomio\n"); scanf("%d", &nbits); a = malloc(k*sizeof(int)); points = malloc(n*sizeof(int)); generatePolinomial(a, k, s, nbits); int j; printf("polinomio: "); for(j = 0; j < k; j++) { printf("%dx^%d ", a[j], j); } printf("\n"); generatePoints(a, points, p, n, k); int i; for(i = 0; i < n; i++) { printf("(%d, %d)\n", i+1, points[i]); } } void main() { int val; printf("1 - criar pontos\n2 - recuperar segredo\n"); scanf("%d", &val); if(val == 1) createSecret(); else if( val == 2) restoreSecret(); else return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* itoa_base.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: jprevota <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/06/16 22:50:50 by jprevota #+# #+# */ /* Updated: 2017/06/16 22:50:50 by jprevota ### ########.fr */ /* */ /* ************************************************************************** */ #include "../inc/ft_printf.h" static int ft_nb_len_imax(intmax_t n, int base) { uintmax_t nb; int nb_len; nb = n; nb_len = 0; if (n < 0) { nb_len++; nb = -n; } while (nb / base > 0) { nb_len++; nb = nb / base; } return (nb_len); } char *itoa_base_imax(intmax_t n, int base) { char *str; int nb_len; uintmax_t nb; char hex; hex = (base == 160) ? 'A' : 'a'; base = (base == 160) ? base / 10 : base; nb_len = ft_nb_len_imax(n, base); nb = (n < 0) ? -n : n; if (!(str = (char *)malloc((nb_len + 1) * sizeof(char)))) return (NULL); ft_memset(str, '\0', nb_len + 1); str[nb_len + 1] = '\0'; while (nb_len >= 0) { if (nb % base >= 10) str[nb_len] = hex + ((nb % base) - 10); else str[nb_len] = nb % base + '0'; nb = nb / base; nb_len--; } if (n < 0) str[0] = '-'; return (str); } static int ft_nb_len_uimax(uintmax_t n, int base) { uintmax_t nb; int nb_len; nb = n; nb_len = 0; while (nb / base > 0) { nb_len++; nb = nb / base; } return (nb_len); } char *itoa_base_uimax(uintmax_t n, int base) { char *str; int nb_len; uintmax_t nb; char hex; hex = (base == 160) ? 'A' : 'a'; base = (base == 160) ? base / 10 : base; nb_len = ft_nb_len_uimax(n, base); nb = n; if (!(str = (char *)malloc((nb_len + 1) * sizeof(char)))) return (NULL); ft_memset(str, '\0', nb_len + 1); str[nb_len + 1] = '\0'; while (nb_len >= 0) { if (nb % base >= 10) str[nb_len] = hex + ((nb % base) - 10); else str[nb_len] = nb % base + '0'; nb = nb / base; nb_len--; } return (str); }
C
// LevelHelpers.h - a few handy tools to ease using levels. // The important thing is the XXXPos functions, which convert // image positions from one level to another. Use these whenever // transforming positions to ensure consistent operation!! #ifndef __LEVEL_HELPERS_H #define __LEVEL_HELPERS_H #define EIGEN_DONT_ALIGN_STATICALLY True #include "eigen3/Eigen/Dense" // Set of global colours useful for drawing stuff: extern Eigen::Vector3d gavLevelColors[]; // (These are filled in in KeyFrame.cc) // What is the scale of a level? inline int LevelScale(int nLevel) { return 1 << nLevel; } // 1-D transform to level zero: inline double LevelZeroPos(double dLevelPos, int nLevel) { return (dLevelPos + 0.5) * LevelScale(nLevel) - 0.5; } // 2-D transforms to level zero: inline Eigen::Vector2d LevelZeroPos(Eigen::Vector2d &v2LevelPos, int nLevel) { Eigen::Vector2d v2Ans; v2Ans(0) = LevelZeroPos((double)v2LevelPos[0], nLevel); v2Ans(1) = LevelZeroPos((double)v2LevelPos(1), nLevel); return v2Ans; } // 1-D transform from level zero to level N: inline double LevelNPos(double dRootPos, int nLevel) { return (dRootPos + 0.5) / LevelScale(nLevel) - 0.5; } // 2-D transform from level zero to level N: inline Eigen::Vector2d LevelNPos(Eigen::Vector2d v2RootPos, int nLevel) { Eigen::Vector2d v2Ans; v2Ans(0) = LevelNPos((double)v2RootPos(0), nLevel); v2Ans(1) = LevelNPos((double)v2RootPos(1), nLevel); return v2Ans; } #endif