language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
typedef struct _inode { int id; char name[51]; char ext[5]; int address; int next_address; struct _inode * next; } inode ; typedef struct _block{ int ind; int position; struct _block * next; }block; void flush() { while (getchar() != '\n'); } void cleardisk(int disk[], int n) { for (int i = n-1; i>= 0; i--) disk[i] = 0; } void createfile(int disk[], int n, inode * first) { inode *newer = (inode*) malloc(sizeof(inode)); puts("Qual o nome do arquivo?"); scanf("%s", newer->name); flush(); puts("Qual a extensão?"); scanf("%s", newer->ext); flush(); }
C
#define _GNU_SOURCE #include <stdio.h> #include <pthread.h> #include <sched.h> const int N = 1000000; int count = 0; void *increment(void*); int main() { const int TRIALS = 10; pthread_attr_t myattr; cpu_set_t cpuset; pthread_attr_init(&myattr); CPU_ZERO(&cpuset); CPU_SET(0, &cpuset); pthread_attr_setaffinity_np(&myattr, sizeof(cpu_set_t), &cpuset); //printf("Successfully set processor affinity!\n"); pthread_t p, q; int i; int wrongs = 0; for (i = 0; i < TRIALS; i++) { printf("Trial %d\n", i); count = 0; pthread_create(&p, &myattr, increment, NULL); pthread_create(&q, &myattr, increment, NULL); pthread_join(p, NULL); pthread_join(q, NULL); if (count != 2*N) { printf("Invalid count: %d\n", count); wrongs++; } } printf("%d incorrect runs out of %d trials\n", wrongs, TRIALS); return 0; } void *increment(void *t) { int i; for (i = 0; i < N; i++) { int loc = count; loc++; count = loc; } }
C
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <errno.h> #include <umem.h> #include "./headers/project_file_check.h" void projdel_usage_fn() { printf("Usage: projdel [-f filename] project\n"); } int main(int argc,char **argv) { FILE* proj_file_ptr; // File pointer for project file FILE* temp_file_ptr; // File pointre for temporary project file char* proj_filename; // Stores project filename char* temp_filename; // Stores temporay project filename char* proj_name_user; // Stores user given project name char* proj_name_file; // Stores project name extracted from file char* proj_detail_line; // Stores the detail line to be written in temp file char* temp_detail_line; // Stores the detail line used for extracting project name char optstring[] = ":f:"; // Stores all the possible options used in projdel char optch; // Stores current option processed extern int optind; // Stores the position of the option processed int exit_status = 0; // Stores the exit value in it int f_flag = 0; // 1 -- if -f option used else 0 int temp_argc; // Temporary variable for storing argc value int match_flag = 0; // 1 -- if project name matched else 0 size_t len = 1024; // Used in getline() ssize_t readlen = 0; // Stores the returned value from getline() optind = 1; // Initializing the variable to 1 so that 1 option process start temp_argc = argc; // // Allocating space for variables proj_filename = (char*)malloc(sizeof(char)*100); temp_filename = (char*)malloc(sizeof(char)*110); proj_name_user = (char*)malloc(sizeof(char)*100); proj_name_file = (char*)malloc(sizeof(char)*100); proj_detail_line = (char*)malloc(sizeof(char)*1024); temp_detail_line = (char*)malloc(sizeof(char)*1024); // // Coomand line argument processing is done below while((optch = getopt(argc,argv,optstring)) != -1) { switch(optch) { case 'f': strcpy(proj_filename,optarg); f_flag = 1; break; case ':': printf("projdel : Option f require an argument \n"); projdel_usage_fn(); exit_status = 2; goto end; case '?': printf("projdel : Unknown option %c\n",optopt); projdel_usage_fn(); exit_status = 2; goto end; } } // Displaying error accorind to the input given on the command line if(temp_argc == 1) { printf("projdel: Invalid command-line arguments\n"); projdel_usage_fn(); exit_status = 2; goto end; } else { if(optind == (temp_argc-1)) strcpy(proj_name_user,argv[optind]); else { printf("projdel: Invalid command-line arguments\n"); projdel_usage_fn(); exit_status = 2; goto end; } } // If user have not used -f option the using default file /etc/project if(f_flag == 0) strcpy(proj_filename,"/etc/project"); // generating temporary filename strcpy(temp_filename,proj_filename); strcpy(temp_filename,".temp"); // Checking the file before using it project_file_checker(proj_filename); // Opening the project file and temporary file for future use proj_file_ptr = fopen(proj_filename,"r"); if(proj_file_ptr == NULL) { fprintf(stderr,"projdel : Error in %s : %s \n",proj_filename,strerror(errno)); exit_status = 5 ; goto end; } temp_file_ptr = fopen(temp_filename,"w"); if(temp_file_ptr == NULL) { fprintf(stderr,"projdel : Error in %s : %s \n",temp_filename,strerror(errno)); exit_status = 5 ; goto end; } // Matching and performing the task according to the output of the match readlen = getline(&temp_detail_line,&len,proj_file_ptr); while(readlen != -1) { strcpy(proj_detail_line,temp_detail_line); proj_name_file = strsep(&temp_detail_line,":"); if(strcmp(proj_name_file,proj_name_user) == 0) match_flag = 1; else fprintf(temp_file_ptr,"%s",proj_detail_line); readlen = getline(&temp_detail_line,&len,proj_file_ptr); } if(match_flag == 0) { printf("projdel : Project name \"%s\" not found in the file \"%s\"\n",proj_name_user,proj_filename); exit_status = 6; goto exit; } exit: fclose(temp_file_ptr); fclose(proj_file_ptr); if(exit_status == 0) { if(remove(proj_filename) == -1) { printf("projdel : Error in %s: %s \n",proj_filename,strerror(errno)); if(remove(temp_filename) == -1) { printf("projdel : Error in %s: %s \n",temp_filename,strerror(errno)); exit_status = 5; goto end; } exit_status = 5; goto end; } if(rename(temp_filename,proj_filename) == -1) { printf("projdel : Error in %s: %s \n",proj_filename,strerror(errno)); exit_status = 5; goto end; } } else { if(remove(temp_filename) == -1) { printf("projdel : Error in %s: %s \n",proj_filename,strerror(errno)); exit_status = 5; goto end; } } end: // free(proj_filename); // free(temp_filename); // free(proj_name_user); // free(proj_name_file); // free(temp_detail_line); // free(proj_detail_line); return exit_status; }
C
#include <stdio.h> #include <stdlib.h> /* run this program using the console pauser or add your own getch, system("pause") or input loop */ int main(int argc, char *argv[]) { int r,h,V; printf("Ban kinh\n"); scanf("%d",&r); printf("Chieu cao\n"); scanf("%d",&h); V=r*r*h*3.14; printf("The tich=%d\n",V); return 0; }
C
#include "mod.h" #include "video.h" #define FALSE 0 #define TRUE (!FALSE) /*-------------- window management declarations --------------------*/ static windowptr my_window,temp_window; static short window_count=4; /*------------------------------------------------------------------*/ void main() { my_window=opendisplay(60,10,21,window_count,NO_CURSOR|BORDER|NEWLINE ,WHITE|ON_BLUE /* data */ ,LT_CYAN|ON_BLUE /* border */ ,0x00 /* curser */ ,"wndw_mgr"); while(TRUE) { temp_window=my_window; while(temp_window->previous_window)temp_window=temp_window->previous_window; /* we now have bottom window in temp_window */ window_count=1; while(temp_window->next_window) { temp_window=temp_window->next_window; window_count++; } /* we now have top window in temp_window and number of windows in window_count */ if((window_count != (my_window->height+1) ) && (!my_window->next_window ) ) { closedisplay(my_window); my_window=opendisplay(60,10,21,window_count ,NO_CURSOR|BORDER|NEWLINE ,WHITE|ON_BLUE ,LT_CYAN|ON_BLUE ,0x00 ,"wndw_mgr"); } window_count=0; do{ position(my_window,0,window_count); displayln(my_window,"*3d *s",window_count,temp_window->title); clr_display(my_window,2); /* Erase to EOL */ temp_window=temp_window->previous_window; window_count++; }while (temp_window && (window_count <= my_window->height) ); Relinquish(-1000L); } }
C
#include "solver.h" tmatrix *newtmatrix(matrix *m) { tmatrix *tm = (tmatrix*) malloc(sizeof(struct tmatrix_s)); tm->x = m->x; tm->y = m->y; tm->matrix = (int*) malloc(sizeof(int) * m->x * m->y); int i,j; for(i = 0; i < tm->x; i++) { for( j = 0; j < tm->y; j++) { if(m->matrix[i*tm->y+j] >= 0) tm->matrix[i*tm->y+j] = 1; else tm->matrix[i*tm->y+j] = 0; } } return tm; } node *newnode(int x, int y) { node *n = (node*) malloc(sizeof(struct node_s)); n->x = x; n->y = y; n->next = 0; return n; } int findezyklus(node *n, tmatrix *m) { node *p = n; if(!nextzeilennachbar(n,m,p)) { if(!nextspaltennachbar(n,m,p)) { return 0; } } return 1; } int nextzeilennachbar(node *n, tmatrix *m, node *p) { int todo[m->x+m->y-1]; int y=0,zaehler=0; for(y=0; y < m->y; y++) { if(y == n->y) continue; if(m->matrix[n->x*m->y+y] == 1) { todo[zaehler] = y; zaehler++; } } for(y=0; y < zaehler; y++) { if(DEBUG) printf("%d,%d => Probiere %d,%d\n",n->x,n->y,n->x,todo[y]); node *new = newnode(n->x,todo[y]); if(todo[y] == p->y) { n->next = (struct node_t*) new; return 1; } int next = nextspaltennachbar(new, m, p); if(next) { n->next = (struct node_t*) new; return 1; } } return 0; } int nextspaltennachbar(node *n, tmatrix *m, node *p) { int todo[m->x+m->y-1]; int x=0,zaehler=0; for(x=0; x < m->x; x++) { if(x == n->x) continue; if(m->matrix[x*m->y+n->y] == 1) { todo[zaehler] = x; zaehler++; } } for(x=0; x < zaehler; x++) { if(DEBUG) printf("%d,%d => Probiere %d,%d\n",n->x,n->y,n->y,todo[x]); node *new = newnode(todo[x],n->y); if(todo[x] == p->x) { n->next = (struct node_t*) new; return 1; } int next = nextzeilennachbar(new, m, p); if(next) { n->next = (struct node_t*) new; return 1; } } return 0; } void cycleprint(node *n) { if(n != NULL) { printf("%2d,%2d\n",n->x,n->y); cycleprint((node*)n->next); } } int zykluskosten(node *n, problem *p, int i, int j) { if(n != NULL) { if(i%2 == 0) { i++; j += p->matrix[n->x*p->nachfrage+n->y]; return zykluskosten((node*)n->next,p,i,j); } else { i++; j -= p->matrix[n->x*p->nachfrage+n->y]; return zykluskosten((node*)n->next,p,i,j); } } return j; } int maxfluss(node *n, matrix *x, int i, int j) { if(n != NULL) { if(i%2 != 0) { i++; if(x->matrix[n->x*x->y+n->y] < j) j = x->matrix[n->x*x->y+n->y]; return maxfluss((node*)n->next,x,i,j); } else { i++; return maxfluss((node*)n->next,x,i,j); } } return j; } void aenderloesung(matrix *x, node *n, int mfluss, int i, int nu) { if(n != NULL) { if(i%2 == 0) { i++; if(x->matrix[n->x*x->y+n->y] == -1) x->matrix[n->x*x->y+n->y] = mfluss; else x->matrix[n->x*x->y+n->y] += mfluss; aenderloesung(x,(node*)n->next,mfluss,i,nu); } else { i++; if(x->matrix[n->x*x->y+n->y] == mfluss) { if(!nu) { x->matrix[n->x*x->y+n->y] = -1; nu = 1; } else if(nu) { x->matrix[n->x*x->y+n->y] = 0; } } else { x->matrix[n->x*x->y+n->y] -= mfluss; } aenderloesung(x,(node*)n->next,mfluss,i,nu); } } }
C
/******************************************************************************* -Ws8 -Itai Marienberg -Mon 20 Nov 2019 14:50:59 -Reviewer: *******************************************************************************/ #include "myprogram.h" /******************************************************************************/ int Initialize(addprint arr[]) { arr[0].print = &PrintInt; *(int*)(&arr[0].data) = 10; arr[0].add = &AddInt; arr[0].clean = &NoNeedCleaner; arr[1].print = &PrintFloat; *(float*)(&arr[1].data) = 2.6; arr[1].add = &AddFloat; arr[1].clean =&NoNeedCleaner; arr[2].data = malloc(STRING_LENGTH); if (NULL == arr[2].data) { printf("Error - fail to allocate memory"); return 0; } strcpy(arr[2].data, "Hello"); arr[2].print = &PrintString; arr[2].add = &AddString; arr[2].clean = &Cleaner; return 0; } /*****************************************************************************/ int RunProgram(addprint arr[]) { int i = 0; for ( i = 0 ; i < NUM_ELEMENTS ; ++i) { arr[i].print(arr[i].data); arr[i].add(&arr[i].data); arr[i].print(arr[i].data); arr[i].clean(arr[i].data); } return 0; } /*****************************************************************************/ int AddInt(void *data) { assert (NULL != data); *(int*)(data) += NUMBER_TO_ADD; return 0; } /*****************************************************************************/ int AddFloat(void *data) { assert (NULL != data); *(float*)(data) += NUMBER_TO_ADD; return 0; } /*****************************************************************************/ int AddString(void *data) { char buffer[BUFFER]; int count = 0; int length = 0; int x = NUMBER_TO_ADD; assert (NULL != data); length = strlen(*(char**)data); while( 0 != x) { x = x / 10; ++count; } *(char**)data = realloc(*(char**)data, length + 1 + count); if (NULL == *(char**)data) { printf("Error - fail to allocate memory"); return 0; } sprintf(buffer,"%d", NUMBER_TO_ADD); strcat(*(char**)data, buffer); return 0; } /*****************************************************************************/ int PrintInt(const void *data) { assert (NULL != (int*)(&data)); printf("int value is %d\n",*(int*)(&data)); return 0; } /*****************************************************************************/ int PrintFloat(const void *data) { assert (NULL != (float*)(&data)); printf("float value is %f\n",*(float*)(&data)); return 0; } /*****************************************************************************/ int PrintString(const void *data) { assert (NULL != (int*)(&data)); printf("%s\n",(char*)(data)); return 0; } /*****************************************************************************/ int Cleaner(void *data) { assert (NULL != (int*)(&data)); free(data); data = NULL; return 0; } /*****************************************************************************/ int NoNeedCleaner(void *data) { assert (NULL != (int*)(&data)); return 0; }
C
#include<stdio.h> #include<stdlib.h> #define MAX 10 struct Stack{ int top; int arr[MAX]; }s; void push(){ if(s.top==MAX-1){ printf("Stack is Full"); } else{ int num; printf("Enter element to be popped : "); scanf("%d",&num); s.top++; s.arr[s.top]=num; } } void pop(){ if(s.top==-1){ printf("Stack is empty"); } else{ s.top--; } } void display(){ if(s.top==-1){ printf("Stack is empty"); } else{ int i; for(i=s.top;i>=0;i--){ printf("%d\n",s.arr[i]); } } } int main(void){ s.top=-1; int option=1; while(option){ printf("1.Push\n2.Pop\n3.Display\n4.Exit"); int a; scanf("%d",&a); switch(a){ case 1: push(); break; case 2: pop(); break; case 3: display(); break; case 4: exit(0); break; } fflush(stdin); printf("Do you want to continue : 0 or 1"); scanf("%d",&option); } }
C
///////////////////////////////////////////////////////////////////////////////////////////////////// // Project Name : Automated_Gardening // // Target Board : atmega32 // // Date Created : 06-11-2017 12:56:07 // // Online Resource : www.electronicsforstudents.com // // Libraries Included : ///////////////////////////////////////////////////////////////////////////////////////////////////// #include<avr/io.h> #include<util/delay.h> #include "adc.h" //Including ADC Library #include "lcd.h" //Including LCD Library #include "pwm.h" //Including PWM Library int main() { adc_init(); //initializing the ADC lcd_init(); //initializing the LCD pwm_init(); //initializing the PWM int a,b,c; while (1) { //---------Checking the value of different sensors connected--------------------------------- a=adc_read(0); //Soil_Sensor is connected to PortA pin0 //Uncomment 'b' if you are using LM35 at Port A Pin 1 //b=adc_read(1); //LM35 is connected to POrtA pin1 //b=b*0.488; //converting value from lm35 to degree C c=read(portd,0); //taking input from PIR sensor, where PIR sensor is connected to PORTD Pin 0 //Giving two loops, i=1,2 for for(int i=1;i<=2;i++) { if(i==1) //Loop1: Water Content detection { a=adc_read(0); while(a>350) //Here 350 is the moisture content of the soil given by the soil sensor, to decide what value your soil gives, checkc it in two conditions: once when it is wet and once when it is dry { pwm(180); //For controlling the speed of water flow by motor write(portb,7,h); //Switching on the relay, which is for turning on the Power 12v Power Supply for the motor driver write(portd,6,h); //Turning the motor ON write(portd,7,l); lcd_gotoxy(0,0); //lcd_gotoxy(column,row); lcd_string("Wat."); // Means watering the plant lcd_gotoxy(0,1); lcd_num(a); a=adc_read(0); } if(a<350) //This loop is for turning of the motor and the power supplies { write(portd,6,l); //turning off the motor write(portd,7,l); write(portb,7,l); //turning off the power supply //Displaying respective messages lcd_gotoxy(0,0); //lcd_gotoxy(column,row) lcd_string("Mois"); lcd_gotoxy(0,1); lcd_num(a); a=adc_read(0); } } if(i==2) //Loop2: Observation for presence of Bird through PIR Sensor { c=read(portd,0); //Getting the value from PIR Sensor while(c==1) //Enters loop if bird is detected { write(portb,7,h); //Turns on Power supply write(portd,4,h); //Turns on Second Motor write(portd,5,l); lcd_gotoxy(12,0); lcd_string("PIR"); lcd_gotoxy(12,1); lcd_num(c); c=read(portd,0); } if(c==0) //If bird is not there, turns the motor and power supply off { write(portd,4,l); write(portd,5,l); write(portb,7,l); lcd_gotoxy(12,0); lcd_string("PIR"); lcd_gotoxy(12,1); lcd_num(c); } //CODE IF LM35 IS INTERFACED, REMOVE // AND USE //lcd_gotoxy(6,0); //lcd_string("LM35"); //lcd_gotoxy(6,1); //lcd_num(b); //lcd_gotoxy(7,1); //lcd_string(" C"); } } } }
C
#include <stdio.h> int main() { int i=1, j=1; while(i < 80*50) { printf("%c", j); i++; } return 0; }
C
/// quicksort.c ///Uses Function:quicksort(1,2) ///the quicksort algorithm to sort values and return a pointer to an array /// Function:quicksort_threaded(1) /// this function returns a sorted array pointer using thread /// Auhor Gayathri Kanagaraj /// Date 11/13/2020 /// #include <stdio.h> #include <pthread.h> #include <getopt.h> #include <string.h> #include<stdio.h> /// function int *quicksort( size_t size, const int *data ) ///Uses the quicksort algorithm above to sort the provided array of data. data is an ///array of int containing size number of values. It sorts without threading. It returns///a pointer to an array of sorted int. The function must not modify the original array.///@param size - size_t number of elements in the int array ///@param data - int pointer ///@return *int - int pointer of the sorted int array int *quicksort( size_t size, const int *data ){ int * qsort =NULL; return qsort; } ///function void *quicksort_threaded( void *args ) ///Uses the quicksort algorithm modified to be threaded. Each recursive call to ///quicksort_threaded runs as a thread. The args will be a data structure of your ///choice, but it must include the information required to perform the sort: a array of ///int and the size. (This is similar to the information required by the non-threaded ///version.) It returns a pointer to an array of sorted int cast to a void *. The function ///@param data - void pointer for the int array //@return *void - sorted int values as an void pointer void *quicksort_threaded( void *args ){ void *qsort =NULL; return qsort; } /// main.c called ./quicksort [-p] file_of_integers /// -p is an optional flag to print out the unsorted value ///Read the file, and print the unsorted value if -p given /// print out the sorted value which uses quicksort() function ///also print out the quicksort_threaded() function //@param argc -int value,will be the number of strings pointed to by argv //@param argv - character array of arguments. ///@return int - 0 on success anything else on failure. int main(int argc, const char * argv[]) { if(argc>0){ int opt = 0; int print =0; char *filename =NULL; while((opt =getopt(argc,argv,"p"))!=-1){ switch(opt){ case 'p': print =1; break; } } for(; optind<argc; optind++){ filename =malloc(sizeof(char)*strlen(argv[optind]+1); strcpy(filename,argv[optind]); } return EXIT_SUCCESS; } else{ fprintf(stderr,"Error: missing argument.\n" "./quicksort [-p] file_of_integers\n"); return EXIT_FAILURE; } }
C
/** * @file parse.c * @author your name (you@domain.com) * @brief * @version 0.1 * @date 2019-09-05 * * @copyright Copyright (c) 2019 * */ #include "parse.h" /* getopt_long stores the option index here. */ static int option_index = 0; static struct option long_options[] = { /* These options set a flag. */ {"name", no_argument, &name_flag, 1}, {"output", optional_argument, 0, 'o'}, {0, 0, 0, 0} }; int ParseCommandline(int argc , char *argv[], char **srcfile ,char **outfile) { int c ; while(1) { c = getopt_long (argc, argv, "o:", long_options, &option_index); if(c ==-1) { //printf("Usage : ./mysort [--name] [sourcefile.txt] [-o outfile.txt]"); break; //end of options } switch (c) { case 0: /* If this option set a flag, do nothing else now. */ if (long_options[option_index].flag != 0) break; case 'o': printf("-o option\n"); if (optarg) { printf ("[Output file]: %s\n", optarg); *outfile = strdup(optarg); output_flag = 1; } else printf ("Write output to stdout !\n"); break; case '?': /* getopt_long already printed an error message. */ break; default: abort (); } } if (name_flag) { puts ("--name : My name is Shreya"); return 1; } /* Print any remaining command line arguments (not options). */ if (optind < argc) { //non-option ARGV-elements while (optind < argc) { printf ("[Source file]: %s ", argv[optind]); *srcfile = argv[optind]; optind++; } putchar ('\n'); } if(output_flag == 1) { return 2; } else return 0; } int FileExistCheck(char* filename) { if( access( filename, F_OK ) != -1 ) return 1; // file exists else return 0; // file doesn't exist }
C
#include <stdio.h> #include <stdlib.h> #include "debug-state.h" #include "define.h" struct debug_state *init_debug_state() { // struct debug_state *ret = calloc(1, sizeof(struct debug_state)); struct debug_state *ret = malloc(sizeof(struct debug_state)); memset(ret, 0, sizeof(struct debug_state)); return ret; } void destroy_debug_state(struct debug_state *dbg_context) { if (dbg_context->logfile) { fclose(dbg_context->logfile); } free (dbg_context); } void add_breakpoint(struct debug_state *dbg_context, word_T val) { dbg_context->breakpoint = val; dbg_context->on = 1; } void remove_breakpoint(struct debug_state *dbg_context) { dbg_context->on = 0; } void check_breakpoint(struct debug_state *dbg_context, word_T val) { if (dbg_context) { if (dbg_context->on && !dbg_context->start_triggered && !dbg_context->stop_triggered && (dbg_context->breakpoint == val)) { printf ("breakpoint reached\n"); dbg_context->stop_triggered = 1; } } } void trigger_start(struct debug_state *dbg_context) { dbg_context->start_triggered = 1; } void untrigger_start(struct debug_state *dbg_context) { dbg_context->start_triggered = 0; } void untrigger_stop(struct debug_state *dbg_context) { dbg_context->stop_triggered = 0; } int stop_triggered(struct debug_state *dbg_context) { if (dbg_context == NULL) { return 0; } else { return dbg_context->stop_triggered; } } int should_write(struct state *context, struct debug_state *dbg_context) { return !context->crashed && !stop_triggered(dbg_context); } int should_write_with_check(struct state *context, struct debug_state *dbg_context, word_T loc) { check_breakpoint(dbg_context, loc); return !context->crashed && !stop_triggered(dbg_context); }
C
#include <stdio.h> #include <stdlib.h> int rotateArray(int *a,int d,int n){ for(int i=0;i<d;i++) leftRotatebyOne(a,n); } int leftRotatebyOne(int *a,int n){ int temp=a[0],i; for(i=0;i<n-1;i++) a[i]=a[i+1]; a[i]=temp; } int main() { int a[10]; int d=3,n=5; // scanf("%d %d",&n,&d); for(int i=0;i<n;i++){ scanf("%d",&a[i]); } rotateArray(a,d,n); for(int i=0;i<n;i++){ printf(" %d ",a[i]); } return 0; }
C
/****************************************************************************** * @File: eeprom.c * @Author: Milandr, L. * @Project: Demo_Project_12-1 * @Version: 1.0.0 * @Compiler: ARM Compiler V5.06 (build 750) * @Microcontroller: К1986ВЕ92QI * @Device: Отладочная плата «МилКиТЭС» * @Date: 16.04.2020 * @Purpose: Функции работы с микросхемой памяти 25LCXXX (Microchip) * @Description: * Адресное пространство микросхемы 25LCXXX разбито на страницы. При чтении или * записи данных используется автоинкремент адреса, но при переходе адреса на * другую физическую страницу должен быть начат новый цикл чтения/записи. Такой * механизм автоматизирован в функциях данного файла. ******************************************************************************/ // Подключение заголовка #include "eeprom.h" // Чтение регистра состояний uint8_t EEPROM_ReadStatus(void) { // Принятые данные uint8_t rx_data; // Активация линии CS SPI_CS_LOW; // Передача инструкции чтения регистра состояний SPI_RW(EEPROM_RDSR); // Приём данных rx_data = SPI_RW(0xAA); // Деактивация линии CS SPI_CS_HIGH; // Возврат принятых данных return rx_data; } // Разрешение записи данных void EEPROM_WriteEnable(void) { // Активация линии CS SPI_CS_LOW; // Передача инструкции разрешения записи данных SPI_RW(EEPROM_WREN); // Деактивация линии CS SPI_CS_HIGH; // Ожидание разрешения записи данных while ((EEPROM_ReadStatus() & 0x02) == false); } // Чтение данных из памяти void EEPROM_ReadData(uint32_t address, uint32_t number, uint8_t *data) { // Инициализация переменных uint32_t batch = 0; // Длина серии чтения uint32_t index = 0; // Индекс элемента в массиве // Цикл чтения данных // (состоит из серий) while (number != 0) { // Определение длины серии // Если прогнозируется переход между страницами... if (number > (address / EEPROM_PAGE_SIZE + 1) * EEPROM_PAGE_SIZE - address) { // То длина серии вычисляется как расстояние до конца страницы batch = (address / EEPROM_PAGE_SIZE + 1) * EEPROM_PAGE_SIZE - address; } // Иначе... else { // Длина серии равна длине цикла batch = number; } // Вычитание длины серии // из общего кол-ва читаемых данных number -= batch; // Активация линии CS SPI_CS_LOW; // Передача инструкции чтения SPI_RW(EEPROM_READ); // Передача адреса SPI_RW(address >> 8); // Старшие 8 бит SPI_RW(address & 0x00FF); // Младшие 8 бит // Серия чтения данных for (uint32_t i = 0; i < batch; i++, index++, address++) { *(data + index) = SPI_RW(0x00); } // Деактивация линии CS SPI_CS_HIGH; } } // Запись данных в память void EEPROM_WriteData(uint32_t address, uint32_t number, uint8_t *data) { // Инициализация переменных uint32_t batch = 0; // Длина серии записи uint32_t index = 0; // Индекс элемента в массиве // Цикл записи данных // (состоит из серий) while (number != 0) { // Определение длины серии // Если прогнозируется переход между страницами... if (number > (address / EEPROM_PAGE_SIZE + 1) * EEPROM_PAGE_SIZE - address) { // То длина серии вычисляется как расстояние до конца страницы batch = (address / EEPROM_PAGE_SIZE + 1) * EEPROM_PAGE_SIZE - address; } // Иначе... else { // Длина серии равна длине цикла batch = number; } // Вычитание длины серии // из общего кол-ва записываемых данных number -= batch; // Разрешение записи данных EEPROM_WriteEnable(); // Активация линии CS SPI_CS_LOW; // Передача инструкции записи SPI_RW(EEPROM_WRITE); // Передача адреса SPI_RW(address >> 8); // Старшие 8 бит SPI_RW(address & 0x00FF); // Младшие 8 бит // Серия записи данных for (uint32_t i = 0; i < batch; i++, index++, address++) { SPI_RW(*(data + index)); } // Деактивация линии CS SPI_CS_HIGH; // Ожидание завершения цикла записи while ((EEPROM_ReadStatus() & 0x01) != false); } } // Стирание страницы памяти void EEPROM_ErasePage(uint16_t page) { // Адрес начала страницы uint32_t address = page * EEPROM_PAGE_SIZE; // Разрешение записи данных EEPROM_WriteEnable(); // Активация линии CS SPI_CS_LOW; // Передача инструкции записи SPI_RW(EEPROM_WRITE); // Передача адреса SPI_RW(address >> 8); // Старшие 8 бит SPI_RW(address & 0x00FF); // Младшие 8 бит // Цикл стирания данных for (uint32_t i = 0; i < EEPROM_PAGE_SIZE; i++) { SPI_RW(0x00); } // Деактивация линии CS SPI_CS_HIGH; // Ожидание завершения цикла стирания while ((EEPROM_ReadStatus() & 0x01) != false); } // Полное стирание памяти void EEPROM_EraseAll(void) { // Цикл стирания данных for (uint16_t i = 0; i < EEPROM_DENSITY / EEPROM_PAGE_SIZE; i++) { EEPROM_ErasePage(i); } }
C
#include <stdio.h> /* Generate all integer compositions * The following algorithm is from this paper: * Toufik Mansour and Ghalib Nassar * "Loop-Free Gray Code Algorithms for the Set of Compositions" * Journal of Mathematical Modelling and Algorithms December 2010, * Volume 9, Issue 4, pp 343-356 */ int main(void) { int a[100], n = 6; a[1] = 1, a[2] = n - 1; // [n] is a composition for (int pos = 1; pos > 0; ) { // a is a composition if (a[pos + 1] > 1) { ++pos; a[pos + 1] = a[pos] - 1; a[pos] = 1; } else { if (--pos > 0) { ++a[pos]; a[pos + 2] -= 1; } } } return 0; }
C
#include "pq.h" #include <stdio.h> #include <stdlib.h> /** * General description: priority queue which stores pairs * <id, priority>. Top of queue is determined by priority * (min or max depending on configuration). * * There can be only one (or zero) entry for a particular id. * * Capacity is fixed on creation. * * IDs are integers in the range [0..N-1] where N is the capacity * of the priority queue set on creation. Any values outside this * range are not valid IDs. **/ struct pq_node { double priority; //priority queue which stores pairs <id, priority>.Top of queue is determined by priority (min or max depending on configuration). int id; //IDs are integers in the range [0..N-1] where N is the capacity of the priority queue set on creation.Any values outside this range are not valid IDs. int location; //Location of the index }; typedef struct pq_node NODE; struct pq_struct{ int count; //Counting integer int min_heap; //if 1 (really non - zero), then it is a min - heap if 0, then a max - heap int capacity; //Capacity is fixed on creation. NODE **index; //Index of the heap NODE *heap; //Holds the id and priority in an array // YOU DECIDE WHAT TO PUT IN HERE TO ENCAPSULATE // A PRIORITY QUEUE! }; // YOU IMPLEMENT ALL OF THE FUNCTIONS SPECIFIED IN // pq.h BELOW! /** * Function: pq_create * Parameters: capacity - self-explanatory * min_heap - if 1 (really non-zero), then it is a min-heap * if 0, then a max-heap * * Returns: Pointer to empty priority queue with given capacity and * min/max behavior as specified. * */ PQ * pq_create(int capacity, int min_heap){ if (capacity <= 0){ exit(1); } PQ *pq = malloc(sizeof(struct pq_struct)); pq->count = 0; pq->capacity = capacity; pq->min_heap = min_heap; pq->heap = malloc(sizeof(NODE)* (pq->capacity + 1)); pq->heap[0].priority = 0; pq->heap[0].id = 0; pq->index = malloc(sizeof(NODE)* (pq->capacity)); int i; for (i = 0; i < capacity + 1; i++){ pq->index[i] = NULL; } return pq; } /** * Function: pq_free * Parameters: PQ * pq * Returns: -- * Desc: deallocates all memory associated with passed priority * queue. * */ void pq_free(PQ * pq){ free(pq->index); free(pq->heap); free(pq); } /** * Function: bubble_up * Parameters: PQ * pq : for the heap * int count : idx of element to perc-up * Returns: pq * * pq->heap[count].priority : heap contents */ PQ *bubble_up(PQ * pq, int i){ double new_priority = pq->heap[i].priority; int new_id = pq->heap[i].id; int p; p = i / 2; if (pq->min_heap != 0){ while (p >= 1 && new_priority < pq->heap[p].priority) { pq->heap[i].priority = pq->heap[p].priority; pq->heap[i].id = pq->heap[p].id; pq->index[pq->heap[p].id] = &(pq->heap[i]); i = p; p = i / 2; } } if (pq->min_heap == 0){ while (p >= 1 && new_priority > pq->heap[p].priority) { pq->heap[i].priority = pq->heap[p].priority; pq->heap[i].id = pq->heap[p].id; pq->index[pq->heap[p].id] = &(pq->heap[i]); i = p; p = i / 2; } } pq->heap[i].priority = new_priority; pq->heap[i].id = new_id; pq->index[new_id] = &(pq->heap[i]); return pq; } /** * Function: bubble_down * Parameters: PQ * pq : for the heap * int i : idx of element to perc-down * Returns: pq * * pq->heap[count].priority : heap contents */ PQ *bubble_down(PQ * pq, int i){ double old_priority; int old_id; int old_location; double new_priority; int new_id; int new_location; int p; p = min_max_child_idx(pq, i); if (pq->min_heap != 0){ while (p != -1 && pq->heap[p].priority < pq->heap[i].priority) { old_id = pq->heap[i].id; old_priority = pq->heap[i].priority; old_location = pq->heap[i].location; new_id = pq->heap[p].id; new_priority = pq->heap[p].priority; new_location = pq->heap[p].location; pq->heap[p].id = old_id; pq->heap[p].priority = old_priority; pq->heap[p].location = new_location; pq->heap[i].id = new_id; pq->heap[i].priority = new_priority; pq->heap[i].location = old_location; pq->index[new_id] = &(pq->heap[i]); pq->index[old_id] = &(pq->heap[p]); i = p; p = min_max_child_idx(pq, i); } } if (pq->min_heap == 0){ while (p != -1 && pq->heap[p].priority > pq->heap[i].priority) { old_id = pq->heap[i].id; old_priority = pq->heap[i].priority; old_location = pq->heap[i].location; new_id = pq->heap[p].id; new_priority = pq->heap[p].priority; new_location = pq->heap[p].location; pq->heap[p].id = old_id; pq->heap[p].priority = old_priority; pq->heap[p].location = new_location; pq->heap[i].id = new_id; pq->heap[i].priority = new_priority; pq->heap[i].location = old_location; pq->index[new_id] = &(pq->heap[i]); pq->index[old_id] = &(pq->heap[p]); i = p; p = min_max_child_idx(pq, i); } } return pq; } /** * Function: min_max_child_idx * Parameters: PQ * pq : for the heap * int count : idx of element * * Returns: index of smallest child or biggest child of root * (if any). * if count is a leaf, -1 is returned * * pq->heap[count].priority : heap contents */ int min_max_child_idx(PQ * pq, int count) { int left, right, min_max; left = 2 * count; right = left + 1; if (left > pq->count){ return -1; } if (left <= pq->count){ min_max = left; } if (pq->min_heap != 0){ if (right <= pq->count && pq->heap[left].priority > pq->heap[right].priority){ min_max = right; } } if (pq->min_heap == 0){ if (right <= pq->count && pq->heap[left].priority < pq->heap[right].priority){ min_max = right; } } return min_max; } /** * Function: pq_insert * Parameters: priority queue pq * id of entry to insert * priority of entry to insert * Returns: 1 on success; 0 on failure. * fails if id is out of range or * there is already an entry for id * succeeds otherwise. * * Desc: self-explanatory * * Runtime: O(log n) * */ int pq_insert(PQ * pq, int id, double priority){ if ((pq->count + 1) > pq->capacity || id >= pq->capacity || id < 0 || pq->index[id] != NULL){ return 0; } pq->count++; pq->heap[pq->count].location = pq->count; pq->heap[pq->count].priority = priority; pq->heap[pq->count].id = id; pq->index[id] = &(pq->heap[pq->count]); pq = bubble_up(pq, pq->count); pq->heap[pq->count].location = pq->count; return 1; } /** * Function: pq_change_priority * Parameters: priority queue ptr pq * element id * new_priority * Returns: 1 on success; 0 on failure * Desc: If there is an entry for the given id, its associated * priority is changed to new_priority and the data * structure is modified accordingly. * Otherwise, it is a failure (id not in pq or out of range) * Runtime: O(log n) * */ int pq_change_priority(PQ * pq, int id, double new_priority){ if (id >= pq->capacity || id < 0 || pq->index[id] == NULL || new_priority == pq->index[id]->priority){ return 0; } if ((pq->min_heap != 0 && new_priority > pq->index[id]->priority) || (pq->min_heap == 0 && new_priority < pq->index[id]->priority)){ pq->index[id]->priority = new_priority; pq = bubble_down(pq, pq->index[id]->location); } if ((pq->min_heap != 0 && new_priority < pq->index[id]->priority) || (pq->min_heap == 0 && new_priority > pq->index[id]->priority)){ pq->index[id]->priority = new_priority; pq = bubble_up(pq, pq->index[id]->location); } return 1; } /** * Function: pq_remove_by_id * Parameters: priority queue pq, * element id * Returns: 1 on success; 0 on failure * Desc: if there is an entry associated with the given id, it is * removed from the priority queue. * Otherwise the data structure is unchanged and 0 is returned. * Runtime: O(log n) * */ int pq_remove_by_id(PQ * pq, int id){ if (pq->count == 0 || id >= pq->capacity || id < 0 || pq->index[id] == NULL){ return 0; } double old_priority; int old_location; double new_priority; int new_id; if (pq->index[id] != NULL){ old_priority = pq->index[id]->priority; old_location = pq->index[id]->location; new_priority = pq->heap[pq->count].priority; new_id = pq->heap[pq->count].id; pq->heap[pq->index[id]->location].priority = new_priority; pq->heap[pq->index[id]->location].id = new_id; pq->heap[pq->count].priority = 0; pq->heap[pq->count].id = 0; pq->index[new_id]->location = old_location; pq->count--; if ((pq->min_heap != 0 && new_priority > old_priority) || (pq->min_heap == 0 && new_priority < old_priority)){ pq = bubble_down(pq, pq->index[new_id]->location); } if ((pq->min_heap != 0 && new_priority < old_priority) || (pq->min_heap == 0 && new_priority > old_priority)){ pq = bubble_up(pq, pq->index[new_id]->location); } } pq->index[id] = NULL; return 1; } /** * Function: pq_get_priority * Parameters: priority queue pq * elment id * double pointer priority ("out" param) * Returns: 1 on success; 0 on failure * Desc: if there is an entry for given id, *priority is assigned * the associated priority and 1 is returned. * Otherwise 0 is returned and *priority has no meaning. * Runtime: O(1) * */ int pq_get_priority(PQ * pq, int id, double *priority){ if (id >= pq->capacity || id < 0 || pq->index[id] == NULL){ return 0; } *priority = pq->index[id]->priority; return 1; } /** * Function: pq_delete_top * Parameters: priority queue pq * int pointers id and priority ("out" parameters) * Returns: 1 on success; 0 on failure (empty priority queue) * Desc: if queue is non-empty the "top" element is deleted and * its id and priority are stored in *id and *priority; * The "top" element will be either min or max (wrt priority) * depending on how the priority queue was configured. * * If queue is empty, 0 is returned. * * Runtime: O(log n) * * */ int pq_delete_top(PQ * pq, int *id, double *priority){ if (pq->count == 0 || id < 0){ return 0; } *id = pq->heap[1].id; *priority = pq->heap[1].priority; pq_remove_by_id(pq, pq->heap[1].id); return 1; } /** * Function: pq_peek_top * Parameters: priority queue pq * int pointers id and priority ("out" parameters) * Returns: 1 on success; 0 on failure (empty priority queue) * Desc: if queue is non-empty information about the "top" * element (id and priority) is stored in *id and *priority; * The "top" element will be either min or max (wrt priority) * depending on how the priority queue was configured. * * The priority queue itself is unchanged (contrast with * pq_delete_top).! * * If queue is empty, 0 is returned. * * Runtime: O(1) * */ int pq_peek_top(PQ * pq, int *id, double *priority){ if (pq->count < 1){ return 0; } *id = pq->heap[1].id; *priority = pq->heap[1].priority; return 1; } /** * Function: pq_capacity * Parameters: priority queue pq * Returns: capacity of priority queue (as set on creation) * Desc: see returns * * Runtime: O(1) * */ int pq_capacity(PQ * pq){ return pq->capacity; } /** * Function: pq_size * Parameters: priority queue pq * Returns: number of elements currently in queue * Desc: see above * * Runtime: O(1) */ int pq_size(PQ * pq){ return pq->count; }
C
#include<stdio.h> #include<stdlib.h> void main() { int l,s,b,t_sales,flag=0; float com; printf("enter the total number of locks\n"); scanf("%d",&l); if((l<0)||(l>70)) flag=1; printf("enter the total number of stocks\n"); scanf("%d",&s); if((s<0)||(s>80)) flag=1; printf("enter the total number of barrels\n"); scanf("%d",&b); if((b<0)||(b>90)) flag=1; if(flag==1) { printf("invalid input\n"); exit(0); } t_sales=l*45+s*30+b*25; if(t_sales<=1000) com=0.10*t_sales; else if(t_sales<1800) { com=com+0.10*1000; com=com+(0.15*(t_sales-1000)); } else if(t_sales>1800) { com=com+0.10*1000; com=com+(0.15*800); com=com+(0.20*(t_sales-1800)); } printf("total sales is %d,the commission is %f\n",t_sales,com); }
C
/* file pltrim.c */ #if !defined(COMPILE_ENVIRONMENT) #include <phone/stdcenvf.h> /* std compile environment for functions */ #endif /***********************************************/ /* pltrim(s) */ /* Trims leading non-whitespace from *s, */ /* returning s, which is not changed. */ /* For a faster version which can be used if */ /* *s is not dynamic memory later freed, see */ /* pltrimf(s). */ /***********************************************/ char *pltrim(char *s) {char *from, *to; /* skip leading blanks */ for (from = s; (*from != '\0') && isspace(*from); from++); /* copy rest of string */ for (to = s; *from != '\0'; from++) *to++ = *from; *to = '\0'; return s; }
C
#include <stdlib.h> #include <stdio.h> #include <pthread.h> #include "filterParallel.h" void applyThread(BMPImage * imageIn, BMPImage * imageOut, BoxFilter f, int tid, int numThreads) { //FILL IN. This is the work that thread #tid should do //You may find it useful to know the number of threads (numThreads) to //figure out what to do. int size; int sect; int all; int red; int blue; int green; int alpha; int x; int y; int a; int b; int fir; int las; size = ((imageOut -> norm_height + numThreads - 1) / numThreads); sect = size * tid; all = sect + size; if(all > imageOut -> norm_height){ all = imageOut -> norm_height; } for(x = sect; x < all; ++x){ for(y = 0; y < imageIn -> header.width_px; ++y){ red = 0; blue = 0; green = 0; alpha = 0; for(a = 0; a < 3; ++a){ for(b = 0; b < 3; ++b){ fir = x - 1 + a; las = y - 1 + b; if(((fir) < 0) || ((fir) >= imageOut -> norm_height) || ((las) < 0) || ((las) >= imageOut -> header.width_px)){ red = red + f.filter[a][b] * imageIn -> pixels[x][y].red; blue = blue + f.filter[a][b] * imageIn -> pixels[x][y].blue; green = green + f.filter[a][b] * imageIn -> pixels[x][y].green; alpha = alpha + f.filter[a][b] * imageIn -> pixels[x][y].alpha; }else{ red = red + f.filter[a][b] * imageIn -> pixels[fir][las].red; blue = blue + f.filter[a][b] * imageIn -> pixels[fir][las].blue; green = green + f.filter[a][b] * imageIn -> pixels[fir][las].green; alpha = alpha + f.filter[a][b] * imageIn -> pixels[fir][las].alpha; } } } red = red / f.norm; blue = blue / f.norm; green = green / f.norm; alpha = alpha / f.norm; if(red > 255){ red = 255; } if(blue > 255){ blue = 255; } if(green > 255){ green = 255; } if(alpha > 255){ alpha = 255; } if(red < 0){ red = 0; } if(blue < 0){ blue = 0; } if(green < 0){ green = 0; } if(alpha < 0){ alpha = 0; } imageOut -> pixels[x][y].red = red; imageOut -> pixels[x][y].blue = blue; imageOut -> pixels[x][y].green = green; imageOut -> pixels[x][y].alpha = alpha; } } return; } void * applyThreadWrapper(void * args) { ApplyArgs * applyArgs = (ApplyArgs *) args; fprintf(stdout, "calling thread %d\n", applyArgs->tid); applyThread(applyArgs->in, applyArgs->out, applyArgs->filter, applyArgs->tid, applyArgs->numThreads); fprintf(stdout, "finished with thread %d\n", applyArgs->tid); return NULL; } void apply(BMPImage * imageIn, BMPImage * imageOut, BoxFilter f, int numThreads) { //FILL IN: //1. create numThreads threads, that each call applyThreadWrapper //2. wait for all threads to finish //3. clean up any memory allocation you did. pthread_t * threads = malloc(sizeof(pthread_t) * numThreads); ApplyArgs * arg = malloc(sizeof(ApplyArgs) * numThreads); int x; for(x = 0; x < numThreads; ++x){ arg[x].in = imageIn; arg[x].out = imageOut; arg[x].tid = x; arg[x].numThreads = numThreads; arg[x].filter = f; pthread_create(&threads[x], NULL, applyThreadWrapper, &arg[x]); pthread_join(threads[x], NULL); } free(threads); free(arg); return; }
C
#include "monty.h" #include <stdio.h> #include <stdlib.h> #include <string.h> /** *save_things - save variables * *Return: No return */ void save_things(void) { things.stack = NULL; things.buffer = NULL; things.line_num = 0; things.value = 0; } /** *main - start of the program *@argc: count of arguments *@argv: arguments wrotes by the user * *Return: 0 is success or 1 its fail */ int main(int argc, char *argv[]) { int check = 0; FILE *fp; size_t nbytes = 0; void (*function)(stack_t **stack, unsigned int line_number); if (argc != 2) { fprintf(stderr, "USAGE: monty file\n"); exit(EXIT_FAILURE); } fp = fopen(argv[1], "r"); if (!fp) { fprintf(stderr, "Error: Can't open file %s\n", argv[1]); exit(EXIT_FAILURE); } things.fp = fp; save_things(); while ((check = getline(&things.buffer, &nbytes, things.fp)) != -1) { things.line_num++; things.data = strtok(things.buffer, "\t\n "); if (!(things.buffer[0] == '\n') && !(things.buffer[0] == '#') && things.buffer && things.data && !(things.data[0] == '#')) { things.data_num = strtok(NULL, "\t\n "); function = get_function(); function(&things.stack, things.line_num); } } free_all(); exit(EXIT_SUCCESS); }
C
#include <stdio.h> #include <stdbool.h> #include <string.h> #include "abnf.h" int est_comment(char *c, int l, char *s, int ls, void (*callback)()) { char S[] = "comment"; int i_search = 0; if (ls == 7) { while (i_search < ls && s[i_search] == S[i_search]) { i_search++; } if (i_search == ls) { callback(c, l); } } int nb = 0; int deb=0, fin=0, k = 1; if (l<2){ return(0); } if (c[0]!='(' && c[l-1]!=')') { return(0); } fin = 1; while (fin<l-1) { if (c[fin]!='(' && c[fin]!=')' ){ if (!est_ctext(c[fin])) { if (fin+1 >= l-1) { return 0; } if (!est_quoted_pair(c + sizeof(char) * fin,2,s,ls,callback)) { return 0; } else { fin++; /*On doit incrmenter de 2, mais le fin++ plus bas complte*/ } } } else { if (c[fin]== '(' && nb==0) { deb=fin; nb++; } else if (c[fin]=='(' && nb>0){ nb++; } else if (c[fin]==')') { nb--; if (nb<0) { return 0; } if (nb =0){ k=(k && est_comment (c+deb*sizeof(char), fin-deb+1, s, ls, callback) ); } } } fin++; } return k; }
C
/*********************************************************************** *Function:main *Description:this program is used to solve the problem in dup.c, dup2 is at * omic *Input:node *Output:write the sting "hello world!" to /tmp/out * **********************************************************************/ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/stat.h> #include <sys/types.h> #include <fcntl.h> #define FILENAME "/tmp/out" int main() { int fd = open(FILENAME, O_WRONLY | O_CREAT | O_TRUNC, 0600); if(fd < 0) { perror("open()"); exit(1); } dup2(fd, 1); if(fd != 1) close(fd); /*********************/ puts("hello world!"); exit(0); }
C
#include<stdio.h> #include<stdlib.h> #include<string.h> typedef struct binaryHeap{ void *h; size_t heapSize; size_t maxSize; size_t size; int (*cmp)(const void *,const void *); } heap; heap* newHeap(const size_t size,int (*cmpF)(const void *,const void *)){ const size_t maxSize=1; heap *res=(heap *)malloc(sizeof(heap)); res->h=malloc(size*(maxSize+1)); res->heapSize=0; res->maxSize=maxSize; res->size=size; res->cmp=cmpF; return res; } int isEmpty(const heap *h){ return h->heapSize==0; } void freeHeap(heap *h){ free(h->h); free(h); return; } void initHeap(heap *h){ h->heapSize=0; return; } static inline void heapFunc_swap(void * restrict a,void * restrict b,void * restrict tmp,size_t size){ memcpy(tmp,a,size); memcpy(a,b,size); memcpy(b,tmp,size); return; } void push(heap *q,const void *p){ if(q->heapSize==q->maxSize){ q->maxSize*=2; q->h=realloc(q->h,q->size*(q->maxSize+1)); } q->heapSize+=1; char *h=(char *)(q->h); int k=q->heapSize; const size_t size=q->size; int (*cmp)(const void *,const void *)=q->cmp; memcpy(h+k*size,p,size); while(k>1){ size_t parent=k/2; if(cmp(h+parent*size,h+k*size)<=0) return; heapFunc_swap(h+parent*size,h+k*size,h,size); k=parent; } return; } void pop(heap *q,void *res){ char *h=(char *)(q->h); const size_t size=q->size; if(res!=NULL) memcpy(res,h+size,size); memcpy(h+size,h+size*q->heapSize,size); q->heapSize-=1; int (*cmp)(const void *,const void *)=q->cmp; const size_t n=q->heapSize; size_t k=1; while(2*k+1<=n){ size_t next=cmp(h+2*k*size,h+(2*k+1)*size)<=0?2*k:2*k+1; if(cmp(h+k*size,h+next*size)<=0) return; heapFunc_swap(h+k*size,h+next*size,h,size); k=next; } if(2*k<=n && cmp(h+k*size,h+2*k*size)>0) heapFunc_swap(h+k*size,h+2*k*size,h,size); return; } void top(const heap *q,void *res){ memcpy(res,(char *)q->h+q->size,q->size); return; } typedef long long int int64; typedef struct edge{ int a,b; int c; } edge; typedef struct indexNode{ int index; int val; } node; int cmpNode(const void *a,const void *b){ return ((node *)a)->val-((node *)b)->val; } int cmpEdge(const void *a,const void *b){ return ((edge *)a)->c-((edge *)b)->c; } int root(int *u,int x){ if(u[x]==x) return x; return u[x]=root(u,u[x]); } int same(int *u,int x,int y){ return root(u,x)==root(u,y); } void unite(int *u,int x,int y){ x=root(u,x); y=root(u,y); if(x==y) return; u[x]=y; } void run(void){ int n; scanf("%d",&n); node *x=(node *)calloc(n,sizeof(node)); node *y=(node *)calloc(n,sizeof(node)); int i; for(i=0;i<n;i++){ int a,b; scanf("%d%d",&a,&b); x[i]=(node){i,a}; y[i]=(node){i,b}; } qsort(x,n,sizeof(node),cmpNode); qsort(y,n,sizeof(node),cmpNode); heap *h=newHeap(sizeof(edge),cmpEdge); for(i=0;i<n-1;i++){ push(h,&((edge){x[i].index,x[i+1].index,x[i+1].val-x[i].val})); push(h,&((edge){y[i].index,y[i+1].index,y[i+1].val-y[i].val})); } int cnt=0; int *u=(int *)calloc(n,sizeof(int)); for(i=0;i<n;i++) u[i]=i; int64 ans=0; for(i=0;cnt<n-1;i++){ edge e; pop(h,&e); if(same(u,e.a,e.b)) continue; unite(u,e.a,e.b); ans+=e.c; cnt++; } printf("%lld\n",ans); } int main(void){ run(); return 0; } ./Main.c: In function run: ./Main.c:128:3: warning: ignoring return value of scanf, declared with attribute warn_unused_result [-Wunused-result] scanf("%d",&n); ^ ./Main.c:134:5: warning: ignoring return value of scanf, declared with attribute warn_unused_result [-Wunused-result] scanf("%d%d",&a,&b); ^
C
#ifndef TIMERS_H #define TIMERS_H #ifndef TIMER_MAX #define TIMER_MAX 1024 #endif #define REGISTER_TIMER(TimerMax) register_timer(TimerMax, timer_controller) #define START_TIMER(Handle) start_timer(Handle, timer_controller) #define STOP_TIMER(Handle) stop_timer(Handle, timer_controller) #define TIMER_DONE(Handle) timer_done(Handle, timer_controller) #define CURRENT_TIME(Handle) get_current_timer_time(Handle, timer_controller) #define MAX_TIME(Handle) get_max_timer_time(Handle, timer_controller) #define RESET_TIMERS() reset_timers(timer_controller) #define PAUSE_TIMERS() pause_timers(timer_controller) #define RESUME_TIMERS() resume_timers(timer_controller) typedef void* CallbackData; typedef void (*TimerCallback)(CallbackData data); struct TimerHandle { i32 handle; }; struct Timer { b32 running; r64 current_time; r64 timer_max; char* name; TimerCallback callback; CallbackData callback_data; }; struct TimerController { b32 paused; Timer timers[TIMER_MAX]; i32 timer_count; }; static void reset_timers(TimerController& timer_controller) { timer_controller.paused = false; timer_controller.timer_count = 0; } static TimerHandle register_timer(r64 timer_max, TimerController& timer_controller, TimerCallback callback = nullptr, CallbackData data = nullptr) { i32 handle = timer_controller.timer_count++; timer_controller.timers[handle].current_time = 0.0f; timer_controller.timers[handle].timer_max = timer_max; timer_controller.timers[handle].callback = callback; timer_controller.timers[handle].callback_data = data; timer_controller.timers[handle].running = true; assert(timer_controller.timer_count <= TIMER_MAX); return { handle + 1 }; } static void start_timer(TimerHandle handle, TimerController& timer_controller) { timer_controller.timers[handle.handle - 1].running = true; timer_controller.timers[handle.handle - 1].current_time = 0.0f; } static void stop_timer(TimerHandle handle, TimerController& timer_controller) { timer_controller.timers[handle.handle - 1].current_time = timer_controller.timers[handle.handle - 1].timer_max; } static r64 get_current_timer_time(TimerHandle handle, TimerController& timer_controller) { return timer_controller.timers[handle.handle - 1].current_time; } static r64 get_max_timer_time(TimerHandle handle, TimerController& timer_controller) { return timer_controller.timers[handle.handle - 1].timer_max; } static b32 timer_done(TimerHandle handle, TimerController& timer_controller) { i32 real_handle = handle.handle - 1; if(real_handle < 0 || real_handle > timer_controller.timer_count) return true; return timer_controller.timers[real_handle].current_time >= timer_controller.timers[real_handle].timer_max; } static void tick_timers(TimerController& timer_controller, r64 delta_time) { if(!timer_controller.paused) { for(i32 index = 0; index < timer_controller.timer_count; index++) { Timer &timer = timer_controller.timers[index]; if(timer.running) { if(timer.current_time >= timer.timer_max) { timer.running = false; if(timer.callback) { timer.callback(timer.callback_data); timer.callback = nullptr; timer.callback_data = nullptr; } } timer.current_time += delta_time; } } } } static void pause_timers(TimerController& timer_controller) { timer_controller.paused = true; } static void resume_timers(TimerController& timer_controller) { timer_controller.paused = false; } #endif
C
#include <stdio.h> int division(int dividend, int divisor, float *rest) { float result = (float)dividend/(float)divisor; *rest = result - (int)result; return result; } void sort4(int *zahl1, int *zahl2, int *zahl3, int *zahl4) { int tmp; int zahlen[4] = {*zahl1, *zahl2, *zahl3, *zahl4}; char i, j; for( i=0; i<=3; i++ ) { for(j=i; j <=3; j++) { if(zahlen[i] > zahlen[j]) { tmp = zahlen[j]; zahlen[j] = zahlen[i]; zahlen[i] = tmp; } } } *zahl1 = zahlen[0]; *zahl2 = zahlen[1]; *zahl3 = zahlen[2]; *zahl4 = zahlen[3]; } unsigned int algorithmus(int zahl1, int zahl2) { int AB = zahl1; int CD = zahl2; while((AB > 0) && (CD > 0)) { if(AB > CD) { AB -= CD; } else { if( CD > AB) { CD -= AB; } else if( AB == CD ) { break; return AB; } } } } int main() { //Variablen int AB1=0, CD1=0; //Zahlen erkennen printf("Erste Zahl eingeben:"); scanf("%d", &AB1); printf("Zweite Zahl eingeben:"); scanf("%d", &CD1); printf("%d \n", algorithmus(AB1, CD1)); return 0; }
C
/* ************************************************************************** */ /* LE - / */ /* / */ /* ft_printf.h .:: .:/ . .:: */ /* +:+:+ +: +: +:+:+ */ /* By: mschneid <mschneid@student.le-101.fr> +:+ +: +: +:+ */ /* #+# #+ #+ #+# */ /* Created: 2018/02/15 11:58:37 by mschneid #+# ## ## #+# */ /* Updated: 2018/02/21 14:07:53 by mschneid ### #+. /#+ ###.fr */ /* / */ /* / */ /* ************************************************************************** */ #ifndef _FT_PRINTF_H # define _FT_PRINTF_H # include <stdarg.h> # include <stdio.h> # include "../libft/libft.h" # define TYPES "sSpdDioOuUxXcC%b" # define FLAGS "#0-+ " # define LENGTH "hljzL" # define C_NONE "\033[00m" # define C_BOLD "\033[01m" # define C_BLACK "\033[30m" # define C_RED "\033[31m" # define C_GREEN "\033[32m" # define C_BROWN "\033[33m" # define C_BLUE "\033[34m" # define C_MAGENTA "\033[35m" # define C_CYAN "\033[36m" # define C_GRAY "\033[37m" /* ** Flags: ** 0 - (#) alternate form ** 1 - (0) fill with 0 if width ** 2 - (-) left align output ** 3 - (+) positive sign ** 4 - ( ) space sign if plus */ /* ** Length: ** h -> h ** hh -> H ** l -> l ** ll -> L ** L -> m ** j -> j ** z -> z */ typedef struct s_output { int size; int lastgood; char *output; } t_output; typedef struct s_conversion { char flags[5]; int min_width; int precision; int precision_isset; char length; char type; void *value; char *output; int size; } t_conversion; char *ft_itoa_base(long long n, int base); char *ft_uitoa_base(unsigned long long n, int base); void ft_outputaddchar(t_output *o, char c); void ft_strstructjoin(t_conversion *a, t_output *o); void printf_process_type(t_conversion *actual); int ft_printf_start(const char **nav, va_list ap, t_output *output); int ft_printf(const char *format, ...); void ft_printf_output_align(t_conversion *a); void ft_printf_output_sign(t_conversion *a, int neg); void ft_printf_output_precision(t_conversion *a, int neg); char *ft_printf_value_hex(t_conversion *actual); char *ft_printf_value_oct(t_conversion *actual); char *ft_printf_value_int(t_conversion *actual); char *ft_printf_value_uint(t_conversion *actual); void ft_nbchar_bef(char c, int i, t_conversion *actual); void ft_nbchar_aft(char c, int i, t_conversion *actual); void printf_process_decimal(t_conversion *actual); void printf_process_u_decimal(t_conversion *actual); void printf_process_hex(t_conversion *actual); void printf_process_oct(t_conversion *actual); void printf_process_char(t_conversion *a); void printf_process_string(t_conversion *a); void printf_process_wstring(t_conversion *actual); void printf_process_pointer(t_conversion *actual); void printf_process_n(t_conversion *actual); void printf_process_b(t_conversion *actual); void struct_blank(t_conversion *ret); int parse_false(t_conversion *result); t_conversion *printf_parsing(const char **nav, va_list ap, t_output *output); int ft_wcharlen(wchar_t c); int ft_wchartostr(wchar_t c, char *str); int verify_chars(wchar_t *str, t_conversion *actual); void ft_printf_find_tag(t_output *output, char *tag, char *result); #endif
C
/* Ŀ һٷƳɼҪɼȼABCDE 90Լ90ΪA80-89ΪB70-79ΪC60-69ΪD60ΪE һ0100 һַʾɼȼ 90 A */ #include<stdio.h> int main8() { int n = 0; scanf("%d",&n); if(n < 0 || n > 100) { printf("wrong\n"); } else if(n >= 90) { printf("A\n"); } else if(n >= 80) { printf("B\n"); } else if(n >= 70) { printf("C\n"); } else if(n >= 60) { printf("D\n"); } else { printf("E\n"); } return 0; }
C
#include <stdio.h> int main(){ int a; //정수형 a를 선언 a = 10; // a에 10을 대입 printf("%d", a); //%d는 정수형을 뜻함 a를 출력 return 0; //함수를 종료하겠다; }
C
/* * TINYEXPR - Tiny recursive descent parser and evaluation engine in C * * Copyright (c) 2015-2018 Lewis Van Winkle * * http://CodePlea.com * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgement in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. */ /* COMPILE TIME OPTIONS */ /* Exponentiation associativity: For a^b^c = (a^b)^c and -a^b = (-a)^b do nothing. For a^b^c = a^(b^c) and -a^b = -(a^b) uncomment the next line.*/ /* #define TE_POW_FROM_RIGHT */ /* Logarithms For log = base 10 log do nothing For log = natural log uncomment the next line. */ /* #define TE_NAT_LOG */ #include "tinyexpr.h" #include <stdio.h> double te_interp(const char *expression, int *error) { te_expr *n = te_compile(expression, 0, 0, error); double ret; if (n) { ret = te_eval(n); te_free(n); } else { ret = NAN; } return ret; } static void pn (const te_expr *n, int depth) { int i, arity; printf("%*s", depth, ""); switch(TYPE_MASK(n->type)) { case TE_CONSTANT: printf("%f\n", n->value); break; case TE_VARIABLE: printf("bound %p\n", n->bound); break; case TE_FUNCTION0: case TE_FUNCTION1: case TE_FUNCTION2: case TE_FUNCTION3: case TE_FUNCTION4: case TE_FUNCTION5: case TE_FUNCTION6: case TE_FUNCTION7: case TE_CLOSURE0: case TE_CLOSURE1: case TE_CLOSURE2: case TE_CLOSURE3: case TE_CLOSURE4: case TE_CLOSURE5: case TE_CLOSURE6: case TE_CLOSURE7: arity = ARITY(n->type); printf("f%d", arity); for(i = 0; i < arity; i++) { printf(" %p", n->parameters[i]); } printf("\n"); for(i = 0; i < arity; i++) { pn(n->parameters[i], depth + 1); } break; } } void te_print(const te_expr *n) { pn(n, 0); }
C
/** * Reverse words in a given string */ #include <stdio.h> #include <string.h> #include <ctype.h> void custom_revert(char *str, int i, int j) { if (str == NULL || i >= j || i < 0 || j >= strlen(str)) return; while(i < j) { char tmp = str[i]; str[i] = str[j]; str[j] = tmp; i++; j--; } } void find_next_indexes(char *str, int crt, int *start, int *end) { if (str == NULL || start == NULL || end == NULL || crt < 0) return; if (crt >= strlen(str)) { *start = *end = -1; return; } int i = crt; int sz = strlen(str); while (i < sz && !isalpha(str[i])) { i++; } if (i != sz) *start = i; else { *start = *end = -1; return; } while (i < sz && isalpha(str[i])) i++; *end = i - 1; } char *reverse_words(char *sentence) { if (sentence == NULL) return NULL; int sz = strlen(sentence); int inf = 0, sup = -1; custom_revert(sentence, 0, sz - 1); while (inf >= 0) { find_next_indexes(sentence, sup + 1, &inf, &sup); custom_revert(sentence, inf, sup); } return sentence; } int main(int argc, char **argv) { printf("Test 1: ana are mere => %s\n", reverse_words(strdup("ana are mere"))); printf("Test 2: this is a beautiful story about kings and queens => %s\n", reverse_words(strdup("this is a beautiful story about kings and queens"))); return 0; }
C
#include "events.h" #include <stdio.h> #include "queue.h" void Entry(Terminal* terminal, int passsenger_id, enum Type type) { Passenger* new_passen = CreatePassenger(passsenger_id, type); InsertPassengerTerminal(terminal, new_passen); } void Abord(Terminal* terminal, int door_id) { int aborded_ids[8]; // Dirty fix! int* pointer_aborded = &aborded_ids[0]; AbordTerminalDoor(terminal, door_id, &pointer_aborded); int pod_index = terminal->doors[door_id]->pod_count - 1; printf("POD %d %d %d LOG\n", terminal->id, door_id, pod_index); for (int i = 0; i < 8; i++) { printf("%d\n", aborded_ids[i]); } } void Close(Terminal* terminal, int door_id) { CloseTerminalDoor(terminal, door_id); } void Closure(Terminal* terminal1, Terminal* terminal2) { ClosureTerminal(terminal1, terminal2); } void Laser(Terminal* terminal, int door_id, int index) { KillPerson(terminal, door_id, index); }
C
#include "clase5.h" #include "stdio.h" /** El ARRAY se pasa por referencia por que cambia el parametro actual del array porque se pasa la direccion de memoria y "cantidad " es una copia del valor original del main y no se modifica*/ int contarPares (int array[],int cantidad) { int contaPares=0; int i; /**todos los arrays comienzan en cero para que acompae los subindices del vector*/ /**si pongo "<="el ultimo elemento que va a tomar va a estar por fuera del array y va a tomar datos basura*/ for(i=0;i<cantidad;i++) { if (array[i]%2==0) { contaPares++; } } return contaPares; } /******************************************************************************************/ int buscarChar(char array[],int cantidad,char caracter ) { /**lo inicializo en -1 para que cambie el valor si es correcto o sino ya salta -1*/ int index=-1; int i; for(i=0;i<cantidad;i++) { if (array[i]==caracter) { /**Modicfico el index con "i" para que indique el valor correcto*/ index=i; /**pongo el break para que no siga iterando el resto de las cosas , asi una vez que lo encuntra ya esta*/ /**El break "Rompe la estructura repetitiva"*/ break; } } return index; }
C
#include <stdlib.h> #include <stdio.h> #include "mymalloc.h" int main(int argc, char** argv){ char* a=(char*)malloc(5); char* b=(char*)malloc(5); char* c=(char*)malloc(5); *a = 'a'; *b = 'b'; *c = 'c'; printf("a = %c, b = %c, c = %c\n", *a, *b, *c); free(a); free(a); char* t=(char*)malloc(5); *t = 't'; printf("a = %c, b = %c, c = %c, t = %c\n", *a, *b, *c, *t); return 0; }
C
#include<stdio.h> int main() { int day = 0, inputDate = 0, endFlag = 0; char *charDay[] = {"土","日","月","火","水","木","金"}; do{ printf("日付を入力して下さい。----"); if(scanf("%d", &inputDate) != 1){ scanf("%*s"); printf("値が不正です。\n"); continue; } //31より大きかったり、マイナスだったらエラー if(inputDate > 31 || inputDate <= 0){ printf("正しい日付を入力してください。\n"); continue; } day = inputDate % 7; printf("%s曜日です\n", charDay[day]); endFlag = 1; } while(endFlag == 0); }
C
#include <stdio.h> #include <stdlib.h> int main(void) { int a,b,c; scanf("%d %d %d",&a,&b,&c); printf(b*b==4*a*c ? "1\n":"0\n"); return 0; }
C
// Practice01.c /* Է ް, ū > main() Է ް, Լ Լ : int Calc(int iNum1, int iNum2) */ #include <stdio.h> //[] int iSub(int iN1, int iN2); void main() { int i1 = 0, i2 = 0; printf(" Է : "); scanf("%d %d", &i1, &i2); printf(" : %d\n", iSub(i1, i2)); } //[] int iSub(int iN1, int iN2) { if (iN1 > iN2) { return iN1 - iN2; } else if (iN2 > iN1) { return iN2 - iN1; } /*else { return NULL; }*/ } /* int Calc (int iN1, int iN2) { int iResult = 0; iResult = iN1 - iN2; // ù ° ڿ ° ڸ . if (iResult < 0) // { iResult = -iResult; // ȯ } return iResult; } */
C
/* * midi.h * * Collection of enums and struct dedicated to incoming MIDI messages * * Created on: Oct 1, 2018 * Author: S. Reynal */ #ifndef MIDI_H_ #define MIDI_H_ #define MAX_MIDI_VALUE 127.0 #define MIDICC_VALUE_OFF 0 #define MIDICC_VALUE_ON 1 /** * a struct for incoming midi messages of type NoteOn/Off */ typedef struct { int note; // 0-127 int velocity; // 0-127 } MidiNote; /* * An enum for the state machine that processes MIDI messages three by three */ typedef enum { WAITING_FOR_BYTE1, // waiting for byte #1 WAITING_FOR_BYTE2, // waiting for byte #2 WAITING_FOR_BYTE3// waiting for byte #3 } midi_receiver_state_t; /* * A collection of constants for MIDI status bytes */ #define NOTE_ON 0x90 #define NOTE_OFF 0x80 #define CONTROL_CHANGE 0xB0 #define PITCH_BEND 0xE0 #endif /* MIDI_H_ */
C
#include <stdio.h> int main (){ float K, M; scanf ("%f", &M); K = M * 3.6; printf ("%f", K); return 0; }
C
//Sharline Aparecida Vieira #include <stdio.h> #include <stdlib.h> #include <locale.h> /* 1. Escreva uma funo que computa a elevncia ab para valores a (double) e b (int) passados por parmetro (no use bibliotecas como math.h). Use a funo anterior e crie um programa que imprima todas as elevncias: 2^0, 2^1,...2^10; 3^0,...3^10;...10^10. */ int main() { setlocale(LC_ALL, ""); double elev(double, int); for(int i=2; i<=10; i++) { for(int j=0; j<=10; j++) { if(j==0){ printf("%d ^ %d = 1 \n", i, j); j++; } printf("%d ^ %d = %lf\n", i, j, elev(i, j)); } printf("\n"); } } double elev(double ba, int ex) { if(ex==0) return 1; double resul=1; do { resul*=ba; ex--; } while(ex>0); return resul; } //Sharline Aparecida Vieira
C
#include <sys/stat.h> #include <fcntl.h> #include <sys/mman.h> #include <unistd.h> #include <pthread.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <dirent.h> #include <ctype.h> #include <errno.h> #include <time.h> #include <pthread.h> #include <signal.h> #include "../libfmrec_1388/libfmrec.h" #include "libFM1388Parameter.h" //output text buffer from parameter list int generate_result(RequestPara* para_list, int para_size, char* para_string) { int i; if (NULL == para_string) { output_debug_log(true, "[FM1388 Parameter Lib--%s] Fail, para_string is NULL!\n", __func__); return -1; } if (NULL == para_list) { output_debug_log(true, "[FM1388 Parameter Lib--%s] Fail, para_list is NULL!\n", __func__); return -1; } if (0 == para_size) { output_debug_log(true, "[FM1388 Parameter Lib--%s] Fail, para_size is 0!\n", __func__); return -1; } char temp_buf[SMALL_BUFFER_SIZE + 1] = { 0 }; for (i = 0; i < para_size; i++) { memset(temp_buf, 0, (SMALL_BUFFER_SIZE + 1) * sizeof(char)); if(para_list[i].addr > 0xFFFF) snprintf(temp_buf, SMALL_BUFFER_SIZE, "0x%08X\t0x%04X\t\t%s\n", para_list[i].addr & 0xFFFFFFFF, para_list[i].value & 0xFFFF, para_list[i].comment); else snprintf(temp_buf, SMALL_BUFFER_SIZE, "0x%X\t0x%04X\t\t%s\n", para_list[i].addr & 0xFFFF, para_list[i].value & 0xFFFF, para_list[i].comment); strncat(para_string, temp_buf, SMALL_BUFFER_SIZE); } return 0; } //output text file from parameter list int generate_result_file(const char* file_path, RequestPara* para_list, int para_size) { FILE* fp_out = NULL; char* para_buffer = NULL; int i; int ret = 0; if (NULL == file_path) { output_debug_log(true, "[FM1388 Parameter Lib--%s] Fail, file_path is NULL!\n", __func__); return -1; } if (NULL == para_list) { output_debug_log(true, "[FM1388 Parameter Lib--%s] Fail, para_list is NULL!\n", __func__); return -1; } if (0 == para_size) { output_debug_log(true, "[FM1388 Parameter Lib--%s] Fail, para_size is 0!\n", __func__); return -1; } //allocate memory for parameter list int buffer_length = 10 + 1 + 6 + 2 + COMMENT_LENGTH + 2; //address + tab + value + tab + tab + comment + CRLF para_buffer = (char*)malloc(sizeof(char) * (para_size * (buffer_length + 1))); if (NULL == para_buffer) { output_debug_log(true, "[FM1388 Parameter Lib--%s] Fail, paraBuffer is NULL!\n", __func__); return -1; } memset(para_buffer, 0, sizeof(char) * (para_size * (buffer_length + 1))); if ((fp_out = fopen(file_path, "wb")) == NULL) { output_debug_log(true, "[FM1388 Parameter Lib--%s] Error open output file %s to write!\n", __func__, file_path); if (NULL != para_buffer) free(para_buffer); return -1; } ret = generate_result(para_list, para_size, para_buffer); if (0 == ret) { fwrite(para_buffer, sizeof(char), strlen(para_buffer), fp_out); } fclose(fp_out); if (NULL != para_buffer) free(para_buffer); return 0; } //parse parameter list from string buffer int parse_para(char* para_string, RequestPara* para_list, char delimiter) { int ret = 0; if (NULL == para_string) { output_debug_log(true, "[FM1388 Parameter Lib--%s] Fail, parameter buffer is NULL!\n", __func__); return -1; } if (NULL == para_list) { output_debug_log(true, "[FM1388 Parameter Lib--%s] Fail, para_list is NULL!\n", __func__); return -1; } char str_temp_line[SMALL_BUFFER_SIZE + 1]; char* temp_line_ptr = NULL; char* temp_line_ptr1 = NULL; unsigned int line_index = 0; char* temp_ptr = NULL; int field_index = 0; int string_length = strlen(para_string); long index = 0L; unsigned int listIndex = 0; char temp_buf[SMALL_BUFFER_SIZE] = { 0 }; char* line = para_string; while (index < string_length) { //get one line temp_line_ptr = strchr(line + index, '\n'); temp_line_ptr1 = strchr(line + index, '\r'); if (temp_line_ptr1 != NULL && (temp_line_ptr1 < temp_line_ptr)) temp_line_ptr = temp_line_ptr1; if(temp_line_ptr == NULL) { //deal with the case that the last line has not CRLF temp_line_ptr = line + strlen(line); } memset(str_temp_line, 0, SMALL_BUFFER_SIZE + 1); strncpy(str_temp_line, line + index, temp_line_ptr - line - index); if ((str_temp_line[0] == '#') || (str_temp_line[0] == '/')) { //skip comment line index = temp_line_ptr - line; while ((line[index] == '\n') || (line[index] == '\r')) index++; continue; } memset(&para_list[listIndex], 0, sizeof(RequestPara)); line_index = 0; //output_debug_log(true, "[FM1388 Parameter Lib--%s] str_temp_line=%s\n", __func__, str_temp_line); //check operation field if (((str_temp_line[0] == OPERATION_READ) || (str_temp_line[0] == OPERATION_WRITE)) && (str_temp_line[1] == delimiter)) { para_list[listIndex].op = str_temp_line[0]; line_index++; } //output_debug_log(true, "[FM1388 Parameter Lib--%s] line_index=%d\n", __func__, line_index); field_index = 0; while (str_temp_line[line_index] == delimiter) line_index++; //skip continuous seperator //output_debug_log(true, "[FM1388 Parameter Lib--%s] line_index111111=%d\n", __func__, line_index); temp_ptr = strchr(str_temp_line + line_index, delimiter); if (temp_ptr == NULL && (line_index < strlen(str_temp_line))) { temp_ptr = str_temp_line + strlen(str_temp_line); } while (temp_ptr != NULL) { memset(temp_buf, 0, SMALL_BUFFER_SIZE); strncpy(temp_buf, str_temp_line + line_index, temp_ptr - (str_temp_line + line_index)); //output_debug_log(true, "[FM1388 Parameter Lib--%s] field_index=%d, temp_buf=%s\n", __func__, field_index, temp_buf); if (field_index == 0) { //address para_list[listIndex].addr = strtol(temp_buf, NULL, 16); } else if (field_index == 1) { //value para_list[listIndex].value = strtol(temp_buf, NULL, 16); } else if (field_index == 2) { //comment strncpy(para_list[listIndex].comment, temp_buf, COMMENT_LENGTH); } else { //wrong output_debug_log(true, "[FM1388 Parameter Lib--%s] listIndex=%x, line_index=%d, lineLength=%d, field_index=%d, temp_buf=%s\n", __func__, listIndex, line_index, strlen(str_temp_line), field_index, temp_buf); output_debug_log(true, "[FM1388 Parameter Lib--%s] wrong format\n", __func__); } field_index++; line_index = temp_ptr - str_temp_line; while (str_temp_line[line_index] == delimiter) line_index++;//skip continuous seperator temp_ptr = strchr(str_temp_line + line_index, delimiter); if (temp_ptr == NULL && (line_index < strlen(str_temp_line))) { temp_ptr = str_temp_line + strlen(str_temp_line); } } index = temp_line_ptr - line; while ((line[index] == '\n') || (line[index] == '\r')) index++; listIndex++; } ret = listIndex; return ret; } int parse_para_file(const char* file_path, RequestPara* para_list, char delimiter) { FILE* fp_para = NULL; char* para_buffer = NULL; int ret = 0; long file_length = 0; if (NULL == file_path) { output_debug_log(true, "[FM1388 Parameter Lib--%s] Fail, file_path is NULL!\n", __func__); return -1; } if (NULL == para_list) { output_debug_log(true, "[FM1388 Parameter Lib--%s] Fail, para_list is NULL!\n", __func__); return -1; } //get file length if ((fp_para = fopen(file_path, "rb")) == NULL) { output_debug_log(true, "[FM1388 Parameter Lib--%s] Error open parameter file %s to read!\n", __func__, file_path); return -1; } fseek(fp_para, 0L, SEEK_END); file_length = ftell(fp_para); fseek(fp_para, 0L, SEEK_SET); if (0 == file_length) { output_debug_log(true, "[FM1388 Parameter Lib--%s] parameter file is empty!\n", __func__); ret = -1; goto EXIT; } para_buffer = (char*)malloc(sizeof(char) * (file_length + 1)); if (NULL == para_buffer) { output_debug_log(true, "[FM1388 Parameter Lib--%s] Fail, para_buffer is NULL!\n", __func__); ret = -1; goto EXIT; } memset(para_buffer, 0, file_length + 1); long read_len = fread(para_buffer, sizeof(char), file_length, fp_para); if (read_len != file_length) { output_debug_log(true, "[FM1388 Parameter Lib--%s] Fail, para_buffer is not completed!\n", __func__); ret = -1; goto EXIT; } //output_debug_log(true, "[FM1388 Parameter Lib--%s] got parameter string: \n%s\n", __func__, para_buffer); ret = parse_para(para_buffer, para_list, delimiter); EXIT: if (NULL != fp_para) fclose(fp_para); if (NULL != para_buffer) free(para_buffer); return ret; } //parse mode list from string buffer int parse_mode(char* mode_string, ModeInfo* mode_list, char delimiter) { int ret = 0; if (NULL == mode_string) { output_debug_log(true, "[FM1388 Parameter Lib--%s] Fail, mode buffer is NULL!\n", __func__); return -1; } if (NULL == mode_list) { output_debug_log(true, "[FM1388 Parameter Lib--%s] Fail, mode_list is NULL!\n", __func__); return -1; } char str_temp_line[LARGE_BUFFER_SIZE + 1]; char* temp_line_ptr = NULL; char* temp_line_ptr1 = NULL; unsigned int line_index = 0; char* temp_ptr = NULL; int field_index = 0; int string_length = strlen(mode_string); long index = 0L; unsigned int list_index = 0; char temp_buf[LARGE_BUFFER_SIZE] = { 0 }; char* line = mode_string; while (index < string_length) { //get one line temp_line_ptr = strchr(line + index, '\n'); temp_line_ptr1 = strchr(line + index, '\r'); if (temp_line_ptr1 != NULL && (temp_line_ptr1 < temp_line_ptr)) temp_line_ptr = temp_line_ptr1; if (temp_line_ptr == NULL) { //deal with the case that the last line has not CRLF temp_line_ptr = line + strlen(line); } memset(str_temp_line, 0, LARGE_BUFFER_SIZE + 1); strncpy(str_temp_line, line + index, temp_line_ptr - line - index); if ((str_temp_line[0] == '#') || (str_temp_line[0] == '/')) { //skip comment line index = temp_line_ptr - line; while ((line[index] == '\n') || (line[index] == '\r')) index++; continue; } memset(&mode_list[list_index], 0, sizeof(ModeInfo)); line_index = 0; //output_debug_log(true, "[FM1388 Parameter Lib--%s] str_temp_line=%s\n", __func__, str_temp_line); //output_debug_log(true, "[FM1388 Parameter Lib--%s] line_index=%d\n", __func__, line_index); //check id field field_index = 0; while (str_temp_line[line_index] == delimiter) line_index++; //skip continuous seperator while (str_temp_line[line_index] == ' ') line_index++; //skip continuous SPACE //output_debug_log(true, "[FM1388 Parameter Lib--%s] line_index111111=%d\n", __func__, line_index); temp_ptr = strchr(str_temp_line + line_index, delimiter); if (temp_ptr == NULL && (line_index < strlen(str_temp_line))) { temp_ptr = str_temp_line + strlen(str_temp_line); } while (temp_ptr != NULL) { memset(temp_buf, 0, LARGE_BUFFER_SIZE); strncpy(temp_buf, str_temp_line + line_index, temp_ptr - (str_temp_line + line_index)); //output_debug_log(true, "[FM1388 Parameter Lib--%s] field_index=%d, temp_buf=%s\n", __func__, field_index, temp_buf); if (field_index == 0) { //id mode_list[list_index].id = (unsigned char)strtol(temp_buf, NULL, 16); } else if (field_index == 1) { //path file strncpy(mode_list[list_index].path_file_name, temp_buf, MAX_NAME_LENGTH); } else if (field_index == 2) { //parameter file strncpy(mode_list[list_index].parameter_file_name, temp_buf, MAX_NAME_LENGTH); } else if (field_index == 3) { //mode name strncpy(mode_list[list_index].mode_name, temp_buf, MAX_NAME_LENGTH); } else { //wrong output_debug_log(true, "[FM1388 Parameter Lib--%s] list_index=%x, line_index=%d, line_length=%d, field_index=%d, temp_buf=%s\n", __func__, list_index, line_index, strlen(str_temp_line), field_index, temp_buf); output_debug_log(true, "[FM1388 Parameter Lib--%s] wrong format\n", __func__); } field_index++; line_index = temp_ptr - str_temp_line; while (str_temp_line[line_index] == delimiter) line_index++;//skip continuous seperator while (str_temp_line[line_index] == ' ') line_index++; //skip continuous SPACE temp_ptr = strchr(str_temp_line + line_index, delimiter); if (temp_ptr == NULL && (line_index < strlen(str_temp_line))) { temp_ptr = str_temp_line + strlen(str_temp_line); } } index = temp_line_ptr - line; while ((line[index] == '\n') || (line[index] == '\r')) index++; list_index++; } ret = list_index; return ret; } int parse_mode_file(const char* file_path, ModeInfo* mode_list, char delimiter) { FILE* fp_mode = NULL; char* mode_buffer = NULL; int ret = 0; long file_length = 0; if (NULL == file_path) { output_debug_log(true, "[FM1388 Parameter Lib--%s] Fail, file_path is NULL!\n", __func__); return -1; } if (NULL == mode_list) { output_debug_log(true, "[FM1388 Parameter Lib--%s] Fail, mode_list is NULL!\n", __func__); return -1; } //get file length if ((fp_mode = fopen(file_path, "rb")) == NULL) { output_debug_log(true, "[FM1388 Parameter Lib--%s] Error open mode config file %s to read!\n", __func__, file_path); return -1; } fseek(fp_mode, 0L, SEEK_END); file_length = ftell(fp_mode); fseek(fp_mode, 0L, SEEK_SET); //output_debug_log(true, "[FM1388 Parameter Lib--%s] file_length=%ld\n", __func__, file_length); if (0 == file_length) { output_debug_log(true, "[FM1388 Parameter Lib--%s] mode config file is empty!\n", __func__); ret = -1; goto EXIT; } mode_buffer = (char*)malloc(sizeof(char) * (file_length + 1)); if (NULL == mode_buffer) { output_debug_log(true, "[FM1388 Parameter Lib--%s] Fail, mode_buffer is NULL!\n", __func__); ret = -1; goto EXIT; } memset(mode_buffer, 0, file_length + 1); long read_len = fread(mode_buffer, sizeof(char), file_length, fp_mode); //output_debug_log(true, "[FM1388 Parameter Lib--%s] read_len=%ld\n", __func__, read_len); if (read_len != file_length) { output_debug_log(true, "[FM1388 Parameter Lib--%s] Fail, mode_buffer is not completed!\n", __func__); ret = -1; goto EXIT; } //output_debug_log(true, "[FM1388 Parameter Lib--%s] got mode string: \n%s\n", __func__, mode_buffer); ret = parse_mode(mode_buffer, mode_list, delimiter); EXIT: if (NULL != fp_mode) fclose(fp_mode); if (NULL != mode_buffer) free(mode_buffer); return ret; } int get_parameter_number(const char* file_path) { FILE* fp_para = NULL; int count = 0; char line[255] = { 0 }; if (NULL == file_path) { output_debug_log(true, "[FM1388 Parameter Lib--%s] Fail, filePath is NULL!\n", __func__); return -1; } //get file line number if ((fp_para = fopen(file_path, "rb")) == NULL) { output_debug_log(true, "[FM1388 Parameter Lib--%s] Error open parameter file %s to read!\n", __func__, file_path); return -1; } while (fgets(line, 255, fp_para) != NULL) { if ((line[0] == '#') || (line[0] == '/')) continue; count++; } if (fp_para != NULL) fclose(fp_para); return count; } //for playback & recording int parse_play_command(char* parameter_string, SPIPlay* p_spi_play) { int i = 0; char str_temp[2]; if (p_spi_play == NULL) { output_debug_log(true, "[FM1388 Parameter Lib--%s] wrong parameter, p_spi_play is NULL.\n", __func__); return -1; } if (parameter_string == NULL) { output_debug_log(true, "[FM1388 Parameter Lib--%s] wrong parameter, parameter_string is NULL.\n", __func__); return -2; } memcpy(p_spi_play, parameter_string, sizeof(SPIPlay)); str_temp[0] = p_spi_play->cChannelNum; str_temp[1] = 0; p_spi_play->cChannelNum = strtol(str_temp, NULL, 16); for(i = 0; i < (MAX_MAP_CH_NUM * 3 + 1); i++) { if(p_spi_play->strChannelMapping[i] == PLACEHOLDER) { p_spi_play->strChannelMapping[i] = 0; } } for(i = 0; i < (MAX_FILEPATH_LEN + 1); i++) { if(p_spi_play->strInputFilePath[i] == PLACEHOLDER) { p_spi_play->strInputFilePath[i] = 0; } } /* output_debug_log(true, "[FM1388 Parameter Lib--%s] p_spi_play->cOperation = %c\n", __func__, p_spi_play->cOperation); output_debug_log(true, "[FM1388 Parameter Lib--%s] p_spi_play->cCommand = %c\n", __func__, p_spi_play->cCommand); output_debug_log(true, "[FM1388 Parameter Lib--%s] p_spi_play->cChannelNum = %d\n", __func__, p_spi_play->cChannelNum); output_debug_log(true, "[FM1388 Parameter Lib--%s] p_spi_play->strChannelMapping = %s\n", __func__, p_spi_play->strChannelMapping); output_debug_log(true, "[FM1388 Parameter Lib--%s] p_spi_play->strInputFilePath = %s\n", __func__, p_spi_play->strInputFilePath); */ return ESUCCESS; } int parse_record_command(char* parameter_string, SPIRecord* p_spi_record, char* strSDCARD) { int i = 0; if (strSDCARD == NULL) { output_debug_log(true, "[FM1388 Parameter Lib--%s] wrong parameter, strSDCARD is NULL.\n", __func__); return -1; } if (p_spi_record == NULL) { output_debug_log(true, "[FM1388 Parameter Lib--%s] wrong parameter, p_spi_record is NULL.\n", __func__); return -1; } if (parameter_string == NULL) { output_debug_log(true, "[FM1388 Parameter Lib--%s] wrong parameter, parameter_string is NULL.\n", __func__); return -2; } memcpy(p_spi_record, parameter_string, sizeof(SPIRecord)); for(i = 0; i < (MAX_FILEPATH_LEN + 1); i++) { if(p_spi_record->strOutputFilePath[i] == PLACEHOLDER) { p_spi_record->strOutputFilePath[i] = 0; } } /* output_debug_log(true, "[FM1388 Parameter Lib--%s] p_spi_record->cOperation = %c\n", __func__, p_spi_record->cOperation); output_debug_log(true, "[FM1388 Parameter Lib--%s] p_spi_record->cCommand = %c\n", __func__, p_spi_record->cCommand); output_debug_log(true, "[FM1388 Parameter Lib--%s] p_spi_record->strChannelIndex = %s\n", __func__, p_spi_record->strChannelIndex); output_debug_log(true, "[FM1388 Parameter Lib--%s] p_spi_record->strOutputFilePath = %s\n", __func__, p_spi_record->strOutputFilePath); */ return ESUCCESS; } int parse_play_record_command(char* parameter_string, SPIPlayRecord* p_spi_play_record, char* strSDCARD) { int i = 0; char str_temp[2]; if (strSDCARD == NULL) { output_debug_log(true, "[FM1388 Parameter Lib--%s] wrong parameter, strSDCARD is NULL.\n", __func__); return -1; } if (p_spi_play_record == NULL) { output_debug_log(true, "[FM1388 Parameter Lib--%s] wrong parameter, p_spi_play_record is NULL.\n", __func__); return -1; } if (parameter_string == NULL) { output_debug_log(true, "[FM1388 Parameter Lib--%s] wrong parameter, parameter_string is NULL.\n", __func__); return -2; } memcpy(p_spi_play_record, parameter_string, sizeof(SPIPlayRecord)); str_temp[0] = p_spi_play_record->cChannelNum; str_temp[1] = 0; p_spi_play_record->cChannelNum = strtol(str_temp , NULL, 16); for(i = 0; i < (MAX_MAP_CH_NUM * 3 + 1); i++) { if(p_spi_play_record->strChannelMapping[i] == PLACEHOLDER) { p_spi_play_record->strChannelMapping[i] = 0; } } for(i = 0; i < (MAX_FILEPATH_LEN + 1); i++) { if(p_spi_play_record->strInputFilePath[i] == PLACEHOLDER) { p_spi_play_record->strInputFilePath[i] = 0; } } for(i = 0; i < (MAX_FILEPATH_LEN + 1); i++) { if(p_spi_play_record->strOutputFilePath[i] == PLACEHOLDER) { p_spi_play_record->strOutputFilePath[i] = 0; } } /* output_debug_log(true, "[FM1388 Parameter Lib--%s] p_spi_play_record->cOperation = %c\n", __func__, p_spi_play_record->cOperation); output_debug_log(true, "[FM1388 Parameter Lib--%s] p_spi_play_record->cCommand = %c\n", __func__, p_spi_play_record->cCommand); output_debug_log(true, "[FM1388 Parameter Lib--%s] p_spi_play_record->cChannelNum = %d\n", __func__, p_spi_play_record->cChannelNum); output_debug_log(true, "[FM1388 Parameter Lib--%s] p_spi_play_record->strChannelMapping = %s\n", __func__, p_spi_play_record->strChannelMapping); output_debug_log(true, "[FM1388 Parameter Lib--%s] p_spi_play_record->strInputFilePath = %s\n", __func__, p_spi_play_record->strInputFilePath); output_debug_log(true, "[FM1388 Parameter Lib--%s] p_spi_play_record->strChannelIndex = %s\n", __func__, p_spi_play_record->strChannelIndex); output_debug_log(true, "[FM1388 Parameter Lib--%s] p_spi_play_record->strOutputFilePath = %s\n", __func__, p_spi_play_record->strOutputFilePath); */ return ESUCCESS; } //
C
#include<stdio.h> int a = 10; void function1() { printf("\nFrom function Global a = %d\n", a); } int main(){ function1(); return 0; }
C
#include "display.h" #include "lcd.h" #include "eeprom.h" #include "eepromSubroutine.h" //sharing define statements volatile unsigned char printSwap; void display(unsigned char number) { if(number < 10) //if time is < 10 add 0. e.g. 05 write_char('0'); write_int(number); //displays value } //display general items, time, pressure, temp void screen1() { unsigned char i; //reset to line 1 of LCD, pos 0 cmd(LCD_HOME); //--------------print time------------- for(i = 2; i != -1; i--) // print HH:MM:SS { display(*(p_time + i)); if(i != 0) write_char(':'); } write_char(' '); //--------------print temperature------------- //check if temperature is negative or positive if(bmpTemp < 0) { write_char('-'); //convert negative value into a positive write_int((!INTbmpTemp) + 1); //((INTbmpTemp ^ 0xFF) & 0x7F) + 1 ); } else { //buffer space write_char(' '); //print positive value display(INTbmpTemp); } //print decimal value write_char('.'); display(bmpTemp % 100); //write temperature symbol *c write_char(0); cmd(LCD_LINE_2); //--------------print date------------- for(i = DATE; i <= YEAR; i++) // print DD:MM:YY { display(*(p_time + i)); if(i != YEAR) write_char('/'); } write_char(' '); //--------------print pressure or humidity------------- printSwap++; //reset when printSwap has been going for too long if(printSwap > SWAPRESETNUM) printSwap = 0; //if x refreshes have occured print pressure if(printSwap > SWAPLENGTH) { write_int(bmpPressure / 1000); write_int((bmpPressure % 1000) / 100); write_char('.'); display(bmpPressure % 100); } else { //print humidity write_char(' '); write_int(*(p_dht11)+2); write_string("%RH"); } write_char(' '); } //display max and min temp/% void screen2() { const char code max[] = "MAX/MIN:"; unsigned char value, i; cmd(LCD_HOME); write_string(max); for(i = tempMax; i <= humidityMin; i++) { write_char(' '); value = eepromRandomRead(0,i); display(value); if(i < 3) write_char(0); //if temperature has been printed, move to next line if(i == 2) { cmd(LCD_LINE_2); write_string(max); } //humidity max and min if(i == 3 || i == 4) { write_char('%'); } } } //display pressure void screen3() { cmd(LCD_HOME); write_string("MAX: "); write_int(eepromRandomRead(0,pressureMaxUpper)); write_int(eepromRandomRead(0,pressureMaxLower)); write_string("hPa"); cmd(LCD_LINE_2); write_string("MIN: "); write_int(eepromRandomRead(0,pressureMinUpper)); write_int(eepromRandomRead(0,pressureMinLower)); write_string("hPa"); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* math.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dgaitsgo <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2016/09/19 18:42:28 by dgaitsgo #+# #+# */ /* Updated: 2016/09/25 19:09:02 by dgaitsgo ### ########.fr */ /* */ /* ************************************************************************** */ #include "ray_trace.h" double square(double n) { return (n * n); } double largest(double a, double b) { return (a > b ? a : b); } double smallest(double a, double b) { return (a > b ? b : a); } int solve_quadratic(t_quadratic *q) { double discriminant; double e; double denom; discriminant = (q->b * q->b) - 4.0 * q->a * q->c; if (discriminant < MIN_PRECISION) return (0); e = sqrt(discriminant); denom = 2.0 * q->a; q->t1 = (-q->b - e) / denom; q->t2 = (-q->b + e) / denom; if (q->t1 > q->t2) swap(&q->t1, &q->t2); if (q->t1 < MIN_PRECISION) { if (q->t2 < MIN_PRECISION) return (0); q->t1 = q->t2; q->t2 = -1; return (-1); } return (1); }
C
#include<stdio.h> int main() { int n,j; scanf("%d",&n); printf("\n"); for(int i=1;i<=n;i++) { for(j=1;j<=n-i;j++) { printf(" "); } for(j=1;j<=2*i-1;j++) { printf(" * "); } printf("\n"); } for(int i=n;i>=1;i--) { for(j=1;j<=n-i;j++) { printf(" "); } for(j=1;j<=2*i-1;j++) { printf(" * "); } printf("\n"); } }
C
// // Created by Rasmus Nylander on 16-04-2021. // #include "LinkedList.h" #include "LinkedListInternalFunctions.h" #include <stdlib.h> #include <time.h> struct _node{ struct _node* next; void* data; }; Node* newNode(void* data){ Node *node = (Node *) malloc(sizeof(Node)); node->next = NULL; node->data = data; return node; } struct linkedList { int size; Node* head; Node* tail; int (*comparator) (void* a, void* b); }; LinkedList* newLinkedList(){ LinkedList *linkedList = (LinkedList *) malloc(sizeof(LinkedList)); linkedList->size = 0; linkedList->head = NULL; //Tail is no longer used. It is in part maintained however. //Todo: determine whether to implement tail completely or scrap it. linkedList->tail = NULL; linkedList->comparator = NULL; } bool hasComparator(LinkedList *linkedList){ return linkedList->comparator != NULL; } void setComparator(LinkedList *linkedList, int (*comparator) (void* a, void* b)){ linkedList->comparator = comparator; } /** * Returns whether the specified index is a valid index of the specified list * @param linkedList the list which the index should be validated for * @param index the index to validate * @return true if the index is valid * @author Rasmus Nylander, s205418 */ bool validIndex(LinkedList *linkedList, int index){ return index < linkedList->size && index >= 0; } void* extractData(Node* node){ if (node == NULL) return NULL; return node->data; } void* get(LinkedList* linkedList, int index){ return extractData(getNodePtr(linkedList, index)); } void* getFirst(LinkedList* linkedList){ return extractData(linkedList->head); } void* getLast(LinkedList *linkedList) { return extractData(getLastNode(linkedList)); } Node* getNodePtr(LinkedList *linkedList, int index){ Node **pNode = getNodePtrPtr(linkedList, index); if (pNode == NULL) return NULL; return *pNode; } Node** getNodePtrPtr(LinkedList *linkedList, int index){ if (!validIndex(linkedList, index)) return NULL; Node **tracer = &linkedList->head; for (int i = 0; i < index; ++i) { tracer = &(*tracer)->next; } return tracer; } Node* getLastNode(LinkedList *linkedList){ Node **tracer = &linkedList->tail; while ((*tracer) && (*tracer)->next != NULL){ tracer = &(*tracer)->next; } if(tracer != &linkedList->tail) linkedList->tail = *tracer; return *tracer; //return linkedList->tail; } bool add(LinkedList *linkedList, void* t){ Node *node = newNode(t); if (node == NULL) return false; Node *lastNode = getLastNode(linkedList); if (lastNode == NULL) return push(linkedList, t); lastNode->next = node; linkedList->size++; linkedList->tail = node; return true; } bool append(LinkedList *appendTo, LinkedList *appending){ if (appendTo->size == 0) return appendToEmpty(appendTo, appending); appendTo->size += appending->size; getLastNode(appendTo)->next = appending->head; appendTo->tail = getLastNode(appending); //Not strictly necessary free(appending); return true; } bool appendToEmpty(LinkedList *appendTo, LinkedList *appending){ appendTo->head = appending->head; appendTo->tail = appending->tail; appendTo->size = appending->size; free(appending); return true; } bool push(LinkedList *linkedList, void *t){ Node *node = newNode(t); if (node == NULL) return false; node->next = linkedList->head; linkedList->head = node; linkedList->size++; if (linkedList->size == 1) linkedList->tail = linkedList->head; return true; } void* pop(LinkedList* linkedList){ if (isEmpty(linkedList)) return NULL; Node *popped = linkedList->head; linkedList->head = linkedList->head->next; linkedList->size--; if (linkedList->size == 1) linkedList->tail = linkedList->head; void *data = popped->data; free(popped); return data; } void* poll(LinkedList* linkedList){ return getFirst(linkedList); } void* removeIndex(LinkedList *linkedList, int index){ if (!validIndex(linkedList, index)) return NULL; Node** tracer = getNodePtrPtr(linkedList, index); Node *target = *tracer; *tracer = (*tracer)->next; void *data = target->data; free(target); return data; } bool removeElement(LinkedList *linkedList, void* t){ if (!hasComparator(linkedList)) return false; bool present = false; Node **tracer = &(linkedList->head); while ((*tracer)->next != NULL) { //This could be a for loop if ( (present = (linkedList->comparator(t, (*tracer)->data)) == 0) ) break; tracer = &(*tracer)->next; } if (present){ Node* node = *tracer; //Remember the node *tracer = (*tracer)->next; //Remove the node from the linked list free(node); //Free the memory of the node linkedList->size--; } return present; } bool insert(LinkedList *linkedList, void *t){ if (linkedList->comparator == NULL) return false; Node* node = newNode(t); if (node == NULL) return false; Node **tracer = &linkedList->head; while ((*tracer != NULL) && linkedList->comparator((*tracer)->data, t) < 1){ tracer = &(*tracer)->next; } node->next = *tracer; *tracer = node; linkedList->size++; return true; } bool insertAt(LinkedList *linkedList, void *t, int index){ if (index == size(linkedList)) return add(linkedList, t); if (!validIndex(linkedList, index)) return false; Node *node = newNode(t); if (node == NULL) return false; Node **tracer = &linkedList->head; for (int i = 0; i < index; ++i) { tracer = &(*tracer)->next; } node->next = *tracer; *tracer = node; return true; } LinkedList* cutList(LinkedList *linkedList, int startIndex, int endIndex){ if (startIndex > endIndex || startIndex < 0 || endIndex >= linkedList->size) return NULL; LinkedList* newList = newLinkedList(); if (newList == NULL) return NULL; //Find the start of the new list Node** tracer = &linkedList->head, **cut; for (int i = 0; i < startIndex; ++i) { tracer = &(*tracer)->next; } newList->head = *tracer; cut = tracer; //Find the end of the new list for (int i = startIndex; i < endIndex; ++i) { tracer = &(*tracer)->next; } *cut = (*tracer)->next; newList->tail = *tracer; if (newList->tail != NULL) newList->tail->next = NULL; else newList->tail = newList->head; newList->size = endIndex - startIndex + 1; linkedList->size -= newList->size; linkedList->tail = linkedList->head; return newList; } LinkedList* cutEnd(LinkedList *linkedList, int startIndex){ return cutList(linkedList, startIndex, linkedList->size - 1); } int size(LinkedList *linkedList){ return linkedList->size; } bool interweaveLinkedList(LinkedList *into, LinkedList *linkedList){ if (linkedList == NULL || into == NULL || linkedList->size == 0) return false; Node *a = into->head, *b = linkedList->head, *aNext; while (a->next != NULL && b != NULL){ aNext = a->next; a->next = b; a = a->next; b = b->next; a->next = aNext; a = a->next; } if (b != NULL) { a->next = b; into->tail = linkedList->tail; } into->size += linkedList->size; free(linkedList); return true; } bool shuffle(LinkedList *linkedList){ int s = size(linkedList); if (s < 2) return false; time_t t; srand((unsigned) time(&t)); int swaps = s - 1; for (int i = 0; i < swaps; ++i) { swap(linkedList, i, (rand() % (s - i)) + i); } return true; } bool swapNodes(Node **a, Node **b){ if (*a == *b || (*a) == NULL || (*b) == NULL) return false; Node *temp = (*a); *a = *b; *b = temp; temp = (*a)->next; (*a)->next = (*b)->next; (*b)->next = temp; return true; } bool swap(LinkedList *linkedList, int i, int j){ if (!validIndex(linkedList, i) || !validIndex(linkedList, j)) return false; return swapNodes(getNodePtrPtr(linkedList, i), getNodePtrPtr(linkedList, j)); } bool mergeSort(LinkedList *linkedList, int startIndex, int endIndex); /** * Sorts a list bubbly! I.e. sorts a list with bubble sort. * @param linkedList the LinkedList to be sorted * @return true if the list is sorted * @author Rasmus Nylander, s205418 */ bool bubbleSort(LinkedList *linkedList); bool sort(LinkedList *linkedList){ if (!hasComparator(linkedList)) return false; if (size(linkedList) < 2) return true; //return mergeSort(linkedList, 0, size(linkedList) - 1); bubbleSort(linkedList); } bool bubbleSort(LinkedList *linkedList){ if (!hasComparator(linkedList)) return false; int listLength = size(linkedList); for (int i = 0; i < listLength; ++i) { bool hasSwapped = false; Node **tracer = &linkedList->head; for (int j = 0; j < listLength - i - 1; ++j) { if (linkedList->comparator((*tracer)->data, (*tracer)->next->data) >= 1){ swapNodes(tracer, &(*tracer)->next); hasSwapped = true; } tracer = &(*tracer)->next; } if (!hasSwapped) return true; } return true; } /**DOES NOT WORK!*/ bool mergeSorted(LinkedList *linkedList, int startIndex, int endIndex, int midPoint); bool mergeSort(LinkedList *linkedList, int startIndex, int endIndex){ if (!hasComparator(linkedList)) return false; if (endIndex - startIndex < 1) return true; int midpoint = ((endIndex - startIndex) / 2) + startIndex; mergeSort(linkedList, startIndex, midpoint); mergeSort(linkedList, midpoint + 1, endIndex); mergeSorted(linkedList, startIndex, endIndex, midpoint); return true; } bool mergeSorted(LinkedList *linkedList, int startIndex, int endIndex, int midPoint){ if (!hasComparator(linkedList)) return false; Node *startNode = getNodePtr(linkedList, startIndex); Node *midNode = getNodePtr(linkedList, midPoint + 1); while (startIndex <= midPoint && endIndex > midPoint){ Node *startNext = startNode->next; if (linkedList->comparator(midNode->data, startNode->data) < 1){ startNode->next = midNode; midNode = midNode->next; startNode->next = startNext; endIndex--; } else startIndex++; startNode = startNode->next; } if (midPoint < endIndex){ startNode->next = midNode; } return true; } bool clearList(LinkedList *linkedList){ bool changed = false; while (!isEmpty(linkedList)){ pop(linkedList); changed = true; } if (linkedList->head != NULL || linkedList->tail != NULL){ linkedList->head = NULL; linkedList->tail = NULL; changed = true; } return changed; } void destroyList(LinkedList *linkedList){ clearList(linkedList); free(linkedList); } bool isEmpty(LinkedList *linkedList){ return size(linkedList) < 1; }
C
#include <stdio.h> #include <stdlib.h> #include <time.h> int main(void){ int n; printf("%s","行列のサイズを入力してください:"); scanf("%d",&n); int A[n][n]; int B[n][n]; for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ A[i][j] = rand() % 10; B[i][j] = rand() % 10; } } int C[n][n]; double times[6]; for(int i=0;i<6;i++){ times[i] = 0; } double max_iter = 10; for(int trial=0;trial<max_iter;trial++){ for(int time=0;time<6;time++){ clock_t start,end; for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ C[i][j] = 0; } } start = clock(); if(time==0){ // i-k-j for(int i=0;i<n;i++){ for(int k=0;k<n;k++){ for(int j=0;j<n;j++){ C[i][j] += A[i][k]*B[k][j]; } } } }else if(time==1){ // i-j-k for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ for(int k=0;k<n;k++){ C[i][j] += A[i][k]*B[k][j]; } } } }else if(time==2){ // k-i-j for(int k=0;k<n;k++){ for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ C[i][j] += A[i][k]*B[k][j]; } } } }else if(time==3){ // k-j-i for(int k=0;k<n;k++){ for(int j=0;j<n;j++){ for(int i=0;i<n;i++){ C[i][j] += A[i][k]*B[k][j]; } } } }else if(time==4){ // j-i-k for(int j=0;j<n;j++){ for(int i=0;i<n;i++){ for(int k=0;k<n;k++){ C[i][j] += A[i][k]*B[k][j]; } } } }else{ // j-k-i for(int j=0;j<n;j++){ for(int k=0;k<n;k++){ for(int i=0;i<n;i++){ C[i][j] += A[i][k]*B[k][j]; } } } } end = clock(); times[time] += (double)(end-start)/CLOCKS_PER_SEC; } } for(int i=0;i<6;i++){ times[i] /= max_iter; } //printf("%.8f秒かかりました\n",(double)(end-start)/CLOCKS_PER_SEC); printf("%s-%s-%s -> %.8f秒\n","j","k","i",times[5]); printf("%s-%s-%s -> %.8f秒\n","j","i","k",times[4]); printf("%s-%s-%s -> %.8f秒\n","k","j","i",times[3]); printf("%s-%s-%s -> %.8f秒\n","k","i","j",times[2]); printf("%s-%s-%s -> %.8f秒\n","i","j","k",times[1]); printf("%s-%s-%s -> %.8f秒\n","i","k","j",times[0]); return 0; }
C
#include "littlePrime.h" #include <stdlib.h> /** * Euler fai function, fai(m) = fai(p)*fai(q),p and q are prime. fai(p^k) = p^k - p^(k-1), p is prime. * input: x, ptable * output: none * return: positive result for success, -1 if x factorization failed */ u64 funcFai(u64 x, PTable *ptable) { PFtable pf; u64 result; pf = primeFact(x, ptable); result = 1; if (pf.size == 0) return 0xffffffffffffffff; for(size_t i = 0; i < pf.size; i++) { if (pf.pftable[i].exp == 1) result *= (pf.pftable[i].fact - 1); else { result *= expu64(pf.pftable[i].fact, pf.pftable[i].exp - 1); result *= (pf.pftable[i].fact - 1); } } free(pf.pftable); return result; } /** * euler delta function, delta(m) = delta(p)*delta(q),p and q are prime. delta(p^k) = (p^(k+1) -1)/(p-1), p is prime. * delta(p) = P+1 * input: x, ptable * output: none * return: positive result for success, -1 if x factorization failed */ u64 funcDelta(u64 x, PTable *ptable) { PFtable pf; u64 result, mid, k; pf = primeFact(x, ptable); result = 1; mid = 0; if (pf.size == 0) return -1; for(size_t i = 0; i < pf.size; i++) { if (pf.pftable[i].exp == 1) result *= (pf.pftable[i].fact + 1); else { k = pf.pftable[i].exp; mid = 0; while(k) { mid += expu64(pf.pftable[i].fact, k); k--; } mid++; result *= mid; } } free(pf.pftable); return result; } /** * Real facts summation * math:Euler delta function deformation to test perfect number,delta(m)-m is the summation of m's real facts. */ u64 funcS(u64 x, PTable *ptable) { return funcDelta(x, ptable) - x; }
C
#include<stdio.h> #include<stdlib.h> typedef struct iterator_array* Iterator_A; typedef struct iterator_list* Iterator_list; typedef struct element* Element; typedef struct node* Node; struct element{ Node tree; Element next; }; struct iterator_array{ Element* array; int currentidx; int maxidx; }; struct iterator_list{ Element head; Element current; }; struct node{ Iterator_list it; int value; }; int hasMoreElements_list(Iterator_list it); Element getNextElement_list(Iterator_list it); int hasMoreElements_array(Iterator_A it); Element getNextElement_array(Iterator_A it); Iterator_A createIterator_array(int c); void createIterator_list(Node n,int c);
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_split_space.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: jwoo <jwoo@student.42seoul.kr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/08/10 13:02:52 by jwoo #+# #+# */ /* Updated: 2021/08/10 13:03:35 by jwoo ### ########.fr */ /* */ /* ************************************************************************** */ #include "minishell.h" void free_two_dimension(char **word) { int n; n = -1; while (word[++n]) { free(word[n]); word[n] = 0; } free(word); word = 0; } int factor_num(char *s) { int num; int idx; if (*s == 0) return (0); num = 0; if (ft_isspace(s[0]) == 0) num++; idx = 0; while (++idx < ft_strlen(s)) { if (ft_isspace(s[idx - 1]) == 1 && ft_isspace(s[idx]) == 0) num++; } return (num); } char **factor_len(char **factor, char *s, int factor_num) { int len; int idx; int num; idx = 0; num = 0; while (factor != 0 && num < factor_num && idx < ft_strlen(s)) { while (ft_isspace(s[idx]) == 1 && idx < ft_strlen(s)) idx++; len = 0; while (ft_isspace(s[idx]) == 0 && idx < ft_strlen(s)) { len++; idx++; } if (len != 0) { factor[num] = (char *)malloc(sizeof(char) * (len + 1)); if (factor[num] == 0) free_two_dimension(factor); num++; } } return (factor); } void factor_split(char **factor, char *s, int factor_num) { int len; int idx; int num; idx = 0; num = 0; len = 0; while (num < factor_num && idx < ft_strlen(s)) { if (ft_isspace(s[idx]) == 1) { idx++; continue ; } len = 0; while (ft_isspace(s[idx]) == 0 && idx < ft_strlen(s)) { factor[num][len] = s[idx]; len++; idx++; } factor[num][len] = '\0'; num++; } factor[num] = 0; } char **ft_split_space(char *s) { char **words; int num; if (s == 0) return (0); num = factor_num(s); words = (char **)malloc(sizeof(char *) * (num + 1)); if (!words) exit(1); if (num == 0) { words[0] = NULL; return (words); } if (factor_len(words, s, num) == 0) exit (1); factor_split(words, s, num); return (words); }
C
#include"process.h" int mainProcess(int clientFileDiscripter) { int n = 0; int fileDescriptor; /*각 메시지를 담을 변수들*/ char buf[BUFSIZE+1] = {'\0', }; char message[BUFSIZE+1] = {'\0', }; char method[BUFSIZE+1] = {'\0', }; memset(headerStruct.method, '\0', 50); memset(headerStruct.contentType, '\0', 50); headerStruct.split = 0; n = recv(clientFileDiscripter, buf, BUFSIZE-1, 0); buf[BUFSIZE] = '\0'; strcpy(message, buf); printf("%s\n", message); //메시지의 포맷이 맞는지 판단 if(isAvailableFormat(buf) == FALSE) { //bad request 반환 char header[BUFSIZE] = {'\0', }; strcpy(header, createHeader(400, "Bad Request")); push(header); response(clientFileDiscripter, buf, header); }else //포맷이 맞으면 { char* p = NULL; p = strtok(buf, " "); /*GET인지 POST인지 판단*/ if(strcmp(p, "GET") == 0) { p = strtok(NULL, " "); /*cgi요청인지 아닌지 판단*/ if(isCgi(p) == TRUE) { int fileDescriptor; int i = 0; char temp[BUFSIZE] = {'\0', }; FILE* pipe; strcpy(temp, p); for(i = 0; i < BUFSIZE; i++) { if(temp[i] == '/') { sprintf(p, "%s", temp+(i+1)); } } //cgi에 필요한 변수를 얻어온다. createRequestCgi(message); if((fileDescriptor = open(p, O_RDONLY)) < 0) { cgiProcess(clientFileDiscripter, p); }else { char header[BUFSIZE] = {'\0', }; strcpy(header, createHeader(400, "Bad Reqeust")); push(header); response(clientFileDiscripter, p, header); } }else { printf("ttttt\n"); int i = 0; char temp[BUFSIZE] = {'\0', }; strcpy(temp, p); /*uri파싱*/ for(i = 0; i < BUFSIZE; i++) { if(temp[i] == '/') { sprintf(p, "%s", temp+(i+1)); } } /*url가 존재하는지 판단*/ if(isExistFile(p) == TRUE) { char header[BUFSIZE] = {'\0', }; strcpy(header, createHeader(200, "OK")); push(header); response(clientFileDiscripter, p, header);//00헤더를 보내고 response안에서 mime헤더와 메시지를 보냄 }else { // error char header[BUFSIZE] = {'\0', }; strcpy(header, createHeader(404, "File Not Found")); push(header); response(clientFileDiscripter, p, header);//404에러 표출 } } }else if(strcmp(p, "POST") == 0) { p = strtok(NULL, " "); /*cgi인지 아닌지 판단*/ if(isCgi(p) == TRUE) { int fileDescriptor; int i = 0; char temp[BUFSIZE] = {'\0', }, header[BUFSIZE] = {'\0', }; FILE* pipe; strcpy(temp, p); for(i = 0; i < BUFSIZE; i++) { if(temp[i] == '/') { sprintf(p, "%s", temp+(i+1)); } } /*200헤더를 보냄 - 이미 iscgi에서 존재하는 파일인지 아닌지 확인 했으므로*/ strcpy(header, createHeader(200, "OK")); send(clientFileDiscripter, header, BUFSIZE, 0); createRequestCgi(message); /*cgi 데이터 전송을 위한 프로세스 실행*/ cgiProcess(clientFileDiscripter, p); close(clientFileDiscripter); }else { int i = 0; char temp[BUFSIZE] = {'\0', }; strcpy(temp, p); for(i = 0; i< BUFSIZE; i++) { if(temp[i] == '/') { sprintf(p, "%s", temp+(i+1)); } } /*URI가 존재하는지 않아는지*/ if(isExistFile(p) == TRUE) { char header[BUFSIZE] = {'\0', }; strcpy(header, createHeader(200, "OK")); push(header); response(clientFileDiscripter, p, header);//200헤더와 MIME헤더, 메시지를 보냄 }else { // 에러 메시지 char header[BUFSIZE] = {'\0', }; strcpy(header, createHeader(404, "File Not Found")); push(header); response(clientFileDiscripter, p, header); } } }else { /*포맷이 잘못되었으면 에러*/ char header[BUFSIZE] = {'\0', }; strcpy(header, createHeader(400, "Bad Request")); push(header); response(clientFileDiscripter, p, header); } } } int isAvailableFormat(char *tempMessage) { char buf[BUFSIZE] = {'\0', }; char* p = NULL; strcpy(buf, tempMessage); p = strtok(buf, " "); if(p != NULL) //빈 메시지면 { p = strtok(NULL, " "); if(p != NULL)//메소드만 존재하면 { p = strtok(NULL, " "); if(p != NULL)//메소드와 uri만 존재 { return TRUE; }else { return FALSE; } }else { return FALSE; } }else { return FALSE; } } int isCgi(char* URL) { int i = 0; char buf[BUFSIZE] = {'\0', }; char* p; struct { char* ext; char* filetype; }cgiExtensions[] = { {"cgi", "text/html"}, {0, 0} }; strcpy(buf, URL); p = strtok(buf, "."); p = strtok(NULL, " "); /* 확장자가 있는 파일일 때 cgi인지 판별*/ if(p != NULL) { for(i = 0; cgiExtensions[i].ext != 0; i++) { if(strcmp(p, cgiExtensions[i].ext) == 0) { return TRUE; } } } return FALSE; } int isExistFile(char* URL) { int fileDiscripter = 0; /*파일이 존재하는지 않하는지를 판별*/ if((fileDiscripter = open(URL, O_RDONLY)) < 0) { close(fileDiscripter); return FALSE; }else { close(fileDiscripter); return TRUE; } } char* createHeader(int code, char* phrase) { /*매개 변수를 받아 헤더 생성*/ char* buf = (char*)malloc(sizeof(char) * BUFSIZE); memset(buf,'\0', BUFSIZE); sprintf(buf, "HTTP/1.1 %d %s\r\n", code, phrase); return buf; } void response(int clientFileDescripter, char* URL, char* header) { int n = 0, i = 0; int fileDescripter = 0; char buf[BUFSIZE] = {'\0', }; char* p; struct { char* ext; char* filetype; }extensions[] = { {"gif", "image/gif"}, {"jpg", "image/jpeg"}, {"bmp", "/image/bmp"}, {"jpeg", "image/jpeg"}, {"png", "image/png"}, {"zip", "image/zip"}, {"gz", "image/gz"}, {"tar", "image/tar"}, {"html", "text/html"}, {"htm", "text/html"}, {0, 0} }; //헤더 전송 n = send(clientFileDescripter, header, BUFSIZE, 0); strcpy(buf, URL); p = strtok(buf, "."); p = strtok(NULL, " "); printf("%s\n", buf); /*MIME헤더 생성 후 전송, 메시지 바디 전송*/ for(i = 0; extensions[i].ext != 0; i++) { if(strcmp(p, extensions[i].ext) == 0) { memset(buf, '\0', BUFSIZE); sprintf(buf, "Content-type: %s; charset=ko-KR\r\n\r\n\0", extensions[i].filetype); n = send(clientFileDescripter, buf, strlen(buf), 0); memset(buf, '\0', BUFSIZE); //printf("%s\n", buf); //strcpy(buf, "\r\n"); //n = send(clientFileDescripter, buf, strlen(buf), 0); //printf("%s\n", buf); if((fileDescripter = open(URL, O_RDONLY)) >= 0) { while((n = read(fileDescripter, buf, BUFSIZE)) > 0) { send(clientFileDescripter, buf, n, 0); printf("%s\n", buf); memset(buf, '\0', BUFSIZE); } break; } } } } void createRequestCgi(char* message) { char buf[BUFSIZE] = {'\0', }; char* p; headerStruct.body = (char*)malloc(sizeof(char) * BUFSIZE); strcpy(buf, message); p = strtok(buf, " "); strcpy(headerStruct.method, p); strcpy(buf, message); /*content-type 파싱*/ p = strstr(buf, "Content-Type:"); strcpy(buf, p); p = NULL; p = strtok(buf, " "); p = strtok(NULL, " "); strcpy(headerStruct.contentType, p); strcpy(buf, message); /*content-Length 파싱*/ p = strstr(buf, "Content-Length:"); strcpy(buf, p); p = NULL; p = strtok(buf, " "); p = strtok(NULL, " \r\n"); headerStruct.contentLength = atoi(p); strcpy(buf, message); if((p = strstr(buf, "\r\n\r\n")) != NULL) { headerStruct.split = 1; strcpy(headerStruct.body, p+strlen("\r\n\r\n")); } } void cgiProcess(int fileDescriptor, char* URL) { int fd[2], fd1[2]; int n = 0; char buf[BUFSIZE] = {'\0', }; pid_t pid; fflush(stdin); fflush(stdout); if(strcmp(headerStruct.method, "GET") == 0) { //GET일 때 URI에서 QUERSTRING 파싱 char* p; char lengthBuf[BUFSIZE] = {'\0', }; sprintf(lengthBuf, "%d", headerStruct.contentLength); p = strtok(URL, "?"); strcpy(buf, p); strcpy(URL, p); p = strtok(NULL, " "); setenv("QUERY_STRING", p, 1); setenv("REQUEST_METHOD", headerStruct.method, 1); setenv("CONTENT_LENGTH", lengthBuf, 1); }else if(strcmp(headerStruct.method, "POST") == 0) { char lengthBuf[BUFSIZE] = {'\0', }; //if(headerStruct.contentLength > BUFSIZE) // headerStruct.contentLength -= strlen(headerStruct.body); sprintf(lengthBuf, "%d", headerStruct.contentLength); setenv("REQUEST_METHOD", headerStruct.method, 1); setenv("CONTENT_LENGTH", lengthBuf, 1); } pipe(fd); pipe(fd1); pid = fork(); if(pid == 0) { //파이프를 출력과 입력용 2개를 열고 CGI프로그램 실행 //파이프의 출력과 입력을 표준 입출력으로 바꿈 close(fd[1]); dup2(fd[0], 0); close(fd1[0]); dup2(fd1[1], 1); if(execl(URL, NULL) == -1) { exit(1); } }else { //파이프를 출력과 입력용 2개를 열고 CGI 필요한 정보를 넘겨줌 필요한 정보를 넘겨줌 //파이프의 출려과 입력을 표준 입출력으로 바꿈 // close(fd[0]); dup2(fd[1], 1); close(fd1[1]); dup2(fd1[0], 0); /*컨텐츠의 길이에 따라 분할로 보낼지 한번에 보낼지 정한다.*/ if(headerStruct.contentLength < BUFSIZE) { printf("%s\n", headerStruct.body); }else{ printf("%s\n", headerStruct.body); while((n = recv(fileDescriptor, buf, 1024, 0)) > 0) { printf("%s\n", buf); memset(buf, '\0', 1024); } } //cgi에서 읽은 메시지를 클라이언트에게 전송 while((n = read(0, buf, 1024)) > 0) { send(fileDescriptor, buf, n, 0); } } }
C
#include<stdio.h> #include<stdlib.h> #include<time.h> #include<pthread.h> #include "mm.h" // Task 1: Flush the cache so that we can do our measurement :) void flush_all_caches() { //For now will just do this with a fixed block size //Will work out later how to dynamically figure out cache size char* temp; //assuming "generouslly" a cache size of 16MB int tempSize = 16*1024*1024; //16M * 1024KB / MB * 1024 Bytes / KB temp = malloc(tempSize*sizeof(char)); for(int i=0; i<tempSize;i++){ //WEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE temp[i] = 0; } free(temp); } void load_matrix_base() { long i; huge_matrixA = malloc(sizeof(long)*(long)SIZEX*(long)SIZEY); huge_matrixB = malloc(sizeof(long)*(long)SIZEX*(long)SIZEY); huge_matrixC = malloc(sizeof(long)*(long)SIZEX*(long)SIZEY); // Load the input // Note: This is suboptimal because each of these loads can be done in parallel. for(i=0;i<((long)SIZEX*(long)SIZEY);i++) { fscanf(fin1,"%ld", (huge_matrixA+i)); fscanf(fin2,"%ld", (huge_matrixB+i)); huge_matrixC[i] = 0; } } void free_all() { printf("Attempting to free all matrix allocations\n"); free(huge_matrixA); free(huge_matrixB); free(huge_matrixC); printf("Freeing matricies successful!\n"); } void multiply_base() { int a,b,c; long sum; for(a = 0; a < SIZEX; a++){ for(b=0; b < SIZEY; b++){ sum=0; for(c=0; c < SIZEX; c++) { sum += ( huge_matrixA[find_loc(a,c)] * huge_matrixB[find_loc(c,b)] ); } huge_matrixC[find_loc(a,b)] = sum; } } } void compare_results() { long i; long temp1, temp2; fout = fopen("./out.in","r"); ftest = fopen("./reference.in","r"); for(i=0;i<((long)SIZEX*(long)SIZEY);i++) { fscanf(fout, "%ld", &temp1); fscanf(ftest, "%ld", &temp2); // printf("temp1 = %ld\ntemp2 = %ld\n", temp1, temp2); if(temp1!=temp2) { printf("Wrong solution!\n"); return; } } printf("Correct Solution!\n"); } void write_results() { fout = fopen("./out.in","w"); int i, j; for(i = 0; i<SIZEX;i++) { for(j=0; j<SIZEY;j++){ fprintf(fout, "%ld ", huge_matrixC[find_loc(i,j)]); } fprintf(fout, "\n"); } fclose(fout); } void load_matrix() { long i; huge_matrixA = malloc(sizeof(long)*(long)SIZEX*(long)SIZEY); huge_matrixB = malloc(sizeof(long)*(long)SIZEX*(long)SIZEY); huge_matrixC = malloc(sizeof(long)*(long)SIZEX*(long)SIZEY); pthread_t th_load_matrix[3]; rewind(fin1); rewind(fin2); pthread_create(&th_load_matrix[0], NULL, &load_matrixA, NULL); pthread_create(&th_load_matrix[1], NULL, &load_matrixB, NULL); pthread_create(&th_load_matrix[2], NULL, &load_matrixC, NULL); pthread_join(th_load_matrix[0], NULL); pthread_join(th_load_matrix[1], NULL); pthread_join(th_load_matrix[2], NULL); } void load_matrixA() { huge_matrixA = malloc(sizeof(long)*(long)SIZEX*(long)SIZEY); long i; for(i=0;i<((long)SIZEX*(long)SIZEY);i++) { fscanf(fin1,"%ld", (huge_matrixA+i)); } pthread_exit(0); } void load_matrixB() { long i; for(i=0;i<((long)SIZEX*(long)SIZEY);i++) { fscanf(fin2,"%ld", (huge_matrixB+i)); } pthread_exit(0); } void load_matrixC() { long i; for(i=0;i<((long)SIZEX*(long)SIZEY);i++) { huge_matrixC[i] = 0; } pthread_exit(0); } void load_matrix_translated() { long i; huge_matrixA = malloc(sizeof(long)*(long)SIZEX*(long)SIZEY); huge_matrixB = malloc(sizeof(long)*(long)SIZEX*(long)SIZEY); huge_matrixC = malloc(sizeof(long)*(long)SIZEX*(long)SIZEY); pthread_t th_load_matrix[3]; rewind(fin1); rewind(fin2); pthread_create(&th_load_matrix[0], NULL, &load_matrixA, NULL); pthread_create(&th_load_matrix[1], NULL, &load_matrixB_translated, NULL); pthread_create(&th_load_matrix[2], NULL, &load_matrixC, NULL); pthread_join(th_load_matrix[0], NULL); pthread_join(th_load_matrix[1], NULL); pthread_join(th_load_matrix[2], NULL); } void load_matrixB_translated() { long i, j; for(i = 0; i < SIZEX; i++) { for(j= 0; j < SIZEX; j++) { fscanf(fin2,"%ld", (huge_matrixB+(find_loc(j,i)))); } } pthread_exit(0); } int find_loc(int row, int col) { return row*SIZEY + col; } void multiply(Task task) { int row, col, blockRow, blockCol, dot; long sum; row = task.a; col = task.b; for(blockRow = row; blockRow < row+BLOCKSIZE; blockRow++){ for(blockCol = col; blockCol < col+BLOCKSIZE; blockCol++){ sum = 0; for(dot = 0; dot < SIZEX; dot++){ //we can gaurentee that no other thread will occupy the same (blockRow, blockCol) at the same time so no need to lock this variable; sum += ( huge_matrixA[find_loc(blockRow,dot)] * huge_matrixB[find_loc(dot,blockCol)] ); } huge_matrixC[find_loc(blockRow,blockCol)] = sum; } } } void baseline() { s = clock(); load_matrix_base(); t = clock(); total_in_base += ((double)t-(double)s) / CLOCKS_PER_SEC; printf("[Baseline] Total time taken during the load = %f seconds\n", total_in_base); s = clock(); multiply_base(); t = clock(); total_mul_base += ((double)t-(double)s) / CLOCKS_PER_SEC; printf("[Baseline] Total time taken during the multiply = %f seconds\n", total_mul_base); } void* startThread(void* args) { usleep(10000); while(1) { Task task; pthread_mutex_lock(&mutexQueue); if(taskCount>0){ task = task_pool[0]; int i; for(i = 0 ; i<taskCount - 1; i++){ task_pool[i] = task_pool[i+1]; } taskCount--; } pthread_mutex_unlock(&mutexQueue); multiply(task); if(taskCount==0) return; } } void work_assignment() { int rows, cols; for(rows = 0; rows < SIZEY; rows+=BLOCKSIZE){ for(cols = 0; cols < SIZEX; cols+=BLOCKSIZE){ task_pool[taskCount].a = rows; task_pool[taskCount].b = cols; taskCount++; } } return; } void improved_matrix_multiply() { flush_all_caches(); struct timespec t1, t2; double elapsedTime; clock_gettime(CLOCK_MONOTONIC, &t1); load_matrix(); clock_gettime(CLOCK_MONOTONIC, &t2); elapsedTime = (t2.tv_sec - t1.tv_sec); elapsedTime += (t2.tv_nsec - t1.tv_nsec) / 1000000000.0; printf("[Multithreaded]Total time taken during to Load = %.3f seconds\n", elapsedTime); int blockSize = BLOCKSIZE; printf("Trying to multiply using blockSize of %d\n", blockSize); int thread_count = 16; //create a thread pool with this many threads taskCount = 0; //Set our current task count to 0 task_pool = malloc((SIZEX*SIZEY/blockSize)*sizeof(Task)); pthread_t th_pool[thread_count]; pthread_mutex_init(&mutexQueue, NULL); int i; for(i=0; i<thread_count; i++){ if(pthread_create(&th_pool[i], NULL, &startThread, NULL) != 0) { perror("Failed to create Thread"); } } clock_gettime(CLOCK_MONOTONIC, &t1); printf("Trying to submit tasks\n"); work_assignment(); printf("work assigned, trying to loop threads now\n"); for(i=0; i<thread_count; i++){ if(pthread_join(th_pool[i], NULL) != 0) perror("Failed to create Thread"); } clock_gettime(CLOCK_MONOTONIC, &t2); pthread_mutex_destroy(&mutexQueue); elapsedTime = (t2.tv_sec - t1.tv_sec); elapsedTime += (t2.tv_nsec - t1.tv_nsec) / 1000000000.0; printf("[Multithreaded]Total time taken during the multiply = %.3f seconds\n", elapsedTime); } void* startThread_translated(void* args) { usleep(10000); while(1) { Task task; pthread_mutex_lock(&mutexQueue); if(taskCount>0){ task = task_pool[0]; int i; for(i = 0 ; i<taskCount - 1; i++){ task_pool[i] = task_pool[i+1]; } taskCount--; } pthread_mutex_unlock(&mutexQueue); multiply_translated(task); if(taskCount==0) return; } } void translated_matrix_multiply() { flush_all_caches(); struct timespec t1, t2; double elapsedTime; clock_gettime(CLOCK_MONOTONIC, &t1); load_matrix_translated(); clock_gettime(CLOCK_MONOTONIC, &t2); elapsedTime = (t2.tv_sec - t1.tv_sec); elapsedTime += (t2.tv_nsec - t1.tv_nsec) / 1000000000.0; printf("[Translated, Multithreaded]Total time taken during to Load = %.3f seconds\n", elapsedTime); int blockSize = BLOCKSIZE; printf("Trying to multiply using blockSize of %d\n", blockSize); int thread_count = 16; //create a thread pool with this many threads taskCount = 0; //Set our current task count to 0 task_pool = malloc((SIZEX*SIZEY/blockSize)*sizeof(Task)); pthread_t th_pool[thread_count]; pthread_mutex_init(&mutexQueue, NULL); int i; for(i=0; i<thread_count; i++){ if(pthread_create(&th_pool[i], NULL, &startThread_translated, NULL) != 0) { perror("Failed to create Thread"); } } clock_gettime(CLOCK_MONOTONIC, &t1); printf("Trying to submit tasks\n"); work_assignment(); printf("work assigned, trying to loop threads now\n"); for(i=0; i<thread_count; i++){ if(pthread_join(th_pool[i], NULL) != 0) perror("Failed to create Thread"); } clock_gettime(CLOCK_MONOTONIC, &t2); pthread_mutex_destroy(&mutexQueue); elapsedTime = (t2.tv_sec - t1.tv_sec); elapsedTime += (t2.tv_nsec - t1.tv_nsec) / 1000000000.0; printf("[Translated, Multithreaded]Total time taken during the multiply = %.3f seconds\n", elapsedTime); } void multiply_translated(Task task) { int row, col, blockRow, blockCol, dot; long sum; row = task.a; col = task.b; for(blockRow = row; blockRow < row+BLOCKSIZE; blockRow++){ for(blockCol = col; blockCol < col+BLOCKSIZE; blockCol++){ sum = 0; for(dot = 0; dot < SIZEX; dot++){ //we can gaurentee that no other thread will occupy the same (blockRow, blockCol) at the same time so no need to lock this variable; sum += ( huge_matrixA[find_loc(blockRow,dot)] * huge_matrixB[find_loc(blockCol, dot)] ); } huge_matrixC[find_loc(blockRow,blockCol)] = sum; } } } int main() { fin1 = fopen("./input1.in","r"); fin2 = fopen("./input2.in","r"); // baseline(); // free_all(); improved_matrix_multiply(); free_all(); translated_matrix_multiply(); printf("Writing results\n"); write_results(); printf("Wrote results\n"); fclose(fin1); fclose(fin2); free_all(); compare_results(); return 0; }
C
/* * @file : raw_video_player.c * * @description : This file contains the code of raw video player. * * @author : Aman Kumar (2015) * * @copyright : The code contained herein is licensed under the GNU General * Public License. You may obtain a copy of the GNU General * Public License Version 2 or later at the following locations: * http://www.opensource.org/licenses/gpl-license.html * http://www.gnu.org/copyleft/gpl.html */ #include <stdio.h> #include <unistd.h> #include <SDL2/SDL.h> #include <SDL2/SDL_pixels.h> #include <sys/types.h> #include <sys/stat.h> #define BPP 2 int get_SDL_pixfmt(int fmt) { switch (fmt) { case 1: return SDL_PIXELFORMAT_YUY2; case 2: return SDL_PIXELFORMAT_YV12; case 3: return SDL_PIXELFORMAT_IYUV; case 4: return SDL_PIXELFORMAT_UYVY; case 5: return SDL_PIXELFORMAT_YVYU; case 6: return SDL_PIXELFORMAT_RGB565; case 7: return SDL_PIXELFORMAT_BGR565; case 8: return SDL_PIXELFORMAT_RGB332; case 0: case 9: return SDL_PIXELFORMAT_UNKNOWN; default: return -1; } } int validPath(char *path) { struct stat st; if (stat(path, &st) < 0) return 0; return 1; } /**************************************************************************** * @function : This is the video player main function. It plays recorded video * using simple DirectMedia Layer(SDL2). * * @arg : command line arg * @return : success/failure * *************************************************************************/ int main(int argc, char **argv) { SDL_Window *win = NULL; SDL_Renderer *renderer = NULL; SDL_Texture *texture = NULL; char resolution[50] = {0}; int format = 0, bpp = BPP; int width, height; FILE *fp; char *frame = NULL; int fps = 0, delay = 0; int kill = 0; if (argc != 2) { printf("Usage: %s <video_file.raw>\n", argv[0]); exit(0); } if (!validPath(argv[1])) { printf("Invalid File\n"); return -1; } printf("Supported Format::\n"); printf("\t0 : Y_only /* Not supported at the moment */\n"); printf("\t1 : YUY2\n"); printf("\t2 : YV12\n"); printf("\t3 : IYUV\n"); printf("\t4 : UYVY\n"); printf("\t5 : YVYU\n"); printf("\t6 : RGB565\n"); printf("\t7 : BGR565\n"); printf("\t8 : RGB332\n"); printf("\t9 : UNKNOWN\n"); printf("Enter the video format : "); if (scanf(" %d", &format) < 0) return -1; format = get_SDL_pixfmt(format); if (format < 0) { printf("Error : Invalid Format\n"); return -1; } printf("Pixel depth(No. of bytes per pixel) : "); if (scanf(" %d", &bpp) < 0) return -1; printf("Width of the video : "); if (scanf(" %d", &width) < 0) return -1; printf("Height of the video : "); if (scanf(" %d", &height) < 0) return -1; printf("Frame Per Second(FPS) : "); if (scanf(" %d", &fps) < 0) return -1; delay = 1000000/(fps+15); snprintf(resolution, 50, "Raw Video Player : %dx%d", width, height); frame = (char *)calloc(1, width*height*bpp); if (!frame) { printf("Failed to allocate frame\n"); return -1; } SDL_Init(SDL_INIT_VIDEO); win = SDL_CreateWindow(resolution, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, width, height, SDL_WINDOW_RESIZABLE); renderer = SDL_CreateRenderer(win, -1, SDL_RENDERER_ACCELERATED); texture = SDL_CreateTexture(renderer, format, SDL_TEXTUREACCESS_STREAMING, width, height); fp = fopen(argv[1], "rb"); if (fp == NULL) { perror("fopen"); return -1; } while (1) { SDL_Event e; if (fread(frame, 1, width*height*bpp, fp) < width*height*bpp) { rewind(fp); continue; } if (SDL_PollEvent(&e)) { if (e.type == SDL_QUIT) { break; } else if (e.key.type == SDL_KEYUP) { switch (e.key.keysym.sym) { case SDLK_ESCAPE:/* exit on Esc */ kill = 1; break; default: break; } } } if (kill) break; SDL_UpdateTexture(texture, 0, frame, width*bpp); usleep(delay); SDL_RenderClear(renderer); SDL_RenderCopy(renderer, texture, NULL, NULL); SDL_RenderPresent(renderer); } SDL_DestroyTexture(texture); SDL_DestroyRenderer(renderer); SDL_DestroyWindow(win); free(frame); fclose(fp); SDL_Quit(); return 0; }
C
#include <stdio.h> #define IN 1 #define OUT 0 int main(void) { int wordlength[50]; int i,j, c, length, state, max; i = j = c = length = max = 0; state = OUT; for (i = 0; i < 50; ++i) wordlength[i] = 0; while((c = getchar()) != EOF){ if(c == '\n' || c == '\t' || c == ' '){ state = OUT; if( length > 0 && length < 50 ){ if (length > max) max = length; wordlength[length]++; } length = 0; } else{ state = IN; length++; } } printf("Histogram\n"); for(i = 0; i < max; ++i) printf("___"); printf("\n"); for(i = max; i > 0; --i){ printf("%2d", i); for(j = 0; j <= max; ++j){ if(wordlength[j] >= i) printf("|%2s",""); else{ printf("%3s",""); } } printf("\n"); } for(i =0; i <= max; ++i){ if(i <= 10){ printf("%2s%d","",i); } else{ printf("%3d",i); } } printf("\n"); for(i = 0; i < max; ++i) printf("___"); printf("\n"); return 0; }
C
/* Segunda tentativa para a P1, dessa vez * simplesmente por vontade própria e com * um tempo que não me leve à loucura */ #define NULO '2' #define FALSE '0' #define TRUE '1' #define LIN 40 #define COL 10 #include <stdio.h> #include <stdlib.h> #include <string.h> int main () { short unsigned int sala, ingressos, ing_meia, ing_bra, cart_est[5], soma = 0, ing_fil; unsigned int cod_bra, track[400], track_lug1[400], track_lug2[400], track_lug3[400]; int i, j, tmp = 0; double valor; char cond = NULO, cart_est_str[6], pol_let = 0, ing_pol, mapa1[LIN][COL], mapa2[LIN][COL], mapa3[LIN][COL]; /* Dar um valor inicial para cada posição das matrizes */ for (i=0; i < LIN; i++) { for (j=0; j < COL; j++) { mapa1[i][j] = '0'; mapa2[i][j] = '0'; mapa3[i][j] = '0'; } } while (1) { printf("Seja bem-vindo ao Cinema Mariano Pinheiro\n" "Entre com o numero da sala correspondente ao filme que deseja assistir (ou 0 para sair):\n" "1 - Star Trek | 2 - Star Wars | 3 - Tron\n"); /* Escolha de sala */ while (1) { scanf("%hu", &sala); if (sala == 0) { printf("Adeus!\n"); return 0; } else if (sala < 1 || sala > 3) { printf("Insira uma sala valida\n"); continue; } else break; } /* Escolha da quantidade de ingressos */ printf("Entre com a quantidade de ingressos que deseja comprar para esse filme:\n"); while (1) { scanf("%hu", &ingressos); if (ingressos > 400 || ingressos <= 0) { printf("A sala não comporta esta quantidade, insira uma quantidade valida\n"); continue; } else break; } /* Escolha de quantidade de ingressos de meia-entrada/carteira de estudante */ printf("Quantos ingressos serao aplicaveis a meia-entrada da carteira de estudante?\n"); while (1) { scanf("%hu", &ing_meia); if (ing_meia > ingressos || ing_meia < 0) { printf("Insira um numero valido de ingressos\n"); continue; } else break; } /* Validação de carteiras de estudante: meia-entrada */ if (ing_meia > 0) { for (i=0; i < ing_meia; ) { printf("Digite o numero da carteira de estudante numero %d:\n", i+1); for (j=0; j < 5; j++) scanf("%1hu", &cart_est[j]); while (getchar() != '\n'); for (j=0; j < 5; j++) sprintf(&cart_est_str[j], "%hu", cart_est[j]); for (j=0; j < ing_meia; j++) if (atoi(cart_est_str) == track[j] && atoi(cart_est_str) != 0) cond = FALSE; for (j=0; j < 5; j++) { if (j <= 3) soma += cart_est[j]; else if (soma % 10 == cart_est[4] && cond != FALSE) cond = TRUE; } if (cond == TRUE) { track[i] = atoi(cart_est_str); ++tmp; i++; cond = NULO; } else if (cond == FALSE) { printf("Carteira ja validada, digite 0 para cancelar o desconto nesse ingresso, " "ou outro numero para tentar novamente\n"); scanf("%c", &cond); while (getchar() != '\n'); if (cond == FALSE) i++; cond = NULO; } else { printf("Numero invalido: digite 0 para cancelar o desconto para esse ingresso, " "ou outro numero para tentar novamente\n"); scanf("%c", &cond); while (getchar() != '\n'); if (cond == FALSE) i++; cond = NULO; } } ing_meia = tmp; tmp = 0; } /* Escolha de quantidade de ingressos de com desconto de cliente Bradau */ printf("Quantos ingressos serao aplicaveis ao desconto de cliente Bradau?\n"); while (1) { scanf("%hu", &ing_bra); if (ing_bra > ingressos || ing_bra < 0) { printf("Insira um numero valido de ingressos\n"); continue; } else break; } /* Validação dos ingressos de clientes Bradau */ if (ing_bra > 0) { for (i=0; i < ing_bra; ) { printf("Digite o codigo do cliente Bradau numero %d:\n", i+1); scanf("%u", &cod_bra); while (getchar() != '\n'); for (j=0; j < ing_bra; j++) if (cod_bra == track[j] && cod_bra != 0) cond = FALSE; if (cod_bra % 237 == 0 && cod_bra % 341 == 0 && cond != FALSE) cond = TRUE; if (cond == TRUE) { track[i] = cod_bra; ++tmp; i++; cond = NULO; } else if (cond == FALSE) { printf("Codigo ja validado, digite 0 para cancelar o desconto nesse ingresso, " "ou outro numero para tentar novamente\n"); scanf("%c", &cond); while (getchar() != '\n'); if (cond == FALSE) i++; cond = NULO; } else { printf("Codigo invalido, digite 0 para cancelar o desconto nesse ingresso, " "ou outro numero para tentar novamente\n"); scanf("%c", &cond); while (getchar() != '\n'); if (cond == FALSE) i++; cond = NULO; } } ing_bra = tmp; tmp = 0; } /* Exibir o mapa da sala de cinema */ printf("\nMapa da sala de cinema:\n"); printf("%5c", pol_let+32); /* Espaçar as letras das poltronas */ /* Imprimir as letras das poltronas */ for (j=0; j < COL; j++) { if (j == 9) printf("%c\n", pol_let+65+j); else printf("%c ", pol_let+65+j); } /* Imprimir as fileiras */ for (i=0; i < LIN; i++) { printf("%2d | ", i+1); for (j=0; j < COL; j++) { if (sala == 1) printf("%c ", mapa1[i][j]); else if (sala == 2) printf("%c ", mapa2[i][j]); else if (sala == 3) printf("%c ", mapa3[i][j]); if (j == 9) putchar('\n'); } } /* Solicitar a escolha dos lugares */ for (i=0; i < ingressos; ) { printf("\nSelecione a poltrona para o ingresso %d/%d\n" "Exemplo: 2 E (case sensitive)\n", i+1, ingressos); scanf("%2hu %1c", &ing_fil, &ing_pol); while (getchar() != '\n'); for (j=0; j < ingressos; j++) { switch (sala) { case 1: if (((ing_fil-65) + ing_pol) == track_lug1[j]) cond = FALSE; break; case 2: if (((ing_fil-65) + ing_pol) == track_lug2[j]) cond = FALSE; break; case 3: if (((ing_fil-65) + ing_pol) == track_lug3[j]) cond = FALSE; break; } } if ((ing_fil >= 1 && ing_fil <= 40) && (ing_pol >= 'A' && ing_pol <= 'J') && cond != FALSE) { switch (sala) { case 1: track_lug1[i] = (ing_fil-65) + ing_pol; mapa1[ing_fil-1][ing_pol-65] = 'X'; break; case 2: track_lug2[i] = (ing_fil-65) + ing_pol; mapa2[ing_fil-1][ing_pol-65] = 'X'; break; case 3: track_lug3[i] = (ing_fil-65) + ing_pol; mapa3[ing_fil-1][ing_pol-65] = 'X'; break; } i++; } else if (cond == FALSE) { printf("Esse lugar ja esta ocupado\n"); cond = NULO; } else printf("Insira um lugar valido\n"); } /* Exibir o valor total */ ingressos -= (ing_meia + ing_bra); valor = (ingressos*20) + ((ing_meia*20) * (50./100.)) + ((ing_bra*20) * (30./100.)); printf("O valor total a ser pago eh de: R$ %02.2f\n" "Obrigado por comprar no Cinema Mariano Pinheiro!\n\n", valor); } return 0; }
C
#include <stdlib.h> #include "grammar.h" #include "parser.h" #include "lexer.h" #include "../General/hashtable.h" #define DEFAULT_OUTPUT_SIZE 500 Node *matchGrammar(GrammarHead *head); int matchPart(GrammarPart *part); #define TOKEN 0 #define NODE 1 typedef struct{ unsigned int type : 1; union{ Token *token; Node *node; } val; } OutputValue; struct{ OutputValue *values; size_t size; size_t cur; //Where read from/write to, if equal to top, where to place next token size_t top; //Where to place next token Tokenizer *tokenizer; } output; void output_setup(char *filepath){ output.values = malloc(DEFAULT_OUTPUT_SIZE * sizeof(OutputValue)); output.size = DEFAULT_OUTPUT_SIZE; output.cur = 0; output.top = 0; output.tokenizer = tokenizer_new(filepath); } void output_reset(){ free(output.values); output.cur = 0; output.top = 0; tokenizer_destroy(output.tokenizer); } OutputValue *output_next(){ if(output.cur == output.top){ //Read from token stream while(output.top >= output.size){ output.size *= 1.5; output.values = realloc(output.values, output.size); } OutputValue entry; entry.type = TOKEN; Token *token = tokenizer_nexttoken(output.tokenizer); entry.val.token = token; output.values[output.top++] = entry; } return output.values + (output.cur++); } Node *parseFile(char *filepath){ output_setup(filepath); Node *prog = matchGrammar(table_lookup(grammarTable, "prog")); output_reset(); return prog; } Node *matchGrammar(GrammarHead *head){ printf("Matching %s!\n", head->name); size_t start = output.cur; GrammarPart *part; for(part = head->grammar; part != NULL; part = part->next){ if(!matchPart(part)) return NULL; } output.top = start + 1; if(output.cur > output.top) output.cur = output.top; return head->builder(start); } int matchPart(GrammarPart *part){ if(part->type == OR){ size_t start = output.cur; OrGrammarPart *orPart = (OrGrammarPart *)part; GrammarPart *p; int success = 1; for(p = orPart->op1; p != NULL; p = p->next){ if(!(success = matchPart(p))) break; } if(success) return 1; output.cur = start; success = 1; for(p = orPart->op2; p != NULL; p = p->next){ if(!(success = matchPart(p))) break; } if(success) return 1; return 0; } else if(part->type == MACRO){ size_t start = output.cur; MacroGrammarPart *macroPart = (MacroGrammarPart *)part; OutputValue entry; entry.type = NODE; entry.val.node = matchGrammar(table_lookup(grammarTable, macroPart->macro)); if(entry.val.node == NULL) return 0; output.values[start] = entry; output.top = start + 1; if(output.cur > start) output.cur = start + 1; return 1; } else if(part->type == LOOP){ LoopGrammarPart *loopPart = (LoopGrammarPart *)part; while(1){ size_t start = output.cur; int success = 1; GrammarPart *p; for(p = loopPart->loop; p != NULL; p = p->next){ if(!(success = matchPart(p))) break; } if(!success){ printf("Loop failed here!\n"); output.cur = start; break; } } return 1; } else if(part->type == OPTIONAL){ OpGrammarPart *opPart= (OpGrammarPart *)part; size_t start = output.cur; int success = 1; GrammarPart *p; for(p = opPart->option; p != NULL; p = p->next){ if(!(success = matchPart(p))) break; } if(!success) output.cur = start; } else{ Token *token = output_next()->val.token; if(token == NULL) return 0; printf("Comparing %d to %d!\n", part->type, token->type); return part->type == token->type; } } Node *buildProg(size_t start){ ProgNode *prog = malloc(sizeof(ProgNode)); ((Node *)prog)->type = PROG; int i; for(i = 0; output.values[start + i].type == NODE; i++) ; printf("Amount of statements in prog: %d\n", i); prog->stmts = malloc(i * sizeof(Node *)); int j; for(j = 0; j < i; j++) prog->stmts[j] = output.values[start + j].val.node; return (Node *)prog; } Node *buildAssign(size_t start){ AssignNode *assign = malloc(sizeof(AssignNode)); ((Node *)assign)->type = ASSIGNSTMT; assign->identifier = output.values[start].val.token; assign->expr = (ExprNode *)output.values[start + 2].val.node; //Skips equals sign return (Node *)assign; } Node *buildReturn(size_t start){ ReturnNode *ret = malloc(sizeof(ReturnNode)); ((Node *)ret)->type = RETURNSTMT; ret->expr = (ExprNode *)output.values[start].val.node; return (Node *)ret; } Node *buildExpr(size_t start){ ExprNode *expr = malloc(sizeof(ExprNode)); ((Node *)expr)->type = EXPR; expr->expression = output.values[start].val.token; return (Node *)expr; }
C
/** Program to Demonstrate the working of Strings using String Functions 1. String Compare - strcmp(s1,s2) - int (0/-1) 2. String Concatenate - strcat(s1,s2) 3. String Length - strlen(s1) - int 4. String Copy - strcpy(s1,s2) */ #include<stdio.h> #include<string.h> int main() { char str1[20],str2[20]; int len; printf("\nEnter two Strings..."); gets(str1); gets(str2); if(strcmp(str1,str2) == 0) printf("Strings %s and %s are Equal...",str1,str2); else printf("Strings %s and %s are NOT Equal...",str1,str2); // Concat Function strcat(str1,str2); printf("\nConcatenated String is %s....\n",str1); // Length Function len = strlen(str1); printf("\n The Length is....%d\n",len); // copy Function strcpy(str1,str2); printf("\nCopied String is %s....\n", str2); return 0; }
C
#include<stdio.h> #include<string.h> int main() { char name[10]; int n,i; printf("\nEnter the string"); scanf("%s",&name); printf("\nEnter how many times it should be repeated"); scanf("%d",&n); for(i=0;i<n-1;i++) { printf("\n%s\n",name); } return 0; }
C
#include <stdlib.h> #include <time.h> #include <stdio.h> /** * main - main * * * Return: 0 */ int main(void) { int n, d; srand(time(0)); n = rand() - RAND_MAX / 2; /* your code goes there */ d = n % 10; if (d > 5) printf("Last digit of %d is %d and is greater than 5\n", n, d); else if (d < 6 && d != 0) printf("Last digit of %d is %d and is less than 6 and not 0\n", n, d); else printf("Last digit of %d is %d and is 0\n", n, d); return (0); }
C
/* NOTES: Trivial exercise for practice */ #include "../include/que.h" /* Initialize Array based Queues */ int queInit(Que **head, const uint8_t MAX_SIZE) { if(head == NULL) return ERR_ARGS; (*head) = malloc(sizeof(Que)); if(*head == NULL) return ERR_MALLOC; /* Initialization */ (*head)->max_size = MAX_SIZE; /* Alloc mem for Que */ (*head)->que = malloc(sizeof((*head)->max_size)); if((*head)->que == NULL) return ERR_MALLOC; /* Array of ints of MAX_SIZE */ memset((*head)->que, 0x0, sizeof(uint8_t) * MAX_SIZE); return ERR_NOERRORS; } /* TRUE on full and FALSE otherwise * * This routine should only be called after valid checks of `head` pointer * * two cases of full: * (a) * +---+---+---+---+---+---+---+---+---+---+ * | | | | | | | | | | | * +---+---+---+---+---+---+---+---+---+---+ * ^ ^ * head/start tail/end * * (b) * +---+---+---+---+---+---+---+---+---+---+ * | | | | | | | | | | | * +---+---+---+---+---+---+---+---+---+---+ * ^ ^ * tail head * */ int isFullQ(Que *head) { int size = head->max_size; int start = head->start; int end = head->end; /* did not wrap */ if(start < end) return (start%size == (end+1)%size); else return (end%size == (start+1)%size); } /* TRUE on empty, False otherwise */ int isEmptyQ(Que *head) { return (head->start == head->end); } /* Add an elem, always at the tail */ int enQ(Que **head, const int elem) { int *idx; int size; /* bad args */ if(head == NULL || *head == NULL) return ERR_ARGS; /* Q full */ if(isFullQ(*head)) return ERR_QFULL; idx = &(*head)->end; size = (*head)->max_size; (*head)->que[*idx] = elem; *idx = (++(*idx))%size; return ERR_NOERRORS; } /* Return an elem from the head/front of Q */ int deQ(Que **head) { int elem, *idx, size; if(head == NULL || *head == NULL) return ERR_ARGS; /* Q empty */ if(isEmptyQ(*head)) return ERR_QEMPTY; idx = &(*head)->start; size = (*head)->max_size; elem = (*head)->que[*idx]; *idx = (++(*idx))%size; // both start and end increments. return elem; } /* Get first elem without removing it */ int peekQ(Que **head) { if(head == NULL || *head == NULL) return ERR_ARGS; if(isEmptyQ(*head)) return ERR_QEMPTY; return (*head)->que[(*head)->start]; } /* Current size of Q */ int curSizeQ(Que **head) { int size, start, end; if(head == NULL || *head == NULL) return ERR_ARGS; size = (*head)->max_size; start = (*head)->start; end = (*head)->end; /* TODO: */ return 0; } /* list items in Q from start to end */ void walk(Que **head) { int i, idx, size, cnt; if(head == NULL || *head == NULL) return ; size = (*head)->max_size; if((*head)->start < (*head)->end) cnt = (*head)->end - (*head)->start; else cnt = (size-(*head)->start) + (*head)->end; for(i=0, idx=(*head)->start; i<cnt; i++) { printf("%d ", (*head)->que[idx]); idx = (idx +1)%size; } printf("\n"); }
C
#include <stdio.h> #include <stdlib.h> /* * */ int main(int argc, char** argv) { int f=8; int x = 0; int xn = 1; int a=1; while (a < f){ printf("%d\n",x); printf("%d\n",xn); x = x + xn; xn = xn + x; a = a+2; } return 0; }
C
#ifndef GENERAL_POINTF_H #define GENERAL_POINTF_H #include <stdbool.h> typedef struct Point Point; typedef struct SizeF SizeF; typedef struct PointF PointF; struct PointF { float x; float y; }; PointF PointF_Construct(float xx, float yy); PointF PointF_ConstructFromPoint(const Point *p); PointF PointF_AddSizeF(const PointF *p, const SizeF *s); PointF Point_Multiply(float factor, const PointF *p); #endif
C
#include "menu.h" #include "term_cmd.h" #include "debug.h" #include <pthread.h> #include <unistd.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #define SEPARATION_LINE_LENGTH 80 #define STATUS_FIELD_OFFSET 2 #define LIVE_SECTION_OFFSET 3 #define MAX_ACTION_LENGTH 3 static pthread_t menu_thr; static struct menu_page *p_curPage; static pthread_mutex_t menu_mut; static struct cursor_pos actionFieldPos; static struct cursor_pos liveSectionPos; static struct cursor_pos statusFieldPos; static int actionBufferEnable = 1; static pthread_mutex_t actionBufferEnable_mut = PTHREAD_MUTEX_INITIALIZER; static void (*p_input_handler)(char c) = NULL; static pthread_mutex_t input_handler_mut = PTHREAD_MUTEX_INITIALIZER; static char input_buffer[MAX_ACTION_LENGTH]; static char* p_getValueBuffer = NULL; static unsigned char getValueBufferLen = 0; static unsigned char getValueBufferCursorPos = 0; void (*p_getValueBufferReturnHandler)(int errno, char* retStr); static void menu_show(void) { int i; pthread_mutex_lock(&menu_mut); // clear page clear_page(); actionFieldPos.line = 1; // set first offset liveSectionPos.line = LIVE_SECTION_OFFSET; liveSectionPos.col = 0; statusFieldPos.line = STATUS_FIELD_OFFSET; statusFieldPos.col = 0; // display the title set_highlight(1); printf("%s\n\r", p_curPage->p_page_title); set_highlight(0); printf("\n\n"); actionFieldPos.line += 3; // display menu for(i=0; i<p_curPage->nb_items; i++) { // display line printf("%3d.\t%s\n\r", i+1, p_curPage->p_items_table[i]->p_item_text); actionFieldPos.line++; } // show the select action if (p_curPage->nb_items > 0) { printf("\n"); actionFieldPos.line++; printf("Select action : "); actionFieldPos.col = strlen("Select action : "); statusFieldPos.line += actionFieldPos.line; // show the separation line between menu and page printf("\n\n\n\r"); liveSectionPos.line = actionFieldPos.line + 4; for (i=0; i<SEPARATION_LINE_LENGTH; i++) { printf("="); } // enable buffer pthread_mutex_lock(&actionBufferEnable_mut); actionBufferEnable = 1; pthread_mutex_unlock(&actionBufferEnable_mut); } else { // disable buffer pthread_mutex_lock(&actionBufferEnable_mut); actionBufferEnable = 0; pthread_mutex_unlock(&actionBufferEnable_mut); } #ifdef DEBUG { char buffer[50]; sprintf(buffer, "actionField line : %d", actionFieldPos.line); debug(buffer); sprintf(buffer, "liveSection line : %d", liveSectionPos.line); debug(buffer); sprintf(buffer, "statusField line : %d", statusFieldPos.line); debug(buffer); } #endif set_cursor_pos(actionFieldPos); fflush(stdout); pthread_mutex_unlock(&menu_mut); } void menu_status(char *status) { pthread_mutex_lock(&menu_mut); // set the cursor position set_cursor_pos(statusFieldPos); clear_end_of_line(); printf("\r"); printf("%s", status); fflush(stdout); pthread_mutex_unlock(&menu_mut); } void menu_set_action_field(char *value) { pthread_mutex_lock(&menu_mut); set_cursor_pos(actionFieldPos); clear_end_of_line(); printf("%s", value); pthread_mutex_unlock(&menu_mut); } void menu_live_clear(void) { pthread_mutex_lock(&menu_mut); set_cursor_pos(liveSectionPos); clear_end_of_page(); pthread_mutex_unlock(&menu_mut); } void menu_live_clearline(int line) { struct cursor_pos p; pthread_mutex_lock(&menu_mut); set_cursor_pos(liveSectionPos); p.line = line; p.col = 0; move_cursor(p); clear_end_of_line(); pthread_mutex_unlock(&menu_mut); } void menu_live_print(struct cursor_pos pos, char *str) { pthread_mutex_lock(&menu_mut); set_cursor_pos(liveSectionPos); move_cursor(pos); printf("%s", str); fflush(stdout); pthread_mutex_unlock(&menu_mut); } static void menu_get_value_input_handler(char c) { int tmpLen; struct cursor_pos p={.line=0}; tmpLen = strlen(p_getValueBuffer); { char str[50]; sprintf(str, "New char received %x | Buffer len : %d", c, strlen(p_getValueBuffer)); debug(str); } if( c >= 0x20 && c < 0x7F) // only allow displayable chars { // store the char p_getValueBuffer[tmpLen] = c; tmpLen++; } else if(c == 0x08 || c == 0x7F) { // remove the last char if(tmpLen > 0) { p_getValueBuffer[tmpLen -1] = 0; } } p.col=getValueBufferCursorPos; // display the buffer pthread_mutex_lock(&menu_mut); set_cursor_pos(statusFieldPos); move_cursor(p); clear_end_of_line(); printf("%s", p_getValueBuffer); fflush(stdout); pthread_mutex_unlock(&menu_mut); // check for CR or LF if(c == 0x0A || c == 0x0D || tmpLen >= getValueBufferLen) { // make sure to force last buffer char to 0 p_getValueBuffer[getValueBufferLen] = 0; // call the callback function if(p_getValueBufferReturnHandler != NULL) p_getValueBufferReturnHandler(0, p_getValueBuffer); // restore the default input handler menu_set_input_handler(NULL); // free the buffer free(p_getValueBuffer); p_getValueBuffer = NULL; getValueBufferLen = 0; } } void menu_get_value(char *message, unsigned char maxLen, void (*returnHandler)(int errno, char* retStr)) { debug("Entering menu_get_value()"); // create the buffer if(p_getValueBuffer != NULL) free(p_getValueBuffer); p_getValueBuffer = malloc(maxLen+1); getValueBufferLen = maxLen; p_getValueBufferReturnHandler = returnHandler; getValueBufferCursorPos = strnlen(message, 255) + 1; if(p_getValueBuffer != NULL) { debug("Buffer is alocated, change the input handler"); menu_status(message); memset(p_getValueBuffer, 0, getValueBufferLen); // set the input handler menu_set_input_handler(menu_get_value_input_handler); } else { char msg[] = "Cannot allocate buffer !!!"; debug(msg); menu_status(msg); getValueBufferLen = 0; if(p_getValueBufferReturnHandler != NULL) p_getValueBufferReturnHandler(-1, NULL); } } void menu_exit(void) { pthread_mutex_lock(&menu_mut); // call the current page exit if (p_curPage->p_page_exit != NULL) p_curPage->p_page_exit(); // check the prev pointer if (p_curPage->p_prev != NULL) { struct menu_page *tmp = p_curPage; p_curPage = p_curPage->p_prev; tmp->p_prev = NULL; // show the new page menu_show(); // call the page enter function if (p_curPage->p_page_enter) p_curPage->p_page_enter(); } else { // exit pthread_cancel(menu_thr); } pthread_mutex_unlock(&menu_mut); } void menu_enter(struct menu_page *p_page) { pthread_mutex_lock(&menu_mut); // save the previous page p_page->p_prev = p_curPage; // call the page exit function if (p_curPage->p_page_exit != NULL) p_curPage->p_page_exit(); // points to the new page p_curPage = p_page; // show the new page menu_show(); // call the page enter function if (p_curPage->p_page_enter) p_curPage->p_page_enter(); pthread_mutex_unlock(&menu_mut); } static void menu_default_input_handler(char c) { switch(c) { // test CR and LF case 0x0A: case 0x0D: { int actionNum; int tmpActionBufferEnable; // check if buffer is enabled pthread_mutex_lock(&actionBufferEnable_mut); tmpActionBufferEnable = actionBufferEnable; pthread_mutex_unlock(&actionBufferEnable_mut); if (!tmpActionBufferEnable) break; // execute the action // compute the number actionNum = atoi(input_buffer); #ifdef DEBUG { char debugBuf[40]; sprintf(debugBuf, "Selected action : %d", actionNum); debug(debugBuf); } #endif if (actionNum > 0 && actionNum <= p_curPage->nb_items) { debug("Action is valid, call the item action"); if (p_curPage->p_items_table[actionNum-1]->p_item_action != NULL) p_curPage->p_items_table[actionNum-1]->p_item_action(); else debug("No action for this item"); } else { menu_status("Invalid action !"); #ifdef DEBUG { char str[50]; debug("Invalid action ! "); sprintf(str, "actionNum = %d | nb_items = %d", actionNum, p_curPage->nb_items); debug(str); } #endif } // clear the buffer memset(input_buffer, 0, sizeof(input_buffer)); set_cursor_pos(actionFieldPos); clear_end_of_line(); }break; // test for backspace case 0x08: case 0x7F: if(strlen(input_buffer) > 0) { // delete the last char input_buffer[strlen(input_buffer)-1] = '\0'; // redraw the buffer menu_set_action_field(input_buffer); } break; // store only numerical chars default: { int tmpActionBufferEnable; debug("Try to store new char in buffer"); // check if buffer is enabled pthread_mutex_lock(&actionBufferEnable_mut); tmpActionBufferEnable = actionBufferEnable; pthread_mutex_unlock(&actionBufferEnable_mut); if (!tmpActionBufferEnable) break; if(c >='0' && c <= '9') { // check for buffer overflow if(strlen(input_buffer) <= MAX_ACTION_LENGTH) { input_buffer[strlen(input_buffer)] = c; // update the display menu_set_action_field(input_buffer); } else { debug("Action buffer full..."); } } }break; } } void menu_set_input_handler(void (*handler)(char c)) { pthread_mutex_lock(&input_handler_mut); p_input_handler = handler; if (handler == NULL) memset(input_buffer,0,sizeof(input_buffer)); pthread_mutex_unlock(&input_handler_mut); } static void* menu_thread(void* unused) { menu_show(); for(;;) { int c; // wait for chars c = getchar(); { char buf[10]; sprintf(buf,"0x%x",c); debug(buf); } // check for specific chars switch(c) { // test escape char case 0x1B: // exit the menu menu_exit(); break; default: if (p_input_handler == NULL) menu_default_input_handler(c); else p_input_handler(c); break; } } return NULL; } void menu_start(struct menu_page *p_page) { pthread_mutexattr_t mutexattr; // disable echo system("stty -echo raw"); // hide cursor set_cursor_visible(0); // set first page p_curPage = p_page; // initialize mutex as reentrent pthread_mutexattr_init(&mutexattr); pthread_mutexattr_settype(&mutexattr, PTHREAD_MUTEX_RECURSIVE); pthread_mutex_init(&menu_mut, &mutexattr); pthread_mutex_init(&input_handler_mut, &mutexattr); pthread_mutexattr_destroy(&mutexattr); // clear input buffer memset(input_buffer, 0, sizeof(input_buffer)); // start menu thread pthread_create(&menu_thr, NULL, menu_thread, NULL); } void menu_join(void) { pthread_join(menu_thr, NULL); clear_end_of_page(); printf("\n\r"); system("stty echo cooked"); set_cursor_visible(1); }
C
#include "queue.h" #include <stdlib.h> #include <string.h> #include <assert.h> void QueueNew(Queue* q, int elem_size, QueueFreeFunction freeFn){ q->logLen = 0; q->allocLen = 1; q->elem_size = elem_size; q->base = malloc(q->elem_size); assert(q->base != NULL); q->freeFn = freeFn; } int QueueIsEmpty(Queue* q){ return q->logLen == 0; } int QueueSize(Queue* q){ return q->logLen; } int QueueCapacity(Queue* q){ return q->allocLen; } void* QueueFront(Queue* q){ assert(q->logLen != 0); void* elem = malloc(q->elem_size); assert(elem != NULL); memcpy(elem, q->base, q->elem_size); return elem; } void* QueueBack(Queue* q){ assert(q->logLen != 0); void* elem = malloc(q->elem_size); assert(elem != NULL); memcpy(elem, (char*)q->base + q->elem_size * (q->logLen - 1), q->elem_size); return elem; } void QueueEnqueue(Queue* q, void* elem){ if(q->logLen >= q->allocLen){ q->allocLen *= 2; q->base = realloc(q->base, q->elem_size * q->allocLen); assert(q->base != NULL); } memcpy((char*)q->base + q->logLen * q->elem_size, elem, q->elem_size); q->logLen++; } void* QueueDequeue(Queue* q){ void* elem = QueueFront(q); if(q->freeFn != NULL) q->freeFn(q->base); q->logLen--; void* newBase = malloc(q->elem_size * q->logLen); assert(newBase != NULL); memcpy(newBase, (char*)q->base + q->elem_size, q->elem_size * q->logLen); free(q->base); q->base = newBase; return elem; } void QueueDestroy(Queue* q){ if(q->freeFn != NULL){ for(int i=0; i<q->logLen; i++){ q->freeFn((char*)q->base + i * q->elem_size); } } free(q->base); }
C
#include <stdio.h> #include "headers/exo0.h" #include "headers/exo1.h" int* merge_sorted_arrays(int* first, int* second) { int* mergedArr; int firstSize, secondSize, totalSize, i, j, k; j = k = 0; firstSize = array_size(first); secondSize = array_size(second); totalSize = firstSize + secondSize; mergedArr = allocate_integer_array(totalSize); if(first == NULL) return second; else if(second == NULL) return first; else if(first == NULL || second == NULL) return NULL; else { for (i = 0; i < totalSize; i++) { if(j < firstSize && k < secondSize) { if(first[j] < second[k]) { mergedArr[i] = first[j]; j++; } else { mergedArr[i] = second[k]; k++; } } else if(j == firstSize) { mergedArr[i] = second[k]; k++; } else { mergedArr[i] = first[j]; j++; } } } mergedArr[totalSize] = -1; return mergedArr; } void split_arrays(int* array, int** first, int** second) { int size, firstSize, secondSize; size = array_size(array); firstSize = size / 2; secondSize = size - firstSize; *first = allocate_integer_array(firstSize); *second = allocate_integer_array(secondSize); int i; for(i = 0; i < size; i++) { if(i < firstSize) (*first)[i] = array[i]; else (*second)[i - firstSize] = array[i]; } (*first)[firstSize] = -1; (*second)[secondSize] = -1; } int* merge_sort(int* array) { int *newArray; int *first, *second, *tmpFirst, *tmpSecond; int size = array_size(array); if(array == NULL) return NULL; else if(size == 1) { newArray = allocate_integer_array(size); newArray[0] = array[0]; newArray[size] = -1; return newArray; } else { printf("\nsplit array in two part :\n"); split_arrays(array, &first, &second); print_array(array); print_array(first); print_array(second); tmpFirst = merge_sort(first); tmpSecond = merge_sort(second); free_integer_array(first); free_integer_array(second); printf("\nmerge the two following ones :\n"); newArray = merge_sorted_arrays(tmpFirst, tmpSecond); print_array(tmpFirst); print_array(tmpSecond); } return newArray; }
C
/* * Author : Alvin Baldemeca * Version : 11.23.2013 * * Copy Right (C): * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * */ /******************************************************************************* * FileName: i2c_page.c * Dependencies: See include below , PICDEM2 PLUS demo board * Processor: PIC18F4520 * Compiler: XC8 * * Synopsis : * #include "i2c_page.c" * write_byte(); * read_byte(); * write_page(); * read_page(); * * Description : * write_byte() - write a byte of data to EEPROM (24LC256) * read_byte() - read a byte of data from EEPROM (24LC256) * write_page() - write a page (64 bytes) of data to EEPROM (24LC256) * read_page() - read a page (64 bytes) of data from EEPROM (24LC256) *******************************************************************************/ #include "global.h" #include "i2c.h" /** * Write a byte of data to EEPROM (24LC256) * @param data - the data to write * @param msb_add - the most significant byte of the EEPROM's memory address * @param lsb_add - the least significant byte of the EEPROM's memory address * @return 0 on success */ int write_byte(unsigned char data, unsigned char msb_add, unsigned char lsb_add) { i2c_start(); while(i2c_send(WRITE_EEPROM)) { i2c_rstart(); } while(i2c_send(msb_add)); while(i2c_send(lsb_add)); while(i2c_send(data)); i2c_stop(); return 0; } /** * Read a byte of data from EEPROM (24LC256) * @param rbyte - the pointer to the char to store the recieved data * @param msb_add - the most significant byte of the EEPROM's memory address * @param lsb_add - the least significant byte of the EEPROM's memory address * @return 0 on success */ int read_byte(unsigned char* rbyte, unsigned char msb_add, unsigned char lsb_add) { i2c_start(); while(i2c_send(WRITE_EEPROM)) { i2c_rstart(); } i2c_send(msb_add); i2c_send(lsb_add); i2c_rstart(); i2c_send(READ_EEPROM); *rbyte = i2c_receive(1); i2c_idle(); i2c_stop(); return 0; } /** * Write a page (64 bytes) of data to EEPROM (24LC256) * @param the_page - the pointer to the page to write to the EEPROM * @param msb_add - the most significant byte of the EEPROM's memory address * @param lsb_add - the least significant byte of the EEPROM's memory address * @return 0 on success */ int write_page(char *the_page, unsigned char msb_add, unsigned char lsb_add) { i2c_start(); // Send START condition while(i2c_send(WRITE_EEPROM)) { i2c_rstart(); } i2c_send(msb_add); i2c_send(lsb_add); int i; for(i=0; i < PAGESIZE; i++) { i2c_send(the_page[i]); } i2c_stop(); return 0; } /** * Read a page (64 bytes) of data from EEPROM (24LC256) * @param message - the pointer to store the data recieved from the EEPROM * @param msb_add - the most significant byte of the EEPROM's memory address * @param lsb_add - the least significant byte of the EEPROM's memory address * @return 0 on success */ int read_page(char *message, unsigned char msb_add, unsigned char lsb_add) { i2c_start(); while(i2c_send(WRITE_EEPROM)) { i2c_rstart(); } i2c_send(msb_add); i2c_send(lsb_add); i2c_rstart(); i2c_send(READ_EEPROM); int i; for(i=0; i < PAGESIZE; i++) { i2c_ack(1); //This was done for timing reasons message[i] = i2c_receive(); } i2c_idle(); i2c_stop(); return 0; }
C
#include<stdio.h> #include<string.h> int spchar(char pass[]) { int i,count_spchars=0; for(i=0;i<strlen(pass);i++) { if(pass[i]>=33 && pass[i]<=47 || pass[i]>=58 && pass[i]<=64) count_spchars++; } return count_spchars; } int nums(char pass[]) { int i,count_nums=0; for(i=0;i<strlen(pass);i++) { if(pass[i]<=48 && pass[i]<=57) count_nums++; } return count_nums; } int count_uc(char pass[]) { int i,count=0; for(i=0;i<strlen(pass);i++) { if(pass[i]>=65 && pass[i]<=90) count++; } return count; } int count_lc(char pass[]) { int i, count=0; for(i=0;i<strlen(pass);i++) { if(pass[i]>=97 && pass[i]<=122) count++; } return count; } int main() { label:; printf("\t\t******Password Validator********\n"); char pass[50],c; printf("Enter your password:"); scanf("%s",pass); //input pass int uc=count_uc(pass); //count upper case int lc=count_lc(pass); //count lower case int count_spchar=spchar(pass); //count special chars int count_nums=nums(pass); //count nums if((count_spchar>=2)&&(count_nums>=2)&&(strlen(pass)>=8)&&(lc>1)&&(uc>1)) { printf("\nSpecial characters: %d\n\nNumbers: %d\n\nUpper cases: %d\n\nLower cases: %d\n\nTotal Size: %d\n",count_spchar,count_nums,uc,lc,strlen(pass)); printf("\n=======Strong=======\n"); } else { printf("\nSpecial characters: %d\n\nNumbers: %d\n\nUpper cases: %d\n\nLower cases: %d\n\nTotal Size: %d\n",count_spchar,count_nums,uc,lc,strlen(pass)); printf("\n=======Weak=======\n"); } printf("Try Again?[Y/N]"); fflush(stdin); scanf("%c",&c); if(c==89 || c==121) { system("cls"); goto label; } }
C
/***********************************************************************/ // INF-01191 - Arquiteturas Avançadas // // Trabalho 1 // // Calculo de Pi utilizando método Montecarlo e OpenMP // // // Gabriel Piscoya Dávila 00246031 // Rubens Ideron dos Santos 00243658 // /**********************************************************************/ #include "pi.h" //#define HARDENING_DEBUG #define READ_HARDENED_VAR(VAR_NAME_1, VAR_NAME_2, VAR_TYPE, VAR_SIZE) (*((VAR_TYPE*)hardened_compare_and_return((void*)(&VAR_NAME_1), (void*)(&VAR_NAME_2), VAR_SIZE))) #define READ_HARDENED_ARRAY(ARRAY_NAME_1, ARRAY_NAME_2, ARRAY_TYPE, ARRAY_SIZE) ((ARRAY_TYPE)((void*)hardened_compare_and_return_array((void*)(&ARRAY_NAME_1), (void*)(&ARRAY_NAME_2), ARRAY_SIZE))) inline void* hardened_compare_and_return(void* var_a, void* var_b, long long size) { if(memcmp(var_a, var_b, size) != 0) { printf("\nHardening error: at file \"%s\"\n\n", __FILE__); exit(1); } return var_a; } inline void* hardened_compare_and_return_array(void* array_ptr_a, void* array_ptr_b, long long size) { char* bytes_array_a = (char*)((char**)array_ptr_a); char* bytes_array_b = (char*)((char**)array_ptr_b); #ifdef HARDENING_DEBUG printf("hardening_array: array_ptr_1 = %p, array_ptr_2 = %p, array_size = %d\n", bytes_array_a, bytes_array_b, size); #endif if(memcmp(bytes_array_a, bytes_array_b, size) != 0) { printf("\nHardening error: at file \"%s\"\n\n", __FILE__); exit(1); } return array_ptr_a; } // Compute a pseudorandom double // from a random integer between 0 and 32767 // Output value in range [0, 1] double pi_montecarlo_parallel(int niter) { double x_hardened_1, x_hardened_2, y_hardened_1, y_hardened_2; unsigned int i, count; /* # of points in the 1st quadrant of unit circle */ double pi; unsigned int g_seed; count = 0; #pragma omp parallel private(g_seed) { /* initialize seeds - one for each thread */ g_seed = time(NULL)*(omp_get_thread_num()+1); #pragma omp for private(x_hardened_1, y_hardened_1) schedule(static) reduction(+:count) for ( i=0; i<niter; i++) { g_seed = (214013*g_seed+2531011); x_hardened_1 = (double)((g_seed>>16)&0x7FFF)/32767; //x_hardened_2 = (double)((g_seed>>16)&0x7FFF)/32767; g_seed = (214013*g_seed+2531011); y_hardened_1 = (double)((g_seed>>16)&0x7FFF)/32767; //y_hardened_2 = (double)((g_seed>>16)&0x7FFF)/32767; //printf("x=%f,y=%f, thread=%d\n",x,y, omp_get_thread_num()); double x_temp, y_temp; x_temp = x_hardened_1;//READ_HARDENED_VAR(x_hardened_1, x_hardened_2, double, sizeof(double)); y_temp = y_hardened_1;//READ_HARDENED_VAR(y_hardened_1, y_hardened_2, double, sizeof(double)); if (x_temp*x_temp+y_temp*y_temp<=1) { count++; } } } pi=(double)count/niter*4; return pi; }
C
//Nearest even Number #include<stdio.h> main() { int num; scanf("%d",&num); if(num%2) printf("%d",num-1); else printf("%d",num); }
C
/* * File: Blink_LED.c * Author: Paras * * Created on May 21, 2017, 10:57 AM */ #include "LED_header.h" #define LED 1 void BlinkLED() { //setvbuf(stdout, NULL, _IONBF, 0); printf ("Raspberry Pi - Blink LED\n"); fflush(stdout); wiringPiSetup(); pinMode(LED, OUTPUT); while(1){ digitalWrite (LED, 1) ; // On delay (500) ; // mS digitalWrite (LED, 0) ; // Off delay (500) ; } }
C
static Uint32 DivFix(Uint32 p1, Uint32 p2, Uint32 fix) { Uint32 ret; ret = p1 / p2; p1 = p1 % p2;/* p1 = p1 - p2 * ret; */ while (fix--) { p1 += p1; ret += ret; if (p1 >= p2) { p1 -= p2; ret++; } } return ret; }
C
/*Author: Prasad Ghangal * Title: Codechef-Factorial(codeERA)*/ #include<stdio.h> #include<stdlib.h> int main() { long double *a; int t,n,i; // scanf("%d",&t); a=(long double*)malloc(sizeof(long double)*101); a[0]=a[1]=1; for(i=2;i<101;i++) { a[i]=i*a[i-1]; } /* for(i=0;i<=100;i++) { printf("%Lf ",a[i]); }*/ printf("%Lf\n",a[5]); // while(t--) // { // } free(a); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> //int candidates[] = {10,1,2,7,6,1,5}; int candidates[] = {1,1,2,5,6,7,10}; int result[] = {0, 0, 0, 0, 0, 0, 0}; int target = 8; int sum(int a[]) { int total = 0, i; for (i = 0; i < 7; ++i) { total += a[i]; } return total; } void printResult(int a[]) { int i; for (i = 0; i < 7; ++i) { if (a[i]) { printf("%d ", a[i]); } } printf("----------------------------------------------\n"); } void backTrack(int i, int total) { if (total == target) { printResult(result); return; } int j; for (j = i; j < 7; ++j) { if ((total + candidates[j]) > target) break; if (j > i && candidates[j] == candidates[j - 1]) continue; result[i] = candidates[j]; backTrack(j + 1, total + candidates[j]); result[i]= 0; } } int main(int argc, char const *argv[]) { backTrack(0, 0); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <errno.h> int BinarySearch(int SearchArray[100],int SearchNum,int length) { int low_bound=1; //position of 1st element in the array int up_bound=length;//position of last element in the array int midPoint; //midpoint of array int comparisons=0; //to get number of comparisons int found=0; // to show number is found or not while(found==0) { if(up_bound<low_bound) { found=2; } midPoint=low_bound+(up_bound-low_bound)/2; if (SearchArray[midPoint-1] < SearchNum) { low_bound = midPoint + 1; } if (SearchArray[midPoint-1] > SearchNum) { up_bound = midPoint - 1; } if (SearchArray[midPoint-1] == SearchNum) { found=1; printf("%d is PRESENT at location %d.\n",SearchNum,midPoint); comparisons++; break; } comparisons++; } printf("Total number of elements in the array= %d\n",length); printf("No. of comparisons= %d\n",comparisons); return found; } int main() { FILE *filePtr ; char fileName[10];//to store filename int flag ; int i ; int numbers[100];//array to store numbers from a file int idx_num ; //index of array int number ; //to scan and store each number from file int search_number; //to store the number to be searched int retVal ; //to store the return value int present; // to show number is found or not printf("Enter the file name: "); scanf("%s", fileName); filePtr = fopen(fileName, "r"); if (filePtr == NULL) { printf("File open error with %s \n",fileName); printf("Error number returned = %d \n", errno); printf("%s\n",strerror(errno)); exit(0); } flag = 1 ; idx_num = 0; while(flag) { retVal = fscanf(filePtr, "%d", &number); if (retVal == EOF) { flag = 0 ; } else { numbers[idx_num] = number ; idx_num++ ; } } fclose(filePtr); for(i = 0; i<idx_num;i++) { printf("%d ", numbers[i]); } printf("\nEnter number to be searched: \n"); scanf("%d",&search_number); present=BinarySearch(numbers,search_number,idx_num); if(present==1) { printf("\n"); } else { printf("The number %d is NOT PRESENT in the array.\n",search_number); } }
C
#include "libft.h" void *ft_calloc(size_t count, size_t size) { void *ptr; ptr = malloc(size * count); if (!ptr) return (0); ft_bzero(ptr, size * count); return (ptr); }
C
/** * @brief Creates the links between spaces * * @file link.h * @author Pablo Sánchez * @copyright GNU Public License */ #ifndef LINK #define LINK #include "../include/types.h" #define MAX_LINK 1024 typedef struct _Link Link; /** * @author: Pablo Sánchez * @brief: Allocs memory for one link * @param: Null * @return: a Link */ Link *link_create(Id); /** * @author: Pablo Sánchez * @brief: Frees the Link * @param: *Link * @return: void */ void link_destroy(Link *); /** * @author: Pablo Sánchez * @brief: Changes the link id to the given one * @param: *Link Id * @return: OK or ERROR */ STATUS link_setId(Link *, Id); /** * @author: Pablo Sánchez * @brief: Changes the Link status to OPENED or CLOSED * @param: *Link LinkStatus * @return: OK or ERROR */ STATUS link_setStatus(Link *, LinkStatus); /** * @author: Pablo Sánchez * @brief: Sets the spaces the link is joining * @param: *Link two spaces ids * @return: OK or ERROR */ STATUS link_setSpaces(Link *, Id, Id); /** * @author: Pablo Sánchez * @brief: Gets the links id * @param: *Link * @return: link->id */ Id link_getId(Link *); /** * @author: Pablo Sánchez * @brief: Gets the first Space of the link * @param: *Link * @return: link->space1 */ Id link_getSpace1(Link *); /** * @author: Pablo Sánchez * @brief: Gets the second Space of the link * @param: *Link * @return: link->space2 */ Id link_getSpace2(Link *); /** * @author: Pablo Sánchez * @brief: Gets the status the given link is in * @param: *Link * @return: OPENED or CLOSED */ LinkStatus link_getStatus(Link *); /** * @author: Pablo Sánchez * @brief: Gets the other space the link is connecting * @param: *Link space_id * @return: space_id */ Id link_getDestination(Link *, Id); /** * @author: Antonio Solana * @brief: Gets the direction of the link (relative to space1) * @param: *Link space_id * @return: space_id */ Id link_getDirection(Link *); /** * @author: Antonio Solana * @brief: Sets the direction of the link (relative to space1) * @param: *Link space_id * @param: int 0 [north] 1 [east] 2 [south] 3 [west] * @return: space_id */ STATUS link_setDirection(Link *, int); /** * @author: Pablo Sánchez * @brief: [DEBUG ONLY] prints the given link in stdout * @param: *Link * @return: OK or ERROR, printed the link; */ STATUS link_print(Link *); #endif
C
#include "WiltDS.h" #include <unistd.h> #include <stdlib.h> // A simple test case to run the code on a desktop machine. // Only works on little-endian machines. int main(int argc,char **argv) { uint32_t size; read(0,&size,4); uint32_t shifts=0; read(0,&shifts,3); uint16_t *buf=malloc(size); DecompressData(0,buf,size,shifts>>20,(shifts>>16)&0xf,(shifts>>12)&0xf,(shifts>>8)&0xf,(shifts>>4)&0xf,shifts&0xf); write(1,buf,size); }
C
#include <stdio.h> int main() { int num1; //변수를 '선언'한다. int num2, num3; int num4 = 10; //변수를 선언하면서 할당하여 초기화한다. int num5 =1, num6=2, num7 =8; num1 = 100; //변수에 값을 '할당'한다. num2 = 50; num3 = 20; printf("%d,%d,%d",num1,num2,num3); //'d'ecimal(10진수) return 0; }
C
/****************************************************************************** * Copyright (C) 2017 by Alex Fosdick - University of Colorado * * Redistribution, modification or use of this software in source or binary * forms is permitted as long as the files maintain this copyright. Users are * permitted to modify this and use it to learn about the field of embedded * software. Alex Fosdick and the University of Colorado are not liable for any * misuse of this material. * *****************************************************************************/ /** * @file stats.h * @author Mohamed Ismail * @date 23/12/2017 * */ #ifndef __STATS_H__ #define __STATS_H__ /* Add Your Declarations and Function Comments here */ /** * @brief <print array function> * * function that take two arguments and iterate over input array * and prints it in well formated style * * @param test -> first argument which contain the arry * @param siz -> secound arg indecate to size of the given array * * @return function return void */ void print_array ( unsigned char test[] , int size); /** * @brief <sort array function> * * function that take two arguments and iterate over input array * and sorted it using buble sort algorithm * * @param test -> first argument which contain the arry * @param siz -> secound arg indecate to size of the given array * * @return function return void */ void sort_array ( unsigned char test[] , int size); /** * @brief <find_median function> * * function that take two arguments and find the middle element of the given array * @param test -> first argument which contain the arry * @param siz -> secound arg indecate to size of the given array * * @return function return void */ int find_median ( unsigned char test[] , int size); /** * @brief <find_mean function> * * function that take two arguments and calculate the average of the given array * @param test -> first argument which contain the arry * @param siz -> secound arg indecate to size of the given array * * @return function return void */ int find_mean ( unsigned char test[] , int size); /** * @brief <find_max function> * * function that take two arguments and find the maximum element in the given array * @param test -> first argument which contain the arry * @param siz -> secound arg indecate to size of the given array * * @return function return void */ int find_maximum ( unsigned char test[] , int size); /** * @brief <find_min function> * * function that take two arguments and find the minimum element of the given array * @param test -> first argument which contain the arry * @param siz -> secound arg indecate to size of the given array * @return function return void */ int find_minimum ( unsigned char test[] , int size); /** * @brief <find_statistics function> * * function that take two arguments and print all statistics of given array * including minimum, maximum, mean, and median * @param test -> first argument which contain the arry * @param siz -> secound arg indecate to size of the given array * @return function return void */ void print_statistics(unsigned char test[] , int size); #endif /* __STATS_H__ */
C
#include <stdio.h> #include <stdlib.h> int main() { float nota[3]; printf("Digite a primeira nota: "); scanf("%f", &nota[0]); printf("Digite a segunda nota: "); scanf("%f", &nota[1]); printf("digite a terceira nota:"); scanf("%f", &nota[2]); nota[3] = (nota[0] + nota[1] + nota[2]) / 3; if (nota[3] >= 7) { printf("APROVADO!! \n"); } else { printf("REPROVADO!! \n"); } printf("A primeira nota = %.1f \n", nota[0]); printf("A segunda nota = %.1f \n", nota[1]); printf("A terceira nota = %.1f \n", nota[2]); printf("A media das 3 notas = %1.f \n\n", nota[3]); system("pause"); return 0; }
C
#include <ctype.h> #include <stdio.h> #include <string.h> #include <time.h> #include <unistd.h> #include "CalendarParser.h" #include "Helpers.h" int main(int argc, char *argv[]) { char *toPrint; char choice[256]; char fileName[256]; time_t t = time(NULL); struct tm tm = *localtime(&t); Alarm *alarm; Calendar *cal = NULL; Calendar *tempCal = NULL; Event *event; ICalErrorCode err; while(true) { printf("\n1) Read iCal file\n2) Display calendar\n3) Create new calendar object\n"); printf("4) Write calendar object to file\n5) Exit\n\n"); scanf("%s", choice); if(strcmp(choice, "1") == 0) { while(true) { if(cal) { printf("Calendar already populated. Would you like to clear it and open another one?"); printf(" Anything that isn't y will return to the main menu.\n"); scanf("%s", choice); if(strcmp(choice, "y") == 0) { deleteCalendar(cal); cal = NULL; } else { break; } } printf("Please input a path string to the file to be parsed or \"exit\" to return to the menu.\n"); scanf("%s", choice); if(strcmp(choice, "exit") == 0) { break; } err = createCalendar(choice, &cal); if(err != OK) { toPrint = printError(err); printf("\nError parsing file: %s\n", toPrint); free(toPrint); cal = NULL; } else { printf("File successfully parsed. Calendar can now be displayed.\n"); break;; } } } else if(strcmp(choice, "2") == 0) { if(cal) { toPrint = printCalendar(cal); printf("%s\n", toPrint); free(toPrint); } else { printf("A file has not been successfully opened, parsed and saved yet.\n"); } } else if(strcmp(choice, "3") == 0) { if(cal) { printf("\nCalendar already populated. Would you like to clear it and create a new custom one?"); printf(" Anything that isn't y will return to the main menu.\n"); scanf("%s", choice); if(strcmp(choice, "y") != 0) { continue; } deleteCalendar(cal); cal = NULL; } tempCal = (Calendar*)malloc(sizeof(Calendar)); tempCal->version = 0.0; tempCal->properties.head = NULL; while(tempCal->version == 0.0) { printf("\n\nPlease enter a valid version number:\n"); scanf("%s", choice); tempCal->version = atof(choice); } printf("\n\nEnter a product ID:\n"); scanf("%s", choice); strcpy(tempCal->prodID, choice); tempCal->events = initializeList(&printFuncEvent, &deleteFuncEvent, &compareFuncEvent); event = (Event*)malloc(sizeof(Event)); event->properties.head = NULL; printf("\n\nEnter UID for the event:\n"); scanf("%s", choice); strcpy(event->UID, choice); strftime(event->creationDateTime.date, 100, "%Y%m%d", &tm); strftime(event->creationDateTime.time, 100, "%H%M%S", &tm); event->creationDateTime.UTC = 0; event->alarms = initializeList(&printFuncAlarm, &deleteFuncAlarm, &compareFuncAlarm); alarm = (Alarm*)malloc(sizeof(Alarm)); alarm->properties.head = NULL; printf("\n\nEnter Trigger for the alarm:\n"); scanf("%s", choice); alarm->trigger = (char*)malloc(sizeof(char) * (strlen(choice) + 1)); strcpy(alarm->trigger, choice); printf("\n\nEnter Action for the event:\n"); scanf("%s", choice); strcpy(alarm->action, choice); insertBack(&event->alarms, (void*)alarm); alarm = NULL; insertBack(&tempCal->events, (void*)event); event = NULL; err = validateCalendar(tempCal); if(err != OK) { toPrint = printError(err); printf("\nCalendar failed to validate: %s\n", toPrint); free(toPrint); deleteCalendar(tempCal); } else { cal = tempCal; } tempCal = NULL; } else if(strcmp(choice, "4") == 0) { if(cal) { printf("Please enter a file name.\n"); scanf("%s", fileName); if(access(fileName, F_OK) != -1) { printf("\nFile already exists. Would you like to overwrite it with your custom calendar?"); printf(" Anything that isn't y will return to the main menu.\n"); scanf("%s", choice); if(strcmp(choice, "y") != 0) { continue; } } err = validateCalendar(cal); if(err == OK) { err = writeCalendar(fileName, cal); } else { toPrint = printError(err); printf("\nCalendar failed to validate: %s\n", toPrint); free(toPrint); continue; } if(err != OK) { toPrint = printError(err); printf("\nError writing to file: %s\n", toPrint); free(toPrint); } else { printf("\n%s successfully written. Calendar can now be displayed. Custom calendar cleared.\n", fileName); deleteCalendar(cal); cal = NULL; } } else { printf("Custom calendar has not been created yet.\n"); } } else if(strcmp(choice, "5") == 0) { printf("Exiting...\n"); break; } else { printf("Please enter a valid input number between 1 and 5.\n"); } } if(cal) { deleteCalendar(cal); } return 0; }
C
#include "option.h" /** * options - initialize and access a static table of options indexed by name * * Return: a pointer to the static option table */ option_table_t *options(void) { static option_table_t option_table = {{0}}; static option_t option_table_init[] = OPTION_TABLE_INIT; static option_t *opt = option_table_init; size_t index = 0; while ((index = opt->name)) option_table[index] = *opt++; return (&option_table); } /** * option_is_defined - check if an option exists in the option table * @c: single-character option identifier * * Return: true if the option c exists, otherwise false */ bool option_is_defined(int c) { return (c < OPTION_TABLE_SIZE && (*options())[c].name); } /** * option_is_enabled - check if an option is enabled in the option table * @c: single-character option identifier * * Return: true if the option c is enabled, otherwise false */ bool option_is_enabled(int c) { return (c < OPTION_TABLE_SIZE && (*options())[c].enabled); }
C
/* ** join_chan.c for epitech in /home/chapuis_s/rendu/ ** ** Made by chapui_s ** Login <chapui_s@epitech.eu> ** ** Started on Tue Apr 7 16:18:21 2015 chapui_s ** Last update Thu Apr 16 00:05:36 2015 chapui_s */ #include "server.h" static void send_to_chanel(t_client *root, char *from, char *channel) { t_client *tmp; tmp = root->next; while (tmp != root) { if (tmp->channel && is_in_channel(tmp->channel, channel)) { reply(tmp, 702, from, channel); } tmp = tmp->next; } } static void send_info(t_server *server, t_client *client, char *channel) { reply(client, RPL_TOPIC, client->nick, channel, TOPIC); names(server, client); } int join_chan(t_server *server, t_client *client) { char *channel; if (!client->tab_cmd[1]) { reply(client, ERR_NEEDMOREPARAMS, client->tab_cmd[0]); } else { channel = client->tab_cmd[1]; if (channel && channel[0] == '#') { channel += 1; } if (!is_in_channel(client->channel, channel)) { push_channel(&(client->channel), channel); send_to_chanel(server->root_clients, client->nick, channel); send_info(server, client, channel); #ifdef DEBUG fprintf(stdout, "--%s JOIN %s\n", client->nick, channel); #endif } } return (0); }
C
#pragma once struct WaveFormat { WaveFormat() { for (int i = 0; i < 4; ++i) { chunkId[i] = NULL; format[i] = NULL; subchunk1Id[i] = NULL; subchunck2Id[i] = NULL; } chunkSize = NULL; subchunk1Size = NULL; audioFormat = NULL; numChannels = NULL; sampleRate = NULL; byteRate = NULL; blockAlign = NULL; bitsPerSample = NULL; subchunk2Size = NULL; } bool Check() const { for (int i = 0; i < 4; ++i) { if (!chunkId[i] || !format[i] || !subchunk1Id[i] || !subchunck2Id[i]) return false; } return chunkSize && subchunk1Size && subchunk2Size && audioFormat && numChannels && sampleRate && byteRate && blockAlign && bitsPerSample; } char chunkId[4]; unsigned long chunkSize; char format[4]; char subchunk1Id[4]; unsigned long subchunk1Size; unsigned short audioFormat; unsigned short numChannels; unsigned long sampleRate; unsigned long byteRate; unsigned short blockAlign; unsigned short bitsPerSample; char subchunck2Id[4]; unsigned long subchunk2Size; }; typedef unsigned char byte; const unsigned long defaultChunkSize = 16384;
C
#include "wild.h" char *pageNotFound() { return "<html><title>PAGE NOT FOUND</title><body> <p> </p> <p>WildBrowser is afraid to inform you that it was unable to reach the site you gave. Press Enter to go type an address.</p> </body></html>"; } char *openingPage() { return "<html> <title>Welcome to WildBrowser!</title><body> <p> </p> <p>Welcome to WildBrowser, a rudimentary text-based web browser! Press Enter to go type an address.</p> </body> </html>"; } char *getHostName(char *request) { int i = 0; char *hostName = (char *)malloc(sizeof(char) * strlen(request)); if(my_modified_strcmp(request, "http://")) request = &request[7]; while(request[i] != '/' && request[i] != '\0') /* if you reach the query or the end */ { hostName[i] = request[i]; i++; } return hostName; } char *getQuery(char *request) { int i = 0; if(my_modified_strcmp(request, "http://")) request = &request[7]; while(request[i] != '/' && request[i] != '\0') /* if you reach the query or the end */ i++; if(request[i] == '\0') return "/"; else return &request[i]; } char *webRequest(char *request) { int sockfd, portno, n, bytesRead, running, pageMalloc, i; struct sockaddr_in serv_addr; struct hostent *receivedServer; struct hostent server; char *readingPage; char *readPage; char *tempPage; char *httpCall; portno = 80; sockfd = socket(AF_INET, SOCK_STREAM, 0); if (sockfd < 0) error("ERROR opening socket"); receivedServer = gethostbyname(getHostName(request)); if(receivedServer == (void *)0) /* received server is null */ return pageNotFound(); else server = *receivedServer; bzero((char *) &serv_addr, sizeof(serv_addr)); serv_addr.sin_family = AF_INET; bcopy((char *)server.h_addr, (char *)&serv_addr.sin_addr.s_addr, server.h_length); serv_addr.sin_port = htons(portno); if (connect(sockfd,(struct sockaddr *) &serv_addr,sizeof(serv_addr)) < 0) error("ERROR connecting"); httpCall = (char *)malloc(sizeof(char) * 1024); strcpy(httpCall, "GET "); strcat(httpCall, getQuery(request)); strcat(httpCall, " HTTP/1.1\r\nHost: "); strcat(httpCall, getHostName(request)); strcat(httpCall, "\r\n\r\n"); my_str(httpCall); if (write(sockfd, httpCall, 1024) < 0) /* request page */ error("write() error!\n"); pageMalloc = 65536; /* get entire page, then parse */ readingPage = (char *)malloc(sizeof(char) * pageMalloc); readPage = (char *)malloc(sizeof(char) * pageMalloc); while(read(sockfd, readingPage, 65536) > 0) { tempPage = (char *)malloc(sizeof(char) * pageMalloc); /* tempPage holds existing readPage */ strcpy(tempPage, readPage); pageMalloc += 65536; readPage = (char *)malloc(sizeof(char) * pageMalloc); strcpy(readPage, tempPage); strcat(readPage, readingPage); bzero(readingPage, 65536); bzero(tempPage, pageMalloc - 65536); } for (i = 0; i < strlen(readPage); i++) { if (readPage[i] == '<') break; } return &readPage[i]; }
C
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <fcntl.h> #include <sys/stat.h> #include "holberton.h" /** * main - copies the content of a file to another file * @argc: integer number of arguments (must be 3) * @argv: array of arguments * * Return: 1 on success, exit with error code otherwise */ int main(int argc, char **argv) { char buffer[1024]; int fd_to, fd_from, bytes_read = 1024, bytes_wrote; if (argc != 3) { dprintf(STDERR_FILENO, "Usage: cp file_from file_to\n"); exit(97); } fd_from = open(argv[1], O_RDONLY); if (fd_from == -1) { dprintf(STDERR_FILENO, "Error: Can't read from file %s\n", argv[1]); exit(98); } fd_to = open(argv[2], O_CREAT | O_TRUNC | O_WRONLY, 0664); if (fd_to == -1) { dprintf(STDERR_FILENO, "Error: Can't write to %s\n", argv[2]); exit(99); } while (bytes_read == 1024) { bytes_read = read(fd_from, buffer, 1024); if (bytes_read == -1) { dprintf(STDERR_FILENO, "Error: Can't read from file %s\n", argv[1]); exit(98); } bytes_wrote = write(fd_to, buffer, bytes_read); if (bytes_wrote == -1 || bytes_wrote < bytes_read) { dprintf(STDERR_FILENO, "Error: Can't write to %s\n", argv[2]); exit(99); } } if (close(fd_to) == -1) { dprintf(STDERR_FILENO, "Error: Can't close fd %d\n", fd_to); exit(100); } if (close(fd_from) == -1) { dprintf(STDERR_FILENO, "Error: Can't close fd %d\n", fd_from); exit(100); } return (0); }
C
#ifndef __ANGLE_CHECKER__ #define __ANGLE_CHECKER__ struct AngleChecker { struct Checker { bool Check( float Angle ) { if( Angle >= Start && Angle <= End )return true; Angle -= 2; if( Angle >= Start && Angle <= End )return true; return false; } void Set( const float& S, const float& E ) { if( S > E ) { Start = E; End = S; } else { Start = S; End = E; } if( End > 2.0f ) { Start -= 2.0f; End -= 2.0f; } } float Start; float End; }; struct Counter : protected Checker { bool Check( const float& Angle ) { if( !Checker::Check( Angle ) )return false; Count++; return true; } void Set( float Angle, float Width ) { if( Angle >= 2 )Angle -= 2; MyAngle = Angle; Checker::Set( Angle-Width, Angle+Width ); Count = 0; } float MyAngle; long Count; }; }; #endif //__ANGLE_CHECKER__
C
#include <stdio.h> #include <stdlib.h> extern int CheckABS( int numx, int tam, int *seq); int main(void) { int x = 20; int tamanho = 8; int ve[] = {7, -8, -23, 56, 20, -10, 0, 40}; int res; res = CheckABS(x, tamanho, ve); printf("Foram modificados %d elementos da sequencia ve[]", res); return EXIT_SUCCESS; }
C
//########################################################## //## R O B O T I S ## //## CM-700 (Atmega2561) Example code for Dynamixel. ## //## 2009.11.10 ## //########################################################## //Edited By Curtis Cox //FIU Discovery Lab #include <avr/io.h> #include <avr/interrupt.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #define F_CPU 16000000 //16mHZ processor #include <util/delay.h> #include "dynamixel.h" #include "serial.h" /// Control table address #define P_STATUS_RETURN_LEVEL 16 #define P_GOAL_POSITION_L 30 #define P_GOAL_POSITION_H 31 #define P_PRESENT_POSITION_L 36 #define P_PRESENT_POSITION_H 37 #define P_MOVING 46 #define P_PGAIN 28 #define P_PGAIN_DEFAULT_VALUE 32 #define P_IGAIN 27 #define P_DGAIN 26 #define P_GOAL_SPEED_L 32 #define P_GOAL_SPEED_H 33 #define MSG_BUF_SIZE 128 #define SERVO_SPEED_DEFAULT_VALUE 100 // Default setting #define DEFAULT_BAUDNUM 1 // 1Mbps #define DEFAULT_ID 1 void PrintCommStatus(int CommStatus); void PrintErrorCode(void); unsigned char msgBuf0[MSG_BUF_SIZE]; unsigned char msgBuf1[MSG_BUF_SIZE]; unsigned char msgBuf2[10]; int msgBufPointer = 0; int gainCounter = 0; int main(void) { unsigned short currentPosition[14]; unsigned short servoIdList[14] = {10, 11, 20, 21, 22, 23, 24, 25, 30, 31, 32, 33, 34, 35}; int wPresentPos; int CommStatus; int servoID = 0; int servoPosition = 0; int servoSpeed = 0; int pGain = 128; int iGain = 0; int dGain = 0; unsigned char ReceivedData; msgBuf2[0] = '<'; msgBuf2[3] = ' '; msgBuf2[8] = '>'; msgBuf2[9] = '\0'; serial_initialize(57600); dxl_initialize(0, DEFAULT_BAUDNUM); // Not using device index sei(); // Interrupt Enable // printf( "\n\nRead/Write example for CM-700\n\n" ); // printf( "\n\nTeleBot Arm Controller (CM-700) ver-0.1.1 (0819-2013)\n\n" ); // printf( "\n\nTeleBot Arm Controller (CM-700) ver-0.1.2 (1023-2013)\n\n" ); // printf( "\n\nTeleBot Arm Controller (CM-700) ver-0.1.3 (1125-2013)\n\n" ); printf( "\n\nTeleBot Arm Controller (CM-700) ver-0.1.4 (0222-2016)\n\n" ); for( int i = 0; i < 14; i++) { servoID = servoIdList[i]; //Set PID values dxl_write_word(servoID, P_PGAIN, pGain); _delay_ms(5); dxl_write_word(servoID, P_IGAIN, iGain); _delay_ms(5); dxl_write_word(servoID, P_DGAIN, dGain); _delay_ms(5); // Set goal speed dxl_write_word(servoID, P_GOAL_SPEED_L, SERVO_SPEED_DEFAULT_VALUE); _delay_ms(5); dxl_write_word(servoID, P_STATUS_RETURN_LEVEL, 1); _delay_ms(5); } while(1) { ReceivedData = getchar(); if(ReceivedData == '?') { //send servo positions if they have changed since last check for (int j = 0; j<14; j++) { servoID = servoIdList[j]; wPresentPos = dxl_read_word(servoID, P_PRESENT_POSITION_L); _delay_ms(1); CommStatus = dxl_get_result(); _delay_ms(1); if(CommStatus == COMM_RXSUCCESS) { if(currentPosition[j] != wPresentPos) { currentPosition[j] = wPresentPos; msgBuf2[1] = servoID/10 + '0'; msgBuf2[2] = servoID%10 + '0'; msgBuf2[4] = wPresentPos/1000 +'0'; wPresentPos %= 1000; msgBuf2[5] = wPresentPos/100 +'0'; wPresentPos %= 100; msgBuf2[6] = wPresentPos/10 + '0'; msgBuf2[7] = wPresentPos%10 + '0'; for(int k = 0; k<10; k++) putchar(msgBuf2[k]); } } } } else if(ReceivedData == '<') { msgBufPointer = 0; } else if(ReceivedData == '>') { msgBuf0[msgBufPointer]='\0'; memcpy ( msgBuf1, msgBuf0, strlen((char*)msgBuf0) ); char * pch1; char * pch2; int cnt = 0; pch1 = strtok ((char*)msgBuf0," "); while (pch1 != NULL) { cnt++; pch1 = strtok (NULL, " "); } pch2 = strtok ((char*)msgBuf1," "); if ( cnt == 1 ) { if(strncmp (pch2,"gn",2)==0) { printf("cm-700\n"); } } else if (cnt == 2) { servoID = -1; servoPosition = -1; servoSpeed = -1; while (pch2 != NULL) { if (cnt == 2) { servoID = atoi(pch2); } else if (cnt == 1) { servoPosition = atoi(pch2); } cnt--; pch2 = strtok (NULL, " "); } dxl_write_word(servoID, P_GOAL_POSITION_L, servoPosition); } else if (cnt == 3) { servoID = -1; servoPosition = -1; servoSpeed = -1; while (pch2 != NULL) { if (cnt == 3) { servoID = atoi(pch2); } else if (cnt == 2) { servoPosition = atoi(pch2); } else if (cnt == 1) { servoSpeed = atoi(pch2); } cnt--; pch2 = strtok (NULL, " "); } // Set pGain dxl_write_word( servoID, P_PGAIN, P_PGAIN_DEFAULT_VALUE); _delay_ms(1); // Set goal speed dxl_write_word( servoID, P_GOAL_SPEED_L, servoSpeed ); _delay_ms(1); // Set goal position dxl_write_word( servoID, P_GOAL_POSITION_L, servoPosition ); } else if (cnt == 4) { servoID = -1; servoPosition = -1; servoSpeed = -1; pGain = 3; while (pch2 != NULL) { if (cnt == 4) { servoID = atoi(pch2); } else if (cnt == 3) { servoPosition = atoi(pch2); } else if (cnt == 2) { servoSpeed = atoi(pch2); } else if (cnt == 1) { pGain = atoi(pch2); if (pGain > 32) pGain = 32; } cnt--; pch2 = strtok (NULL, " "); } // Set pGain dxl_write_word( servoID, P_PGAIN, pGain); _delay_ms(1); // Set goal speed if(servoSpeed != 0) { dxl_write_word( servoID, P_GOAL_SPEED_L, servoSpeed ); _delay_ms(1); } // Set goal position dxl_write_word( servoID, P_GOAL_POSITION_L, servoPosition ); _delay_ms(1); } for(int i = 0; i < MSG_BUF_SIZE; i++) { msgBuf0[i]=0x00; msgBuf1[i]=0x00; } } else { if (msgBufPointer >= MSG_BUF_SIZE-1) { msgBufPointer = 0; for(int i = 0; i < MSG_BUF_SIZE; i++) { msgBuf0[i]=0x00; msgBuf1[i]=0x00; } } msgBuf0[msgBufPointer]=ReceivedData; msgBufPointer++; } } return 0; } // Print communication result void PrintCommStatus(int CommStatus) { switch(CommStatus) { case COMM_TXFAIL: printf("COMM_TXFAIL: Failed transmit instruction packet!\n"); break; case COMM_TXERROR: printf("COMM_TXERROR: Incorrect instruction packet!\n"); break; case COMM_RXFAIL: printf("COMM_RXFAIL: Failed get status packet from device!\n"); break; case COMM_RXWAITING: printf("COMM_RXWAITING: Now recieving status packet!\n"); break; case COMM_RXTIMEOUT: printf("COMM_RXTIMEOUT: There is no status packet!\n"); break; case COMM_RXCORRUPT: printf("COMM_RXCORRUPT: Incorrect status packet!\n"); break; default: printf("This is unknown error code!\n"); break; } } // Print error bit of status packet void PrintErrorCode() { if(dxl_get_rxpacket_error(ERRBIT_VOLTAGE) == 1) printf("Input voltage error!\n"); if(dxl_get_rxpacket_error(ERRBIT_ANGLE) == 1) printf("Angle limit error!\n"); if(dxl_get_rxpacket_error(ERRBIT_OVERHEAT) == 1) printf("Overheat error!\n"); if(dxl_get_rxpacket_error(ERRBIT_RANGE) == 1) printf("Out of range error!\n"); if(dxl_get_rxpacket_error(ERRBIT_CHECKSUM) == 1) printf("Checksum error!\n"); if(dxl_get_rxpacket_error(ERRBIT_OVERLOAD) == 1) printf("Overload error!\n"); if(dxl_get_rxpacket_error(ERRBIT_INSTRUCTION) == 1) printf("Instruction code error!\n"); }
C
#include "avm.h" unsigned currLine = 0; unsigned pc = 0; unsigned char executionFinished = 0; unsigned totalActuals = 0; unsigned codeSize = 0; instruction* code = (instruction*) 0; unsigned currCode = 0; avm_memcell ax; avm_memcell bx; avm_memcell cx; avm_memcell retval; execute_func_t executeFuncs[] = { execute_assign, execute_add, execute_sub, execute_mul, execute_div, execute_mod, execute_uminus, execute_and, execute_or, execute_not, execute_jeq, execute_jne, execute_jle, execute_jge, execute_jlt, execute_jgt, execute_call, execute_pusharg, execute_funcenter, execute_funcexit, execute_newtable, execute_tablegetelem, execute_tablesetelem, execute_nop }; void init_code(unsigned size) { code = (instruction*) malloc(sizeof(instruction)* size); currCode = 0; codeSize = size; } void emit_code (instruction t) { instruction* temp = code + currCode++; temp->opcode = t.opcode; temp->arg1 = t.arg1; temp->arg2 = t.arg2; temp->result = t.result; } void print_operand(vmarg arg) { char* str = (char*) malloc(sizeof(char)*50); switch (arg.type) { case label_a : sprintf(str, "%d, %d ", arg.type, arg.val); break; case global_a : sprintf(str, "%d, %d:%s ", arg.type, arg.val, arg.id); break; case formal_a : sprintf(str, "%d, %d:%s ", arg.type, arg.val, arg.id); break; case local_a : sprintf(str, "%d, %d:%s ", arg.type, arg.val, arg.id); break; case number_a : sprintf(str, "%d,%d:%f ", arg.type, arg.val, numConsts[arg.val]); break; case string_a : sprintf(str, "%d,%d:%s ", arg.type, arg.val, stringConsts[arg.val]); break; case bool_a : sprintf(str, "%d, %d:%s ", arg.type, arg.val, arg.id); break; case nil_a : sprintf(str, "%d ", arg.type); break; case userfunc_a : sprintf(str, "%d, %d:%s ", arg.type, arg.val, userFuncs[arg.val].id); break; case libfunc_a : sprintf(str, "%d, %d:%s ", arg.type, arg.val, namedLibfuncs[arg.val]); break; case retval_a : sprintf(str, "%d ", arg.type) ; break; } printf("|%-20s", str); } void print_stack() { int i; for (i = AVM_STACKSIZE-1; stack[i].type != undef_m; i--) { printf("%d: %f\n", i, stack[i].data.numVal); } } void print_code () { char* op_array[] = { "assign", "add", "sub", "mul", "div", "mod", "uminus", "and", "or", "not", "jeq", "jne", "jle" "jge", "jlt" "jqt", "call", "pusharg", "funcenter", "funcexit", "newtable" "tablegetelem", "tablesetelem", "jump", "nop" }; int i; for (i = 0; i < codeSize; i++) { printf("%-2d %-30s ", i, op_array[code[i].opcode]); print_operand(code[i].result); print_operand(code[i].arg1); print_operand(code[i].arg2); printf("\n"); } printf("-----------------------------------------\n"); } avm_memcell* avm_translate_operand(vmarg* arg, avm_memcell* reg){ switch(arg->type){ /*Variables*/ case global_a: return &stack[AVM_STACKSIZE-1-arg->val]; case local_a: return &stack[topsp-arg->val]; case formal_a: return &stack[topsp+AVM_STACKENV_SIZE+1+arg->val]; case retval_a: return &retval; case number_a: { reg->type = number_m; reg->data.numVal = numConsts[arg->val]; return reg; } case string_a: { reg->type = string_m; reg->data.strVal = strdup(stringConsts[arg->val]); return reg; } case bool_a: { reg->type = bool_m; reg->data.boolVal = arg->val; return reg; } case nil_a: reg->type = nil_m; return reg; case userfunc_a: { reg->type = userfunc_m; reg->data.funcVal = arg->val; /*Address already stored*/ return reg; } case libfunc_a: { reg->type = libfunc_m; reg->data.libfuncVal = libfuncs_getused(arg->val); return reg; } default: assert (0); } } void execute_cycle(void) { if(executionFinished) return; else if(pc == AVM_ENDING_PC){ executionFinished = 1; return; } else { assert(pc < AVM_ENDING_PC ); instruction* instr = code + pc; assert(instr->opcode >= 0 && instr->opcode <= AVM_MAX_INSTRUCTIONS); if (instr-> srcLine) { currLine = instr->srcLine; } unsigned oldPC = pc; (*executeFuncs[instr->opcode])(instr); if (pc == oldPC) { ++pc; } execute_cycle(); } } void avm_warning(char* war){ printf("Warning: %s", war); } void avm_error(char* err, void *content) { executionFinished = 1; printf(err, content); } void avm_assign (avm_memcell* lv, avm_memcell* rv){ if (lv == rv) return; if (lv->type == table_m && rv->type == table_m && lv->data.tableVal == rv->data.tableVal) { return; } if (rv->type == undef_m) { avm_warning("assigning from 'undef' content!"); } avm_memcellclear(lv); memcpy(lv , rv , sizeof(avm_memcell)); if (lv->type == string_m) lv->data.strVal= strdup(rv->data.strVal); else if (lv->type == table_m) avm_tableincrefcounter(lv->data.tableVal); } void execute_assign (instruction* instr) { avm_memcell* lv = avm_translate_operand(&instr->result , (avm_memcell*)0); avm_memcell* rv = avm_translate_operand(&instr->arg1 , &ax); //printf("ARG1 %s %f RESULT %s %f \n",instr->result.id, lv->data.numVal ,instr->arg1.id ,rv->data.numVal); assert(lv); //assert(&stack[AVM_STACKSIZE-1] <= lv); //assert(lv > &stack[top] || lv == &retval); //assert(lv && ( &stack[AVM_STACKSIZE-1] <= lv && lv > &stack[top] || lv == &retval)); //assert(rv && ( &stack[AVM_STACKSIZE-1] <= rv && lv > &stack[top] || rv == &retval)); avm_assign(lv,rv); } void execute_uminus(instruction* t){} void execute_and(instruction* t) {} void execute_or(instruction* t) {} void execute_not(instruction* t) {} void execute_jeq(instruction* instr){ assert(instr->result.type == label_a); avm_memcell* rv1 = avm_translate_operand(&instr->arg1, &ax); avm_memcell* rv2 = avm_translate_operand(&instr->arg2, &bx); unsigned char result = 0; if (rv1->type == undef_m || rv2->type == undef_m) { avm_error("'Undef' involved in equality!", ""); } else if(rv1->type == nil_m || rv2->type == nil_m) { result = (rv1->type == nil_m) && (rv2->type == nil_m); } else if(rv1->type == bool_m || rv2->type == bool_m) { result=rv1->data.boolVal == rv2->data.boolVal; } else if(rv1->type !=rv2->type) { avm_error("String is illegal!", ""); } else { } if(!executionFinished && result){ pc = instr->result.val; } } void execute_jne(instruction* t) { } void execute_jle(instruction* t) { } void execute_jge(instruction* t) { } void execute_jlt(instruction* t) { execute_relop(t); } void execute_jgt(instruction* t) { printf("HELL\n" ); execute_relop(t); } void execute_nop(instruction* t){ } // void avm_initialize() { // avm_initstack(); // avm_registerlibfunc("print", libfunc_print); // avm_registerlibfunc("input", libfunc_input); // avm_registerlibfunc("objectmemberkyes", libfunc_objectmemberkyes); // avm_registerlibfunc("objectotslmembers", libfunc_objectotslmembers); // avm_registerlibfunc("objectcopy", libfunc_objectcopy); // avm_registerlibfunc("totalarguments", libfunc_totalarguments); // avm_registerlibfunc("argument", libfunc_argument); // avm_registerlibfunc("typeof", libfunc_typeof); // avm_registerlibfunc("strtonum", libfunc_strtonum); // avm_registerlibfunc("sqrt", libfunc_sqrt); // avm_registerlibfunc("cos", libfunc_cos); // avm_registerlibfunc("sin", libfunc_sin); // }
C
#include <stdbool.h> #include <math.h> double nop(double x, int n); double ln(double x, int n); int main (int argc, char *argv[] ) { double result; result = ln(atof(argv[1]), 1000); printf("ln: %f", result); return 0; } double nop(double x, int n) { return x; } double ln(double x, int n) { int i; double result = 0; bool invert = false; if(x > 2) { x = 1/x; //taylor series works only for 0 < x < 2 invert = true; //we can use this to solve for remaining nums } if (x <= 0) { return 0; //ln of 0 or less is invalid } for(i=1; i<n; i++) { if(i%2 == 1) //add for odd, subtract for even result += pow((x-1), i) / i; else result -= pow((x-1), i) / i; } if(invert) result *= -1; return result; }
C
#include <stdlib.h> #include <assert.h> #include <unistd.h> #include <stdio.h> #include <signal.h> #include <limits.h> #include <e-hal.h> #include <e-loader.h> #include "addresses.h" #define BARRIER() __asm__("DMB") e_epiphany_t workgroup; e_mem_t memory; #define EXTERNAL_BASE 0x8e000000 #define READ(CORENO, PTR) read_mem(CORENO, PTR) int read_mem(int coreno, volatile void *ptr) { int word; ssize_t amount; if ((unsigned)ptr > EXTERNAL_BASE) { amount = e_read(&memory, 0, 0, (off_t)ptr - EXTERNAL_BASE, &word, sizeof(word)); } else { int row, col; e_get_coords_from_num(&workgroup, coreno, &row, &col); amount = e_read(&workgroup, row, col, (off_t)ptr, &word, sizeof(word)); } assert(amount == sizeof(word)); return word; } #define WRITE(CORENO, PTR, DATA) write_mem(CORENO, PTR, DATA) void write_mem(int coreno, volatile void *ptr, int data) { ssize_t amount; if ((unsigned)ptr > EXTERNAL_BASE) { amount = e_write(&memory, 0, 0, (off_t)ptr - EXTERNAL_BASE, &data, sizeof(data)); } else { int row, col; e_get_coords_from_num(&workgroup, coreno, &row, &col); amount = e_read(&workgroup, row, col, (off_t)ptr, &data, sizeof(data)); } assert(amount == sizeof(data)); } void cleanup() { int ret; ret = e_finalize(); if (ret != E_OK) perror("e_finalize"); } int memory_online = 0; void exit_with(const char *msg, int status) { fprintf(stderr, "%s\n", msg); cleanup(); exit(status); } void interrupted() { exit_with("Exiting! ", 130); } #define WIDTH 4 #define HEIGHT 4 #define COUNT (WIDTH*HEIGHT) volatile struct counter *get_mem(int core) { #if TEST_SHARED_MEMORY return &INCREMENT_VECTOR_ADDR[core * INCREMENT_CORE_STEP]; #else /* * We don't need to repeat the coordinate mirroring here; it's not important * what order we read the data. */ return INCREMENT_VECTOR_ADDR; #endif } void zero_vector() { for (int i = 0; i < COUNT; i++) { WRITE(i, &get_mem(i)->counter, 0); } BARRIER(); } /* * Return -1 if all cores are done and OK. * Return i+1 if core i detected a problem. */ int check_for_result() { int done = 0, result = 0; for (int i = 0; i < COUNT; i++) { volatile struct counter *mem = get_mem(i); int val = READ(i, &mem->counter); printf("%10d ", val); /* The cores set mem->counter to -i when they detect a problem */ if (val < 0) { result = i+1; printf(" (%d)", READ(i, &mem->actual)); } if (val == INT_MAX - 1) done++; } printf("\n"); if (done == COUNT) result = -1; return result; } int main(int argc, char *argv[]) { if (argc < 2) { fprintf(stderr, "Usage: %s [epiphany binary]\n", argv[0]); exit(1); } char *binary = argv[1]; int ret; signal(SIGINT, interrupted); ret = e_init(NULL); if (ret != E_OK) { return 1; } e_reset_system(); if (ret != E_OK) { perror("e_reset_system"); cleanup(); return 1; } ret = e_open(&workgroup, 0, 0, WIDTH, HEIGHT); if (ret != E_OK) { perror("e_open"); cleanup(); return 1; } ret = e_alloc(&memory, 0, 0x02000000 - 4); if (ret != E_OK) { perror("e_alloc"); cleanup(); return 1; } memory_online = 1; fprintf(stderr, "Testing address %p\n", get_mem(0)); zero_vector(); ret = e_load_group(binary, &workgroup, 0, 0, WIDTH, HEIGHT, E_TRUE); if (ret != E_OK) { perror("e_load"); cleanup(); return 1; } while(1) { int r = check_for_result(); if (r > 0) { exit_with("A core detected a memory inconsistency", r); } else if (r < 0) { exit_with("All cores finished OK", 0); } sleep(1); } }
C
//Header files #include <at89c5131.h> #include <stdio.h> //for sprintf functions #include <stdlib.h> //Bit definitions sbit RS=P0^0; sbit RW=0x81; //Also can use P0^1 or 0x80^1 sbit EN=P0^2; //Global variables //LCD functions void lcd_init(void); void lcd_cmd(unsigned int i); void lcd_char(unsigned char ch); void lcd_write_string(unsigned char *s); void port_init(void); //Delay function for time*1ms void msdelay(unsigned int time) { int i,j; for(i=0;i<time;i++) { for(j=0;j<318;j++); } } //LCD utility functions void lcd_cmd(unsigned int i) { RS=0; RW=0; EN=1; P2=i; msdelay(10); EN=0; } void lcd_char(unsigned char ch) { RS=1; RW=0; EN=1; P2=ch; msdelay(10); EN=0; } void lcd_write_string(unsigned char *s) { while(*s!='\0') //Can use while(*s) { lcd_char(*s++); } } void lcd_init(void) using 3 { lcd_cmd(0x38); msdelay(4); lcd_cmd(0x06); msdelay(4); lcd_cmd(0x0C); msdelay(4); lcd_cmd(0x01); msdelay(4); } //Port initialization void port_init(void) { P2=0x00; EN=0; RS=0; RW=0; } short sgn(short v){ if(v < 0) return -1; if(v > 0) return 1; return 0; } //Main function int main(void) { unsigned char floor_num1[16]; unsigned char floor_num2[16]; short curr_floor1 = 0; //current floor for lift 1 short curr_floor2 = 0; //current floor for lift 2 short init_pos = 0; //initial position of switch after each loop short inp = 0; // input from switch unsigned char prev_p0; port_init(); lcd_init(); P1 =0x00; sprintf(floor_num1,"Floor 1 = 0%d",0); lcd_cmd(0x80); lcd_write_string(floor_num1); sprintf(floor_num2,"Floor 2 = 0%d",0); lcd_cmd(0xC0); lcd_write_string(floor_num2); msdelay(500); P1 |= 0x0F; //port reading enabled prev_p0 = P1&0x01; while(1) { while(P1_0==prev_p0){P1_5=1;} //toggle P1_0 to tell the lift that a user is going to give its location prev_p0 = (~prev_p0)&0x01; while(P1_0==prev_p0){P1_5=0;} P1_7 = 1; //ready to take input msdelay(10000); //give 10 sec time to user to give whole input inp = P1&0x0F; //current postion of switches P1_7 = 0; //now lift action processing //if lift 1 is closer if(abs(curr_floor1 - inp) <= abs(curr_floor2 - inp)){ short iter; short diff = abs(curr_floor1 - inp); for(iter=1;iter<=diff;iter++){ msdelay(1000); curr_floor1 = curr_floor1 + sgn(inp - curr_floor1); //increase or decrease the current floor with 1sec delay if (curr_floor1 < 10){ sprintf(floor_num1," 0%d",curr_floor1); lcd_cmd(0x89); lcd_write_string(floor_num1); } else{ sprintf(floor_num1," %d",curr_floor1); lcd_cmd(0x89); lcd_write_string(floor_num1); } } init_pos = P1&0x0F; //initial postion of the switch inp = init_pos; P1_4 = 1; while(inp==init_pos){ inp = P1&0x0F; //current postion of switches msdelay(5000); //give time to user to give whole input P1_4 = 0; msdelay(1000); P1_4 = 1; } P1_4 = 0; //now lift action processing diff = abs(curr_floor1 - inp); for(iter=1; iter<=diff; iter++){ msdelay(1000); curr_floor1 = curr_floor1 + sgn(inp - curr_floor1); //increase or decrease the current floor with 1sec delay if (curr_floor1 < 10){ sprintf(floor_num1," 0%d",curr_floor1); lcd_cmd(0x89); lcd_write_string(floor_num1); } else{ sprintf(floor_num1," %d",curr_floor1); lcd_cmd(0x89); lcd_write_string(floor_num1); } } } //if lift 2 is closer else{ short iter; short diff = abs(curr_floor2 - inp); for(iter=1; iter<=diff; iter++){ msdelay(1000); curr_floor2 = curr_floor2 + sgn(inp - curr_floor2); //increase or decrease the current floor with 1sec delay if (curr_floor2 < 10){ sprintf(floor_num2," 0%d",curr_floor2); lcd_cmd(0xC9); lcd_write_string(floor_num2); } else{ sprintf(floor_num2," %d",curr_floor2); lcd_cmd(0xC9); lcd_write_string(floor_num2); } } init_pos = P1&0x0F; //initial postion of the switch inp = init_pos; P1_4 = 1; while(inp==init_pos){ inp = P1&0x0F; //current postion of switches msdelay(5000); //give time to user to give whole input P1_4 = 0; msdelay(1000); P1_4 = 1; } P1_4 = 0; //now lift action processing diff = abs(curr_floor2 - inp); for(iter=1; iter<=diff; iter++){ msdelay(1000); curr_floor2 = curr_floor2 + sgn(inp - curr_floor2); //increase or decrease the current floor with 1sec delay if (curr_floor2 < 10){ sprintf(floor_num2," 0%d",curr_floor2); lcd_cmd(0xC9); lcd_write_string(floor_num2); } else{ sprintf(floor_num2," %d",curr_floor2); lcd_cmd(0xC9); lcd_write_string(floor_num2); } } } prev_p0 = P1_0; //store the current position of switch so as toggle for next iteration } }
C
#include <stdio.h> int main () { int coordinate; printf("Input target coordinate: "); scanf("%d", &coordinate); if (coordinate >= -5 && coordinate <= 5 ) { puts("Close enough!"); } else { puts("Target is out of range."); } return(0); }
C
// lac_data.h #pragma once #include <stdint.h> #include <stdlib.h> #include <string.h> // counted strings are used as dictionary keys typedef struct { size_t size; uint8_t data[]; } lac_data; // allocate lac_data and copy data // use free() to free static inline lac_data* lac_data_alloc(size_t size, const uint8_t* data) { lac_data* p = malloc(sizeof(lac_data) + size); if (p) { p->size = size; memcpy(p->data, data, size); } return p; } static inline int lac_data_cmp(const lac_data* a, const lac_data* b) { int ret = b->size - a->size; if (0 == ret) { ret = memcmp(a->data, b->data, a->size); } return ret; }
C
#include <stdio.h> #include <stdlib.h> int* pascal(int size){ int* thisRow; if (size == 1){ thisRow = malloc(sizeof(int)); thisRow[0] = 1; }else{ int* lastRow = pascal(size-1); thisRow = malloc(sizeof(int)*size); thisRow[0] = 1; thisRow[size-1] = 1; for(int i = 1 ; i < size-1 ; i++){ thisRow[i] = lastRow[i-1] + lastRow[i]; } free(lastRow); } return thisRow; } int main(int argc, char** argv){ if(argc < 2){ printf("Not enough arguments\n"); return 1; } int size = atoi(argv[1])+1; int* pass = pascal(size); if (argc == 2){ for(int i=0; i<size; i++){ printf("%d,",pass[i]); } printf("\n"); } else{ printf("%d\n",pass[atoi(argv[2])]); } free(pass); return 0; }
C
# include "shared_tools.h" void delay(float number_of_seconds) { uint32_t dlyTicks = number_of_seconds * 667; uint32_t curTicks; curTicks = msTicks; while ((msTicks - curTicks) < dlyTicks) ; } void flushLocalBuffer(unsigned char *buf, int maxlen) { for (int i = 0; i < maxlen + 1; ++i) { buf[i] = '\0'; } }
C
#include <ons/ons.h> #include <memoria/memoria.h> #include <stdio.h> int main() { unsigned long i, ii, COUNT = 10000; mem_rbtree_t tree; mem_rbnode_t *nodes[COUNT]; char buffer[100]; for(i = 0; i < COUNT; ++i) nodes[i] = NULL; mem_rbt_init(&tree, NULL); for(ii = 0; ii < 100; ++ii) { for(i = 0; i < COUNT; ++i) { sprintf(buffer, "%u", rand()); if(!mem_rbt_add(&tree, MEM_STR(buffer), mem_malloc(100), &nodes[i])) ONS_ABORT("mem_rbt_add failed (collision in RNG)"); } for(i = 0; i < COUNT; ++i) { mem_free(mem_rbt_del(&tree, nodes[i])); nodes[i] = NULL; } } return 0; }
C
#include <stdio.h> #include <stdlib.h> #include "board.h" //set up the board void set_up(Board* b, int num_rows, int num_cols){ b->board = make_b(num_rows,num_cols); b->num_rows = num_rows; b->num_cols = num_cols; //pass in the type of numrows and numcols from struct return; } //make the board by using the values of numrows and numcols char** make_b(int num_rows, int num_cols){ char** b = (char**)malloc((num_rows) * sizeof(char*)); int i, j; for(i = 0; i < num_rows; ++i){ b[i] = (char*)malloc(num_cols*sizeof(char)); for(j = 0; j < num_cols; ++j){ b[i][j] = '*'; } } return b; } //print out the board void print_b(Board* b){ int i,j; for(i =(b->num_rows) - 1; i >= 0; --i){ printf("%d ", i); for(j = 0; j < b->num_cols; ++j){ printf("%c ",b->board[i][j]); } printf("\n"); } printf(" "); for(j = 0; j < b->num_cols; ++j){ printf("%d ", j); } printf("\n"); } //clean up the board(free the 2D array we created) void clean_b(Board* b){ int i; for(i = 0; i < b->num_rows; ++i){ free(b->board[i]); } free(b->board); }
C
//[TITANS] Processo Seletivo 01/2017 //Projeto Fantasma - Eletrônica Digital //Código Auxiliador v1.0 #include <stdlib.h> #include <stdio.h> int SF=0,ST=0,SD=0,SE=0; int MD=0, ME=0, AR=0; int estado_atual = 0; /* Sinais de entrada: SF: Sensor da Frente ST: Sensor de Trás SD: Sensor da Direita SE: Sensor da Esquerda Sinais de Controle: MD: Motor Direito ME: Motor Esquerdo AR: Arma Estados: Parado: estado_atual = 0 Para_Frente: estado_atual = 1 Virar_direita: estado_atual = 2 Virar_esquerda: estado_atual = 3 Atacar: estado_atual = 4 */ void Sinais_de_Entrada(){ printf("Sinais de Entrada:"); scanf("%d %d %d %d", &SF, &ST, &SD, &SE); } void Sinais_de_Controle(int estado){ switch(estado){ case 0: MD = 0; ME = 0; AR = 0; estado_atual = 0; printf("Parado\n"); printf("MD = %d\nME = %d\nAR = %d\n", MD, ME, AR); break; case 1: MD = 1; ME = 1; AR = 0; estado_atual = 1; printf("Para Frente\n"); printf("MD = %d\nME = %d\nAR = %d\n", MD, ME, AR); break; case 2: MD = 0; ME = 1; AR = 0; estado_atual = 2; printf("Virar a Direita\n"); printf("MD = %d\nME = %d\nAR = %d\n", MD, ME, AR); break; case 3: MD = 1; ME = 0; AR = 0; estado_atual = 3; printf("Virar a Esquerda\n"); printf("MD = %d\nME = %d\nAR = %d\n", MD, ME, AR); break; case 4: MD = 0; ME = 0; AR = 1; estado_atual = 4; printf("Atacar\n"); printf("MD = %d\nME = %d\nAR = %d\n", MD, ME, AR); break; default: printf("Estado Impossivel\n"); } } int main(){ while(1){ Sinais_de_Entrada(); // Monte sua Máquina de Estados Aqui // } return 0; }