language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
#include <gmp.h> /// Calculates the [n]th number in the Fibonacci sequence. /// \param n nth value to calculate /// \param r result variable /// \return 0 | success /// 1 | syntax error int fib(mpz_t n, mpz_t r);
C
#include <pbc/pbc.h> #include <string.h> #include <sha256.h> //#include <keys.h> #include <bls.h> struct element_s* bls_hash(void* data, int length, pairing_t pairing) { struct element_s* new_elem = (struct element_s*)malloc(sizeof(element_t)); element_init_G1(new_elem, pairing); element_from_hash(new_elem,data,length); return new_elem; } struct element_s* bls_hash_int(unsigned long long fid, unsigned long long value, pairing_t pairing) { struct element_s* ret; char int_str[22]; unsigned long long pow = 10; while(value >= pow) pow *= 10; unsigned long long concat = (fid * pow) + value; //printf("concat is %llu\n", concat); int len = sprintf(int_str,"%llu",concat); ret = bls_hash((void*)int_str,len,pairing); return ret; } char* hexstring(unsigned char* bytes, int len) { char* buffer = (char*)malloc(sizeof(char)*((2*len)+1)); char* temp = buffer; for(int i=0;i<len;i++) { sprintf(temp,"%02x",bytes[i]); temp += 2; } *temp = '\0'; return buffer; }
C
//An Array is a derived data-type, which is a collection of All Homogeneous elements stored in a sequential order. #include <stdio.h> int main() { //Declaration of an array. int arr[5]; int *ptr = arr; //int arr[]; //Not allowed. //Base address of an array. printf("Base Address of an array : %p\n", arr); //printf("%p\n", arr++); //We cannot change the base address of an array. //We can access the array index-wise and pointer-wise. //As we did not initialize the array, the below statement will represent the default value. printf("Element with its default value : %d\n", arr[0]); //Initialize the array. //Without iteration. arr[0] = 10, arr[1] = 20, arr[2] = 30, arr[3] = 40, arr[4] = 50; printf("\nElements without iteration : \n"); printf("%d\n", arr[0]); printf("%d\n", arr[1]); printf("%d\n", arr[2]); printf("%d\n", arr[3]); printf("%d\n", arr[4]); //With iteration. for(int i = 0; i < 5; i++) { arr[i] = i + 20; } printf("\nElements with iteration : \n"); for(int i = 0; i < 5; i++) { printf("%d\n", arr[i]); } printf("\nTaking value from user : \n"); scanf("%d", &arr[0]); printf("\nUpdated value of arr[0]: \n"); printf("%d", arr[0]); printf("\nSize of whole array in bytes : %ld\n", sizeof(arr)); printf("\nSize of First element in array in bytes : %ld\n", sizeof(arr[0])); printf("\nSize of pointer to an array : %ld\n", sizeof(ptr)); printf("\nSize of *ptr : %ld\n", sizeof(*ptr)); printf("\nBase Address of Array : %p\n", arr); printf("\nAddress of Whole Array : %p\n", &arr); printf("\nAddress of First Array : %p\n", &arr[0]); printf("\nAddress of Second Element: %p\n", arr + 1); //base address of an array + (size of an element) * constant :: 100 + 4 * 1, where 100 is base address, 4 is size of an element and 1 is that constant number. //printf("\nAddress of Second Element : %p\n", &(arr + 1)); printf("\nAddress at which this whole array ends: %p\n", &arr + 1); //100 + 1 * sizeof(whole array) //array initialization with member initialization list. //In the case of the member initialization list, the size of an array is optional. int brr[8] = {11,12,13,14}; printf("\nFirst element : %d\n", brr[0]); printf("\nFifth element : %d\n", brr[4]); for(int i = 0; i < 8; i++) { printf("%d\n", brr[i]); } printf("\nSize of whole array in bytes : %ld\n", sizeof(brr)); printf("\nSize of First element in array in bytes: %ld\n", sizeof(brr[0])); printf("\nSize of address of whole array in bytes : %ld\n", sizeof(&brr)); //We can access an index that is out of the array and also execute that index, but it will print some garbage value that is not in their memory space. printf("\nOut of Bound index : %d\n", brr[11]); return 0; }
C
//apt-get install gcc-multilib #include "thread.h" #include <assert.h> #include <stdlib.h> #include <stdio.h> // thread metadata struct thread { void *esp; struct thread *next; struct thread *prev; struct lock * lock; void * sp; }; struct thread *ready_list = NULL; // ready list struct thread *cur_thread = NULL; // current thread struct thread *sleeping_list = NULL; struct thread * exit_check=NULL; // defined in context.s void context_switch(struct thread *prev, struct thread *next); // insert the input thread to the end of the ready list. static void push_back(struct thread *t) { t->next = NULL; t->prev = NULL; struct thread * temp = ready_list; if(temp!=NULL){ // printf("second timeeeeee time\n"); while(temp->next!=NULL){ temp=temp->next; } temp->next=t; t->prev=temp; } else{ // printf("first time\n"); ready_list=t; ready_list->next = NULL; } } // remove the first thread from the ready list and return to caller. static struct thread *pop_front() { // printf("readyyyyyyyyyyyyyy before %p\n",ready_list); struct thread * temp=ready_list; ready_list=ready_list->next; // printf("readyyyyyyyyyyyyyy after %p\n",ready_list); return temp; } // the next thread to schedule is the first thread in the ready list. // obtain the next thread from the ready list and call context_switch. static void schedule() { // printf("ohhh laaaa scedule hu m\n" ); struct thread *prev = cur_thread; struct thread *next = pop_front(); cur_thread = next; context_switch(prev, next); } // push the cur_thread to the end of the ready list and call schedule // if cur_thread is null, allocate struct thread for cur_thread static void schedule1() { // printf("dfsgdhfg\n"); // printf("ohhh laaaa\n" ); if(cur_thread==NULL){ // printf("ohhh laaaa\n" ); int size=sizeof(cur_thread); cur_thread=(struct thread *)malloc(size); } // printf("push called in scedule1 \n"); push_back(cur_thread); schedule(); } // allocate stack and struct thread for new thread // save the callee-saved registers and parameters on the stack // set the return address to the target thread // save the stack pointer in struct thread // push the current thread to the end of the ready list void create_thread(func_t func, void *param) { struct thread *t = malloc(sizeof(struct thread)); unsigned *stack = malloc(4096); t->sp=stack; stack += 1024; // struct thread *t = malloc(sizeof(struct thread)); printf("mallloc ka ptr. %p\n",t); printf("stack vala ptr %p\n", stack); stack-=1; *(void * *)stack =param; stack-=1; *stack=0; stack-=1; *(func_t* )stack=func; stack-=1; *stack=0; stack-=1; *stack=0; stack-=1; *stack=0; stack-=1; *stack=0; t->esp=stack; push_back(t); } // call schedule1 void thread_yield() { schedule1(); } // call schedule void thread_exit() { if(exit_check!=NULL){ printf("free k sp %p\n", exit_check->sp); printf("free k thread %p\n", exit_check); fflush(NULL); free(exit_check->sp); free(exit_check); } exit_check=cur_thread; schedule(); } // call schedule1 until ready_list is null void wait_for_all() { while(ready_list!=NULL ){ schedule1(); } while(ready_list==NULL || sleeping_list!=NULL){ struct thread* temp=sleeping_list; // printf("temp hu m %p\n",temp); if(temp!=NULL){ sleeping_list=sleeping_list->next; if(sleeping_list!=NULL){ sleeping_list->prev=NULL; } } struct lock *lock; if(temp!=NULL){ lock=temp->lock; temp->lock->val=1; } // printf("lock ki waitlist hu mmmmmmmmm %p\n",lock->wait_list); // printf("lock hu m %p\n",lock); struct thread * pre; struct thread * curr; printf("lock hu mmmmmm %p\n",lock); if(lock==NULL){ printf("yipeeeeeeeee\n"); } if(lock!=NULL){ if(lock->wait_list!=NULL){ pre=((struct thread *)lock->wait_list)->prev; curr=lock->wait_list; } } // printf("preeeee %p\n",pre); while(curr!=NULL){ if(temp==curr){ if(pre==NULL){ // printf("yhssssssssss\n"); lock->wait_list=((struct thread *)lock->wait_list)->next; printf("lock sfter head %p\n",lock->wait_list); if(lock->wait_list!=NULL){ ((struct thread *)lock->wait_list)->prev=NULL; } curr->next=NULL; curr=lock->wait_list; pre=NULL; continue; } else{ // printf("yhsssssssssssssssssssssssssssssssss\n"); pre->next=curr->next; if(curr->next!=NULL){ curr->next->prev=pre; } curr->prev=NULL; curr=curr->next; continue; } } pre=curr; curr=curr->next; } // printf("lock ki waitlist hu m %p\n",lock->wait_list); if(temp!=NULL){ // printf("push calll \n"); push_back(temp); } schedule1(); // printf("readyyyyyyyyyyyyyy %p\n",ready_list); } } void sleep(struct lock *lock) { cur_thread->lock=lock; if(sleeping_list==NULL){ sleeping_list = cur_thread; cur_thread->next = NULL; } else{ struct thread * temp = sleeping_list; if(temp!=NULL){ while(temp->next!=NULL){ temp=temp->next; } temp->next=cur_thread; cur_thread->prev=temp; } } struct thread * temp = lock->wait_list; if(temp!=NULL){ while(temp->next!=NULL){ temp=temp->next; } temp->next=cur_thread; cur_thread->prev=temp; } else{ lock->wait_list = cur_thread; cur_thread->next = NULL; } // printf("wait_list of lock %p\n",lock->wait_list); schedule(); } void wakeup(struct lock *lock) { printf("wait_list of lock %p\n",lock->wait_list); if(lock->wait_list!=NULL){ struct thread * temp=lock->wait_list; temp->next=NULL; temp->prev=NULL; struct thread * pre=NULL; struct thread * curr=NULL; // printf("sleeeeee %p\n",sleeping_list ); if(sleeping_list!=NULL){ // printf("hereeeeee\n"); pre=sleeping_list->prev; curr=sleeping_list; } // printf("sleeeeee %p\n",sleeping_list ); // printf("currrrrrrrr %p\n",curr ); while(curr!=NULL){ // printf("currrrrrrrrrrrrrr %p\n",curr ); if(temp==curr){ // printf("athe hu m\n"); if(pre==NULL){ sleeping_list=sleeping_list->next; if(sleeping_list!=NULL){ sleeping_list->prev=NULL; } curr->next=NULL; curr=sleeping_list; pre=NULL; continue; } else{ pre->next=curr->next; if(curr->next!=NULL){ curr->next->prev=pre; } curr->prev=NULL; curr=curr->next; continue; } } pre=curr; curr=curr->next; } lock->wait_list=((struct thread*)lock->wait_list)->next; if(lock->wait_list!=NULL){ ((struct thread*)lock->wait_list)->prev=NULL; } push_back(temp); // printf("push called in wakeup\n"); } }
C
/* * File: util.h * Author: Georgios Varisteas * * Created on May 25, 2012, 1:15 PM */ #ifndef POND_UTIL_H #define POND_UTIL_H #ifdef BARRELFISH #include <barrelfish/domain.h> #else #include <stdlib.h> #include <stdio.h> #include <stdarg.h> #include <assert.h> #endif #include <pthread_compat.h> #include <config.h> #ifdef __cplusplus extern "C" { #endif #define ENTRIES(array) (sizeof(array) / sizeof(array[0])) static inline void *checked_malloc(int len) { void *p = malloc(len); if (!p) { #ifdef BARRELFISH USER_PANIC("Run out of memory!"); #else error("Run out of memory!"); #endif exit(1); } return p; } #ifndef BARRELFISH int setaffinity(pthread_t thread, unsigned short int c); int getaffinity(pthread_t thread); #endif char *itoa(int n, char *s, unsigned int b); char *strrev(char *); #define MIN(X,Y) ((X) < (Y) ? (X) : (Y)) #define MAX(X,Y) ((X) > (Y) ? (X) : (Y)) #define SLEEP(T) nanosleep(&T, NULL) /** * Wrapper function to wait on the conditional variable for a threaded event to complete */ static inline __attribute__((always_inline)) void signal_all_done(cond_t *c, mutex_t *m) { cerror(_SYS_DEBUG_SIGNAL, "signaling all done\n"); pthread_mutex_lock(m); pthread_cond_signal(c); pthread_mutex_unlock(m); cerror(_SYS_DEBUG_SIGNAL, "signaled all done\n"); } /** * Wrapper function to wait on the conditional variable for a threaded event to complete */ static inline __attribute__((always_inline)) void wait_on_all_done(cond_t *c, mutex_t *m) { cerror(_SYS_DEBUG_SIGNAL, "wait completion on all other cores...\n"); pthread_mutex_lock(m); pthread_cond_wait(c, m); pthread_mutex_unlock(m); cerror(_SYS_DEBUG_SIGNAL, "signaled.\n"); } /** * Return the worker descriptor of given index * @param _workers The collection_t of worker descriptors * @param indx The index of the worker to return * @return Pointer to the worker thread descriptor of given index */ #define get_worker(_ws, _i) (_ws[_i]) #ifdef BARRRELFISH /** * Helper function to get the worker descriptor without knowing the id * @param _workers The collection_t of worker descriptors * @return Pointer to the worker thread descriptor of given index */ #define get_self(_ws) (_ws[disp_get_core_id()]) #endif /** * Wrapper function to pause a worker thread. * @param curr_core_nr The id of the worker thread to be paused. */ #define worker_pause(_w) \ if (_w->state != TRD_PAUSED){ \ pthread_mutex_lock(&(_w->lock)); \ _w->state = TRD_PAUSED; \ pthread_cond_wait(&(_w->plock), &(_w->lock));\ _w->state = TRD_ACTIVE; \ pthread_mutex_unlock(&(_w->lock)); \ } #define worker_pause_get(_ws,_cid) \ worker_pause(get_worker(_ws, _cid)) /** * Wrapper function to resume a paused worker thread. If the thread is not paused this function has no effect other than a slight unnecessary overhead * @param t curr_core_nr The id of the worker thread to be resumed. */ #define worker_resume(_w) \ { \ pthread_mutex_lock(&(_w->lock)); \ if (_w->state == TRD_PAUSED){ \ _w->pause = false; \ pthread_cond_signal(&(_w->plock)); \ } \ pthread_mutex_unlock(&(_w->lock)); \ } #define worker_resume_get(_ws, _cid) \ worker_resume(get_worker(_ws, _cid)) #ifdef __cplusplus } #endif #endif /* POND_UTIL_H */
C
#include "test.h" #include <time.h> #define FUNC_TEST "_test" static run_test(_test_fun f) { #if !TEST_TIME clock_t start, end; start = clock(); f(); end = clock(); printf("cpu time: %ld ms ", end - start); #else f(); #endif } char buff [256] = { 0 }; int main (int argc, char **argv) { _test_fun f = NULL; char *file = argc <= 2 ? NULL : argv [2]; char *name = argc <= 1 ? NULL : argv [1]; printf ("Args: [func=%s] [dll=%s]\n", name == NULL ? "(all)" : name, file == NULL ? argv [0] : file); void *m = file == NULL ? GetModuleHandleA(NULL) : LoadLibraryA(file); if (!m) { printf ("Load file failed. %s", file); return -1; } if (name != NULL) { // run specify snprintf (buff, 255, "%s" FUNC_TEST, name); // insert a "_test" f = (_test_fun)GetProcAddress(m, buff); if (f) run_test(f); else printf ("No test function found!\n"); } else { #if _WIN32 int i = 1; do { f = (_test_fun)GetProcAddress(m, i); if (f) { printf ("%d ", i++); run_test(f); } putchar ('\n'); } while (f != NULL); #elif __linux__ // find all *_test symbol snprintf (buff, 255, "nm %s -D | grep %s |while read ptr type name; do printf " "\"%%s\\n\" ${name}; done", file == NULL ? argv [0] : file, FUNC_TEST); FILE *fn = popen (buff, "r"); while (!feof (fn)) { memset (buff, 0, sizeof (buff)); if (fgets (buff, 255, fn) > 0 && buff [0] != '\n') { buff [strlen (buff) - 1] = '\0'; // remove the last \n f = (_test_fun)dlsym(m, buff); if (f) run_test(f); else printf ("%s: no found!\n", buff); putchar ('\n'); } } pclose (fn); #endif } printf ("End.\n"); return 0; } test_start (test2) { test_func ("test %x", 1, 123); } test_end ()
C
short cd(char *fsfilename, char*rest, short cwd); short cd(char *fsfilename, char*rest, short cwd) { FILE *fs = fopen(fsfilename,"r+"); int bitmapsize_bytes = FILESYSSIZE/BLOCKSIZE/8; if(!rest) //change directory to root { //printf("change directory to root\n"); cwd = bitmapsize_bytes; } else { if(!strcmp(rest,"..")) //you want to go up one directory level { //printf("You are trying to go up one directory level.\n"); fseek(fs,cwd,SEEK_SET); char name[8]; fread(name,1,8,fs); //printf("Upper directory is %s.\n",name); fseek(fs,cwd+8,SEEK_SET); short parent_addr; fread(&parent_addr,sizeof(short),1,fs); if(parent_addr != -1) { cwd = parent_addr; //printf("cwd changed to %d\n",cwd); } else { printf("You are in the root directory, you can't go up any further, silly!\n"); } } else if(strcmp(rest,".") != 0) //you don't want to stay in the same directory and you're not moving up one level, so you want to move to the directory you specified { //try to find the directory specified - looking in the children of cwd short child_addr = find_child(fsfilename,rest,cwd); //now if we found the correct child it's address will be stored in child_addr char type; if(child_addr != 0) { fseek(fs,child_addr+18,SEEK_SET); fread(&type,1,1,fs); } if(child_addr != 0 && type == 'd' ) //if we fould the child { cwd = child_addr; } else { printf("The directory you requested does not exist.\n"); } } else { printf("The directory you requested does not exist.\n"); } } fclose(fs); return cwd; }
C
/* a simple openMP program */ #include <stdio.h> #include <omp.h> int main(int argc, char *argv[]){ int num_threads = 999999; // omp_set_num_threads(4); // or use num_threads(4) as part of the pragma below #pragma omp parallel { int thread_id = omp_get_thread_num(); #pragma omp master { num_threads = omp_get_num_threads(); } #pragma omp barrier printf("Hello from thread %d nthread %d\n", thread_id, num_threads); } // End of Parallel region return 0; }
C
#include <stdio.h> int main(int argc,char** argv) { long i =-1; printf("sizeof(i)=%d\n",sizeof(i)); if(i < sizeof(i)) { printf("OK\n"); } else { printf("error\n"); } printf("sizeof(i)=%d\n",sizeof(i)); printf("i=%d\n",i); return 0; }
C
#include "main.h" #include "terrain.h" #include "player.h" #include "screen.h" // Converts a world x coord to a screen x coord int getScreenX (float xPos) { float screenOrigin = player.position.x - player.currentOffset; int screenX = (int)(xPos - screenOrigin); while (screenX < 0) { screenX += terrainWidth; } screenX %= terrainWidth; return screenX; } // Checks whether a given screen coordinate is on screen int isOnScreen (float screenX) { return (((int)screenX >= 0) && ((int)screenX < windowWidth)); }
C
/* ** tools.c for Rush1 in /Rush1/step_3/src/my_unarchive ** ** Made by Antoine Baché ** Login <bache_a@epitech.net> ** ** Started on Sun Jan 10 12:15:21 2016 Antoine Baché ** Last update Sun Jan 10 12:58:02 2016 Antoine Baché */ #include "my_unarchive.h" int create_dir(t_header *head) { mode_t mode; #ifdef DEBUG printf("CREATE DIR\nDir = \"%s\"\n", head->mode); #endif mode = strtol(head->mode, NULL, 8); if (mkdir(head->name, mode) == -1) return (1); return (0); } int extract_file(int fd, t_header *head) { size_t size; int mode; int file; char *buff; size = strtol(head->size, NULL, 8); mode = strtol(head->mode, NULL, 8); if ((buff = malloc(sizeof(char) * size)) == NULL || (read(fd, buff, size) < 0) || (file = open(head->name, O_CREAT | O_TRUNC | O_WRONLY, mode)) < 0 || write(file, buff, size) < 0) return (1); size = 512 - size % 512; if (read(fd, buff, size) < 0 || close(file) < 0) return (1); free(buff); return (0); }
C
#include <stdio.h> #include "displayShell.h" #include "complex.h" /*Main Function*/ int main(int argc, char *argv[]) { /*Initialize variables*/ complx c1, c2, c3; /*Start program*/ init_bar();//Display the init bar. input_cartesian(&c1);//Input a complex number in cartesian format. display(&c1);//Display a complex number. input_cartesian(&c2);//Input a complex number in cartesian format. display(&c2);//Display a complex number. c1 = cartesian_polar(&c1);//Transform a cartesian complex number to polar complex number. display(&c1);//Display a complex number. c1 = polar_cartesian(&c1);//Transform a polar complex number to cartesian complex number. display(&c1);//Display a complex number. c3 = add(&c1, &c2);//Add two complex numbers. display(&c3);//Display a complex number. end_bar();//Display the end bar. return 0; }
C
int numSquareSum(int n) { int squareSum = 0; while (n) { squareSum += (n % 10) * (n % 10); n /= 10; } return squareSum; } bool isHappy(int n) { int slow, fast; slow = fast = n; do { slow = numSquareSum(slow); fast = numSquareSum(numSquareSum(fast)); } while (slow != fast); return (slow == 1); }
C
#include <stdio.h> int main() { int a = -5; int b = 10; printf("\n %d - %d = %d", b, a, (b - a)); }
C
/* parse/flavor.c */ #include "unit-test.h" #include "init.h" #include "obj-tval.h" #include "obj-properties.h" #include "object.h" #include "z-color.h" static char dummy_light_1[16] = "Test Light 1"; static char dummy_light_2[16] = "Test Light 2"; static char dummy_art_light_1[24] = "Test Art. Light 1"; static char dummy_art_light_2[24] = "Test Art. Light 2"; struct object_kind dummy_kinds[] = { { .name = NULL, .kidx = 0, .tval = 0, .sval = 0 }, { .name = dummy_light_1, .kidx = 1, .tval = TV_LIGHT, .sval = 1 }, { .name = dummy_light_2, .kidx = 2, .tval = TV_LIGHT, .sval = 2 }, { .name = dummy_art_light_1, .kidx = 3, .tval = TV_LIGHT, .sval = 3 }, { .name = dummy_art_light_2, .kidx = 4, .tval = TV_LIGHT, .sval = 4 } }; int setup_tests(void **state) { *state = flavor_parser.init(); /* * Do minimal setup so sval lookups work for the tests of fixed flavors. */ z_info = mem_zalloc(sizeof(*z_info)); z_info->k_max = (uint16_t) N_ELEMENTS(dummy_kinds); z_info->ordinary_kind_max = z_info->k_max - 2; k_info = dummy_kinds; return !*state; } int teardown_tests(void *state) { struct parser *p = (struct parser*) state; struct flavor *f = (struct flavor*) parser_priv(p); while (f) { struct flavor *fn = f->next; string_free(f->text); mem_free(f); f = fn; } parser_destroy(p); mem_free(z_info); return 0; } static int test_kind0(void *state) { enum parser_error r = parser_parse(state, "kind:light:&"); eq(r, PARSE_ERROR_NONE); ok; } static int test_flavor0(void *state) { struct parser *p = (struct parser*) state; enum parser_error r = parser_parse(p, "flavor:2:blue:Fishy"); struct flavor *f; eq(r, PARSE_ERROR_NONE); f = (struct flavor*) parser_priv(p); notnull(f); eq(f->fidx, 2); eq(f->tval, TV_LIGHT); eq(f->sval, SV_UNKNOWN); eq(f->d_char, L'&'); eq(f->d_attr, COLOUR_BLUE); notnull(f->text); require(streq(f->text, "Fishy")); /* Check without a description and using a single letter color code. */ r = parser_parse(p, "flavor:3:G"); eq(r, PARSE_ERROR_NONE); f = (struct flavor*) parser_priv(p); notnull(f); eq(f->fidx, 3); eq(f->tval, TV_LIGHT); eq(f->sval, SV_UNKNOWN); eq(f->d_char, L'&'); eq(f->d_attr, COLOUR_L_GREEN); null(f->text); ok; } static int test_kind_bad0(void *state) { struct parser *p = (struct parser*) state; /* Try an invalid tval. */ enum parser_error r = parser_parse(p, "kind:xyzzy:'"); eq(r, PARSE_ERROR_UNRECOGNISED_TVAL); ok; } const char *suite_name = "parse/flavor"; /* * test_flavor0() and test_fixed0() have to be after test_kind0(). Run * test_kind_bad0() to avoid potential effects on the other tests. */ struct test tests[] = { { "kind0", test_kind0 }, { "flavor0", test_flavor0 }, { "kind_bad0", test_kind_bad0 }, { NULL, NULL } };
C
#include <unistd.h> #include <stdio.h> int main(){ pid_t pid_base_process = getpid(); printf("[%d] MAIN START\n", getpid()); char *args[]={"./called_by_exec",NULL}; execvp("./called_by_exec", args); printf("[%d] MAIN END\n", getpid()); // Will not be executed return 0; }
C
#include <stdio.h> void printMenu(void); void printBGNconvert(void); void printEURconvert(void); void printUSDconvert(void); double dBGN = 0; double dEUR = 0; double dUSD = 0; int main() { int iChoice = 0; char cContinue[20]; cContinue[0] = 'y'; do { printMenu(); scanf("%d", &iChoice); switch (iChoice) { case 1: printBGNconvert(); break; case 2: printEURconvert(); break; case 3: printUSDconvert(); break; case 0: printf(" -- See you later.\n"); break; default: printf(" !! Please, enter valid choice !!\n"); break; } if(iChoice != 0) { printf(" -- Do you want to continue with converts? [y/n]: "); scanf("%s", &cContinue); } } while (iChoice != 0 && cContinue[0] != 'n'); return 0; } void printMenu(void) { printf(" -- Menu --\n"); printf(" -- Enter 1 for convert from BGN to USD and EUR \n"); printf(" -- Enter 2 for convert from EUR to USD and BGN \n"); printf(" -- Enter 3 for convert from USD to EUR and BGN \n"); printf(" -- Enter 0 for quit from program \n"); printf(" -- Please, enter your choice: \n"); } void printBGNconvert(void) { printf("Please, enter your amount in BGN: "); scanf("%lf", &dBGN); if(dBGN < 0) { printf("Please enter valid amount."); } else { double dTotalInEUR = dBGN * 0.51129188; double dTotalInUSD = dBGN * 0.59293029; printf("-- -- %.2f BGN is %.2f EUR \n",dBGN, dTotalInEUR); printf("-- -- %.2f BGN is %.2f USD \n",dBGN, dTotalInUSD); } } void printEURconvert(void) { printf("Please, enter your amount in EUR: "); scanf("%lf", &dEUR); if(dEUR < 0) { printf("Please enter valid amount."); } else { double dTotalInBGN = dEUR * 1.95583; double dTotalInUSD = dEUR * 1.1596709; printf("-- -- %.2f EUR is %.2f BGN \n",dEUR, dTotalInBGN); printf("-- -- %.2f EUR is %.2f USD \n",dEUR, dTotalInUSD); } } void printUSDconvert(void) { printf("Please, enter your amount in USD: "); scanf("%lf", &dUSD); if(dUSD < 0) { printf("Please enter valid amount."); } else { double dTotalInBGN = dUSD * 1.6865389; double dTotalInEUR = dUSD * 0.86231365; printf("-- -- %.2f USD is %.2f BGN \n",dUSD, dTotalInBGN); printf("-- -- %.2f USD is %.2f EUR \n",dUSD, dTotalInEUR); } }
C
#include<stdio.h> //Funco com mais de um parametro, exemplo 1. int funcao_retorno (int nume1, int nume2) { return nume1*nume2; } void main () { int retorno, ex; printf("Valor para multiplicar com 5 da funcao: "); scanf("%d", &ex); retorno = funcao_retorno(ex,5); printf("Retorno da funcao: %d", retorno); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* heredoc.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: amottier <amottier@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/04/10 17:29:36 by ysalaun #+# #+# */ /* Updated: 2018/05/22 15:53:14 by amottier ### ########.fr */ /* */ /* ************************************************************************** */ #include "../includes/minishell.h" void add_heredoc(t_cmd **cmd, int pos, char *end_word) { t_heredoc *hd; t_heredoc *new_hd; new_hd = malloc(sizeof(t_heredoc)); new_hd->position = pos; new_hd->end_word = ft_strdup(end_word); new_hd->content = NULL; new_hd->next = NULL; hd = (*cmd)->heredoc; if (!(hd)) { (*cmd)->heredoc = new_hd; (*cmd)->heredoc1 = new_hd; } else { while (hd->next) hd = hd->next; hd->next = new_hd; } (*cmd)->heredoc_total++; } int parse_heredoc(t_cmd **cmd) { t_token *tmp; char *end_word; int pos; pos = 0; tmp = (*cmd)->head; while (tmp->next) { if (tmp->type == TOKEN_DLESS) { tmp = tmp->next; while (tmp->type == TOKEN_BLANK) tmp = tmp->next; end_word = tmp->str; add_heredoc(cmd, pos, end_word); pos++; } if (tmp->next) tmp = tmp->next; } if (!(pos)) (*cmd)->heredoc_mode = 2; return (pos); }
C
#define _GNU_SOURCE #include <ctype.h> #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdbool.h> #include <stdint.h> #include <stdlib.h> #include <assert.h> #include <errno.h> typedef enum { TK_RESERVED, TK_RETURN, TK_IF, TK_ELSE, TK_WHILE, TK_FOR, TK_INT, TK_CHAR, TK_STR, TK_STATIC, TK_SIZEOF, TK_IDENT, TK_NUM, TK_EOF, } TokenKind; typedef struct Token Token; struct Token { TokenKind kind; Token *next; int val; char *str; int len; // For error info int ln; int col; }; typedef enum { ND_ADD, // 0 ND_SUB, // 1 ND_MUL, // 2 ND_DIV, // 3 ND_EQ, // 4 ND_NOT_EQ, // 5 ND_LT, // 6 ND_LE, // 7 ND_NUM, // 8 ND_ASSIGN, // 9 ND_LVAR, // 10 ND_RETURN, // 11 ND_IF, // 12 ND_WHILE, // 13 ND_FOR, // 14 ND_BLOCK, // 15 ND_CALL, // 16 ND_FUNC, // 17 ND_ADDR, // 18 ND_DEREF, // 19 ND_VARDEF, // 20 ND_GVAR, // 21 ND_STR, // 22 } NodeKind; typedef struct Type Type; struct Type { enum { INT, PTR, ARRAY, CHAR } ty; struct Type *ptr_to; size_t array_size; bool is_static; int unique_num; // For static var uniqueness by appearance count }; typedef struct { void **data; int capacity; int len; } Vector; Vector *new_vec(void); void vec_push(Vector *v, void *elem); void vec_pushi(Vector *v, int val); void *vec_pop(Vector *v); void *vec_last(Vector *v); bool vec_contains(Vector *v, void *elem); bool vec_union1(Vector *v, void *elem); typedef struct { Vector *keys; Vector *vals; } Map; /** * util * */ Map *new_map(void); void map_put(Map *map, char *key, void *val); void map_puti(Map *map, char *key, int val); void *map_get(Map *map, char *key); int map_geti(Map *map, char *key, int default_); bool map_exists(Map *map, char *key); int size_of(Type *ty); int calc_need_byte(Type *ty); void error(char *fmr, ...); typedef struct Node Node; struct Node { NodeKind kind; Node *lhs; Node *rhs; char *name; Type *type; // LVar Vector *stmts; // Compound statement Vector *args; // Function call Vector *params; // Function defenition // "if" (cond) then "else" els // "while" (cond) body // "for" (init; cond; inc) body Node *cond; Node *then; Node *els; Node *body; Node *init; Node *inc; int val; // If kind is ND_NUM, this hold value int offset; // If kind is ND_LVAR, this hold offset from RBP int str_index; // If kind is ND_STR, this hold the number appeared in lavel suffix like .LC0 }; typedef struct Var Var; struct Var { char *name; // The name of var int len; // The length of var name int offset; // Offset from RBP Type *type; bool is_local; }; typedef struct { char *name; Node *node; Map *lvars; } Function; typedef struct { Map *funcs; Map *gvars; } Program; /** * parser * */ Token *tokenize(char *p); Program *parse(); Node *stmt(); Node *expr(); Node *assign(); Node *equality(); Node *relational(); Node *add(); Node *mul(); Node *unary(); Node *primary(); /** * codegen * */ void gen(Node *node); void gen_func(Function *func); void gen_program(Program *program); /** * Globals * */ extern Token *token; extern char *source; extern char *filename; extern int static_count; extern Map *lvars; extern Map *gvars; extern Map *funcs; extern Vector *found_strs;
C
#include <stdlib.h> #include <conio.h> #include <stdio.h> #include <math.h> /*************found**************/ double fun(int n) {double sum, s0, s1, s2, s; int k; sum=1.0; if (n<=2) sum=0.0; s0=0.0; s1=0.0; s2=1.0; for (k=4;k<=n;k++) { s=s0+s1+s2; sum+=sqrt(s); s0=s1;s1=s2;s2=s; } /*************found**************/ return sum; /*(1ݺķֵ֪funӦΪdouble͡(2﷨ȱֺš*/ } void main() {int n; system("CLS"); printf("Input N="); scanf("%d",&n); printf("%f\n",fun(n)); system("pause"); }
C
#include <stdlib.h> #include <string.h> #include <ctype.h> #include "matrix.h" #include "constant.h" /* * Функция считывания(создания) матрицы из файла. Возвращает считанную матрицу или NULL(ошибка). * file - файл из которого производится считывание. */ matrix_s *create_matrix_from_file(FILE *file) { int row = 0, col = 0; if (fscanf(file, "%d %d", &row, &col) != 2) { return NULL; } if ((row <= 0) || (col <= 0)) { return NULL; } matrix_s *matrix = create_matrix(row, col); if (!matrix) { return NULL; } int rc = 1; for (row = 0; row < matrix->rows; ++row) { for (col = 0; col < matrix->columns; ++col) { rc = fscanf(file, "%lf", &((*matrix).data[row][col])); if (rc == 0 || rc == -1) { free_matrix(matrix); return NULL; } } } return matrix; } /* * Функция создания матрицы(выделение памяти). Возвращает созданую матрицу или NULL(ошибка). * row - кол-во эл-тов в строке массива, который надо создать. * column - кол-во эл-тов в столбце массива, который надо создать. */ matrix_s *create_matrix(int row, int col) { matrix_s *matrix; matrix = (matrix_s*) malloc(sizeof(matrix_s)); if (!matrix) { return NULL; } matrix->columns = col; matrix->rows = row; matrix->data = malloc(row * sizeof(double*) + row * col * sizeof(double)); /* matrix->data = (double**) calloc(row, sizeof(double*)); */ if (!(matrix->data)) { free(matrix); return NULL; } for (int i = 0; i < row; ++i) { matrix->data[i] = (double*)((char*)matrix->data + row * sizeof(double*) + i * col * sizeof(double)); /*matrix->data[i] = (double*) calloc(col, sizeof(double)); if (!(matrix->data[i])) { free_matrix(matrix); return NULL; }*/ } return matrix; } /* * Функция удаления матрицы. * matrix - матрицу, которую надо удалить. */ void free_matrix(matrix_s *matrix) { /* for (int i = 0; i < matrix->rows; ++i) { free(matrix->data[i]); } */ free(matrix->data); free(matrix); } /* * Статическая функция создания дополнительного минора. Возвращает дополнительный минор или NULL(ошибку). * matrix - матрица из которой берется дополнительный минор. * count - кол-во эл-тов в строке или столбце matrix. * exclude_row - * exclude_column - */ static matrix_s *matrix_det(int count, int exclude_row, int exclude_column, const matrix_s *matrix) { matrix_s *new_matrix = create_matrix(count - 1, count - 1); if (!new_matrix) { return NULL; } int ki = 0, kj = 0; for (int i = 0; i < count - 1; ++i) { if (i == exclude_row) { ki = 1; } for (int j = 0; j < count - 1; ++j) { if (j == exclude_column) { kj = 1; } new_matrix->data[i][j] = matrix->data[i + ki][j + kj]; } } return new_matrix; } /* * Статическая функция высчитывания значения определителя. Возвращает (значения определителя и flag = OK) или (0 и flag = ERROR_DETERMINANT(ошибку)). * matrix - матрица из которой высчитывается значение определителя. * count - кол-во эл-тов в строке или столбце matrix. * flag - Проверка высчитывания значения определителя. */ static double determinant_value(int count, const matrix_s *matrix, int *flag) { int sign = 1, new_count = count - 1; double det = 0; if (count == 1) { return matrix->data[0][0]; } if (count == 2) { return ((matrix->data[0][0] * matrix->data[1][1]) - (matrix->data[1][0] * matrix->data[0][1])); } if (count > 2) { for (int i = 0; i < count; ++i) { matrix_s *new_matrix = matrix_det(count, i, 0, matrix); if (!new_matrix) { *flag = ERROR_DETERMINANT; return 0; } det = det + sign * matrix->data[i][0] * determinant_value(new_count, new_matrix, flag); sign = -sign; free_matrix(new_matrix); } } return det; } /* * Функция высчитывания значения определителя. Возвращает flag-считывания OK - все хорошо или ERROR_DETERMINANT - ошибка. * matrix - матрица из которой высчитывается значение определителя. * det - значение определителя. */ int determinant(const matrix_s *matrix, double *det) { if (!(matrix->rows == matrix->columns)) { return ERROR_DETERMINANT; } int flag = OK; *det = determinant_value(matrix->rows, matrix, &flag); if (flag) { return ERROR_DETERMINANT; } return OK; } /* * Функция вычисления суммы матриц matrix_a и matrix_b. Возвращает сумму матриц или NULL(ошибку). * matrix_a/matrix_b - матрицы для суммирования. */ matrix_s *addition_matrix(matrix_s *matrix_a, matrix_s *matrix_b) { if (!((matrix_a->rows == matrix_b->rows) && (matrix_a->columns == matrix_b->columns))) { return NULL; } matrix_s *new_matrix = create_matrix(matrix_a->rows, matrix_a->columns); if (!new_matrix) { return NULL; } for (int i = 0; i < matrix_a->rows ; ++i) { for (int j = 0; j < matrix_a->columns; ++j) { new_matrix->data[i][j] = matrix_a->data[i][j] + matrix_b->data[i][j]; } } return new_matrix; } /* * Функция вычисления произведения матриц matrix_a и matrix_b. Возвращает произведение матриц или NULL(ошибку). * matrix_a/matrix_b - матрицы для произведения. */ matrix_s *multiply_matrix(matrix_s *matrix_a, matrix_s *matrix_b) { if (!(matrix_a->columns == matrix_b->rows)) { return NULL; } matrix_s *new_matrix = create_matrix(matrix_a->rows, matrix_b->columns); if (!new_matrix) { return NULL; } for (int i = 0; i < matrix_a->rows; ++i) { for (int j = 0; j < matrix_b->columns; ++j) { new_matrix->data[i][j] = 0; for (int k = 0; k < matrix_b->rows; ++k) { new_matrix->data[i][j] += matrix_a->data[i][k] * matrix_b->data[k][j]; } } } return new_matrix; } /* * Функция печати матрицы в поток(консоль). * matrix - матрица, которая будет напечатана. */ void print_matrix(const matrix_s *matrix) { for (int i = 0; i < matrix->rows; ++i) { for (int j = 0; j < matrix->columns; ++j) { printf("%f ", matrix->data[i][j]); } printf("\n"); } } /* * Функция печати матрицы в файл. * file_write - файл, в который будет произведена запись. * matrix - матрица, которая будет напечатана. */ void print_to_file(FILE *file_write, const matrix_s *matrix) { fprintf(file_write, "%d %d\n", matrix->rows, matrix->columns); for (int i = 0; i < matrix->rows; ++i) { for (int j = 0; j < matrix->columns; ++j) { fprintf(file_write, "%f", matrix->data[i][j]); fprintf(file_write, "%c", ' '); } if (i != matrix->rows - 1) fprintf(file_write, "%c", '\n'); } }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include <unistd.h> #include <sys/sem.h> #include <sys/shm.h> #include <sys/stat.h> #include <sys/wait.h> #include <sys/time.h> #include "structs.h" #include "functions.h" int main(int argc, char **argv){ int i, j, c, M, n, *matrix, counter, readers; pid_t pid, childID; int status, shmid, child_pid, shm_access, readers_sem; struct entry *shared_memory, tmpEntry; time_t t, timestamp, curTime, start, end, total_time; struct timeval tv; float *runningAverage; char path[32], id[8]; FILE *fd; M = atoi(argv[1]); n = atoi(argv[2]); runningAverage = malloc(n*sizeof(float)); for(i=0; i<n; i++){ runningAverage[i] = 0; } if ((shmid = shmget(IPC_PRIVATE, sizeof(struct entry), IPC_CREAT | IPC_EXCL | S_IRUSR | S_IWUSR)) == -1){ //Create shared memory perror("shmget"); exit(1); } if((shm_access = semget((key_t)1234, 1, 0666 | IPC_CREAT)) == -1){ //Create semaphore for access in shared memory printf("Fail in creating semaphore\n"); } if((readers_sem = semget((key_t)1234, 1, 0666 | IPC_CREAT)) == -1){ //Create semaphore for readers queue printf("Fail in creating semaphore\n"); } set_semvalue(shm_access, 0, 1); set_semvalue(readers_sem, 0, 1); readers = 0; counter = 0; for(c=0; c<n; c++){ if( (pid=fork()) <= 0){ break; } } if(pid == 0){ //child strcpy(path, "output"); childID = getpid(); sprintf(id, "%d", childID); strncat(path, id, strlen(id)); strncat(path, ".txt", 4); fd = fopen(path, "w"); sleep(1); while(counter < M){ sem_down(readers_sem, 0); readers++; if(readers == 1){ //first reader set_semvalue(shm_access, 0, 1); sem_down(shm_access, 0); counter++; } sem_up(readers_sem, 0); shared_memory = (struct entry *)shmat(shmid, 0, 0); //perform reading memcpy(&tmpEntry, shared_memory, sizeof(struct entry)); gettimeofday(&tv, NULL); curTime = tv.tv_sec; runningAverage[c] += curTime - tmpEntry.timestamp; fprintf(fd, "%d\n", tmpEntry.element); shmdt(shared_memory); sem_down(readers_sem, 0); readers--; if(readers == 0){ //last reader sem_up(shm_access, 0); sleep(2); } sem_up(readers_sem, 0); } runningAverage[c] = runningAverage[c] / M; fprintf(fd, "Running Average: %.3fsec\n", runningAverage[c]); fprintf(fd, "PID: %d\n", childID); printf("PID:%d\tRunning Average:%.3fsec\n", childID, runningAverage[c]); exit(1); } else{ //parent matrix = malloc(sizeof(int)); srand((unsigned) time(&t)); for(i=0; i<M; i++){ matrix[i] = rand() % 10000; } for(j=0; j<M; j++){ sem_down(shm_access, 0); shared_memory = (struct entry *)shmat(shmid, 0, 0); //perform writing gettimeofday(&tv, NULL); timestamp = tv.tv_sec; tmpEntry.element = matrix[j]; tmpEntry.timestamp = tv.tv_sec; memcpy(shared_memory, &tmpEntry, sizeof(struct entry)); shmdt(shared_memory); sem_up(shm_access, 0); sleep(2); } while( (child_pid = wait(&status)>0) ){ if(WIFEXITED(status)){ printf("Child exited with code %d\n", WEXITSTATUS(status)); } else{ printf("Child terminated abnormally\n"); } } shmctl(shmid, IPC_RMID, 0); del_semvalue(shm_access, 0); del_semvalue(readers_sem, 0); free(matrix); exit(1); } }
C
#include "parallel.h" #include <mpi.h> #define N_BORDER_VEL 5 void Program_Message(char *txt) /* produces a stderr text output */ { int myrank; MPI_Comm_rank(MPI_COMM_WORLD, &myrank); fprintf(stderr,"-MESSAGE- P:%2d : %s\n",myrank,txt); fflush(stdout); fflush(stderr); } void Programm_Sync(char *txt) /* produces a stderr textoutput and synchronize all processes */ { int myrank; MPI_Comm_rank(MPI_COMM_WORLD, &myrank); MPI_Barrier(MPI_COMM_WORLD); /* synchronize output */ fprintf(stderr,"-MESSAGE- P:%2d : %s\n",myrank,txt); fflush(stdout); fflush(stderr); MPI_Barrier(MPI_COMM_WORLD); } void Programm_Stop(char *txt) /* all processes will produce a text output, be synchronized and finished */ { int myrank; MPI_Comm_rank(MPI_COMM_WORLD, &myrank); MPI_Barrier(MPI_COMM_WORLD); /* synchronize output */ fprintf(stderr,"-STOP- P:%2d : %s\n",myrank,txt); fflush(stdout); fflush(stderr); MPI_Barrier(MPI_COMM_WORLD); MPI_Finalize(); exit(0); } /*void initialiseBuffers ( double **sendBuffer, double **readBuffer, int *subdomain, int *flagField) { int kx = subdomain[0] + 2; //size of buffer x int ky = subdomain[1] + 2; //size of buffer y int kz = subdomain[2] + 2; //size of buffer z if (flagField[compute_index(0, ky/2, kz/2, subdomain)]==PARALLEL_BOUNDARY){ //left buffers sendBuffer[0] = calloc(kz*ky*5, sizeof(double)); readBuffer[0] = calloc(kz*ky*5, sizeof(double)); } if (flagField[compute_index(kx-1, ky/2, kz/2, subdomain)]==PARALLEL_BOUNDARY){ // right buffers sendBuffer[1] = calloc(kz*ky*5, sizeof(double)); readBuffer[1] = calloc(kz*ky*5, sizeof(double)); } if (flagField[compute_index(kx/2, ky/2, kz-1, subdomain)]==PARALLEL_BOUNDARY){ //top buffers sendBuffer[2] = calloc(kx*ky*5, sizeof(double)); readBuffer[2] = calloc(kx*ky*5, sizeof(double)); } if (flagField[compute_index(kx/2, ky/2, 0, subdomain)]==PARALLEL_BOUNDARY){ //bottom buffers sendBuffer[3] = calloc(kx*ky*5, sizeof(double)); readBuffer[3] = calloc(kx*ky*5, sizeof(double)); } if (flagField[compute_index(kx/2, 0, kz/2, subdomain)]==PARALLEL_BOUNDARY){ //front buffers sendBuffer[4] = calloc(kx*kz*5, sizeof(double)); readBuffer[4] = calloc(kx*kz*5, sizeof(double)); } if (flagField[compute_index(kx/2, ky-1, kz/2, subdomain)]==PARALLEL_BOUNDARY){ //back buffers sendBuffer[5] = calloc(kx*kz*5, sizeof(double)); readBuffer[5] = calloc(kx*kz*5, sizeof(double)); } }*/ // E X T R A C T I O N F U N C T I O N S // Here we extract the five pdfs that would be streamed into our neighbour, x direction. void extractionXleft ( double **sendBuffer, double *collideField, int *subdomain){ // 1. EXTRACT TO LEFT // pdfs, that need to be extracted are the ones with indices 1, 5, 8, 11, 15. int i = 0; /* before calling it, we need to check that front boundary is not a no-slip: if (rank%proc[0]!=0){ */ for (int z=0; z<subdomain[2]+2; z++){ for (int y=0; y<subdomain[1]+2; y++){ *(sendBuffer[0] + i++) = collideField [ Q*compute_index(1, y, z, subdomain) + 1 ]; *(sendBuffer[0] + i++) = collideField [ Q*compute_index(1, y, z, subdomain) + 5 ]; *(sendBuffer[0] + i++) = collideField [ Q*compute_index(1, y, z, subdomain) + 8 ]; *(sendBuffer[0] + i++) = collideField [ Q*compute_index(1, y, z, subdomain) + 11 ]; *(sendBuffer[0] + i++) = collideField [ Q*compute_index(1, y, z, subdomain) + 15 ]; } } } void extractionXright (double **sendBuffer, double *collideField, int *subdomain){ // 2. EXTRACT TO RIGHT // here, we extract pdfs with indeces 3, 7, 10, 13, 17. int i = 0; /* before calling it, we need to check that front boundary is not a no-slip: if (rank%proc[0]!=proc[0]-1){ */ for (int z=0; z<subdomain[2]+2; z++){ for (int y=0; y<subdomain[1]+2; y++){ *(sendBuffer[1] + i++) = collideField [ Q*compute_index(subdomain[0], y, z, subdomain) + 3 ]; *(sendBuffer[1] + i++) = collideField [ Q*compute_index(subdomain[0], y, z, subdomain) + 7 ]; *(sendBuffer[1] + i++) = collideField [ Q*compute_index(subdomain[0], y, z, subdomain) + 10 ]; *(sendBuffer[1] + i++) = collideField [ Q*compute_index(subdomain[0], y, z, subdomain) + 13 ]; *(sendBuffer[1] + i++) = collideField [ Q*compute_index(subdomain[0], y, z, subdomain) + 17 ]; } } } // Here we extract the five pdfs that would be streamed into our neighbour, y direction. void extractionYfront (double **sendBuffer, double *collideField, int *subdomain){ // 1. EXTRACT TO FRONT // pdfs, that need to be extracted are the ones with indices 0, 5, 6, 7, 14. int i = 0; /* before calling it, we need to check that front boundary is not a no-slip: if (rank%(proc[0]*proc[1])>=proc[0]){ */ for (int z=0; z<subdomain[2]+2; z++){ for (int x=0; x<subdomain[0]+2; x++){ *(sendBuffer[4] + i++) = collideField [ Q*compute_index(x, 1, z, subdomain) ]; *(sendBuffer[4] + i++) = collideField [ Q*compute_index(x, 1, z, subdomain) + 5 ]; *(sendBuffer[4] + i++) = collideField [ Q*compute_index(x, 1, z, subdomain) + 6 ]; *(sendBuffer[4] + i++) = collideField [ Q*compute_index(x, 1, z, subdomain) + 7 ]; *(sendBuffer[4] + i++) = collideField [ Q*compute_index(x, 1, z, subdomain) + 14 ]; } } } void extractionYback (double **sendBuffer, double *collideField, int *subdomain){ // 2. EXTRACT TO BACK // we need to extract pdfs with indices 4, 11, 12, 13, 18. int i = 0; /* before calling it, we need to check that front boundary is not a no-slip: if (rank%(proc[0]*proc[1])<proc[0]*(proc[1]-1)){ */ for (int z=0; z<subdomain[2]+2; z++){ for (int x=0; x<subdomain[0]+2; x++){ *(sendBuffer[5] + i++) = collideField [ Q*compute_index(x, subdomain[1], z, subdomain) + 4 ]; *(sendBuffer[5] + i++) = collideField [ Q*compute_index(x, subdomain[1], z, subdomain) + 11 ]; *(sendBuffer[5] + i++) = collideField [ Q*compute_index(x, subdomain[1], z, subdomain) + 12 ]; *(sendBuffer[5] + i++) = collideField [ Q*compute_index(x, subdomain[1], z, subdomain) + 13 ]; *(sendBuffer[5] + i++) = collideField [ Q*compute_index(x, subdomain[1], z, subdomain) + 18 ]; } } } // Here we extract the five pdfs that would be streamed into our neighbour, z direction. void extractionZtop (double **sendBuffer, double *collideField, int *subdomain){ // 1. EXTRACT TO TOP // pdfs, that need to be extracted are the ones with indices 14, 15, 16, 17, 18. int i = 0; /* before calling it, we need to check that front boundary is not a no-slip: if (rank>=proc[0]*proc[1]*(proc[2]-1)){ */ for (int y=0; y<subdomain[1]+2; y++){ for (int x=0; x<subdomain[0]+2; x++){ *(sendBuffer[2] + i++) = collideField [ Q*compute_index(x, y, subdomain[2], subdomain) + 14 ]; *(sendBuffer[2] + i++) = collideField [ Q*compute_index(x, y, subdomain[2], subdomain) + 15 ]; *(sendBuffer[2] + i++) = collideField [ Q*compute_index(x, y, subdomain[2], subdomain) + 16 ]; *(sendBuffer[2] + i++) = collideField [ Q*compute_index(x, y, subdomain[2], subdomain) + 17 ]; *(sendBuffer[2] + i++) = collideField [ Q*compute_index(x, y, subdomain[2], subdomain) + 18 ]; } } } void extractionZbottom (double **sendBuffer, double *collideField, int *subdomain){ // 2. EXTRACT TO BOTTOM // pdfs, that need to be extracted are the ones with indices 0, 1, 2, 3, 4. int i = 0; /* before calling it, we need to check that front boundary is not a no-slip: if (rank<proc[0]*proc[1]){ */ for (int y=0; y<subdomain[1]+2; y++){ for (int x=0; x<subdomain[0]+2; x++){ *(sendBuffer[3] + i++) = collideField [ Q*compute_index(x, y, 1, subdomain) ]; *(sendBuffer[3] + i++) = collideField [ Q*compute_index(x, y, 1, subdomain) + 1 ]; *(sendBuffer[3] + i++) = collideField [ Q*compute_index(x, y, 1, subdomain) + 2 ]; *(sendBuffer[3] + i++) = collideField [ Q*compute_index(x, y, 1, subdomain) + 3 ]; *(sendBuffer[3] + i++) = collideField [ Q*compute_index(x, y, 1, subdomain) + 4 ]; } } } /* the MPI_Send and MPI_Recv are kept in comments, because we wanna check the deadlock!*/ //Swap for left layer void swapXleft( double **sendBuffer, double **readBuffer, int *subdomain, int *proc, int rank){ /*MPI_Send(&sendBuffer[0][0], 5 * (subdomain[1] + 2) * (subdomain[2]+ 2), MPI_DOUBLE, rank - 1, 0, MPI_COMM_WORLD); MPI_Recv(&readBuffer[0][0], 5 * (subdomain[1] + 2) * (subdomain[2] + 2), MPI_DOUBLE, rank - 1, 0, MPI_COMM_WORLD, &status);*/ MPI_Sendrecv(&sendBuffer[0][0], 5 * (subdomain[1] + 2) * (subdomain[2] + 2), MPI_DOUBLE, rank - 1, 0, &readBuffer[0][0], 5 * (subdomain[1] + 2) * (subdomain[2] + 2), MPI_DOUBLE, rank - 1, 1, MPI_COMM_WORLD, MPI_STATUS_IGNORE); } //Swap for right layer void swapXright( double **sendBuffer, double **readBuffer, int *subdomain, int *proc, int rank){ /*MPI_Send(&sendBuffer[1][0], 5 * (subdomain[1] + 2) * (subdomain[2]+ 2), MPI_DOUBLE, rank + 1, 0, MPI_COMM_WORLD); MPI_Recv(&readBuffer[1][0], 5 * (subdomain[1] + 2) * (subdomain[2] + 2), MPI_DOUBLE, rank + 1, 0, MPI_COMM_WORLD, &status);*/ MPI_Sendrecv(&sendBuffer[1][0], 5 * (subdomain[1] + 2) * (subdomain[2] + 2), MPI_DOUBLE, rank + 1, 1, &readBuffer[1][0], 5 * (subdomain[1] + 2) * (subdomain[2] + 2), MPI_DOUBLE, rank + 1, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); } //Swap for front layer void swapYfront( double **sendBuffer, double **readBuffer, int *subdomain, int *proc, int rank){ /*MPI_Send(&sendBuffer[4][0], 5 * (subdomain[0] + 2) * (subdomain[2]+ 2), MPI_DOUBLE, rank - proc[1], 0,MPI_COMM_WORLD); MPI_Recv(&readBuffer[4][0], 5 * (subdomain[0] + 2) * (subdomain[2] + 2), MPI_DOUBLE, rank - proc[1], 0,MPI_COMM_WORLD, &status);*/ MPI_Sendrecv(&sendBuffer[4][0], 5 * (subdomain[0] + 2) * (subdomain[2] + 2), MPI_DOUBLE, rank - proc[1], 2, &readBuffer[4][0], 5 * (subdomain[0] + 2) * (subdomain[2] + 2), MPI_DOUBLE, rank - proc[1], 3, MPI_COMM_WORLD, MPI_STATUS_IGNORE); } //Swap for back layer void swapYback( double **sendBuffer, double **readBuffer, int *subdomain, int *proc, int rank){ /* MPI_Send(&sendBuffer[5][0], 5 * (subdomain[0] + 2) * (subdomain[2]+ 2), MPI_DOUBLE, rank + proc[1], 0, MPI_COMM_WORLD); MPI_Recv(&readBuffer[5][0], 5 * (subdomain[0] + 2) * (subdomain[2] + 2), MPI_DOUBLE, rank + proc[1], 0,MPI_COMM_WORLD, &status);*/ MPI_Sendrecv(&sendBuffer[5][0], 5 * (subdomain[0] + 2) * (subdomain[2] + 2), MPI_DOUBLE, rank + proc[1], 3, &readBuffer[5][0], 5 * (subdomain[0] + 2) * (subdomain[2] + 2), MPI_DOUBLE, rank + proc[1], 2, MPI_COMM_WORLD, MPI_STATUS_IGNORE); } //Swap for top layer void swapZtop( double **sendBuffer, double **readBuffer, int *subdomain, int *proc, int rank){ /*MPI_Send(&sendBuffer[2][0], 5 * (subdomain[0] + 2) * (subdomain[1]+ 2), MPI_DOUBLE, rank + proc[0]*proc[1], 0, MPI_COMM_WORLD); MPI_Recv(&readBuffer[2][0], 5 * (subdomain[0] + 2) * (subdomain[1] + 2), MPI_DOUBLE, rank + proc[0]*proc[1], 0, MPI_COMM_WORLD, &status);*/ MPI_Sendrecv(&sendBuffer[2][0], 5 * (subdomain[0] + 2) * (subdomain[1] + 2), MPI_DOUBLE, rank + proc[0]*proc[1], 4, &readBuffer[2][0], 5 * (subdomain[0] + 2) * (subdomain[1] + 2), MPI_DOUBLE, rank + proc[0]*proc[1], 5, MPI_COMM_WORLD, MPI_STATUS_IGNORE); } //Swap for bottom layer void swapZbottom( double **sendBuffer, double **readBuffer, int *subdomain, int *proc, int rank){ /*MPI_Send(&sendBuffer[3][0], 5 * (subdomain[0] + 2) * (subdomain[1]+ 2), MPI_DOUBLE, rank - proc[0]*proc[1], 0, MPI_COMM_WORLD); MPI_Recv(&readBuffer[3][0], 5 * (subdomain[0] + 2) * (subdomain[1] + 2), MPI_DOUBLE, rank - proc[0]*proc[1], 0, MPI_COMM_WORLD, &status);*/ MPI_Sendrecv(&sendBuffer[3][0], 5 * (subdomain[0] + 2) * (subdomain[1] + 2), MPI_DOUBLE, rank - proc[0]*proc[1], 5, &readBuffer[3][0], 5 * (subdomain[0] + 2) * (subdomain[1] + 2), MPI_DOUBLE, rank - proc[0]*proc[1], 4, MPI_COMM_WORLD, MPI_STATUS_IGNORE); } // I N J E C T I O N F U N C T I O N S //here we inject the five pdfs that would be streamed into our neighbour, x direction. void injectionXright ( double **readBuffer, double *collideField, int *subdomain){ // 1. INJECT TO RIGHT // pdfs, that need to be extracted are the ones with indices 1, 5, 8, 11, 15. int i = 0; /* before calling it, we need to check that right boundary is not a no-slip: if (rank%proc[0]!=proc[0]-1){ */ for (int z=0; z<subdomain[2]+2; z++){ for (int y=0; y<subdomain[1]+2; y++){ //at the right boundary layer, the x index is subdomain[0]+1 collideField [ Q*compute_index(subdomain[0]+1, y, z, subdomain) + 1 ] = *(readBuffer[1] + i++); collideField [ Q*compute_index(subdomain[0]+1, y, z, subdomain) + 5 ] = *(readBuffer[1] + i++); collideField [ Q*compute_index(subdomain[0]+1, y, z, subdomain) + 8 ] = *(readBuffer[1] + i++); collideField [ Q*compute_index(subdomain[0]+1, y, z, subdomain) + 11 ] = *(readBuffer[1] + i++); collideField [ Q*compute_index(subdomain[0]+1, y, z, subdomain) + 15 ] = *(readBuffer[1] + i++); } } } void injectionXleft ( double **readBuffer, double *collideField, int *subdomain){ // 2. INJECT FROM LEFT // here, we extract pdfs with indices 3, 7, 10, 13, 17. int i = 0; /* before calling it, we need to check that left boundary is not a no-slip: if (rank%proc[0]!=0){ */ for (int z=0; z<subdomain[2]+2; z++){ for (int y=0; y<subdomain[1]+2; y++){ //at the left boundary layer, the x index is 0 collideField [ Q*compute_index(0, y, z, subdomain) + 3 ] = *(readBuffer[0] + i++); collideField [ Q*compute_index(0, y, z, subdomain) + 7 ] = *(readBuffer[0] + i++); collideField [ Q*compute_index(0, y, z, subdomain) + 10 ] = *(readBuffer[0] + i++); collideField [ Q*compute_index(0, y, z, subdomain) + 13 ] = *(readBuffer[0] + i++); collideField [ Q*compute_index(0, y, z, subdomain) + 17 ] = *(readBuffer[0] + i++); } } } void injectionYback ( double **readBuffer, double *collideField, int *subdomain){ // 3. INJECT FROM BACK // pdfs, that need to be extracted are the ones with indices 0, 5, 6, 7, 14. int i = 0; /* before calling it, we need to check that back boundary is not a no-slip: if (rank%(proc[0]*proc[1])<(proc[1]-1)){ */ for (int z=0; z<subdomain[2]+2; z++){ for (int x=0; x<subdomain[0]+2; x++){ //at the back boundary layer, the y index is subdomain[0]+1 collideField [ Q*compute_index(x, subdomain[0]+1, z, subdomain) ] = *(readBuffer[5] + i++); collideField [ Q*compute_index(x, subdomain[0]+1, z, subdomain) + 5 ] = *(readBuffer[5] + i++); collideField [ Q*compute_index(x, subdomain[0]+1, z, subdomain) + 6 ] = *(readBuffer[5] + i++); collideField [ Q*compute_index(x, subdomain[0]+1, z, subdomain) + 7 ] = *(readBuffer[5] + i++); collideField [ Q*compute_index(x, subdomain[0]+1, z, subdomain) + 14 ] = *(readBuffer[5] + i++); } } } void injectionYfront ( double **readBuffer, double *collideField, int *subdomain){ // 4. INJECT FROM FRONT // pdfs, that need to be extracted are the ones with indices 4, 11, 12, 13, 18. int i = 0; /* before calling it, we need to check that back boundary is not a no-slip: if (rank%(proc[0]*proc[1])>=proc[0]){ */ for (int z=0; z<subdomain[2]+2; z++){ for (int x=0; x<subdomain[0]+2; x++){ //at the front boundary layer, the y index is 0 collideField [ Q*compute_index(x, 0, z, subdomain) + 4 ] = *(readBuffer[4] + i++); collideField [ Q*compute_index(x, 0, z, subdomain) + 11 ] = *(readBuffer[4] + i++); collideField [ Q*compute_index(x, 0, z, subdomain) + 12 ] = *(readBuffer[4] + i++); collideField [ Q*compute_index(x, 0, z, subdomain) + 13 ] = *(readBuffer[4] + i++); collideField [ Q*compute_index(x, 0, z, subdomain) + 18 ] = *(readBuffer[4] + i++); } } } void injectionZbottom ( double **readBuffer, double *collideField, int *subdomain){ // 5. INJECT FROM BOTTOM // pdfs, that need to be extracted are the ones with indices 14, 15, 16, 17, 18. int i = 0; /* before calling it, we need to check that bottom boundary is not a no-slip: if (rank<proc[0]*proc[1]){ */ for (int y=0; y<subdomain[1]+2; y++){ for (int x=0; x<subdomain[0]+2; x++){ //at the bottom boundary layer, the z index is 0 collideField [ Q*compute_index(x, y, 0, subdomain) + 14] = *(readBuffer[3] + i++); collideField [ Q*compute_index(x, y, 0, subdomain) + 15 ] = *(readBuffer[3] + i++); collideField [ Q*compute_index(x, y, 0, subdomain) + 16 ] = *(readBuffer[3] + i++); collideField [ Q*compute_index(x, y, 0, subdomain) + 17 ] = *(readBuffer[3] + i++); collideField [ Q*compute_index(x, y, 0, subdomain) + 18 ] = *(readBuffer[3] + i++); } } } void injectionZtop ( double **readBuffer, double *collideField, int *subdomain){ // 6. INJECT FROM TOP // pdfs, that need to be extracted are the ones with indices 0, 1, 2, 3, 4. int i = 0; /* before calling it, we need to check that top boundary is not a no-slip: if (rank>=proc[0]*proc[1]*(proc[2]-1)){ */ for (int y=0; y<subdomain[1]+2; y++){ for (int x=0; x<subdomain[0]+2; x++){ //at the top boundary layer, the z index is subdomain[0]+1 collideField [ Q*compute_index(x, y, subdomain[0]+1, subdomain) ] = *(readBuffer[2] + i++); collideField [ Q*compute_index(x, y, subdomain[0]+1, subdomain) + 1 ] = *(readBuffer[2] + i++); collideField [ Q*compute_index(x, y, subdomain[0]+1, subdomain) + 2 ] = *(readBuffer[2] + i++); collideField [ Q*compute_index(x, y, subdomain[0]+1, subdomain) + 3 ] = *(readBuffer[2] + i++); collideField [ Q*compute_index(x, y, subdomain[0]+1, subdomain) + 4 ] = *(readBuffer[2] + i++); } } }
C
#include<stdio.h> int main() { int n,i,fact=1; printf("Enter the number for Factorial\n"); scanf("%d",&n); for(i=n;i>0;i--) { fact=fact*i; } printf("Factorial of the number %d is %d ",n,fact); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <fcntl.h> #include <sys/mman.h> #include <sys/stat.h> int main(int argc, char *args[]) { const int SIZE = 4096; // size of shared memory object const char *NAME = "OS"; // name of shared memory object int shm_fd; // shared memory file descriptor void *ptr; // pointer to shared memory object // Create shared memory object and configure its size. shm_fd = shm_open(NAME, O_CREAT | O_RDWR, 0666); ftruncate(shm_fd, SIZE); // Memory map the shared memory object. ptr = mmap(0, SIZE, PROT_WRITE, MAP_SHARED, shm_fd, 0); // Write to the shared memory object. sprintf(ptr, "%s", args[1]); return 0; }
C
/* CREATED BY: Benjamin Hamlin Chapter 1 Question 3 "URLify" PROMPT: Write a method to replace all spaces in a string with '%20'. You may assume that the string has sufficient space at the end to hold the additional characters, and that you are given the 'true' length of the string (Note: if implementing in java, please use a character array so that you can perform this operation in place) DATE: 11/23/2019 */ #include "header.h" char* p3(char* str, int length){ char* arr = (char*)malloc(length); char* token = strtok(str, ' '); while(token != NULL){ strcat(arr,token); strcat(arr,"%20"); token = strtok(NULL, ' '); } strcpy(str, arr); free(arr); return str; }
C
/* ============================================================================ Name : main.c Author : Nahuel Version : Copyright : Your copyright notice Description : Hello World in C, Ansi-style ============================================================================ */ #include <stdio.h> #include <stdlib.h> #include "LinkedList.h" #include "controller.h" #include "utn.h" int main(void) { setbuf(stdout,NULL); LinkedList* pArrayArticulos = ll_newLinkedList(); int option = 0; char path[51]; while(option != 7) { printf("\n1-Cargar un archivo y abrirlo\n2-Ordenar\n3-Listar\n4-Realizar descuento\n5-Save datos\n6-Informe\n7-Salir"); fflush(stdin); utn_getInt(&option,"\nElija una opcion: " ,"\nError\n",1,10,3); switch(option) { case 1: fflush(stdin); if(utn_getTexto("\nIngrese el nombre del archivo: ","\nError\n",3,51,3,path)==0) { if(controller_loadData(path,pArrayArticulos)==0) printf("\nSe cargo los datos correctamente\n"); else printf("\nNo se cargo los datos correctamente\n"); } break; case 2: if(controller_sortArticulos(pArrayArticulos)==0) printf("\nSe orden por articulo y de manera ascendente con exito.\n"); else printf("\nNo se pudo ordenar\n"); break; case 3: controller_listArticulos(pArrayArticulos); break; case 4: if(controller_descuentoLimpieza(pArrayArticulos)==0) printf("\nSe realizo el descuento\n"); else printf("\nNo se realizo el descuento\n"); break; case 5: if(controller_saveData("mapeado.csv",pArrayArticulos)==0) printf("\nSe guardo el archivo con exito\n"); else printf("\nNo se guardo el archivo con exito\n"); break; case 6: if(controller_informe(pArrayArticulos)==0) printf("\nSe realizo el informe con exito\n"); else printf("\nNo se realizo el informe con exito\n"); break; case 7: printf("\nSali.\n"); break; default: printf("\nIngrese un valor del men\n"); } } return 0; }
C
#include <stdio.h> #define NL "\n" #define D "%d" #define D1 D NL #define D2 D D NL #define D3 D D D NL int main(void) { printf(D1, 1); printf(D2, 1, 2); printf(D3, 1, 2, 3); return 0; }
C
#include <stdio.h> #include <pthread.h> #include <stdlib.h> #include <unistd.h> #define MAX_THREADS 2 #define ARR_SIZE 1200 typedef struct data_t { int begin; int end; int* results; } data_t; void* do_the_thing(void *d) { int i; data_t data = *((data_t*) d); for (i = data.begin; i <= data.end; i++) { data.results[i] = i*4 + 20; } return NULL; } void print_arr(int* arr, int size) { int i = 0; for (; i < size-1; i++) { printf("%d ", arr[i]); } printf("%d\n", arr[i]); } int main() { int i; int results[ARR_SIZE] = { [0 ... ARR_SIZE-1] = 0 }; pthread_t threads[MAX_THREADS]; data_t datas[MAX_THREADS]; for (i = 0; i < MAX_THREADS; i++) { datas[i].results = results; datas[i].begin = i*400; datas[i].end = datas[i].begin + 400 - 1; printf("begin %d\n", datas[i].begin); printf("end %d\n", datas[i].end ); pthread_create(&threads[i], NULL, &do_the_thing, &datas[i]); } data_t data; data.begin = i*400; data.end = data.begin + 400 - 1; data.results = results; printf("i = %d\n", i); printf("begin %d\n", data.begin); printf("end %d\n", data.end ); do_the_thing(&data); for (i = 0; i < MAX_THREADS; i++) { pthread_join(threads[i], NULL); } print_arr(results, ARR_SIZE); return 0; }
C
#include <stdio.h> #include <stdlib.h> int funcion_activacion(float x, int salidas[],float t); double sumatoria(double *entradas, double *pesos, double umbral, int size); int main(int argc, char *argv[]){ int ctd = atof(argv[1]); double entradas[ctd]; double pesos[ctd]; double umbral = atof(argv[argc-2]); double t = atof(argv[argc-1]); for(int i=0;i<ctd;i++){ entradas[i] = atof(argv[i+2]); pesos[i] = atof(argv[i+2+ctd]); printf("entradas[%d]: %f\n", i,entradas[i]); printf("pesos[%d]: %f\n", i,pesos[i]); } printf("umbral: %f\n", umbral); float sum = sumatoria(entradas,pesos,umbral,sizeof(entradas)/sizeof(double)); printf("sumatoria: %f\n", sum); int salidas_sigmoidal[2] = {1,-1}; int salidas_escalon[2] = {1,0}; int salida_funcion_sigmoidal = funcion_activacion(sum,salidas_sigmoidal,0); int salida_funcion_escalon = funcion_activacion(sum,salidas_escalon,t); printf("Salida funcion_sigmoidal: %d\n", salida_funcion_sigmoidal); printf("Salida funcion_escalon: %d\n", salida_funcion_escalon); return 0; } double sumatoria(double *entradas, double *pesos, double umbral, int size){ double sum = 0.0; for(int i=0; i<size; i++){ sum += entradas[i]*pesos[i]; } return sum-umbral; } int funcion_activacion(float x, int *salidas,float t){ if(x >= t) return salidas[0]; return salidas[1]; }
C
/* * backtrace.c */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <signal.h> /* for signal */ #include <execinfo.h> /* for backtrace() */ extern void dump(void); extern void signal_handler(int signo); extern int add(int num); int main(int argc, char *argv[]) { int sum = 0x00; signal(SIGSEGV, signal_handler); /* 为SIGSEGV信号安装新的处理函数,捕获内核的异常信号*/ sum = add(sum); printf(" sum = %d \n", sum); return 0x00; }
C
#include <stdio.h> int main(){ printf("<< Media de n alunos. Maximo 100 alunos >>\n"); int numAlunos = 0; printf("Entre com o numero de alunos: "); scanf("%d",&numAlunos); if(numAlunos > 100){ printf("Erro! O numero maximo de alunos permitidos eh 100."); } else{ int nota[numAlunos]; float media = 0; int i; for (i = 0; i < numAlunos; i++) { printf("\nDigite a nota do aluno %d: ",i+1); scanf("%d",&nota[i]); media = media + nota[i]; } media = media/numAlunos; printf("\nRelatorio de Notas\n"); for (i = 0; i < numAlunos; i++) { printf("Nota do aluno %d: %d\n",i, nota[i]); } printf("Media da turma: %.1f\n",media); } return 0; } /* Faça um programa que calcula a média das notas dos alunos de uma turma. Note que uma turma pode ter no máximo 100 alunos (mostrar uma mensagem de erro caso o número escolhido seja maior que 100). Peça para o usuário entrar com o número de alunos e ao final mostre a nota de todos os alunos. Exemplo de Saída << Media de n alunos. Maximo 100 alunos >> Entre com o numero de alunos: 4 Digite a nota do aluno 1: 6 Digite a nota do aluno 2: 7 Digite a nota do aluno 3: 5 Digite a nota do aluno 4: 4 Relatorio de Notas Nota do aluno 0: 6 Nota do aluno 1: 7 Nota do aluno 2: 5 Nota do aluno 3: 4 Media da turma: 5.5 ------------------------------------ Exemplo de Saída 2 << Media de n alunos. Maximo 100 alunos >> Entre com o numero de alunos: 400 Erro! O numero maximo de alunos permitido eh 100. */
C
#include<stdio.h> void main() { int n; printf("\n Enter a number : "); scanf("%d", &n); if(n<=0) { printf("\n Invalid"); } else if(n%2==0) { printf("\n Even"); } else { printf("\n Odd"); } }
C
#include "shader.h" #include <stdio.h> struct Shader s1; struct Shader* s1_ptr = &s1; struct Shader s2; struct Shader* s2_ptr = &s2; struct Shader s3; struct Shader* s3_ptr = &s3; //#define DEBUG // Prints to console //#define VERIFYFILE // Handle file errors //#define READFROMFILE // If the shaders are read from an external file void doShader() { #ifndef READFROMFILE #include "coolShader.h" #include "perlinShader.h" #include "interference.h" #include "phong.h" s1_ptr->vs_source = perlinNoise_vs; s1_ptr->fs_source = perlinNoise_fs; s2_ptr->vs_source = phong_vs; s2_ptr->fs_source = phong_fs; s3_ptr->vs_source = perlinNoise_vs; s3_ptr->fs_source = perlinNoise_fs; #else s1_ptr->vs_source = loadSource("coolShader.vs"); s1_ptr->fs_source = loadSource("coolShader.fs"); #endif #ifdef DEBUG fprintf(stderr, "%s\n**%s\n**", s1_ptr->vs_source, s1_ptr->fs_source); #endif compile(s1_ptr); compile(s2_ptr); } #ifdef READFROMFILE char* loadSource(const char* filename) { FILE* filePtr; char* buffer = NULL; int count = 0; #ifdef VERIFYFILE if (filename != NULL) { filePtr = fopen(filename, "rt"); if (filePtr != NULL) { #ifdef DEBUG fprintf(stderr, "Opened file %s\n", filename); #endif fseek(filePtr, 0, SEEK_END); count = ftell(filePtr); rewind(filePtr); if (count > 0) { buffer = (char *)malloc(sizeof(char) * (count+1)); count = fread(buffer,sizeof(char),count,filePtr); buffer[count] = '\0'; } fclose(filePtr); } else { #ifdef DEBUG fprintf(stderr, "Could not open file %s\n", filename); #endif } } #else filePtr = fopen(filename, "rt"); #ifdef DEBUG fprintf(stderr, "Opened file %s\n", filename); #endif fseek(filePtr, 0, SEEK_END); count = ftell(filePtr); rewind(filePtr); if (count > 0) { buffer = (char *)malloc(sizeof(char) * (count+1)); count = fread(buffer,sizeof(char),count,filePtr); buffer[count] = '\0'; } fclose(filePtr); #endif return buffer; } #endif void compile(struct Shader* toCompile) { #ifdef DEBUG fprintf(stderr, "Compiling\n"); #endif toCompile->vs_handle = glCreateShader(GL_VERTEX_SHADER); toCompile->fs_handle = glCreateShader(GL_FRAGMENT_SHADER); const GLchar* vs_src = toCompile->vs_source; const GLchar* fs_src = toCompile->fs_source; char* infoLog; int infoLogLength = 0; glShaderSource(toCompile->vs_handle, 1, &vs_src, NULL); glShaderSource(toCompile->fs_handle, 1, &fs_src, NULL); #ifdef DEBUG fprintf(stderr, "---\n\n%s\n\n%s\n\n", toCompile->vs_source, toCompile->fs_source); #endif glCompileShader(toCompile->vs_handle); #ifdef DEBUG printShaderInfoLog(toCompile->vs_handle); if (!(glGetError() == GL_NO_ERROR)) { fprintf(stderr, "Error compiling vertex shader %d\n", glGetError()); } #endif glCompileShader(toCompile->fs_handle); #ifdef DEBUG printShaderInfoLog(toCompile->fs_handle); if (!(glGetError() == GL_NO_ERROR)) { fprintf(stderr, "Error compiling fragment shader %d\n", glGetError()); } #endif toCompile->shader_handle = glCreateProgram(); #ifdef DEBUG fprintf(stderr, "shader_handle is %d\n", toCompile->shader_handle); #endif glAttachShader(toCompile->shader_handle, toCompile->vs_handle); glAttachShader(toCompile->shader_handle, toCompile->fs_handle); glLinkProgram(toCompile->shader_handle); #ifdef DEBUG fprintf(stderr, "shader_handle is %d\n", toCompile->shader_handle); printProgramInfoLog(toCompile->shader_handle); #endif } struct Shader* getShader(int id) { if (id == 0) return s1_ptr; if (id == 1) return s2_ptr; else return NULL; } #ifdef DEBUG void printShaderInfoLog(GLuint obj) { int infologLength = 0; int charsWritten = 0; char *infoLog; glGetShaderiv(obj, GL_INFO_LOG_LENGTH,&infologLength); if (infologLength > 0) { infoLog = (char *)malloc(infologLength); glGetShaderInfoLog(obj, infologLength, &charsWritten, infoLog); fprintf(stderr, "%s\n",infoLog); free(infoLog); } } void printProgramInfoLog(GLuint obj) { int infologLength = 0; int charsWritten = 0; char *infoLog; glGetProgramiv(obj, GL_INFO_LOG_LENGTH,&infologLength); if (infologLength > 0) { infoLog = (char *)malloc(infologLength); glGetProgramInfoLog(obj, infologLength, &charsWritten, infoLog); printf("%s\n",infoLog); free(infoLog); } } #endif void destroyShader(struct Shader* s) { #ifdef DEBUG fprintf(stderr, "Destroying shader\n"); #endif glDeleteProgram(s1_ptr->shader_handle); glDeleteShader(s->vs_handle); glDeleteShader(s->fs_handle); #ifdef DEBUG fprintf(stderr, "Freeing source\n"); #endif free(s->vs_source); #ifdef DEBUG fprintf(stderr, "Freeing source\n"); #endif free(s->fs_source); #ifdef DEBUG fprintf(stderr, "Shader destroyed\n"); #endif } void useShader(struct Shader* s) { glUseProgram(s->shader_handle); } void unuseShader() { glUseProgram(0); } void shaderSetInt(const char* n, int i, struct Shader* s) { glUniform1i(glGetUniformLocation(s->shader_handle, n), i); } void shaderSetFloat(const char* n, float f, struct Shader* s) { glUniform1f(glGetUniformLocation(s->shader_handle, n), f); }
C
#include <stdio.h> int factorial(int num) { int res = 0; /** * BASIS */ if (num == 0 || num == 1) { return 1; } else { res = num * factorial(num - 1); // proses rekursif return res; } } int main() { int num = 5; int fact = factorial(num); if (fact > 0) printf("\n The factorial of [%d] is [%d]\n", num, fact); return 0; }
C
#include <stdio.h> #include <stdlib.h> main () { int status; if ((status = system("date")) < 0) { // system은 fork하고, "date" command를 실행할 프로세를 exec하는데, 프로세스를 fork하는데 실패하면 -1를 리턴한다. perror("system"); exit(1); } printf("exit status = %d\n", status); if ((status = system("nosuchcommand")) < 0) { // 32512 리턴 perror("system"); exit(1); } printf("exit status = %d\n", status); if ((status = system("who; exit 44;")) < 0) { // 누가 로그인 되어있는지 출력하고, exit. 11264 리턴. perror("system"); exit(1); } printf("exit status = %d\n", status); }
C
/* TASKS: LAST COMPLETED: adding handlers for possible error handlers NEXT: Create all error possibilities and handle them IMPORTANT NOTES: Should add floats: so let 'f' be acceptable in number literals When adding values to one of the arrays, ensure to update the array size in their respective analyze functions */ /* ANALYZE METHODS RETURN VALUES: 1 --> lexeme completed 0 --> match -1 --> no match -2 --> error -3 --> single-line comment -4 --> multiline comment */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include "Header.h" //ONLY DOING int, double, void, char char *keywords[] = { "auto", "break", "case", "char", "const", "continue", "default", "do", "double", "else", "enum", "extern", "float", "for", "goto", "if", "int", "long", "NULL", "register", "return", "short", "signed", "sizeof", "static", "struct", "switch", "typedef", "union", "unsigned", "void", "volatile", "while" }; char *seperators[] = { "{", "}", ",", "[", "]", "(", ")", ";" }; char *operators[] = { //Should add modulus, and remember to update the array size in analyzeOperators************************ "+", "-", "/", "*", "=", ">", "<", "<=", ">=", "==", "!=", "++", "--", "+=", "-=", "/=", "*=", "&&", "||" }; char * comments[] = { "//", "/*", "*/" }; char *literalsymbols[] = { ".", "'", "\"" }; /* typedef enum { IDENTIFIER, KEYWORD, SEPERATOR, OPERATOR, COMMENT, LITERAL, NONE, ERROR } lexemetypes; */ /* typedef struct { char tempcurrentlexemevalue[50]; char *currentlexemevalue; int charcount; int lexemevaluecompleted; int iserror; lexemetypes currentlexemetype; } lexeme; */ //lexemetypes currentlexemetype; FILE * fp; //lexeme thislexeme; lexeme tokens[100]; lexeme getNextToken(); int analyzeComment(char letter, lexeme *thislexeme, FILE * fp); int analyzeIdentifier(char letter, lexeme *thislexeme, FILE *fp); int analyzeKeyword(char letter, lexeme *thislexeme, FILE *fp); int analyzeSeperator(char letter, lexeme *thislexeme, FILE *fp); int analyzeOperator(char letter, lexeme *thislexeme, FILE *fp); int analyzeLiteral(char letter, lexeme *thislexeme, FILE *fp); void printtokens(); char *lexemetypetostring(lexemetypes type); int firstcall = 0; int main() { lexeme thislexeme; thislexeme.iserror = 0; while (thislexeme.iserror != 1) { thislexeme = getNextToken(); if (thislexeme.iserror != 1) { char *value = thislexeme.currentlexemevalue; char *type = lexemetypetostring(thislexeme.currentlexemetype); printf("( %s , %s ) \n", type, value); } } } lexeme getNextToken() { /////////////////////////////////////////////////////////////////////////////// //thislexeme.lexemevaluecompleted = 0; //thislexeme.currentlexemetype = NONE; if (firstcall == 0) { fp = fopen("C:\\Users\\Owner\\Documents\\Yousef\\Programming Projects Connected To Github\\Compiler\\LexerTests\\Test2.txt", "r"); firstcall++; } if (fp == NULL) { printf("DERE WAS UN ERROR WHEN OPENING FILE"); lexeme thislexeme; thislexeme.iserror = 1; return thislexeme; } char currentchar = 0; int i = 0; static int isSingleLineComment = 0; static int isMultiLineComment = 0; static int tokenfinished = 0; int error = 0; if (currentchar != EOF) { if (tokenfinished != -3 && tokenfinished != -4) { tokenfinished = 0; } lexeme thislexeme; thislexeme.lexemevaluecompleted = 0; thislexeme.iserror = 0; thislexeme.currentlexemetype = NONE; thislexeme.charcount = 0; if (currentchar != 0) { fseek(fp, -1, SEEK_CUR); } while ((currentchar = getc(fp)) != EOF && (tokenfinished != 1 && tokenfinished != -2)) { ////DEBUG//// // char *type = lexemetypetostring(thislexeme.currentlexemetype); // printf("%s", type); /// if (isSingleLineComment == 1 && currentchar != '\n') { //isSingleLineComment = 0; continue; } else if (isSingleLineComment == 1) { isSingleLineComment = 0; continue; } if (isMultiLineComment == 1) { if ((tokenfinished = analyzeComment(currentchar, &thislexeme, fp)) == -4 && currentchar == '/') { isMultiLineComment = 0; } continue; } if (thislexeme.currentlexemetype == NONE || thislexeme.currentlexemetype == COMMENT) { tokenfinished = analyzeComment(currentchar, &thislexeme, fp); if (tokenfinished == -3) { //single-line comment tokenfinished = 1; isSingleLineComment = 1; } else if (tokenfinished == -4 && currentchar == '*') { tokenfinished = 1; isMultiLineComment = 1; continue; } //else if (tokenfinished == -4 && currentchar == '/') { // thislexeme.currentlexemetype = ERROR; // tokenfinished = 1; //} else if (tokenfinished == -2) { } } if (thislexeme.currentlexemetype == NONE || thislexeme.currentlexemetype == KEYWORD) { tokenfinished = analyzeKeyword(currentchar, &thislexeme, fp); } if (thislexeme.currentlexemetype == IDENTIFIER) { tokenfinished = analyzeIdentifier(currentchar, &thislexeme, fp); } if (thislexeme.currentlexemetype == NONE || thislexeme.currentlexemetype == SEPERATOR) { tokenfinished = analyzeSeperator(currentchar, &thislexeme, fp); } if (thislexeme.currentlexemetype == NONE || thislexeme.currentlexemetype == OPERATOR) { tokenfinished = analyzeOperator(currentchar, &thislexeme, fp); } if (thislexeme.currentlexemetype == NONE || thislexeme.currentlexemetype == LITERAL) { tokenfinished = analyzeLiteral(currentchar, &thislexeme, fp); } //I don't think we should have this! if (tokenfinished == -2) { lexeme thislexeme; thislexeme.iserror = 1; return thislexeme; } } //CHECK TO MAKE IT ERROR char *value = malloc(sizeof(char) * (thislexeme.charcount + 1)); for (int j = 0; j != thislexeme.charcount; j++) { *(value + j) = thislexeme.tempcurrentlexemevalue[j]; //+ value 0xcccccccc <Error reading characters of string.> char * } *(value + thislexeme.charcount) = '\0'; thislexeme.currentlexemevalue = value; //for unended char's and strings if (thislexeme.currentlexemetype == LITERAL) { if (*thislexeme.currentlexemevalue == '"' && *(thislexeme.currentlexemevalue + thislexeme.charcount - 1) != '"') { thislexeme.currentlexemetype = ERROR; } else if (*thislexeme.currentlexemevalue == '\'' && *(thislexeme.currentlexemevalue + thislexeme.charcount - 1) != '\'') { thislexeme.currentlexemetype = ERROR; } } if (thislexeme.iserror == 1) { thislexeme.currentlexemetype = ERROR; } // an identifier that starts with a number: 1aa //////////////////////////// if (thislexeme.currentlexemetype != NONE) { return thislexeme; //what's going on with this future me??? //char *value = thislexeme.currentlexemevalue; //char *type = lexemetypetostring(thislexeme.currentlexemetype); //printf("( %s , %s ) \n", type, value); } } fclose(fp); //printtokens(); lexeme thislexeme; thislexeme.iserror = 1; return thislexeme; } int analyzeComment(char letter, lexeme *thislexeme, FILE * fp) { static int ismultiline = 0; if (letter == '/' && thislexeme->currentlexemetype == NONE && ismultiline != 1) { char nextchar = getc(fp); if (nextchar != '*' && nextchar != '/') { fseek(fp, -1, SEEK_CUR); return -1; } fseek(fp, -1, SEEK_CUR); thislexeme->currentlexemetype = COMMENT; thislexeme->tempcurrentlexemevalue[thislexeme->charcount++] = letter; return 0; } else if (letter == '*' && thislexeme->currentlexemetype == COMMENT && thislexeme->tempcurrentlexemevalue[0] == '/') { thislexeme->tempcurrentlexemevalue[thislexeme->charcount++] = letter; char *value = malloc(sizeof(char) * thislexeme->charcount + 1); for (int j = 0; j != thislexeme->charcount; j++) { *(value + j) = thislexeme->tempcurrentlexemevalue[j]; //+ value 0xcccccccc <Error reading characters of string.> char * } *(value + thislexeme->charcount) = '\0'; thislexeme->currentlexemevalue = value; ismultiline = 1; thislexeme->lexemevaluecompleted = 1; return -4; } else if (letter == '*' && ismultiline == 1 && thislexeme->currentlexemetype == NONE) { thislexeme->currentlexemetype = COMMENT; thislexeme->tempcurrentlexemevalue[thislexeme->charcount++] = letter; return 0; } else if (letter == '/' && thislexeme->currentlexemetype == COMMENT && thislexeme->tempcurrentlexemevalue[0] == '/') { thislexeme->tempcurrentlexemevalue[thislexeme->charcount++] = letter; char *value = malloc(sizeof(char) * thislexeme->charcount + 1); for (int j = 0; j != thislexeme->charcount; j++) { *(value + j) = thislexeme->tempcurrentlexemevalue[j]; //+ value 0xcccccccc <Error reading characters of string.> char * } *(value + thislexeme->charcount) = '\0'; thislexeme->currentlexemevalue = value; thislexeme->lexemevaluecompleted = 1; return -3; } else if (letter == '/' && thislexeme->currentlexemetype == COMMENT && thislexeme->tempcurrentlexemevalue[0] == '*') { thislexeme->tempcurrentlexemevalue[thislexeme->charcount++] = letter; char *value = malloc(sizeof(char) * thislexeme->charcount + 1); for (int j = 0; j != thislexeme->charcount; j++) { *(value + j) = thislexeme->tempcurrentlexemevalue[j]; //+ value 0xcccccccc <Error reading characters of string.> char * } *(value + thislexeme->charcount) = '\0'; thislexeme->currentlexemevalue = value; ismultiline = 0; thislexeme->lexemevaluecompleted = 1; return -4; } else { return -1; } } int analyzeKeyword(char letter, lexeme *thislexeme, FILE *fp) { if (thislexeme->currentlexemetype == NONE) { if (isalpha(letter) || letter == '_') { thislexeme->currentlexemetype = KEYWORD; thislexeme->tempcurrentlexemevalue[thislexeme->charcount++] = letter; return 0; } else { return -1; } } if (thislexeme->currentlexemetype == KEYWORD) { if (isalpha(letter) || letter == '_') { thislexeme->tempcurrentlexemevalue[thislexeme->charcount++] = letter; return 0; } else if (letter == ' ') { thislexeme->currentlexemetype = IDENTIFIER; //thislexeme->tempcurrentlexemevalue[thislexeme->charcount++] = letter;//remove this line; dont add the space! char *value = malloc(sizeof(char) * thislexeme->charcount + 1); for (int j = 0; j != thislexeme->charcount; j++) { *(value + j) = thislexeme->tempcurrentlexemevalue[j]; //+ value 0xcccccccc <Error reading characters of string.> char * } *(value + thislexeme->charcount) = '\0'; thislexeme->currentlexemevalue = value; for (int i = 0; i < 32; i++) { if (strcmp(thislexeme->currentlexemevalue, keywords[i]) == 0) { //Exception thrown at 0x66A0CA20 (ucrtbased.dll) in Compiler Phases Practice.exe: 0xC0000005 : Access violation reading location 0xCCCCCCCC. //that was after iteration 17 thought, which should not have happened thislexeme->currentlexemetype = KEYWORD; thislexeme->lexemevaluecompleted = 1; return 1; } } return -1; } else if (isdigit(letter)) { thislexeme->currentlexemetype = IDENTIFIER; return -1; } else { //symbols char *value = malloc(sizeof(char) * thislexeme->charcount + 1); for (int j = 0; j != thislexeme->charcount; j++) { *(value + j) = thislexeme->tempcurrentlexemevalue[j]; //+ value 0xcccccccc <Error reading characters of string.> char * } *(value + thislexeme->charcount) = '\0'; thislexeme->currentlexemevalue = value; thislexeme->currentlexemetype = IDENTIFIER; for (int i = 0; i < 32; i++) { if (strcmp(thislexeme->currentlexemevalue, keywords[i]) == 0) { thislexeme->currentlexemetype = KEYWORD; } } thislexeme->lexemevaluecompleted = 1; return 1; } } return -2; } int analyzeIdentifier(char letter, lexeme *thislexeme, FILE *fp) { if (isalnum(letter) || letter == '_') { //alpha or numeric thislexeme->tempcurrentlexemevalue[thislexeme->charcount++] = letter; return 0; } else if (letter == ' ') { //space char *value = malloc(sizeof(char) * thislexeme->charcount + 1); for (int j = 0; j != thislexeme->charcount; j++) { *(value + j) = thislexeme->tempcurrentlexemevalue[j]; //+ value 0xcccccccc <Error reading characters of string.> char * } *(value + thislexeme->charcount) = '\0'; thislexeme->currentlexemevalue = value; thislexeme->lexemevaluecompleted = 1; return 1; } else { //symbol char *value = malloc(sizeof(char) * thislexeme->charcount + 1); for (int j = 0; j != thislexeme->charcount; j++) { *(value + j) = thislexeme->tempcurrentlexemevalue[j]; //+ value 0xcccccccc <Error reading characters of string.> char * } *(value + thislexeme->charcount) = '\0'; thislexeme->currentlexemevalue = value; fseek(fp, -1, SEEK_CUR); thislexeme->lexemevaluecompleted = 1; return 1; } } int analyzeLiteral(char letter, lexeme *thislexeme, FILE *fp) { static int ischar = 0; static int isstring = 0; static int charcount = 0; //static int iserror = 0; if (thislexeme->currentlexemetype == NONE) { if (isdigit(letter)) { thislexeme->currentlexemetype = LITERAL; thislexeme->tempcurrentlexemevalue[thislexeme->charcount++] = letter; return 0; } else if (letter == '\'') { thislexeme->currentlexemetype = LITERAL; thislexeme->tempcurrentlexemevalue[thislexeme->charcount++] = letter; ischar = 1; return 0; } else if (letter == '"') { thislexeme->currentlexemetype = LITERAL; thislexeme->tempcurrentlexemevalue[thislexeme->charcount++] = letter; isstring = 1; return 0; } return -1; } if (thislexeme->currentlexemetype == LITERAL && ischar == 0 && isstring == 0) { //int and float first if (isdigit(letter)) { thislexeme->tempcurrentlexemevalue[thislexeme->charcount++] = letter; return 0; } else if (letter == '.') { thislexeme->tempcurrentlexemevalue[thislexeme->charcount++] = letter; return 0; } else if (isalpha(letter) || letter == '_') { thislexeme->iserror = 1; thislexeme->tempcurrentlexemevalue[thislexeme->charcount++] = letter; return 0; } char *value = malloc(sizeof(char) * thislexeme->charcount + 1); for (int j = 0; j != thislexeme->charcount; j++) { *(value + j) = thislexeme->tempcurrentlexemevalue[j]; //+ value 0xcccccccc <Error reading characters of string.> char * } *(value + thislexeme->charcount) = '\0'; thislexeme->currentlexemevalue = value; //fseek(fp, -1, SEEK_CUR); if (thislexeme->iserror == 0) { thislexeme->lexemevaluecompleted = 1; return 1; } else if (thislexeme->iserror == 1) { thislexeme->currentlexemetype = ERROR; thislexeme->lexemevaluecompleted = 1; return 1; } } //for char literals else if (thislexeme->currentlexemetype == LITERAL && ischar == 1 && isstring == 0) { if (letter != '\'' && thislexeme->charcount == 1) { //all letters thislexeme->tempcurrentlexemevalue[thislexeme->charcount++] = letter; return 0; } else if (letter == '\'' && thislexeme->charcount == 1) { // if the literal is '' thislexeme->tempcurrentlexemevalue[thislexeme->charcount++] = letter; char *value = malloc(sizeof(char) * thislexeme->charcount + 1); for (int j = 0; j != thislexeme->charcount; j++) { *(value + j) = thislexeme->tempcurrentlexemevalue[j]; //+ value 0xcccccccc <Error reading characters of string.> char * } *(value + thislexeme->charcount) = '\0'; thislexeme->currentlexemevalue = value; ischar = 0; thislexeme->lexemevaluecompleted = 1; return 1; } else if (thislexeme->charcount == 2 && *(thislexeme->tempcurrentlexemevalue + 1) == '\\') { thislexeme->tempcurrentlexemevalue[thislexeme->charcount++] = letter; return 0; } else if (letter == '\'' && (thislexeme->charcount == 2 || thislexeme->charcount == 3)) { thislexeme->tempcurrentlexemevalue[thislexeme->charcount++] = letter; char *value = malloc(sizeof(char) * thislexeme->charcount + 1); for (int j = 0; j != thislexeme->charcount; j++) { *(value + j) = thislexeme->tempcurrentlexemevalue[j]; //+ value 0xcccccccc <Error reading characters of string.> char * } *(value + thislexeme->charcount) = '\0'; thislexeme->currentlexemevalue = value; ischar = 0; thislexeme->lexemevaluecompleted = 1; return 1; } thislexeme->currentlexemetype = NONE; ischar = 0; return -2; } //for string literals else if (thislexeme->currentlexemetype == LITERAL && ischar == 0 && isstring == 1) { if (letter != '"') { thislexeme->tempcurrentlexemevalue[thislexeme->charcount++] = letter; return 0; } else if (letter == '"' && *(thislexeme->tempcurrentlexemevalue + thislexeme->charcount - 1) == '\\') { thislexeme->tempcurrentlexemevalue[thislexeme->charcount++] = letter; return 0; } else if (letter == '"') { thislexeme->tempcurrentlexemevalue[thislexeme->charcount++] = letter; char *value = malloc(sizeof(char) * thislexeme->charcount + 1); for (int j = 0; j != thislexeme->charcount; j++) { *(value + j) = thislexeme->tempcurrentlexemevalue[j]; //+ value 0xcccccccc <Error reading characters of string.> char * } *(value + thislexeme->charcount) = '\0'; thislexeme->currentlexemevalue = value; isstring = 0; thislexeme->lexemevaluecompleted = 1; return 1; } isstring = 0; return -2; } return -2; } int analyzeOperator(char letter, lexeme *thislexeme, FILE *fp) { if (thislexeme->currentlexemetype == NONE) { //iterate through list of operators for (int i = 0; i < 19; i++) { if (letter == operators[i][0]) { thislexeme->currentlexemetype = OPERATOR; thislexeme->tempcurrentlexemevalue[thislexeme->charcount++] = letter; return 0; } } return -1; } if (thislexeme->currentlexemetype == OPERATOR) { //check if operator //iterate through list of operators //check if its a 1 'digit' operator, and if not, check if letter == operators[i][1] INSTEAD: for (int i = 0; i < 19; i++) { if (letter == operators[i][1]) { if (thislexeme->charcount < 2) { //OPTIMIZE::: move this outside of the for loop thislexeme->tempcurrentlexemevalue[thislexeme->charcount++] = letter; char *value = malloc(sizeof(char) * thislexeme->charcount + 1); for (int j = 0; j < thislexeme->charcount; j++) { *(value + j) = thislexeme->tempcurrentlexemevalue[j]; //+ value 0xcccccccc <Error reading characters of string.> char * } *(value + thislexeme->charcount) = '\0'; thislexeme->currentlexemevalue = value; thislexeme->lexemevaluecompleted = 1; return 1; } return -2; } } //Dont add the whole for-loop/value * thing, this is good thislexeme->lexemevaluecompleted = 1; return 1; } return -2; } int analyzeSeperator(char letter, lexeme *thislexeme, FILE *fp) { if (thislexeme->currentlexemetype == NONE) { //iterate through list of seperators for (int i = 0; i < 8; i++) { if (letter == seperators[i][0]) { thislexeme->currentlexemetype = SEPERATOR; thislexeme->tempcurrentlexemevalue[0] = letter; thislexeme->currentlexemevalue = malloc(sizeof(char) * 2); *(thislexeme->currentlexemevalue) = letter; *(thislexeme->currentlexemevalue + 1) = '\0'; thislexeme->charcount++; thislexeme->lexemevaluecompleted = 1; return 1; } } } return -1; } void printtokens() { for (int i = 0; i < 100; i++) { char *value = tokens[i].tempcurrentlexemevalue; char *type = lexemetypetostring(tokens[i].currentlexemetype); printf("( %s , %s ) \n", type, value); } } char *lexemetypetostring(lexemetypes type) { if (type == NONE) { return "None"; } else if (type == COMMENT) { return "Comment"; } else if (type == KEYWORD) { return "Keyword"; } else if (type == IDENTIFIER) { return "Identifier"; } else if (type == LITERAL) { return "Literal"; } else if (type == OPERATOR) { return "Operator"; } else if (type == SEPERATOR) { return "Seperator"; } else { return "Error"; } }
C
#include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <time.h> #include "memorymanager.h" int launcher(FILE *p, char *fileName, PCB *pcb) { //Copy the entire file into the backing store. char buffer[1024]; snprintf(buffer, sizeof(buffer), "cp %s BackingStore/", fileName); system(buffer); //close the file fclose(p); //Open the file from backing store char *filePath = malloc(strlen("BackingStore/") + strlen(pcb->fileName) + 1); strcpy(filePath, "BackingStore/"); strcat(filePath, pcb->fileName); FILE *file = fopen(filePath, "r"); if (file == NULL) { printf("file is not backedup!\n"); return 0; } // figure our the total number of pages int totalPages = countTotalPages(file); for (int i = 0; i < 2; i++) { if (totalPages < 2 && i == 1) { return 1; } //find an empty frame int emptyFrameNumber = findFrame(); //load the page into ram loadPage(i, file, emptyFrameNumber); //update pbc's page table updatePageTable(pcb, i, emptyFrameNumber, -1); } return 1; } int countTotalPages(FILE *f) { rewind(f); int count = 1; int ch = 0; while (!feof(f)) { ch = fgetc(f); if (ch == '\n') { count++; } } if (count % 4 != 0) return count / 4 + 1; else return count / 4; } void loadPage(int pageNumber, FILE *file, int frameNumber) { rewind(file); int index_BackingStore = pageNumber * 4; int maxIndex_BackingStore = index_BackingStore + 4; int index_RAM = frameNumber * 4; char line[256]; int i = 0; while (fgets(line, sizeof(line), file) && (line != '/0' || line != '/n' || line != '/r' || line != NULL)) { if (i >= index_BackingStore && i < maxIndex_BackingStore) { ram[index_RAM] = (char *)malloc(sizeof(char) * 10000); strcpy(ram[index_RAM], line); index_RAM++; index_BackingStore++; } i++; } } int findFrame() { for (int i = 0; i < 40; i += 4) { if (ram[i] == NULL) { return i / 4; } } return -1; } int findVictim(PCB *pcb) { srand(time(0)); int randomFrameNumber = rand() % 10; while (true) { if (frameNumberDoesNotBelongToPCB(randomFrameNumber, pcb)) { return randomFrameNumber; } randomFrameNumber++; } return -1; } bool frameNumberDoesNotBelongToPCB(int frameNumber, PCB *pcb) { for (int i = 0; i < 10; i++) { if (pcb->pageTable[i] == frameNumber) return false; } return true; } int updatePageTable(PCB *pcb, int pageNumber, int frameNumber, int victimFrame) { if (victimFrame == -1) { pcb->pageTable[pageNumber] = frameNumber; } else { pcb->pageTable[pageNumber] = victimFrame; } }
C
// NIM : Adiyansa Prasetya Wicaksana // Nama : 13520044 // Tanggal : 9 September 2021 // Topik : Implementasi ADT List #include <stdio.h> #include <stdlib.h> #include "listpos.h" int main() { ListPos l1; ElType min, max; int x, idx; CreateListPos(&l1); readList(&l1); scanf("%d", &x); extremes(l1, &max, &min); idx = length(l1); if (indexOf(l1, x) != IDX_UNDEF) { displayList(l1); printf("\n"); printf("%d", indexOf(l1, x)); printf("\n"); sort(&l1, true); if (max == x) { printf("maksimum\n"); } if (min == x) { printf("minimum\n"); } if (idx % 2 == 0) { if (ELMT(l1, idx/2 -1) == x) { printf("median\n"); } } else { if (ELMT(l1, (idx/2)) == x) { printf("median\n"); } } } else { displayList(l1); printf("\n"); printf("%d tidak ada", x); printf("\n"); } return 0; }
C
#include "process_ancestors.h" #include <linux/unistd.h> #include <linux/kernel.h> #include <linux/slab.h> #include <linux/uaccess.h> #include <linux/sched.h> #define __PROCESS_ANCESTORS_ 332 #define ANCESTOR_NAME_LEN 16 //function def asmlinkage long sys_process_ancestors(struct process_info info_array[], long size, long *num_filled); struct process_info process_info_getter(struct task_struct* curr_task); struct process_info process_info_getter(struct task_struct* curr_task){ struct process_info result; int num_children, num_sibling; struct list_head* ptr; result.pid = curr_task->pid; result.state = curr_task->state; result.uid = curr_task->cred->uid.val; result.nvcsw = curr_task->nvcsw; result.nivcsw = curr_task->nivcsw; // name is in .comm and can be copied using memcpy function memcpy(result.name, curr_task->comm, ANCESTOR_NAME_LEN); //list_for_each used to traverse //list_for_each(p, list) { /* p points to an entry in the list */ //} list_for_each(ptr, &(curr_task->children)){ ++num_children; } list_for_each(ptr, &(curr_task->sibling)){ ++num_sibling; } result.num_children = num_children; result.num_sibling = num_sibling; return result; } asmlinkage long sys_process_ancestors(struct process_info info_array[], long size, long *num_filled) { long curr_num_filled = 0; struct process_info* temp_info_array; struct task_struct* curr_process, prev_process; if (size <=0){return -EINVAL;} temp_info_array = kmalloc(sizeof(struct process_info)*size, GFP_KERNEL); for (int i=0;i<size;i++){ if(copy_from_user(&temp_info_array[i],&info_array[i], sizeof(struct process_info))){ kfree(temp_info_array); return -EFAULT; } } //latest children temp_info_array[0] = get_process_info(current); curr_num_filled++; int j=1; while (j<size && curr_process != prev_process){ temp_info_array[j] = process_info_getter(curr_process); curr_num_filled++; prev_process = curr_process; curr_process = curr_process->parent; j++ } for (int k=0; k<num_filled;k++){ if (copy_to_user(&info_array[k], &temp_info_array[k], sizeof(struct process_info))){ kfree(temp_info_array); return -EFAULT; } } if (copy_to_user(num_filled, &curr_num_filled, sizeof(long))){ return -EFAULT; } kfree(temp_info_array); return 0; }
C
#ifndef showplot_h #define showplot_h // Number of cues in each scene // FIXME: these must be manually maintained const Scene SCENE_TEST = {2,sceneTest}; const Scene SCENE_WHITE_FLASHES = {5,sceneWhiteFlashes}; const Scene SCENE_WHITE_BREATH = {1,sceneWhiteBreath}; const Scene SCENE_CHASE = {7,sceneChase}; const Scene SCENE_COLOUR = {9,sceneColour}; const Scene SCENE_MAGNETOMETER = {1,sceneMagnetometer}; // Sequence of scenes in show const Scene SHOW_PLOT[] = { SCENE_TEST, SCENE_WHITE_FLASHES, SCENE_WHITE_BREATH, SCENE_CHASE, SCENE_COLOUR, SCENE_MAGNETOMETER }; const short NUM_SCENES_IN_SHOW_PLOT = sizeof(SHOW_PLOT) / sizeof(Scene); #endif
C
#include <stdlib.h> void main( void ) { int _far *timer = (int _far *)0x0040006C; unsigned long counter; double x; double y; unsigned long hits = 0; double pi; srand( *timer ); for( counter = 1; counter <= 10000; counter++ ) { x = (double)(rand() % 351) / 350; y = (double)(rand() % 351) / 350; if( (x * x) + (y * y) <= 1 ) hits++; } pi = (double)hits * 4 / (double)counter; printf( "Pi-Nherung: %f", (float)pi ); }
C
#include <stdio.h> #include <stdlib.h> #include <math.h> #include "arg_complex.h" #include <complex.h> void printComplex(Complex c){ printf("(%5.2f,%5.2f)",c.real,c.imag); } Complex add(Complex a,Complex b){ Complex result = {a.real+b.real,a.imag+b.imag}; return result; } Complex sub(Complex a,Complex b){ Complex result = {a.real-b.real,a.imag-b.imag}; return result; } Complex mult(Complex a,Complex b){ Complex result = {a.real*b.real-a.imag*b.imag ,a.real*b.imag+a.imag*b.real}; return result; } Complex divC(Complex a,Complex b){ Complex result = { (a.real*b.real+a.imag*b.imag) /(b.imag*b.imag+b.real*b.real) , (a.imag*b.real-a.real*b.imag) /(b.imag*b.imag+b.real*b.real)}; return result; } Complex cconj(Complex a){ Complex result ={(a.real),(a.imag*-1)}; return result; } Complex real(Complex a){ Complex result ={(a.real)}; return result; } Complex imag(Complex a){ Complex result ={(a.real*0),(a.imag)}; return result; } Complex betrag(Complex a){ Complex result ={(sqrt(pow(a.real,2))+(pow(a.imag,2)))}; return result; }
C
/****WAP THAT ACCEPT TWO CHARACTERS FROM THE USER, AND PRINT MESSAGE THAT "BOTH CHARACTERS ARE SAME" IF BOTH ALPHABETS ARE SAME AND IN OPPOSITE CASE OTHERWISE CONVERT THE SECOND ALPHABET AS THE OPPOSTE CASE OF THE FIRST ALPHABET*****/ #include<stdio.h> void main() { char a,b; printf("Enter two characters : "); scanf("%c %c",&a,&b); if(a==b+32 || a+32==b) { printf("Both Characters are Same"); } else { char x=a; if(x>='A'&&x<='Z') { b=b+32; printf("After conversion : %c %c",a,b); } else if(x>='a'&&x<='z') { b=b-32; printf("After conversion : %c %c",a,b); } } }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* print_inf_nan.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: pdemocri <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/06/06 16:15:10 by pdemocri #+# #+# */ /* Updated: 2020/06/06 16:21:30 by pdemocri ### ########.fr */ /* */ /* ************************************************************************** */ #include <stdarg.h> #include <float.h> #include "libftprintf.h" #include "libft.h" int isinfnan(double *d) { double d1; double d2; d1 = -DBL_MAX + 1 / ft_pow(10, 308); d2 = DBL_MAX - 1 / ft_pow(10, 308); if (*((unsigned long *)(d)) == DBL_INF || *((unsigned long *)(d)) == DBL_NINF || *((unsigned long *)(d)) == DBL_NAN || *((unsigned long *)(d)) == DBL_NZERO || *((unsigned long *)(d)) == FTPF_LDBL_INF || *d <= d1 || *d >= d2) return (1); return (0); } static int get_inftnan(t_flags *f, char buf[5], double *d) { if (*((unsigned long *)(d)) == DBL_NAN) buf = ft_strcpy(buf, "nan"); else if (*((unsigned long *)(d)) == DBL_INF) { if (f->plus || f->hidden) buf = f->plus ? ft_strcpy(buf, "+inf") : ft_strcpy(buf, " inf"); else buf = ft_strcpy(buf, "inf"); } else if (*((unsigned long *)(d)) == DBL_NINF) buf = ft_strcpy(buf, "-inf"); else if (*((unsigned long *)(d)) == DBL_NZERO) { f->nzero = 1; f->sign = 1; return (print_f(f, 0)); } return (0); } int print_infnan(t_flags *f, double *d) { int n; int len; int spaces; char buf[5]; ft_bzero(buf, 5); if (*((unsigned long *)(d)) == DBL_NAN || *((unsigned long *)(d)) == DBL_INF || *((unsigned long *)(d)) == DBL_NINF) get_inftnan(f, buf, d); else if (*((unsigned long *)(d)) == DBL_NZERO) return (get_inftnan(f, buf, d)); else if (*d >= DBL_MAX - 1 / ft_pow(10, 308)) return (print_dblmax()); else if (*d <= -DBL_MAX + 1 / ft_pow(10, 308)) return (ft_putchar('-') + print_dblmax()); ignored_flags(f); len = ft_strlen(buf); n = print_space_ch(f->zero_l - len, ' '); if (f->dot) len = (f->dot_l < len) ? f->dot_l : len; spaces = f->spaces_l - len; n += (f->minus ? (write(1, buf, len) + print_space_ch(spaces, ' ')) : print_space_ch(spaces, ' ') + write(1, buf, len)); return (n); } int print_dblmax(void) { return (ft_putstr("1797693134862315708145274237317043567980705675258449") + ft_putstr("965989174768031572607800285387605895586327668781715404589535") + ft_putstr("143824642343213268894641827684675467035375169860499105765512") + ft_putstr("820762454900903893289440758685084551339423045832369032229481") + ft_putstr("658085593321233482747978262041447231687381771809192998812504") + ft_putstr("04026184124858368.000000")); }
C
//acosh(), atanh(), sinh(), cosh(), tanh() //csinh(), casinh() #include <math.h> double asinh(double x); float asinhf(float x); long double asinhl(long double x); puts("x asinh(x) log(x + sqrt(x*x+1))\n" "-----------------------------------"); for(double x = -2.0; x < 2.1; x += 0.5) { printf("%6.2f %15f %20f\n", x, asinh(x), log(x +sqrt(x * 1.0))); }
C
#include "unity.h" #include "node.h" void setUp(void){} void tearDown(void){} void test_create_a_new_node_with_the_node_value_is_forty(void){ int color = 20; int data = 40; Node *newNode; newNode = createNode(color, data); TEST_ASSERT_EQUAL(20, newNode->colour); TEST_ASSERT_EQUAL(40, newNode->value); TEST_ASSERT_EQUAL(NULL, newNode->right); TEST_ASSERT_EQUAL(NULL, newNode->left); } void test_insert_a_child_into_the_tree_right_side(void){ int color = 20; int data = 80; int data2 = 150; Node *newNode, *child; newNode = createNode(color, data); child = createNode(color, data2); insert(newNode, child); TEST_ASSERT_EQUAL_PTR(newNode->right, child); TEST_ASSERT_EQUAL_PTR(newNode->left, NULL); } void test_insert_a_child_into_the_tree_left_side(void){ int color = 20; int data = 80; int data2 = 40; Node *newNode, *child; newNode = createNode(color, data); child = createNode(color, data2); insert(newNode, child); TEST_ASSERT_EQUAL_PTR(newNode->left, child); TEST_ASSERT_EQUAL_PTR(newNode->right, NULL); } void xtest_insert_two_layer_into_the_tree(void){ int color = 2; int data = 80; int data2 = 40; int data3 = 100; int data4 = 20; Node *newNode, *child1, *child2, *grandChild; newNode = createNode(color, data); child1 = createNode(color, data2); child2 = createNode(color, data3); grandChild = createNode(color, data4); insert(newNode, child1); insert(newNode, child2); insert(newNode, grandChild); TEST_ASSERT_EQUAL_PTR(newNode->left, child1); TEST_ASSERT_EQUAL_PTR(newNode->right, child2); TEST_ASSERT_EQUAL_PTR(newNode->left->left, grandChild); TEST_ASSERT_EQUAL_PTR(newNode->left->right, NULL); }
C
#include <stdio.h> #include <stdlib.h> #include "algoritmo.h" int LRU(Frame* listFrames, int lenList, int* nextIndexes) { int index, max_time = 0x0FFFFFFF; for (int i = 0; i < lenList; ++i) if (listFrames[i].time < max_time) { index = i; max_time = listFrames[i].time; } return index; } int NRU(Frame* listFrames, int lenList, int* nextIndexes) { int ind1 = -1, ind2 = -1, ind3 = -1; for (int i = 0; i < lenList; ++i) { if ((listFrames[i].flagR == '0') && (listFrames[i].flagW == '0')) return i; else if ((listFrames[i].flagR == '0') && (listFrames[i].flagW == '1')) ind1=i; else if ((listFrames[i].flagR == '1') && (listFrames[i].flagW == '0')) ind2 = i; else if ((listFrames[i].flagR == '1') && (listFrames[i].flagW == '1')) ind3 = i; } if(ind1 != -1) return ind1; else if (ind2 != -1) return ind2; else return ind3; } int NOVO(Frame* listFrames, int lenList, int* nextIndexes) { char* possibleIndexes = (char*)malloc(sizeof(char) * lenList); for(int i = 0; i < lenList; ++i) possibleIndexes[i] = '1'; for (int i = 0; i < 50; ++i) { if (nextIndexes[i] == -1) continue; else possibleIndexes[nextIndexes[i]] = '0'; } for (int i = 0; i < lenList; ++i) { if(possibleIndexes[i] == '1') return i; } return LRU(listFrames, lenList, nextIndexes); }
C
/******************************************************************** Author: Jordan A. Caraballo Vega Operating Systems, Prof. Jose Sotero Esteva Objective: Use fork to create a parent and children processes ancestral line. Parent, son, younger son, yongest son References: A. Silberschatz, Operating Systems Concepts (9th Edition). http://www.csl.mtu.edu/cs4411.ck/www/NOTES/process/fork/create.html http://pubs.opengroup.org/onlinepubs/009695399/functions/getppid.html TODO: Make this program run for N generations (foor loop - did not have time to finish it). *********************************************************************/ #include <sys/types.h> #include <stdio.h> #include <unistd.h> int main() { /* Define the number of ancesters that you want and call the forks */ int numAnces = 3; // number of children wanted int integer = 5; // value to prove stack local values printf( "Se definio variable local tipo entero = 5.\n"); /* Get the pid from the initial process (dad) */ printf( "Papa con pid %d. ", getpid() ); printf("Stack Test: Sumando %d + 0 = %d\n", integer, integer + 0); // stack test /* Iterate and fork over each children */ if (fork() == 0) { /* New son from previous parent */ printf("Hijo con pid %d. Papa con pid %d. ", getpid(), getppid()); printf("Stack Test: Sumando %d + 1 = %d\n", integer, integer + 1); // stack test if (fork() == 0) { /* New son from previous parent */ printf("Nieto con pid %d. Papa con pid %d. ", getpid(), getppid()); printf("Stack Test: Sumando %d + 2 = %d\n", integer, integer + 2); // stack test if (fork() == 0) { /* New son from previous parent */ printf("Bisnieto con pid %d. Papa con pid %d. ", getpid(), getppid()); printf("Stack Test: Sumando %d + 3 = %d\n", integer, integer + 3); // stack test } } } return 0; }
C
#include "register.h" void init_registers(struct Registers * regs){ memset((void *) regs->reg, 0, 32 * sizeof(unsigned int)); } unsigned int get_register_value(struct Registers * regs, unsigned int addr){ if(0 <= addr && addr < 32){ return regs->reg[addr]; } else { printf("invalid address for register read\n"); return 0; } } void write_register_value(struct Registers * regs, unsigned int addr, unsigned int value){ if(0 < addr && addr < 32){ regs->reg[addr] = value; } else { printf("invalid address for register write\n"); } }
C
//This program is similar to ascii.c except the for loop is running from A to Z, instead of a number #include <cs50.h> #include <stdio.h> int main(void) { for (char c = 'A'; c <= 'Z'; c++) { printf("%c is %i\n", c, c); }
C
/// @file mtga.c /// @author Vesa Oikonen /// @brief Multiple-time graphical analysis (including Patlak and Logan plots). /// /*****************************************************************************/ #include "libtpcmodel.h" /*****************************************************************************/ /*****************************************************************************/ /** Calculates Gjedde-Patlak plot x,y values from the measured input and ROI concentration TACs. Plot will not include data where: 1) any of the values is not available (NaN), 2) integral is negative at this or later point, 3) divider is too close to zero, 4) plot x value is negative. @sa logan_data, img_patlak, llsqperp, mtga_best_perp @return Returns the number of acceptable Gjedde-Patlak plot data pairs, or <0 in case of an error. Note that zero or one return values prevent the line fitting, but are here not considered as errors. */ int patlak_data( /** Nr of samples. */ int data_nr, /** Array of input concentrations. */ double *i, /** Array of integrals (from zero to sample time) of input concentrations; if reference region input, then remember to consider the frame length. */ double *ii, /** Array of ROI concentrations. */ double *c, /** Pointer to preallocated memory (at least size dnr) where MTGA plot x values will be written. */ double *x, /** Pointer to preallocated memory (at least size dnr) where MTGA plot y values will be written. */ double *y ) { int fi, plot_nr=0; double divider_limit=1.0E-12; if(data_nr<0 || i==NULL || ii==NULL || c==NULL || x==NULL || y==NULL) return -1; for(fi=0; fi<data_nr; fi++) { // check that all measured data is available if(isnan(i[fi]) || isnan(ii[fi]) || isnan(c[fi])) continue; if(!(i[fi]>-1.0E+20 && i[fi]<+1.0E+20)) continue; if(!(ii[fi]>-1.0E+20 && ii[fi]<+1.0E+20)) continue; if(!(c[fi]>-1.0E+20 && c[fi]<+1.0E+20)) continue; // check that integral has been >=0 all the time if(ii[fi]<0.0) {plot_nr=0; continue;} // check that dividers are not too close to zero if(fabs(i[fi])<divider_limit) continue; // calculate plot x axis value x[plot_nr]=ii[fi]/i[fi]; if(!(x[plot_nr]>-1.0E+20 && x[plot_nr]<+1.0E+20)) continue; if(x[plot_nr]<0.0) continue; // calculate plot y axis value y[plot_nr]=c[fi]/i[fi]; if(!(y[plot_nr]>-1.0E+20 && y[plot_nr]<+1.0E+20)) continue; // so this plot data point is fine plot_nr++; } return(plot_nr); } /*****************************************************************************/ /*****************************************************************************/ /** Calculates Logan plot x,y values from the measured input and ROI concentration TACs. Plot will not include data where: 1) any of the values is not available (NaN), 2) integral is negative at this or later point, 3) divider is too close to zero. @sa patlak_data, img_logan, llsqperp, mtga_best_perp @return Returns the number of acceptable Logan plot data pairs, or <0 in case of an error. Note that zero or one return values prevent the line fitting, but are here not considered as errors. */ int logan_data( /** Nr of samples. */ int data_nr, /** Array of input concentrations. */ double *i, /** Array of integrals (from zero to sample time) of input concentrations; if reference region input, then remember to consider the frame length. */ double *ii, /** Array of ROI concentrations. */ double *c, /** Array of ROI integrals (from zero to frame middle time). */ double *ci, /** Reference region k2; set to <=0 if not needed. */ double k2, /** Pointer to preallocated memory (at least size dnr) where MTGA plot x values will be written. */ double *x, /** Pointer to preallocated memory (at least size dnr) where MTGA plot y values will be written. */ double *y ) { int fi, plot_nr=0; double divider_limit=1.0E-18; if(data_nr<0 || i==NULL || ii==NULL || c==NULL || ci==NULL) return -1; if(x==NULL || y==NULL) return -1; for(fi=0; fi<data_nr; fi++) { // check that all measured data is available if(isnan(i[fi]) || isnan(ii[fi]) || isnan(c[fi]) || isnan(ci[fi])) continue; if(!(i[fi]>-1.0E+30 && i[fi]<+1.0E+30)) continue; if(!(ii[fi]>-1.0E+30 && ii[fi]<+1.0E+30)) continue; if(!(c[fi]>-1.0E+30 && c[fi]<+1.0E+30)) continue; if(!(ci[fi]>-1.0E+30 && ci[fi]<+1.0E+30)) continue; // check that integrals have been >=0 all the time if(ii[fi]<0.0) {plot_nr=0; continue;} if(ci[fi]<0.0) {plot_nr=0; continue;} // check that dividers are not too close to zero if(fabs(c[fi])<divider_limit) continue; // calculate plot x axis value if(k2>0.0) x[plot_nr]=(ii[fi]+i[fi]/k2)/c[fi]; else x[plot_nr]=ii[fi]/c[fi]; if(!(x[plot_nr]>-1.0E+30 && x[plot_nr]<+1.0E+30)) continue; // calculate plot y axis value y[plot_nr]=ci[fi]/c[fi]; if(!(y[plot_nr]>-1.0E+30 && y[plot_nr]<+1.0E+30)) continue; // so this plot data point is fine plot_nr++; } return(plot_nr); } /*****************************************************************************/ /*****************************************************************************/ /** Finds the best regression line to (x,y)-data, leaving points out from the beginning, because Gjedde-Patlak and Logan plots reach linearity at some later phase. This function applies llsqperp() which is a non-iterative perpendicular line fitting routine. @sa llsqperp(), logan_data, patlak_data @return Returns 0, if successful, and <>0 in case of an error */ int mtga_best_perp( /** Plot x axis values. */ double *x, /** Plot y axis values. */ double *y, /** Nr of plot data points. */ int nr, /** Slope is returned in here. */ double *slope, /** Y axis intercept is returned in here. */ double *ic, /** Sum of squared distances / fnr, or NULL if not needed. */ double *ssd, /** Number of points in the best fit, or NULL if not needed. */ int *fnr ) { int from, to, ret, from_min, to_min; double lic, lslope, lssd, ssd_min; /* Search the plot range that gives the lowest ssd */ ssd_min=9.99E+99; from_min=to_min=-1; for(from=0, to=nr-1; ((to-from)+1)>=MTGA_BEST_MIN_NR; from++) { ret=llsqperp(x+from, y+from, (to-from)+1, &lslope, &lic, &lssd); if(ret==0 && lssd<ssd_min) { ssd_min=lssd; from_min=from; to_min=to; *slope=lslope; *ic=lic; if(ssd!=NULL) *ssd=lssd; } } if(from_min<0) { if(fnr!=NULL) *fnr=0; if(ssd!=NULL) *ssd=0.0; return(5); } if(fnr!=NULL) *fnr=(to_min-from_min)+1; return(0); } /*****************************************************************************/ /*****************************************************************************/
C
#include "tiny.h" void swap_xyzw(t_xyzw *a, t_xyzw *b) { t_xyzw c; c = *a; *a = *b; *b = c; } // Height-based vertex sorting, required by draw_tri. void sort_tri(t_face *face) { if (face->vert[1].y < face->vert[0].y) swap_xyzw(&face->vert[0], &face->vert[1]); if (face->vert[2].y < face->vert[1].y) swap_xyzw(&face->vert[1], &face->vert[2]); if (face->vert[1].y < face->vert[0].y) swap_xyzw(&face->vert[0], &face->vert[1]); assert(face->vert[0].y <= face->vert[1].y && face->vert[1].y <= face->vert[2].y); } // Raster-space bounding box t_xy bb_min(t_face face) { int i; t_vert lowest; t_vert current; lowest = face.vert[0]; i = 1; while (i < face.verts) { current = face.vert[i]; if (current.y < lowest.y) lowest.y = current.y; if (current.x < lowest.x) lowest.x = current.x; ++i; } return vec2_clamp(vec2(lowest.x, lowest.y), 0, WIN_WIDTH); } // Raster-space bounding box t_xy bb_max(t_face face) { int i; t_vert highest; t_vert current; highest = face.vert[0]; i = 1; while (i < face.verts) { current = face.vert[i]; if (current.y > highest.y) highest.y = current.y; if (current.x > highest.x) highest.x = current.x; ++i; } return vec2_clamp(vec2(highest.x, highest.y), 0, WIN_HEIGHT); } // Note: left < 0, edge == 0, right > 0 double edge(t_xy p, t_xy a, t_xy b) { return ((p.x - a.x) * (b.y - a.y) - (p.y - a.y) * (b.x - a.x)); } // Note: Triangles are assumed to be in CCW order as per Wavefront. // When this is the case, the INSIDE of the triangle // is on the left side of each edge. (negative space) int inside(t_xy p, t_face face) { t_xy v0 = vec42(face.vert[0]); t_xy v1 = vec42(face.vert[1]); t_xy v2 = vec42(face.vert[2]); return (edge(p, v0, v1) <= 0 && (edge(p, v1, v2) <= 0) && (edge(p, v2, v0) <= 0)); } t_xyz bary(t_xy p, t_face face) { t_xy v0 = vec42(face.vert[0]); t_xy v1 = vec42(face.vert[1]); t_xy v2 = vec42(face.vert[2]); t_xyz weight; weight.x = edge(p, v0, v1); weight.y = edge(p, v1, v2); weight.z = edge(p, v2, v0); return (weight); }
C
#include "algorithm.h" static int get_head_index(head_t graph[], int size, char *input_marker) { for(int i = 0; i < size; i++) { if(!strcmp(graph[i].node.marker, input_marker)) { return i; } } return -1; } static int set_elem_path_value(double head_value, elem_t *elem) { double value = head_value * elem->denom_cost; value = elem->fee_type ? value - elem->fee : value - value * elem->fee / 100; if(value > elem->node->path_value) { elem->node->path_value = value; return 1; } return 0; } static void set_head_path_values(head_t *head, char *input_marker) { elem_t *neighbor = head->next; if(head->node.path_value == 0.0) { return; } while(neighbor != NULL) { if(!strcmp(neighbor->node->marker, input_marker) || is_marker_in_stack(head->node.path, neighbor->node->marker)) { neighbor = neighbor->next; } else { if(set_elem_path_value(head->node.path_value, neighbor)) { change_stack(&(neighbor->node->path), head->node.path); put(&(neighbor->node->path), head->node.marker); } neighbor = neighbor->next; } } } static int set_head_path_values_arbitrage(head_t *head, char *input_marker) { elem_t *neighbor = head->next; if(head->node.path_value == 0.0) { return 0; } while(neighbor != NULL) { if(set_elem_path_value(head->node.path_value, neighbor)) { change_stack(&(neighbor->node->path), head->node.path); put(&(neighbor->node->path), head->node.marker); if(!strcmp(neighbor->node->marker, input_marker)) { return 1; } } neighbor = neighbor->next; } return 0; } result_t get_path_value(head_t graph[], int size, input_t input) { result_t result; int input_index = get_head_index(graph, size, input.input_marker); int output_index = get_head_index(graph, size, input.output_marker); head_t *input_head = &graph[input_index]; head_t *output_head = &graph[output_index]; input_head->node.path_value = input.input_value; for(int i = 0; i < size - 2; i++) { set_head_path_values(input_head, input.input_marker); for(int i = 0; i < input_index; i++) { set_head_path_values(&graph[i], input.input_marker); } for(int i = input_index + 1; i < size; i++) { set_head_path_values(&graph[i], input.input_marker); } } put(&(graph[output_index].node.path), input.output_marker); result.input_value = input.input_value; result.path_value = output_head->node.path_value; result.path = output_head->node.path; return result; } static double get_arbitrage_result(head_t graph[], int size, input_t input) { int input_index = get_head_index(graph, size, input.input_marker); head_t *input_head = &graph[input_index]; input_head->node.path_value = input.input_value; for(int i = 0; i < size - 1; i++) { set_head_path_values_arbitrage(input_head, input.input_marker); for(int i = 0; i < input_index; i++) { if(set_head_path_values_arbitrage(&graph[i], input.input_marker)) { put(&(input_head->node.path), input.input_marker); return input_head->node.path_value; } } for(int i = input_index + 1; i < size; i++) { if(set_head_path_values_arbitrage(&graph[i], input.input_marker)) { put(&(input_head->node.path), input.input_marker); return input_head->node.path_value; } } } put(&(input_head->node.path), input.input_marker); return input_head->node.path_value;; } void set_path_values_arbitrage(head_t graph[], int size, double input_value, result_t arbitrage_result[]) { input_t input; input.input_value = input_value; for(int i = 0; i < size; i++) { input.input_marker = graph[i].node.marker; arbitrage_result[i].input_value = input_value; init(&(arbitrage_result[i].path)); arbitrage_result[i].path_value = get_arbitrage_result(graph, size, input); change_stack(&(arbitrage_result[i].path), graph[i].node.path); reset_graph(graph, size); } } void print_result(result_t result) { printf("Starting value: %f\n", result.input_value); printf("Most optimal path: "); print_stack(result.path); printf("Path value: %f\n", result.path_value); } void free_results(result_t results[], int size) { for(int i = 0; i < size; i++) { free_stack(&(results[i].path)); } }
C
#include <stdio.h> #include <stdlib.h> #include <assert.h> #include <sys/time.h> #include <time.h> #include <math.h> const int FACTORS = 30; int numberMovies = 0; int numberUsers = 0; #define LEARNING_RATE (0.00125) #define REGULARIZATION_PARAMETER (0.005) #define BLOCKSIZE (256) #define LEARNING_DATA_SIZE (99072112) #define ERROR_THRESHOLD (0.145) typedef struct rating { int rating; int userIndex; int movieIndex; } rating_t; rating_t* h_learningData; double* h_userFactors; double* h_movieFactors; double get_walltime() { struct timeval tp; gettimeofday(&tp, NULL); return (double)(tp.tv_sec + tp.tv_usec*1e-6); } void CreateLearningDataAndFactors() { h_learningData = (rating_t*)malloc(sizeof(rating_t) * LEARNING_DATA_SIZE); assert(NULL != h_learningData); int indexLearningData = 0; FILE* netflixDataFile = fopen("netflix.dat", "r"); char buffer[60]; while (indexLearningData < LEARNING_DATA_SIZE && fgets(buffer, 60, netflixDataFile) != NULL) { assert(indexLearningData < LEARNING_DATA_SIZE); char* startPointer = buffer; char* endPointer = buffer; h_learningData[indexLearningData].userIndex = ((int)strtol(startPointer, &endPointer, 10)) - 1; startPointer = endPointer; h_learningData[indexLearningData].movieIndex = ((int)strtol(startPointer, &endPointer, 10)) - 1; startPointer = endPointer; h_learningData[indexLearningData].rating = ((int)strtol(startPointer, &endPointer, 10)); if (h_learningData[indexLearningData].userIndex > numberUsers) numberUsers = h_learningData[indexLearningData].userIndex; if (h_learningData[indexLearningData].movieIndex > numberMovies) numberMovies = h_learningData[indexLearningData].movieIndex; ++indexLearningData; } ++numberMovies; ++numberUsers; printf("Allocating memory for user and movie factors\n"); h_userFactors = (double*)malloc(sizeof(double) * FACTORS * numberUsers); assert(NULL != h_userFactors); h_movieFactors = (double*)malloc(sizeof(double) * FACTORS * numberMovies); assert(NULL != h_movieFactors); #pragma omp parallel for for (int n = 0; n < (FACTORS * numberUsers); ++n) h_userFactors[n] = 1.0; int index = 0; int currentMovieIndex = 0; size_t sumRating = 0; size_t timesAdded = 0; while (index < LEARNING_DATA_SIZE) { if (h_learningData[index].movieIndex != currentMovieIndex) { for (int f = 0; f < FACTORS; ++f) h_movieFactors[currentMovieIndex * FACTORS + f] = (sumRating / ((double)timesAdded)) / ((double)FACTORS); currentMovieIndex = h_learningData[index].movieIndex; sumRating = 0; timesAdded = 0; continue; } sumRating += h_learningData[index].rating; ++timesAdded; ++index; } for (int f = 0; f < FACTORS; ++f) h_movieFactors[currentMovieIndex * FACTORS + f] = (sumRating / ((double)timesAdded)) / ((double)FACTORS); printf("Randomizing the learning data\n"); srand(time(NULL)); for (int n = 0; n < (LEARNING_DATA_SIZE / numberMovies); ++n) { rating_t tempRatingBlock; size_t m = ((rand() % numberMovies) * (LEARNING_DATA_SIZE / numberMovies)) + (rand() % (LEARNING_DATA_SIZE / numberMovies)); assert(m < LEARNING_DATA_SIZE); tempRatingBlock.rating = h_learningData[n].rating; tempRatingBlock.userIndex = h_learningData[n].userIndex; tempRatingBlock.movieIndex = h_learningData[n].movieIndex; h_learningData[n].rating = h_learningData[m].rating; h_learningData[n].userIndex = h_learningData[m].userIndex; h_learningData[n].movieIndex = h_learningData[m].movieIndex; h_learningData[m].rating = tempRatingBlock.rating; h_learningData[m].userIndex = tempRatingBlock.userIndex; h_learningData[m].movieIndex = tempRatingBlock.movieIndex; } } double DotProduct(const double* vectorA, const double* vectorB, const int length) { double dotProduct = 0.0; for (int n = 0; n < length; ++n) dotProduct += vectorA[n] * vectorB[n]; return dotProduct; } void PrintPredictedData() { int indexQueryData = 0; FILE* netflixQueryFile = fopen("netflix_query", "r"); char buffer[60]; while (fgets(buffer, 60, netflixQueryFile) != NULL) { char* startPointer = buffer; char* endPointer = buffer; int userIndex = ((int)strtol(startPointer, &endPointer, 10)); startPointer = endPointer; int movieIndex = ((int)strtol(startPointer, &endPointer, 10)); startPointer = endPointer; assert(userIndex < numberUsers); assert(movieIndex < numberMovies); double predictedRating = DotProduct(&h_movieFactors[movieIndex * FACTORS], &h_userFactors[userIndex * FACTORS], FACTORS); printf("User#:%d\tMovie#:%d\tPredicted Rating = %lf\n", userIndex, movieIndex, predictedRating); ++indexQueryData; } } int main(int argc, char** argv) { printf("Starting Netflix Recommender System Algorithm with Stochastic Gradient Descent\n"); printf("Creating Learning Data\n"); CreateLearningDataAndFactors(); double* h_sumErrorSquared = (double*)malloc(sizeof(double)); *h_sumErrorSquared = 0.0; printf("Starting Algorith now\n"); fflush(stdout); unsigned int iterations = 0; double startTime = get_walltime(); do { for (int indexKnownData = 0; indexKnownData < LEARNING_DATA_SIZE; ++indexKnownData) { if (indexKnownData == 0) *h_sumErrorSquared = 0.0; if (indexKnownData < LEARNING_DATA_SIZE) { int userIndex = h_learningData[indexKnownData].userIndex; int movieIndex = h_learningData[indexKnownData].movieIndex; int rating = h_learningData[indexKnownData].rating; double errorTerm = rating - DotProduct(&h_movieFactors[movieIndex * FACTORS], &h_userFactors[userIndex * FACTORS], FACTORS); for (int f = 0; f < FACTORS; ++f) { h_movieFactors[movieIndex * FACTORS + f] += LEARNING_RATE * (errorTerm * h_userFactors[userIndex * FACTORS + f] - REGULARIZATION_PARAMETER * h_movieFactors[movieIndex * FACTORS + f]); } for (int f = 0; f < FACTORS; ++f) { h_userFactors[userIndex * FACTORS + f] += LEARNING_RATE * (errorTerm * h_movieFactors[movieIndex * FACTORS + f] - REGULARIZATION_PARAMETER * h_userFactors[userIndex * FACTORS + f]); } } } for (int indexKnownData = 0; indexKnownData < LEARNING_DATA_SIZE; ++indexKnownData) { int userIndex = h_learningData[indexKnownData].userIndex; int movieIndex = h_learningData[indexKnownData].movieIndex; int rating = h_learningData[indexKnownData].rating; double errorTerm2 = rating - DotProduct(&h_movieFactors[movieIndex * FACTORS], &h_userFactors[userIndex * FACTORS], FACTORS); *h_sumErrorSquared += errorTerm2 * errorTerm2; } printf("\th_sumErrorSquared = %lf, (1/N(h_sumErrorSquared))^(1/2) = %lf\n", *h_sumErrorSquared, sqrt((1.0/LEARNING_DATA_SIZE**h_sumErrorSquared))); ++iterations; } while (iterations < 10);//(*h_sumErrorSquared > LEARNING_DATA_SIZE * (ERROR_THRESHOLD * ERROR_THRESHOLD)); double endTime = get_walltime(); printf("Performed %u iterations\n", iterations); printf("Total time = %lf\n", endTime - startTime); PrintPredictedData(); free(h_sumErrorSquared); free(h_userFactors); free(h_movieFactors); free(h_learningData); return 0; }
C
//numerical recursion of square root #include <stdio.h> #include <math.h> double mysqrt(double a, double x0) { double x1;// local variable x1=(x0+a/x0)/2.0; if (fabs(x1-x0)>0.00001) return mysqrt(a,x1); else return x1; } main() { double a;//global variable printf("please enter a: \n"); scanf("%lf",&a); printf("the sqrt of %f = %f\n",a,mysqrt(a,1.0)); }
C
#include <string.h> #include <stdio.h> #include <stdlib.h> #include <assert.h> #include "env.h" #include "../log.h" char* homeDirBuffer; // 1 - true // 0 - false int startsWith(char* prefix, char* text) { unsigned prefix_length = strlen(prefix); unsigned text_length = strlen(text); return (text_length < prefix_length) ? 0 : (0 == strncmp(prefix, text, prefix_length)); } void setHomeDir(char** envp) { char * prefix = "HOME="; while (*envp) { if (startsWith(prefix, *envp)) { char *tmp = *envp + strlen(prefix); int tmp_len = strlen(tmp); homeDirBuffer = malloc(tmp_len + 1); strncpy(homeDirBuffer, tmp, tmp_len); homeDirBuffer[tmp_len] = '\0'; return; } char* tmp = *envp++; (void) tmp; } } char* replaceTildeWithHomeDir(char* buffer) { char* text = NULL; char* ptr_to_tilde = strchr(buffer, '~'); // The first and last tilde should be the same char. assert(strchr(buffer, '~') == strrchr(buffer, '~')); if (NULL == ptr_to_tilde) { text = malloc(strlen(buffer) + 1); strncpy(text, buffer, strlen(buffer) + 1); text[strlen(buffer) + 1] = '\0'; return text; } else { int text_len = strlen(buffer) - 1 + strlen(homeDirBuffer); SLOGD("strlen(homeDirBuffer) = %u", (unsigned)strlen(homeDirBuffer)); SLOGD("text_len = %2.d", text_len); text = malloc(text_len + 1); for (int i = 0, j = 0; j < text_len + 1; ++i, ++j) { SLOGD("i=%2.d, j=%2.d text=%s",i,j,text); if ((buffer + i) == ptr_to_tilde) { for (unsigned k = 0; k < strlen(homeDirBuffer); ++k, ++j) { // *(text + j) = *(buffer + k); text[j] = homeDirBuffer[k]; SLOGD("i=%2.d, j=%2.d, homeDirBuffer[k]=%c, text[j] = %c, text=%s",i, j, homeDirBuffer[k], text[j], text); } --j; } else { // *(text + j) = *(buffer + i); text[j] = buffer[i]; SLOGD("text[j] = %c", text[j]); } } text[text_len + 1] = '\0'; return text; } }
C
// SHARED MEMORY - WRITE /* Another mechanism of Interprocess Communication. This can be done between any two processes, That is they need not be related. By default a page of memory (4kbytes) would be allocated for Shared memory from any process. There are three steps: 1. Initialization 2. Attach 3. Detach. */ #include <sys/ipc.h> #include <sys/shm.h> #include <sys/types.h> #include <stdio.h> #include <string.h> #include <unistd.h> int main () { int r, shmid; char *p, *mem, c; key_t key = 123; // step 1 - initialization of shared memory /* int shmget(key_t key, size_t size, int shmflg); shmget() returns the identifier of the System V shared memory segment associated with the value of the argument key. A new shared memory segment, with size equal to the value of size is created*/ shmid = shmget (key, 26, IPC_CREAT|0666 ); if (shmid < 0) { printf ("The Creation has gone as a failure \n"); } printf ("We are getting the shared memory created with id %d\n", shmid); /* step 2 - attach to shared memory void *shmat(int shmid, const void *shmaddr, int shmflg); shmat() attaches the System V shared memory segment identified by shmid to the address space of the calling process. If shmaddr is NULL, the system chooses a suitable (unused) address at which to attach the segment */ mem = shmat (shmid, NULL, 0); //On success shmat() returns the address of the attached shared memory segment if (mem == NULL) { printf ("Attachment failure\n "); return 0; } /* write some content to memory */ p = mem; for (c = 'a'; c <= 'z'; c++) { *p++ = c; } /* Wait until the other process changes the first character of our memory to '*', indicating that it has read what we put there. */ printf("\n Waiting for reader to read the string and change the first character to * \n"); while ( *mem != '*') sleep(1); printf("\n Modified string is \n \n"); for (p = mem; *p != '\0'; p++) putchar(*p); putchar('\n'); /* step 4 - detach from shared memory int shmdt(const void *shmaddr); int shmctl(int shmid, int cmd, struct shmid_ds *buf); */ r = shmdt (mem); if (r < 0) { printf ("Couldn't detach\n"); return 0; } r = shmctl (shmid, IPC_RMID, NULL); /* if shhmdt and shmctl are commented , reader can access the shared memory any time it is executed.. */ return 0; }
C
// Filter and function pointers // #include <stdlib.h> #include <string.h> #include "filter.h" void filter(void *base, size_t msize, size_t nmemb, void **out_data, size_t *out_nmemb, predicate_t p){ size_t i; *out_data = (void *) malloc(msize*nmemb); *out_nmemb = 0; for(i=0; i<nmemb; i++){ if (p(base+i*msize)){ memcpy(*out_data + *out_nmemb*msize, base+i*msize, msize); *out_nmemb = *out_nmemb + 1; } } }
C
#include <stdio.h> int foo(){ //this is my homework :) return 3; } int main(){ for (int x = 0; x < 10;x++){ printf("hi\n"); } return 0; }
C
#define N 100 //缓冲区中的槽数目 typedef int semaphore; //信号量是一种整形数据 semaphore mutex = 1; semaphore empty = N; semaphore full = 0; void producer(void){ int item; while(1){ item = produce_item(); } }
C
/* ** my_strcpy for in /home/daniel_b/Piscine_C_J06 ** ** Made by Erwan DANIEL ** Login <daniel_b@epitech.net> ** ** Started on Mon Oct 6 11:37:33 2014 Erwan DANIEL ** Last update Sun Feb 1 19:38:13 2015 DANIEL Erwan */ #include <stdlib.h> char *my_strcpy(char *src) { char *new; int size; size = 0; while (src[size++]); if (!(new = malloc(sizeof (char) * size))) return (0); while (size) new[--size] = src[size]; return (new); }
C
/** baekjoon Oct.28.2016 for문 구구단 */ #include <stdio.h> int main() { int i, n; scanf("%d", &n); for(i=1;i<=9;i++) printf("%d * %d = %d\n", n, i, n*i); return 0; }
C
#include "grt_debug.h" /** * grt_debug_print_skb() - print a socket buffer * @param label : The label to be printed before the skb data * @param skb : The socket buffer. */ void grt_debug_print_skb(char * label, struct sk_buff * skb) { int i; GRT_PRINT_DEBUG("%s\n", label); for(i = 0; i < skb->len; i++){ GRT_PRINT_DEBUG("%02x ", skb->data[i] & 0x0FF); if(((i + 1) % 16) == 0){ GRT_PRINT_DEBUG("\n"); } } GRT_PRINT_DEBUG("\n"); } /** * grt_info_print_bf() - print a grt_buf as an info message * @param label : The label to be printed before the skb data * @param bf : The buf to be printed */ void grt_info_print_bf(char * label, struct grt_buf *bf) { int i; GRT_PRINT_INFO("%s\n", label); GRT_PRINT_INFO("needs ack : %s\n", ((bf->needs_ack == 0) ? "NO" : "YES")); GRT_PRINT_INFO("rates & tries : "); for(i = 0; i < IEEE80211_TX_MAX_RATES; i++){ GRT_PRINT_INFO("(0x%x, %d) ", bf->rates[i], bf->tries[i]); } GRT_PRINT_INFO("\n"); for(i = 0; i < bf->skb->len; i++){ GRT_PRINT_INFO("%02x ", bf->skb->data[i] & 0x0FF); if(((i + 1) % 16) == 0){ GRT_PRINT_INFO("\n"); } } GRT_PRINT_INFO("\n"); }
C
/*************************************************************************** * Laser Display : Display Subroutine File : display9.c * * * * Displays each file in the display list in turn. * * If a file cannot be opened, it is simply skipped over. * * * * R S Barker 6/2/90 8/4/90 * ***************************************************************************/ #include "header.h" #include <graph.h> extern F_HEADER dlist[MAXFILES]; extern char ctrlwd; void display(listlength) int listlength; /* Length of display list */ { int count; time_t tstart,tnow; FILE *finp; char tempname[FPATHLNG]; time(&tstart); ctrlwd |= NOBLANK; /* Ensure no blanking */ for(count=0;count<listlength;count++) /* Repeat for each entry on display list */ { sprintf(tempname,"%s%s",TMPDIR,dlist[count].name); /* Concatenate path and filename */ if((finp=fopen(tempname,RACCESS))!=(FILE *)NULL) { _clearscreen(0); printf("outputting file no. %d : %s\n",count,dlist[count].name); output_data(finp); /* Output bitmap via printer port */ fclose(finp); screen_display(tempname); /* Display on computer screen */ time(&tnow); while((tnow-tstart)<DISPSECS) /* Wait for duration of message */ time(&tnow); tstart=tnow; } } return; }
C
#include <stdio.h> #define MAX 5 void ConverToUpper(char* str) { for (int i = 0; ; i++) { if (*(str + i) == NULL) break; if (*(str + i) >= 'a' && *(str + i) <= 'z') *(str + i) -= 32; } } void Bigger(int* Max, int* Min) { if (*Max < *Min) *Max = *Min; } void Gauss(int* Num, int * Sum) { for (int i = 1; i <= *Num; i++) { *Sum = *Sum + i; } } void DoAlignment(int Alignment[]) { int temp; for (int i = 0; i < MAX - 1; i++) { for (int j = i; j < MAX; j++) { if (Alignment[i] >= Alignment[j]) { temp = Alignment[i]; Alignment[i] = Alignment[j]; Alignment[j] = temp; } } } } void main() { char problem_one[50]; int problem_two_max, problem_two_min; int problem_three; int sum = 0; int Alignment[MAX]; printf("1. ڿ Էϼ : "); gets(problem_one); printf("Լ ȣ = %s\n", problem_one); ConverToUpper(problem_one); printf("Լ ȣ = %s\n\n", problem_one); // 1 printf("2. Էϼ : "); scanf("%d%d", &problem_two_max, &problem_two_min); printf("%d %d ū ", problem_two_max, problem_two_min); Bigger(&problem_two_max, &problem_two_min); printf("%d\n\n", problem_two_max); // 2 printf("3. Էϼ : "); scanf("%d", &problem_three); printf("1 ~ %d : ", problem_three); Gauss(&problem_three, &sum); printf("%d\n\n", sum); // 3 printf("4. \n"); for (int i = 0; i < MAX; i++) { printf("[%d]° Է : ", i + 1); scanf("%d", &Alignment[i]); } printf(" : %d %d %d %d %d\n", Alignment[0], Alignment[1], Alignment[2], Alignment[3], Alignment[4]); DoAlignment(Alignment); printf(" : %d %d %d %d %d\n", Alignment[0], Alignment[1], Alignment[2], Alignment[3], Alignment[4]); getch(); }
C
#include <stdio.h> #include <stdlib.h> #include <ctype.h> #include <math.h> int main(){ char c; do{ system("cls"); printf("\n"); printf("======\n\n"); printf("\n\nDesea efectuar una nueva operacion (s/n)? "); fflush(stdin); c=toupper(getchar()); }while (c!='N'); return 0; }
C
#include <stdio.h> #include <string.h> #include <stdlib.h> int main(int argc, char *argv[]) { FILE *file; int i,j,k; if(argc < 3) { nothing:; return 0; } i=0; next:; while(argv[2][i] != ':' && argv[2][i] != 0)i++; if(argv[2][i] == 0) { return 0; } k=i; i++; if(argv[2][i] == ' ' && argv[2][i+1] == 'E' && argv[2][i+2] == 'L' && argv[2][i+3] == 'F' && argv[2][i+4] == ' ') { while(argv[2][k] != '/' && k>0)k--; if(k<=3)return 0; j=k-3; sprintf(&argv[2][j],"include"); while(j>0 && argv[2][j-1] != 10) { j--; } if(argv[2][i+5] == '3' && argv[2][i+6] == '2') { if(argv[1][0] == '1') { printf("-I%s",&argv[2][j]); return; } } else { if(argv[1][0] == '2') { printf("-I%s",&argv[2][j]); return; } } } goto next; }
C
#include<stdio.h> #include<math.h> void main() { int j,i,num,count=0, a[1000], x, y; printf("\n"); scanf("%d", &num); for(i=0;i<num;i++) { scanf("%d", &a[i]); } for(i=0;i<num;i++) { for(j=i+1;j<num;j++) { x=pow(a[i], a[j]); y=pow(a[j], a[i]); if(x>y) { count++; } } } printf("\n%d", count); }
C
#include <stdio.h> /*Essa função conta quantos digitos um string tem*/ int tamanho(char string[]) { int cont=0; while(string[cont]!='\0') { cont++; } return cont; } /*Compara compara string*/ int compstring(char s1[], char s2[], int m , int n) { int saida=0; while( (s1[m-1]==s2[n-1]) && (n>0) ) { if(n==1) { saida=1; } m--; n--; } return saida; } int main(void) { int i, n ; char a[100] , b[100]; /*Entrada de dado*/ scanf("%d", &n); for(i=0;i<n;i++) { scanf("%s", a); scanf("%s", b); if( compstring(a,b,tamanho(a),tamanho(b))==1 ) { printf("Encaixa\n"); } else { printf("Nao encaixa\n"); } } return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <sys/file.h> #include <sys/stat.h> #include <unistd.h> #include <fcntl.h> #include <sys/types.h> #include <dirent.h> #include "apue.h" #include <sys/wait.h> void set(){ printf("Processo corrente: %d -> Generato da: %d\n",getpid(),getppid()); } int main(int argc, char *argv[]){ if(argc == 1){ printf("Dare un numero in input\n"); exit(1); } int i; pid_t childpid; printf("START %d\n",getpid()); for(i=0;i<atoi(argv[1]);i++){ childpid= fork(); if(!childpid){ set(); exit(3); } } while(waitpid(-1,NULL,0)>0){ // attende che finiscano i processi printf("\n ASPETTO FINISCA..."); } printf("\n %d-> fine processo %d\n",i,getpid()); exit(0); }
C
/* CITS2002 Project 2 2019 Name(s): Frinze Lapuz, Thye Shan Ng Student number(s): 22711649, 22727425 */ #include "sifs-internal.h" #include "helper.h" // add a copy of a new file to an existing volume int SIFS_writefile(const char *volumename, const char *pathname, void *data, size_t nbytes) { FILE *fp = getFileReaderPointer(volumename); //PRE-PROCESSING ERROR CHECK - will return EXIT_FAILURE IN THE SCOPE OF THE API CHECK_VOLUME_EXIST CHECK_VALID_VOLUME SIFS_BLOCKID containerId = getDirBlockIdBeforePathEnds(fp, pathname); char *tail = getPathTail(pathname); if (writeFileBlock(fp, containerId, tail, data, nbytes)) { return EXIT_FAILURE; } return EXIT_SUCCESS; }
C
/* * main_imgProcessingLib.h * * Created on: Oct 28, 2016 * Author: gnouchnam */ #ifndef MAIN_IMGPROCESSINGLIB_H_ #define MAIN_IMGPROCESSINGLIB_H_ #include "common.h" #include "dirent.h" #include "Model/DataStructure.h" // Variables, structures and classes #if STATIC_IMAGE #define WAIT_TIME 0//2000 DIR *dir; struct dirent *ent; #elif VIDEO || CAMERA #define WAIT_TIME 1 VideoCapture capture; #endif // Function headers void init(int argc, char** args); void onExit(); // Predefined Functions void init(int argc, char** args){ #if STATIC_IMAGE dir = opendir (DATASET_DIR); assert(dir && "Cannot open image directory"); #elif CAMERA int cameraId = 0; if(argc > 1) cameraId = atoi(args[1]); capture = VideoCapture(cameraId); assert(capture.isOpened() && "Cannot open the camera"); #elif VIDEO capture = VideoCapture(VIDEO_FILE); assert(capture.isOpened() && "Cannot open video file"); #endif } void onExit(){ #if STATIC_IMAGE if(dir) closedir (dir); #endif } #if STATIC_IMAGE Mat readImage(string imgName) #elif VIDEO || CAMERA Mat readImage(VideoCapture &cap) #endif { Mat input; #if STATIC_IMAGE string imgPath = DATASET_DIR + imgName; cout<<"\nReading Img:"<<imgName<<endl; input = imread(imgPath); #elif VIDEO || CAMERA cap >> input; #endif if(input.empty()) perror(""); else{ // int newRows = COLS/(input.cols*1.0/input.rows); // resize(input, input, Size(COLS,newRows)); resize(input, input, Size(input.cols/4*3,input.rows/4*3)); } return input; } #endif /* MAIN_IMGPROCESSINGLIB_H_ */
C
/* ----------------------------------------------------------------------- * smithy Tescase * ----------------------------------------------------------------------- */ #include "dominion.h" #include "dominion_helpers.h" #include <string.h> #include <stdio.h> #include <assert.h> #include "rngs.h" // set NOISY_TEST to 0 to remove printfs from output #define NOISY_TEST 1 int main() { int results =0; int player=0; int beforeCards,afterCards=0; int temphand[MAX_HAND]; int provinces,eachCard,supplyCount =0; int i; int seed = 1000; int numPlayer = 2; //int maxBonus = 10; int p, r, handCount; //int bonus; int k[10] = {adventurer, council_room, feast, gardens, mine , remodel, smithy, village, baron, great_hall}; struct gameState G; int maxHandCount = 5; printf ("TESTING Smithy():\n"); memset(&G, 23, sizeof(struct gameState)); // clear the game state r = initializeGame(numPlayer, k, seed, &G); player = whoseTurn(&G); printf("player %d",player); beforeCards = G.deckCount[player]; results = smithi(0,&G,player,0,temphand,0,0,0,0); afterCards = G.deckCount[player]; printf("beforeCard count: %d, afterCard count: %d", beforeCards, afterCards); if((beforeCards +3) == afterCards) { printf(" PASSED! \n"); } else { printf("FAILED \n"); } printf("checking return value, should return 0 for passing: "); if(results == 0) printf("PASSED \n"); else printf("FAILED \n"); return 0; }
C
#include <stdio.h> int main(){ //gets/puts = for chars/strings char b[100]; printf("input with gets, B = "); gets(b); printf("\noutput with puts, B = "); puts(b); int a; //scanf = for all data types printf("Input with scanf, A = "); scanf("%d", &a); printf("Given input with scanf = %d\n", a); }
C
//2) Write a Program to remove a Specific line from the given text file. #include<stdio.h> #include<stdlib.h> #include<string.h> main(int a1,char **v) { int i,c=0,l=1,c1=0,b,j,n; char ch,**p,a[100]; FILE *f; n=atoi(v[2]); if(a1!=3) { printf("Usage:: ./a.out F_name select_line\n"); return; } if((f=fopen(v[1],"r"))==NULL) { printf("%s is not present.\n",v[1]); return; } while((ch=fgetc(f))!=EOF) { c++;c1++; if(ch=='\n') { l++; if(b<c1)b=c1; c1=0; } } printf("CHAR::%d LINE::%d MAX_CHAR::%d\n",c,l,b); p=malloc(sizeof(int *) * l); for(i=0;i<l;i++) p[i]=malloc(b+1); rewind(f); i=0; while((fgets(a,100,f))!=NULL) { if(i!=n-1) strcpy(p[i++],a); else i++; } fclose(f); f=fopen(v[1],"w"); for(i=0;i<l-1;fputs(p[i++],f)); }
C
#include<stdio.h> /* PRE DEFINED HEADER FILES */ #include<conio.h> #include<string.h> #include<stdlib.h> /*MINI PROJECT : SUBMITED BY : Name: Sunil Joshi and Shubham Gupta Roll No: 2007563 and 2007562 Section:CSE MY MACHINE NAME IS : "MONTEUR" "MONTEUR" is a german word for "ASSEMBLER"; Note: Input file has to be in the same format ; */ int main() // Main function(not returning any value) { char a[10],ad[10],label[10],opcode[10],operand[10],symbol[10],ch,fnm[15],ab[15]; // Initializing character value. int st,diff,diff1,i,address,address1,add,len,alen,finaddr,prevaddr,j=0; char mnemonic[15][15]={"LDA","STA","LDCH","STCH","ADD","SUB","MUL","DIV","J","JSUB"}; //Initializing mnemonics. int locctr=0x0,start,l,c=0x0,k=0,bol=0; // Initalizing Location counter to zero for further use. char code[15][15]={"00","0C","50","54","28","29","3A","3B","3E","3F"}; // Defining object code for differnt mnemonics. FILE *fp1,*fp2,*fp3,*fp4; // Making File pointer to operate different files. printf("ENTER THE PROGRAM FILE NAME : \n"); scanf("%s",&fnm); fp1 = fopen("MEDIATOR.txt","w"); // Opening MEDIATOR.txt in write mode. fp3 = fopen(fnm,"r"); // Opening fnm in read mode. printf("\n\n\t\t\tINPUT FILE:\n\n"); ch=fgetc(fp3); while(ch!=EOF) { printf("%c",ch); // Printing Character. ch=fgetc(fp3); } rewind(fp3); printf("\n\nSTART OF PASS 1 "); fp2=fopen("SYMTAB.txt","w"); //Opening SYMTAB.txt in write mode. fscanf(fp3,"%s%s%s%X",label,opcode,operand,&address); if(strcmp(operand,"START")==0) { start=address; locctr=start; prevaddr=locctr; c=address; fprintf(fp1,"%s\t%s\t%X\n",opcode,operand,address); // printing opcode and ites operand with address. } else locctr=0x0; fscanf(fp3,"%s%s%s",label,opcode,operand); while(strcmp(opcode,"END")!=0) { if(strcmp(label,"**")!=0) fprintf(fp2,"%s\t%X\n",label,locctr); if(strcmp(opcode,"BYTE")==0) { fprintf(fp1,"%X\t%s\t%s\t%s\t\n",address,label,opcode,operand); len=strlen(operand); address+=len-3; locctr+=len-3; } else if(strcmp(opcode,"RESB")==0) { fprintf(fp1,"%X\t%s\t%s\t%s\n",address,label,opcode,operand); address+=(atoi(operand)); locctr+=(atoi(operand)); } else if (strcmp(opcode,"RESW")==0) { fprintf(fp1,"%X\t%s\t%s\t%s\n",address,label,opcode,operand); address+=(3*(atoi(operand))); locctr+=(3*(atoi(operand))); } else { fprintf(fp1,"%X\t%s\t%s\t%s\n",address,label,opcode,operand); address+=3; locctr+=3; } fscanf(fp3,"%s%s%s",label,opcode,operand); } fprintf(fp1,"%X\t%s\t%s\t%s\n",address,label,opcode,operand); l=address; fclose(fp1); // Closing file fp1. fclose(fp2); // Closing file fp2. fclose(fp3); // Closing file fp3. printf("\n\nINTERMEDIATE FILE : AFTER ADRESSING \n\n\t"); fp1=fopen("MEDIATOR.txt","r"); // Reading from MEDIATOR.TXT. ch=fgetc(fp1); while(ch!=EOF) { printf("%c",ch); ch=fgetc(fp1); } fclose(fp1); printf("\n\nTHE LENGTH OF THE PROGRAM IS : %X",l-c); //ADDRESSING DONE IN MEDIATOR FILE; //AFTER ADDRESING : printf("\n\nSYMBOL TABLE CREATED"); printf("\n\n\t\t\tSYMBOL TABLE :\n\n"); fp2=fopen("SYMTAB.txt","r"); ch=fgetc(fp2); while(ch!=EOF) { printf("%c",ch); ch=fgetc(fp2); } fclose(fp2); printf("\n\nEND OF PASS 1"); printf("\n\nSTART OF PASS 2 "); fp1 = fopen("OUTPUT.txt","w"); // Writing to output.txt fp2 = fopen("SYMTAB.txt","r"); // Reading from SYMTAB.txt fp3 = fopen("abc.txt","r"); // Reading from abc.txt. fp4 = fopen("OBJCODE.txt","w"); //Writing to OBJCODE.txt/ fscanf(fp3,"%s%s%s",label,opcode,operand); while(strcmp(opcode,"END")!=0) { prevaddr=address; fscanf(fp3,"%X%s%s%s",&address,label,opcode,operand); } finaddr=address; fclose(fp3); fp3=fopen("MEDIATOR.txt","r"); fscanf(fp3,"%s%s%s",label,opcode,operand); if(strcmp(opcode,"START")==0) { fprintf(fp1,"\t%s\t%s\t%s\n",label,opcode,operand); fprintf(fp4,"H^%s^00%s^00%X\n",label,operand,finaddr); fscanf(fp3,"%X%s%s%s",&address,label,opcode,operand); st=address; diff=prevaddr-st; fprintf(fp4,"T^00%X^%X",address,diff); } while(strcmp(opcode,"END")!=0) { if(strcmp(opcode,"BYTE")==0) { fprintf(fp1,"%X\t%s\t%s\t%s\t",address,label,opcode,operand); len=strlen(operand); alen=len-3; fprintf(fp4,"^"); for(i=2;i<(alen+2);i++) { itoa(operand[i],ad,16); fprintf(fp1,"%s",ad); fprintf(fp4,"%s",ad); } fprintf(fp1,"\n"); } else if(strcmp(opcode,"WORD")==0) { len=strlen(operand); itoa(atoi(operand),a,10); fprintf(fp1,"%X\t%s\t%s\t%s\t00000%s\n",address,label,opcode,operand,a); fprintf(fp4,"^00000%s",a); } else if((strcmp(opcode,"RESB")==0)||(strcmp(opcode,"RESW")==0)) fprintf(fp1,"%X\t%s\t%s\t%s\n",address,label,opcode,operand); else { while(strcmp(opcode,mnemonic[j])!=0) j++; if(strcmp(operand,"COPY")==0) fprintf(fp1,"%X\t%s\t%s\t%s\t%s0000\n",address,label,opcode,operand,code[j]); else { rewind(fp2); fscanf(fp2,"%s%X",symbol,&add); while(strcmp(operand,symbol)!=0) fscanf(fp2,"%s%X",symbol,&add); fprintf(fp1,"%X\t%s\t%s\t%s\t%s%X\n",address,label,opcode,operand,code[j],add); fprintf(fp4,"^%s%X",code[j],add); } } fscanf(fp3,"%X%s%s%s",&address,label,opcode,operand); } fprintf(fp1,"%X\t%s\t%s\t%s\n",address,label,opcode,operand); fprintf(fp4,"\nE^00%X",st); printf("\n\n\tINTERMEDIATE FILE IS COVERTED INTO OBJECT CODE"); printf("\n\nEND OF PASS 2"); fclose(fp1); fclose(fp2); fclose(fp3); fclose(fp4); printf("\n\n\t\t\tOUTPUT FILE :\n\n"); fp1=fopen("OUTPUT.txt","r"); ch=fgetc(fp1); while(ch!=EOF) { printf("%c",ch); ch=fgetc(fp1); } printf("\n\nCONTENTS OF OBJECT CODE FILE :\n\n"); fp4=fopen("OBJCODE.txt","r"); ch=fgetc(fp4); while(ch!=EOF) { printf("%c",ch); ch=fgetc(fp4); } fclose(fp1); fclose(fp3); fclose(fp4); getch(); // For holding screen. return(0); }
C
/* * sieve.c * * Created on: Oct 6, 2013 * Author: sam */ #include <stdio.h> #include <stdlib.h> #include <math.h> int main(){ int n; int *prime; int i, k; printf("To what number would you like to see prime numbers to? \n"); scanf("%d", &n); prime = (int*)malloc( (n+1) * sizeof(int)); for ( i = 2; i < n; i++ ){ //Fills array but skips numbers 0 and 1 becasue they are special. prime[i] = i; } for ( i = 2; i <= sqrt(n); i++ ){ //loops until sqrt(n) is reached. for ( k = i + i; k <= n; k += i ){ prime[k] = 0; } } printf("The prime numbers up to the number %d are : \n", n); for ( i = 2; i <= n; i++ ){ if ( prime[i] != 0 ){ printf("%d\n", prime[i]); // Prints only the values not marked with a 0. } } free(prime); return 0; }
C
#include "main.h" /** * get_line - Read entire line from stream into a buffer. * Return: Buffer containing line read. */ char *get_line() { char *line = NULL; int bytes_size; size_t len = 0; bytes_size = getline(&line, &len, stdin); *(line + strlen(line) - 1) = '\0'; if (bytes_size < 0) perror("Error:"); return (line); } /** * split_line - Splits a string by a given delimiter. * @line: String to be splitted; * Return: An array of pointers to parsed string. */ char **split_line(char *line) { char delim[] = " "; char *token; char **array; int index = 0, len = 100; array = malloc(sizeof(char *) * len); if (!array) perror("low memory"); token = strtok(line, delim); while (token != NULL) { array[index] = token; index++; token = strtok(NULL, delim); } array[index] = NULL; return (array); }
C
#include <unistd.h> int board[10][10]; int row; int col; int ft_error(int, char **); int ft_vals(int, int, int, int); void ft_putchar(char c) { write(1,&c,1); } void ft_printboard(void) { int i; int j; i = 0; while (i < 9) { j = 0; while (j < 9) { ft_putchar(board[i][j] + '0'); j++; } ft_putchar('\n'); i++; } } int ft_findcell(int update) { int i; int j; i = 0; while (i < 9) { j = 0; while (j < 9) { if (board[i][j] == 0) { if (update) { row = i; col = j; } return (1); } j++; } i++; } return 0; } int ft_play(int r, int c) { int num; int nextsqr; int solved; nextsqr = ft_findcell(0); if (!nextsqr)//check for first avail square return (1); num = 1; while (num <= 9) { if (ft_vals(r, c, num, 0)) //if the num is a valid solution { board[r][c] = num; //update board ft_findcell(1);//find next square solved = ft_play(row,col);//test the next step if (solved)//if the test works, return 1 return 1; board[r][c] = 0;//else set the value of the square to 0 ft_vals(r, c, num, 1);//free the number, free the world } num++; } return (0); } void ft_buildboard(int argc, char **argv) { int i; int j; i = 0; while (++i < argc) { j = 0; while (j < 9) { if (argv[i][j] == '.') board[i - 1][j] = 0; else board[i - 1][j] = argv[i][j] - '0'; j++; } } } void ft_sudoku(int argc, char **argv) { ft_buildboard(argc, argv); ft_findcell(1); ft_play(row, col); ft_printboard(); } int main(int argc, char **argv) { (void)argc; if (!(ft_error(argc, argv))) { write(2,"Error\n",6); return 0; } ft_sudoku(argc, argv); return (0); }
C
#include <stdio.h> typedef struct vector { float x; float y; } vec; void vec_sum(vec v1, vec v2, float *sum_x, float *sum_y) { *sum_x = v1.x + v2.x; *sum_y = v1.y + v2.y; } int main() { struct vector v1, v2; // v1.x = 4; // v1.y = 6; // v2.x = 8; // v2.y = 12; printf("\nEnter value for x1:~> "); scanf("%f", &v1.x); printf("\nEnter value for y1:~> "); scanf("%f", &v1.y); printf("\nEnter value for x2:~> "); scanf("%f", &v2.x); printf("\nEnter value for y2:~> "); scanf("%f", &v2.y); float x_sum; float y_sum; vec_sum(v1, v2, &x_sum, &y_sum); printf("\n(%.2f, %.2f) + (%.2f, %.2f) = (%.2f, %.2f)\n", v1.x, v1.y, v2.x, v2.y, x_sum, y_sum); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <dirent.h> #include <unistd.h> #include <sys/stat.h> #include <sys/types.h> int main() { DIR *tmp=opendir("tmp"); struct dirent *dp=readdir(tmp); char command[64],path[64]; struct stat data; while (dp != NULL) { if (dp->d_name[0] != '.') { sprintf(path,"./tmp/%s",dp->d_name); stat(path,&data); if (data.st_nlink >= 2) { printf("For %s",dp->d_name,"Link:\n" ); sprintf(command, "find -inum %lu", data.st_ino); system(command); } } dp=readdir(tmp); } }
C
#include <stdio.h> #include <stdlib.h> #include <math.h> //include of usual_function.h #include "..\headers\usual_functions.h" typedef struct array{ int length; int *value; }array; void new_random_array( array* my_array, int taille); void read_array( array* my_array); void clean_array(array* my_array); void new_random_array( array* my_array, int taille) { if (my_array!=NULL) { my_array->length = taille; int i; my_array->value = malloc(sizeof(int*)*my_array->length); for(i = 0; i< my_array->length; i++) { my_array->value[i] = (rand() % 100) + 1; } } else { exit(0); } } void read_array( array* my_array) { int i; printf("\n"); for(i = 0; i< my_array->length; i++) { printf(" %i |",my_array->value[i]); } } void clean_array(array* my_array) { int i; free(my_array->value); free(my_array); } int main(int argc, char** argv) { //On initialise la structure array int taille = 15; array* my_array = malloc(sizeof(array)); new_random_array(my_array, taille); //ici on execute les tests //bubble_sort_int(my_array->value, my_array->length); quick_sort(my_array->value, 0, my_array->length); //lecture du tableau read_array(my_array); //On efface le tableau proprement clean_array(my_array); return 0; }
C
#include <stdio.h> int fact() { int n, count; unsigned long long int factorial=1; printf("Enter an integer: "); scanf("%d",&n); if ( n< 0) printf("Error!!! Factorial of negative number doesn't exist."); else { for(count=1;count<=n;++count) /* for loop terminates if count>n */ { factorial*=count; /* factorial=factorial*count */ } printf("Factorial = %lu",factorial); } return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> int sorting(int car[]){ int i,j,n,g[]={0,1,2,3}; for(i=3;i>0;i--){ for(j=0;j<i;j++){ if(car[j]>car[j+1]){ n=car[j]; car[j]=car[j+1]; car[j+1]=n; n=g[j]; g[j]=g[j+1]; g[j+1]=n; } } } for(i=0;i<4;i++){ switch(g[i]){ case 0: printf("大型車:%d\n",car[i]); break; case 1: printf("中型車:%d\n",car[i]); break; case 2: printf("小型車:%d\n",car[i]); break; case 3: printf("公務車:%d\n",car[i]); break; } } } int main(int argc, char *argv[]) { FILE *fi; fi=fopen("car.txt","r"); int x,i,j,n,f[]={0,1,2,3},q,w,e,r; char day[20]; printf("請選擇以依車輛種類(1)或依星期別(2)顯示:\n"); scanf("%d",&x); if(x==1){ int car[4]; while(fscanf(fi,"%s %d %d %d %d",day,&q,&w,&e,&r)!=EOF){ car[0]+=q; car[1]+=w; car[2]+=e; car[3]+=r; } sorting(car); } else if(x==2){ int to[]={0,0,0,0,0,0,0}; while(fscanf(fi,"%s %d %d %d %d",day,&q,&w,&e,&r)!=EOF){ if(day[0]=='M') to[0]+=q+w+e+r; else if(day[0]=='T'){ if(day[1]=='H') to[3]+=q+w+e+r; else to[1]+=q+w+e+r; } else if(day[0]=='W') to[2]+=q+w+e+r; else if(day[0]=='F') to[4]+=q+w+e+r; else if(day[0]=='S'){ if(day[1]=='A') to[5]+=q+w+e+r; else to[6]+=q+w+e+r; } } printf("星期一:%d\n",to[0]); printf("星期二:%d\n",to[1]); printf("星期三:%d\n",to[2]); printf("星期四:%d\n",to[3]); printf("星期五:%d\n",to[4]); printf("星期六:%d\n",to[5]); printf("星期日:%d\n",to[6]); } fclose(fi); system("pause"); return 0; }
C
// // Created by Lander Brandt on 4/1/15. // #include <stdio.h> #include "utility.h" void flushStdin() { int c; while((c = getchar()) != '\n' && c != EOF); } int menu() { int response = -1; int read = 0; while (response < 1 || response > 6 || read != 1) { printf("\n1) Print the List\n"); printf("2) Add First\n"); printf("3) Add Last\n"); printf("4) Sort the List (ascending order)\n"); printf("5) Delete a word\n"); printf("6) Quit --\n"); read = scanf("%d", &response); flushStdin(); printf("\n"); } return response; } /** * Prompts the user for a file to open, and continues prompting until a valid file is given */ FILE * openFile() { FILE *returnFile = NULL; char fileName[MAX]; int result = 0; while (returnFile == NULL) { printf("Enter the path of the file you'd like to open: "); // vulnerable to buffer overflow, but screw it result = scanf("%s", fileName); if (result != 1) { continue; } returnFile = fopen(fileName, "r"); } return returnFile; } void strip(char *array) { if (array == NULL) { return; } int i; for (i = 0; array[i] != '\0'; i++) { if (array[i] == '\r' || array[i] == '\n') { array[i] = '\0'; return; } } } /** * Counts the number of lines in a file and divides by "lines" */ int countRecords(FILE * fin, int lines) { rewind(fin); int count = 0; while (!feof(fin)) { if (fgetc(fin) == '\n') { count++; } } if (count < lines || lines == 0) { perror("File had 0 records"); } count /= lines; return count; } Node * buildNode(FILE * in, void *(*buildData)(FILE * in) ) { Node *temp = calloc(1, sizeof(Node)); temp->data = buildData(in); return temp; } void buildList(LinkedList * myList, FILE * fin, int total, void * (*buildData)(FILE * in)) { rewind(fin); int i; for (i = 0; i < total && !feof(fin); i++) { addLast(myList, buildNode(fin, buildData)); } }
C
#include <cs50.h> #include <ctype.h> #include <stdio.h> #include <string.h> // Checks key to make sure each letter of // the alpha is present once and only once bool has_each_letter(string key); // Checks if a string only contains letters bool str_isalpha(string s); // Prints a ciphertext from given // plaintext and key void print_cipher(string ptext, string key); // Turns every char in a string's case to upper void str_toupper(string s); int main(int argc, string argv[]) { // key validity checks if (argc != 2) { printf("Usage: ./substitution key\n"); return 1; } else if (strlen(argv[1]) != 26) { printf("Key must contain 26 characters.\n"); return 1; } else if (!str_isalpha(argv[1])) { printf("Key must only contain letters of the alphabet.\n"); return 1; } else if (!has_each_letter(argv[1])) { printf("Each letter of the alphabet must be present in your key.\n"); return 1; } // end key validity check // set key to be all uppercase str_toupper(argv[1]); // request plaintext string user = get_string("plaintext: "); // print ciphertext printf("ciphertext: "); print_cipher(user, argv[1]); return 0; } bool has_each_letter(string key) { /* Each index of alcount reps a letter in the alphabet where a is i=0, z is i=25 When a letter is seen, its count is added to its respective index of alcount We want each letter to be used once. No more, no less. */ int alcount[26] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; for (int i = 0; i < 26; i++) // we should know by now that the key is len 26 { int index = (int) toupper(key[i]) - 65; alcount[index] += 1; if (alcount[index] > 1) { return false; } } for (int i = 0; i < 26; i++) { if (!alcount[i]) { return false; } } return true; } bool str_isalpha(string s) { for (int i = 0, n = strlen(s); i < n; i++) { if (!isalpha(s[i])) { return false; } } return true; } // print cipher text out // doesn't save to memory void print_cipher(string ptext, string key) { char h; for (int i = 0, n = strlen(ptext); i < n; i++) { // check if char is a letter if (isalpha(ptext[i])) { // do conversion h = key[(int) toupper(ptext[i]) - 65]; // check if ptext char is lower case. if ((int) ptext[i] > 96) { h = tolower(h); } printf("%c", h); } else { printf("%c", ptext[i]); } } printf("\n"); } void str_toupper(string s) { for (int i = 0, n = strlen(s); i < n; i++) { s[i] = toupper(s[i]); } }
C
#include "file.h" #include "assert.h" #include "errno.h" int main() { char buf[5]; buf[5]='\0'; read(0, (void*) &buf, 5); assert(!strcmp((char*) &buf, "hello")); assert(read(42, (char*) &buf, 5)==-EBADF); int fd=open("tmp/read-mode.txt", O_WRONLY|O_APPEND|O_CREAT, 0200); assert(fd!=-1); assert(read(fd, (char*) &buf, 5)==-EBADF); close(fd); return 0; }
C
/* Design, Develop and Implement a Program in C for the following operations on Graph(G) of Cities a. Create a Graph of N cities using Adjacency Matrix. b. Print all the nodes reachable from a given starting node in a digraph using DFS/BFS method */ #include <stdio.h> #include <stdlib.h> int a[10][10], n, m, i, j, source, s[10], b[10]; int visited[10]; void create() { printf("\nEnter the number of vertices of the digraph: "); scanf("%d", &n); printf("\nEnter the adjacency matrix of the graph: \n"); for (i = 1; i <= n; i++) for (j = 1; j <= n; j++) scanf("%d", &a[i][j]); } void bfs() { int q[10], u, front = 0, rear = -1; printf("\nEnter the source vertex to find other nodes reachable or not: "); scanf("%d", &source); q[++rear] = source; visited[source] = 1; printf("\nThe reachable vertices are: \n"); while (front <= rear) { u = q[front++]; for (i = 1; i <= n; i++) { if (a[u][i] == 1 && visited[i] == 0) { q[++rear] = i; visited[i] = 1; printf("\n%d", i); } } } } void dfs(int source) { int v, top = -1; s[++top] = 1; b[source] = 1; for (v = 1; v <= n; v++) { if (a[source][v] == 1 && b[v] == 0) { printf("\n%d -> %d", source, v); dfs(v); } } } void main() { int ch; while (1) { printf("\n1. Create Graph\n2. BFS\n3. Check graph connected or not(DFS)\n4. Exit\n"); printf("\nEnter your choice : "); scanf("%d", &ch); switch (ch) { case 1: create(); break; case 2: bfs(); for (i = 1; i <= n; i++) if (visited[i] == 0) printf("\nThe vertex that is not reachable %d", i); break; case 3: printf("\nEnter the source vertex to find the connectivity: "); scanf("%d", &source); m = 1; dfs(source); for (i = 1; i <= n; i++) { if (b[i] == 0) m = 0; } if (m == 1) printf("\nGraph is Connected\n"); else printf("\nGraph is not Connected\n"); break; default: exit(0); } } }
C
#include<stdio.h> double qq(double a,int b) { if(b>0) { return a*qq(a,--b); } else if(b==0) { return 1; } else if(b<0) { return 1/qq(a,-b); } } int main() { double a; int b; scanf("%lf %d",&a,&b); a=qq(a,b); printf("%lf\n",a); return 0; }
C
#include<stdio.h> main() { char a[10],b[10]; int i,k,j; gets(a); scanf("%d",&k); j=0; for(i=0;i<k;i++) { b[j]=a[i]; j++; } b[j]='\0'; printf("%s",b); }
C
#include <stdio.h> #include <unistd.h> #include <sys/socket.h> #include <sys/types.h> #include "info.h" #include "signal.h" #include <string.h> #define SOCKET_ERR -1 #define BIND_ERR -2 #define RECV_ERR -3 int sockfd; int sigint_flag = 0; void sigint_catch(int signum) { close(sockfd); unlink(SOCKET_NAME); printf("\nCtrl + C catched; Socket closed\n"); sigint_flag = 1; } int main() { sockfd = socket(PF_LOCAL, SOCK_DGRAM, 0); if (sockfd < 0) { printf("Error in socket(). \n"); return SOCKET_ERR; } struct sockaddr client_addr; client_addr.sa_family = PF_LOCAL; strcpy(client_addr.sa_data, SOCKET_NAME); if (bind(sockfd, &client_addr, sizeof(client_addr)) < 0) { close(sockfd); unlink(SOCKET_NAME); printf("Error in bind(). \n"); return BIND_ERR; } printf("Server is running."); signal(SIGINT, sigint_catch); char msg[MSG_LEN]; for(;;) { int msg_len = recv(sockfd, msg, sizeof(msg), 0); if (sigint_flag == 1) { return 0; } if (msg_len < 0) { close(sockfd); unlink(SOCKET_NAME); printf("Error in recv(). \n"); return RECV_ERR; } msg[msg_len] = 0; printf("\nMessage from client: %s", msg); } close(sockfd); unlink(SOCKET_NAME); printf("Socket closed."); return 0; }
C
//hollow diamond star pattern #include<stdio.h> int main() { int i,j,n,count,l=0,k,m; printf("enter no. of rows in upper half:"); scanf("%d",&n); m=n; for(i=1;i<=n;i++) { for(j=1;j<=n+1-i;j++) printf("*"); count=i; while(count<=2*l) { printf(" "); count++; } for(k=1;k<=n+1-i;k++) printf("*"); l++; printf("\n"); } for(i=1;i<=n;i++) { for(j=1;j<=i;j++) printf("*"); count=1; while(count<=2*(m-i)) { printf(" "); count++; } for(k=1;k<=i;k++) printf("*"); l++; printf("\n"); } return 0; }
C
#include "log.h" #ifndef UNUSED #define UNUSED(x) ((void)x); #endif #ifndef min #define min(a, b) ((a) <= (b) ? (a) : (b)) #endif #ifndef max #define max(a, b) ((a) >= (b) ? (a) : (b)) #endif static inline void do_output(const char *msg, bool endl) { fprintf(stderr, "%s%s", msg, endl ? "\n" : ""); } static inline void do_log_tag(const int level, const char *func, int line) { char tag[64]; UNUSED(level); snprintf(tag, sizeof(tag), "%s@%d ", func, line); do_output(tag, false); } void PRINTF(4, 5) do_log(const int level, const char *func, int line, const char *fmt, ...) { int rc; char *msg; va_list ap; va_start(ap, fmt); rc = vasprintf(&msg, fmt, ap); va_end(ap); if (rc > 0) { do_log_tag(level, func, line); do_output(msg, true); } free(msg); } void do_dump(const int level, const char *func, int line, const char *tag, const char *buf, size_t len) { char msg[64]; size_t i, n, np; do_log_tag(level, func, line); do_output(tag, true); i = n = np = 0; while (np < len) { n = min(len - np, 16); snprintf(msg, sizeof(msg), "0x%08x: ", (unsigned int)(np / 16) * 16); do_output(msg, false); msg[0] = 0; for (i = 0; i < n; i++) snprintf(msg + strlen(msg), sizeof(msg) - strlen(msg), "%02X ", (unsigned char)buf[np++]); do_output(msg, true); } }
C
//Program to copy the contents of one array into another in the reverse order. #include<stdio.h> int main() { int i,j,arr1[10],arr2[10]; printf("Enter 10 elements of an array: \n"); for(i=0; i<=9; i++) scanf("%d",&arr1[i]); for(i=0,j=9; i<=9; i++,j--) arr2[i]=arr1[j]; printf("Reversed elements are\n"); for(i=0; i<=9; i++) printf("%d ",arr2[i]); }
C
#include <stdio.h> #include <stdlib.h> #include "listaencadeada.h" int main(void){ void *Lista = criarLista(); for(int i = 1 ; i <= 10 ; i++){ incluirLista(Lista, i); } void *no = buscar(Lista, 4); buscar(Lista, 15); // Imprime a mensagem que não encontrou o nó imprimirLista(Lista); removerLista(Lista, no); imprimirLista(Lista); // Imprime a lista sem o 4 (nó excluído) apagarLista(Lista); return 0; }
C
#include <stdio.h> #include <sys/types.h> #include <sys/stat.h> #include <stdlib.h> #include <unistd.h> #include <dirent.h> int main() { char buf[100]; getcwd(buf, 100); printf("current dir: %s\n", buf); if (mkdir("testdir", 0777)) { perror("create failed"); } chdir("testdir"); getcwd(buf, 100); printf("current dir: %s\n", buf); DIR *dir; dir = opendir(buf); struct dirent *dirent = readdir(dir); printf("%s\n", dirent->d_name); printf("current pos: %d\n", telldir(dir)); closedir(dir); exit(0); }
C
/** * This program use static library funcions * author : Naresh * email :nareshchemchem35@gmail.com * date :08-09-2021 * */ #include<stdio.h> /* required for printf */ /* main program */ main() { int r; printf("Hello"); r=add(10,20); printf("r=%d\n",r); r=sub(10,20); printf("r=%d\n",r); }
C
#include "types.h" #include "user.h" int main(int argc, char const *argv[]) { int ticks = 50; if (argc > 2) { printf(1,"usage: sleep [ticks]\n"); exit(); } if(argc == 2) ticks = atoi(argv[1]); sleep(ticks); exit(); }